2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014
3 Ben Kibbey <bjk@luxsci.net>
5 This file is part of pwmd.
7 Pwmd is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 2 of the License, or
10 (at your option) any later version.
12 Pwmd is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
30 #include <sys/socket.h>
44 #include <netinet/in.h>
45 #include <arpa/inet.h>
48 #include <sys/resource.h>
62 #ifdef HAVE_GETOPT_LONG
67 #include "getopt_long.h"
70 #ifdef HAVE_PR_SET_NAME
71 #include <sys/prctl.h>
74 #include "pwmd-error.h"
77 #include "util-misc.h"
83 #include "util-string.h"
90 /* In tenths of a second. */
93 /* For (tcp_)accept_thread (usec). */
94 #define ACCEPT_TIMEOUT 30000
101 static pthread_cond_t quit_cond
;
102 static pthread_mutex_t quit_mutex
;
103 static int no_passphrase_file
= 0;
104 static pthread_t keepalive_tid
;
107 #ifndef HAVE_PTHREAD_CANCEL
108 static pthread_key_t signal_thread_key
;
114 static pthread_t tls_tid
;
115 static pthread_t tls6_tid
;
116 static int spawned_tls
;
117 static int spawned_tls6
;
119 static int start_stop_tls (int term
);
122 static int do_cache_push (const char *filename
, struct crypto_s
*crypto
);
123 static int signal_loop (sigset_t sigset
);
125 GCRY_THREAD_OPTION_PTHREAD_IMPL
;
127 #ifndef HAVE_PTHREAD_CANCEL
128 #define INIT_THREAD_SIGNAL do { \
129 struct sigaction act; \
131 sigemptyset (&sigset); \
132 sigaddset (&sigset, SIGUSR2); \
133 pthread_sigmask (SIG_UNBLOCK, &sigset, NULL); \
134 memset (&act, 0, sizeof(act)); \
135 act.sa_flags = SA_SIGINFO; \
136 act.sa_mask = sigset; \
137 act.sa_sigaction = catch_thread_signal; \
138 sigaction (SIGUSR2, &act, NULL); \
142 catch_thread_signal (int sig
, siginfo_t
*info
, void *ctx
)
144 int *n
= (int *) pthread_getspecific (signal_thread_key
);
147 pthread_setspecific (signal_thread_key
, n
);
152 cache_push_from_rcfile ()
154 struct crypto_s
*crypto
= NULL
;
156 gpg_error_t rc
= init_client_crypto (&crypto
);
160 log_write ("%s: %s", __FUNCTION__
, pwmd_strerror (rc
));
167 rc
= set_agent_option (crypto
->agent
, "pinentry-mode", "error");
170 log_write ("%s: %s", __FUNCTION__
, pwmd_strerror (rc
));
176 cache_push
= config_get_list ("global", "cache_push");
181 for (p
= cache_push
; *p
; p
++)
183 (void) do_cache_push (*p
, crypto
);
184 cleanup_crypto_stage1 (crypto
);
187 strv_free (cache_push
);
191 (void) kill_scd (crypto
->agent
);
193 cleanup_crypto (&crypto
);
199 int n
= config_get_boolean ("global", "enable_logging");
203 char *p
= config_get_string ("global", "log_path");
205 if (!p
|| (logfile
&& p
&& log_fd
!= -1 && strcmp(p
, logfile
)))
214 logfile
= expand_homedir (p
);
227 log_syslog
= config_get_boolean ("global", "syslog");
229 openlog ("pwmd", LOG_NDELAY
| LOG_PID
, LOG_DAEMON
);
233 reload_rcfile_thread (void *arg
)
235 #ifndef HAVE_PTHREAD_CANCEL
236 int *n
= xmalloc (sizeof (int));
239 pthread_setspecific (signal_thread_key
, n
);
243 #ifdef HAVE_PR_SET_NAME
244 prctl (PR_SET_NAME
, "reload rcfile");
246 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
247 MUTEX_LOCK (&rcfile_mutex
);
248 pthread_cleanup_push (cleanup_mutex_cb
, &rcfile_mutex
);
252 struct allowed_users_s
257 struct slist_s
*allowed_users
= NULL
;
258 struct slist_s
*config
;
259 int b
= disable_list_and_dump
;
261 int require_save_key
= config_get_bool_param (global_config
, "global",
265 int tcp_require_key
= config_get_bool_param (global_config
, "global",
270 pthread_cond_wait (&rcfile_cond
, &rcfile_mutex
);
271 #ifndef HAVE_PTHREAD_CANCEL
272 int *cancel
= (int *) pthread_getspecific (signal_thread_key
);
277 /* Keep the "allowed" parameter across rcfile reloads to prevent
279 int n
, t
= slist_length (global_config
);
280 for (n
= 0; n
< t
; n
++)
282 struct config_section_s
*section
;
285 section
= slist_nth_data (global_config
, n
);
286 users
= config_get_list_param (global_config
, section
->name
,
290 struct allowed_users_s
*allowed
;
292 allowed
= xmalloc (sizeof(struct allowed_users_s
));
293 allowed
->section
= str_dup (section
->name
);
294 allowed
->users
= users
;
295 allowed_users
= slist_append (allowed_users
, allowed
);
299 log_write (_("reloading configuration file '%s'"), rcfile
);
300 config
= config_parse (rcfile
);
303 config_free (global_config
);
304 global_config
= config
;
306 cache_push_from_rcfile ();
307 config_clear_keys ();
310 disable_list_and_dump
= !disable_list_and_dump
? b
: 1;
311 config_set_bool_param (&global_config
, "global", "require_save_key",
312 require_save_key
? "true" : "false");
314 if (config_get_bool_param (global_config
, "global", "tcp_require_key",
318 config_set_bool_param (&global_config
, "global", "tcp_require_key",
319 tcp_require_key
? "true" : "false");
324 int n
, t
= slist_length (allowed_users
);
326 for (n
= 0; n
< t
; n
++)
328 struct allowed_users_s
*allowed
;
331 allowed
= slist_nth_data (allowed_users
, n
);
332 tmp
= strv_join (",", allowed
->users
);
333 config_set_list_param (&global_config
, allowed
->section
,
336 xfree (allowed
->section
);
337 strv_free (allowed
->users
);
341 slist_free (allowed_users
);
345 /* Kill existing listening threads since the configured listening
346 * protocols may have changed. */
352 pthread_cleanup_pop (1);
357 send_error (assuan_context_t ctx
, gpg_error_t e
)
359 struct client_s
*client
= assuan_get_pointer (ctx
);
361 if (gpg_err_source (e
) == GPG_ERR_SOURCE_UNKNOWN
)
368 return assuan_process_done (ctx
, 0);
372 log_write ("ERR %i: %s", e
, pwmd_strerror (e
));
376 if (client
&& client
->xml_error
)
378 log_write ("%s", client
->xml_error
->message
);
379 xfree (client
->last_error
);
380 client
->last_error
= NULL
;
381 if (client
->xml_error
->message
)
382 client
->last_error
= str_dup (client
->xml_error
->message
);
384 e
= assuan_process_done (ctx
,
385 assuan_set_error (ctx
, e
,
386 client
->xml_error
->message
? client
->xml_error
->message
: NULL
));
387 xmlResetLastError ();
388 xmlResetError (client
->xml_error
);
389 xfree (client
->xml_error
);
390 client
->xml_error
= NULL
;
394 return assuan_process_done (ctx
,
395 assuan_set_error (ctx
, e
, pwmd_strerror (e
)));
399 assuan_log_cb (assuan_context_t ctx
, void *data
, unsigned cat
,
402 static pthread_mutex_t m
= PTHREAD_MUTEX_INITIALIZER
;
406 pthread_mutex_lock (&m
);
407 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock
, &m
);
408 t
= strv_length (debug_level
);
410 for (i
= 0; i
< t
; i
++)
412 if (!strcasecmp (debug_level
[i
], (char *) "init")
413 && cat
== ASSUAN_LOG_INIT
)
419 if (!strcasecmp (debug_level
[i
], (char *) "ctx")
420 && cat
== ASSUAN_LOG_CTX
)
426 if (!strcasecmp (debug_level
[i
], (char *) "engine")
427 && cat
== ASSUAN_LOG_ENGINE
)
433 if (!strcasecmp (debug_level
[i
], (char *) "data")
434 && cat
== ASSUAN_LOG_DATA
)
440 if (!strcasecmp (debug_level
[i
], (char *) "sysio")
441 && cat
== ASSUAN_LOG_SYSIO
)
447 if (!strcasecmp (debug_level
[i
], (char *) "control")
448 && cat
== ASSUAN_LOG_CONTROL
)
462 open (logfile
, O_WRONLY
| O_CREAT
| O_APPEND
, 0600)) == -1)
463 warn ("%s", logfile
);
466 pthread_cleanup_push (cleanup_fd_cb
, &fd
);
467 write (fd
, msg
, strlen (msg
));
468 pthread_cleanup_pop (1);
474 fprintf (stderr
, "%s%s", data
? (char *) data
: "", msg
);
479 pthread_cleanup_pop (1);
484 log_write (const char *fmt
, ...)
490 pthread_t tid
= pthread_self ();
491 static pthread_mutex_t m
= PTHREAD_MUTEX_INITIALIZER
;
493 if ((!logfile
&& !isatty (STDERR_FILENO
) && !log_syslog
) || !fmt
)
496 pthread_mutex_lock (&m
);
497 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock
, &m
);
499 if (!cmdline
&& logfile
&& log_fd
== -1)
501 log_fd
= open (logfile
, O_WRONLY
| O_CREAT
| O_APPEND
, 0600);
503 warn ("%s", logfile
);
508 if (str_vasprintf (&args
, fmt
, ap
) != -1)
512 pthread_cleanup_push (xfree
, args
);
513 fprintf (stderr
, "pwmd: %s\n", args
);
515 pthread_cleanup_pop (1);
519 char *name
= pthread_getspecific (thread_name_key
);
522 pthread_cleanup_push (xfree
, args
);
523 snprintf (buf
, sizeof (buf
), "%s(%p): ", name
? name
: _("unknown"),
527 if (!cmdline
&& log_syslog
&& !nofork
)
528 syslog (LOG_INFO
, "%s%s", name
, args
);
531 struct tm
*tm
= localtime (&now
);
533 strftime (tbuf
, sizeof (tbuf
), "%b %d %Y %H:%M:%S ", tm
);
534 tbuf
[sizeof (tbuf
) - 1] = 0;
536 if (args
[strlen (args
) - 1] == '\n')
537 args
[strlen (args
) - 1] = 0;
539 line
= str_asprintf ("%s %i %s%s\n", tbuf
, getpid (), name
,
541 pthread_cleanup_pop (1);
544 pthread_cleanup_push (xfree
, line
);
545 if (logfile
&& log_fd
!= -1)
547 write (log_fd
, line
, strlen (line
));
553 fprintf (stdout
, "%s", line
);
557 pthread_cleanup_pop (1);
563 pthread_cleanup_pop (0);
565 if (log_fd
!= -1 && config_get_boolean (NULL
, "log_keepopen") <= 0)
571 pthread_mutex_unlock (&m
);
576 secure_mem_check (const void *arg
)
585 gcry_control (GCRYCTL_SET_THREAD_CBS
, &gcry_threads_pthread
);
587 if (!gcry_check_version (GCRYPT_VERSION
))
589 fprintf (stderr
, _("gcry_check_version(): Incompatible libgcrypt. "
590 "Wanted %s, got %s.\n"), GCRYPT_VERSION
,
591 gcry_check_version (NULL
));
592 return GPG_ERR_UNKNOWN_VERSION
;
595 gcry_set_allocation_handler (xmalloc
, xmalloc
, NULL
, xrealloc
, xfree
);
599 #ifdef HAVE_GETGRNAM_R
601 do_validate_peer (assuan_context_t ctx
, const char *section
,
602 assuan_peercred_t
* peer
)
608 struct client_s
*client
= assuan_get_pointer (ctx
);
610 if (client
&& client
->thd
->remote
)
611 return tls_validate_access (client
, section
);
614 rc
= assuan_get_peercred (ctx
, peer
);
618 users
= config_get_list (section
, "allowed");
621 for (char **p
= users
; *p
; p
++)
623 struct passwd pw
, *result
;
624 struct group gr
, *gresult
;
627 int deny
= (*user
== '-') ? 1 : 0;
632 if (*user
== '@') // all users in group
634 size_t len
= sysconf (_SC_GETGR_R_SIZE_MAX
);
643 return GPG_ERR_ENOMEM
;
647 if (!getgrnam_r (user
, &gr
, buf
, len
, &gresult
) && gresult
)
649 if (gresult
->gr_gid
== (*peer
)->gid
)
656 len
= sysconf (_SC_GETPW_R_SIZE_MAX
);
660 char *tbuf
= xmalloc (len
);
661 for (char **t
= gresult
->gr_mem
; *t
; t
++)
663 if (!getpwnam_r (*t
, &pw
, tbuf
, len
, &result
) && result
)
665 if (result
->pw_uid
== (*peer
)->uid
)
676 size_t len
= sysconf (_SC_GETPW_R_SIZE_MAX
);
686 return GPG_ERR_ENOMEM
;
689 if (!getpwnam_r (user
, &pw
, buf
, len
, &result
) && result
)
691 if (result
->pw_uid
== (*peer
)->uid
)
702 return allowed
? 0 : GPG_ERR_INV_USER_ID
;
706 do_validate_peer (assuan_context_t ctx
, const char *section
,
707 assuan_peercred_t
* peer
)
713 struct client_s
*client
= assuan_get_pointer (ctx
);
715 if (client
&& client
->thd
->remote
)
716 return tls_validate_access (client
, section
);
719 rc
= assuan_get_peercred (ctx
, peer
);
723 users
= config_get_list (section
, "allowed");
726 for (char **p
= users
; *p
; p
++)
728 struct passwd
*result
;
729 struct group
*gresult
;
731 int deny
= (*user
== '-') ? 1 : 0;
736 if (*user
== '@') // all users in group
739 gresult
= getgrnam (user
);
740 if (gresult
&& gresult
->gr_gid
== (*peer
)->gid
)
746 for (char **t
= gresult
->gr_mem
; *t
; t
++)
748 result
= getpwnam (*t
);
749 if (result
&& result
->pw_uid
== (*peer
)->uid
)
758 result
= getpwnam (user
);
759 if (result
&& result
->pw_uid
== (*peer
)->uid
)
767 return allowed
? 0 : GPG_ERR_INV_USER_ID
;
772 validate_peer (struct client_s
*cl
)
775 assuan_peercred_t peer
;
779 return tls_validate_access (cl
, NULL
);
782 rc
= do_validate_peer (cl
->ctx
, "global", &peer
);
783 if (!rc
|| gpg_err_code (rc
) == GPG_ERR_INV_USER_ID
)
784 log_write ("peer %s: uid=%i, gid=%i, pid=%i",
785 !rc
? _("accepted") : _("rejected"), peer
->uid
, peer
->gid
,
788 log_write ("%s: %s", __FUNCTION__
, pwmd_strerror (rc
));
794 xml_error_cb (void *data
, xmlErrorPtr e
)
796 struct client_s
*client
= data
;
799 * Keep the first reported error as the one to show in the error
800 * description. Reset in send_error().
802 if (client
->xml_error
)
805 client
->xml_error
= xcalloc (1, sizeof(xmlError
));
806 xmlCopyError (e
, client
->xml_error
);
810 hook_waitpid (assuan_context_t ctx
, pid_t pid
, int action
,
811 int *status
, int options
)
813 return waitpid (pid
, status
, options
);
817 hook_read (assuan_context_t ctx
, assuan_fd_t fd
, void *data
, size_t len
)
820 struct client_s
*client
= assuan_get_pointer (ctx
);
822 if (client
->thd
->remote
)
823 return tls_read_hook (ctx
, (int) fd
, data
, len
);
826 return read ((int) fd
, data
, len
);
830 hook_write (assuan_context_t ctx
, assuan_fd_t fd
,
831 const void *data
, size_t len
)
834 struct client_s
*client
= assuan_get_pointer (ctx
);
836 if (client
->thd
->remote
)
837 return tls_write_hook (ctx
, (int) fd
, data
, len
);
840 return write ((int) fd
, data
, len
);
844 new_connection (struct client_s
*cl
)
847 static struct assuan_malloc_hooks mhooks
= { xmalloc
, xrealloc
, xfree
};
848 static struct assuan_system_hooks shooks
= {
849 ASSUAN_SYSTEM_HOOKS_VERSION
,
857 NULL
, //sendmsg both are used for FD passing
868 char *prio
= config_get_string ("global", "tls_cipher_suite");
870 cl
->thd
->tls
= tls_init (cl
->thd
->fd
, cl
->thd
->timeout
, prio
);
877 rc
= assuan_new_ext (&cl
->ctx
, GPG_ERR_SOURCE_DEFAULT
, &mhooks
,
878 debug_level
? assuan_log_cb
: NULL
, NULL
);
882 assuan_ctx_set_system_hooks (cl
->ctx
, &shooks
);
883 rc
= assuan_init_socket_server (cl
->ctx
, cl
->thd
->fd
, 2);
887 assuan_set_pointer (cl
->ctx
, cl
);
888 assuan_set_hello_line (cl
->ctx
, PACKAGE_STRING
);
889 rc
= register_commands (cl
->ctx
);
896 cl
->thd
->timeout
= config_get_integer ("global", "tls_timeout");
897 fcntl (cl
->thd
->fd
, F_SETFL
, O_NONBLOCK
);
901 rc
= assuan_accept (cl
->ctx
);
905 rc
= validate_peer (cl
);
906 /* May not be implemented on all platforms. */
907 if (rc
&& gpg_err_code (rc
) != GPG_ERR_ASS_GENERAL
)
910 rc
= init_client_crypto (&cl
->crypto
);
916 cl
->crypto
->agent
->client_ctx
= cl
->ctx
;
919 cl
->crypto
->client_ctx
= cl
->ctx
;
920 xmlSetStructuredErrorFunc (cl
, xml_error_cb
);
924 log_write ("%s", pwmd_strerror (rc
));
929 * This is called after a client_thread() terminates. Set with
930 * pthread_cleanup_push().
933 cleanup_cb (void *arg
)
935 struct client_thread_s
*cn
= arg
;
936 struct client_s
*cl
= cn
->cl
;
938 MUTEX_LOCK (&cn_mutex
);
939 cn_thread_list
= slist_remove (cn_thread_list
, cn
);
940 MUTEX_UNLOCK (&cn_mutex
);
946 xmlResetError (cl
->xml_error
);
948 xfree (cl
->xml_error
);
953 gnutls_deinit (cn
->tls
->ses
);
959 if (!cn
->atfork
&& cl
->ctx
)
960 assuan_release (cl
->ctx
);
961 else if (!cn
->atfork
&& cl
->thd
&& cl
->thd
->fd
!= -1)
965 cleanup_crypto (&cl
->crypto
);
967 pinentry_free_opts (&cl
->pinentry_opts
);
976 while (cn
->msg_queue
)
978 struct status_msg_s
*msg
= cn
->msg_queue
;
980 cn
->msg_queue
= msg
->next
;
985 if (!cn
->atfork
&& cn
->status_msg_pipe
[0] != -1)
986 close (cn
->status_msg_pipe
[0]);
988 if (!cn
->atfork
&& cn
->status_msg_pipe
[1] != -1)
989 close (cn
->status_msg_pipe
[1]);
991 pthread_mutex_destroy (&cn
->status_mutex
);
995 log_write (_("exiting, fd=%i"), cn
->fd
);
996 send_status_all (STATUS_CLIENTS
, NULL
);
1000 pthread_cond_signal (&quit_cond
);
1004 cleanup_all_clients (int atfork
)
1006 /* This function may be called from pthread_atfork() which requires
1007 reinitialization. */
1010 pthread_mutexattr_t attr
;
1012 pthread_mutexattr_init (&attr
);
1013 pthread_mutexattr_settype (&attr
, PTHREAD_MUTEX_RECURSIVE
);
1014 pthread_mutex_init (&cn_mutex
, &attr
);
1015 pthread_mutexattr_destroy (&attr
);
1016 cache_mutex_init ();
1019 MUTEX_LOCK (&cn_mutex
);
1021 while (slist_length (cn_thread_list
))
1023 struct client_thread_s
*thd
= slist_nth_data (cn_thread_list
, 0);
1025 thd
->atfork
= atfork
;
1030 MUTEX_UNLOCK (&cn_mutex
);
1031 cache_deinit (atfork
);
1035 send_msg_queue (struct client_thread_s
*thd
)
1037 MUTEX_LOCK (&thd
->status_mutex
);
1041 read (thd
->status_msg_pipe
[0], &c
, 1);
1043 while (thd
->msg_queue
)
1045 struct status_msg_s
*msg
= thd
->msg_queue
;
1047 thd
->msg_queue
= thd
->msg_queue
->next
;
1048 MUTEX_UNLOCK (&thd
->status_mutex
);
1049 rc
= send_status (thd
->cl
->ctx
, msg
->s
, msg
->line
);
1050 MUTEX_LOCK (&thd
->status_mutex
);
1058 MUTEX_UNLOCK (&thd
->status_mutex
);
1059 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1060 log_write ("%s: %s", __FUNCTION__
, pwmd_strerror (rc
));
1066 client_thread (void *data
)
1068 struct client_thread_s
*thd
= data
;
1069 struct client_s
*cl
= xcalloc (1, sizeof (struct client_s
));
1071 #ifdef HAVE_PR_SET_NAME
1072 prctl (PR_SET_NAME
, "client");
1074 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1078 log_write ("%s(%i): %s", __FILE__
, __LINE__
,
1079 pwmd_strerror (GPG_ERR_ENOMEM
));
1083 MUTEX_LOCK (&cn_mutex
);
1084 pthread_cleanup_push (cleanup_cb
, thd
);
1087 MUTEX_UNLOCK (&cn_mutex
);
1089 if (new_connection (cl
))
1094 send_status_all (STATUS_CLIENTS
, NULL
);
1095 rc
= send_status (cl
->ctx
, STATUS_CACHE
, NULL
);
1098 log_write ("%s(%i): %s", __FILE__
, __LINE__
, pwmd_strerror (rc
));
1109 FD_SET (thd
->fd
, &rfds
);
1110 FD_SET (thd
->status_msg_pipe
[0], &rfds
);
1111 n
= thd
->fd
> thd
->status_msg_pipe
[0]
1112 ? thd
->fd
: thd
->status_msg_pipe
[0];
1114 n
= select (n
+ 1, &rfds
, NULL
, NULL
, NULL
);
1117 log_write ("%s", strerror (errno
));
1121 if (FD_ISSET (thd
->status_msg_pipe
[0], &rfds
))
1123 rc
= send_msg_queue (thd
);
1124 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1128 if (!FD_ISSET (thd
->fd
, &rfds
))
1131 rc
= assuan_process_next (cl
->ctx
, &eof
);
1134 if (gpg_err_code (rc
) == GPG_ERR_EOF
|| eof
)
1137 log_write ("assuan_process_next(): rc=%i %s", rc
,
1138 pwmd_strerror (rc
));
1139 if (rc
== gpg_error (GPG_ERR_ETIMEDOUT
))
1142 rc
= send_error (cl
->ctx
, rc
);
1145 log_write ("assuan_process_done(): rc=%i %s", rc
,
1146 pwmd_strerror (rc
));
1151 /* Since the msg queue pipe fd's are non-blocking, check for
1152 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1153 * client has already disconnected and will be converted to
1154 * GPG_ERR_EOF during assuan_process_next().
1156 rc
= send_msg_queue (thd
);
1157 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1162 pthread_cleanup_pop (1);
1167 xml_import (const char *filename
, const char *outfile
,
1168 const char *keygrip
, const char *sign_keygrip
,
1169 const char *keyfile
, int no_passphrase
, const char *cipher
,
1170 const char *params
, unsigned long s2k_count
, uint64_t iterations
)
1179 struct crypto_s
*crypto
= NULL
;
1182 int algo
= cipher
? cipher_string_to_gcrypt ((char *) cipher
) :
1187 log_write ("ERR %i: %s", gpg_error (GPG_ERR_CIPHER_ALGO
),
1188 pwmd_strerror (GPG_ERR_CIPHER_ALGO
));
1192 if (stat (filename
, &st
) == -1)
1194 log_write ("%s: %s", filename
,
1195 pwmd_strerror (gpg_error_from_errno (errno
)));
1199 rc
= init_client_crypto (&crypto
);
1203 memcpy (&crypto
->save
.hdr
, &crypto
->hdr
, sizeof (file_header_t
));
1204 crypto
->save
.hdr
.flags
= set_cipher_flag (crypto
->save
.hdr
.flags
, algo
);
1205 log_write (_("Importing XML from '%s'. Output will be written to '%s' ..."),
1208 if ((fd
= open (filename
, O_RDONLY
)) == -1)
1210 log_write ("%s: %s", filename
,
1211 pwmd_strerror (gpg_error_from_errno (errno
)));
1215 if ((xmlbuf
= xmalloc (st
.st_size
+ 1)) == NULL
)
1218 log_write ("%s(%i): %s", __FILE__
, __LINE__
,
1219 pwmd_strerror (GPG_ERR_ENOMEM
));
1223 if (read (fd
, xmlbuf
, st
.st_size
) == -1)
1225 rc
= gpg_error_from_errno (errno
);
1227 log_write ("%s: %s", filename
, pwmd_strerror (rc
));
1232 xmlbuf
[st
.st_size
] = 0;
1234 * Make sure the document validates.
1236 if ((doc
= xmlReadDoc (xmlbuf
, NULL
, "UTF-8", XML_PARSE_NOBLANKS
)) == NULL
)
1238 log_write ("xmlReadDoc() failed");
1244 xmlNodePtr n
= xmlDocGetRootElement (doc
);
1245 if (n
&& !xmlStrEqual (n
->name
, (xmlChar
*) "pwmd"))
1247 log_write (_("Could not find root \"pwmd\" element."));
1248 rc
= GPG_ERR_BAD_DATA
;
1252 rc
= validate_import (n
? n
->children
: n
);
1256 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
1261 xmlDocDumpMemory (doc
, &xml
, &len
);
1263 crypto
->save
.s2k_count
= s2k_count
;
1264 crypto
->save
.hdr
.iterations
= iterations
;
1267 rc
= export_common (NULL
, 0, crypto
, xml
, len
, outfile
, keyfile
, &key
,
1268 &keylen
, 0, 0, no_passphrase
);
1270 log_write (_("Success!"));
1275 rc
= agent_set_pinentry_options (crypto
->agent
);
1277 rc
= agent_export_common (crypto
, keygrip
, sign_keygrip
, no_passphrase
,
1278 xml
, len
, outfile
, params
, keyfile
);
1286 send_error (NULL
, rc
);
1290 cleanup_crypto (&crypto
);
1294 cleanup_crypto (&crypto
);
1299 do_cache_push (const char *filename
, struct crypto_s
*crypto
)
1301 unsigned char md5file
[16];
1306 struct cache_data_s
*cdata
;
1310 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1313 if (valid_filename (filename
) == 0)
1315 log_write (_("%s: Invalid characters in filename"), filename
);
1319 rc
= decrypt_common (NULL
, 0, crypto
, filename
, &key
, &keylen
);
1323 rc
= parse_doc ((char *) crypto
->plaintext
, crypto
->plaintext_len
, &doc
);
1326 log_write ("%s", pwmd_strerror (rc
));
1331 gcry_md_hash_buffer (GCRY_MD_MD5
, md5file
, filename
, strlen (filename
));
1332 cdata
= xcalloc (1, sizeof (struct cache_data_s
));
1336 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM
));
1341 rc
= get_checksum (filename
, &crc
, &len
);
1344 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
1346 free_cache_data_once (cdata
);
1352 rc
= encrypt_xml (NULL
, cache_key
, cache_keysize
, GCRY_CIPHER_AES
,
1353 crypto
->plaintext
, crypto
->plaintext_len
, &cdata
->doc
,
1354 &cdata
->doclen
, &cache_iv
, &cache_blocksize
, 0);
1355 if (!rc
&& !IS_PKI (crypto
))
1358 cdata
->keylen
= keylen
;
1365 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
1367 free_cache_data_once (cdata
);
1372 if (use_agent
&& IS_PKI (crypto
))
1374 gcry_sexp_build ((gcry_sexp_t
*) & cdata
->pubkey
, NULL
, "%S",
1376 gcry_sexp_build ((gcry_sexp_t
*) & cdata
->sigkey
, NULL
, "%S",
1377 crypto
->sigpkey_sexp
);
1381 int timeout
= config_get_integer (filename
, "cache_timeout");
1382 cache_add_file (md5file
, crypto
->grip
, cdata
, timeout
);
1383 log_write (_("Successfully added '%s' to the cache."), filename
);
1388 init_client (int fd
, const char *addr
)
1391 struct client_thread_s
*new = xcalloc (1, sizeof (struct client_thread_s
));
1396 return GPG_ERR_ENOMEM
;
1399 MUTEX_LOCK (&cn_mutex
);
1400 pthread_cleanup_push (cleanup_mutex_cb
, &cn_mutex
);
1402 if (pipe (new->status_msg_pipe
) == -1)
1403 rc
= gpg_error_from_errno (errno
);
1407 fcntl (new->status_msg_pipe
[0], F_SETFL
, O_NONBLOCK
);
1408 fcntl (new->status_msg_pipe
[1], F_SETFL
, O_NONBLOCK
);
1409 pthread_mutex_init (&new->status_mutex
, NULL
);
1415 new->remote
= addr
? 1 : 0;
1418 rc
= create_thread (client_thread
, new, &new->tid
, 1);
1421 close (new->status_msg_pipe
[0]);
1422 close (new->status_msg_pipe
[1]);
1423 pthread_mutex_destroy (&new->status_mutex
);
1429 struct slist_s
*list
= slist_append (cn_thread_list
, new);
1433 cn_thread_list
= list
;
1435 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1436 (pthread_t
*) new->tid
, fd
, addr
);
1438 log_write (_("new connection: tid=%p, fd=%i"),
1439 (pthread_t
*) new->tid
, fd
);
1442 rc
= GPG_ERR_ENOMEM
;
1445 pthread_cleanup_pop (1);
1451 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1452 pwmd_strerror (rc
));
1458 keepalive_thread (void *arg
)
1460 #ifndef HAVE_PTHREAD_CANCEL
1461 int *n
= xmalloc (sizeof (int));
1464 pthread_setspecific (signal_thread_key
, n
);
1468 #ifdef HAVE_PR_SET_NAME
1469 prctl (PR_SET_NAME
, "keepalive");
1471 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1475 int n
= config_get_integer ("global", "keepalive_interval");
1476 struct timeval tv
= { n
, 0 };
1477 #ifndef HAVE_PTHREAD_CANCEL
1480 sigusr2
= (int *) pthread_getspecific (signal_thread_key
);
1485 send_status_all (STATUS_KEEPALIVE
, NULL
);
1486 select (0, NULL
, NULL
, NULL
, &tv
);
1493 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1495 get_in_addr (struct sockaddr
*sa
)
1497 if (sa
->sa_family
== AF_INET
)
1498 return &(((struct sockaddr_in
*) sa
)->sin_addr
);
1500 return &(((struct sockaddr_in6
*) sa
)->sin6_addr
);
1504 tcp_accept_thread (void *arg
)
1506 int sockfd
= *(int *) arg
;
1507 #ifndef HAVE_PTHREAD_CANCEL
1508 int *n
= xmalloc (sizeof (int));
1511 pthread_setspecific (signal_thread_key
, n
);
1513 fcntl (sockfd
, F_SETFL
, O_NONBLOCK
);
1516 #ifdef HAVE_PR_SET_NAME
1517 prctl (PR_SET_NAME
, "tcp_accept");
1519 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1523 struct sockaddr_storage raddr
;
1524 socklen_t slen
= sizeof (raddr
);
1527 char s
[INET6_ADDRSTRLEN
];
1528 struct timeval tv
= { 0, ACCEPT_TIMEOUT
};
1529 #ifndef HAVE_PTHREAD_CANCEL
1532 sigusr2
= (int *) pthread_getspecific (signal_thread_key
);
1537 fd
= accept (sockfd
, (struct sockaddr
*) &raddr
, &slen
);
1540 if (errno
== EMFILE
|| errno
== ENFILE
)
1541 log_write ("accept(): %s",
1542 pwmd_strerror (gpg_error_from_errno (errno
)));
1543 else if (errno
!= EAGAIN
)
1545 if (!quit
) // probably EBADF
1546 log_write ("accept(): %s", strerror (errno
));
1551 #ifndef HAVE_PTHREAD_CANCEL
1552 select (0, NULL
, NULL
, NULL
, &tv
);
1560 inet_ntop (raddr
.ss_family
, get_in_addr ((struct sockaddr
*) &raddr
),
1562 (void) init_client (fd
, s
);
1563 n
= config_get_integer ("global", "tcp_wait");
1566 tv
.tv_sec
= (n
* 100000) / 100000;
1567 tv
.tv_usec
= (n
* 100000) % 100000;
1568 select (0, NULL
, NULL
, NULL
, &tv
);
1576 start_stop_tls_with_protocol (int ipv6
, int term
)
1578 struct addrinfo hints
, *servinfo
, *p
;
1579 int port
= config_get_integer ("global", "tcp_port");
1583 int *fd
= ipv6
? &tls6_fd
: &tls_fd
;
1585 if (term
|| config_get_boolean ("global", "enable_tcp") == 0)
1591 #ifdef HAVE_PTHREAD_CANCEL
1592 pthread_cancel (tls6_tid
);
1594 pthread_kill (tls6_tid
, SIGUSR2
);
1596 pthread_join (tls6_tid
, NULL
);
1599 shutdown (tls6_fd
, SHUT_RDWR
);
1609 #ifdef HAVE_PTHREAD_CANCEL
1610 pthread_cancel (tls_tid
);
1612 pthread_kill (tls_tid
, SIGUSR2
);
1614 pthread_join (tls_tid
, NULL
);
1617 shutdown (tls_fd
, SHUT_RDWR
);
1623 /* A client may still be connected. */
1624 if (!quit
&& x509_cred
!= NULL
)
1625 tls_deinit_params ();
1630 if ((ipv6
&& tls6_fd
!= -1) || (!ipv6
&& tls_fd
!= -1))
1633 memset (&hints
, 0, sizeof (hints
));
1634 hints
.ai_family
= ipv6
? AF_INET6
: AF_INET
;
1635 hints
.ai_socktype
= SOCK_STREAM
;
1636 hints
.ai_flags
= AI_PASSIVE
;
1637 snprintf (buf
, sizeof (buf
), "%i", port
);
1639 if ((n
= getaddrinfo (NULL
, buf
, &hints
, &servinfo
)) == -1)
1641 log_write ("getaddrinfo(): %s", gai_strerror (n
));
1645 for (n
= 0, p
= servinfo
; p
!= NULL
; p
= p
->ai_next
)
1649 if ((ipv6
&& p
->ai_family
!= AF_INET6
)
1650 || (!ipv6
&& p
->ai_family
!= AF_INET
))
1653 if ((*fd
= socket (p
->ai_family
, p
->ai_socktype
, p
->ai_protocol
)) == -1)
1655 log_write ("socket(): %s", strerror (errno
));
1659 if (setsockopt (*fd
, SOL_SOCKET
, SO_REUSEADDR
, &r
, sizeof (int)) == -1)
1661 log_write ("setsockopt(): %s",
1662 pwmd_strerror (gpg_error_from_errno (errno
)));
1663 freeaddrinfo (servinfo
);
1667 if (bind (*fd
, p
->ai_addr
, p
->ai_addrlen
) == -1)
1670 log_write ("bind(): %s",
1671 pwmd_strerror (gpg_error_from_errno (errno
)));
1679 freeaddrinfo (servinfo
);
1684 #if HAVE_DECL_SO_BINDTODEVICE != 0
1685 char *tmp
= config_get_string ("global", "tcp_interface");
1686 if (tmp
&& setsockopt (*fd
, SOL_SOCKET
, SO_BINDTODEVICE
, tmp
,
1687 strlen (tmp
)) == -1)
1689 log_write ("setsockopt(): %s",
1690 pwmd_strerror (gpg_error_from_errno (errno
)));
1698 if (x509_cred
== NULL
)
1700 rc
= tls_init_params ();
1705 if (listen (*fd
, 0) == -1)
1707 log_write ("listen(): %s", strerror (errno
));
1712 rc
= create_thread (tcp_accept_thread
, fd
, &tls6_tid
, 0);
1714 rc
= create_thread (tcp_accept_thread
, fd
, &tls_tid
, 0);
1718 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1719 pwmd_strerror (rc
));
1731 start_stop_tls_with_protocol (0, 1);
1744 start_stop_tls (int term
)
1746 char *s
= config_get_string ("global", "tcp_bind");
1752 if (!strcmp (s
, "any"))
1754 b
= start_stop_tls_with_protocol (0, term
);
1756 b
= start_stop_tls_with_protocol (1, term
);
1758 else if (!strcmp (s
, "ipv4"))
1759 b
= start_stop_tls_with_protocol (0, term
);
1760 else if (!strcmp (s
, "ipv6"))
1761 b
= start_stop_tls_with_protocol (1, term
);
1771 accept_thread (void *arg
)
1773 int sockfd
= *(int *) arg
;
1774 #ifndef HAVE_PTHREAD_CANCEL
1775 int *n
= xmalloc (sizeof (int));
1778 pthread_setspecific (signal_thread_key
, n
);
1780 fcntl (sockfd
, F_SETFL
, O_NONBLOCK
);
1783 #ifdef HAVE_PR_SET_NAME
1784 prctl (PR_SET_NAME
, "accept");
1786 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1790 socklen_t slen
= sizeof (struct sockaddr_un
);
1791 struct sockaddr_un raddr
;
1793 #ifndef HAVE_PTHREAD_CANCEL
1794 struct timeval tv
= { 0, ACCEPT_TIMEOUT
};
1795 int *sigusr2
= (int *) pthread_getspecific (signal_thread_key
);
1801 fd
= accept (sockfd
, (struct sockaddr
*) &raddr
, &slen
);
1804 if (errno
== EMFILE
|| errno
== ENFILE
)
1805 log_write ("accept(): %s",
1806 pwmd_strerror (gpg_error_from_errno (errno
)));
1807 else if (errno
!= EAGAIN
)
1809 if (!quit
) // probably EBADF
1810 log_write ("accept(): %s",
1811 pwmd_strerror (gpg_error_from_errno (errno
)));
1816 #ifndef HAVE_PTHREAD_CANCEL
1817 select (0, NULL
, NULL
, NULL
, &tv
);
1822 (void) init_client (fd
, NULL
);
1825 /* Just in case accept() failed for some reason other than EBADF */
1831 cache_timer_thread (void *arg
)
1833 #ifndef HAVE_PTHREAD_CANCEL
1834 int *n
= xmalloc (sizeof (int));
1837 pthread_setspecific (signal_thread_key
, n
);
1841 #ifdef HAVE_PR_SET_NAME
1842 prctl (PR_SET_NAME
, "cache timer");
1844 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1848 struct timeval tv
= { 1, 0 };
1849 #ifndef HAVE_PTHREAD_CANCEL
1852 n
= (int *) pthread_getspecific (signal_thread_key
);
1857 select (0, NULL
, NULL
, NULL
, &tv
);
1858 cache_adjust_timeout ();
1865 signal_loop (sigset_t sigset
)
1874 sigwait (&sigset
, &sig
);
1877 log_write (_("caught signal %i (%s)"), sig
, strsignal (sig
));
1882 pthread_cond_signal (&rcfile_cond
);
1885 log_write (_("clearing file cache"));
1887 send_status_all (STATUS_CACHE
, NULL
);
1906 log_write (_ ("Caught signal %i (%s). Exiting."), sig
, strsignal (sig
));
1907 #ifdef HAVE_BACKTRACE
1908 BACKTRACE (__FUNCTION__
);
1914 waiting_for_exit (void *arg
)
1917 #ifndef HAVE_PTHREAD_CANCEL
1918 int *n
= xmalloc (sizeof (int));
1921 pthread_setspecific (signal_thread_key
, n
);
1925 #ifdef HAVE_PR_SET_NAME
1926 prctl (PR_SET_NAME
, "exiting");
1928 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1929 log_write (_("waiting for all clients to disconnect"));
1930 MUTEX_LOCK (&quit_mutex
);
1931 pthread_cleanup_push (cleanup_mutex_cb
, &quit_mutex
);
1938 MUTEX_LOCK (&cn_mutex
);
1939 n
= slist_length (cn_thread_list
);
1940 MUTEX_UNLOCK (&cn_mutex
);
1944 #ifndef HAVE_PTHREAD_CANCEL
1945 int *s
= (int *) pthread_getspecific (signal_thread_key
);
1952 log_write (_("%i clients remain"), n
);
1956 INIT_TIMESPEC (SIG_TIMEOUT
, ts
);
1957 pthread_cond_timedwait (&quit_cond
, &quit_mutex
, &ts
);
1960 kill (getpid (), SIGQUIT
);
1961 pthread_cleanup_pop (1);
1966 server_loop (int sockfd
, char **socketpath
)
1968 pthread_t accept_tid
;
1969 pthread_t cache_timeout_tid
;
1970 int cancel_timeout_thread
= 0, cancel_accept_thread
= 0;
1971 int cancel_keepalive_thread
= 0;
1978 sigemptyset (&sigset
);
1981 sigaddset (&sigset
, SIGTERM
);
1982 sigaddset (&sigset
, SIGINT
);
1984 /* Clears the file cache. */
1985 sigaddset (&sigset
, SIGUSR1
);
1987 /* Configuration file reloading. */
1988 sigaddset (&sigset
, SIGHUP
);
1990 /* For exiting cleanly. */
1991 sigaddset (&sigset
, SIGQUIT
);
1993 #ifndef HAVE_PTHREAD_CANCEL
1995 The socket, cache and rcfile threads use this signal when
1996 pthread_cancel() is unavailable. Prevent the main thread from
1997 catching this signal from another process.
1999 sigaddset (&sigset
, SIGUSR2
);
2002 /* When mem.c cannot find a pointer in the list (double free). */
2003 signal (SIGABRT
, catchsig
);
2004 sigaddset (&sigset
, SIGABRT
);
2005 sigprocmask (SIG_BLOCK
, &sigset
, NULL
);
2007 #ifndef HAVE_PTHREAD_CANCEL
2008 /* Remove this signal from the watched signals in signal_loop(). */
2009 sigdelset (&sigset
, SIGUSR2
);
2012 /* Ignored everywhere. When a client disconnects abnormally this signal
2013 * gets raised. It isn't needed though because client_thread() will check
2014 * for rcs even after the client disconnects. */
2015 signal (SIGPIPE
, SIG_IGN
);
2017 /* Can show a backtrace of the stack in the log. */
2018 signal (SIGSEGV
, catchsig
);
2021 /* Needs to be done after the fork(). */
2022 if (!start_stop_tls (0))
2029 pthread_mutex_init (&quit_mutex
, NULL
);
2030 pthread_cond_init (&quit_cond
, NULL
);
2031 log_write (_("%s started for user %s"), PACKAGE_STRING
, get_username ());
2034 if (config_get_boolean ("global", "enable_tcp"))
2035 log_write (_("Listening on %s and TCP port %i"), *socketpath
,
2036 config_get_integer ("global", "tcp_port"));
2038 log_write (_("Listening on %s"), *socketpath
);
2040 log_write (_("Listening on %s"), *socketpath
);
2043 rc
= create_thread (keepalive_thread
, NULL
, &keepalive_tid
, 0);
2046 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2047 pwmd_strerror (rc
));
2051 cancel_keepalive_thread
= 1;
2052 rc
= create_thread (reload_rcfile_thread
, NULL
, &rcfile_tid
, 0);
2055 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2056 pwmd_strerror (rc
));
2060 rc
= create_thread (cache_timer_thread
, NULL
, &cache_timeout_tid
, 0);
2063 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2064 pwmd_strerror (rc
));
2068 cancel_timeout_thread
= 1;
2069 rc
= create_thread (accept_thread
, &sockfd
, &accept_tid
, 0);
2072 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2073 pwmd_strerror (rc
));
2077 cancel_accept_thread
= 1;
2079 signal_loop (sigset
);
2085 * We're out of the main server loop. This happens when a signal was sent
2086 * to terminate the daemon. We'll wait for all clients to disconnect
2087 * before exiting but exit immediately if another termination signal is
2090 if (cancel_accept_thread
)
2092 #ifdef HAVE_PTHREAD_CANCEL
2093 int n
= pthread_cancel (accept_tid
);
2095 int n
= pthread_kill (accept_tid
, SIGUSR2
);
2098 pthread_join (accept_tid
, NULL
);
2104 shutdown (sockfd
, SHUT_RDWR
);
2106 unlink (*socketpath
);
2107 xfree (*socketpath
);
2109 MUTEX_LOCK (&cn_mutex
);
2110 n
= slist_length (cn_thread_list
);
2111 MUTEX_UNLOCK (&cn_mutex
);
2117 rc
= create_thread (waiting_for_exit
, NULL
, &tid
, 0);
2120 if (signal_loop (sigset
))
2122 log_write (_("Received second termination request. Exiting."));
2123 #ifdef HAVE_PTHREAD_CANCEL
2124 pthread_cancel (tid
);
2126 pthread_kill (tid
, SIGUSR2
);
2128 pthread_join (tid
, NULL
);
2132 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2133 pwmd_strerror (rc
));
2136 if (cancel_timeout_thread
)
2138 #ifdef HAVE_PTHREAD_CANCEL
2139 pthread_cancel (cache_timeout_tid
);
2141 pthread_kill (cache_timeout_tid
, SIGUSR2
);
2143 pthread_join (cache_timeout_tid
, NULL
);
2146 if (cancel_keepalive_thread
)
2148 #ifdef HAVE_PTHREAD_CANCEL
2149 pthread_cancel (keepalive_tid
);
2151 pthread_kill (keepalive_tid
, SIGUSR2
);
2153 pthread_join (keepalive_tid
, NULL
);
2156 cleanup_all_clients (0);
2161 pthread_cond_destroy (&quit_cond
);
2162 pthread_mutex_destroy (&quit_mutex
);
2163 return segv
? EXIT_FAILURE
: EXIT_SUCCESS
;;
2170 ("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
2174 /* This is called from cache.c:clear_once(). See
2175 * command.c:clearcache_command() for details about lock checking.
2178 free_cache_data (file_cache_t
* cache
)
2180 gpg_error_t rc
= GPG_ERR_NO_DATA
;
2182 struct client_thread_s
*found
= NULL
;
2189 MUTEX_LOCK (&cn_mutex
);
2190 pthread_cleanup_push (cleanup_mutex_cb
, &cn_mutex
);
2191 t
= slist_length (cn_thread_list
);
2193 for (i
= 0; i
< t
; i
++)
2195 struct client_thread_s
*thd
= slist_nth_data (cn_thread_list
, i
);
2200 if (!memcmp (thd
->cl
->md5file
, cache
->filename
,
2201 sizeof (cache
->filename
)))
2203 if (pthread_equal (pthread_self (), thd
->tid
))
2210 /* Continue trying to find a client who has the same file open and
2211 * also has a lock. */
2212 rc
= cache_lock_mutex (thd
->cl
->ctx
, thd
->cl
->md5file
, -1, 0, -1);
2222 if (self
&& (!rc
|| rc
== GPG_ERR_NO_DATA
))
2223 rc
= cache_lock_mutex (found
->cl
->ctx
, found
->cl
->md5file
, -1, 0, -1);
2225 if (exiting
|| !rc
|| rc
== GPG_ERR_NO_DATA
)
2227 free_cache_data_once (cache
->data
);
2229 cache
->defer_clear
= 0;
2230 cache
->timeout
= -1;
2233 cache_unlock_mutex (found
->cl
->md5file
, 0);
2239 cache
->defer_clear
= 1;
2241 pthread_cleanup_pop (1);
2247 convert_v2_datafile (const char *filename
, const char *cipher
,
2248 const char *keyfile
, const char *keygrip
,
2249 const char *sign_keygrip
, int nopass
,
2250 const char *outfile
, const char *keyparam
,
2251 unsigned long s2k_count
, uint64_t iterations
)
2256 struct crypto_s
*crypto
= NULL
;
2262 if (outfile
[0] == '-' && outfile
[1] == 0)
2265 log_write (_("Converting version 2 data file \"%s\" ..."), filename
);
2266 if (access (filename
, R_OK
) == -1)
2268 log_write ("%s: %s", filename
,
2269 pwmd_strerror (gpg_error_from_errno (errno
)));
2275 log_write (_("Using passphrase file \"%s\" for decryption ..."),
2277 if (access (keyfile
, R_OK
) == -1)
2279 log_write ("%s: %s", keyfile
,
2280 pwmd_strerror (gpg_error_from_errno (errno
)));
2285 rc
= read_v2_datafile (filename
, keyfile
, &data
, &datalen
, &ver
, &algo
);
2288 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
2294 algo
= cipher_string_to_gcrypt (cipher
);
2297 rc
= GPG_ERR_CIPHER_ALGO
;
2306 rc
= parse_doc (data
, datalen
, &doc
);
2310 rc
= convert_pre_212_elements (doc
);
2315 xmlDocDumpFormatMemory (doc
, (xmlChar
**) & data
, (int *) &datalen
,
2318 rc
= GPG_ERR_ENOMEM
;
2326 rc
= init_client_crypto (&crypto
);
2329 memcpy (&crypto
->save
.hdr
, &crypto
->hdr
, sizeof (file_header_t
));
2330 crypto
->save
.hdr
.flags
= set_cipher_flag (crypto
->save
.hdr
.flags
, algo
);
2331 crypto
->save
.s2k_count
= s2k_count
;
2332 crypto
->save
.hdr
.iterations
= iterations
;
2336 rc
= export_common (NULL
, 0, crypto
, data
, datalen
, outfile
, keyfile
,
2337 &key
, &keylen
, 0, 0, nopass
);
2342 rc
= agent_set_pinentry_options (crypto
->agent
);
2344 rc
= agent_export_common (crypto
, keygrip
, sign_keygrip
, nopass
,
2345 data
, datalen
, outfile
, keyparam
,
2346 no_passphrase_file
? NULL
: keyfile
);
2350 log_write (_("Output written to \"%s\"."), outfile
);
2360 cleanup_crypto (&crypto
);
2363 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
2368 usage (const char *pn
, int status
)
2370 FILE *fp
= status
== EXIT_FAILURE
? stderr
: stdout
;
2372 fprintf (fp
, _("Usage: %s [OPTIONS] [file1] [...]\n"
2373 " -f, --rcfile=filename load the specfied configuration file\n"
2374 " (~/.pwmd/config)\n"
2375 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2377 " --use-agent enable use of gpg-agent\n"
2379 " -n, --no-fork run as a foreground process\n"
2380 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2381 " --ignore, --force ignore file errors during startup\n"
2382 " --debug-level=keywords log protocol output (see manual for details)\n"
2383 " -o, --outfile=filename output file when importing or converting\n"
2384 " -C, --convert=filename convert a version 2 data file to version 3\n"
2385 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2386 " -k, --passphrase-file=file for use when importing or converting\n"
2387 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2389 " --no-passphrase when importing or converting\n"
2390 " --keygrip=hex public key to use when encrypting\n"
2391 " --sign-keygrip=hex private key to use when signing\n"
2392 " --keyparam=s-exp custom key parameters to use (RSA-2048)\n"
2393 " --cipher=string encryption cipher (aes256)\n"
2394 " --iterations=N cipher iteration count (N+1)\n"
2395 " --s2k-count=N hash iteration count (>65536, calibrated)\n"
2396 " --help this help text\n"
2397 " --version show version and compile time features\n"),
2403 unlink_stale_socket (const char *sock
, const char *pidfile
)
2405 log_write (_ ("removing stale socket %s"), sock
);
2411 test_pidfile (const char *path
, const char *sock
, char *buf
, size_t buflen
,
2412 char **pidfile
, int create
, mode_t mode
)
2420 snprintf (buf
, buflen
, "%s/%s.pid", homedir
, sock
);
2421 *pidfile
= str_dup (buf
);
2422 fd
= open (buf
, O_RDONLY
);
2425 fd
= open (*pidfile
, O_CREAT
|O_WRONLY
|O_TRUNC
, mode
);
2429 if (!create
&& errno
!= ENOENT
)
2431 log_write ("%s: %s", buf
, pwmd_strerror (errno
));
2439 log_write ("%s: %s", *pidfile
, strerror (errno
));
2445 snprintf (buf
, buflen
, "%i", getpid ());
2446 write (fd
, buf
, strlen (buf
));
2451 len
= read (fd
, buf
, sizeof(buf
));
2455 unlink_stale_socket (path
, *pidfile
);
2459 if (sscanf (buf
, "%5i", &pid
) != 1 || pid
== 0)
2461 unlink_stale_socket (path
, *pidfile
);
2465 if (kill (pid
, 0) == -1)
2467 unlink_stale_socket (path
, *pidfile
);
2471 log_write (_ ("an instance for socket %s is already running"), path
);
2478 main (int argc
, char *argv
[])
2481 struct sockaddr_un addr
;
2483 char *socketpath
= NULL
, *socketdir
, *socketname
= NULL
;
2484 char *socketarg
= NULL
;
2485 char *datadir
= NULL
;
2486 char *pidfile
= NULL
;
2490 char **cache_push
= NULL
;
2491 char *import
= NULL
, *keygrip
= NULL
, *sign_keygrip
= NULL
;
2492 char *keyparam
= NULL
;
2493 int estatus
= EXIT_FAILURE
;
2495 char *outfile
= NULL
;
2498 int show_version
= 0;
2500 int no_passphrase
= 0;
2502 char *convertfile
= NULL
;
2503 char *cipher
= NULL
;
2504 char *keyfile
= NULL
;
2505 unsigned long s2k_count
= 0;
2506 uint64_t iterations
= 0;
2508 char *debug_level_opt
= NULL
;
2510 /* Must maintain the same order as longopts[] */
2513 OPT_VERSION
, OPT_HELP
,
2517 OPT_DEBUG_LEVEL
, OPT_HOMEDIR
, OPT_NO_FORK
, OPT_DISABLE_DUMP
,
2518 OPT_IGNORE
, OPT_FORCE
, OPT_RCFILE
, OPT_CONVERT
,
2519 OPT_PASSPHRASE_FILE
, OPT_IMPORT
, OPT_OUTFILE
,
2520 OPT_NO_PASSPHRASE_FILE
, OPT_KEYGRIP
, OPT_SIGN_KEYGRIP
,
2521 OPT_KEYPARAM
, OPT_CIPHER
, OPT_ITERATIONS
, OPT_S2K_COUNT
,
2524 const char *optstring
= "nf:C:k:I:o:";
2525 const struct option longopts
[] = {
2526 {"version", no_argument
, 0, 0},
2527 {"help", no_argument
, 0, 0},
2529 {"use-agent", no_argument
, 0, 0},
2531 {"debug-level", required_argument
, 0, 0},
2532 {"homedir", required_argument
, 0, 0},
2533 {"no-fork", no_argument
, 0, 'n'},
2534 {"disable_dump", no_argument
, 0, 0},
2535 {"ignore", no_argument
, 0, 0},
2536 {"force", no_argument
, 0, 0},
2537 {"rcfile", required_argument
, 0, 'f'},
2538 {"convert", required_argument
, 0, 'C'},
2539 {"passphrase-file", required_argument
, 0, 'k'},
2540 {"import", required_argument
, 0, 'I'},
2541 {"outfile", required_argument
, 0, 'o'},
2542 {"no-passphrase-file", no_argument
, 0, 0},
2543 {"keygrip", required_argument
, 0, 0},
2544 {"sign-keygrip", required_argument
, 0, 0},
2545 {"keyparam", required_argument
, 0, 0},
2546 {"cipher", required_argument
, 0, 0},
2547 {"cipher-iterations", required_argument
, 0, 0},
2548 {"s2k-count", required_argument
, 0, 0},
2549 {"no-passphrase", no_argument
, 0, 0},
2556 #ifdef HAVE_SETRLIMIT
2559 rl
.rlim_cur
= rl
.rlim_max
= 0;
2561 if (setrlimit (RLIMIT_CORE
, &rl
) != 0)
2562 err (EXIT_FAILURE
, "setrlimit()");
2567 setlocale (LC_ALL
, "");
2568 bindtextdomain ("pwmd", LOCALEDIR
);
2569 textdomain ("pwmd");
2577 if (setup_crypto ())
2578 exit (EXIT_FAILURE
);
2581 gnutls_global_set_mem_functions (xmalloc
, xmalloc
, secure_mem_check
,
2583 gnutls_global_init ();
2584 gnutls_global_set_log_function (tls_log
);
2585 gnutls_global_set_log_level (1);
2589 xmlMemSetup (xfree
, xmalloc
, xrealloc
, str_dup
);
2597 while ((opt
= getopt_long (argc
, argv
, optstring
, longopts
, &optindex
))
2606 convertfile
= optarg
;
2621 rcfile
= str_dup (optarg
);
2624 usage (argv
[0], EXIT_FAILURE
);
2640 case OPT_DEBUG_LEVEL
:
2641 debug_level_opt
= optarg
;
2644 homedir
= str_dup (optarg
);
2649 case OPT_DISABLE_DUMP
:
2657 rcfile
= str_dup (optarg
);
2660 convertfile
= optarg
;
2662 case OPT_PASSPHRASE_FILE
:
2671 case OPT_NO_PASSPHRASE_FILE
:
2672 no_passphrase_file
= 1;
2677 case OPT_SIGN_KEYGRIP
:
2678 sign_keygrip
= optarg
;
2686 case OPT_ITERATIONS
:
2687 iterations
= strtoull (optarg
, NULL
, 10);
2690 s2k_count
= strtoul (optarg
, NULL
, 10);
2692 case OPT_NO_PASSPHRASE
:
2704 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014\n"
2706 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2707 "Compile time features:\n%s"), PACKAGE_STRING
,
2710 "+PWMD_HOMEDIR=" PWMD_HOMEDIR
"\n"
2748 exit (EXIT_SUCCESS
);
2753 homedir
= str_dup(PWMD_HOMEDIR
);
2755 homedir
= str_asprintf ("%s/.pwmd", get_home_dir ());
2758 if (mkdir (homedir
, 0700) == -1 && errno
!= EEXIST
)
2759 err (EXIT_FAILURE
, "%s", homedir
);
2761 snprintf (buf
, sizeof (buf
), "%s/data", homedir
);
2762 if (mkdir (buf
, 0700) == -1 && errno
!= EEXIST
)
2763 err (EXIT_FAILURE
, "%s", buf
);
2765 datadir
= str_dup (buf
);
2766 pthread_mutexattr_t attr
;
2767 pthread_mutexattr_init (&attr
);
2768 pthread_mutexattr_settype (&attr
, PTHREAD_MUTEX_RECURSIVE
);
2769 pthread_mutex_init (&rcfile_mutex
, &attr
);
2770 pthread_cond_init (&rcfile_cond
, NULL
);
2771 pthread_mutex_init (&cn_mutex
, &attr
);
2772 pthread_mutexattr_destroy (&attr
);
2773 pthread_key_create (&last_error_key
, free_key
);
2774 #ifndef HAVE_PTHREAD_CANCEL
2775 pthread_key_create (&signal_thread_key
, free_key
);
2779 rcfile
= str_asprintf ("%s/config", homedir
);
2781 global_config
= config_parse (rcfile
);
2783 exit (EXIT_FAILURE
);
2787 use_agent
= config_get_boolean ("global", "use_agent");
2792 if (debug_level_opt
)
2793 debug_level
= str_split (debug_level_opt
, ",", 0);
2795 x
= config_get_int_param (global_config
, "global", "priority", &exists
);
2796 if (exists
&& x
!= atoi(INVALID_PRIORITY
))
2799 if (setpriority (PRIO_PROCESS
, 0, x
) == -1)
2801 log_write ("setpriority(): %s",
2802 pwmd_strerror (gpg_error_from_errno (errno
)));
2806 #ifdef HAVE_MLOCKALL
2807 if (disable_mlock
== 0 && mlockall (MCL_CURRENT
| MCL_FUTURE
) == -1)
2809 log_write ("mlockall(): %s",
2810 pwmd_strerror (gpg_error_from_errno (errno
)));
2815 rc
= cache_init (free_cache_data
);
2818 log_write ("pwmd: ERR %i: %s", rc
,
2819 gpg_err_code (rc
) == GPG_ERR_UNKNOWN_VERSION
2820 ? _("incompatible gpg-agent version: 2.1.0 or later required")
2821 : pwmd_strerror (rc
));
2826 s2k_count
= config_get_ulong (NULL
, "s2k_count");
2830 if (!outfile
|| !*outfile
|| argc
!= optind
)
2831 usage (argv
[0], EXIT_FAILURE
);
2833 estatus
= convert_v2_datafile (convertfile
, cipher
, keyfile
, keygrip
,
2834 sign_keygrip
, no_passphrase
, outfile
,
2835 keyparam
, s2k_count
, iterations
);
2836 config_free (global_config
);
2843 if (!outfile
|| !*outfile
|| argc
!= optind
)
2844 usage (argv
[0], EXIT_FAILURE
);
2846 if (outfile
&& outfile
[0] == '-' && outfile
[1] == 0)
2849 estatus
= xml_import (import
, outfile
, keygrip
, sign_keygrip
, keyfile
,
2850 no_passphrase
, cipher
, keyparam
, s2k_count
,
2852 config_free (global_config
);
2857 p
= config_get_string ("global", "socket_path");
2859 p
= str_asprintf ("%s/socket", homedir
);
2861 socketarg
= expand_homedir (p
);
2865 disable_list_and_dump
= config_get_boolean ("global",
2866 "disable_list_and_dump");
2868 disable_list_and_dump
= secure
;
2870 cache_push
= config_get_list ("global", "cache_push");
2872 while (optind
< argc
)
2874 if (strv_printf (&cache_push
, "%s", argv
[optind
++]) == 0)
2875 errx (EXIT_FAILURE
, "%s", pwmd_strerror (GPG_ERR_ENOMEM
));
2878 if (strchr (socketarg
, '/') == NULL
)
2880 socketdir
= getcwd (buf
, sizeof (buf
));
2881 socketname
= str_dup (socketarg
);
2882 socketpath
= str_asprintf ("%s/%s", socketdir
, socketname
);
2886 socketname
= str_dup (strrchr (socketarg
, '/'));
2888 socketarg
[strlen (socketarg
) - strlen (socketname
) - 1] = 0;
2889 socketdir
= str_dup (socketarg
);
2890 socketpath
= str_asprintf ("%s/%s", socketdir
, socketname
);
2893 if (chdir (datadir
))
2895 log_write ("%s: %s", datadir
,
2896 pwmd_strerror (gpg_error_from_errno (errno
)));
2897 unlink (socketpath
);
2901 if (test_pidfile (socketpath
, socketname
, buf
, sizeof(buf
), &pidfile
, 0,
2906 * bind() doesn't like the full pathname of the socket or any non alphanum
2907 * characters so change to the directory where the socket is wanted then
2908 * create it then change to datadir.
2910 if (chdir (socketdir
))
2912 log_write ("%s: %s", socketdir
,
2913 pwmd_strerror (gpg_error_from_errno (errno
)));
2919 if ((sockfd
= socket (PF_UNIX
, SOCK_STREAM
, 0)) == -1)
2921 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
2925 addr
.sun_family
= AF_UNIX
;
2926 snprintf (addr
.sun_path
, sizeof (addr
.sun_path
), "%s", socketname
);
2928 if (bind (sockfd
, (struct sockaddr
*) &addr
, sizeof (struct sockaddr
)) ==
2931 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
2933 if (errno
== EADDRINUSE
)
2936 log_write (_("Either there is another pwmd running or '%s' is a \n"
2937 "stale socket. Please remove it manually."), socketpath
);
2944 char *t
= config_get_string ("global", "socket_perms");
2949 mode
= strtol (t
, NULL
, 8);
2953 if (chmod (socketname
, mode
) == -1)
2955 log_write ("%s: %s", socketname
,
2956 pwmd_strerror (gpg_error_from_errno (errno
)));
2966 xfree (--socketname
);
2968 if (chdir (datadir
))
2970 log_write ("%s: %s", datadir
,
2971 pwmd_strerror (gpg_error_from_errno (errno
)));
2979 * Set the cache entry for a file. Prompts for the password.
2983 struct crypto_s
*crypto
= NULL
;
2984 gpg_error_t rc
= init_client_crypto (&crypto
);
2988 estatus
= EXIT_FAILURE
;
2995 rc
= agent_set_pinentry_options (crypto
->agent
);
2998 estatus
= EXIT_FAILURE
;
3004 for (opt
= 0; cache_push
[opt
]; opt
++)
3006 if (!do_cache_push (cache_push
[opt
], crypto
) && !force
)
3008 strv_free (cache_push
);
3010 estatus
= EXIT_FAILURE
;
3011 cleanup_crypto (&crypto
);
3015 cleanup_crypto_stage1 (crypto
);
3020 (void) kill_scd (crypto
->agent
);
3023 cleanup_crypto (&crypto
);
3024 strv_free (cache_push
);
3025 log_write (!nofork
? _("Done. Daemonizing...") :
3026 _("Done. Waiting for connections..."));
3029 config_clear_keys ();
3031 if (listen (sockfd
, 0) == -1)
3033 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
3042 log_write ("fork(): %s",
3043 pwmd_strerror (gpg_error_from_errno (errno
)));
3052 _exit (EXIT_SUCCESS
);
3056 (void)test_pidfile (socketpath
, socketname
, buf
, sizeof(buf
), &pidfile
, 1,
3059 pthread_key_create (&thread_name_key
, free_key
);
3060 pthread_setspecific (thread_name_key
, str_dup ("main"));
3061 estatus
= server_loop (sockfd
, &socketpath
);
3064 if (socketpath
&& do_unlink
)
3066 unlink (socketpath
);
3072 gnutls_global_deinit ();
3076 #ifdef HAVE_PTHREAD_CANCEL
3077 pthread_cancel (rcfile_tid
);
3079 pthread_kill (rcfile_tid
, SIGUSR2
);
3080 pthread_cond_signal (&rcfile_cond
);
3082 pthread_join (rcfile_tid
, NULL
);
3085 pthread_cond_destroy (&rcfile_cond
);
3086 pthread_mutex_destroy (&rcfile_mutex
);
3087 pthread_key_delete (last_error_key
);
3088 #ifndef HAVE_PTHREAD_CANCEL
3089 pthread_key_delete (signal_thread_key
);
3093 config_free (global_config
);
3096 xfree (home_directory
);
3098 xmlCleanupParser ();
3099 xmlCleanupGlobals ();
3105 if (estatus
== EXIT_SUCCESS
)
3106 log_write (_("pwmd exiting normally"));
3108 pthread_key_delete (thread_name_key
);
3110 #if defined(DEBUG) && !defined(MEM_DEBUG)