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 char *tmp
= config_get_string ("global", "tls_dh_level");
1812 rc
= tls_init_params (tmp
);
1818 if (listen (*fd
, 0) == -1)
1820 log_write ("listen(): %s", strerror (errno
));
1825 rc
= create_thread (tcp_accept_thread
, fd
, &tls6_tid
, 0);
1827 rc
= create_thread (tcp_accept_thread
, fd
, &tls_tid
, 0);
1831 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1832 pwmd_strerror (rc
));
1844 start_stop_tls_with_protocol (0, 1);
1857 start_stop_tls (int term
)
1859 char *s
= config_get_string ("global", "tcp_bind");
1865 if (!strcmp (s
, "any"))
1867 b
= start_stop_tls_with_protocol (0, term
);
1869 b
= start_stop_tls_with_protocol (1, term
);
1871 else if (!strcmp (s
, "ipv4"))
1872 b
= start_stop_tls_with_protocol (0, term
);
1873 else if (!strcmp (s
, "ipv6"))
1874 b
= start_stop_tls_with_protocol (1, term
);
1884 accept_thread (void *arg
)
1886 int sockfd
= *(int *) arg
;
1887 #ifndef HAVE_PTHREAD_CANCEL
1888 int *n
= xmalloc (sizeof (int));
1891 pthread_setspecific (signal_thread_key
, n
);
1893 fcntl (sockfd
, F_SETFL
, O_NONBLOCK
);
1896 #ifdef HAVE_PR_SET_NAME
1897 prctl (PR_SET_NAME
, "accept");
1899 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1903 socklen_t slen
= sizeof (struct sockaddr_un
);
1904 struct sockaddr_un raddr
;
1906 #ifndef HAVE_PTHREAD_CANCEL
1907 struct timeval tv
= { 0, ACCEPT_TIMEOUT
};
1908 int *sigusr2
= (int *) pthread_getspecific (signal_thread_key
);
1914 fd
= accept (sockfd
, (struct sockaddr
*) &raddr
, &slen
);
1917 if (errno
== EMFILE
|| errno
== ENFILE
)
1918 log_write ("accept(): %s",
1919 pwmd_strerror (gpg_error_from_errno (errno
)));
1920 else if (errno
!= EAGAIN
)
1922 if (!quit
) // probably EBADF
1923 log_write ("accept(): %s",
1924 pwmd_strerror (gpg_error_from_errno (errno
)));
1929 #ifndef HAVE_PTHREAD_CANCEL
1930 select (0, NULL
, NULL
, NULL
, &tv
);
1935 (void) init_client (fd
, NULL
);
1938 /* Just in case accept() failed for some reason other than EBADF */
1944 cache_timer_thread (void *arg
)
1946 #ifndef HAVE_PTHREAD_CANCEL
1947 int *n
= xmalloc (sizeof (int));
1950 pthread_setspecific (signal_thread_key
, n
);
1954 #ifdef HAVE_PR_SET_NAME
1955 prctl (PR_SET_NAME
, "cache timer");
1957 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1961 struct timeval tv
= { 1, 0 };
1962 #ifndef HAVE_PTHREAD_CANCEL
1965 n
= (int *) pthread_getspecific (signal_thread_key
);
1970 select (0, NULL
, NULL
, NULL
, &tv
);
1971 cache_adjust_timeout ();
1978 signal_loop (sigset_t sigset
)
1987 sigwait (&sigset
, &sig
);
1990 log_write (_("caught signal %i (%s)"), sig
, strsignal (sig
));
1995 pthread_cond_signal (&rcfile_cond
);
1998 log_write (_("clearing file cache"));
2000 send_status_all (STATUS_CACHE
, NULL
);
2019 log_write (_ ("Caught signal %i (%s). Exiting."), sig
, strsignal (sig
));
2020 #ifdef HAVE_BACKTRACE
2021 BACKTRACE (__FUNCTION__
);
2027 waiting_for_exit (void *arg
)
2030 #ifndef HAVE_PTHREAD_CANCEL
2031 int *n
= xmalloc (sizeof (int));
2034 pthread_setspecific (signal_thread_key
, n
);
2038 #ifdef HAVE_PR_SET_NAME
2039 prctl (PR_SET_NAME
, "exiting");
2041 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
2042 log_write (_("waiting for all clients to disconnect"));
2043 MUTEX_LOCK (&quit_mutex
);
2044 pthread_cleanup_push (cleanup_mutex_cb
, &quit_mutex
);
2051 MUTEX_LOCK (&cn_mutex
);
2052 n
= slist_length (cn_thread_list
);
2053 MUTEX_UNLOCK (&cn_mutex
);
2057 #ifndef HAVE_PTHREAD_CANCEL
2058 int *s
= (int *) pthread_getspecific (signal_thread_key
);
2065 log_write (_("%i clients remain"), n
);
2069 INIT_TIMESPEC (SIG_TIMEOUT
, ts
);
2070 pthread_cond_timedwait (&quit_cond
, &quit_mutex
, &ts
);
2073 kill (getpid (), SIGQUIT
);
2074 pthread_cleanup_pop (1);
2079 server_loop (int sockfd
, char **socketpath
)
2081 pthread_t accept_tid
;
2082 pthread_t cache_timeout_tid
;
2083 int cancel_timeout_thread
= 0, cancel_accept_thread
= 0;
2084 int cancel_keepalive_thread
= 0;
2091 sigemptyset (&sigset
);
2094 sigaddset (&sigset
, SIGTERM
);
2095 sigaddset (&sigset
, SIGINT
);
2097 /* Clears the file cache. */
2098 sigaddset (&sigset
, SIGUSR1
);
2100 /* Configuration file reloading. */
2101 sigaddset (&sigset
, SIGHUP
);
2103 /* For exiting cleanly. */
2104 sigaddset (&sigset
, SIGQUIT
);
2106 #ifndef HAVE_PTHREAD_CANCEL
2108 The socket, cache and rcfile threads use this signal when
2109 pthread_cancel() is unavailable. Prevent the main thread from
2110 catching this signal from another process.
2112 sigaddset (&sigset
, SIGUSR2
);
2115 /* When mem.c cannot find a pointer in the list (double free). */
2116 signal (SIGABRT
, catchsig
);
2117 sigaddset (&sigset
, SIGABRT
);
2118 sigprocmask (SIG_BLOCK
, &sigset
, NULL
);
2120 #ifndef HAVE_PTHREAD_CANCEL
2121 /* Remove this signal from the watched signals in signal_loop(). */
2122 sigdelset (&sigset
, SIGUSR2
);
2125 /* Ignored everywhere. When a client disconnects abnormally this signal
2126 * gets raised. It isn't needed though because client_thread() will check
2127 * for rcs even after the client disconnects. */
2128 signal (SIGPIPE
, SIG_IGN
);
2130 /* Can show a backtrace of the stack in the log. */
2131 signal (SIGSEGV
, catchsig
);
2134 /* Needs to be done after the fork(). */
2135 if (!start_stop_tls (0))
2142 pthread_mutex_init (&quit_mutex
, NULL
);
2143 pthread_cond_init (&quit_cond
, NULL
);
2144 char *p
= get_username (getuid());
2145 log_write (_("%s started for user %s"), PACKAGE_STRING
, p
);
2149 if (config_get_boolean ("global", "enable_tcp"))
2150 log_write (_("Listening on %s and TCP port %i as user %i"), *socketpath
,
2151 config_get_integer ("global", "tcp_port"), invoking_uid
);
2153 log_write (_("Listening on %s"), *socketpath
);
2155 log_write (_("Listening on %s"), *socketpath
);
2158 rc
= create_thread (keepalive_thread
, NULL
, &keepalive_tid
, 0);
2161 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2162 pwmd_strerror (rc
));
2166 cancel_keepalive_thread
= 1;
2167 rc
= create_thread (reload_rcfile_thread
, NULL
, &rcfile_tid
, 0);
2170 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2171 pwmd_strerror (rc
));
2175 rc
= create_thread (cache_timer_thread
, NULL
, &cache_timeout_tid
, 0);
2178 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2179 pwmd_strerror (rc
));
2183 cancel_timeout_thread
= 1;
2184 rc
= create_thread (accept_thread
, &sockfd
, &accept_tid
, 0);
2187 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2188 pwmd_strerror (rc
));
2192 cancel_accept_thread
= 1;
2194 signal_loop (sigset
);
2200 * We're out of the main server loop. This happens when a signal was sent
2201 * to terminate the daemon. We'll wait for all clients to disconnect
2202 * before exiting but exit immediately if another termination signal is
2205 if (cancel_accept_thread
)
2207 #ifdef HAVE_PTHREAD_CANCEL
2208 int n
= pthread_cancel (accept_tid
);
2210 int n
= pthread_kill (accept_tid
, SIGUSR2
);
2213 pthread_join (accept_tid
, NULL
);
2219 shutdown (sockfd
, SHUT_RDWR
);
2221 unlink (*socketpath
);
2222 xfree (*socketpath
);
2224 MUTEX_LOCK (&cn_mutex
);
2225 n
= slist_length (cn_thread_list
);
2226 MUTEX_UNLOCK (&cn_mutex
);
2232 rc
= create_thread (waiting_for_exit
, NULL
, &tid
, 0);
2235 if (signal_loop (sigset
))
2237 log_write (_("Received second termination request. Exiting."));
2238 #ifdef HAVE_PTHREAD_CANCEL
2239 pthread_cancel (tid
);
2241 pthread_kill (tid
, SIGUSR2
);
2243 pthread_join (tid
, NULL
);
2247 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2248 pwmd_strerror (rc
));
2251 if (cancel_timeout_thread
)
2253 #ifdef HAVE_PTHREAD_CANCEL
2254 pthread_cancel (cache_timeout_tid
);
2256 pthread_kill (cache_timeout_tid
, SIGUSR2
);
2258 pthread_join (cache_timeout_tid
, NULL
);
2261 if (cancel_keepalive_thread
)
2263 #ifdef HAVE_PTHREAD_CANCEL
2264 pthread_cancel (keepalive_tid
);
2266 pthread_kill (keepalive_tid
, SIGUSR2
);
2268 pthread_join (keepalive_tid
, NULL
);
2271 cleanup_all_clients (0);
2276 pthread_cond_destroy (&quit_cond
);
2277 pthread_mutex_destroy (&quit_mutex
);
2278 return segv
? EXIT_FAILURE
: EXIT_SUCCESS
;;
2285 ("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
2289 /* This is called from cache.c:clear_once(). See
2290 * command.c:clearcache_command() for details about lock checking.
2293 free_cache_data (file_cache_t
* cache
)
2295 gpg_error_t rc
= GPG_ERR_NO_DATA
;
2297 struct client_thread_s
*found
= NULL
;
2304 MUTEX_LOCK (&cn_mutex
);
2305 pthread_cleanup_push (cleanup_mutex_cb
, &cn_mutex
);
2306 t
= slist_length (cn_thread_list
);
2308 for (i
= 0; i
< t
; i
++)
2310 struct client_thread_s
*thd
= slist_nth_data (cn_thread_list
, i
);
2315 if (!memcmp (thd
->cl
->md5file
, cache
->filename
,
2316 sizeof (cache
->filename
)))
2318 if (pthread_equal (pthread_self (), thd
->tid
))
2325 /* Continue trying to find a client who has the same file open and
2326 * also has a lock. */
2327 rc
= cache_lock_mutex (thd
->cl
->ctx
, thd
->cl
->md5file
, -1, 0, -1);
2337 if (self
&& (!rc
|| rc
== GPG_ERR_NO_DATA
))
2338 rc
= cache_lock_mutex (found
->cl
->ctx
, found
->cl
->md5file
, -1, 0, -1);
2340 if (exiting
|| !rc
|| rc
== GPG_ERR_NO_DATA
)
2342 free_cache_data_once (cache
->data
);
2344 cache
->defer_clear
= 0;
2345 cache
->timeout
= -1;
2348 cache_unlock_mutex (found
->cl
->md5file
, 0);
2354 cache
->defer_clear
= 1;
2356 pthread_cleanup_pop (1);
2362 convert_v2_datafile (const char *filename
, const char *cipher
,
2363 const char *keyfile
, const char *keygrip
,
2364 const char *sign_keygrip
, int nopass
,
2365 const char *outfile
, const char *keyparam
,
2366 unsigned long s2k_count
, uint64_t iterations
)
2371 struct crypto_s
*crypto
= NULL
;
2377 if (outfile
[0] == '-' && outfile
[1] == 0)
2380 log_write (_("Converting version 2 data file \"%s\" ..."), filename
);
2381 if (access (filename
, R_OK
) == -1)
2383 log_write ("%s: %s", filename
,
2384 pwmd_strerror (gpg_error_from_errno (errno
)));
2390 log_write (_("Using passphrase file \"%s\" for decryption ..."),
2392 if (access (keyfile
, R_OK
) == -1)
2394 log_write ("%s: %s", keyfile
,
2395 pwmd_strerror (gpg_error_from_errno (errno
)));
2400 rc
= read_v2_datafile (filename
, keyfile
, &data
, &datalen
, &ver
, &algo
);
2403 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
2409 algo
= cipher_string_to_gcrypt (cipher
);
2412 rc
= GPG_ERR_CIPHER_ALGO
;
2421 rc
= parse_doc (data
, datalen
, &doc
);
2425 rc
= convert_pre_212_elements (doc
);
2430 xmlDocDumpFormatMemory (doc
, (xmlChar
**) & data
, (int *) &datalen
,
2433 rc
= GPG_ERR_ENOMEM
;
2441 rc
= init_client_crypto (&crypto
);
2444 memcpy (&crypto
->save
.hdr
, &crypto
->hdr
, sizeof (file_header_t
));
2445 crypto
->save
.hdr
.flags
= set_cipher_flag (crypto
->save
.hdr
.flags
, algo
);
2446 crypto
->save
.s2k_count
= s2k_count
;
2447 crypto
->save
.hdr
.iterations
= iterations
;
2451 rc
= export_common (NULL
, 0, crypto
, data
, datalen
, outfile
, keyfile
,
2452 &key
, &keylen
, 0, 0, nopass
);
2457 rc
= agent_set_pinentry_options (crypto
->agent
);
2459 rc
= agent_export_common (crypto
, keygrip
, sign_keygrip
, nopass
,
2460 data
, datalen
, outfile
, keyparam
,
2461 no_passphrase_file
? NULL
: keyfile
);
2465 log_write (_("Output written to \"%s\"."),
2466 outfile
? outfile
: "<stdout>");
2476 cleanup_crypto (&crypto
);
2479 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
2484 usage (const char *pn
, int status
)
2486 FILE *fp
= status
== EXIT_FAILURE
? stderr
: stdout
;
2488 fprintf (fp
, _("Usage: %s [OPTIONS] [file1] [...]\n"
2489 " -f, --rcfile=filename load the specfied configuration file\n"
2490 " (~/.pwmd/config)\n"
2491 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2492 " --kill terminate an existing instance of pwmd\n"
2494 " --use-agent[=integer] enable/disable use of gpg-agent\n"
2496 " -n, --no-fork run as a foreground process\n"
2497 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2498 " --ignore, --force ignore file errors during startup\n"
2499 " --debug-level=keywords log protocol output (see manual for details)\n"
2500 " -o, --outfile=filename output file when importing or converting\n"
2501 " -C, --convert=filename convert a version 2 data file to version 3\n"
2502 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2503 " -k, --passphrase-file=file for use when importing or converting\n"
2504 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2506 " --no-passphrase when importing or converting\n"
2507 " --keygrip=hex public key to use when encrypting\n"
2508 " --sign-keygrip=hex private key to use when signing\n"
2509 " --keyparam=s-exp custom key parameters to use (RSA-2048)\n"
2510 " --cipher=string encryption cipher (aes256)\n"
2511 " --cipher-iterations=N cipher iteration count (N+1)\n"
2512 " --s2k-count=N hash iteration count (>65536, calibrated)\n"
2513 " --help this help text\n"
2514 " --version show version and compile time features\n"),
2520 unlink_stale_socket (const char *sock
, const char *pidfile
)
2522 log_write (_ ("removing stale socket %s"), sock
);
2528 test_pidfile (const char *path
, const char *sock
, char *buf
, size_t buflen
,
2529 char **pidfile
, int create
, mode_t mode
, int terminate
)
2537 snprintf (buf
, buflen
, "%s/%s.pid", homedir
, sock
);
2538 *pidfile
= str_dup (buf
);
2539 fd
= open (buf
, O_RDONLY
);
2542 fd
= open (*pidfile
, O_CREAT
|O_WRONLY
|O_TRUNC
, mode
);
2546 if (!create
&& errno
!= ENOENT
)
2548 log_write ("%s: %s", buf
, pwmd_strerror (errno
));
2553 else if (!create
&& !terminate
)
2556 log_write ("%s: %s", *pidfile
, strerror (errno
));
2562 snprintf (buf
, buflen
, "%i", getpid ());
2563 write (fd
, buf
, strlen (buf
));
2568 len
= read (fd
, buf
, buflen
);
2572 unlink_stale_socket (path
, *pidfile
);
2576 if (sscanf (buf
, "%5i", &pid
) != 1 || pid
== 0)
2580 unlink_stale_socket (path
, *pidfile
);
2585 if (kill (pid
, 0) == -1)
2587 unlink_stale_socket (path
, *pidfile
);
2593 if (kill (pid
, SIGTERM
) == -1)
2594 log_write ("%s: %s", path
, pwmd_strerror (errno
));
2597 log_write (_ ("an instance for socket %s is already running"), path
);
2605 main (int argc
, char *argv
[])
2608 struct sockaddr_un addr
;
2610 char *socketpath
= NULL
, *socketdir
, *socketname
= NULL
;
2611 char *socketarg
= NULL
;
2612 char *datadir
= NULL
;
2613 char *pidfile
= NULL
;
2617 char **cache_push
= NULL
;
2618 char *import
= NULL
, *keygrip
= NULL
, *sign_keygrip
= NULL
;
2619 char *keyparam
= NULL
;
2620 int estatus
= EXIT_FAILURE
;
2622 char *outfile
= NULL
;
2625 int show_version
= 0;
2627 int no_passphrase
= 0;
2629 char *convertfile
= NULL
;
2630 char *cipher
= NULL
;
2631 char *keyfile
= NULL
;
2632 unsigned long s2k_count
= 0;
2633 uint64_t iterations
= 0;
2635 char *debug_level_opt
= NULL
;
2638 /* Must maintain the same order as longopts[] */
2641 OPT_VERSION
, OPT_HELP
,
2645 OPT_DEBUG_LEVEL
, OPT_HOMEDIR
, OPT_NO_FORK
, OPT_DISABLE_DUMP
,
2646 OPT_IGNORE
, OPT_FORCE
, OPT_RCFILE
, OPT_CONVERT
,
2647 OPT_PASSPHRASE_FILE
, OPT_IMPORT
, OPT_OUTFILE
,
2648 OPT_NO_PASSPHRASE_FILE
, OPT_KEYGRIP
, OPT_SIGN_KEYGRIP
,
2649 OPT_KEYPARAM
, OPT_CIPHER
, OPT_ITERATIONS
, OPT_S2K_COUNT
,
2650 OPT_NO_PASSPHRASE
, OPT_KILL
2652 const char *optstring
= "nf:C:k:I:o:";
2653 const struct option longopts
[] = {
2654 {"version", no_argument
, 0, 0},
2655 {"help", no_argument
, 0, 0},
2657 {"use-agent", optional_argument
, 0, 0},
2659 {"debug-level", required_argument
, 0, 0},
2660 {"homedir", required_argument
, 0, 0},
2661 {"no-fork", no_argument
, 0, 'n'},
2662 {"disable_dump", no_argument
, 0, 0},
2663 {"ignore", no_argument
, 0, 0},
2664 {"force", no_argument
, 0, 0},
2665 {"rcfile", required_argument
, 0, 'f'},
2666 {"convert", required_argument
, 0, 'C'},
2667 {"passphrase-file", required_argument
, 0, 'k'},
2668 {"import", required_argument
, 0, 'I'},
2669 {"outfile", required_argument
, 0, 'o'},
2670 {"no-passphrase-file", no_argument
, 0, 0},
2671 {"keygrip", required_argument
, 0, 0},
2672 {"sign-keygrip", required_argument
, 0, 0},
2673 {"keyparam", required_argument
, 0, 0},
2674 {"cipher", required_argument
, 0, 0},
2675 {"cipher-iterations", required_argument
, 0, 0},
2676 {"s2k-count", required_argument
, 0, 0},
2677 {"no-passphrase", no_argument
, 0, 0},
2678 {"kill", no_argument
, 0, 0},
2685 #ifdef HAVE_SETRLIMIT
2688 rl
.rlim_cur
= rl
.rlim_max
= 0;
2690 if (setrlimit (RLIMIT_CORE
, &rl
) != 0)
2691 err (EXIT_FAILURE
, "setrlimit()");
2694 #ifdef HAVE_PR_SET_DUMPABLE
2695 prctl (PR_SET_DUMPABLE
, 0);
2700 setlocale (LC_ALL
, "");
2701 bindtextdomain ("pwmd", LOCALEDIR
);
2702 textdomain ("pwmd");
2710 if (setup_crypto ())
2711 exit (EXIT_FAILURE
);
2714 gnutls_global_set_mem_functions (xmalloc
, xmalloc
, secure_mem_check
,
2716 gnutls_global_init ();
2717 gnutls_global_set_log_function (tls_log
);
2718 gnutls_global_set_log_level (1);
2722 xmlMemSetup (xfree
, xmalloc
, xrealloc
, str_dup
);
2730 while ((opt
= getopt_long (argc
, argv
, optstring
, longopts
, &optindex
))
2739 convertfile
= optarg
;
2754 rcfile
= str_dup (optarg
);
2757 usage (argv
[0], EXIT_FAILURE
);
2770 use_agent
= optarg
&& *optarg
? atoi (optarg
) : 1;
2771 if (use_agent
< 0 || use_agent
> 1)
2775 case OPT_DEBUG_LEVEL
:
2776 debug_level_opt
= optarg
;
2779 homedir
= str_dup (optarg
);
2784 case OPT_DISABLE_DUMP
:
2792 rcfile
= str_dup (optarg
);
2795 convertfile
= optarg
;
2797 case OPT_PASSPHRASE_FILE
:
2806 case OPT_NO_PASSPHRASE_FILE
:
2807 no_passphrase_file
= 1;
2812 case OPT_SIGN_KEYGRIP
:
2813 sign_keygrip
= optarg
;
2821 case OPT_ITERATIONS
:
2822 iterations
= strtoull (optarg
, NULL
, 10);
2825 s2k_count
= strtoul (optarg
, NULL
, 10);
2827 case OPT_NO_PASSPHRASE
:
2842 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015\n"
2844 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2845 "Compile time features:\n%s"), PACKAGE_STRING
,
2848 "+PWMD_HOMEDIR=" PWMD_HOMEDIR
"\n"
2881 exit (EXIT_SUCCESS
);
2886 homedir
= str_dup(PWMD_HOMEDIR
);
2888 homedir
= str_asprintf ("%s/.pwmd", get_home_dir());
2891 if (mkdir (homedir
, 0700) == -1 && errno
!= EEXIST
)
2892 err (EXIT_FAILURE
, "%s", homedir
);
2894 snprintf (buf
, sizeof (buf
), "%s/data", homedir
);
2895 if (mkdir (buf
, 0700) == -1 && errno
!= EEXIST
)
2896 err (EXIT_FAILURE
, "%s", buf
);
2898 datadir
= str_dup (buf
);
2899 pthread_mutexattr_t attr
;
2900 pthread_mutexattr_init (&attr
);
2901 pthread_mutexattr_settype (&attr
, PTHREAD_MUTEX_RECURSIVE
);
2902 pthread_mutex_init (&rcfile_mutex
, &attr
);
2903 pthread_cond_init (&rcfile_cond
, NULL
);
2904 pthread_mutex_init (&cn_mutex
, &attr
);
2905 pthread_mutexattr_destroy (&attr
);
2906 pthread_key_create (&last_error_key
, free_key
);
2907 #ifndef HAVE_PTHREAD_CANCEL
2908 pthread_key_create (&signal_thread_key
, free_key
);
2912 rcfile
= str_asprintf ("%s/config", homedir
);
2914 global_config
= config_parse (rcfile
);
2916 exit (EXIT_FAILURE
);
2919 if (use_agent
== -1)
2920 use_agent
= config_get_boolean ("global", "use_agent");
2925 if (debug_level_opt
)
2926 debug_level
= str_split (debug_level_opt
, ",", 0);
2928 x
= config_get_int_param (global_config
, "global", "priority", &exists
);
2929 if (exists
&& x
!= atoi(INVALID_PRIORITY
))
2932 if (setpriority (PRIO_PROCESS
, 0, x
) == -1)
2934 log_write ("setpriority(): %s",
2935 pwmd_strerror (gpg_error_from_errno (errno
)));
2939 #ifdef HAVE_MLOCKALL
2940 if (disable_mlock
== 0 && mlockall (MCL_CURRENT
| MCL_FUTURE
) == -1)
2942 log_write ("mlockall(): %s",
2943 pwmd_strerror (gpg_error_from_errno (errno
)));
2948 rc
= cache_init (free_cache_data
);
2951 log_write ("pwmd: ERR %i: %s", rc
,
2952 gpg_err_code (rc
) == GPG_ERR_UNKNOWN_VERSION
2953 ? _("incompatible gpg-agent version: 2.1.0 or later required")
2954 : pwmd_strerror (rc
));
2959 s2k_count
= config_get_ulong (NULL
, "s2k_count");
2963 if (!outfile
|| !*outfile
|| argc
!= optind
)
2964 usage (argv
[0], EXIT_FAILURE
);
2966 estatus
= convert_v2_datafile (convertfile
, cipher
, keyfile
, keygrip
,
2967 sign_keygrip
, no_passphrase
, outfile
,
2968 keyparam
, s2k_count
, iterations
);
2969 config_free (global_config
);
2976 if (!outfile
|| !*outfile
|| argc
!= optind
)
2977 usage (argv
[0], EXIT_FAILURE
);
2979 if (outfile
&& outfile
[0] == '-' && outfile
[1] == 0)
2982 estatus
= xml_import (import
, outfile
, keygrip
, sign_keygrip
, keyfile
,
2983 no_passphrase
, cipher
, keyparam
, s2k_count
,
2985 config_free (global_config
);
2990 p
= config_get_string ("global", "socket_path");
2992 p
= str_asprintf ("%s/socket", homedir
);
2994 socketarg
= expand_homedir (p
);
2998 disable_list_and_dump
= config_get_boolean ("global",
2999 "disable_list_and_dump");
3001 disable_list_and_dump
= secure
;
3003 cache_push
= config_get_list ("global", "cache_push");
3005 while (optind
< argc
)
3007 if (strv_printf (&cache_push
, "%s", argv
[optind
++]) == 0)
3008 errx (EXIT_FAILURE
, "%s", pwmd_strerror (GPG_ERR_ENOMEM
));
3011 if (strchr (socketarg
, '/') == NULL
)
3013 socketdir
= getcwd (buf
, sizeof (buf
));
3014 socketname
= str_dup (socketarg
);
3015 socketpath
= str_asprintf ("%s/%s", socketdir
, socketname
);
3019 socketname
= str_dup (strrchr (socketarg
, '/'));
3021 socketarg
[strlen (socketarg
) - strlen (socketname
) - 1] = 0;
3022 socketdir
= str_dup (socketarg
);
3023 socketpath
= str_asprintf ("%s/%s", socketdir
, socketname
);
3026 if (chdir (datadir
))
3028 log_write ("%s: %s", datadir
,
3029 pwmd_strerror (gpg_error_from_errno (errno
)));
3030 unlink (socketpath
);
3034 x
= test_pidfile (socketpath
, socketname
, buf
, sizeof(buf
), &pidfile
, 0,
3036 if (!terminate
&& x
)
3040 estatus
= x
!= 1 ? EXIT_FAILURE
: EXIT_SUCCESS
;
3045 * bind() doesn't like the full pathname of the socket or any non alphanum
3046 * characters so change to the directory where the socket is wanted then
3047 * create it then change to datadir.
3049 if (chdir (socketdir
))
3051 log_write ("%s: %s", socketdir
,
3052 pwmd_strerror (gpg_error_from_errno (errno
)));
3058 if ((sockfd
= socket (PF_UNIX
, SOCK_STREAM
, 0)) == -1)
3060 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
3064 addr
.sun_family
= AF_UNIX
;
3065 snprintf (addr
.sun_path
, sizeof (addr
.sun_path
), "%s", socketname
);
3067 if (bind (sockfd
, (struct sockaddr
*) &addr
, sizeof (struct sockaddr
)) ==
3070 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
3072 if (errno
== EADDRINUSE
)
3075 log_write (_("Either there is another pwmd running or '%s' is a \n"
3076 "stale socket. Please remove it manually."), socketpath
);
3083 char *t
= config_get_string ("global", "socket_perms");
3088 mode
= strtol (t
, NULL
, 8);
3092 if (chmod (socketname
, mode
) == -1)
3094 log_write ("%s: %s", socketname
,
3095 pwmd_strerror (gpg_error_from_errno (errno
)));
3105 xfree (--socketname
);
3107 if (chdir (datadir
))
3109 log_write ("%s: %s", datadir
,
3110 pwmd_strerror (gpg_error_from_errno (errno
)));
3118 * Set the cache entry for a file. Prompts for the password.
3122 struct crypto_s
*crypto
= NULL
;
3123 gpg_error_t rc
= init_client_crypto (&crypto
);
3127 estatus
= EXIT_FAILURE
;
3134 rc
= agent_set_pinentry_options (crypto
->agent
);
3137 estatus
= EXIT_FAILURE
;
3143 for (opt
= 0; cache_push
[opt
]; opt
++)
3145 if (!do_cache_push (cache_push
[opt
], crypto
) && !force
)
3147 strv_free (cache_push
);
3149 estatus
= EXIT_FAILURE
;
3150 cleanup_crypto (&crypto
);
3154 cleanup_crypto_stage1 (crypto
);
3159 (void) kill_scd (crypto
->agent
);
3162 cleanup_crypto (&crypto
);
3163 strv_free (cache_push
);
3164 log_write (!nofork
? _("Done. Daemonizing...") :
3165 _("Done. Waiting for connections..."));
3168 config_clear_keys ();
3170 if (listen (sockfd
, 0) == -1)
3172 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
3181 log_write ("fork(): %s",
3182 pwmd_strerror (gpg_error_from_errno (errno
)));
3191 _exit (EXIT_SUCCESS
);
3195 (void)test_pidfile (socketpath
, socketname
, buf
, sizeof(buf
), &pidfile
, 1,
3198 pthread_key_create (&thread_name_key
, free_key
);
3199 pthread_setspecific (thread_name_key
, str_dup ("main"));
3200 estatus
= server_loop (sockfd
, &socketpath
);
3203 if (socketpath
&& do_unlink
)
3205 unlink (socketpath
);
3211 gnutls_global_deinit ();
3212 xfree (invoking_tls
);
3216 #ifdef HAVE_PTHREAD_CANCEL
3217 pthread_cancel (rcfile_tid
);
3219 pthread_kill (rcfile_tid
, SIGUSR2
);
3220 pthread_cond_signal (&rcfile_cond
);
3222 pthread_join (rcfile_tid
, NULL
);
3225 pthread_cond_destroy (&rcfile_cond
);
3226 pthread_mutex_destroy (&rcfile_mutex
);
3227 pthread_key_delete (last_error_key
);
3228 #ifndef HAVE_PTHREAD_CANCEL
3229 pthread_key_delete (signal_thread_key
);
3233 config_free (global_config
);
3236 xfree (home_directory
);
3238 xmlCleanupParser ();
3239 xmlCleanupGlobals ();
3245 if (estatus
== EXIT_SUCCESS
&& !terminate
)
3246 log_write (_("pwmd exiting normally"));
3248 pthread_key_delete (thread_name_key
);
3250 #if defined(DEBUG) && !defined(MEM_DEBUG)