Test for error from cache_iscached().
[pwmd.git] / src / pwmd.c
blob0e6969cd31384a1205895c61c36e7a8ece71874f
1 /*
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/>.
20 #ifdef HAVE_CONFIG_H
21 #include <config.h>
22 #endif
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <unistd.h>
27 #include <err.h>
28 #include <ctype.h>
29 #include <string.h>
30 #include <sys/socket.h>
31 #include <sys/un.h>
32 #include <signal.h>
33 #include <stdarg.h>
34 #include <string.h>
35 #include <sys/wait.h>
36 #include <fcntl.h>
37 #include <pwd.h>
38 #include <grp.h>
39 #include <pthread.h>
40 #include <sys/mman.h>
41 #include <termios.h>
42 #include <assert.h>
43 #include <syslog.h>
44 #include <netinet/in.h>
45 #include <arpa/inet.h>
46 #include <netdb.h>
47 #include <sys/time.h>
48 #include <sys/resource.h>
49 #include <setjmp.h>
50 #include <errno.h>
52 #ifdef TM_IN_SYS_TIME
53 #include <sys/time.h>
54 #else
55 #include <time.h>
56 #endif
58 #ifdef HAVE_LIMITS_H
59 #include <limits.h>
60 #endif
62 #ifdef HAVE_GETOPT_LONG
63 #ifdef HAVE_GETOPT_H
64 #include <getopt.h>
65 #endif
66 #else
67 #include "getopt_long.h"
68 #endif
70 #ifdef HAVE_PR_SET_NAME
71 #include <sys/prctl.h>
72 #endif
74 #include "pwmd-error.h"
75 #include <gcrypt.h>
77 #include "util-misc.h"
78 #include "mem.h"
79 #include "xml.h"
80 #include "common.h"
81 #include "commands.h"
82 #include "cache.h"
83 #include "util-string.h"
84 #include "mutex.h"
85 #include "rcfile.h"
86 #include "crypto.h"
87 #include "convert.h"
88 #include "pinentry.h"
90 /* In tenths of a second. */
91 #define SIG_TIMEOUT 1
93 /* For (tcp_)accept_thread (usec). */
94 #define ACCEPT_TIMEOUT 30000
96 static int quit;
97 static int exiting;
98 static int cmdline;
99 static jmp_buf jmp;
100 static int nofork;
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;
108 #endif
110 #ifdef WITH_GNUTLS
111 static int tls_fd;
112 static int tls6_fd;
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);
119 #endif
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; \
129 sigset_t sigset; \
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); \
138 } while (0)
140 static void
141 catch_thread_signal (int sig, siginfo_t *info, void *ctx)
143 int *n = (int *) pthread_getspecific (signal_thread_key);
145 *n = 1;
146 pthread_setspecific (signal_thread_key, n);
148 #endif
150 static void
151 cache_push_from_rcfile ()
153 struct crypto_s *crypto = NULL;
154 char **cache_push;
155 gpg_error_t rc = init_client_crypto (&crypto);
157 if (rc)
159 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
160 return;
163 #ifdef WITH_AGENT
164 if (use_agent)
166 rc = set_agent_option (crypto->agent, "pinentry-mode", "error");
167 if (rc)
169 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
170 return;
173 #endif
175 cache_push = config_get_list ("global", "cache_push");
176 if (cache_push)
178 char **p;
180 for (p = cache_push; *p; p++)
182 (void) do_cache_push (*p, crypto);
183 cleanup_crypto_stage1 (crypto);
186 strv_free (cache_push);
189 #ifdef WITH_AGENT
190 (void) kill_scd (crypto->agent);
191 #endif
192 cleanup_crypto (&crypto);
195 static void
196 setup_logging ()
198 int n = config_get_boolean ("global", "enable_logging");
200 if (n)
202 char *p = config_get_string ("global", "log_path");
204 xfree (logfile);
205 logfile = expand_homedir (p);
206 xfree (p);
208 else
210 xfree (logfile);
211 logfile = NULL;
214 log_syslog = config_get_boolean ("global", "syslog");
215 if (log_syslog == 1)
216 openlog ("pwmd", LOG_NDELAY | LOG_PID, LOG_DAEMON);
219 static void *
220 reload_rcfile_thread (void *arg)
222 #ifndef HAVE_PTHREAD_CANCEL
223 int *n = xmalloc (sizeof (int));
225 *n = 0;
226 pthread_setspecific (signal_thread_key, n);
227 INIT_THREAD_SIGNAL;
228 #endif
230 #ifdef HAVE_PR_SET_NAME
231 prctl (PR_SET_NAME, "reload rcfile");
232 #endif
233 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
234 MUTEX_LOCK (&rcfile_mutex);
235 pthread_cleanup_push (cleanup_mutex_cb, &rcfile_mutex);
237 for (;;)
239 struct slist_s *config;
240 char **users;
241 int b = disable_list_and_dump;
242 int exists;
243 int require_save_key = config_get_bool_param (global_config, "global",
244 "require_save_key",
245 &exists);
246 #ifdef WITH_GNUTLS
247 int tcp_require_key = config_get_bool_param (global_config, "global",
248 "tcp_require_key",
249 &exists);
250 #endif
252 pthread_cond_wait (&rcfile_cond, &rcfile_mutex);
253 #ifndef HAVE_PTHREAD_CANCEL
254 int *n = (int *) pthread_getspecific (signal_thread_key);
255 if (*n)
256 break;
257 #endif
259 users = config_get_list ("global", "allowed");
260 log_write (_("reloading configuration file '%s'"), rcfile);
261 config = config_parse (rcfile);
262 if (config)
264 config_free (global_config);
265 global_config = config;
266 setup_logging ();
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");
274 #ifdef WITH_GNUTLS
275 if (config_get_bool_param (global_config, "global", "tcp_require_key",
276 &exists) && exists)
277 tcp_require_key = 1;
279 config_set_bool_param (&global_config, "global", "tcp_require_key",
280 tcp_require_key ? "true" : "false");
281 #endif
282 char *tmp = strv_join (",", users);
283 config_set_list_param (&global_config, "global", "allowed", tmp);
284 xfree (tmp);
285 strv_free (users);
286 #ifdef WITH_GNUTLS
287 /* Kill existing listening threads since the configured listening
288 * protocols may have changed. */
289 start_stop_tls (1);
290 start_stop_tls (0);
291 #endif
294 pthread_cleanup_pop (1);
295 return NULL;
298 gpg_error_t
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)
304 e = gpg_error (e);
306 if (client)
307 client->last_rc = e;
309 if (!e)
310 return assuan_process_done (ctx, 0);
312 if (!ctx)
314 log_write ("ERR %i: %s", e, pwmd_strerror (e));
315 return e;
318 if (client && gpg_err_code (e) == GPG_ERR_BAD_DATA)
320 xmlErrorPtr xe = client->xml_error;
322 if (!xe)
323 xe = xmlGetLastError ();
324 if (xe)
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,
334 xe ? xe->message :
335 NULL));
337 if (xe == client->xml_error)
338 xmlResetError (xe);
339 else
340 xmlResetLastError ();
342 client->xml_error = NULL;
343 return e;
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,
352 const char *msg)
354 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
355 int i, t;
356 int match = 0;
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)
367 match = 1;
368 break;
371 if (!strcasecmp (debug_level[i], (char *) "ctx")
372 && cat == ASSUAN_LOG_CTX)
374 match = 1;
375 break;
378 if (!strcasecmp (debug_level[i], (char *) "engine")
379 && cat == ASSUAN_LOG_ENGINE)
381 match = 1;
382 break;
385 if (!strcasecmp (debug_level[i], (char *) "data")
386 && cat == ASSUAN_LOG_DATA)
388 match = 1;
389 break;
392 if (!strcasecmp (debug_level[i], (char *) "sysio")
393 && cat == ASSUAN_LOG_SYSIO)
395 match = 1;
396 break;
399 if (!strcasecmp (debug_level[i], (char *) "control")
400 && cat == ASSUAN_LOG_CONTROL)
402 match = 1;
403 break;
407 if (match && msg)
409 if (logfile)
411 int fd;
413 if ((fd =
414 open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600)) == -1)
415 warn ("%s", logfile);
416 else
418 pthread_cleanup_push (cleanup_fd_cb, &fd);
419 write (fd, msg, strlen (msg));
420 pthread_cleanup_pop (1);
424 if (nofork)
426 fprintf (stderr, "%s%s", data ? (char *) data : "", msg);
427 fflush (stderr);
431 pthread_cleanup_pop (1);
432 return match;
435 void
436 log_write (const char *fmt, ...)
438 char *args, *line;
439 va_list ap;
440 struct tm *tm;
441 time_t now;
442 char tbuf[21];
443 int fd = -1;
444 char *name = NULL;
445 char buf[255];
446 pthread_t tid = pthread_self ();
447 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
449 if ((!logfile && !isatty (STDERR_FILENO) && !log_syslog) || !fmt)
450 return;
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);
462 va_start (ap, fmt);
464 if (str_vasprintf (&args, fmt, ap) != -1)
466 if (cmdline)
468 pthread_cleanup_push (xfree, args);
469 fprintf (stderr, "%s\n", args);
470 fflush (stderr);
471 pthread_cleanup_pop (1);
473 else
475 pthread_cleanup_push (xfree, args);
476 name = pthread_getspecific (thread_name_key);
477 snprintf (buf, sizeof (buf), "%s(%p): ", name ? name : _("unknown"),
478 (pthread_t *) tid);
479 name = buf;
481 if (!cmdline && log_syslog && !nofork)
482 syslog (LOG_INFO, "%s%s", name, args);
484 time (&now);
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);
494 if (line)
496 pthread_cleanup_push (xfree, line);
497 if (logfile && fd != -1)
499 write (fd, line, strlen (line));
500 fsync (fd);
503 if (nofork)
505 fprintf (stdout, "%s", line);
506 fflush (stdout);
509 pthread_cleanup_pop (1);
514 va_end (ap);
515 pthread_cleanup_pop (1);
516 pthread_cleanup_pop (0);
517 pthread_mutex_unlock (&m);
520 #ifdef WITH_GNUTLS
521 static int
522 secure_mem_check (const void *arg)
524 return 1;
526 #endif
528 static gpg_error_t
529 setup_crypto ()
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);
542 return 0;
545 #ifdef HAVE_GETGRNAM_R
546 static gpg_error_t
547 do_validate_peer (struct client_s *cl, assuan_peercred_t * peer)
549 char **users;
550 int allowed = 0;
551 gpg_error_t rc;
553 rc = assuan_get_peercred (cl->ctx, peer);
554 if (rc)
555 return rc;
557 users = config_get_list ("global", "allowed");
558 if (users)
560 for (char **p = users; *p; p++)
562 struct passwd pw, *result;
563 struct group gr, *gresult;
564 char *buf;
566 if (*(*p) == '@')
568 size_t len = sysconf (_SC_GETGR_R_SIZE_MAX);
570 if (len == -1)
571 len = 16384;
573 buf = xmalloc (len);
574 if (!buf)
576 strv_free (users);
577 return GPG_ERR_ENOMEM;
580 if (!getgrnam_r (*(p) + 1, &gr, buf, len, &gresult) && gresult)
582 if (gresult->gr_gid == (*peer)->gid)
584 xfree (buf);
585 allowed = 1;
586 break;
589 len = sysconf (_SC_GETPW_R_SIZE_MAX);
590 if (len == -1)
591 len = 16384;
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)
600 xfree (buf);
601 allowed = 1;
602 break;
607 xfree (tbuf);
609 if (allowed)
610 break;
613 else
615 size_t len = sysconf (_SC_GETPW_R_SIZE_MAX);
617 if (len == -1)
618 len = 16384;
620 buf = xmalloc (len);
622 if (!buf)
624 strv_free (users);
625 return GPG_ERR_ENOMEM;
628 if (!getpwnam_r (*p, &pw, buf, len, &result) && result)
630 if (result->pw_uid == (*peer)->uid)
632 xfree (buf);
633 allowed = 1;
634 break;
639 xfree (buf);
642 strv_free (users);
645 return allowed ? 0 : GPG_ERR_INV_USER_ID;
647 #else
648 static gpg_error_t
649 do_validate_peer (struct client_s *cl, assuan_peercred_t * peer)
651 char **users;
652 int allowed = 0;
653 gpg_error_t rc;
655 rc = assuan_get_peercred (cl->ctx, peer);
656 if (rc)
657 return rc;
659 users = config_get_list ("global", "allowed");
660 if (users)
662 for (char **p = users; *p; p++)
664 struct passwd *result;
665 struct group *gresult;
667 if (*(*p) == '@')
669 gresult = getgrnam (*(p) + 1);
670 if (gresult && gresult->gr_gid == (*peer)->gid)
672 allowed = 1;
673 break;
676 for (char **t = gresult->gr_mem; *t; t++)
678 result = getpwnam (*t);
679 if (result && result->pw_uid == (*peer)->uid)
681 allowed = 1;
682 break;
686 else
688 result = getpwnam (*p);
689 if (result && result->pw_uid == (*peer)->uid)
691 allowed = 1;
692 break;
696 if (allowed)
697 break;
700 strv_free (users);
703 return allowed ? 0 : GPG_ERR_INV_USER_ID;
705 #endif
707 static gpg_error_t
708 validate_peer (struct client_s *cl)
710 gpg_error_t rc;
711 assuan_peercred_t peer;
713 #ifdef WITH_GNUTLS
714 if (cl->thd->remote)
715 return tls_validate_access (cl, NULL);
716 #endif
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,
722 peer->pid);
723 else if (rc)
724 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
726 return rc;
729 static void
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)
739 return;
741 xmlCopyError (e, client->xml_error);
744 static pid_t
745 hook_waitpid (assuan_context_t ctx, pid_t pid, int action,
746 int *status, int options)
748 return waitpid (pid, status, options);
751 static ssize_t
752 hook_read (assuan_context_t ctx, assuan_fd_t fd, void *data, size_t len)
754 #ifdef WITH_GNUTLS
755 struct client_s *client = assuan_get_pointer (ctx);
757 if (client->thd->remote)
758 return tls_read_hook (ctx, (int) fd, data, len);
759 #endif
761 return read ((int) fd, data, len);
764 static ssize_t
765 hook_write (assuan_context_t ctx, assuan_fd_t fd,
766 const void *data, size_t len)
768 #ifdef WITH_GNUTLS
769 struct client_s *client = assuan_get_pointer (ctx);
771 if (client->thd->remote)
772 return tls_write_hook (ctx, (int) fd, data, len);
773 #endif
775 return write ((int) fd, data, len);
778 static int
779 new_connection (struct client_s *cl)
781 gpg_error_t rc;
782 static struct assuan_malloc_hooks mhooks = { xmalloc, xrealloc, xfree };
783 static struct assuan_system_hooks shooks = {
784 ASSUAN_SYSTEM_HOOKS_VERSION,
785 __assuan_usleep,
786 __assuan_pipe,
787 __assuan_close,
788 hook_read,
789 hook_write,
790 //FIXME
791 NULL, //recvmsg
792 NULL, //sendmsg both are used for FD passing
793 __assuan_spawn,
794 hook_waitpid,
795 __assuan_socketpair,
796 __assuan_socket,
797 __assuan_connect
800 #ifdef WITH_GNUTLS
801 if (cl->thd->remote)
803 char *prio = config_get_string ("global", "tls_cipher_suite");
805 cl->thd->tls = tls_init (cl->thd->fd, cl->thd->timeout, prio);
806 xfree (prio);
807 if (!cl->thd->tls)
808 return 0;
810 #endif
812 rc = assuan_new_ext (&cl->ctx, GPG_ERR_SOURCE_DEFAULT, &mhooks,
813 debug_level ? assuan_log_cb : NULL, NULL);
814 if (rc)
815 goto fail;
817 assuan_ctx_set_system_hooks (cl->ctx, &shooks);
818 rc = assuan_init_socket_server (cl->ctx, cl->thd->fd, 2);
819 if (rc)
820 goto fail;
822 assuan_set_pointer (cl->ctx, cl);
823 assuan_set_hello_line (cl->ctx, PACKAGE_STRING);
824 rc = register_commands (cl->ctx);
825 if (rc)
826 goto fail;
828 #ifdef WITH_GNUTLS
829 if (cl->thd->remote)
831 cl->thd->timeout = config_get_integer ("global", "tls_timeout");
832 fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK);
834 #endif
836 rc = assuan_accept (cl->ctx);
837 if (rc)
838 goto fail;
840 rc = validate_peer (cl);
841 /* May not be implemented on all platforms. */
842 if (rc && gpg_err_code (rc) != GPG_ERR_ASS_GENERAL)
843 goto fail;
845 rc = init_client_crypto (&cl->crypto);
846 if (rc)
847 goto fail;
849 #ifdef WITH_AGENT
850 if (use_agent)
851 cl->crypto->agent->client_ctx = cl->ctx;
852 #endif
854 cl->crypto->client_ctx = cl->ctx;
855 xmlSetStructuredErrorFunc (cl, xml_error_cb);
856 return 1;
858 fail:
859 log_write ("%s", pwmd_strerror (rc));
860 return 0;
864 * This is called after a client_thread() terminates. Set with
865 * pthread_cleanup_push().
867 static void
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);
877 if (cl)
879 cleanup_client (cl);
881 #ifdef WITH_GNUTLS
882 if (cn->tls)
884 gnutls_deinit (cn->tls->ses);
885 xfree (cn->tls->fp);
886 xfree (cn->tls);
888 #endif
890 if (!cn->atfork && cl->ctx)
891 assuan_release (cl->ctx);
892 else if (!cn->atfork && cl->thd && cl->thd->fd != -1)
893 close (cl->thd->fd);
895 if (cl->crypto)
896 cleanup_crypto (&cl->crypto);
898 pinentry_free_opts (&cl->pinentry_opts);
899 xfree (cl);
901 else
903 if (cn->fd != -1)
904 close (cn->fd);
907 while (cn->msg_queue)
909 struct status_msg_s *msg = cn->msg_queue;
911 cn->msg_queue = msg->next;
912 xfree (msg->line);
913 xfree (msg);
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);
924 if (!cn->atfork)
926 log_write (_("exiting, fd=%i"), cn->fd);
927 send_status_all (STATUS_CLIENTS, NULL);
930 xfree (cn);
931 pthread_cond_signal (&quit_cond);
934 void
935 cleanup_all_clients (int atfork)
937 /* This function may be called from pthread_atfork() which requires
938 reinitialization. */
939 if (atfork)
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);
947 cache_mutex_init ();
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;
957 cleanup_cb (thd);
960 exiting = 1;
961 cache_deinit (atfork);
962 MUTEX_UNLOCK (&cn_mutex);
965 static gpg_error_t
966 send_msg_queue (struct client_thread_s *thd)
968 MUTEX_LOCK (&thd->status_mutex);
969 gpg_error_t rc = 0;
970 char c;
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);
982 xfree (msg->line);
983 xfree (msg);
985 if (rc)
986 break;
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));
993 return rc;
996 static void *
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");
1004 #endif
1005 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1007 if (!cl)
1009 log_write ("%s(%i): %s", __FILE__, __LINE__,
1010 pwmd_strerror (GPG_ERR_ENOMEM));
1011 return NULL;
1014 MUTEX_LOCK (&cn_mutex);
1015 pthread_cleanup_push (cleanup_cb, thd);
1016 thd->cl = cl;
1017 cl->thd = thd;
1018 MUTEX_UNLOCK (&cn_mutex);
1020 if (new_connection (cl))
1022 int finished = 0;
1023 gpg_error_t rc;
1025 send_status_all (STATUS_CLIENTS, NULL);
1026 rc = send_status (cl->ctx, STATUS_CACHE, NULL);
1027 if (rc)
1029 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
1030 finished = 1;
1033 while (!finished)
1035 fd_set rfds;
1036 int n;
1037 int eof;
1039 FD_ZERO (&rfds);
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);
1046 if (n == -1)
1048 log_write ("%s", strerror (errno));
1049 break;
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)
1056 break;
1059 if (!FD_ISSET (thd->fd, &rfds))
1060 continue;
1062 rc = assuan_process_next (cl->ctx, &eof);
1063 if (rc || eof)
1065 if (gpg_err_code (rc) == GPG_ERR_EOF || eof)
1066 break;
1068 log_write ("assuan_process_next(): rc=%i %s", rc,
1069 pwmd_strerror (rc));
1070 if (rc == gpg_error (GPG_ERR_ETIMEDOUT))
1071 break;
1073 rc = send_error (cl->ctx, rc);
1074 if (rc)
1076 log_write ("assuan_process_done(): rc=%i %s", rc,
1077 pwmd_strerror (rc));
1078 break;
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)
1089 break;
1093 pthread_cleanup_pop (1);
1094 return NULL;
1097 static int
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)
1103 xmlDocPtr doc;
1104 int fd;
1105 struct stat st;
1106 int len;
1107 xmlChar *xmlbuf;
1108 xmlChar *xml;
1109 gpg_error_t rc;
1110 struct crypto_s *crypto = NULL;
1111 void *key = NULL;
1112 size_t keylen = 0;
1113 int algo = cipher ? cipher_string_to_gcrypt ((char *) cipher) :
1114 GCRY_CIPHER_AES256;
1116 if (algo == -1)
1118 log_write ("ERR %i: %s", gpg_error (GPG_ERR_CIPHER_ALGO),
1119 pwmd_strerror (GPG_ERR_CIPHER_ALGO));
1120 return 0;
1123 if (stat (filename, &st) == -1)
1125 log_write ("%s: %s", filename,
1126 pwmd_strerror (gpg_error_from_errno (errno)));
1127 return 0;
1130 rc = init_client_crypto (&crypto);
1131 if (rc)
1132 return 0;
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' ..."),
1137 filename, outfile);
1139 if ((fd = open (filename, O_RDONLY)) == -1)
1141 log_write ("%s: %s", filename,
1142 pwmd_strerror (gpg_error_from_errno (errno)));
1143 goto fail;
1146 if ((xmlbuf = xmalloc (st.st_size + 1)) == NULL)
1148 close (fd);
1149 log_write ("%s(%i): %s", __FILE__, __LINE__,
1150 pwmd_strerror (GPG_ERR_ENOMEM));
1151 goto fail;
1154 if (read (fd, xmlbuf, st.st_size) == -1)
1156 rc = gpg_error_from_errno (errno);
1157 close (fd);
1158 log_write ("%s: %s", filename, pwmd_strerror (rc));
1159 goto fail;
1162 close (fd);
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");
1170 xfree (xmlbuf);
1171 goto fail;
1174 xfree (xmlbuf);
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;
1182 if (!rc)
1183 rc = validate_import (n ? n->children : n);
1185 if (rc)
1187 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1188 xmlFreeDoc (doc);
1189 goto fail;
1192 xmlDocDumpMemory (doc, &xml, &len);
1193 xmlFreeDoc (doc);
1194 crypto->save.s2k_count = s2k_count;
1195 crypto->save.hdr.iterations = iterations;
1196 if (!use_agent)
1198 rc = export_common (NULL, 0, crypto, xml, len, outfile, keyfile, &key,
1199 &keylen, 0, 0);
1200 if (!rc)
1201 log_write (_("Success!"));
1203 #ifdef WITH_AGENT
1204 else
1206 rc = agent_set_pinentry_options (crypto->agent);
1207 if (!rc)
1208 rc = agent_export_common (crypto, keygrip, sign_keygrip, no_passphrase,
1209 xml, len, outfile, params, keyfile);
1211 #endif
1213 gcry_free (key);
1214 xmlFree (xml);
1215 if (rc)
1217 send_error (NULL, rc);
1218 goto fail;
1221 cleanup_crypto (&crypto);
1222 return 1;
1224 fail:
1225 cleanup_crypto (&crypto);
1226 return 0;
1229 static int
1230 do_cache_push (const char *filename, struct crypto_s *crypto)
1232 unsigned char md5file[16];
1233 gpg_error_t rc;
1234 char *key = NULL;
1235 size_t keylen = 0;
1236 xmlDocPtr doc;
1237 struct cache_data_s *cdata;
1238 unsigned char *crc;
1239 size_t len;
1241 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1242 filename);
1244 if (valid_filename (filename) == 0)
1246 log_write (_("%s: Invalid characters in filename"), filename);
1247 return 0;
1250 rc = decrypt_common (NULL, 0, crypto, filename, &key, &keylen);
1251 if (rc)
1252 return 0;
1254 doc = parse_doc ((char *) crypto->plaintext, crypto->plaintext_len);
1255 if (!doc)
1257 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM));
1258 xfree (key);
1259 return 0;
1262 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
1263 cdata = xcalloc (1, sizeof (struct cache_data_s));
1264 if (!cdata)
1266 xmlFreeDoc (doc);
1267 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM));
1268 xfree (key);
1269 return 0;
1272 rc = get_checksum (filename, &crc, &len);
1273 if (rc)
1275 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1276 xmlFreeDoc (doc);
1277 free_cache_data_once (cdata);
1278 xfree (key);
1279 return 0;
1282 cdata->crc = crc;
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))
1288 cdata->key = key;
1289 cdata->keylen = keylen;
1291 else
1292 xfree (key);
1294 if (rc)
1296 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1297 xmlFreeDoc (doc);
1298 free_cache_data_once (cdata);
1299 return 0;
1302 #ifdef WITH_AGENT
1303 if (use_agent && IS_PKI (crypto))
1305 gcry_sexp_build ((gcry_sexp_t *) & cdata->pubkey, NULL, "%S",
1306 crypto->pkey_sexp);
1307 gcry_sexp_build ((gcry_sexp_t *) & cdata->sigkey, NULL, "%S",
1308 crypto->sigpkey_sexp);
1310 #endif
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);
1315 return 1;
1318 static gpg_error_t
1319 init_client (int fd, const char *addr)
1321 gpg_error_t rc = 0;
1322 struct client_thread_s *new = xcalloc (1, sizeof (struct client_thread_s));
1324 if (!new)
1326 close (fd);
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);
1336 if (!rc)
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);
1343 if (!rc)
1345 #ifdef WITH_GNUTLS
1346 new->remote = addr ? 1 : 0;
1347 #endif
1348 new->fd = fd;
1349 rc = create_thread (client_thread, new, &new->tid, 1);
1350 if (rc)
1352 close (new->status_msg_pipe[0]);
1353 close (new->status_msg_pipe[1]);
1354 pthread_mutex_destroy (&new->status_mutex);
1358 if (!rc)
1360 struct slist_s *list = slist_append (cn_thread_list, new);
1362 if (list)
1364 cn_thread_list = list;
1365 if (addr)
1366 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1367 (pthread_t *) new->tid, fd, addr);
1368 else
1369 log_write (_("new connection: tid=%p, fd=%i"),
1370 (pthread_t *) new->tid, fd);
1372 else
1373 rc = GPG_ERR_ENOMEM;
1376 pthread_cleanup_pop (1);
1378 if (rc)
1380 xfree (new);
1381 close (fd);
1382 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1383 pwmd_strerror (rc));
1385 return rc;
1388 static void*
1389 keepalive_thread (void *arg)
1391 #ifndef HAVE_PTHREAD_CANCEL
1392 int *n = xmalloc (sizeof (int));
1394 *n = 0;
1395 pthread_setspecific (signal_thread_key, n);
1396 INIT_THREAD_SIGNAL;
1397 #endif
1399 #ifdef HAVE_PR_SET_NAME
1400 prctl (PR_SET_NAME, "keepalive");
1401 #endif
1402 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1404 for (;;)
1406 int n = config_get_integer ("global", "keepalive_interval");
1407 struct timeval tv = { n, 0 };
1408 #ifndef HAVE_PTHREAD_CANCEL
1409 int *sigusr2;
1411 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1412 if (*sigusr2)
1413 break;
1414 #endif
1416 send_status_all (STATUS_KEEPALIVE, NULL);
1417 select (0, NULL, NULL, NULL, &tv);
1420 return NULL;
1423 #ifdef WITH_GNUTLS
1424 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1425 static void *
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);
1434 static void *
1435 tcp_accept_thread (void *arg)
1437 int sockfd = *(int *) arg;
1438 #ifndef HAVE_PTHREAD_CANCEL
1439 int *n = xmalloc (sizeof (int));
1441 *n = 0;
1442 pthread_setspecific (signal_thread_key, n);
1443 INIT_THREAD_SIGNAL;
1444 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1445 #endif
1447 #ifdef HAVE_PR_SET_NAME
1448 prctl (PR_SET_NAME, "tcp_accept");
1449 #endif
1450 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1452 for (;;)
1454 struct sockaddr_storage raddr;
1455 socklen_t slen = sizeof (raddr);
1456 int fd = -1;
1457 unsigned long n;
1458 char s[INET6_ADDRSTRLEN];
1459 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1460 #ifndef HAVE_PTHREAD_CANCEL
1461 int *sigusr2;
1463 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1464 if (*sigusr2)
1465 break;
1466 #endif
1468 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1469 if (fd == -1)
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));
1479 break;
1482 #ifndef HAVE_PTHREAD_CANCEL
1483 select (0, NULL, NULL, NULL, &tv);
1484 #endif
1485 continue;
1488 if (quit)
1489 break;
1491 inet_ntop (raddr.ss_family, get_in_addr ((struct sockaddr *) &raddr),
1492 s, sizeof s);
1493 (void) init_client (fd, s);
1494 n = config_get_integer ("global", "tcp_wait");
1495 if (n > 0)
1497 tv.tv_sec = (n * 100000) / 100000;
1498 tv.tv_usec = (n * 100000) % 100000;
1499 select (0, NULL, NULL, NULL, &tv);
1503 return NULL;
1506 static int
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");
1511 char buf[7];
1512 int n;
1513 gpg_error_t rc;
1514 int *fd = ipv6 ? &tls6_fd : &tls_fd;
1516 if (term || config_get_boolean ("global", "enable_tcp") == 0)
1518 if (tls6_fd != -1)
1520 if (spawned_tls6)
1522 #ifdef HAVE_PTHREAD_CANCEL
1523 pthread_cancel (tls6_tid);
1524 #else
1525 pthread_kill (tls6_tid, SIGUSR2);
1526 #endif
1527 pthread_join (tls6_tid, NULL);
1530 shutdown (tls6_fd, SHUT_RDWR);
1531 close (tls6_fd);
1532 tls6_fd = -1;
1533 spawned_tls6 = 0;
1536 if (tls_fd != -1)
1538 if (spawned_tls)
1540 #ifdef HAVE_PTHREAD_CANCEL
1541 pthread_cancel (tls_tid);
1542 #else
1543 pthread_kill (tls_tid, SIGUSR2);
1544 #endif
1545 pthread_join (tls_tid, NULL);
1548 shutdown (tls_fd, SHUT_RDWR);
1549 close (tls_fd);
1550 tls_fd = -1;
1551 spawned_tls = 0;
1554 /* A client may still be connected. */
1555 if (!quit && x509_cred != NULL)
1556 tls_deinit_params ();
1558 return 1;
1561 if ((ipv6 && tls6_fd != -1) || (!ipv6 && tls_fd != -1))
1562 return 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));
1573 return 0;
1576 for (n = 0, p = servinfo; p != NULL; p = p->ai_next)
1578 int r = 1;
1580 if ((ipv6 && p->ai_family != AF_INET6)
1581 || (!ipv6 && p->ai_family != AF_INET))
1582 continue;
1584 if ((*fd = socket (p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
1586 log_write ("socket(): %s", strerror (errno));
1587 continue;
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);
1595 goto fail;
1598 if (bind (*fd, p->ai_addr, p->ai_addrlen) == -1)
1600 close (*fd);
1601 log_write ("bind(): %s",
1602 pwmd_strerror (gpg_error_from_errno (errno)));
1603 continue;
1606 n++;
1607 break;
1610 freeaddrinfo (servinfo);
1612 if (!n)
1613 goto fail;
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)));
1622 xfree (tmp);
1623 goto fail;
1626 xfree (tmp);
1627 #endif
1629 if (x509_cred == NULL)
1631 rc = tls_init_params ();
1632 if (rc)
1633 goto fail;
1636 if (listen (*fd, 0) == -1)
1638 log_write ("listen(): %s", strerror (errno));
1639 goto fail;
1642 if (ipv6)
1643 rc = create_thread (tcp_accept_thread, fd, &tls6_tid, 0);
1644 else
1645 rc = create_thread (tcp_accept_thread, fd, &tls_tid, 0);
1647 if (rc)
1649 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1650 pwmd_strerror (rc));
1651 goto fail;
1654 if (ipv6)
1655 spawned_tls6 = 1;
1656 else
1657 spawned_tls = 1;
1659 return 1;
1661 fail:
1662 start_stop_tls_with_protocol (0, 1);
1663 if (tls_fd != -1)
1664 close (tls_fd);
1666 if (tls6_fd != -1)
1667 close (tls6_fd);
1669 tls_fd = -1;
1670 tls6_fd = -1;
1671 return 0;
1674 static int
1675 start_stop_tls (int term)
1677 char *s = config_get_string ("global", "tcp_bind");
1678 int b;
1680 if (!s)
1681 return 0;
1683 if (!strcmp (s, "any"))
1685 b = start_stop_tls_with_protocol (0, term);
1686 if (b)
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);
1693 else
1694 b = 0;
1696 xfree (s);
1697 return b;
1699 #endif
1701 static void *
1702 accept_thread (void *arg)
1704 int sockfd = *(int *) arg;
1705 #ifndef HAVE_PTHREAD_CANCEL
1706 int *n = xmalloc (sizeof (int));
1708 *n = 0;
1709 pthread_setspecific (signal_thread_key, n);
1710 INIT_THREAD_SIGNAL;
1711 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1712 #endif
1714 #ifdef HAVE_PR_SET_NAME
1715 prctl (PR_SET_NAME, "accept");
1716 #endif
1717 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1719 for (;;)
1721 socklen_t slen = sizeof (struct sockaddr_un);
1722 struct sockaddr_un raddr;
1723 int fd;
1724 #ifndef HAVE_PTHREAD_CANCEL
1725 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1726 int *sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1728 if (*sigusr2)
1729 break;
1730 #endif
1732 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1733 if (fd == -1)
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)));
1744 break;
1747 #ifndef HAVE_PTHREAD_CANCEL
1748 select (0, NULL, NULL, NULL, &tv);
1749 #endif
1750 continue;
1753 (void) init_client (fd, NULL);
1756 /* Just in case accept() failed for some reason other than EBADF */
1757 quit = 1;
1758 return NULL;
1761 static void *
1762 cache_timer_thread (void *arg)
1764 #ifndef HAVE_PTHREAD_CANCEL
1765 int *n = xmalloc (sizeof (int));
1767 *n = 0;
1768 pthread_setspecific (signal_thread_key, n);
1769 INIT_THREAD_SIGNAL;
1770 #endif
1772 #ifdef HAVE_PR_SET_NAME
1773 prctl (PR_SET_NAME, "cache timer");
1774 #endif
1775 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1777 for (;;)
1779 struct timeval tv = { 1, 0 };
1780 #ifndef HAVE_PTHREAD_CANCEL
1781 int *n;
1783 n = (int *) pthread_getspecific (signal_thread_key);
1784 if (*n)
1785 break;
1786 #endif
1788 select (0, NULL, NULL, NULL, &tv);
1789 cache_adjust_timeout ();
1792 return NULL;
1795 static void
1796 catch_sigabrt (int sig)
1798 cache_clear (NULL);
1799 #ifndef MEM_DEBUG
1800 xpanic ();
1801 #endif
1804 static int
1805 signal_loop (sigset_t sigset)
1807 int done = 0;
1808 int siint = 0;
1812 int sig;
1814 sigwait (&sigset, &sig);
1816 if (sig != SIGQUIT)
1817 log_write (_("caught signal %i (%s)"), sig, strsignal (sig));
1819 switch (sig)
1821 case SIGHUP:
1822 pthread_cond_signal (&rcfile_cond);
1823 break;
1824 case SIGABRT:
1825 // not really handled here.
1826 catch_sigabrt (SIGABRT);
1827 break;
1828 case SIGUSR1:
1829 log_write (_("clearing file cache"));
1830 cache_clear (NULL);
1831 send_status_all (STATUS_CACHE, NULL);
1832 break;
1833 case SIGQUIT:
1834 done = 1;
1835 break;
1836 default:
1837 siint = 1;
1838 done = 1;
1839 break;
1842 while (!done);
1844 return siint;
1847 static void
1848 catchsig (int sig)
1850 log_write ("Caught SIGSEGV. Exiting.");
1851 #ifdef HAVE_BACKTRACE
1852 BACKTRACE (__FUNCTION__);
1853 #endif
1854 longjmp (jmp, 1);
1857 static void *
1858 waiting_for_exit (void *arg)
1860 int last = 0;
1861 #ifndef HAVE_PTHREAD_CANCEL
1862 int *n = xmalloc (sizeof (int));
1864 *n = 0;
1865 pthread_setspecific (signal_thread_key, n);
1866 INIT_THREAD_SIGNAL;
1867 #endif
1869 #ifdef HAVE_PR_SET_NAME
1870 prctl (PR_SET_NAME, "exiting");
1871 #endif
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);
1877 for (;;)
1879 struct timespec ts;
1880 int n;
1882 MUTEX_LOCK (&cn_mutex);
1883 n = slist_length (cn_thread_list);
1884 MUTEX_UNLOCK (&cn_mutex);
1885 if (!n)
1886 break;
1888 #ifndef HAVE_PTHREAD_CANCEL
1889 int *s = (int *) pthread_getspecific (signal_thread_key);
1890 if (*s)
1891 break;
1892 #endif
1894 if (last != n)
1896 log_write (_("%i clients remain"), n);
1897 last = 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);
1906 return NULL;
1909 static int
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;
1916 sigset_t sigset;
1917 int n;
1918 int segv = 0;
1919 gpg_error_t rc;
1921 init_commands ();
1922 sigemptyset (&sigset);
1924 /* Termination */
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);
1944 #endif
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);
1954 #endif
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);
1964 #ifdef WITH_GNUTLS
1965 /* Needs to be done after the fork(). */
1966 if (!start_stop_tls (0))
1968 segv = 1;
1969 goto done;
1971 #endif
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 ());
1977 #ifdef WITH_GNUTLS
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"));
1981 else
1982 log_write (_("Listening on %s"), *socketpath);
1983 #else
1984 log_write (_("Listening on %s"), *socketpath);
1985 #endif
1987 rc = create_thread (keepalive_thread, NULL, &keepalive_tid, 0);
1988 if (rc)
1990 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1991 pwmd_strerror (rc));
1992 goto done;
1995 cancel_keepalive_thread = 1;
1996 rc = create_thread (reload_rcfile_thread, NULL, &rcfile_tid, 0);
1997 if (rc)
1999 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2000 pwmd_strerror (rc));
2001 goto done;
2004 rc = create_thread (cache_timer_thread, NULL, &cache_timeout_tid, 0);
2005 if (rc)
2007 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2008 pwmd_strerror (rc));
2009 goto done;
2012 cancel_timeout_thread = 1;
2013 rc = create_thread (accept_thread, &sockfd, &accept_tid, 0);
2014 if (rc)
2016 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2017 pwmd_strerror (rc));
2018 goto done;
2021 cancel_accept_thread = 1;
2022 if (!setjmp (jmp))
2023 signal_loop (sigset);
2024 else
2025 segv = 1;
2027 done:
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
2032 * sent.
2034 if (cancel_accept_thread)
2036 #ifdef HAVE_PTHREAD_CANCEL
2037 int n = pthread_cancel (accept_tid);
2038 #else
2039 int n = pthread_kill (accept_tid, SIGUSR2);
2040 #endif
2041 if (!n)
2042 pthread_join (accept_tid, NULL);
2045 #ifdef WITH_GNUTLS
2046 start_stop_tls (1);
2047 #endif
2048 shutdown (sockfd, SHUT_RDWR);
2049 close (sockfd);
2050 unlink (*socketpath);
2051 xfree (*socketpath);
2052 *socketpath = NULL;
2053 MUTEX_LOCK (&cn_mutex);
2054 n = slist_length (cn_thread_list);
2055 MUTEX_UNLOCK (&cn_mutex);
2057 if (n && !segv)
2059 pthread_t tid;
2061 rc = create_thread (waiting_for_exit, NULL, &tid, 0);
2062 if (!rc)
2064 if (signal_loop (sigset))
2066 log_write (_("Received second termination request. Exiting."));
2067 #ifdef HAVE_PTHREAD_CANCEL
2068 pthread_cancel (tid);
2069 #else
2070 pthread_kill (tid, SIGUSR2);
2071 #endif
2072 pthread_join (tid, NULL);
2075 else
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);
2084 #else
2085 pthread_kill (cache_timeout_tid, SIGUSR2);
2086 #endif
2087 pthread_join (cache_timeout_tid, NULL);
2090 if (cancel_keepalive_thread)
2092 #ifdef HAVE_PTHREAD_CANCEL
2093 pthread_cancel (keepalive_tid);
2094 #else
2095 pthread_kill (keepalive_tid, SIGUSR2);
2096 #endif
2097 pthread_join (keepalive_tid, NULL);
2100 cleanup_all_clients (0);
2101 #ifdef WITH_GNUTLS
2102 start_stop_tls (1);
2103 #endif
2104 deinit_commands ();
2105 pthread_cond_destroy (&quit_cond);
2106 pthread_mutex_destroy (&quit_mutex);
2107 return segv ? EXIT_FAILURE : EXIT_SUCCESS;;
2110 static void
2111 startup_failure ()
2113 log_write (_
2114 ("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
2115 cache_clear (NULL);
2118 /* This is called from cache.c:clear_once(). See
2119 * command.c:clearcache_command() for details about lock checking.
2121 static gpg_error_t
2122 free_cache_data (file_cache_t * cache)
2124 gpg_error_t rc = GPG_ERR_NO_DATA;
2125 int i, t;
2126 struct client_thread_s *found = NULL;
2127 int self = 0;
2129 if (!cache->data)
2130 return 0;
2132 cache_lock ();
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);
2141 if (!thd->cl)
2142 continue;
2144 if (!memcmp (thd->cl->md5file, cache->filename,
2145 sizeof (cache->filename)))
2147 if (pthread_equal (pthread_self (), thd->tid))
2149 found = thd;
2150 self = 1;
2151 continue;
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);
2157 if (!rc)
2159 self = 0;
2160 found = thd;
2161 break;
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);
2172 cache->data = NULL;
2173 cache->defer_clear = 0;
2174 cache->timeout = -1;
2176 if (found)
2177 cache_unlock_mutex (found->cl->md5file, 0);
2179 rc = 0;
2182 if (rc)
2183 cache->defer_clear = 1;
2185 pthread_cleanup_pop (1);
2186 cache_unlock ();
2187 return rc;
2190 static int
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)
2197 gpg_error_t rc;
2198 void *data = NULL;
2199 size_t datalen;
2200 struct crypto_s *crypto = NULL;
2201 uint16_t ver;
2202 int algo;
2203 void *key = NULL;
2204 size_t keylen = 0;
2206 if (outfile[0] == '-' && outfile[1] == 0)
2207 outfile = NULL;
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)));
2214 return 0;
2217 if (keyfile)
2219 log_write (_("Using passphrase file \"%s\" for decryption ..."),
2220 keyfile);
2221 if (access (keyfile, R_OK) == -1)
2223 log_write ("%s: %s", keyfile,
2224 pwmd_strerror (gpg_error_from_errno (errno)));
2225 return 0;
2229 rc = read_v2_datafile (filename, keyfile, &data, &datalen, &ver, &algo);
2230 if (rc)
2232 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2233 return 0;
2236 if (cipher)
2238 algo = cipher_string_to_gcrypt (cipher);
2239 if (algo == -1)
2241 rc = GPG_ERR_CIPHER_ALGO;
2242 goto fail;
2246 if (ver < 0x212)
2248 xmlDocPtr doc = parse_doc (data, datalen);
2250 if (!doc)
2252 rc = GPG_ERR_BAD_DATA;
2253 goto fail;
2256 rc = convert_pre_212_elements (doc);
2257 gcry_free (data);
2258 data = NULL;
2259 if (!rc)
2261 xmlDocDumpFormatMemory (doc, (xmlChar **) & data, (int *) &datalen,
2263 if (!data)
2264 rc = GPG_ERR_ENOMEM;
2267 xmlFreeDoc (doc);
2268 if (rc)
2269 goto fail;
2272 rc = init_client_crypto (&crypto);
2273 if (!rc)
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;
2280 if (!use_agent)
2282 rc = export_common (NULL, 0, crypto, data, datalen, outfile, keyfile,
2283 &key, &keylen, 0, 0);
2285 #ifdef WITH_AGENT
2286 else
2288 rc = agent_set_pinentry_options (crypto->agent);
2289 if (!rc)
2290 rc = agent_export_common (crypto, keygrip, sign_keygrip, nopass,
2291 data, datalen, outfile, keyparam,
2292 no_passphrase_file ? NULL : keyfile);
2294 #endif
2295 if (!rc)
2296 log_write (_("Output written to \"%s\"."), outfile);
2299 fail:
2300 if (ver < 0x212)
2301 xmlFree (data);
2302 else
2303 gcry_free (data);
2305 gcry_free (key);
2306 cleanup_crypto (&crypto);
2308 if (rc)
2309 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2310 return rc ? 0 : 1;
2313 static void
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"
2322 #ifdef WITH_AGENT
2323 " --use-agent enable use of gpg-agent\n"
2324 #endif
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"
2334 " converting\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"),
2344 pn);
2345 exit (status);
2349 main (int argc, char *argv[])
2351 int opt;
2352 struct sockaddr_un addr;
2353 char buf[PATH_MAX];
2354 char *socketpath = NULL, *socketdir, *socketname = NULL;
2355 char *socketarg = NULL;
2356 char *datadir = NULL;
2357 int x;
2358 char *p;
2359 char **cache_push = NULL;
2360 char *import = NULL, *keygrip = NULL, *sign_keygrip = NULL;
2361 char *keyparam = NULL;
2362 int estatus = EXIT_FAILURE;
2363 int sockfd;
2364 char *outfile = NULL;
2365 int do_unlink = 0;
2366 int secure = 0;
2367 int show_version = 0;
2368 int force = 0;
2369 int no_passphrase = 0;
2370 gpg_error_t rc;
2371 char *convertfile = NULL;
2372 char *cipher = NULL;
2373 char *keyfile = NULL;
2374 unsigned long s2k_count = 0;
2375 uint64_t iterations = 0;
2376 int exists;
2377 char *debug_level_opt = NULL;
2378 int optindex;
2379 /* Must maintain the same order as longopts[] */
2380 enum
2382 OPT_VERSION, OPT_HELP,
2383 #ifdef WITH_AGENT
2384 OPT_AGENT,
2385 #endif
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},
2395 #ifdef WITH_AGENT
2396 {"use-agent", no_argument, 0, 0},
2397 #endif
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},
2416 {0, 0, 0, 0}
2419 #ifndef DEBUG
2420 #ifdef HAVE_SETRLIMIT
2421 struct rlimit rl;
2423 rl.rlim_cur = rl.rlim_max = 0;
2425 if (setrlimit (RLIMIT_CORE, &rl) != 0)
2426 err (EXIT_FAILURE, "setrlimit()");
2427 #endif
2428 #endif
2430 #ifdef ENABLE_NLS
2431 setlocale (LC_ALL, "");
2432 bindtextdomain ("pwmd", LOCALEDIR);
2433 textdomain ("pwmd");
2434 #endif
2436 #ifndef MEM_DEBUG
2437 xmem_init ();
2438 #endif
2439 gpg_err_init ();
2441 if (setup_crypto ())
2442 exit (EXIT_FAILURE);
2444 #ifdef WITH_GNUTLS
2445 gnutls_global_set_mem_functions (xmalloc, xmalloc, secure_mem_check,
2446 xrealloc, xfree);
2447 gnutls_global_init ();
2448 gnutls_global_set_log_function (tls_log);
2449 gnutls_global_set_log_level (1);
2450 tls_fd = -1;
2451 tls6_fd = -1;
2452 #endif
2453 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
2454 xmlInitMemory ();
2455 xmlInitGlobals ();
2456 xmlInitParser ();
2457 xmlXPathInit ();
2458 cmdline = 1;
2459 use_agent = 0;
2461 while ((opt = getopt_long (argc, argv, optstring, longopts, &optindex))
2462 != -1)
2464 switch (opt)
2466 case 'I':
2467 import = optarg;
2468 break;
2469 case 'C':
2470 convertfile = optarg;
2471 break;
2472 case 'k':
2473 keyfile = optarg;
2474 break;
2475 case 'o':
2476 outfile = optarg;
2477 break;
2478 case 'D':
2479 secure = 1;
2480 break;
2481 case 'n':
2482 nofork = 1;
2483 break;
2484 case 'f':
2485 rcfile = str_dup (optarg);
2486 break;
2487 default:
2488 usage (argv[0], EXIT_FAILURE);
2489 break;
2490 case 0:
2491 switch (optindex)
2493 case OPT_VERSION:
2494 show_version = 1;
2495 break;
2496 case OPT_HELP:
2497 usage (argv[0], 0);
2498 break;
2499 #ifdef WITH_AGENT
2500 case OPT_AGENT:
2501 use_agent = 1;
2502 break;
2503 #endif
2504 case OPT_DEBUG_LEVEL:
2505 debug_level_opt = optarg;
2506 break;
2507 case OPT_HOMEDIR:
2508 homedir = str_dup (optarg);
2509 break;
2510 case OPT_NO_FORK:
2511 nofork = 1;
2512 break;
2513 case OPT_DISABLE_DUMP:
2514 secure = 1;
2515 break;
2516 case OPT_IGNORE:
2517 force = 1;
2518 break;
2519 case OPT_RCFILE:
2520 rcfile = str_dup (optarg);
2521 break;
2522 case OPT_CONVERT:
2523 convertfile = optarg;
2524 break;
2525 case OPT_PASSPHRASE_FILE:
2526 keyfile = optarg;
2527 break;
2528 case OPT_IMPORT:
2529 import = optarg;
2530 break;
2531 case OPT_OUTFILE:
2532 outfile = optarg;
2533 break;
2534 case OPT_NO_PASSPHRASE_FILE:
2535 no_passphrase_file = 1;
2536 break;
2537 case OPT_KEYGRIP:
2538 keygrip = optarg;
2539 break;
2540 case OPT_SIGN_KEYGRIP:
2541 sign_keygrip = optarg;
2542 break;
2543 case OPT_KEYPARAM:
2544 keyparam = optarg;
2545 break;
2546 case OPT_CIPHER:
2547 cipher = optarg;
2548 break;
2549 case OPT_ITERATIONS:
2550 iterations = strtoull (optarg, NULL, 10);
2551 break;
2552 case OPT_S2K_COUNT:
2553 s2k_count = strtoul (optarg, NULL, 10);
2554 break;
2555 case OPT_NO_PASSPHRASE:
2556 no_passphrase = 1;
2557 break;
2558 default:
2559 usage (argv[0], 1);
2564 if (show_version)
2566 printf (_("%s\n\n"
2567 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013\n"
2568 "%s\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,
2571 PACKAGE_BUGREPORT,
2572 #ifdef PWMD_HOMEDIR
2573 "+PWMD_HOMEDIR=" PWMD_HOMEDIR "\n"
2574 #endif
2575 #ifdef WITH_AGENT
2576 "+WITH_AGENT\n"
2577 #else
2578 "-WITH_AGENT\n"
2579 #endif
2580 #ifdef WITH_QUALITY
2581 "+WITH_QUALITY\n"
2582 #else
2583 "-WITH_QUALITY\n"
2584 #endif
2585 #ifdef WITH_GNUTLS
2586 "+WITH_GNUTLS\n"
2587 #else
2588 "-WITH_GNUTLS\n"
2589 #endif
2590 #ifdef WITH_LIBACL
2591 "+WITH_LIBACL\n"
2592 #else
2593 "-WITH_LIBACL\n"
2594 #endif
2595 #ifdef DEBUG
2596 "+DEBUG\n"
2597 #else
2598 "-DEBUG\n"
2599 #endif
2600 #ifdef MEM_DEBUG
2601 "+MEM_DEBUG\n"
2602 #else
2603 "-MEM_DEBUG\n"
2604 #endif
2605 #ifdef MUTEX_DEBUG
2606 "+MUTEX_DEBUG\n"
2607 #else
2608 "-MUTEX_DEBUG\n"
2609 #endif
2611 exit (EXIT_SUCCESS);
2614 if (!homedir)
2615 #ifdef PWMD_HOMEDIR
2616 homedir = str_dup(PWMD_HOMEDIR);
2617 #else
2618 homedir = str_asprintf ("%s/.pwmd", get_home_dir ());
2619 #endif
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);
2639 #endif
2641 if (!rcfile)
2642 rcfile = str_asprintf ("%s/config", homedir);
2644 global_config = config_parse (rcfile);
2645 if (!global_config)
2646 exit (EXIT_FAILURE);
2648 #ifdef WITH_AGENT
2649 if (!use_agent)
2650 use_agent = config_get_boolean ("global", "use_agent");
2651 #endif
2653 setup_logging ();
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))
2661 errno = 0;
2662 if (setpriority (PRIO_PROCESS, 0, x) == -1)
2664 log_write ("setpriority(): %s",
2665 pwmd_strerror (gpg_error_from_errno (errno)));
2666 goto do_exit;
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)));
2674 goto do_exit;
2676 #endif
2678 rc = cache_init (free_cache_data);
2679 if (rc)
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));
2685 goto do_exit;
2688 if (s2k_count == 0)
2689 s2k_count = config_get_ulong (NULL, "s2k_count");
2691 if (convertfile)
2693 if (!outfile)
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);
2700 xfree (rcfile);
2701 exit (!estatus);
2704 if (import)
2706 if (!outfile || !*outfile)
2707 usage (argv[0], EXIT_FAILURE);
2709 if (outfile && outfile[0] == '-' && outfile[1] == 0)
2710 outfile = NULL;
2712 estatus = xml_import (import, outfile, keygrip, sign_keygrip, keyfile,
2713 no_passphrase, cipher, keyparam, s2k_count,
2714 iterations);
2715 config_free (global_config);
2716 xfree (rcfile);
2717 exit (!estatus);
2720 p = config_get_string ("global", "socket_path");
2721 if (!p)
2722 p = str_asprintf ("%s/socket", homedir);
2724 socketarg = expand_homedir (p);
2725 xfree (p);
2727 if (!secure)
2728 disable_list_and_dump = config_get_boolean ("global",
2729 "disable_list_and_dump");
2730 else
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);
2747 else
2749 socketname = str_dup (strrchr (socketarg, '/'));
2750 socketname++;
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);
2761 goto do_exit;
2765 * Set the cache entry for a file. Prompts for the password.
2767 if (cache_push)
2769 struct crypto_s *crypto = NULL;
2770 gpg_error_t rc = init_client_crypto (&crypto);
2772 if (rc)
2774 estatus = EXIT_FAILURE;
2775 goto do_exit;
2778 #ifdef WITH_AGENT
2779 if (use_agent)
2781 rc = agent_set_pinentry_options (crypto->agent);
2782 if (rc)
2784 estatus = EXIT_FAILURE;
2785 goto do_exit;
2788 #endif
2790 for (opt = 0; cache_push[opt]; opt++)
2792 if (!do_cache_push (cache_push[opt], crypto) && !force)
2794 strv_free (cache_push);
2795 startup_failure ();
2796 estatus = EXIT_FAILURE;
2797 cleanup_crypto (&crypto);
2798 goto do_exit;
2801 cleanup_crypto_stage1 (crypto);
2804 #ifdef WITH_AGENT
2805 if (use_agent)
2806 (void) kill_scd (crypto->agent);
2807 #endif
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)));
2826 goto do_exit;
2829 xfree (socketdir);
2831 if ((sockfd = socket (PF_UNIX, SOCK_STREAM, 0)) == -1)
2833 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2834 goto do_exit;
2837 addr.sun_family = AF_UNIX;
2838 snprintf (addr.sun_path, sizeof (addr.sun_path), "%s", socketname);
2839 do_unlink = 1;
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)
2847 do_unlink = 0;
2848 log_write (_("Either there is another pwmd running or '%s' is a \n"
2849 "stale socket. Please remove it manually."), socketpath);
2852 goto do_exit;
2856 char *t = config_get_string ("global", "socket_perms");
2857 mode_t mode;
2858 mode_t mask;
2860 if (t)
2862 mode = strtol (t, NULL, 8);
2863 mask = umask (0);
2864 xfree (t);
2866 if (chmod (socketname, mode) == -1)
2868 log_write ("%s: %s", socketname,
2869 pwmd_strerror (gpg_error_from_errno (errno)));
2870 close (sockfd);
2871 umask (mask);
2872 goto do_exit;
2875 umask (mask);
2879 xfree (--socketname);
2881 if (chdir (datadir))
2883 log_write ("%s: %s", datadir,
2884 pwmd_strerror (gpg_error_from_errno (errno)));
2885 close (sockfd);
2886 goto do_exit;
2889 xfree (datadir);
2891 if (listen (sockfd, 0) == -1)
2893 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2894 goto do_exit;
2897 cmdline = 0;
2899 if (!nofork)
2901 switch (fork ())
2903 case -1:
2904 log_write ("fork(): %s",
2905 pwmd_strerror (gpg_error_from_errno (errno)));
2906 goto do_exit;
2907 case 0:
2908 close (0);
2909 close (1);
2910 close (2);
2911 setsid ();
2912 break;
2913 default:
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);
2922 do_exit:
2923 if (socketpath && do_unlink)
2925 unlink (socketpath);
2926 xfree (socketpath);
2929 xfree (socketarg);
2930 #ifdef WITH_GNUTLS
2931 gnutls_global_deinit ();
2932 #endif
2933 if (rcfile_tid)
2935 #ifdef HAVE_PTHREAD_CANCEL
2936 pthread_cancel (rcfile_tid);
2937 #else
2938 pthread_kill (rcfile_tid, SIGUSR2);
2939 pthread_cond_signal (&rcfile_cond);
2940 #endif
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);
2949 #endif
2951 if (global_config)
2952 config_free (global_config);
2954 xfree (rcfile);
2955 xfree (home_directory);
2956 xfree (homedir);
2957 xmlCleanupParser ();
2958 xmlCleanupGlobals ();
2960 if (estatus == EXIT_SUCCESS)
2961 log_write (_("pwmd exiting normally"));
2963 pthread_key_delete (thread_name_key);
2964 closelog ();
2965 #if defined(DEBUG) && !defined(MEM_DEBUG)
2966 xdump ();
2967 #endif
2968 exit (estatus);