2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013
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>
61 #ifdef HAVE_GETOPT_LONG
66 #include "getopt_long.h"
69 #ifdef HAVE_PR_SET_NAME
70 #include <sys/prctl.h>
73 #include "pwmd-error.h"
76 #include "util-misc.h"
82 #include "util-string.h"
89 /* In tenths of a second. */
92 /* For (tcp_)accept_thread (usec). */
93 #define ACCEPT_TIMEOUT 30000
100 static pthread_cond_t quit_cond
;
101 static pthread_mutex_t quit_mutex
;
102 static int no_passphrase_file
= 0;
104 #ifndef HAVE_PTHREAD_CANCEL
105 static pthread_key_t signal_thread_key
;
111 static pthread_t tls_tid
;
112 static pthread_t tls6_tid
;
113 static int spawned_tls
;
114 static int spawned_tls6
;
116 static int start_stop_tls (int term
);
119 static int do_cache_push (const char *filename
, struct crypto_s
*crypto
);
120 static int signal_loop (sigset_t sigset
);
122 GCRY_THREAD_OPTION_PTHREAD_IMPL
;
124 #ifndef HAVE_PTHREAD_CANCEL
125 #define INIT_THREAD_SIGNAL do { \
126 struct sigaction act; \
128 sigemptyset (&sigset); \
129 sigaddset (&sigset, SIGUSR2); \
130 pthread_sigmask (SIG_UNBLOCK, &sigset, NULL); \
131 memset (&act, 0, sizeof(act)); \
132 act.sa_flags = SA_SIGINFO; \
133 act.sa_mask = sigset; \
134 act.sa_sigaction = catch_thread_signal; \
135 sigaction (SIGUSR2, &act, NULL); \
139 catch_thread_signal (int sig
, siginfo_t
*info
, void *ctx
)
141 int *n
= (int *) pthread_getspecific (signal_thread_key
);
144 pthread_setspecific (signal_thread_key
, n
);
149 cache_push_from_rcfile ()
151 struct crypto_s
*crypto
= NULL
;
153 gpg_error_t rc
= init_client_crypto (&crypto
);
157 log_write ("%s: %s", __FUNCTION__
, pwmd_strerror (rc
));
164 rc
= set_agent_option (crypto
->agent
, "pinentry-mode", "error");
167 log_write ("%s: %s", __FUNCTION__
, pwmd_strerror (rc
));
173 cache_push
= config_get_list ("global", "cache_push");
178 for (p
= cache_push
; *p
; p
++)
180 (void) do_cache_push (*p
, crypto
);
181 cleanup_crypto_stage1 (crypto
);
184 strv_free (cache_push
);
188 (void) kill_scd (crypto
->agent
);
190 cleanup_crypto (&crypto
);
196 int n
= config_get_boolean ("global", "enable_logging");
200 char *p
= config_get_string ("global", "log_path");
203 logfile
= expand_homedir (p
);
212 log_syslog
= config_get_boolean ("global", "syslog");
214 openlog ("pwmd", LOG_NDELAY
| LOG_PID
, LOG_DAEMON
);
218 reload_rcfile_thread (void *arg
)
220 #ifndef HAVE_PTHREAD_CANCEL
221 int *n
= xmalloc (sizeof (int));
224 pthread_setspecific (signal_thread_key
, n
);
228 #ifdef HAVE_PR_SET_NAME
229 prctl (PR_SET_NAME
, "reload rcfile");
231 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
232 MUTEX_LOCK (&rcfile_mutex
);
233 pthread_cleanup_push (cleanup_mutex_cb
, &rcfile_mutex
);
237 struct slist_s
*config
;
239 int b
= disable_list_and_dump
;
242 int tcp_require_key
= config_get_bool_param (global_config
, "global",
247 pthread_cond_wait (&rcfile_cond
, &rcfile_mutex
);
248 #ifndef HAVE_PTHREAD_CANCEL
249 int *n
= (int *) pthread_getspecific (signal_thread_key
);
254 users
= config_get_list ("global", "allowed");
255 log_write (_("reloading configuration file '%s'"), rcfile
);
256 config
= config_parse (rcfile
);
259 config_free (global_config
);
260 global_config
= config
;
262 cache_push_from_rcfile ();
263 config_clear_keys ();
266 disable_list_and_dump
= !disable_list_and_dump
? b
: 1;
268 if (config_get_bool_param (global_config
, "global", "tcp_require_key",
272 config_set_bool_param (&global_config
, "global", "tcp_require_key",
273 tcp_require_key
? "true" : "false");
275 char *tmp
= strv_join (",", users
);
276 config_set_list_param (&global_config
, "global", "allowed", tmp
);
280 /* Kill existing listening threads since the configured listening
281 * protocols may have changed. */
287 pthread_cleanup_pop (1);
292 send_error (assuan_context_t ctx
, gpg_error_t e
)
294 struct client_s
*client
= assuan_get_pointer (ctx
);
296 if (gpg_err_source (e
) == GPG_ERR_SOURCE_UNKNOWN
)
303 return assuan_process_done (ctx
, 0);
307 log_write ("%s", pwmd_strerror (e
));
311 if (client
&& gpg_err_code (e
) == GPG_ERR_BAD_DATA
)
313 xmlErrorPtr xe
= client
->xml_error
;
316 xe
= xmlGetLastError ();
319 log_write ("%s", xe
->message
);
320 if (client
->last_error
)
321 xfree (client
->last_error
);
323 client
->last_error
= str_dup (xe
->message
);
326 e
= assuan_process_done (ctx
, assuan_set_error (ctx
, e
,
330 if (xe
== client
->xml_error
)
333 xmlResetLastError ();
335 client
->xml_error
= NULL
;
339 return assuan_process_done (ctx
,
340 assuan_set_error (ctx
, e
, pwmd_strerror (e
)));
344 assuan_log_cb (assuan_context_t ctx
, void *data
, unsigned cat
,
347 static pthread_mutex_t m
= PTHREAD_MUTEX_INITIALIZER
;
351 pthread_mutex_lock (&m
);
352 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock
, &m
);
353 t
= strv_length (debug_level
);
355 for (i
= 0; i
< t
; i
++)
357 if (!strcasecmp (debug_level
[i
], (char *) "init")
358 && cat
== ASSUAN_LOG_INIT
)
364 if (!strcasecmp (debug_level
[i
], (char *) "ctx")
365 && cat
== ASSUAN_LOG_CTX
)
371 if (!strcasecmp (debug_level
[i
], (char *) "engine")
372 && cat
== ASSUAN_LOG_ENGINE
)
378 if (!strcasecmp (debug_level
[i
], (char *) "data")
379 && cat
== ASSUAN_LOG_DATA
)
385 if (!strcasecmp (debug_level
[i
], (char *) "sysio")
386 && cat
== ASSUAN_LOG_SYSIO
)
392 if (!strcasecmp (debug_level
[i
], (char *) "control")
393 && cat
== ASSUAN_LOG_CONTROL
)
407 open (logfile
, O_WRONLY
| O_CREAT
| O_APPEND
, 0600)) == -1)
408 warn ("%s", logfile
);
411 pthread_cleanup_push (cleanup_fd_cb
, &fd
);
412 write (fd
, msg
, strlen (msg
));
413 pthread_cleanup_pop (1);
419 fprintf (stderr
, "%s%s", data
? (char *) data
: "", msg
);
424 pthread_cleanup_pop (1);
429 log_write (const char *fmt
, ...)
439 pthread_t tid
= pthread_self ();
440 static pthread_mutex_t m
= PTHREAD_MUTEX_INITIALIZER
;
442 if ((!logfile
&& !isatty (STDERR_FILENO
) && !log_syslog
) || !fmt
)
445 pthread_mutex_lock (&m
);
446 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock
, &m
);
447 pthread_cleanup_push (cleanup_fd_cb
, &fd
);
449 if (!cmdline
&& logfile
)
451 if ((fd
= open (logfile
, O_WRONLY
| O_CREAT
| O_APPEND
, 0600)) == -1)
452 warn ("%s", logfile
);
457 if (str_vasprintf (&args
, fmt
, ap
) != -1)
461 pthread_cleanup_push (xfree
, args
);
462 fprintf (stderr
, "%s\n", args
);
464 pthread_cleanup_pop (1);
468 pthread_cleanup_push (xfree
, args
);
469 name
= pthread_getspecific (thread_name_key
);
470 snprintf (buf
, sizeof (buf
), "%s(%p): ", name
? name
: _("unknown"),
474 if (!cmdline
&& log_syslog
&& !nofork
)
475 syslog (LOG_INFO
, "%s%s", name
, args
);
478 tm
= localtime (&now
);
479 strftime (tbuf
, sizeof (tbuf
), "%b %d %Y %H:%M:%S ", tm
);
480 tbuf
[sizeof (tbuf
) - 1] = 0;
482 if (args
[strlen (args
) - 1] == '\n')
483 args
[strlen (args
) - 1] = 0;
485 line
= str_asprintf ("%s %i %s%s\n", tbuf
, getpid (), name
, args
);
486 pthread_cleanup_pop (1);
489 pthread_cleanup_push (xfree
, line
);
490 if (logfile
&& fd
!= -1)
492 write (fd
, line
, strlen (line
));
498 fprintf (stdout
, "%s", line
);
502 pthread_cleanup_pop (1);
508 pthread_cleanup_pop (1);
509 pthread_cleanup_pop (0);
510 pthread_mutex_unlock (&m
);
515 secure_mem_check (const void *arg
)
524 gcry_control (GCRYCTL_SET_THREAD_CBS
, &gcry_threads_pthread
);
526 if (!gcry_check_version (GCRYPT_VERSION
))
528 fprintf (stderr
, _("gcry_check_version(): Incompatible libgcrypt. "
529 "Wanted %s, got %s.\n"), GCRYPT_VERSION
,
530 gcry_check_version (NULL
));
531 return GPG_ERR_UNKNOWN_VERSION
;
534 gcry_set_allocation_handler (xmalloc
, xmalloc
, NULL
, xrealloc
, xfree
);
538 #ifdef HAVE_GETGRNAM_R
540 do_validate_peer (struct client_s
*cl
, assuan_peercred_t
* peer
)
546 rc
= assuan_get_peercred (cl
->ctx
, peer
);
550 users
= config_get_list ("global", "allowed");
553 for (char **p
= users
; *p
; p
++)
555 struct passwd pw
, *result
;
556 struct group gr
, *gresult
;
561 size_t len
= sysconf (_SC_GETGR_R_SIZE_MAX
);
570 return GPG_ERR_ENOMEM
;
573 if (!getgrnam_r (*(p
) + 1, &gr
, buf
, len
, &gresult
) && gresult
)
575 if (gresult
->gr_gid
== (*peer
)->gid
)
582 len
= sysconf (_SC_GETPW_R_SIZE_MAX
);
586 char *tbuf
= xmalloc (len
);
587 for (char **t
= gresult
->gr_mem
; *t
; t
++)
589 if (!getpwnam_r (*t
, &pw
, tbuf
, len
, &result
) && result
)
591 if (result
->pw_uid
== (*peer
)->uid
)
608 size_t len
= sysconf (_SC_GETPW_R_SIZE_MAX
);
618 return GPG_ERR_ENOMEM
;
621 if (!getpwnam_r (*p
, &pw
, buf
, len
, &result
) && result
)
623 if (result
->pw_uid
== (*peer
)->uid
)
638 return allowed
? 0 : GPG_ERR_INV_USER_ID
;
642 do_validate_peer (struct client_s
*cl
, assuan_peercred_t
* peer
)
648 rc
= assuan_get_peercred (cl
->ctx
, peer
);
652 users
= config_get_list ("global", "allowed");
655 for (char **p
= users
; *p
; p
++)
657 struct passwd
*result
;
658 struct group
*gresult
;
662 gresult
= getgrnam (*(p
) + 1);
663 if (gresult
&& gresult
->gr_gid
== (*peer
)->gid
)
669 for (char **t
= gresult
->gr_mem
; *t
; t
++)
671 result
= getpwnam (*t
);
672 if (result
&& result
->pw_uid
== (*peer
)->uid
)
681 result
= getpwnam (*p
);
682 if (result
&& result
->pw_uid
== (*peer
)->uid
)
696 return allowed
? 0 : GPG_ERR_INV_USER_ID
;
701 validate_peer (struct client_s
*cl
)
704 assuan_peercred_t peer
;
711 rc
= do_validate_peer (cl
, &peer
);
712 if (!rc
|| gpg_err_code (rc
) == GPG_ERR_INV_USER_ID
)
713 log_write ("peer %s: uid=%i, gid=%i, pid=%i",
714 !rc
? _("accepted") : _("rejected"), peer
->uid
, peer
->gid
,
717 log_write ("%s: %s", __FUNCTION__
, pwmd_strerror (rc
));
723 xml_error_cb (void *data
, xmlErrorPtr e
)
725 struct client_s
*client
= data
;
728 * Keep the first reported error as the one to show in the error
729 * description. Reset in send_error().
731 if (client
->xml_error
)
734 xmlCopyError (e
, client
->xml_error
);
738 hook_waitpid (assuan_context_t ctx
, pid_t pid
, int action
,
739 int *status
, int options
)
741 return waitpid (pid
, status
, options
);
745 hook_read (assuan_context_t ctx
, assuan_fd_t fd
, void *data
, size_t len
)
748 struct client_s
*client
= assuan_get_pointer (ctx
);
750 if (client
->thd
->remote
)
751 return tls_read_hook (ctx
, (int) fd
, data
, len
);
754 return read ((int) fd
, data
, len
);
758 hook_write (assuan_context_t ctx
, assuan_fd_t fd
,
759 const void *data
, size_t len
)
762 struct client_s
*client
= assuan_get_pointer (ctx
);
764 if (client
->thd
->remote
)
765 return tls_write_hook (ctx
, (int) fd
, data
, len
);
768 return write ((int) fd
, data
, len
);
772 new_connection (struct client_s
*cl
)
775 static struct assuan_malloc_hooks mhooks
= { xmalloc
, xrealloc
, xfree
};
776 static struct assuan_system_hooks shooks
= {
777 ASSUAN_SYSTEM_HOOKS_VERSION
,
785 NULL
, //sendmsg both are used for FD passing
796 char *prio
= config_get_string ("global", "tls_cipher_suite");
798 cl
->thd
->tls
= tls_init (cl
->thd
->fd
, cl
->thd
->timeout
, prio
);
805 rc
= assuan_new_ext (&cl
->ctx
, GPG_ERR_SOURCE_DEFAULT
, &mhooks
,
806 debug_level
? assuan_log_cb
: NULL
, NULL
);
810 assuan_ctx_set_system_hooks (cl
->ctx
, &shooks
);
811 rc
= assuan_init_socket_server (cl
->ctx
, cl
->thd
->fd
, 2);
815 assuan_set_pointer (cl
->ctx
, cl
);
816 assuan_set_hello_line (cl
->ctx
, PACKAGE_STRING
);
817 rc
= register_commands (cl
->ctx
);
823 cl
->thd
->timeout
= config_get_integer ("global", "tls_timeout");
824 fcntl (cl
->thd
->fd
, F_SETFL
, O_NONBLOCK
);
827 rc
= assuan_accept (cl
->ctx
);
831 rc
= validate_peer (cl
);
832 /* May not be implemented on all platforms. */
833 if (rc
&& gpg_err_code (rc
) != GPG_ERR_ASS_GENERAL
)
836 rc
= init_client_crypto (&cl
->crypto
);
842 cl
->crypto
->agent
->client_ctx
= cl
->ctx
;
845 cl
->crypto
->client_ctx
= cl
->ctx
;
846 xmlSetStructuredErrorFunc (cl
, xml_error_cb
);
850 log_write ("%s", pwmd_strerror (rc
));
855 * This is called after a client_thread() terminates. Set with
856 * pthread_cleanup_push().
859 cleanup_cb (void *arg
)
861 struct client_thread_s
*cn
= arg
;
862 struct client_s
*cl
= cn
->cl
;
864 MUTEX_LOCK (&cn_mutex
);
865 cn_thread_list
= slist_remove (cn_thread_list
, cn
);
866 MUTEX_UNLOCK (&cn_mutex
);
875 gnutls_deinit (cn
->tls
->ses
);
881 if (!cn
->atfork
&& cl
->ctx
)
882 assuan_release (cl
->ctx
);
883 else if (!cn
->atfork
&& cl
->thd
&& cl
->thd
->fd
!= -1)
887 cleanup_crypto (&cl
->crypto
);
889 pinentry_free_opts (&cl
->pinentry_opts
);
898 while (cn
->msg_queue
)
900 struct status_msg_s
*msg
= cn
->msg_queue
;
902 cn
->msg_queue
= msg
->next
;
907 if (!cn
->atfork
&& cn
->status_msg_pipe
[0] != -1)
908 close (cn
->status_msg_pipe
[0]);
910 if (!cn
->atfork
&& cn
->status_msg_pipe
[1] != -1)
911 close (cn
->status_msg_pipe
[1]);
913 pthread_mutex_destroy (&cn
->status_mutex
);
917 log_write (_("exiting, fd=%i"), cn
->fd
);
918 send_status_all (STATUS_CLIENTS
, NULL
);
922 pthread_cond_signal (&quit_cond
);
926 cleanup_all_clients (int atfork
)
928 /* This function may be called from pthread_atfork() which requires
932 pthread_mutexattr_t attr
;
934 pthread_mutexattr_init (&attr
);
935 pthread_mutexattr_settype (&attr
, PTHREAD_MUTEX_RECURSIVE
);
936 pthread_mutex_init (&cn_mutex
, &attr
);
937 pthread_mutexattr_destroy (&attr
);
941 MUTEX_LOCK (&cn_mutex
);
943 while (slist_length (cn_thread_list
))
945 struct client_thread_s
*thd
= slist_nth_data (cn_thread_list
, 0);
947 thd
->atfork
= atfork
;
952 cache_deinit (atfork
);
953 MUTEX_UNLOCK (&cn_mutex
);
957 send_msg_queue (struct client_thread_s
*thd
)
959 MUTEX_LOCK (&thd
->status_mutex
);
963 read (thd
->status_msg_pipe
[0], &c
, 1);
965 while (thd
->msg_queue
)
967 struct status_msg_s
*msg
= thd
->msg_queue
;
969 thd
->msg_queue
= thd
->msg_queue
->next
;
970 MUTEX_UNLOCK (&thd
->status_mutex
);
971 rc
= send_status (thd
->cl
->ctx
, msg
->s
, msg
->line
);
972 MUTEX_LOCK (&thd
->status_mutex
);
980 MUTEX_UNLOCK (&thd
->status_mutex
);
985 client_thread (void *data
)
987 struct client_thread_s
*thd
= data
;
988 struct client_s
*cl
= xcalloc (1, sizeof (struct client_s
));
990 #ifdef HAVE_PR_SET_NAME
991 prctl (PR_SET_NAME
, "client");
993 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
997 log_write ("%s(%i): %s", __FILE__
, __LINE__
,
998 pwmd_strerror (GPG_ERR_ENOMEM
));
1002 MUTEX_LOCK (&cn_mutex
);
1003 pthread_cleanup_push (cleanup_cb
, thd
);
1006 MUTEX_UNLOCK (&cn_mutex
);
1008 if (new_connection (cl
))
1013 send_status_all (STATUS_CLIENTS
, NULL
);
1014 rc
= send_status (cl
->ctx
, STATUS_CACHE
, NULL
);
1017 log_write ("%s(%i): %s", __FILE__
, __LINE__
, pwmd_strerror (rc
));
1028 FD_SET (thd
->fd
, &rfds
);
1029 FD_SET (thd
->status_msg_pipe
[0], &rfds
);
1030 n
= thd
->fd
> thd
->status_msg_pipe
[0]
1031 ? thd
->fd
: thd
->status_msg_pipe
[0];
1033 n
= select (n
+ 1, &rfds
, NULL
, NULL
, NULL
);
1036 log_write ("%s", strerror (errno
));
1040 if (FD_ISSET (thd
->status_msg_pipe
[0], &rfds
))
1042 rc
= send_msg_queue (thd
);
1043 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1045 log_write ("%s(%i): %s", __FUNCTION__
, __LINE__
,
1046 pwmd_strerror (rc
));
1051 if (!FD_ISSET (thd
->fd
, &rfds
))
1054 rc
= assuan_process_next (cl
->ctx
, &eof
);
1057 if (gpg_err_code (rc
) == GPG_ERR_EOF
|| eof
)
1060 log_write ("assuan_process_next(): rc=%i %s", rc
,
1061 pwmd_strerror (rc
));
1062 if (rc
== gpg_error (GPG_ERR_ETIMEDOUT
))
1065 rc
= send_error (cl
->ctx
, rc
);
1068 log_write ("assuan_process_done(): rc=%i %s", rc
,
1069 pwmd_strerror (rc
));
1074 /* Since the msg queue pipe fd's are non-blocking, check for
1075 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1076 * client has already disconnected and will be converted to
1077 * GPG_ERR_EOF during assuan_process_next().
1079 rc
= send_msg_queue (thd
);
1080 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1082 log_write ("%s(%i): %s", __FUNCTION__
, __LINE__
,
1083 pwmd_strerror (rc
));
1089 pthread_cleanup_pop (1);
1094 xml_import (const char *filename
, const char *outfile
,
1095 const char *keygrip
, const char *sign_keygrip
,
1096 const char *keyfile
, int no_passphrase
, const char *cipher
,
1097 const char *params
, unsigned long s2k_count
, uint64_t iterations
)
1106 struct crypto_s
*crypto
= NULL
;
1109 int algo
= cipher
? cipher_string_to_gcrypt ((char *) cipher
) :
1114 log_write ("ERR %i: %s", gpg_error (GPG_ERR_CIPHER_ALGO
),
1115 pwmd_strerror (GPG_ERR_CIPHER_ALGO
));
1119 if (stat (filename
, &st
) == -1)
1121 log_write ("%s: %s", filename
,
1122 pwmd_strerror (gpg_error_from_syserror ()));
1126 rc
= init_client_crypto (&crypto
);
1130 memcpy (&crypto
->save
.hdr
, &crypto
->hdr
, sizeof (file_header_t
));
1131 crypto
->save
.hdr
.flags
= set_cipher_flag (crypto
->save
.hdr
.flags
, algo
);
1132 log_write (_("Importing XML from '%s'. Output will be written to '%s' ..."),
1135 if ((fd
= open (filename
, O_RDONLY
)) == -1)
1137 log_write ("%s: %s", filename
,
1138 pwmd_strerror (gpg_error_from_syserror ()));
1142 if ((xmlbuf
= xmalloc (st
.st_size
+ 1)) == NULL
)
1145 log_write ("%s(%i): %s", __FILE__
, __LINE__
,
1146 pwmd_strerror (GPG_ERR_ENOMEM
));
1150 if (read (fd
, xmlbuf
, st
.st_size
) == -1)
1152 rc
= gpg_error_from_syserror ();
1154 log_write ("%s: %s", filename
, pwmd_strerror (rc
));
1159 xmlbuf
[st
.st_size
] = 0;
1161 * Make sure the document validates.
1163 if ((doc
= xmlReadDoc (xmlbuf
, NULL
, "UTF-8", XML_PARSE_NOBLANKS
)) == NULL
)
1165 log_write ("xmlReadDoc() failed");
1171 xmlNodePtr n
= xmlDocGetRootElement (doc
);
1172 if (n
&& !xmlStrEqual (n
->name
, (xmlChar
*) "pwmd"))
1174 log_write (_("Could not find root \"pwmd\" element."));
1175 rc
= GPG_ERR_BAD_DATA
;
1179 rc
= validate_import (n
? n
->children
: n
);
1183 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
1188 xmlDocDumpMemory (doc
, &xml
, &len
);
1190 crypto
->save
.s2k_count
= s2k_count
;
1191 crypto
->save
.hdr
.iterations
= iterations
;
1194 rc
= export_common (NULL
, 0, crypto
, xml
, len
, outfile
, keyfile
, &key
,
1197 log_write (_("Success!"));
1202 rc
= agent_set_pinentry_options (crypto
->agent
);
1204 rc
= agent_export_common (crypto
, keygrip
, sign_keygrip
, no_passphrase
,
1205 xml
, len
, outfile
, params
, keyfile
);
1213 send_error (NULL
, rc
);
1217 cleanup_crypto (&crypto
);
1221 cleanup_crypto (&crypto
);
1226 do_cache_push (const char *filename
, struct crypto_s
*crypto
)
1228 unsigned char md5file
[16];
1233 struct cache_data_s
*cdata
;
1237 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1240 if (valid_filename (filename
) == 0)
1242 log_write (_("%s: Invalid characters in filename"), filename
);
1246 rc
= decrypt_common (NULL
, 0, crypto
, filename
, &key
, &keylen
);
1250 doc
= parse_doc ((char *) crypto
->plaintext
, crypto
->plaintext_len
);
1253 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM
));
1258 gcry_md_hash_buffer (GCRY_MD_MD5
, md5file
, filename
, strlen (filename
));
1259 cdata
= xcalloc (1, sizeof (struct cache_data_s
));
1263 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM
));
1268 rc
= get_checksum (filename
, &crc
, &len
);
1271 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
1273 free_cache_data_once (cdata
);
1279 rc
= encrypt_xml (NULL
, cache_key
, cache_keysize
, GCRY_CIPHER_AES
,
1280 crypto
->plaintext
, crypto
->plaintext_len
, &cdata
->doc
,
1281 &cdata
->doclen
, &cache_iv
, &cache_blocksize
, 0);
1282 if (!rc
&& !IS_PKCS (crypto
))
1285 cdata
->keylen
= keylen
;
1292 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
1294 free_cache_data_once (cdata
);
1301 gcry_sexp_build ((gcry_sexp_t
*) & cdata
->pubkey
, NULL
, "%S",
1303 gcry_sexp_build ((gcry_sexp_t
*) & cdata
->sigkey
, NULL
, "%S",
1304 crypto
->sigpkey_sexp
);
1308 int timeout
= config_get_integer (filename
, "cache_timeout");
1309 cache_add_file (md5file
, crypto
->grip
, cdata
, timeout
);
1310 log_write (_("Successfully added '%s' to the cache."), filename
);
1315 init_client (int fd
, const char *addr
)
1318 struct client_thread_s
*new = xcalloc (1, sizeof (struct client_thread_s
));
1323 return GPG_ERR_ENOMEM
;
1326 MUTEX_LOCK (&cn_mutex
);
1327 pthread_cleanup_push (cleanup_mutex_cb
, &cn_mutex
);
1329 if (pipe (new->status_msg_pipe
) == -1)
1330 rc
= gpg_error_from_syserror ();
1334 fcntl (new->status_msg_pipe
[0], F_SETFL
, O_NONBLOCK
);
1335 fcntl (new->status_msg_pipe
[1], F_SETFL
, O_NONBLOCK
);
1336 pthread_mutex_init (&new->status_mutex
, NULL
);
1342 new->remote
= addr
? 1 : 0;
1345 rc
= create_thread (client_thread
, new, &new->tid
, 1);
1348 close (new->status_msg_pipe
[0]);
1349 close (new->status_msg_pipe
[1]);
1350 pthread_mutex_destroy (&new->status_mutex
);
1356 struct slist_s
*list
= slist_append (cn_thread_list
, new);
1360 cn_thread_list
= list
;
1362 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1363 (pthread_t
*) new->tid
, fd
, addr
);
1365 log_write (_("new connection: tid=%p, fd=%i"),
1366 (pthread_t
*) new->tid
, fd
);
1369 rc
= GPG_ERR_ENOMEM
;
1372 pthread_cleanup_pop (1);
1378 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1379 pwmd_strerror (rc
));
1385 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1387 get_in_addr (struct sockaddr
*sa
)
1389 if (sa
->sa_family
== AF_INET
)
1390 return &(((struct sockaddr_in
*) sa
)->sin_addr
);
1392 return &(((struct sockaddr_in6
*) sa
)->sin6_addr
);
1396 tcp_accept_thread (void *arg
)
1398 int sockfd
= *(int *) arg
;
1399 #ifndef HAVE_PTHREAD_CANCEL
1400 int *n
= xmalloc (sizeof (int));
1403 pthread_setspecific (signal_thread_key
, n
);
1405 fcntl (sockfd
, F_SETFL
, O_NONBLOCK
);
1408 #ifdef HAVE_PR_SET_NAME
1409 prctl (PR_SET_NAME
, "tcp_accept");
1411 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1415 struct sockaddr_storage raddr
;
1416 socklen_t slen
= sizeof (raddr
);
1419 char s
[INET6_ADDRSTRLEN
];
1420 struct timeval tv
= { 0, ACCEPT_TIMEOUT
};
1421 #ifndef HAVE_PTHREAD_CANCEL
1424 sigusr2
= (int *) pthread_getspecific (signal_thread_key
);
1429 fd
= accept (sockfd
, (struct sockaddr
*) &raddr
, &slen
);
1432 if (errno
== EMFILE
|| errno
== ENFILE
)
1433 log_write ("accept(): %s",
1434 pwmd_strerror (gpg_error_from_syserror ()));
1435 else if (errno
!= EAGAIN
)
1437 if (!quit
) // probably EBADF
1438 log_write ("accept(): %s", strerror (errno
));
1443 #ifndef HAVE_PTHREAD_CANCEL
1444 select (0, NULL
, NULL
, NULL
, &tv
);
1452 inet_ntop (raddr
.ss_family
, get_in_addr ((struct sockaddr
*) &raddr
),
1454 (void) init_client (fd
, s
);
1455 n
= config_get_integer ("global", "tcp_wait");
1458 tv
.tv_sec
= (n
* 100000) / 100000;
1459 tv
.tv_usec
= (n
* 100000) % 100000;
1460 select (0, NULL
, NULL
, NULL
, &tv
);
1468 start_stop_tls_with_protocol (int ipv6
, int term
)
1470 struct addrinfo hints
, *servinfo
, *p
;
1471 int port
= config_get_integer ("global", "tcp_port");
1475 int *fd
= ipv6
? &tls6_fd
: &tls_fd
;
1477 if (term
|| config_get_boolean ("global", "enable_tcp") == 0)
1483 #ifdef HAVE_PTHREAD_CANCEL
1484 pthread_cancel (tls6_tid
);
1486 pthread_kill (tls6_tid
, SIGUSR2
);
1488 pthread_join (tls6_tid
, NULL
);
1491 shutdown (tls6_fd
, SHUT_RDWR
);
1501 #ifdef HAVE_PTHREAD_CANCEL
1502 pthread_cancel (tls_tid
);
1504 pthread_kill (tls_tid
, SIGUSR2
);
1506 pthread_join (tls_tid
, NULL
);
1509 shutdown (tls_fd
, SHUT_RDWR
);
1515 /* A client may still be connected. */
1516 if (!quit
&& x509_cred
!= NULL
)
1517 tls_deinit_params ();
1522 if ((ipv6
&& tls6_fd
!= -1) || (!ipv6
&& tls_fd
!= -1))
1525 memset (&hints
, 0, sizeof (hints
));
1526 hints
.ai_family
= ipv6
? AF_INET6
: AF_INET
;
1527 hints
.ai_socktype
= SOCK_STREAM
;
1528 hints
.ai_flags
= AI_PASSIVE
;
1529 snprintf (buf
, sizeof (buf
), "%i", port
);
1531 if ((n
= getaddrinfo (NULL
, buf
, &hints
, &servinfo
)) == -1)
1533 log_write ("getaddrinfo(): %s", gai_strerror (n
));
1537 for (n
= 0, p
= servinfo
; p
!= NULL
; p
= p
->ai_next
)
1541 if ((ipv6
&& p
->ai_family
!= AF_INET6
)
1542 || (!ipv6
&& p
->ai_family
!= AF_INET
))
1545 if ((*fd
= socket (p
->ai_family
, p
->ai_socktype
, p
->ai_protocol
)) == -1)
1547 log_write ("socket(): %s", strerror (errno
));
1551 if (setsockopt (*fd
, SOL_SOCKET
, SO_REUSEADDR
, &r
, sizeof (int)) == -1)
1553 log_write ("setsockopt(): %s",
1554 pwmd_strerror (gpg_error_from_syserror ()));
1555 freeaddrinfo (servinfo
);
1559 if (bind (*fd
, p
->ai_addr
, p
->ai_addrlen
) == -1)
1562 log_write ("bind(): %s",
1563 pwmd_strerror (gpg_error_from_syserror ()));
1571 freeaddrinfo (servinfo
);
1576 #if HAVE_DECL_SO_BINDTODEVICE != 0
1577 char *tmp
= config_get_string ("global", "tcp_interface");
1578 if (tmp
&& setsockopt (*fd
, SOL_SOCKET
, SO_BINDTODEVICE
, tmp
,
1579 strlen (tmp
)) == -1)
1581 log_write ("setsockopt(): %s",
1582 pwmd_strerror (gpg_error_from_syserror ()));
1590 if (x509_cred
== NULL
)
1592 rc
= tls_init_params ();
1597 if (listen (*fd
, 0) == -1)
1599 log_write ("listen(): %s", strerror (errno
));
1604 rc
= create_thread (tcp_accept_thread
, fd
, &tls6_tid
, 0);
1606 rc
= create_thread (tcp_accept_thread
, fd
, &tls_tid
, 0);
1610 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1611 pwmd_strerror (rc
));
1623 start_stop_tls_with_protocol (0, 1);
1636 start_stop_tls (int term
)
1638 char *s
= config_get_string ("global", "tcp_bind");
1644 if (!strcmp (s
, "any"))
1646 b
= start_stop_tls_with_protocol (0, term
);
1648 b
= start_stop_tls_with_protocol (1, term
);
1650 else if (!strcmp (s
, "ipv4"))
1651 b
= start_stop_tls_with_protocol (0, term
);
1652 else if (!strcmp (s
, "ipv6"))
1653 b
= start_stop_tls_with_protocol (1, term
);
1663 accept_thread (void *arg
)
1665 int sockfd
= *(int *) arg
;
1666 #ifndef HAVE_PTHREAD_CANCEL
1667 int *n
= xmalloc (sizeof (int));
1670 pthread_setspecific (signal_thread_key
, n
);
1672 fcntl (sockfd
, F_SETFL
, O_NONBLOCK
);
1675 #ifdef HAVE_PR_SET_NAME
1676 prctl (PR_SET_NAME
, "accept");
1678 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1682 socklen_t slen
= sizeof (struct sockaddr_un
);
1683 struct sockaddr_un raddr
;
1685 #ifndef HAVE_PTHREAD_CANCEL
1686 struct timeval tv
= { 0, ACCEPT_TIMEOUT
};
1687 int *sigusr2
= (int *) pthread_getspecific (signal_thread_key
);
1693 fd
= accept (sockfd
, (struct sockaddr
*) &raddr
, &slen
);
1696 if (errno
== EMFILE
|| errno
== ENFILE
)
1697 log_write ("accept(): %s",
1698 pwmd_strerror (gpg_error_from_syserror ()));
1699 else if (errno
!= EAGAIN
)
1701 if (!quit
) // probably EBADF
1702 log_write ("accept(): %s",
1703 pwmd_strerror (gpg_error_from_syserror ()));
1708 #ifndef HAVE_PTHREAD_CANCEL
1709 select (0, NULL
, NULL
, NULL
, &tv
);
1714 (void) init_client (fd
, NULL
);
1717 /* Just in case accept() failed for some reason other than EBADF */
1723 cache_timer_thread (void *arg
)
1725 #ifndef HAVE_PTHREAD_CANCEL
1726 int *n
= xmalloc (sizeof (int));
1729 pthread_setspecific (signal_thread_key
, n
);
1733 #ifdef HAVE_PR_SET_NAME
1734 prctl (PR_SET_NAME
, "cache timer");
1736 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1740 struct timeval tv
= { 1, 0 };
1741 #ifndef HAVE_PTHREAD_CANCEL
1744 n
= (int *) pthread_getspecific (signal_thread_key
);
1749 select (0, NULL
, NULL
, NULL
, &tv
);
1750 cache_adjust_timeout ();
1757 catch_sigabrt (int sig
)
1766 signal_loop (sigset_t sigset
)
1775 sigwait (&sigset
, &sig
);
1778 log_write (_("caught signal %i (%s)"), sig
, strsignal (sig
));
1783 pthread_cond_signal (&rcfile_cond
);
1786 // not really handled here.
1787 catch_sigabrt (SIGABRT
);
1790 log_write (_("clearing file cache"));
1792 send_status_all (STATUS_CACHE
, NULL
);
1811 log_write ("Caught SIGSEGV. Exiting.");
1812 #ifdef HAVE_BACKTRACE
1813 BACKTRACE (__FUNCTION__
);
1819 waiting_for_exit (void *arg
)
1822 #ifndef HAVE_PTHREAD_CANCEL
1823 int *n
= xmalloc (sizeof (int));
1826 pthread_setspecific (signal_thread_key
, n
);
1830 #ifdef HAVE_PR_SET_NAME
1831 prctl (PR_SET_NAME
, "exiting");
1833 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1834 log_write (_("waiting for all clients to disconnect"));
1835 MUTEX_LOCK (&quit_mutex
);
1836 pthread_cleanup_push (cleanup_mutex_cb
, &quit_mutex
);
1843 MUTEX_LOCK (&cn_mutex
);
1844 n
= slist_length (cn_thread_list
);
1845 MUTEX_UNLOCK (&cn_mutex
);
1849 #ifndef HAVE_PTHREAD_CANCEL
1850 int *s
= (int *) pthread_getspecific (signal_thread_key
);
1857 log_write (_("%i clients remain"), n
);
1861 INIT_TIMESPEC (SIG_TIMEOUT
, ts
);
1862 pthread_cond_timedwait (&quit_cond
, &quit_mutex
, &ts
);
1865 kill (getpid (), SIGQUIT
);
1866 pthread_cleanup_pop (1);
1871 server_loop (int sockfd
, char **socketpath
)
1873 pthread_t accept_tid
;
1874 pthread_t cache_timeout_tid
;
1875 int cancel_timeout_thread
= 0, cancel_accept_thread
= 0;
1882 sigemptyset (&sigset
);
1885 sigaddset (&sigset
, SIGTERM
);
1886 sigaddset (&sigset
, SIGINT
);
1888 /* Clears the file cache. */
1889 sigaddset (&sigset
, SIGUSR1
);
1891 /* Configuration file reloading. */
1892 sigaddset (&sigset
, SIGHUP
);
1894 /* For exiting cleanly. */
1895 sigaddset (&sigset
, SIGQUIT
);
1897 #ifndef HAVE_PTHREAD_CANCEL
1899 The socket, cache and rcfile threads use this signal when
1900 pthread_cancel() is unavailable. Prevent the main thread from
1901 catching this signal from another process.
1903 sigaddset (&sigset
, SIGUSR2
);
1906 /* Clears the cache and exits when something bad happens. */
1907 signal (SIGABRT
, catch_sigabrt
);
1908 sigaddset (&sigset
, SIGABRT
);
1909 sigprocmask (SIG_BLOCK
, &sigset
, NULL
);
1911 #ifndef HAVE_PTHREAD_CANCEL
1912 /* Remove this signal from the watched signals in signal_loop(). */
1913 sigdelset (&sigset
, SIGUSR2
);
1916 /* Ignored everywhere. When a client disconnects abnormally this signal
1917 * gets raised. It isn't needed though because client_thread() will check
1918 * for rcs even after the client disconnects. */
1919 signal (SIGPIPE
, SIG_IGN
);
1921 /* Can show a backtrace of the stack in the log. */
1922 signal (SIGSEGV
, catchsig
);
1925 /* Needs to be done after the fork(). */
1926 if (!start_stop_tls (0))
1933 pthread_mutex_init (&quit_mutex
, NULL
);
1934 pthread_cond_init (&quit_cond
, NULL
);
1935 log_write (_("%s started for user %s"), PACKAGE_STRING
, get_username ());
1938 if (config_get_boolean ("global", "enable_tcp"))
1939 log_write (_("Listening on %s and TCP port %i"), *socketpath
,
1940 config_get_integer ("global", "tcp_port"));
1942 log_write (_("Listening on %s"), *socketpath
);
1944 log_write (_("Listening on %s"), *socketpath
);
1947 rc
= create_thread (reload_rcfile_thread
, NULL
, &rcfile_tid
, 0);
1950 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1951 pwmd_strerror (rc
));
1955 rc
= create_thread (cache_timer_thread
, NULL
, &cache_timeout_tid
, 0);
1958 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1959 pwmd_strerror (rc
));
1963 cancel_timeout_thread
= 1;
1964 rc
= create_thread (accept_thread
, &sockfd
, &accept_tid
, 0);
1967 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1968 pwmd_strerror (rc
));
1972 cancel_accept_thread
= 1;
1974 signal_loop (sigset
);
1980 * We're out of the main server loop. This happens when a signal was sent
1981 * to terminate the daemon. We'll wait for all clients to disconnect
1982 * before exiting but exit immediately if another termination signal is
1985 if (cancel_accept_thread
)
1987 #ifdef HAVE_PTHREAD_CANCEL
1988 int n
= pthread_cancel (accept_tid
);
1990 int n
= pthread_kill (accept_tid
, SIGUSR2
);
1993 pthread_join (accept_tid
, NULL
);
1999 shutdown (sockfd
, SHUT_RDWR
);
2001 unlink (*socketpath
);
2002 xfree (*socketpath
);
2004 MUTEX_LOCK (&cn_mutex
);
2005 n
= slist_length (cn_thread_list
);
2006 MUTEX_UNLOCK (&cn_mutex
);
2012 rc
= create_thread (waiting_for_exit
, NULL
, &tid
, 0);
2015 if (signal_loop (sigset
))
2017 log_write (_("Received second termination request. Exiting."));
2018 #ifdef HAVE_PTHREAD_CANCEL
2019 pthread_cancel (tid
);
2021 pthread_kill (tid
, SIGUSR2
);
2023 pthread_join (tid
, NULL
);
2027 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2028 pwmd_strerror (rc
));
2031 if (cancel_timeout_thread
)
2033 #ifdef HAVE_PTHREAD_CANCEL
2034 pthread_cancel (cache_timeout_tid
);
2036 pthread_kill (cache_timeout_tid
, SIGUSR2
);
2038 pthread_join (cache_timeout_tid
, NULL
);
2041 cleanup_all_clients (0);
2046 pthread_cond_destroy (&quit_cond
);
2047 pthread_mutex_destroy (&quit_mutex
);
2048 return segv
? EXIT_FAILURE
: EXIT_SUCCESS
;;
2055 ("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
2059 /* This is called from cache.c:clear_once(). See
2060 * command.c:clearcache_command() for details about lock checking.
2063 free_cache_data (file_cache_t
* cache
)
2065 gpg_error_t rc
= GPG_ERR_NO_DATA
;
2067 struct client_thread_s
*found
= NULL
;
2074 MUTEX_LOCK (&cn_mutex
);
2075 pthread_cleanup_push (cleanup_mutex_cb
, &cn_mutex
);
2076 t
= slist_length (cn_thread_list
);
2078 for (i
= 0; i
< t
; i
++)
2080 struct client_thread_s
*thd
= slist_nth_data (cn_thread_list
, i
);
2085 if (!memcmp (thd
->cl
->md5file
, cache
->filename
,
2086 sizeof (cache
->filename
)))
2088 if (pthread_equal (pthread_self (), thd
->tid
))
2095 /* Continue trying to find a client who has the same file open and
2096 * also has a lock. */
2097 rc
= cache_lock_mutex (thd
->cl
->ctx
, thd
->cl
->md5file
, -1, 0, -1);
2107 if (self
&& (!rc
|| rc
== GPG_ERR_NO_DATA
))
2108 rc
= cache_lock_mutex (found
->cl
->ctx
, found
->cl
->md5file
, -1, 0, -1);
2110 if (exiting
|| !rc
|| rc
== GPG_ERR_NO_DATA
)
2112 free_cache_data_once (cache
->data
);
2114 cache
->defer_clear
= 0;
2115 cache
->timeout
= -1;
2118 cache_unlock_mutex (found
->cl
->md5file
, 0);
2124 cache
->defer_clear
= 1;
2126 pthread_cleanup_pop (1);
2132 convert_v2_datafile (const char *filename
, const char *cipher
,
2133 const char *keyfile
, const char *keygrip
,
2134 const char *sign_keygrip
, int nopass
,
2135 const char *outfile
, const char *keyparam
,
2136 unsigned long s2k_count
, uint64_t iterations
)
2141 struct crypto_s
*crypto
= NULL
;
2147 if (outfile
[0] == '-' && outfile
[1] == 0)
2150 log_write (_("Converting version 2 data file \"%s\" ..."), filename
);
2151 if (access (filename
, R_OK
) == -1)
2153 log_write ("%s: %s", filename
,
2154 pwmd_strerror (gpg_error_from_syserror ()));
2160 log_write (_("Using passphrase file \"%s\" for decryption ..."),
2162 if (access (keyfile
, R_OK
) == -1)
2164 log_write ("%s: %s", keyfile
,
2165 pwmd_strerror (gpg_error_from_syserror ()));
2170 rc
= read_v2_datafile (filename
, keyfile
, &data
, &datalen
, &ver
, &algo
);
2173 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
2179 algo
= cipher_string_to_gcrypt (cipher
);
2182 rc
= GPG_ERR_CIPHER_ALGO
;
2189 xmlDocPtr doc
= parse_doc (data
, datalen
);
2193 rc
= GPG_ERR_BAD_DATA
;
2197 rc
= convert_pre_212_elements (doc
);
2202 xmlDocDumpFormatMemory (doc
, (xmlChar
**) & data
, (int *) &datalen
,
2205 rc
= GPG_ERR_ENOMEM
;
2213 rc
= init_client_crypto (&crypto
);
2216 memcpy (&crypto
->save
.hdr
, &crypto
->hdr
, sizeof (file_header_t
));
2217 crypto
->save
.hdr
.flags
= set_cipher_flag (crypto
->save
.hdr
.flags
, algo
);
2218 crypto
->save
.s2k_count
= s2k_count
;
2219 crypto
->save
.hdr
.iterations
= iterations
;
2223 rc
= export_common (NULL
, 0, crypto
, data
, datalen
, outfile
, keyfile
,
2224 &key
, &keylen
, 0, 0);
2229 rc
= agent_set_pinentry_options (crypto
->agent
);
2231 rc
= agent_export_common (crypto
, keygrip
, sign_keygrip
, nopass
,
2232 data
, datalen
, outfile
, keyparam
,
2233 no_passphrase_file
? NULL
: keyfile
);
2237 log_write (_("Output written to \"%s\"."), outfile
);
2247 cleanup_crypto (&crypto
);
2250 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
2255 usage (const char *pn
, int status
)
2257 FILE *fp
= status
== EXIT_FAILURE
? stderr
: stdout
;
2259 fprintf (fp
, _("Usage: %s [OPTIONS] [file1] [...]\n"
2260 " -f, --rcfile=filename load the specfied configuration file\n"
2261 " (~/.pwmd/config)\n"
2262 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2264 " --no-agent disable use of gpg-agent\n"
2266 " -n, --no-fork run as a foreground process\n"
2267 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2268 " --ignore ignore file errors during startup\n"
2269 " --debug-level=keywords log protocol output (see manual for details)\n"
2270 " -o, --outfile=filename output file when importing or converting\n"
2271 " -C, --convert=filename convert a version 2 data file to version 3\n"
2272 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2273 " -k, --passphrase-file=file for use when importing or converting\n"
2274 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2276 " --no-passphrase when importing or converting\n"
2277 " --keygrip=hex public key to use when encrypting\n"
2278 " --sign-keygrip=hex private key to use when signing\n"
2279 " --keyparam=s-exp custom key parameters to use (RSA-2048)\n"
2280 " --cipher=string encryption cipher (aes256)\n"
2281 " --iterations=N cipher iteration count (N+1)\n"
2282 " --s2k-count=N hash iteration count (>65536, calibrated)\n"
2283 " --help this help text\n"
2284 " --version show version and compile time features\n"),
2290 main (int argc
, char *argv
[])
2293 struct sockaddr_un addr
;
2295 char *socketpath
= NULL
, *socketdir
, *socketname
= NULL
;
2296 char *socketarg
= NULL
;
2297 char *datadir
= NULL
;
2300 char **cache_push
= NULL
;
2301 char *import
= NULL
, *keygrip
= NULL
, *sign_keygrip
= NULL
;
2302 char *keyparam
= NULL
;
2303 int estatus
= EXIT_FAILURE
;
2305 char *outfile
= NULL
;
2308 int show_version
= 0;
2310 int no_passphrase
= 0;
2312 char *convertfile
= NULL
;
2313 char *cipher
= NULL
;
2314 char *keyfile
= NULL
;
2315 unsigned long s2k_count
= 0;
2316 uint64_t iterations
= 0;
2318 char *debug_level_opt
= NULL
;
2320 /* Must maintain the same order as longopts[] */
2322 { OPT_VERSION
, OPT_HELP
, OPT_NO_AGENT
,
2323 OPT_DEBUG_LEVEL
, OPT_HOMEDIR
, OPT_NO_FORK
, OPT_DISABLE_DUMP
, OPT_IGNORE
,
2324 OPT_RCFILE
, OPT_CONVERT
, OPT_PASSPHRASE_FILE
, OPT_IMPORT
, OPT_OUTFILE
,
2325 OPT_NO_PASSPHRASE_FILE
, OPT_KEYGRIP
, OPT_SIGN_KEYGRIP
, OPT_KEYPARAM
,
2326 OPT_CIPHER
, OPT_ITERATIONS
, OPT_S2K_COUNT
, OPT_NO_PASSPHRASE
2328 const char *optstring
= "nf:C:k:I:o:";
2329 const struct option longopts
[] = {
2330 {"version", no_argument
, 0, 0},
2331 {"help", no_argument
, 0, 0},
2332 {"no-agent", no_argument
, 0, 0},
2333 {"debug-level", required_argument
, 0, 0},
2334 {"homedir", required_argument
, 0, 0},
2335 {"no-fork", no_argument
, 0, 'n'},
2336 {"disable_dump", no_argument
, 0, 0},
2337 {"ignore", no_argument
, 0, 0},
2338 {"rcfile", required_argument
, 0, 'f'},
2339 {"convert", required_argument
, 0, 'C'},
2340 {"passphrase-file", required_argument
, 0, 'k'},
2341 {"import", required_argument
, 0, 'I'},
2342 {"outfile", required_argument
, 0, 'o'},
2343 {"no-passphrase-file", no_argument
, 0, 0},
2344 {"keygrip", required_argument
, 0, 0},
2345 {"sign-keygrip", required_argument
, 0, 0},
2346 {"keyparam", required_argument
, 0, 0},
2347 {"cipher", required_argument
, 0, 0},
2348 {"cipher-iterations", required_argument
, 0, 0},
2349 {"s2k-count", required_argument
, 0, 0},
2350 {"no-passphrase", no_argument
, 0, 0},
2355 #ifdef HAVE_SETRLIMIT
2358 rl
.rlim_cur
= rl
.rlim_max
= 0;
2360 if (setrlimit (RLIMIT_CORE
, &rl
) != 0)
2361 err (EXIT_FAILURE
, "setrlimit()");
2366 setlocale (LC_ALL
, "");
2367 bindtextdomain ("pwmd", LOCALEDIR
);
2368 textdomain ("pwmd");
2376 if (setup_crypto ())
2377 exit (EXIT_FAILURE
);
2380 gnutls_global_set_mem_functions (xmalloc
, xmalloc
, secure_mem_check
,
2382 gnutls_global_init ();
2383 gnutls_global_set_log_function (tls_log
);
2384 gnutls_global_set_log_level (1);
2388 xmlMemSetup (xfree
, xmalloc
, xrealloc
, str_dup
);
2399 getopt_long (argc
, argv
, optstring
, longopts
, &optindex
)) != -1)
2407 convertfile
= optarg
;
2422 rcfile
= str_dup (optarg
);
2425 usage (argv
[0], EXIT_FAILURE
);
2439 case OPT_DEBUG_LEVEL
:
2440 debug_level_opt
= optarg
;
2443 homedir
= str_dup (optarg
);
2448 case OPT_DISABLE_DUMP
:
2455 rcfile
= str_dup (optarg
);
2458 convertfile
= optarg
;
2460 case OPT_PASSPHRASE_FILE
:
2469 case OPT_NO_PASSPHRASE_FILE
:
2470 no_passphrase_file
= 1;
2475 case OPT_SIGN_KEYGRIP
:
2476 sign_keygrip
= optarg
;
2484 case OPT_ITERATIONS
:
2485 iterations
= strtoull (optarg
, NULL
, 10);
2488 s2k_count
= strtoul (optarg
, NULL
, 10);
2490 case OPT_NO_PASSPHRASE
:
2502 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013\n"
2504 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2505 "Compile time features:\n%s"), PACKAGE_STRING
,
2508 "+PWMD_HOMEDIR=" PWMD_HOMEDIR
"\n"
2546 exit (EXIT_SUCCESS
);
2551 homedir
= str_dup(PWMD_HOMEDIR
);
2553 homedir
= str_asprintf ("%s/.pwmd", get_home_dir ());
2556 if (mkdir (homedir
, 0700) == -1 && errno
!= EEXIST
)
2557 err (EXIT_FAILURE
, "%s", homedir
);
2559 snprintf (buf
, sizeof (buf
), "%s/data", homedir
);
2560 if (mkdir (buf
, 0700) == -1 && errno
!= EEXIST
)
2561 err (EXIT_FAILURE
, "%s", buf
);
2563 datadir
= str_dup (buf
);
2564 pthread_mutexattr_t attr
;
2565 pthread_mutexattr_init (&attr
);
2566 pthread_mutexattr_settype (&attr
, PTHREAD_MUTEX_RECURSIVE
);
2567 pthread_mutex_init (&rcfile_mutex
, &attr
);
2568 pthread_cond_init (&rcfile_cond
, NULL
);
2569 pthread_mutex_init (&cn_mutex
, &attr
);
2570 pthread_mutexattr_destroy (&attr
);
2571 pthread_key_create (&last_error_key
, free_key
);
2572 #ifndef HAVE_PTHREAD_CANCEL
2573 pthread_key_create (&signal_thread_key
, free_key
);
2577 rcfile
= str_asprintf ("%s/config", homedir
);
2579 global_config
= config_parse (rcfile
);
2581 exit (EXIT_FAILURE
);
2585 if (debug_level_opt
)
2586 debug_level
= str_split (debug_level_opt
, ",", 0);
2588 x
= config_get_int_param (global_config
, "global", "priority", &exists
);
2589 if (exists
&& x
!= atoi(INVALID_PRIORITY
))
2592 if (setpriority (PRIO_PROCESS
, 0, x
) == -1)
2594 log_write ("setpriority(): %s",
2595 pwmd_strerror (gpg_error_from_syserror ()));
2599 #ifdef HAVE_MLOCKALL
2600 if (disable_mlock
== 0 && mlockall (MCL_CURRENT
| MCL_FUTURE
) == -1)
2602 log_write ("mlockall(): %s",
2603 pwmd_strerror (gpg_error_from_syserror ()));
2608 rc
= cache_init (free_cache_data
);
2611 log_write ("pwmd: ERR %i: %s", rc
,
2612 gpg_err_code (rc
) == GPG_ERR_UNKNOWN_VERSION
2613 ? _("incompatible version: 2.1.0 or later required")
2614 : pwmd_strerror (rc
));
2619 s2k_count
= config_get_ulong (NULL
, "s2k_count");
2624 usage (argv
[0], EXIT_FAILURE
);
2626 estatus
= convert_v2_datafile (convertfile
, cipher
, keyfile
, keygrip
,
2627 sign_keygrip
, no_passphrase
, outfile
,
2628 keyparam
, s2k_count
, iterations
);
2629 config_free (global_config
);
2636 if (!outfile
|| !*outfile
)
2637 usage (argv
[0], EXIT_FAILURE
);
2639 if (outfile
&& outfile
[0] == '-' && outfile
[1] == 0)
2642 estatus
= xml_import (import
, outfile
, keygrip
, sign_keygrip
, keyfile
,
2643 no_passphrase
, cipher
, keyparam
, s2k_count
,
2645 config_free (global_config
);
2650 p
= config_get_string ("global", "socket_path");
2652 p
= str_asprintf ("%s/socket", homedir
);
2654 socketarg
= expand_homedir (p
);
2658 disable_list_and_dump
= config_get_boolean ("global",
2659 "disable_list_and_dump");
2661 disable_list_and_dump
= secure
;
2663 cache_push
= config_get_list ("global", "cache_push");
2665 while (optind
< argc
)
2667 if (strv_printf (&cache_push
, "%s", argv
[optind
++]) == 0)
2668 errx (EXIT_FAILURE
, "%s", pwmd_strerror (GPG_ERR_ENOMEM
));
2671 if (strchr (socketarg
, '/') == NULL
)
2673 socketdir
= getcwd (buf
, sizeof (buf
));
2674 socketname
= str_dup (socketarg
);
2675 socketpath
= str_asprintf ("%s/%s", socketdir
, socketname
);
2679 socketname
= str_dup (strrchr (socketarg
, '/'));
2681 socketarg
[strlen (socketarg
) - strlen (socketname
) - 1] = 0;
2682 socketdir
= str_dup (socketarg
);
2683 socketpath
= str_asprintf ("%s/%s", socketdir
, socketname
);
2686 if (chdir (datadir
))
2688 log_write ("%s: %s", datadir
,
2689 pwmd_strerror (gpg_error_from_syserror ()));
2690 unlink (socketpath
);
2695 * Set the cache entry for a file. Prompts for the password.
2699 struct crypto_s
*crypto
= NULL
;
2700 gpg_error_t rc
= init_client_crypto (&crypto
);
2704 estatus
= EXIT_FAILURE
;
2711 rc
= agent_set_pinentry_options (crypto
->agent
);
2714 estatus
= EXIT_FAILURE
;
2720 for (opt
= 0; cache_push
[opt
]; opt
++)
2722 if (!do_cache_push (cache_push
[opt
], crypto
) && !force
)
2724 strv_free (cache_push
);
2726 estatus
= EXIT_FAILURE
;
2727 cleanup_crypto (&crypto
);
2731 cleanup_crypto_stage1 (crypto
);
2736 (void) kill_scd (crypto
->agent
);
2739 cleanup_crypto (&crypto
);
2740 strv_free (cache_push
);
2741 log_write (!nofork
? _("Done. Daemonizing...") :
2742 _("Done. Waiting for connections..."));
2745 config_clear_keys ();
2748 * bind() doesn't like the full pathname of the socket or any non alphanum
2749 * characters so change to the directory where the socket is wanted then
2750 * create it then change to datadir.
2752 if (chdir (socketdir
))
2754 log_write ("%s: %s", socketdir
,
2755 pwmd_strerror (gpg_error_from_syserror ()));
2761 if ((sockfd
= socket (PF_UNIX
, SOCK_STREAM
, 0)) == -1)
2763 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_syserror ()));
2767 addr
.sun_family
= AF_UNIX
;
2768 snprintf (addr
.sun_path
, sizeof (addr
.sun_path
), "%s", socketname
);
2770 if (bind (sockfd
, (struct sockaddr
*) &addr
, sizeof (struct sockaddr
)) ==
2773 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_syserror ()));
2775 if (errno
== EADDRINUSE
)
2776 log_write (_("Either there is another pwmd running or '%s' is a \n"
2777 "stale socket. Please remove it manually."), socketpath
);
2783 char *t
= config_get_string ("global", "socket_perms");
2789 mode
= strtol (t
, NULL
, 8);
2793 if (chmod (socketname
, mode
) == -1)
2795 log_write ("%s: %s", socketname
,
2796 pwmd_strerror (gpg_error_from_syserror ()));
2806 xfree (--socketname
);
2808 if (chdir (datadir
))
2810 log_write ("%s: %s", datadir
,
2811 pwmd_strerror (gpg_error_from_syserror ()));
2818 if (listen (sockfd
, 0) == -1)
2820 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_syserror ()));
2831 log_write ("fork(): %s",
2832 pwmd_strerror (gpg_error_from_syserror ()));
2841 _exit (EXIT_SUCCESS
);
2845 pthread_key_create (&thread_name_key
, free_key
);
2846 pthread_setspecific (thread_name_key
, str_dup ("main"));
2847 estatus
= server_loop (sockfd
, &socketpath
);
2850 if (socketpath
&& do_unlink
)
2852 unlink (socketpath
);
2858 gnutls_global_deinit ();
2862 #ifdef HAVE_PTHREAD_CANCEL
2863 pthread_cancel (rcfile_tid
);
2865 pthread_kill (rcfile_tid
, SIGUSR2
);
2866 pthread_cond_signal (&rcfile_cond
);
2868 pthread_join (rcfile_tid
, NULL
);
2871 pthread_cond_destroy (&rcfile_cond
);
2872 pthread_mutex_destroy (&rcfile_mutex
);
2873 pthread_key_delete (last_error_key
);
2874 pthread_key_delete (thread_name_key
);
2875 #ifndef HAVE_PTHREAD_CANCEL
2876 pthread_key_delete (signal_thread_key
);
2880 config_free (global_config
);
2883 xfree (home_directory
);
2885 xmlCleanupParser ();
2886 xmlCleanupGlobals ();
2888 if (estatus
== EXIT_SUCCESS
)
2889 log_write (_("pwmd exiting normally"));
2892 #if defined(DEBUG) && !defined(MEM_DEBUG)