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;
103 static pthread_t keepalive_tid
;
105 #ifndef HAVE_PTHREAD_CANCEL
106 static pthread_key_t signal_thread_key
;
112 static pthread_t tls_tid
;
113 static pthread_t tls6_tid
;
114 static int spawned_tls
;
115 static int spawned_tls6
;
117 static int start_stop_tls (int term
);
120 static int do_cache_push (const char *filename
, struct crypto_s
*crypto
);
121 static int signal_loop (sigset_t sigset
);
123 GCRY_THREAD_OPTION_PTHREAD_IMPL
;
125 #ifndef HAVE_PTHREAD_CANCEL
126 #define INIT_THREAD_SIGNAL do { \
127 struct sigaction act; \
129 sigemptyset (&sigset); \
130 sigaddset (&sigset, SIGUSR2); \
131 pthread_sigmask (SIG_UNBLOCK, &sigset, NULL); \
132 memset (&act, 0, sizeof(act)); \
133 act.sa_flags = SA_SIGINFO; \
134 act.sa_mask = sigset; \
135 act.sa_sigaction = catch_thread_signal; \
136 sigaction (SIGUSR2, &act, NULL); \
140 catch_thread_signal (int sig
, siginfo_t
*info
, void *ctx
)
142 int *n
= (int *) pthread_getspecific (signal_thread_key
);
145 pthread_setspecific (signal_thread_key
, n
);
150 cache_push_from_rcfile ()
152 struct crypto_s
*crypto
= NULL
;
154 gpg_error_t rc
= init_client_crypto (&crypto
);
158 log_write ("%s: %s", __FUNCTION__
, pwmd_strerror (rc
));
165 rc
= set_agent_option (crypto
->agent
, "pinentry-mode", "error");
168 log_write ("%s: %s", __FUNCTION__
, pwmd_strerror (rc
));
174 cache_push
= config_get_list ("global", "cache_push");
179 for (p
= cache_push
; *p
; p
++)
181 (void) do_cache_push (*p
, crypto
);
182 cleanup_crypto_stage1 (crypto
);
185 strv_free (cache_push
);
189 (void) kill_scd (crypto
->agent
);
191 cleanup_crypto (&crypto
);
197 int n
= config_get_boolean ("global", "enable_logging");
201 char *p
= config_get_string ("global", "log_path");
204 logfile
= expand_homedir (p
);
213 log_syslog
= config_get_boolean ("global", "syslog");
215 openlog ("pwmd", LOG_NDELAY
| LOG_PID
, LOG_DAEMON
);
219 reload_rcfile_thread (void *arg
)
221 #ifndef HAVE_PTHREAD_CANCEL
222 int *n
= xmalloc (sizeof (int));
225 pthread_setspecific (signal_thread_key
, n
);
229 #ifdef HAVE_PR_SET_NAME
230 prctl (PR_SET_NAME
, "reload rcfile");
232 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
233 MUTEX_LOCK (&rcfile_mutex
);
234 pthread_cleanup_push (cleanup_mutex_cb
, &rcfile_mutex
);
238 struct slist_s
*config
;
240 int b
= disable_list_and_dump
;
242 int require_save_key
= config_get_bool_param (global_config
, "global",
246 int tcp_require_key
= config_get_bool_param (global_config
, "global",
251 pthread_cond_wait (&rcfile_cond
, &rcfile_mutex
);
252 #ifndef HAVE_PTHREAD_CANCEL
253 int *n
= (int *) pthread_getspecific (signal_thread_key
);
258 users
= config_get_list ("global", "allowed");
259 log_write (_("reloading configuration file '%s'"), rcfile
);
260 config
= config_parse (rcfile
);
263 config_free (global_config
);
264 global_config
= config
;
266 cache_push_from_rcfile ();
267 config_clear_keys ();
270 disable_list_and_dump
= !disable_list_and_dump
? b
: 1;
271 config_set_bool_param (&global_config
, "global", "require_save_key",
272 require_save_key
? "true" : "false");
274 if (config_get_bool_param (global_config
, "global", "tcp_require_key",
278 config_set_bool_param (&global_config
, "global", "tcp_require_key",
279 tcp_require_key
? "true" : "false");
281 char *tmp
= strv_join (",", users
);
282 config_set_list_param (&global_config
, "global", "allowed", tmp
);
286 /* Kill existing listening threads since the configured listening
287 * protocols may have changed. */
293 pthread_cleanup_pop (1);
298 send_error (assuan_context_t ctx
, gpg_error_t e
)
300 struct client_s
*client
= assuan_get_pointer (ctx
);
302 if (gpg_err_source (e
) == GPG_ERR_SOURCE_UNKNOWN
)
309 return assuan_process_done (ctx
, 0);
313 log_write ("ERR %i: %s", e
, pwmd_strerror (e
));
317 if (client
&& gpg_err_code (e
) == GPG_ERR_BAD_DATA
)
319 xmlErrorPtr xe
= client
->xml_error
;
322 xe
= xmlGetLastError ();
325 log_write ("%s", xe
->message
);
326 if (client
->last_error
)
327 xfree (client
->last_error
);
329 client
->last_error
= str_dup (xe
->message
);
332 e
= assuan_process_done (ctx
, assuan_set_error (ctx
, e
,
336 if (xe
== client
->xml_error
)
339 xmlResetLastError ();
341 client
->xml_error
= NULL
;
345 return assuan_process_done (ctx
,
346 assuan_set_error (ctx
, e
, pwmd_strerror (e
)));
350 assuan_log_cb (assuan_context_t ctx
, void *data
, unsigned cat
,
353 static pthread_mutex_t m
= PTHREAD_MUTEX_INITIALIZER
;
357 pthread_mutex_lock (&m
);
358 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock
, &m
);
359 t
= strv_length (debug_level
);
361 for (i
= 0; i
< t
; i
++)
363 if (!strcasecmp (debug_level
[i
], (char *) "init")
364 && cat
== ASSUAN_LOG_INIT
)
370 if (!strcasecmp (debug_level
[i
], (char *) "ctx")
371 && cat
== ASSUAN_LOG_CTX
)
377 if (!strcasecmp (debug_level
[i
], (char *) "engine")
378 && cat
== ASSUAN_LOG_ENGINE
)
384 if (!strcasecmp (debug_level
[i
], (char *) "data")
385 && cat
== ASSUAN_LOG_DATA
)
391 if (!strcasecmp (debug_level
[i
], (char *) "sysio")
392 && cat
== ASSUAN_LOG_SYSIO
)
398 if (!strcasecmp (debug_level
[i
], (char *) "control")
399 && cat
== ASSUAN_LOG_CONTROL
)
413 open (logfile
, O_WRONLY
| O_CREAT
| O_APPEND
, 0600)) == -1)
414 warn ("%s", logfile
);
417 pthread_cleanup_push (cleanup_fd_cb
, &fd
);
418 write (fd
, msg
, strlen (msg
));
419 pthread_cleanup_pop (1);
425 fprintf (stderr
, "%s%s", data
? (char *) data
: "", msg
);
430 pthread_cleanup_pop (1);
435 log_write (const char *fmt
, ...)
445 pthread_t tid
= pthread_self ();
446 static pthread_mutex_t m
= PTHREAD_MUTEX_INITIALIZER
;
448 if ((!logfile
&& !isatty (STDERR_FILENO
) && !log_syslog
) || !fmt
)
451 pthread_mutex_lock (&m
);
452 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock
, &m
);
453 pthread_cleanup_push (cleanup_fd_cb
, &fd
);
455 if (!cmdline
&& logfile
)
457 if ((fd
= open (logfile
, O_WRONLY
| O_CREAT
| O_APPEND
, 0600)) == -1)
458 warn ("%s", logfile
);
463 if (str_vasprintf (&args
, fmt
, ap
) != -1)
467 pthread_cleanup_push (xfree
, args
);
468 fprintf (stderr
, "%s\n", args
);
470 pthread_cleanup_pop (1);
474 pthread_cleanup_push (xfree
, args
);
475 name
= pthread_getspecific (thread_name_key
);
476 snprintf (buf
, sizeof (buf
), "%s(%p): ", name
? name
: _("unknown"),
480 if (!cmdline
&& log_syslog
&& !nofork
)
481 syslog (LOG_INFO
, "%s%s", name
, args
);
484 tm
= localtime (&now
);
485 strftime (tbuf
, sizeof (tbuf
), "%b %d %Y %H:%M:%S ", tm
);
486 tbuf
[sizeof (tbuf
) - 1] = 0;
488 if (args
[strlen (args
) - 1] == '\n')
489 args
[strlen (args
) - 1] = 0;
491 line
= str_asprintf ("%s %i %s%s\n", tbuf
, getpid (), name
, args
);
492 pthread_cleanup_pop (1);
495 pthread_cleanup_push (xfree
, line
);
496 if (logfile
&& fd
!= -1)
498 write (fd
, line
, strlen (line
));
504 fprintf (stdout
, "%s", line
);
508 pthread_cleanup_pop (1);
514 pthread_cleanup_pop (1);
515 pthread_cleanup_pop (0);
516 pthread_mutex_unlock (&m
);
521 secure_mem_check (const void *arg
)
530 gcry_control (GCRYCTL_SET_THREAD_CBS
, &gcry_threads_pthread
);
532 if (!gcry_check_version (GCRYPT_VERSION
))
534 fprintf (stderr
, _("gcry_check_version(): Incompatible libgcrypt. "
535 "Wanted %s, got %s.\n"), GCRYPT_VERSION
,
536 gcry_check_version (NULL
));
537 return GPG_ERR_UNKNOWN_VERSION
;
540 gcry_set_allocation_handler (xmalloc
, xmalloc
, NULL
, xrealloc
, xfree
);
544 #ifdef HAVE_GETGRNAM_R
546 do_validate_peer (struct client_s
*cl
, assuan_peercred_t
* peer
)
552 rc
= assuan_get_peercred (cl
->ctx
, peer
);
556 users
= config_get_list ("global", "allowed");
559 for (char **p
= users
; *p
; p
++)
561 struct passwd pw
, *result
;
562 struct group gr
, *gresult
;
567 size_t len
= sysconf (_SC_GETGR_R_SIZE_MAX
);
576 return GPG_ERR_ENOMEM
;
579 if (!getgrnam_r (*(p
) + 1, &gr
, buf
, len
, &gresult
) && gresult
)
581 if (gresult
->gr_gid
== (*peer
)->gid
)
588 len
= sysconf (_SC_GETPW_R_SIZE_MAX
);
592 char *tbuf
= xmalloc (len
);
593 for (char **t
= gresult
->gr_mem
; *t
; t
++)
595 if (!getpwnam_r (*t
, &pw
, tbuf
, len
, &result
) && result
)
597 if (result
->pw_uid
== (*peer
)->uid
)
614 size_t len
= sysconf (_SC_GETPW_R_SIZE_MAX
);
624 return GPG_ERR_ENOMEM
;
627 if (!getpwnam_r (*p
, &pw
, buf
, len
, &result
) && result
)
629 if (result
->pw_uid
== (*peer
)->uid
)
644 return allowed
? 0 : GPG_ERR_INV_USER_ID
;
648 do_validate_peer (struct client_s
*cl
, assuan_peercred_t
* peer
)
654 rc
= assuan_get_peercred (cl
->ctx
, peer
);
658 users
= config_get_list ("global", "allowed");
661 for (char **p
= users
; *p
; p
++)
663 struct passwd
*result
;
664 struct group
*gresult
;
668 gresult
= getgrnam (*(p
) + 1);
669 if (gresult
&& gresult
->gr_gid
== (*peer
)->gid
)
675 for (char **t
= gresult
->gr_mem
; *t
; t
++)
677 result
= getpwnam (*t
);
678 if (result
&& result
->pw_uid
== (*peer
)->uid
)
687 result
= getpwnam (*p
);
688 if (result
&& result
->pw_uid
== (*peer
)->uid
)
702 return allowed
? 0 : GPG_ERR_INV_USER_ID
;
707 validate_peer (struct client_s
*cl
)
710 assuan_peercred_t peer
;
714 return tls_validate_access (cl
, NULL
);
717 rc
= do_validate_peer (cl
, &peer
);
718 if (!rc
|| gpg_err_code (rc
) == GPG_ERR_INV_USER_ID
)
719 log_write ("peer %s: uid=%i, gid=%i, pid=%i",
720 !rc
? _("accepted") : _("rejected"), peer
->uid
, peer
->gid
,
723 log_write ("%s: %s", __FUNCTION__
, pwmd_strerror (rc
));
729 xml_error_cb (void *data
, xmlErrorPtr e
)
731 struct client_s
*client
= data
;
734 * Keep the first reported error as the one to show in the error
735 * description. Reset in send_error().
737 if (client
->xml_error
)
740 xmlCopyError (e
, client
->xml_error
);
744 hook_waitpid (assuan_context_t ctx
, pid_t pid
, int action
,
745 int *status
, int options
)
747 return waitpid (pid
, status
, options
);
751 hook_read (assuan_context_t ctx
, assuan_fd_t fd
, void *data
, size_t len
)
754 struct client_s
*client
= assuan_get_pointer (ctx
);
756 if (client
->thd
->remote
)
757 return tls_read_hook (ctx
, (int) fd
, data
, len
);
760 return read ((int) fd
, data
, len
);
764 hook_write (assuan_context_t ctx
, assuan_fd_t fd
,
765 const void *data
, size_t len
)
768 struct client_s
*client
= assuan_get_pointer (ctx
);
770 if (client
->thd
->remote
)
771 return tls_write_hook (ctx
, (int) fd
, data
, len
);
774 return write ((int) fd
, data
, len
);
778 new_connection (struct client_s
*cl
)
781 static struct assuan_malloc_hooks mhooks
= { xmalloc
, xrealloc
, xfree
};
782 static struct assuan_system_hooks shooks
= {
783 ASSUAN_SYSTEM_HOOKS_VERSION
,
791 NULL
, //sendmsg both are used for FD passing
802 char *prio
= config_get_string ("global", "tls_cipher_suite");
804 cl
->thd
->tls
= tls_init (cl
->thd
->fd
, cl
->thd
->timeout
, prio
);
811 rc
= assuan_new_ext (&cl
->ctx
, GPG_ERR_SOURCE_DEFAULT
, &mhooks
,
812 debug_level
? assuan_log_cb
: NULL
, NULL
);
816 assuan_ctx_set_system_hooks (cl
->ctx
, &shooks
);
817 rc
= assuan_init_socket_server (cl
->ctx
, cl
->thd
->fd
, 2);
821 assuan_set_pointer (cl
->ctx
, cl
);
822 assuan_set_hello_line (cl
->ctx
, PACKAGE_STRING
);
823 rc
= register_commands (cl
->ctx
);
830 cl
->thd
->timeout
= config_get_integer ("global", "tls_timeout");
831 fcntl (cl
->thd
->fd
, F_SETFL
, O_NONBLOCK
);
835 rc
= assuan_accept (cl
->ctx
);
839 rc
= validate_peer (cl
);
840 /* May not be implemented on all platforms. */
841 if (rc
&& gpg_err_code (rc
) != GPG_ERR_ASS_GENERAL
)
844 rc
= init_client_crypto (&cl
->crypto
);
850 cl
->crypto
->agent
->client_ctx
= cl
->ctx
;
853 cl
->crypto
->client_ctx
= cl
->ctx
;
854 xmlSetStructuredErrorFunc (cl
, xml_error_cb
);
858 log_write ("%s", pwmd_strerror (rc
));
863 * This is called after a client_thread() terminates. Set with
864 * pthread_cleanup_push().
867 cleanup_cb (void *arg
)
869 struct client_thread_s
*cn
= arg
;
870 struct client_s
*cl
= cn
->cl
;
872 MUTEX_LOCK (&cn_mutex
);
873 cn_thread_list
= slist_remove (cn_thread_list
, cn
);
874 MUTEX_UNLOCK (&cn_mutex
);
883 gnutls_deinit (cn
->tls
->ses
);
889 if (!cn
->atfork
&& cl
->ctx
)
890 assuan_release (cl
->ctx
);
891 else if (!cn
->atfork
&& cl
->thd
&& cl
->thd
->fd
!= -1)
895 cleanup_crypto (&cl
->crypto
);
897 pinentry_free_opts (&cl
->pinentry_opts
);
906 while (cn
->msg_queue
)
908 struct status_msg_s
*msg
= cn
->msg_queue
;
910 cn
->msg_queue
= msg
->next
;
915 if (!cn
->atfork
&& cn
->status_msg_pipe
[0] != -1)
916 close (cn
->status_msg_pipe
[0]);
918 if (!cn
->atfork
&& cn
->status_msg_pipe
[1] != -1)
919 close (cn
->status_msg_pipe
[1]);
921 pthread_mutex_destroy (&cn
->status_mutex
);
925 log_write (_("exiting, fd=%i"), cn
->fd
);
926 send_status_all (STATUS_CLIENTS
, NULL
);
930 pthread_cond_signal (&quit_cond
);
934 cleanup_all_clients (int atfork
)
936 /* This function may be called from pthread_atfork() which requires
940 pthread_mutexattr_t attr
;
942 pthread_mutexattr_init (&attr
);
943 pthread_mutexattr_settype (&attr
, PTHREAD_MUTEX_RECURSIVE
);
944 pthread_mutex_init (&cn_mutex
, &attr
);
945 pthread_mutexattr_destroy (&attr
);
949 MUTEX_LOCK (&cn_mutex
);
951 while (slist_length (cn_thread_list
))
953 struct client_thread_s
*thd
= slist_nth_data (cn_thread_list
, 0);
955 thd
->atfork
= atfork
;
960 cache_deinit (atfork
);
961 MUTEX_UNLOCK (&cn_mutex
);
965 send_msg_queue (struct client_thread_s
*thd
)
967 MUTEX_LOCK (&thd
->status_mutex
);
971 read (thd
->status_msg_pipe
[0], &c
, 1);
973 while (thd
->msg_queue
)
975 struct status_msg_s
*msg
= thd
->msg_queue
;
977 thd
->msg_queue
= thd
->msg_queue
->next
;
978 MUTEX_UNLOCK (&thd
->status_mutex
);
979 rc
= send_status (thd
->cl
->ctx
, msg
->s
, msg
->line
);
980 MUTEX_LOCK (&thd
->status_mutex
);
988 MUTEX_UNLOCK (&thd
->status_mutex
);
989 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
990 log_write ("%s: %s", __FUNCTION__
, pwmd_strerror (rc
));
996 client_thread (void *data
)
998 struct client_thread_s
*thd
= data
;
999 struct client_s
*cl
= xcalloc (1, sizeof (struct client_s
));
1001 #ifdef HAVE_PR_SET_NAME
1002 prctl (PR_SET_NAME
, "client");
1004 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1008 log_write ("%s(%i): %s", __FILE__
, __LINE__
,
1009 pwmd_strerror (GPG_ERR_ENOMEM
));
1013 MUTEX_LOCK (&cn_mutex
);
1014 pthread_cleanup_push (cleanup_cb
, thd
);
1017 MUTEX_UNLOCK (&cn_mutex
);
1019 if (new_connection (cl
))
1024 send_status_all (STATUS_CLIENTS
, NULL
);
1025 rc
= send_status (cl
->ctx
, STATUS_CACHE
, NULL
);
1028 log_write ("%s(%i): %s", __FILE__
, __LINE__
, pwmd_strerror (rc
));
1039 FD_SET (thd
->fd
, &rfds
);
1040 FD_SET (thd
->status_msg_pipe
[0], &rfds
);
1041 n
= thd
->fd
> thd
->status_msg_pipe
[0]
1042 ? thd
->fd
: thd
->status_msg_pipe
[0];
1044 n
= select (n
+ 1, &rfds
, NULL
, NULL
, NULL
);
1047 log_write ("%s", strerror (errno
));
1051 if (FD_ISSET (thd
->status_msg_pipe
[0], &rfds
))
1053 rc
= send_msg_queue (thd
);
1054 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1058 if (!FD_ISSET (thd
->fd
, &rfds
))
1061 rc
= assuan_process_next (cl
->ctx
, &eof
);
1064 if (gpg_err_code (rc
) == GPG_ERR_EOF
|| eof
)
1067 log_write ("assuan_process_next(): rc=%i %s", rc
,
1068 pwmd_strerror (rc
));
1069 if (rc
== gpg_error (GPG_ERR_ETIMEDOUT
))
1072 rc
= send_error (cl
->ctx
, rc
);
1075 log_write ("assuan_process_done(): rc=%i %s", rc
,
1076 pwmd_strerror (rc
));
1081 /* Since the msg queue pipe fd's are non-blocking, check for
1082 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1083 * client has already disconnected and will be converted to
1084 * GPG_ERR_EOF during assuan_process_next().
1086 rc
= send_msg_queue (thd
);
1087 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1092 pthread_cleanup_pop (1);
1097 xml_import (const char *filename
, const char *outfile
,
1098 const char *keygrip
, const char *sign_keygrip
,
1099 const char *keyfile
, int no_passphrase
, const char *cipher
,
1100 const char *params
, unsigned long s2k_count
, uint64_t iterations
)
1109 struct crypto_s
*crypto
= NULL
;
1112 int algo
= cipher
? cipher_string_to_gcrypt ((char *) cipher
) :
1117 log_write ("ERR %i: %s", gpg_error (GPG_ERR_CIPHER_ALGO
),
1118 pwmd_strerror (GPG_ERR_CIPHER_ALGO
));
1122 if (stat (filename
, &st
) == -1)
1124 log_write ("%s: %s", filename
,
1125 pwmd_strerror (gpg_error_from_syserror ()));
1129 rc
= init_client_crypto (&crypto
);
1133 memcpy (&crypto
->save
.hdr
, &crypto
->hdr
, sizeof (file_header_t
));
1134 crypto
->save
.hdr
.flags
= set_cipher_flag (crypto
->save
.hdr
.flags
, algo
);
1135 log_write (_("Importing XML from '%s'. Output will be written to '%s' ..."),
1138 if ((fd
= open (filename
, O_RDONLY
)) == -1)
1140 log_write ("%s: %s", filename
,
1141 pwmd_strerror (gpg_error_from_syserror ()));
1145 if ((xmlbuf
= xmalloc (st
.st_size
+ 1)) == NULL
)
1148 log_write ("%s(%i): %s", __FILE__
, __LINE__
,
1149 pwmd_strerror (GPG_ERR_ENOMEM
));
1153 if (read (fd
, xmlbuf
, st
.st_size
) == -1)
1155 rc
= gpg_error_from_syserror ();
1157 log_write ("%s: %s", filename
, pwmd_strerror (rc
));
1162 xmlbuf
[st
.st_size
] = 0;
1164 * Make sure the document validates.
1166 if ((doc
= xmlReadDoc (xmlbuf
, NULL
, "UTF-8", XML_PARSE_NOBLANKS
)) == NULL
)
1168 log_write ("xmlReadDoc() failed");
1174 xmlNodePtr n
= xmlDocGetRootElement (doc
);
1175 if (n
&& !xmlStrEqual (n
->name
, (xmlChar
*) "pwmd"))
1177 log_write (_("Could not find root \"pwmd\" element."));
1178 rc
= GPG_ERR_BAD_DATA
;
1182 rc
= validate_import (n
? n
->children
: n
);
1186 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
1191 xmlDocDumpMemory (doc
, &xml
, &len
);
1193 crypto
->save
.s2k_count
= s2k_count
;
1194 crypto
->save
.hdr
.iterations
= iterations
;
1197 rc
= export_common (NULL
, 0, crypto
, xml
, len
, outfile
, keyfile
, &key
,
1200 log_write (_("Success!"));
1205 rc
= agent_set_pinentry_options (crypto
->agent
);
1207 rc
= agent_export_common (crypto
, keygrip
, sign_keygrip
, no_passphrase
,
1208 xml
, len
, outfile
, params
, keyfile
);
1216 send_error (NULL
, rc
);
1220 cleanup_crypto (&crypto
);
1224 cleanup_crypto (&crypto
);
1229 do_cache_push (const char *filename
, struct crypto_s
*crypto
)
1231 unsigned char md5file
[16];
1236 struct cache_data_s
*cdata
;
1240 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1243 if (valid_filename (filename
) == 0)
1245 log_write (_("%s: Invalid characters in filename"), filename
);
1249 rc
= decrypt_common (NULL
, 0, crypto
, filename
, &key
, &keylen
);
1253 doc
= parse_doc ((char *) crypto
->plaintext
, crypto
->plaintext_len
);
1256 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM
));
1261 gcry_md_hash_buffer (GCRY_MD_MD5
, md5file
, filename
, strlen (filename
));
1262 cdata
= xcalloc (1, sizeof (struct cache_data_s
));
1266 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM
));
1271 rc
= get_checksum (filename
, &crc
, &len
);
1274 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
1276 free_cache_data_once (cdata
);
1282 rc
= encrypt_xml (NULL
, cache_key
, cache_keysize
, GCRY_CIPHER_AES
,
1283 crypto
->plaintext
, crypto
->plaintext_len
, &cdata
->doc
,
1284 &cdata
->doclen
, &cache_iv
, &cache_blocksize
, 0);
1285 if (!rc
&& !IS_PKI (crypto
))
1288 cdata
->keylen
= keylen
;
1295 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
1297 free_cache_data_once (cdata
);
1302 if (use_agent
&& IS_PKI (crypto
))
1304 gcry_sexp_build ((gcry_sexp_t
*) & cdata
->pubkey
, NULL
, "%S",
1306 gcry_sexp_build ((gcry_sexp_t
*) & cdata
->sigkey
, NULL
, "%S",
1307 crypto
->sigpkey_sexp
);
1311 int timeout
= config_get_integer (filename
, "cache_timeout");
1312 cache_add_file (md5file
, crypto
->grip
, cdata
, timeout
);
1313 log_write (_("Successfully added '%s' to the cache."), filename
);
1318 init_client (int fd
, const char *addr
)
1321 struct client_thread_s
*new = xcalloc (1, sizeof (struct client_thread_s
));
1326 return GPG_ERR_ENOMEM
;
1329 MUTEX_LOCK (&cn_mutex
);
1330 pthread_cleanup_push (cleanup_mutex_cb
, &cn_mutex
);
1332 if (pipe (new->status_msg_pipe
) == -1)
1333 rc
= gpg_error_from_syserror ();
1337 fcntl (new->status_msg_pipe
[0], F_SETFL
, O_NONBLOCK
);
1338 fcntl (new->status_msg_pipe
[1], F_SETFL
, O_NONBLOCK
);
1339 pthread_mutex_init (&new->status_mutex
, NULL
);
1345 new->remote
= addr
? 1 : 0;
1348 rc
= create_thread (client_thread
, new, &new->tid
, 1);
1351 close (new->status_msg_pipe
[0]);
1352 close (new->status_msg_pipe
[1]);
1353 pthread_mutex_destroy (&new->status_mutex
);
1359 struct slist_s
*list
= slist_append (cn_thread_list
, new);
1363 cn_thread_list
= list
;
1365 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1366 (pthread_t
*) new->tid
, fd
, addr
);
1368 log_write (_("new connection: tid=%p, fd=%i"),
1369 (pthread_t
*) new->tid
, fd
);
1372 rc
= GPG_ERR_ENOMEM
;
1375 pthread_cleanup_pop (1);
1381 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1382 pwmd_strerror (rc
));
1388 keepalive_thread (void *arg
)
1390 #ifndef HAVE_PTHREAD_CANCEL
1391 int *n
= xmalloc (sizeof (int));
1394 pthread_setspecific (signal_thread_key
, n
);
1398 #ifdef HAVE_PR_SET_NAME
1399 prctl (PR_SET_NAME
, "keepalive");
1401 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1405 int n
= config_get_integer ("global", "keepalive_interval");
1406 struct timeval tv
= { n
, 0 };
1407 #ifndef HAVE_PTHREAD_CANCEL
1410 sigusr2
= (int *) pthread_getspecific (signal_thread_key
);
1415 send_status_all (STATUS_KEEPALIVE
, NULL
);
1416 select (0, NULL
, NULL
, NULL
, &tv
);
1423 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1425 get_in_addr (struct sockaddr
*sa
)
1427 if (sa
->sa_family
== AF_INET
)
1428 return &(((struct sockaddr_in
*) sa
)->sin_addr
);
1430 return &(((struct sockaddr_in6
*) sa
)->sin6_addr
);
1434 tcp_accept_thread (void *arg
)
1436 int sockfd
= *(int *) arg
;
1437 #ifndef HAVE_PTHREAD_CANCEL
1438 int *n
= xmalloc (sizeof (int));
1441 pthread_setspecific (signal_thread_key
, n
);
1443 fcntl (sockfd
, F_SETFL
, O_NONBLOCK
);
1446 #ifdef HAVE_PR_SET_NAME
1447 prctl (PR_SET_NAME
, "tcp_accept");
1449 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1453 struct sockaddr_storage raddr
;
1454 socklen_t slen
= sizeof (raddr
);
1457 char s
[INET6_ADDRSTRLEN
];
1458 struct timeval tv
= { 0, ACCEPT_TIMEOUT
};
1459 #ifndef HAVE_PTHREAD_CANCEL
1462 sigusr2
= (int *) pthread_getspecific (signal_thread_key
);
1467 fd
= accept (sockfd
, (struct sockaddr
*) &raddr
, &slen
);
1470 if (errno
== EMFILE
|| errno
== ENFILE
)
1471 log_write ("accept(): %s",
1472 pwmd_strerror (gpg_error_from_syserror ()));
1473 else if (errno
!= EAGAIN
)
1475 if (!quit
) // probably EBADF
1476 log_write ("accept(): %s", strerror (errno
));
1481 #ifndef HAVE_PTHREAD_CANCEL
1482 select (0, NULL
, NULL
, NULL
, &tv
);
1490 inet_ntop (raddr
.ss_family
, get_in_addr ((struct sockaddr
*) &raddr
),
1492 (void) init_client (fd
, s
);
1493 n
= config_get_integer ("global", "tcp_wait");
1496 tv
.tv_sec
= (n
* 100000) / 100000;
1497 tv
.tv_usec
= (n
* 100000) % 100000;
1498 select (0, NULL
, NULL
, NULL
, &tv
);
1506 start_stop_tls_with_protocol (int ipv6
, int term
)
1508 struct addrinfo hints
, *servinfo
, *p
;
1509 int port
= config_get_integer ("global", "tcp_port");
1513 int *fd
= ipv6
? &tls6_fd
: &tls_fd
;
1515 if (term
|| config_get_boolean ("global", "enable_tcp") == 0)
1521 #ifdef HAVE_PTHREAD_CANCEL
1522 pthread_cancel (tls6_tid
);
1524 pthread_kill (tls6_tid
, SIGUSR2
);
1526 pthread_join (tls6_tid
, NULL
);
1529 shutdown (tls6_fd
, SHUT_RDWR
);
1539 #ifdef HAVE_PTHREAD_CANCEL
1540 pthread_cancel (tls_tid
);
1542 pthread_kill (tls_tid
, SIGUSR2
);
1544 pthread_join (tls_tid
, NULL
);
1547 shutdown (tls_fd
, SHUT_RDWR
);
1553 /* A client may still be connected. */
1554 if (!quit
&& x509_cred
!= NULL
)
1555 tls_deinit_params ();
1560 if ((ipv6
&& tls6_fd
!= -1) || (!ipv6
&& tls_fd
!= -1))
1563 memset (&hints
, 0, sizeof (hints
));
1564 hints
.ai_family
= ipv6
? AF_INET6
: AF_INET
;
1565 hints
.ai_socktype
= SOCK_STREAM
;
1566 hints
.ai_flags
= AI_PASSIVE
;
1567 snprintf (buf
, sizeof (buf
), "%i", port
);
1569 if ((n
= getaddrinfo (NULL
, buf
, &hints
, &servinfo
)) == -1)
1571 log_write ("getaddrinfo(): %s", gai_strerror (n
));
1575 for (n
= 0, p
= servinfo
; p
!= NULL
; p
= p
->ai_next
)
1579 if ((ipv6
&& p
->ai_family
!= AF_INET6
)
1580 || (!ipv6
&& p
->ai_family
!= AF_INET
))
1583 if ((*fd
= socket (p
->ai_family
, p
->ai_socktype
, p
->ai_protocol
)) == -1)
1585 log_write ("socket(): %s", strerror (errno
));
1589 if (setsockopt (*fd
, SOL_SOCKET
, SO_REUSEADDR
, &r
, sizeof (int)) == -1)
1591 log_write ("setsockopt(): %s",
1592 pwmd_strerror (gpg_error_from_syserror ()));
1593 freeaddrinfo (servinfo
);
1597 if (bind (*fd
, p
->ai_addr
, p
->ai_addrlen
) == -1)
1600 log_write ("bind(): %s",
1601 pwmd_strerror (gpg_error_from_syserror ()));
1609 freeaddrinfo (servinfo
);
1614 #if HAVE_DECL_SO_BINDTODEVICE != 0
1615 char *tmp
= config_get_string ("global", "tcp_interface");
1616 if (tmp
&& setsockopt (*fd
, SOL_SOCKET
, SO_BINDTODEVICE
, tmp
,
1617 strlen (tmp
)) == -1)
1619 log_write ("setsockopt(): %s",
1620 pwmd_strerror (gpg_error_from_syserror ()));
1628 if (x509_cred
== NULL
)
1630 rc
= tls_init_params ();
1635 if (listen (*fd
, 0) == -1)
1637 log_write ("listen(): %s", strerror (errno
));
1642 rc
= create_thread (tcp_accept_thread
, fd
, &tls6_tid
, 0);
1644 rc
= create_thread (tcp_accept_thread
, fd
, &tls_tid
, 0);
1648 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1649 pwmd_strerror (rc
));
1661 start_stop_tls_with_protocol (0, 1);
1674 start_stop_tls (int term
)
1676 char *s
= config_get_string ("global", "tcp_bind");
1682 if (!strcmp (s
, "any"))
1684 b
= start_stop_tls_with_protocol (0, term
);
1686 b
= start_stop_tls_with_protocol (1, term
);
1688 else if (!strcmp (s
, "ipv4"))
1689 b
= start_stop_tls_with_protocol (0, term
);
1690 else if (!strcmp (s
, "ipv6"))
1691 b
= start_stop_tls_with_protocol (1, term
);
1701 accept_thread (void *arg
)
1703 int sockfd
= *(int *) arg
;
1704 #ifndef HAVE_PTHREAD_CANCEL
1705 int *n
= xmalloc (sizeof (int));
1708 pthread_setspecific (signal_thread_key
, n
);
1710 fcntl (sockfd
, F_SETFL
, O_NONBLOCK
);
1713 #ifdef HAVE_PR_SET_NAME
1714 prctl (PR_SET_NAME
, "accept");
1716 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1720 socklen_t slen
= sizeof (struct sockaddr_un
);
1721 struct sockaddr_un raddr
;
1723 #ifndef HAVE_PTHREAD_CANCEL
1724 struct timeval tv
= { 0, ACCEPT_TIMEOUT
};
1725 int *sigusr2
= (int *) pthread_getspecific (signal_thread_key
);
1731 fd
= accept (sockfd
, (struct sockaddr
*) &raddr
, &slen
);
1734 if (errno
== EMFILE
|| errno
== ENFILE
)
1735 log_write ("accept(): %s",
1736 pwmd_strerror (gpg_error_from_syserror ()));
1737 else if (errno
!= EAGAIN
)
1739 if (!quit
) // probably EBADF
1740 log_write ("accept(): %s",
1741 pwmd_strerror (gpg_error_from_syserror ()));
1746 #ifndef HAVE_PTHREAD_CANCEL
1747 select (0, NULL
, NULL
, NULL
, &tv
);
1752 (void) init_client (fd
, NULL
);
1755 /* Just in case accept() failed for some reason other than EBADF */
1761 cache_timer_thread (void *arg
)
1763 #ifndef HAVE_PTHREAD_CANCEL
1764 int *n
= xmalloc (sizeof (int));
1767 pthread_setspecific (signal_thread_key
, n
);
1771 #ifdef HAVE_PR_SET_NAME
1772 prctl (PR_SET_NAME
, "cache timer");
1774 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1778 struct timeval tv
= { 1, 0 };
1779 #ifndef HAVE_PTHREAD_CANCEL
1782 n
= (int *) pthread_getspecific (signal_thread_key
);
1787 select (0, NULL
, NULL
, NULL
, &tv
);
1788 cache_adjust_timeout ();
1795 catch_sigabrt (int sig
)
1804 signal_loop (sigset_t sigset
)
1813 sigwait (&sigset
, &sig
);
1816 log_write (_("caught signal %i (%s)"), sig
, strsignal (sig
));
1821 pthread_cond_signal (&rcfile_cond
);
1824 // not really handled here.
1825 catch_sigabrt (SIGABRT
);
1828 log_write (_("clearing file cache"));
1830 send_status_all (STATUS_CACHE
, NULL
);
1849 log_write ("Caught SIGSEGV. Exiting.");
1850 #ifdef HAVE_BACKTRACE
1851 BACKTRACE (__FUNCTION__
);
1857 waiting_for_exit (void *arg
)
1860 #ifndef HAVE_PTHREAD_CANCEL
1861 int *n
= xmalloc (sizeof (int));
1864 pthread_setspecific (signal_thread_key
, n
);
1868 #ifdef HAVE_PR_SET_NAME
1869 prctl (PR_SET_NAME
, "exiting");
1871 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1872 log_write (_("waiting for all clients to disconnect"));
1873 MUTEX_LOCK (&quit_mutex
);
1874 pthread_cleanup_push (cleanup_mutex_cb
, &quit_mutex
);
1881 MUTEX_LOCK (&cn_mutex
);
1882 n
= slist_length (cn_thread_list
);
1883 MUTEX_UNLOCK (&cn_mutex
);
1887 #ifndef HAVE_PTHREAD_CANCEL
1888 int *s
= (int *) pthread_getspecific (signal_thread_key
);
1895 log_write (_("%i clients remain"), n
);
1899 INIT_TIMESPEC (SIG_TIMEOUT
, ts
);
1900 pthread_cond_timedwait (&quit_cond
, &quit_mutex
, &ts
);
1903 kill (getpid (), SIGQUIT
);
1904 pthread_cleanup_pop (1);
1909 server_loop (int sockfd
, char **socketpath
)
1911 pthread_t accept_tid
;
1912 pthread_t cache_timeout_tid
;
1913 int cancel_timeout_thread
= 0, cancel_accept_thread
= 0;
1914 int cancel_keepalive_thread
= 0;
1921 sigemptyset (&sigset
);
1924 sigaddset (&sigset
, SIGTERM
);
1925 sigaddset (&sigset
, SIGINT
);
1927 /* Clears the file cache. */
1928 sigaddset (&sigset
, SIGUSR1
);
1930 /* Configuration file reloading. */
1931 sigaddset (&sigset
, SIGHUP
);
1933 /* For exiting cleanly. */
1934 sigaddset (&sigset
, SIGQUIT
);
1936 #ifndef HAVE_PTHREAD_CANCEL
1938 The socket, cache and rcfile threads use this signal when
1939 pthread_cancel() is unavailable. Prevent the main thread from
1940 catching this signal from another process.
1942 sigaddset (&sigset
, SIGUSR2
);
1945 /* Clears the cache and exits when something bad happens. */
1946 signal (SIGABRT
, catch_sigabrt
);
1947 sigaddset (&sigset
, SIGABRT
);
1948 sigprocmask (SIG_BLOCK
, &sigset
, NULL
);
1950 #ifndef HAVE_PTHREAD_CANCEL
1951 /* Remove this signal from the watched signals in signal_loop(). */
1952 sigdelset (&sigset
, SIGUSR2
);
1955 /* Ignored everywhere. When a client disconnects abnormally this signal
1956 * gets raised. It isn't needed though because client_thread() will check
1957 * for rcs even after the client disconnects. */
1958 signal (SIGPIPE
, SIG_IGN
);
1960 /* Can show a backtrace of the stack in the log. */
1961 signal (SIGSEGV
, catchsig
);
1964 /* Needs to be done after the fork(). */
1965 if (!start_stop_tls (0))
1972 pthread_mutex_init (&quit_mutex
, NULL
);
1973 pthread_cond_init (&quit_cond
, NULL
);
1974 log_write (_("%s started for user %s"), PACKAGE_STRING
, get_username ());
1977 if (config_get_boolean ("global", "enable_tcp"))
1978 log_write (_("Listening on %s and TCP port %i"), *socketpath
,
1979 config_get_integer ("global", "tcp_port"));
1981 log_write (_("Listening on %s"), *socketpath
);
1983 log_write (_("Listening on %s"), *socketpath
);
1986 rc
= create_thread (keepalive_thread
, NULL
, &keepalive_tid
, 0);
1989 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1990 pwmd_strerror (rc
));
1994 cancel_keepalive_thread
= 1;
1995 rc
= create_thread (reload_rcfile_thread
, NULL
, &rcfile_tid
, 0);
1998 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1999 pwmd_strerror (rc
));
2003 rc
= create_thread (cache_timer_thread
, NULL
, &cache_timeout_tid
, 0);
2006 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2007 pwmd_strerror (rc
));
2011 cancel_timeout_thread
= 1;
2012 rc
= create_thread (accept_thread
, &sockfd
, &accept_tid
, 0);
2015 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2016 pwmd_strerror (rc
));
2020 cancel_accept_thread
= 1;
2022 signal_loop (sigset
);
2028 * We're out of the main server loop. This happens when a signal was sent
2029 * to terminate the daemon. We'll wait for all clients to disconnect
2030 * before exiting but exit immediately if another termination signal is
2033 if (cancel_accept_thread
)
2035 #ifdef HAVE_PTHREAD_CANCEL
2036 int n
= pthread_cancel (accept_tid
);
2038 int n
= pthread_kill (accept_tid
, SIGUSR2
);
2041 pthread_join (accept_tid
, NULL
);
2047 shutdown (sockfd
, SHUT_RDWR
);
2049 unlink (*socketpath
);
2050 xfree (*socketpath
);
2052 MUTEX_LOCK (&cn_mutex
);
2053 n
= slist_length (cn_thread_list
);
2054 MUTEX_UNLOCK (&cn_mutex
);
2060 rc
= create_thread (waiting_for_exit
, NULL
, &tid
, 0);
2063 if (signal_loop (sigset
))
2065 log_write (_("Received second termination request. Exiting."));
2066 #ifdef HAVE_PTHREAD_CANCEL
2067 pthread_cancel (tid
);
2069 pthread_kill (tid
, SIGUSR2
);
2071 pthread_join (tid
, NULL
);
2075 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2076 pwmd_strerror (rc
));
2079 if (cancel_timeout_thread
)
2081 #ifdef HAVE_PTHREAD_CANCEL
2082 pthread_cancel (cache_timeout_tid
);
2084 pthread_kill (cache_timeout_tid
, SIGUSR2
);
2086 pthread_join (cache_timeout_tid
, NULL
);
2089 if (cancel_keepalive_thread
)
2091 #ifdef HAVE_PTHREAD_CANCEL
2092 pthread_cancel (keepalive_tid
);
2094 pthread_kill (keepalive_tid
, SIGUSR2
);
2096 pthread_join (keepalive_tid
, NULL
);
2099 cleanup_all_clients (0);
2104 pthread_cond_destroy (&quit_cond
);
2105 pthread_mutex_destroy (&quit_mutex
);
2106 return segv
? EXIT_FAILURE
: EXIT_SUCCESS
;;
2113 ("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
2117 /* This is called from cache.c:clear_once(). See
2118 * command.c:clearcache_command() for details about lock checking.
2121 free_cache_data (file_cache_t
* cache
)
2123 gpg_error_t rc
= GPG_ERR_NO_DATA
;
2125 struct client_thread_s
*found
= NULL
;
2132 MUTEX_LOCK (&cn_mutex
);
2133 pthread_cleanup_push (cleanup_mutex_cb
, &cn_mutex
);
2134 t
= slist_length (cn_thread_list
);
2136 for (i
= 0; i
< t
; i
++)
2138 struct client_thread_s
*thd
= slist_nth_data (cn_thread_list
, i
);
2143 if (!memcmp (thd
->cl
->md5file
, cache
->filename
,
2144 sizeof (cache
->filename
)))
2146 if (pthread_equal (pthread_self (), thd
->tid
))
2153 /* Continue trying to find a client who has the same file open and
2154 * also has a lock. */
2155 rc
= cache_lock_mutex (thd
->cl
->ctx
, thd
->cl
->md5file
, -1, 0, -1);
2165 if (self
&& (!rc
|| rc
== GPG_ERR_NO_DATA
))
2166 rc
= cache_lock_mutex (found
->cl
->ctx
, found
->cl
->md5file
, -1, 0, -1);
2168 if (exiting
|| !rc
|| rc
== GPG_ERR_NO_DATA
)
2170 free_cache_data_once (cache
->data
);
2172 cache
->defer_clear
= 0;
2173 cache
->timeout
= -1;
2176 cache_unlock_mutex (found
->cl
->md5file
, 0);
2182 cache
->defer_clear
= 1;
2184 pthread_cleanup_pop (1);
2190 convert_v2_datafile (const char *filename
, const char *cipher
,
2191 const char *keyfile
, const char *keygrip
,
2192 const char *sign_keygrip
, int nopass
,
2193 const char *outfile
, const char *keyparam
,
2194 unsigned long s2k_count
, uint64_t iterations
)
2199 struct crypto_s
*crypto
= NULL
;
2205 if (outfile
[0] == '-' && outfile
[1] == 0)
2208 log_write (_("Converting version 2 data file \"%s\" ..."), filename
);
2209 if (access (filename
, R_OK
) == -1)
2211 log_write ("%s: %s", filename
,
2212 pwmd_strerror (gpg_error_from_syserror ()));
2218 log_write (_("Using passphrase file \"%s\" for decryption ..."),
2220 if (access (keyfile
, R_OK
) == -1)
2222 log_write ("%s: %s", keyfile
,
2223 pwmd_strerror (gpg_error_from_syserror ()));
2228 rc
= read_v2_datafile (filename
, keyfile
, &data
, &datalen
, &ver
, &algo
);
2231 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
2237 algo
= cipher_string_to_gcrypt (cipher
);
2240 rc
= GPG_ERR_CIPHER_ALGO
;
2247 xmlDocPtr doc
= parse_doc (data
, datalen
);
2251 rc
= GPG_ERR_BAD_DATA
;
2255 rc
= convert_pre_212_elements (doc
);
2260 xmlDocDumpFormatMemory (doc
, (xmlChar
**) & data
, (int *) &datalen
,
2263 rc
= GPG_ERR_ENOMEM
;
2271 rc
= init_client_crypto (&crypto
);
2274 memcpy (&crypto
->save
.hdr
, &crypto
->hdr
, sizeof (file_header_t
));
2275 crypto
->save
.hdr
.flags
= set_cipher_flag (crypto
->save
.hdr
.flags
, algo
);
2276 crypto
->save
.s2k_count
= s2k_count
;
2277 crypto
->save
.hdr
.iterations
= iterations
;
2281 rc
= export_common (NULL
, 0, crypto
, data
, datalen
, outfile
, keyfile
,
2282 &key
, &keylen
, 0, 0);
2287 rc
= agent_set_pinentry_options (crypto
->agent
);
2289 rc
= agent_export_common (crypto
, keygrip
, sign_keygrip
, nopass
,
2290 data
, datalen
, outfile
, keyparam
,
2291 no_passphrase_file
? NULL
: keyfile
);
2295 log_write (_("Output written to \"%s\"."), outfile
);
2305 cleanup_crypto (&crypto
);
2308 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
2313 usage (const char *pn
, int status
)
2315 FILE *fp
= status
== EXIT_FAILURE
? stderr
: stdout
;
2317 fprintf (fp
, _("Usage: %s [OPTIONS] [file1] [...]\n"
2318 " -f, --rcfile=filename load the specfied configuration file\n"
2319 " (~/.pwmd/config)\n"
2320 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2322 " --use-agent enable use of gpg-agent\n"
2324 " -n, --no-fork run as a foreground process\n"
2325 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2326 " --ignore ignore file errors during startup\n"
2327 " --debug-level=keywords log protocol output (see manual for details)\n"
2328 " -o, --outfile=filename output file when importing or converting\n"
2329 " -C, --convert=filename convert a version 2 data file to version 3\n"
2330 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2331 " -k, --passphrase-file=file for use when importing or converting\n"
2332 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2334 " --no-passphrase when importing or converting\n"
2335 " --keygrip=hex public key to use when encrypting\n"
2336 " --sign-keygrip=hex private key to use when signing\n"
2337 " --keyparam=s-exp custom key parameters to use (RSA-2048)\n"
2338 " --cipher=string encryption cipher (aes256)\n"
2339 " --iterations=N cipher iteration count (N+1)\n"
2340 " --s2k-count=N hash iteration count (>65536, calibrated)\n"
2341 " --help this help text\n"
2342 " --version show version and compile time features\n"),
2348 main (int argc
, char *argv
[])
2351 struct sockaddr_un addr
;
2353 char *socketpath
= NULL
, *socketdir
, *socketname
= NULL
;
2354 char *socketarg
= NULL
;
2355 char *datadir
= NULL
;
2358 char **cache_push
= NULL
;
2359 char *import
= NULL
, *keygrip
= NULL
, *sign_keygrip
= NULL
;
2360 char *keyparam
= NULL
;
2361 int estatus
= EXIT_FAILURE
;
2363 char *outfile
= NULL
;
2366 int show_version
= 0;
2368 int no_passphrase
= 0;
2370 char *convertfile
= NULL
;
2371 char *cipher
= NULL
;
2372 char *keyfile
= NULL
;
2373 unsigned long s2k_count
= 0;
2374 uint64_t iterations
= 0;
2376 char *debug_level_opt
= NULL
;
2378 /* Must maintain the same order as longopts[] */
2381 OPT_VERSION
, OPT_HELP
,
2385 OPT_DEBUG_LEVEL
, OPT_HOMEDIR
, OPT_NO_FORK
, OPT_DISABLE_DUMP
, OPT_IGNORE
,
2386 OPT_RCFILE
, OPT_CONVERT
, OPT_PASSPHRASE_FILE
, OPT_IMPORT
, OPT_OUTFILE
,
2387 OPT_NO_PASSPHRASE_FILE
, OPT_KEYGRIP
, OPT_SIGN_KEYGRIP
, OPT_KEYPARAM
,
2388 OPT_CIPHER
, OPT_ITERATIONS
, OPT_S2K_COUNT
, OPT_NO_PASSPHRASE
2390 const char *optstring
= "nf:C:k:I:o:";
2391 const struct option longopts
[] = {
2392 {"version", no_argument
, 0, 0},
2393 {"help", no_argument
, 0, 0},
2395 {"use-agent", no_argument
, 0, 0},
2397 {"debug-level", required_argument
, 0, 0},
2398 {"homedir", required_argument
, 0, 0},
2399 {"no-fork", no_argument
, 0, 'n'},
2400 {"disable_dump", no_argument
, 0, 0},
2401 {"ignore", no_argument
, 0, 0},
2402 {"rcfile", required_argument
, 0, 'f'},
2403 {"convert", required_argument
, 0, 'C'},
2404 {"passphrase-file", required_argument
, 0, 'k'},
2405 {"import", required_argument
, 0, 'I'},
2406 {"outfile", required_argument
, 0, 'o'},
2407 {"no-passphrase-file", no_argument
, 0, 0},
2408 {"keygrip", required_argument
, 0, 0},
2409 {"sign-keygrip", required_argument
, 0, 0},
2410 {"keyparam", required_argument
, 0, 0},
2411 {"cipher", required_argument
, 0, 0},
2412 {"cipher-iterations", required_argument
, 0, 0},
2413 {"s2k-count", required_argument
, 0, 0},
2414 {"no-passphrase", no_argument
, 0, 0},
2419 #ifdef HAVE_SETRLIMIT
2422 rl
.rlim_cur
= rl
.rlim_max
= 0;
2424 if (setrlimit (RLIMIT_CORE
, &rl
) != 0)
2425 err (EXIT_FAILURE
, "setrlimit()");
2430 setlocale (LC_ALL
, "");
2431 bindtextdomain ("pwmd", LOCALEDIR
);
2432 textdomain ("pwmd");
2440 if (setup_crypto ())
2441 exit (EXIT_FAILURE
);
2444 gnutls_global_set_mem_functions (xmalloc
, xmalloc
, secure_mem_check
,
2446 gnutls_global_init ();
2447 gnutls_global_set_log_function (tls_log
);
2448 gnutls_global_set_log_level (1);
2452 xmlMemSetup (xfree
, xmalloc
, xrealloc
, str_dup
);
2460 while ((opt
= getopt_long (argc
, argv
, optstring
, longopts
, &optindex
))
2469 convertfile
= optarg
;
2484 rcfile
= str_dup (optarg
);
2487 usage (argv
[0], EXIT_FAILURE
);
2503 case OPT_DEBUG_LEVEL
:
2504 debug_level_opt
= optarg
;
2507 homedir
= str_dup (optarg
);
2512 case OPT_DISABLE_DUMP
:
2519 rcfile
= str_dup (optarg
);
2522 convertfile
= optarg
;
2524 case OPT_PASSPHRASE_FILE
:
2533 case OPT_NO_PASSPHRASE_FILE
:
2534 no_passphrase_file
= 1;
2539 case OPT_SIGN_KEYGRIP
:
2540 sign_keygrip
= optarg
;
2548 case OPT_ITERATIONS
:
2549 iterations
= strtoull (optarg
, NULL
, 10);
2552 s2k_count
= strtoul (optarg
, NULL
, 10);
2554 case OPT_NO_PASSPHRASE
:
2566 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013\n"
2568 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2569 "Compile time features:\n%s"), PACKAGE_STRING
,
2572 "+PWMD_HOMEDIR=" PWMD_HOMEDIR
"\n"
2610 exit (EXIT_SUCCESS
);
2615 homedir
= str_dup(PWMD_HOMEDIR
);
2617 homedir
= str_asprintf ("%s/.pwmd", get_home_dir ());
2620 if (mkdir (homedir
, 0700) == -1 && errno
!= EEXIST
)
2621 err (EXIT_FAILURE
, "%s", homedir
);
2623 snprintf (buf
, sizeof (buf
), "%s/data", homedir
);
2624 if (mkdir (buf
, 0700) == -1 && errno
!= EEXIST
)
2625 err (EXIT_FAILURE
, "%s", buf
);
2627 datadir
= str_dup (buf
);
2628 pthread_mutexattr_t attr
;
2629 pthread_mutexattr_init (&attr
);
2630 pthread_mutexattr_settype (&attr
, PTHREAD_MUTEX_RECURSIVE
);
2631 pthread_mutex_init (&rcfile_mutex
, &attr
);
2632 pthread_cond_init (&rcfile_cond
, NULL
);
2633 pthread_mutex_init (&cn_mutex
, &attr
);
2634 pthread_mutexattr_destroy (&attr
);
2635 pthread_key_create (&last_error_key
, free_key
);
2636 #ifndef HAVE_PTHREAD_CANCEL
2637 pthread_key_create (&signal_thread_key
, free_key
);
2641 rcfile
= str_asprintf ("%s/config", homedir
);
2643 global_config
= config_parse (rcfile
);
2645 exit (EXIT_FAILURE
);
2649 use_agent
= config_get_boolean ("global", "use_agent");
2654 if (debug_level_opt
)
2655 debug_level
= str_split (debug_level_opt
, ",", 0);
2657 x
= config_get_int_param (global_config
, "global", "priority", &exists
);
2658 if (exists
&& x
!= atoi(INVALID_PRIORITY
))
2661 if (setpriority (PRIO_PROCESS
, 0, x
) == -1)
2663 log_write ("setpriority(): %s",
2664 pwmd_strerror (gpg_error_from_syserror ()));
2668 #ifdef HAVE_MLOCKALL
2669 if (disable_mlock
== 0 && mlockall (MCL_CURRENT
| MCL_FUTURE
) == -1)
2671 log_write ("mlockall(): %s",
2672 pwmd_strerror (gpg_error_from_syserror ()));
2677 rc
= cache_init (free_cache_data
);
2680 log_write ("pwmd: ERR %i: %s", rc
,
2681 gpg_err_code (rc
) == GPG_ERR_UNKNOWN_VERSION
2682 ? _("incompatible gpg-agent version: 2.1.0 or later required")
2683 : pwmd_strerror (rc
));
2688 s2k_count
= config_get_ulong (NULL
, "s2k_count");
2693 usage (argv
[0], EXIT_FAILURE
);
2695 estatus
= convert_v2_datafile (convertfile
, cipher
, keyfile
, keygrip
,
2696 sign_keygrip
, no_passphrase
, outfile
,
2697 keyparam
, s2k_count
, iterations
);
2698 config_free (global_config
);
2705 if (!outfile
|| !*outfile
)
2706 usage (argv
[0], EXIT_FAILURE
);
2708 if (outfile
&& outfile
[0] == '-' && outfile
[1] == 0)
2711 estatus
= xml_import (import
, outfile
, keygrip
, sign_keygrip
, keyfile
,
2712 no_passphrase
, cipher
, keyparam
, s2k_count
,
2714 config_free (global_config
);
2719 p
= config_get_string ("global", "socket_path");
2721 p
= str_asprintf ("%s/socket", homedir
);
2723 socketarg
= expand_homedir (p
);
2727 disable_list_and_dump
= config_get_boolean ("global",
2728 "disable_list_and_dump");
2730 disable_list_and_dump
= secure
;
2732 cache_push
= config_get_list ("global", "cache_push");
2734 while (optind
< argc
)
2736 if (strv_printf (&cache_push
, "%s", argv
[optind
++]) == 0)
2737 errx (EXIT_FAILURE
, "%s", pwmd_strerror (GPG_ERR_ENOMEM
));
2740 if (strchr (socketarg
, '/') == NULL
)
2742 socketdir
= getcwd (buf
, sizeof (buf
));
2743 socketname
= str_dup (socketarg
);
2744 socketpath
= str_asprintf ("%s/%s", socketdir
, socketname
);
2748 socketname
= str_dup (strrchr (socketarg
, '/'));
2750 socketarg
[strlen (socketarg
) - strlen (socketname
) - 1] = 0;
2751 socketdir
= str_dup (socketarg
);
2752 socketpath
= str_asprintf ("%s/%s", socketdir
, socketname
);
2755 if (chdir (datadir
))
2757 log_write ("%s: %s", datadir
,
2758 pwmd_strerror (gpg_error_from_syserror ()));
2759 unlink (socketpath
);
2764 * Set the cache entry for a file. Prompts for the password.
2768 struct crypto_s
*crypto
= NULL
;
2769 gpg_error_t rc
= init_client_crypto (&crypto
);
2773 estatus
= EXIT_FAILURE
;
2780 rc
= agent_set_pinentry_options (crypto
->agent
);
2783 estatus
= EXIT_FAILURE
;
2789 for (opt
= 0; cache_push
[opt
]; opt
++)
2791 if (!do_cache_push (cache_push
[opt
], crypto
) && !force
)
2793 strv_free (cache_push
);
2795 estatus
= EXIT_FAILURE
;
2796 cleanup_crypto (&crypto
);
2800 cleanup_crypto_stage1 (crypto
);
2805 (void) kill_scd (crypto
->agent
);
2808 cleanup_crypto (&crypto
);
2809 strv_free (cache_push
);
2810 log_write (!nofork
? _("Done. Daemonizing...") :
2811 _("Done. Waiting for connections..."));
2814 config_clear_keys ();
2817 * bind() doesn't like the full pathname of the socket or any non alphanum
2818 * characters so change to the directory where the socket is wanted then
2819 * create it then change to datadir.
2821 if (chdir (socketdir
))
2823 log_write ("%s: %s", socketdir
,
2824 pwmd_strerror (gpg_error_from_syserror ()));
2830 if ((sockfd
= socket (PF_UNIX
, SOCK_STREAM
, 0)) == -1)
2832 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_syserror ()));
2836 addr
.sun_family
= AF_UNIX
;
2837 snprintf (addr
.sun_path
, sizeof (addr
.sun_path
), "%s", socketname
);
2839 if (bind (sockfd
, (struct sockaddr
*) &addr
, sizeof (struct sockaddr
)) ==
2842 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_syserror ()));
2844 if (errno
== EADDRINUSE
)
2847 log_write (_("Either there is another pwmd running or '%s' is a \n"
2848 "stale socket. Please remove it manually."), socketpath
);
2855 char *t
= config_get_string ("global", "socket_perms");
2861 mode
= strtol (t
, NULL
, 8);
2865 if (chmod (socketname
, mode
) == -1)
2867 log_write ("%s: %s", socketname
,
2868 pwmd_strerror (gpg_error_from_syserror ()));
2878 xfree (--socketname
);
2880 if (chdir (datadir
))
2882 log_write ("%s: %s", datadir
,
2883 pwmd_strerror (gpg_error_from_syserror ()));
2890 if (listen (sockfd
, 0) == -1)
2892 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_syserror ()));
2903 log_write ("fork(): %s",
2904 pwmd_strerror (gpg_error_from_syserror ()));
2913 _exit (EXIT_SUCCESS
);
2917 pthread_key_create (&thread_name_key
, free_key
);
2918 pthread_setspecific (thread_name_key
, str_dup ("main"));
2919 estatus
= server_loop (sockfd
, &socketpath
);
2922 if (socketpath
&& do_unlink
)
2924 unlink (socketpath
);
2930 gnutls_global_deinit ();
2934 #ifdef HAVE_PTHREAD_CANCEL
2935 pthread_cancel (rcfile_tid
);
2937 pthread_kill (rcfile_tid
, SIGUSR2
);
2938 pthread_cond_signal (&rcfile_cond
);
2940 pthread_join (rcfile_tid
, NULL
);
2943 pthread_cond_destroy (&rcfile_cond
);
2944 pthread_mutex_destroy (&rcfile_mutex
);
2945 pthread_key_delete (last_error_key
);
2946 #ifndef HAVE_PTHREAD_CANCEL
2947 pthread_key_delete (signal_thread_key
);
2951 config_free (global_config
);
2954 xfree (home_directory
);
2956 xmlCleanupParser ();
2957 xmlCleanupGlobals ();
2959 if (estatus
== EXIT_SUCCESS
)
2960 log_write (_("pwmd exiting normally"));
2962 pthread_key_delete (thread_name_key
);
2964 #if defined(DEBUG) && !defined(MEM_DEBUG)