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
100 static pthread_cond_t quit_cond
;
101 static pthread_mutex_t quit_mutex
;
102 static pthread_t keepalive_tid
;
104 static unsigned assuan_level
;
106 #ifndef HAVE_PTHREAD_CANCEL
107 static pthread_key_t signal_thread_key
;
113 static pthread_t tls_tid
;
114 static pthread_t tls6_tid
;
115 static int spawned_tls
;
116 static int spawned_tls6
;
118 static int start_stop_tls (int term
);
121 static gpg_error_t
do_cache_push (struct crypto_s
*crypto
);
122 static int signal_loop (sigset_t sigset
);
124 #ifndef HAVE_PTHREAD_CANCEL
125 #define INIT_THREAD_SIGNAL do { \
126 struct sigaction act; \
128 sigemptyset (&sigset); \
129 sigaddset (&sigset, SIGUSR2); \
130 pthread_sigmask (SIG_UNBLOCK, &sigset, NULL); \
131 memset (&act, 0, sizeof(act)); \
132 act.sa_flags = SA_SIGINFO; \
133 act.sa_mask = sigset; \
134 act.sa_sigaction = catch_thread_signal; \
135 sigaction (SIGUSR2, &act, NULL); \
139 catch_thread_signal (int sig
, siginfo_t
*info
, void *ctx
)
141 int *n
= (int *) pthread_getspecific (signal_thread_key
);
144 pthread_setspecific (signal_thread_key
, n
);
151 int n
= config_get_boolean ("global", "enable_logging");
155 char *p
= config_get_string ("global", "log_path");
157 if (!p
|| (logfile
&& p
&& log_fd
!= -1 && strcmp(p
, logfile
)))
168 logfile
= expand_homedir (p
);
182 log_syslog
= config_get_boolean ("global", "syslog");
184 openlog ("pwmd", LOG_NDELAY
| LOG_PID
, LOG_DAEMON
);
188 reload_rcfile_thread (void *arg
)
190 #ifndef HAVE_PTHREAD_CANCEL
191 int *n
= xmalloc (sizeof (int));
194 pthread_setspecific (signal_thread_key
, n
);
198 #ifdef HAVE_PR_SET_NAME
199 prctl (PR_SET_NAME
, "reload rcfile");
201 pthread_setspecific (thread_name_key
, str_asprintf ("!%s", __FUNCTION__
));
202 MUTEX_LOCK (&rcfile_mutex
);
206 struct slist_s
*keep
= NULL
;
207 struct slist_s
*config
;
208 int b
= disable_list_and_dump
;
210 pthread_cleanup_push (cleanup_mutex_cb
, &rcfile_mutex
);
211 pthread_cond_wait (&rcfile_cond
, &rcfile_mutex
);
212 #ifndef HAVE_PTHREAD_CANCEL
213 int *cancel
= (int *) pthread_getspecific (signal_thread_key
);
218 keep
= config_keep_save ();
219 log_write (_("reloading configuration file '%s'"), rcfile
);
221 config
= config_parse (rcfile
, 1);
224 config_free (global_config
);
225 global_config
= config
;
229 config_keep_restore (keep
);
230 disable_list_and_dump
= !disable_list_and_dump
? b
: 1;
233 /* Kill existing listening threads since the configured listening
234 * protocols may have changed. */
238 crypto_set_keepalive ();
239 pthread_cleanup_pop (0);
242 MUTEX_UNLOCK (&rcfile_mutex
);
247 send_error (assuan_context_t ctx
, gpg_error_t e
)
249 struct client_s
*client
= assuan_get_pointer (ctx
);
251 if (gpg_err_source (e
) == GPG_ERR_SOURCE_UNKNOWN
)
258 return assuan_process_done (ctx
, 0);
262 log_write ("ERR %i: %s", e
, pwmd_strerror (e
));
266 if (client
&& client
->xml_error
)
268 log_write ("%s", client
->xml_error
->message
);
269 xfree (client
->last_error
);
270 client
->last_error
= NULL
;
271 if (client
->xml_error
->message
)
272 client
->last_error
= str_dup (client
->xml_error
->message
);
274 e
= assuan_process_done (ctx
,
275 assuan_set_error (ctx
, e
,
276 client
->xml_error
->message
? client
->xml_error
->message
: NULL
));
277 xmlResetLastError ();
278 xmlResetError (client
->xml_error
);
279 xfree (client
->xml_error
);
280 client
->xml_error
= NULL
;
284 return assuan_process_done (ctx
,
285 assuan_set_error (ctx
, e
, pwmd_strerror (e
)));
289 log_write (const char *fmt
, ...)
295 pthread_t tid
= pthread_self ();
296 static pthread_mutex_t m
= PTHREAD_MUTEX_INITIALIZER
;
298 if ((!logfile
&& !isatty (STDERR_FILENO
) && !log_syslog
) || !fmt
)
301 pthread_mutex_lock (&m
);
302 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock
, &m
);
304 if (!cmdline
&& logfile
&& log_fd
== -1)
306 log_fd
= open (logfile
, O_WRONLY
| O_CREAT
| O_APPEND
, 0600);
308 warn ("%s", logfile
);
313 if (str_vasprintf (&args
, fmt
, ap
) != -1)
317 pthread_cleanup_push (xfree
, args
);
318 fprintf (stderr
, "pwmd: %s\n", args
);
320 pthread_cleanup_pop (1);
324 char *name
= pthread_getspecific (thread_name_key
);
327 pthread_cleanup_push (xfree
, args
);
328 snprintf (buf
, sizeof (buf
),
329 name
&& *name
== '!' ? "%s: " : name
? "%s(%p): " : "%s",
330 name
? *name
== '!' ? name
+1 : name
: "",
331 name
&& *name
== '!' ? 0 : name
? (pthread_t
*) tid
: 0);
334 if (!cmdline
&& log_syslog
&& !nofork
)
335 syslog (LOG_INFO
, "%s%s", name
, args
);
338 struct tm
*tm
= localtime (&now
);
340 strftime (tbuf
, sizeof (tbuf
), "%b %d %Y %H:%M:%S ", tm
);
341 tbuf
[sizeof (tbuf
) - 1] = 0;
343 if (args
[strlen (args
) - 1] == '\n')
344 args
[strlen (args
) - 1] = 0;
346 line
= str_asprintf ("%s %i %s%s\n", tbuf
, getpid (), name
,
348 pthread_cleanup_pop (1);
351 pthread_cleanup_push (xfree
, line
);
352 if (logfile
&& log_fd
!= -1)
354 ssize_t ret
= write (log_fd
, line
, strlen (line
));
361 fprintf (stdout
, "%s", line
);
365 pthread_cleanup_pop (1);
371 pthread_cleanup_pop (0);
373 if (log_fd
!= -1 && log_keepopen
<= 0)
379 pthread_mutex_unlock (&m
);
387 if (!gpgrt_check_version (REQUIRE_LIBGPGERROR_VERSION
))
389 fprintf (stderr
, _("gpgrt_check_version(): Incompatible libgpg-error. "
390 "Wanted %s, got %s.\n"), REQUIRE_LIBGPGERROR_VERSION
,
391 gpgrt_check_version (NULL
));
392 return GPG_ERR_UNKNOWN_VERSION
;
396 gpgrt_set_alloc_func (xrealloc_gpgrt
);
398 if (!assuan_check_version (REQUIRE_LIBASSUAN_VERSION
))
400 fprintf (stderr
, _("assuan_check_version(): Incompatible libassuan. "
401 "Wanted %s, got %s.\n"), REQUIRE_LIBASSUAN_VERSION
,
402 assuan_check_version (NULL
));
403 return GPG_ERR_UNKNOWN_VERSION
;
406 if (!gcry_check_version (REQUIRE_LIBGCRYPT_VERSION
))
408 fprintf (stderr
, _("gcry_check_version(): Incompatible libgcrypt. "
409 "Wanted %s, got %s.\n"), REQUIRE_LIBGCRYPT_VERSION
,
410 gcry_check_version (NULL
));
411 return GPG_ERR_UNKNOWN_VERSION
;
414 gcry_set_allocation_handler (xmalloc
, xmalloc
, NULL
, xrealloc
, xfree
);
416 if (!gpgme_check_version (REQUIRE_LIBGPGME_VERSION
))
418 fprintf (stderr
, _("gpgme_check_version(): Incompatible libgpgme. "
419 "Wanted %s, got %s.\n"), REQUIRE_LIBGPGME_VERSION
,
420 gpgme_check_version (NULL
));
421 return GPG_ERR_UNKNOWN_VERSION
;
424 rc
= gpgme_engine_check_version (GPGME_PROTOCOL_OPENPGP
);
427 fprintf (stderr
, _("gpgme_engine_check_version(GPGME_PROTOCOL_OPENPGP): %s"), gpgme_strerror (rc
));
428 return GPG_ERR_UNKNOWN_VERSION
;
431 //gpgme_set_global_flag ("require-gnupg", REQUIRE_GNUPG_VERSION);
433 gpgme_set_locale (NULL
, LC_CTYPE
, setlocale (LC_CTYPE
, NULL
));
434 gpgme_set_locale (NULL
, LC_MESSAGES
, setlocale (LC_MESSAGES
, NULL
));
438 if (gnutls_global_init ())
440 fprintf(stderr
, _("gnutls_global_init() failed.\n"));
441 return GPG_ERR_UNKNOWN_VERSION
;
444 gnutls_global_set_log_function (tls_log
);
445 gnutls_global_set_audit_log_function (tls_audit_log
);
451 do_validate_peer (assuan_context_t ctx
, const char *section
,
452 assuan_peercred_t
* peer
)
457 struct client_s
*client
= assuan_get_pointer (ctx
);
460 return GPG_ERR_FORBIDDEN
;
463 if (client
->thd
->remote
)
464 return tls_validate_access (client
, section
);
467 rc
= assuan_get_peercred (ctx
, peer
);
471 users
= config_get_list (section
, "allowed");
474 for (char **p
= users
; !rc
&& *p
; p
++)
476 rc
= acl_check_common(client
, *p
, (*peer
)->uid
, (*peer
)->gid
,
482 else if (client
->no_access_param
)
485 return allowed
&& !rc
? 0 : rc
? rc
: GPG_ERR_FORBIDDEN
;
488 /* Test if uid is a member of group 'name'. Invert when 'not' is true. */
489 #ifdef HAVE_GETGRNAM_R
491 acl_check_group (const char *name
, uid_t uid
, gid_t gid
, int not, int *allowed
)
494 struct group gr
, *gresult
;
495 size_t len
= sysconf (_SC_GETGR_R_SIZE_MAX
);
504 return GPG_ERR_ENOMEM
;
506 err
= getgrnam_r (name
, &gr
, buf
, len
, &gresult
);
509 if (gresult
->gr_gid
== gid
)
516 for (char **t
= gresult
->gr_mem
; !rc
&& *t
; t
++)
520 struct passwd
*result
= get_pwd_struct (*t
, 0, &pw
, &tbuf
, &rc
);
522 if (!rc
&& result
&& result
->pw_uid
== uid
)
536 rc
= gpg_error_from_errno (err
);
539 return rc
? rc
: !gresult
? 0 : GPG_ERR_EACCES
;
543 acl_check_group (const char *name
, uid_t uid
, gid_t gid
, int not, int *allowed
)
545 struct group
*gresult
;
549 gresult
= getgrnam (name
);
550 if (!errno
&& gresult
&& gresult
->gr_gid
== gid
)
556 rc
= gpg_error_from_syserror ();
560 for (char **t
= gresult
->gr_mem
; !rc
&& *t
; t
++)
564 struct passwd
*result
= get_pwd_struct (*t
, 0, &pw
, &buf
, &rc
);
566 if (!rc
&& result
&& result
->pw_uid
== uid
)
581 peer_is_invoker(struct client_s
*client
)
583 struct invoking_user_s
*user
;
586 if (client
->thd
->state
== CLIENT_STATE_UNKNOWN
)
587 return GPG_ERR_EACCES
;
589 for (user
= invoking_users
; user
; user
= user
->next
)
592 if (client
->thd
->remote
)
594 if (user
->type
== INVOKING_TLS
595 && !strcmp(client
->thd
->tls
->fp
, user
->id
))
596 allowed
= user
->not ? 0 : 1;
602 if (user
->type
== INVOKING_GID
)
604 gpg_error_t rc
= acl_check_group (user
->id
,
605 client
->thd
->peer
->uid
,
606 client
->thd
->peer
->gid
,
607 user
->not, &allowed
);
611 else if (user
->type
== INVOKING_UID
&& client
->thd
->peer
->uid
== user
->uid
)
612 allowed
= user
->not ? 0 : 1;
615 return allowed
? 0 : GPG_ERR_EACCES
;
618 #ifdef HAVE_GETGRNAM_R
620 acl_check_common (struct client_s
*client
, const char *user
, uid_t uid
,
621 gid_t gid
, int *allowed
)
631 if (*user
== '-' || *user
== '!')
634 if (*user
== '+') // not implemented yet
637 if (*user
== '#') // TLS fingerprint hash
640 if (not || rw
|| tls
)
646 if (client
->thd
->remote
)
648 if (!strcasecmp (client
->thd
->tls
->fp
, user
))
658 else if (client
->thd
->remote
) // Remote client with no FP in the ACL
662 if (*user
== '@') // all users in group
663 return acl_check_group (user
+1, uid
, gid
, not, allowed
);
668 struct passwd
*pwd
= get_pwd_struct (user
, 0, &pw
, &buf
, &rc
);
670 if (!rc
&& pwd
&& pwd
->pw_uid
== uid
)
680 acl_check_common (struct client_s
*client
, const char *user
, uid_t uid
,
681 gid_t gid
, int *allowed
)
691 if (*user
== '-' || *user
== '!')
694 if (*user
== '+') // not implemented yet
697 if (*user
== '#') // TLS fingerprint hash
700 if (not || rw
|| tls
)
706 if (client
->thd
->remote
)
708 if (!strcasecmp (client
->thd
->tls
->fp
, user
))
718 if (*user
== '@') // all users in group
719 return acl_check_group (user
+1, uid
, gid
, not, allowed
);
724 struct passwd
*result
= get_pwd_struct (user
, 0, &pw
, &buf
, &rc
);
726 if (!rc
&& result
&& result
->pw_uid
== uid
)
737 validate_peer (struct client_s
*cl
)
743 return tls_validate_access (cl
, NULL
);
746 MUTEX_LOCK (&cn_mutex
);
747 rc
= do_validate_peer (cl
->ctx
, "global", &cl
->thd
->peer
);
748 MUTEX_UNLOCK (&cn_mutex
);
749 log_write ("peer %s: uid=%i, gid=%i, pid=%i, rc=%u",
750 !rc
? _("accepted") : _("rejected"), cl
->thd
->peer
->uid
,
751 cl
->thd
->peer
->gid
, cl
->thd
->peer
->pid
, rc
);
756 xml_error_cb (void *data
, xmlErrorPtr e
)
758 struct client_s
*client
= data
;
761 * Keep the first reported error as the one to show in the error
762 * description. Reset in send_error().
764 if (client
->xml_error
)
767 client
->xml_error
= xcalloc (1, sizeof(xmlError
));
768 xmlCopyError (e
, client
->xml_error
);
772 hook_waitpid (assuan_context_t ctx
, pid_t pid
, int action
,
773 int *status
, int options
)
775 return waitpid (pid
, status
, options
);
779 hook_read (assuan_context_t ctx
, assuan_fd_t fd
, void *data
, size_t len
)
782 struct client_s
*client
= assuan_get_pointer (ctx
);
784 if (client
->thd
->remote
)
785 return tls_read_hook (ctx
, (int) fd
, data
, len
);
788 return read ((int) fd
, data
, len
);
792 hook_write (assuan_context_t ctx
, assuan_fd_t fd
,
793 const void *data
, size_t len
)
796 struct client_s
*client
= assuan_get_pointer (ctx
);
798 if (client
->thd
->remote
)
799 return tls_write_hook (ctx
, (int) fd
, data
, len
);
802 return write ((int) fd
, data
, len
);
806 assuan_log_cb (assuan_context_t ctx
, void *data
, unsigned cat
,
809 struct client_s
*client
= data
;
814 if (!(assuan_level
& cat
))
822 case ASSUAN_LOG_INIT
:
823 str
= "ASSUAN[INIT]";
828 case ASSUAN_LOG_ENGINE
:
829 str
= "ASSUAN[ENGINE]";
831 case ASSUAN_LOG_DATA
:
832 str
= "ASSUAN[DATA]";
834 case ASSUAN_LOG_SYSIO
:
835 str
= "ASSUAN[SYSIO]";
837 case ASSUAN_LOG_CONTROL
:
838 str
= "ASSUAN[CONTROL]";
841 str
= "ASSUAN[UNKNOWN]";
845 log_write ("%s: %s", str
, msg
);
850 new_connection (struct client_s
*cl
)
853 static struct assuan_malloc_hooks mhooks
= { xmalloc
, xrealloc
, xfree
};
854 static struct assuan_system_hooks shooks
= {
855 ASSUAN_SYSTEM_HOOKS_VERSION
,
863 NULL
, //sendmsg both are used for FD passing
874 char *prio
= config_get_string ("global", "tls_cipher_suite");
876 cl
->thd
->timeout
= config_get_integer ("global", "tls_timeout");
877 if (fcntl (cl
->thd
->fd
, F_SETFL
, O_NONBLOCK
) == -1)
880 cl
->thd
->tls
= tls_init (cl
->thd
->fd
, cl
->thd
->timeout
, prio
);
887 rc
= assuan_new_ext (&cl
->ctx
, GPG_ERR_SOURCE_DEFAULT
, &mhooks
,
892 assuan_ctx_set_system_hooks (cl
->ctx
, &shooks
);
893 rc
= assuan_init_socket_server (cl
->ctx
, cl
->thd
->fd
, 2);
897 assuan_set_pointer (cl
->ctx
, cl
);
898 assuan_set_hello_line (cl
->ctx
, PACKAGE_STRING
);
899 rc
= register_commands (cl
->ctx
);
903 rc
= assuan_accept (cl
->ctx
);
907 rc
= validate_peer (cl
);
908 /* May not be implemented on all platforms. */
909 if (rc
&& gpg_err_code (rc
) != GPG_ERR_ASS_GENERAL
)
912 MUTEX_LOCK (&cn_mutex
);
913 cl
->thd
->state
= CLIENT_STATE_INIT
;
914 MUTEX_UNLOCK (&cn_mutex
);
915 cl
->lock_timeout
= config_get_integer ("global", "lock_timeout");
916 xmlSetStructuredErrorFunc (cl
, xml_error_cb
);
920 log_write ("%s", pwmd_strerror (rc
));
925 * This is called after a client_thread() terminates. Set with
926 * pthread_cleanup_push().
929 cleanup_cb (void *arg
)
931 struct client_thread_s
*cn
= arg
;
932 struct client_s
*cl
= cn
->cl
;
934 MUTEX_LOCK (&cn_mutex
);
935 cn_thread_list
= slist_remove (cn_thread_list
, cn
);
936 MUTEX_UNLOCK (&cn_mutex
);
940 unlock_flock (&cl
->flock_fd
);
943 xmlResetError (cl
->xml_error
);
945 xfree (cl
->xml_error
);
950 gnutls_deinit (cn
->tls
->ses
);
956 if (!cn
->atfork
&& cl
->ctx
)
957 assuan_release (cl
->ctx
);
958 else if (!cn
->atfork
&& cl
->thd
&& cl
->thd
->fd
!= -1)
962 crypto_free (cl
->crypto
);
973 while (cn
->msg_queue
)
975 struct status_msg_s
*msg
= cn
->msg_queue
;
977 cn
->msg_queue
= msg
->next
;
982 if (!cn
->atfork
&& cn
->status_msg_pipe
[0] != -1)
983 close (cn
->status_msg_pipe
[0]);
985 if (!cn
->atfork
&& cn
->status_msg_pipe
[1] != -1)
986 close (cn
->status_msg_pipe
[1]);
988 pthread_mutex_destroy (&cn
->status_mutex
);
992 log_write (_("exiting, fd=%i"), cn
->fd
);
993 send_status_all (STATUS_CLIENTS
, NULL
);
998 xfree (cn
->peeraddr
);
1001 pthread_cond_signal (&quit_cond
);
1005 cleanup_all_clients (int atfork
)
1007 /* This function may be called from pthread_atfork() which requires
1008 reinitialization. */
1011 pthread_mutexattr_t attr
;
1013 pthread_mutexattr_init (&attr
);
1014 pthread_mutexattr_settype (&attr
, PTHREAD_MUTEX_RECURSIVE
);
1015 pthread_mutex_init (&cn_mutex
, &attr
);
1016 pthread_mutexattr_destroy (&attr
);
1017 cache_mutex_init ();
1020 MUTEX_LOCK (&cn_mutex
);
1022 while (slist_length (cn_thread_list
))
1024 struct client_thread_s
*thd
= slist_nth_data (cn_thread_list
, 0);
1026 thd
->atfork
= atfork
;
1031 MUTEX_UNLOCK (&cn_mutex
);
1032 cache_deinit (atfork
);
1036 send_msg_queue (struct client_thread_s
*thd
)
1038 MUTEX_LOCK (&thd
->status_mutex
);
1043 ret
= read (thd
->status_msg_pipe
[0], &c
, 1);
1044 rc
= gpg_error_from_syserror ();
1045 if (ret
== -1 && gpg_err_code (rc
) != GPG_ERR_EAGAIN
)
1046 log_write ("%s (%i): %s", __FUNCTION__
, __LINE__
, pwmd_strerror (rc
));
1050 thd
->wrote_status
= 0;
1052 while (thd
->msg_queue
)
1054 struct status_msg_s
*msg
= thd
->msg_queue
;
1056 #ifndef HAVE_PTHREAD_CANCEL
1061 thd
->msg_queue
= thd
->msg_queue
->next
;
1062 MUTEX_UNLOCK (&thd
->status_mutex
);
1063 rc
= send_status (thd
->cl
->ctx
, msg
->s
, msg
->line
);
1064 MUTEX_LOCK (&thd
->status_mutex
);
1072 MUTEX_UNLOCK (&thd
->status_mutex
);
1073 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1074 log_write ("%s (%i): %s", __FUNCTION__
, __LINE__
, pwmd_strerror (rc
));
1080 client_thread (void *data
)
1082 struct client_thread_s
*thd
= data
;
1083 struct client_s
*cl
= xcalloc (1, sizeof (struct client_s
));
1085 #ifdef HAVE_PR_SET_NAME
1086 prctl (PR_SET_NAME
, "client");
1088 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1092 log_write ("%s(%i): %s", __FILE__
, __LINE__
,
1093 pwmd_strerror (GPG_ERR_ENOMEM
));
1097 MUTEX_LOCK (&cn_mutex
);
1098 pthread_cleanup_push (cleanup_cb
, thd
);
1102 MUTEX_UNLOCK (&cn_mutex
);
1104 if (new_connection (cl
))
1108 struct pollfd fds
[2];
1110 fds
[0].fd
= thd
->fd
;
1111 fds
[0].events
= POLLIN
;
1112 fds
[1].fd
= thd
->status_msg_pipe
[0];
1113 fds
[1].events
= POLLIN
;
1115 send_status_all (STATUS_CLIENTS
, NULL
);
1116 rc
= send_status (cl
->ctx
, STATUS_CACHE
, NULL
);
1119 log_write ("%s(%i): %s", __FILE__
, __LINE__
, pwmd_strerror (rc
));
1128 n
= poll (fds
, 2, -1);
1131 log_write ("%s", strerror (errno
));
1135 if (fds
[1].revents
& POLLIN
)
1137 rc
= send_msg_queue (thd
);
1138 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1142 #ifdef HAVE_PTHREAD_CANCEL
1143 if (!(fds
[0].revents
& POLLIN
))
1145 if (thd
->fd
!= -1 && !(fds
[0].revents
& POLLIN
))
1149 rc
= assuan_process_next (cl
->ctx
, &eof
);
1152 if (gpg_err_code (rc
) == GPG_ERR_EOF
|| eof
)
1155 log_write ("assuan_process_next(): rc=%u %s", rc
,
1156 pwmd_strerror (rc
));
1157 if (rc
== gpg_error (GPG_ERR_ETIMEDOUT
))
1160 rc
= send_error (cl
->ctx
, rc
);
1163 log_write ("assuan_process_done(): rc=%u %s", rc
,
1164 pwmd_strerror (rc
));
1169 /* Since the msg queue pipe fd's are non-blocking, check for
1170 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1171 * client has already disconnected and will be converted to
1172 * GPG_ERR_EOF during assuan_process_next().
1174 rc
= send_msg_queue (thd
);
1175 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1180 /* Don't do pthread_exit() here because any set pthread_cleanup_push
1181 * functions would be called after a command failed but then the client
1182 * exited normally which may lead to a double free. */
1183 pthread_cleanup_pop (1);
1188 xml_import (const char *filename
, const char *outfile
, char **keyid
,
1189 char **sign_keyid
, char *keyfile
, const char *keyparam
,
1198 struct crypto_s
*crypto
= NULL
;
1200 if (stat (filename
, &st
) == -1)
1202 rc
= gpg_error_from_errno (errno
);
1206 fd
= open (filename
, O_RDONLY
);
1208 return gpg_error_from_errno (errno
);
1210 xmlbuf
= xmalloc (st
.st_size
+ 1);
1214 return GPG_ERR_ENOMEM
;
1217 if (read (fd
, xmlbuf
, st
.st_size
) == -1)
1219 rc
= gpg_error_from_errno (errno
);
1226 xmlbuf
[st
.st_size
] = 0;
1227 // Be sure the document validates.
1228 doc
= xmlReadDoc (xmlbuf
, NULL
, "UTF-8", XML_PARSE_NOBLANKS
);
1231 return GPG_ERR_BAD_DATA
;
1233 xmlNodePtr n
= xmlDocGetRootElement (doc
);
1234 if (n
&& !xmlStrEqual (n
->name
, (xmlChar
*) "pwmd"))
1235 rc
= GPG_ERR_BAD_DATA
;
1239 rc
= xml_validate_import (NULL
, n
? n
->children
: n
);
1242 rc
= crypto_init (&crypto
, NULL
, filename
, keyfile
!= NULL
, keyfile
);
1247 crypto
->flags
|= CRYPTO_FLAG_KEYFILE
;
1248 crypto
->keyfile
= str_dup (keyfile
);
1251 xmlDocDumpMemory (doc
, &crypto
->plaintext
, &len
);
1253 crypto
->plaintext_size
= len
;
1255 rc
= GPG_ERR_ENOMEM
;
1262 if (!symmetric
&& (keyparam
|| !keyid
))
1268 fd
= open (keyparam
, O_RDONLY
);
1270 rc
= gpg_error_from_errno (errno
);
1274 if (stat (keyparam
, &st
) == -1)
1275 rc
= gpg_error_from_errno (errno
);
1279 buf
= xmalloc (st
.st_size
+1);
1281 rc
= GPG_ERR_ENOMEM
;
1285 len
= read (fd
, buf
, st
.st_size
);
1286 if (len
!= st
.st_size
)
1287 rc
= gpg_error_from_errno (errno
);
1300 buf
= crypto_default_key_params ();
1302 rc
= GPG_ERR_ENOMEM
;
1306 rc
= crypto_genkey (NULL
, crypto
, (unsigned char *)buf
);
1312 crypto
->save
.pubkey
= strv_dup (keyid
);
1313 crypto
->save
.sigkey
= strv_dup (sign_keyid
);
1318 crypto
->flags
|= symmetric
? CRYPTO_FLAG_SYMMETRIC
: 0;
1319 rc
= crypto_encrypt (NULL
, crypto
);
1325 if (!strcmp (outfile
, "-"))
1328 xfree (crypto
->plaintext
);
1329 crypto
->plaintext
= NULL
;
1330 xfree (crypto
->filename
);
1331 crypto
->filename
= outfile
? str_dup (outfile
) : NULL
;
1332 rc
= crypto_write_file (crypto
);
1336 crypto_free (crypto
);
1341 do_cache_push (struct crypto_s
*crypto
)
1345 struct cache_data_s
*cdata
;
1350 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1353 if (valid_filename (crypto
->filename
) == 0)
1355 log_write (_("%s: Invalid characters in filename"), crypto
->filename
);
1356 return GPG_ERR_INV_VALUE
;
1359 rc
= lock_flock (NULL
, crypto
->filename
, LOCK_SH
, &fd
);
1361 rc
= crypto_decrypt (NULL
, crypto
);
1368 rc
= xml_parse_doc ((char *) crypto
->plaintext
, crypto
->plaintext_size
, &doc
);
1372 log_write ("%s", pwmd_strerror (rc
));
1376 cdata
= xcalloc (1, sizeof (struct cache_data_s
));
1381 return GPG_ERR_ENOMEM
;
1384 rc
= get_checksum (crypto
->filename
, &crc
, &len
);
1389 free_cache_data_once (cdata
);
1394 rc
= cache_encrypt (crypto
);
1397 cdata
->doc
= crypto
->plaintext
;
1398 cdata
->size
= crypto
->plaintext_size
;
1399 crypto
->plaintext
= NULL
;
1400 cdata
->pubkey
= crypto
->pubkey
;
1401 cdata
->sigkey
= crypto
->sigkey
;
1402 crypto
->pubkey
= NULL
;
1403 crypto
->sigkey
= NULL
;
1408 free_cache_data_once (cdata
);
1412 int timeout
= config_get_integer (crypto
->filename
, "cache_timeout");
1413 rc
= cache_add_file (crypto
->filename
, cdata
, timeout
);
1418 init_client (int fd
, const char *addr
)
1421 struct client_thread_s
*new = xcalloc (1, sizeof (struct client_thread_s
));
1426 return GPG_ERR_ENOMEM
;
1429 MUTEX_LOCK (&cn_mutex
);
1430 new->conntime
= time (NULL
);
1431 pthread_cleanup_push (cleanup_mutex_cb
, &cn_mutex
);
1433 if (pipe (new->status_msg_pipe
) == -1)
1434 rc
= gpg_error_from_errno (errno
);
1438 if (fcntl (new->status_msg_pipe
[0], F_SETFL
, O_NONBLOCK
) == -1)
1439 rc
= gpg_error_from_errno (errno
);
1442 if (fcntl (new->status_msg_pipe
[1], F_SETFL
, O_NONBLOCK
) == -1)
1443 rc
= gpg_error_from_errno (errno
);
1445 pthread_mutex_init (&new->status_mutex
, NULL
);
1451 new->remote
= addr
? 1 : 0;
1454 rc
= create_thread (client_thread
, new, &new->tid
, 1);
1457 close (new->status_msg_pipe
[0]);
1458 close (new->status_msg_pipe
[1]);
1459 pthread_mutex_destroy (&new->status_mutex
);
1465 struct slist_s
*list
= slist_append (cn_thread_list
, new);
1469 cn_thread_list
= list
;
1472 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1473 (pthread_t
*) new->tid
, fd
, addr
);
1475 new->peeraddr
= str_dup (addr
);
1479 log_write (_("new connection: tid=%p, fd=%i"),
1480 (pthread_t
*) new->tid
, fd
);
1483 rc
= GPG_ERR_ENOMEM
;
1486 pthread_cleanup_pop (1);
1492 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1493 pwmd_strerror (rc
));
1499 keepalive_thread (void *arg
)
1501 #ifndef HAVE_PTHREAD_CANCEL
1502 int *n
= xmalloc (sizeof (int));
1505 pthread_setspecific (signal_thread_key
, n
);
1509 #ifdef HAVE_PR_SET_NAME
1510 prctl (PR_SET_NAME
, "keepalive");
1512 pthread_setspecific (thread_name_key
, str_asprintf ("!%s", __FUNCTION__
));
1516 int n
= config_get_integer ("global", "keepalive_interval");
1517 struct timeval tv
= { n
, 0 };
1518 #ifndef HAVE_PTHREAD_CANCEL
1521 sigusr2
= (int *) pthread_getspecific (signal_thread_key
);
1526 send_status_all (STATUS_KEEPALIVE
, NULL
);
1527 select (0, NULL
, NULL
, NULL
, &tv
);
1534 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1536 get_in_addr (struct sockaddr
*sa
)
1538 if (sa
->sa_family
== AF_INET
)
1539 return &(((struct sockaddr_in
*) sa
)->sin_addr
);
1541 return &(((struct sockaddr_in6
*) sa
)->sin6_addr
);
1545 tcp_accept_thread (void *arg
)
1547 int sockfd
= *(int *) arg
;
1550 int regen_interval
= config_get_integer ("global", "tls_regen_interval");
1551 char *tmp
= config_get_string ("global", "tls_dh_level");
1552 #ifndef HAVE_PTHREAD_CANCEL
1553 int *n
= xmalloc (sizeof (int));
1556 pthread_setspecific (signal_thread_key
, n
);
1558 fcntl (sockfd
, F_SETFL
, O_NONBLOCK
);
1561 #ifdef HAVE_PR_SET_NAME
1562 prctl (PR_SET_NAME
, "tcp_accept");
1564 pthread_setspecific (thread_name_key
, str_asprintf ("!%s", __FUNCTION__
));
1565 fcntl (sockfd
, F_SETFL
, O_NONBLOCK
);
1567 rc
= tls_init_params (tmp
);
1576 struct sockaddr_storage raddr
;
1577 socklen_t slen
= sizeof (raddr
);
1580 char s
[INET6_ADDRSTRLEN
];
1581 struct timeval tv
= { 0, ACCEPT_TIMEOUT
};
1582 #ifndef HAVE_PTHREAD_CANCEL
1585 sigusr2
= (int *) pthread_getspecific (signal_thread_key
);
1590 fd
= accept (sockfd
, (struct sockaddr
*) &raddr
, &slen
);
1591 if (init
== 0 || fd
== -1)
1593 if ((init
== 0 && (errno
== EAGAIN
|| errno
== EWOULDBLOCK
))
1594 || (errno
== EAGAIN
|| errno
== EWOULDBLOCK
))
1596 if (regen_interval
> 0
1597 && (init
== 0 || time (NULL
) - init
>= regen_interval
))
1600 int remote_client
= 0;
1602 MUTEX_LOCK(&cn_mutex
);
1603 for (i
= 0; i
< slist_length (cn_thread_list
); i
++)
1605 struct client_thread_s
*thd
=
1606 slist_nth_data (cn_thread_list
, i
);
1614 MUTEX_UNLOCK(&cn_mutex
);
1618 char *tmp
= config_get_string ("global", "tls_dh_level");
1621 rc
= tls_init_params (tmp
);
1643 select (0, NULL
, NULL
, NULL
, &tv
);
1648 if (errno
== EMFILE
|| errno
== ENFILE
)
1649 log_write ("accept(): %s",
1650 pwmd_strerror (gpg_error_from_errno (errno
)));
1651 else if (errno
!= EAGAIN
)
1653 if (!quit
) // probably EBADF
1654 log_write ("accept(): %s", strerror (errno
));
1659 #ifndef HAVE_PTHREAD_CANCEL
1660 select (0, NULL
, NULL
, NULL
, &tv
);
1671 inet_ntop (raddr
.ss_family
, get_in_addr ((struct sockaddr
*) &raddr
),
1673 (void) init_client (fd
, s
);
1674 n
= config_get_integer ("global", "tcp_wait");
1677 tv
.tv_sec
= (n
* 100000) / 100000;
1678 tv
.tv_usec
= (n
* 100000) % 100000;
1679 select (0, NULL
, NULL
, NULL
, &tv
);
1687 start_stop_tls_with_protocol (int ipv6
, int term
)
1689 struct addrinfo hints
, *servinfo
, *p
;
1690 int port
= config_get_integer ("global", "tcp_port");
1694 int *fd
= ipv6
? &tls6_fd
: &tls_fd
;
1696 if (term
|| config_get_boolean ("global", "enable_tcp") == 0)
1702 #ifdef HAVE_PTHREAD_CANCEL
1703 pthread_cancel (tls6_tid
);
1705 pthread_kill (tls6_tid
, SIGUSR2
);
1707 pthread_join (tls6_tid
, NULL
);
1710 shutdown (tls6_fd
, SHUT_RDWR
);
1720 #ifdef HAVE_PTHREAD_CANCEL
1721 pthread_cancel (tls_tid
);
1723 pthread_kill (tls_tid
, SIGUSR2
);
1725 pthread_join (tls_tid
, NULL
);
1728 shutdown (tls_fd
, SHUT_RDWR
);
1737 if ((ipv6
&& tls6_fd
!= -1) || (!ipv6
&& tls_fd
!= -1))
1740 memset (&hints
, 0, sizeof (hints
));
1741 hints
.ai_family
= ipv6
? AF_INET6
: AF_INET
;
1742 hints
.ai_socktype
= SOCK_STREAM
;
1743 hints
.ai_flags
= AI_PASSIVE
;
1744 snprintf (buf
, sizeof (buf
), "%i", port
);
1746 if ((n
= getaddrinfo (NULL
, buf
, &hints
, &servinfo
)) == -1)
1748 log_write ("getaddrinfo(): %s", gai_strerror (n
));
1752 for (n
= 0, p
= servinfo
; p
!= NULL
; p
= p
->ai_next
)
1756 if ((ipv6
&& p
->ai_family
!= AF_INET6
)
1757 || (!ipv6
&& p
->ai_family
!= AF_INET
))
1760 if ((*fd
= socket (p
->ai_family
, p
->ai_socktype
, p
->ai_protocol
)) == -1)
1762 log_write ("socket(): %s", strerror (errno
));
1766 if (setsockopt (*fd
, SOL_SOCKET
, SO_REUSEADDR
, &r
, sizeof (int)) == -1)
1768 log_write ("setsockopt(): %s",
1769 pwmd_strerror (gpg_error_from_errno (errno
)));
1770 freeaddrinfo (servinfo
);
1774 if (bind (*fd
, p
->ai_addr
, p
->ai_addrlen
) == -1)
1777 log_write ("bind(): %s",
1778 pwmd_strerror (gpg_error_from_errno (errno
)));
1786 freeaddrinfo (servinfo
);
1791 #if HAVE_DECL_SO_BINDTODEVICE != 0
1792 char *tmp
= config_get_string ("global", "tcp_interface");
1793 if (tmp
&& setsockopt (*fd
, SOL_SOCKET
, SO_BINDTODEVICE
, tmp
,
1794 strlen (tmp
)) == -1)
1796 log_write ("setsockopt(): %s",
1797 pwmd_strerror (gpg_error_from_errno (errno
)));
1805 if (listen (*fd
, 128) == -1)
1807 log_write ("listen(): %s", strerror (errno
));
1812 rc
= create_thread (tcp_accept_thread
, fd
, &tls6_tid
, 0);
1814 rc
= create_thread (tcp_accept_thread
, fd
, &tls_tid
, 0);
1818 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1819 pwmd_strerror (rc
));
1831 start_stop_tls_with_protocol (0, 1);
1844 start_stop_tls (int term
)
1846 char *s
= config_get_string ("global", "tcp_bind");
1852 if (!strcmp (s
, "any"))
1854 b
= start_stop_tls_with_protocol (0, term
);
1856 b
= start_stop_tls_with_protocol (1, term
);
1858 else if (!strcmp (s
, "ipv4"))
1859 b
= start_stop_tls_with_protocol (0, term
);
1860 else if (!strcmp (s
, "ipv6"))
1861 b
= start_stop_tls_with_protocol (1, term
);
1871 accept_thread (void *arg
)
1873 int sockfd
= *(int *) arg
;
1874 #ifndef HAVE_PTHREAD_CANCEL
1875 int *n
= xmalloc (sizeof (int));
1878 pthread_setspecific (signal_thread_key
, n
);
1880 fcntl (sockfd
, F_SETFL
, O_NONBLOCK
);
1883 #ifdef HAVE_PR_SET_NAME
1884 prctl (PR_SET_NAME
, "accept");
1886 pthread_setspecific (thread_name_key
, str_asprintf ("!%s", __FUNCTION__
));
1890 socklen_t slen
= sizeof (struct sockaddr_un
);
1891 struct sockaddr_un raddr
;
1893 #ifndef HAVE_PTHREAD_CANCEL
1894 struct timeval tv
= { 0, ACCEPT_TIMEOUT
};
1895 int *sigusr2
= (int *) pthread_getspecific (signal_thread_key
);
1901 fd
= accept (sockfd
, (struct sockaddr
*) &raddr
, &slen
);
1904 if (errno
== EMFILE
|| errno
== ENFILE
)
1905 log_write ("accept(): %s",
1906 pwmd_strerror (gpg_error_from_errno (errno
)));
1907 else if (errno
!= EAGAIN
)
1909 if (!quit
) // probably EBADF
1910 log_write ("accept(): %s",
1911 pwmd_strerror (gpg_error_from_errno (errno
)));
1916 #ifndef HAVE_PTHREAD_CANCEL
1917 select (0, NULL
, NULL
, NULL
, &tv
);
1922 (void) init_client (fd
, NULL
);
1925 /* Just in case accept() failed for some reason other than EBADF */
1931 cache_timer_thread (void *arg
)
1933 #ifndef HAVE_PTHREAD_CANCEL
1934 int *n
= xmalloc (sizeof (int));
1937 pthread_setspecific (signal_thread_key
, n
);
1941 #ifdef HAVE_PR_SET_NAME
1942 prctl (PR_SET_NAME
, "cache timer");
1944 pthread_setspecific (thread_name_key
, str_asprintf ("!%s", __FUNCTION__
));
1948 struct timeval tv
= { 1, 0 };
1949 #ifndef HAVE_PTHREAD_CANCEL
1952 n
= (int *) pthread_getspecific (signal_thread_key
);
1957 select (0, NULL
, NULL
, NULL
, &tv
);
1958 cache_adjust_timeout ();
1965 signal_loop (sigset_t sigset
)
1974 sigwait (&sigset
, &sig
);
1977 log_write (_("caught signal %i (%s)"), sig
, strsignal (sig
));
1982 pthread_cond_signal (&rcfile_cond
);
1985 log_write (_("clearing file cache"));
1986 cache_clear (NULL
, NULL
, 1);
1987 send_status_all (STATUS_CACHE
, NULL
);
2006 log_write (_ ("Caught signal %i (%s). Exiting."), sig
, strsignal (sig
));
2007 #ifdef HAVE_BACKTRACE
2008 BACKTRACE (__FUNCTION__
);
2014 waiting_for_exit (void *arg
)
2017 #ifndef HAVE_PTHREAD_CANCEL
2018 int *n
= xmalloc (sizeof (int));
2021 pthread_setspecific (signal_thread_key
, n
);
2025 #ifdef HAVE_PR_SET_NAME
2026 prctl (PR_SET_NAME
, "exiting");
2028 pthread_setspecific (thread_name_key
, str_asprintf ("!%s", __FUNCTION__
));
2029 log_write (_("waiting for all clients to disconnect"));
2030 MUTEX_LOCK (&quit_mutex
);
2031 pthread_cleanup_push (cleanup_mutex_cb
, &quit_mutex
);
2038 MUTEX_LOCK (&cn_mutex
);
2039 n
= slist_length (cn_thread_list
);
2040 MUTEX_UNLOCK (&cn_mutex
);
2044 #ifndef HAVE_PTHREAD_CANCEL
2045 int *s
= (int *) pthread_getspecific (signal_thread_key
);
2052 log_write (_("%i clients remain"), n
);
2056 INIT_TIMESPEC (SIG_TIMEOUT
, ts
);
2057 pthread_cond_timedwait (&quit_cond
, &quit_mutex
, &ts
);
2060 kill (getpid (), SIGQUIT
);
2061 pthread_cleanup_pop (1);
2066 server_loop (int sockfd
, char **socketpath
)
2068 pthread_t accept_tid
;
2069 pthread_t cache_timeout_tid
;
2070 int cancel_timeout_thread
= 0, cancel_accept_thread
= 0;
2071 int cancel_keepalive_thread
= 0;
2078 sigemptyset (&sigset
);
2081 sigaddset (&sigset
, SIGTERM
);
2082 sigaddset (&sigset
, SIGINT
);
2084 /* Clears the file cache. */
2085 sigaddset (&sigset
, SIGUSR1
);
2087 /* Configuration file reloading. */
2088 sigaddset (&sigset
, SIGHUP
);
2090 /* For exiting cleanly. */
2091 sigaddset (&sigset
, SIGQUIT
);
2093 #ifndef HAVE_PTHREAD_CANCEL
2095 The socket, cache and rcfile threads use this signal when
2096 pthread_cancel() is unavailable. Prevent the main thread from
2097 catching this signal from another process.
2099 sigaddset (&sigset
, SIGUSR2
);
2102 /* When mem.c cannot find a pointer in the list (double free). */
2103 signal (SIGABRT
, catchsig
);
2104 sigaddset (&sigset
, SIGABRT
);
2105 sigprocmask (SIG_BLOCK
, &sigset
, NULL
);
2107 #ifndef HAVE_PTHREAD_CANCEL
2108 /* Remove this signal from the watched signals in signal_loop(). */
2109 sigdelset (&sigset
, SIGUSR2
);
2112 /* Can show a backtrace of the stack in the log. */
2113 signal (SIGSEGV
, catchsig
);
2116 /* Needs to be done after the fork(). */
2117 if (!start_stop_tls (0))
2124 pthread_mutex_init (&quit_mutex
, NULL
);
2125 pthread_cond_init (&quit_cond
, NULL
);
2126 char *p
= get_username (getuid());
2127 log_write (_("%s started for user %s"), PACKAGE_STRING
, p
);
2131 if (config_get_boolean ("global", "enable_tcp"))
2132 log_write (_("Listening on %s and TCP port %i"), *socketpath
,
2133 config_get_integer ("global", "tcp_port"));
2135 log_write (_("Listening on %s"), *socketpath
);
2137 log_write (_("Listening on %s"), *socketpath
);
2140 rc
= create_thread (keepalive_thread
, NULL
, &keepalive_tid
, 0);
2143 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2144 pwmd_strerror (rc
));
2148 cancel_keepalive_thread
= 1;
2149 rc
= create_thread (reload_rcfile_thread
, NULL
, &rcfile_tid
, 0);
2152 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2153 pwmd_strerror (rc
));
2157 rc
= create_thread (cache_timer_thread
, NULL
, &cache_timeout_tid
, 0);
2160 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2161 pwmd_strerror (rc
));
2165 cancel_timeout_thread
= 1;
2166 rc
= create_thread (accept_thread
, &sockfd
, &accept_tid
, 0);
2169 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2170 pwmd_strerror (rc
));
2174 cancel_accept_thread
= 1;
2176 signal_loop (sigset
);
2182 * We're out of the main server loop. This happens when a signal was sent
2183 * to terminate the daemon. We'll wait for all clients to disconnect
2184 * before exiting but exit immediately if another termination signal is
2187 if (cancel_accept_thread
)
2189 #ifdef HAVE_PTHREAD_CANCEL
2190 int n
= pthread_cancel (accept_tid
);
2192 int n
= pthread_kill (accept_tid
, SIGUSR2
);
2195 pthread_join (accept_tid
, NULL
);
2201 shutdown (sockfd
, SHUT_RDWR
);
2203 unlink (*socketpath
);
2204 xfree (*socketpath
);
2206 MUTEX_LOCK (&cn_mutex
);
2207 n
= slist_length (cn_thread_list
);
2208 MUTEX_UNLOCK (&cn_mutex
);
2214 rc
= create_thread (waiting_for_exit
, NULL
, &tid
, 0);
2217 if (signal_loop (sigset
))
2219 log_write (_("Received second termination request. Exiting."));
2220 #ifdef HAVE_PTHREAD_CANCEL
2221 pthread_cancel (tid
);
2223 pthread_kill (tid
, SIGUSR2
);
2225 pthread_join (tid
, NULL
);
2229 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2230 pwmd_strerror (rc
));
2233 if (cancel_timeout_thread
)
2235 #ifdef HAVE_PTHREAD_CANCEL
2236 pthread_cancel (cache_timeout_tid
);
2238 pthread_kill (cache_timeout_tid
, SIGUSR2
);
2240 pthread_join (cache_timeout_tid
, NULL
);
2243 if (cancel_keepalive_thread
)
2245 #ifdef HAVE_PTHREAD_CANCEL
2246 pthread_cancel (keepalive_tid
);
2248 pthread_kill (keepalive_tid
, SIGUSR2
);
2250 pthread_join (keepalive_tid
, NULL
);
2253 cleanup_all_clients (0);
2258 pthread_cond_destroy (&quit_cond
);
2259 pthread_mutex_destroy (&quit_mutex
);
2260 return segv
? EXIT_FAILURE
: EXIT_SUCCESS
;;
2267 ("Failed to add a file to the cache. Use --force to force startup. Exiting."));
2268 cache_clear (NULL
, NULL
, 1);
2272 usage (const char *pn
, int status
)
2274 FILE *fp
= status
== EXIT_FAILURE
? stderr
: stdout
;
2276 fprintf (fp
, _("Usage: %s [OPTIONS] [file1] [...]\n"
2277 " --debug=[a:..][,g:N][,t:N] enable debugging (a:[ixedsc],g:[1-9],t:[0-N])\n"
2278 " -f, --rcfile=filename load the specfied configuration file\n"
2279 " (~/.pwmd/config)\n"
2280 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2281 " --kill terminate an existing instance of pwmd\n"
2282 " -n, --no-fork run as a foreground process\n"
2283 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2284 " --ignore, --force ignore file errors during startup\n"
2285 " -o, --outfile=filename output file when importing or converting\n"
2286 " -C, --convert=filename convert a version 2 data file to version 3\n"
2287 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2288 " -k, --passphrase-file=file for use when importing or converting\n"
2289 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2291 " --no-passphrase when importing or converting\n"
2292 " --keyid=keyID[,..] public key to use when encrypting\n"
2293 " --sign-keyid=fpr[,..] fingerprint of the signing key to use\n"
2294 " --symmetric use conventional encryption with optional signer\n"
2295 " --keyparam=filename custom key parameters to use (gpg default)\n"
2296 " --help this help text\n"
2297 " --version show version and compile time features\n"),
2303 unlink_stale_socket (const char *sock
, const char *pidfile
)
2305 log_write (_ ("removing stale socket %s"), sock
);
2311 test_pidfile (const char *path
, const char *sock
, char *buf
, size_t buflen
,
2312 char **pidfile
, int create
, mode_t mode
, int terminate
)
2320 snprintf (buf
, buflen
, "%s/%s.pid", homedir
, sock
);
2321 *pidfile
= str_dup (buf
);
2322 fd
= open (buf
, O_RDONLY
);
2325 fd
= open (*pidfile
, O_CREAT
|O_WRONLY
|O_TRUNC
, mode
);
2329 if (!create
&& errno
!= ENOENT
)
2331 log_write ("%s: %s", buf
, pwmd_strerror (errno
));
2336 else if (!create
&& !terminate
)
2339 log_write ("%s: %s", *pidfile
, strerror (errno
));
2345 snprintf (buf
, buflen
, "%i", getpid ());
2346 ssize_t ret
= write (fd
, buf
, strlen (buf
));
2348 log_write ("%s (%i): %s", __FUNCTION__
, __LINE__
,
2349 pwmd_strerror (gpg_error_from_syserror ()));
2354 len
= read (fd
, buf
, buflen
);
2358 unlink_stale_socket (path
, *pidfile
);
2362 if (sscanf (buf
, "%5i", &pid
) != 1 || pid
== 0)
2366 unlink_stale_socket (path
, *pidfile
);
2371 if (kill (pid
, 0) == -1)
2373 unlink_stale_socket (path
, *pidfile
);
2379 if (kill (pid
, SIGTERM
) == -1)
2380 log_write ("%s: %s", path
, pwmd_strerror (errno
));
2383 log_write (_ ("an instance for socket %s is already running"), path
);
2391 parse_debug_level (const char *str
, unsigned *debug
, int *gpgme
, int *tls
)
2397 for (p
= str
; p
&& *p
; p
++)
2399 if (*p
== 'a') // assuan debug flags
2409 level
|= ASSUAN_LOG_INIT
;
2412 level
|= ASSUAN_LOG_CTX
;
2415 level
|= ASSUAN_LOG_ENGINE
;
2418 level
|= ASSUAN_LOG_DATA
;
2421 level
|= ASSUAN_LOG_SYSIO
;
2424 level
|= ASSUAN_LOG_CONTROL
;
2439 else if (*p
== 'g' || *p
== 't') // gpgme and TLS debug level
2447 if (!isdigit (*++p
))
2456 if (tl
< 0 || gl
< 0 || gl
> 9)
2459 while (isdigit (*p
))
2463 if (*(p
+1) && *(p
+1) != ',')
2483 main (int argc
, char *argv
[])
2486 struct sockaddr_un addr
;
2488 char *socketpath
= NULL
, *socketdir
, *socketname
= NULL
;
2489 char *socketarg
= NULL
;
2490 char *datadir
= NULL
;
2491 char *pidfile
= NULL
;
2495 char **cache_push
= NULL
;
2496 char *import
= NULL
, *keyid
= NULL
, *sign_keyid
= NULL
;
2497 char *keyparam
= NULL
;
2498 int estatus
= EXIT_FAILURE
;
2500 char *outfile
= NULL
;
2503 int show_version
= 0;
2506 char *keyfile
= NULL
;
2511 int gpgme_level
= -1;
2513 /* Must maintain the same order as longopts[] */
2516 OPT_VERSION
, OPT_HELP
, OPT_HOMEDIR
, OPT_NO_FORK
, OPT_DISABLE_DUMP
,
2517 OPT_FORCE
, OPT_RCFILE
, OPT_PASSPHRASE_FILE
, OPT_IMPORT
, OPT_OUTFILE
,
2518 OPT_KEYID
, OPT_SIGN_KEYID
, OPT_SYMMETRIC
, OPT_KEYPARAM
, OPT_KILL
,
2521 const char *optstring
= "nf:C:k:I:o:s";
2522 const struct option longopts
[] = {
2523 {"version", no_argument
, 0, 0},
2524 {"help", no_argument
, 0, 0},
2525 {"homedir", required_argument
, 0, 0},
2526 {"no-fork", no_argument
, 0, 'n'},
2527 {"disable_dump", no_argument
, 0, 0},
2528 {"force", no_argument
, 0, 0},
2529 {"rcfile", required_argument
, 0, 'f'},
2530 {"passphrase-file", required_argument
, 0, 'k'},
2531 {"import", required_argument
, 0, 'I'},
2532 {"outfile", required_argument
, 0, 'o'},
2533 {"keyid", required_argument
, 0, 0},
2534 {"sign-keyid", required_argument
, 0, 0},
2535 {"symmetric", no_argument
, 0, 's'},
2536 {"keyparam", required_argument
, 0, 0},
2537 {"kill", no_argument
, 0, 0},
2538 {"debug", required_argument
, 0, 0},
2546 #ifdef HAVE_SETRLIMIT
2549 rl
.rlim_cur
= rl
.rlim_max
= 0;
2551 if (setrlimit (RLIMIT_CORE
, &rl
) != 0)
2552 err (EXIT_FAILURE
, "setrlimit()");
2555 #ifdef HAVE_PR_SET_DUMPABLE
2556 prctl (PR_SET_DUMPABLE
, 0);
2561 setlocale (LC_ALL
, "");
2562 bindtextdomain ("pwmd", LOCALEDIR
);
2563 textdomain ("pwmd");
2566 if (setup_crypto ())
2567 exit (EXIT_FAILURE
);
2570 tls_level
= tls_level
== -1 ? 1 : tls_level
;
2571 gnutls_global_set_log_level (tls_level
);
2575 xmlMemSetup (xfree
, xmalloc
, xrealloc
, str_dup
);
2581 while ((opt
= getopt_long (argc
, argv
, optstring
, longopts
, &optindex
))
2602 rcfile
= str_dup (optarg
);
2608 usage (argv
[0], EXIT_FAILURE
);
2614 if (parse_debug_level (optarg
, &assuan_level
, &gpgme_level
,
2616 usage (argv
[0], EXIT_FAILURE
);
2625 usage (argv
[0], EXIT_SUCCESS
);
2628 homedir
= str_dup (optarg
);
2633 case OPT_DISABLE_DUMP
:
2640 rcfile
= str_dup (optarg
);
2642 case OPT_PASSPHRASE_FILE
:
2654 case OPT_SIGN_KEYID
:
2655 sign_keyid
= optarg
;
2664 usage (argv
[0], EXIT_FAILURE
);
2672 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016\n"
2674 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2675 "Compile time features:\n%s"), PACKAGE_STRING
,
2678 "+PWMD_HOMEDIR=" PWMD_HOMEDIR
"\n"
2706 exit (EXIT_SUCCESS
);
2711 homedir
= str_dup(PWMD_HOMEDIR
);
2713 homedir
= str_asprintf ("%s/.pwmd", get_home_dir());
2716 if (mkdir (homedir
, 0700) == -1 && errno
!= EEXIST
)
2717 err (EXIT_FAILURE
, "%s", homedir
);
2720 rcfile
= str_asprintf ("%s/config", homedir
);
2722 pthread_key_create (&last_error_key
, free_key
);
2723 #ifndef HAVE_PTHREAD_CANCEL
2724 pthread_key_create (&signal_thread_key
, free_key
);
2727 pthread_mutexattr_t attr
;
2728 pthread_mutexattr_init (&attr
);
2729 pthread_mutexattr_settype (&attr
, PTHREAD_MUTEX_RECURSIVE
);
2730 pthread_mutex_init (&rcfile_mutex
, &attr
);
2731 global_config
= config_parse (rcfile
, 0);
2734 pthread_mutexattr_destroy (&attr
);
2735 pthread_mutex_destroy (&rcfile_mutex
);
2736 exit (EXIT_FAILURE
);
2739 p
= config_get_string ("global", "gpg_homedir");
2741 datadir
= str_asprintf ("%s/.gnupg", homedir
);
2743 datadir
= expand_homedir (p
);
2746 if (mkdir (datadir
, 0700) == -1 && errno
!= EEXIST
)
2747 err (EXIT_FAILURE
, "%s", datadir
);
2749 if (gpgme_level
!= -1)
2751 char s
[2] = { gpgme_level
+ '0', 0 };
2753 if (getenv ("GPGME_DEBUG"))
2754 log_write (_ ("Overriding GPGME_DEBUG environment with level %u!"),
2757 gpgme_set_global_flag ("debug", s
);
2760 rc
= gpgme_set_engine_info (GPGME_PROTOCOL_OpenPGP
, NULL
, datadir
);
2763 snprintf (buf
, sizeof (buf
), "%s/data", homedir
);
2764 if (mkdir (buf
, 0700) == -1 && errno
!= EEXIST
)
2765 err (EXIT_FAILURE
, "%s", buf
);
2767 datadir
= str_dup (buf
);
2768 pthread_cond_init (&rcfile_cond
, NULL
);
2769 pthread_mutex_init (&cn_mutex
, &attr
);
2770 pthread_mutexattr_destroy (&attr
);
2774 x
= config_get_int_param (global_config
, "global", "priority", &exists
);
2775 if (exists
&& x
!= atoi(INVALID_PRIORITY
))
2778 if (setpriority (PRIO_PROCESS
, 0, x
) == -1)
2780 log_write ("setpriority(): %s",
2781 pwmd_strerror (gpg_error_from_errno (errno
)));
2785 #ifdef HAVE_MLOCKALL
2786 if (disable_mlock
== 0 && mlockall (MCL_CURRENT
| MCL_FUTURE
) == -1)
2788 log_write ("mlockall(): %s",
2789 pwmd_strerror (gpg_error_from_errno (errno
)));
2797 log_write ("pwmd: ERR %i: %s", rc
, pwmd_strerror (rc
));
2798 exit (EXIT_FAILURE
);
2803 char **keyids
= NULL
, **sign_keyids
= NULL
;
2805 if (!outfile
|| !*outfile
|| argc
!= optind
)
2806 usage (argv
[0], EXIT_FAILURE
);
2809 keyids
= str_split (keyid
, ",", 0);
2811 sign_keyids
= str_split (sign_keyid
, ",", 0);
2812 rc
= xml_import (import
, outfile
, keyids
, sign_keyids
, keyfile
, keyparam
, sym
);
2814 strv_free (sign_keyids
);
2817 if (gpg_err_source (rc
) == GPG_ERR_SOURCE_UNKNOWN
)
2818 rc
= gpg_error (rc
);
2820 log_write ("%s: %u: %s", import
, rc
, pwmd_strerror (rc
));
2823 config_free (global_config
);
2825 exit (rc
? EXIT_FAILURE
: EXIT_SUCCESS
);
2828 p
= config_get_string ("global", "socket_path");
2830 p
= str_asprintf ("%s/socket", homedir
);
2832 socketarg
= expand_homedir (p
);
2836 disable_list_and_dump
= config_get_boolean ("global",
2837 "disable_list_and_dump");
2839 disable_list_and_dump
= secure
;
2841 cache_push
= config_get_list ("global", "cache_push");
2843 while (optind
< argc
)
2845 if (strv_printf (&cache_push
, "%s", argv
[optind
++]) == 0)
2846 errx (EXIT_FAILURE
, "%s", pwmd_strerror (GPG_ERR_ENOMEM
));
2849 if (strchr (socketarg
, '/') == NULL
)
2851 socketdir
= getcwd (buf
, sizeof (buf
));
2852 socketname
= str_dup (socketarg
);
2853 socketpath
= str_asprintf ("%s/%s", socketdir
, socketname
);
2857 socketname
= str_dup (strrchr (socketarg
, '/'));
2859 socketarg
[strlen (socketarg
) - strlen (socketname
) - 1] = 0;
2860 socketdir
= str_dup (socketarg
);
2861 socketpath
= str_asprintf ("%s/%s", socketdir
, socketname
);
2864 if (chdir (datadir
))
2866 log_write ("%s: %s", datadir
,
2867 pwmd_strerror (gpg_error_from_errno (errno
)));
2868 unlink (socketpath
);
2872 x
= test_pidfile (socketpath
, socketname
, buf
, sizeof(buf
), &pidfile
, 0,
2874 if (!terminate
&& x
)
2878 estatus
= x
!= 1 ? EXIT_FAILURE
: EXIT_SUCCESS
;
2883 * bind() doesn't like the full pathname of the socket or any non alphanum
2884 * characters so change to the directory where the socket is wanted then
2885 * create it then change to datadir.
2887 if (chdir (socketdir
))
2889 log_write ("%s: %s", socketdir
,
2890 pwmd_strerror (gpg_error_from_errno (errno
)));
2896 if ((sockfd
= socket (PF_UNIX
, SOCK_STREAM
, 0)) == -1)
2898 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
2902 addr
.sun_family
= AF_UNIX
;
2903 snprintf (addr
.sun_path
, sizeof (addr
.sun_path
), "%s", socketname
);
2905 if (bind (sockfd
, (struct sockaddr
*) &addr
, sizeof (struct sockaddr
)) ==
2908 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
2910 if (errno
== EADDRINUSE
)
2913 log_write (_("Either there is another pwmd running or '%s' is a \n"
2914 "stale socket. Please remove it manually."), socketpath
);
2921 char *t
= config_get_string ("global", "socket_perms");
2926 mode
= strtol (t
, NULL
, 8);
2930 if (chmod (socketname
, mode
) == -1)
2932 log_write ("%s: %s", socketname
,
2933 pwmd_strerror (gpg_error_from_errno (errno
)));
2943 xfree (--socketname
);
2945 if (chdir (datadir
))
2947 log_write ("%s: %s", datadir
,
2948 pwmd_strerror (gpg_error_from_errno (errno
)));
2956 * Set the cache entry for a file. Prompts for the password.
2960 for (opt
= 0; cache_push
[opt
]; opt
++)
2962 struct crypto_s
*crypto
= NULL
;
2963 char *pw_file
= config_get_string (cache_push
[opt
],
2965 gpg_error_t rc
= crypto_init (&crypto
, NULL
, cache_push
[opt
],
2966 pw_file
!= NULL
, pw_file
);
2970 crypto
->flags
|= pw_file
? CRYPTO_FLAG_KEYFILE
: 0;
2971 crypto
->keyfile
= pw_file
;
2978 estatus
= EXIT_FAILURE
;
2982 rc
= do_cache_push (crypto
);
2985 log_write ("ERR %u: %s", rc
, pwmd_strerror(rc
));
2986 strv_free (cache_push
);
2988 estatus
= EXIT_FAILURE
;
2989 crypto_free (crypto
);
2993 log_write ("%s: %s", crypto
->filename
, pwmd_strerror(rc
));
2995 log_write (_("Successfully added '%s' to the cache."),
2998 crypto_free (crypto
);
3001 strv_free (cache_push
);
3002 log_write (!nofork
? _("Done. Daemonizing...") :
3003 _("Done. Waiting for connections..."));
3006 if (listen (sockfd
, 128) == -1)
3008 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
3017 log_write ("fork(): %s",
3018 pwmd_strerror (gpg_error_from_errno (errno
)));
3027 _exit (EXIT_SUCCESS
);
3031 (void)test_pidfile (socketpath
, socketname
, buf
, sizeof(buf
), &pidfile
, 1,
3034 pthread_key_create (&thread_name_key
, free_key
);
3035 estatus
= server_loop (sockfd
, &socketpath
);
3038 if (socketpath
&& do_unlink
)
3040 unlink (socketpath
);
3046 gnutls_global_deinit ();
3047 tls_deinit_params ();
3051 #ifdef HAVE_PTHREAD_CANCEL
3052 pthread_cancel (rcfile_tid
);
3054 pthread_kill (rcfile_tid
, SIGUSR2
);
3055 pthread_cond_signal (&rcfile_cond
);
3057 pthread_join (rcfile_tid
, NULL
);
3060 pthread_cond_destroy (&rcfile_cond
);
3061 pthread_mutex_destroy (&rcfile_mutex
);
3062 pthread_key_delete (last_error_key
);
3063 #ifndef HAVE_PTHREAD_CANCEL
3064 pthread_key_delete (signal_thread_key
);
3068 config_free (global_config
);
3070 free_invoking_users (invoking_users
);
3072 xfree (home_directory
);
3074 xmlCleanupParser ();
3075 xmlCleanupGlobals ();
3081 if (estatus
== EXIT_SUCCESS
&& !terminate
)
3082 log_write (_("pwmd exiting normally"));
3084 pthread_key_delete (thread_name_key
);
3093 gpg_error_t
lock_flock (assuan_context_t ctx
, const char *filename
,
3099 *fd
= open (filename
, O_RDONLY
);
3101 return gpg_error_from_syserror ();
3103 TRY_FLOCK (ctx
, *fd
, type
, rc
);
3114 void unlock_flock (int *fd
)