Add "socket_timeout" configuration parameter.
[pwmd.git] / src / pwmd.c
blob7f19ae2ea6c28e937cc5a9a80037990b6bdf57be
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;
104 #ifndef HAVE_PTHREAD_CANCEL
105 static pthread_key_t signal_thread_key;
106 #endif
108 #ifdef WITH_GNUTLS
109 static int tls_fd;
110 static int tls6_fd;
111 static pthread_t tls_tid;
112 static pthread_t tls6_tid;
113 static int spawned_tls;
114 static int spawned_tls6;
116 static int start_stop_tls (int term);
117 #endif
119 static int do_cache_push (const char *filename, struct crypto_s *crypto);
120 static int signal_loop (sigset_t sigset);
122 GCRY_THREAD_OPTION_PTHREAD_IMPL;
124 #ifndef HAVE_PTHREAD_CANCEL
125 #define INIT_THREAD_SIGNAL do { \
126 struct sigaction act; \
127 sigset_t sigset; \
128 sigemptyset (&sigset); \
129 sigaddset (&sigset, SIGUSR2); \
130 pthread_sigmask (SIG_UNBLOCK, &sigset, NULL); \
131 memset (&act, 0, sizeof(act)); \
132 act.sa_flags = SA_SIGINFO; \
133 act.sa_mask = sigset; \
134 act.sa_sigaction = catch_thread_signal; \
135 sigaction (SIGUSR2, &act, NULL); \
136 } while (0)
138 static void
139 catch_thread_signal (int sig, siginfo_t *info, void *ctx)
141 int *n = (int *) pthread_getspecific (signal_thread_key);
143 *n = 1;
144 pthread_setspecific (signal_thread_key, n);
146 #endif
148 static void
149 cache_push_from_rcfile ()
151 struct crypto_s *crypto = NULL;
152 char **cache_push;
153 gpg_error_t rc = init_client_crypto (&crypto);
155 if (rc)
157 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
158 return;
161 #ifdef WITH_AGENT
162 if (use_agent)
164 rc = set_agent_option (crypto->agent, "pinentry-mode", "error");
165 if (rc)
167 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
168 return;
171 #endif
173 cache_push = config_get_list ("global", "cache_push");
174 if (cache_push)
176 char **p;
178 for (p = cache_push; *p; p++)
180 (void) do_cache_push (*p, crypto);
181 cleanup_crypto_stage1 (crypto);
184 strv_free (cache_push);
187 #ifdef WITH_AGENT
188 (void) kill_scd (crypto->agent);
189 #endif
190 cleanup_crypto (&crypto);
193 static void
194 setup_logging ()
196 int n = config_get_boolean ("global", "enable_logging");
198 if (n)
200 char *p = config_get_string ("global", "log_path");
202 xfree (logfile);
203 logfile = expand_homedir (p);
204 xfree (p);
206 else
208 xfree (logfile);
209 logfile = NULL;
212 log_syslog = config_get_boolean ("global", "syslog");
213 if (log_syslog == 1)
214 openlog ("pwmd", LOG_NDELAY | LOG_PID, LOG_DAEMON);
217 static void *
218 reload_rcfile_thread (void *arg)
220 #ifndef HAVE_PTHREAD_CANCEL
221 int *n = xmalloc (sizeof (int));
223 *n = 0;
224 pthread_setspecific (signal_thread_key, n);
225 INIT_THREAD_SIGNAL;
226 #endif
228 #ifdef HAVE_PR_SET_NAME
229 prctl (PR_SET_NAME, "reload rcfile");
230 #endif
231 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
232 MUTEX_LOCK (&rcfile_mutex);
233 pthread_cleanup_push (cleanup_mutex_cb, &rcfile_mutex);
235 for (;;)
237 struct slist_s *config;
238 char **users;
239 int b = disable_list_and_dump;
240 #ifdef WITH_GNUTLS
241 int exists;
242 int tcp_require_key = config_get_bool_param (global_config, "global",
243 "tcp_require_key",
244 &exists);
245 #endif
247 pthread_cond_wait (&rcfile_cond, &rcfile_mutex);
248 #ifndef HAVE_PTHREAD_CANCEL
249 int *n = (int *) pthread_getspecific (signal_thread_key);
250 if (*n)
251 break;
252 #endif
254 users = config_get_list ("global", "allowed");
255 log_write (_("reloading configuration file '%s'"), rcfile);
256 config = config_parse (rcfile);
257 if (config)
259 config_free (global_config);
260 global_config = config;
261 setup_logging ();
262 cache_push_from_rcfile ();
263 config_clear_keys ();
266 disable_list_and_dump = !disable_list_and_dump ? b : 1;
267 #ifdef WITH_GNUTLS
268 if (config_get_bool_param (global_config, "global", "tcp_require_key",
269 &exists) && exists)
270 tcp_require_key = 1;
272 config_set_bool_param (&global_config, "global", "tcp_require_key",
273 tcp_require_key ? "true" : "false");
274 #endif
275 char *tmp = strv_join (",", users);
276 config_set_list_param (&global_config, "global", "allowed", tmp);
277 xfree (tmp);
278 strv_free (users);
279 #ifdef WITH_GNUTLS
280 /* Kill existing listening threads since the configured listening
281 * protocols may have changed. */
282 start_stop_tls (1);
283 start_stop_tls (0);
284 #endif
287 pthread_cleanup_pop (1);
288 return NULL;
291 gpg_error_t
292 send_error (assuan_context_t ctx, gpg_error_t e)
294 struct client_s *client = assuan_get_pointer (ctx);
296 if (gpg_err_source (e) == GPG_ERR_SOURCE_UNKNOWN)
297 e = gpg_error (e);
299 if (client)
300 client->last_rc = e;
302 if (!e)
303 return assuan_process_done (ctx, 0);
305 if (!ctx)
307 log_write ("%s", pwmd_strerror (e));
308 return e;
311 if (client && gpg_err_code (e) == GPG_ERR_BAD_DATA)
313 xmlErrorPtr xe = client->xml_error;
315 if (!xe)
316 xe = xmlGetLastError ();
317 if (xe)
319 log_write ("%s", xe->message);
320 if (client->last_error)
321 xfree (client->last_error);
323 client->last_error = str_dup (xe->message);
326 e = assuan_process_done (ctx, assuan_set_error (ctx, e,
327 xe ? xe->message :
328 NULL));
330 if (xe == client->xml_error)
331 xmlResetError (xe);
332 else
333 xmlResetLastError ();
335 client->xml_error = NULL;
336 return e;
339 return assuan_process_done (ctx,
340 assuan_set_error (ctx, e, pwmd_strerror (e)));
344 assuan_log_cb (assuan_context_t ctx, void *data, unsigned cat,
345 const char *msg)
347 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
348 int i, t;
349 int match = 0;
351 pthread_mutex_lock (&m);
352 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock, &m);
353 t = strv_length (debug_level);
355 for (i = 0; i < t; i++)
357 if (!strcasecmp (debug_level[i], (char *) "init")
358 && cat == ASSUAN_LOG_INIT)
360 match = 1;
361 break;
364 if (!strcasecmp (debug_level[i], (char *) "ctx")
365 && cat == ASSUAN_LOG_CTX)
367 match = 1;
368 break;
371 if (!strcasecmp (debug_level[i], (char *) "engine")
372 && cat == ASSUAN_LOG_ENGINE)
374 match = 1;
375 break;
378 if (!strcasecmp (debug_level[i], (char *) "data")
379 && cat == ASSUAN_LOG_DATA)
381 match = 1;
382 break;
385 if (!strcasecmp (debug_level[i], (char *) "sysio")
386 && cat == ASSUAN_LOG_SYSIO)
388 match = 1;
389 break;
392 if (!strcasecmp (debug_level[i], (char *) "control")
393 && cat == ASSUAN_LOG_CONTROL)
395 match = 1;
396 break;
400 if (match && msg)
402 if (logfile)
404 int fd;
406 if ((fd =
407 open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600)) == -1)
408 warn ("%s", logfile);
409 else
411 pthread_cleanup_push (cleanup_fd_cb, &fd);
412 write (fd, msg, strlen (msg));
413 pthread_cleanup_pop (1);
417 if (nofork)
419 fprintf (stderr, "%s%s", data ? (char *) data : "", msg);
420 fflush (stderr);
424 pthread_cleanup_pop (1);
425 return match;
428 void
429 log_write (const char *fmt, ...)
431 char *args, *line;
432 va_list ap;
433 struct tm *tm;
434 time_t now;
435 char tbuf[21];
436 int fd = -1;
437 char *name = NULL;
438 char buf[255];
439 pthread_t tid = pthread_self ();
440 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
442 if ((!logfile && !isatty (STDERR_FILENO) && !log_syslog) || !fmt)
443 return;
445 pthread_mutex_lock (&m);
446 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock, &m);
447 pthread_cleanup_push (cleanup_fd_cb, &fd);
449 if (!cmdline && logfile)
451 if ((fd = open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600)) == -1)
452 warn ("%s", logfile);
455 va_start (ap, fmt);
457 if (str_vasprintf (&args, fmt, ap) != -1)
459 if (cmdline)
461 pthread_cleanup_push (xfree, args);
462 fprintf (stderr, "%s\n", args);
463 fflush (stderr);
464 pthread_cleanup_pop (1);
466 else
468 pthread_cleanup_push (xfree, args);
469 name = pthread_getspecific (thread_name_key);
470 snprintf (buf, sizeof (buf), "%s(%p): ", name ? name : _("unknown"),
471 (pthread_t *) tid);
472 name = buf;
474 if (!cmdline && log_syslog && !nofork)
475 syslog (LOG_INFO, "%s%s", name, args);
477 time (&now);
478 tm = localtime (&now);
479 strftime (tbuf, sizeof (tbuf), "%b %d %Y %H:%M:%S ", tm);
480 tbuf[sizeof (tbuf) - 1] = 0;
482 if (args[strlen (args) - 1] == '\n')
483 args[strlen (args) - 1] = 0;
485 line = str_asprintf ("%s %i %s%s\n", tbuf, getpid (), name, args);
486 pthread_cleanup_pop (1);
487 if (line)
489 pthread_cleanup_push (xfree, line);
490 if (logfile && fd != -1)
492 write (fd, line, strlen (line));
493 fsync (fd);
496 if (nofork)
498 fprintf (stdout, "%s", line);
499 fflush (stdout);
502 pthread_cleanup_pop (1);
507 va_end (ap);
508 pthread_cleanup_pop (1);
509 pthread_cleanup_pop (0);
510 pthread_mutex_unlock (&m);
513 #ifdef WITH_GNUTLS
514 static int
515 secure_mem_check (const void *arg)
517 return 1;
519 #endif
521 static gpg_error_t
522 setup_crypto ()
524 gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
526 if (!gcry_check_version (GCRYPT_VERSION))
528 fprintf (stderr, _("gcry_check_version(): Incompatible libgcrypt. "
529 "Wanted %s, got %s.\n"), GCRYPT_VERSION,
530 gcry_check_version (NULL));
531 return GPG_ERR_UNKNOWN_VERSION;
534 gcry_set_allocation_handler (xmalloc, xmalloc, NULL, xrealloc, xfree);
535 return 0;
538 #ifdef HAVE_GETGRNAM_R
539 static gpg_error_t
540 do_validate_peer (struct client_s *cl, assuan_peercred_t * peer)
542 char **users;
543 int allowed = 0;
544 gpg_error_t rc;
546 rc = assuan_get_peercred (cl->ctx, peer);
547 if (rc)
548 return rc;
550 users = config_get_list ("global", "allowed");
551 if (users)
553 for (char **p = users; *p; p++)
555 struct passwd pw, *result;
556 struct group gr, *gresult;
557 char *buf;
559 if (*(*p) == '@')
561 size_t len = sysconf (_SC_GETGR_R_SIZE_MAX);
563 if (len == -1)
564 len = 16384;
566 buf = xmalloc (len);
567 if (!buf)
569 strv_free (users);
570 return GPG_ERR_ENOMEM;
573 if (!getgrnam_r (*(p) + 1, &gr, buf, len, &gresult) && gresult)
575 if (gresult->gr_gid == (*peer)->gid)
577 xfree (buf);
578 allowed = 1;
579 break;
582 len = sysconf (_SC_GETPW_R_SIZE_MAX);
583 if (len == -1)
584 len = 16384;
586 char *tbuf = xmalloc (len);
587 for (char **t = gresult->gr_mem; *t; t++)
589 if (!getpwnam_r (*t, &pw, tbuf, len, &result) && result)
591 if (result->pw_uid == (*peer)->uid)
593 xfree (buf);
594 allowed = 1;
595 break;
600 xfree (tbuf);
602 if (allowed)
603 break;
606 else
608 size_t len = sysconf (_SC_GETPW_R_SIZE_MAX);
610 if (len == -1)
611 len = 16384;
613 buf = xmalloc (len);
615 if (!buf)
617 strv_free (users);
618 return GPG_ERR_ENOMEM;
621 if (!getpwnam_r (*p, &pw, buf, len, &result) && result)
623 if (result->pw_uid == (*peer)->uid)
625 xfree (buf);
626 allowed = 1;
627 break;
632 xfree (buf);
635 strv_free (users);
638 return allowed ? 0 : GPG_ERR_INV_USER_ID;
640 #else
641 static gpg_error_t
642 do_validate_peer (struct client_s *cl, assuan_peercred_t * peer)
644 char **users;
645 int allowed = 0;
646 gpg_error_t rc;
648 rc = assuan_get_peercred (cl->ctx, peer);
649 if (rc)
650 return rc;
652 users = config_get_list ("global", "allowed");
653 if (users)
655 for (char **p = users; *p; p++)
657 struct passwd *result;
658 struct group *gresult;
660 if (*(*p) == '@')
662 gresult = getgrnam (*(p) + 1);
663 if (gresult && gresult->gr_gid == (*peer)->gid)
665 allowed = 1;
666 break;
669 for (char **t = gresult->gr_mem; *t; t++)
671 result = getpwnam (*t);
672 if (result && result->pw_uid == (*peer)->uid)
674 allowed = 1;
675 break;
679 else
681 result = getpwnam (*p);
682 if (result && result->pw_uid == (*peer)->uid)
684 allowed = 1;
685 break;
689 if (allowed)
690 break;
693 strv_free (users);
696 return allowed ? 0 : GPG_ERR_INV_USER_ID;
698 #endif
700 static gpg_error_t
701 validate_peer (struct client_s *cl)
703 gpg_error_t rc;
704 assuan_peercred_t peer;
706 #ifdef WITH_GNUTLS
707 if (cl->thd->remote)
708 return 0;
709 #endif
711 rc = do_validate_peer (cl, &peer);
712 if (!rc || gpg_err_code (rc) == GPG_ERR_INV_USER_ID)
713 log_write ("peer %s: uid=%i, gid=%i, pid=%i",
714 !rc ? _("accepted") : _("rejected"), peer->uid, peer->gid,
715 peer->pid);
716 else if (rc)
717 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
719 return rc;
722 static void
723 xml_error_cb (void *data, xmlErrorPtr e)
725 struct client_s *client = data;
728 * Keep the first reported error as the one to show in the error
729 * description. Reset in send_error().
731 if (client->xml_error)
732 return;
734 xmlCopyError (e, client->xml_error);
737 static pid_t
738 hook_waitpid (assuan_context_t ctx, pid_t pid, int action,
739 int *status, int options)
741 return waitpid (pid, status, options);
744 static ssize_t
745 hook_read (assuan_context_t ctx, assuan_fd_t fd, void *data, size_t len)
747 #ifdef WITH_GNUTLS
748 struct client_s *client = assuan_get_pointer (ctx);
750 if (client->thd->remote)
751 return tls_read_hook (ctx, (int) fd, data, len);
752 #endif
754 return read ((int) fd, data, len);
757 static ssize_t
758 hook_write (assuan_context_t ctx, assuan_fd_t fd,
759 const void *data, size_t len)
761 #ifdef WITH_GNUTLS
762 struct client_s *client = assuan_get_pointer (ctx);
764 if (client->thd->remote)
765 return tls_write_hook (ctx, (int) fd, data, len);
766 #endif
768 return write ((int) fd, data, len);
771 static int
772 new_connection (struct client_s *cl)
774 gpg_error_t rc;
775 static struct assuan_malloc_hooks mhooks = { xmalloc, xrealloc, xfree };
776 static struct assuan_system_hooks shooks = {
777 ASSUAN_SYSTEM_HOOKS_VERSION,
778 __assuan_usleep,
779 __assuan_pipe,
780 __assuan_close,
781 hook_read,
782 hook_write,
783 //FIXME
784 NULL, //recvmsg
785 NULL, //sendmsg both are used for FD passing
786 __assuan_spawn,
787 hook_waitpid,
788 __assuan_socketpair,
789 __assuan_socket,
790 __assuan_connect
793 #ifdef WITH_GNUTLS
794 if (cl->thd->remote)
796 char *prio = config_get_string ("global", "tls_cipher_suite");
798 cl->thd->tls = tls_init (cl->thd->fd, cl->thd->timeout, prio);
799 xfree (prio);
800 if (!cl->thd->tls)
801 return 0;
803 #endif
805 rc = assuan_new_ext (&cl->ctx, GPG_ERR_SOURCE_DEFAULT, &mhooks,
806 debug_level ? assuan_log_cb : NULL, NULL);
807 if (rc)
808 goto fail;
810 assuan_ctx_set_system_hooks (cl->ctx, &shooks);
811 rc = assuan_init_socket_server (cl->ctx, cl->thd->fd, 2);
812 if (rc)
813 goto fail;
815 assuan_set_pointer (cl->ctx, cl);
816 assuan_set_hello_line (cl->ctx, PACKAGE_STRING);
817 rc = register_commands (cl->ctx);
818 if (rc)
819 goto fail;
821 if (cl->thd->remote)
823 cl->thd->timeout = config_get_integer ("global", "tls_timeout");
824 fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK);
827 rc = assuan_accept (cl->ctx);
828 if (rc)
829 goto fail;
831 rc = validate_peer (cl);
832 /* May not be implemented on all platforms. */
833 if (rc && gpg_err_code (rc) != GPG_ERR_ASS_GENERAL)
834 goto fail;
836 rc = init_client_crypto (&cl->crypto);
837 if (rc)
838 goto fail;
840 #ifdef WITH_AGENT
841 if (use_agent)
842 cl->crypto->agent->client_ctx = cl->ctx;
843 #endif
845 cl->crypto->client_ctx = cl->ctx;
846 xmlSetStructuredErrorFunc (cl, xml_error_cb);
847 return 1;
849 fail:
850 log_write ("%s", pwmd_strerror (rc));
851 return 0;
855 * This is called after a client_thread() terminates. Set with
856 * pthread_cleanup_push().
858 static void
859 cleanup_cb (void *arg)
861 struct client_thread_s *cn = arg;
862 struct client_s *cl = cn->cl;
864 MUTEX_LOCK (&cn_mutex);
865 cn_thread_list = slist_remove (cn_thread_list, cn);
866 MUTEX_UNLOCK (&cn_mutex);
868 if (cl)
870 cleanup_client (cl);
872 #ifdef WITH_GNUTLS
873 if (cn->tls)
875 gnutls_deinit (cn->tls->ses);
876 xfree (cn->tls->fp);
877 xfree (cn->tls);
879 #endif
881 if (!cn->atfork && cl->ctx)
882 assuan_release (cl->ctx);
883 else if (!cn->atfork && cl->thd && cl->thd->fd != -1)
884 close (cl->thd->fd);
886 if (cl->crypto)
887 cleanup_crypto (&cl->crypto);
889 pinentry_free_opts (&cl->pinentry_opts);
890 xfree (cl);
892 else
894 if (cn->fd != -1)
895 close (cn->fd);
898 while (cn->msg_queue)
900 struct status_msg_s *msg = cn->msg_queue;
902 cn->msg_queue = msg->next;
903 xfree (msg->line);
904 xfree (msg);
907 if (!cn->atfork && cn->status_msg_pipe[0] != -1)
908 close (cn->status_msg_pipe[0]);
910 if (!cn->atfork && cn->status_msg_pipe[1] != -1)
911 close (cn->status_msg_pipe[1]);
913 pthread_mutex_destroy (&cn->status_mutex);
915 if (!cn->atfork)
917 log_write (_("exiting, fd=%i"), cn->fd);
918 send_status_all (STATUS_CLIENTS, NULL);
921 xfree (cn);
922 pthread_cond_signal (&quit_cond);
925 void
926 cleanup_all_clients (int atfork)
928 /* This function may be called from pthread_atfork() which requires
929 reinitialization. */
930 if (atfork)
932 pthread_mutexattr_t attr;
934 pthread_mutexattr_init (&attr);
935 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
936 pthread_mutex_init (&cn_mutex, &attr);
937 pthread_mutexattr_destroy (&attr);
938 cache_mutex_init ();
941 MUTEX_LOCK (&cn_mutex);
943 while (slist_length (cn_thread_list))
945 struct client_thread_s *thd = slist_nth_data (cn_thread_list, 0);
947 thd->atfork = atfork;
948 cleanup_cb (thd);
951 exiting = 1;
952 cache_deinit (atfork);
953 MUTEX_UNLOCK (&cn_mutex);
956 static gpg_error_t
957 send_msg_queue (struct client_thread_s *thd)
959 MUTEX_LOCK (&thd->status_mutex);
960 gpg_error_t rc = 0;
961 char c;
963 read (thd->status_msg_pipe[0], &c, 1);
965 while (thd->msg_queue)
967 struct status_msg_s *msg = thd->msg_queue;
969 thd->msg_queue = thd->msg_queue->next;
970 MUTEX_UNLOCK (&thd->status_mutex);
971 rc = send_status (thd->cl->ctx, msg->s, msg->line);
972 MUTEX_LOCK (&thd->status_mutex);
973 xfree (msg->line);
974 xfree (msg);
976 if (rc)
977 break;
980 MUTEX_UNLOCK (&thd->status_mutex);
981 return rc;
984 static void *
985 client_thread (void *data)
987 struct client_thread_s *thd = data;
988 struct client_s *cl = xcalloc (1, sizeof (struct client_s));
990 #ifdef HAVE_PR_SET_NAME
991 prctl (PR_SET_NAME, "client");
992 #endif
993 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
995 if (!cl)
997 log_write ("%s(%i): %s", __FILE__, __LINE__,
998 pwmd_strerror (GPG_ERR_ENOMEM));
999 return NULL;
1002 MUTEX_LOCK (&cn_mutex);
1003 pthread_cleanup_push (cleanup_cb, thd);
1004 thd->cl = cl;
1005 cl->thd = thd;
1006 MUTEX_UNLOCK (&cn_mutex);
1008 if (new_connection (cl))
1010 int finished = 0;
1011 gpg_error_t rc;
1013 send_status_all (STATUS_CLIENTS, NULL);
1014 rc = send_status (cl->ctx, STATUS_CACHE, NULL);
1015 if (rc)
1017 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
1018 finished = 1;
1021 while (!finished)
1023 fd_set rfds;
1024 int n;
1025 int eof;
1027 FD_ZERO (&rfds);
1028 FD_SET (thd->fd, &rfds);
1029 FD_SET (thd->status_msg_pipe[0], &rfds);
1030 n = thd->fd > thd->status_msg_pipe[0]
1031 ? thd->fd : thd->status_msg_pipe[0];
1033 n = select (n + 1, &rfds, NULL, NULL, NULL);
1034 if (n == -1)
1036 log_write ("%s", strerror (errno));
1037 break;
1040 if (FD_ISSET (thd->status_msg_pipe[0], &rfds))
1042 rc = send_msg_queue (thd);
1043 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1045 log_write ("%s(%i): %s", __FUNCTION__, __LINE__,
1046 pwmd_strerror (rc));
1047 break;
1051 if (!FD_ISSET (thd->fd, &rfds))
1052 continue;
1054 rc = assuan_process_next (cl->ctx, &eof);
1055 if (rc || eof)
1057 if (gpg_err_code (rc) == GPG_ERR_EOF || eof)
1058 break;
1060 log_write ("assuan_process_next(): rc=%i %s", rc,
1061 pwmd_strerror (rc));
1062 if (rc == gpg_error (GPG_ERR_ETIMEDOUT))
1063 break;
1065 rc = send_error (cl->ctx, rc);
1066 if (rc)
1068 log_write ("assuan_process_done(): rc=%i %s", rc,
1069 pwmd_strerror (rc));
1070 break;
1074 /* Since the msg queue pipe fd's are non-blocking, check for
1075 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1076 * client has already disconnected and will be converted to
1077 * GPG_ERR_EOF during assuan_process_next().
1079 rc = send_msg_queue (thd);
1080 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1082 log_write ("%s(%i): %s", __FUNCTION__, __LINE__,
1083 pwmd_strerror (rc));
1084 break;
1089 pthread_cleanup_pop (1);
1090 return NULL;
1093 static int
1094 xml_import (const char *filename, const char *outfile,
1095 const char *keygrip, const char *sign_keygrip,
1096 const char *keyfile, int no_passphrase, const char *cipher,
1097 const char *params, unsigned long s2k_count, uint64_t iterations)
1099 xmlDocPtr doc;
1100 int fd;
1101 struct stat st;
1102 int len;
1103 xmlChar *xmlbuf;
1104 xmlChar *xml;
1105 gpg_error_t rc;
1106 struct crypto_s *crypto = NULL;
1107 void *key = NULL;
1108 size_t keylen = 0;
1109 int algo = cipher ? cipher_string_to_gcrypt ((char *) cipher) :
1110 GCRY_CIPHER_AES256;
1112 if (algo == -1)
1114 log_write ("ERR %i: %s", gpg_error (GPG_ERR_CIPHER_ALGO),
1115 pwmd_strerror (GPG_ERR_CIPHER_ALGO));
1116 return 0;
1119 if (stat (filename, &st) == -1)
1121 log_write ("%s: %s", filename,
1122 pwmd_strerror (gpg_error_from_syserror ()));
1123 return 0;
1126 rc = init_client_crypto (&crypto);
1127 if (rc)
1128 return 0;
1130 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
1131 crypto->save.hdr.flags = set_cipher_flag (crypto->save.hdr.flags, algo);
1132 log_write (_("Importing XML from '%s'. Output will be written to '%s' ..."),
1133 filename, outfile);
1135 if ((fd = open (filename, O_RDONLY)) == -1)
1137 log_write ("%s: %s", filename,
1138 pwmd_strerror (gpg_error_from_syserror ()));
1139 goto fail;
1142 if ((xmlbuf = xmalloc (st.st_size + 1)) == NULL)
1144 close (fd);
1145 log_write ("%s(%i): %s", __FILE__, __LINE__,
1146 pwmd_strerror (GPG_ERR_ENOMEM));
1147 goto fail;
1150 if (read (fd, xmlbuf, st.st_size) == -1)
1152 rc = gpg_error_from_syserror ();
1153 close (fd);
1154 log_write ("%s: %s", filename, pwmd_strerror (rc));
1155 goto fail;
1158 close (fd);
1159 xmlbuf[st.st_size] = 0;
1161 * Make sure the document validates.
1163 if ((doc = xmlReadDoc (xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS)) == NULL)
1165 log_write ("xmlReadDoc() failed");
1166 xfree (xmlbuf);
1167 goto fail;
1170 xfree (xmlbuf);
1171 xmlNodePtr n = xmlDocGetRootElement (doc);
1172 if (n && !xmlStrEqual (n->name, (xmlChar *) "pwmd"))
1174 log_write (_("Could not find root \"pwmd\" element."));
1175 rc = GPG_ERR_BAD_DATA;
1178 if (!rc)
1179 rc = validate_import (n ? n->children : n);
1181 if (rc)
1183 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1184 xmlFreeDoc (doc);
1185 goto fail;
1188 xmlDocDumpMemory (doc, &xml, &len);
1189 xmlFreeDoc (doc);
1190 crypto->save.s2k_count = s2k_count;
1191 crypto->save.hdr.iterations = iterations;
1192 if (!use_agent)
1194 rc = export_common (NULL, 0, crypto, xml, len, outfile, keyfile, &key,
1195 &keylen, 0, 0);
1196 if (!rc)
1197 log_write (_("Success!"));
1199 #ifdef WITH_AGENT
1200 else
1202 rc = agent_set_pinentry_options (crypto->agent);
1203 if (!rc)
1204 rc = agent_export_common (crypto, keygrip, sign_keygrip, no_passphrase,
1205 xml, len, outfile, params, keyfile);
1207 #endif
1209 gcry_free (key);
1210 xmlFree (xml);
1211 if (rc)
1213 send_error (NULL, rc);
1214 goto fail;
1217 cleanup_crypto (&crypto);
1218 return 1;
1220 fail:
1221 cleanup_crypto (&crypto);
1222 return 0;
1225 static int
1226 do_cache_push (const char *filename, struct crypto_s *crypto)
1228 unsigned char md5file[16];
1229 gpg_error_t rc;
1230 char *key = NULL;
1231 size_t keylen = 0;
1232 xmlDocPtr doc;
1233 struct cache_data_s *cdata;
1234 unsigned char *crc;
1235 size_t len;
1237 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1238 filename);
1240 if (valid_filename (filename) == 0)
1242 log_write (_("%s: Invalid characters in filename"), filename);
1243 return 0;
1246 rc = decrypt_common (NULL, 0, crypto, filename, &key, &keylen);
1247 if (rc)
1248 return 0;
1250 doc = parse_doc ((char *) crypto->plaintext, crypto->plaintext_len);
1251 if (!doc)
1253 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM));
1254 xfree (key);
1255 return 0;
1258 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
1259 cdata = xcalloc (1, sizeof (struct cache_data_s));
1260 if (!cdata)
1262 xmlFreeDoc (doc);
1263 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM));
1264 xfree (key);
1265 return 0;
1268 rc = get_checksum (filename, &crc, &len);
1269 if (rc)
1271 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1272 xmlFreeDoc (doc);
1273 free_cache_data_once (cdata);
1274 xfree (key);
1275 return 0;
1278 cdata->crc = crc;
1279 rc = encrypt_xml (NULL, cache_key, cache_keysize, GCRY_CIPHER_AES,
1280 crypto->plaintext, crypto->plaintext_len, &cdata->doc,
1281 &cdata->doclen, &cache_iv, &cache_blocksize, 0);
1282 if (!rc && !IS_PKCS (crypto))
1284 cdata->key = key;
1285 cdata->keylen = keylen;
1287 else
1288 xfree (key);
1290 if (rc)
1292 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1293 xmlFreeDoc (doc);
1294 free_cache_data_once (cdata);
1295 return 0;
1298 #ifdef WITH_AGENT
1299 if (use_agent)
1301 gcry_sexp_build ((gcry_sexp_t *) & cdata->pubkey, NULL, "%S",
1302 crypto->pkey_sexp);
1303 gcry_sexp_build ((gcry_sexp_t *) & cdata->sigkey, NULL, "%S",
1304 crypto->sigpkey_sexp);
1306 #endif
1308 int timeout = config_get_integer (filename, "cache_timeout");
1309 cache_add_file (md5file, crypto->grip, cdata, timeout);
1310 log_write (_("Successfully added '%s' to the cache."), filename);
1311 return 1;
1314 static gpg_error_t
1315 init_client (int fd, const char *addr)
1317 gpg_error_t rc = 0;
1318 struct client_thread_s *new = xcalloc (1, sizeof (struct client_thread_s));
1320 if (!new)
1322 close (fd);
1323 return GPG_ERR_ENOMEM;
1326 MUTEX_LOCK (&cn_mutex);
1327 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
1329 if (pipe (new->status_msg_pipe) == -1)
1330 rc = gpg_error_from_syserror ();
1332 if (!rc)
1334 fcntl (new->status_msg_pipe[0], F_SETFL, O_NONBLOCK);
1335 fcntl (new->status_msg_pipe[1], F_SETFL, O_NONBLOCK);
1336 pthread_mutex_init (&new->status_mutex, NULL);
1339 if (!rc)
1341 #ifdef WITH_GNUTLS
1342 new->remote = addr ? 1 : 0;
1343 #endif
1344 new->fd = fd;
1345 rc = create_thread (client_thread, new, &new->tid, 1);
1346 if (rc)
1348 close (new->status_msg_pipe[0]);
1349 close (new->status_msg_pipe[1]);
1350 pthread_mutex_destroy (&new->status_mutex);
1354 if (!rc)
1356 struct slist_s *list = slist_append (cn_thread_list, new);
1358 if (list)
1360 cn_thread_list = list;
1361 if (addr)
1362 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1363 (pthread_t *) new->tid, fd, addr);
1364 else
1365 log_write (_("new connection: tid=%p, fd=%i"),
1366 (pthread_t *) new->tid, fd);
1368 else
1369 rc = GPG_ERR_ENOMEM;
1372 pthread_cleanup_pop (1);
1374 if (rc)
1376 xfree (new);
1377 close (fd);
1378 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1379 pwmd_strerror (rc));
1381 return rc;
1384 #ifdef WITH_GNUTLS
1385 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1386 static void *
1387 get_in_addr (struct sockaddr *sa)
1389 if (sa->sa_family == AF_INET)
1390 return &(((struct sockaddr_in *) sa)->sin_addr);
1392 return &(((struct sockaddr_in6 *) sa)->sin6_addr);
1395 static void *
1396 tcp_accept_thread (void *arg)
1398 int sockfd = *(int *) arg;
1399 #ifndef HAVE_PTHREAD_CANCEL
1400 int *n = xmalloc (sizeof (int));
1402 *n = 0;
1403 pthread_setspecific (signal_thread_key, n);
1404 INIT_THREAD_SIGNAL;
1405 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1406 #endif
1408 #ifdef HAVE_PR_SET_NAME
1409 prctl (PR_SET_NAME, "tcp_accept");
1410 #endif
1411 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1413 for (;;)
1415 struct sockaddr_storage raddr;
1416 socklen_t slen = sizeof (raddr);
1417 int fd = -1;
1418 unsigned long n;
1419 char s[INET6_ADDRSTRLEN];
1420 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1421 #ifndef HAVE_PTHREAD_CANCEL
1422 int *sigusr2;
1424 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1425 if (*sigusr2)
1426 break;
1427 #endif
1429 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1430 if (fd == -1)
1432 if (errno == EMFILE || errno == ENFILE)
1433 log_write ("accept(): %s",
1434 pwmd_strerror (gpg_error_from_syserror ()));
1435 else if (errno != EAGAIN)
1437 if (!quit) // probably EBADF
1438 log_write ("accept(): %s", strerror (errno));
1440 break;
1443 #ifndef HAVE_PTHREAD_CANCEL
1444 select (0, NULL, NULL, NULL, &tv);
1445 #endif
1446 continue;
1449 if (quit)
1450 break;
1452 inet_ntop (raddr.ss_family, get_in_addr ((struct sockaddr *) &raddr),
1453 s, sizeof s);
1454 (void) init_client (fd, s);
1455 n = config_get_integer ("global", "tcp_wait");
1456 if (n > 0)
1458 tv.tv_sec = (n * 100000) / 100000;
1459 tv.tv_usec = (n * 100000) % 100000;
1460 select (0, NULL, NULL, NULL, &tv);
1464 return NULL;
1467 static int
1468 start_stop_tls_with_protocol (int ipv6, int term)
1470 struct addrinfo hints, *servinfo, *p;
1471 int port = config_get_integer ("global", "tcp_port");
1472 char buf[7];
1473 int n;
1474 gpg_error_t rc;
1475 int *fd = ipv6 ? &tls6_fd : &tls_fd;
1477 if (term || config_get_boolean ("global", "enable_tcp") == 0)
1479 if (tls6_fd != -1)
1481 if (spawned_tls6)
1483 #ifdef HAVE_PTHREAD_CANCEL
1484 pthread_cancel (tls6_tid);
1485 #else
1486 pthread_kill (tls6_tid, SIGUSR2);
1487 #endif
1488 pthread_join (tls6_tid, NULL);
1491 shutdown (tls6_fd, SHUT_RDWR);
1492 close (tls6_fd);
1493 tls6_fd = -1;
1494 spawned_tls6 = 0;
1497 if (tls_fd != -1)
1499 if (spawned_tls)
1501 #ifdef HAVE_PTHREAD_CANCEL
1502 pthread_cancel (tls_tid);
1503 #else
1504 pthread_kill (tls_tid, SIGUSR2);
1505 #endif
1506 pthread_join (tls_tid, NULL);
1509 shutdown (tls_fd, SHUT_RDWR);
1510 close (tls_fd);
1511 tls_fd = -1;
1512 spawned_tls = 0;
1515 /* A client may still be connected. */
1516 if (!quit && x509_cred != NULL)
1517 tls_deinit_params ();
1519 return 1;
1522 if ((ipv6 && tls6_fd != -1) || (!ipv6 && tls_fd != -1))
1523 return 1;
1525 memset (&hints, 0, sizeof (hints));
1526 hints.ai_family = ipv6 ? AF_INET6 : AF_INET;
1527 hints.ai_socktype = SOCK_STREAM;
1528 hints.ai_flags = AI_PASSIVE;
1529 snprintf (buf, sizeof (buf), "%i", port);
1531 if ((n = getaddrinfo (NULL, buf, &hints, &servinfo)) == -1)
1533 log_write ("getaddrinfo(): %s", gai_strerror (n));
1534 return 0;
1537 for (n = 0, p = servinfo; p != NULL; p = p->ai_next)
1539 int r = 1;
1541 if ((ipv6 && p->ai_family != AF_INET6)
1542 || (!ipv6 && p->ai_family != AF_INET))
1543 continue;
1545 if ((*fd = socket (p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
1547 log_write ("socket(): %s", strerror (errno));
1548 continue;
1551 if (setsockopt (*fd, SOL_SOCKET, SO_REUSEADDR, &r, sizeof (int)) == -1)
1553 log_write ("setsockopt(): %s",
1554 pwmd_strerror (gpg_error_from_syserror ()));
1555 freeaddrinfo (servinfo);
1556 goto fail;
1559 if (bind (*fd, p->ai_addr, p->ai_addrlen) == -1)
1561 close (*fd);
1562 log_write ("bind(): %s",
1563 pwmd_strerror (gpg_error_from_syserror ()));
1564 continue;
1567 n++;
1568 break;
1571 freeaddrinfo (servinfo);
1573 if (!n)
1574 goto fail;
1576 #if HAVE_DECL_SO_BINDTODEVICE != 0
1577 char *tmp = config_get_string ("global", "tcp_interface");
1578 if (tmp && setsockopt (*fd, SOL_SOCKET, SO_BINDTODEVICE, tmp,
1579 strlen (tmp)) == -1)
1581 log_write ("setsockopt(): %s",
1582 pwmd_strerror (gpg_error_from_syserror ()));
1583 xfree (tmp);
1584 goto fail;
1587 xfree (tmp);
1588 #endif
1590 if (x509_cred == NULL)
1592 rc = tls_init_params ();
1593 if (rc)
1594 goto fail;
1597 if (listen (*fd, 0) == -1)
1599 log_write ("listen(): %s", strerror (errno));
1600 goto fail;
1603 if (ipv6)
1604 rc = create_thread (tcp_accept_thread, fd, &tls6_tid, 0);
1605 else
1606 rc = create_thread (tcp_accept_thread, fd, &tls_tid, 0);
1608 if (rc)
1610 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1611 pwmd_strerror (rc));
1612 goto fail;
1615 if (ipv6)
1616 spawned_tls6 = 1;
1617 else
1618 spawned_tls = 1;
1620 return 1;
1622 fail:
1623 start_stop_tls_with_protocol (0, 1);
1624 if (tls_fd != -1)
1625 close (tls_fd);
1627 if (tls6_fd != -1)
1628 close (tls6_fd);
1630 tls_fd = -1;
1631 tls6_fd = -1;
1632 return 0;
1635 static int
1636 start_stop_tls (int term)
1638 char *s = config_get_string ("global", "tcp_bind");
1639 int b;
1641 if (!s)
1642 return 0;
1644 if (!strcmp (s, "any"))
1646 b = start_stop_tls_with_protocol (0, term);
1647 if (b)
1648 b = start_stop_tls_with_protocol (1, term);
1650 else if (!strcmp (s, "ipv4"))
1651 b = start_stop_tls_with_protocol (0, term);
1652 else if (!strcmp (s, "ipv6"))
1653 b = start_stop_tls_with_protocol (1, term);
1654 else
1655 b = 0;
1657 xfree (s);
1658 return b;
1660 #endif
1662 static void *
1663 accept_thread (void *arg)
1665 int sockfd = *(int *) arg;
1666 #ifndef HAVE_PTHREAD_CANCEL
1667 int *n = xmalloc (sizeof (int));
1669 *n = 0;
1670 pthread_setspecific (signal_thread_key, n);
1671 INIT_THREAD_SIGNAL;
1672 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1673 #endif
1675 #ifdef HAVE_PR_SET_NAME
1676 prctl (PR_SET_NAME, "accept");
1677 #endif
1678 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1680 for (;;)
1682 socklen_t slen = sizeof (struct sockaddr_un);
1683 struct sockaddr_un raddr;
1684 int fd;
1685 #ifndef HAVE_PTHREAD_CANCEL
1686 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1687 int *sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1689 if (*sigusr2)
1690 break;
1691 #endif
1693 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1694 if (fd == -1)
1696 if (errno == EMFILE || errno == ENFILE)
1697 log_write ("accept(): %s",
1698 pwmd_strerror (gpg_error_from_syserror ()));
1699 else if (errno != EAGAIN)
1701 if (!quit) // probably EBADF
1702 log_write ("accept(): %s",
1703 pwmd_strerror (gpg_error_from_syserror ()));
1705 break;
1708 #ifndef HAVE_PTHREAD_CANCEL
1709 select (0, NULL, NULL, NULL, &tv);
1710 #endif
1711 continue;
1714 (void) init_client (fd, NULL);
1717 /* Just in case accept() failed for some reason other than EBADF */
1718 quit = 1;
1719 return NULL;
1722 static void *
1723 cache_timer_thread (void *arg)
1725 #ifndef HAVE_PTHREAD_CANCEL
1726 int *n = xmalloc (sizeof (int));
1728 *n = 0;
1729 pthread_setspecific (signal_thread_key, n);
1730 INIT_THREAD_SIGNAL;
1731 #endif
1733 #ifdef HAVE_PR_SET_NAME
1734 prctl (PR_SET_NAME, "cache timer");
1735 #endif
1736 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1738 for (;;)
1740 struct timeval tv = { 1, 0 };
1741 #ifndef HAVE_PTHREAD_CANCEL
1742 int *n;
1744 n = (int *) pthread_getspecific (signal_thread_key);
1745 if (*n)
1746 break;
1747 #endif
1749 select (0, NULL, NULL, NULL, &tv);
1750 cache_adjust_timeout ();
1753 return NULL;
1756 static void
1757 catch_sigabrt (int sig)
1759 cache_clear (NULL);
1760 #ifndef MEM_DEBUG
1761 xpanic ();
1762 #endif
1765 static int
1766 signal_loop (sigset_t sigset)
1768 int done = 0;
1769 int siint = 0;
1773 int sig;
1775 sigwait (&sigset, &sig);
1777 if (sig != SIGQUIT)
1778 log_write (_("caught signal %i (%s)"), sig, strsignal (sig));
1780 switch (sig)
1782 case SIGHUP:
1783 pthread_cond_signal (&rcfile_cond);
1784 break;
1785 case SIGABRT:
1786 // not really handled here.
1787 catch_sigabrt (SIGABRT);
1788 break;
1789 case SIGUSR1:
1790 log_write (_("clearing file cache"));
1791 cache_clear (NULL);
1792 send_status_all (STATUS_CACHE, NULL);
1793 break;
1794 case SIGQUIT:
1795 done = 1;
1796 break;
1797 default:
1798 siint = 1;
1799 done = 1;
1800 break;
1803 while (!done);
1805 return siint;
1808 static void
1809 catchsig (int sig)
1811 log_write ("Caught SIGSEGV. Exiting.");
1812 #ifdef HAVE_BACKTRACE
1813 BACKTRACE (__FUNCTION__);
1814 #endif
1815 longjmp (jmp, 1);
1818 static void *
1819 waiting_for_exit (void *arg)
1821 int last = 0;
1822 #ifndef HAVE_PTHREAD_CANCEL
1823 int *n = xmalloc (sizeof (int));
1825 *n = 0;
1826 pthread_setspecific (signal_thread_key, n);
1827 INIT_THREAD_SIGNAL;
1828 #endif
1830 #ifdef HAVE_PR_SET_NAME
1831 prctl (PR_SET_NAME, "exiting");
1832 #endif
1833 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1834 log_write (_("waiting for all clients to disconnect"));
1835 MUTEX_LOCK (&quit_mutex);
1836 pthread_cleanup_push (cleanup_mutex_cb, &quit_mutex);
1838 for (;;)
1840 struct timespec ts;
1841 int n;
1843 MUTEX_LOCK (&cn_mutex);
1844 n = slist_length (cn_thread_list);
1845 MUTEX_UNLOCK (&cn_mutex);
1846 if (!n)
1847 break;
1849 #ifndef HAVE_PTHREAD_CANCEL
1850 int *s = (int *) pthread_getspecific (signal_thread_key);
1851 if (*s)
1852 break;
1853 #endif
1855 if (last != n)
1857 log_write (_("%i clients remain"), n);
1858 last = n;
1861 INIT_TIMESPEC (SIG_TIMEOUT, ts);
1862 pthread_cond_timedwait (&quit_cond, &quit_mutex, &ts);
1865 kill (getpid (), SIGQUIT);
1866 pthread_cleanup_pop (1);
1867 return NULL;
1870 static int
1871 server_loop (int sockfd, char **socketpath)
1873 pthread_t accept_tid;
1874 pthread_t cache_timeout_tid;
1875 int cancel_timeout_thread = 0, cancel_accept_thread = 0;
1876 sigset_t sigset;
1877 int n;
1878 int segv = 0;
1879 gpg_error_t rc;
1881 init_commands ();
1882 sigemptyset (&sigset);
1884 /* Termination */
1885 sigaddset (&sigset, SIGTERM);
1886 sigaddset (&sigset, SIGINT);
1888 /* Clears the file cache. */
1889 sigaddset (&sigset, SIGUSR1);
1891 /* Configuration file reloading. */
1892 sigaddset (&sigset, SIGHUP);
1894 /* For exiting cleanly. */
1895 sigaddset (&sigset, SIGQUIT);
1897 #ifndef HAVE_PTHREAD_CANCEL
1899 The socket, cache and rcfile threads use this signal when
1900 pthread_cancel() is unavailable. Prevent the main thread from
1901 catching this signal from another process.
1903 sigaddset (&sigset, SIGUSR2);
1904 #endif
1906 /* Clears the cache and exits when something bad happens. */
1907 signal (SIGABRT, catch_sigabrt);
1908 sigaddset (&sigset, SIGABRT);
1909 sigprocmask (SIG_BLOCK, &sigset, NULL);
1911 #ifndef HAVE_PTHREAD_CANCEL
1912 /* Remove this signal from the watched signals in signal_loop(). */
1913 sigdelset (&sigset, SIGUSR2);
1914 #endif
1916 /* Ignored everywhere. When a client disconnects abnormally this signal
1917 * gets raised. It isn't needed though because client_thread() will check
1918 * for rcs even after the client disconnects. */
1919 signal (SIGPIPE, SIG_IGN);
1921 /* Can show a backtrace of the stack in the log. */
1922 signal (SIGSEGV, catchsig);
1924 #ifdef WITH_GNUTLS
1925 /* Needs to be done after the fork(). */
1926 if (!start_stop_tls (0))
1928 segv = 1;
1929 goto done;
1931 #endif
1933 pthread_mutex_init (&quit_mutex, NULL);
1934 pthread_cond_init (&quit_cond, NULL);
1935 log_write (_("%s started for user %s"), PACKAGE_STRING, get_username ());
1937 #ifdef WITH_GNUTLS
1938 if (config_get_boolean ("global", "enable_tcp"))
1939 log_write (_("Listening on %s and TCP port %i"), *socketpath,
1940 config_get_integer ("global", "tcp_port"));
1941 else
1942 log_write (_("Listening on %s"), *socketpath);
1943 #else
1944 log_write (_("Listening on %s"), *socketpath);
1945 #endif
1947 rc = create_thread (reload_rcfile_thread, NULL, &rcfile_tid, 0);
1948 if (rc)
1950 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1951 pwmd_strerror (rc));
1952 goto done;
1955 rc = create_thread (cache_timer_thread, NULL, &cache_timeout_tid, 0);
1956 if (rc)
1958 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1959 pwmd_strerror (rc));
1960 goto done;
1963 cancel_timeout_thread = 1;
1964 rc = create_thread (accept_thread, &sockfd, &accept_tid, 0);
1965 if (rc)
1967 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1968 pwmd_strerror (rc));
1969 goto done;
1972 cancel_accept_thread = 1;
1973 if (!setjmp (jmp))
1974 signal_loop (sigset);
1975 else
1976 segv = 1;
1978 done:
1980 * We're out of the main server loop. This happens when a signal was sent
1981 * to terminate the daemon. We'll wait for all clients to disconnect
1982 * before exiting but exit immediately if another termination signal is
1983 * sent.
1985 if (cancel_accept_thread)
1987 #ifdef HAVE_PTHREAD_CANCEL
1988 int n = pthread_cancel (accept_tid);
1989 #else
1990 int n = pthread_kill (accept_tid, SIGUSR2);
1991 #endif
1992 if (!n)
1993 pthread_join (accept_tid, NULL);
1996 #ifdef WITH_GNUTLS
1997 start_stop_tls (1);
1998 #endif
1999 shutdown (sockfd, SHUT_RDWR);
2000 close (sockfd);
2001 unlink (*socketpath);
2002 xfree (*socketpath);
2003 *socketpath = NULL;
2004 MUTEX_LOCK (&cn_mutex);
2005 n = slist_length (cn_thread_list);
2006 MUTEX_UNLOCK (&cn_mutex);
2008 if (n && !segv)
2010 pthread_t tid;
2012 rc = create_thread (waiting_for_exit, NULL, &tid, 0);
2013 if (!rc)
2015 if (signal_loop (sigset))
2017 log_write (_("Received second termination request. Exiting."));
2018 #ifdef HAVE_PTHREAD_CANCEL
2019 pthread_cancel (tid);
2020 #else
2021 pthread_kill (tid, SIGUSR2);
2022 #endif
2023 pthread_join (tid, NULL);
2026 else
2027 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2028 pwmd_strerror (rc));
2031 if (cancel_timeout_thread)
2033 #ifdef HAVE_PTHREAD_CANCEL
2034 pthread_cancel (cache_timeout_tid);
2035 #else
2036 pthread_kill (cache_timeout_tid, SIGUSR2);
2037 #endif
2038 pthread_join (cache_timeout_tid, NULL);
2041 cleanup_all_clients (0);
2042 #ifdef WITH_GNUTLS
2043 start_stop_tls (1);
2044 #endif
2045 deinit_commands ();
2046 pthread_cond_destroy (&quit_cond);
2047 pthread_mutex_destroy (&quit_mutex);
2048 return segv ? EXIT_FAILURE : EXIT_SUCCESS;;
2051 static void
2052 startup_failure ()
2054 log_write (_
2055 ("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
2056 cache_clear (NULL);
2059 /* This is called from cache.c:clear_once(). See
2060 * command.c:clearcache_command() for details about lock checking.
2062 static gpg_error_t
2063 free_cache_data (file_cache_t * cache)
2065 gpg_error_t rc = GPG_ERR_NO_DATA;
2066 int i, t;
2067 struct client_thread_s *found = NULL;
2068 int self = 0;
2070 if (!cache->data)
2071 return 0;
2073 cache_lock ();
2074 MUTEX_LOCK (&cn_mutex);
2075 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
2076 t = slist_length (cn_thread_list);
2078 for (i = 0; i < t; i++)
2080 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2082 if (!thd->cl)
2083 continue;
2085 if (!memcmp (thd->cl->md5file, cache->filename,
2086 sizeof (cache->filename)))
2088 if (pthread_equal (pthread_self (), thd->tid))
2090 found = thd;
2091 self = 1;
2092 continue;
2095 /* Continue trying to find a client who has the same file open and
2096 * also has a lock. */
2097 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0, -1);
2098 if (!rc)
2100 self = 0;
2101 found = thd;
2102 break;
2107 if (self && (!rc || rc == GPG_ERR_NO_DATA))
2108 rc = cache_lock_mutex (found->cl->ctx, found->cl->md5file, -1, 0, -1);
2110 if (exiting || !rc || rc == GPG_ERR_NO_DATA)
2112 free_cache_data_once (cache->data);
2113 cache->data = NULL;
2114 cache->defer_clear = 0;
2115 cache->timeout = -1;
2117 if (found)
2118 cache_unlock_mutex (found->cl->md5file, 0);
2120 rc = 0;
2123 if (rc)
2124 cache->defer_clear = 1;
2126 pthread_cleanup_pop (1);
2127 cache_unlock ();
2128 return rc;
2131 static int
2132 convert_v2_datafile (const char *filename, const char *cipher,
2133 const char *keyfile, const char *keygrip,
2134 const char *sign_keygrip, int nopass,
2135 const char *outfile, const char *keyparam,
2136 unsigned long s2k_count, uint64_t iterations)
2138 gpg_error_t rc;
2139 void *data = NULL;
2140 size_t datalen;
2141 struct crypto_s *crypto = NULL;
2142 uint16_t ver;
2143 int algo;
2144 void *key = NULL;
2145 size_t keylen = 0;
2147 if (outfile[0] == '-' && outfile[1] == 0)
2148 outfile = NULL;
2150 log_write (_("Converting version 2 data file \"%s\" ..."), filename);
2151 if (access (filename, R_OK) == -1)
2153 log_write ("%s: %s", filename,
2154 pwmd_strerror (gpg_error_from_syserror ()));
2155 return 0;
2158 if (keyfile)
2160 log_write (_("Using passphrase file \"%s\" for decryption ..."),
2161 keyfile);
2162 if (access (keyfile, R_OK) == -1)
2164 log_write ("%s: %s", keyfile,
2165 pwmd_strerror (gpg_error_from_syserror ()));
2166 return 0;
2170 rc = read_v2_datafile (filename, keyfile, &data, &datalen, &ver, &algo);
2171 if (rc)
2173 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2174 return 0;
2177 if (cipher)
2179 algo = cipher_string_to_gcrypt (cipher);
2180 if (algo == -1)
2182 rc = GPG_ERR_CIPHER_ALGO;
2183 goto fail;
2187 if (ver < 0x212)
2189 xmlDocPtr doc = parse_doc (data, datalen);
2191 if (!doc)
2193 rc = GPG_ERR_BAD_DATA;
2194 goto fail;
2197 rc = convert_pre_212_elements (doc);
2198 gcry_free (data);
2199 data = NULL;
2200 if (!rc)
2202 xmlDocDumpFormatMemory (doc, (xmlChar **) & data, (int *) &datalen,
2204 if (!data)
2205 rc = GPG_ERR_ENOMEM;
2208 xmlFreeDoc (doc);
2209 if (rc)
2210 goto fail;
2213 rc = init_client_crypto (&crypto);
2214 if (!rc)
2216 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
2217 crypto->save.hdr.flags = set_cipher_flag (crypto->save.hdr.flags, algo);
2218 crypto->save.s2k_count = s2k_count;
2219 crypto->save.hdr.iterations = iterations;
2221 if (!use_agent)
2223 rc = export_common (NULL, 0, crypto, data, datalen, outfile, keyfile,
2224 &key, &keylen, 0, 0);
2226 #ifdef WITH_AGENT
2227 else
2229 rc = agent_set_pinentry_options (crypto->agent);
2230 if (!rc)
2231 rc = agent_export_common (crypto, keygrip, sign_keygrip, nopass,
2232 data, datalen, outfile, keyparam,
2233 no_passphrase_file ? NULL : keyfile);
2235 #endif
2236 if (!rc)
2237 log_write (_("Output written to \"%s\"."), outfile);
2240 fail:
2241 if (ver < 0x212)
2242 xmlFree (data);
2243 else
2244 gcry_free (data);
2246 gcry_free (key);
2247 cleanup_crypto (&crypto);
2249 if (rc)
2250 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2251 return rc ? 0 : 1;
2254 static void
2255 usage (const char *pn, int status)
2257 FILE *fp = status == EXIT_FAILURE ? stderr : stdout;
2259 fprintf (fp, _("Usage: %s [OPTIONS] [file1] [...]\n"
2260 " -f, --rcfile=filename load the specfied configuration file\n"
2261 " (~/.pwmd/config)\n"
2262 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2263 #ifdef WITH_AGENT
2264 " --no-agent disable use of gpg-agent\n"
2265 #endif
2266 " -n, --no-fork run as a foreground process\n"
2267 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2268 " --ignore ignore file errors during startup\n"
2269 " --debug-level=keywords log protocol output (see manual for details)\n"
2270 " -o, --outfile=filename output file when importing or converting\n"
2271 " -C, --convert=filename convert a version 2 data file to version 3\n"
2272 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2273 " -k, --passphrase-file=file for use when importing or converting\n"
2274 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2275 " converting\n"
2276 " --no-passphrase when importing or converting\n"
2277 " --keygrip=hex public key to use when encrypting\n"
2278 " --sign-keygrip=hex private key to use when signing\n"
2279 " --keyparam=s-exp custom key parameters to use (RSA-2048)\n"
2280 " --cipher=string encryption cipher (aes256)\n"
2281 " --iterations=N cipher iteration count (N+1)\n"
2282 " --s2k-count=N hash iteration count (>65536, calibrated)\n"
2283 " --help this help text\n"
2284 " --version show version and compile time features\n"),
2285 pn);
2286 exit (status);
2290 main (int argc, char *argv[])
2292 int opt;
2293 struct sockaddr_un addr;
2294 char buf[PATH_MAX];
2295 char *socketpath = NULL, *socketdir, *socketname = NULL;
2296 char *socketarg = NULL;
2297 char *datadir = NULL;
2298 int x;
2299 char *p;
2300 char **cache_push = NULL;
2301 char *import = NULL, *keygrip = NULL, *sign_keygrip = NULL;
2302 char *keyparam = NULL;
2303 int estatus = EXIT_FAILURE;
2304 int sockfd;
2305 char *outfile = NULL;
2306 int do_unlink = 0;
2307 int secure = 0;
2308 int show_version = 0;
2309 int force = 0;
2310 int no_passphrase = 0;
2311 gpg_error_t rc;
2312 char *convertfile = NULL;
2313 char *cipher = NULL;
2314 char *keyfile = NULL;
2315 unsigned long s2k_count = 0;
2316 uint64_t iterations = 0;
2317 int exists;
2318 char *debug_level_opt = NULL;
2319 int optindex;
2320 /* Must maintain the same order as longopts[] */
2321 enum
2322 { OPT_VERSION, OPT_HELP, OPT_NO_AGENT,
2323 OPT_DEBUG_LEVEL, OPT_HOMEDIR, OPT_NO_FORK, OPT_DISABLE_DUMP, OPT_IGNORE,
2324 OPT_RCFILE, OPT_CONVERT, OPT_PASSPHRASE_FILE, OPT_IMPORT, OPT_OUTFILE,
2325 OPT_NO_PASSPHRASE_FILE, OPT_KEYGRIP, OPT_SIGN_KEYGRIP, OPT_KEYPARAM,
2326 OPT_CIPHER, OPT_ITERATIONS, OPT_S2K_COUNT, OPT_NO_PASSPHRASE
2328 const char *optstring = "nf:C:k:I:o:";
2329 const struct option longopts[] = {
2330 {"version", no_argument, 0, 0},
2331 {"help", no_argument, 0, 0},
2332 {"no-agent", no_argument, 0, 0},
2333 {"debug-level", required_argument, 0, 0},
2334 {"homedir", required_argument, 0, 0},
2335 {"no-fork", no_argument, 0, 'n'},
2336 {"disable_dump", no_argument, 0, 0},
2337 {"ignore", no_argument, 0, 0},
2338 {"rcfile", required_argument, 0, 'f'},
2339 {"convert", required_argument, 0, 'C'},
2340 {"passphrase-file", required_argument, 0, 'k'},
2341 {"import", required_argument, 0, 'I'},
2342 {"outfile", required_argument, 0, 'o'},
2343 {"no-passphrase-file", no_argument, 0, 0},
2344 {"keygrip", required_argument, 0, 0},
2345 {"sign-keygrip", required_argument, 0, 0},
2346 {"keyparam", required_argument, 0, 0},
2347 {"cipher", required_argument, 0, 0},
2348 {"cipher-iterations", required_argument, 0, 0},
2349 {"s2k-count", required_argument, 0, 0},
2350 {"no-passphrase", no_argument, 0, 0},
2351 {0, 0, 0, 0}
2354 #ifndef DEBUG
2355 #ifdef HAVE_SETRLIMIT
2356 struct rlimit rl;
2358 rl.rlim_cur = rl.rlim_max = 0;
2360 if (setrlimit (RLIMIT_CORE, &rl) != 0)
2361 err (EXIT_FAILURE, "setrlimit()");
2362 #endif
2363 #endif
2365 #ifdef ENABLE_NLS
2366 setlocale (LC_ALL, "");
2367 bindtextdomain ("pwmd", LOCALEDIR);
2368 textdomain ("pwmd");
2369 #endif
2371 #ifndef MEM_DEBUG
2372 xmem_init ();
2373 #endif
2374 gpg_err_init ();
2376 if (setup_crypto ())
2377 exit (EXIT_FAILURE);
2379 #ifdef WITH_GNUTLS
2380 gnutls_global_set_mem_functions (xmalloc, xmalloc, secure_mem_check,
2381 xrealloc, xfree);
2382 gnutls_global_init ();
2383 gnutls_global_set_log_function (tls_log);
2384 gnutls_global_set_log_level (1);
2385 tls_fd = -1;
2386 tls6_fd = -1;
2387 #endif
2388 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
2389 xmlInitMemory ();
2390 xmlInitGlobals ();
2391 xmlInitParser ();
2392 xmlXPathInit ();
2393 cmdline = 1;
2394 #ifdef WITH_AGENT
2395 use_agent = 1;
2396 #endif
2398 while ((opt =
2399 getopt_long (argc, argv, optstring, longopts, &optindex)) != -1)
2401 switch (opt)
2403 case 'I':
2404 import = optarg;
2405 break;
2406 case 'C':
2407 convertfile = optarg;
2408 break;
2409 case 'k':
2410 keyfile = optarg;
2411 break;
2412 case 'o':
2413 outfile = optarg;
2414 break;
2415 case 'D':
2416 secure = 1;
2417 break;
2418 case 'n':
2419 nofork = 1;
2420 break;
2421 case 'f':
2422 rcfile = str_dup (optarg);
2423 break;
2424 default:
2425 usage (argv[0], EXIT_FAILURE);
2426 break;
2427 case 0:
2428 switch (optindex)
2430 case OPT_VERSION:
2431 show_version = 1;
2432 break;
2433 case OPT_HELP:
2434 usage (argv[0], 0);
2435 break;
2436 case OPT_NO_AGENT:
2437 use_agent = 0;
2438 break;
2439 case OPT_DEBUG_LEVEL:
2440 debug_level_opt = optarg;
2441 break;
2442 case OPT_HOMEDIR:
2443 homedir = str_dup (optarg);
2444 break;
2445 case OPT_NO_FORK:
2446 nofork = 1;
2447 break;
2448 case OPT_DISABLE_DUMP:
2449 secure = 1;
2450 break;
2451 case OPT_IGNORE:
2452 force = 1;
2453 break;
2454 case OPT_RCFILE:
2455 rcfile = str_dup (optarg);
2456 break;
2457 case OPT_CONVERT:
2458 convertfile = optarg;
2459 break;
2460 case OPT_PASSPHRASE_FILE:
2461 keyfile = optarg;
2462 break;
2463 case OPT_IMPORT:
2464 import = optarg;
2465 break;
2466 case OPT_OUTFILE:
2467 outfile = optarg;
2468 break;
2469 case OPT_NO_PASSPHRASE_FILE:
2470 no_passphrase_file = 1;
2471 break;
2472 case OPT_KEYGRIP:
2473 keygrip = optarg;
2474 break;
2475 case OPT_SIGN_KEYGRIP:
2476 sign_keygrip = optarg;
2477 break;
2478 case OPT_KEYPARAM:
2479 keyparam = optarg;
2480 break;
2481 case OPT_CIPHER:
2482 cipher = optarg;
2483 break;
2484 case OPT_ITERATIONS:
2485 iterations = strtoull (optarg, NULL, 10);
2486 break;
2487 case OPT_S2K_COUNT:
2488 s2k_count = strtoul (optarg, NULL, 10);
2489 break;
2490 case OPT_NO_PASSPHRASE:
2491 no_passphrase = 1;
2492 break;
2493 default:
2494 usage (argv[0], 1);
2499 if (show_version)
2501 printf (_("%s\n\n"
2502 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013\n"
2503 "%s\n"
2504 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2505 "Compile time features:\n%s"), PACKAGE_STRING,
2506 PACKAGE_BUGREPORT,
2507 #ifdef PWMD_HOMEDIR
2508 "+PWMD_HOMEDIR=" PWMD_HOMEDIR "\n"
2509 #endif
2510 #ifdef WITH_AGENT
2511 "+WITH_AGENT\n"
2512 #else
2513 "-WITH_AGENT\n"
2514 #endif
2515 #ifdef WITH_QUALITY
2516 "+WITH_QUALITY\n"
2517 #else
2518 "-WITH_QUALITY\n"
2519 #endif
2520 #ifdef WITH_GNUTLS
2521 "+WITH_GNUTLS\n"
2522 #else
2523 "-WITH_GNUTLS\n"
2524 #endif
2525 #ifdef WITH_LIBACL
2526 "+WITH_LIBACL\n"
2527 #else
2528 "-WITH_LIBACL\n"
2529 #endif
2530 #ifdef DEBUG
2531 "+DEBUG\n"
2532 #else
2533 "-DEBUG\n"
2534 #endif
2535 #ifdef MEM_DEBUG
2536 "+MEM_DEBUG\n"
2537 #else
2538 "-MEM_DEBUG\n"
2539 #endif
2540 #ifdef MUTEX_DEBUG
2541 "+MUTEX_DEBUG\n"
2542 #else
2543 "-MUTEX_DEBUG\n"
2544 #endif
2546 exit (EXIT_SUCCESS);
2549 if (!homedir)
2550 #ifdef PWMD_HOMEDIR
2551 homedir = str_dup(PWMD_HOMEDIR);
2552 #else
2553 homedir = str_asprintf ("%s/.pwmd", get_home_dir ());
2554 #endif
2556 if (mkdir (homedir, 0700) == -1 && errno != EEXIST)
2557 err (EXIT_FAILURE, "%s", homedir);
2559 snprintf (buf, sizeof (buf), "%s/data", homedir);
2560 if (mkdir (buf, 0700) == -1 && errno != EEXIST)
2561 err (EXIT_FAILURE, "%s", buf);
2563 datadir = str_dup (buf);
2564 pthread_mutexattr_t attr;
2565 pthread_mutexattr_init (&attr);
2566 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
2567 pthread_mutex_init (&rcfile_mutex, &attr);
2568 pthread_cond_init (&rcfile_cond, NULL);
2569 pthread_mutex_init (&cn_mutex, &attr);
2570 pthread_mutexattr_destroy (&attr);
2571 pthread_key_create (&last_error_key, free_key);
2572 #ifndef HAVE_PTHREAD_CANCEL
2573 pthread_key_create (&signal_thread_key, free_key);
2574 #endif
2576 if (!rcfile)
2577 rcfile = str_asprintf ("%s/config", homedir);
2579 global_config = config_parse (rcfile);
2580 if (!global_config)
2581 exit (EXIT_FAILURE);
2583 setup_logging ();
2585 if (debug_level_opt)
2586 debug_level = str_split (debug_level_opt, ",", 0);
2588 x = config_get_int_param (global_config, "global", "priority", &exists);
2589 if (exists && x != atoi(INVALID_PRIORITY))
2591 errno = 0;
2592 if (setpriority (PRIO_PROCESS, 0, x) == -1)
2594 log_write ("setpriority(): %s",
2595 pwmd_strerror (gpg_error_from_syserror ()));
2596 goto do_exit;
2599 #ifdef HAVE_MLOCKALL
2600 if (disable_mlock == 0 && mlockall (MCL_CURRENT | MCL_FUTURE) == -1)
2602 log_write ("mlockall(): %s",
2603 pwmd_strerror (gpg_error_from_syserror ()));
2604 goto do_exit;
2606 #endif
2608 rc = cache_init (free_cache_data);
2609 if (rc)
2611 log_write ("pwmd: ERR %i: %s", rc,
2612 gpg_err_code (rc) == GPG_ERR_UNKNOWN_VERSION
2613 ? _("incompatible version: 2.1.0 or later required")
2614 : pwmd_strerror (rc));
2615 goto do_exit;
2618 if (s2k_count == 0)
2619 s2k_count = config_get_ulong (NULL, "s2k_count");
2621 if (convertfile)
2623 if (!outfile)
2624 usage (argv[0], EXIT_FAILURE);
2626 estatus = convert_v2_datafile (convertfile, cipher, keyfile, keygrip,
2627 sign_keygrip, no_passphrase, outfile,
2628 keyparam, s2k_count, iterations);
2629 config_free (global_config);
2630 xfree (rcfile);
2631 exit (!estatus);
2634 if (import)
2636 if (!outfile || !*outfile)
2637 usage (argv[0], EXIT_FAILURE);
2639 if (outfile && outfile[0] == '-' && outfile[1] == 0)
2640 outfile = NULL;
2642 estatus = xml_import (import, outfile, keygrip, sign_keygrip, keyfile,
2643 no_passphrase, cipher, keyparam, s2k_count,
2644 iterations);
2645 config_free (global_config);
2646 xfree (rcfile);
2647 exit (!estatus);
2650 p = config_get_string ("global", "socket_path");
2651 if (!p)
2652 p = str_asprintf ("%s/socket", homedir);
2654 socketarg = expand_homedir (p);
2655 xfree (p);
2657 if (!secure)
2658 disable_list_and_dump = config_get_boolean ("global",
2659 "disable_list_and_dump");
2660 else
2661 disable_list_and_dump = secure;
2663 cache_push = config_get_list ("global", "cache_push");
2665 while (optind < argc)
2667 if (strv_printf (&cache_push, "%s", argv[optind++]) == 0)
2668 errx (EXIT_FAILURE, "%s", pwmd_strerror (GPG_ERR_ENOMEM));
2671 if (strchr (socketarg, '/') == NULL)
2673 socketdir = getcwd (buf, sizeof (buf));
2674 socketname = str_dup (socketarg);
2675 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2677 else
2679 socketname = str_dup (strrchr (socketarg, '/'));
2680 socketname++;
2681 socketarg[strlen (socketarg) - strlen (socketname) - 1] = 0;
2682 socketdir = str_dup (socketarg);
2683 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2686 if (chdir (datadir))
2688 log_write ("%s: %s", datadir,
2689 pwmd_strerror (gpg_error_from_syserror ()));
2690 unlink (socketpath);
2691 goto do_exit;
2695 * Set the cache entry for a file. Prompts for the password.
2697 if (cache_push)
2699 struct crypto_s *crypto = NULL;
2700 gpg_error_t rc = init_client_crypto (&crypto);
2702 if (rc)
2704 estatus = EXIT_FAILURE;
2705 goto do_exit;
2708 #ifdef WITH_AGENT
2709 if (use_agent)
2711 rc = agent_set_pinentry_options (crypto->agent);
2712 if (rc)
2714 estatus = EXIT_FAILURE;
2715 goto do_exit;
2718 #endif
2720 for (opt = 0; cache_push[opt]; opt++)
2722 if (!do_cache_push (cache_push[opt], crypto) && !force)
2724 strv_free (cache_push);
2725 startup_failure ();
2726 estatus = EXIT_FAILURE;
2727 cleanup_crypto (&crypto);
2728 goto do_exit;
2731 cleanup_crypto_stage1 (crypto);
2734 #ifdef WITH_AGENT
2735 if (use_agent)
2736 (void) kill_scd (crypto->agent);
2737 #endif
2739 cleanup_crypto (&crypto);
2740 strv_free (cache_push);
2741 log_write (!nofork ? _("Done. Daemonizing...") :
2742 _("Done. Waiting for connections..."));
2745 config_clear_keys ();
2748 * bind() doesn't like the full pathname of the socket or any non alphanum
2749 * characters so change to the directory where the socket is wanted then
2750 * create it then change to datadir.
2752 if (chdir (socketdir))
2754 log_write ("%s: %s", socketdir,
2755 pwmd_strerror (gpg_error_from_syserror ()));
2756 goto do_exit;
2759 xfree (socketdir);
2761 if ((sockfd = socket (PF_UNIX, SOCK_STREAM, 0)) == -1)
2763 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_syserror ()));
2764 goto do_exit;
2767 addr.sun_family = AF_UNIX;
2768 snprintf (addr.sun_path, sizeof (addr.sun_path), "%s", socketname);
2769 do_unlink = 1;
2770 if (bind (sockfd, (struct sockaddr *) &addr, sizeof (struct sockaddr)) ==
2773 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_syserror ()));
2775 if (errno == EADDRINUSE)
2776 log_write (_("Either there is another pwmd running or '%s' is a \n"
2777 "stale socket. Please remove it manually."), socketpath);
2779 goto do_exit;
2783 char *t = config_get_string ("global", "socket_perms");
2784 mode_t mode;
2785 mode_t mask;
2787 if (t)
2789 mode = strtol (t, NULL, 8);
2790 mask = umask (0);
2791 xfree (t);
2793 if (chmod (socketname, mode) == -1)
2795 log_write ("%s: %s", socketname,
2796 pwmd_strerror (gpg_error_from_syserror ()));
2797 close (sockfd);
2798 umask (mask);
2799 goto do_exit;
2802 umask (mask);
2806 xfree (--socketname);
2808 if (chdir (datadir))
2810 log_write ("%s: %s", datadir,
2811 pwmd_strerror (gpg_error_from_syserror ()));
2812 close (sockfd);
2813 goto do_exit;
2816 xfree (datadir);
2818 if (listen (sockfd, 0) == -1)
2820 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_syserror ()));
2821 goto do_exit;
2824 cmdline = 0;
2826 if (!nofork)
2828 switch (fork ())
2830 case -1:
2831 log_write ("fork(): %s",
2832 pwmd_strerror (gpg_error_from_syserror ()));
2833 goto do_exit;
2834 case 0:
2835 close (0);
2836 close (1);
2837 close (2);
2838 setsid ();
2839 break;
2840 default:
2841 _exit (EXIT_SUCCESS);
2845 pthread_key_create (&thread_name_key, free_key);
2846 pthread_setspecific (thread_name_key, str_dup ("main"));
2847 estatus = server_loop (sockfd, &socketpath);
2849 do_exit:
2850 if (socketpath && do_unlink)
2852 unlink (socketpath);
2853 xfree (socketpath);
2856 xfree (socketarg);
2857 #ifdef WITH_GNUTLS
2858 gnutls_global_deinit ();
2859 #endif
2860 if (rcfile_tid)
2862 #ifdef HAVE_PTHREAD_CANCEL
2863 pthread_cancel (rcfile_tid);
2864 #else
2865 pthread_kill (rcfile_tid, SIGUSR2);
2866 pthread_cond_signal (&rcfile_cond);
2867 #endif
2868 pthread_join (rcfile_tid, NULL);
2871 pthread_cond_destroy (&rcfile_cond);
2872 pthread_mutex_destroy (&rcfile_mutex);
2873 pthread_key_delete (last_error_key);
2874 pthread_key_delete (thread_name_key);
2875 #ifndef HAVE_PTHREAD_CANCEL
2876 pthread_key_delete (signal_thread_key);
2877 #endif
2879 if (global_config)
2880 config_free (global_config);
2882 xfree (rcfile);
2883 xfree (home_directory);
2884 xfree (homedir);
2885 xmlCleanupParser ();
2886 xmlCleanupGlobals ();
2888 if (estatus == EXIT_SUCCESS)
2889 log_write (_("pwmd exiting normally"));
2891 closelog ();
2892 #if defined(DEBUG) && !defined(MEM_DEBUG)
2893 xdump ();
2894 #endif
2895 exit (estatus);