Reimplement the KEEPALIVE status message.
[pwmd.git] / src / pwmd.c
blobd1bacbb7aab8692253baff0799e31009ed6412d5
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>
51 #ifdef TM_IN_SYS_TIME
52 #include <sys/time.h>
53 #else
54 #include <time.h>
55 #endif
57 #ifdef HAVE_LIMITS_H
58 #include <limits.h>
59 #endif
61 #ifdef HAVE_GETOPT_LONG
62 #ifdef HAVE_GETOPT_H
63 #include <getopt.h>
64 #endif
65 #else
66 #include "getopt_long.h"
67 #endif
69 #ifdef HAVE_PR_SET_NAME
70 #include <sys/prctl.h>
71 #endif
73 #include "pwmd-error.h"
74 #include <gcrypt.h>
76 #include "util-misc.h"
77 #include "mem.h"
78 #include "xml.h"
79 #include "common.h"
80 #include "commands.h"
81 #include "cache.h"
82 #include "util-string.h"
83 #include "mutex.h"
84 #include "rcfile.h"
85 #include "crypto.h"
86 #include "convert.h"
87 #include "pinentry.h"
89 /* In tenths of a second. */
90 #define SIG_TIMEOUT 1
92 /* For (tcp_)accept_thread (usec). */
93 #define ACCEPT_TIMEOUT 30000
95 static int quit;
96 static int exiting;
97 static int cmdline;
98 static jmp_buf jmp;
99 static int nofork;
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;
107 #endif
109 #ifdef WITH_GNUTLS
110 static int tls_fd;
111 static int tls6_fd;
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);
118 #endif
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; \
128 sigset_t sigset; \
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); \
137 } while (0)
139 static void
140 catch_thread_signal (int sig, siginfo_t *info, void *ctx)
142 int *n = (int *) pthread_getspecific (signal_thread_key);
144 *n = 1;
145 pthread_setspecific (signal_thread_key, n);
147 #endif
149 static void
150 cache_push_from_rcfile ()
152 struct crypto_s *crypto = NULL;
153 char **cache_push;
154 gpg_error_t rc = init_client_crypto (&crypto);
156 if (rc)
158 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
159 return;
162 #ifdef WITH_AGENT
163 if (use_agent)
165 rc = set_agent_option (crypto->agent, "pinentry-mode", "error");
166 if (rc)
168 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
169 return;
172 #endif
174 cache_push = config_get_list ("global", "cache_push");
175 if (cache_push)
177 char **p;
179 for (p = cache_push; *p; p++)
181 (void) do_cache_push (*p, crypto);
182 cleanup_crypto_stage1 (crypto);
185 strv_free (cache_push);
188 #ifdef WITH_AGENT
189 (void) kill_scd (crypto->agent);
190 #endif
191 cleanup_crypto (&crypto);
194 static void
195 setup_logging ()
197 int n = config_get_boolean ("global", "enable_logging");
199 if (n)
201 char *p = config_get_string ("global", "log_path");
203 xfree (logfile);
204 logfile = expand_homedir (p);
205 xfree (p);
207 else
209 xfree (logfile);
210 logfile = NULL;
213 log_syslog = config_get_boolean ("global", "syslog");
214 if (log_syslog == 1)
215 openlog ("pwmd", LOG_NDELAY | LOG_PID, LOG_DAEMON);
218 static void *
219 reload_rcfile_thread (void *arg)
221 #ifndef HAVE_PTHREAD_CANCEL
222 int *n = xmalloc (sizeof (int));
224 *n = 0;
225 pthread_setspecific (signal_thread_key, n);
226 INIT_THREAD_SIGNAL;
227 #endif
229 #ifdef HAVE_PR_SET_NAME
230 prctl (PR_SET_NAME, "reload rcfile");
231 #endif
232 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
233 MUTEX_LOCK (&rcfile_mutex);
234 pthread_cleanup_push (cleanup_mutex_cb, &rcfile_mutex);
236 for (;;)
238 struct slist_s *config;
239 char **users;
240 int b = disable_list_and_dump;
241 #ifdef WITH_GNUTLS
242 int exists;
243 int tcp_require_key = config_get_bool_param (global_config, "global",
244 "tcp_require_key",
245 &exists);
246 #endif
248 pthread_cond_wait (&rcfile_cond, &rcfile_mutex);
249 #ifndef HAVE_PTHREAD_CANCEL
250 int *n = (int *) pthread_getspecific (signal_thread_key);
251 if (*n)
252 break;
253 #endif
255 users = config_get_list ("global", "allowed");
256 log_write (_("reloading configuration file '%s'"), rcfile);
257 config = config_parse (rcfile);
258 if (config)
260 config_free (global_config);
261 global_config = config;
262 setup_logging ();
263 cache_push_from_rcfile ();
264 config_clear_keys ();
267 disable_list_and_dump = !disable_list_and_dump ? b : 1;
268 #ifdef WITH_GNUTLS
269 if (config_get_bool_param (global_config, "global", "tcp_require_key",
270 &exists) && exists)
271 tcp_require_key = 1;
273 config_set_bool_param (&global_config, "global", "tcp_require_key",
274 tcp_require_key ? "true" : "false");
275 #endif
276 char *tmp = strv_join (",", users);
277 config_set_list_param (&global_config, "global", "allowed", tmp);
278 xfree (tmp);
279 strv_free (users);
280 #ifdef WITH_GNUTLS
281 /* Kill existing listening threads since the configured listening
282 * protocols may have changed. */
283 start_stop_tls (1);
284 start_stop_tls (0);
285 #endif
288 pthread_cleanup_pop (1);
289 return NULL;
292 gpg_error_t
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)
298 e = gpg_error (e);
300 if (client)
301 client->last_rc = e;
303 if (!e)
304 return assuan_process_done (ctx, 0);
306 if (!ctx)
308 log_write ("%s", pwmd_strerror (e));
309 return e;
312 if (client && gpg_err_code (e) == GPG_ERR_BAD_DATA)
314 xmlErrorPtr xe = client->xml_error;
316 if (!xe)
317 xe = xmlGetLastError ();
318 if (xe)
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,
328 xe ? xe->message :
329 NULL));
331 if (xe == client->xml_error)
332 xmlResetError (xe);
333 else
334 xmlResetLastError ();
336 client->xml_error = NULL;
337 return e;
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,
346 const char *msg)
348 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
349 int i, t;
350 int match = 0;
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)
361 match = 1;
362 break;
365 if (!strcasecmp (debug_level[i], (char *) "ctx")
366 && cat == ASSUAN_LOG_CTX)
368 match = 1;
369 break;
372 if (!strcasecmp (debug_level[i], (char *) "engine")
373 && cat == ASSUAN_LOG_ENGINE)
375 match = 1;
376 break;
379 if (!strcasecmp (debug_level[i], (char *) "data")
380 && cat == ASSUAN_LOG_DATA)
382 match = 1;
383 break;
386 if (!strcasecmp (debug_level[i], (char *) "sysio")
387 && cat == ASSUAN_LOG_SYSIO)
389 match = 1;
390 break;
393 if (!strcasecmp (debug_level[i], (char *) "control")
394 && cat == ASSUAN_LOG_CONTROL)
396 match = 1;
397 break;
401 if (match && msg)
403 if (logfile)
405 int fd;
407 if ((fd =
408 open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600)) == -1)
409 warn ("%s", logfile);
410 else
412 pthread_cleanup_push (cleanup_fd_cb, &fd);
413 write (fd, msg, strlen (msg));
414 pthread_cleanup_pop (1);
418 if (nofork)
420 fprintf (stderr, "%s%s", data ? (char *) data : "", msg);
421 fflush (stderr);
425 pthread_cleanup_pop (1);
426 return match;
429 void
430 log_write (const char *fmt, ...)
432 char *args, *line;
433 va_list ap;
434 struct tm *tm;
435 time_t now;
436 char tbuf[21];
437 int fd = -1;
438 char *name = NULL;
439 char buf[255];
440 pthread_t tid = pthread_self ();
441 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
443 if ((!logfile && !isatty (STDERR_FILENO) && !log_syslog) || !fmt)
444 return;
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);
456 va_start (ap, fmt);
458 if (str_vasprintf (&args, fmt, ap) != -1)
460 if (cmdline)
462 pthread_cleanup_push (xfree, args);
463 fprintf (stderr, "%s\n", args);
464 fflush (stderr);
465 pthread_cleanup_pop (1);
467 else
469 pthread_cleanup_push (xfree, args);
470 name = pthread_getspecific (thread_name_key);
471 snprintf (buf, sizeof (buf), "%s(%p): ", name ? name : _("unknown"),
472 (pthread_t *) tid);
473 name = buf;
475 if (!cmdline && log_syslog && !nofork)
476 syslog (LOG_INFO, "%s%s", name, args);
478 time (&now);
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);
488 if (line)
490 pthread_cleanup_push (xfree, line);
491 if (logfile && fd != -1)
493 write (fd, line, strlen (line));
494 fsync (fd);
497 if (nofork)
499 fprintf (stdout, "%s", line);
500 fflush (stdout);
503 pthread_cleanup_pop (1);
508 va_end (ap);
509 pthread_cleanup_pop (1);
510 pthread_cleanup_pop (0);
511 pthread_mutex_unlock (&m);
514 #ifdef WITH_GNUTLS
515 static int
516 secure_mem_check (const void *arg)
518 return 1;
520 #endif
522 static gpg_error_t
523 setup_crypto ()
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);
536 return 0;
539 #ifdef HAVE_GETGRNAM_R
540 static gpg_error_t
541 do_validate_peer (struct client_s *cl, assuan_peercred_t * peer)
543 char **users;
544 int allowed = 0;
545 gpg_error_t rc;
547 rc = assuan_get_peercred (cl->ctx, peer);
548 if (rc)
549 return rc;
551 users = config_get_list ("global", "allowed");
552 if (users)
554 for (char **p = users; *p; p++)
556 struct passwd pw, *result;
557 struct group gr, *gresult;
558 char *buf;
560 if (*(*p) == '@')
562 size_t len = sysconf (_SC_GETGR_R_SIZE_MAX);
564 if (len == -1)
565 len = 16384;
567 buf = xmalloc (len);
568 if (!buf)
570 strv_free (users);
571 return GPG_ERR_ENOMEM;
574 if (!getgrnam_r (*(p) + 1, &gr, buf, len, &gresult) && gresult)
576 if (gresult->gr_gid == (*peer)->gid)
578 xfree (buf);
579 allowed = 1;
580 break;
583 len = sysconf (_SC_GETPW_R_SIZE_MAX);
584 if (len == -1)
585 len = 16384;
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)
594 xfree (buf);
595 allowed = 1;
596 break;
601 xfree (tbuf);
603 if (allowed)
604 break;
607 else
609 size_t len = sysconf (_SC_GETPW_R_SIZE_MAX);
611 if (len == -1)
612 len = 16384;
614 buf = xmalloc (len);
616 if (!buf)
618 strv_free (users);
619 return GPG_ERR_ENOMEM;
622 if (!getpwnam_r (*p, &pw, buf, len, &result) && result)
624 if (result->pw_uid == (*peer)->uid)
626 xfree (buf);
627 allowed = 1;
628 break;
633 xfree (buf);
636 strv_free (users);
639 return allowed ? 0 : GPG_ERR_INV_USER_ID;
641 #else
642 static gpg_error_t
643 do_validate_peer (struct client_s *cl, assuan_peercred_t * peer)
645 char **users;
646 int allowed = 0;
647 gpg_error_t rc;
649 rc = assuan_get_peercred (cl->ctx, peer);
650 if (rc)
651 return rc;
653 users = config_get_list ("global", "allowed");
654 if (users)
656 for (char **p = users; *p; p++)
658 struct passwd *result;
659 struct group *gresult;
661 if (*(*p) == '@')
663 gresult = getgrnam (*(p) + 1);
664 if (gresult && gresult->gr_gid == (*peer)->gid)
666 allowed = 1;
667 break;
670 for (char **t = gresult->gr_mem; *t; t++)
672 result = getpwnam (*t);
673 if (result && result->pw_uid == (*peer)->uid)
675 allowed = 1;
676 break;
680 else
682 result = getpwnam (*p);
683 if (result && result->pw_uid == (*peer)->uid)
685 allowed = 1;
686 break;
690 if (allowed)
691 break;
694 strv_free (users);
697 return allowed ? 0 : GPG_ERR_INV_USER_ID;
699 #endif
701 static gpg_error_t
702 validate_peer (struct client_s *cl)
704 gpg_error_t rc;
705 assuan_peercred_t peer;
707 #ifdef WITH_GNUTLS
708 if (cl->thd->remote)
709 return 0;
710 #endif
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,
716 peer->pid);
717 else if (rc)
718 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
720 return rc;
723 static void
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)
733 return;
735 xmlCopyError (e, client->xml_error);
738 static pid_t
739 hook_waitpid (assuan_context_t ctx, pid_t pid, int action,
740 int *status, int options)
742 return waitpid (pid, status, options);
745 static ssize_t
746 hook_read (assuan_context_t ctx, assuan_fd_t fd, void *data, size_t len)
748 #ifdef WITH_GNUTLS
749 struct client_s *client = assuan_get_pointer (ctx);
751 if (client->thd->remote)
752 return tls_read_hook (ctx, (int) fd, data, len);
753 #endif
755 return read ((int) fd, data, len);
758 static ssize_t
759 hook_write (assuan_context_t ctx, assuan_fd_t fd,
760 const void *data, size_t len)
762 #ifdef WITH_GNUTLS
763 struct client_s *client = assuan_get_pointer (ctx);
765 if (client->thd->remote)
766 return tls_write_hook (ctx, (int) fd, data, len);
767 #endif
769 return write ((int) fd, data, len);
772 static int
773 new_connection (struct client_s *cl)
775 gpg_error_t rc;
776 static struct assuan_malloc_hooks mhooks = { xmalloc, xrealloc, xfree };
777 static struct assuan_system_hooks shooks = {
778 ASSUAN_SYSTEM_HOOKS_VERSION,
779 __assuan_usleep,
780 __assuan_pipe,
781 __assuan_close,
782 hook_read,
783 hook_write,
784 //FIXME
785 NULL, //recvmsg
786 NULL, //sendmsg both are used for FD passing
787 __assuan_spawn,
788 hook_waitpid,
789 __assuan_socketpair,
790 __assuan_socket,
791 __assuan_connect
794 #ifdef WITH_GNUTLS
795 if (cl->thd->remote)
797 char *prio = config_get_string ("global", "tls_cipher_suite");
799 cl->thd->tls = tls_init (cl->thd->fd, cl->thd->timeout, prio);
800 xfree (prio);
801 if (!cl->thd->tls)
802 return 0;
804 #endif
806 rc = assuan_new_ext (&cl->ctx, GPG_ERR_SOURCE_DEFAULT, &mhooks,
807 debug_level ? assuan_log_cb : NULL, NULL);
808 if (rc)
809 goto fail;
811 assuan_ctx_set_system_hooks (cl->ctx, &shooks);
812 rc = assuan_init_socket_server (cl->ctx, cl->thd->fd, 2);
813 if (rc)
814 goto fail;
816 assuan_set_pointer (cl->ctx, cl);
817 assuan_set_hello_line (cl->ctx, PACKAGE_STRING);
818 rc = register_commands (cl->ctx);
819 if (rc)
820 goto fail;
822 #ifdef WITH_GNUTLS
823 if (cl->thd->remote)
825 cl->thd->timeout = config_get_integer ("global", "tls_timeout");
826 fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK);
828 #endif
830 rc = assuan_accept (cl->ctx);
831 if (rc)
832 goto fail;
834 rc = validate_peer (cl);
835 /* May not be implemented on all platforms. */
836 if (rc && gpg_err_code (rc) != GPG_ERR_ASS_GENERAL)
837 goto fail;
839 rc = init_client_crypto (&cl->crypto);
840 if (rc)
841 goto fail;
843 #ifdef WITH_AGENT
844 if (use_agent)
845 cl->crypto->agent->client_ctx = cl->ctx;
846 #endif
848 cl->crypto->client_ctx = cl->ctx;
849 xmlSetStructuredErrorFunc (cl, xml_error_cb);
850 return 1;
852 fail:
853 log_write ("%s", pwmd_strerror (rc));
854 return 0;
858 * This is called after a client_thread() terminates. Set with
859 * pthread_cleanup_push().
861 static void
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);
871 if (cl)
873 cleanup_client (cl);
875 #ifdef WITH_GNUTLS
876 if (cn->tls)
878 gnutls_deinit (cn->tls->ses);
879 xfree (cn->tls->fp);
880 xfree (cn->tls);
882 #endif
884 if (!cn->atfork && cl->ctx)
885 assuan_release (cl->ctx);
886 else if (!cn->atfork && cl->thd && cl->thd->fd != -1)
887 close (cl->thd->fd);
889 if (cl->crypto)
890 cleanup_crypto (&cl->crypto);
892 pinentry_free_opts (&cl->pinentry_opts);
893 xfree (cl);
895 else
897 if (cn->fd != -1)
898 close (cn->fd);
901 while (cn->msg_queue)
903 struct status_msg_s *msg = cn->msg_queue;
905 cn->msg_queue = msg->next;
906 xfree (msg->line);
907 xfree (msg);
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);
918 if (!cn->atfork)
920 log_write (_("exiting, fd=%i"), cn->fd);
921 send_status_all (STATUS_CLIENTS, NULL);
924 xfree (cn);
925 pthread_cond_signal (&quit_cond);
928 void
929 cleanup_all_clients (int atfork)
931 /* This function may be called from pthread_atfork() which requires
932 reinitialization. */
933 if (atfork)
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);
941 cache_mutex_init ();
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;
951 cleanup_cb (thd);
954 exiting = 1;
955 cache_deinit (atfork);
956 MUTEX_UNLOCK (&cn_mutex);
959 static gpg_error_t
960 send_msg_queue (struct client_thread_s *thd)
962 MUTEX_LOCK (&thd->status_mutex);
963 gpg_error_t rc = 0;
964 char c;
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);
976 xfree (msg->line);
977 xfree (msg);
979 if (rc)
980 break;
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));
987 return rc;
990 static void *
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");
998 #endif
999 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1001 if (!cl)
1003 log_write ("%s(%i): %s", __FILE__, __LINE__,
1004 pwmd_strerror (GPG_ERR_ENOMEM));
1005 return NULL;
1008 MUTEX_LOCK (&cn_mutex);
1009 pthread_cleanup_push (cleanup_cb, thd);
1010 thd->cl = cl;
1011 cl->thd = thd;
1012 MUTEX_UNLOCK (&cn_mutex);
1014 if (new_connection (cl))
1016 int finished = 0;
1017 gpg_error_t rc;
1019 send_status_all (STATUS_CLIENTS, NULL);
1020 rc = send_status (cl->ctx, STATUS_CACHE, NULL);
1021 if (rc)
1023 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
1024 finished = 1;
1027 while (!finished)
1029 fd_set rfds;
1030 int n;
1031 int eof;
1033 FD_ZERO (&rfds);
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);
1040 if (n == -1)
1042 log_write ("%s", strerror (errno));
1043 break;
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)
1050 break;
1053 if (!FD_ISSET (thd->fd, &rfds))
1054 continue;
1056 rc = assuan_process_next (cl->ctx, &eof);
1057 if (rc || eof)
1059 if (gpg_err_code (rc) == GPG_ERR_EOF || eof)
1060 break;
1062 log_write ("assuan_process_next(): rc=%i %s", rc,
1063 pwmd_strerror (rc));
1064 if (rc == gpg_error (GPG_ERR_ETIMEDOUT))
1065 break;
1067 rc = send_error (cl->ctx, rc);
1068 if (rc)
1070 log_write ("assuan_process_done(): rc=%i %s", rc,
1071 pwmd_strerror (rc));
1072 break;
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)
1083 break;
1087 pthread_cleanup_pop (1);
1088 return NULL;
1091 static int
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)
1097 xmlDocPtr doc;
1098 int fd;
1099 struct stat st;
1100 int len;
1101 xmlChar *xmlbuf;
1102 xmlChar *xml;
1103 gpg_error_t rc;
1104 struct crypto_s *crypto = NULL;
1105 void *key = NULL;
1106 size_t keylen = 0;
1107 int algo = cipher ? cipher_string_to_gcrypt ((char *) cipher) :
1108 GCRY_CIPHER_AES256;
1110 if (algo == -1)
1112 log_write ("ERR %i: %s", gpg_error (GPG_ERR_CIPHER_ALGO),
1113 pwmd_strerror (GPG_ERR_CIPHER_ALGO));
1114 return 0;
1117 if (stat (filename, &st) == -1)
1119 log_write ("%s: %s", filename,
1120 pwmd_strerror (gpg_error_from_syserror ()));
1121 return 0;
1124 rc = init_client_crypto (&crypto);
1125 if (rc)
1126 return 0;
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' ..."),
1131 filename, outfile);
1133 if ((fd = open (filename, O_RDONLY)) == -1)
1135 log_write ("%s: %s", filename,
1136 pwmd_strerror (gpg_error_from_syserror ()));
1137 goto fail;
1140 if ((xmlbuf = xmalloc (st.st_size + 1)) == NULL)
1142 close (fd);
1143 log_write ("%s(%i): %s", __FILE__, __LINE__,
1144 pwmd_strerror (GPG_ERR_ENOMEM));
1145 goto fail;
1148 if (read (fd, xmlbuf, st.st_size) == -1)
1150 rc = gpg_error_from_syserror ();
1151 close (fd);
1152 log_write ("%s: %s", filename, pwmd_strerror (rc));
1153 goto fail;
1156 close (fd);
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");
1164 xfree (xmlbuf);
1165 goto fail;
1168 xfree (xmlbuf);
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;
1176 if (!rc)
1177 rc = validate_import (n ? n->children : n);
1179 if (rc)
1181 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1182 xmlFreeDoc (doc);
1183 goto fail;
1186 xmlDocDumpMemory (doc, &xml, &len);
1187 xmlFreeDoc (doc);
1188 crypto->save.s2k_count = s2k_count;
1189 crypto->save.hdr.iterations = iterations;
1190 if (!use_agent)
1192 rc = export_common (NULL, 0, crypto, xml, len, outfile, keyfile, &key,
1193 &keylen, 0, 0);
1194 if (!rc)
1195 log_write (_("Success!"));
1197 #ifdef WITH_AGENT
1198 else
1200 rc = agent_set_pinentry_options (crypto->agent);
1201 if (!rc)
1202 rc = agent_export_common (crypto, keygrip, sign_keygrip, no_passphrase,
1203 xml, len, outfile, params, keyfile);
1205 #endif
1207 gcry_free (key);
1208 xmlFree (xml);
1209 if (rc)
1211 send_error (NULL, rc);
1212 goto fail;
1215 cleanup_crypto (&crypto);
1216 return 1;
1218 fail:
1219 cleanup_crypto (&crypto);
1220 return 0;
1223 static int
1224 do_cache_push (const char *filename, struct crypto_s *crypto)
1226 unsigned char md5file[16];
1227 gpg_error_t rc;
1228 char *key = NULL;
1229 size_t keylen = 0;
1230 xmlDocPtr doc;
1231 struct cache_data_s *cdata;
1232 unsigned char *crc;
1233 size_t len;
1235 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1236 filename);
1238 if (valid_filename (filename) == 0)
1240 log_write (_("%s: Invalid characters in filename"), filename);
1241 return 0;
1244 rc = decrypt_common (NULL, 0, crypto, filename, &key, &keylen);
1245 if (rc)
1246 return 0;
1248 doc = parse_doc ((char *) crypto->plaintext, crypto->plaintext_len);
1249 if (!doc)
1251 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM));
1252 xfree (key);
1253 return 0;
1256 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
1257 cdata = xcalloc (1, sizeof (struct cache_data_s));
1258 if (!cdata)
1260 xmlFreeDoc (doc);
1261 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM));
1262 xfree (key);
1263 return 0;
1266 rc = get_checksum (filename, &crc, &len);
1267 if (rc)
1269 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1270 xmlFreeDoc (doc);
1271 free_cache_data_once (cdata);
1272 xfree (key);
1273 return 0;
1276 cdata->crc = crc;
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))
1282 cdata->key = key;
1283 cdata->keylen = keylen;
1285 else
1286 xfree (key);
1288 if (rc)
1290 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1291 xmlFreeDoc (doc);
1292 free_cache_data_once (cdata);
1293 return 0;
1296 #ifdef WITH_AGENT
1297 if (use_agent)
1299 gcry_sexp_build ((gcry_sexp_t *) & cdata->pubkey, NULL, "%S",
1300 crypto->pkey_sexp);
1301 gcry_sexp_build ((gcry_sexp_t *) & cdata->sigkey, NULL, "%S",
1302 crypto->sigpkey_sexp);
1304 #endif
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);
1309 return 1;
1312 static gpg_error_t
1313 init_client (int fd, const char *addr)
1315 gpg_error_t rc = 0;
1316 struct client_thread_s *new = xcalloc (1, sizeof (struct client_thread_s));
1318 if (!new)
1320 close (fd);
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 ();
1330 if (!rc)
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);
1337 if (!rc)
1339 #ifdef WITH_GNUTLS
1340 new->remote = addr ? 1 : 0;
1341 #endif
1342 new->fd = fd;
1343 rc = create_thread (client_thread, new, &new->tid, 1);
1344 if (rc)
1346 close (new->status_msg_pipe[0]);
1347 close (new->status_msg_pipe[1]);
1348 pthread_mutex_destroy (&new->status_mutex);
1352 if (!rc)
1354 struct slist_s *list = slist_append (cn_thread_list, new);
1356 if (list)
1358 cn_thread_list = list;
1359 if (addr)
1360 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1361 (pthread_t *) new->tid, fd, addr);
1362 else
1363 log_write (_("new connection: tid=%p, fd=%i"),
1364 (pthread_t *) new->tid, fd);
1366 else
1367 rc = GPG_ERR_ENOMEM;
1370 pthread_cleanup_pop (1);
1372 if (rc)
1374 xfree (new);
1375 close (fd);
1376 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1377 pwmd_strerror (rc));
1379 return rc;
1382 static void*
1383 keepalive_thread (void *arg)
1385 #ifndef HAVE_PTHREAD_CANCEL
1386 int *n = xmalloc (sizeof (int));
1388 *n = 0;
1389 pthread_setspecific (signal_thread_key, n);
1390 INIT_THREAD_SIGNAL;
1391 #endif
1393 #ifdef HAVE_PR_SET_NAME
1394 prctl (PR_SET_NAME, "keepalive");
1395 #endif
1396 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1398 for (;;)
1400 int n = config_get_integer ("global", "keepalive_interval");
1401 struct timeval tv = { n, 0 };
1402 #ifndef HAVE_PTHREAD_CANCEL
1403 int *sigusr2;
1405 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1406 if (*sigusr2)
1407 break;
1408 #endif
1410 send_status_all (STATUS_KEEPALIVE, NULL);
1411 select (0, NULL, NULL, NULL, &tv);
1414 return NULL;
1417 #ifdef WITH_GNUTLS
1418 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1419 static void *
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);
1428 static void *
1429 tcp_accept_thread (void *arg)
1431 int sockfd = *(int *) arg;
1432 #ifndef HAVE_PTHREAD_CANCEL
1433 int *n = xmalloc (sizeof (int));
1435 *n = 0;
1436 pthread_setspecific (signal_thread_key, n);
1437 INIT_THREAD_SIGNAL;
1438 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1439 #endif
1441 #ifdef HAVE_PR_SET_NAME
1442 prctl (PR_SET_NAME, "tcp_accept");
1443 #endif
1444 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1446 for (;;)
1448 struct sockaddr_storage raddr;
1449 socklen_t slen = sizeof (raddr);
1450 int fd = -1;
1451 unsigned long n;
1452 char s[INET6_ADDRSTRLEN];
1453 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1454 #ifndef HAVE_PTHREAD_CANCEL
1455 int *sigusr2;
1457 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1458 if (*sigusr2)
1459 break;
1460 #endif
1462 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1463 if (fd == -1)
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));
1473 break;
1476 #ifndef HAVE_PTHREAD_CANCEL
1477 select (0, NULL, NULL, NULL, &tv);
1478 #endif
1479 continue;
1482 if (quit)
1483 break;
1485 inet_ntop (raddr.ss_family, get_in_addr ((struct sockaddr *) &raddr),
1486 s, sizeof s);
1487 (void) init_client (fd, s);
1488 n = config_get_integer ("global", "tcp_wait");
1489 if (n > 0)
1491 tv.tv_sec = (n * 100000) / 100000;
1492 tv.tv_usec = (n * 100000) % 100000;
1493 select (0, NULL, NULL, NULL, &tv);
1497 return NULL;
1500 static int
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");
1505 char buf[7];
1506 int n;
1507 gpg_error_t rc;
1508 int *fd = ipv6 ? &tls6_fd : &tls_fd;
1510 if (term || config_get_boolean ("global", "enable_tcp") == 0)
1512 if (tls6_fd != -1)
1514 if (spawned_tls6)
1516 #ifdef HAVE_PTHREAD_CANCEL
1517 pthread_cancel (tls6_tid);
1518 #else
1519 pthread_kill (tls6_tid, SIGUSR2);
1520 #endif
1521 pthread_join (tls6_tid, NULL);
1524 shutdown (tls6_fd, SHUT_RDWR);
1525 close (tls6_fd);
1526 tls6_fd = -1;
1527 spawned_tls6 = 0;
1530 if (tls_fd != -1)
1532 if (spawned_tls)
1534 #ifdef HAVE_PTHREAD_CANCEL
1535 pthread_cancel (tls_tid);
1536 #else
1537 pthread_kill (tls_tid, SIGUSR2);
1538 #endif
1539 pthread_join (tls_tid, NULL);
1542 shutdown (tls_fd, SHUT_RDWR);
1543 close (tls_fd);
1544 tls_fd = -1;
1545 spawned_tls = 0;
1548 /* A client may still be connected. */
1549 if (!quit && x509_cred != NULL)
1550 tls_deinit_params ();
1552 return 1;
1555 if ((ipv6 && tls6_fd != -1) || (!ipv6 && tls_fd != -1))
1556 return 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));
1567 return 0;
1570 for (n = 0, p = servinfo; p != NULL; p = p->ai_next)
1572 int r = 1;
1574 if ((ipv6 && p->ai_family != AF_INET6)
1575 || (!ipv6 && p->ai_family != AF_INET))
1576 continue;
1578 if ((*fd = socket (p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
1580 log_write ("socket(): %s", strerror (errno));
1581 continue;
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);
1589 goto fail;
1592 if (bind (*fd, p->ai_addr, p->ai_addrlen) == -1)
1594 close (*fd);
1595 log_write ("bind(): %s",
1596 pwmd_strerror (gpg_error_from_syserror ()));
1597 continue;
1600 n++;
1601 break;
1604 freeaddrinfo (servinfo);
1606 if (!n)
1607 goto fail;
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 ()));
1616 xfree (tmp);
1617 goto fail;
1620 xfree (tmp);
1621 #endif
1623 if (x509_cred == NULL)
1625 rc = tls_init_params ();
1626 if (rc)
1627 goto fail;
1630 if (listen (*fd, 0) == -1)
1632 log_write ("listen(): %s", strerror (errno));
1633 goto fail;
1636 if (ipv6)
1637 rc = create_thread (tcp_accept_thread, fd, &tls6_tid, 0);
1638 else
1639 rc = create_thread (tcp_accept_thread, fd, &tls_tid, 0);
1641 if (rc)
1643 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1644 pwmd_strerror (rc));
1645 goto fail;
1648 if (ipv6)
1649 spawned_tls6 = 1;
1650 else
1651 spawned_tls = 1;
1653 return 1;
1655 fail:
1656 start_stop_tls_with_protocol (0, 1);
1657 if (tls_fd != -1)
1658 close (tls_fd);
1660 if (tls6_fd != -1)
1661 close (tls6_fd);
1663 tls_fd = -1;
1664 tls6_fd = -1;
1665 return 0;
1668 static int
1669 start_stop_tls (int term)
1671 char *s = config_get_string ("global", "tcp_bind");
1672 int b;
1674 if (!s)
1675 return 0;
1677 if (!strcmp (s, "any"))
1679 b = start_stop_tls_with_protocol (0, term);
1680 if (b)
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);
1687 else
1688 b = 0;
1690 xfree (s);
1691 return b;
1693 #endif
1695 static void *
1696 accept_thread (void *arg)
1698 int sockfd = *(int *) arg;
1699 #ifndef HAVE_PTHREAD_CANCEL
1700 int *n = xmalloc (sizeof (int));
1702 *n = 0;
1703 pthread_setspecific (signal_thread_key, n);
1704 INIT_THREAD_SIGNAL;
1705 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1706 #endif
1708 #ifdef HAVE_PR_SET_NAME
1709 prctl (PR_SET_NAME, "accept");
1710 #endif
1711 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1713 for (;;)
1715 socklen_t slen = sizeof (struct sockaddr_un);
1716 struct sockaddr_un raddr;
1717 int fd;
1718 #ifndef HAVE_PTHREAD_CANCEL
1719 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1720 int *sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1722 if (*sigusr2)
1723 break;
1724 #endif
1726 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1727 if (fd == -1)
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 ()));
1738 break;
1741 #ifndef HAVE_PTHREAD_CANCEL
1742 select (0, NULL, NULL, NULL, &tv);
1743 #endif
1744 continue;
1747 (void) init_client (fd, NULL);
1750 /* Just in case accept() failed for some reason other than EBADF */
1751 quit = 1;
1752 return NULL;
1755 static void *
1756 cache_timer_thread (void *arg)
1758 #ifndef HAVE_PTHREAD_CANCEL
1759 int *n = xmalloc (sizeof (int));
1761 *n = 0;
1762 pthread_setspecific (signal_thread_key, n);
1763 INIT_THREAD_SIGNAL;
1764 #endif
1766 #ifdef HAVE_PR_SET_NAME
1767 prctl (PR_SET_NAME, "cache timer");
1768 #endif
1769 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1771 for (;;)
1773 struct timeval tv = { 1, 0 };
1774 #ifndef HAVE_PTHREAD_CANCEL
1775 int *n;
1777 n = (int *) pthread_getspecific (signal_thread_key);
1778 if (*n)
1779 break;
1780 #endif
1782 select (0, NULL, NULL, NULL, &tv);
1783 cache_adjust_timeout ();
1786 return NULL;
1789 static void
1790 catch_sigabrt (int sig)
1792 cache_clear (NULL);
1793 #ifndef MEM_DEBUG
1794 xpanic ();
1795 #endif
1798 static int
1799 signal_loop (sigset_t sigset)
1801 int done = 0;
1802 int siint = 0;
1806 int sig;
1808 sigwait (&sigset, &sig);
1810 if (sig != SIGQUIT)
1811 log_write (_("caught signal %i (%s)"), sig, strsignal (sig));
1813 switch (sig)
1815 case SIGHUP:
1816 pthread_cond_signal (&rcfile_cond);
1817 break;
1818 case SIGABRT:
1819 // not really handled here.
1820 catch_sigabrt (SIGABRT);
1821 break;
1822 case SIGUSR1:
1823 log_write (_("clearing file cache"));
1824 cache_clear (NULL);
1825 send_status_all (STATUS_CACHE, NULL);
1826 break;
1827 case SIGQUIT:
1828 done = 1;
1829 break;
1830 default:
1831 siint = 1;
1832 done = 1;
1833 break;
1836 while (!done);
1838 return siint;
1841 static void
1842 catchsig (int sig)
1844 log_write ("Caught SIGSEGV. Exiting.");
1845 #ifdef HAVE_BACKTRACE
1846 BACKTRACE (__FUNCTION__);
1847 #endif
1848 longjmp (jmp, 1);
1851 static void *
1852 waiting_for_exit (void *arg)
1854 int last = 0;
1855 #ifndef HAVE_PTHREAD_CANCEL
1856 int *n = xmalloc (sizeof (int));
1858 *n = 0;
1859 pthread_setspecific (signal_thread_key, n);
1860 INIT_THREAD_SIGNAL;
1861 #endif
1863 #ifdef HAVE_PR_SET_NAME
1864 prctl (PR_SET_NAME, "exiting");
1865 #endif
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);
1871 for (;;)
1873 struct timespec ts;
1874 int n;
1876 MUTEX_LOCK (&cn_mutex);
1877 n = slist_length (cn_thread_list);
1878 MUTEX_UNLOCK (&cn_mutex);
1879 if (!n)
1880 break;
1882 #ifndef HAVE_PTHREAD_CANCEL
1883 int *s = (int *) pthread_getspecific (signal_thread_key);
1884 if (*s)
1885 break;
1886 #endif
1888 if (last != n)
1890 log_write (_("%i clients remain"), n);
1891 last = 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);
1900 return NULL;
1903 static int
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;
1910 sigset_t sigset;
1911 int n;
1912 int segv = 0;
1913 gpg_error_t rc;
1915 init_commands ();
1916 sigemptyset (&sigset);
1918 /* Termination */
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);
1938 #endif
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);
1948 #endif
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);
1958 #ifdef WITH_GNUTLS
1959 /* Needs to be done after the fork(). */
1960 if (!start_stop_tls (0))
1962 segv = 1;
1963 goto done;
1965 #endif
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 ());
1971 #ifdef WITH_GNUTLS
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"));
1975 else
1976 log_write (_("Listening on %s"), *socketpath);
1977 #else
1978 log_write (_("Listening on %s"), *socketpath);
1979 #endif
1981 rc = create_thread (keepalive_thread, NULL, &keepalive_tid, 0);
1982 if (rc)
1984 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1985 pwmd_strerror (rc));
1986 goto done;
1989 cancel_keepalive_thread = 1;
1990 rc = create_thread (reload_rcfile_thread, NULL, &rcfile_tid, 0);
1991 if (rc)
1993 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1994 pwmd_strerror (rc));
1995 goto done;
1998 rc = create_thread (cache_timer_thread, NULL, &cache_timeout_tid, 0);
1999 if (rc)
2001 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2002 pwmd_strerror (rc));
2003 goto done;
2006 cancel_timeout_thread = 1;
2007 rc = create_thread (accept_thread, &sockfd, &accept_tid, 0);
2008 if (rc)
2010 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2011 pwmd_strerror (rc));
2012 goto done;
2015 cancel_accept_thread = 1;
2016 if (!setjmp (jmp))
2017 signal_loop (sigset);
2018 else
2019 segv = 1;
2021 done:
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
2026 * sent.
2028 if (cancel_accept_thread)
2030 #ifdef HAVE_PTHREAD_CANCEL
2031 int n = pthread_cancel (accept_tid);
2032 #else
2033 int n = pthread_kill (accept_tid, SIGUSR2);
2034 #endif
2035 if (!n)
2036 pthread_join (accept_tid, NULL);
2039 #ifdef WITH_GNUTLS
2040 start_stop_tls (1);
2041 #endif
2042 shutdown (sockfd, SHUT_RDWR);
2043 close (sockfd);
2044 unlink (*socketpath);
2045 xfree (*socketpath);
2046 *socketpath = NULL;
2047 MUTEX_LOCK (&cn_mutex);
2048 n = slist_length (cn_thread_list);
2049 MUTEX_UNLOCK (&cn_mutex);
2051 if (n && !segv)
2053 pthread_t tid;
2055 rc = create_thread (waiting_for_exit, NULL, &tid, 0);
2056 if (!rc)
2058 if (signal_loop (sigset))
2060 log_write (_("Received second termination request. Exiting."));
2061 #ifdef HAVE_PTHREAD_CANCEL
2062 pthread_cancel (tid);
2063 #else
2064 pthread_kill (tid, SIGUSR2);
2065 #endif
2066 pthread_join (tid, NULL);
2069 else
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);
2078 #else
2079 pthread_kill (cache_timeout_tid, SIGUSR2);
2080 #endif
2081 pthread_join (cache_timeout_tid, NULL);
2084 if (cancel_keepalive_thread)
2086 #ifdef HAVE_PTHREAD_CANCEL
2087 pthread_cancel (keepalive_tid);
2088 #else
2089 pthread_kill (keepalive_tid, SIGUSR2);
2090 #endif
2091 pthread_join (keepalive_tid, NULL);
2094 cleanup_all_clients (0);
2095 #ifdef WITH_GNUTLS
2096 start_stop_tls (1);
2097 #endif
2098 deinit_commands ();
2099 pthread_cond_destroy (&quit_cond);
2100 pthread_mutex_destroy (&quit_mutex);
2101 return segv ? EXIT_FAILURE : EXIT_SUCCESS;;
2104 static void
2105 startup_failure ()
2107 log_write (_
2108 ("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
2109 cache_clear (NULL);
2112 /* This is called from cache.c:clear_once(). See
2113 * command.c:clearcache_command() for details about lock checking.
2115 static gpg_error_t
2116 free_cache_data (file_cache_t * cache)
2118 gpg_error_t rc = GPG_ERR_NO_DATA;
2119 int i, t;
2120 struct client_thread_s *found = NULL;
2121 int self = 0;
2123 if (!cache->data)
2124 return 0;
2126 cache_lock ();
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);
2135 if (!thd->cl)
2136 continue;
2138 if (!memcmp (thd->cl->md5file, cache->filename,
2139 sizeof (cache->filename)))
2141 if (pthread_equal (pthread_self (), thd->tid))
2143 found = thd;
2144 self = 1;
2145 continue;
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);
2151 if (!rc)
2153 self = 0;
2154 found = thd;
2155 break;
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);
2166 cache->data = NULL;
2167 cache->defer_clear = 0;
2168 cache->timeout = -1;
2170 if (found)
2171 cache_unlock_mutex (found->cl->md5file, 0);
2173 rc = 0;
2176 if (rc)
2177 cache->defer_clear = 1;
2179 pthread_cleanup_pop (1);
2180 cache_unlock ();
2181 return rc;
2184 static int
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)
2191 gpg_error_t rc;
2192 void *data = NULL;
2193 size_t datalen;
2194 struct crypto_s *crypto = NULL;
2195 uint16_t ver;
2196 int algo;
2197 void *key = NULL;
2198 size_t keylen = 0;
2200 if (outfile[0] == '-' && outfile[1] == 0)
2201 outfile = NULL;
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 ()));
2208 return 0;
2211 if (keyfile)
2213 log_write (_("Using passphrase file \"%s\" for decryption ..."),
2214 keyfile);
2215 if (access (keyfile, R_OK) == -1)
2217 log_write ("%s: %s", keyfile,
2218 pwmd_strerror (gpg_error_from_syserror ()));
2219 return 0;
2223 rc = read_v2_datafile (filename, keyfile, &data, &datalen, &ver, &algo);
2224 if (rc)
2226 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2227 return 0;
2230 if (cipher)
2232 algo = cipher_string_to_gcrypt (cipher);
2233 if (algo == -1)
2235 rc = GPG_ERR_CIPHER_ALGO;
2236 goto fail;
2240 if (ver < 0x212)
2242 xmlDocPtr doc = parse_doc (data, datalen);
2244 if (!doc)
2246 rc = GPG_ERR_BAD_DATA;
2247 goto fail;
2250 rc = convert_pre_212_elements (doc);
2251 gcry_free (data);
2252 data = NULL;
2253 if (!rc)
2255 xmlDocDumpFormatMemory (doc, (xmlChar **) & data, (int *) &datalen,
2257 if (!data)
2258 rc = GPG_ERR_ENOMEM;
2261 xmlFreeDoc (doc);
2262 if (rc)
2263 goto fail;
2266 rc = init_client_crypto (&crypto);
2267 if (!rc)
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;
2274 if (!use_agent)
2276 rc = export_common (NULL, 0, crypto, data, datalen, outfile, keyfile,
2277 &key, &keylen, 0, 0);
2279 #ifdef WITH_AGENT
2280 else
2282 rc = agent_set_pinentry_options (crypto->agent);
2283 if (!rc)
2284 rc = agent_export_common (crypto, keygrip, sign_keygrip, nopass,
2285 data, datalen, outfile, keyparam,
2286 no_passphrase_file ? NULL : keyfile);
2288 #endif
2289 if (!rc)
2290 log_write (_("Output written to \"%s\"."), outfile);
2293 fail:
2294 if (ver < 0x212)
2295 xmlFree (data);
2296 else
2297 gcry_free (data);
2299 gcry_free (key);
2300 cleanup_crypto (&crypto);
2302 if (rc)
2303 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2304 return rc ? 0 : 1;
2307 static void
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"
2316 #ifdef WITH_AGENT
2317 " --no-agent disable use of gpg-agent\n"
2318 #endif
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"
2328 " converting\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"),
2338 pn);
2339 exit (status);
2343 main (int argc, char *argv[])
2345 int opt;
2346 struct sockaddr_un addr;
2347 char buf[PATH_MAX];
2348 char *socketpath = NULL, *socketdir, *socketname = NULL;
2349 char *socketarg = NULL;
2350 char *datadir = NULL;
2351 int x;
2352 char *p;
2353 char **cache_push = NULL;
2354 char *import = NULL, *keygrip = NULL, *sign_keygrip = NULL;
2355 char *keyparam = NULL;
2356 int estatus = EXIT_FAILURE;
2357 int sockfd;
2358 char *outfile = NULL;
2359 int do_unlink = 0;
2360 int secure = 0;
2361 int show_version = 0;
2362 int force = 0;
2363 int no_passphrase = 0;
2364 gpg_error_t rc;
2365 char *convertfile = NULL;
2366 char *cipher = NULL;
2367 char *keyfile = NULL;
2368 unsigned long s2k_count = 0;
2369 uint64_t iterations = 0;
2370 int exists;
2371 char *debug_level_opt = NULL;
2372 int optindex;
2373 /* Must maintain the same order as longopts[] */
2374 enum
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},
2404 {0, 0, 0, 0}
2407 #ifndef DEBUG
2408 #ifdef HAVE_SETRLIMIT
2409 struct rlimit rl;
2411 rl.rlim_cur = rl.rlim_max = 0;
2413 if (setrlimit (RLIMIT_CORE, &rl) != 0)
2414 err (EXIT_FAILURE, "setrlimit()");
2415 #endif
2416 #endif
2418 #ifdef ENABLE_NLS
2419 setlocale (LC_ALL, "");
2420 bindtextdomain ("pwmd", LOCALEDIR);
2421 textdomain ("pwmd");
2422 #endif
2424 #ifndef MEM_DEBUG
2425 xmem_init ();
2426 #endif
2427 gpg_err_init ();
2429 if (setup_crypto ())
2430 exit (EXIT_FAILURE);
2432 #ifdef WITH_GNUTLS
2433 gnutls_global_set_mem_functions (xmalloc, xmalloc, secure_mem_check,
2434 xrealloc, xfree);
2435 gnutls_global_init ();
2436 gnutls_global_set_log_function (tls_log);
2437 gnutls_global_set_log_level (1);
2438 tls_fd = -1;
2439 tls6_fd = -1;
2440 #endif
2441 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
2442 xmlInitMemory ();
2443 xmlInitGlobals ();
2444 xmlInitParser ();
2445 xmlXPathInit ();
2446 cmdline = 1;
2447 #ifdef WITH_AGENT
2448 use_agent = 1;
2449 #endif
2451 while ((opt =
2452 getopt_long (argc, argv, optstring, longopts, &optindex)) != -1)
2454 switch (opt)
2456 case 'I':
2457 import = optarg;
2458 break;
2459 case 'C':
2460 convertfile = optarg;
2461 break;
2462 case 'k':
2463 keyfile = optarg;
2464 break;
2465 case 'o':
2466 outfile = optarg;
2467 break;
2468 case 'D':
2469 secure = 1;
2470 break;
2471 case 'n':
2472 nofork = 1;
2473 break;
2474 case 'f':
2475 rcfile = str_dup (optarg);
2476 break;
2477 default:
2478 usage (argv[0], EXIT_FAILURE);
2479 break;
2480 case 0:
2481 switch (optindex)
2483 case OPT_VERSION:
2484 show_version = 1;
2485 break;
2486 case OPT_HELP:
2487 usage (argv[0], 0);
2488 break;
2489 case OPT_NO_AGENT:
2490 use_agent = 0;
2491 break;
2492 case OPT_DEBUG_LEVEL:
2493 debug_level_opt = optarg;
2494 break;
2495 case OPT_HOMEDIR:
2496 homedir = str_dup (optarg);
2497 break;
2498 case OPT_NO_FORK:
2499 nofork = 1;
2500 break;
2501 case OPT_DISABLE_DUMP:
2502 secure = 1;
2503 break;
2504 case OPT_IGNORE:
2505 force = 1;
2506 break;
2507 case OPT_RCFILE:
2508 rcfile = str_dup (optarg);
2509 break;
2510 case OPT_CONVERT:
2511 convertfile = optarg;
2512 break;
2513 case OPT_PASSPHRASE_FILE:
2514 keyfile = optarg;
2515 break;
2516 case OPT_IMPORT:
2517 import = optarg;
2518 break;
2519 case OPT_OUTFILE:
2520 outfile = optarg;
2521 break;
2522 case OPT_NO_PASSPHRASE_FILE:
2523 no_passphrase_file = 1;
2524 break;
2525 case OPT_KEYGRIP:
2526 keygrip = optarg;
2527 break;
2528 case OPT_SIGN_KEYGRIP:
2529 sign_keygrip = optarg;
2530 break;
2531 case OPT_KEYPARAM:
2532 keyparam = optarg;
2533 break;
2534 case OPT_CIPHER:
2535 cipher = optarg;
2536 break;
2537 case OPT_ITERATIONS:
2538 iterations = strtoull (optarg, NULL, 10);
2539 break;
2540 case OPT_S2K_COUNT:
2541 s2k_count = strtoul (optarg, NULL, 10);
2542 break;
2543 case OPT_NO_PASSPHRASE:
2544 no_passphrase = 1;
2545 break;
2546 default:
2547 usage (argv[0], 1);
2552 if (show_version)
2554 printf (_("%s\n\n"
2555 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013\n"
2556 "%s\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,
2559 PACKAGE_BUGREPORT,
2560 #ifdef PWMD_HOMEDIR
2561 "+PWMD_HOMEDIR=" PWMD_HOMEDIR "\n"
2562 #endif
2563 #ifdef WITH_AGENT
2564 "+WITH_AGENT\n"
2565 #else
2566 "-WITH_AGENT\n"
2567 #endif
2568 #ifdef WITH_QUALITY
2569 "+WITH_QUALITY\n"
2570 #else
2571 "-WITH_QUALITY\n"
2572 #endif
2573 #ifdef WITH_GNUTLS
2574 "+WITH_GNUTLS\n"
2575 #else
2576 "-WITH_GNUTLS\n"
2577 #endif
2578 #ifdef WITH_LIBACL
2579 "+WITH_LIBACL\n"
2580 #else
2581 "-WITH_LIBACL\n"
2582 #endif
2583 #ifdef DEBUG
2584 "+DEBUG\n"
2585 #else
2586 "-DEBUG\n"
2587 #endif
2588 #ifdef MEM_DEBUG
2589 "+MEM_DEBUG\n"
2590 #else
2591 "-MEM_DEBUG\n"
2592 #endif
2593 #ifdef MUTEX_DEBUG
2594 "+MUTEX_DEBUG\n"
2595 #else
2596 "-MUTEX_DEBUG\n"
2597 #endif
2599 exit (EXIT_SUCCESS);
2602 if (!homedir)
2603 #ifdef PWMD_HOMEDIR
2604 homedir = str_dup(PWMD_HOMEDIR);
2605 #else
2606 homedir = str_asprintf ("%s/.pwmd", get_home_dir ());
2607 #endif
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);
2627 #endif
2629 if (!rcfile)
2630 rcfile = str_asprintf ("%s/config", homedir);
2632 global_config = config_parse (rcfile);
2633 if (!global_config)
2634 exit (EXIT_FAILURE);
2636 setup_logging ();
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))
2644 errno = 0;
2645 if (setpriority (PRIO_PROCESS, 0, x) == -1)
2647 log_write ("setpriority(): %s",
2648 pwmd_strerror (gpg_error_from_syserror ()));
2649 goto do_exit;
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 ()));
2657 goto do_exit;
2659 #endif
2661 rc = cache_init (free_cache_data);
2662 if (rc)
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));
2668 goto do_exit;
2671 if (s2k_count == 0)
2672 s2k_count = config_get_ulong (NULL, "s2k_count");
2674 if (convertfile)
2676 if (!outfile)
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);
2683 xfree (rcfile);
2684 exit (!estatus);
2687 if (import)
2689 if (!outfile || !*outfile)
2690 usage (argv[0], EXIT_FAILURE);
2692 if (outfile && outfile[0] == '-' && outfile[1] == 0)
2693 outfile = NULL;
2695 estatus = xml_import (import, outfile, keygrip, sign_keygrip, keyfile,
2696 no_passphrase, cipher, keyparam, s2k_count,
2697 iterations);
2698 config_free (global_config);
2699 xfree (rcfile);
2700 exit (!estatus);
2703 p = config_get_string ("global", "socket_path");
2704 if (!p)
2705 p = str_asprintf ("%s/socket", homedir);
2707 socketarg = expand_homedir (p);
2708 xfree (p);
2710 if (!secure)
2711 disable_list_and_dump = config_get_boolean ("global",
2712 "disable_list_and_dump");
2713 else
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);
2730 else
2732 socketname = str_dup (strrchr (socketarg, '/'));
2733 socketname++;
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);
2744 goto do_exit;
2748 * Set the cache entry for a file. Prompts for the password.
2750 if (cache_push)
2752 struct crypto_s *crypto = NULL;
2753 gpg_error_t rc = init_client_crypto (&crypto);
2755 if (rc)
2757 estatus = EXIT_FAILURE;
2758 goto do_exit;
2761 #ifdef WITH_AGENT
2762 if (use_agent)
2764 rc = agent_set_pinentry_options (crypto->agent);
2765 if (rc)
2767 estatus = EXIT_FAILURE;
2768 goto do_exit;
2771 #endif
2773 for (opt = 0; cache_push[opt]; opt++)
2775 if (!do_cache_push (cache_push[opt], crypto) && !force)
2777 strv_free (cache_push);
2778 startup_failure ();
2779 estatus = EXIT_FAILURE;
2780 cleanup_crypto (&crypto);
2781 goto do_exit;
2784 cleanup_crypto_stage1 (crypto);
2787 #ifdef WITH_AGENT
2788 if (use_agent)
2789 (void) kill_scd (crypto->agent);
2790 #endif
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 ()));
2809 goto do_exit;
2812 xfree (socketdir);
2814 if ((sockfd = socket (PF_UNIX, SOCK_STREAM, 0)) == -1)
2816 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_syserror ()));
2817 goto do_exit;
2820 addr.sun_family = AF_UNIX;
2821 snprintf (addr.sun_path, sizeof (addr.sun_path), "%s", socketname);
2822 do_unlink = 1;
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);
2832 goto do_exit;
2836 char *t = config_get_string ("global", "socket_perms");
2837 mode_t mode;
2838 mode_t mask;
2840 if (t)
2842 mode = strtol (t, NULL, 8);
2843 mask = umask (0);
2844 xfree (t);
2846 if (chmod (socketname, mode) == -1)
2848 log_write ("%s: %s", socketname,
2849 pwmd_strerror (gpg_error_from_syserror ()));
2850 close (sockfd);
2851 umask (mask);
2852 goto do_exit;
2855 umask (mask);
2859 xfree (--socketname);
2861 if (chdir (datadir))
2863 log_write ("%s: %s", datadir,
2864 pwmd_strerror (gpg_error_from_syserror ()));
2865 close (sockfd);
2866 goto do_exit;
2869 xfree (datadir);
2871 if (listen (sockfd, 0) == -1)
2873 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_syserror ()));
2874 goto do_exit;
2877 cmdline = 0;
2879 if (!nofork)
2881 switch (fork ())
2883 case -1:
2884 log_write ("fork(): %s",
2885 pwmd_strerror (gpg_error_from_syserror ()));
2886 goto do_exit;
2887 case 0:
2888 close (0);
2889 close (1);
2890 close (2);
2891 setsid ();
2892 break;
2893 default:
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);
2902 do_exit:
2903 if (socketpath && do_unlink)
2905 unlink (socketpath);
2906 xfree (socketpath);
2909 xfree (socketarg);
2910 #ifdef WITH_GNUTLS
2911 gnutls_global_deinit ();
2912 #endif
2913 if (rcfile_tid)
2915 #ifdef HAVE_PTHREAD_CANCEL
2916 pthread_cancel (rcfile_tid);
2917 #else
2918 pthread_kill (rcfile_tid, SIGUSR2);
2919 pthread_cond_signal (&rcfile_cond);
2920 #endif
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);
2930 #endif
2932 if (global_config)
2933 config_free (global_config);
2935 xfree (rcfile);
2936 xfree (home_directory);
2937 xfree (homedir);
2938 xmlCleanupParser ();
2939 xmlCleanupGlobals ();
2941 if (estatus == EXIT_SUCCESS)
2942 log_write (_("pwmd exiting normally"));
2944 closelog ();
2945 #if defined(DEBUG) && !defined(MEM_DEBUG)
2946 xdump ();
2947 #endif
2948 exit (estatus);