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 slist_s
*keep
= NULL
;
255 struct slist_s
*config
;
256 int b
= disable_list_and_dump
;
258 pthread_cond_wait (&rcfile_cond
, &rcfile_mutex
);
259 #ifndef HAVE_PTHREAD_CANCEL
260 int *cancel
= (int *) pthread_getspecific (signal_thread_key
);
265 pthread_cleanup_push (cleanup_mutex_cb
, &rcfile_mutex
);
266 keep
= config_keep_save ();
267 log_write (_("reloading configuration file '%s'"), rcfile
);
269 config
= config_parse (rcfile
, 1);
272 config_free (global_config
);
273 global_config
= config
;
275 cache_push_from_rcfile ();
276 config_clear_keys ();
279 config_keep_restore (keep
);
280 disable_list_and_dump
= !disable_list_and_dump
? b
: 1;
283 /* Kill existing listening threads since the configured listening
284 * protocols may have changed. */
288 pthread_cleanup_pop (0);
291 pthread_cleanup_pop (1);
296 send_error (assuan_context_t ctx
, gpg_error_t e
)
298 struct client_s
*client
= assuan_get_pointer (ctx
);
300 if (gpg_err_source (e
) == GPG_ERR_SOURCE_UNKNOWN
)
307 return assuan_process_done (ctx
, 0);
311 log_write ("ERR %i: %s", e
, pwmd_strerror (e
));
315 if (client
&& client
->xml_error
)
317 log_write ("%s", client
->xml_error
->message
);
318 xfree (client
->last_error
);
319 client
->last_error
= NULL
;
320 if (client
->xml_error
->message
)
321 client
->last_error
= str_dup (client
->xml_error
->message
);
323 e
= assuan_process_done (ctx
,
324 assuan_set_error (ctx
, e
,
325 client
->xml_error
->message
? client
->xml_error
->message
: NULL
));
326 xmlResetLastError ();
327 xmlResetError (client
->xml_error
);
328 xfree (client
->xml_error
);
329 client
->xml_error
= NULL
;
333 return assuan_process_done (ctx
,
334 assuan_set_error (ctx
, e
, pwmd_strerror (e
)));
338 assuan_log_cb (assuan_context_t ctx
, void *data
, unsigned cat
,
341 static pthread_mutex_t m
= PTHREAD_MUTEX_INITIALIZER
;
345 pthread_mutex_lock (&m
);
346 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock
, &m
);
347 t
= strv_length (debug_level
);
349 for (i
= 0; i
< t
; i
++)
351 if (!strcasecmp (debug_level
[i
], (char *) "init")
352 && cat
== ASSUAN_LOG_INIT
)
358 if (!strcasecmp (debug_level
[i
], (char *) "ctx")
359 && cat
== ASSUAN_LOG_CTX
)
365 if (!strcasecmp (debug_level
[i
], (char *) "engine")
366 && cat
== ASSUAN_LOG_ENGINE
)
372 if (!strcasecmp (debug_level
[i
], (char *) "data")
373 && cat
== ASSUAN_LOG_DATA
)
379 if (!strcasecmp (debug_level
[i
], (char *) "sysio")
380 && cat
== ASSUAN_LOG_SYSIO
)
386 if (!strcasecmp (debug_level
[i
], (char *) "control")
387 && cat
== ASSUAN_LOG_CONTROL
)
401 open (logfile
, O_WRONLY
| O_CREAT
| O_APPEND
, 0600)) == -1)
402 warn ("%s", logfile
);
405 pthread_cleanup_push (cleanup_fd_cb
, &fd
);
406 write (fd
, msg
, strlen (msg
));
407 pthread_cleanup_pop (1);
413 fprintf (stderr
, "%s%s", data
? (char *) data
: "", msg
);
418 pthread_cleanup_pop (1);
423 log_write (const char *fmt
, ...)
429 pthread_t tid
= pthread_self ();
430 static pthread_mutex_t m
= PTHREAD_MUTEX_INITIALIZER
;
432 if ((!logfile
&& !isatty (STDERR_FILENO
) && !log_syslog
) || !fmt
)
435 pthread_mutex_lock (&m
);
436 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock
, &m
);
438 if (!cmdline
&& logfile
&& log_fd
== -1)
440 log_fd
= open (logfile
, O_WRONLY
| O_CREAT
| O_APPEND
, 0600);
442 warn ("%s", logfile
);
447 if (str_vasprintf (&args
, fmt
, ap
) != -1)
451 pthread_cleanup_push (xfree
, args
);
452 fprintf (stderr
, "pwmd: %s\n", args
);
454 pthread_cleanup_pop (1);
458 char *name
= pthread_getspecific (thread_name_key
);
461 pthread_cleanup_push (xfree
, args
);
462 snprintf (buf
, sizeof (buf
), "%s(%p): ", name
? name
: _("unknown"),
466 if (!cmdline
&& log_syslog
&& !nofork
)
467 syslog (LOG_INFO
, "%s%s", name
, args
);
470 struct tm
*tm
= localtime (&now
);
472 strftime (tbuf
, sizeof (tbuf
), "%b %d %Y %H:%M:%S ", tm
);
473 tbuf
[sizeof (tbuf
) - 1] = 0;
475 if (args
[strlen (args
) - 1] == '\n')
476 args
[strlen (args
) - 1] = 0;
478 line
= str_asprintf ("%s %i %s%s\n", tbuf
, getpid (), name
,
480 pthread_cleanup_pop (1);
483 pthread_cleanup_push (xfree
, line
);
484 if (logfile
&& log_fd
!= -1)
486 write (log_fd
, line
, strlen (line
));
492 fprintf (stdout
, "%s", line
);
496 pthread_cleanup_pop (1);
502 pthread_cleanup_pop (0);
504 if (log_fd
!= -1 && config_get_boolean (NULL
, "log_keepopen") <= 0)
510 pthread_mutex_unlock (&m
);
516 gcry_control (GCRYCTL_SET_THREAD_CBS
, &gcry_threads_pthread
);
518 if (!gcry_check_version (GCRYPT_VERSION
))
520 fprintf (stderr
, _("gcry_check_version(): Incompatible libgcrypt. "
521 "Wanted %s, got %s.\n"), GCRYPT_VERSION
,
522 gcry_check_version (NULL
));
523 return GPG_ERR_UNKNOWN_VERSION
;
526 gcry_set_allocation_handler (xmalloc
, xmalloc
, NULL
, xrealloc
, xfree
);
531 do_validate_peer (assuan_context_t ctx
, const char *section
,
532 assuan_peercred_t
* peer
)
537 struct client_s
*client
= assuan_get_pointer (ctx
);
540 return GPG_ERR_EACCES
;
543 if (client
->thd
->remote
)
544 return tls_validate_access (client
, section
);
547 rc
= assuan_get_peercred (ctx
, peer
);
551 users
= config_get_list (section
, "allowed");
554 for (char **p
= users
; *p
; p
++)
556 rc
= acl_check_common(client
, *p
, (*peer
)->uid
, (*peer
)->gid
,
563 return allowed
? 0 : rc
? rc
: GPG_ERR_EACCES
;
566 /* Test if uid is a member of group 'name'. Invert when 'not' is true. */
567 #ifdef HAVE_GETGRNAM_R
569 acl_check_group (const char *name
, uid_t uid
, gid_t gid
, int not, int *allowed
)
572 struct group gr
, *gresult
;
573 size_t len
= sysconf (_SC_GETGR_R_SIZE_MAX
);
580 return GPG_ERR_ENOMEM
;
582 if (!getgrnam_r (name
, &gr
, buf
, len
, &gresult
) && gresult
)
584 if (gresult
->gr_gid
== gid
)
591 len
= sysconf (_SC_GETPW_R_SIZE_MAX
);
595 for (char **t
= gresult
->gr_mem
; *t
; t
++)
599 struct passwd
*result
= get_pwd_struct (*t
, 0, &pw
, &tbuf
);
601 if (result
&& result
->pw_uid
== uid
)
616 return GPG_ERR_EACCES
;
620 acl_check_group (const char *name
, uid_t uid
, gid_t gid
, int not, int *allowed
)
622 struct group
*gresult
;
624 gresult
= getgrnam (name
);
625 if (gresult
&& gresult
->gr_gid
== gid
)
631 for (char **t
= gresult
->gr_mem
; *t
; t
++)
635 struct passwd
*result
= get_pwd_struct (*t
, 0, &pw
, &buf
);
637 if (result
&& result
->pw_uid
== uid
)
652 peer_is_invoker(struct client_s
*client
)
654 struct invoking_user_s
*user
;
657 if (client
->thd
->state
== CLIENT_STATE_UNKNOWN
)
658 return GPG_ERR_EACCES
;
660 for (user
= invoking_users
; user
; user
= user
->next
)
663 if (client
->thd
->remote
)
665 if (user
->type
== INVOKING_TLS
666 && !strcmp(client
->thd
->tls
->fp
, user
->id
))
667 allowed
= user
->not ? 0 : 1;
673 if (user
->type
== INVOKING_GID
)
675 gpg_error_t rc
= acl_check_group (user
->id
,
676 client
->thd
->peer
->uid
,
677 client
->thd
->peer
->gid
,
678 user
->not, &allowed
);
682 else if (user
->type
== INVOKING_UID
&& client
->thd
->peer
->uid
== user
->uid
)
683 allowed
= user
->not ? 0 : 1;
686 return allowed
? 0 : GPG_ERR_EACCES
;
689 #ifdef HAVE_GETGRNAM_R
691 acl_check_common (struct client_s
*client
, const char *user
, uid_t uid
,
692 gid_t gid
, int *allowed
)
701 if (*user
== '-' || *user
== '!')
704 if (*user
== '+') // not implemented yet
707 if (*user
== '#') // TLS fingerprint hash
710 if (not || rw
|| tls
)
716 if (client
->thd
->remote
)
718 if (!strcasecmp (client
->thd
->tls
->fp
, user
))
728 else if (client
->thd
->remote
) // Remote client with no TLS in the ACL
732 if (*user
== '@') // all users in group
733 return acl_check_group (user
+1, uid
, gid
, not, allowed
);
738 struct passwd
*pwd
= get_pwd_struct (user
, 0, &pw
, &buf
);
740 if (pwd
&& pwd
->pw_uid
== uid
)
750 acl_check_common (struct client_s
*client
, const char *user
, uid_t uid
,
751 gid_t gid
, int *allowed
)
760 if (*user
== '-' || *user
== '!')
763 if (*user
== '+') // not implemented yet
766 if (*user
== '#') // TLS fingerprint hash
769 if (not || rw
|| tls
)
775 if (client
->thd
->remote
)
777 if (!strcasecmp (client
->thd
->tls
->fp
, user
))
787 if (*user
== '@') // all users in group
788 return acl_check_group (user
+1, uid
, gid
, not, allowed
);
793 struct passwd
*result
= get_pwd_struct (user
, 0, &pw
, &buf
);
795 if (result
&& result
->pw_uid
== uid
)
806 validate_peer (struct client_s
*cl
)
812 return tls_validate_access (cl
, NULL
);
815 MUTEX_LOCK (&cn_mutex
);
816 rc
= do_validate_peer (cl
->ctx
, "global", &cl
->thd
->peer
);
817 MUTEX_UNLOCK (&cn_mutex
);
818 if (!rc
|| gpg_err_code (rc
) == GPG_ERR_EACCES
)
819 log_write ("peer %s: uid=%i, gid=%i, pid=%i",
820 !rc
? _("accepted") : _("rejected"), cl
->thd
->peer
->uid
,
821 cl
->thd
->peer
->gid
, cl
->thd
->peer
->pid
);
823 log_write ("%s: %s", __FUNCTION__
, pwmd_strerror (rc
));
829 xml_error_cb (void *data
, xmlErrorPtr e
)
831 struct client_s
*client
= data
;
834 * Keep the first reported error as the one to show in the error
835 * description. Reset in send_error().
837 if (client
->xml_error
)
840 client
->xml_error
= xcalloc (1, sizeof(xmlError
));
841 xmlCopyError (e
, client
->xml_error
);
845 hook_waitpid (assuan_context_t ctx
, pid_t pid
, int action
,
846 int *status
, int options
)
848 return waitpid (pid
, status
, options
);
852 hook_read (assuan_context_t ctx
, assuan_fd_t fd
, void *data
, size_t len
)
855 struct client_s
*client
= assuan_get_pointer (ctx
);
857 if (client
->thd
->remote
)
858 return tls_read_hook (ctx
, (int) fd
, data
, len
);
861 return read ((int) fd
, data
, len
);
865 hook_write (assuan_context_t ctx
, assuan_fd_t fd
,
866 const void *data
, size_t len
)
869 struct client_s
*client
= assuan_get_pointer (ctx
);
871 if (client
->thd
->remote
)
872 return tls_write_hook (ctx
, (int) fd
, data
, len
);
875 return write ((int) fd
, data
, len
);
879 new_connection (struct client_s
*cl
)
882 static struct assuan_malloc_hooks mhooks
= { xmalloc
, xrealloc
, xfree
};
883 static struct assuan_system_hooks shooks
= {
884 ASSUAN_SYSTEM_HOOKS_VERSION
,
892 NULL
, //sendmsg both are used for FD passing
903 char *prio
= config_get_string ("global", "tls_cipher_suite");
905 cl
->thd
->timeout
= config_get_integer ("global", "tls_timeout");
906 if (fcntl (cl
->thd
->fd
, F_SETFL
, O_NONBLOCK
) == -1)
909 cl
->thd
->tls
= tls_init (cl
->thd
->fd
, cl
->thd
->timeout
, prio
);
916 rc
= assuan_new_ext (&cl
->ctx
, GPG_ERR_SOURCE_DEFAULT
, &mhooks
,
917 debug_level
? assuan_log_cb
: NULL
, NULL
);
921 assuan_ctx_set_system_hooks (cl
->ctx
, &shooks
);
922 rc
= assuan_init_socket_server (cl
->ctx
, cl
->thd
->fd
, 2);
926 assuan_set_pointer (cl
->ctx
, cl
);
927 assuan_set_hello_line (cl
->ctx
, PACKAGE_STRING
);
928 rc
= register_commands (cl
->ctx
);
932 rc
= assuan_accept (cl
->ctx
);
936 rc
= validate_peer (cl
);
937 /* May not be implemented on all platforms. */
938 if (rc
&& gpg_err_code (rc
) != GPG_ERR_ASS_GENERAL
)
941 MUTEX_LOCK (&cn_mutex
);
942 cl
->thd
->state
= CLIENT_STATE_INIT
;
943 MUTEX_UNLOCK (&cn_mutex
);
944 rc
= init_client_crypto (&cl
->crypto
);
950 cl
->crypto
->agent
->client_ctx
= cl
->ctx
;
953 cl
->crypto
->client_ctx
= cl
->ctx
;
954 cl
->lock_timeout
= config_get_integer ("global", "lock_timeout");
955 xmlSetStructuredErrorFunc (cl
, xml_error_cb
);
959 log_write ("%s", pwmd_strerror (rc
));
964 * This is called after a client_thread() terminates. Set with
965 * pthread_cleanup_push().
968 cleanup_cb (void *arg
)
970 struct client_thread_s
*cn
= arg
;
971 struct client_s
*cl
= cn
->cl
;
973 MUTEX_LOCK (&cn_mutex
);
974 cn_thread_list
= slist_remove (cn_thread_list
, cn
);
975 MUTEX_UNLOCK (&cn_mutex
);
981 xmlResetError (cl
->xml_error
);
983 xfree (cl
->xml_error
);
988 gnutls_deinit (cn
->tls
->ses
);
994 if (!cn
->atfork
&& cl
->ctx
)
995 assuan_release (cl
->ctx
);
996 else if (!cn
->atfork
&& cl
->thd
&& cl
->thd
->fd
!= -1)
1000 cleanup_crypto (&cl
->crypto
);
1002 pinentry_free_opts (&cl
->pinentry_opts
);
1011 while (cn
->msg_queue
)
1013 struct status_msg_s
*msg
= cn
->msg_queue
;
1015 cn
->msg_queue
= msg
->next
;
1020 if (!cn
->atfork
&& cn
->status_msg_pipe
[0] != -1)
1021 close (cn
->status_msg_pipe
[0]);
1023 if (!cn
->atfork
&& cn
->status_msg_pipe
[1] != -1)
1024 close (cn
->status_msg_pipe
[1]);
1026 pthread_mutex_destroy (&cn
->status_mutex
);
1030 log_write (_("exiting, fd=%i"), cn
->fd
);
1031 send_status_all (STATUS_CLIENTS
, NULL
);
1036 xfree (cn
->peeraddr
);
1039 pthread_cond_signal (&quit_cond
);
1043 cleanup_all_clients (int atfork
)
1045 /* This function may be called from pthread_atfork() which requires
1046 reinitialization. */
1049 pthread_mutexattr_t attr
;
1051 pthread_mutexattr_init (&attr
);
1052 pthread_mutexattr_settype (&attr
, PTHREAD_MUTEX_RECURSIVE
);
1053 pthread_mutex_init (&cn_mutex
, &attr
);
1054 pthread_mutexattr_destroy (&attr
);
1055 cache_mutex_init ();
1058 MUTEX_LOCK (&cn_mutex
);
1060 while (slist_length (cn_thread_list
))
1062 struct client_thread_s
*thd
= slist_nth_data (cn_thread_list
, 0);
1064 thd
->atfork
= atfork
;
1069 MUTEX_UNLOCK (&cn_mutex
);
1070 cache_deinit (atfork
);
1074 send_msg_queue (struct client_thread_s
*thd
)
1076 MUTEX_LOCK (&thd
->status_mutex
);
1080 read (thd
->status_msg_pipe
[0], &c
, 1);
1081 thd
->wrote_status
= 0;
1083 while (thd
->msg_queue
)
1085 struct status_msg_s
*msg
= thd
->msg_queue
;
1087 thd
->msg_queue
= thd
->msg_queue
->next
;
1088 MUTEX_UNLOCK (&thd
->status_mutex
);
1089 rc
= send_status (thd
->cl
->ctx
, msg
->s
, msg
->line
);
1090 MUTEX_LOCK (&thd
->status_mutex
);
1098 MUTEX_UNLOCK (&thd
->status_mutex
);
1099 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1100 log_write ("%s: %s", __FUNCTION__
, pwmd_strerror (rc
));
1106 client_thread (void *data
)
1108 struct client_thread_s
*thd
= data
;
1109 struct client_s
*cl
= xcalloc (1, sizeof (struct client_s
));
1111 #ifdef HAVE_PR_SET_NAME
1112 prctl (PR_SET_NAME
, "client");
1114 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1118 log_write ("%s(%i): %s", __FILE__
, __LINE__
,
1119 pwmd_strerror (GPG_ERR_ENOMEM
));
1123 MUTEX_LOCK (&cn_mutex
);
1124 pthread_cleanup_push (cleanup_cb
, thd
);
1127 MUTEX_UNLOCK (&cn_mutex
);
1129 if (new_connection (cl
))
1134 send_status_all (STATUS_CLIENTS
, NULL
);
1135 rc
= send_status (cl
->ctx
, STATUS_CACHE
, NULL
);
1138 log_write ("%s(%i): %s", __FILE__
, __LINE__
, pwmd_strerror (rc
));
1149 FD_SET (thd
->fd
, &rfds
);
1150 FD_SET (thd
->status_msg_pipe
[0], &rfds
);
1151 n
= thd
->fd
> thd
->status_msg_pipe
[0]
1152 ? thd
->fd
: thd
->status_msg_pipe
[0];
1154 n
= select (n
+ 1, &rfds
, NULL
, NULL
, NULL
);
1157 log_write ("%s", strerror (errno
));
1161 if (FD_ISSET (thd
->status_msg_pipe
[0], &rfds
))
1163 rc
= send_msg_queue (thd
);
1164 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1168 if (!FD_ISSET (thd
->fd
, &rfds
))
1171 rc
= assuan_process_next (cl
->ctx
, &eof
);
1174 if (gpg_err_code (rc
) == GPG_ERR_EOF
|| eof
)
1177 log_write ("assuan_process_next(): rc=%i %s", rc
,
1178 pwmd_strerror (rc
));
1179 if (rc
== gpg_error (GPG_ERR_ETIMEDOUT
))
1182 rc
= send_error (cl
->ctx
, rc
);
1185 log_write ("assuan_process_done(): rc=%i %s", rc
,
1186 pwmd_strerror (rc
));
1191 /* Since the msg queue pipe fd's are non-blocking, check for
1192 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1193 * client has already disconnected and will be converted to
1194 * GPG_ERR_EOF during assuan_process_next().
1196 rc
= send_msg_queue (thd
);
1197 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1202 /* Don't do pthread_exit() here because any set pthread_cleanup_push
1203 * functions would be called after a command failed but then the client
1204 * exited normally which may lead to a double free. */
1205 pthread_cleanup_pop (1);
1210 xml_import (const char *filename
, const char *outfile
,
1211 const char *keygrip
, const char *sign_keygrip
,
1212 const char *keyfile
, int no_passphrase
, const char *cipher
,
1213 const char *params
, uint64_t iterations
)
1222 struct crypto_s
*crypto
= NULL
;
1225 int algo
= cipher
? cipher_string_to_gcrypt ((char *) cipher
) :
1230 log_write ("ERR %i: %s", gpg_error (GPG_ERR_CIPHER_ALGO
),
1231 pwmd_strerror (GPG_ERR_CIPHER_ALGO
));
1235 if (stat (filename
, &st
) == -1)
1237 log_write ("%s: %s", filename
,
1238 pwmd_strerror (gpg_error_from_errno (errno
)));
1242 rc
= init_client_crypto (&crypto
);
1246 memcpy (&crypto
->save
.hdr
, &crypto
->hdr
, sizeof (file_header_t
));
1247 crypto
->save
.hdr
.flags
= set_cipher_flag (crypto
->save
.hdr
.flags
, algo
);
1248 log_write (_("Importing XML from '%s'. Output will be written to '%s' ..."),
1251 if ((fd
= open (filename
, O_RDONLY
)) == -1)
1253 log_write ("%s: %s", filename
,
1254 pwmd_strerror (gpg_error_from_errno (errno
)));
1258 if ((xmlbuf
= xmalloc (st
.st_size
+ 1)) == NULL
)
1261 log_write ("%s(%i): %s", __FILE__
, __LINE__
,
1262 pwmd_strerror (GPG_ERR_ENOMEM
));
1266 if (read (fd
, xmlbuf
, st
.st_size
) == -1)
1268 rc
= gpg_error_from_errno (errno
);
1270 log_write ("%s: %s", filename
, pwmd_strerror (rc
));
1275 xmlbuf
[st
.st_size
] = 0;
1277 * Make sure the document validates.
1279 if ((doc
= xmlReadDoc (xmlbuf
, NULL
, "UTF-8", XML_PARSE_NOBLANKS
)) == NULL
)
1281 log_write ("xmlReadDoc() failed");
1287 xmlNodePtr n
= xmlDocGetRootElement (doc
);
1288 if (n
&& !xmlStrEqual (n
->name
, (xmlChar
*) "pwmd"))
1290 log_write (_("Could not find root \"pwmd\" element."));
1291 rc
= GPG_ERR_BAD_DATA
;
1295 rc
= validate_import (NULL
, n
? n
->children
: n
);
1299 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
1304 xmlDocDumpMemory (doc
, &xml
, &len
);
1306 crypto
->save
.hdr
.s2k_count
= iterations
;
1309 rc
= export_common (NULL
, 0, crypto
, xml
, len
, outfile
, keyfile
, &key
,
1310 &keylen
, 0, 0, no_passphrase
);
1312 log_write (_("Success!"));
1317 rc
= agent_set_pinentry_options (crypto
->agent
);
1319 rc
= agent_export_common (crypto
, keygrip
, sign_keygrip
, no_passphrase
,
1320 xml
, len
, outfile
, params
, keyfile
);
1328 send_error (NULL
, rc
);
1332 cleanup_crypto (&crypto
);
1336 cleanup_crypto (&crypto
);
1341 do_cache_push (const char *filename
, struct crypto_s
*crypto
)
1343 unsigned char md5file
[16];
1348 struct cache_data_s
*cdata
;
1352 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1355 if (valid_filename (filename
) == 0)
1357 log_write (_("%s: Invalid characters in filename"), filename
);
1361 rc
= decrypt_common (NULL
, 0, crypto
, filename
, &key
, &keylen
, NULL
, NULL
);
1365 rc
= parse_doc ((char *) crypto
->plaintext
, crypto
->plaintext_len
, &doc
);
1368 log_write ("%s", pwmd_strerror (rc
));
1373 gcry_md_hash_buffer (GCRY_MD_MD5
, md5file
, filename
, strlen (filename
));
1374 cdata
= xcalloc (1, sizeof (struct cache_data_s
));
1378 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM
));
1383 rc
= get_checksum (filename
, &crc
, &len
);
1386 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
1388 free_cache_data_once (cdata
);
1394 rc
= encrypt_xml (NULL
, cache_key
, cache_keysize
, GCRY_CIPHER_AES
,
1395 crypto
->plaintext
, crypto
->plaintext_len
, &cdata
->doc
,
1396 &cdata
->doclen
, &cache_iv
, &cache_blocksize
);
1397 if (!rc
&& !IS_PKI (crypto
))
1400 cdata
->keylen
= keylen
;
1407 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
1409 free_cache_data_once (cdata
);
1414 if (use_agent
&& IS_PKI (crypto
))
1416 gcry_sexp_build ((gcry_sexp_t
*) & cdata
->pubkey
, NULL
, "%S",
1418 gcry_sexp_build ((gcry_sexp_t
*) & cdata
->sigkey
, NULL
, "%S",
1419 crypto
->sigpkey_sexp
);
1423 int timeout
= config_get_integer (filename
, "cache_timeout");
1424 cache_add_file (md5file
, crypto
->grip
, cdata
, timeout
);
1425 log_write (_("Successfully added '%s' to the cache."), filename
);
1430 init_client (int fd
, const char *addr
)
1433 struct client_thread_s
*new = xcalloc (1, sizeof (struct client_thread_s
));
1438 return GPG_ERR_ENOMEM
;
1441 MUTEX_LOCK (&cn_mutex
);
1442 pthread_cleanup_push (cleanup_mutex_cb
, &cn_mutex
);
1444 if (pipe (new->status_msg_pipe
) == -1)
1445 rc
= gpg_error_from_errno (errno
);
1449 if (fcntl (new->status_msg_pipe
[0], F_SETFL
, O_NONBLOCK
) == -1)
1450 rc
= gpg_error_from_errno (errno
);
1453 if (fcntl (new->status_msg_pipe
[1], F_SETFL
, O_NONBLOCK
) == -1)
1454 rc
= gpg_error_from_errno (errno
);
1456 pthread_mutex_init (&new->status_mutex
, NULL
);
1462 new->remote
= addr
? 1 : 0;
1465 rc
= create_thread (client_thread
, new, &new->tid
, 1);
1468 close (new->status_msg_pipe
[0]);
1469 close (new->status_msg_pipe
[1]);
1470 pthread_mutex_destroy (&new->status_mutex
);
1476 struct slist_s
*list
= slist_append (cn_thread_list
, new);
1480 cn_thread_list
= list
;
1483 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1484 (pthread_t
*) new->tid
, fd
, addr
);
1486 new->peeraddr
= str_dup (addr
);
1490 log_write (_("new connection: tid=%p, fd=%i"),
1491 (pthread_t
*) new->tid
, fd
);
1494 rc
= GPG_ERR_ENOMEM
;
1497 pthread_cleanup_pop (1);
1503 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1504 pwmd_strerror (rc
));
1510 keepalive_thread (void *arg
)
1512 #ifndef HAVE_PTHREAD_CANCEL
1513 int *n
= xmalloc (sizeof (int));
1516 pthread_setspecific (signal_thread_key
, n
);
1520 #ifdef HAVE_PR_SET_NAME
1521 prctl (PR_SET_NAME
, "keepalive");
1523 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1527 int n
= config_get_integer ("global", "keepalive_interval");
1528 struct timeval tv
= { n
, 0 };
1529 #ifndef HAVE_PTHREAD_CANCEL
1532 sigusr2
= (int *) pthread_getspecific (signal_thread_key
);
1537 send_status_all (STATUS_KEEPALIVE
, NULL
);
1538 select (0, NULL
, NULL
, NULL
, &tv
);
1545 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1547 get_in_addr (struct sockaddr
*sa
)
1549 if (sa
->sa_family
== AF_INET
)
1550 return &(((struct sockaddr_in
*) sa
)->sin_addr
);
1552 return &(((struct sockaddr_in6
*) sa
)->sin6_addr
);
1556 tcp_accept_thread (void *arg
)
1558 int sockfd
= *(int *) arg
;
1559 #ifndef HAVE_PTHREAD_CANCEL
1560 int *n
= xmalloc (sizeof (int));
1563 pthread_setspecific (signal_thread_key
, n
);
1565 fcntl (sockfd
, F_SETFL
, O_NONBLOCK
);
1568 #ifdef HAVE_PR_SET_NAME
1569 prctl (PR_SET_NAME
, "tcp_accept");
1571 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1575 struct sockaddr_storage raddr
;
1576 socklen_t slen
= sizeof (raddr
);
1579 char s
[INET6_ADDRSTRLEN
];
1580 struct timeval tv
= { 0, ACCEPT_TIMEOUT
};
1581 #ifndef HAVE_PTHREAD_CANCEL
1584 sigusr2
= (int *) pthread_getspecific (signal_thread_key
);
1589 fd
= accept (sockfd
, (struct sockaddr
*) &raddr
, &slen
);
1592 if (errno
== EMFILE
|| errno
== ENFILE
)
1593 log_write ("accept(): %s",
1594 pwmd_strerror (gpg_error_from_errno (errno
)));
1595 else if (errno
!= EAGAIN
)
1597 if (!quit
) // probably EBADF
1598 log_write ("accept(): %s", strerror (errno
));
1603 #ifndef HAVE_PTHREAD_CANCEL
1604 select (0, NULL
, NULL
, NULL
, &tv
);
1615 inet_ntop (raddr
.ss_family
, get_in_addr ((struct sockaddr
*) &raddr
),
1617 (void) init_client (fd
, s
);
1618 n
= config_get_integer ("global", "tcp_wait");
1621 tv
.tv_sec
= (n
* 100000) / 100000;
1622 tv
.tv_usec
= (n
* 100000) % 100000;
1623 select (0, NULL
, NULL
, NULL
, &tv
);
1631 start_stop_tls_with_protocol (int ipv6
, int term
)
1633 struct addrinfo hints
, *servinfo
, *p
;
1634 int port
= config_get_integer ("global", "tcp_port");
1638 int *fd
= ipv6
? &tls6_fd
: &tls_fd
;
1640 if (term
|| config_get_boolean ("global", "enable_tcp") == 0)
1646 #ifdef HAVE_PTHREAD_CANCEL
1647 pthread_cancel (tls6_tid
);
1649 pthread_kill (tls6_tid
, SIGUSR2
);
1651 pthread_join (tls6_tid
, NULL
);
1654 shutdown (tls6_fd
, SHUT_RDWR
);
1664 #ifdef HAVE_PTHREAD_CANCEL
1665 pthread_cancel (tls_tid
);
1667 pthread_kill (tls_tid
, SIGUSR2
);
1669 pthread_join (tls_tid
, NULL
);
1672 shutdown (tls_fd
, SHUT_RDWR
);
1678 /* A client may still be connected. */
1679 if (!quit
&& x509_cred
!= NULL
)
1680 tls_deinit_params ();
1685 if ((ipv6
&& tls6_fd
!= -1) || (!ipv6
&& tls_fd
!= -1))
1688 memset (&hints
, 0, sizeof (hints
));
1689 hints
.ai_family
= ipv6
? AF_INET6
: AF_INET
;
1690 hints
.ai_socktype
= SOCK_STREAM
;
1691 hints
.ai_flags
= AI_PASSIVE
;
1692 snprintf (buf
, sizeof (buf
), "%i", port
);
1694 if ((n
= getaddrinfo (NULL
, buf
, &hints
, &servinfo
)) == -1)
1696 log_write ("getaddrinfo(): %s", gai_strerror (n
));
1700 for (n
= 0, p
= servinfo
; p
!= NULL
; p
= p
->ai_next
)
1704 if ((ipv6
&& p
->ai_family
!= AF_INET6
)
1705 || (!ipv6
&& p
->ai_family
!= AF_INET
))
1708 if ((*fd
= socket (p
->ai_family
, p
->ai_socktype
, p
->ai_protocol
)) == -1)
1710 log_write ("socket(): %s", strerror (errno
));
1714 if (setsockopt (*fd
, SOL_SOCKET
, SO_REUSEADDR
, &r
, sizeof (int)) == -1)
1716 log_write ("setsockopt(): %s",
1717 pwmd_strerror (gpg_error_from_errno (errno
)));
1718 freeaddrinfo (servinfo
);
1722 if (bind (*fd
, p
->ai_addr
, p
->ai_addrlen
) == -1)
1725 log_write ("bind(): %s",
1726 pwmd_strerror (gpg_error_from_errno (errno
)));
1734 freeaddrinfo (servinfo
);
1739 #if HAVE_DECL_SO_BINDTODEVICE != 0
1740 char *tmp
= config_get_string ("global", "tcp_interface");
1741 if (tmp
&& setsockopt (*fd
, SOL_SOCKET
, SO_BINDTODEVICE
, tmp
,
1742 strlen (tmp
)) == -1)
1744 log_write ("setsockopt(): %s",
1745 pwmd_strerror (gpg_error_from_errno (errno
)));
1753 if (x509_cred
== NULL
)
1755 char *tmp
= config_get_string ("global", "tls_dh_level");
1757 rc
= tls_init_params (tmp
);
1763 if (listen (*fd
, 0) == -1)
1765 log_write ("listen(): %s", strerror (errno
));
1770 rc
= create_thread (tcp_accept_thread
, fd
, &tls6_tid
, 0);
1772 rc
= create_thread (tcp_accept_thread
, fd
, &tls_tid
, 0);
1776 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1777 pwmd_strerror (rc
));
1789 start_stop_tls_with_protocol (0, 1);
1802 start_stop_tls (int term
)
1804 char *s
= config_get_string ("global", "tcp_bind");
1810 if (!strcmp (s
, "any"))
1812 b
= start_stop_tls_with_protocol (0, term
);
1814 b
= start_stop_tls_with_protocol (1, term
);
1816 else if (!strcmp (s
, "ipv4"))
1817 b
= start_stop_tls_with_protocol (0, term
);
1818 else if (!strcmp (s
, "ipv6"))
1819 b
= start_stop_tls_with_protocol (1, term
);
1829 accept_thread (void *arg
)
1831 int sockfd
= *(int *) arg
;
1832 #ifndef HAVE_PTHREAD_CANCEL
1833 int *n
= xmalloc (sizeof (int));
1836 pthread_setspecific (signal_thread_key
, n
);
1838 fcntl (sockfd
, F_SETFL
, O_NONBLOCK
);
1841 #ifdef HAVE_PR_SET_NAME
1842 prctl (PR_SET_NAME
, "accept");
1844 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1848 socklen_t slen
= sizeof (struct sockaddr_un
);
1849 struct sockaddr_un raddr
;
1851 #ifndef HAVE_PTHREAD_CANCEL
1852 struct timeval tv
= { 0, ACCEPT_TIMEOUT
};
1853 int *sigusr2
= (int *) pthread_getspecific (signal_thread_key
);
1859 fd
= accept (sockfd
, (struct sockaddr
*) &raddr
, &slen
);
1862 if (errno
== EMFILE
|| errno
== ENFILE
)
1863 log_write ("accept(): %s",
1864 pwmd_strerror (gpg_error_from_errno (errno
)));
1865 else if (errno
!= EAGAIN
)
1867 if (!quit
) // probably EBADF
1868 log_write ("accept(): %s",
1869 pwmd_strerror (gpg_error_from_errno (errno
)));
1874 #ifndef HAVE_PTHREAD_CANCEL
1875 select (0, NULL
, NULL
, NULL
, &tv
);
1880 (void) init_client (fd
, NULL
);
1883 /* Just in case accept() failed for some reason other than EBADF */
1889 cache_timer_thread (void *arg
)
1891 #ifndef HAVE_PTHREAD_CANCEL
1892 int *n
= xmalloc (sizeof (int));
1895 pthread_setspecific (signal_thread_key
, n
);
1899 #ifdef HAVE_PR_SET_NAME
1900 prctl (PR_SET_NAME
, "cache timer");
1902 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1906 struct timeval tv
= { 1, 0 };
1907 #ifndef HAVE_PTHREAD_CANCEL
1910 n
= (int *) pthread_getspecific (signal_thread_key
);
1915 select (0, NULL
, NULL
, NULL
, &tv
);
1916 cache_adjust_timeout ();
1923 signal_loop (sigset_t sigset
)
1932 sigwait (&sigset
, &sig
);
1935 log_write (_("caught signal %i (%s)"), sig
, strsignal (sig
));
1940 pthread_cond_signal (&rcfile_cond
);
1943 log_write (_("clearing file cache"));
1945 send_status_all (STATUS_CACHE
, NULL
);
1964 log_write (_ ("Caught signal %i (%s). Exiting."), sig
, strsignal (sig
));
1965 #ifdef HAVE_BACKTRACE
1966 BACKTRACE (__FUNCTION__
);
1972 waiting_for_exit (void *arg
)
1975 #ifndef HAVE_PTHREAD_CANCEL
1976 int *n
= xmalloc (sizeof (int));
1979 pthread_setspecific (signal_thread_key
, n
);
1983 #ifdef HAVE_PR_SET_NAME
1984 prctl (PR_SET_NAME
, "exiting");
1986 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1987 log_write (_("waiting for all clients to disconnect"));
1988 MUTEX_LOCK (&quit_mutex
);
1989 pthread_cleanup_push (cleanup_mutex_cb
, &quit_mutex
);
1996 MUTEX_LOCK (&cn_mutex
);
1997 n
= slist_length (cn_thread_list
);
1998 MUTEX_UNLOCK (&cn_mutex
);
2002 #ifndef HAVE_PTHREAD_CANCEL
2003 int *s
= (int *) pthread_getspecific (signal_thread_key
);
2010 log_write (_("%i clients remain"), n
);
2014 INIT_TIMESPEC (SIG_TIMEOUT
, ts
);
2015 pthread_cond_timedwait (&quit_cond
, &quit_mutex
, &ts
);
2018 kill (getpid (), SIGQUIT
);
2019 pthread_cleanup_pop (1);
2024 server_loop (int sockfd
, char **socketpath
)
2026 pthread_t accept_tid
;
2027 pthread_t cache_timeout_tid
;
2028 int cancel_timeout_thread
= 0, cancel_accept_thread
= 0;
2029 int cancel_keepalive_thread
= 0;
2036 sigemptyset (&sigset
);
2039 sigaddset (&sigset
, SIGTERM
);
2040 sigaddset (&sigset
, SIGINT
);
2042 /* Clears the file cache. */
2043 sigaddset (&sigset
, SIGUSR1
);
2045 /* Configuration file reloading. */
2046 sigaddset (&sigset
, SIGHUP
);
2048 /* For exiting cleanly. */
2049 sigaddset (&sigset
, SIGQUIT
);
2051 #ifndef HAVE_PTHREAD_CANCEL
2053 The socket, cache and rcfile threads use this signal when
2054 pthread_cancel() is unavailable. Prevent the main thread from
2055 catching this signal from another process.
2057 sigaddset (&sigset
, SIGUSR2
);
2060 /* When mem.c cannot find a pointer in the list (double free). */
2061 signal (SIGABRT
, catchsig
);
2062 sigaddset (&sigset
, SIGABRT
);
2063 sigprocmask (SIG_BLOCK
, &sigset
, NULL
);
2065 #ifndef HAVE_PTHREAD_CANCEL
2066 /* Remove this signal from the watched signals in signal_loop(). */
2067 sigdelset (&sigset
, SIGUSR2
);
2070 /* Ignored everywhere. When a client disconnects abnormally this signal
2071 * gets raised. It isn't needed though because client_thread() will check
2072 * for rcs even after the client disconnects. */
2073 signal (SIGPIPE
, SIG_IGN
);
2075 /* Can show a backtrace of the stack in the log. */
2076 signal (SIGSEGV
, catchsig
);
2079 /* Needs to be done after the fork(). */
2080 if (!start_stop_tls (0))
2087 pthread_mutex_init (&quit_mutex
, NULL
);
2088 pthread_cond_init (&quit_cond
, NULL
);
2089 char *p
= get_username (getuid());
2090 log_write (_("%s started for user %s"), PACKAGE_STRING
, p
);
2094 if (config_get_boolean ("global", "enable_tcp"))
2095 log_write (_("Listening on %s and TCP port %i"), *socketpath
,
2096 config_get_integer ("global", "tcp_port"));
2098 log_write (_("Listening on %s"), *socketpath
);
2100 log_write (_("Listening on %s"), *socketpath
);
2103 rc
= create_thread (keepalive_thread
, NULL
, &keepalive_tid
, 0);
2106 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2107 pwmd_strerror (rc
));
2111 cancel_keepalive_thread
= 1;
2112 rc
= create_thread (reload_rcfile_thread
, NULL
, &rcfile_tid
, 0);
2115 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2116 pwmd_strerror (rc
));
2120 rc
= create_thread (cache_timer_thread
, NULL
, &cache_timeout_tid
, 0);
2123 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2124 pwmd_strerror (rc
));
2128 cancel_timeout_thread
= 1;
2129 rc
= create_thread (accept_thread
, &sockfd
, &accept_tid
, 0);
2132 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2133 pwmd_strerror (rc
));
2137 cancel_accept_thread
= 1;
2139 signal_loop (sigset
);
2145 * We're out of the main server loop. This happens when a signal was sent
2146 * to terminate the daemon. We'll wait for all clients to disconnect
2147 * before exiting but exit immediately if another termination signal is
2150 if (cancel_accept_thread
)
2152 #ifdef HAVE_PTHREAD_CANCEL
2153 int n
= pthread_cancel (accept_tid
);
2155 int n
= pthread_kill (accept_tid
, SIGUSR2
);
2158 pthread_join (accept_tid
, NULL
);
2164 shutdown (sockfd
, SHUT_RDWR
);
2166 unlink (*socketpath
);
2167 xfree (*socketpath
);
2169 MUTEX_LOCK (&cn_mutex
);
2170 n
= slist_length (cn_thread_list
);
2171 MUTEX_UNLOCK (&cn_mutex
);
2177 rc
= create_thread (waiting_for_exit
, NULL
, &tid
, 0);
2180 if (signal_loop (sigset
))
2182 log_write (_("Received second termination request. Exiting."));
2183 #ifdef HAVE_PTHREAD_CANCEL
2184 pthread_cancel (tid
);
2186 pthread_kill (tid
, SIGUSR2
);
2188 pthread_join (tid
, NULL
);
2192 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2193 pwmd_strerror (rc
));
2196 if (cancel_timeout_thread
)
2198 #ifdef HAVE_PTHREAD_CANCEL
2199 pthread_cancel (cache_timeout_tid
);
2201 pthread_kill (cache_timeout_tid
, SIGUSR2
);
2203 pthread_join (cache_timeout_tid
, NULL
);
2206 if (cancel_keepalive_thread
)
2208 #ifdef HAVE_PTHREAD_CANCEL
2209 pthread_cancel (keepalive_tid
);
2211 pthread_kill (keepalive_tid
, SIGUSR2
);
2213 pthread_join (keepalive_tid
, NULL
);
2216 cleanup_all_clients (0);
2221 pthread_cond_destroy (&quit_cond
);
2222 pthread_mutex_destroy (&quit_mutex
);
2223 return segv
? EXIT_FAILURE
: EXIT_SUCCESS
;;
2230 ("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
2234 /* This is called from cache.c:clear_once(). See
2235 * command.c:clearcache_command() for details about lock checking.
2238 free_cache_data (file_cache_t
* cache
)
2240 gpg_error_t rc
= GPG_ERR_NO_DATA
;
2242 struct client_thread_s
*found
= NULL
;
2249 MUTEX_LOCK (&cn_mutex
);
2250 pthread_cleanup_push (cleanup_mutex_cb
, &cn_mutex
);
2251 t
= slist_length (cn_thread_list
);
2253 for (i
= 0; i
< t
; i
++)
2255 struct client_thread_s
*thd
= slist_nth_data (cn_thread_list
, i
);
2260 if (!memcmp (thd
->cl
->md5file
, cache
->filename
,
2261 sizeof (cache
->filename
)))
2263 if (pthread_equal (pthread_self (), thd
->tid
))
2270 /* Continue trying to find a client who has the same file open and
2271 * also has a lock. */
2272 rc
= cache_lock_mutex (thd
->cl
->ctx
, thd
->cl
->md5file
, -1, 0, -1);
2282 if (self
&& (!rc
|| rc
== GPG_ERR_NO_DATA
))
2283 rc
= cache_lock_mutex (found
->cl
->ctx
, found
->cl
->md5file
, -1, 0, -1);
2285 if (exiting
|| !rc
|| rc
== GPG_ERR_NO_DATA
)
2287 free_cache_data_once (cache
->data
);
2289 cache
->defer_clear
= 0;
2290 cache
->timeout
= -1;
2293 cache_unlock_mutex (found
->cl
->md5file
, 0);
2299 cache
->defer_clear
= 1;
2301 pthread_cleanup_pop (1);
2307 convert_v2_datafile (const char *filename
, const char *cipher
,
2308 const char *keyfile
, const char *keygrip
,
2309 const char *sign_keygrip
, int nopass
,
2310 const char *outfile
, const char *keyparam
,
2311 uint64_t iterations
)
2316 struct crypto_s
*crypto
= NULL
;
2322 if (outfile
[0] == '-' && outfile
[1] == 0)
2325 log_write (_("Converting version 2 data file \"%s\" ..."), filename
);
2326 if (access (filename
, R_OK
) == -1)
2328 log_write ("%s: %s", filename
,
2329 pwmd_strerror (gpg_error_from_errno (errno
)));
2335 log_write (_("Using passphrase file \"%s\" for decryption ..."),
2337 if (access (keyfile
, R_OK
) == -1)
2339 log_write ("%s: %s", keyfile
,
2340 pwmd_strerror (gpg_error_from_errno (errno
)));
2345 rc
= read_v2_datafile (filename
, keyfile
, &data
, &datalen
, &ver
, &algo
);
2348 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
2354 algo
= cipher_string_to_gcrypt (cipher
);
2357 rc
= GPG_ERR_CIPHER_ALGO
;
2366 rc
= parse_doc (data
, datalen
, &doc
);
2370 rc
= convert_pre_212_elements (doc
);
2375 xmlDocDumpFormatMemory (doc
, (xmlChar
**) & data
, (int *) &datalen
,
2378 rc
= GPG_ERR_ENOMEM
;
2386 rc
= init_client_crypto (&crypto
);
2389 memcpy (&crypto
->save
.hdr
, &crypto
->hdr
, sizeof (file_header_t
));
2390 crypto
->save
.hdr
.flags
= set_cipher_flag (crypto
->save
.hdr
.flags
, algo
);
2391 crypto
->save
.hdr
.s2k_count
= iterations
;
2395 rc
= export_common (NULL
, 0, crypto
, data
, datalen
, outfile
, keyfile
,
2396 &key
, &keylen
, 0, 0, nopass
);
2401 rc
= agent_set_pinentry_options (crypto
->agent
);
2403 rc
= agent_export_common (crypto
, keygrip
, sign_keygrip
, nopass
,
2404 data
, datalen
, outfile
, keyparam
,
2405 no_passphrase_file
? NULL
: keyfile
);
2409 log_write (_("Output written to \"%s\"."),
2410 outfile
? outfile
: "<stdout>");
2420 cleanup_crypto (&crypto
);
2423 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
2428 usage (const char *pn
, int status
)
2430 FILE *fp
= status
== EXIT_FAILURE
? stderr
: stdout
;
2432 fprintf (fp
, _("Usage: %s [OPTIONS] [file1] [...]\n"
2433 " -f, --rcfile=filename load the specfied configuration file\n"
2434 " (~/.pwmd/config)\n"
2435 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2436 " --kill terminate an existing instance of pwmd\n"
2438 " --use-agent[=integer] enable/disable use of gpg-agent\n"
2440 " -n, --no-fork run as a foreground process\n"
2441 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2442 " --ignore, --force ignore file errors during startup\n"
2443 " --debug-level=keywords log protocol output (see manual for details)\n"
2444 " -o, --outfile=filename output file when importing or converting\n"
2445 " -C, --convert=filename convert a version 2 data file to version 3\n"
2446 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2447 " -k, --passphrase-file=file for use when importing or converting\n"
2448 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2450 " --no-passphrase when importing or converting\n"
2451 " --keygrip=hex public key to use when encrypting\n"
2452 " --sign-keygrip=hex private key to use when signing\n"
2453 " --keyparam=s-exp custom key parameters to use (RSA-2048)\n"
2454 " --cipher=string encryption cipher (aes256)\n"
2455 " --cipher-iterations=N cipher iteration count (alias for --s2k-count)\n"
2456 " --s2k-count=N hash iteration count (>65536, calibrated)\n"
2457 " --help this help text\n"
2458 " --version show version and compile time features\n"),
2464 unlink_stale_socket (const char *sock
, const char *pidfile
)
2466 log_write (_ ("removing stale socket %s"), sock
);
2472 test_pidfile (const char *path
, const char *sock
, char *buf
, size_t buflen
,
2473 char **pidfile
, int create
, mode_t mode
, int terminate
)
2481 snprintf (buf
, buflen
, "%s/%s.pid", homedir
, sock
);
2482 *pidfile
= str_dup (buf
);
2483 fd
= open (buf
, O_RDONLY
);
2486 fd
= open (*pidfile
, O_CREAT
|O_WRONLY
|O_TRUNC
, mode
);
2490 if (!create
&& errno
!= ENOENT
)
2492 log_write ("%s: %s", buf
, pwmd_strerror (errno
));
2497 else if (!create
&& !terminate
)
2500 log_write ("%s: %s", *pidfile
, strerror (errno
));
2506 snprintf (buf
, buflen
, "%i", getpid ());
2507 write (fd
, buf
, strlen (buf
));
2512 len
= read (fd
, buf
, buflen
);
2516 unlink_stale_socket (path
, *pidfile
);
2520 if (sscanf (buf
, "%5i", &pid
) != 1 || pid
== 0)
2524 unlink_stale_socket (path
, *pidfile
);
2529 if (kill (pid
, 0) == -1)
2531 unlink_stale_socket (path
, *pidfile
);
2537 if (kill (pid
, SIGTERM
) == -1)
2538 log_write ("%s: %s", path
, pwmd_strerror (errno
));
2541 log_write (_ ("an instance for socket %s is already running"), path
);
2549 main (int argc
, char *argv
[])
2552 struct sockaddr_un addr
;
2554 char *socketpath
= NULL
, *socketdir
, *socketname
= NULL
;
2555 char *socketarg
= NULL
;
2556 char *datadir
= NULL
;
2557 char *pidfile
= NULL
;
2561 char **cache_push
= NULL
;
2562 char *import
= NULL
, *keygrip
= NULL
, *sign_keygrip
= NULL
;
2563 char *keyparam
= NULL
;
2564 int estatus
= EXIT_FAILURE
;
2566 char *outfile
= NULL
;
2569 int show_version
= 0;
2571 int no_passphrase
= 0;
2573 char *convertfile
= NULL
;
2574 char *cipher
= NULL
;
2575 char *keyfile
= NULL
;
2576 uint64_t s2k_count
= 0;
2578 char *debug_level_opt
= NULL
;
2581 /* Must maintain the same order as longopts[] */
2584 OPT_VERSION
, OPT_HELP
,
2588 OPT_DEBUG_LEVEL
, OPT_HOMEDIR
, OPT_NO_FORK
, OPT_DISABLE_DUMP
,
2589 OPT_IGNORE
, OPT_FORCE
, OPT_RCFILE
, OPT_CONVERT
,
2590 OPT_PASSPHRASE_FILE
, OPT_IMPORT
, OPT_OUTFILE
,
2591 OPT_NO_PASSPHRASE_FILE
, OPT_KEYGRIP
, OPT_SIGN_KEYGRIP
,
2592 OPT_KEYPARAM
, OPT_CIPHER
, OPT_ITERATIONS
, OPT_S2K_COUNT
,
2593 OPT_NO_PASSPHRASE
, OPT_KILL
2595 const char *optstring
= "nf:C:k:I:o:";
2596 const struct option longopts
[] = {
2597 {"version", no_argument
, 0, 0},
2598 {"help", no_argument
, 0, 0},
2600 {"use-agent", optional_argument
, 0, 0},
2602 {"debug-level", required_argument
, 0, 0},
2603 {"homedir", required_argument
, 0, 0},
2604 {"no-fork", no_argument
, 0, 'n'},
2605 {"disable_dump", no_argument
, 0, 0},
2606 {"ignore", no_argument
, 0, 0},
2607 {"force", no_argument
, 0, 0},
2608 {"rcfile", required_argument
, 0, 'f'},
2609 {"convert", required_argument
, 0, 'C'},
2610 {"passphrase-file", required_argument
, 0, 'k'},
2611 {"import", required_argument
, 0, 'I'},
2612 {"outfile", required_argument
, 0, 'o'},
2613 {"no-passphrase-file", no_argument
, 0, 0},
2614 {"keygrip", required_argument
, 0, 0},
2615 {"sign-keygrip", required_argument
, 0, 0},
2616 {"keyparam", required_argument
, 0, 0},
2617 {"cipher", required_argument
, 0, 0},
2618 {"cipher-iterations", required_argument
, 0, 0},
2619 {"s2k-count", required_argument
, 0, 0},
2620 {"no-passphrase", no_argument
, 0, 0},
2621 {"kill", no_argument
, 0, 0},
2628 #ifdef HAVE_SETRLIMIT
2631 rl
.rlim_cur
= rl
.rlim_max
= 0;
2633 if (setrlimit (RLIMIT_CORE
, &rl
) != 0)
2634 err (EXIT_FAILURE
, "setrlimit()");
2637 #ifdef HAVE_PR_SET_DUMPABLE
2638 prctl (PR_SET_DUMPABLE
, 0);
2643 setlocale (LC_ALL
, "");
2644 bindtextdomain ("pwmd", LOCALEDIR
);
2645 textdomain ("pwmd");
2653 if (setup_crypto ())
2654 exit (EXIT_FAILURE
);
2657 gnutls_global_init ();
2658 gnutls_global_set_log_level (1);
2659 gnutls_global_set_log_function (tls_log
);
2660 gnutls_global_set_audit_log_function (tls_audit_log
);
2664 xmlMemSetup (xfree
, xmalloc
, xrealloc
, str_dup
);
2672 while ((opt
= getopt_long (argc
, argv
, optstring
, longopts
, &optindex
))
2681 convertfile
= optarg
;
2696 rcfile
= str_dup (optarg
);
2699 usage (argv
[0], EXIT_FAILURE
);
2712 use_agent
= optarg
&& *optarg
? atoi (optarg
) : 1;
2713 if (use_agent
< 0 || use_agent
> 1)
2717 case OPT_DEBUG_LEVEL
:
2718 debug_level_opt
= optarg
;
2721 homedir
= str_dup (optarg
);
2726 case OPT_DISABLE_DUMP
:
2734 rcfile
= str_dup (optarg
);
2737 convertfile
= optarg
;
2739 case OPT_PASSPHRASE_FILE
:
2748 case OPT_NO_PASSPHRASE_FILE
:
2749 no_passphrase_file
= 1;
2754 case OPT_SIGN_KEYGRIP
:
2755 sign_keygrip
= optarg
;
2763 case OPT_ITERATIONS
:
2765 s2k_count
= strtoull (optarg
, NULL
, 10);
2767 case OPT_NO_PASSPHRASE
:
2782 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015\n"
2784 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2785 "Compile time features:\n%s"), PACKAGE_STRING
,
2788 "+PWMD_HOMEDIR=" PWMD_HOMEDIR
"\n"
2821 exit (EXIT_SUCCESS
);
2826 homedir
= str_dup(PWMD_HOMEDIR
);
2828 homedir
= str_asprintf ("%s/.pwmd", get_home_dir());
2831 if (mkdir (homedir
, 0700) == -1 && errno
!= EEXIST
)
2832 err (EXIT_FAILURE
, "%s", homedir
);
2834 snprintf (buf
, sizeof (buf
), "%s/data", homedir
);
2835 if (mkdir (buf
, 0700) == -1 && errno
!= EEXIST
)
2836 err (EXIT_FAILURE
, "%s", buf
);
2838 datadir
= str_dup (buf
);
2839 pthread_mutexattr_t attr
;
2840 pthread_mutexattr_init (&attr
);
2841 pthread_mutexattr_settype (&attr
, PTHREAD_MUTEX_RECURSIVE
);
2842 pthread_mutex_init (&rcfile_mutex
, &attr
);
2843 pthread_cond_init (&rcfile_cond
, NULL
);
2844 pthread_mutex_init (&cn_mutex
, &attr
);
2845 pthread_mutexattr_destroy (&attr
);
2846 pthread_key_create (&last_error_key
, free_key
);
2847 #ifndef HAVE_PTHREAD_CANCEL
2848 pthread_key_create (&signal_thread_key
, free_key
);
2852 rcfile
= str_asprintf ("%s/config", homedir
);
2854 global_config
= config_parse (rcfile
, 0);
2856 exit (EXIT_FAILURE
);
2859 if (use_agent
== -1)
2860 use_agent
= config_get_boolean ("global", "use_agent");
2865 if (debug_level_opt
)
2866 debug_level
= str_split (debug_level_opt
, ",", 0);
2868 x
= config_get_int_param (global_config
, "global", "priority", &exists
);
2869 if (exists
&& x
!= atoi(INVALID_PRIORITY
))
2872 if (setpriority (PRIO_PROCESS
, 0, x
) == -1)
2874 log_write ("setpriority(): %s",
2875 pwmd_strerror (gpg_error_from_errno (errno
)));
2879 #ifdef HAVE_MLOCKALL
2880 if (disable_mlock
== 0 && mlockall (MCL_CURRENT
| MCL_FUTURE
) == -1)
2882 log_write ("mlockall(): %s",
2883 pwmd_strerror (gpg_error_from_errno (errno
)));
2888 rc
= cache_init (free_cache_data
);
2891 log_write ("pwmd: ERR %i: %s", rc
,
2892 gpg_err_code (rc
) == GPG_ERR_UNKNOWN_VERSION
2893 ? _("incompatible gpg-agent version: 2.1.0 or later required")
2894 : pwmd_strerror (rc
));
2899 s2k_count
= config_get_ulonglong (NULL
, "s2k_count");
2903 if (!outfile
|| !*outfile
|| argc
!= optind
)
2904 usage (argv
[0], EXIT_FAILURE
);
2906 estatus
= convert_v2_datafile (convertfile
, cipher
, keyfile
, keygrip
,
2907 sign_keygrip
, no_passphrase
, outfile
,
2908 keyparam
, s2k_count
);
2909 config_free (global_config
);
2916 if (!outfile
|| !*outfile
|| argc
!= optind
)
2917 usage (argv
[0], EXIT_FAILURE
);
2919 if (outfile
&& outfile
[0] == '-' && outfile
[1] == 0)
2922 estatus
= xml_import (import
, outfile
, keygrip
, sign_keygrip
, keyfile
,
2923 no_passphrase
, cipher
, keyparam
, s2k_count
);
2924 config_free (global_config
);
2929 p
= config_get_string ("global", "socket_path");
2931 p
= str_asprintf ("%s/socket", homedir
);
2933 socketarg
= expand_homedir (p
);
2937 disable_list_and_dump
= config_get_boolean ("global",
2938 "disable_list_and_dump");
2940 disable_list_and_dump
= secure
;
2942 cache_push
= config_get_list ("global", "cache_push");
2944 while (optind
< argc
)
2946 if (strv_printf (&cache_push
, "%s", argv
[optind
++]) == 0)
2947 errx (EXIT_FAILURE
, "%s", pwmd_strerror (GPG_ERR_ENOMEM
));
2950 if (strchr (socketarg
, '/') == NULL
)
2952 socketdir
= getcwd (buf
, sizeof (buf
));
2953 socketname
= str_dup (socketarg
);
2954 socketpath
= str_asprintf ("%s/%s", socketdir
, socketname
);
2958 socketname
= str_dup (strrchr (socketarg
, '/'));
2960 socketarg
[strlen (socketarg
) - strlen (socketname
) - 1] = 0;
2961 socketdir
= str_dup (socketarg
);
2962 socketpath
= str_asprintf ("%s/%s", socketdir
, socketname
);
2965 if (chdir (datadir
))
2967 log_write ("%s: %s", datadir
,
2968 pwmd_strerror (gpg_error_from_errno (errno
)));
2969 unlink (socketpath
);
2973 x
= test_pidfile (socketpath
, socketname
, buf
, sizeof(buf
), &pidfile
, 0,
2975 if (!terminate
&& x
)
2979 estatus
= x
!= 1 ? EXIT_FAILURE
: EXIT_SUCCESS
;
2984 * bind() doesn't like the full pathname of the socket or any non alphanum
2985 * characters so change to the directory where the socket is wanted then
2986 * create it then change to datadir.
2988 if (chdir (socketdir
))
2990 log_write ("%s: %s", socketdir
,
2991 pwmd_strerror (gpg_error_from_errno (errno
)));
2997 if ((sockfd
= socket (PF_UNIX
, SOCK_STREAM
, 0)) == -1)
2999 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
3003 addr
.sun_family
= AF_UNIX
;
3004 snprintf (addr
.sun_path
, sizeof (addr
.sun_path
), "%s", socketname
);
3006 if (bind (sockfd
, (struct sockaddr
*) &addr
, sizeof (struct sockaddr
)) ==
3009 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
3011 if (errno
== EADDRINUSE
)
3014 log_write (_("Either there is another pwmd running or '%s' is a \n"
3015 "stale socket. Please remove it manually."), socketpath
);
3022 char *t
= config_get_string ("global", "socket_perms");
3027 mode
= strtol (t
, NULL
, 8);
3031 if (chmod (socketname
, mode
) == -1)
3033 log_write ("%s: %s", socketname
,
3034 pwmd_strerror (gpg_error_from_errno (errno
)));
3044 xfree (--socketname
);
3046 if (chdir (datadir
))
3048 log_write ("%s: %s", datadir
,
3049 pwmd_strerror (gpg_error_from_errno (errno
)));
3057 * Set the cache entry for a file. Prompts for the password.
3061 struct crypto_s
*crypto
= NULL
;
3062 gpg_error_t rc
= init_client_crypto (&crypto
);
3066 estatus
= EXIT_FAILURE
;
3073 rc
= agent_set_pinentry_options (crypto
->agent
);
3076 estatus
= EXIT_FAILURE
;
3082 for (opt
= 0; cache_push
[opt
]; opt
++)
3084 if (!do_cache_push (cache_push
[opt
], crypto
) && !force
)
3086 strv_free (cache_push
);
3088 estatus
= EXIT_FAILURE
;
3089 cleanup_crypto (&crypto
);
3093 cleanup_crypto_stage1 (crypto
);
3098 (void) kill_scd (crypto
->agent
);
3101 cleanup_crypto (&crypto
);
3102 strv_free (cache_push
);
3103 log_write (!nofork
? _("Done. Daemonizing...") :
3104 _("Done. Waiting for connections..."));
3107 config_clear_keys ();
3109 if (listen (sockfd
, 0) == -1)
3111 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
3120 log_write ("fork(): %s",
3121 pwmd_strerror (gpg_error_from_errno (errno
)));
3130 _exit (EXIT_SUCCESS
);
3134 (void)test_pidfile (socketpath
, socketname
, buf
, sizeof(buf
), &pidfile
, 1,
3137 pthread_key_create (&thread_name_key
, free_key
);
3138 pthread_setspecific (thread_name_key
, str_dup ("main"));
3139 estatus
= server_loop (sockfd
, &socketpath
);
3142 if (socketpath
&& do_unlink
)
3144 unlink (socketpath
);
3150 gnutls_global_deinit ();
3154 #ifdef HAVE_PTHREAD_CANCEL
3155 pthread_cancel (rcfile_tid
);
3157 pthread_kill (rcfile_tid
, SIGUSR2
);
3158 pthread_cond_signal (&rcfile_cond
);
3160 pthread_join (rcfile_tid
, NULL
);
3163 pthread_cond_destroy (&rcfile_cond
);
3164 pthread_mutex_destroy (&rcfile_mutex
);
3165 pthread_key_delete (last_error_key
);
3166 #ifndef HAVE_PTHREAD_CANCEL
3167 pthread_key_delete (signal_thread_key
);
3171 config_free (global_config
);
3173 free_invoking_users (invoking_users
);
3175 xfree (home_directory
);
3177 xmlCleanupParser ();
3178 xmlCleanupGlobals ();
3184 if (estatus
== EXIT_SUCCESS
&& !terminate
)
3185 log_write (_("pwmd exiting normally"));
3187 pthread_key_delete (thread_name_key
);
3189 #if defined(DEBUG) && !defined(MEM_DEBUG)