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\"."), outfile
);
2472 cleanup_crypto (&crypto
);
2475 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
2480 usage (const char *pn
, int status
)
2482 FILE *fp
= status
== EXIT_FAILURE
? stderr
: stdout
;
2484 fprintf (fp
, _("Usage: %s [OPTIONS] [file1] [...]\n"
2485 " -f, --rcfile=filename load the specfied configuration file\n"
2486 " (~/.pwmd/config)\n"
2487 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2488 " --kill terminate an existing instance of pwmd\n"
2490 " --use-agent enable use of gpg-agent\n"
2492 " -n, --no-fork run as a foreground process\n"
2493 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2494 " --ignore, --force ignore file errors during startup\n"
2495 " --debug-level=keywords log protocol output (see manual for details)\n"
2496 " -o, --outfile=filename output file when importing or converting\n"
2497 " -C, --convert=filename convert a version 2 data file to version 3\n"
2498 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2499 " -k, --passphrase-file=file for use when importing or converting\n"
2500 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2502 " --no-passphrase when importing or converting\n"
2503 " --keygrip=hex public key to use when encrypting\n"
2504 " --sign-keygrip=hex private key to use when signing\n"
2505 " --keyparam=s-exp custom key parameters to use (RSA-2048)\n"
2506 " --cipher=string encryption cipher (aes256)\n"
2507 " --cipher-iterations=N cipher iteration count (N+1)\n"
2508 " --s2k-count=N hash iteration count (>65536, calibrated)\n"
2509 " --help this help text\n"
2510 " --version show version and compile time features\n"),
2516 unlink_stale_socket (const char *sock
, const char *pidfile
)
2518 log_write (_ ("removing stale socket %s"), sock
);
2524 test_pidfile (const char *path
, const char *sock
, char *buf
, size_t buflen
,
2525 char **pidfile
, int create
, mode_t mode
, int terminate
)
2533 snprintf (buf
, buflen
, "%s/%s.pid", homedir
, sock
);
2534 *pidfile
= str_dup (buf
);
2535 fd
= open (buf
, O_RDONLY
);
2538 fd
= open (*pidfile
, O_CREAT
|O_WRONLY
|O_TRUNC
, mode
);
2542 if (!create
&& errno
!= ENOENT
)
2544 log_write ("%s: %s", buf
, pwmd_strerror (errno
));
2549 else if (!create
&& !terminate
)
2552 log_write ("%s: %s", *pidfile
, strerror (errno
));
2558 snprintf (buf
, buflen
, "%i", getpid ());
2559 write (fd
, buf
, strlen (buf
));
2564 len
= read (fd
, buf
, buflen
);
2568 unlink_stale_socket (path
, *pidfile
);
2572 if (sscanf (buf
, "%5i", &pid
) != 1 || pid
== 0)
2576 unlink_stale_socket (path
, *pidfile
);
2581 if (kill (pid
, 0) == -1)
2583 unlink_stale_socket (path
, *pidfile
);
2589 if (kill (pid
, SIGTERM
) == -1)
2590 log_write ("%s: %s", path
, pwmd_strerror (errno
));
2593 log_write (_ ("an instance for socket %s is already running"), path
);
2601 main (int argc
, char *argv
[])
2604 struct sockaddr_un addr
;
2606 char *socketpath
= NULL
, *socketdir
, *socketname
= NULL
;
2607 char *socketarg
= NULL
;
2608 char *datadir
= NULL
;
2609 char *pidfile
= NULL
;
2613 char **cache_push
= NULL
;
2614 char *import
= NULL
, *keygrip
= NULL
, *sign_keygrip
= NULL
;
2615 char *keyparam
= NULL
;
2616 int estatus
= EXIT_FAILURE
;
2618 char *outfile
= NULL
;
2621 int show_version
= 0;
2623 int no_passphrase
= 0;
2625 char *convertfile
= NULL
;
2626 char *cipher
= NULL
;
2627 char *keyfile
= NULL
;
2628 unsigned long s2k_count
= 0;
2629 uint64_t iterations
= 0;
2631 char *debug_level_opt
= NULL
;
2634 /* Must maintain the same order as longopts[] */
2637 OPT_VERSION
, OPT_HELP
,
2641 OPT_DEBUG_LEVEL
, OPT_HOMEDIR
, OPT_NO_FORK
, OPT_DISABLE_DUMP
,
2642 OPT_IGNORE
, OPT_FORCE
, OPT_RCFILE
, OPT_CONVERT
,
2643 OPT_PASSPHRASE_FILE
, OPT_IMPORT
, OPT_OUTFILE
,
2644 OPT_NO_PASSPHRASE_FILE
, OPT_KEYGRIP
, OPT_SIGN_KEYGRIP
,
2645 OPT_KEYPARAM
, OPT_CIPHER
, OPT_ITERATIONS
, OPT_S2K_COUNT
,
2646 OPT_NO_PASSPHRASE
, OPT_KILL
2648 const char *optstring
= "nf:C:k:I:o:";
2649 const struct option longopts
[] = {
2650 {"version", no_argument
, 0, 0},
2651 {"help", no_argument
, 0, 0},
2653 {"use-agent", no_argument
, 0, 0},
2655 {"debug-level", required_argument
, 0, 0},
2656 {"homedir", required_argument
, 0, 0},
2657 {"no-fork", no_argument
, 0, 'n'},
2658 {"disable_dump", no_argument
, 0, 0},
2659 {"ignore", no_argument
, 0, 0},
2660 {"force", no_argument
, 0, 0},
2661 {"rcfile", required_argument
, 0, 'f'},
2662 {"convert", required_argument
, 0, 'C'},
2663 {"passphrase-file", required_argument
, 0, 'k'},
2664 {"import", required_argument
, 0, 'I'},
2665 {"outfile", required_argument
, 0, 'o'},
2666 {"no-passphrase-file", no_argument
, 0, 0},
2667 {"keygrip", required_argument
, 0, 0},
2668 {"sign-keygrip", required_argument
, 0, 0},
2669 {"keyparam", required_argument
, 0, 0},
2670 {"cipher", required_argument
, 0, 0},
2671 {"cipher-iterations", required_argument
, 0, 0},
2672 {"s2k-count", required_argument
, 0, 0},
2673 {"no-passphrase", no_argument
, 0, 0},
2674 {"kill", no_argument
, 0, 0},
2681 #ifdef HAVE_SETRLIMIT
2684 rl
.rlim_cur
= rl
.rlim_max
= 0;
2686 if (setrlimit (RLIMIT_CORE
, &rl
) != 0)
2687 err (EXIT_FAILURE
, "setrlimit()");
2690 #ifdef HAVE_PR_SET_DUMPABLE
2691 prctl (PR_SET_DUMPABLE
, 0);
2696 setlocale (LC_ALL
, "");
2697 bindtextdomain ("pwmd", LOCALEDIR
);
2698 textdomain ("pwmd");
2706 if (setup_crypto ())
2707 exit (EXIT_FAILURE
);
2710 gnutls_global_set_mem_functions (xmalloc
, xmalloc
, secure_mem_check
,
2712 gnutls_global_init ();
2713 gnutls_global_set_log_function (tls_log
);
2714 gnutls_global_set_log_level (1);
2718 xmlMemSetup (xfree
, xmalloc
, xrealloc
, str_dup
);
2726 while ((opt
= getopt_long (argc
, argv
, optstring
, longopts
, &optindex
))
2735 convertfile
= optarg
;
2750 rcfile
= str_dup (optarg
);
2753 usage (argv
[0], EXIT_FAILURE
);
2769 case OPT_DEBUG_LEVEL
:
2770 debug_level_opt
= optarg
;
2773 homedir
= str_dup (optarg
);
2778 case OPT_DISABLE_DUMP
:
2786 rcfile
= str_dup (optarg
);
2789 convertfile
= optarg
;
2791 case OPT_PASSPHRASE_FILE
:
2800 case OPT_NO_PASSPHRASE_FILE
:
2801 no_passphrase_file
= 1;
2806 case OPT_SIGN_KEYGRIP
:
2807 sign_keygrip
= optarg
;
2815 case OPT_ITERATIONS
:
2816 iterations
= strtoull (optarg
, NULL
, 10);
2819 s2k_count
= strtoul (optarg
, NULL
, 10);
2821 case OPT_NO_PASSPHRASE
:
2836 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015\n"
2838 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2839 "Compile time features:\n%s"), PACKAGE_STRING
,
2842 "+PWMD_HOMEDIR=" PWMD_HOMEDIR
"\n"
2875 exit (EXIT_SUCCESS
);
2880 homedir
= str_dup(PWMD_HOMEDIR
);
2882 homedir
= str_asprintf ("%s/.pwmd", get_home_dir());
2885 if (mkdir (homedir
, 0700) == -1 && errno
!= EEXIST
)
2886 err (EXIT_FAILURE
, "%s", homedir
);
2888 snprintf (buf
, sizeof (buf
), "%s/data", homedir
);
2889 if (mkdir (buf
, 0700) == -1 && errno
!= EEXIST
)
2890 err (EXIT_FAILURE
, "%s", buf
);
2892 datadir
= str_dup (buf
);
2893 pthread_mutexattr_t attr
;
2894 pthread_mutexattr_init (&attr
);
2895 pthread_mutexattr_settype (&attr
, PTHREAD_MUTEX_RECURSIVE
);
2896 pthread_mutex_init (&rcfile_mutex
, &attr
);
2897 pthread_cond_init (&rcfile_cond
, NULL
);
2898 pthread_mutex_init (&cn_mutex
, &attr
);
2899 pthread_mutexattr_destroy (&attr
);
2900 pthread_key_create (&last_error_key
, free_key
);
2901 #ifndef HAVE_PTHREAD_CANCEL
2902 pthread_key_create (&signal_thread_key
, free_key
);
2906 rcfile
= str_asprintf ("%s/config", homedir
);
2908 global_config
= config_parse (rcfile
);
2910 exit (EXIT_FAILURE
);
2914 use_agent
= config_get_boolean ("global", "use_agent");
2919 if (debug_level_opt
)
2920 debug_level
= str_split (debug_level_opt
, ",", 0);
2922 x
= config_get_int_param (global_config
, "global", "priority", &exists
);
2923 if (exists
&& x
!= atoi(INVALID_PRIORITY
))
2926 if (setpriority (PRIO_PROCESS
, 0, x
) == -1)
2928 log_write ("setpriority(): %s",
2929 pwmd_strerror (gpg_error_from_errno (errno
)));
2933 #ifdef HAVE_MLOCKALL
2934 if (disable_mlock
== 0 && mlockall (MCL_CURRENT
| MCL_FUTURE
) == -1)
2936 log_write ("mlockall(): %s",
2937 pwmd_strerror (gpg_error_from_errno (errno
)));
2942 rc
= cache_init (free_cache_data
);
2945 log_write ("pwmd: ERR %i: %s", rc
,
2946 gpg_err_code (rc
) == GPG_ERR_UNKNOWN_VERSION
2947 ? _("incompatible gpg-agent version: 2.1.0 or later required")
2948 : pwmd_strerror (rc
));
2953 s2k_count
= config_get_ulong (NULL
, "s2k_count");
2957 if (!outfile
|| !*outfile
|| argc
!= optind
)
2958 usage (argv
[0], EXIT_FAILURE
);
2960 estatus
= convert_v2_datafile (convertfile
, cipher
, keyfile
, keygrip
,
2961 sign_keygrip
, no_passphrase
, outfile
,
2962 keyparam
, s2k_count
, iterations
);
2963 config_free (global_config
);
2970 if (!outfile
|| !*outfile
|| argc
!= optind
)
2971 usage (argv
[0], EXIT_FAILURE
);
2973 if (outfile
&& outfile
[0] == '-' && outfile
[1] == 0)
2976 estatus
= xml_import (import
, outfile
, keygrip
, sign_keygrip
, keyfile
,
2977 no_passphrase
, cipher
, keyparam
, s2k_count
,
2979 config_free (global_config
);
2984 p
= config_get_string ("global", "socket_path");
2986 p
= str_asprintf ("%s/socket", homedir
);
2988 socketarg
= expand_homedir (p
);
2992 disable_list_and_dump
= config_get_boolean ("global",
2993 "disable_list_and_dump");
2995 disable_list_and_dump
= secure
;
2997 cache_push
= config_get_list ("global", "cache_push");
2999 while (optind
< argc
)
3001 if (strv_printf (&cache_push
, "%s", argv
[optind
++]) == 0)
3002 errx (EXIT_FAILURE
, "%s", pwmd_strerror (GPG_ERR_ENOMEM
));
3005 if (strchr (socketarg
, '/') == NULL
)
3007 socketdir
= getcwd (buf
, sizeof (buf
));
3008 socketname
= str_dup (socketarg
);
3009 socketpath
= str_asprintf ("%s/%s", socketdir
, socketname
);
3013 socketname
= str_dup (strrchr (socketarg
, '/'));
3015 socketarg
[strlen (socketarg
) - strlen (socketname
) - 1] = 0;
3016 socketdir
= str_dup (socketarg
);
3017 socketpath
= str_asprintf ("%s/%s", socketdir
, socketname
);
3020 if (chdir (datadir
))
3022 log_write ("%s: %s", datadir
,
3023 pwmd_strerror (gpg_error_from_errno (errno
)));
3024 unlink (socketpath
);
3028 x
= test_pidfile (socketpath
, socketname
, buf
, sizeof(buf
), &pidfile
, 0,
3030 if (!terminate
&& x
)
3034 estatus
= x
!= 1 ? EXIT_FAILURE
: EXIT_SUCCESS
;
3039 * bind() doesn't like the full pathname of the socket or any non alphanum
3040 * characters so change to the directory where the socket is wanted then
3041 * create it then change to datadir.
3043 if (chdir (socketdir
))
3045 log_write ("%s: %s", socketdir
,
3046 pwmd_strerror (gpg_error_from_errno (errno
)));
3052 if ((sockfd
= socket (PF_UNIX
, SOCK_STREAM
, 0)) == -1)
3054 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
3058 addr
.sun_family
= AF_UNIX
;
3059 snprintf (addr
.sun_path
, sizeof (addr
.sun_path
), "%s", socketname
);
3061 if (bind (sockfd
, (struct sockaddr
*) &addr
, sizeof (struct sockaddr
)) ==
3064 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
3066 if (errno
== EADDRINUSE
)
3069 log_write (_("Either there is another pwmd running or '%s' is a \n"
3070 "stale socket. Please remove it manually."), socketpath
);
3077 char *t
= config_get_string ("global", "socket_perms");
3082 mode
= strtol (t
, NULL
, 8);
3086 if (chmod (socketname
, mode
) == -1)
3088 log_write ("%s: %s", socketname
,
3089 pwmd_strerror (gpg_error_from_errno (errno
)));
3099 xfree (--socketname
);
3101 if (chdir (datadir
))
3103 log_write ("%s: %s", datadir
,
3104 pwmd_strerror (gpg_error_from_errno (errno
)));
3112 * Set the cache entry for a file. Prompts for the password.
3116 struct crypto_s
*crypto
= NULL
;
3117 gpg_error_t rc
= init_client_crypto (&crypto
);
3121 estatus
= EXIT_FAILURE
;
3128 rc
= agent_set_pinentry_options (crypto
->agent
);
3131 estatus
= EXIT_FAILURE
;
3137 for (opt
= 0; cache_push
[opt
]; opt
++)
3139 if (!do_cache_push (cache_push
[opt
], crypto
) && !force
)
3141 strv_free (cache_push
);
3143 estatus
= EXIT_FAILURE
;
3144 cleanup_crypto (&crypto
);
3148 cleanup_crypto_stage1 (crypto
);
3153 (void) kill_scd (crypto
->agent
);
3156 cleanup_crypto (&crypto
);
3157 strv_free (cache_push
);
3158 log_write (!nofork
? _("Done. Daemonizing...") :
3159 _("Done. Waiting for connections..."));
3162 config_clear_keys ();
3164 if (listen (sockfd
, 0) == -1)
3166 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
3175 log_write ("fork(): %s",
3176 pwmd_strerror (gpg_error_from_errno (errno
)));
3185 _exit (EXIT_SUCCESS
);
3189 (void)test_pidfile (socketpath
, socketname
, buf
, sizeof(buf
), &pidfile
, 1,
3192 pthread_key_create (&thread_name_key
, free_key
);
3193 pthread_setspecific (thread_name_key
, str_dup ("main"));
3194 estatus
= server_loop (sockfd
, &socketpath
);
3197 if (socketpath
&& do_unlink
)
3199 unlink (socketpath
);
3205 gnutls_global_deinit ();
3206 xfree (invoking_tls
);
3210 #ifdef HAVE_PTHREAD_CANCEL
3211 pthread_cancel (rcfile_tid
);
3213 pthread_kill (rcfile_tid
, SIGUSR2
);
3214 pthread_cond_signal (&rcfile_cond
);
3216 pthread_join (rcfile_tid
, NULL
);
3219 pthread_cond_destroy (&rcfile_cond
);
3220 pthread_mutex_destroy (&rcfile_mutex
);
3221 pthread_key_delete (last_error_key
);
3222 #ifndef HAVE_PTHREAD_CANCEL
3223 pthread_key_delete (signal_thread_key
);
3227 config_free (global_config
);
3230 xfree (home_directory
);
3232 xmlCleanupParser ();
3233 xmlCleanupGlobals ();
3239 if (estatus
== EXIT_SUCCESS
&& !terminate
)
3240 log_write (_("pwmd exiting normally"));
3242 pthread_key_delete (thread_name_key
);
3244 #if defined(DEBUG) && !defined(MEM_DEBUG)