2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015,
4 Ben Kibbey <bjk@luxsci.net>
6 This file is part of pwmd.
8 Pwmd is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 2 of the License, or
11 (at your option) any later version.
13 Pwmd is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
31 #include <sys/socket.h>
45 #include <netinet/in.h>
46 #include <arpa/inet.h>
49 #include <sys/resource.h>
64 #ifdef HAVE_GETOPT_LONG
69 #include "getopt_long.h"
72 #ifdef HAVE_PR_SET_NAME
73 #include <sys/prctl.h>
76 #include "pwmd-error.h"
79 #include "util-misc.h"
85 #include "util-string.h"
90 /* In tenths of a second. */
93 /* For (tcp_)accept_thread (usec). */
94 #define ACCEPT_TIMEOUT 50000
101 static unsigned assuan_level
;
103 pthread_t accept_tid
;
107 static int start_stop_tls (int term
);
110 static gpg_error_t
do_cache_push (struct crypto_s
*crypto
);
111 static int signal_loop (sigset_t sigset
);
113 #ifndef HAVE_PTHREAD_CANCEL
114 #define INIT_SIGNAL(s, cb) do { \
115 int *n = xmalloc (sizeof (int)); \
117 pthread_setspecific (signal_thread_key, n); \
118 struct sigaction act; \
120 sigemptyset (&sigset); \
121 sigaddset (&sigset, s); \
122 pthread_sigmask (SIG_UNBLOCK, &sigset, NULL); \
123 memset (&act, 0, sizeof(act)); \
124 act.sa_flags = SA_SIGINFO; \
125 act.sa_mask = sigset; \
126 act.sa_sigaction = cb; \
127 sigaction (s, &act, NULL); \
131 #ifndef HAVE_PTHREAD_CANCEL
133 catch_thread_signal (int sig
, siginfo_t
*info
, void *ctx
)
135 int *n
= (int *) pthread_getspecific (signal_thread_key
);
144 int n
= config_get_boolean ("global", "enable_logging");
148 char *p
= config_get_string ("global", "log_path");
150 if (!p
|| (logfile
&& p
&& log_fd
!= -1 && strcmp(p
, logfile
)))
161 logfile
= expand_homedir (p
);
175 log_syslog
= config_get_boolean ("global", "syslog");
177 openlog ("pwmd", LOG_NDELAY
| LOG_PID
, LOG_DAEMON
);
181 reload_rcfile_thread (void *arg
)
183 #ifndef HAVE_PTHREAD_CANCEL
184 INIT_SIGNAL (SIGUSR2
, catch_thread_signal
);
187 #ifdef HAVE_PR_SET_NAME
188 prctl (PR_SET_NAME
, "reload rcfile");
190 pthread_setspecific (thread_name_key
, str_asprintf ("!%s", __FUNCTION__
));
191 MUTEX_LOCK (&rcfile_mutex
);
195 struct slist_s
*keep
= NULL
;
196 struct slist_s
*config
;
197 int b
= disable_list_and_dump
;
203 pthread_cleanup_push (release_mutex_cb
, &rcfile_mutex
);
204 pthread_cond_wait (&rcfile_cond
, &rcfile_mutex
);
206 keep
= config_keep_save ();
207 log_write (_("reloading configuration file '%s'"), rcfile
);
210 prio
= config_get_string ("global", "tls_cipher_suite");
212 config
= config_parse (rcfile
, 1);
215 config_free (global_config
);
216 global_config
= config
;
220 config_keep_restore (keep
);
221 disable_list_and_dump
= !disable_list_and_dump
? b
: 1;
224 /* Restart listening sockets since they may have changed. */
228 prio2
= config_get_string ("global", "tls_cipher_suite");
229 if ((prio2
&& (!prio
|| strcmp (prio
, prio2
))) || (prio
&& !prio2
))
235 crypto_set_keepalive ();
236 pthread_cleanup_pop (0);
239 MUTEX_UNLOCK (&rcfile_mutex
);
244 send_error (assuan_context_t ctx
, gpg_error_t e
)
246 struct client_s
*client
= assuan_get_pointer (ctx
);
248 if (gpg_err_source (e
) == GPG_ERR_SOURCE_UNKNOWN
)
255 return assuan_process_done (ctx
, 0);
259 log_write ("ERR %i: %s", e
, pwmd_strerror (e
));
263 if (client
&& client
->xml_error
)
265 log_write ("%s", client
->xml_error
->message
);
266 xfree (client
->last_error
);
267 client
->last_error
= NULL
;
268 if (client
->xml_error
->message
)
269 client
->last_error
= str_dup (client
->xml_error
->message
);
271 e
= assuan_process_done (ctx
,
272 assuan_set_error (ctx
, e
,
273 client
->xml_error
->message
? client
->xml_error
->message
: NULL
));
274 xmlResetLastError ();
275 xmlResetError (client
->xml_error
);
276 xfree (client
->xml_error
);
277 client
->xml_error
= NULL
;
281 return assuan_process_done (ctx
,
282 assuan_set_error (ctx
, e
, pwmd_strerror (e
)));
286 log_write (const char *fmt
, ...)
292 pthread_t tid
= pthread_self ();
293 static pthread_mutex_t m
= PTHREAD_MUTEX_INITIALIZER
;
295 if ((!logfile
&& !isatty (STDERR_FILENO
) && !log_syslog
) || !fmt
)
298 pthread_mutex_lock (&m
);
299 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock
, &m
);
301 if (!cmdline
&& logfile
&& log_fd
== -1)
303 log_fd
= open (logfile
, O_WRONLY
| O_CREAT
| O_APPEND
, 0600);
305 warn ("%s", logfile
);
310 if (str_vasprintf (&args
, fmt
, ap
) != -1)
314 pthread_cleanup_push (xfree
, args
);
315 fprintf (stderr
, "pwmd: %s\n", args
);
317 pthread_cleanup_pop (1);
321 char *name
= pthread_getspecific (thread_name_key
);
324 pthread_cleanup_push (xfree
, args
);
328 snprintf (buf
, sizeof (buf
), "%s: ", name
+1);
330 snprintf (buf
, sizeof (buf
), "%s(%p): ", name
,
334 snprintf (buf
, sizeof (buf
), "%p: ", (pthread_t
*)tid
);
337 if (!cmdline
&& log_syslog
&& !nofork
)
338 syslog (LOG_INFO
, "%s%s", name
, args
);
341 struct tm
*tm
= localtime (&now
);
343 strftime (tbuf
, sizeof (tbuf
), "%b %d %Y %H:%M:%S ", tm
);
344 tbuf
[sizeof (tbuf
) - 1] = 0;
346 if (args
[strlen (args
) - 1] == '\n')
347 args
[strlen (args
) - 1] = 0;
349 line
= str_asprintf ("%s %i %s%s\n", tbuf
, getpid (), name
,
351 pthread_cleanup_pop (1);
354 pthread_cleanup_push (xfree
, line
);
355 if (logfile
&& log_fd
!= -1)
357 ssize_t ret
= write (log_fd
, line
, strlen (line
));
364 fprintf (stdout
, "%s", line
);
368 pthread_cleanup_pop (1);
374 pthread_cleanup_pop (0);
376 if (log_fd
!= -1 && log_keepopen
<= 0)
382 pthread_mutex_unlock (&m
);
390 if (!gpgrt_check_version (REQUIRE_LIBGPGERROR_VERSION
))
392 fprintf (stderr
, _("gpgrt_check_version(): Incompatible libgpg-error. "
393 "Wanted %s, got %s.\n"), REQUIRE_LIBGPGERROR_VERSION
,
394 gpgrt_check_version (NULL
));
395 return GPG_ERR_UNKNOWN_VERSION
;
399 //gpgrt_set_alloc_func (xrealloc_gpgrt);
401 if (!assuan_check_version (REQUIRE_LIBASSUAN_VERSION
))
403 fprintf (stderr
, _("assuan_check_version(): Incompatible libassuan. "
404 "Wanted %s, got %s.\n"), REQUIRE_LIBASSUAN_VERSION
,
405 assuan_check_version (NULL
));
406 return GPG_ERR_UNKNOWN_VERSION
;
409 if (!gcry_check_version (REQUIRE_LIBGCRYPT_VERSION
))
411 fprintf (stderr
, _("gcry_check_version(): Incompatible libgcrypt. "
412 "Wanted %s, got %s.\n"), REQUIRE_LIBGCRYPT_VERSION
,
413 gcry_check_version (NULL
));
414 return GPG_ERR_UNKNOWN_VERSION
;
417 gcry_set_allocation_handler (xmalloc
, xmalloc
, NULL
, xrealloc
, xfree
);
419 if (!gpgme_check_version (REQUIRE_LIBGPGME_VERSION
))
421 fprintf (stderr
, _("gpgme_check_version(): Incompatible libgpgme. "
422 "Wanted %s, got %s.\n"), REQUIRE_LIBGPGME_VERSION
,
423 gpgme_check_version (NULL
));
424 return GPG_ERR_UNKNOWN_VERSION
;
427 rc
= gpgme_engine_check_version (GPGME_PROTOCOL_OPENPGP
);
430 fprintf (stderr
, _("gpgme_engine_check_version(GPGME_PROTOCOL_OPENPGP): %s"), gpgme_strerror (rc
));
431 return GPG_ERR_UNKNOWN_VERSION
;
434 //gpgme_set_global_flag ("require-gnupg", REQUIRE_GNUPG_VERSION);
436 gpgme_set_locale (NULL
, LC_CTYPE
, setlocale (LC_CTYPE
, NULL
));
437 gpgme_set_locale (NULL
, LC_MESSAGES
, setlocale (LC_MESSAGES
, NULL
));
441 if (gnutls_global_init ())
443 fprintf(stderr
, _("gnutls_global_init() failed.\n"));
444 return GPG_ERR_UNKNOWN_VERSION
;
447 if (!gnutls_check_version (REQUIRE_LIBGNUTLS_VERSION
))
449 fprintf (stderr
, _("gnutls_check_version(): Incompatible libgnutls. "
450 "Wanted %s, got %s.\n"), REQUIRE_LIBGNUTLS_VERSION
,
451 gnutls_check_version (NULL
));
452 return GPG_ERR_UNKNOWN_VERSION
;
455 gnutls_global_set_log_function (tls_log
);
456 gnutls_global_set_audit_log_function (tls_audit_log
);
462 do_validate_peer (assuan_context_t ctx
, const char *section
,
463 assuan_peercred_t
* peer
)
468 struct client_s
*client
= assuan_get_pointer (ctx
);
471 return GPG_ERR_FORBIDDEN
;
474 if (client
->thd
->remote
)
475 return tls_validate_access (client
, section
);
478 rc
= assuan_get_peercred (ctx
, peer
);
482 users
= config_get_list (section
, "allowed");
485 for (char **p
= users
; !rc
&& *p
; p
++)
487 rc
= acl_check_common(client
, *p
, (*peer
)->uid
, (*peer
)->gid
,
493 else if (client
->no_access_param
)
496 return allowed
&& !rc
? 0 : rc
? rc
: GPG_ERR_FORBIDDEN
;
499 /* Test if uid is a member of group 'name'. Invert when 'not' is true. */
500 #ifdef HAVE_GETGRNAM_R
502 acl_check_group (const char *name
, uid_t uid
, gid_t gid
, int not, int *allowed
)
505 struct group gr
, *gresult
;
506 size_t len
= sysconf (_SC_GETGR_R_SIZE_MAX
);
515 return GPG_ERR_ENOMEM
;
517 err
= getgrnam_r (name
, &gr
, buf
, len
, &gresult
);
520 if (gresult
->gr_gid
== gid
)
527 for (char **t
= gresult
->gr_mem
; !rc
&& *t
; t
++)
531 struct passwd
*result
= get_pwd_struct (*t
, 0, &pw
, &tbuf
, &rc
);
533 if (!rc
&& result
&& result
->pw_uid
== uid
)
547 rc
= gpg_error_from_errno (err
);
550 return rc
? rc
: !gresult
? 0 : GPG_ERR_EACCES
;
554 acl_check_group (const char *name
, uid_t uid
, gid_t gid
, int not, int *allowed
)
556 struct group
*gresult
;
560 gresult
= getgrnam (name
);
561 if (!errno
&& gresult
&& gresult
->gr_gid
== gid
)
567 rc
= gpg_error_from_syserror ();
571 for (char **t
= gresult
->gr_mem
; !rc
&& *t
; t
++)
575 struct passwd
*result
= get_pwd_struct (*t
, 0, &pw
, &buf
, &rc
);
577 if (!rc
&& result
&& result
->pw_uid
== uid
)
592 peer_is_invoker(struct client_s
*client
)
594 struct invoking_user_s
*user
;
597 if (client
->thd
->state
== CLIENT_STATE_UNKNOWN
)
598 return GPG_ERR_EACCES
;
600 for (user
= invoking_users
; user
; user
= user
->next
)
603 if (client
->thd
->remote
)
605 if (user
->type
== INVOKING_TLS
606 && !strcmp(client
->thd
->tls
->fp
, user
->id
))
607 allowed
= user
->not ? 0 : 1;
613 if (user
->type
== INVOKING_GID
)
615 gpg_error_t rc
= acl_check_group (user
->id
,
616 client
->thd
->peer
->uid
,
617 client
->thd
->peer
->gid
,
618 user
->not, &allowed
);
622 else if (user
->type
== INVOKING_UID
&& client
->thd
->peer
->uid
== user
->uid
)
623 allowed
= user
->not ? 0 : 1;
626 return allowed
? 0 : GPG_ERR_EACCES
;
629 #ifdef HAVE_GETGRNAM_R
631 acl_check_common (struct client_s
*client
, const char *user
, uid_t uid
,
632 gid_t gid
, int *allowed
)
642 if (*user
== '-' || *user
== '!')
645 if (*user
== '+') // not implemented yet
648 if (*user
== '#') // TLS fingerprint hash
651 if (not || rw
|| tls
)
657 if (client
->thd
->remote
)
659 if (!strcasecmp (client
->thd
->tls
->fp
, user
))
669 else if (client
->thd
->remote
) // Remote client with no FP in the ACL
673 if (*user
== '@') // all users in group
674 return acl_check_group (user
+1, uid
, gid
, not, allowed
);
679 struct passwd
*pwd
= get_pwd_struct (user
, 0, &pw
, &buf
, &rc
);
681 if (!rc
&& pwd
&& pwd
->pw_uid
== uid
)
691 acl_check_common (struct client_s
*client
, const char *user
, uid_t uid
,
692 gid_t gid
, int *allowed
)
702 if (*user
== '-' || *user
== '!')
705 if (*user
== '+') // not implemented yet
708 if (*user
== '#') // TLS fingerprint hash
711 if (not || rw
|| tls
)
717 if (client
->thd
->remote
)
719 if (!strcasecmp (client
->thd
->tls
->fp
, user
))
729 if (*user
== '@') // all users in group
730 return acl_check_group (user
+1, uid
, gid
, not, allowed
);
735 struct passwd
*result
= get_pwd_struct (user
, 0, &pw
, &buf
, &rc
);
737 if (!rc
&& result
&& result
->pw_uid
== uid
)
748 validate_peer (struct client_s
*cl
)
754 return tls_validate_access (cl
, NULL
);
757 MUTEX_LOCK (&cn_mutex
);
758 pthread_cleanup_push (release_mutex_cb
, &cn_mutex
);
759 rc
= do_validate_peer (cl
->ctx
, "global", &cl
->thd
->peer
);
760 pthread_cleanup_pop (1);
761 log_write ("peer %s: uid=%i, gid=%i, pid=%i, rc=%u",
762 !rc
? _("accepted") : _("rejected"), cl
->thd
->peer
->uid
,
763 cl
->thd
->peer
->gid
, cl
->thd
->peer
->pid
, rc
);
768 xml_error_cb (void *data
, xmlErrorPtr e
)
770 struct client_s
*client
= data
;
773 * Keep the first reported error as the one to show in the error
774 * description. Reset in send_error().
776 if (client
->xml_error
)
779 client
->xml_error
= xcalloc (1, sizeof(xmlError
));
780 xmlCopyError (e
, client
->xml_error
);
784 hook_waitpid (assuan_context_t ctx
, pid_t pid
, int action
,
785 int *status
, int options
)
787 return waitpid (pid
, status
, options
);
791 hook_read (assuan_context_t ctx
, assuan_fd_t fd
, void *data
, size_t len
)
794 struct client_s
*client
= assuan_get_pointer (ctx
);
796 if (client
->thd
->remote
)
797 return tls_read_hook (ctx
, (int) fd
, data
, len
);
800 return read ((int) fd
, data
, len
);
804 hook_write (assuan_context_t ctx
, assuan_fd_t fd
,
805 const void *data
, size_t len
)
808 struct client_s
*client
= assuan_get_pointer (ctx
);
810 if (client
->thd
->remote
)
811 return tls_write_hook (ctx
, (int) fd
, data
, len
);
814 return write ((int) fd
, data
, len
);
818 assuan_log_cb (assuan_context_t ctx
, void *data
, unsigned cat
,
821 struct client_s
*client
= data
;
826 if (!(assuan_level
& cat
))
834 case ASSUAN_LOG_INIT
:
835 str
= "ASSUAN[INIT]";
840 case ASSUAN_LOG_ENGINE
:
841 str
= "ASSUAN[ENGINE]";
843 case ASSUAN_LOG_DATA
:
844 str
= "ASSUAN[DATA]";
846 case ASSUAN_LOG_SYSIO
:
847 str
= "ASSUAN[SYSIO]";
849 case ASSUAN_LOG_CONTROL
:
850 str
= "ASSUAN[CONTROL]";
853 str
= "ASSUAN[UNKNOWN]";
857 log_write ("%s: %s", str
, msg
);
862 new_connection (struct client_s
*cl
)
865 static struct assuan_malloc_hooks mhooks
= { xmalloc
, xrealloc
, xfree
};
866 static struct assuan_system_hooks shooks
= {
867 ASSUAN_SYSTEM_HOOKS_VERSION
,
875 NULL
, //sendmsg both are used for FD passing
886 char *prio
= config_get_string ("global", "tls_cipher_suite");
888 cl
->thd
->timeout
= config_get_integer ("global", "tls_timeout");
889 if (fcntl (cl
->thd
->fd
, F_SETFL
, O_NONBLOCK
) == -1)
892 cl
->thd
->tls
= tls_init_client (cl
->thd
->fd
, cl
->thd
->timeout
, prio
);
899 rc
= assuan_new_ext (&cl
->ctx
, GPG_ERR_SOURCE_DEFAULT
, &mhooks
,
904 assuan_ctx_set_system_hooks (cl
->ctx
, &shooks
);
905 rc
= assuan_init_socket_server (cl
->ctx
, cl
->thd
->fd
, 2);
909 assuan_set_pointer (cl
->ctx
, cl
);
910 assuan_set_hello_line (cl
->ctx
, PACKAGE_STRING
);
911 rc
= register_commands (cl
->ctx
);
915 rc
= assuan_accept (cl
->ctx
);
919 rc
= validate_peer (cl
);
920 /* May not be implemented on all platforms. */
921 if (rc
&& gpg_err_code (rc
) != GPG_ERR_ASS_GENERAL
)
924 MUTEX_LOCK (&cn_mutex
);
925 cl
->thd
->state
= CLIENT_STATE_INIT
;
926 MUTEX_UNLOCK (&cn_mutex
);
927 cl
->lock_timeout
= config_get_integer ("global", "lock_timeout");
928 xmlSetStructuredErrorFunc (cl
, xml_error_cb
);
932 log_write ("%s", pwmd_strerror (rc
));
937 * This is called after a client_thread() terminates. Set with
938 * pthread_cleanup_push().
941 free_client_cb (void *arg
)
943 struct client_thread_s
*cn
= arg
;
944 struct client_s
*cl
= cn
->cl
;
946 MUTEX_LOCK (&cn_mutex
);
947 cn_thread_list
= slist_remove (cn_thread_list
, cn
);
948 MUTEX_UNLOCK (&cn_mutex
);
952 unlock_flock (&cl
->flock_fd
);
955 xmlResetError (cl
->xml_error
);
957 xfree (cl
->xml_error
);
962 gnutls_deinit (cn
->tls
->ses
);
969 assuan_release (cl
->ctx
);
970 else if (cl
->thd
&& cl
->thd
->fd
!= -1)
974 crypto_free (cl
->crypto
);
985 while (cn
->msg_queue
)
987 struct status_msg_s
*msg
= cn
->msg_queue
;
989 cn
->msg_queue
= msg
->next
;
994 if (cn
->status_msg_pipe
[0] != -1)
995 close (cn
->status_msg_pipe
[0]);
997 if (cn
->status_msg_pipe
[1] != -1)
998 close (cn
->status_msg_pipe
[1]);
1000 pthread_mutex_destroy (&cn
->status_mutex
);
1001 log_write (_("exiting, fd=%i"), cn
->fd
);
1002 send_status_all (STATUS_CLIENTS
, NULL
);
1005 xfree (cn
->peeraddr
);
1013 MUTEX_LOCK (&cn_mutex
);
1014 pthread_cleanup_push (release_mutex_cb
, &cn_mutex
);
1016 while (slist_length (cn_thread_list
))
1018 struct client_thread_s
*thd
= slist_nth_data (cn_thread_list
, 0);
1020 free_client_cb (thd
);
1023 pthread_cleanup_pop (1);
1027 send_msg_queue (struct client_thread_s
*thd
)
1029 MUTEX_LOCK (&thd
->status_mutex
);
1034 ret
= read (thd
->status_msg_pipe
[0], &c
, 1);
1035 rc
= gpg_error_from_syserror ();
1036 if (ret
== -1 && gpg_err_code (rc
) != GPG_ERR_EAGAIN
)
1037 log_write ("%s (%i): %s", __FUNCTION__
, __LINE__
, pwmd_strerror (rc
));
1041 thd
->wrote_status
= 0;
1043 while (thd
->msg_queue
)
1045 struct status_msg_s
*msg
= thd
->msg_queue
;
1047 #ifndef HAVE_PTHREAD_CANCEL
1052 thd
->msg_queue
= thd
->msg_queue
->next
;
1053 MUTEX_UNLOCK (&thd
->status_mutex
);
1054 rc
= send_status (thd
->cl
->ctx
, msg
->s
, msg
->line
);
1055 MUTEX_LOCK (&thd
->status_mutex
);
1063 MUTEX_UNLOCK (&thd
->status_mutex
);
1064 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1065 log_write ("%s (%i): %s", __FUNCTION__
, __LINE__
, pwmd_strerror (rc
));
1071 client_thread (void *data
)
1073 struct client_thread_s
*thd
= data
;
1074 struct client_s
*cl
= xcalloc (1, sizeof (struct client_s
));
1075 struct slist_s
*list
;
1077 #ifndef HAVE_PTHREAD_CANCEL
1078 INIT_SIGNAL (SIGUSR2
, catch_thread_signal
);
1081 #ifdef HAVE_PR_SET_NAME
1082 prctl (PR_SET_NAME
, "client");
1084 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1088 log_write ("%s(%i): %s", __FILE__
, __LINE__
,
1089 pwmd_strerror (GPG_ERR_ENOMEM
));
1093 MUTEX_LOCK (&cn_mutex
);
1094 pthread_cleanup_push (free_client_cb
, thd
);
1099 list
= slist_append (cn_thread_list
, thd
);
1101 cn_thread_list
= list
;
1104 log_write ("%s(%i): %s", __FILE__
, __LINE__
,
1105 pwmd_strerror (GPG_ERR_ENOMEM
));
1106 MUTEX_UNLOCK (&cn_mutex
);
1110 if (fcntl (thd
->status_msg_pipe
[0], F_SETFL
, O_NONBLOCK
) == -1)
1111 rc
= gpg_error_from_errno (errno
);
1114 if (fcntl (thd
->status_msg_pipe
[1], F_SETFL
, O_NONBLOCK
) == -1)
1115 rc
= gpg_error_from_errno (errno
);
1117 MUTEX_UNLOCK (&cn_mutex
);
1121 log_write ("%s(%i): %s", __FILE__
, __LINE__
, pwmd_strerror (rc
));
1125 if (new_connection (cl
))
1129 struct pollfd fds
[2];
1131 fds
[0].fd
= thd
->fd
;
1132 fds
[0].events
= POLLIN
;
1133 fds
[1].fd
= thd
->status_msg_pipe
[0];
1134 fds
[1].events
= POLLIN
;
1136 send_status_all (STATUS_CLIENTS
, NULL
);
1137 rc
= send_status (cl
->ctx
, STATUS_CACHE
, NULL
);
1140 log_write ("%s(%i): %s", __FILE__
, __LINE__
, pwmd_strerror (rc
));
1149 n
= poll (fds
, 2, 100);
1152 log_write ("%s", strerror (errno
));
1157 if (thd
->remote
&& thd
->tls
&& thd
->tls
->rehandshake
)
1163 if (thd
->tls
->rehandshake
== 1)
1165 prio
= config_get_string ("global", "tls_cipher_suite");
1168 thd
->tls
->rehandshake
= 0;
1172 ret
= gnutls_priority_set_direct (thd
->tls
->ses
, prio
, &e
);
1173 if (ret
== GNUTLS_E_SUCCESS
)
1175 rc
= send_status (cl
->ctx
, STATUS_REHANDSHAKE
, NULL
);
1178 rc
= assuan_send_data (cl
->ctx
, NULL
, 0);
1181 ret
= gnutls_rehandshake (thd
->tls
->ses
);
1184 log_write ("%s", gnutls_strerror (ret
));
1185 thd
->tls
->rehandshake
= 0;
1188 thd
->tls
->rehandshake
= 2;
1193 log_write ("%s", pwmd_strerror (rc
));
1196 log_write ("%s: %s", gnutls_strerror (ret
), e
);
1207 if (fds
[1].revents
& POLLIN
)
1210 if (!thd
->remote
|| (thd
->tls
&& !thd
->tls
->rehandshake
))
1213 rc
= send_msg_queue (thd
);
1214 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1219 #ifdef HAVE_PTHREAD_CANCEL
1220 if (!(fds
[0].revents
& POLLIN
))
1222 if (thd
->fd
!= -1 && !(fds
[0].revents
& POLLIN
))
1226 rc
= assuan_process_next (cl
->ctx
, &eof
);
1229 if (gpg_err_code (rc
) == GPG_ERR_EOF
|| eof
)
1232 log_write ("assuan_process_next(): rc=%u %s", rc
,
1233 pwmd_strerror (rc
));
1234 if (rc
== gpg_error (GPG_ERR_ETIMEDOUT
))
1237 rc
= send_error (cl
->ctx
, rc
);
1240 log_write ("assuan_process_done(): rc=%u %s", rc
,
1241 pwmd_strerror (rc
));
1246 /* Since the msg queue pipe fd's are non-blocking, check for
1247 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1248 * client has already disconnected and will be converted to
1249 * GPG_ERR_EOF during assuan_process_next().
1252 if (!thd
->remote
|| (thd
->tls
&& !thd
->tls
->rehandshake
))
1255 rc
= send_msg_queue (thd
);
1256 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1262 /* Don't do pthread_exit() here because any set pthread_cleanup_push
1263 * functions would be called after a command failed but then the client
1264 * exited normally which may lead to a double free. */
1265 pthread_cleanup_pop (1);
1270 xml_import (const char *filename
, const char *outfile
, char **keyid
,
1271 char **sign_keyid
, char *keyfile
, const char *keyparam
,
1280 struct crypto_s
*crypto
= NULL
;
1282 if (stat (filename
, &st
) == -1)
1284 rc
= gpg_error_from_errno (errno
);
1288 fd
= open (filename
, O_RDONLY
);
1290 return gpg_error_from_errno (errno
);
1292 xmlbuf
= xmalloc (st
.st_size
+ 1);
1296 return GPG_ERR_ENOMEM
;
1299 if (read (fd
, xmlbuf
, st
.st_size
) == -1)
1301 rc
= gpg_error_from_errno (errno
);
1308 xmlbuf
[st
.st_size
] = 0;
1309 // Be sure the document validates.
1310 doc
= xmlReadDoc (xmlbuf
, NULL
, "UTF-8", XML_PARSE_NOBLANKS
);
1313 return GPG_ERR_BAD_DATA
;
1315 xmlNodePtr n
= xmlDocGetRootElement (doc
);
1316 if (n
&& !xmlStrEqual (n
->name
, (xmlChar
*) "pwmd"))
1317 rc
= GPG_ERR_BAD_DATA
;
1321 rc
= xml_validate_import (NULL
, n
? n
->children
: n
);
1324 rc
= crypto_init (&crypto
, NULL
, filename
, keyfile
!= NULL
, keyfile
);
1329 crypto
->flags
|= CRYPTO_FLAG_KEYFILE
;
1330 crypto
->keyfile
= str_dup (keyfile
);
1333 xmlDocDumpMemory (doc
, &crypto
->plaintext
, &len
);
1335 crypto
->plaintext_size
= len
;
1337 rc
= GPG_ERR_ENOMEM
;
1344 if (!symmetric
&& (keyparam
|| !keyid
))
1350 fd
= open (keyparam
, O_RDONLY
);
1352 rc
= gpg_error_from_errno (errno
);
1356 if (stat (keyparam
, &st
) == -1)
1357 rc
= gpg_error_from_errno (errno
);
1361 buf
= xmalloc (st
.st_size
+1);
1363 rc
= GPG_ERR_ENOMEM
;
1367 len
= read (fd
, buf
, st
.st_size
);
1368 if (len
!= st
.st_size
)
1369 rc
= gpg_error_from_errno (errno
);
1382 buf
= crypto_default_key_params ();
1384 rc
= GPG_ERR_ENOMEM
;
1388 rc
= crypto_genkey (NULL
, crypto
, (unsigned char *)buf
);
1394 crypto
->save
.pubkey
= strv_dup (keyid
);
1395 crypto
->save
.sigkey
= strv_dup (sign_keyid
);
1400 crypto
->flags
|= symmetric
? CRYPTO_FLAG_SYMMETRIC
: 0;
1401 rc
= crypto_encrypt (NULL
, crypto
);
1407 if (!strcmp (outfile
, "-"))
1410 xfree (crypto
->plaintext
);
1411 crypto
->plaintext
= NULL
;
1412 xfree (crypto
->filename
);
1413 crypto
->filename
= outfile
? str_dup (outfile
) : NULL
;
1414 rc
= crypto_write_file (crypto
);
1418 crypto_free (crypto
);
1423 do_cache_push (struct crypto_s
*crypto
)
1427 struct cache_data_s
*cdata
;
1432 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1435 if (valid_filename (crypto
->filename
) == 0)
1437 log_write (_("%s: Invalid characters in filename"), crypto
->filename
);
1438 return GPG_ERR_INV_VALUE
;
1441 rc
= lock_flock (NULL
, crypto
->filename
, LOCK_SH
, &fd
);
1443 rc
= crypto_decrypt (NULL
, crypto
);
1450 rc
= xml_parse_doc ((char *) crypto
->plaintext
, crypto
->plaintext_size
, &doc
);
1454 log_write ("%s", pwmd_strerror (rc
));
1458 cdata
= xcalloc (1, sizeof (struct cache_data_s
));
1463 return GPG_ERR_ENOMEM
;
1466 rc
= get_checksum (crypto
->filename
, &crc
, &len
);
1471 cache_free_data_once (cdata
);
1476 rc
= cache_encrypt (crypto
);
1479 cdata
->doc
= crypto
->plaintext
;
1480 cdata
->size
= crypto
->plaintext_size
;
1481 crypto
->plaintext
= NULL
;
1482 cdata
->pubkey
= crypto
->pubkey
;
1483 cdata
->sigkey
= crypto
->sigkey
;
1484 crypto
->pubkey
= NULL
;
1485 crypto
->sigkey
= NULL
;
1490 cache_free_data_once (cdata
);
1494 int timeout
= config_get_integer (crypto
->filename
, "cache_timeout");
1495 rc
= cache_add_file (crypto
->filename
, cdata
, timeout
);
1500 init_client (int fd
, const char *addr
)
1503 struct client_thread_s
*new = xcalloc (1, sizeof (struct client_thread_s
));
1508 log_write ("%s: %s", __FUNCTION__
, pwmd_strerror (ENOMEM
));
1509 return GPG_ERR_ENOMEM
;
1512 MUTEX_LOCK (&cn_mutex
);
1513 pthread_cleanup_push (release_mutex_cb
, &cn_mutex
);
1514 new->conntime
= time (NULL
);
1516 if (pipe (new->status_msg_pipe
) == -1)
1517 rc
= gpg_error_from_errno (errno
);
1519 pthread_mutex_init (&new->status_mutex
, NULL
);
1524 new->remote
= addr
? 1 : 0;
1526 new->peeraddr
= str_dup (addr
);
1529 rc
= create_thread (client_thread
, new, &new->tid
, 1);
1532 close (new->status_msg_pipe
[0]);
1533 close (new->status_msg_pipe
[1]);
1534 pthread_mutex_destroy (&new->status_mutex
);
1541 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1542 (pthread_t
*) new->tid
, fd
, addr
);
1544 log_write (_("new connection: tid=%p, fd=%i"),
1545 (pthread_t
*) new->tid
, fd
);
1548 pthread_cleanup_pop (1);
1554 log_write ("%s(%i): %s", __FILE__
, __LINE__
, pwmd_strerror (rc
));
1560 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1562 get_in_addr (struct sockaddr
*sa
)
1564 if (sa
->sa_family
== AF_INET
)
1565 return &(((struct sockaddr_in
*) sa
)->sin_addr
);
1567 return &(((struct sockaddr_in6
*) sa
)->sin6_addr
);
1571 start_stop_tls_with_protocol (int ipv6
, int term
)
1573 struct addrinfo hints
, *servinfo
, *p
;
1574 int port
= config_get_integer ("global", "tcp_port");
1577 int *fd
= ipv6
? &tls6_fd
: &tls_fd
;
1579 if (term
|| config_get_boolean ("global", "enable_tcp") == 0)
1583 shutdown (tls6_fd
, SHUT_RDWR
);
1590 shutdown (tls_fd
, SHUT_RDWR
);
1598 memset (&hints
, 0, sizeof (hints
));
1599 hints
.ai_family
= ipv6
? AF_INET6
: AF_INET
;
1600 hints
.ai_socktype
= SOCK_STREAM
;
1601 hints
.ai_flags
= AI_PASSIVE
;
1602 snprintf (buf
, sizeof (buf
), "%i", port
);
1604 if ((n
= getaddrinfo (NULL
, buf
, &hints
, &servinfo
)) == -1)
1606 log_write ("getaddrinfo(): %s", gai_strerror (n
));
1610 for (n
= 0, p
= servinfo
; p
!= NULL
; p
= p
->ai_next
)
1614 if ((ipv6
&& p
->ai_family
!= AF_INET6
)
1615 || (!ipv6
&& p
->ai_family
!= AF_INET
))
1618 if ((*fd
= socket (p
->ai_family
, p
->ai_socktype
, p
->ai_protocol
)) == -1)
1620 log_write ("socket(): %s", strerror (errno
));
1624 if (setsockopt (*fd
, SOL_SOCKET
, SO_REUSEADDR
, &r
, sizeof (int)) == -1)
1626 log_write ("setsockopt(): %s",
1627 pwmd_strerror (gpg_error_from_errno (errno
)));
1628 freeaddrinfo (servinfo
);
1632 if (bind (*fd
, p
->ai_addr
, p
->ai_addrlen
) == -1)
1635 log_write ("bind(): %s",
1636 pwmd_strerror (gpg_error_from_errno (errno
)));
1644 freeaddrinfo (servinfo
);
1649 #if HAVE_DECL_SO_BINDTODEVICE != 0
1650 char *tmp
= config_get_string ("global", "tcp_interface");
1651 if (tmp
&& setsockopt (*fd
, SOL_SOCKET
, SO_BINDTODEVICE
, tmp
,
1652 strlen (tmp
)) == -1)
1654 log_write ("setsockopt(): %s",
1655 pwmd_strerror (gpg_error_from_errno (errno
)));
1663 if (listen (*fd
, 128) == -1)
1665 log_write ("listen(): %s", strerror (errno
));
1672 start_stop_tls_with_protocol (0, 1);
1685 start_stop_tls (int term
)
1687 char *s
= config_get_string ("global", "tcp_bind");
1693 if (!strcmp (s
, "any"))
1695 b
= start_stop_tls_with_protocol (0, term
);
1697 b
= start_stop_tls_with_protocol (1, term
);
1699 else if (!strcmp (s
, "ipv4"))
1700 b
= start_stop_tls_with_protocol (0, term
);
1701 else if (!strcmp (s
, "ipv6"))
1702 b
= start_stop_tls_with_protocol (1, term
);
1709 gpg_error_t rc
= tls_init_params ();
1712 start_stop_tls_with_protocol (0, 1);
1723 do_tls_accept (struct pollfd
*fds
)
1725 struct sockaddr_storage raddr
;
1726 socklen_t slen
= sizeof (raddr
);
1728 char s
[INET6_ADDRSTRLEN
];
1730 if (!(fds
->revents
& POLLIN
))
1733 fd
= accept (fds
->fd
, (struct sockaddr
*) &raddr
, &slen
);
1738 if (errno
!= EAGAIN
&& !quit
)
1739 log_write ("%s: %s", __FUNCTION__
,
1740 pwmd_strerror (gpg_error_from_syserror()));
1742 return gpg_error_from_errno (e
);
1745 inet_ntop (raddr
.ss_family
, get_in_addr ((struct sockaddr
*) &raddr
), s
,
1747 (void) init_client (fd
, s
);
1753 accept_thread (void *arg
)
1755 int sockfd
= *(int *) arg
;
1756 #ifndef HAVE_PTHREAD_CANCEL
1757 INIT_SIGNAL (SIGUSR2
, catch_thread_signal
);
1758 fcntl (sockfd
, F_SETFL
, O_NONBLOCK
);
1761 #ifdef HAVE_PR_SET_NAME
1762 prctl (PR_SET_NAME
, "accept");
1764 pthread_setspecific (thread_name_key
, str_asprintf ("!%s", __FUNCTION__
));
1768 socklen_t slen
= sizeof (struct sockaddr_un
);
1769 struct sockaddr_un raddr
;
1771 struct pollfd fds
[3];
1774 memset (fds
, 0, sizeof (fds
));
1776 fds
[s
++].events
= POLLIN
;
1782 fds
[s
++].events
= POLLIN
;
1789 fds
[s
].fd
= tls6_fd
;
1790 fds
[s
++].events
= POLLIN
;
1793 fds
[s
].fd
= tls6_fd
;
1796 s
= poll (fds
, s
, 500);
1800 log_write ("%s", strerror (errno
));
1806 if (fds
[0].revents
& POLLIN
)
1808 fd
= accept (sockfd
, (struct sockaddr
*) &raddr
, &slen
);
1811 if (errno
== EMFILE
|| errno
== ENFILE
)
1812 log_write ("%s: %s", __FUNCTION__
,
1813 pwmd_strerror (gpg_error_from_errno (errno
)));
1814 else if (errno
!= EAGAIN
&& errno
!= EINTR
)
1816 if (!quit
) // probably EBADF
1817 log_write ("%s: %s", __FUNCTION__
,
1818 pwmd_strerror (gpg_error_from_errno (errno
)));
1826 (void) init_client (fd
, NULL
);
1830 if (tls_fd
!= -1 && fds
[1].fd
== tls_fd
)
1831 (void)do_tls_accept (&fds
[1]);
1833 if (tls6_fd
!= -1 && fds
[1].fd
== tls6_fd
)
1834 (void)do_tls_accept (&fds
[1]);
1836 if (tls6_fd
!= -1 && fds
[2].fd
== tls6_fd
)
1837 (void)do_tls_accept (&fds
[2]);
1841 /* Just in case accept() failed for some reason other than EBADF */
1847 cache_timer_thread (void *arg
)
1850 #ifndef HAVE_PTHREAD_CANCEL
1851 INIT_SIGNAL (SIGUSR2
, catch_thread_signal
);
1854 #ifdef HAVE_PR_SET_NAME
1855 prctl (PR_SET_NAME
, "timer");
1857 pthread_setspecific (thread_name_key
, str_asprintf ("!%s", __FUNCTION__
));
1861 struct timeval tv
= { 1, 0 };
1862 unsigned keepalive
= config_get_integer ("global", "keepalive_interval");
1865 select (0, NULL
, NULL
, NULL
, &tv
);
1866 cache_adjust_timeout ();
1868 if (++k
>= keepalive
)
1870 send_status_all (STATUS_KEEPALIVE
, NULL
);
1879 signal_loop (sigset_t sigset
)
1888 sigwait (&sigset
, &sig
);
1889 log_write (_("caught signal %i (%s)"), sig
, strsignal (sig
));
1894 pthread_cond_signal (&rcfile_cond
);
1897 log_write (_("clearing file cache"));
1898 cache_clear (NULL
, NULL
, 1);
1899 send_status_all (STATUS_CACHE
, NULL
);
1915 log_write (_ ("Caught signal %i (%s). Exiting."), sig
, strsignal (sig
));
1916 #ifdef HAVE_BACKTRACE
1917 BACKTRACE (__FUNCTION__
);
1923 cancel_all_clients ()
1927 MUTEX_LOCK (&cn_mutex
);
1928 t
= slist_length (cn_thread_list
);
1929 for (i
= 0; i
< t
; i
++)
1931 struct client_thread_s
*thd
= slist_nth_data (cn_thread_list
, i
);
1933 #ifdef HAVE_PTHREAD_CANCEL
1934 pthread_cancel (thd
->tid
);
1936 pthread_kill (thd
->tid
, SIGUSR2
);
1940 while (slist_length (cn_thread_list
))
1942 MUTEX_UNLOCK (&cn_mutex
);
1944 MUTEX_LOCK (&cn_mutex
);
1947 MUTEX_UNLOCK (&cn_mutex
);
1951 server_loop (int sockfd
, char **socketpath
)
1953 pthread_t cache_timeout_tid
;
1954 int cancel_timeout_thread
= 0, cancel_accept_thread
= 0;
1961 sigemptyset (&sigset
);
1964 sigaddset (&sigset
, SIGTERM
);
1965 sigaddset (&sigset
, SIGINT
);
1967 /* Clears the file cache. */
1968 sigaddset (&sigset
, SIGUSR1
);
1970 /* Configuration file reloading. */
1971 sigaddset (&sigset
, SIGHUP
);
1973 #ifndef HAVE_PTHREAD_CANCEL
1975 The socket, cache and rcfile threads use this signal when
1976 pthread_cancel() is unavailable. Prevent the main thread from
1977 catching this signal from another process.
1979 sigaddset (&sigset
, SIGUSR2
);
1982 /* An assertion failure. */
1983 signal (SIGABRT
, catchsig
);
1984 sigaddset (&sigset
, SIGABRT
);
1985 sigprocmask (SIG_BLOCK
, &sigset
, NULL
);
1987 #ifndef HAVE_PTHREAD_CANCEL
1988 /* Remove this signal from the watched signals in signal_loop(). */
1989 sigdelset (&sigset
, SIGUSR2
);
1992 /* Can show a backtrace of the stack in the log. */
1993 signal (SIGSEGV
, catchsig
);
1995 char *p
= get_username (getuid());
1996 log_write (_("%s started for user %s"), PACKAGE_STRING
, p
);
2000 if (config_get_boolean ("global", "enable_tcp"))
2001 log_write (_("Listening on %s and TCP port %i"), *socketpath
,
2002 config_get_integer ("global", "tcp_port"));
2004 log_write (_("Listening on %s"), *socketpath
);
2006 log_write (_("Listening on %s"), *socketpath
);
2009 rc
= create_thread (reload_rcfile_thread
, NULL
, &rcfile_tid
, 0);
2012 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2013 pwmd_strerror (rc
));
2017 rc
= create_thread (cache_timer_thread
, NULL
, &cache_timeout_tid
, 0);
2020 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2021 pwmd_strerror (rc
));
2025 cancel_timeout_thread
= 1;
2026 rc
= create_thread (accept_thread
, &sockfd
, &accept_tid
, 0);
2029 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2030 pwmd_strerror (rc
));
2034 cancel_accept_thread
= 1;
2036 signal_loop (sigset
);
2042 * We're out of the main server loop. This happens when a signal was sent
2043 * to terminate the daemon. We'll wait for all clients to disconnect
2044 * before exiting but exit immediately if another termination signal is
2047 if (cancel_accept_thread
)
2049 #ifdef HAVE_PTHREAD_CANCEL
2050 int n
= pthread_cancel (accept_tid
);
2052 int n
= pthread_kill (accept_tid
, SIGUSR2
);
2055 pthread_join (accept_tid
, NULL
);
2058 if (cancel_timeout_thread
)
2060 #ifdef HAVE_PTHREAD_CANCEL
2061 n
= pthread_cancel (cache_timeout_tid
);
2063 n
= pthread_kill (cache_timeout_tid
, SIGUSR2
);
2066 pthread_join (cache_timeout_tid
, NULL
);
2072 shutdown (sockfd
, SHUT_RDWR
);
2074 unlink (*socketpath
);
2075 xfree (*socketpath
);
2077 MUTEX_LOCK (&cn_mutex
);
2078 n
= slist_length (cn_thread_list
);
2079 MUTEX_UNLOCK (&cn_mutex
);
2082 cancel_all_clients ();
2084 free_all_clients ();
2088 return segv
? EXIT_FAILURE
: EXIT_SUCCESS
;;
2095 ("Failed to add a file to the cache. Use --force to force startup. Exiting."));
2096 cache_clear (NULL
, NULL
, 1);
2100 usage (const char *pn
, int status
)
2102 FILE *fp
= status
== EXIT_FAILURE
? stderr
: stdout
;
2104 fprintf (fp
, _("Usage: %s [OPTIONS] [file1] [...]\n"
2105 " --debug=[a:..][,g:N][,t:N] enable debugging (a:[ixedsc],g:[1-9],t:[0-N])\n"
2106 " -f, --rcfile=filename load the specfied configuration file\n"
2107 " (~/.pwmd/config)\n"
2108 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2109 " --kill terminate an existing instance of pwmd\n"
2110 " -n, --no-fork run as a foreground process\n"
2111 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2112 " --ignore, --force ignore file errors during startup\n"
2113 " -o, --outfile=filename output file when importing or converting\n"
2114 " -C, --convert=filename convert a version 2 data file to version 3\n"
2115 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2116 " -k, --passphrase-file=file for use when importing or converting\n"
2117 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2119 " --no-passphrase when importing or converting\n"
2120 " --keyid=keyID[,..] public key to use when encrypting\n"
2121 " --sign-keyid=fpr[,..] fingerprint of the signing key to use\n"
2122 " --symmetric use conventional encryption with optional signer\n"
2123 " --keyparam=filename custom key parameters to use (gpg default)\n"
2124 " --help this help text\n"
2125 " --version show version and compile time features\n"),
2131 unlink_stale_socket (const char *sock
, const char *pidfile
)
2133 log_write (_ ("removing stale socket %s"), sock
);
2139 test_pidfile (const char *path
, const char *sock
, char *buf
, size_t buflen
,
2140 char **pidfile
, int create
, mode_t mode
, int terminate
)
2148 snprintf (buf
, buflen
, "%s/%s.pid", homedir
, sock
);
2149 *pidfile
= str_dup (buf
);
2150 fd
= open (buf
, O_RDONLY
);
2153 fd
= open (*pidfile
, O_CREAT
|O_WRONLY
|O_TRUNC
, mode
);
2157 if (!create
&& errno
!= ENOENT
)
2159 log_write ("%s: %s", buf
, pwmd_strerror (errno
));
2164 else if (!create
&& !terminate
)
2167 log_write ("%s: %s", *pidfile
, strerror (errno
));
2173 snprintf (buf
, buflen
, "%i", getpid ());
2174 ssize_t ret
= write (fd
, buf
, strlen (buf
));
2176 log_write ("%s (%i): %s", __FUNCTION__
, __LINE__
,
2177 pwmd_strerror (gpg_error_from_syserror ()));
2182 len
= read (fd
, buf
, buflen
);
2186 unlink_stale_socket (path
, *pidfile
);
2190 if (sscanf (buf
, "%5i", &pid
) != 1 || pid
== 0)
2194 unlink_stale_socket (path
, *pidfile
);
2199 if (kill (pid
, 0) == -1)
2201 unlink_stale_socket (path
, *pidfile
);
2207 if (kill (pid
, SIGTERM
) == -1)
2208 log_write ("%s: %s", path
, pwmd_strerror (errno
));
2211 log_write (_ ("an instance for socket %s is already running"), path
);
2219 parse_debug_level (const char *str
, unsigned *debug
, int *gpgme
, int *tls
)
2225 for (p
= str
; p
&& *p
; p
++)
2227 if (*p
== 'a') // assuan debug flags
2237 level
|= ASSUAN_LOG_INIT
;
2240 level
|= ASSUAN_LOG_CTX
;
2243 level
|= ASSUAN_LOG_ENGINE
;
2246 level
|= ASSUAN_LOG_DATA
;
2249 level
|= ASSUAN_LOG_SYSIO
;
2252 level
|= ASSUAN_LOG_CONTROL
;
2267 else if (*p
== 'g' || *p
== 't') // gpgme and TLS debug level
2275 if (!isdigit (*++p
))
2284 if (tl
< 0 || gl
< 0 || gl
> 9)
2287 while (isdigit (*p
))
2291 if (*(p
+1) && *(p
+1) != ',')
2311 main (int argc
, char *argv
[])
2314 struct sockaddr_un addr
;
2316 char *socketpath
= NULL
, *socketdir
, *socketname
= NULL
;
2317 char *socketarg
= NULL
;
2318 char *datadir
= NULL
;
2319 char *pidfile
= NULL
;
2323 char **cache_push
= NULL
;
2324 char *import
= NULL
, *keyid
= NULL
, *sign_keyid
= NULL
;
2325 char *keyparam
= NULL
;
2326 int estatus
= EXIT_FAILURE
;
2328 char *outfile
= NULL
;
2331 int show_version
= 0;
2334 char *keyfile
= NULL
;
2339 int gpgme_level
= -1;
2341 /* Must maintain the same order as longopts[] */
2344 OPT_VERSION
, OPT_HELP
, OPT_HOMEDIR
, OPT_NO_FORK
, OPT_DISABLE_DUMP
,
2345 OPT_FORCE
, OPT_RCFILE
, OPT_PASSPHRASE_FILE
, OPT_IMPORT
, OPT_OUTFILE
,
2346 OPT_KEYID
, OPT_SIGN_KEYID
, OPT_SYMMETRIC
, OPT_KEYPARAM
, OPT_KILL
,
2349 const char *optstring
= "nf:C:k:I:o:s";
2350 const struct option longopts
[] = {
2351 {"version", no_argument
, 0, 0},
2352 {"help", no_argument
, 0, 0},
2353 {"homedir", required_argument
, 0, 0},
2354 {"no-fork", no_argument
, 0, 'n'},
2355 {"disable_dump", no_argument
, 0, 0},
2356 {"force", no_argument
, 0, 0},
2357 {"rcfile", required_argument
, 0, 'f'},
2358 {"passphrase-file", required_argument
, 0, 'k'},
2359 {"import", required_argument
, 0, 'I'},
2360 {"outfile", required_argument
, 0, 'o'},
2361 {"keyid", required_argument
, 0, 0},
2362 {"sign-keyid", required_argument
, 0, 0},
2363 {"symmetric", no_argument
, 0, 's'},
2364 {"keyparam", required_argument
, 0, 0},
2365 {"kill", no_argument
, 0, 0},
2366 {"debug", required_argument
, 0, 0},
2374 #ifdef HAVE_SETRLIMIT
2377 rl
.rlim_cur
= rl
.rlim_max
= 0;
2379 if (setrlimit (RLIMIT_CORE
, &rl
) != 0)
2380 err (EXIT_FAILURE
, "setrlimit()");
2383 #ifdef HAVE_PR_SET_DUMPABLE
2384 prctl (PR_SET_DUMPABLE
, 0);
2389 setlocale (LC_ALL
, "");
2390 bindtextdomain ("pwmd", LOCALEDIR
);
2391 textdomain ("pwmd");
2394 if (setup_crypto ())
2395 exit (EXIT_FAILURE
);
2398 tls_level
= tls_level
== -1 ? 1 : tls_level
;
2399 gnutls_global_set_log_level (tls_level
);
2403 xmlMemSetup (xfree
, xmalloc
, xrealloc
, str_dup
);
2409 while ((opt
= getopt_long (argc
, argv
, optstring
, longopts
, &optindex
))
2430 rcfile
= str_dup (optarg
);
2436 usage (argv
[0], EXIT_FAILURE
);
2442 if (parse_debug_level (optarg
, &assuan_level
, &gpgme_level
,
2444 usage (argv
[0], EXIT_FAILURE
);
2453 usage (argv
[0], EXIT_SUCCESS
);
2456 homedir
= str_dup (optarg
);
2461 case OPT_DISABLE_DUMP
:
2468 rcfile
= str_dup (optarg
);
2470 case OPT_PASSPHRASE_FILE
:
2482 case OPT_SIGN_KEYID
:
2483 sign_keyid
= optarg
;
2492 usage (argv
[0], EXIT_FAILURE
);
2500 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016\n"
2502 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2503 "Compile time features:\n%s"), PACKAGE_STRING
,
2506 "+PWMD_HOMEDIR=" PWMD_HOMEDIR
"\n"
2534 exit (EXIT_SUCCESS
);
2539 homedir
= str_dup(PWMD_HOMEDIR
);
2541 homedir
= str_asprintf ("%s/.pwmd", get_home_dir());
2544 if (mkdir (homedir
, 0700) == -1 && errno
!= EEXIST
)
2545 err (EXIT_FAILURE
, "%s", homedir
);
2548 rcfile
= str_asprintf ("%s/config", homedir
);
2550 pthread_key_create (&last_error_key
, free_key
);
2551 #ifndef HAVE_PTHREAD_CANCEL
2552 pthread_key_create (&signal_thread_key
, free_key
);
2555 pthread_mutexattr_t attr
;
2556 pthread_mutexattr_init (&attr
);
2557 pthread_mutexattr_settype (&attr
, PTHREAD_MUTEX_RECURSIVE
);
2558 pthread_mutex_init (&rcfile_mutex
, &attr
);
2559 global_config
= config_parse (rcfile
, 0);
2562 pthread_mutexattr_destroy (&attr
);
2563 pthread_mutex_destroy (&rcfile_mutex
);
2564 exit (EXIT_FAILURE
);
2567 p
= config_get_string ("global", "gpg_homedir");
2569 datadir
= str_asprintf ("%s/.gnupg", homedir
);
2571 datadir
= expand_homedir (p
);
2574 if (mkdir (datadir
, 0700) == -1 && errno
!= EEXIST
)
2575 err (EXIT_FAILURE
, "%s", datadir
);
2577 if (gpgme_level
!= -1)
2579 char s
[2] = { gpgme_level
+ '0', 0 };
2581 if (getenv ("GPGME_DEBUG"))
2582 log_write (_ ("Overriding GPGME_DEBUG environment with level %u!"),
2585 gpgme_set_global_flag ("debug", s
);
2588 rc
= gpgme_set_engine_info (GPGME_PROTOCOL_OpenPGP
, NULL
, datadir
);
2591 snprintf (buf
, sizeof (buf
), "%s/data", homedir
);
2592 if (mkdir (buf
, 0700) == -1 && errno
!= EEXIST
)
2593 err (EXIT_FAILURE
, "%s", buf
);
2595 datadir
= str_dup (buf
);
2596 pthread_cond_init (&rcfile_cond
, NULL
);
2597 pthread_mutex_init (&cn_mutex
, &attr
);
2598 pthread_mutexattr_destroy (&attr
);
2602 x
= config_get_int_param (global_config
, "global", "priority", &exists
);
2603 if (exists
&& x
!= atoi(INVALID_PRIORITY
))
2606 if (setpriority (PRIO_PROCESS
, 0, x
) == -1)
2608 log_write ("setpriority(): %s",
2609 pwmd_strerror (gpg_error_from_errno (errno
)));
2613 #ifdef HAVE_MLOCKALL
2614 if (disable_mlock
== 0 && mlockall (MCL_CURRENT
| MCL_FUTURE
) == -1)
2616 log_write ("mlockall(): %s",
2617 pwmd_strerror (gpg_error_from_errno (errno
)));
2625 log_write ("pwmd: ERR %i: %s", rc
, pwmd_strerror (rc
));
2626 exit (EXIT_FAILURE
);
2631 char **keyids
= NULL
, **sign_keyids
= NULL
;
2633 if (!outfile
|| !*outfile
|| argc
!= optind
)
2634 usage (argv
[0], EXIT_FAILURE
);
2637 keyids
= str_split (keyid
, ",", 0);
2639 sign_keyids
= str_split (sign_keyid
, ",", 0);
2640 rc
= xml_import (import
, outfile
, keyids
, sign_keyids
, keyfile
, keyparam
, sym
);
2642 strv_free (sign_keyids
);
2645 if (gpg_err_source (rc
) == GPG_ERR_SOURCE_UNKNOWN
)
2646 rc
= gpg_error (rc
);
2648 log_write ("%s: %u: %s", import
, rc
, pwmd_strerror (rc
));
2651 config_free (global_config
);
2653 exit (rc
? EXIT_FAILURE
: EXIT_SUCCESS
);
2656 p
= config_get_string ("global", "socket_path");
2658 p
= str_asprintf ("%s/socket", homedir
);
2660 socketarg
= expand_homedir (p
);
2664 disable_list_and_dump
= config_get_boolean ("global",
2665 "disable_list_and_dump");
2667 disable_list_and_dump
= secure
;
2669 cache_push
= config_get_list ("global", "cache_push");
2671 while (optind
< argc
)
2673 if (strv_printf (&cache_push
, "%s", argv
[optind
++]) == 0)
2674 errx (EXIT_FAILURE
, "%s", pwmd_strerror (GPG_ERR_ENOMEM
));
2677 if (strchr (socketarg
, '/') == NULL
)
2679 socketdir
= getcwd (buf
, sizeof (buf
));
2680 socketname
= str_dup (socketarg
);
2681 socketpath
= str_asprintf ("%s/%s", socketdir
, socketname
);
2685 socketname
= str_dup (strrchr (socketarg
, '/'));
2687 socketarg
[strlen (socketarg
) - strlen (socketname
) - 1] = 0;
2688 socketdir
= str_dup (socketarg
);
2689 socketpath
= str_asprintf ("%s/%s", socketdir
, socketname
);
2692 if (chdir (datadir
))
2694 log_write ("%s: %s", datadir
,
2695 pwmd_strerror (gpg_error_from_errno (errno
)));
2696 unlink (socketpath
);
2700 x
= test_pidfile (socketpath
, socketname
, buf
, sizeof(buf
), &pidfile
, 0,
2702 if (!terminate
&& x
)
2706 estatus
= x
!= 1 ? EXIT_FAILURE
: EXIT_SUCCESS
;
2711 * bind() doesn't like the full pathname of the socket or any non alphanum
2712 * characters so change to the directory where the socket is wanted then
2713 * create it then change to datadir.
2715 if (chdir (socketdir
))
2717 log_write ("%s: %s", socketdir
,
2718 pwmd_strerror (gpg_error_from_errno (errno
)));
2724 if ((sockfd
= socket (PF_UNIX
, SOCK_STREAM
, 0)) == -1)
2726 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
2730 addr
.sun_family
= AF_UNIX
;
2731 snprintf (addr
.sun_path
, sizeof (addr
.sun_path
), "%s", socketname
);
2733 if (bind (sockfd
, (struct sockaddr
*) &addr
, sizeof (struct sockaddr
)) ==
2736 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
2738 if (errno
== EADDRINUSE
)
2741 log_write (_("Either there is another pwmd running or '%s' is a \n"
2742 "stale socket. Please remove it manually."), socketpath
);
2749 char *t
= config_get_string ("global", "socket_perms");
2754 mode
= strtol (t
, NULL
, 8);
2758 if (chmod (socketname
, mode
) == -1)
2760 log_write ("%s: %s", socketname
,
2761 pwmd_strerror (gpg_error_from_errno (errno
)));
2771 xfree (--socketname
);
2773 if (chdir (datadir
))
2775 log_write ("%s: %s", datadir
,
2776 pwmd_strerror (gpg_error_from_errno (errno
)));
2783 if (config_get_boolean ("global", "enable_tcp"))
2785 if (!start_stop_tls (0))
2794 * Set the cache entry for a file. Prompts for the password.
2798 for (opt
= 0; cache_push
[opt
]; opt
++)
2800 struct crypto_s
*crypto
= NULL
;
2801 char *pw_file
= config_get_string (cache_push
[opt
],
2803 gpg_error_t rc
= crypto_init (&crypto
, NULL
, cache_push
[opt
],
2804 pw_file
!= NULL
, pw_file
);
2808 crypto
->flags
|= pw_file
? CRYPTO_FLAG_KEYFILE
: 0;
2809 crypto
->keyfile
= pw_file
;
2816 estatus
= EXIT_FAILURE
;
2820 rc
= do_cache_push (crypto
);
2823 log_write ("ERR %u: %s", rc
, pwmd_strerror(rc
));
2824 strv_free (cache_push
);
2826 estatus
= EXIT_FAILURE
;
2827 crypto_free (crypto
);
2831 log_write ("%s: %s", crypto
->filename
, pwmd_strerror(rc
));
2833 log_write (_("Successfully added '%s' to the cache."),
2836 crypto_free (crypto
);
2839 strv_free (cache_push
);
2840 log_write (!nofork
? _("Done. Daemonizing...") :
2841 _("Done. Waiting for connections..."));
2844 if (listen (sockfd
, 128) == -1)
2846 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
2855 log_write ("fork(): %s",
2856 pwmd_strerror (gpg_error_from_errno (errno
)));
2865 _exit (EXIT_SUCCESS
);
2869 (void)test_pidfile (socketpath
, socketname
, buf
, sizeof(buf
), &pidfile
, 1,
2872 pthread_key_create (&thread_name_key
, free_key
);
2873 pthread_setspecific (thread_name_key
, str_asprintf ("!%s", __FUNCTION__
));
2874 estatus
= server_loop (sockfd
, &socketpath
);
2877 if (socketpath
&& do_unlink
)
2879 unlink (socketpath
);
2885 gnutls_global_deinit ();
2886 tls_deinit_params ();
2890 #ifdef HAVE_PTHREAD_CANCEL
2891 pthread_cancel (rcfile_tid
);
2893 pthread_kill (rcfile_tid
, SIGUSR2
);
2894 pthread_cond_signal (&rcfile_cond
);
2896 pthread_join (rcfile_tid
, NULL
);
2899 pthread_cond_destroy (&rcfile_cond
);
2900 pthread_mutex_destroy (&rcfile_mutex
);
2901 pthread_key_delete (last_error_key
);
2902 #ifndef HAVE_PTHREAD_CANCEL
2903 pthread_key_delete (signal_thread_key
);
2907 config_free (global_config
);
2909 free_invoking_users (invoking_users
);
2911 xfree (home_directory
);
2913 xmlCleanupParser ();
2914 xmlCleanupGlobals ();
2920 if (estatus
== EXIT_SUCCESS
&& !terminate
)
2921 log_write (_("pwmd exiting normally"));
2923 pthread_key_delete (thread_name_key
);
2932 gpg_error_t
lock_flock (assuan_context_t ctx
, const char *filename
,
2938 *fd
= open (filename
, O_RDONLY
);
2940 return gpg_error_from_syserror ();
2942 TRY_FLOCK (ctx
, *fd
, type
, rc
);
2953 void unlock_flock (int *fd
)