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>
63 #ifdef HAVE_GETOPT_LONG
68 #include "getopt_long.h"
71 #ifdef HAVE_PR_SET_NAME
72 #include <sys/prctl.h>
75 #include "pwmd-error.h"
78 #include "util-misc.h"
84 #include "util-string.h"
91 /* In tenths of a second. */
94 /* For (tcp_)accept_thread (usec). */
95 #define ACCEPT_TIMEOUT 30000
102 static pthread_cond_t quit_cond
;
103 static pthread_mutex_t quit_mutex
;
104 static int no_passphrase_file
= 0;
105 static pthread_t keepalive_tid
;
108 #ifndef HAVE_PTHREAD_CANCEL
109 static pthread_key_t signal_thread_key
;
115 static pthread_t tls_tid
;
116 static pthread_t tls6_tid
;
117 static int spawned_tls
;
118 static int spawned_tls6
;
120 static int start_stop_tls (int term
);
123 static int do_cache_push (const char *filename
, struct crypto_s
*crypto
);
124 static int signal_loop (sigset_t sigset
);
126 #ifndef HAVE_PTHREAD_CANCEL
127 #define INIT_THREAD_SIGNAL do { \
128 struct sigaction act; \
130 sigemptyset (&sigset); \
131 sigaddset (&sigset, SIGUSR2); \
132 pthread_sigmask (SIG_UNBLOCK, &sigset, NULL); \
133 memset (&act, 0, sizeof(act)); \
134 act.sa_flags = SA_SIGINFO; \
135 act.sa_mask = sigset; \
136 act.sa_sigaction = catch_thread_signal; \
137 sigaction (SIGUSR2, &act, NULL); \
141 catch_thread_signal (int sig
, siginfo_t
*info
, void *ctx
)
143 int *n
= (int *) pthread_getspecific (signal_thread_key
);
146 pthread_setspecific (signal_thread_key
, n
);
151 cache_push_from_rcfile ()
153 struct crypto_s
*crypto
= NULL
;
155 gpg_error_t rc
= init_client_crypto (&crypto
);
159 log_write ("%s: %s", __FUNCTION__
, pwmd_strerror (rc
));
166 rc
= set_agent_option (crypto
->agent
, "pinentry-mode", "error");
169 log_write ("%s: %s", __FUNCTION__
, pwmd_strerror (rc
));
175 cache_push
= config_get_list ("global", "cache_push");
180 for (p
= cache_push
; *p
; p
++)
182 (void) do_cache_push (*p
, crypto
);
183 cleanup_crypto_stage1 (crypto
);
186 strv_free (cache_push
);
190 (void) kill_scd (crypto
->agent
);
192 cleanup_crypto (&crypto
);
198 int n
= config_get_boolean ("global", "enable_logging");
202 char *p
= config_get_string ("global", "log_path");
204 if (!p
|| (logfile
&& p
&& log_fd
!= -1 && strcmp(p
, logfile
)))
215 logfile
= expand_homedir (p
);
228 log_syslog
= config_get_boolean ("global", "syslog");
230 openlog ("pwmd", LOG_NDELAY
| LOG_PID
, LOG_DAEMON
);
234 reload_rcfile_thread (void *arg
)
236 #ifndef HAVE_PTHREAD_CANCEL
237 int *n
= xmalloc (sizeof (int));
240 pthread_setspecific (signal_thread_key
, n
);
244 #ifdef HAVE_PR_SET_NAME
245 prctl (PR_SET_NAME
, "reload rcfile");
247 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
248 MUTEX_LOCK (&rcfile_mutex
);
249 pthread_cleanup_push (cleanup_mutex_cb
, &rcfile_mutex
);
253 struct slist_s
*keep
= NULL
;
254 struct slist_s
*config
;
255 int b
= disable_list_and_dump
;
257 pthread_cond_wait (&rcfile_cond
, &rcfile_mutex
);
258 #ifndef HAVE_PTHREAD_CANCEL
259 int *cancel
= (int *) pthread_getspecific (signal_thread_key
);
264 pthread_cleanup_push (cleanup_mutex_cb
, &rcfile_mutex
);
265 keep
= config_keep_save ();
266 log_write (_("reloading configuration file '%s'"), rcfile
);
268 config
= config_parse (rcfile
, 1);
271 config_free (global_config
);
272 global_config
= config
;
274 cache_push_from_rcfile ();
275 config_clear_keys ();
278 config_keep_restore (keep
);
279 disable_list_and_dump
= !disable_list_and_dump
? b
: 1;
282 /* Kill existing listening threads since the configured listening
283 * protocols may have changed. */
287 pthread_cleanup_pop (0);
290 pthread_cleanup_pop (1);
295 send_error (assuan_context_t ctx
, gpg_error_t e
)
297 struct client_s
*client
= assuan_get_pointer (ctx
);
299 if (gpg_err_source (e
) == GPG_ERR_SOURCE_UNKNOWN
)
306 return assuan_process_done (ctx
, 0);
310 log_write ("ERR %i: %s", e
, pwmd_strerror (e
));
314 if (client
&& client
->xml_error
)
316 log_write ("%s", client
->xml_error
->message
);
317 xfree (client
->last_error
);
318 client
->last_error
= NULL
;
319 if (client
->xml_error
->message
)
320 client
->last_error
= str_dup (client
->xml_error
->message
);
322 e
= assuan_process_done (ctx
,
323 assuan_set_error (ctx
, e
,
324 client
->xml_error
->message
? client
->xml_error
->message
: NULL
));
325 xmlResetLastError ();
326 xmlResetError (client
->xml_error
);
327 xfree (client
->xml_error
);
328 client
->xml_error
= NULL
;
332 return assuan_process_done (ctx
,
333 assuan_set_error (ctx
, e
, pwmd_strerror (e
)));
337 assuan_log_cb (assuan_context_t ctx
, void *data
, unsigned cat
,
340 static pthread_mutex_t m
= PTHREAD_MUTEX_INITIALIZER
;
344 pthread_mutex_lock (&m
);
345 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock
, &m
);
346 t
= strv_length (debug_level
);
348 for (i
= 0; i
< t
; i
++)
350 if (!strcasecmp (debug_level
[i
], (char *) "init")
351 && cat
== ASSUAN_LOG_INIT
)
357 if (!strcasecmp (debug_level
[i
], (char *) "ctx")
358 && cat
== ASSUAN_LOG_CTX
)
364 if (!strcasecmp (debug_level
[i
], (char *) "engine")
365 && cat
== ASSUAN_LOG_ENGINE
)
371 if (!strcasecmp (debug_level
[i
], (char *) "data")
372 && cat
== ASSUAN_LOG_DATA
)
378 if (!strcasecmp (debug_level
[i
], (char *) "sysio")
379 && cat
== ASSUAN_LOG_SYSIO
)
385 if (!strcasecmp (debug_level
[i
], (char *) "control")
386 && cat
== ASSUAN_LOG_CONTROL
)
400 open (logfile
, O_WRONLY
| O_CREAT
| O_APPEND
, 0600)) == -1)
401 warn ("%s", logfile
);
404 pthread_cleanup_push (cleanup_fd_cb
, &fd
);
405 write (fd
, msg
, strlen (msg
));
406 pthread_cleanup_pop (1);
412 fprintf (stderr
, "%s%s", data
? (char *) data
: "", msg
);
417 pthread_cleanup_pop (1);
422 log_write (const char *fmt
, ...)
428 pthread_t tid
= pthread_self ();
429 static pthread_mutex_t m
= PTHREAD_MUTEX_INITIALIZER
;
431 if ((!logfile
&& !isatty (STDERR_FILENO
) && !log_syslog
) || !fmt
)
434 pthread_mutex_lock (&m
);
435 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock
, &m
);
437 if (!cmdline
&& logfile
&& log_fd
== -1)
439 log_fd
= open (logfile
, O_WRONLY
| O_CREAT
| O_APPEND
, 0600);
441 warn ("%s", logfile
);
446 if (str_vasprintf (&args
, fmt
, ap
) != -1)
450 pthread_cleanup_push (xfree
, args
);
451 fprintf (stderr
, "pwmd: %s\n", args
);
453 pthread_cleanup_pop (1);
457 char *name
= pthread_getspecific (thread_name_key
);
460 pthread_cleanup_push (xfree
, args
);
461 snprintf (buf
, sizeof (buf
), "%s(%p): ", name
? name
: _("unknown"),
465 if (!cmdline
&& log_syslog
&& !nofork
)
466 syslog (LOG_INFO
, "%s%s", name
, args
);
469 struct tm
*tm
= localtime (&now
);
471 strftime (tbuf
, sizeof (tbuf
), "%b %d %Y %H:%M:%S ", tm
);
472 tbuf
[sizeof (tbuf
) - 1] = 0;
474 if (args
[strlen (args
) - 1] == '\n')
475 args
[strlen (args
) - 1] = 0;
477 line
= str_asprintf ("%s %i %s%s\n", tbuf
, getpid (), name
,
479 pthread_cleanup_pop (1);
482 pthread_cleanup_push (xfree
, line
);
483 if (logfile
&& log_fd
!= -1)
485 write (log_fd
, line
, strlen (line
));
491 fprintf (stdout
, "%s", line
);
495 pthread_cleanup_pop (1);
501 pthread_cleanup_pop (0);
503 if (log_fd
!= -1 && log_keepopen
<= 0)
509 pthread_mutex_unlock (&m
);
515 if (!gcry_check_version (GCRYPT_VERSION
))
517 fprintf (stderr
, _("gcry_check_version(): Incompatible libgcrypt. "
518 "Wanted %s, got %s.\n"), GCRYPT_VERSION
,
519 gcry_check_version (NULL
));
520 return GPG_ERR_UNKNOWN_VERSION
;
523 gcry_set_allocation_handler (xmalloc
, xmalloc
, NULL
, xrealloc
, xfree
);
528 do_validate_peer (assuan_context_t ctx
, const char *section
,
529 assuan_peercred_t
* peer
)
534 struct client_s
*client
= assuan_get_pointer (ctx
);
537 return GPG_ERR_EACCES
;
540 if (client
->thd
->remote
)
541 return tls_validate_access (client
, section
);
544 rc
= assuan_get_peercred (ctx
, peer
);
548 users
= config_get_list (section
, "allowed");
551 for (char **p
= users
; !rc
&& *p
; p
++)
553 rc
= acl_check_common(client
, *p
, (*peer
)->uid
, (*peer
)->gid
,
560 return allowed
&& !rc
? 0 : rc
? rc
: GPG_ERR_EACCES
;
563 /* Test if uid is a member of group 'name'. Invert when 'not' is true. */
564 #ifdef HAVE_GETGRNAM_R
566 acl_check_group (const char *name
, uid_t uid
, gid_t gid
, int not, int *allowed
)
569 struct group gr
, *gresult
;
570 size_t len
= sysconf (_SC_GETGR_R_SIZE_MAX
);
579 return GPG_ERR_ENOMEM
;
581 err
= getgrnam_r (name
, &gr
, buf
, len
, &gresult
);
584 if (gresult
->gr_gid
== gid
)
591 len
= sysconf (_SC_GETPW_R_SIZE_MAX
);
595 for (char **t
= gresult
->gr_mem
; !rc
&& *t
; t
++)
599 struct passwd
*result
= get_pwd_struct (*t
, 0, &pw
, &tbuf
, &rc
);
601 if (!rc
&& result
&& result
->pw_uid
== uid
)
615 rc
= gpg_error_from_errno (err
);
618 return rc
? rc
: GPG_ERR_EACCES
;
622 acl_check_group (const char *name
, uid_t uid
, gid_t gid
, int not, int *allowed
)
624 struct group
*gresult
;
628 gresult
= getgrnam (name
);
629 if (!errno
&& gresult
&& gresult
->gr_gid
== gid
)
635 rc
= gpg_error_from_syserror ();
637 for (char **t
= gresult
->gr_mem
; !rc
&& *t
; t
++)
641 struct passwd
*result
= get_pwd_struct (*t
, 0, &pw
, &buf
, &rc
);
643 if (!rc
&& result
&& result
->pw_uid
== uid
)
658 peer_is_invoker(struct client_s
*client
)
660 struct invoking_user_s
*user
;
663 if (client
->thd
->state
== CLIENT_STATE_UNKNOWN
)
664 return GPG_ERR_EACCES
;
666 for (user
= invoking_users
; user
; user
= user
->next
)
669 if (client
->thd
->remote
)
671 if (user
->type
== INVOKING_TLS
672 && !strcmp(client
->thd
->tls
->fp
, user
->id
))
673 allowed
= user
->not ? 0 : 1;
679 if (user
->type
== INVOKING_GID
)
681 gpg_error_t rc
= acl_check_group (user
->id
,
682 client
->thd
->peer
->uid
,
683 client
->thd
->peer
->gid
,
684 user
->not, &allowed
);
688 else if (user
->type
== INVOKING_UID
&& client
->thd
->peer
->uid
== user
->uid
)
689 allowed
= user
->not ? 0 : 1;
692 return allowed
? 0 : GPG_ERR_EACCES
;
695 #ifdef HAVE_GETGRNAM_R
697 acl_check_common (struct client_s
*client
, const char *user
, uid_t uid
,
698 gid_t gid
, int *allowed
)
708 if (*user
== '-' || *user
== '!')
711 if (*user
== '+') // not implemented yet
714 if (*user
== '#') // TLS fingerprint hash
717 if (not || rw
|| tls
)
723 if (client
->thd
->remote
)
725 if (!strcasecmp (client
->thd
->tls
->fp
, user
))
735 else if (client
->thd
->remote
) // Remote client with no TLS in the ACL
739 if (*user
== '@') // all users in group
740 return acl_check_group (user
+1, uid
, gid
, not, allowed
);
745 struct passwd
*pwd
= get_pwd_struct (user
, 0, &pw
, &buf
, &rc
);
747 if (!rc
&& pwd
&& pwd
->pw_uid
== uid
)
757 acl_check_common (struct client_s
*client
, const char *user
, uid_t uid
,
758 gid_t gid
, int *allowed
)
768 if (*user
== '-' || *user
== '!')
771 if (*user
== '+') // not implemented yet
774 if (*user
== '#') // TLS fingerprint hash
777 if (not || rw
|| tls
)
783 if (client
->thd
->remote
)
785 if (!strcasecmp (client
->thd
->tls
->fp
, user
))
795 if (*user
== '@') // all users in group
796 return acl_check_group (user
+1, uid
, gid
, not, allowed
);
801 struct passwd
*result
= get_pwd_struct (user
, 0, &pw
, &buf
, &rc
);
803 if (!rc
&& result
&& result
->pw_uid
== uid
)
814 validate_peer (struct client_s
*cl
)
820 return tls_validate_access (cl
, NULL
);
823 MUTEX_LOCK (&cn_mutex
);
824 rc
= do_validate_peer (cl
->ctx
, "global", &cl
->thd
->peer
);
825 MUTEX_UNLOCK (&cn_mutex
);
826 log_write ("peer %s: uid=%i, gid=%i, pid=%i, rc=%u",
827 !rc
? _("accepted") : _("rejected"), cl
->thd
->peer
->uid
,
828 cl
->thd
->peer
->gid
, cl
->thd
->peer
->pid
, rc
);
833 xml_error_cb (void *data
, xmlErrorPtr e
)
835 struct client_s
*client
= data
;
838 * Keep the first reported error as the one to show in the error
839 * description. Reset in send_error().
841 if (client
->xml_error
)
844 client
->xml_error
= xcalloc (1, sizeof(xmlError
));
845 xmlCopyError (e
, client
->xml_error
);
849 hook_waitpid (assuan_context_t ctx
, pid_t pid
, int action
,
850 int *status
, int options
)
852 return waitpid (pid
, status
, options
);
856 hook_read (assuan_context_t ctx
, assuan_fd_t fd
, void *data
, size_t len
)
859 struct client_s
*client
= assuan_get_pointer (ctx
);
861 if (client
->thd
->remote
)
862 return tls_read_hook (ctx
, (int) fd
, data
, len
);
865 return read ((int) fd
, data
, len
);
869 hook_write (assuan_context_t ctx
, assuan_fd_t fd
,
870 const void *data
, size_t len
)
873 struct client_s
*client
= assuan_get_pointer (ctx
);
875 if (client
->thd
->remote
)
876 return tls_write_hook (ctx
, (int) fd
, data
, len
);
879 return write ((int) fd
, data
, len
);
883 new_connection (struct client_s
*cl
)
886 static struct assuan_malloc_hooks mhooks
= { xmalloc
, xrealloc
, xfree
};
887 static struct assuan_system_hooks shooks
= {
888 ASSUAN_SYSTEM_HOOKS_VERSION
,
896 NULL
, //sendmsg both are used for FD passing
907 char *prio
= config_get_string ("global", "tls_cipher_suite");
909 cl
->thd
->timeout
= config_get_integer ("global", "tls_timeout");
910 if (fcntl (cl
->thd
->fd
, F_SETFL
, O_NONBLOCK
) == -1)
913 cl
->thd
->tls
= tls_init (cl
->thd
->fd
, cl
->thd
->timeout
, prio
);
920 rc
= assuan_new_ext (&cl
->ctx
, GPG_ERR_SOURCE_DEFAULT
, &mhooks
,
921 debug_level
? assuan_log_cb
: NULL
, NULL
);
925 assuan_ctx_set_system_hooks (cl
->ctx
, &shooks
);
926 rc
= assuan_init_socket_server (cl
->ctx
, cl
->thd
->fd
, 2);
930 assuan_set_pointer (cl
->ctx
, cl
);
931 assuan_set_hello_line (cl
->ctx
, PACKAGE_STRING
);
932 rc
= register_commands (cl
->ctx
);
936 rc
= assuan_accept (cl
->ctx
);
940 rc
= validate_peer (cl
);
941 /* May not be implemented on all platforms. */
942 if (rc
&& gpg_err_code (rc
) != GPG_ERR_ASS_GENERAL
)
945 MUTEX_LOCK (&cn_mutex
);
946 cl
->thd
->state
= CLIENT_STATE_INIT
;
947 MUTEX_UNLOCK (&cn_mutex
);
948 rc
= init_client_crypto (&cl
->crypto
);
954 cl
->crypto
->agent
->client_ctx
= cl
->ctx
;
957 cl
->crypto
->client_ctx
= cl
->ctx
;
958 cl
->lock_timeout
= config_get_integer ("global", "lock_timeout");
959 xmlSetStructuredErrorFunc (cl
, xml_error_cb
);
963 log_write ("%s", pwmd_strerror (rc
));
968 * This is called after a client_thread() terminates. Set with
969 * pthread_cleanup_push().
972 cleanup_cb (void *arg
)
974 struct client_thread_s
*cn
= arg
;
975 struct client_s
*cl
= cn
->cl
;
977 MUTEX_LOCK (&cn_mutex
);
978 cn_thread_list
= slist_remove (cn_thread_list
, cn
);
979 MUTEX_UNLOCK (&cn_mutex
);
983 unlock_flock (&cl
->flock_fd
);
986 xmlResetError (cl
->xml_error
);
988 xfree (cl
->xml_error
);
993 gnutls_deinit (cn
->tls
->ses
);
999 if (!cn
->atfork
&& cl
->ctx
)
1000 assuan_release (cl
->ctx
);
1001 else if (!cn
->atfork
&& cl
->thd
&& cl
->thd
->fd
!= -1)
1002 close (cl
->thd
->fd
);
1005 cleanup_crypto (&cl
->crypto
);
1007 pinentry_free_opts (&cl
->pinentry_opts
);
1016 while (cn
->msg_queue
)
1018 struct status_msg_s
*msg
= cn
->msg_queue
;
1020 cn
->msg_queue
= msg
->next
;
1025 if (!cn
->atfork
&& cn
->status_msg_pipe
[0] != -1)
1026 close (cn
->status_msg_pipe
[0]);
1028 if (!cn
->atfork
&& cn
->status_msg_pipe
[1] != -1)
1029 close (cn
->status_msg_pipe
[1]);
1031 pthread_mutex_destroy (&cn
->status_mutex
);
1035 log_write (_("exiting, fd=%i"), cn
->fd
);
1036 send_status_all (STATUS_CLIENTS
, NULL
);
1041 xfree (cn
->peeraddr
);
1044 pthread_cond_signal (&quit_cond
);
1048 cleanup_all_clients (int atfork
)
1050 /* This function may be called from pthread_atfork() which requires
1051 reinitialization. */
1054 pthread_mutexattr_t attr
;
1056 pthread_mutexattr_init (&attr
);
1057 pthread_mutexattr_settype (&attr
, PTHREAD_MUTEX_RECURSIVE
);
1058 pthread_mutex_init (&cn_mutex
, &attr
);
1059 pthread_mutexattr_destroy (&attr
);
1060 cache_mutex_init ();
1063 MUTEX_LOCK (&cn_mutex
);
1065 while (slist_length (cn_thread_list
))
1067 struct client_thread_s
*thd
= slist_nth_data (cn_thread_list
, 0);
1069 thd
->atfork
= atfork
;
1074 MUTEX_UNLOCK (&cn_mutex
);
1075 cache_deinit (atfork
);
1079 send_msg_queue (struct client_thread_s
*thd
)
1081 MUTEX_LOCK (&thd
->status_mutex
);
1085 read (thd
->status_msg_pipe
[0], &c
, 1);
1086 thd
->wrote_status
= 0;
1088 while (thd
->msg_queue
)
1090 struct status_msg_s
*msg
= thd
->msg_queue
;
1092 #ifndef HAVE_PTHREAD_CANCEL
1097 thd
->msg_queue
= thd
->msg_queue
->next
;
1098 MUTEX_UNLOCK (&thd
->status_mutex
);
1099 rc
= send_status (thd
->cl
->ctx
, msg
->s
, msg
->line
);
1100 MUTEX_LOCK (&thd
->status_mutex
);
1108 MUTEX_UNLOCK (&thd
->status_mutex
);
1109 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1110 log_write ("%s: %s", __FUNCTION__
, pwmd_strerror (rc
));
1116 client_thread (void *data
)
1118 struct client_thread_s
*thd
= data
;
1119 struct client_s
*cl
= xcalloc (1, sizeof (struct client_s
));
1121 #ifdef HAVE_PR_SET_NAME
1122 prctl (PR_SET_NAME
, "client");
1124 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1128 log_write ("%s(%i): %s", __FILE__
, __LINE__
,
1129 pwmd_strerror (GPG_ERR_ENOMEM
));
1133 MUTEX_LOCK (&cn_mutex
);
1134 pthread_cleanup_push (cleanup_cb
, thd
);
1138 MUTEX_UNLOCK (&cn_mutex
);
1140 if (new_connection (cl
))
1144 struct pollfd fds
[2];
1146 fds
[0].fd
= thd
->fd
;
1147 fds
[0].events
= POLLIN
;
1148 fds
[1].fd
= thd
->status_msg_pipe
[0];
1149 fds
[1].events
= POLLIN
;
1151 send_status_all (STATUS_CLIENTS
, NULL
);
1152 rc
= send_status (cl
->ctx
, STATUS_CACHE
, NULL
);
1155 log_write ("%s(%i): %s", __FILE__
, __LINE__
, pwmd_strerror (rc
));
1164 n
= poll (fds
, 2, -1);
1167 log_write ("%s", strerror (errno
));
1171 if (fds
[1].revents
& POLLIN
)
1173 rc
= send_msg_queue (thd
);
1174 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1178 #ifdef HAVE_PTHREAD_CANCEL
1179 if (!(fds
[0].revents
& POLLIN
))
1181 if (thd
->fd
!= -1 && !(fds
[0].revents
& POLLIN
))
1185 rc
= assuan_process_next (cl
->ctx
, &eof
);
1188 if (gpg_err_code (rc
) == GPG_ERR_EOF
|| eof
)
1191 log_write ("assuan_process_next(): rc=%i %s", rc
,
1192 pwmd_strerror (rc
));
1193 if (rc
== gpg_error (GPG_ERR_ETIMEDOUT
))
1196 rc
= send_error (cl
->ctx
, rc
);
1199 log_write ("assuan_process_done(): rc=%i %s", rc
,
1200 pwmd_strerror (rc
));
1205 /* Since the msg queue pipe fd's are non-blocking, check for
1206 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1207 * client has already disconnected and will be converted to
1208 * GPG_ERR_EOF during assuan_process_next().
1210 rc
= send_msg_queue (thd
);
1211 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1216 /* Don't do pthread_exit() here because any set pthread_cleanup_push
1217 * functions would be called after a command failed but then the client
1218 * exited normally which may lead to a double free. */
1219 pthread_cleanup_pop (1);
1224 xml_import (const char *filename
, const char *outfile
,
1225 const char *keygrip
, const char *sign_keygrip
,
1226 const char *keyfile
, int no_passphrase
, const char *cipher
,
1227 const char *params
, uint64_t iterations
)
1236 struct crypto_s
*crypto
= NULL
;
1239 int algo
= cipher
? cipher_string_to_gcrypt ((char *) cipher
) :
1244 log_write ("ERR %i: %s", gpg_error (GPG_ERR_CIPHER_ALGO
),
1245 pwmd_strerror (GPG_ERR_CIPHER_ALGO
));
1249 if (stat (filename
, &st
) == -1)
1251 log_write ("%s: %s", filename
,
1252 pwmd_strerror (gpg_error_from_errno (errno
)));
1256 rc
= init_client_crypto (&crypto
);
1260 memcpy (&crypto
->save
.hdr
, &crypto
->hdr
, sizeof (file_header_t
));
1261 crypto
->save
.hdr
.flags
= set_cipher_flag (crypto
->save
.hdr
.flags
, algo
);
1262 log_write (_("Importing XML from '%s'. Output will be written to '%s' ..."),
1265 if ((fd
= open (filename
, O_RDONLY
)) == -1)
1267 log_write ("%s: %s", filename
,
1268 pwmd_strerror (gpg_error_from_errno (errno
)));
1272 if ((xmlbuf
= xmalloc (st
.st_size
+ 1)) == NULL
)
1275 log_write ("%s(%i): %s", __FILE__
, __LINE__
,
1276 pwmd_strerror (GPG_ERR_ENOMEM
));
1280 if (read (fd
, xmlbuf
, st
.st_size
) == -1)
1282 rc
= gpg_error_from_errno (errno
);
1284 log_write ("%s: %s", filename
, pwmd_strerror (rc
));
1289 xmlbuf
[st
.st_size
] = 0;
1291 * Make sure the document validates.
1293 if ((doc
= xmlReadDoc (xmlbuf
, NULL
, "UTF-8", XML_PARSE_NOBLANKS
)) == NULL
)
1295 log_write ("xmlReadDoc() failed");
1301 xmlNodePtr n
= xmlDocGetRootElement (doc
);
1302 if (n
&& !xmlStrEqual (n
->name
, (xmlChar
*) "pwmd"))
1304 log_write (_("Could not find root \"pwmd\" element."));
1305 rc
= GPG_ERR_BAD_DATA
;
1309 rc
= validate_import (NULL
, n
? n
->children
: n
);
1313 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
1318 xmlDocDumpMemory (doc
, &xml
, &len
);
1320 crypto
->save
.hdr
.s2k_count
= iterations
;
1323 rc
= export_common (NULL
, 0, crypto
, xml
, len
, outfile
, keyfile
, &key
,
1324 &keylen
, 0, 0, no_passphrase
);
1326 log_write (_("Success!"));
1331 rc
= agent_set_pinentry_options (crypto
->agent
);
1333 rc
= agent_export_common (crypto
, keygrip
, sign_keygrip
, no_passphrase
,
1334 xml
, len
, outfile
, params
, keyfile
);
1342 send_error (NULL
, rc
);
1346 cleanup_crypto (&crypto
);
1350 cleanup_crypto (&crypto
);
1355 do_cache_push (const char *filename
, struct crypto_s
*crypto
)
1357 unsigned char md5file
[16];
1362 struct cache_data_s
*cdata
;
1367 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1370 if (valid_filename (filename
) == 0)
1372 log_write (_("%s: Invalid characters in filename"), filename
);
1376 rc
= lock_flock (NULL
, filename
, LOCK_SH
, &fd
);
1378 rc
= decrypt_common (NULL
, 0, crypto
, filename
, &key
, &keylen
, NULL
, NULL
);
1382 rc
= parse_doc ((char *) crypto
->plaintext
, crypto
->plaintext_len
, &doc
);
1389 gcry_md_hash_buffer (GCRY_MD_MD5
, md5file
, filename
, strlen (filename
));
1390 cdata
= xcalloc (1, sizeof (struct cache_data_s
));
1398 rc
= get_checksum (filename
, &crc
, &len
);
1403 free_cache_data_once (cdata
);
1408 rc
= encrypt_xml (NULL
, cache_key
, cache_keysize
, GCRY_CIPHER_AES
,
1409 crypto
->plaintext
, crypto
->plaintext_len
, &cdata
->doc
,
1410 &cdata
->doclen
, &cache_iv
, &cache_blocksize
);
1411 if (!rc
&& !IS_PKI (crypto
))
1414 cdata
->keylen
= keylen
;
1422 free_cache_data_once (cdata
);
1427 if (use_agent
&& IS_PKI (crypto
))
1429 gcry_sexp_build ((gcry_sexp_t
*) & cdata
->pubkey
, NULL
, "%S",
1431 gcry_sexp_build ((gcry_sexp_t
*) & cdata
->sigkey
, NULL
, "%S",
1432 crypto
->sigpkey_sexp
);
1437 int timeout
= config_get_integer (filename
, "cache_timeout");
1438 cache_add_file (md5file
, crypto
->grip
, cdata
, timeout
);
1439 log_write (_("Successfully added '%s' to the cache."), filename
);
1444 log_write ("ERR %u: %s: %s", rc
, filename
, pwmd_strerror (rc
));
1449 init_client (int fd
, const char *addr
)
1452 struct client_thread_s
*new = xcalloc (1, sizeof (struct client_thread_s
));
1457 return GPG_ERR_ENOMEM
;
1460 MUTEX_LOCK (&cn_mutex
);
1461 pthread_cleanup_push (cleanup_mutex_cb
, &cn_mutex
);
1463 if (pipe (new->status_msg_pipe
) == -1)
1464 rc
= gpg_error_from_errno (errno
);
1468 if (fcntl (new->status_msg_pipe
[0], F_SETFL
, O_NONBLOCK
) == -1)
1469 rc
= gpg_error_from_errno (errno
);
1472 if (fcntl (new->status_msg_pipe
[1], F_SETFL
, O_NONBLOCK
) == -1)
1473 rc
= gpg_error_from_errno (errno
);
1475 pthread_mutex_init (&new->status_mutex
, NULL
);
1481 new->remote
= addr
? 1 : 0;
1484 rc
= create_thread (client_thread
, new, &new->tid
, 1);
1487 close (new->status_msg_pipe
[0]);
1488 close (new->status_msg_pipe
[1]);
1489 pthread_mutex_destroy (&new->status_mutex
);
1495 struct slist_s
*list
= slist_append (cn_thread_list
, new);
1499 cn_thread_list
= list
;
1502 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1503 (pthread_t
*) new->tid
, fd
, addr
);
1505 new->peeraddr
= str_dup (addr
);
1509 log_write (_("new connection: tid=%p, fd=%i"),
1510 (pthread_t
*) new->tid
, fd
);
1513 rc
= GPG_ERR_ENOMEM
;
1516 pthread_cleanup_pop (1);
1522 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1523 pwmd_strerror (rc
));
1529 keepalive_thread (void *arg
)
1531 #ifndef HAVE_PTHREAD_CANCEL
1532 int *n
= xmalloc (sizeof (int));
1535 pthread_setspecific (signal_thread_key
, n
);
1539 #ifdef HAVE_PR_SET_NAME
1540 prctl (PR_SET_NAME
, "keepalive");
1542 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1546 int n
= config_get_integer ("global", "keepalive_interval");
1547 struct timeval tv
= { n
, 0 };
1548 #ifndef HAVE_PTHREAD_CANCEL
1551 sigusr2
= (int *) pthread_getspecific (signal_thread_key
);
1556 send_status_all (STATUS_KEEPALIVE
, NULL
);
1557 select (0, NULL
, NULL
, NULL
, &tv
);
1564 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1566 get_in_addr (struct sockaddr
*sa
)
1568 if (sa
->sa_family
== AF_INET
)
1569 return &(((struct sockaddr_in
*) sa
)->sin_addr
);
1571 return &(((struct sockaddr_in6
*) sa
)->sin6_addr
);
1575 tcp_accept_thread (void *arg
)
1577 int sockfd
= *(int *) arg
;
1578 #ifndef HAVE_PTHREAD_CANCEL
1579 int *n
= xmalloc (sizeof (int));
1582 pthread_setspecific (signal_thread_key
, n
);
1584 fcntl (sockfd
, F_SETFL
, O_NONBLOCK
);
1587 #ifdef HAVE_PR_SET_NAME
1588 prctl (PR_SET_NAME
, "tcp_accept");
1590 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1594 struct sockaddr_storage raddr
;
1595 socklen_t slen
= sizeof (raddr
);
1598 char s
[INET6_ADDRSTRLEN
];
1599 struct timeval tv
= { 0, ACCEPT_TIMEOUT
};
1600 #ifndef HAVE_PTHREAD_CANCEL
1603 sigusr2
= (int *) pthread_getspecific (signal_thread_key
);
1608 fd
= accept (sockfd
, (struct sockaddr
*) &raddr
, &slen
);
1611 if (errno
== EMFILE
|| errno
== ENFILE
)
1612 log_write ("accept(): %s",
1613 pwmd_strerror (gpg_error_from_errno (errno
)));
1614 else if (errno
!= EAGAIN
)
1616 if (!quit
) // probably EBADF
1617 log_write ("accept(): %s", strerror (errno
));
1622 #ifndef HAVE_PTHREAD_CANCEL
1623 select (0, NULL
, NULL
, NULL
, &tv
);
1634 inet_ntop (raddr
.ss_family
, get_in_addr ((struct sockaddr
*) &raddr
),
1636 (void) init_client (fd
, s
);
1637 n
= config_get_integer ("global", "tcp_wait");
1640 tv
.tv_sec
= (n
* 100000) / 100000;
1641 tv
.tv_usec
= (n
* 100000) % 100000;
1642 select (0, NULL
, NULL
, NULL
, &tv
);
1650 start_stop_tls_with_protocol (int ipv6
, int term
)
1652 struct addrinfo hints
, *servinfo
, *p
;
1653 int port
= config_get_integer ("global", "tcp_port");
1657 int *fd
= ipv6
? &tls6_fd
: &tls_fd
;
1659 if (term
|| config_get_boolean ("global", "enable_tcp") == 0)
1665 #ifdef HAVE_PTHREAD_CANCEL
1666 pthread_cancel (tls6_tid
);
1668 pthread_kill (tls6_tid
, SIGUSR2
);
1670 pthread_join (tls6_tid
, NULL
);
1673 shutdown (tls6_fd
, SHUT_RDWR
);
1683 #ifdef HAVE_PTHREAD_CANCEL
1684 pthread_cancel (tls_tid
);
1686 pthread_kill (tls_tid
, SIGUSR2
);
1688 pthread_join (tls_tid
, NULL
);
1691 shutdown (tls_fd
, SHUT_RDWR
);
1697 /* A client may still be connected. */
1698 if (!quit
&& x509_cred
!= NULL
)
1699 tls_deinit_params ();
1704 if ((ipv6
&& tls6_fd
!= -1) || (!ipv6
&& tls_fd
!= -1))
1707 memset (&hints
, 0, sizeof (hints
));
1708 hints
.ai_family
= ipv6
? AF_INET6
: AF_INET
;
1709 hints
.ai_socktype
= SOCK_STREAM
;
1710 hints
.ai_flags
= AI_PASSIVE
;
1711 snprintf (buf
, sizeof (buf
), "%i", port
);
1713 if ((n
= getaddrinfo (NULL
, buf
, &hints
, &servinfo
)) == -1)
1715 log_write ("getaddrinfo(): %s", gai_strerror (n
));
1719 for (n
= 0, p
= servinfo
; p
!= NULL
; p
= p
->ai_next
)
1723 if ((ipv6
&& p
->ai_family
!= AF_INET6
)
1724 || (!ipv6
&& p
->ai_family
!= AF_INET
))
1727 if ((*fd
= socket (p
->ai_family
, p
->ai_socktype
, p
->ai_protocol
)) == -1)
1729 log_write ("socket(): %s", strerror (errno
));
1733 if (setsockopt (*fd
, SOL_SOCKET
, SO_REUSEADDR
, &r
, sizeof (int)) == -1)
1735 log_write ("setsockopt(): %s",
1736 pwmd_strerror (gpg_error_from_errno (errno
)));
1737 freeaddrinfo (servinfo
);
1741 if (bind (*fd
, p
->ai_addr
, p
->ai_addrlen
) == -1)
1744 log_write ("bind(): %s",
1745 pwmd_strerror (gpg_error_from_errno (errno
)));
1753 freeaddrinfo (servinfo
);
1758 #if HAVE_DECL_SO_BINDTODEVICE != 0
1759 char *tmp
= config_get_string ("global", "tcp_interface");
1760 if (tmp
&& setsockopt (*fd
, SOL_SOCKET
, SO_BINDTODEVICE
, tmp
,
1761 strlen (tmp
)) == -1)
1763 log_write ("setsockopt(): %s",
1764 pwmd_strerror (gpg_error_from_errno (errno
)));
1772 if (x509_cred
== NULL
)
1774 char *tmp
= config_get_string ("global", "tls_dh_level");
1776 rc
= tls_init_params (tmp
);
1782 if (listen (*fd
, 0) == -1)
1784 log_write ("listen(): %s", strerror (errno
));
1789 rc
= create_thread (tcp_accept_thread
, fd
, &tls6_tid
, 0);
1791 rc
= create_thread (tcp_accept_thread
, fd
, &tls_tid
, 0);
1795 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1796 pwmd_strerror (rc
));
1808 start_stop_tls_with_protocol (0, 1);
1821 start_stop_tls (int term
)
1823 char *s
= config_get_string ("global", "tcp_bind");
1829 if (!strcmp (s
, "any"))
1831 b
= start_stop_tls_with_protocol (0, term
);
1833 b
= start_stop_tls_with_protocol (1, term
);
1835 else if (!strcmp (s
, "ipv4"))
1836 b
= start_stop_tls_with_protocol (0, term
);
1837 else if (!strcmp (s
, "ipv6"))
1838 b
= start_stop_tls_with_protocol (1, term
);
1848 accept_thread (void *arg
)
1850 int sockfd
= *(int *) arg
;
1851 #ifndef HAVE_PTHREAD_CANCEL
1852 int *n
= xmalloc (sizeof (int));
1855 pthread_setspecific (signal_thread_key
, n
);
1857 fcntl (sockfd
, F_SETFL
, O_NONBLOCK
);
1860 #ifdef HAVE_PR_SET_NAME
1861 prctl (PR_SET_NAME
, "accept");
1863 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1867 socklen_t slen
= sizeof (struct sockaddr_un
);
1868 struct sockaddr_un raddr
;
1870 #ifndef HAVE_PTHREAD_CANCEL
1871 struct timeval tv
= { 0, ACCEPT_TIMEOUT
};
1872 int *sigusr2
= (int *) pthread_getspecific (signal_thread_key
);
1878 fd
= accept (sockfd
, (struct sockaddr
*) &raddr
, &slen
);
1881 if (errno
== EMFILE
|| errno
== ENFILE
)
1882 log_write ("accept(): %s",
1883 pwmd_strerror (gpg_error_from_errno (errno
)));
1884 else if (errno
!= EAGAIN
)
1886 if (!quit
) // probably EBADF
1887 log_write ("accept(): %s",
1888 pwmd_strerror (gpg_error_from_errno (errno
)));
1893 #ifndef HAVE_PTHREAD_CANCEL
1894 select (0, NULL
, NULL
, NULL
, &tv
);
1899 (void) init_client (fd
, NULL
);
1902 /* Just in case accept() failed for some reason other than EBADF */
1908 cache_timer_thread (void *arg
)
1910 #ifndef HAVE_PTHREAD_CANCEL
1911 int *n
= xmalloc (sizeof (int));
1914 pthread_setspecific (signal_thread_key
, n
);
1918 #ifdef HAVE_PR_SET_NAME
1919 prctl (PR_SET_NAME
, "cache timer");
1921 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1925 struct timeval tv
= { 1, 0 };
1926 #ifndef HAVE_PTHREAD_CANCEL
1929 n
= (int *) pthread_getspecific (signal_thread_key
);
1934 select (0, NULL
, NULL
, NULL
, &tv
);
1935 cache_adjust_timeout ();
1942 signal_loop (sigset_t sigset
)
1951 sigwait (&sigset
, &sig
);
1954 log_write (_("caught signal %i (%s)"), sig
, strsignal (sig
));
1959 pthread_cond_signal (&rcfile_cond
);
1962 log_write (_("clearing file cache"));
1964 send_status_all (STATUS_CACHE
, NULL
);
1983 log_write (_ ("Caught signal %i (%s). Exiting."), sig
, strsignal (sig
));
1984 #ifdef HAVE_BACKTRACE
1985 BACKTRACE (__FUNCTION__
);
1991 waiting_for_exit (void *arg
)
1994 #ifndef HAVE_PTHREAD_CANCEL
1995 int *n
= xmalloc (sizeof (int));
1998 pthread_setspecific (signal_thread_key
, n
);
2002 #ifdef HAVE_PR_SET_NAME
2003 prctl (PR_SET_NAME
, "exiting");
2005 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
2006 log_write (_("waiting for all clients to disconnect"));
2007 MUTEX_LOCK (&quit_mutex
);
2008 pthread_cleanup_push (cleanup_mutex_cb
, &quit_mutex
);
2015 MUTEX_LOCK (&cn_mutex
);
2016 n
= slist_length (cn_thread_list
);
2017 MUTEX_UNLOCK (&cn_mutex
);
2021 #ifndef HAVE_PTHREAD_CANCEL
2022 int *s
= (int *) pthread_getspecific (signal_thread_key
);
2029 log_write (_("%i clients remain"), n
);
2033 INIT_TIMESPEC (SIG_TIMEOUT
, ts
);
2034 pthread_cond_timedwait (&quit_cond
, &quit_mutex
, &ts
);
2037 kill (getpid (), SIGQUIT
);
2038 pthread_cleanup_pop (1);
2043 server_loop (int sockfd
, char **socketpath
)
2045 pthread_t accept_tid
;
2046 pthread_t cache_timeout_tid
;
2047 int cancel_timeout_thread
= 0, cancel_accept_thread
= 0;
2048 int cancel_keepalive_thread
= 0;
2055 sigemptyset (&sigset
);
2058 sigaddset (&sigset
, SIGTERM
);
2059 sigaddset (&sigset
, SIGINT
);
2061 /* Clears the file cache. */
2062 sigaddset (&sigset
, SIGUSR1
);
2064 /* Configuration file reloading. */
2065 sigaddset (&sigset
, SIGHUP
);
2067 /* For exiting cleanly. */
2068 sigaddset (&sigset
, SIGQUIT
);
2070 #ifndef HAVE_PTHREAD_CANCEL
2072 The socket, cache and rcfile threads use this signal when
2073 pthread_cancel() is unavailable. Prevent the main thread from
2074 catching this signal from another process.
2076 sigaddset (&sigset
, SIGUSR2
);
2079 /* When mem.c cannot find a pointer in the list (double free). */
2080 signal (SIGABRT
, catchsig
);
2081 sigaddset (&sigset
, SIGABRT
);
2082 sigprocmask (SIG_BLOCK
, &sigset
, NULL
);
2084 #ifndef HAVE_PTHREAD_CANCEL
2085 /* Remove this signal from the watched signals in signal_loop(). */
2086 sigdelset (&sigset
, SIGUSR2
);
2089 /* Ignored everywhere. When a client disconnects abnormally this signal
2090 * gets raised. It isn't needed though because client_thread() will check
2091 * for rcs even after the client disconnects. */
2092 signal (SIGPIPE
, SIG_IGN
);
2094 /* Can show a backtrace of the stack in the log. */
2095 signal (SIGSEGV
, catchsig
);
2098 /* Needs to be done after the fork(). */
2099 if (!start_stop_tls (0))
2106 pthread_mutex_init (&quit_mutex
, NULL
);
2107 pthread_cond_init (&quit_cond
, NULL
);
2108 char *p
= get_username (getuid());
2109 log_write (_("%s started for user %s"), PACKAGE_STRING
, p
);
2113 if (config_get_boolean ("global", "enable_tcp"))
2114 log_write (_("Listening on %s and TCP port %i"), *socketpath
,
2115 config_get_integer ("global", "tcp_port"));
2117 log_write (_("Listening on %s"), *socketpath
);
2119 log_write (_("Listening on %s"), *socketpath
);
2122 rc
= create_thread (keepalive_thread
, NULL
, &keepalive_tid
, 0);
2125 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2126 pwmd_strerror (rc
));
2130 cancel_keepalive_thread
= 1;
2131 rc
= create_thread (reload_rcfile_thread
, NULL
, &rcfile_tid
, 0);
2134 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2135 pwmd_strerror (rc
));
2139 rc
= create_thread (cache_timer_thread
, NULL
, &cache_timeout_tid
, 0);
2142 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2143 pwmd_strerror (rc
));
2147 cancel_timeout_thread
= 1;
2148 rc
= create_thread (accept_thread
, &sockfd
, &accept_tid
, 0);
2151 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2152 pwmd_strerror (rc
));
2156 cancel_accept_thread
= 1;
2158 signal_loop (sigset
);
2164 * We're out of the main server loop. This happens when a signal was sent
2165 * to terminate the daemon. We'll wait for all clients to disconnect
2166 * before exiting but exit immediately if another termination signal is
2169 if (cancel_accept_thread
)
2171 #ifdef HAVE_PTHREAD_CANCEL
2172 int n
= pthread_cancel (accept_tid
);
2174 int n
= pthread_kill (accept_tid
, SIGUSR2
);
2177 pthread_join (accept_tid
, NULL
);
2183 shutdown (sockfd
, SHUT_RDWR
);
2185 unlink (*socketpath
);
2186 xfree (*socketpath
);
2188 MUTEX_LOCK (&cn_mutex
);
2189 n
= slist_length (cn_thread_list
);
2190 MUTEX_UNLOCK (&cn_mutex
);
2196 rc
= create_thread (waiting_for_exit
, NULL
, &tid
, 0);
2199 if (signal_loop (sigset
))
2201 log_write (_("Received second termination request. Exiting."));
2202 #ifdef HAVE_PTHREAD_CANCEL
2203 pthread_cancel (tid
);
2205 pthread_kill (tid
, SIGUSR2
);
2207 pthread_join (tid
, NULL
);
2211 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2212 pwmd_strerror (rc
));
2215 if (cancel_timeout_thread
)
2217 #ifdef HAVE_PTHREAD_CANCEL
2218 pthread_cancel (cache_timeout_tid
);
2220 pthread_kill (cache_timeout_tid
, SIGUSR2
);
2222 pthread_join (cache_timeout_tid
, NULL
);
2225 if (cancel_keepalive_thread
)
2227 #ifdef HAVE_PTHREAD_CANCEL
2228 pthread_cancel (keepalive_tid
);
2230 pthread_kill (keepalive_tid
, SIGUSR2
);
2232 pthread_join (keepalive_tid
, NULL
);
2235 cleanup_all_clients (0);
2240 pthread_cond_destroy (&quit_cond
);
2241 pthread_mutex_destroy (&quit_mutex
);
2242 return segv
? EXIT_FAILURE
: EXIT_SUCCESS
;;
2249 ("Failed to add a file to the cache. Use --force to force startup. Exiting."));
2253 /* This is called from cache.c:clear_once(). See
2254 * command.c:clearcache_command() for details about lock checking.
2257 free_cache_data (file_cache_t
* cache
)
2259 gpg_error_t rc
= GPG_ERR_NO_DATA
;
2261 struct client_thread_s
*found
= NULL
;
2268 MUTEX_LOCK (&cn_mutex
);
2269 pthread_cleanup_push (cleanup_mutex_cb
, &cn_mutex
);
2270 t
= slist_length (cn_thread_list
);
2272 for (i
= 0; i
< t
; i
++)
2274 struct client_thread_s
*thd
= slist_nth_data (cn_thread_list
, i
);
2279 if (!memcmp (thd
->cl
->md5file
, cache
->filename
,
2280 sizeof (cache
->filename
)))
2282 if (pthread_equal (pthread_self (), thd
->tid
))
2289 /* Continue trying to find a client who has the same file open and
2290 * also has a lock. */
2291 rc
= cache_lock_mutex (thd
->cl
->ctx
, thd
->cl
->md5file
, -1, 0, -1);
2301 if (self
&& (!rc
|| rc
== GPG_ERR_NO_DATA
))
2302 rc
= cache_lock_mutex (found
->cl
->ctx
, found
->cl
->md5file
, -1, 0, -1);
2304 if (exiting
|| !rc
|| rc
== GPG_ERR_NO_DATA
)
2306 free_cache_data_once (cache
->data
);
2308 cache
->defer_clear
= 0;
2309 cache
->timeout
= -1;
2312 cache_unlock_mutex (found
->cl
->md5file
, 0);
2318 cache
->defer_clear
= 1;
2320 pthread_cleanup_pop (1);
2326 convert_v2_datafile (const char *filename
, const char *cipher
,
2327 const char *keyfile
, const char *keygrip
,
2328 const char *sign_keygrip
, int nopass
,
2329 const char *outfile
, const char *keyparam
,
2330 uint64_t iterations
)
2335 struct crypto_s
*crypto
= NULL
;
2341 if (outfile
[0] == '-' && outfile
[1] == 0)
2344 log_write (_("Converting version 2 data file \"%s\" ..."), filename
);
2345 if (access (filename
, R_OK
) == -1)
2347 log_write ("%s: %s", filename
,
2348 pwmd_strerror (gpg_error_from_errno (errno
)));
2354 log_write (_("Using passphrase file \"%s\" for decryption ..."),
2356 if (access (keyfile
, R_OK
) == -1)
2358 log_write ("%s: %s", keyfile
,
2359 pwmd_strerror (gpg_error_from_errno (errno
)));
2364 rc
= read_v2_datafile (filename
, keyfile
, &data
, &datalen
, &ver
, &algo
);
2367 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
2373 algo
= cipher_string_to_gcrypt (cipher
);
2376 rc
= GPG_ERR_CIPHER_ALGO
;
2385 rc
= parse_doc (data
, datalen
, &doc
);
2389 rc
= convert_pre_212_elements (doc
);
2394 xmlDocDumpFormatMemory (doc
, (xmlChar
**) & data
, (int *) &datalen
,
2397 rc
= GPG_ERR_ENOMEM
;
2405 rc
= init_client_crypto (&crypto
);
2408 memcpy (&crypto
->save
.hdr
, &crypto
->hdr
, sizeof (file_header_t
));
2409 crypto
->save
.hdr
.flags
= set_cipher_flag (crypto
->save
.hdr
.flags
, algo
);
2410 crypto
->save
.hdr
.s2k_count
= iterations
;
2414 rc
= export_common (NULL
, 0, crypto
, data
, datalen
, outfile
, keyfile
,
2415 &key
, &keylen
, 0, 0, nopass
);
2420 rc
= agent_set_pinentry_options (crypto
->agent
);
2422 rc
= agent_export_common (crypto
, keygrip
, sign_keygrip
, nopass
,
2423 data
, datalen
, outfile
, keyparam
,
2424 no_passphrase_file
? NULL
: keyfile
);
2428 log_write (_("Output written to \"%s\"."),
2429 outfile
? outfile
: "<stdout>");
2439 cleanup_crypto (&crypto
);
2442 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
2447 usage (const char *pn
, int status
)
2449 FILE *fp
= status
== EXIT_FAILURE
? stderr
: stdout
;
2451 fprintf (fp
, _("Usage: %s [OPTIONS] [file1] [...]\n"
2452 " -f, --rcfile=filename load the specfied configuration file\n"
2453 " (~/.pwmd/config)\n"
2454 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2455 " --kill terminate an existing instance of pwmd\n"
2457 " --use-agent[=integer] enable/disable use of gpg-agent\n"
2459 " -n, --no-fork run as a foreground process\n"
2460 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2461 " --force ignore file errors during startup\n"
2462 " --debug-level=keywords log protocol output (see manual for details)\n"
2463 " -o, --outfile=filename output file when importing or converting\n"
2464 " -C, --convert=filename convert a version 2 data file to version 3\n"
2465 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2466 " -k, --passphrase-file=file for use when importing or converting\n"
2467 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2469 " --no-passphrase when importing or converting\n"
2470 " --keygrip=hex public key to use when encrypting\n"
2471 " --sign-keygrip=hex private key to use when signing\n"
2472 " --keyparam=s-exp custom key parameters to use (RSA-2048)\n"
2473 " --cipher=string encryption cipher (aes256)\n"
2474 " --cipher-iterations=N cipher iteration count (alias for --s2k-count)\n"
2475 " --s2k-count=N hash iteration count (>65536, calibrated)\n"
2476 " --help this help text\n"
2477 " --version show version and compile time features\n"),
2483 unlink_stale_socket (const char *sock
, const char *pidfile
)
2485 log_write (_ ("removing stale socket %s"), sock
);
2491 test_pidfile (const char *path
, const char *sock
, char *buf
, size_t buflen
,
2492 char **pidfile
, int create
, mode_t mode
, int terminate
)
2500 snprintf (buf
, buflen
, "%s/%s.pid", homedir
, sock
);
2501 *pidfile
= str_dup (buf
);
2502 fd
= open (buf
, O_RDONLY
);
2505 fd
= open (*pidfile
, O_CREAT
|O_WRONLY
|O_TRUNC
, mode
);
2509 if (!create
&& errno
!= ENOENT
)
2511 log_write ("%s: %s", buf
, pwmd_strerror (errno
));
2516 else if (!create
&& !terminate
)
2519 log_write ("%s: %s", *pidfile
, strerror (errno
));
2525 snprintf (buf
, buflen
, "%i", getpid ());
2526 write (fd
, buf
, strlen (buf
));
2531 len
= read (fd
, buf
, buflen
);
2535 unlink_stale_socket (path
, *pidfile
);
2539 if (sscanf (buf
, "%5i", &pid
) != 1 || pid
== 0)
2543 unlink_stale_socket (path
, *pidfile
);
2548 if (kill (pid
, 0) == -1)
2550 unlink_stale_socket (path
, *pidfile
);
2556 if (kill (pid
, SIGTERM
) == -1)
2557 log_write ("%s: %s", path
, pwmd_strerror (errno
));
2560 log_write (_ ("an instance for socket %s is already running"), path
);
2568 main (int argc
, char *argv
[])
2571 struct sockaddr_un addr
;
2573 char *socketpath
= NULL
, *socketdir
, *socketname
= NULL
;
2574 char *socketarg
= NULL
;
2575 char *datadir
= NULL
;
2576 char *pidfile
= NULL
;
2580 char **cache_push
= NULL
;
2581 char *import
= NULL
, *keygrip
= NULL
, *sign_keygrip
= NULL
;
2582 char *keyparam
= NULL
;
2583 int estatus
= EXIT_FAILURE
;
2585 char *outfile
= NULL
;
2588 int show_version
= 0;
2590 int no_passphrase
= 0;
2592 char *convertfile
= NULL
;
2593 char *cipher
= NULL
;
2594 char *keyfile
= NULL
;
2595 uint64_t s2k_count
= 0;
2597 char *debug_level_opt
= NULL
;
2600 /* Must maintain the same order as longopts[] */
2603 OPT_VERSION
, OPT_HELP
,
2607 OPT_DEBUG_LEVEL
, OPT_HOMEDIR
, OPT_NO_FORK
, OPT_DISABLE_DUMP
,
2608 OPT_IGNORE
, OPT_FORCE
, OPT_RCFILE
, OPT_CONVERT
,
2609 OPT_PASSPHRASE_FILE
, OPT_IMPORT
, OPT_OUTFILE
,
2610 OPT_NO_PASSPHRASE_FILE
, OPT_KEYGRIP
, OPT_SIGN_KEYGRIP
,
2611 OPT_KEYPARAM
, OPT_CIPHER
, OPT_ITERATIONS
, OPT_S2K_COUNT
,
2612 OPT_NO_PASSPHRASE
, OPT_KILL
2614 const char *optstring
= "nf:C:k:I:o:";
2615 const struct option longopts
[] = {
2616 {"version", no_argument
, 0, 0},
2617 {"help", no_argument
, 0, 0},
2619 {"use-agent", optional_argument
, 0, 0},
2621 {"debug-level", required_argument
, 0, 0},
2622 {"homedir", required_argument
, 0, 0},
2623 {"no-fork", no_argument
, 0, 'n'},
2624 {"disable_dump", no_argument
, 0, 0},
2625 {"ignore", no_argument
, 0, 0},
2626 {"force", no_argument
, 0, 0},
2627 {"rcfile", required_argument
, 0, 'f'},
2628 {"convert", required_argument
, 0, 'C'},
2629 {"passphrase-file", required_argument
, 0, 'k'},
2630 {"import", required_argument
, 0, 'I'},
2631 {"outfile", required_argument
, 0, 'o'},
2632 {"no-passphrase-file", no_argument
, 0, 0},
2633 {"keygrip", required_argument
, 0, 0},
2634 {"sign-keygrip", required_argument
, 0, 0},
2635 {"keyparam", required_argument
, 0, 0},
2636 {"cipher", required_argument
, 0, 0},
2637 {"cipher-iterations", required_argument
, 0, 0},
2638 {"s2k-count", required_argument
, 0, 0},
2639 {"no-passphrase", no_argument
, 0, 0},
2640 {"kill", no_argument
, 0, 0},
2647 #ifdef HAVE_SETRLIMIT
2650 rl
.rlim_cur
= rl
.rlim_max
= 0;
2652 if (setrlimit (RLIMIT_CORE
, &rl
) != 0)
2653 err (EXIT_FAILURE
, "setrlimit()");
2656 #ifdef HAVE_PR_SET_DUMPABLE
2657 prctl (PR_SET_DUMPABLE
, 0);
2662 setlocale (LC_ALL
, "");
2663 bindtextdomain ("pwmd", LOCALEDIR
);
2664 textdomain ("pwmd");
2672 if (setup_crypto ())
2673 exit (EXIT_FAILURE
);
2676 gnutls_global_init ();
2677 gnutls_global_set_log_level (1);
2678 gnutls_global_set_log_function (tls_log
);
2679 gnutls_global_set_audit_log_function (tls_audit_log
);
2683 xmlMemSetup (xfree
, xmalloc
, xrealloc
, str_dup
);
2691 while ((opt
= getopt_long (argc
, argv
, optstring
, longopts
, &optindex
))
2700 convertfile
= optarg
;
2715 rcfile
= str_dup (optarg
);
2718 usage (argv
[0], EXIT_FAILURE
);
2731 use_agent
= optarg
&& *optarg
? atoi (optarg
) : 1;
2732 if (use_agent
< 0 || use_agent
> 1)
2736 case OPT_DEBUG_LEVEL
:
2737 debug_level_opt
= optarg
;
2740 homedir
= str_dup (optarg
);
2745 case OPT_DISABLE_DUMP
:
2753 rcfile
= str_dup (optarg
);
2756 convertfile
= optarg
;
2758 case OPT_PASSPHRASE_FILE
:
2767 case OPT_NO_PASSPHRASE_FILE
:
2768 no_passphrase_file
= 1;
2773 case OPT_SIGN_KEYGRIP
:
2774 sign_keygrip
= optarg
;
2782 case OPT_ITERATIONS
:
2784 s2k_count
= strtoull (optarg
, NULL
, 10);
2786 case OPT_NO_PASSPHRASE
:
2801 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015\n"
2803 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2804 "Compile time features:\n%s"), PACKAGE_STRING
,
2807 "+PWMD_HOMEDIR=" PWMD_HOMEDIR
"\n"
2845 exit (EXIT_SUCCESS
);
2850 homedir
= str_dup(PWMD_HOMEDIR
);
2852 homedir
= str_asprintf ("%s/.pwmd", get_home_dir());
2855 if (mkdir (homedir
, 0700) == -1 && errno
!= EEXIST
)
2856 err (EXIT_FAILURE
, "%s", homedir
);
2858 snprintf (buf
, sizeof (buf
), "%s/data", homedir
);
2859 if (mkdir (buf
, 0700) == -1 && errno
!= EEXIST
)
2860 err (EXIT_FAILURE
, "%s", buf
);
2862 datadir
= str_dup (buf
);
2863 pthread_mutexattr_t attr
;
2864 pthread_mutexattr_init (&attr
);
2865 pthread_mutexattr_settype (&attr
, PTHREAD_MUTEX_RECURSIVE
);
2866 pthread_mutex_init (&rcfile_mutex
, &attr
);
2867 pthread_cond_init (&rcfile_cond
, NULL
);
2868 pthread_mutex_init (&cn_mutex
, &attr
);
2869 pthread_mutexattr_destroy (&attr
);
2870 pthread_key_create (&last_error_key
, free_key
);
2871 #ifndef HAVE_PTHREAD_CANCEL
2872 pthread_key_create (&signal_thread_key
, free_key
);
2876 rcfile
= str_asprintf ("%s/config", homedir
);
2878 global_config
= config_parse (rcfile
, 0);
2880 exit (EXIT_FAILURE
);
2883 if (use_agent
== -1)
2884 use_agent
= config_get_boolean ("global", "use_agent");
2889 if (debug_level_opt
)
2890 debug_level
= str_split (debug_level_opt
, ",", 0);
2892 x
= config_get_int_param (global_config
, "global", "priority", &exists
);
2893 if (exists
&& x
!= atoi(INVALID_PRIORITY
))
2896 if (setpriority (PRIO_PROCESS
, 0, x
) == -1)
2898 log_write ("setpriority(): %s",
2899 pwmd_strerror (gpg_error_from_errno (errno
)));
2903 #ifdef HAVE_MLOCKALL
2904 if (disable_mlock
== 0 && mlockall (MCL_CURRENT
| MCL_FUTURE
) == -1)
2906 log_write ("mlockall(): %s",
2907 pwmd_strerror (gpg_error_from_errno (errno
)));
2912 rc
= cache_init (free_cache_data
);
2915 log_write ("pwmd: ERR %i: %s", rc
,
2916 gpg_err_code (rc
) == GPG_ERR_UNKNOWN_VERSION
2917 ? _("incompatible gpg-agent version: 2.1.0 or later required")
2918 : pwmd_strerror (rc
));
2923 s2k_count
= config_get_ulonglong (NULL
, "s2k_count");
2927 if (!outfile
|| !*outfile
|| argc
!= optind
)
2928 usage (argv
[0], EXIT_FAILURE
);
2930 estatus
= convert_v2_datafile (convertfile
, cipher
, keyfile
, keygrip
,
2931 sign_keygrip
, no_passphrase
, outfile
,
2932 keyparam
, s2k_count
);
2933 config_free (global_config
);
2940 if (!outfile
|| !*outfile
|| argc
!= optind
)
2941 usage (argv
[0], EXIT_FAILURE
);
2943 if (outfile
&& outfile
[0] == '-' && outfile
[1] == 0)
2946 estatus
= xml_import (import
, outfile
, keygrip
, sign_keygrip
, keyfile
,
2947 no_passphrase
, cipher
, keyparam
, s2k_count
);
2948 config_free (global_config
);
2953 p
= config_get_string ("global", "socket_path");
2955 p
= str_asprintf ("%s/socket", homedir
);
2957 socketarg
= expand_homedir (p
);
2961 disable_list_and_dump
= config_get_boolean ("global",
2962 "disable_list_and_dump");
2964 disable_list_and_dump
= secure
;
2966 cache_push
= config_get_list ("global", "cache_push");
2968 while (optind
< argc
)
2970 if (strv_printf (&cache_push
, "%s", argv
[optind
++]) == 0)
2971 errx (EXIT_FAILURE
, "%s", pwmd_strerror (GPG_ERR_ENOMEM
));
2974 if (strchr (socketarg
, '/') == NULL
)
2976 socketdir
= getcwd (buf
, sizeof (buf
));
2977 socketname
= str_dup (socketarg
);
2978 socketpath
= str_asprintf ("%s/%s", socketdir
, socketname
);
2982 socketname
= str_dup (strrchr (socketarg
, '/'));
2984 socketarg
[strlen (socketarg
) - strlen (socketname
) - 1] = 0;
2985 socketdir
= str_dup (socketarg
);
2986 socketpath
= str_asprintf ("%s/%s", socketdir
, socketname
);
2989 if (chdir (datadir
))
2991 log_write ("%s: %s", datadir
,
2992 pwmd_strerror (gpg_error_from_errno (errno
)));
2993 unlink (socketpath
);
2997 x
= test_pidfile (socketpath
, socketname
, buf
, sizeof(buf
), &pidfile
, 0,
2999 if (!terminate
&& x
)
3003 estatus
= x
!= 1 ? EXIT_FAILURE
: EXIT_SUCCESS
;
3008 * bind() doesn't like the full pathname of the socket or any non alphanum
3009 * characters so change to the directory where the socket is wanted then
3010 * create it then change to datadir.
3012 if (chdir (socketdir
))
3014 log_write ("%s: %s", socketdir
,
3015 pwmd_strerror (gpg_error_from_errno (errno
)));
3021 if ((sockfd
= socket (PF_UNIX
, SOCK_STREAM
, 0)) == -1)
3023 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
3027 addr
.sun_family
= AF_UNIX
;
3028 snprintf (addr
.sun_path
, sizeof (addr
.sun_path
), "%s", socketname
);
3030 if (bind (sockfd
, (struct sockaddr
*) &addr
, sizeof (struct sockaddr
)) ==
3033 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
3035 if (errno
== EADDRINUSE
)
3038 log_write (_("Either there is another pwmd running or '%s' is a \n"
3039 "stale socket. Please remove it manually."), socketpath
);
3046 char *t
= config_get_string ("global", "socket_perms");
3051 mode
= strtol (t
, NULL
, 8);
3055 if (chmod (socketname
, mode
) == -1)
3057 log_write ("%s: %s", socketname
,
3058 pwmd_strerror (gpg_error_from_errno (errno
)));
3068 xfree (--socketname
);
3070 if (chdir (datadir
))
3072 log_write ("%s: %s", datadir
,
3073 pwmd_strerror (gpg_error_from_errno (errno
)));
3081 * Set the cache entry for a file. Prompts for the password.
3085 struct crypto_s
*crypto
= NULL
;
3086 gpg_error_t rc
= init_client_crypto (&crypto
);
3090 estatus
= EXIT_FAILURE
;
3097 rc
= agent_set_pinentry_options (crypto
->agent
);
3100 estatus
= EXIT_FAILURE
;
3106 for (opt
= 0; cache_push
[opt
]; opt
++)
3108 if (!do_cache_push (cache_push
[opt
], crypto
) && !force
)
3110 strv_free (cache_push
);
3112 estatus
= EXIT_FAILURE
;
3113 cleanup_crypto (&crypto
);
3117 cleanup_crypto_stage1 (crypto
);
3122 (void) kill_scd (crypto
->agent
);
3125 cleanup_crypto (&crypto
);
3126 strv_free (cache_push
);
3127 log_write (!nofork
? _("Done. Daemonizing...") :
3128 _("Done. Waiting for connections..."));
3131 config_clear_keys ();
3133 if (listen (sockfd
, 0) == -1)
3135 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
3144 log_write ("fork(): %s",
3145 pwmd_strerror (gpg_error_from_errno (errno
)));
3154 _exit (EXIT_SUCCESS
);
3158 (void)test_pidfile (socketpath
, socketname
, buf
, sizeof(buf
), &pidfile
, 1,
3161 pthread_key_create (&thread_name_key
, free_key
);
3162 pthread_setspecific (thread_name_key
, str_dup ("main"));
3163 estatus
= server_loop (sockfd
, &socketpath
);
3166 if (socketpath
&& do_unlink
)
3168 unlink (socketpath
);
3174 gnutls_global_deinit ();
3178 #ifdef HAVE_PTHREAD_CANCEL
3179 pthread_cancel (rcfile_tid
);
3181 pthread_kill (rcfile_tid
, SIGUSR2
);
3182 pthread_cond_signal (&rcfile_cond
);
3184 pthread_join (rcfile_tid
, NULL
);
3187 pthread_cond_destroy (&rcfile_cond
);
3188 pthread_mutex_destroy (&rcfile_mutex
);
3189 pthread_key_delete (last_error_key
);
3190 #ifndef HAVE_PTHREAD_CANCEL
3191 pthread_key_delete (signal_thread_key
);
3195 config_free (global_config
);
3197 free_invoking_users (invoking_users
);
3199 xfree (home_directory
);
3201 xmlCleanupParser ();
3202 xmlCleanupGlobals ();
3208 if (estatus
== EXIT_SUCCESS
&& !terminate
)
3209 log_write (_("pwmd exiting normally"));
3211 pthread_key_delete (thread_name_key
);
3213 #if defined(DEBUG) && !defined(MEM_DEBUG)
3223 gpg_error_t
lock_flock (assuan_context_t ctx
, const char *filename
,
3229 *fd
= open (filename
, O_RDONLY
);
3231 return gpg_error_from_syserror ();
3233 TRY_FLOCK (ctx
, *fd
, type
, rc
);
3244 void unlock_flock (int *fd
)