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
;
243 int tcp_require_key
= config_get_bool_param (global_config
, "global",
248 pthread_cond_wait (&rcfile_cond
, &rcfile_mutex
);
249 #ifndef HAVE_PTHREAD_CANCEL
250 int *n
= (int *) pthread_getspecific (signal_thread_key
);
255 users
= config_get_list ("global", "allowed");
256 log_write (_("reloading configuration file '%s'"), rcfile
);
257 config
= config_parse (rcfile
);
260 config_free (global_config
);
261 global_config
= config
;
263 cache_push_from_rcfile ();
264 config_clear_keys ();
267 disable_list_and_dump
= !disable_list_and_dump
? b
: 1;
269 if (config_get_bool_param (global_config
, "global", "tcp_require_key",
273 config_set_bool_param (&global_config
, "global", "tcp_require_key",
274 tcp_require_key
? "true" : "false");
276 char *tmp
= strv_join (",", users
);
277 config_set_list_param (&global_config
, "global", "allowed", tmp
);
281 /* Kill existing listening threads since the configured listening
282 * protocols may have changed. */
288 pthread_cleanup_pop (1);
293 send_error (assuan_context_t ctx
, gpg_error_t e
)
295 struct client_s
*client
= assuan_get_pointer (ctx
);
297 if (gpg_err_source (e
) == GPG_ERR_SOURCE_UNKNOWN
)
304 return assuan_process_done (ctx
, 0);
308 log_write ("%s", pwmd_strerror (e
));
312 if (client
&& gpg_err_code (e
) == GPG_ERR_BAD_DATA
)
314 xmlErrorPtr xe
= client
->xml_error
;
317 xe
= xmlGetLastError ();
320 log_write ("%s", xe
->message
);
321 if (client
->last_error
)
322 xfree (client
->last_error
);
324 client
->last_error
= str_dup (xe
->message
);
327 e
= assuan_process_done (ctx
, assuan_set_error (ctx
, e
,
331 if (xe
== client
->xml_error
)
334 xmlResetLastError ();
336 client
->xml_error
= NULL
;
340 return assuan_process_done (ctx
,
341 assuan_set_error (ctx
, e
, pwmd_strerror (e
)));
345 assuan_log_cb (assuan_context_t ctx
, void *data
, unsigned cat
,
348 static pthread_mutex_t m
= PTHREAD_MUTEX_INITIALIZER
;
352 pthread_mutex_lock (&m
);
353 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock
, &m
);
354 t
= strv_length (debug_level
);
356 for (i
= 0; i
< t
; i
++)
358 if (!strcasecmp (debug_level
[i
], (char *) "init")
359 && cat
== ASSUAN_LOG_INIT
)
365 if (!strcasecmp (debug_level
[i
], (char *) "ctx")
366 && cat
== ASSUAN_LOG_CTX
)
372 if (!strcasecmp (debug_level
[i
], (char *) "engine")
373 && cat
== ASSUAN_LOG_ENGINE
)
379 if (!strcasecmp (debug_level
[i
], (char *) "data")
380 && cat
== ASSUAN_LOG_DATA
)
386 if (!strcasecmp (debug_level
[i
], (char *) "sysio")
387 && cat
== ASSUAN_LOG_SYSIO
)
393 if (!strcasecmp (debug_level
[i
], (char *) "control")
394 && cat
== ASSUAN_LOG_CONTROL
)
408 open (logfile
, O_WRONLY
| O_CREAT
| O_APPEND
, 0600)) == -1)
409 warn ("%s", logfile
);
412 pthread_cleanup_push (cleanup_fd_cb
, &fd
);
413 write (fd
, msg
, strlen (msg
));
414 pthread_cleanup_pop (1);
420 fprintf (stderr
, "%s%s", data
? (char *) data
: "", msg
);
425 pthread_cleanup_pop (1);
430 log_write (const char *fmt
, ...)
440 pthread_t tid
= pthread_self ();
441 static pthread_mutex_t m
= PTHREAD_MUTEX_INITIALIZER
;
443 if ((!logfile
&& !isatty (STDERR_FILENO
) && !log_syslog
) || !fmt
)
446 pthread_mutex_lock (&m
);
447 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock
, &m
);
448 pthread_cleanup_push (cleanup_fd_cb
, &fd
);
450 if (!cmdline
&& logfile
)
452 if ((fd
= open (logfile
, O_WRONLY
| O_CREAT
| O_APPEND
, 0600)) == -1)
453 warn ("%s", logfile
);
458 if (str_vasprintf (&args
, fmt
, ap
) != -1)
462 pthread_cleanup_push (xfree
, args
);
463 fprintf (stderr
, "%s\n", args
);
465 pthread_cleanup_pop (1);
469 pthread_cleanup_push (xfree
, args
);
470 name
= pthread_getspecific (thread_name_key
);
471 snprintf (buf
, sizeof (buf
), "%s(%p): ", name
? name
: _("unknown"),
475 if (!cmdline
&& log_syslog
&& !nofork
)
476 syslog (LOG_INFO
, "%s%s", name
, args
);
479 tm
= localtime (&now
);
480 strftime (tbuf
, sizeof (tbuf
), "%b %d %Y %H:%M:%S ", tm
);
481 tbuf
[sizeof (tbuf
) - 1] = 0;
483 if (args
[strlen (args
) - 1] == '\n')
484 args
[strlen (args
) - 1] = 0;
486 line
= str_asprintf ("%s %i %s%s\n", tbuf
, getpid (), name
, args
);
487 pthread_cleanup_pop (1);
490 pthread_cleanup_push (xfree
, line
);
491 if (logfile
&& fd
!= -1)
493 write (fd
, line
, strlen (line
));
499 fprintf (stdout
, "%s", line
);
503 pthread_cleanup_pop (1);
509 pthread_cleanup_pop (1);
510 pthread_cleanup_pop (0);
511 pthread_mutex_unlock (&m
);
516 secure_mem_check (const void *arg
)
525 gcry_control (GCRYCTL_SET_THREAD_CBS
, &gcry_threads_pthread
);
527 if (!gcry_check_version (GCRYPT_VERSION
))
529 fprintf (stderr
, _("gcry_check_version(): Incompatible libgcrypt. "
530 "Wanted %s, got %s.\n"), GCRYPT_VERSION
,
531 gcry_check_version (NULL
));
532 return GPG_ERR_UNKNOWN_VERSION
;
535 gcry_set_allocation_handler (xmalloc
, xmalloc
, NULL
, xrealloc
, xfree
);
539 #ifdef HAVE_GETGRNAM_R
541 do_validate_peer (struct client_s
*cl
, assuan_peercred_t
* peer
)
547 rc
= assuan_get_peercred (cl
->ctx
, peer
);
551 users
= config_get_list ("global", "allowed");
554 for (char **p
= users
; *p
; p
++)
556 struct passwd pw
, *result
;
557 struct group gr
, *gresult
;
562 size_t len
= sysconf (_SC_GETGR_R_SIZE_MAX
);
571 return GPG_ERR_ENOMEM
;
574 if (!getgrnam_r (*(p
) + 1, &gr
, buf
, len
, &gresult
) && gresult
)
576 if (gresult
->gr_gid
== (*peer
)->gid
)
583 len
= sysconf (_SC_GETPW_R_SIZE_MAX
);
587 char *tbuf
= xmalloc (len
);
588 for (char **t
= gresult
->gr_mem
; *t
; t
++)
590 if (!getpwnam_r (*t
, &pw
, tbuf
, len
, &result
) && result
)
592 if (result
->pw_uid
== (*peer
)->uid
)
609 size_t len
= sysconf (_SC_GETPW_R_SIZE_MAX
);
619 return GPG_ERR_ENOMEM
;
622 if (!getpwnam_r (*p
, &pw
, buf
, len
, &result
) && result
)
624 if (result
->pw_uid
== (*peer
)->uid
)
639 return allowed
? 0 : GPG_ERR_INV_USER_ID
;
643 do_validate_peer (struct client_s
*cl
, assuan_peercred_t
* peer
)
649 rc
= assuan_get_peercred (cl
->ctx
, peer
);
653 users
= config_get_list ("global", "allowed");
656 for (char **p
= users
; *p
; p
++)
658 struct passwd
*result
;
659 struct group
*gresult
;
663 gresult
= getgrnam (*(p
) + 1);
664 if (gresult
&& gresult
->gr_gid
== (*peer
)->gid
)
670 for (char **t
= gresult
->gr_mem
; *t
; t
++)
672 result
= getpwnam (*t
);
673 if (result
&& result
->pw_uid
== (*peer
)->uid
)
682 result
= getpwnam (*p
);
683 if (result
&& result
->pw_uid
== (*peer
)->uid
)
697 return allowed
? 0 : GPG_ERR_INV_USER_ID
;
702 validate_peer (struct client_s
*cl
)
705 assuan_peercred_t peer
;
712 rc
= do_validate_peer (cl
, &peer
);
713 if (!rc
|| gpg_err_code (rc
) == GPG_ERR_INV_USER_ID
)
714 log_write ("peer %s: uid=%i, gid=%i, pid=%i",
715 !rc
? _("accepted") : _("rejected"), peer
->uid
, peer
->gid
,
718 log_write ("%s: %s", __FUNCTION__
, pwmd_strerror (rc
));
724 xml_error_cb (void *data
, xmlErrorPtr e
)
726 struct client_s
*client
= data
;
729 * Keep the first reported error as the one to show in the error
730 * description. Reset in send_error().
732 if (client
->xml_error
)
735 xmlCopyError (e
, client
->xml_error
);
739 hook_waitpid (assuan_context_t ctx
, pid_t pid
, int action
,
740 int *status
, int options
)
742 return waitpid (pid
, status
, options
);
746 hook_read (assuan_context_t ctx
, assuan_fd_t fd
, void *data
, size_t len
)
749 struct client_s
*client
= assuan_get_pointer (ctx
);
751 if (client
->thd
->remote
)
752 return tls_read_hook (ctx
, (int) fd
, data
, len
);
755 return read ((int) fd
, data
, len
);
759 hook_write (assuan_context_t ctx
, assuan_fd_t fd
,
760 const void *data
, size_t len
)
763 struct client_s
*client
= assuan_get_pointer (ctx
);
765 if (client
->thd
->remote
)
766 return tls_write_hook (ctx
, (int) fd
, data
, len
);
769 return write ((int) fd
, data
, len
);
773 new_connection (struct client_s
*cl
)
776 static struct assuan_malloc_hooks mhooks
= { xmalloc
, xrealloc
, xfree
};
777 static struct assuan_system_hooks shooks
= {
778 ASSUAN_SYSTEM_HOOKS_VERSION
,
786 NULL
, //sendmsg both are used for FD passing
797 char *prio
= config_get_string ("global", "tls_cipher_suite");
799 cl
->thd
->tls
= tls_init (cl
->thd
->fd
, cl
->thd
->timeout
, prio
);
806 rc
= assuan_new_ext (&cl
->ctx
, GPG_ERR_SOURCE_DEFAULT
, &mhooks
,
807 debug_level
? assuan_log_cb
: NULL
, NULL
);
811 assuan_ctx_set_system_hooks (cl
->ctx
, &shooks
);
812 rc
= assuan_init_socket_server (cl
->ctx
, cl
->thd
->fd
, 2);
816 assuan_set_pointer (cl
->ctx
, cl
);
817 assuan_set_hello_line (cl
->ctx
, PACKAGE_STRING
);
818 rc
= register_commands (cl
->ctx
);
825 cl
->thd
->timeout
= config_get_integer ("global", "tls_timeout");
826 fcntl (cl
->thd
->fd
, F_SETFL
, O_NONBLOCK
);
830 rc
= assuan_accept (cl
->ctx
);
834 rc
= validate_peer (cl
);
835 /* May not be implemented on all platforms. */
836 if (rc
&& gpg_err_code (rc
) != GPG_ERR_ASS_GENERAL
)
839 rc
= init_client_crypto (&cl
->crypto
);
845 cl
->crypto
->agent
->client_ctx
= cl
->ctx
;
848 cl
->crypto
->client_ctx
= cl
->ctx
;
849 xmlSetStructuredErrorFunc (cl
, xml_error_cb
);
853 log_write ("%s", pwmd_strerror (rc
));
858 * This is called after a client_thread() terminates. Set with
859 * pthread_cleanup_push().
862 cleanup_cb (void *arg
)
864 struct client_thread_s
*cn
= arg
;
865 struct client_s
*cl
= cn
->cl
;
867 MUTEX_LOCK (&cn_mutex
);
868 cn_thread_list
= slist_remove (cn_thread_list
, cn
);
869 MUTEX_UNLOCK (&cn_mutex
);
878 gnutls_deinit (cn
->tls
->ses
);
884 if (!cn
->atfork
&& cl
->ctx
)
885 assuan_release (cl
->ctx
);
886 else if (!cn
->atfork
&& cl
->thd
&& cl
->thd
->fd
!= -1)
890 cleanup_crypto (&cl
->crypto
);
892 pinentry_free_opts (&cl
->pinentry_opts
);
901 while (cn
->msg_queue
)
903 struct status_msg_s
*msg
= cn
->msg_queue
;
905 cn
->msg_queue
= msg
->next
;
910 if (!cn
->atfork
&& cn
->status_msg_pipe
[0] != -1)
911 close (cn
->status_msg_pipe
[0]);
913 if (!cn
->atfork
&& cn
->status_msg_pipe
[1] != -1)
914 close (cn
->status_msg_pipe
[1]);
916 pthread_mutex_destroy (&cn
->status_mutex
);
920 log_write (_("exiting, fd=%i"), cn
->fd
);
921 send_status_all (STATUS_CLIENTS
, NULL
);
925 pthread_cond_signal (&quit_cond
);
929 cleanup_all_clients (int atfork
)
931 /* This function may be called from pthread_atfork() which requires
935 pthread_mutexattr_t attr
;
937 pthread_mutexattr_init (&attr
);
938 pthread_mutexattr_settype (&attr
, PTHREAD_MUTEX_RECURSIVE
);
939 pthread_mutex_init (&cn_mutex
, &attr
);
940 pthread_mutexattr_destroy (&attr
);
944 MUTEX_LOCK (&cn_mutex
);
946 while (slist_length (cn_thread_list
))
948 struct client_thread_s
*thd
= slist_nth_data (cn_thread_list
, 0);
950 thd
->atfork
= atfork
;
955 cache_deinit (atfork
);
956 MUTEX_UNLOCK (&cn_mutex
);
960 send_msg_queue (struct client_thread_s
*thd
)
962 MUTEX_LOCK (&thd
->status_mutex
);
966 read (thd
->status_msg_pipe
[0], &c
, 1);
968 while (thd
->msg_queue
)
970 struct status_msg_s
*msg
= thd
->msg_queue
;
972 thd
->msg_queue
= thd
->msg_queue
->next
;
973 MUTEX_UNLOCK (&thd
->status_mutex
);
974 rc
= send_status (thd
->cl
->ctx
, msg
->s
, msg
->line
);
975 MUTEX_LOCK (&thd
->status_mutex
);
983 MUTEX_UNLOCK (&thd
->status_mutex
);
984 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
985 log_write ("%s: %s", __FUNCTION__
, pwmd_strerror (rc
));
991 client_thread (void *data
)
993 struct client_thread_s
*thd
= data
;
994 struct client_s
*cl
= xcalloc (1, sizeof (struct client_s
));
996 #ifdef HAVE_PR_SET_NAME
997 prctl (PR_SET_NAME
, "client");
999 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1003 log_write ("%s(%i): %s", __FILE__
, __LINE__
,
1004 pwmd_strerror (GPG_ERR_ENOMEM
));
1008 MUTEX_LOCK (&cn_mutex
);
1009 pthread_cleanup_push (cleanup_cb
, thd
);
1012 MUTEX_UNLOCK (&cn_mutex
);
1014 if (new_connection (cl
))
1019 send_status_all (STATUS_CLIENTS
, NULL
);
1020 rc
= send_status (cl
->ctx
, STATUS_CACHE
, NULL
);
1023 log_write ("%s(%i): %s", __FILE__
, __LINE__
, pwmd_strerror (rc
));
1034 FD_SET (thd
->fd
, &rfds
);
1035 FD_SET (thd
->status_msg_pipe
[0], &rfds
);
1036 n
= thd
->fd
> thd
->status_msg_pipe
[0]
1037 ? thd
->fd
: thd
->status_msg_pipe
[0];
1039 n
= select (n
+ 1, &rfds
, NULL
, NULL
, NULL
);
1042 log_write ("%s", strerror (errno
));
1046 if (FD_ISSET (thd
->status_msg_pipe
[0], &rfds
))
1048 rc
= send_msg_queue (thd
);
1049 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1053 if (!FD_ISSET (thd
->fd
, &rfds
))
1056 rc
= assuan_process_next (cl
->ctx
, &eof
);
1059 if (gpg_err_code (rc
) == GPG_ERR_EOF
|| eof
)
1062 log_write ("assuan_process_next(): rc=%i %s", rc
,
1063 pwmd_strerror (rc
));
1064 if (rc
== gpg_error (GPG_ERR_ETIMEDOUT
))
1067 rc
= send_error (cl
->ctx
, rc
);
1070 log_write ("assuan_process_done(): rc=%i %s", rc
,
1071 pwmd_strerror (rc
));
1076 /* Since the msg queue pipe fd's are non-blocking, check for
1077 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1078 * client has already disconnected and will be converted to
1079 * GPG_ERR_EOF during assuan_process_next().
1081 rc
= send_msg_queue (thd
);
1082 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1087 pthread_cleanup_pop (1);
1092 xml_import (const char *filename
, const char *outfile
,
1093 const char *keygrip
, const char *sign_keygrip
,
1094 const char *keyfile
, int no_passphrase
, const char *cipher
,
1095 const char *params
, unsigned long s2k_count
, uint64_t iterations
)
1104 struct crypto_s
*crypto
= NULL
;
1107 int algo
= cipher
? cipher_string_to_gcrypt ((char *) cipher
) :
1112 log_write ("ERR %i: %s", gpg_error (GPG_ERR_CIPHER_ALGO
),
1113 pwmd_strerror (GPG_ERR_CIPHER_ALGO
));
1117 if (stat (filename
, &st
) == -1)
1119 log_write ("%s: %s", filename
,
1120 pwmd_strerror (gpg_error_from_syserror ()));
1124 rc
= init_client_crypto (&crypto
);
1128 memcpy (&crypto
->save
.hdr
, &crypto
->hdr
, sizeof (file_header_t
));
1129 crypto
->save
.hdr
.flags
= set_cipher_flag (crypto
->save
.hdr
.flags
, algo
);
1130 log_write (_("Importing XML from '%s'. Output will be written to '%s' ..."),
1133 if ((fd
= open (filename
, O_RDONLY
)) == -1)
1135 log_write ("%s: %s", filename
,
1136 pwmd_strerror (gpg_error_from_syserror ()));
1140 if ((xmlbuf
= xmalloc (st
.st_size
+ 1)) == NULL
)
1143 log_write ("%s(%i): %s", __FILE__
, __LINE__
,
1144 pwmd_strerror (GPG_ERR_ENOMEM
));
1148 if (read (fd
, xmlbuf
, st
.st_size
) == -1)
1150 rc
= gpg_error_from_syserror ();
1152 log_write ("%s: %s", filename
, pwmd_strerror (rc
));
1157 xmlbuf
[st
.st_size
] = 0;
1159 * Make sure the document validates.
1161 if ((doc
= xmlReadDoc (xmlbuf
, NULL
, "UTF-8", XML_PARSE_NOBLANKS
)) == NULL
)
1163 log_write ("xmlReadDoc() failed");
1169 xmlNodePtr n
= xmlDocGetRootElement (doc
);
1170 if (n
&& !xmlStrEqual (n
->name
, (xmlChar
*) "pwmd"))
1172 log_write (_("Could not find root \"pwmd\" element."));
1173 rc
= GPG_ERR_BAD_DATA
;
1177 rc
= validate_import (n
? n
->children
: n
);
1181 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
1186 xmlDocDumpMemory (doc
, &xml
, &len
);
1188 crypto
->save
.s2k_count
= s2k_count
;
1189 crypto
->save
.hdr
.iterations
= iterations
;
1192 rc
= export_common (NULL
, 0, crypto
, xml
, len
, outfile
, keyfile
, &key
,
1195 log_write (_("Success!"));
1200 rc
= agent_set_pinentry_options (crypto
->agent
);
1202 rc
= agent_export_common (crypto
, keygrip
, sign_keygrip
, no_passphrase
,
1203 xml
, len
, outfile
, params
, keyfile
);
1211 send_error (NULL
, rc
);
1215 cleanup_crypto (&crypto
);
1219 cleanup_crypto (&crypto
);
1224 do_cache_push (const char *filename
, struct crypto_s
*crypto
)
1226 unsigned char md5file
[16];
1231 struct cache_data_s
*cdata
;
1235 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1238 if (valid_filename (filename
) == 0)
1240 log_write (_("%s: Invalid characters in filename"), filename
);
1244 rc
= decrypt_common (NULL
, 0, crypto
, filename
, &key
, &keylen
);
1248 doc
= parse_doc ((char *) crypto
->plaintext
, crypto
->plaintext_len
);
1251 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM
));
1256 gcry_md_hash_buffer (GCRY_MD_MD5
, md5file
, filename
, strlen (filename
));
1257 cdata
= xcalloc (1, sizeof (struct cache_data_s
));
1261 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM
));
1266 rc
= get_checksum (filename
, &crc
, &len
);
1269 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
1271 free_cache_data_once (cdata
);
1277 rc
= encrypt_xml (NULL
, cache_key
, cache_keysize
, GCRY_CIPHER_AES
,
1278 crypto
->plaintext
, crypto
->plaintext_len
, &cdata
->doc
,
1279 &cdata
->doclen
, &cache_iv
, &cache_blocksize
, 0);
1280 if (!rc
&& !IS_PKCS (crypto
))
1283 cdata
->keylen
= keylen
;
1290 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
1292 free_cache_data_once (cdata
);
1299 gcry_sexp_build ((gcry_sexp_t
*) & cdata
->pubkey
, NULL
, "%S",
1301 gcry_sexp_build ((gcry_sexp_t
*) & cdata
->sigkey
, NULL
, "%S",
1302 crypto
->sigpkey_sexp
);
1306 int timeout
= config_get_integer (filename
, "cache_timeout");
1307 cache_add_file (md5file
, crypto
->grip
, cdata
, timeout
);
1308 log_write (_("Successfully added '%s' to the cache."), filename
);
1313 init_client (int fd
, const char *addr
)
1316 struct client_thread_s
*new = xcalloc (1, sizeof (struct client_thread_s
));
1321 return GPG_ERR_ENOMEM
;
1324 MUTEX_LOCK (&cn_mutex
);
1325 pthread_cleanup_push (cleanup_mutex_cb
, &cn_mutex
);
1327 if (pipe (new->status_msg_pipe
) == -1)
1328 rc
= gpg_error_from_syserror ();
1332 fcntl (new->status_msg_pipe
[0], F_SETFL
, O_NONBLOCK
);
1333 fcntl (new->status_msg_pipe
[1], F_SETFL
, O_NONBLOCK
);
1334 pthread_mutex_init (&new->status_mutex
, NULL
);
1340 new->remote
= addr
? 1 : 0;
1343 rc
= create_thread (client_thread
, new, &new->tid
, 1);
1346 close (new->status_msg_pipe
[0]);
1347 close (new->status_msg_pipe
[1]);
1348 pthread_mutex_destroy (&new->status_mutex
);
1354 struct slist_s
*list
= slist_append (cn_thread_list
, new);
1358 cn_thread_list
= list
;
1360 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1361 (pthread_t
*) new->tid
, fd
, addr
);
1363 log_write (_("new connection: tid=%p, fd=%i"),
1364 (pthread_t
*) new->tid
, fd
);
1367 rc
= GPG_ERR_ENOMEM
;
1370 pthread_cleanup_pop (1);
1376 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1377 pwmd_strerror (rc
));
1383 keepalive_thread (void *arg
)
1385 #ifndef HAVE_PTHREAD_CANCEL
1386 int *n
= xmalloc (sizeof (int));
1389 pthread_setspecific (signal_thread_key
, n
);
1393 #ifdef HAVE_PR_SET_NAME
1394 prctl (PR_SET_NAME
, "keepalive");
1396 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1400 int n
= config_get_integer ("global", "keepalive_interval");
1401 struct timeval tv
= { n
, 0 };
1402 #ifndef HAVE_PTHREAD_CANCEL
1405 sigusr2
= (int *) pthread_getspecific (signal_thread_key
);
1410 send_status_all (STATUS_KEEPALIVE
, NULL
);
1411 select (0, NULL
, NULL
, NULL
, &tv
);
1418 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1420 get_in_addr (struct sockaddr
*sa
)
1422 if (sa
->sa_family
== AF_INET
)
1423 return &(((struct sockaddr_in
*) sa
)->sin_addr
);
1425 return &(((struct sockaddr_in6
*) sa
)->sin6_addr
);
1429 tcp_accept_thread (void *arg
)
1431 int sockfd
= *(int *) arg
;
1432 #ifndef HAVE_PTHREAD_CANCEL
1433 int *n
= xmalloc (sizeof (int));
1436 pthread_setspecific (signal_thread_key
, n
);
1438 fcntl (sockfd
, F_SETFL
, O_NONBLOCK
);
1441 #ifdef HAVE_PR_SET_NAME
1442 prctl (PR_SET_NAME
, "tcp_accept");
1444 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1448 struct sockaddr_storage raddr
;
1449 socklen_t slen
= sizeof (raddr
);
1452 char s
[INET6_ADDRSTRLEN
];
1453 struct timeval tv
= { 0, ACCEPT_TIMEOUT
};
1454 #ifndef HAVE_PTHREAD_CANCEL
1457 sigusr2
= (int *) pthread_getspecific (signal_thread_key
);
1462 fd
= accept (sockfd
, (struct sockaddr
*) &raddr
, &slen
);
1465 if (errno
== EMFILE
|| errno
== ENFILE
)
1466 log_write ("accept(): %s",
1467 pwmd_strerror (gpg_error_from_syserror ()));
1468 else if (errno
!= EAGAIN
)
1470 if (!quit
) // probably EBADF
1471 log_write ("accept(): %s", strerror (errno
));
1476 #ifndef HAVE_PTHREAD_CANCEL
1477 select (0, NULL
, NULL
, NULL
, &tv
);
1485 inet_ntop (raddr
.ss_family
, get_in_addr ((struct sockaddr
*) &raddr
),
1487 (void) init_client (fd
, s
);
1488 n
= config_get_integer ("global", "tcp_wait");
1491 tv
.tv_sec
= (n
* 100000) / 100000;
1492 tv
.tv_usec
= (n
* 100000) % 100000;
1493 select (0, NULL
, NULL
, NULL
, &tv
);
1501 start_stop_tls_with_protocol (int ipv6
, int term
)
1503 struct addrinfo hints
, *servinfo
, *p
;
1504 int port
= config_get_integer ("global", "tcp_port");
1508 int *fd
= ipv6
? &tls6_fd
: &tls_fd
;
1510 if (term
|| config_get_boolean ("global", "enable_tcp") == 0)
1516 #ifdef HAVE_PTHREAD_CANCEL
1517 pthread_cancel (tls6_tid
);
1519 pthread_kill (tls6_tid
, SIGUSR2
);
1521 pthread_join (tls6_tid
, NULL
);
1524 shutdown (tls6_fd
, SHUT_RDWR
);
1534 #ifdef HAVE_PTHREAD_CANCEL
1535 pthread_cancel (tls_tid
);
1537 pthread_kill (tls_tid
, SIGUSR2
);
1539 pthread_join (tls_tid
, NULL
);
1542 shutdown (tls_fd
, SHUT_RDWR
);
1548 /* A client may still be connected. */
1549 if (!quit
&& x509_cred
!= NULL
)
1550 tls_deinit_params ();
1555 if ((ipv6
&& tls6_fd
!= -1) || (!ipv6
&& tls_fd
!= -1))
1558 memset (&hints
, 0, sizeof (hints
));
1559 hints
.ai_family
= ipv6
? AF_INET6
: AF_INET
;
1560 hints
.ai_socktype
= SOCK_STREAM
;
1561 hints
.ai_flags
= AI_PASSIVE
;
1562 snprintf (buf
, sizeof (buf
), "%i", port
);
1564 if ((n
= getaddrinfo (NULL
, buf
, &hints
, &servinfo
)) == -1)
1566 log_write ("getaddrinfo(): %s", gai_strerror (n
));
1570 for (n
= 0, p
= servinfo
; p
!= NULL
; p
= p
->ai_next
)
1574 if ((ipv6
&& p
->ai_family
!= AF_INET6
)
1575 || (!ipv6
&& p
->ai_family
!= AF_INET
))
1578 if ((*fd
= socket (p
->ai_family
, p
->ai_socktype
, p
->ai_protocol
)) == -1)
1580 log_write ("socket(): %s", strerror (errno
));
1584 if (setsockopt (*fd
, SOL_SOCKET
, SO_REUSEADDR
, &r
, sizeof (int)) == -1)
1586 log_write ("setsockopt(): %s",
1587 pwmd_strerror (gpg_error_from_syserror ()));
1588 freeaddrinfo (servinfo
);
1592 if (bind (*fd
, p
->ai_addr
, p
->ai_addrlen
) == -1)
1595 log_write ("bind(): %s",
1596 pwmd_strerror (gpg_error_from_syserror ()));
1604 freeaddrinfo (servinfo
);
1609 #if HAVE_DECL_SO_BINDTODEVICE != 0
1610 char *tmp
= config_get_string ("global", "tcp_interface");
1611 if (tmp
&& setsockopt (*fd
, SOL_SOCKET
, SO_BINDTODEVICE
, tmp
,
1612 strlen (tmp
)) == -1)
1614 log_write ("setsockopt(): %s",
1615 pwmd_strerror (gpg_error_from_syserror ()));
1623 if (x509_cred
== NULL
)
1625 rc
= tls_init_params ();
1630 if (listen (*fd
, 0) == -1)
1632 log_write ("listen(): %s", strerror (errno
));
1637 rc
= create_thread (tcp_accept_thread
, fd
, &tls6_tid
, 0);
1639 rc
= create_thread (tcp_accept_thread
, fd
, &tls_tid
, 0);
1643 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1644 pwmd_strerror (rc
));
1656 start_stop_tls_with_protocol (0, 1);
1669 start_stop_tls (int term
)
1671 char *s
= config_get_string ("global", "tcp_bind");
1677 if (!strcmp (s
, "any"))
1679 b
= start_stop_tls_with_protocol (0, term
);
1681 b
= start_stop_tls_with_protocol (1, term
);
1683 else if (!strcmp (s
, "ipv4"))
1684 b
= start_stop_tls_with_protocol (0, term
);
1685 else if (!strcmp (s
, "ipv6"))
1686 b
= start_stop_tls_with_protocol (1, term
);
1696 accept_thread (void *arg
)
1698 int sockfd
= *(int *) arg
;
1699 #ifndef HAVE_PTHREAD_CANCEL
1700 int *n
= xmalloc (sizeof (int));
1703 pthread_setspecific (signal_thread_key
, n
);
1705 fcntl (sockfd
, F_SETFL
, O_NONBLOCK
);
1708 #ifdef HAVE_PR_SET_NAME
1709 prctl (PR_SET_NAME
, "accept");
1711 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1715 socklen_t slen
= sizeof (struct sockaddr_un
);
1716 struct sockaddr_un raddr
;
1718 #ifndef HAVE_PTHREAD_CANCEL
1719 struct timeval tv
= { 0, ACCEPT_TIMEOUT
};
1720 int *sigusr2
= (int *) pthread_getspecific (signal_thread_key
);
1726 fd
= accept (sockfd
, (struct sockaddr
*) &raddr
, &slen
);
1729 if (errno
== EMFILE
|| errno
== ENFILE
)
1730 log_write ("accept(): %s",
1731 pwmd_strerror (gpg_error_from_syserror ()));
1732 else if (errno
!= EAGAIN
)
1734 if (!quit
) // probably EBADF
1735 log_write ("accept(): %s",
1736 pwmd_strerror (gpg_error_from_syserror ()));
1741 #ifndef HAVE_PTHREAD_CANCEL
1742 select (0, NULL
, NULL
, NULL
, &tv
);
1747 (void) init_client (fd
, NULL
);
1750 /* Just in case accept() failed for some reason other than EBADF */
1756 cache_timer_thread (void *arg
)
1758 #ifndef HAVE_PTHREAD_CANCEL
1759 int *n
= xmalloc (sizeof (int));
1762 pthread_setspecific (signal_thread_key
, n
);
1766 #ifdef HAVE_PR_SET_NAME
1767 prctl (PR_SET_NAME
, "cache timer");
1769 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1773 struct timeval tv
= { 1, 0 };
1774 #ifndef HAVE_PTHREAD_CANCEL
1777 n
= (int *) pthread_getspecific (signal_thread_key
);
1782 select (0, NULL
, NULL
, NULL
, &tv
);
1783 cache_adjust_timeout ();
1790 catch_sigabrt (int sig
)
1799 signal_loop (sigset_t sigset
)
1808 sigwait (&sigset
, &sig
);
1811 log_write (_("caught signal %i (%s)"), sig
, strsignal (sig
));
1816 pthread_cond_signal (&rcfile_cond
);
1819 // not really handled here.
1820 catch_sigabrt (SIGABRT
);
1823 log_write (_("clearing file cache"));
1825 send_status_all (STATUS_CACHE
, NULL
);
1844 log_write ("Caught SIGSEGV. Exiting.");
1845 #ifdef HAVE_BACKTRACE
1846 BACKTRACE (__FUNCTION__
);
1852 waiting_for_exit (void *arg
)
1855 #ifndef HAVE_PTHREAD_CANCEL
1856 int *n
= xmalloc (sizeof (int));
1859 pthread_setspecific (signal_thread_key
, n
);
1863 #ifdef HAVE_PR_SET_NAME
1864 prctl (PR_SET_NAME
, "exiting");
1866 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1867 log_write (_("waiting for all clients to disconnect"));
1868 MUTEX_LOCK (&quit_mutex
);
1869 pthread_cleanup_push (cleanup_mutex_cb
, &quit_mutex
);
1876 MUTEX_LOCK (&cn_mutex
);
1877 n
= slist_length (cn_thread_list
);
1878 MUTEX_UNLOCK (&cn_mutex
);
1882 #ifndef HAVE_PTHREAD_CANCEL
1883 int *s
= (int *) pthread_getspecific (signal_thread_key
);
1890 log_write (_("%i clients remain"), n
);
1894 INIT_TIMESPEC (SIG_TIMEOUT
, ts
);
1895 pthread_cond_timedwait (&quit_cond
, &quit_mutex
, &ts
);
1898 kill (getpid (), SIGQUIT
);
1899 pthread_cleanup_pop (1);
1904 server_loop (int sockfd
, char **socketpath
)
1906 pthread_t accept_tid
;
1907 pthread_t cache_timeout_tid
;
1908 int cancel_timeout_thread
= 0, cancel_accept_thread
= 0;
1909 int cancel_keepalive_thread
= 0;
1916 sigemptyset (&sigset
);
1919 sigaddset (&sigset
, SIGTERM
);
1920 sigaddset (&sigset
, SIGINT
);
1922 /* Clears the file cache. */
1923 sigaddset (&sigset
, SIGUSR1
);
1925 /* Configuration file reloading. */
1926 sigaddset (&sigset
, SIGHUP
);
1928 /* For exiting cleanly. */
1929 sigaddset (&sigset
, SIGQUIT
);
1931 #ifndef HAVE_PTHREAD_CANCEL
1933 The socket, cache and rcfile threads use this signal when
1934 pthread_cancel() is unavailable. Prevent the main thread from
1935 catching this signal from another process.
1937 sigaddset (&sigset
, SIGUSR2
);
1940 /* Clears the cache and exits when something bad happens. */
1941 signal (SIGABRT
, catch_sigabrt
);
1942 sigaddset (&sigset
, SIGABRT
);
1943 sigprocmask (SIG_BLOCK
, &sigset
, NULL
);
1945 #ifndef HAVE_PTHREAD_CANCEL
1946 /* Remove this signal from the watched signals in signal_loop(). */
1947 sigdelset (&sigset
, SIGUSR2
);
1950 /* Ignored everywhere. When a client disconnects abnormally this signal
1951 * gets raised. It isn't needed though because client_thread() will check
1952 * for rcs even after the client disconnects. */
1953 signal (SIGPIPE
, SIG_IGN
);
1955 /* Can show a backtrace of the stack in the log. */
1956 signal (SIGSEGV
, catchsig
);
1959 /* Needs to be done after the fork(). */
1960 if (!start_stop_tls (0))
1967 pthread_mutex_init (&quit_mutex
, NULL
);
1968 pthread_cond_init (&quit_cond
, NULL
);
1969 log_write (_("%s started for user %s"), PACKAGE_STRING
, get_username ());
1972 if (config_get_boolean ("global", "enable_tcp"))
1973 log_write (_("Listening on %s and TCP port %i"), *socketpath
,
1974 config_get_integer ("global", "tcp_port"));
1976 log_write (_("Listening on %s"), *socketpath
);
1978 log_write (_("Listening on %s"), *socketpath
);
1981 rc
= create_thread (keepalive_thread
, NULL
, &keepalive_tid
, 0);
1984 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1985 pwmd_strerror (rc
));
1989 cancel_keepalive_thread
= 1;
1990 rc
= create_thread (reload_rcfile_thread
, NULL
, &rcfile_tid
, 0);
1993 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1994 pwmd_strerror (rc
));
1998 rc
= create_thread (cache_timer_thread
, NULL
, &cache_timeout_tid
, 0);
2001 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2002 pwmd_strerror (rc
));
2006 cancel_timeout_thread
= 1;
2007 rc
= create_thread (accept_thread
, &sockfd
, &accept_tid
, 0);
2010 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2011 pwmd_strerror (rc
));
2015 cancel_accept_thread
= 1;
2017 signal_loop (sigset
);
2023 * We're out of the main server loop. This happens when a signal was sent
2024 * to terminate the daemon. We'll wait for all clients to disconnect
2025 * before exiting but exit immediately if another termination signal is
2028 if (cancel_accept_thread
)
2030 #ifdef HAVE_PTHREAD_CANCEL
2031 int n
= pthread_cancel (accept_tid
);
2033 int n
= pthread_kill (accept_tid
, SIGUSR2
);
2036 pthread_join (accept_tid
, NULL
);
2042 shutdown (sockfd
, SHUT_RDWR
);
2044 unlink (*socketpath
);
2045 xfree (*socketpath
);
2047 MUTEX_LOCK (&cn_mutex
);
2048 n
= slist_length (cn_thread_list
);
2049 MUTEX_UNLOCK (&cn_mutex
);
2055 rc
= create_thread (waiting_for_exit
, NULL
, &tid
, 0);
2058 if (signal_loop (sigset
))
2060 log_write (_("Received second termination request. Exiting."));
2061 #ifdef HAVE_PTHREAD_CANCEL
2062 pthread_cancel (tid
);
2064 pthread_kill (tid
, SIGUSR2
);
2066 pthread_join (tid
, NULL
);
2070 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
2071 pwmd_strerror (rc
));
2074 if (cancel_timeout_thread
)
2076 #ifdef HAVE_PTHREAD_CANCEL
2077 pthread_cancel (cache_timeout_tid
);
2079 pthread_kill (cache_timeout_tid
, SIGUSR2
);
2081 pthread_join (cache_timeout_tid
, NULL
);
2084 if (cancel_keepalive_thread
)
2086 #ifdef HAVE_PTHREAD_CANCEL
2087 pthread_cancel (keepalive_tid
);
2089 pthread_kill (keepalive_tid
, SIGUSR2
);
2091 pthread_join (keepalive_tid
, NULL
);
2094 cleanup_all_clients (0);
2099 pthread_cond_destroy (&quit_cond
);
2100 pthread_mutex_destroy (&quit_mutex
);
2101 return segv
? EXIT_FAILURE
: EXIT_SUCCESS
;;
2108 ("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
2112 /* This is called from cache.c:clear_once(). See
2113 * command.c:clearcache_command() for details about lock checking.
2116 free_cache_data (file_cache_t
* cache
)
2118 gpg_error_t rc
= GPG_ERR_NO_DATA
;
2120 struct client_thread_s
*found
= NULL
;
2127 MUTEX_LOCK (&cn_mutex
);
2128 pthread_cleanup_push (cleanup_mutex_cb
, &cn_mutex
);
2129 t
= slist_length (cn_thread_list
);
2131 for (i
= 0; i
< t
; i
++)
2133 struct client_thread_s
*thd
= slist_nth_data (cn_thread_list
, i
);
2138 if (!memcmp (thd
->cl
->md5file
, cache
->filename
,
2139 sizeof (cache
->filename
)))
2141 if (pthread_equal (pthread_self (), thd
->tid
))
2148 /* Continue trying to find a client who has the same file open and
2149 * also has a lock. */
2150 rc
= cache_lock_mutex (thd
->cl
->ctx
, thd
->cl
->md5file
, -1, 0, -1);
2160 if (self
&& (!rc
|| rc
== GPG_ERR_NO_DATA
))
2161 rc
= cache_lock_mutex (found
->cl
->ctx
, found
->cl
->md5file
, -1, 0, -1);
2163 if (exiting
|| !rc
|| rc
== GPG_ERR_NO_DATA
)
2165 free_cache_data_once (cache
->data
);
2167 cache
->defer_clear
= 0;
2168 cache
->timeout
= -1;
2171 cache_unlock_mutex (found
->cl
->md5file
, 0);
2177 cache
->defer_clear
= 1;
2179 pthread_cleanup_pop (1);
2185 convert_v2_datafile (const char *filename
, const char *cipher
,
2186 const char *keyfile
, const char *keygrip
,
2187 const char *sign_keygrip
, int nopass
,
2188 const char *outfile
, const char *keyparam
,
2189 unsigned long s2k_count
, uint64_t iterations
)
2194 struct crypto_s
*crypto
= NULL
;
2200 if (outfile
[0] == '-' && outfile
[1] == 0)
2203 log_write (_("Converting version 2 data file \"%s\" ..."), filename
);
2204 if (access (filename
, R_OK
) == -1)
2206 log_write ("%s: %s", filename
,
2207 pwmd_strerror (gpg_error_from_syserror ()));
2213 log_write (_("Using passphrase file \"%s\" for decryption ..."),
2215 if (access (keyfile
, R_OK
) == -1)
2217 log_write ("%s: %s", keyfile
,
2218 pwmd_strerror (gpg_error_from_syserror ()));
2223 rc
= read_v2_datafile (filename
, keyfile
, &data
, &datalen
, &ver
, &algo
);
2226 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
2232 algo
= cipher_string_to_gcrypt (cipher
);
2235 rc
= GPG_ERR_CIPHER_ALGO
;
2242 xmlDocPtr doc
= parse_doc (data
, datalen
);
2246 rc
= GPG_ERR_BAD_DATA
;
2250 rc
= convert_pre_212_elements (doc
);
2255 xmlDocDumpFormatMemory (doc
, (xmlChar
**) & data
, (int *) &datalen
,
2258 rc
= GPG_ERR_ENOMEM
;
2266 rc
= init_client_crypto (&crypto
);
2269 memcpy (&crypto
->save
.hdr
, &crypto
->hdr
, sizeof (file_header_t
));
2270 crypto
->save
.hdr
.flags
= set_cipher_flag (crypto
->save
.hdr
.flags
, algo
);
2271 crypto
->save
.s2k_count
= s2k_count
;
2272 crypto
->save
.hdr
.iterations
= iterations
;
2276 rc
= export_common (NULL
, 0, crypto
, data
, datalen
, outfile
, keyfile
,
2277 &key
, &keylen
, 0, 0);
2282 rc
= agent_set_pinentry_options (crypto
->agent
);
2284 rc
= agent_export_common (crypto
, keygrip
, sign_keygrip
, nopass
,
2285 data
, datalen
, outfile
, keyparam
,
2286 no_passphrase_file
? NULL
: keyfile
);
2290 log_write (_("Output written to \"%s\"."), outfile
);
2300 cleanup_crypto (&crypto
);
2303 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
2308 usage (const char *pn
, int status
)
2310 FILE *fp
= status
== EXIT_FAILURE
? stderr
: stdout
;
2312 fprintf (fp
, _("Usage: %s [OPTIONS] [file1] [...]\n"
2313 " -f, --rcfile=filename load the specfied configuration file\n"
2314 " (~/.pwmd/config)\n"
2315 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2317 " --no-agent disable use of gpg-agent\n"
2319 " -n, --no-fork run as a foreground process\n"
2320 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2321 " --ignore ignore file errors during startup\n"
2322 " --debug-level=keywords log protocol output (see manual for details)\n"
2323 " -o, --outfile=filename output file when importing or converting\n"
2324 " -C, --convert=filename convert a version 2 data file to version 3\n"
2325 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2326 " -k, --passphrase-file=file for use when importing or converting\n"
2327 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2329 " --no-passphrase when importing or converting\n"
2330 " --keygrip=hex public key to use when encrypting\n"
2331 " --sign-keygrip=hex private key to use when signing\n"
2332 " --keyparam=s-exp custom key parameters to use (RSA-2048)\n"
2333 " --cipher=string encryption cipher (aes256)\n"
2334 " --iterations=N cipher iteration count (N+1)\n"
2335 " --s2k-count=N hash iteration count (>65536, calibrated)\n"
2336 " --help this help text\n"
2337 " --version show version and compile time features\n"),
2343 main (int argc
, char *argv
[])
2346 struct sockaddr_un addr
;
2348 char *socketpath
= NULL
, *socketdir
, *socketname
= NULL
;
2349 char *socketarg
= NULL
;
2350 char *datadir
= NULL
;
2353 char **cache_push
= NULL
;
2354 char *import
= NULL
, *keygrip
= NULL
, *sign_keygrip
= NULL
;
2355 char *keyparam
= NULL
;
2356 int estatus
= EXIT_FAILURE
;
2358 char *outfile
= NULL
;
2361 int show_version
= 0;
2363 int no_passphrase
= 0;
2365 char *convertfile
= NULL
;
2366 char *cipher
= NULL
;
2367 char *keyfile
= NULL
;
2368 unsigned long s2k_count
= 0;
2369 uint64_t iterations
= 0;
2371 char *debug_level_opt
= NULL
;
2373 /* Must maintain the same order as longopts[] */
2375 { OPT_VERSION
, OPT_HELP
, OPT_NO_AGENT
,
2376 OPT_DEBUG_LEVEL
, OPT_HOMEDIR
, OPT_NO_FORK
, OPT_DISABLE_DUMP
, OPT_IGNORE
,
2377 OPT_RCFILE
, OPT_CONVERT
, OPT_PASSPHRASE_FILE
, OPT_IMPORT
, OPT_OUTFILE
,
2378 OPT_NO_PASSPHRASE_FILE
, OPT_KEYGRIP
, OPT_SIGN_KEYGRIP
, OPT_KEYPARAM
,
2379 OPT_CIPHER
, OPT_ITERATIONS
, OPT_S2K_COUNT
, OPT_NO_PASSPHRASE
2381 const char *optstring
= "nf:C:k:I:o:";
2382 const struct option longopts
[] = {
2383 {"version", no_argument
, 0, 0},
2384 {"help", no_argument
, 0, 0},
2385 {"no-agent", no_argument
, 0, 0},
2386 {"debug-level", required_argument
, 0, 0},
2387 {"homedir", required_argument
, 0, 0},
2388 {"no-fork", no_argument
, 0, 'n'},
2389 {"disable_dump", no_argument
, 0, 0},
2390 {"ignore", no_argument
, 0, 0},
2391 {"rcfile", required_argument
, 0, 'f'},
2392 {"convert", required_argument
, 0, 'C'},
2393 {"passphrase-file", required_argument
, 0, 'k'},
2394 {"import", required_argument
, 0, 'I'},
2395 {"outfile", required_argument
, 0, 'o'},
2396 {"no-passphrase-file", no_argument
, 0, 0},
2397 {"keygrip", required_argument
, 0, 0},
2398 {"sign-keygrip", required_argument
, 0, 0},
2399 {"keyparam", required_argument
, 0, 0},
2400 {"cipher", required_argument
, 0, 0},
2401 {"cipher-iterations", required_argument
, 0, 0},
2402 {"s2k-count", required_argument
, 0, 0},
2403 {"no-passphrase", no_argument
, 0, 0},
2408 #ifdef HAVE_SETRLIMIT
2411 rl
.rlim_cur
= rl
.rlim_max
= 0;
2413 if (setrlimit (RLIMIT_CORE
, &rl
) != 0)
2414 err (EXIT_FAILURE
, "setrlimit()");
2419 setlocale (LC_ALL
, "");
2420 bindtextdomain ("pwmd", LOCALEDIR
);
2421 textdomain ("pwmd");
2429 if (setup_crypto ())
2430 exit (EXIT_FAILURE
);
2433 gnutls_global_set_mem_functions (xmalloc
, xmalloc
, secure_mem_check
,
2435 gnutls_global_init ();
2436 gnutls_global_set_log_function (tls_log
);
2437 gnutls_global_set_log_level (1);
2441 xmlMemSetup (xfree
, xmalloc
, xrealloc
, str_dup
);
2452 getopt_long (argc
, argv
, optstring
, longopts
, &optindex
)) != -1)
2460 convertfile
= optarg
;
2475 rcfile
= str_dup (optarg
);
2478 usage (argv
[0], EXIT_FAILURE
);
2492 case OPT_DEBUG_LEVEL
:
2493 debug_level_opt
= optarg
;
2496 homedir
= str_dup (optarg
);
2501 case OPT_DISABLE_DUMP
:
2508 rcfile
= str_dup (optarg
);
2511 convertfile
= optarg
;
2513 case OPT_PASSPHRASE_FILE
:
2522 case OPT_NO_PASSPHRASE_FILE
:
2523 no_passphrase_file
= 1;
2528 case OPT_SIGN_KEYGRIP
:
2529 sign_keygrip
= optarg
;
2537 case OPT_ITERATIONS
:
2538 iterations
= strtoull (optarg
, NULL
, 10);
2541 s2k_count
= strtoul (optarg
, NULL
, 10);
2543 case OPT_NO_PASSPHRASE
:
2555 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013\n"
2557 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2558 "Compile time features:\n%s"), PACKAGE_STRING
,
2561 "+PWMD_HOMEDIR=" PWMD_HOMEDIR
"\n"
2599 exit (EXIT_SUCCESS
);
2604 homedir
= str_dup(PWMD_HOMEDIR
);
2606 homedir
= str_asprintf ("%s/.pwmd", get_home_dir ());
2609 if (mkdir (homedir
, 0700) == -1 && errno
!= EEXIST
)
2610 err (EXIT_FAILURE
, "%s", homedir
);
2612 snprintf (buf
, sizeof (buf
), "%s/data", homedir
);
2613 if (mkdir (buf
, 0700) == -1 && errno
!= EEXIST
)
2614 err (EXIT_FAILURE
, "%s", buf
);
2616 datadir
= str_dup (buf
);
2617 pthread_mutexattr_t attr
;
2618 pthread_mutexattr_init (&attr
);
2619 pthread_mutexattr_settype (&attr
, PTHREAD_MUTEX_RECURSIVE
);
2620 pthread_mutex_init (&rcfile_mutex
, &attr
);
2621 pthread_cond_init (&rcfile_cond
, NULL
);
2622 pthread_mutex_init (&cn_mutex
, &attr
);
2623 pthread_mutexattr_destroy (&attr
);
2624 pthread_key_create (&last_error_key
, free_key
);
2625 #ifndef HAVE_PTHREAD_CANCEL
2626 pthread_key_create (&signal_thread_key
, free_key
);
2630 rcfile
= str_asprintf ("%s/config", homedir
);
2632 global_config
= config_parse (rcfile
);
2634 exit (EXIT_FAILURE
);
2638 if (debug_level_opt
)
2639 debug_level
= str_split (debug_level_opt
, ",", 0);
2641 x
= config_get_int_param (global_config
, "global", "priority", &exists
);
2642 if (exists
&& x
!= atoi(INVALID_PRIORITY
))
2645 if (setpriority (PRIO_PROCESS
, 0, x
) == -1)
2647 log_write ("setpriority(): %s",
2648 pwmd_strerror (gpg_error_from_syserror ()));
2652 #ifdef HAVE_MLOCKALL
2653 if (disable_mlock
== 0 && mlockall (MCL_CURRENT
| MCL_FUTURE
) == -1)
2655 log_write ("mlockall(): %s",
2656 pwmd_strerror (gpg_error_from_syserror ()));
2661 rc
= cache_init (free_cache_data
);
2664 log_write ("pwmd: ERR %i: %s", rc
,
2665 gpg_err_code (rc
) == GPG_ERR_UNKNOWN_VERSION
2666 ? _("incompatible version: 2.1.0 or later required")
2667 : pwmd_strerror (rc
));
2672 s2k_count
= config_get_ulong (NULL
, "s2k_count");
2677 usage (argv
[0], EXIT_FAILURE
);
2679 estatus
= convert_v2_datafile (convertfile
, cipher
, keyfile
, keygrip
,
2680 sign_keygrip
, no_passphrase
, outfile
,
2681 keyparam
, s2k_count
, iterations
);
2682 config_free (global_config
);
2689 if (!outfile
|| !*outfile
)
2690 usage (argv
[0], EXIT_FAILURE
);
2692 if (outfile
&& outfile
[0] == '-' && outfile
[1] == 0)
2695 estatus
= xml_import (import
, outfile
, keygrip
, sign_keygrip
, keyfile
,
2696 no_passphrase
, cipher
, keyparam
, s2k_count
,
2698 config_free (global_config
);
2703 p
= config_get_string ("global", "socket_path");
2705 p
= str_asprintf ("%s/socket", homedir
);
2707 socketarg
= expand_homedir (p
);
2711 disable_list_and_dump
= config_get_boolean ("global",
2712 "disable_list_and_dump");
2714 disable_list_and_dump
= secure
;
2716 cache_push
= config_get_list ("global", "cache_push");
2718 while (optind
< argc
)
2720 if (strv_printf (&cache_push
, "%s", argv
[optind
++]) == 0)
2721 errx (EXIT_FAILURE
, "%s", pwmd_strerror (GPG_ERR_ENOMEM
));
2724 if (strchr (socketarg
, '/') == NULL
)
2726 socketdir
= getcwd (buf
, sizeof (buf
));
2727 socketname
= str_dup (socketarg
);
2728 socketpath
= str_asprintf ("%s/%s", socketdir
, socketname
);
2732 socketname
= str_dup (strrchr (socketarg
, '/'));
2734 socketarg
[strlen (socketarg
) - strlen (socketname
) - 1] = 0;
2735 socketdir
= str_dup (socketarg
);
2736 socketpath
= str_asprintf ("%s/%s", socketdir
, socketname
);
2739 if (chdir (datadir
))
2741 log_write ("%s: %s", datadir
,
2742 pwmd_strerror (gpg_error_from_syserror ()));
2743 unlink (socketpath
);
2748 * Set the cache entry for a file. Prompts for the password.
2752 struct crypto_s
*crypto
= NULL
;
2753 gpg_error_t rc
= init_client_crypto (&crypto
);
2757 estatus
= EXIT_FAILURE
;
2764 rc
= agent_set_pinentry_options (crypto
->agent
);
2767 estatus
= EXIT_FAILURE
;
2773 for (opt
= 0; cache_push
[opt
]; opt
++)
2775 if (!do_cache_push (cache_push
[opt
], crypto
) && !force
)
2777 strv_free (cache_push
);
2779 estatus
= EXIT_FAILURE
;
2780 cleanup_crypto (&crypto
);
2784 cleanup_crypto_stage1 (crypto
);
2789 (void) kill_scd (crypto
->agent
);
2792 cleanup_crypto (&crypto
);
2793 strv_free (cache_push
);
2794 log_write (!nofork
? _("Done. Daemonizing...") :
2795 _("Done. Waiting for connections..."));
2798 config_clear_keys ();
2801 * bind() doesn't like the full pathname of the socket or any non alphanum
2802 * characters so change to the directory where the socket is wanted then
2803 * create it then change to datadir.
2805 if (chdir (socketdir
))
2807 log_write ("%s: %s", socketdir
,
2808 pwmd_strerror (gpg_error_from_syserror ()));
2814 if ((sockfd
= socket (PF_UNIX
, SOCK_STREAM
, 0)) == -1)
2816 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_syserror ()));
2820 addr
.sun_family
= AF_UNIX
;
2821 snprintf (addr
.sun_path
, sizeof (addr
.sun_path
), "%s", socketname
);
2823 if (bind (sockfd
, (struct sockaddr
*) &addr
, sizeof (struct sockaddr
)) ==
2826 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_syserror ()));
2828 if (errno
== EADDRINUSE
)
2829 log_write (_("Either there is another pwmd running or '%s' is a \n"
2830 "stale socket. Please remove it manually."), socketpath
);
2836 char *t
= config_get_string ("global", "socket_perms");
2842 mode
= strtol (t
, NULL
, 8);
2846 if (chmod (socketname
, mode
) == -1)
2848 log_write ("%s: %s", socketname
,
2849 pwmd_strerror (gpg_error_from_syserror ()));
2859 xfree (--socketname
);
2861 if (chdir (datadir
))
2863 log_write ("%s: %s", datadir
,
2864 pwmd_strerror (gpg_error_from_syserror ()));
2871 if (listen (sockfd
, 0) == -1)
2873 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_syserror ()));
2884 log_write ("fork(): %s",
2885 pwmd_strerror (gpg_error_from_syserror ()));
2894 _exit (EXIT_SUCCESS
);
2898 pthread_key_create (&thread_name_key
, free_key
);
2899 pthread_setspecific (thread_name_key
, str_dup ("main"));
2900 estatus
= server_loop (sockfd
, &socketpath
);
2903 if (socketpath
&& do_unlink
)
2905 unlink (socketpath
);
2911 gnutls_global_deinit ();
2915 #ifdef HAVE_PTHREAD_CANCEL
2916 pthread_cancel (rcfile_tid
);
2918 pthread_kill (rcfile_tid
, SIGUSR2
);
2919 pthread_cond_signal (&rcfile_cond
);
2921 pthread_join (rcfile_tid
, NULL
);
2924 pthread_cond_destroy (&rcfile_cond
);
2925 pthread_mutex_destroy (&rcfile_mutex
);
2926 pthread_key_delete (last_error_key
);
2927 pthread_key_delete (thread_name_key
);
2928 #ifndef HAVE_PTHREAD_CANCEL
2929 pthread_key_delete (signal_thread_key
);
2933 config_free (global_config
);
2936 xfree (home_directory
);
2938 xmlCleanupParser ();
2939 xmlCleanupGlobals ();
2941 if (estatus
== EXIT_SUCCESS
)
2942 log_write (_("pwmd exiting normally"));
2945 #if defined(DEBUG) && !defined(MEM_DEBUG)