2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015
3 Ben Kibbey <bjk@luxsci.net>
5 This file is part of pwmd.
7 Pwmd is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 2 of the License, or
10 (at your option) any later version.
12 Pwmd is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
30 #include <sys/socket.h>
44 #include <netinet/in.h>
45 #include <arpa/inet.h>
48 #include <sys/resource.h>
62 #ifdef HAVE_GETOPT_LONG
67 #include "getopt_long.h"
70 #ifdef HAVE_PR_SET_NAME
71 #include <sys/prctl.h>
74 #include "pwmd-error.h"
77 #include "util-misc.h"
83 #include "util-string.h"
90 /* In tenths of a second. */
93 /* For (tcp_)accept_thread (usec). */
94 #define ACCEPT_TIMEOUT 30000
101 static pthread_cond_t quit_cond
;
102 static pthread_mutex_t quit_mutex
;
103 static int no_passphrase_file
= 0;
104 static pthread_t keepalive_tid
;
107 #ifndef HAVE_PTHREAD_CANCEL
108 static pthread_key_t signal_thread_key
;
114 static pthread_t tls_tid
;
115 static pthread_t tls6_tid
;
116 static int spawned_tls
;
117 static int spawned_tls6
;
119 static int start_stop_tls (int term
);
122 static int do_cache_push (const char *filename
, struct crypto_s
*crypto
);
123 static int signal_loop (sigset_t sigset
);
125 GCRY_THREAD_OPTION_PTHREAD_IMPL
;
127 #ifndef HAVE_PTHREAD_CANCEL
128 #define INIT_THREAD_SIGNAL do { \
129 struct sigaction act; \
131 sigemptyset (&sigset); \
132 sigaddset (&sigset, SIGUSR2); \
133 pthread_sigmask (SIG_UNBLOCK, &sigset, NULL); \
134 memset (&act, 0, sizeof(act)); \
135 act.sa_flags = SA_SIGINFO; \
136 act.sa_mask = sigset; \
137 act.sa_sigaction = catch_thread_signal; \
138 sigaction (SIGUSR2, &act, NULL); \
142 catch_thread_signal (int sig
, siginfo_t
*info
, void *ctx
)
144 int *n
= (int *) pthread_getspecific (signal_thread_key
);
147 pthread_setspecific (signal_thread_key
, n
);
152 cache_push_from_rcfile ()
154 struct crypto_s
*crypto
= NULL
;
156 gpg_error_t rc
= init_client_crypto (&crypto
);
160 log_write ("%s: %s", __FUNCTION__
, pwmd_strerror (rc
));
167 rc
= set_agent_option (crypto
->agent
, "pinentry-mode", "error");
170 log_write ("%s: %s", __FUNCTION__
, pwmd_strerror (rc
));
176 cache_push
= config_get_list ("global", "cache_push");
181 for (p
= cache_push
; *p
; p
++)
183 (void) do_cache_push (*p
, crypto
);
184 cleanup_crypto_stage1 (crypto
);
187 strv_free (cache_push
);
191 (void) kill_scd (crypto
->agent
);
193 cleanup_crypto (&crypto
);
199 int n
= config_get_boolean ("global", "enable_logging");
203 char *p
= config_get_string ("global", "log_path");
205 if (!p
|| (logfile
&& p
&& log_fd
!= -1 && strcmp(p
, logfile
)))
216 logfile
= expand_homedir (p
);
229 log_syslog
= config_get_boolean ("global", "syslog");
231 openlog ("pwmd", LOG_NDELAY
| LOG_PID
, LOG_DAEMON
);
235 reload_rcfile_thread (void *arg
)
237 #ifndef HAVE_PTHREAD_CANCEL
238 int *n
= xmalloc (sizeof (int));
241 pthread_setspecific (signal_thread_key
, n
);
245 #ifdef HAVE_PR_SET_NAME
246 prctl (PR_SET_NAME
, "reload rcfile");
248 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
249 MUTEX_LOCK (&rcfile_mutex
);
250 pthread_cleanup_push (cleanup_mutex_cb
, &rcfile_mutex
);
254 struct allowed_users_s
259 struct slist_s
*allowed_users
= NULL
;
260 struct slist_s
*config
;
261 int b
= disable_list_and_dump
;
262 uid_t invoking_uid_orig
= invoking_uid
;
263 gid_t invoking_gid_orig
= invoking_gid
;
264 char *invoking_tls_orig
;
266 int require_save_key
= config_get_bool_param (global_config
, "global",
270 int tcp_require_key
= config_get_bool_param (global_config
, "global",
275 pthread_cond_wait (&rcfile_cond
, &rcfile_mutex
);
276 #ifndef HAVE_PTHREAD_CANCEL
277 int *cancel
= (int *) pthread_getspecific (signal_thread_key
);
282 /* Keep the "allowed" parameter across rcfile reloads to prevent
284 int n
, t
= slist_length (global_config
);
285 for (n
= 0; n
< t
; n
++)
287 struct config_section_s
*section
;
290 section
= slist_nth_data (global_config
, n
);
291 users
= config_get_list_param (global_config
, section
->name
,
295 struct allowed_users_s
*allowed
;
297 allowed
= xmalloc (sizeof(struct allowed_users_s
));
298 allowed
->section
= str_dup (section
->name
);
299 allowed
->users
= users
;
300 allowed_users
= slist_append (allowed_users
, allowed
);
304 invoking_tls_orig
= invoking_tls
? str_dup (invoking_tls
) : NULL
;
305 xfree (invoking_tls
);
307 log_write (_("reloading configuration file '%s'"), rcfile
);
309 config
= config_parse (rcfile
);
312 config_free (global_config
);
313 global_config
= config
;
315 cache_push_from_rcfile ();
316 config_clear_keys ();
319 xfree (invoking_tls
);
320 invoking_tls
= invoking_tls_orig
;
321 invoking_uid
= invoking_uid_orig
;
322 invoking_gid
= invoking_gid_orig
;
323 disable_list_and_dump
= !disable_list_and_dump
? b
: 1;
324 config_set_bool_param (&global_config
, "global", "require_save_key",
325 require_save_key
? "true" : "false");
327 if (config_get_bool_param (global_config
, "global", "tcp_require_key",
331 config_set_bool_param (&global_config
, "global", "tcp_require_key",
332 tcp_require_key
? "true" : "false");
337 int n
, t
= slist_length (allowed_users
);
339 for (n
= 0; n
< t
; n
++)
341 struct allowed_users_s
*allowed
;
344 allowed
= slist_nth_data (allowed_users
, n
);
345 tmp
= strv_join (",", allowed
->users
);
346 config_set_list_param (&global_config
, allowed
->section
,
349 xfree (allowed
->section
);
350 strv_free (allowed
->users
);
354 slist_free (allowed_users
);
358 /* Kill existing listening threads since the configured listening
359 * protocols may have changed. */
365 pthread_cleanup_pop (1);
370 send_error (assuan_context_t ctx
, gpg_error_t e
)
372 struct client_s
*client
= assuan_get_pointer (ctx
);
374 if (gpg_err_source (e
) == GPG_ERR_SOURCE_UNKNOWN
)
381 return assuan_process_done (ctx
, 0);
385 log_write ("ERR %i: %s", e
, pwmd_strerror (e
));
389 if (client
&& client
->xml_error
)
391 log_write ("%s", client
->xml_error
->message
);
392 xfree (client
->last_error
);
393 client
->last_error
= NULL
;
394 if (client
->xml_error
->message
)
395 client
->last_error
= str_dup (client
->xml_error
->message
);
397 e
= assuan_process_done (ctx
,
398 assuan_set_error (ctx
, e
,
399 client
->xml_error
->message
? client
->xml_error
->message
: NULL
));
400 xmlResetLastError ();
401 xmlResetError (client
->xml_error
);
402 xfree (client
->xml_error
);
403 client
->xml_error
= NULL
;
407 return assuan_process_done (ctx
,
408 assuan_set_error (ctx
, e
, pwmd_strerror (e
)));
412 assuan_log_cb (assuan_context_t ctx
, void *data
, unsigned cat
,
415 static pthread_mutex_t m
= PTHREAD_MUTEX_INITIALIZER
;
419 pthread_mutex_lock (&m
);
420 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock
, &m
);
421 t
= strv_length (debug_level
);
423 for (i
= 0; i
< t
; i
++)
425 if (!strcasecmp (debug_level
[i
], (char *) "init")
426 && cat
== ASSUAN_LOG_INIT
)
432 if (!strcasecmp (debug_level
[i
], (char *) "ctx")
433 && cat
== ASSUAN_LOG_CTX
)
439 if (!strcasecmp (debug_level
[i
], (char *) "engine")
440 && cat
== ASSUAN_LOG_ENGINE
)
446 if (!strcasecmp (debug_level
[i
], (char *) "data")
447 && cat
== ASSUAN_LOG_DATA
)
453 if (!strcasecmp (debug_level
[i
], (char *) "sysio")
454 && cat
== ASSUAN_LOG_SYSIO
)
460 if (!strcasecmp (debug_level
[i
], (char *) "control")
461 && cat
== ASSUAN_LOG_CONTROL
)
475 open (logfile
, O_WRONLY
| O_CREAT
| O_APPEND
, 0600)) == -1)
476 warn ("%s", logfile
);
479 pthread_cleanup_push (cleanup_fd_cb
, &fd
);
480 write (fd
, msg
, strlen (msg
));
481 pthread_cleanup_pop (1);
487 fprintf (stderr
, "%s%s", data
? (char *) data
: "", msg
);
492 pthread_cleanup_pop (1);
497 log_write (const char *fmt
, ...)
503 pthread_t tid
= pthread_self ();
504 static pthread_mutex_t m
= PTHREAD_MUTEX_INITIALIZER
;
506 if ((!logfile
&& !isatty (STDERR_FILENO
) && !log_syslog
) || !fmt
)
509 pthread_mutex_lock (&m
);
510 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock
, &m
);
512 if (!cmdline
&& logfile
&& log_fd
== -1)
514 log_fd
= open (logfile
, O_WRONLY
| O_CREAT
| O_APPEND
, 0600);
516 warn ("%s", logfile
);
521 if (str_vasprintf (&args
, fmt
, ap
) != -1)
525 pthread_cleanup_push (xfree
, args
);
526 fprintf (stderr
, "pwmd: %s\n", args
);
528 pthread_cleanup_pop (1);
532 char *name
= pthread_getspecific (thread_name_key
);
535 pthread_cleanup_push (xfree
, args
);
536 snprintf (buf
, sizeof (buf
), "%s(%p): ", name
? name
: _("unknown"),
540 if (!cmdline
&& log_syslog
&& !nofork
)
541 syslog (LOG_INFO
, "%s%s", name
, args
);
544 struct tm
*tm
= localtime (&now
);
546 strftime (tbuf
, sizeof (tbuf
), "%b %d %Y %H:%M:%S ", tm
);
547 tbuf
[sizeof (tbuf
) - 1] = 0;
549 if (args
[strlen (args
) - 1] == '\n')
550 args
[strlen (args
) - 1] = 0;
552 line
= str_asprintf ("%s %i %s%s\n", tbuf
, getpid (), name
,
554 pthread_cleanup_pop (1);
557 pthread_cleanup_push (xfree
, line
);
558 if (logfile
&& log_fd
!= -1)
560 write (log_fd
, line
, strlen (line
));
566 fprintf (stdout
, "%s", line
);
570 pthread_cleanup_pop (1);
576 pthread_cleanup_pop (0);
578 if (log_fd
!= -1 && config_get_boolean (NULL
, "log_keepopen") <= 0)
584 pthread_mutex_unlock (&m
);
589 secure_mem_check (const void *arg
)
598 gcry_control (GCRYCTL_SET_THREAD_CBS
, &gcry_threads_pthread
);
600 if (!gcry_check_version (GCRYPT_VERSION
))
602 fprintf (stderr
, _("gcry_check_version(): Incompatible libgcrypt. "
603 "Wanted %s, got %s.\n"), GCRYPT_VERSION
,
604 gcry_check_version (NULL
));
605 return GPG_ERR_UNKNOWN_VERSION
;
608 gcry_set_allocation_handler (xmalloc
, xmalloc
, NULL
, xrealloc
, xfree
);
613 do_validate_peer (assuan_context_t ctx
, const char *section
,
614 assuan_peercred_t
* peer
)
619 struct client_s
*client
= assuan_get_pointer (ctx
);
622 return GPG_ERR_EACCES
;
625 if (client
->thd
->remote
)
626 return tls_validate_access (client
, section
);
629 rc
= assuan_get_peercred (ctx
, peer
);
633 users
= config_get_list (section
, "allowed");
636 for (char **p
= users
; *p
; p
++)
638 rc
= acl_check_common(client
, *p
, (*peer
)->uid
, (*peer
)->gid
,
645 return allowed
? 0 : rc
? rc
: GPG_ERR_EACCES
;
649 peer_is_invoker(struct client_s
*client
)
651 if (client
->thd
->state
== CLIENT_STATE_UNKNOWN
)
652 return GPG_ERR_EACCES
;
655 if (client
->thd
->remote
)
657 char *p
= invoking_tls
;
659 if (!p
|| !*p
|| *p
++ != '#')
660 return GPG_ERR_EACCES
;
662 if (!strcmp(client
->thd
->tls
->fp
, p
))
665 return GPG_ERR_EACCES
;
669 if (client
->thd
->peer
->uid
== invoking_uid
)
672 return GPG_ERR_EACCES
;
675 #ifdef HAVE_GETGRNAM_R
677 acl_check_common (struct client_s
*client
, const char *user
, uid_t uid
,
678 gid_t gid
, int *allowed
)
680 struct passwd pw
, *result
;
689 if (*user
== '-' || *user
== '!')
692 if (*user
== '+') // not implemented yet
695 if (*user
== '#') // TLS fingerprint hash
698 if (not || rw
|| tls
)
704 if (client
->thd
->remote
)
706 if (!strcasecmp (client
->thd
->tls
->fp
, user
))
716 else if (client
->thd
->remote
) // Remote client with no TLS in the ACL
720 if (*user
== '@') // all users in group
722 struct group gr
, *gresult
;
723 size_t len
= sysconf (_SC_GETGR_R_SIZE_MAX
);
730 return GPG_ERR_ENOMEM
;
733 if (!getgrnam_r (user
, &gr
, buf
, len
, &gresult
) && gresult
)
735 if (gresult
->gr_gid
== gid
)
742 len
= sysconf (_SC_GETPW_R_SIZE_MAX
);
746 char *tbuf
= xmalloc (len
);
747 for (char **t
= gresult
->gr_mem
; *t
; t
++)
749 if (!getpwnam_r (*t
, &pw
, tbuf
, len
, &result
) && result
)
751 if (result
->pw_uid
== uid
)
764 size_t len
= sysconf (_SC_GETPW_R_SIZE_MAX
);
771 return GPG_ERR_ENOMEM
;
773 if (!getpwnam_r (user
, &pw
, buf
, len
, &result
) && result
)
775 if (result
->pw_uid
== uid
)
786 acl_check_common (struct client_s
*client
, const char *user
, uid_t uid
,
787 gid_t gid
, int *allowed
)
789 struct passwd
*result
;
797 if (*user
== '-' || *user
== '!')
800 if (*user
== '+') // not implemented yet
803 if (*user
== '#') // TLS fingerprint hash
806 if (not || rw
|| tls
)
812 if (client
->thd
->remote
)
814 if (!strcasecmp (client
->thd
->tls
->fp
, user
))
824 if (*user
== '@') // all users in group
826 struct group
*gresult
;
829 gresult
= getgrnam (user
);
830 if (gresult
&& gresult
->gr_gid
== gid
)
836 for (char **t
= gresult
->gr_mem
; *t
; t
++)
838 result
= getpwnam (*t
);
839 if (result
&& result
->pw_uid
== uid
)
850 result
= getpwnam (user
);
851 if (result
&& result
->pw_uid
== uid
)
860 validate_peer (struct client_s
*cl
)
866 return tls_validate_access (cl
, NULL
);
869 MUTEX_LOCK (&cn_mutex
);
870 rc
= do_validate_peer (cl
->ctx
, "global", &cl
->thd
->peer
);
871 MUTEX_UNLOCK (&cn_mutex
);
872 if (!rc
|| gpg_err_code (rc
) == GPG_ERR_EACCES
)
873 log_write ("peer %s: uid=%i, gid=%i, pid=%i",
874 !rc
? _("accepted") : _("rejected"), cl
->thd
->peer
->uid
,
875 cl
->thd
->peer
->gid
, cl
->thd
->peer
->pid
);
877 log_write ("%s: %s", __FUNCTION__
, pwmd_strerror (rc
));
883 xml_error_cb (void *data
, xmlErrorPtr e
)
885 struct client_s
*client
= data
;
888 * Keep the first reported error as the one to show in the error
889 * description. Reset in send_error().
891 if (client
->xml_error
)
894 client
->xml_error
= xcalloc (1, sizeof(xmlError
));
895 xmlCopyError (e
, client
->xml_error
);
899 hook_waitpid (assuan_context_t ctx
, pid_t pid
, int action
,
900 int *status
, int options
)
902 return waitpid (pid
, status
, options
);
906 hook_read (assuan_context_t ctx
, assuan_fd_t fd
, void *data
, size_t len
)
909 struct client_s
*client
= assuan_get_pointer (ctx
);
911 if (client
->thd
->remote
)
912 return tls_read_hook (ctx
, (int) fd
, data
, len
);
915 return read ((int) fd
, data
, len
);
919 hook_write (assuan_context_t ctx
, assuan_fd_t fd
,
920 const void *data
, size_t len
)
923 struct client_s
*client
= assuan_get_pointer (ctx
);
925 if (client
->thd
->remote
)
926 return tls_write_hook (ctx
, (int) fd
, data
, len
);
929 return write ((int) fd
, data
, len
);
933 new_connection (struct client_s
*cl
)
936 static struct assuan_malloc_hooks mhooks
= { xmalloc
, xrealloc
, xfree
};
937 static struct assuan_system_hooks shooks
= {
938 ASSUAN_SYSTEM_HOOKS_VERSION
,
946 NULL
, //sendmsg both are used for FD passing
957 char *prio
= config_get_string ("global", "tls_cipher_suite");
959 cl
->thd
->timeout
= config_get_integer ("global", "tls_timeout");
960 if (fcntl (cl
->thd
->fd
, F_SETFL
, O_NONBLOCK
) == -1)
963 cl
->thd
->tls
= tls_init (cl
->thd
->fd
, cl
->thd
->timeout
, prio
);
970 rc
= assuan_new_ext (&cl
->ctx
, GPG_ERR_SOURCE_DEFAULT
, &mhooks
,
971 debug_level
? assuan_log_cb
: NULL
, NULL
);
975 assuan_ctx_set_system_hooks (cl
->ctx
, &shooks
);
976 rc
= assuan_init_socket_server (cl
->ctx
, cl
->thd
->fd
, 2);
980 assuan_set_pointer (cl
->ctx
, cl
);
981 assuan_set_hello_line (cl
->ctx
, PACKAGE_STRING
);
982 rc
= register_commands (cl
->ctx
);
986 rc
= assuan_accept (cl
->ctx
);
990 rc
= validate_peer (cl
);
991 /* May not be implemented on all platforms. */
992 if (rc
&& gpg_err_code (rc
) != GPG_ERR_ASS_GENERAL
)
995 MUTEX_LOCK (&cn_mutex
);
996 cl
->thd
->state
= CLIENT_STATE_INIT
;
997 MUTEX_UNLOCK (&cn_mutex
);
998 rc
= init_client_crypto (&cl
->crypto
);
1004 cl
->crypto
->agent
->client_ctx
= cl
->ctx
;
1007 cl
->crypto
->client_ctx
= cl
->ctx
;
1008 cl
->lock_timeout
= config_get_integer ("global", "lock_timeout");
1009 xmlSetStructuredErrorFunc (cl
, xml_error_cb
);
1013 log_write ("%s", pwmd_strerror (rc
));
1018 * This is called after a client_thread() terminates. Set with
1019 * pthread_cleanup_push().
1022 cleanup_cb (void *arg
)
1024 struct client_thread_s
*cn
= arg
;
1025 struct client_s
*cl
= cn
->cl
;
1027 MUTEX_LOCK (&cn_mutex
);
1028 cn_thread_list
= slist_remove (cn_thread_list
, cn
);
1029 MUTEX_UNLOCK (&cn_mutex
);
1033 cleanup_client (cl
);
1035 xmlResetError (cl
->xml_error
);
1037 xfree (cl
->xml_error
);
1042 gnutls_deinit (cn
->tls
->ses
);
1043 xfree (cn
->tls
->fp
);
1048 if (!cn
->atfork
&& cl
->ctx
)
1049 assuan_release (cl
->ctx
);
1050 else if (!cn
->atfork
&& cl
->thd
&& cl
->thd
->fd
!= -1)
1051 close (cl
->thd
->fd
);
1054 cleanup_crypto (&cl
->crypto
);
1056 pinentry_free_opts (&cl
->pinentry_opts
);
1065 while (cn
->msg_queue
)
1067 struct status_msg_s
*msg
= cn
->msg_queue
;
1069 cn
->msg_queue
= msg
->next
;
1074 if (!cn
->atfork
&& cn
->status_msg_pipe
[0] != -1)
1075 close (cn
->status_msg_pipe
[0]);
1077 if (!cn
->atfork
&& cn
->status_msg_pipe
[1] != -1)
1078 close (cn
->status_msg_pipe
[1]);
1080 pthread_mutex_destroy (&cn
->status_mutex
);
1084 log_write (_("exiting, fd=%i"), cn
->fd
);
1085 send_status_all (STATUS_CLIENTS
, NULL
);
1090 xfree (cn
->peeraddr
);
1093 pthread_cond_signal (&quit_cond
);
1097 cleanup_all_clients (int atfork
)
1099 /* This function may be called from pthread_atfork() which requires
1100 reinitialization. */
1103 pthread_mutexattr_t attr
;
1105 pthread_mutexattr_init (&attr
);
1106 pthread_mutexattr_settype (&attr
, PTHREAD_MUTEX_RECURSIVE
);
1107 pthread_mutex_init (&cn_mutex
, &attr
);
1108 pthread_mutexattr_destroy (&attr
);
1109 cache_mutex_init ();
1112 MUTEX_LOCK (&cn_mutex
);
1114 while (slist_length (cn_thread_list
))
1116 struct client_thread_s
*thd
= slist_nth_data (cn_thread_list
, 0);
1118 thd
->atfork
= atfork
;
1123 MUTEX_UNLOCK (&cn_mutex
);
1124 cache_deinit (atfork
);
1128 send_msg_queue (struct client_thread_s
*thd
)
1130 MUTEX_LOCK (&thd
->status_mutex
);
1134 read (thd
->status_msg_pipe
[0], &c
, 1);
1135 thd
->wrote_status
= 0;
1137 while (thd
->msg_queue
)
1139 struct status_msg_s
*msg
= thd
->msg_queue
;
1141 thd
->msg_queue
= thd
->msg_queue
->next
;
1142 MUTEX_UNLOCK (&thd
->status_mutex
);
1143 rc
= send_status (thd
->cl
->ctx
, msg
->s
, msg
->line
);
1144 MUTEX_LOCK (&thd
->status_mutex
);
1152 MUTEX_UNLOCK (&thd
->status_mutex
);
1153 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1154 log_write ("%s: %s", __FUNCTION__
, pwmd_strerror (rc
));
1160 client_thread (void *data
)
1162 struct client_thread_s
*thd
= data
;
1163 struct client_s
*cl
= xcalloc (1, sizeof (struct client_s
));
1165 #ifdef HAVE_PR_SET_NAME
1166 prctl (PR_SET_NAME
, "client");
1168 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1172 log_write ("%s(%i): %s", __FILE__
, __LINE__
,
1173 pwmd_strerror (GPG_ERR_ENOMEM
));
1177 MUTEX_LOCK (&cn_mutex
);
1178 pthread_cleanup_push (cleanup_cb
, thd
);
1181 MUTEX_UNLOCK (&cn_mutex
);
1183 if (new_connection (cl
))
1188 send_status_all (STATUS_CLIENTS
, NULL
);
1189 rc
= send_status (cl
->ctx
, STATUS_CACHE
, NULL
);
1192 log_write ("%s(%i): %s", __FILE__
, __LINE__
, pwmd_strerror (rc
));
1203 FD_SET (thd
->fd
, &rfds
);
1204 FD_SET (thd
->status_msg_pipe
[0], &rfds
);
1205 n
= thd
->fd
> thd
->status_msg_pipe
[0]
1206 ? thd
->fd
: thd
->status_msg_pipe
[0];
1208 n
= select (n
+ 1, &rfds
, NULL
, NULL
, NULL
);
1211 log_write ("%s", strerror (errno
));
1215 if (FD_ISSET (thd
->status_msg_pipe
[0], &rfds
))
1217 rc
= send_msg_queue (thd
);
1218 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1222 if (!FD_ISSET (thd
->fd
, &rfds
))
1225 rc
= assuan_process_next (cl
->ctx
, &eof
);
1228 if (gpg_err_code (rc
) == GPG_ERR_EOF
|| eof
)
1231 log_write ("assuan_process_next(): rc=%i %s", rc
,
1232 pwmd_strerror (rc
));
1233 if (rc
== gpg_error (GPG_ERR_ETIMEDOUT
))
1236 rc
= send_error (cl
->ctx
, rc
);
1239 log_write ("assuan_process_done(): rc=%i %s", rc
,
1240 pwmd_strerror (rc
));
1245 /* Since the msg queue pipe fd's are non-blocking, check for
1246 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1247 * client has already disconnected and will be converted to
1248 * GPG_ERR_EOF during assuan_process_next().
1250 rc
= send_msg_queue (thd
);
1251 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1256 /* Don't do pthread_exit() here because any set pthread_cleanup_push
1257 * functions would be called after a command failed but then the client
1258 * exited normally which may lead to a double free. */
1259 pthread_cleanup_pop (1);
1264 xml_import (const char *filename
, const char *outfile
,
1265 const char *keygrip
, const char *sign_keygrip
,
1266 const char *keyfile
, int no_passphrase
, const char *cipher
,
1267 const char *params
, unsigned long s2k_count
, uint64_t iterations
)
1276 struct crypto_s
*crypto
= NULL
;
1279 int algo
= cipher
? cipher_string_to_gcrypt ((char *) cipher
) :
1284 log_write ("ERR %i: %s", gpg_error (GPG_ERR_CIPHER_ALGO
),
1285 pwmd_strerror (GPG_ERR_CIPHER_ALGO
));
1289 if (stat (filename
, &st
) == -1)
1291 log_write ("%s: %s", filename
,
1292 pwmd_strerror (gpg_error_from_errno (errno
)));
1296 rc
= init_client_crypto (&crypto
);
1300 memcpy (&crypto
->save
.hdr
, &crypto
->hdr
, sizeof (file_header_t
));
1301 crypto
->save
.hdr
.flags
= set_cipher_flag (crypto
->save
.hdr
.flags
, algo
);
1302 log_write (_("Importing XML from '%s'. Output will be written to '%s' ..."),
1305 if ((fd
= open (filename
, O_RDONLY
)) == -1)
1307 log_write ("%s: %s", filename
,
1308 pwmd_strerror (gpg_error_from_errno (errno
)));
1312 if ((xmlbuf
= xmalloc (st
.st_size
+ 1)) == NULL
)
1315 log_write ("%s(%i): %s", __FILE__
, __LINE__
,
1316 pwmd_strerror (GPG_ERR_ENOMEM
));
1320 if (read (fd
, xmlbuf
, st
.st_size
) == -1)
1322 rc
= gpg_error_from_errno (errno
);
1324 log_write ("%s: %s", filename
, pwmd_strerror (rc
));
1329 xmlbuf
[st
.st_size
] = 0;
1331 * Make sure the document validates.
1333 if ((doc
= xmlReadDoc (xmlbuf
, NULL
, "UTF-8", XML_PARSE_NOBLANKS
)) == NULL
)
1335 log_write ("xmlReadDoc() failed");
1341 xmlNodePtr n
= xmlDocGetRootElement (doc
);
1342 if (n
&& !xmlStrEqual (n
->name
, (xmlChar
*) "pwmd"))
1344 log_write (_("Could not find root \"pwmd\" element."));
1345 rc
= GPG_ERR_BAD_DATA
;
1349 rc
= validate_import (NULL
, n
? n
->children
: n
);
1353 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
1358 xmlDocDumpMemory (doc
, &xml
, &len
);
1360 crypto
->save
.s2k_count
= s2k_count
;
1361 crypto
->save
.hdr
.iterations
= iterations
;
1364 rc
= export_common (NULL
, 0, crypto
, xml
, len
, outfile
, keyfile
, &key
,
1365 &keylen
, 0, 0, no_passphrase
);
1367 log_write (_("Success!"));
1372 rc
= agent_set_pinentry_options (crypto
->agent
);
1374 rc
= agent_export_common (crypto
, keygrip
, sign_keygrip
, no_passphrase
,
1375 xml
, len
, outfile
, params
, keyfile
);
1383 send_error (NULL
, rc
);
1387 cleanup_crypto (&crypto
);
1391 cleanup_crypto (&crypto
);
1396 do_cache_push (const char *filename
, struct crypto_s
*crypto
)
1398 unsigned char md5file
[16];
1403 struct cache_data_s
*cdata
;
1407 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1410 if (valid_filename (filename
) == 0)
1412 log_write (_("%s: Invalid characters in filename"), filename
);
1416 rc
= decrypt_common (NULL
, 0, crypto
, filename
, &key
, &keylen
);
1420 rc
= parse_doc ((char *) crypto
->plaintext
, crypto
->plaintext_len
, &doc
);
1423 log_write ("%s", pwmd_strerror (rc
));
1428 gcry_md_hash_buffer (GCRY_MD_MD5
, md5file
, filename
, strlen (filename
));
1429 cdata
= xcalloc (1, sizeof (struct cache_data_s
));
1433 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM
));
1438 rc
= get_checksum (filename
, &crc
, &len
);
1441 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
1443 free_cache_data_once (cdata
);
1449 rc
= encrypt_xml (NULL
, cache_key
, cache_keysize
, GCRY_CIPHER_AES
,
1450 crypto
->plaintext
, crypto
->plaintext_len
, &cdata
->doc
,
1451 &cdata
->doclen
, &cache_iv
, &cache_blocksize
, 0);
1452 if (!rc
&& !IS_PKI (crypto
))
1455 cdata
->keylen
= keylen
;
1462 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
1464 free_cache_data_once (cdata
);
1469 if (use_agent
&& IS_PKI (crypto
))
1471 gcry_sexp_build ((gcry_sexp_t
*) & cdata
->pubkey
, NULL
, "%S",
1473 gcry_sexp_build ((gcry_sexp_t
*) & cdata
->sigkey
, NULL
, "%S",
1474 crypto
->sigpkey_sexp
);
1478 int timeout
= config_get_integer (filename
, "cache_timeout");
1479 cache_add_file (md5file
, crypto
->grip
, cdata
, timeout
);
1480 log_write (_("Successfully added '%s' to the cache."), filename
);
1485 init_client (int fd
, const char *addr
)
1488 struct client_thread_s
*new = xcalloc (1, sizeof (struct client_thread_s
));
1493 return GPG_ERR_ENOMEM
;
1496 MUTEX_LOCK (&cn_mutex
);
1497 pthread_cleanup_push (cleanup_mutex_cb
, &cn_mutex
);
1499 if (pipe (new->status_msg_pipe
) == -1)
1500 rc
= gpg_error_from_errno (errno
);
1504 if (fcntl (new->status_msg_pipe
[0], F_SETFL
, O_NONBLOCK
) == -1)
1505 rc
= gpg_error_from_errno (errno
);
1508 if (fcntl (new->status_msg_pipe
[1], F_SETFL
, O_NONBLOCK
) == -1)
1509 rc
= gpg_error_from_errno (errno
);
1511 pthread_mutex_init (&new->status_mutex
, NULL
);
1517 new->remote
= addr
? 1 : 0;
1520 rc
= create_thread (client_thread
, new, &new->tid
, 1);
1523 close (new->status_msg_pipe
[0]);
1524 close (new->status_msg_pipe
[1]);
1525 pthread_mutex_destroy (&new->status_mutex
);
1531 struct slist_s
*list
= slist_append (cn_thread_list
, new);
1535 cn_thread_list
= list
;
1538 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1539 (pthread_t
*) new->tid
, fd
, addr
);
1541 new->peeraddr
= str_dup (addr
);
1545 log_write (_("new connection: tid=%p, fd=%i"),
1546 (pthread_t
*) new->tid
, fd
);
1549 rc
= GPG_ERR_ENOMEM
;
1552 pthread_cleanup_pop (1);
1558 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1559 pwmd_strerror (rc
));
1565 keepalive_thread (void *arg
)
1567 #ifndef HAVE_PTHREAD_CANCEL
1568 int *n
= xmalloc (sizeof (int));
1571 pthread_setspecific (signal_thread_key
, n
);
1575 #ifdef HAVE_PR_SET_NAME
1576 prctl (PR_SET_NAME
, "keepalive");
1578 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1582 int n
= config_get_integer ("global", "keepalive_interval");
1583 struct timeval tv
= { n
, 0 };
1584 #ifndef HAVE_PTHREAD_CANCEL
1587 sigusr2
= (int *) pthread_getspecific (signal_thread_key
);
1592 send_status_all (STATUS_KEEPALIVE
, NULL
);
1593 select (0, NULL
, NULL
, NULL
, &tv
);
1600 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1602 get_in_addr (struct sockaddr
*sa
)
1604 if (sa
->sa_family
== AF_INET
)
1605 return &(((struct sockaddr_in
*) sa
)->sin_addr
);
1607 return &(((struct sockaddr_in6
*) sa
)->sin6_addr
);
1611 tcp_accept_thread (void *arg
)
1613 int sockfd
= *(int *) arg
;
1614 #ifndef HAVE_PTHREAD_CANCEL
1615 int *n
= xmalloc (sizeof (int));
1618 pthread_setspecific (signal_thread_key
, n
);
1620 fcntl (sockfd
, F_SETFL
, O_NONBLOCK
);
1623 #ifdef HAVE_PR_SET_NAME
1624 prctl (PR_SET_NAME
, "tcp_accept");
1626 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1630 struct sockaddr_storage raddr
;
1631 socklen_t slen
= sizeof (raddr
);
1634 char s
[INET6_ADDRSTRLEN
];
1635 struct timeval tv
= { 0, ACCEPT_TIMEOUT
};
1636 #ifndef HAVE_PTHREAD_CANCEL
1639 sigusr2
= (int *) pthread_getspecific (signal_thread_key
);
1644 fd
= accept (sockfd
, (struct sockaddr
*) &raddr
, &slen
);
1647 if (errno
== EMFILE
|| errno
== ENFILE
)
1648 log_write ("accept(): %s",
1649 pwmd_strerror (gpg_error_from_errno (errno
)));
1650 else if (errno
!= EAGAIN
)
1652 if (!quit
) // probably EBADF
1653 log_write ("accept(): %s", strerror (errno
));
1658 #ifndef HAVE_PTHREAD_CANCEL
1659 select (0, NULL
, NULL
, NULL
, &tv
);
1670 inet_ntop (raddr
.ss_family
, get_in_addr ((struct sockaddr
*) &raddr
),
1672 (void) init_client (fd
, s
);
1673 n
= config_get_integer ("global", "tcp_wait");
1676 tv
.tv_sec
= (n
* 100000) / 100000;
1677 tv
.tv_usec
= (n
* 100000) % 100000;
1678 select (0, NULL
, NULL
, NULL
, &tv
);
1686 start_stop_tls_with_protocol (int ipv6
, int term
)
1688 struct addrinfo hints
, *servinfo
, *p
;
1689 int port
= config_get_integer ("global", "tcp_port");
1693 int *fd
= ipv6
? &tls6_fd
: &tls_fd
;
1695 if (term
|| config_get_boolean ("global", "enable_tcp") == 0)
1701 #ifdef HAVE_PTHREAD_CANCEL
1702 pthread_cancel (tls6_tid
);
1704 pthread_kill (tls6_tid
, SIGUSR2
);
1706 pthread_join (tls6_tid
, NULL
);
1709 shutdown (tls6_fd
, SHUT_RDWR
);
1719 #ifdef HAVE_PTHREAD_CANCEL
1720 pthread_cancel (tls_tid
);
1722 pthread_kill (tls_tid
, SIGUSR2
);
1724 pthread_join (tls_tid
, NULL
);
1727 shutdown (tls_fd
, SHUT_RDWR
);
1733 /* A client may still be connected. */
1734 if (!quit
&& x509_cred
!= NULL
)
1735 tls_deinit_params ();
1740 if ((ipv6
&& tls6_fd
!= -1) || (!ipv6
&& tls_fd
!= -1))
1743 memset (&hints
, 0, sizeof (hints
));
1744 hints
.ai_family
= ipv6
? AF_INET6
: AF_INET
;
1745 hints
.ai_socktype
= SOCK_STREAM
;
1746 hints
.ai_flags
= AI_PASSIVE
;
1747 snprintf (buf
, sizeof (buf
), "%i", port
);
1749 if ((n
= getaddrinfo (NULL
, buf
, &hints
, &servinfo
)) == -1)
1751 log_write ("getaddrinfo(): %s", gai_strerror (n
));
1755 for (n
= 0, p
= servinfo
; p
!= NULL
; p
= p
->ai_next
)
1759 if ((ipv6
&& p
->ai_family
!= AF_INET6
)
1760 || (!ipv6
&& p
->ai_family
!= AF_INET
))
1763 if ((*fd
= socket (p
->ai_family
, p
->ai_socktype
, p
->ai_protocol
)) == -1)
1765 log_write ("socket(): %s", strerror (errno
));
1769 if (setsockopt (*fd
, SOL_SOCKET
, SO_REUSEADDR
, &r
, sizeof (int)) == -1)
1771 log_write ("setsockopt(): %s",
1772 pwmd_strerror (gpg_error_from_errno (errno
)));
1773 freeaddrinfo (servinfo
);
1777 if (bind (*fd
, p
->ai_addr
, p
->ai_addrlen
) == -1)
1780 log_write ("bind(): %s",
1781 pwmd_strerror (gpg_error_from_errno (errno
)));
1789 freeaddrinfo (servinfo
);
1794 #if HAVE_DECL_SO_BINDTODEVICE != 0
1795 char *tmp
= config_get_string ("global", "tcp_interface");
1796 if (tmp
&& setsockopt (*fd
, SOL_SOCKET
, SO_BINDTODEVICE
, tmp
,
1797 strlen (tmp
)) == -1)
1799 log_write ("setsockopt(): %s",
1800 pwmd_strerror (gpg_error_from_errno (errno
)));
1808 if (x509_cred
== NULL
)
1810 rc
= tls_init_params ();
1815 if (listen (*fd
, 0) == -1)
1817 log_write ("listen(): %s", strerror (errno
));
1822 rc
= create_thread (tcp_accept_thread
, fd
, &tls6_tid
, 0);
1824 rc
= create_thread (tcp_accept_thread
, fd
, &tls_tid
, 0);
1828 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1829 pwmd_strerror (rc
));
1841 start_stop_tls_with_protocol (0, 1);
1854 start_stop_tls (int term
)
1856 char *s
= config_get_string ("global", "tcp_bind");
1862 if (!strcmp (s
, "any"))
1864 b
= start_stop_tls_with_protocol (0, term
);
1866 b
= start_stop_tls_with_protocol (1, term
);
1868 else if (!strcmp (s
, "ipv4"))
1869 b
= start_stop_tls_with_protocol (0, term
);
1870 else if (!strcmp (s
, "ipv6"))
1871 b
= start_stop_tls_with_protocol (1, term
);
1881 accept_thread (void *arg
)
1883 int sockfd
= *(int *) arg
;
1884 #ifndef HAVE_PTHREAD_CANCEL
1885 int *n
= xmalloc (sizeof (int));
1888 pthread_setspecific (signal_thread_key
, n
);
1890 fcntl (sockfd
, F_SETFL
, O_NONBLOCK
);
1893 #ifdef HAVE_PR_SET_NAME
1894 prctl (PR_SET_NAME
, "accept");
1896 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1900 socklen_t slen
= sizeof (struct sockaddr_un
);
1901 struct sockaddr_un raddr
;
1903 #ifndef HAVE_PTHREAD_CANCEL
1904 struct timeval tv
= { 0, ACCEPT_TIMEOUT
};
1905 int *sigusr2
= (int *) pthread_getspecific (signal_thread_key
);
1911 fd
= accept (sockfd
, (struct sockaddr
*) &raddr
, &slen
);
1914 if (errno
== EMFILE
|| errno
== ENFILE
)
1915 log_write ("accept(): %s",
1916 pwmd_strerror (gpg_error_from_errno (errno
)));
1917 else if (errno
!= EAGAIN
)
1919 if (!quit
) // probably EBADF
1920 log_write ("accept(): %s",
1921 pwmd_strerror (gpg_error_from_errno (errno
)));
1926 #ifndef HAVE_PTHREAD_CANCEL
1927 select (0, NULL
, NULL
, NULL
, &tv
);
1932 (void) init_client (fd
, NULL
);
1935 /* Just in case accept() failed for some reason other than EBADF */
1941 cache_timer_thread (void *arg
)
1943 #ifndef HAVE_PTHREAD_CANCEL
1944 int *n
= xmalloc (sizeof (int));
1947 pthread_setspecific (signal_thread_key
, n
);
1951 #ifdef HAVE_PR_SET_NAME
1952 prctl (PR_SET_NAME
, "cache timer");
1954 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1958 struct timeval tv
= { 1, 0 };
1959 #ifndef HAVE_PTHREAD_CANCEL
1962 n
= (int *) pthread_getspecific (signal_thread_key
);
1967 select (0, NULL
, NULL
, NULL
, &tv
);
1968 cache_adjust_timeout ();
1975 signal_loop (sigset_t sigset
)
1984 sigwait (&sigset
, &sig
);
1987 log_write (_("caught signal %i (%s)"), sig
, strsignal (sig
));
1992 pthread_cond_signal (&rcfile_cond
);
1995 log_write (_("clearing file cache"));
1997 send_status_all (STATUS_CACHE
, NULL
);
2016 log_write (_ ("Caught signal %i (%s). Exiting."), sig
, strsignal (sig
));
2017 #ifdef HAVE_BACKTRACE
2018 BACKTRACE (__FUNCTION__
);
2024 waiting_for_exit (void *arg
)
2027 #ifndef HAVE_PTHREAD_CANCEL
2028 int *n
= xmalloc (sizeof (int));
2031 pthread_setspecific (signal_thread_key
, n
);
2035 #ifdef HAVE_PR_SET_NAME
2036 prctl (PR_SET_NAME
, "exiting");
2038 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
2039 log_write (_("waiting for all clients to disconnect"));
2040 MUTEX_LOCK (&quit_mutex
);
2041 pthread_cleanup_push (cleanup_mutex_cb
, &quit_mutex
);
2048 MUTEX_LOCK (&cn_mutex
);
2049 n
= slist_length (cn_thread_list
);
2050 MUTEX_UNLOCK (&cn_mutex
);
2054 #ifndef HAVE_PTHREAD_CANCEL
2055 int *s
= (int *) pthread_getspecific (signal_thread_key
);
2062 log_write (_("%i clients remain"), n
);
2066 INIT_TIMESPEC (SIG_TIMEOUT
, ts
);
2067 pthread_cond_timedwait (&quit_cond
, &quit_mutex
, &ts
);
2070 kill (getpid (), SIGQUIT
);
2071 pthread_cleanup_pop (1);
2076 server_loop (int sockfd
, char **socketpath
)
2078 pthread_t accept_tid
;
2079 pthread_t cache_timeout_tid
;
2080 int cancel_timeout_thread
= 0, cancel_accept_thread
= 0;
2081 int cancel_keepalive_thread
= 0;
2088 sigemptyset (&sigset
);
2091 sigaddset (&sigset
, SIGTERM
);
2092 sigaddset (&sigset
, SIGINT
);
2094 /* Clears the file cache. */
2095 sigaddset (&sigset
, SIGUSR1
);
2097 /* Configuration file reloading. */
2098 sigaddset (&sigset
, SIGHUP
);
2100 /* For exiting cleanly. */
2101 sigaddset (&sigset
, SIGQUIT
);
2103 #ifndef HAVE_PTHREAD_CANCEL
2105 The socket, cache and rcfile threads use this signal when
2106 pthread_cancel() is unavailable. Prevent the main thread from
2107 catching this signal from another process.
2109 sigaddset (&sigset
, SIGUSR2
);
2112 /* When mem.c cannot find a pointer in the list (double free). */
2113 signal (SIGABRT
, catchsig
);
2114 sigaddset (&sigset
, SIGABRT
);
2115 sigprocmask (SIG_BLOCK
, &sigset
, NULL
);
2117 #ifndef HAVE_PTHREAD_CANCEL
2118 /* Remove this signal from the watched signals in signal_loop(). */
2119 sigdelset (&sigset
, SIGUSR2
);
2122 /* Ignored everywhere. When a client disconnects abnormally this signal
2123 * gets raised. It isn't needed though because client_thread() will check
2124 * for rcs even after the client disconnects. */
2125 signal (SIGPIPE
, SIG_IGN
);
2127 /* Can show a backtrace of the stack in the log. */
2128 signal (SIGSEGV
, catchsig
);
2131 /* Needs to be done after the fork(). */
2132 if (!start_stop_tls (0))
2139 pthread_mutex_init (&quit_mutex
, NULL
);
2140 pthread_cond_init (&quit_cond
, NULL
);
2141 char *p
= get_username (getuid());
2142 log_write (_("%s started for user %s"), PACKAGE_STRING
, p
);
2146 if (config_get_boolean ("global", "enable_tcp"))
2147 log_write (_("Listening on %s and TCP port %i as user %i"), *socketpath
,
2148 config_get_integer ("global", "tcp_port"), invoking_uid
);
2150 log_write (_("Listening on %s"), *socketpath
);
2152 log_write (_("Listening on %s"), *socketpath
);
2155 rc
= create_thread (keepalive_thread
, NULL
, &keepalive_tid
, 0);
2158 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2159 pwmd_strerror (rc
));
2163 cancel_keepalive_thread
= 1;
2164 rc
= create_thread (reload_rcfile_thread
, NULL
, &rcfile_tid
, 0);
2167 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2168 pwmd_strerror (rc
));
2172 rc
= create_thread (cache_timer_thread
, NULL
, &cache_timeout_tid
, 0);
2175 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2176 pwmd_strerror (rc
));
2180 cancel_timeout_thread
= 1;
2181 rc
= create_thread (accept_thread
, &sockfd
, &accept_tid
, 0);
2184 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2185 pwmd_strerror (rc
));
2189 cancel_accept_thread
= 1;
2191 signal_loop (sigset
);
2197 * We're out of the main server loop. This happens when a signal was sent
2198 * to terminate the daemon. We'll wait for all clients to disconnect
2199 * before exiting but exit immediately if another termination signal is
2202 if (cancel_accept_thread
)
2204 #ifdef HAVE_PTHREAD_CANCEL
2205 int n
= pthread_cancel (accept_tid
);
2207 int n
= pthread_kill (accept_tid
, SIGUSR2
);
2210 pthread_join (accept_tid
, NULL
);
2216 shutdown (sockfd
, SHUT_RDWR
);
2218 unlink (*socketpath
);
2219 xfree (*socketpath
);
2221 MUTEX_LOCK (&cn_mutex
);
2222 n
= slist_length (cn_thread_list
);
2223 MUTEX_UNLOCK (&cn_mutex
);
2229 rc
= create_thread (waiting_for_exit
, NULL
, &tid
, 0);
2232 if (signal_loop (sigset
))
2234 log_write (_("Received second termination request. Exiting."));
2235 #ifdef HAVE_PTHREAD_CANCEL
2236 pthread_cancel (tid
);
2238 pthread_kill (tid
, SIGUSR2
);
2240 pthread_join (tid
, NULL
);
2244 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2245 pwmd_strerror (rc
));
2248 if (cancel_timeout_thread
)
2250 #ifdef HAVE_PTHREAD_CANCEL
2251 pthread_cancel (cache_timeout_tid
);
2253 pthread_kill (cache_timeout_tid
, SIGUSR2
);
2255 pthread_join (cache_timeout_tid
, NULL
);
2258 if (cancel_keepalive_thread
)
2260 #ifdef HAVE_PTHREAD_CANCEL
2261 pthread_cancel (keepalive_tid
);
2263 pthread_kill (keepalive_tid
, SIGUSR2
);
2265 pthread_join (keepalive_tid
, NULL
);
2268 cleanup_all_clients (0);
2273 pthread_cond_destroy (&quit_cond
);
2274 pthread_mutex_destroy (&quit_mutex
);
2275 return segv
? EXIT_FAILURE
: EXIT_SUCCESS
;;
2282 ("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
2286 /* This is called from cache.c:clear_once(). See
2287 * command.c:clearcache_command() for details about lock checking.
2290 free_cache_data (file_cache_t
* cache
)
2292 gpg_error_t rc
= GPG_ERR_NO_DATA
;
2294 struct client_thread_s
*found
= NULL
;
2301 MUTEX_LOCK (&cn_mutex
);
2302 pthread_cleanup_push (cleanup_mutex_cb
, &cn_mutex
);
2303 t
= slist_length (cn_thread_list
);
2305 for (i
= 0; i
< t
; i
++)
2307 struct client_thread_s
*thd
= slist_nth_data (cn_thread_list
, i
);
2312 if (!memcmp (thd
->cl
->md5file
, cache
->filename
,
2313 sizeof (cache
->filename
)))
2315 if (pthread_equal (pthread_self (), thd
->tid
))
2322 /* Continue trying to find a client who has the same file open and
2323 * also has a lock. */
2324 rc
= cache_lock_mutex (thd
->cl
->ctx
, thd
->cl
->md5file
, -1, 0, -1);
2334 if (self
&& (!rc
|| rc
== GPG_ERR_NO_DATA
))
2335 rc
= cache_lock_mutex (found
->cl
->ctx
, found
->cl
->md5file
, -1, 0, -1);
2337 if (exiting
|| !rc
|| rc
== GPG_ERR_NO_DATA
)
2339 free_cache_data_once (cache
->data
);
2341 cache
->defer_clear
= 0;
2342 cache
->timeout
= -1;
2345 cache_unlock_mutex (found
->cl
->md5file
, 0);
2351 cache
->defer_clear
= 1;
2353 pthread_cleanup_pop (1);
2359 convert_v2_datafile (const char *filename
, const char *cipher
,
2360 const char *keyfile
, const char *keygrip
,
2361 const char *sign_keygrip
, int nopass
,
2362 const char *outfile
, const char *keyparam
,
2363 unsigned long s2k_count
, uint64_t iterations
)
2368 struct crypto_s
*crypto
= NULL
;
2374 if (outfile
[0] == '-' && outfile
[1] == 0)
2377 log_write (_("Converting version 2 data file \"%s\" ..."), filename
);
2378 if (access (filename
, R_OK
) == -1)
2380 log_write ("%s: %s", filename
,
2381 pwmd_strerror (gpg_error_from_errno (errno
)));
2387 log_write (_("Using passphrase file \"%s\" for decryption ..."),
2389 if (access (keyfile
, R_OK
) == -1)
2391 log_write ("%s: %s", keyfile
,
2392 pwmd_strerror (gpg_error_from_errno (errno
)));
2397 rc
= read_v2_datafile (filename
, keyfile
, &data
, &datalen
, &ver
, &algo
);
2400 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
2406 algo
= cipher_string_to_gcrypt (cipher
);
2409 rc
= GPG_ERR_CIPHER_ALGO
;
2418 rc
= parse_doc (data
, datalen
, &doc
);
2422 rc
= convert_pre_212_elements (doc
);
2427 xmlDocDumpFormatMemory (doc
, (xmlChar
**) & data
, (int *) &datalen
,
2430 rc
= GPG_ERR_ENOMEM
;
2438 rc
= init_client_crypto (&crypto
);
2441 memcpy (&crypto
->save
.hdr
, &crypto
->hdr
, sizeof (file_header_t
));
2442 crypto
->save
.hdr
.flags
= set_cipher_flag (crypto
->save
.hdr
.flags
, algo
);
2443 crypto
->save
.s2k_count
= s2k_count
;
2444 crypto
->save
.hdr
.iterations
= iterations
;
2448 rc
= export_common (NULL
, 0, crypto
, data
, datalen
, outfile
, keyfile
,
2449 &key
, &keylen
, 0, 0, nopass
);
2454 rc
= agent_set_pinentry_options (crypto
->agent
);
2456 rc
= agent_export_common (crypto
, keygrip
, sign_keygrip
, nopass
,
2457 data
, datalen
, outfile
, keyparam
,
2458 no_passphrase_file
? NULL
: keyfile
);
2462 log_write (_("Output written to \"%s\"."),
2463 outfile
? outfile
: "<stdout>");
2473 cleanup_crypto (&crypto
);
2476 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
2481 usage (const char *pn
, int status
)
2483 FILE *fp
= status
== EXIT_FAILURE
? stderr
: stdout
;
2485 fprintf (fp
, _("Usage: %s [OPTIONS] [file1] [...]\n"
2486 " -f, --rcfile=filename load the specfied configuration file\n"
2487 " (~/.pwmd/config)\n"
2488 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2489 " --kill terminate an existing instance of pwmd\n"
2491 " --use-agent[=integer] enable/disable use of gpg-agent\n"
2493 " -n, --no-fork run as a foreground process\n"
2494 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2495 " --ignore, --force ignore file errors during startup\n"
2496 " --debug-level=keywords log protocol output (see manual for details)\n"
2497 " -o, --outfile=filename output file when importing or converting\n"
2498 " -C, --convert=filename convert a version 2 data file to version 3\n"
2499 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2500 " -k, --passphrase-file=file for use when importing or converting\n"
2501 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2503 " --no-passphrase when importing or converting\n"
2504 " --keygrip=hex public key to use when encrypting\n"
2505 " --sign-keygrip=hex private key to use when signing\n"
2506 " --keyparam=s-exp custom key parameters to use (RSA-2048)\n"
2507 " --cipher=string encryption cipher (aes256)\n"
2508 " --cipher-iterations=N cipher iteration count (N+1)\n"
2509 " --s2k-count=N hash iteration count (>65536, calibrated)\n"
2510 " --help this help text\n"
2511 " --version show version and compile time features\n"),
2517 unlink_stale_socket (const char *sock
, const char *pidfile
)
2519 log_write (_ ("removing stale socket %s"), sock
);
2525 test_pidfile (const char *path
, const char *sock
, char *buf
, size_t buflen
,
2526 char **pidfile
, int create
, mode_t mode
, int terminate
)
2534 snprintf (buf
, buflen
, "%s/%s.pid", homedir
, sock
);
2535 *pidfile
= str_dup (buf
);
2536 fd
= open (buf
, O_RDONLY
);
2539 fd
= open (*pidfile
, O_CREAT
|O_WRONLY
|O_TRUNC
, mode
);
2543 if (!create
&& errno
!= ENOENT
)
2545 log_write ("%s: %s", buf
, pwmd_strerror (errno
));
2550 else if (!create
&& !terminate
)
2553 log_write ("%s: %s", *pidfile
, strerror (errno
));
2559 snprintf (buf
, buflen
, "%i", getpid ());
2560 write (fd
, buf
, strlen (buf
));
2565 len
= read (fd
, buf
, buflen
);
2569 unlink_stale_socket (path
, *pidfile
);
2573 if (sscanf (buf
, "%5i", &pid
) != 1 || pid
== 0)
2577 unlink_stale_socket (path
, *pidfile
);
2582 if (kill (pid
, 0) == -1)
2584 unlink_stale_socket (path
, *pidfile
);
2590 if (kill (pid
, SIGTERM
) == -1)
2591 log_write ("%s: %s", path
, pwmd_strerror (errno
));
2594 log_write (_ ("an instance for socket %s is already running"), path
);
2602 main (int argc
, char *argv
[])
2605 struct sockaddr_un addr
;
2607 char *socketpath
= NULL
, *socketdir
, *socketname
= NULL
;
2608 char *socketarg
= NULL
;
2609 char *datadir
= NULL
;
2610 char *pidfile
= NULL
;
2614 char **cache_push
= NULL
;
2615 char *import
= NULL
, *keygrip
= NULL
, *sign_keygrip
= NULL
;
2616 char *keyparam
= NULL
;
2617 int estatus
= EXIT_FAILURE
;
2619 char *outfile
= NULL
;
2622 int show_version
= 0;
2624 int no_passphrase
= 0;
2626 char *convertfile
= NULL
;
2627 char *cipher
= NULL
;
2628 char *keyfile
= NULL
;
2629 unsigned long s2k_count
= 0;
2630 uint64_t iterations
= 0;
2632 char *debug_level_opt
= NULL
;
2635 /* Must maintain the same order as longopts[] */
2638 OPT_VERSION
, OPT_HELP
,
2642 OPT_DEBUG_LEVEL
, OPT_HOMEDIR
, OPT_NO_FORK
, OPT_DISABLE_DUMP
,
2643 OPT_IGNORE
, OPT_FORCE
, OPT_RCFILE
, OPT_CONVERT
,
2644 OPT_PASSPHRASE_FILE
, OPT_IMPORT
, OPT_OUTFILE
,
2645 OPT_NO_PASSPHRASE_FILE
, OPT_KEYGRIP
, OPT_SIGN_KEYGRIP
,
2646 OPT_KEYPARAM
, OPT_CIPHER
, OPT_ITERATIONS
, OPT_S2K_COUNT
,
2647 OPT_NO_PASSPHRASE
, OPT_KILL
2649 const char *optstring
= "nf:C:k:I:o:";
2650 const struct option longopts
[] = {
2651 {"version", no_argument
, 0, 0},
2652 {"help", no_argument
, 0, 0},
2654 {"use-agent", optional_argument
, 0, 0},
2656 {"debug-level", required_argument
, 0, 0},
2657 {"homedir", required_argument
, 0, 0},
2658 {"no-fork", no_argument
, 0, 'n'},
2659 {"disable_dump", no_argument
, 0, 0},
2660 {"ignore", no_argument
, 0, 0},
2661 {"force", no_argument
, 0, 0},
2662 {"rcfile", required_argument
, 0, 'f'},
2663 {"convert", required_argument
, 0, 'C'},
2664 {"passphrase-file", required_argument
, 0, 'k'},
2665 {"import", required_argument
, 0, 'I'},
2666 {"outfile", required_argument
, 0, 'o'},
2667 {"no-passphrase-file", no_argument
, 0, 0},
2668 {"keygrip", required_argument
, 0, 0},
2669 {"sign-keygrip", required_argument
, 0, 0},
2670 {"keyparam", required_argument
, 0, 0},
2671 {"cipher", required_argument
, 0, 0},
2672 {"cipher-iterations", required_argument
, 0, 0},
2673 {"s2k-count", required_argument
, 0, 0},
2674 {"no-passphrase", no_argument
, 0, 0},
2675 {"kill", no_argument
, 0, 0},
2682 #ifdef HAVE_SETRLIMIT
2685 rl
.rlim_cur
= rl
.rlim_max
= 0;
2687 if (setrlimit (RLIMIT_CORE
, &rl
) != 0)
2688 err (EXIT_FAILURE
, "setrlimit()");
2691 #ifdef HAVE_PR_SET_DUMPABLE
2692 prctl (PR_SET_DUMPABLE
, 0);
2697 setlocale (LC_ALL
, "");
2698 bindtextdomain ("pwmd", LOCALEDIR
);
2699 textdomain ("pwmd");
2707 if (setup_crypto ())
2708 exit (EXIT_FAILURE
);
2711 gnutls_global_set_mem_functions (xmalloc
, xmalloc
, secure_mem_check
,
2713 gnutls_global_init ();
2714 gnutls_global_set_log_function (tls_log
);
2715 gnutls_global_set_log_level (1);
2719 xmlMemSetup (xfree
, xmalloc
, xrealloc
, str_dup
);
2727 while ((opt
= getopt_long (argc
, argv
, optstring
, longopts
, &optindex
))
2736 convertfile
= optarg
;
2751 rcfile
= str_dup (optarg
);
2754 usage (argv
[0], EXIT_FAILURE
);
2767 use_agent
= optarg
&& *optarg
? atoi (optarg
) : 1;
2768 if (use_agent
< 0 || use_agent
> 1)
2772 case OPT_DEBUG_LEVEL
:
2773 debug_level_opt
= optarg
;
2776 homedir
= str_dup (optarg
);
2781 case OPT_DISABLE_DUMP
:
2789 rcfile
= str_dup (optarg
);
2792 convertfile
= optarg
;
2794 case OPT_PASSPHRASE_FILE
:
2803 case OPT_NO_PASSPHRASE_FILE
:
2804 no_passphrase_file
= 1;
2809 case OPT_SIGN_KEYGRIP
:
2810 sign_keygrip
= optarg
;
2818 case OPT_ITERATIONS
:
2819 iterations
= strtoull (optarg
, NULL
, 10);
2822 s2k_count
= strtoul (optarg
, NULL
, 10);
2824 case OPT_NO_PASSPHRASE
:
2839 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015\n"
2841 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2842 "Compile time features:\n%s"), PACKAGE_STRING
,
2845 "+PWMD_HOMEDIR=" PWMD_HOMEDIR
"\n"
2878 exit (EXIT_SUCCESS
);
2883 homedir
= str_dup(PWMD_HOMEDIR
);
2885 homedir
= str_asprintf ("%s/.pwmd", get_home_dir());
2888 if (mkdir (homedir
, 0700) == -1 && errno
!= EEXIST
)
2889 err (EXIT_FAILURE
, "%s", homedir
);
2891 snprintf (buf
, sizeof (buf
), "%s/data", homedir
);
2892 if (mkdir (buf
, 0700) == -1 && errno
!= EEXIST
)
2893 err (EXIT_FAILURE
, "%s", buf
);
2895 datadir
= str_dup (buf
);
2896 pthread_mutexattr_t attr
;
2897 pthread_mutexattr_init (&attr
);
2898 pthread_mutexattr_settype (&attr
, PTHREAD_MUTEX_RECURSIVE
);
2899 pthread_mutex_init (&rcfile_mutex
, &attr
);
2900 pthread_cond_init (&rcfile_cond
, NULL
);
2901 pthread_mutex_init (&cn_mutex
, &attr
);
2902 pthread_mutexattr_destroy (&attr
);
2903 pthread_key_create (&last_error_key
, free_key
);
2904 #ifndef HAVE_PTHREAD_CANCEL
2905 pthread_key_create (&signal_thread_key
, free_key
);
2909 rcfile
= str_asprintf ("%s/config", homedir
);
2911 global_config
= config_parse (rcfile
);
2913 exit (EXIT_FAILURE
);
2916 if (use_agent
== -1)
2917 use_agent
= config_get_boolean ("global", "use_agent");
2922 if (debug_level_opt
)
2923 debug_level
= str_split (debug_level_opt
, ",", 0);
2925 x
= config_get_int_param (global_config
, "global", "priority", &exists
);
2926 if (exists
&& x
!= atoi(INVALID_PRIORITY
))
2929 if (setpriority (PRIO_PROCESS
, 0, x
) == -1)
2931 log_write ("setpriority(): %s",
2932 pwmd_strerror (gpg_error_from_errno (errno
)));
2936 #ifdef HAVE_MLOCKALL
2937 if (disable_mlock
== 0 && mlockall (MCL_CURRENT
| MCL_FUTURE
) == -1)
2939 log_write ("mlockall(): %s",
2940 pwmd_strerror (gpg_error_from_errno (errno
)));
2945 rc
= cache_init (free_cache_data
);
2948 log_write ("pwmd: ERR %i: %s", rc
,
2949 gpg_err_code (rc
) == GPG_ERR_UNKNOWN_VERSION
2950 ? _("incompatible gpg-agent version: 2.1.0 or later required")
2951 : pwmd_strerror (rc
));
2956 s2k_count
= config_get_ulong (NULL
, "s2k_count");
2960 if (!outfile
|| !*outfile
|| argc
!= optind
)
2961 usage (argv
[0], EXIT_FAILURE
);
2963 estatus
= convert_v2_datafile (convertfile
, cipher
, keyfile
, keygrip
,
2964 sign_keygrip
, no_passphrase
, outfile
,
2965 keyparam
, s2k_count
, iterations
);
2966 config_free (global_config
);
2973 if (!outfile
|| !*outfile
|| argc
!= optind
)
2974 usage (argv
[0], EXIT_FAILURE
);
2976 if (outfile
&& outfile
[0] == '-' && outfile
[1] == 0)
2979 estatus
= xml_import (import
, outfile
, keygrip
, sign_keygrip
, keyfile
,
2980 no_passphrase
, cipher
, keyparam
, s2k_count
,
2982 config_free (global_config
);
2987 p
= config_get_string ("global", "socket_path");
2989 p
= str_asprintf ("%s/socket", homedir
);
2991 socketarg
= expand_homedir (p
);
2995 disable_list_and_dump
= config_get_boolean ("global",
2996 "disable_list_and_dump");
2998 disable_list_and_dump
= secure
;
3000 cache_push
= config_get_list ("global", "cache_push");
3002 while (optind
< argc
)
3004 if (strv_printf (&cache_push
, "%s", argv
[optind
++]) == 0)
3005 errx (EXIT_FAILURE
, "%s", pwmd_strerror (GPG_ERR_ENOMEM
));
3008 if (strchr (socketarg
, '/') == NULL
)
3010 socketdir
= getcwd (buf
, sizeof (buf
));
3011 socketname
= str_dup (socketarg
);
3012 socketpath
= str_asprintf ("%s/%s", socketdir
, socketname
);
3016 socketname
= str_dup (strrchr (socketarg
, '/'));
3018 socketarg
[strlen (socketarg
) - strlen (socketname
) - 1] = 0;
3019 socketdir
= str_dup (socketarg
);
3020 socketpath
= str_asprintf ("%s/%s", socketdir
, socketname
);
3023 if (chdir (datadir
))
3025 log_write ("%s: %s", datadir
,
3026 pwmd_strerror (gpg_error_from_errno (errno
)));
3027 unlink (socketpath
);
3031 x
= test_pidfile (socketpath
, socketname
, buf
, sizeof(buf
), &pidfile
, 0,
3033 if (!terminate
&& x
)
3037 estatus
= x
!= 1 ? EXIT_FAILURE
: EXIT_SUCCESS
;
3042 * bind() doesn't like the full pathname of the socket or any non alphanum
3043 * characters so change to the directory where the socket is wanted then
3044 * create it then change to datadir.
3046 if (chdir (socketdir
))
3048 log_write ("%s: %s", socketdir
,
3049 pwmd_strerror (gpg_error_from_errno (errno
)));
3055 if ((sockfd
= socket (PF_UNIX
, SOCK_STREAM
, 0)) == -1)
3057 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
3061 addr
.sun_family
= AF_UNIX
;
3062 snprintf (addr
.sun_path
, sizeof (addr
.sun_path
), "%s", socketname
);
3064 if (bind (sockfd
, (struct sockaddr
*) &addr
, sizeof (struct sockaddr
)) ==
3067 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
3069 if (errno
== EADDRINUSE
)
3072 log_write (_("Either there is another pwmd running or '%s' is a \n"
3073 "stale socket. Please remove it manually."), socketpath
);
3080 char *t
= config_get_string ("global", "socket_perms");
3085 mode
= strtol (t
, NULL
, 8);
3089 if (chmod (socketname
, mode
) == -1)
3091 log_write ("%s: %s", socketname
,
3092 pwmd_strerror (gpg_error_from_errno (errno
)));
3102 xfree (--socketname
);
3104 if (chdir (datadir
))
3106 log_write ("%s: %s", datadir
,
3107 pwmd_strerror (gpg_error_from_errno (errno
)));
3115 * Set the cache entry for a file. Prompts for the password.
3119 struct crypto_s
*crypto
= NULL
;
3120 gpg_error_t rc
= init_client_crypto (&crypto
);
3124 estatus
= EXIT_FAILURE
;
3131 rc
= agent_set_pinentry_options (crypto
->agent
);
3134 estatus
= EXIT_FAILURE
;
3140 for (opt
= 0; cache_push
[opt
]; opt
++)
3142 if (!do_cache_push (cache_push
[opt
], crypto
) && !force
)
3144 strv_free (cache_push
);
3146 estatus
= EXIT_FAILURE
;
3147 cleanup_crypto (&crypto
);
3151 cleanup_crypto_stage1 (crypto
);
3156 (void) kill_scd (crypto
->agent
);
3159 cleanup_crypto (&crypto
);
3160 strv_free (cache_push
);
3161 log_write (!nofork
? _("Done. Daemonizing...") :
3162 _("Done. Waiting for connections..."));
3165 config_clear_keys ();
3167 if (listen (sockfd
, 0) == -1)
3169 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
3178 log_write ("fork(): %s",
3179 pwmd_strerror (gpg_error_from_errno (errno
)));
3188 _exit (EXIT_SUCCESS
);
3192 (void)test_pidfile (socketpath
, socketname
, buf
, sizeof(buf
), &pidfile
, 1,
3195 pthread_key_create (&thread_name_key
, free_key
);
3196 pthread_setspecific (thread_name_key
, str_dup ("main"));
3197 estatus
= server_loop (sockfd
, &socketpath
);
3200 if (socketpath
&& do_unlink
)
3202 unlink (socketpath
);
3208 gnutls_global_deinit ();
3209 xfree (invoking_tls
);
3213 #ifdef HAVE_PTHREAD_CANCEL
3214 pthread_cancel (rcfile_tid
);
3216 pthread_kill (rcfile_tid
, SIGUSR2
);
3217 pthread_cond_signal (&rcfile_cond
);
3219 pthread_join (rcfile_tid
, NULL
);
3222 pthread_cond_destroy (&rcfile_cond
);
3223 pthread_mutex_destroy (&rcfile_mutex
);
3224 pthread_key_delete (last_error_key
);
3225 #ifndef HAVE_PTHREAD_CANCEL
3226 pthread_key_delete (signal_thread_key
);
3230 config_free (global_config
);
3233 xfree (home_directory
);
3235 xmlCleanupParser ();
3236 xmlCleanupGlobals ();
3242 if (estatus
== EXIT_SUCCESS
&& !terminate
)
3243 log_write (_("pwmd exiting normally"));
3245 pthread_key_delete (thread_name_key
);
3247 #if defined(DEBUG) && !defined(MEM_DEBUG)