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
; *p
; p
++)
553 rc
= acl_check_common(client
, *p
, (*peer
)->uid
, (*peer
)->gid
,
560 return allowed
? 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
);
577 return GPG_ERR_ENOMEM
;
579 if (!getgrnam_r (name
, &gr
, buf
, len
, &gresult
) && gresult
)
581 if (gresult
->gr_gid
== gid
)
588 len
= sysconf (_SC_GETPW_R_SIZE_MAX
);
592 for (char **t
= gresult
->gr_mem
; *t
; t
++)
596 struct passwd
*result
= get_pwd_struct (*t
, 0, &pw
, &tbuf
);
598 if (result
&& result
->pw_uid
== uid
)
613 return GPG_ERR_EACCES
;
617 acl_check_group (const char *name
, uid_t uid
, gid_t gid
, int not, int *allowed
)
619 struct group
*gresult
;
621 gresult
= getgrnam (name
);
622 if (gresult
&& gresult
->gr_gid
== gid
)
628 for (char **t
= gresult
->gr_mem
; *t
; t
++)
632 struct passwd
*result
= get_pwd_struct (*t
, 0, &pw
, &buf
);
634 if (result
&& result
->pw_uid
== uid
)
649 peer_is_invoker(struct client_s
*client
)
651 struct invoking_user_s
*user
;
654 if (client
->thd
->state
== CLIENT_STATE_UNKNOWN
)
655 return GPG_ERR_EACCES
;
657 for (user
= invoking_users
; user
; user
= user
->next
)
660 if (client
->thd
->remote
)
662 if (user
->type
== INVOKING_TLS
663 && !strcmp(client
->thd
->tls
->fp
, user
->id
))
664 allowed
= user
->not ? 0 : 1;
670 if (user
->type
== INVOKING_GID
)
672 gpg_error_t rc
= acl_check_group (user
->id
,
673 client
->thd
->peer
->uid
,
674 client
->thd
->peer
->gid
,
675 user
->not, &allowed
);
679 else if (user
->type
== INVOKING_UID
&& client
->thd
->peer
->uid
== user
->uid
)
680 allowed
= user
->not ? 0 : 1;
683 return allowed
? 0 : GPG_ERR_EACCES
;
686 #ifdef HAVE_GETGRNAM_R
688 acl_check_common (struct client_s
*client
, const char *user
, uid_t uid
,
689 gid_t gid
, int *allowed
)
698 if (*user
== '-' || *user
== '!')
701 if (*user
== '+') // not implemented yet
704 if (*user
== '#') // TLS fingerprint hash
707 if (not || rw
|| tls
)
713 if (client
->thd
->remote
)
715 if (!strcasecmp (client
->thd
->tls
->fp
, user
))
725 else if (client
->thd
->remote
) // Remote client with no TLS in the ACL
729 if (*user
== '@') // all users in group
730 return acl_check_group (user
+1, uid
, gid
, not, allowed
);
735 struct passwd
*pwd
= get_pwd_struct (user
, 0, &pw
, &buf
);
737 if (pwd
&& pwd
->pw_uid
== uid
)
747 acl_check_common (struct client_s
*client
, const char *user
, uid_t uid
,
748 gid_t gid
, int *allowed
)
757 if (*user
== '-' || *user
== '!')
760 if (*user
== '+') // not implemented yet
763 if (*user
== '#') // TLS fingerprint hash
766 if (not || rw
|| tls
)
772 if (client
->thd
->remote
)
774 if (!strcasecmp (client
->thd
->tls
->fp
, user
))
784 if (*user
== '@') // all users in group
785 return acl_check_group (user
+1, uid
, gid
, not, allowed
);
790 struct passwd
*result
= get_pwd_struct (user
, 0, &pw
, &buf
);
792 if (result
&& result
->pw_uid
== uid
)
803 validate_peer (struct client_s
*cl
)
809 return tls_validate_access (cl
, NULL
);
812 MUTEX_LOCK (&cn_mutex
);
813 rc
= do_validate_peer (cl
->ctx
, "global", &cl
->thd
->peer
);
814 MUTEX_UNLOCK (&cn_mutex
);
815 if (!rc
|| gpg_err_code (rc
) == GPG_ERR_EACCES
)
816 log_write ("peer %s: uid=%i, gid=%i, pid=%i",
817 !rc
? _("accepted") : _("rejected"), cl
->thd
->peer
->uid
,
818 cl
->thd
->peer
->gid
, cl
->thd
->peer
->pid
);
820 log_write ("%s: %s", __FUNCTION__
, pwmd_strerror (rc
));
826 xml_error_cb (void *data
, xmlErrorPtr e
)
828 struct client_s
*client
= data
;
831 * Keep the first reported error as the one to show in the error
832 * description. Reset in send_error().
834 if (client
->xml_error
)
837 client
->xml_error
= xcalloc (1, sizeof(xmlError
));
838 xmlCopyError (e
, client
->xml_error
);
842 hook_waitpid (assuan_context_t ctx
, pid_t pid
, int action
,
843 int *status
, int options
)
845 return waitpid (pid
, status
, options
);
849 hook_read (assuan_context_t ctx
, assuan_fd_t fd
, void *data
, size_t len
)
852 struct client_s
*client
= assuan_get_pointer (ctx
);
854 if (client
->thd
->remote
)
855 return tls_read_hook (ctx
, (int) fd
, data
, len
);
858 return read ((int) fd
, data
, len
);
862 hook_write (assuan_context_t ctx
, assuan_fd_t fd
,
863 const void *data
, size_t len
)
866 struct client_s
*client
= assuan_get_pointer (ctx
);
868 if (client
->thd
->remote
)
869 return tls_write_hook (ctx
, (int) fd
, data
, len
);
872 return write ((int) fd
, data
, len
);
876 new_connection (struct client_s
*cl
)
879 static struct assuan_malloc_hooks mhooks
= { xmalloc
, xrealloc
, xfree
};
880 static struct assuan_system_hooks shooks
= {
881 ASSUAN_SYSTEM_HOOKS_VERSION
,
889 NULL
, //sendmsg both are used for FD passing
900 char *prio
= config_get_string ("global", "tls_cipher_suite");
902 cl
->thd
->timeout
= config_get_integer ("global", "tls_timeout");
903 if (fcntl (cl
->thd
->fd
, F_SETFL
, O_NONBLOCK
) == -1)
906 cl
->thd
->tls
= tls_init (cl
->thd
->fd
, cl
->thd
->timeout
, prio
);
913 rc
= assuan_new_ext (&cl
->ctx
, GPG_ERR_SOURCE_DEFAULT
, &mhooks
,
914 debug_level
? assuan_log_cb
: NULL
, NULL
);
918 assuan_ctx_set_system_hooks (cl
->ctx
, &shooks
);
919 rc
= assuan_init_socket_server (cl
->ctx
, cl
->thd
->fd
, 2);
923 assuan_set_pointer (cl
->ctx
, cl
);
924 assuan_set_hello_line (cl
->ctx
, PACKAGE_STRING
);
925 rc
= register_commands (cl
->ctx
);
929 rc
= assuan_accept (cl
->ctx
);
933 rc
= validate_peer (cl
);
934 /* May not be implemented on all platforms. */
935 if (rc
&& gpg_err_code (rc
) != GPG_ERR_ASS_GENERAL
)
938 MUTEX_LOCK (&cn_mutex
);
939 cl
->thd
->state
= CLIENT_STATE_INIT
;
940 MUTEX_UNLOCK (&cn_mutex
);
941 rc
= init_client_crypto (&cl
->crypto
);
947 cl
->crypto
->agent
->client_ctx
= cl
->ctx
;
950 cl
->crypto
->client_ctx
= cl
->ctx
;
951 cl
->lock_timeout
= config_get_integer ("global", "lock_timeout");
952 xmlSetStructuredErrorFunc (cl
, xml_error_cb
);
956 log_write ("%s", pwmd_strerror (rc
));
961 * This is called after a client_thread() terminates. Set with
962 * pthread_cleanup_push().
965 cleanup_cb (void *arg
)
967 struct client_thread_s
*cn
= arg
;
968 struct client_s
*cl
= cn
->cl
;
970 MUTEX_LOCK (&cn_mutex
);
971 cn_thread_list
= slist_remove (cn_thread_list
, cn
);
972 MUTEX_UNLOCK (&cn_mutex
);
976 unlock_flock (&cl
->flock_fd
);
979 xmlResetError (cl
->xml_error
);
981 xfree (cl
->xml_error
);
986 gnutls_deinit (cn
->tls
->ses
);
992 if (!cn
->atfork
&& cl
->ctx
)
993 assuan_release (cl
->ctx
);
994 else if (!cn
->atfork
&& cl
->thd
&& cl
->thd
->fd
!= -1)
998 cleanup_crypto (&cl
->crypto
);
1000 pinentry_free_opts (&cl
->pinentry_opts
);
1009 while (cn
->msg_queue
)
1011 struct status_msg_s
*msg
= cn
->msg_queue
;
1013 cn
->msg_queue
= msg
->next
;
1018 if (!cn
->atfork
&& cn
->status_msg_pipe
[0] != -1)
1019 close (cn
->status_msg_pipe
[0]);
1021 if (!cn
->atfork
&& cn
->status_msg_pipe
[1] != -1)
1022 close (cn
->status_msg_pipe
[1]);
1024 pthread_mutex_destroy (&cn
->status_mutex
);
1028 log_write (_("exiting, fd=%i"), cn
->fd
);
1029 send_status_all (STATUS_CLIENTS
, NULL
);
1034 xfree (cn
->peeraddr
);
1037 pthread_cond_signal (&quit_cond
);
1041 cleanup_all_clients (int atfork
)
1043 /* This function may be called from pthread_atfork() which requires
1044 reinitialization. */
1047 pthread_mutexattr_t attr
;
1049 pthread_mutexattr_init (&attr
);
1050 pthread_mutexattr_settype (&attr
, PTHREAD_MUTEX_RECURSIVE
);
1051 pthread_mutex_init (&cn_mutex
, &attr
);
1052 pthread_mutexattr_destroy (&attr
);
1053 cache_mutex_init ();
1056 MUTEX_LOCK (&cn_mutex
);
1058 while (slist_length (cn_thread_list
))
1060 struct client_thread_s
*thd
= slist_nth_data (cn_thread_list
, 0);
1062 thd
->atfork
= atfork
;
1067 MUTEX_UNLOCK (&cn_mutex
);
1068 cache_deinit (atfork
);
1072 send_msg_queue (struct client_thread_s
*thd
)
1074 MUTEX_LOCK (&thd
->status_mutex
);
1078 read (thd
->status_msg_pipe
[0], &c
, 1);
1079 thd
->wrote_status
= 0;
1081 while (thd
->msg_queue
)
1083 struct status_msg_s
*msg
= thd
->msg_queue
;
1085 #ifndef HAVE_PTHREAD_CANCEL
1090 thd
->msg_queue
= thd
->msg_queue
->next
;
1091 MUTEX_UNLOCK (&thd
->status_mutex
);
1092 rc
= send_status (thd
->cl
->ctx
, msg
->s
, msg
->line
);
1093 MUTEX_LOCK (&thd
->status_mutex
);
1101 MUTEX_UNLOCK (&thd
->status_mutex
);
1102 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1103 log_write ("%s: %s", __FUNCTION__
, pwmd_strerror (rc
));
1109 client_thread (void *data
)
1111 struct client_thread_s
*thd
= data
;
1112 struct client_s
*cl
= xcalloc (1, sizeof (struct client_s
));
1114 #ifdef HAVE_PR_SET_NAME
1115 prctl (PR_SET_NAME
, "client");
1117 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1121 log_write ("%s(%i): %s", __FILE__
, __LINE__
,
1122 pwmd_strerror (GPG_ERR_ENOMEM
));
1126 MUTEX_LOCK (&cn_mutex
);
1127 pthread_cleanup_push (cleanup_cb
, thd
);
1131 MUTEX_UNLOCK (&cn_mutex
);
1133 if (new_connection (cl
))
1137 struct pollfd fds
[2];
1139 fds
[0].fd
= thd
->fd
;
1140 fds
[0].events
= POLLIN
;
1141 fds
[1].fd
= thd
->status_msg_pipe
[0];
1142 fds
[1].events
= POLLIN
;
1144 send_status_all (STATUS_CLIENTS
, NULL
);
1145 rc
= send_status (cl
->ctx
, STATUS_CACHE
, NULL
);
1148 log_write ("%s(%i): %s", __FILE__
, __LINE__
, pwmd_strerror (rc
));
1157 n
= poll (fds
, 2, -1);
1160 log_write ("%s", strerror (errno
));
1164 if (fds
[1].revents
& POLLIN
)
1166 rc
= send_msg_queue (thd
);
1167 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1171 #ifdef HAVE_PTHREAD_CANCEL
1172 if (!(fds
[0].revents
& POLLIN
))
1174 if (thd
->fd
!= -1 && !(fds
[0].revents
& POLLIN
))
1178 rc
= assuan_process_next (cl
->ctx
, &eof
);
1181 if (gpg_err_code (rc
) == GPG_ERR_EOF
|| eof
)
1184 log_write ("assuan_process_next(): rc=%i %s", rc
,
1185 pwmd_strerror (rc
));
1186 if (rc
== gpg_error (GPG_ERR_ETIMEDOUT
))
1189 rc
= send_error (cl
->ctx
, rc
);
1192 log_write ("assuan_process_done(): rc=%i %s", rc
,
1193 pwmd_strerror (rc
));
1198 /* Since the msg queue pipe fd's are non-blocking, check for
1199 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1200 * client has already disconnected and will be converted to
1201 * GPG_ERR_EOF during assuan_process_next().
1203 rc
= send_msg_queue (thd
);
1204 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1209 /* Don't do pthread_exit() here because any set pthread_cleanup_push
1210 * functions would be called after a command failed but then the client
1211 * exited normally which may lead to a double free. */
1212 pthread_cleanup_pop (1);
1217 xml_import (const char *filename
, const char *outfile
,
1218 const char *keygrip
, const char *sign_keygrip
,
1219 const char *keyfile
, int no_passphrase
, const char *cipher
,
1220 const char *params
, uint64_t iterations
)
1229 struct crypto_s
*crypto
= NULL
;
1232 int algo
= cipher
? cipher_string_to_gcrypt ((char *) cipher
) :
1237 log_write ("ERR %i: %s", gpg_error (GPG_ERR_CIPHER_ALGO
),
1238 pwmd_strerror (GPG_ERR_CIPHER_ALGO
));
1242 if (stat (filename
, &st
) == -1)
1244 log_write ("%s: %s", filename
,
1245 pwmd_strerror (gpg_error_from_errno (errno
)));
1249 rc
= init_client_crypto (&crypto
);
1253 memcpy (&crypto
->save
.hdr
, &crypto
->hdr
, sizeof (file_header_t
));
1254 crypto
->save
.hdr
.flags
= set_cipher_flag (crypto
->save
.hdr
.flags
, algo
);
1255 log_write (_("Importing XML from '%s'. Output will be written to '%s' ..."),
1258 if ((fd
= open (filename
, O_RDONLY
)) == -1)
1260 log_write ("%s: %s", filename
,
1261 pwmd_strerror (gpg_error_from_errno (errno
)));
1265 if ((xmlbuf
= xmalloc (st
.st_size
+ 1)) == NULL
)
1268 log_write ("%s(%i): %s", __FILE__
, __LINE__
,
1269 pwmd_strerror (GPG_ERR_ENOMEM
));
1273 if (read (fd
, xmlbuf
, st
.st_size
) == -1)
1275 rc
= gpg_error_from_errno (errno
);
1277 log_write ("%s: %s", filename
, pwmd_strerror (rc
));
1282 xmlbuf
[st
.st_size
] = 0;
1284 * Make sure the document validates.
1286 if ((doc
= xmlReadDoc (xmlbuf
, NULL
, "UTF-8", XML_PARSE_NOBLANKS
)) == NULL
)
1288 log_write ("xmlReadDoc() failed");
1294 xmlNodePtr n
= xmlDocGetRootElement (doc
);
1295 if (n
&& !xmlStrEqual (n
->name
, (xmlChar
*) "pwmd"))
1297 log_write (_("Could not find root \"pwmd\" element."));
1298 rc
= GPG_ERR_BAD_DATA
;
1302 rc
= validate_import (NULL
, n
? n
->children
: n
);
1306 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
1311 xmlDocDumpMemory (doc
, &xml
, &len
);
1313 crypto
->save
.hdr
.s2k_count
= iterations
;
1316 rc
= export_common (NULL
, 0, crypto
, xml
, len
, outfile
, keyfile
, &key
,
1317 &keylen
, 0, 0, no_passphrase
);
1319 log_write (_("Success!"));
1324 rc
= agent_set_pinentry_options (crypto
->agent
);
1326 rc
= agent_export_common (crypto
, keygrip
, sign_keygrip
, no_passphrase
,
1327 xml
, len
, outfile
, params
, keyfile
);
1335 send_error (NULL
, rc
);
1339 cleanup_crypto (&crypto
);
1343 cleanup_crypto (&crypto
);
1348 do_cache_push (const char *filename
, struct crypto_s
*crypto
)
1350 unsigned char md5file
[16];
1355 struct cache_data_s
*cdata
;
1360 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1363 if (valid_filename (filename
) == 0)
1365 log_write (_("%s: Invalid characters in filename"), filename
);
1369 rc
= lock_flock (NULL
, crypto
->filename
, LOCK_SH
, &fd
);
1371 rc
= decrypt_common (NULL
, 0, crypto
, filename
, &key
, &keylen
, NULL
, NULL
);
1378 rc
= parse_doc ((char *) crypto
->plaintext
, crypto
->plaintext_len
, &doc
);
1382 log_write ("%s", pwmd_strerror (rc
));
1387 gcry_md_hash_buffer (GCRY_MD_MD5
, md5file
, filename
, strlen (filename
));
1388 cdata
= xcalloc (1, sizeof (struct cache_data_s
));
1393 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM
));
1398 rc
= get_checksum (filename
, &crc
, &len
);
1402 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
1404 free_cache_data_once (cdata
);
1410 rc
= encrypt_xml (NULL
, cache_key
, cache_keysize
, GCRY_CIPHER_AES
,
1411 crypto
->plaintext
, crypto
->plaintext_len
, &cdata
->doc
,
1412 &cdata
->doclen
, &cache_iv
, &cache_blocksize
);
1413 if (!rc
&& !IS_PKI (crypto
))
1416 cdata
->keylen
= keylen
;
1423 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
1425 free_cache_data_once (cdata
);
1430 if (use_agent
&& IS_PKI (crypto
))
1432 gcry_sexp_build ((gcry_sexp_t
*) & cdata
->pubkey
, NULL
, "%S",
1434 gcry_sexp_build ((gcry_sexp_t
*) & cdata
->sigkey
, NULL
, "%S",
1435 crypto
->sigpkey_sexp
);
1439 int timeout
= config_get_integer (filename
, "cache_timeout");
1440 cache_add_file (md5file
, crypto
->grip
, cdata
, timeout
);
1441 log_write (_("Successfully added '%s' to the cache."), filename
);
1446 init_client (int fd
, const char *addr
)
1449 struct client_thread_s
*new = xcalloc (1, sizeof (struct client_thread_s
));
1454 return GPG_ERR_ENOMEM
;
1457 MUTEX_LOCK (&cn_mutex
);
1458 pthread_cleanup_push (cleanup_mutex_cb
, &cn_mutex
);
1460 if (pipe (new->status_msg_pipe
) == -1)
1461 rc
= gpg_error_from_errno (errno
);
1465 if (fcntl (new->status_msg_pipe
[0], F_SETFL
, O_NONBLOCK
) == -1)
1466 rc
= gpg_error_from_errno (errno
);
1469 if (fcntl (new->status_msg_pipe
[1], F_SETFL
, O_NONBLOCK
) == -1)
1470 rc
= gpg_error_from_errno (errno
);
1472 pthread_mutex_init (&new->status_mutex
, NULL
);
1478 new->remote
= addr
? 1 : 0;
1481 rc
= create_thread (client_thread
, new, &new->tid
, 1);
1484 close (new->status_msg_pipe
[0]);
1485 close (new->status_msg_pipe
[1]);
1486 pthread_mutex_destroy (&new->status_mutex
);
1492 struct slist_s
*list
= slist_append (cn_thread_list
, new);
1496 cn_thread_list
= list
;
1499 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1500 (pthread_t
*) new->tid
, fd
, addr
);
1502 new->peeraddr
= str_dup (addr
);
1506 log_write (_("new connection: tid=%p, fd=%i"),
1507 (pthread_t
*) new->tid
, fd
);
1510 rc
= GPG_ERR_ENOMEM
;
1513 pthread_cleanup_pop (1);
1519 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1520 pwmd_strerror (rc
));
1526 keepalive_thread (void *arg
)
1528 #ifndef HAVE_PTHREAD_CANCEL
1529 int *n
= xmalloc (sizeof (int));
1532 pthread_setspecific (signal_thread_key
, n
);
1536 #ifdef HAVE_PR_SET_NAME
1537 prctl (PR_SET_NAME
, "keepalive");
1539 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1543 int n
= config_get_integer ("global", "keepalive_interval");
1544 struct timeval tv
= { n
, 0 };
1545 #ifndef HAVE_PTHREAD_CANCEL
1548 sigusr2
= (int *) pthread_getspecific (signal_thread_key
);
1553 send_status_all (STATUS_KEEPALIVE
, NULL
);
1554 select (0, NULL
, NULL
, NULL
, &tv
);
1561 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1563 get_in_addr (struct sockaddr
*sa
)
1565 if (sa
->sa_family
== AF_INET
)
1566 return &(((struct sockaddr_in
*) sa
)->sin_addr
);
1568 return &(((struct sockaddr_in6
*) sa
)->sin6_addr
);
1572 tcp_accept_thread (void *arg
)
1574 int sockfd
= *(int *) arg
;
1575 #ifndef HAVE_PTHREAD_CANCEL
1576 int *n
= xmalloc (sizeof (int));
1579 pthread_setspecific (signal_thread_key
, n
);
1581 fcntl (sockfd
, F_SETFL
, O_NONBLOCK
);
1584 #ifdef HAVE_PR_SET_NAME
1585 prctl (PR_SET_NAME
, "tcp_accept");
1587 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1591 struct sockaddr_storage raddr
;
1592 socklen_t slen
= sizeof (raddr
);
1595 char s
[INET6_ADDRSTRLEN
];
1596 struct timeval tv
= { 0, ACCEPT_TIMEOUT
};
1597 #ifndef HAVE_PTHREAD_CANCEL
1600 sigusr2
= (int *) pthread_getspecific (signal_thread_key
);
1605 fd
= accept (sockfd
, (struct sockaddr
*) &raddr
, &slen
);
1608 if (errno
== EMFILE
|| errno
== ENFILE
)
1609 log_write ("accept(): %s",
1610 pwmd_strerror (gpg_error_from_errno (errno
)));
1611 else if (errno
!= EAGAIN
)
1613 if (!quit
) // probably EBADF
1614 log_write ("accept(): %s", strerror (errno
));
1619 #ifndef HAVE_PTHREAD_CANCEL
1620 select (0, NULL
, NULL
, NULL
, &tv
);
1631 inet_ntop (raddr
.ss_family
, get_in_addr ((struct sockaddr
*) &raddr
),
1633 (void) init_client (fd
, s
);
1634 n
= config_get_integer ("global", "tcp_wait");
1637 tv
.tv_sec
= (n
* 100000) / 100000;
1638 tv
.tv_usec
= (n
* 100000) % 100000;
1639 select (0, NULL
, NULL
, NULL
, &tv
);
1647 start_stop_tls_with_protocol (int ipv6
, int term
)
1649 struct addrinfo hints
, *servinfo
, *p
;
1650 int port
= config_get_integer ("global", "tcp_port");
1654 int *fd
= ipv6
? &tls6_fd
: &tls_fd
;
1656 if (term
|| config_get_boolean ("global", "enable_tcp") == 0)
1662 #ifdef HAVE_PTHREAD_CANCEL
1663 pthread_cancel (tls6_tid
);
1665 pthread_kill (tls6_tid
, SIGUSR2
);
1667 pthread_join (tls6_tid
, NULL
);
1670 shutdown (tls6_fd
, SHUT_RDWR
);
1680 #ifdef HAVE_PTHREAD_CANCEL
1681 pthread_cancel (tls_tid
);
1683 pthread_kill (tls_tid
, SIGUSR2
);
1685 pthread_join (tls_tid
, NULL
);
1688 shutdown (tls_fd
, SHUT_RDWR
);
1694 /* A client may still be connected. */
1695 if (!quit
&& x509_cred
!= NULL
)
1696 tls_deinit_params ();
1701 if ((ipv6
&& tls6_fd
!= -1) || (!ipv6
&& tls_fd
!= -1))
1704 memset (&hints
, 0, sizeof (hints
));
1705 hints
.ai_family
= ipv6
? AF_INET6
: AF_INET
;
1706 hints
.ai_socktype
= SOCK_STREAM
;
1707 hints
.ai_flags
= AI_PASSIVE
;
1708 snprintf (buf
, sizeof (buf
), "%i", port
);
1710 if ((n
= getaddrinfo (NULL
, buf
, &hints
, &servinfo
)) == -1)
1712 log_write ("getaddrinfo(): %s", gai_strerror (n
));
1716 for (n
= 0, p
= servinfo
; p
!= NULL
; p
= p
->ai_next
)
1720 if ((ipv6
&& p
->ai_family
!= AF_INET6
)
1721 || (!ipv6
&& p
->ai_family
!= AF_INET
))
1724 if ((*fd
= socket (p
->ai_family
, p
->ai_socktype
, p
->ai_protocol
)) == -1)
1726 log_write ("socket(): %s", strerror (errno
));
1730 if (setsockopt (*fd
, SOL_SOCKET
, SO_REUSEADDR
, &r
, sizeof (int)) == -1)
1732 log_write ("setsockopt(): %s",
1733 pwmd_strerror (gpg_error_from_errno (errno
)));
1734 freeaddrinfo (servinfo
);
1738 if (bind (*fd
, p
->ai_addr
, p
->ai_addrlen
) == -1)
1741 log_write ("bind(): %s",
1742 pwmd_strerror (gpg_error_from_errno (errno
)));
1750 freeaddrinfo (servinfo
);
1755 #if HAVE_DECL_SO_BINDTODEVICE != 0
1756 char *tmp
= config_get_string ("global", "tcp_interface");
1757 if (tmp
&& setsockopt (*fd
, SOL_SOCKET
, SO_BINDTODEVICE
, tmp
,
1758 strlen (tmp
)) == -1)
1760 log_write ("setsockopt(): %s",
1761 pwmd_strerror (gpg_error_from_errno (errno
)));
1769 if (x509_cred
== NULL
)
1771 char *tmp
= config_get_string ("global", "tls_dh_level");
1773 rc
= tls_init_params (tmp
);
1779 if (listen (*fd
, 0) == -1)
1781 log_write ("listen(): %s", strerror (errno
));
1786 rc
= create_thread (tcp_accept_thread
, fd
, &tls6_tid
, 0);
1788 rc
= create_thread (tcp_accept_thread
, fd
, &tls_tid
, 0);
1792 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1793 pwmd_strerror (rc
));
1805 start_stop_tls_with_protocol (0, 1);
1818 start_stop_tls (int term
)
1820 char *s
= config_get_string ("global", "tcp_bind");
1826 if (!strcmp (s
, "any"))
1828 b
= start_stop_tls_with_protocol (0, term
);
1830 b
= start_stop_tls_with_protocol (1, term
);
1832 else if (!strcmp (s
, "ipv4"))
1833 b
= start_stop_tls_with_protocol (0, term
);
1834 else if (!strcmp (s
, "ipv6"))
1835 b
= start_stop_tls_with_protocol (1, term
);
1845 accept_thread (void *arg
)
1847 int sockfd
= *(int *) arg
;
1848 #ifndef HAVE_PTHREAD_CANCEL
1849 int *n
= xmalloc (sizeof (int));
1852 pthread_setspecific (signal_thread_key
, n
);
1854 fcntl (sockfd
, F_SETFL
, O_NONBLOCK
);
1857 #ifdef HAVE_PR_SET_NAME
1858 prctl (PR_SET_NAME
, "accept");
1860 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1864 socklen_t slen
= sizeof (struct sockaddr_un
);
1865 struct sockaddr_un raddr
;
1867 #ifndef HAVE_PTHREAD_CANCEL
1868 struct timeval tv
= { 0, ACCEPT_TIMEOUT
};
1869 int *sigusr2
= (int *) pthread_getspecific (signal_thread_key
);
1875 fd
= accept (sockfd
, (struct sockaddr
*) &raddr
, &slen
);
1878 if (errno
== EMFILE
|| errno
== ENFILE
)
1879 log_write ("accept(): %s",
1880 pwmd_strerror (gpg_error_from_errno (errno
)));
1881 else if (errno
!= EAGAIN
)
1883 if (!quit
) // probably EBADF
1884 log_write ("accept(): %s",
1885 pwmd_strerror (gpg_error_from_errno (errno
)));
1890 #ifndef HAVE_PTHREAD_CANCEL
1891 select (0, NULL
, NULL
, NULL
, &tv
);
1896 (void) init_client (fd
, NULL
);
1899 /* Just in case accept() failed for some reason other than EBADF */
1905 cache_timer_thread (void *arg
)
1907 #ifndef HAVE_PTHREAD_CANCEL
1908 int *n
= xmalloc (sizeof (int));
1911 pthread_setspecific (signal_thread_key
, n
);
1915 #ifdef HAVE_PR_SET_NAME
1916 prctl (PR_SET_NAME
, "cache timer");
1918 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1922 struct timeval tv
= { 1, 0 };
1923 #ifndef HAVE_PTHREAD_CANCEL
1926 n
= (int *) pthread_getspecific (signal_thread_key
);
1931 select (0, NULL
, NULL
, NULL
, &tv
);
1932 cache_adjust_timeout ();
1939 signal_loop (sigset_t sigset
)
1948 sigwait (&sigset
, &sig
);
1951 log_write (_("caught signal %i (%s)"), sig
, strsignal (sig
));
1956 pthread_cond_signal (&rcfile_cond
);
1959 log_write (_("clearing file cache"));
1961 send_status_all (STATUS_CACHE
, NULL
);
1980 log_write (_ ("Caught signal %i (%s). Exiting."), sig
, strsignal (sig
));
1981 #ifdef HAVE_BACKTRACE
1982 BACKTRACE (__FUNCTION__
);
1988 waiting_for_exit (void *arg
)
1991 #ifndef HAVE_PTHREAD_CANCEL
1992 int *n
= xmalloc (sizeof (int));
1995 pthread_setspecific (signal_thread_key
, n
);
1999 #ifdef HAVE_PR_SET_NAME
2000 prctl (PR_SET_NAME
, "exiting");
2002 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
2003 log_write (_("waiting for all clients to disconnect"));
2004 MUTEX_LOCK (&quit_mutex
);
2005 pthread_cleanup_push (cleanup_mutex_cb
, &quit_mutex
);
2012 MUTEX_LOCK (&cn_mutex
);
2013 n
= slist_length (cn_thread_list
);
2014 MUTEX_UNLOCK (&cn_mutex
);
2018 #ifndef HAVE_PTHREAD_CANCEL
2019 int *s
= (int *) pthread_getspecific (signal_thread_key
);
2026 log_write (_("%i clients remain"), n
);
2030 INIT_TIMESPEC (SIG_TIMEOUT
, ts
);
2031 pthread_cond_timedwait (&quit_cond
, &quit_mutex
, &ts
);
2034 kill (getpid (), SIGQUIT
);
2035 pthread_cleanup_pop (1);
2040 server_loop (int sockfd
, char **socketpath
)
2042 pthread_t accept_tid
;
2043 pthread_t cache_timeout_tid
;
2044 int cancel_timeout_thread
= 0, cancel_accept_thread
= 0;
2045 int cancel_keepalive_thread
= 0;
2052 sigemptyset (&sigset
);
2055 sigaddset (&sigset
, SIGTERM
);
2056 sigaddset (&sigset
, SIGINT
);
2058 /* Clears the file cache. */
2059 sigaddset (&sigset
, SIGUSR1
);
2061 /* Configuration file reloading. */
2062 sigaddset (&sigset
, SIGHUP
);
2064 /* For exiting cleanly. */
2065 sigaddset (&sigset
, SIGQUIT
);
2067 #ifndef HAVE_PTHREAD_CANCEL
2069 The socket, cache and rcfile threads use this signal when
2070 pthread_cancel() is unavailable. Prevent the main thread from
2071 catching this signal from another process.
2073 sigaddset (&sigset
, SIGUSR2
);
2076 /* When mem.c cannot find a pointer in the list (double free). */
2077 signal (SIGABRT
, catchsig
);
2078 sigaddset (&sigset
, SIGABRT
);
2079 sigprocmask (SIG_BLOCK
, &sigset
, NULL
);
2081 #ifndef HAVE_PTHREAD_CANCEL
2082 /* Remove this signal from the watched signals in signal_loop(). */
2083 sigdelset (&sigset
, SIGUSR2
);
2086 /* Ignored everywhere. When a client disconnects abnormally this signal
2087 * gets raised. It isn't needed though because client_thread() will check
2088 * for rcs even after the client disconnects. */
2089 signal (SIGPIPE
, SIG_IGN
);
2091 /* Can show a backtrace of the stack in the log. */
2092 signal (SIGSEGV
, catchsig
);
2095 /* Needs to be done after the fork(). */
2096 if (!start_stop_tls (0))
2103 pthread_mutex_init (&quit_mutex
, NULL
);
2104 pthread_cond_init (&quit_cond
, NULL
);
2105 char *p
= get_username (getuid());
2106 log_write (_("%s started for user %s"), PACKAGE_STRING
, p
);
2110 if (config_get_boolean ("global", "enable_tcp"))
2111 log_write (_("Listening on %s and TCP port %i"), *socketpath
,
2112 config_get_integer ("global", "tcp_port"));
2114 log_write (_("Listening on %s"), *socketpath
);
2116 log_write (_("Listening on %s"), *socketpath
);
2119 rc
= create_thread (keepalive_thread
, NULL
, &keepalive_tid
, 0);
2122 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2123 pwmd_strerror (rc
));
2127 cancel_keepalive_thread
= 1;
2128 rc
= create_thread (reload_rcfile_thread
, NULL
, &rcfile_tid
, 0);
2131 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2132 pwmd_strerror (rc
));
2136 rc
= create_thread (cache_timer_thread
, NULL
, &cache_timeout_tid
, 0);
2139 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2140 pwmd_strerror (rc
));
2144 cancel_timeout_thread
= 1;
2145 rc
= create_thread (accept_thread
, &sockfd
, &accept_tid
, 0);
2148 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2149 pwmd_strerror (rc
));
2153 cancel_accept_thread
= 1;
2155 signal_loop (sigset
);
2161 * We're out of the main server loop. This happens when a signal was sent
2162 * to terminate the daemon. We'll wait for all clients to disconnect
2163 * before exiting but exit immediately if another termination signal is
2166 if (cancel_accept_thread
)
2168 #ifdef HAVE_PTHREAD_CANCEL
2169 int n
= pthread_cancel (accept_tid
);
2171 int n
= pthread_kill (accept_tid
, SIGUSR2
);
2174 pthread_join (accept_tid
, NULL
);
2180 shutdown (sockfd
, SHUT_RDWR
);
2182 unlink (*socketpath
);
2183 xfree (*socketpath
);
2185 MUTEX_LOCK (&cn_mutex
);
2186 n
= slist_length (cn_thread_list
);
2187 MUTEX_UNLOCK (&cn_mutex
);
2193 rc
= create_thread (waiting_for_exit
, NULL
, &tid
, 0);
2196 if (signal_loop (sigset
))
2198 log_write (_("Received second termination request. Exiting."));
2199 #ifdef HAVE_PTHREAD_CANCEL
2200 pthread_cancel (tid
);
2202 pthread_kill (tid
, SIGUSR2
);
2204 pthread_join (tid
, NULL
);
2208 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2209 pwmd_strerror (rc
));
2212 if (cancel_timeout_thread
)
2214 #ifdef HAVE_PTHREAD_CANCEL
2215 pthread_cancel (cache_timeout_tid
);
2217 pthread_kill (cache_timeout_tid
, SIGUSR2
);
2219 pthread_join (cache_timeout_tid
, NULL
);
2222 if (cancel_keepalive_thread
)
2224 #ifdef HAVE_PTHREAD_CANCEL
2225 pthread_cancel (keepalive_tid
);
2227 pthread_kill (keepalive_tid
, SIGUSR2
);
2229 pthread_join (keepalive_tid
, NULL
);
2232 cleanup_all_clients (0);
2237 pthread_cond_destroy (&quit_cond
);
2238 pthread_mutex_destroy (&quit_mutex
);
2239 return segv
? EXIT_FAILURE
: EXIT_SUCCESS
;;
2246 ("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
2250 /* This is called from cache.c:clear_once(). See
2251 * command.c:clearcache_command() for details about lock checking.
2254 free_cache_data (file_cache_t
* cache
)
2256 gpg_error_t rc
= GPG_ERR_NO_DATA
;
2258 struct client_thread_s
*found
= NULL
;
2265 MUTEX_LOCK (&cn_mutex
);
2266 pthread_cleanup_push (cleanup_mutex_cb
, &cn_mutex
);
2267 t
= slist_length (cn_thread_list
);
2269 for (i
= 0; i
< t
; i
++)
2271 struct client_thread_s
*thd
= slist_nth_data (cn_thread_list
, i
);
2276 if (!memcmp (thd
->cl
->md5file
, cache
->filename
,
2277 sizeof (cache
->filename
)))
2279 if (pthread_equal (pthread_self (), thd
->tid
))
2286 /* Continue trying to find a client who has the same file open and
2287 * also has a lock. */
2288 rc
= cache_lock_mutex (thd
->cl
->ctx
, thd
->cl
->md5file
, -1, 0, -1);
2298 if (self
&& (!rc
|| rc
== GPG_ERR_NO_DATA
))
2299 rc
= cache_lock_mutex (found
->cl
->ctx
, found
->cl
->md5file
, -1, 0, -1);
2301 if (exiting
|| !rc
|| rc
== GPG_ERR_NO_DATA
)
2303 free_cache_data_once (cache
->data
);
2305 cache
->defer_clear
= 0;
2306 cache
->timeout
= -1;
2309 cache_unlock_mutex (found
->cl
->md5file
, 0);
2315 cache
->defer_clear
= 1;
2317 pthread_cleanup_pop (1);
2323 convert_v2_datafile (const char *filename
, const char *cipher
,
2324 const char *keyfile
, const char *keygrip
,
2325 const char *sign_keygrip
, int nopass
,
2326 const char *outfile
, const char *keyparam
,
2327 uint64_t iterations
)
2332 struct crypto_s
*crypto
= NULL
;
2338 if (outfile
[0] == '-' && outfile
[1] == 0)
2341 log_write (_("Converting version 2 data file \"%s\" ..."), filename
);
2342 if (access (filename
, R_OK
) == -1)
2344 log_write ("%s: %s", filename
,
2345 pwmd_strerror (gpg_error_from_errno (errno
)));
2351 log_write (_("Using passphrase file \"%s\" for decryption ..."),
2353 if (access (keyfile
, R_OK
) == -1)
2355 log_write ("%s: %s", keyfile
,
2356 pwmd_strerror (gpg_error_from_errno (errno
)));
2361 rc
= read_v2_datafile (filename
, keyfile
, &data
, &datalen
, &ver
, &algo
);
2364 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
2370 algo
= cipher_string_to_gcrypt (cipher
);
2373 rc
= GPG_ERR_CIPHER_ALGO
;
2382 rc
= parse_doc (data
, datalen
, &doc
);
2386 rc
= convert_pre_212_elements (doc
);
2391 xmlDocDumpFormatMemory (doc
, (xmlChar
**) & data
, (int *) &datalen
,
2394 rc
= GPG_ERR_ENOMEM
;
2402 rc
= init_client_crypto (&crypto
);
2405 memcpy (&crypto
->save
.hdr
, &crypto
->hdr
, sizeof (file_header_t
));
2406 crypto
->save
.hdr
.flags
= set_cipher_flag (crypto
->save
.hdr
.flags
, algo
);
2407 crypto
->save
.hdr
.s2k_count
= iterations
;
2411 rc
= export_common (NULL
, 0, crypto
, data
, datalen
, outfile
, keyfile
,
2412 &key
, &keylen
, 0, 0, nopass
);
2417 rc
= agent_set_pinentry_options (crypto
->agent
);
2419 rc
= agent_export_common (crypto
, keygrip
, sign_keygrip
, nopass
,
2420 data
, datalen
, outfile
, keyparam
,
2421 no_passphrase_file
? NULL
: keyfile
);
2425 log_write (_("Output written to \"%s\"."),
2426 outfile
? outfile
: "<stdout>");
2436 cleanup_crypto (&crypto
);
2439 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
2444 usage (const char *pn
, int status
)
2446 FILE *fp
= status
== EXIT_FAILURE
? stderr
: stdout
;
2448 fprintf (fp
, _("Usage: %s [OPTIONS] [file1] [...]\n"
2449 " -f, --rcfile=filename load the specfied configuration file\n"
2450 " (~/.pwmd/config)\n"
2451 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2452 " --kill terminate an existing instance of pwmd\n"
2454 " --use-agent[=integer] enable/disable use of gpg-agent\n"
2456 " -n, --no-fork run as a foreground process\n"
2457 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2458 " --ignore, --force ignore file errors during startup\n"
2459 " --debug-level=keywords log protocol output (see manual for details)\n"
2460 " -o, --outfile=filename output file when importing or converting\n"
2461 " -C, --convert=filename convert a version 2 data file to version 3\n"
2462 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2463 " -k, --passphrase-file=file for use when importing or converting\n"
2464 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2466 " --no-passphrase when importing or converting\n"
2467 " --keygrip=hex public key to use when encrypting\n"
2468 " --sign-keygrip=hex private key to use when signing\n"
2469 " --keyparam=s-exp custom key parameters to use (RSA-2048)\n"
2470 " --cipher=string encryption cipher (aes256)\n"
2471 " --cipher-iterations=N cipher iteration count (alias for --s2k-count)\n"
2472 " --s2k-count=N hash iteration count (>65536, calibrated)\n"
2473 " --help this help text\n"
2474 " --version show version and compile time features\n"),
2480 unlink_stale_socket (const char *sock
, const char *pidfile
)
2482 log_write (_ ("removing stale socket %s"), sock
);
2488 test_pidfile (const char *path
, const char *sock
, char *buf
, size_t buflen
,
2489 char **pidfile
, int create
, mode_t mode
, int terminate
)
2497 snprintf (buf
, buflen
, "%s/%s.pid", homedir
, sock
);
2498 *pidfile
= str_dup (buf
);
2499 fd
= open (buf
, O_RDONLY
);
2502 fd
= open (*pidfile
, O_CREAT
|O_WRONLY
|O_TRUNC
, mode
);
2506 if (!create
&& errno
!= ENOENT
)
2508 log_write ("%s: %s", buf
, pwmd_strerror (errno
));
2513 else if (!create
&& !terminate
)
2516 log_write ("%s: %s", *pidfile
, strerror (errno
));
2522 snprintf (buf
, buflen
, "%i", getpid ());
2523 write (fd
, buf
, strlen (buf
));
2528 len
= read (fd
, buf
, buflen
);
2532 unlink_stale_socket (path
, *pidfile
);
2536 if (sscanf (buf
, "%5i", &pid
) != 1 || pid
== 0)
2540 unlink_stale_socket (path
, *pidfile
);
2545 if (kill (pid
, 0) == -1)
2547 unlink_stale_socket (path
, *pidfile
);
2553 if (kill (pid
, SIGTERM
) == -1)
2554 log_write ("%s: %s", path
, pwmd_strerror (errno
));
2557 log_write (_ ("an instance for socket %s is already running"), path
);
2565 main (int argc
, char *argv
[])
2568 struct sockaddr_un addr
;
2570 char *socketpath
= NULL
, *socketdir
, *socketname
= NULL
;
2571 char *socketarg
= NULL
;
2572 char *datadir
= NULL
;
2573 char *pidfile
= NULL
;
2577 char **cache_push
= NULL
;
2578 char *import
= NULL
, *keygrip
= NULL
, *sign_keygrip
= NULL
;
2579 char *keyparam
= NULL
;
2580 int estatus
= EXIT_FAILURE
;
2582 char *outfile
= NULL
;
2585 int show_version
= 0;
2587 int no_passphrase
= 0;
2589 char *convertfile
= NULL
;
2590 char *cipher
= NULL
;
2591 char *keyfile
= NULL
;
2592 uint64_t s2k_count
= 0;
2594 char *debug_level_opt
= NULL
;
2597 /* Must maintain the same order as longopts[] */
2600 OPT_VERSION
, OPT_HELP
,
2604 OPT_DEBUG_LEVEL
, OPT_HOMEDIR
, OPT_NO_FORK
, OPT_DISABLE_DUMP
,
2605 OPT_IGNORE
, OPT_FORCE
, OPT_RCFILE
, OPT_CONVERT
,
2606 OPT_PASSPHRASE_FILE
, OPT_IMPORT
, OPT_OUTFILE
,
2607 OPT_NO_PASSPHRASE_FILE
, OPT_KEYGRIP
, OPT_SIGN_KEYGRIP
,
2608 OPT_KEYPARAM
, OPT_CIPHER
, OPT_ITERATIONS
, OPT_S2K_COUNT
,
2609 OPT_NO_PASSPHRASE
, OPT_KILL
2611 const char *optstring
= "nf:C:k:I:o:";
2612 const struct option longopts
[] = {
2613 {"version", no_argument
, 0, 0},
2614 {"help", no_argument
, 0, 0},
2616 {"use-agent", optional_argument
, 0, 0},
2618 {"debug-level", required_argument
, 0, 0},
2619 {"homedir", required_argument
, 0, 0},
2620 {"no-fork", no_argument
, 0, 'n'},
2621 {"disable_dump", no_argument
, 0, 0},
2622 {"ignore", no_argument
, 0, 0},
2623 {"force", no_argument
, 0, 0},
2624 {"rcfile", required_argument
, 0, 'f'},
2625 {"convert", required_argument
, 0, 'C'},
2626 {"passphrase-file", required_argument
, 0, 'k'},
2627 {"import", required_argument
, 0, 'I'},
2628 {"outfile", required_argument
, 0, 'o'},
2629 {"no-passphrase-file", no_argument
, 0, 0},
2630 {"keygrip", required_argument
, 0, 0},
2631 {"sign-keygrip", required_argument
, 0, 0},
2632 {"keyparam", required_argument
, 0, 0},
2633 {"cipher", required_argument
, 0, 0},
2634 {"cipher-iterations", required_argument
, 0, 0},
2635 {"s2k-count", required_argument
, 0, 0},
2636 {"no-passphrase", no_argument
, 0, 0},
2637 {"kill", no_argument
, 0, 0},
2644 #ifdef HAVE_SETRLIMIT
2647 rl
.rlim_cur
= rl
.rlim_max
= 0;
2649 if (setrlimit (RLIMIT_CORE
, &rl
) != 0)
2650 err (EXIT_FAILURE
, "setrlimit()");
2653 #ifdef HAVE_PR_SET_DUMPABLE
2654 prctl (PR_SET_DUMPABLE
, 0);
2659 setlocale (LC_ALL
, "");
2660 bindtextdomain ("pwmd", LOCALEDIR
);
2661 textdomain ("pwmd");
2669 if (setup_crypto ())
2670 exit (EXIT_FAILURE
);
2673 gnutls_global_init ();
2674 gnutls_global_set_log_level (1);
2675 gnutls_global_set_log_function (tls_log
);
2676 gnutls_global_set_audit_log_function (tls_audit_log
);
2680 xmlMemSetup (xfree
, xmalloc
, xrealloc
, str_dup
);
2688 while ((opt
= getopt_long (argc
, argv
, optstring
, longopts
, &optindex
))
2697 convertfile
= optarg
;
2712 rcfile
= str_dup (optarg
);
2715 usage (argv
[0], EXIT_FAILURE
);
2728 use_agent
= optarg
&& *optarg
? atoi (optarg
) : 1;
2729 if (use_agent
< 0 || use_agent
> 1)
2733 case OPT_DEBUG_LEVEL
:
2734 debug_level_opt
= optarg
;
2737 homedir
= str_dup (optarg
);
2742 case OPT_DISABLE_DUMP
:
2750 rcfile
= str_dup (optarg
);
2753 convertfile
= optarg
;
2755 case OPT_PASSPHRASE_FILE
:
2764 case OPT_NO_PASSPHRASE_FILE
:
2765 no_passphrase_file
= 1;
2770 case OPT_SIGN_KEYGRIP
:
2771 sign_keygrip
= optarg
;
2779 case OPT_ITERATIONS
:
2781 s2k_count
= strtoull (optarg
, NULL
, 10);
2783 case OPT_NO_PASSPHRASE
:
2798 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015\n"
2800 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2801 "Compile time features:\n%s"), PACKAGE_STRING
,
2804 "+PWMD_HOMEDIR=" PWMD_HOMEDIR
"\n"
2837 exit (EXIT_SUCCESS
);
2842 homedir
= str_dup(PWMD_HOMEDIR
);
2844 homedir
= str_asprintf ("%s/.pwmd", get_home_dir());
2847 if (mkdir (homedir
, 0700) == -1 && errno
!= EEXIST
)
2848 err (EXIT_FAILURE
, "%s", homedir
);
2850 snprintf (buf
, sizeof (buf
), "%s/data", homedir
);
2851 if (mkdir (buf
, 0700) == -1 && errno
!= EEXIST
)
2852 err (EXIT_FAILURE
, "%s", buf
);
2854 datadir
= str_dup (buf
);
2855 pthread_mutexattr_t attr
;
2856 pthread_mutexattr_init (&attr
);
2857 pthread_mutexattr_settype (&attr
, PTHREAD_MUTEX_RECURSIVE
);
2858 pthread_mutex_init (&rcfile_mutex
, &attr
);
2859 pthread_cond_init (&rcfile_cond
, NULL
);
2860 pthread_mutex_init (&cn_mutex
, &attr
);
2861 pthread_mutexattr_destroy (&attr
);
2862 pthread_key_create (&last_error_key
, free_key
);
2863 #ifndef HAVE_PTHREAD_CANCEL
2864 pthread_key_create (&signal_thread_key
, free_key
);
2868 rcfile
= str_asprintf ("%s/config", homedir
);
2870 global_config
= config_parse (rcfile
, 0);
2872 exit (EXIT_FAILURE
);
2875 if (use_agent
== -1)
2876 use_agent
= config_get_boolean ("global", "use_agent");
2881 if (debug_level_opt
)
2882 debug_level
= str_split (debug_level_opt
, ",", 0);
2884 x
= config_get_int_param (global_config
, "global", "priority", &exists
);
2885 if (exists
&& x
!= atoi(INVALID_PRIORITY
))
2888 if (setpriority (PRIO_PROCESS
, 0, x
) == -1)
2890 log_write ("setpriority(): %s",
2891 pwmd_strerror (gpg_error_from_errno (errno
)));
2895 #ifdef HAVE_MLOCKALL
2896 if (disable_mlock
== 0 && mlockall (MCL_CURRENT
| MCL_FUTURE
) == -1)
2898 log_write ("mlockall(): %s",
2899 pwmd_strerror (gpg_error_from_errno (errno
)));
2904 rc
= cache_init (free_cache_data
);
2907 log_write ("pwmd: ERR %i: %s", rc
,
2908 gpg_err_code (rc
) == GPG_ERR_UNKNOWN_VERSION
2909 ? _("incompatible gpg-agent version: 2.1.0 or later required")
2910 : pwmd_strerror (rc
));
2915 s2k_count
= config_get_ulonglong (NULL
, "s2k_count");
2919 if (!outfile
|| !*outfile
|| argc
!= optind
)
2920 usage (argv
[0], EXIT_FAILURE
);
2922 estatus
= convert_v2_datafile (convertfile
, cipher
, keyfile
, keygrip
,
2923 sign_keygrip
, no_passphrase
, outfile
,
2924 keyparam
, s2k_count
);
2925 config_free (global_config
);
2932 if (!outfile
|| !*outfile
|| argc
!= optind
)
2933 usage (argv
[0], EXIT_FAILURE
);
2935 if (outfile
&& outfile
[0] == '-' && outfile
[1] == 0)
2938 estatus
= xml_import (import
, outfile
, keygrip
, sign_keygrip
, keyfile
,
2939 no_passphrase
, cipher
, keyparam
, s2k_count
);
2940 config_free (global_config
);
2945 p
= config_get_string ("global", "socket_path");
2947 p
= str_asprintf ("%s/socket", homedir
);
2949 socketarg
= expand_homedir (p
);
2953 disable_list_and_dump
= config_get_boolean ("global",
2954 "disable_list_and_dump");
2956 disable_list_and_dump
= secure
;
2958 cache_push
= config_get_list ("global", "cache_push");
2960 while (optind
< argc
)
2962 if (strv_printf (&cache_push
, "%s", argv
[optind
++]) == 0)
2963 errx (EXIT_FAILURE
, "%s", pwmd_strerror (GPG_ERR_ENOMEM
));
2966 if (strchr (socketarg
, '/') == NULL
)
2968 socketdir
= getcwd (buf
, sizeof (buf
));
2969 socketname
= str_dup (socketarg
);
2970 socketpath
= str_asprintf ("%s/%s", socketdir
, socketname
);
2974 socketname
= str_dup (strrchr (socketarg
, '/'));
2976 socketarg
[strlen (socketarg
) - strlen (socketname
) - 1] = 0;
2977 socketdir
= str_dup (socketarg
);
2978 socketpath
= str_asprintf ("%s/%s", socketdir
, socketname
);
2981 if (chdir (datadir
))
2983 log_write ("%s: %s", datadir
,
2984 pwmd_strerror (gpg_error_from_errno (errno
)));
2985 unlink (socketpath
);
2989 x
= test_pidfile (socketpath
, socketname
, buf
, sizeof(buf
), &pidfile
, 0,
2991 if (!terminate
&& x
)
2995 estatus
= x
!= 1 ? EXIT_FAILURE
: EXIT_SUCCESS
;
3000 * bind() doesn't like the full pathname of the socket or any non alphanum
3001 * characters so change to the directory where the socket is wanted then
3002 * create it then change to datadir.
3004 if (chdir (socketdir
))
3006 log_write ("%s: %s", socketdir
,
3007 pwmd_strerror (gpg_error_from_errno (errno
)));
3013 if ((sockfd
= socket (PF_UNIX
, SOCK_STREAM
, 0)) == -1)
3015 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
3019 addr
.sun_family
= AF_UNIX
;
3020 snprintf (addr
.sun_path
, sizeof (addr
.sun_path
), "%s", socketname
);
3022 if (bind (sockfd
, (struct sockaddr
*) &addr
, sizeof (struct sockaddr
)) ==
3025 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
3027 if (errno
== EADDRINUSE
)
3030 log_write (_("Either there is another pwmd running or '%s' is a \n"
3031 "stale socket. Please remove it manually."), socketpath
);
3038 char *t
= config_get_string ("global", "socket_perms");
3043 mode
= strtol (t
, NULL
, 8);
3047 if (chmod (socketname
, mode
) == -1)
3049 log_write ("%s: %s", socketname
,
3050 pwmd_strerror (gpg_error_from_errno (errno
)));
3060 xfree (--socketname
);
3062 if (chdir (datadir
))
3064 log_write ("%s: %s", datadir
,
3065 pwmd_strerror (gpg_error_from_errno (errno
)));
3073 * Set the cache entry for a file. Prompts for the password.
3077 struct crypto_s
*crypto
= NULL
;
3078 gpg_error_t rc
= init_client_crypto (&crypto
);
3082 estatus
= EXIT_FAILURE
;
3089 rc
= agent_set_pinentry_options (crypto
->agent
);
3092 estatus
= EXIT_FAILURE
;
3098 for (opt
= 0; cache_push
[opt
]; opt
++)
3100 if (!do_cache_push (cache_push
[opt
], crypto
) && !force
)
3102 strv_free (cache_push
);
3104 estatus
= EXIT_FAILURE
;
3105 cleanup_crypto (&crypto
);
3109 cleanup_crypto_stage1 (crypto
);
3114 (void) kill_scd (crypto
->agent
);
3117 cleanup_crypto (&crypto
);
3118 strv_free (cache_push
);
3119 log_write (!nofork
? _("Done. Daemonizing...") :
3120 _("Done. Waiting for connections..."));
3123 config_clear_keys ();
3125 if (listen (sockfd
, 0) == -1)
3127 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
3136 log_write ("fork(): %s",
3137 pwmd_strerror (gpg_error_from_errno (errno
)));
3146 _exit (EXIT_SUCCESS
);
3150 (void)test_pidfile (socketpath
, socketname
, buf
, sizeof(buf
), &pidfile
, 1,
3153 pthread_key_create (&thread_name_key
, free_key
);
3154 pthread_setspecific (thread_name_key
, str_dup ("main"));
3155 estatus
= server_loop (sockfd
, &socketpath
);
3158 if (socketpath
&& do_unlink
)
3160 unlink (socketpath
);
3166 gnutls_global_deinit ();
3170 #ifdef HAVE_PTHREAD_CANCEL
3171 pthread_cancel (rcfile_tid
);
3173 pthread_kill (rcfile_tid
, SIGUSR2
);
3174 pthread_cond_signal (&rcfile_cond
);
3176 pthread_join (rcfile_tid
, NULL
);
3179 pthread_cond_destroy (&rcfile_cond
);
3180 pthread_mutex_destroy (&rcfile_mutex
);
3181 pthread_key_delete (last_error_key
);
3182 #ifndef HAVE_PTHREAD_CANCEL
3183 pthread_key_delete (signal_thread_key
);
3187 config_free (global_config
);
3189 free_invoking_users (invoking_users
);
3191 xfree (home_directory
);
3193 xmlCleanupParser ();
3194 xmlCleanupGlobals ();
3200 if (estatus
== EXIT_SUCCESS
&& !terminate
)
3201 log_write (_("pwmd exiting normally"));
3203 pthread_key_delete (thread_name_key
);
3205 #if defined(DEBUG) && !defined(MEM_DEBUG)
3215 gpg_error_t
lock_flock (assuan_context_t ctx
, const char *filename
,
3221 *fd
= open (filename
, O_RDONLY
);
3223 return gpg_error_from_syserror ();
3225 TRY_FLOCK (ctx
, *fd
, type
, rc
);
3236 void unlock_flock (int *fd
)