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>
62 #ifdef HAVE_GETOPT_LONG
67 #include "getopt_long.h"
70 #ifdef HAVE_PR_SET_NAME
71 #include <sys/prctl.h>
74 #include "pwmd-error.h"
77 #include "util-misc.h"
83 #include "util-string.h"
90 /* In tenths of a second. */
93 /* For (tcp_)accept_thread (usec). */
94 #define ACCEPT_TIMEOUT 30000
101 static pthread_cond_t quit_cond
;
102 static pthread_mutex_t quit_mutex
;
103 static int no_passphrase_file
= 0;
104 static pthread_t keepalive_tid
;
106 #ifndef HAVE_PTHREAD_CANCEL
107 static pthread_key_t signal_thread_key
;
113 static pthread_t tls_tid
;
114 static pthread_t tls6_tid
;
115 static int spawned_tls
;
116 static int spawned_tls6
;
118 static int start_stop_tls (int term
);
121 static int do_cache_push (const char *filename
, struct crypto_s
*crypto
);
122 static int signal_loop (sigset_t sigset
);
124 GCRY_THREAD_OPTION_PTHREAD_IMPL
;
126 #ifndef HAVE_PTHREAD_CANCEL
127 #define INIT_THREAD_SIGNAL do { \
128 struct sigaction act; \
130 sigemptyset (&sigset); \
131 sigaddset (&sigset, SIGUSR2); \
132 pthread_sigmask (SIG_UNBLOCK, &sigset, NULL); \
133 memset (&act, 0, sizeof(act)); \
134 act.sa_flags = SA_SIGINFO; \
135 act.sa_mask = sigset; \
136 act.sa_sigaction = catch_thread_signal; \
137 sigaction (SIGUSR2, &act, NULL); \
141 catch_thread_signal (int sig
, siginfo_t
*info
, void *ctx
)
143 int *n
= (int *) pthread_getspecific (signal_thread_key
);
146 pthread_setspecific (signal_thread_key
, n
);
151 cache_push_from_rcfile ()
153 struct crypto_s
*crypto
= NULL
;
155 gpg_error_t rc
= init_client_crypto (&crypto
);
159 log_write ("%s: %s", __FUNCTION__
, pwmd_strerror (rc
));
166 rc
= set_agent_option (crypto
->agent
, "pinentry-mode", "error");
169 log_write ("%s: %s", __FUNCTION__
, pwmd_strerror (rc
));
175 cache_push
= config_get_list ("global", "cache_push");
180 for (p
= cache_push
; *p
; p
++)
182 (void) do_cache_push (*p
, crypto
);
183 cleanup_crypto_stage1 (crypto
);
186 strv_free (cache_push
);
190 (void) kill_scd (crypto
->agent
);
192 cleanup_crypto (&crypto
);
198 int n
= config_get_boolean ("global", "enable_logging");
202 char *p
= config_get_string ("global", "log_path");
205 logfile
= expand_homedir (p
);
214 log_syslog
= config_get_boolean ("global", "syslog");
216 openlog ("pwmd", LOG_NDELAY
| LOG_PID
, LOG_DAEMON
);
220 reload_rcfile_thread (void *arg
)
222 #ifndef HAVE_PTHREAD_CANCEL
223 int *n
= xmalloc (sizeof (int));
226 pthread_setspecific (signal_thread_key
, n
);
230 #ifdef HAVE_PR_SET_NAME
231 prctl (PR_SET_NAME
, "reload rcfile");
233 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
234 MUTEX_LOCK (&rcfile_mutex
);
235 pthread_cleanup_push (cleanup_mutex_cb
, &rcfile_mutex
);
239 struct slist_s
*config
;
241 int b
= disable_list_and_dump
;
243 int require_save_key
= config_get_bool_param (global_config
, "global",
247 int tcp_require_key
= config_get_bool_param (global_config
, "global",
252 pthread_cond_wait (&rcfile_cond
, &rcfile_mutex
);
253 #ifndef HAVE_PTHREAD_CANCEL
254 int *n
= (int *) pthread_getspecific (signal_thread_key
);
259 users
= config_get_list ("global", "allowed");
260 log_write (_("reloading configuration file '%s'"), rcfile
);
261 config
= config_parse (rcfile
);
264 config_free (global_config
);
265 global_config
= config
;
267 cache_push_from_rcfile ();
268 config_clear_keys ();
271 disable_list_and_dump
= !disable_list_and_dump
? b
: 1;
272 config_set_bool_param (&global_config
, "global", "require_save_key",
273 require_save_key
? "true" : "false");
275 if (config_get_bool_param (global_config
, "global", "tcp_require_key",
279 config_set_bool_param (&global_config
, "global", "tcp_require_key",
280 tcp_require_key
? "true" : "false");
282 char *tmp
= strv_join (",", users
);
283 config_set_list_param (&global_config
, "global", "allowed", tmp
);
287 /* Kill existing listening threads since the configured listening
288 * protocols may have changed. */
294 pthread_cleanup_pop (1);
299 send_error (assuan_context_t ctx
, gpg_error_t e
)
301 struct client_s
*client
= assuan_get_pointer (ctx
);
303 if (gpg_err_source (e
) == GPG_ERR_SOURCE_UNKNOWN
)
310 return assuan_process_done (ctx
, 0);
314 log_write ("ERR %i: %s", e
, pwmd_strerror (e
));
318 if (client
&& gpg_err_code (e
) == GPG_ERR_BAD_DATA
)
320 xmlErrorPtr xe
= client
->xml_error
;
323 xe
= xmlGetLastError ();
326 log_write ("%s", xe
->message
);
327 if (client
->last_error
)
328 xfree (client
->last_error
);
330 client
->last_error
= str_dup (xe
->message
);
333 e
= assuan_process_done (ctx
, assuan_set_error (ctx
, e
,
337 if (xe
== client
->xml_error
)
340 xmlResetLastError ();
342 client
->xml_error
= NULL
;
346 return assuan_process_done (ctx
,
347 assuan_set_error (ctx
, e
, pwmd_strerror (e
)));
351 assuan_log_cb (assuan_context_t ctx
, void *data
, unsigned cat
,
354 static pthread_mutex_t m
= PTHREAD_MUTEX_INITIALIZER
;
358 pthread_mutex_lock (&m
);
359 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock
, &m
);
360 t
= strv_length (debug_level
);
362 for (i
= 0; i
< t
; i
++)
364 if (!strcasecmp (debug_level
[i
], (char *) "init")
365 && cat
== ASSUAN_LOG_INIT
)
371 if (!strcasecmp (debug_level
[i
], (char *) "ctx")
372 && cat
== ASSUAN_LOG_CTX
)
378 if (!strcasecmp (debug_level
[i
], (char *) "engine")
379 && cat
== ASSUAN_LOG_ENGINE
)
385 if (!strcasecmp (debug_level
[i
], (char *) "data")
386 && cat
== ASSUAN_LOG_DATA
)
392 if (!strcasecmp (debug_level
[i
], (char *) "sysio")
393 && cat
== ASSUAN_LOG_SYSIO
)
399 if (!strcasecmp (debug_level
[i
], (char *) "control")
400 && cat
== ASSUAN_LOG_CONTROL
)
414 open (logfile
, O_WRONLY
| O_CREAT
| O_APPEND
, 0600)) == -1)
415 warn ("%s", logfile
);
418 pthread_cleanup_push (cleanup_fd_cb
, &fd
);
419 write (fd
, msg
, strlen (msg
));
420 pthread_cleanup_pop (1);
426 fprintf (stderr
, "%s%s", data
? (char *) data
: "", msg
);
431 pthread_cleanup_pop (1);
436 log_write (const char *fmt
, ...)
446 pthread_t tid
= pthread_self ();
447 static pthread_mutex_t m
= PTHREAD_MUTEX_INITIALIZER
;
449 if ((!logfile
&& !isatty (STDERR_FILENO
) && !log_syslog
) || !fmt
)
452 pthread_mutex_lock (&m
);
453 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock
, &m
);
454 pthread_cleanup_push (cleanup_fd_cb
, &fd
);
456 if (!cmdline
&& logfile
)
458 if ((fd
= open (logfile
, O_WRONLY
| O_CREAT
| O_APPEND
, 0600)) == -1)
459 warn ("%s", logfile
);
464 if (str_vasprintf (&args
, fmt
, ap
) != -1)
468 pthread_cleanup_push (xfree
, args
);
469 fprintf (stderr
, "%s\n", args
);
471 pthread_cleanup_pop (1);
475 pthread_cleanup_push (xfree
, args
);
476 name
= pthread_getspecific (thread_name_key
);
477 snprintf (buf
, sizeof (buf
), "%s(%p): ", name
? name
: _("unknown"),
481 if (!cmdline
&& log_syslog
&& !nofork
)
482 syslog (LOG_INFO
, "%s%s", name
, args
);
485 tm
= localtime (&now
);
486 strftime (tbuf
, sizeof (tbuf
), "%b %d %Y %H:%M:%S ", tm
);
487 tbuf
[sizeof (tbuf
) - 1] = 0;
489 if (args
[strlen (args
) - 1] == '\n')
490 args
[strlen (args
) - 1] = 0;
492 line
= str_asprintf ("%s %i %s%s\n", tbuf
, getpid (), name
, args
);
493 pthread_cleanup_pop (1);
496 pthread_cleanup_push (xfree
, line
);
497 if (logfile
&& fd
!= -1)
499 write (fd
, line
, strlen (line
));
505 fprintf (stdout
, "%s", line
);
509 pthread_cleanup_pop (1);
515 pthread_cleanup_pop (1);
516 pthread_cleanup_pop (0);
517 pthread_mutex_unlock (&m
);
522 secure_mem_check (const void *arg
)
531 gcry_control (GCRYCTL_SET_THREAD_CBS
, &gcry_threads_pthread
);
533 if (!gcry_check_version (GCRYPT_VERSION
))
535 fprintf (stderr
, _("gcry_check_version(): Incompatible libgcrypt. "
536 "Wanted %s, got %s.\n"), GCRYPT_VERSION
,
537 gcry_check_version (NULL
));
538 return GPG_ERR_UNKNOWN_VERSION
;
541 gcry_set_allocation_handler (xmalloc
, xmalloc
, NULL
, xrealloc
, xfree
);
545 #ifdef HAVE_GETGRNAM_R
547 do_validate_peer (struct client_s
*cl
, assuan_peercred_t
* peer
)
553 rc
= assuan_get_peercred (cl
->ctx
, peer
);
557 users
= config_get_list ("global", "allowed");
560 for (char **p
= users
; *p
; p
++)
562 struct passwd pw
, *result
;
563 struct group gr
, *gresult
;
568 size_t len
= sysconf (_SC_GETGR_R_SIZE_MAX
);
577 return GPG_ERR_ENOMEM
;
580 if (!getgrnam_r (*(p
) + 1, &gr
, buf
, len
, &gresult
) && gresult
)
582 if (gresult
->gr_gid
== (*peer
)->gid
)
589 len
= sysconf (_SC_GETPW_R_SIZE_MAX
);
593 char *tbuf
= xmalloc (len
);
594 for (char **t
= gresult
->gr_mem
; *t
; t
++)
596 if (!getpwnam_r (*t
, &pw
, tbuf
, len
, &result
) && result
)
598 if (result
->pw_uid
== (*peer
)->uid
)
615 size_t len
= sysconf (_SC_GETPW_R_SIZE_MAX
);
625 return GPG_ERR_ENOMEM
;
628 if (!getpwnam_r (*p
, &pw
, buf
, len
, &result
) && result
)
630 if (result
->pw_uid
== (*peer
)->uid
)
645 return allowed
? 0 : GPG_ERR_INV_USER_ID
;
649 do_validate_peer (struct client_s
*cl
, assuan_peercred_t
* peer
)
655 rc
= assuan_get_peercred (cl
->ctx
, peer
);
659 users
= config_get_list ("global", "allowed");
662 for (char **p
= users
; *p
; p
++)
664 struct passwd
*result
;
665 struct group
*gresult
;
669 gresult
= getgrnam (*(p
) + 1);
670 if (gresult
&& gresult
->gr_gid
== (*peer
)->gid
)
676 for (char **t
= gresult
->gr_mem
; *t
; t
++)
678 result
= getpwnam (*t
);
679 if (result
&& result
->pw_uid
== (*peer
)->uid
)
688 result
= getpwnam (*p
);
689 if (result
&& result
->pw_uid
== (*peer
)->uid
)
703 return allowed
? 0 : GPG_ERR_INV_USER_ID
;
708 validate_peer (struct client_s
*cl
)
711 assuan_peercred_t peer
;
715 return tls_validate_access (cl
, NULL
);
718 rc
= do_validate_peer (cl
, &peer
);
719 if (!rc
|| gpg_err_code (rc
) == GPG_ERR_INV_USER_ID
)
720 log_write ("peer %s: uid=%i, gid=%i, pid=%i",
721 !rc
? _("accepted") : _("rejected"), peer
->uid
, peer
->gid
,
724 log_write ("%s: %s", __FUNCTION__
, pwmd_strerror (rc
));
730 xml_error_cb (void *data
, xmlErrorPtr e
)
732 struct client_s
*client
= data
;
735 * Keep the first reported error as the one to show in the error
736 * description. Reset in send_error().
738 if (client
->xml_error
)
741 xmlCopyError (e
, client
->xml_error
);
745 hook_waitpid (assuan_context_t ctx
, pid_t pid
, int action
,
746 int *status
, int options
)
748 return waitpid (pid
, status
, options
);
752 hook_read (assuan_context_t ctx
, assuan_fd_t fd
, void *data
, size_t len
)
755 struct client_s
*client
= assuan_get_pointer (ctx
);
757 if (client
->thd
->remote
)
758 return tls_read_hook (ctx
, (int) fd
, data
, len
);
761 return read ((int) fd
, data
, len
);
765 hook_write (assuan_context_t ctx
, assuan_fd_t fd
,
766 const void *data
, size_t len
)
769 struct client_s
*client
= assuan_get_pointer (ctx
);
771 if (client
->thd
->remote
)
772 return tls_write_hook (ctx
, (int) fd
, data
, len
);
775 return write ((int) fd
, data
, len
);
779 new_connection (struct client_s
*cl
)
782 static struct assuan_malloc_hooks mhooks
= { xmalloc
, xrealloc
, xfree
};
783 static struct assuan_system_hooks shooks
= {
784 ASSUAN_SYSTEM_HOOKS_VERSION
,
792 NULL
, //sendmsg both are used for FD passing
803 char *prio
= config_get_string ("global", "tls_cipher_suite");
805 cl
->thd
->tls
= tls_init (cl
->thd
->fd
, cl
->thd
->timeout
, prio
);
812 rc
= assuan_new_ext (&cl
->ctx
, GPG_ERR_SOURCE_DEFAULT
, &mhooks
,
813 debug_level
? assuan_log_cb
: NULL
, NULL
);
817 assuan_ctx_set_system_hooks (cl
->ctx
, &shooks
);
818 rc
= assuan_init_socket_server (cl
->ctx
, cl
->thd
->fd
, 2);
822 assuan_set_pointer (cl
->ctx
, cl
);
823 assuan_set_hello_line (cl
->ctx
, PACKAGE_STRING
);
824 rc
= register_commands (cl
->ctx
);
831 cl
->thd
->timeout
= config_get_integer ("global", "tls_timeout");
832 fcntl (cl
->thd
->fd
, F_SETFL
, O_NONBLOCK
);
836 rc
= assuan_accept (cl
->ctx
);
840 rc
= validate_peer (cl
);
841 /* May not be implemented on all platforms. */
842 if (rc
&& gpg_err_code (rc
) != GPG_ERR_ASS_GENERAL
)
845 rc
= init_client_crypto (&cl
->crypto
);
851 cl
->crypto
->agent
->client_ctx
= cl
->ctx
;
854 cl
->crypto
->client_ctx
= cl
->ctx
;
855 xmlSetStructuredErrorFunc (cl
, xml_error_cb
);
859 log_write ("%s", pwmd_strerror (rc
));
864 * This is called after a client_thread() terminates. Set with
865 * pthread_cleanup_push().
868 cleanup_cb (void *arg
)
870 struct client_thread_s
*cn
= arg
;
871 struct client_s
*cl
= cn
->cl
;
873 MUTEX_LOCK (&cn_mutex
);
874 cn_thread_list
= slist_remove (cn_thread_list
, cn
);
875 MUTEX_UNLOCK (&cn_mutex
);
884 gnutls_deinit (cn
->tls
->ses
);
890 if (!cn
->atfork
&& cl
->ctx
)
891 assuan_release (cl
->ctx
);
892 else if (!cn
->atfork
&& cl
->thd
&& cl
->thd
->fd
!= -1)
896 cleanup_crypto (&cl
->crypto
);
898 pinentry_free_opts (&cl
->pinentry_opts
);
907 while (cn
->msg_queue
)
909 struct status_msg_s
*msg
= cn
->msg_queue
;
911 cn
->msg_queue
= msg
->next
;
916 if (!cn
->atfork
&& cn
->status_msg_pipe
[0] != -1)
917 close (cn
->status_msg_pipe
[0]);
919 if (!cn
->atfork
&& cn
->status_msg_pipe
[1] != -1)
920 close (cn
->status_msg_pipe
[1]);
922 pthread_mutex_destroy (&cn
->status_mutex
);
926 log_write (_("exiting, fd=%i"), cn
->fd
);
927 send_status_all (STATUS_CLIENTS
, NULL
);
931 pthread_cond_signal (&quit_cond
);
935 cleanup_all_clients (int atfork
)
937 /* This function may be called from pthread_atfork() which requires
941 pthread_mutexattr_t attr
;
943 pthread_mutexattr_init (&attr
);
944 pthread_mutexattr_settype (&attr
, PTHREAD_MUTEX_RECURSIVE
);
945 pthread_mutex_init (&cn_mutex
, &attr
);
946 pthread_mutexattr_destroy (&attr
);
950 MUTEX_LOCK (&cn_mutex
);
952 while (slist_length (cn_thread_list
))
954 struct client_thread_s
*thd
= slist_nth_data (cn_thread_list
, 0);
956 thd
->atfork
= atfork
;
961 cache_deinit (atfork
);
962 MUTEX_UNLOCK (&cn_mutex
);
966 send_msg_queue (struct client_thread_s
*thd
)
968 MUTEX_LOCK (&thd
->status_mutex
);
972 read (thd
->status_msg_pipe
[0], &c
, 1);
974 while (thd
->msg_queue
)
976 struct status_msg_s
*msg
= thd
->msg_queue
;
978 thd
->msg_queue
= thd
->msg_queue
->next
;
979 MUTEX_UNLOCK (&thd
->status_mutex
);
980 rc
= send_status (thd
->cl
->ctx
, msg
->s
, msg
->line
);
981 MUTEX_LOCK (&thd
->status_mutex
);
989 MUTEX_UNLOCK (&thd
->status_mutex
);
990 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
991 log_write ("%s: %s", __FUNCTION__
, pwmd_strerror (rc
));
997 client_thread (void *data
)
999 struct client_thread_s
*thd
= data
;
1000 struct client_s
*cl
= xcalloc (1, sizeof (struct client_s
));
1002 #ifdef HAVE_PR_SET_NAME
1003 prctl (PR_SET_NAME
, "client");
1005 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1009 log_write ("%s(%i): %s", __FILE__
, __LINE__
,
1010 pwmd_strerror (GPG_ERR_ENOMEM
));
1014 MUTEX_LOCK (&cn_mutex
);
1015 pthread_cleanup_push (cleanup_cb
, thd
);
1018 MUTEX_UNLOCK (&cn_mutex
);
1020 if (new_connection (cl
))
1025 send_status_all (STATUS_CLIENTS
, NULL
);
1026 rc
= send_status (cl
->ctx
, STATUS_CACHE
, NULL
);
1029 log_write ("%s(%i): %s", __FILE__
, __LINE__
, pwmd_strerror (rc
));
1040 FD_SET (thd
->fd
, &rfds
);
1041 FD_SET (thd
->status_msg_pipe
[0], &rfds
);
1042 n
= thd
->fd
> thd
->status_msg_pipe
[0]
1043 ? thd
->fd
: thd
->status_msg_pipe
[0];
1045 n
= select (n
+ 1, &rfds
, NULL
, NULL
, NULL
);
1048 log_write ("%s", strerror (errno
));
1052 if (FD_ISSET (thd
->status_msg_pipe
[0], &rfds
))
1054 rc
= send_msg_queue (thd
);
1055 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1059 if (!FD_ISSET (thd
->fd
, &rfds
))
1062 rc
= assuan_process_next (cl
->ctx
, &eof
);
1065 if (gpg_err_code (rc
) == GPG_ERR_EOF
|| eof
)
1068 log_write ("assuan_process_next(): rc=%i %s", rc
,
1069 pwmd_strerror (rc
));
1070 if (rc
== gpg_error (GPG_ERR_ETIMEDOUT
))
1073 rc
= send_error (cl
->ctx
, rc
);
1076 log_write ("assuan_process_done(): rc=%i %s", rc
,
1077 pwmd_strerror (rc
));
1082 /* Since the msg queue pipe fd's are non-blocking, check for
1083 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1084 * client has already disconnected and will be converted to
1085 * GPG_ERR_EOF during assuan_process_next().
1087 rc
= send_msg_queue (thd
);
1088 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1093 pthread_cleanup_pop (1);
1098 xml_import (const char *filename
, const char *outfile
,
1099 const char *keygrip
, const char *sign_keygrip
,
1100 const char *keyfile
, int no_passphrase
, const char *cipher
,
1101 const char *params
, unsigned long s2k_count
, uint64_t iterations
)
1110 struct crypto_s
*crypto
= NULL
;
1113 int algo
= cipher
? cipher_string_to_gcrypt ((char *) cipher
) :
1118 log_write ("ERR %i: %s", gpg_error (GPG_ERR_CIPHER_ALGO
),
1119 pwmd_strerror (GPG_ERR_CIPHER_ALGO
));
1123 if (stat (filename
, &st
) == -1)
1125 log_write ("%s: %s", filename
,
1126 pwmd_strerror (gpg_error_from_errno (errno
)));
1130 rc
= init_client_crypto (&crypto
);
1134 memcpy (&crypto
->save
.hdr
, &crypto
->hdr
, sizeof (file_header_t
));
1135 crypto
->save
.hdr
.flags
= set_cipher_flag (crypto
->save
.hdr
.flags
, algo
);
1136 log_write (_("Importing XML from '%s'. Output will be written to '%s' ..."),
1139 if ((fd
= open (filename
, O_RDONLY
)) == -1)
1141 log_write ("%s: %s", filename
,
1142 pwmd_strerror (gpg_error_from_errno (errno
)));
1146 if ((xmlbuf
= xmalloc (st
.st_size
+ 1)) == NULL
)
1149 log_write ("%s(%i): %s", __FILE__
, __LINE__
,
1150 pwmd_strerror (GPG_ERR_ENOMEM
));
1154 if (read (fd
, xmlbuf
, st
.st_size
) == -1)
1156 rc
= gpg_error_from_errno (errno
);
1158 log_write ("%s: %s", filename
, pwmd_strerror (rc
));
1163 xmlbuf
[st
.st_size
] = 0;
1165 * Make sure the document validates.
1167 if ((doc
= xmlReadDoc (xmlbuf
, NULL
, "UTF-8", XML_PARSE_NOBLANKS
)) == NULL
)
1169 log_write ("xmlReadDoc() failed");
1175 xmlNodePtr n
= xmlDocGetRootElement (doc
);
1176 if (n
&& !xmlStrEqual (n
->name
, (xmlChar
*) "pwmd"))
1178 log_write (_("Could not find root \"pwmd\" element."));
1179 rc
= GPG_ERR_BAD_DATA
;
1183 rc
= validate_import (n
? n
->children
: n
);
1187 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
1192 xmlDocDumpMemory (doc
, &xml
, &len
);
1194 crypto
->save
.s2k_count
= s2k_count
;
1195 crypto
->save
.hdr
.iterations
= iterations
;
1198 rc
= export_common (NULL
, 0, crypto
, xml
, len
, outfile
, keyfile
, &key
,
1201 log_write (_("Success!"));
1206 rc
= agent_set_pinentry_options (crypto
->agent
);
1208 rc
= agent_export_common (crypto
, keygrip
, sign_keygrip
, no_passphrase
,
1209 xml
, len
, outfile
, params
, keyfile
);
1217 send_error (NULL
, rc
);
1221 cleanup_crypto (&crypto
);
1225 cleanup_crypto (&crypto
);
1230 do_cache_push (const char *filename
, struct crypto_s
*crypto
)
1232 unsigned char md5file
[16];
1237 struct cache_data_s
*cdata
;
1241 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1244 if (valid_filename (filename
) == 0)
1246 log_write (_("%s: Invalid characters in filename"), filename
);
1250 rc
= decrypt_common (NULL
, 0, crypto
, filename
, &key
, &keylen
);
1254 doc
= parse_doc ((char *) crypto
->plaintext
, crypto
->plaintext_len
);
1257 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM
));
1262 gcry_md_hash_buffer (GCRY_MD_MD5
, md5file
, filename
, strlen (filename
));
1263 cdata
= xcalloc (1, sizeof (struct cache_data_s
));
1267 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM
));
1272 rc
= get_checksum (filename
, &crc
, &len
);
1275 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
1277 free_cache_data_once (cdata
);
1283 rc
= encrypt_xml (NULL
, cache_key
, cache_keysize
, GCRY_CIPHER_AES
,
1284 crypto
->plaintext
, crypto
->plaintext_len
, &cdata
->doc
,
1285 &cdata
->doclen
, &cache_iv
, &cache_blocksize
, 0);
1286 if (!rc
&& !IS_PKI (crypto
))
1289 cdata
->keylen
= keylen
;
1296 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
1298 free_cache_data_once (cdata
);
1303 if (use_agent
&& IS_PKI (crypto
))
1305 gcry_sexp_build ((gcry_sexp_t
*) & cdata
->pubkey
, NULL
, "%S",
1307 gcry_sexp_build ((gcry_sexp_t
*) & cdata
->sigkey
, NULL
, "%S",
1308 crypto
->sigpkey_sexp
);
1312 int timeout
= config_get_integer (filename
, "cache_timeout");
1313 cache_add_file (md5file
, crypto
->grip
, cdata
, timeout
);
1314 log_write (_("Successfully added '%s' to the cache."), filename
);
1319 init_client (int fd
, const char *addr
)
1322 struct client_thread_s
*new = xcalloc (1, sizeof (struct client_thread_s
));
1327 return GPG_ERR_ENOMEM
;
1330 MUTEX_LOCK (&cn_mutex
);
1331 pthread_cleanup_push (cleanup_mutex_cb
, &cn_mutex
);
1333 if (pipe (new->status_msg_pipe
) == -1)
1334 rc
= gpg_error_from_errno (errno
);
1338 fcntl (new->status_msg_pipe
[0], F_SETFL
, O_NONBLOCK
);
1339 fcntl (new->status_msg_pipe
[1], F_SETFL
, O_NONBLOCK
);
1340 pthread_mutex_init (&new->status_mutex
, NULL
);
1346 new->remote
= addr
? 1 : 0;
1349 rc
= create_thread (client_thread
, new, &new->tid
, 1);
1352 close (new->status_msg_pipe
[0]);
1353 close (new->status_msg_pipe
[1]);
1354 pthread_mutex_destroy (&new->status_mutex
);
1360 struct slist_s
*list
= slist_append (cn_thread_list
, new);
1364 cn_thread_list
= list
;
1366 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1367 (pthread_t
*) new->tid
, fd
, addr
);
1369 log_write (_("new connection: tid=%p, fd=%i"),
1370 (pthread_t
*) new->tid
, fd
);
1373 rc
= GPG_ERR_ENOMEM
;
1376 pthread_cleanup_pop (1);
1382 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1383 pwmd_strerror (rc
));
1389 keepalive_thread (void *arg
)
1391 #ifndef HAVE_PTHREAD_CANCEL
1392 int *n
= xmalloc (sizeof (int));
1395 pthread_setspecific (signal_thread_key
, n
);
1399 #ifdef HAVE_PR_SET_NAME
1400 prctl (PR_SET_NAME
, "keepalive");
1402 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1406 int n
= config_get_integer ("global", "keepalive_interval");
1407 struct timeval tv
= { n
, 0 };
1408 #ifndef HAVE_PTHREAD_CANCEL
1411 sigusr2
= (int *) pthread_getspecific (signal_thread_key
);
1416 send_status_all (STATUS_KEEPALIVE
, NULL
);
1417 select (0, NULL
, NULL
, NULL
, &tv
);
1424 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1426 get_in_addr (struct sockaddr
*sa
)
1428 if (sa
->sa_family
== AF_INET
)
1429 return &(((struct sockaddr_in
*) sa
)->sin_addr
);
1431 return &(((struct sockaddr_in6
*) sa
)->sin6_addr
);
1435 tcp_accept_thread (void *arg
)
1437 int sockfd
= *(int *) arg
;
1438 #ifndef HAVE_PTHREAD_CANCEL
1439 int *n
= xmalloc (sizeof (int));
1442 pthread_setspecific (signal_thread_key
, n
);
1444 fcntl (sockfd
, F_SETFL
, O_NONBLOCK
);
1447 #ifdef HAVE_PR_SET_NAME
1448 prctl (PR_SET_NAME
, "tcp_accept");
1450 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1454 struct sockaddr_storage raddr
;
1455 socklen_t slen
= sizeof (raddr
);
1458 char s
[INET6_ADDRSTRLEN
];
1459 struct timeval tv
= { 0, ACCEPT_TIMEOUT
};
1460 #ifndef HAVE_PTHREAD_CANCEL
1463 sigusr2
= (int *) pthread_getspecific (signal_thread_key
);
1468 fd
= accept (sockfd
, (struct sockaddr
*) &raddr
, &slen
);
1471 if (errno
== EMFILE
|| errno
== ENFILE
)
1472 log_write ("accept(): %s",
1473 pwmd_strerror (gpg_error_from_errno (errno
)));
1474 else if (errno
!= EAGAIN
)
1476 if (!quit
) // probably EBADF
1477 log_write ("accept(): %s", strerror (errno
));
1482 #ifndef HAVE_PTHREAD_CANCEL
1483 select (0, NULL
, NULL
, NULL
, &tv
);
1491 inet_ntop (raddr
.ss_family
, get_in_addr ((struct sockaddr
*) &raddr
),
1493 (void) init_client (fd
, s
);
1494 n
= config_get_integer ("global", "tcp_wait");
1497 tv
.tv_sec
= (n
* 100000) / 100000;
1498 tv
.tv_usec
= (n
* 100000) % 100000;
1499 select (0, NULL
, NULL
, NULL
, &tv
);
1507 start_stop_tls_with_protocol (int ipv6
, int term
)
1509 struct addrinfo hints
, *servinfo
, *p
;
1510 int port
= config_get_integer ("global", "tcp_port");
1514 int *fd
= ipv6
? &tls6_fd
: &tls_fd
;
1516 if (term
|| config_get_boolean ("global", "enable_tcp") == 0)
1522 #ifdef HAVE_PTHREAD_CANCEL
1523 pthread_cancel (tls6_tid
);
1525 pthread_kill (tls6_tid
, SIGUSR2
);
1527 pthread_join (tls6_tid
, NULL
);
1530 shutdown (tls6_fd
, SHUT_RDWR
);
1540 #ifdef HAVE_PTHREAD_CANCEL
1541 pthread_cancel (tls_tid
);
1543 pthread_kill (tls_tid
, SIGUSR2
);
1545 pthread_join (tls_tid
, NULL
);
1548 shutdown (tls_fd
, SHUT_RDWR
);
1554 /* A client may still be connected. */
1555 if (!quit
&& x509_cred
!= NULL
)
1556 tls_deinit_params ();
1561 if ((ipv6
&& tls6_fd
!= -1) || (!ipv6
&& tls_fd
!= -1))
1564 memset (&hints
, 0, sizeof (hints
));
1565 hints
.ai_family
= ipv6
? AF_INET6
: AF_INET
;
1566 hints
.ai_socktype
= SOCK_STREAM
;
1567 hints
.ai_flags
= AI_PASSIVE
;
1568 snprintf (buf
, sizeof (buf
), "%i", port
);
1570 if ((n
= getaddrinfo (NULL
, buf
, &hints
, &servinfo
)) == -1)
1572 log_write ("getaddrinfo(): %s", gai_strerror (n
));
1576 for (n
= 0, p
= servinfo
; p
!= NULL
; p
= p
->ai_next
)
1580 if ((ipv6
&& p
->ai_family
!= AF_INET6
)
1581 || (!ipv6
&& p
->ai_family
!= AF_INET
))
1584 if ((*fd
= socket (p
->ai_family
, p
->ai_socktype
, p
->ai_protocol
)) == -1)
1586 log_write ("socket(): %s", strerror (errno
));
1590 if (setsockopt (*fd
, SOL_SOCKET
, SO_REUSEADDR
, &r
, sizeof (int)) == -1)
1592 log_write ("setsockopt(): %s",
1593 pwmd_strerror (gpg_error_from_errno (errno
)));
1594 freeaddrinfo (servinfo
);
1598 if (bind (*fd
, p
->ai_addr
, p
->ai_addrlen
) == -1)
1601 log_write ("bind(): %s",
1602 pwmd_strerror (gpg_error_from_errno (errno
)));
1610 freeaddrinfo (servinfo
);
1615 #if HAVE_DECL_SO_BINDTODEVICE != 0
1616 char *tmp
= config_get_string ("global", "tcp_interface");
1617 if (tmp
&& setsockopt (*fd
, SOL_SOCKET
, SO_BINDTODEVICE
, tmp
,
1618 strlen (tmp
)) == -1)
1620 log_write ("setsockopt(): %s",
1621 pwmd_strerror (gpg_error_from_errno (errno
)));
1629 if (x509_cred
== NULL
)
1631 rc
= tls_init_params ();
1636 if (listen (*fd
, 0) == -1)
1638 log_write ("listen(): %s", strerror (errno
));
1643 rc
= create_thread (tcp_accept_thread
, fd
, &tls6_tid
, 0);
1645 rc
= create_thread (tcp_accept_thread
, fd
, &tls_tid
, 0);
1649 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1650 pwmd_strerror (rc
));
1662 start_stop_tls_with_protocol (0, 1);
1675 start_stop_tls (int term
)
1677 char *s
= config_get_string ("global", "tcp_bind");
1683 if (!strcmp (s
, "any"))
1685 b
= start_stop_tls_with_protocol (0, term
);
1687 b
= start_stop_tls_with_protocol (1, term
);
1689 else if (!strcmp (s
, "ipv4"))
1690 b
= start_stop_tls_with_protocol (0, term
);
1691 else if (!strcmp (s
, "ipv6"))
1692 b
= start_stop_tls_with_protocol (1, term
);
1702 accept_thread (void *arg
)
1704 int sockfd
= *(int *) arg
;
1705 #ifndef HAVE_PTHREAD_CANCEL
1706 int *n
= xmalloc (sizeof (int));
1709 pthread_setspecific (signal_thread_key
, n
);
1711 fcntl (sockfd
, F_SETFL
, O_NONBLOCK
);
1714 #ifdef HAVE_PR_SET_NAME
1715 prctl (PR_SET_NAME
, "accept");
1717 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1721 socklen_t slen
= sizeof (struct sockaddr_un
);
1722 struct sockaddr_un raddr
;
1724 #ifndef HAVE_PTHREAD_CANCEL
1725 struct timeval tv
= { 0, ACCEPT_TIMEOUT
};
1726 int *sigusr2
= (int *) pthread_getspecific (signal_thread_key
);
1732 fd
= accept (sockfd
, (struct sockaddr
*) &raddr
, &slen
);
1735 if (errno
== EMFILE
|| errno
== ENFILE
)
1736 log_write ("accept(): %s",
1737 pwmd_strerror (gpg_error_from_errno (errno
)));
1738 else if (errno
!= EAGAIN
)
1740 if (!quit
) // probably EBADF
1741 log_write ("accept(): %s",
1742 pwmd_strerror (gpg_error_from_errno (errno
)));
1747 #ifndef HAVE_PTHREAD_CANCEL
1748 select (0, NULL
, NULL
, NULL
, &tv
);
1753 (void) init_client (fd
, NULL
);
1756 /* Just in case accept() failed for some reason other than EBADF */
1762 cache_timer_thread (void *arg
)
1764 #ifndef HAVE_PTHREAD_CANCEL
1765 int *n
= xmalloc (sizeof (int));
1768 pthread_setspecific (signal_thread_key
, n
);
1772 #ifdef HAVE_PR_SET_NAME
1773 prctl (PR_SET_NAME
, "cache timer");
1775 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1779 struct timeval tv
= { 1, 0 };
1780 #ifndef HAVE_PTHREAD_CANCEL
1783 n
= (int *) pthread_getspecific (signal_thread_key
);
1788 select (0, NULL
, NULL
, NULL
, &tv
);
1789 cache_adjust_timeout ();
1796 catch_sigabrt (int sig
)
1805 signal_loop (sigset_t sigset
)
1814 sigwait (&sigset
, &sig
);
1817 log_write (_("caught signal %i (%s)"), sig
, strsignal (sig
));
1822 pthread_cond_signal (&rcfile_cond
);
1825 // not really handled here.
1826 catch_sigabrt (SIGABRT
);
1829 log_write (_("clearing file cache"));
1831 send_status_all (STATUS_CACHE
, NULL
);
1850 log_write ("Caught SIGSEGV. Exiting.");
1851 #ifdef HAVE_BACKTRACE
1852 BACKTRACE (__FUNCTION__
);
1858 waiting_for_exit (void *arg
)
1861 #ifndef HAVE_PTHREAD_CANCEL
1862 int *n
= xmalloc (sizeof (int));
1865 pthread_setspecific (signal_thread_key
, n
);
1869 #ifdef HAVE_PR_SET_NAME
1870 prctl (PR_SET_NAME
, "exiting");
1872 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1873 log_write (_("waiting for all clients to disconnect"));
1874 MUTEX_LOCK (&quit_mutex
);
1875 pthread_cleanup_push (cleanup_mutex_cb
, &quit_mutex
);
1882 MUTEX_LOCK (&cn_mutex
);
1883 n
= slist_length (cn_thread_list
);
1884 MUTEX_UNLOCK (&cn_mutex
);
1888 #ifndef HAVE_PTHREAD_CANCEL
1889 int *s
= (int *) pthread_getspecific (signal_thread_key
);
1896 log_write (_("%i clients remain"), n
);
1900 INIT_TIMESPEC (SIG_TIMEOUT
, ts
);
1901 pthread_cond_timedwait (&quit_cond
, &quit_mutex
, &ts
);
1904 kill (getpid (), SIGQUIT
);
1905 pthread_cleanup_pop (1);
1910 server_loop (int sockfd
, char **socketpath
)
1912 pthread_t accept_tid
;
1913 pthread_t cache_timeout_tid
;
1914 int cancel_timeout_thread
= 0, cancel_accept_thread
= 0;
1915 int cancel_keepalive_thread
= 0;
1922 sigemptyset (&sigset
);
1925 sigaddset (&sigset
, SIGTERM
);
1926 sigaddset (&sigset
, SIGINT
);
1928 /* Clears the file cache. */
1929 sigaddset (&sigset
, SIGUSR1
);
1931 /* Configuration file reloading. */
1932 sigaddset (&sigset
, SIGHUP
);
1934 /* For exiting cleanly. */
1935 sigaddset (&sigset
, SIGQUIT
);
1937 #ifndef HAVE_PTHREAD_CANCEL
1939 The socket, cache and rcfile threads use this signal when
1940 pthread_cancel() is unavailable. Prevent the main thread from
1941 catching this signal from another process.
1943 sigaddset (&sigset
, SIGUSR2
);
1946 /* Clears the cache and exits when something bad happens. */
1947 signal (SIGABRT
, catch_sigabrt
);
1948 sigaddset (&sigset
, SIGABRT
);
1949 sigprocmask (SIG_BLOCK
, &sigset
, NULL
);
1951 #ifndef HAVE_PTHREAD_CANCEL
1952 /* Remove this signal from the watched signals in signal_loop(). */
1953 sigdelset (&sigset
, SIGUSR2
);
1956 /* Ignored everywhere. When a client disconnects abnormally this signal
1957 * gets raised. It isn't needed though because client_thread() will check
1958 * for rcs even after the client disconnects. */
1959 signal (SIGPIPE
, SIG_IGN
);
1961 /* Can show a backtrace of the stack in the log. */
1962 signal (SIGSEGV
, catchsig
);
1965 /* Needs to be done after the fork(). */
1966 if (!start_stop_tls (0))
1973 pthread_mutex_init (&quit_mutex
, NULL
);
1974 pthread_cond_init (&quit_cond
, NULL
);
1975 log_write (_("%s started for user %s"), PACKAGE_STRING
, get_username ());
1978 if (config_get_boolean ("global", "enable_tcp"))
1979 log_write (_("Listening on %s and TCP port %i"), *socketpath
,
1980 config_get_integer ("global", "tcp_port"));
1982 log_write (_("Listening on %s"), *socketpath
);
1984 log_write (_("Listening on %s"), *socketpath
);
1987 rc
= create_thread (keepalive_thread
, NULL
, &keepalive_tid
, 0);
1990 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1991 pwmd_strerror (rc
));
1995 cancel_keepalive_thread
= 1;
1996 rc
= create_thread (reload_rcfile_thread
, NULL
, &rcfile_tid
, 0);
1999 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2000 pwmd_strerror (rc
));
2004 rc
= create_thread (cache_timer_thread
, NULL
, &cache_timeout_tid
, 0);
2007 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2008 pwmd_strerror (rc
));
2012 cancel_timeout_thread
= 1;
2013 rc
= create_thread (accept_thread
, &sockfd
, &accept_tid
, 0);
2016 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2017 pwmd_strerror (rc
));
2021 cancel_accept_thread
= 1;
2023 signal_loop (sigset
);
2029 * We're out of the main server loop. This happens when a signal was sent
2030 * to terminate the daemon. We'll wait for all clients to disconnect
2031 * before exiting but exit immediately if another termination signal is
2034 if (cancel_accept_thread
)
2036 #ifdef HAVE_PTHREAD_CANCEL
2037 int n
= pthread_cancel (accept_tid
);
2039 int n
= pthread_kill (accept_tid
, SIGUSR2
);
2042 pthread_join (accept_tid
, NULL
);
2048 shutdown (sockfd
, SHUT_RDWR
);
2050 unlink (*socketpath
);
2051 xfree (*socketpath
);
2053 MUTEX_LOCK (&cn_mutex
);
2054 n
= slist_length (cn_thread_list
);
2055 MUTEX_UNLOCK (&cn_mutex
);
2061 rc
= create_thread (waiting_for_exit
, NULL
, &tid
, 0);
2064 if (signal_loop (sigset
))
2066 log_write (_("Received second termination request. Exiting."));
2067 #ifdef HAVE_PTHREAD_CANCEL
2068 pthread_cancel (tid
);
2070 pthread_kill (tid
, SIGUSR2
);
2072 pthread_join (tid
, NULL
);
2076 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2077 pwmd_strerror (rc
));
2080 if (cancel_timeout_thread
)
2082 #ifdef HAVE_PTHREAD_CANCEL
2083 pthread_cancel (cache_timeout_tid
);
2085 pthread_kill (cache_timeout_tid
, SIGUSR2
);
2087 pthread_join (cache_timeout_tid
, NULL
);
2090 if (cancel_keepalive_thread
)
2092 #ifdef HAVE_PTHREAD_CANCEL
2093 pthread_cancel (keepalive_tid
);
2095 pthread_kill (keepalive_tid
, SIGUSR2
);
2097 pthread_join (keepalive_tid
, NULL
);
2100 cleanup_all_clients (0);
2105 pthread_cond_destroy (&quit_cond
);
2106 pthread_mutex_destroy (&quit_mutex
);
2107 return segv
? EXIT_FAILURE
: EXIT_SUCCESS
;;
2114 ("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
2118 /* This is called from cache.c:clear_once(). See
2119 * command.c:clearcache_command() for details about lock checking.
2122 free_cache_data (file_cache_t
* cache
)
2124 gpg_error_t rc
= GPG_ERR_NO_DATA
;
2126 struct client_thread_s
*found
= NULL
;
2133 MUTEX_LOCK (&cn_mutex
);
2134 pthread_cleanup_push (cleanup_mutex_cb
, &cn_mutex
);
2135 t
= slist_length (cn_thread_list
);
2137 for (i
= 0; i
< t
; i
++)
2139 struct client_thread_s
*thd
= slist_nth_data (cn_thread_list
, i
);
2144 if (!memcmp (thd
->cl
->md5file
, cache
->filename
,
2145 sizeof (cache
->filename
)))
2147 if (pthread_equal (pthread_self (), thd
->tid
))
2154 /* Continue trying to find a client who has the same file open and
2155 * also has a lock. */
2156 rc
= cache_lock_mutex (thd
->cl
->ctx
, thd
->cl
->md5file
, -1, 0, -1);
2166 if (self
&& (!rc
|| rc
== GPG_ERR_NO_DATA
))
2167 rc
= cache_lock_mutex (found
->cl
->ctx
, found
->cl
->md5file
, -1, 0, -1);
2169 if (exiting
|| !rc
|| rc
== GPG_ERR_NO_DATA
)
2171 free_cache_data_once (cache
->data
);
2173 cache
->defer_clear
= 0;
2174 cache
->timeout
= -1;
2177 cache_unlock_mutex (found
->cl
->md5file
, 0);
2183 cache
->defer_clear
= 1;
2185 pthread_cleanup_pop (1);
2191 convert_v2_datafile (const char *filename
, const char *cipher
,
2192 const char *keyfile
, const char *keygrip
,
2193 const char *sign_keygrip
, int nopass
,
2194 const char *outfile
, const char *keyparam
,
2195 unsigned long s2k_count
, uint64_t iterations
)
2200 struct crypto_s
*crypto
= NULL
;
2206 if (outfile
[0] == '-' && outfile
[1] == 0)
2209 log_write (_("Converting version 2 data file \"%s\" ..."), filename
);
2210 if (access (filename
, R_OK
) == -1)
2212 log_write ("%s: %s", filename
,
2213 pwmd_strerror (gpg_error_from_errno (errno
)));
2219 log_write (_("Using passphrase file \"%s\" for decryption ..."),
2221 if (access (keyfile
, R_OK
) == -1)
2223 log_write ("%s: %s", keyfile
,
2224 pwmd_strerror (gpg_error_from_errno (errno
)));
2229 rc
= read_v2_datafile (filename
, keyfile
, &data
, &datalen
, &ver
, &algo
);
2232 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
2238 algo
= cipher_string_to_gcrypt (cipher
);
2241 rc
= GPG_ERR_CIPHER_ALGO
;
2248 xmlDocPtr doc
= parse_doc (data
, datalen
);
2252 rc
= GPG_ERR_BAD_DATA
;
2256 rc
= convert_pre_212_elements (doc
);
2261 xmlDocDumpFormatMemory (doc
, (xmlChar
**) & data
, (int *) &datalen
,
2264 rc
= GPG_ERR_ENOMEM
;
2272 rc
= init_client_crypto (&crypto
);
2275 memcpy (&crypto
->save
.hdr
, &crypto
->hdr
, sizeof (file_header_t
));
2276 crypto
->save
.hdr
.flags
= set_cipher_flag (crypto
->save
.hdr
.flags
, algo
);
2277 crypto
->save
.s2k_count
= s2k_count
;
2278 crypto
->save
.hdr
.iterations
= iterations
;
2282 rc
= export_common (NULL
, 0, crypto
, data
, datalen
, outfile
, keyfile
,
2283 &key
, &keylen
, 0, 0);
2288 rc
= agent_set_pinentry_options (crypto
->agent
);
2290 rc
= agent_export_common (crypto
, keygrip
, sign_keygrip
, nopass
,
2291 data
, datalen
, outfile
, keyparam
,
2292 no_passphrase_file
? NULL
: keyfile
);
2296 log_write (_("Output written to \"%s\"."), outfile
);
2306 cleanup_crypto (&crypto
);
2309 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
2314 usage (const char *pn
, int status
)
2316 FILE *fp
= status
== EXIT_FAILURE
? stderr
: stdout
;
2318 fprintf (fp
, _("Usage: %s [OPTIONS] [file1] [...]\n"
2319 " -f, --rcfile=filename load the specfied configuration file\n"
2320 " (~/.pwmd/config)\n"
2321 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2323 " --use-agent enable use of gpg-agent\n"
2325 " -n, --no-fork run as a foreground process\n"
2326 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2327 " --ignore ignore file errors during startup\n"
2328 " --debug-level=keywords log protocol output (see manual for details)\n"
2329 " -o, --outfile=filename output file when importing or converting\n"
2330 " -C, --convert=filename convert a version 2 data file to version 3\n"
2331 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2332 " -k, --passphrase-file=file for use when importing or converting\n"
2333 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2335 " --no-passphrase when importing or converting\n"
2336 " --keygrip=hex public key to use when encrypting\n"
2337 " --sign-keygrip=hex private key to use when signing\n"
2338 " --keyparam=s-exp custom key parameters to use (RSA-2048)\n"
2339 " --cipher=string encryption cipher (aes256)\n"
2340 " --iterations=N cipher iteration count (N+1)\n"
2341 " --s2k-count=N hash iteration count (>65536, calibrated)\n"
2342 " --help this help text\n"
2343 " --version show version and compile time features\n"),
2349 main (int argc
, char *argv
[])
2352 struct sockaddr_un addr
;
2354 char *socketpath
= NULL
, *socketdir
, *socketname
= NULL
;
2355 char *socketarg
= NULL
;
2356 char *datadir
= NULL
;
2359 char **cache_push
= NULL
;
2360 char *import
= NULL
, *keygrip
= NULL
, *sign_keygrip
= NULL
;
2361 char *keyparam
= NULL
;
2362 int estatus
= EXIT_FAILURE
;
2364 char *outfile
= NULL
;
2367 int show_version
= 0;
2369 int no_passphrase
= 0;
2371 char *convertfile
= NULL
;
2372 char *cipher
= NULL
;
2373 char *keyfile
= NULL
;
2374 unsigned long s2k_count
= 0;
2375 uint64_t iterations
= 0;
2377 char *debug_level_opt
= NULL
;
2379 /* Must maintain the same order as longopts[] */
2382 OPT_VERSION
, OPT_HELP
,
2386 OPT_DEBUG_LEVEL
, OPT_HOMEDIR
, OPT_NO_FORK
, OPT_DISABLE_DUMP
, OPT_IGNORE
,
2387 OPT_RCFILE
, OPT_CONVERT
, OPT_PASSPHRASE_FILE
, OPT_IMPORT
, OPT_OUTFILE
,
2388 OPT_NO_PASSPHRASE_FILE
, OPT_KEYGRIP
, OPT_SIGN_KEYGRIP
, OPT_KEYPARAM
,
2389 OPT_CIPHER
, OPT_ITERATIONS
, OPT_S2K_COUNT
, OPT_NO_PASSPHRASE
2391 const char *optstring
= "nf:C:k:I:o:";
2392 const struct option longopts
[] = {
2393 {"version", no_argument
, 0, 0},
2394 {"help", no_argument
, 0, 0},
2396 {"use-agent", no_argument
, 0, 0},
2398 {"debug-level", required_argument
, 0, 0},
2399 {"homedir", required_argument
, 0, 0},
2400 {"no-fork", no_argument
, 0, 'n'},
2401 {"disable_dump", no_argument
, 0, 0},
2402 {"ignore", no_argument
, 0, 0},
2403 {"rcfile", required_argument
, 0, 'f'},
2404 {"convert", required_argument
, 0, 'C'},
2405 {"passphrase-file", required_argument
, 0, 'k'},
2406 {"import", required_argument
, 0, 'I'},
2407 {"outfile", required_argument
, 0, 'o'},
2408 {"no-passphrase-file", no_argument
, 0, 0},
2409 {"keygrip", required_argument
, 0, 0},
2410 {"sign-keygrip", required_argument
, 0, 0},
2411 {"keyparam", required_argument
, 0, 0},
2412 {"cipher", required_argument
, 0, 0},
2413 {"cipher-iterations", required_argument
, 0, 0},
2414 {"s2k-count", required_argument
, 0, 0},
2415 {"no-passphrase", no_argument
, 0, 0},
2420 #ifdef HAVE_SETRLIMIT
2423 rl
.rlim_cur
= rl
.rlim_max
= 0;
2425 if (setrlimit (RLIMIT_CORE
, &rl
) != 0)
2426 err (EXIT_FAILURE
, "setrlimit()");
2431 setlocale (LC_ALL
, "");
2432 bindtextdomain ("pwmd", LOCALEDIR
);
2433 textdomain ("pwmd");
2441 if (setup_crypto ())
2442 exit (EXIT_FAILURE
);
2445 gnutls_global_set_mem_functions (xmalloc
, xmalloc
, secure_mem_check
,
2447 gnutls_global_init ();
2448 gnutls_global_set_log_function (tls_log
);
2449 gnutls_global_set_log_level (1);
2453 xmlMemSetup (xfree
, xmalloc
, xrealloc
, str_dup
);
2461 while ((opt
= getopt_long (argc
, argv
, optstring
, longopts
, &optindex
))
2470 convertfile
= optarg
;
2485 rcfile
= str_dup (optarg
);
2488 usage (argv
[0], EXIT_FAILURE
);
2504 case OPT_DEBUG_LEVEL
:
2505 debug_level_opt
= optarg
;
2508 homedir
= str_dup (optarg
);
2513 case OPT_DISABLE_DUMP
:
2520 rcfile
= str_dup (optarg
);
2523 convertfile
= optarg
;
2525 case OPT_PASSPHRASE_FILE
:
2534 case OPT_NO_PASSPHRASE_FILE
:
2535 no_passphrase_file
= 1;
2540 case OPT_SIGN_KEYGRIP
:
2541 sign_keygrip
= optarg
;
2549 case OPT_ITERATIONS
:
2550 iterations
= strtoull (optarg
, NULL
, 10);
2553 s2k_count
= strtoul (optarg
, NULL
, 10);
2555 case OPT_NO_PASSPHRASE
:
2567 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013\n"
2569 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2570 "Compile time features:\n%s"), PACKAGE_STRING
,
2573 "+PWMD_HOMEDIR=" PWMD_HOMEDIR
"\n"
2611 exit (EXIT_SUCCESS
);
2616 homedir
= str_dup(PWMD_HOMEDIR
);
2618 homedir
= str_asprintf ("%s/.pwmd", get_home_dir ());
2621 if (mkdir (homedir
, 0700) == -1 && errno
!= EEXIST
)
2622 err (EXIT_FAILURE
, "%s", homedir
);
2624 snprintf (buf
, sizeof (buf
), "%s/data", homedir
);
2625 if (mkdir (buf
, 0700) == -1 && errno
!= EEXIST
)
2626 err (EXIT_FAILURE
, "%s", buf
);
2628 datadir
= str_dup (buf
);
2629 pthread_mutexattr_t attr
;
2630 pthread_mutexattr_init (&attr
);
2631 pthread_mutexattr_settype (&attr
, PTHREAD_MUTEX_RECURSIVE
);
2632 pthread_mutex_init (&rcfile_mutex
, &attr
);
2633 pthread_cond_init (&rcfile_cond
, NULL
);
2634 pthread_mutex_init (&cn_mutex
, &attr
);
2635 pthread_mutexattr_destroy (&attr
);
2636 pthread_key_create (&last_error_key
, free_key
);
2637 #ifndef HAVE_PTHREAD_CANCEL
2638 pthread_key_create (&signal_thread_key
, free_key
);
2642 rcfile
= str_asprintf ("%s/config", homedir
);
2644 global_config
= config_parse (rcfile
);
2646 exit (EXIT_FAILURE
);
2650 use_agent
= config_get_boolean ("global", "use_agent");
2655 if (debug_level_opt
)
2656 debug_level
= str_split (debug_level_opt
, ",", 0);
2658 x
= config_get_int_param (global_config
, "global", "priority", &exists
);
2659 if (exists
&& x
!= atoi(INVALID_PRIORITY
))
2662 if (setpriority (PRIO_PROCESS
, 0, x
) == -1)
2664 log_write ("setpriority(): %s",
2665 pwmd_strerror (gpg_error_from_errno (errno
)));
2669 #ifdef HAVE_MLOCKALL
2670 if (disable_mlock
== 0 && mlockall (MCL_CURRENT
| MCL_FUTURE
) == -1)
2672 log_write ("mlockall(): %s",
2673 pwmd_strerror (gpg_error_from_errno (errno
)));
2678 rc
= cache_init (free_cache_data
);
2681 log_write ("pwmd: ERR %i: %s", rc
,
2682 gpg_err_code (rc
) == GPG_ERR_UNKNOWN_VERSION
2683 ? _("incompatible gpg-agent version: 2.1.0 or later required")
2684 : pwmd_strerror (rc
));
2689 s2k_count
= config_get_ulong (NULL
, "s2k_count");
2694 usage (argv
[0], EXIT_FAILURE
);
2696 estatus
= convert_v2_datafile (convertfile
, cipher
, keyfile
, keygrip
,
2697 sign_keygrip
, no_passphrase
, outfile
,
2698 keyparam
, s2k_count
, iterations
);
2699 config_free (global_config
);
2706 if (!outfile
|| !*outfile
)
2707 usage (argv
[0], EXIT_FAILURE
);
2709 if (outfile
&& outfile
[0] == '-' && outfile
[1] == 0)
2712 estatus
= xml_import (import
, outfile
, keygrip
, sign_keygrip
, keyfile
,
2713 no_passphrase
, cipher
, keyparam
, s2k_count
,
2715 config_free (global_config
);
2720 p
= config_get_string ("global", "socket_path");
2722 p
= str_asprintf ("%s/socket", homedir
);
2724 socketarg
= expand_homedir (p
);
2728 disable_list_and_dump
= config_get_boolean ("global",
2729 "disable_list_and_dump");
2731 disable_list_and_dump
= secure
;
2733 cache_push
= config_get_list ("global", "cache_push");
2735 while (optind
< argc
)
2737 if (strv_printf (&cache_push
, "%s", argv
[optind
++]) == 0)
2738 errx (EXIT_FAILURE
, "%s", pwmd_strerror (GPG_ERR_ENOMEM
));
2741 if (strchr (socketarg
, '/') == NULL
)
2743 socketdir
= getcwd (buf
, sizeof (buf
));
2744 socketname
= str_dup (socketarg
);
2745 socketpath
= str_asprintf ("%s/%s", socketdir
, socketname
);
2749 socketname
= str_dup (strrchr (socketarg
, '/'));
2751 socketarg
[strlen (socketarg
) - strlen (socketname
) - 1] = 0;
2752 socketdir
= str_dup (socketarg
);
2753 socketpath
= str_asprintf ("%s/%s", socketdir
, socketname
);
2756 if (chdir (datadir
))
2758 log_write ("%s: %s", datadir
,
2759 pwmd_strerror (gpg_error_from_errno (errno
)));
2760 unlink (socketpath
);
2765 * Set the cache entry for a file. Prompts for the password.
2769 struct crypto_s
*crypto
= NULL
;
2770 gpg_error_t rc
= init_client_crypto (&crypto
);
2774 estatus
= EXIT_FAILURE
;
2781 rc
= agent_set_pinentry_options (crypto
->agent
);
2784 estatus
= EXIT_FAILURE
;
2790 for (opt
= 0; cache_push
[opt
]; opt
++)
2792 if (!do_cache_push (cache_push
[opt
], crypto
) && !force
)
2794 strv_free (cache_push
);
2796 estatus
= EXIT_FAILURE
;
2797 cleanup_crypto (&crypto
);
2801 cleanup_crypto_stage1 (crypto
);
2806 (void) kill_scd (crypto
->agent
);
2809 cleanup_crypto (&crypto
);
2810 strv_free (cache_push
);
2811 log_write (!nofork
? _("Done. Daemonizing...") :
2812 _("Done. Waiting for connections..."));
2815 config_clear_keys ();
2818 * bind() doesn't like the full pathname of the socket or any non alphanum
2819 * characters so change to the directory where the socket is wanted then
2820 * create it then change to datadir.
2822 if (chdir (socketdir
))
2824 log_write ("%s: %s", socketdir
,
2825 pwmd_strerror (gpg_error_from_errno (errno
)));
2831 if ((sockfd
= socket (PF_UNIX
, SOCK_STREAM
, 0)) == -1)
2833 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
2837 addr
.sun_family
= AF_UNIX
;
2838 snprintf (addr
.sun_path
, sizeof (addr
.sun_path
), "%s", socketname
);
2840 if (bind (sockfd
, (struct sockaddr
*) &addr
, sizeof (struct sockaddr
)) ==
2843 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
2845 if (errno
== EADDRINUSE
)
2848 log_write (_("Either there is another pwmd running or '%s' is a \n"
2849 "stale socket. Please remove it manually."), socketpath
);
2856 char *t
= config_get_string ("global", "socket_perms");
2862 mode
= strtol (t
, NULL
, 8);
2866 if (chmod (socketname
, mode
) == -1)
2868 log_write ("%s: %s", socketname
,
2869 pwmd_strerror (gpg_error_from_errno (errno
)));
2879 xfree (--socketname
);
2881 if (chdir (datadir
))
2883 log_write ("%s: %s", datadir
,
2884 pwmd_strerror (gpg_error_from_errno (errno
)));
2891 if (listen (sockfd
, 0) == -1)
2893 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno
)));
2904 log_write ("fork(): %s",
2905 pwmd_strerror (gpg_error_from_errno (errno
)));
2914 _exit (EXIT_SUCCESS
);
2918 pthread_key_create (&thread_name_key
, free_key
);
2919 pthread_setspecific (thread_name_key
, str_dup ("main"));
2920 estatus
= server_loop (sockfd
, &socketpath
);
2923 if (socketpath
&& do_unlink
)
2925 unlink (socketpath
);
2931 gnutls_global_deinit ();
2935 #ifdef HAVE_PTHREAD_CANCEL
2936 pthread_cancel (rcfile_tid
);
2938 pthread_kill (rcfile_tid
, SIGUSR2
);
2939 pthread_cond_signal (&rcfile_cond
);
2941 pthread_join (rcfile_tid
, NULL
);
2944 pthread_cond_destroy (&rcfile_cond
);
2945 pthread_mutex_destroy (&rcfile_mutex
);
2946 pthread_key_delete (last_error_key
);
2947 #ifndef HAVE_PTHREAD_CANCEL
2948 pthread_key_delete (signal_thread_key
);
2952 config_free (global_config
);
2955 xfree (home_directory
);
2957 xmlCleanupParser ();
2958 xmlCleanupGlobals ();
2960 if (estatus
== EXIT_SUCCESS
)
2961 log_write (_("pwmd exiting normally"));
2963 pthread_key_delete (thread_name_key
);
2965 #if defined(DEBUG) && !defined(MEM_DEBUG)