Fix deadlock on SIGSEGV and exiting.
[pwmd.git] / src / pwmd.c
blobe742011b24185ec21bfd5178e7387ffc8dd76e9e
1 /*
2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013
3 Ben Kibbey <bjk@luxsci.net>
5 This file is part of pwmd.
7 Pwmd is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 2 of the License, or
10 (at your option) any later version.
12 Pwmd is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
20 #ifdef HAVE_CONFIG_H
21 #include <config.h>
22 #endif
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <unistd.h>
27 #include <err.h>
28 #include <ctype.h>
29 #include <string.h>
30 #include <sys/socket.h>
31 #include <sys/un.h>
32 #include <signal.h>
33 #include <stdarg.h>
34 #include <string.h>
35 #include <sys/wait.h>
36 #include <fcntl.h>
37 #include <pwd.h>
38 #include <grp.h>
39 #include <pthread.h>
40 #include <sys/mman.h>
41 #include <termios.h>
42 #include <assert.h>
43 #include <syslog.h>
44 #include <netinet/in.h>
45 #include <arpa/inet.h>
46 #include <netdb.h>
47 #include <sys/time.h>
48 #include <sys/resource.h>
49 #include <setjmp.h>
50 #include <errno.h>
52 #ifdef TM_IN_SYS_TIME
53 #include <sys/time.h>
54 #else
55 #include <time.h>
56 #endif
58 #ifdef HAVE_LIMITS_H
59 #include <limits.h>
60 #endif
62 #ifdef HAVE_GETOPT_LONG
63 #ifdef HAVE_GETOPT_H
64 #include <getopt.h>
65 #endif
66 #else
67 #include "getopt_long.h"
68 #endif
70 #ifdef HAVE_PR_SET_NAME
71 #include <sys/prctl.h>
72 #endif
74 #include "pwmd-error.h"
75 #include <gcrypt.h>
77 #include "util-misc.h"
78 #include "mem.h"
79 #include "xml.h"
80 #include "common.h"
81 #include "commands.h"
82 #include "cache.h"
83 #include "util-string.h"
84 #include "mutex.h"
85 #include "rcfile.h"
86 #include "crypto.h"
87 #include "convert.h"
88 #include "pinentry.h"
90 /* In tenths of a second. */
91 #define SIG_TIMEOUT 1
93 /* For (tcp_)accept_thread (usec). */
94 #define ACCEPT_TIMEOUT 30000
96 static int quit;
97 static int exiting;
98 static int cmdline;
99 static jmp_buf jmp;
100 static int nofork;
101 static pthread_cond_t quit_cond;
102 static pthread_mutex_t quit_mutex;
103 static int no_passphrase_file = 0;
104 static pthread_t keepalive_tid;
106 #ifndef HAVE_PTHREAD_CANCEL
107 static pthread_key_t signal_thread_key;
108 #endif
110 #ifdef WITH_GNUTLS
111 static int tls_fd;
112 static int tls6_fd;
113 static pthread_t tls_tid;
114 static pthread_t tls6_tid;
115 static int spawned_tls;
116 static int spawned_tls6;
118 static int start_stop_tls (int term);
119 #endif
121 static int do_cache_push (const char *filename, struct crypto_s *crypto);
122 static int signal_loop (sigset_t sigset);
124 GCRY_THREAD_OPTION_PTHREAD_IMPL;
126 #ifndef HAVE_PTHREAD_CANCEL
127 #define INIT_THREAD_SIGNAL do { \
128 struct sigaction act; \
129 sigset_t sigset; \
130 sigemptyset (&sigset); \
131 sigaddset (&sigset, SIGUSR2); \
132 pthread_sigmask (SIG_UNBLOCK, &sigset, NULL); \
133 memset (&act, 0, sizeof(act)); \
134 act.sa_flags = SA_SIGINFO; \
135 act.sa_mask = sigset; \
136 act.sa_sigaction = catch_thread_signal; \
137 sigaction (SIGUSR2, &act, NULL); \
138 } while (0)
140 static void
141 catch_thread_signal (int sig, siginfo_t *info, void *ctx)
143 int *n = (int *) pthread_getspecific (signal_thread_key);
145 *n = 1;
146 pthread_setspecific (signal_thread_key, n);
148 #endif
150 static void
151 cache_push_from_rcfile ()
153 struct crypto_s *crypto = NULL;
154 char **cache_push;
155 gpg_error_t rc = init_client_crypto (&crypto);
157 if (rc)
159 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
160 return;
163 #ifdef WITH_AGENT
164 if (use_agent)
166 rc = set_agent_option (crypto->agent, "pinentry-mode", "error");
167 if (rc)
169 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
170 return;
173 #endif
175 cache_push = config_get_list ("global", "cache_push");
176 if (cache_push)
178 char **p;
180 for (p = cache_push; *p; p++)
182 (void) do_cache_push (*p, crypto);
183 cleanup_crypto_stage1 (crypto);
186 strv_free (cache_push);
189 #ifdef WITH_AGENT
190 (void) kill_scd (crypto->agent);
191 #endif
192 cleanup_crypto (&crypto);
195 static void
196 setup_logging ()
198 int n = config_get_boolean ("global", "enable_logging");
200 if (n)
202 char *p = config_get_string ("global", "log_path");
204 xfree (logfile);
205 logfile = expand_homedir (p);
206 xfree (p);
208 else
210 xfree (logfile);
211 logfile = NULL;
214 log_syslog = config_get_boolean ("global", "syslog");
215 if (log_syslog == 1)
216 openlog ("pwmd", LOG_NDELAY | LOG_PID, LOG_DAEMON);
219 static void *
220 reload_rcfile_thread (void *arg)
222 #ifndef HAVE_PTHREAD_CANCEL
223 int *n = xmalloc (sizeof (int));
225 *n = 0;
226 pthread_setspecific (signal_thread_key, n);
227 INIT_THREAD_SIGNAL;
228 #endif
230 #ifdef HAVE_PR_SET_NAME
231 prctl (PR_SET_NAME, "reload rcfile");
232 #endif
233 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
234 MUTEX_LOCK (&rcfile_mutex);
235 pthread_cleanup_push (cleanup_mutex_cb, &rcfile_mutex);
237 for (;;)
239 struct allowed_users_s
241 char *section;
242 char **users;
244 struct slist_s *allowed_users = NULL;
245 struct slist_s *config;
246 int b = disable_list_and_dump;
247 int exists;
248 int require_save_key = config_get_bool_param (global_config, "global",
249 "require_save_key",
250 &exists);
251 #ifdef WITH_GNUTLS
252 int tcp_require_key = config_get_bool_param (global_config, "global",
253 "tcp_require_key",
254 &exists);
255 #endif
257 pthread_cond_wait (&rcfile_cond, &rcfile_mutex);
258 #ifndef HAVE_PTHREAD_CANCEL
259 int *cancel = (int *) pthread_getspecific (signal_thread_key);
260 if (*cancel)
261 break;
262 #endif
264 /* Keep the "allowed" parameter across rcfile reloads to prevent
265 tampering. */
266 int n, t = slist_length (global_config);
267 for (n = 0; n < t; n++)
269 struct allowed_users_s *allowed;
270 struct config_section_s *section;
271 char **users;
273 section = slist_nth_data (global_config, n);
274 users = config_get_list_param (global_config, section->name,
275 "allowed", &exists);
276 if (users)
278 allowed = xmalloc (sizeof(struct allowed_users_s));
279 allowed->section = str_dup (section->name);
280 allowed->users = users;
281 allowed_users = slist_append (allowed_users, allowed);
285 log_write (_("reloading configuration file '%s'"), rcfile);
286 config = config_parse (rcfile);
287 if (config)
289 config_free (global_config);
290 global_config = config;
291 setup_logging ();
292 cache_push_from_rcfile ();
293 config_clear_keys ();
296 disable_list_and_dump = !disable_list_and_dump ? b : 1;
297 config_set_bool_param (&global_config, "global", "require_save_key",
298 require_save_key ? "true" : "false");
299 #ifdef WITH_GNUTLS
300 if (config_get_bool_param (global_config, "global", "tcp_require_key",
301 &exists) && exists)
302 tcp_require_key = 1;
304 config_set_bool_param (&global_config, "global", "tcp_require_key",
305 tcp_require_key ? "true" : "false");
306 #endif
308 if (allowed_users)
310 int n, t = slist_length (allowed_users);
312 for (n = 0; n < t; n++)
314 struct allowed_users_s *allowed;
315 char *tmp;
317 allowed = slist_nth_data (allowed_users, n);
318 tmp = strv_join (",", allowed->users);
319 config_set_list_param (&global_config, allowed->section,
320 "allowed", tmp);
321 xfree (tmp);
322 xfree (allowed->section);
323 strv_free (allowed->users);
324 xfree (allowed);
327 slist_free (allowed_users);
330 #ifdef WITH_GNUTLS
331 /* Kill existing listening threads since the configured listening
332 * protocols may have changed. */
333 start_stop_tls (1);
334 start_stop_tls (0);
335 #endif
338 pthread_cleanup_pop (1);
339 return NULL;
342 gpg_error_t
343 send_error (assuan_context_t ctx, gpg_error_t e)
345 struct client_s *client = assuan_get_pointer (ctx);
347 if (gpg_err_source (e) == GPG_ERR_SOURCE_UNKNOWN)
348 e = gpg_error (e);
350 if (client)
351 client->last_rc = e;
353 if (!e)
354 return assuan_process_done (ctx, 0);
356 if (!ctx)
358 log_write ("ERR %i: %s", e, pwmd_strerror (e));
359 return e;
362 if (client && gpg_err_code (e) == GPG_ERR_BAD_DATA)
364 xmlErrorPtr xe = client->xml_error;
366 if (!xe)
367 xe = xmlGetLastError ();
368 if (xe)
370 log_write ("%s", xe->message);
371 if (client->last_error)
372 xfree (client->last_error);
374 client->last_error = str_dup (xe->message);
377 e = assuan_process_done (ctx, assuan_set_error (ctx, e,
378 xe ? xe->message :
379 NULL));
381 if (xe == client->xml_error)
382 xmlResetError (xe);
383 else
384 xmlResetLastError ();
386 client->xml_error = NULL;
387 return e;
390 return assuan_process_done (ctx,
391 assuan_set_error (ctx, e, pwmd_strerror (e)));
395 assuan_log_cb (assuan_context_t ctx, void *data, unsigned cat,
396 const char *msg)
398 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
399 int i, t;
400 int match = 0;
402 pthread_mutex_lock (&m);
403 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock, &m);
404 t = strv_length (debug_level);
406 for (i = 0; i < t; i++)
408 if (!strcasecmp (debug_level[i], (char *) "init")
409 && cat == ASSUAN_LOG_INIT)
411 match = 1;
412 break;
415 if (!strcasecmp (debug_level[i], (char *) "ctx")
416 && cat == ASSUAN_LOG_CTX)
418 match = 1;
419 break;
422 if (!strcasecmp (debug_level[i], (char *) "engine")
423 && cat == ASSUAN_LOG_ENGINE)
425 match = 1;
426 break;
429 if (!strcasecmp (debug_level[i], (char *) "data")
430 && cat == ASSUAN_LOG_DATA)
432 match = 1;
433 break;
436 if (!strcasecmp (debug_level[i], (char *) "sysio")
437 && cat == ASSUAN_LOG_SYSIO)
439 match = 1;
440 break;
443 if (!strcasecmp (debug_level[i], (char *) "control")
444 && cat == ASSUAN_LOG_CONTROL)
446 match = 1;
447 break;
451 if (match && msg)
453 if (logfile)
455 int fd;
457 if ((fd =
458 open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600)) == -1)
459 warn ("%s", logfile);
460 else
462 pthread_cleanup_push (cleanup_fd_cb, &fd);
463 write (fd, msg, strlen (msg));
464 pthread_cleanup_pop (1);
468 if (nofork)
470 fprintf (stderr, "%s%s", data ? (char *) data : "", msg);
471 fflush (stderr);
475 pthread_cleanup_pop (1);
476 return match;
479 void
480 log_write (const char *fmt, ...)
482 char *args, *line;
483 va_list ap;
484 struct tm *tm;
485 time_t now;
486 char tbuf[21];
487 int fd = -1;
488 char *name = NULL;
489 char buf[255];
490 pthread_t tid = pthread_self ();
491 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
493 if ((!logfile && !isatty (STDERR_FILENO) && !log_syslog) || !fmt)
494 return;
496 pthread_mutex_lock (&m);
497 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock, &m);
498 pthread_cleanup_push (cleanup_fd_cb, &fd);
500 if (!cmdline && logfile)
502 if ((fd = open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600)) == -1)
503 warn ("%s", logfile);
506 va_start (ap, fmt);
508 if (str_vasprintf (&args, fmt, ap) != -1)
510 if (cmdline)
512 pthread_cleanup_push (xfree, args);
513 fprintf (stderr, "%s\n", args);
514 fflush (stderr);
515 pthread_cleanup_pop (1);
517 else
519 pthread_cleanup_push (xfree, args);
520 name = pthread_getspecific (thread_name_key);
521 snprintf (buf, sizeof (buf), "%s(%p): ", name ? name : _("unknown"),
522 (pthread_t *) tid);
523 name = buf;
525 if (!cmdline && log_syslog && !nofork)
526 syslog (LOG_INFO, "%s%s", name, args);
528 time (&now);
529 tm = localtime (&now);
530 strftime (tbuf, sizeof (tbuf), "%b %d %Y %H:%M:%S ", tm);
531 tbuf[sizeof (tbuf) - 1] = 0;
533 if (args[strlen (args) - 1] == '\n')
534 args[strlen (args) - 1] = 0;
536 line = str_asprintf ("%s %i %s%s\n", tbuf, getpid (), name, args);
537 pthread_cleanup_pop (1);
538 if (line)
540 pthread_cleanup_push (xfree, line);
541 if (logfile && fd != -1)
543 write (fd, line, strlen (line));
544 fsync (fd);
547 if (nofork)
549 fprintf (stdout, "%s", line);
550 fflush (stdout);
553 pthread_cleanup_pop (1);
558 va_end (ap);
559 pthread_cleanup_pop (1);
560 pthread_cleanup_pop (0);
561 pthread_mutex_unlock (&m);
564 #ifdef WITH_GNUTLS
565 static int
566 secure_mem_check (const void *arg)
568 return 1;
570 #endif
572 static gpg_error_t
573 setup_crypto ()
575 gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
577 if (!gcry_check_version (GCRYPT_VERSION))
579 fprintf (stderr, _("gcry_check_version(): Incompatible libgcrypt. "
580 "Wanted %s, got %s.\n"), GCRYPT_VERSION,
581 gcry_check_version (NULL));
582 return GPG_ERR_UNKNOWN_VERSION;
585 gcry_set_allocation_handler (xmalloc, xmalloc, NULL, xrealloc, xfree);
586 return 0;
589 #ifdef HAVE_GETGRNAM_R
590 gpg_error_t
591 do_validate_peer (assuan_context_t ctx, const char *section,
592 assuan_peercred_t * peer)
594 char **users;
595 int allowed = 0;
596 gpg_error_t rc;
598 rc = assuan_get_peercred (ctx, peer);
599 if (rc)
600 return rc;
602 users = config_get_list (section, "allowed");
603 if (users)
605 for (char **p = users; *p; p++)
607 struct passwd pw, *result;
608 struct group gr, *gresult;
609 char *buf = NULL;
610 char *user = *p;
611 int deny = (*user == '-') ? 1 : 0;
613 if (deny)
614 user++;
616 if (*user == '@') // all users in group
618 size_t len = sysconf (_SC_GETGR_R_SIZE_MAX);
620 if (len == -1)
621 len = 16384;
623 buf = xmalloc (len);
624 if (!buf)
626 strv_free (users);
627 return GPG_ERR_ENOMEM;
630 user++;
631 if (!getgrnam_r (user, &gr, buf, len, &gresult) && gresult)
633 if (gresult->gr_gid == (*peer)->gid)
635 xfree (buf);
636 allowed = !deny;
637 continue;
640 len = sysconf (_SC_GETPW_R_SIZE_MAX);
641 if (len == -1)
642 len = 16384;
644 char *tbuf = xmalloc (len);
645 for (char **t = gresult->gr_mem; *t; t++)
647 if (!getpwnam_r (*t, &pw, tbuf, len, &result) && result)
649 if (result->pw_uid == (*peer)->uid)
651 allowed = !deny;
652 break;
658 else
660 size_t len = sysconf (_SC_GETPW_R_SIZE_MAX);
662 if (len == -1)
663 len = 16384;
665 buf = xmalloc (len);
667 if (!buf)
669 strv_free (users);
670 return GPG_ERR_ENOMEM;
673 if (!getpwnam_r (user, &pw, buf, len, &result) && result)
675 if (result->pw_uid == (*peer)->uid)
676 allowed = !deny;
680 xfree (buf);
683 strv_free (users);
686 return allowed ? 0 : GPG_ERR_INV_USER_ID;
688 #else
689 gpg_error_t
690 do_validate_peer (assuan_context_t ctx, const char *section,
691 assuan_peercred_t * peer)
693 char **users;
694 int allowed = 0;
695 gpg_error_t rc;
697 rc = assuan_get_peercred (ctx, peer);
698 if (rc)
699 return rc;
701 users = config_get_list (section, "allowed");
702 if (users)
704 for (char **p = users; *p; p++)
706 struct passwd *result;
707 struct group *gresult;
708 char *user = *p;
709 int deny = (*user == '-') ? 1 : 0;
711 if (deny)
712 user++;
714 if (*user == '@') // all users in group
716 user++;
717 gresult = getgrnam (user);
718 if (gresult && gresult->gr_gid == (*peer)->gid)
720 allowed = !deny;
721 continue;
724 for (char **t = gresult->gr_mem; *t; t++)
726 result = getpwnam (*t);
727 if (result && result->pw_uid == (*peer)->uid)
729 allowed = !deny;
730 break;
734 else
736 result = getpwnam (user);
737 if (result && result->pw_uid == (*peer)->uid)
738 allowed = !deny;
742 strv_free (users);
745 return allowed ? 0 : GPG_ERR_INV_USER_ID;
747 #endif
749 static gpg_error_t
750 validate_peer (struct client_s *cl)
752 gpg_error_t rc;
753 assuan_peercred_t peer;
755 #ifdef WITH_GNUTLS
756 if (cl->thd->remote)
757 return tls_validate_access (cl, NULL);
758 #endif
760 rc = do_validate_peer (cl->ctx, "global", &peer);
761 if (!rc || gpg_err_code (rc) == GPG_ERR_INV_USER_ID)
762 log_write ("peer %s: uid=%i, gid=%i, pid=%i",
763 !rc ? _("accepted") : _("rejected"), peer->uid, peer->gid,
764 peer->pid);
765 else if (rc)
766 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
768 return rc;
771 static void
772 xml_error_cb (void *data, xmlErrorPtr e)
774 struct client_s *client = data;
777 * Keep the first reported error as the one to show in the error
778 * description. Reset in send_error().
780 if (client->xml_error)
781 return;
783 xmlCopyError (e, client->xml_error);
786 static pid_t
787 hook_waitpid (assuan_context_t ctx, pid_t pid, int action,
788 int *status, int options)
790 return waitpid (pid, status, options);
793 static ssize_t
794 hook_read (assuan_context_t ctx, assuan_fd_t fd, void *data, size_t len)
796 #ifdef WITH_GNUTLS
797 struct client_s *client = assuan_get_pointer (ctx);
799 if (client->thd->remote)
800 return tls_read_hook (ctx, (int) fd, data, len);
801 #endif
803 return read ((int) fd, data, len);
806 static ssize_t
807 hook_write (assuan_context_t ctx, assuan_fd_t fd,
808 const void *data, size_t len)
810 #ifdef WITH_GNUTLS
811 struct client_s *client = assuan_get_pointer (ctx);
813 if (client->thd->remote)
814 return tls_write_hook (ctx, (int) fd, data, len);
815 #endif
817 return write ((int) fd, data, len);
820 static int
821 new_connection (struct client_s *cl)
823 gpg_error_t rc;
824 static struct assuan_malloc_hooks mhooks = { xmalloc, xrealloc, xfree };
825 static struct assuan_system_hooks shooks = {
826 ASSUAN_SYSTEM_HOOKS_VERSION,
827 __assuan_usleep,
828 __assuan_pipe,
829 __assuan_close,
830 hook_read,
831 hook_write,
832 //FIXME
833 NULL, //recvmsg
834 NULL, //sendmsg both are used for FD passing
835 __assuan_spawn,
836 hook_waitpid,
837 __assuan_socketpair,
838 __assuan_socket,
839 __assuan_connect
842 #ifdef WITH_GNUTLS
843 if (cl->thd->remote)
845 char *prio = config_get_string ("global", "tls_cipher_suite");
847 cl->thd->tls = tls_init (cl->thd->fd, cl->thd->timeout, prio);
848 xfree (prio);
849 if (!cl->thd->tls)
850 return 0;
852 #endif
854 rc = assuan_new_ext (&cl->ctx, GPG_ERR_SOURCE_DEFAULT, &mhooks,
855 debug_level ? assuan_log_cb : NULL, NULL);
856 if (rc)
857 goto fail;
859 assuan_ctx_set_system_hooks (cl->ctx, &shooks);
860 rc = assuan_init_socket_server (cl->ctx, cl->thd->fd, 2);
861 if (rc)
862 goto fail;
864 assuan_set_pointer (cl->ctx, cl);
865 assuan_set_hello_line (cl->ctx, PACKAGE_STRING);
866 rc = register_commands (cl->ctx);
867 if (rc)
868 goto fail;
870 #ifdef WITH_GNUTLS
871 if (cl->thd->remote)
873 cl->thd->timeout = config_get_integer ("global", "tls_timeout");
874 fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK);
876 #endif
878 rc = assuan_accept (cl->ctx);
879 if (rc)
880 goto fail;
882 rc = validate_peer (cl);
883 /* May not be implemented on all platforms. */
884 if (rc && gpg_err_code (rc) != GPG_ERR_ASS_GENERAL)
885 goto fail;
887 rc = init_client_crypto (&cl->crypto);
888 if (rc)
889 goto fail;
891 #ifdef WITH_AGENT
892 if (use_agent)
893 cl->crypto->agent->client_ctx = cl->ctx;
894 #endif
896 cl->crypto->client_ctx = cl->ctx;
897 xmlSetStructuredErrorFunc (cl, xml_error_cb);
898 return 1;
900 fail:
901 log_write ("%s", pwmd_strerror (rc));
902 return 0;
906 * This is called after a client_thread() terminates. Set with
907 * pthread_cleanup_push().
909 static void
910 cleanup_cb (void *arg)
912 struct client_thread_s *cn = arg;
913 struct client_s *cl = cn->cl;
915 MUTEX_LOCK (&cn_mutex);
916 cn_thread_list = slist_remove (cn_thread_list, cn);
917 MUTEX_UNLOCK (&cn_mutex);
919 if (cl)
921 cleanup_client (cl);
923 #ifdef WITH_GNUTLS
924 if (cn->tls)
926 gnutls_deinit (cn->tls->ses);
927 xfree (cn->tls->fp);
928 xfree (cn->tls);
930 #endif
932 if (!cn->atfork && cl->ctx)
933 assuan_release (cl->ctx);
934 else if (!cn->atfork && cl->thd && cl->thd->fd != -1)
935 close (cl->thd->fd);
937 if (cl->crypto)
938 cleanup_crypto (&cl->crypto);
940 pinentry_free_opts (&cl->pinentry_opts);
941 xfree (cl);
943 else
945 if (cn->fd != -1)
946 close (cn->fd);
949 while (cn->msg_queue)
951 struct status_msg_s *msg = cn->msg_queue;
953 cn->msg_queue = msg->next;
954 xfree (msg->line);
955 xfree (msg);
958 if (!cn->atfork && cn->status_msg_pipe[0] != -1)
959 close (cn->status_msg_pipe[0]);
961 if (!cn->atfork && cn->status_msg_pipe[1] != -1)
962 close (cn->status_msg_pipe[1]);
964 pthread_mutex_destroy (&cn->status_mutex);
966 if (!cn->atfork)
968 log_write (_("exiting, fd=%i"), cn->fd);
969 send_status_all (STATUS_CLIENTS, NULL);
972 xfree (cn);
973 pthread_cond_signal (&quit_cond);
976 void
977 cleanup_all_clients (int atfork)
979 /* This function may be called from pthread_atfork() which requires
980 reinitialization. */
981 if (atfork)
983 pthread_mutexattr_t attr;
985 pthread_mutexattr_init (&attr);
986 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
987 pthread_mutex_init (&cn_mutex, &attr);
988 pthread_mutexattr_destroy (&attr);
989 cache_mutex_init ();
992 MUTEX_LOCK (&cn_mutex);
994 while (slist_length (cn_thread_list))
996 struct client_thread_s *thd = slist_nth_data (cn_thread_list, 0);
998 thd->atfork = atfork;
999 cleanup_cb (thd);
1002 exiting = 1;
1003 MUTEX_UNLOCK (&cn_mutex);
1004 cache_deinit (atfork);
1007 static gpg_error_t
1008 send_msg_queue (struct client_thread_s *thd)
1010 MUTEX_LOCK (&thd->status_mutex);
1011 gpg_error_t rc = 0;
1012 char c;
1014 read (thd->status_msg_pipe[0], &c, 1);
1016 while (thd->msg_queue)
1018 struct status_msg_s *msg = thd->msg_queue;
1020 thd->msg_queue = thd->msg_queue->next;
1021 MUTEX_UNLOCK (&thd->status_mutex);
1022 rc = send_status (thd->cl->ctx, msg->s, msg->line);
1023 MUTEX_LOCK (&thd->status_mutex);
1024 xfree (msg->line);
1025 xfree (msg);
1027 if (rc)
1028 break;
1031 MUTEX_UNLOCK (&thd->status_mutex);
1032 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1033 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
1035 return rc;
1038 static void *
1039 client_thread (void *data)
1041 struct client_thread_s *thd = data;
1042 struct client_s *cl = xcalloc (1, sizeof (struct client_s));
1044 #ifdef HAVE_PR_SET_NAME
1045 prctl (PR_SET_NAME, "client");
1046 #endif
1047 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1049 if (!cl)
1051 log_write ("%s(%i): %s", __FILE__, __LINE__,
1052 pwmd_strerror (GPG_ERR_ENOMEM));
1053 return NULL;
1056 MUTEX_LOCK (&cn_mutex);
1057 pthread_cleanup_push (cleanup_cb, thd);
1058 thd->cl = cl;
1059 cl->thd = thd;
1060 MUTEX_UNLOCK (&cn_mutex);
1062 if (new_connection (cl))
1064 int finished = 0;
1065 gpg_error_t rc;
1067 send_status_all (STATUS_CLIENTS, NULL);
1068 rc = send_status (cl->ctx, STATUS_CACHE, NULL);
1069 if (rc)
1071 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
1072 finished = 1;
1075 while (!finished)
1077 fd_set rfds;
1078 int n;
1079 int eof;
1081 FD_ZERO (&rfds);
1082 FD_SET (thd->fd, &rfds);
1083 FD_SET (thd->status_msg_pipe[0], &rfds);
1084 n = thd->fd > thd->status_msg_pipe[0]
1085 ? thd->fd : thd->status_msg_pipe[0];
1087 n = select (n + 1, &rfds, NULL, NULL, NULL);
1088 if (n == -1)
1090 log_write ("%s", strerror (errno));
1091 break;
1094 if (FD_ISSET (thd->status_msg_pipe[0], &rfds))
1096 rc = send_msg_queue (thd);
1097 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1098 break;
1101 if (!FD_ISSET (thd->fd, &rfds))
1102 continue;
1104 rc = assuan_process_next (cl->ctx, &eof);
1105 if (rc || eof)
1107 if (gpg_err_code (rc) == GPG_ERR_EOF || eof)
1108 break;
1110 log_write ("assuan_process_next(): rc=%i %s", rc,
1111 pwmd_strerror (rc));
1112 if (rc == gpg_error (GPG_ERR_ETIMEDOUT))
1113 break;
1115 rc = send_error (cl->ctx, rc);
1116 if (rc)
1118 log_write ("assuan_process_done(): rc=%i %s", rc,
1119 pwmd_strerror (rc));
1120 break;
1124 /* Since the msg queue pipe fd's are non-blocking, check for
1125 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1126 * client has already disconnected and will be converted to
1127 * GPG_ERR_EOF during assuan_process_next().
1129 rc = send_msg_queue (thd);
1130 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1131 break;
1135 pthread_cleanup_pop (1);
1136 return NULL;
1139 static int
1140 xml_import (const char *filename, const char *outfile,
1141 const char *keygrip, const char *sign_keygrip,
1142 const char *keyfile, int no_passphrase, const char *cipher,
1143 const char *params, unsigned long s2k_count, uint64_t iterations)
1145 xmlDocPtr doc;
1146 int fd;
1147 struct stat st;
1148 int len;
1149 xmlChar *xmlbuf;
1150 xmlChar *xml;
1151 gpg_error_t rc;
1152 struct crypto_s *crypto = NULL;
1153 void *key = NULL;
1154 size_t keylen = 0;
1155 int algo = cipher ? cipher_string_to_gcrypt ((char *) cipher) :
1156 GCRY_CIPHER_AES256;
1158 if (algo == -1)
1160 log_write ("ERR %i: %s", gpg_error (GPG_ERR_CIPHER_ALGO),
1161 pwmd_strerror (GPG_ERR_CIPHER_ALGO));
1162 return 0;
1165 if (stat (filename, &st) == -1)
1167 log_write ("%s: %s", filename,
1168 pwmd_strerror (gpg_error_from_errno (errno)));
1169 return 0;
1172 rc = init_client_crypto (&crypto);
1173 if (rc)
1174 return 0;
1176 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
1177 crypto->save.hdr.flags = set_cipher_flag (crypto->save.hdr.flags, algo);
1178 log_write (_("Importing XML from '%s'. Output will be written to '%s' ..."),
1179 filename, outfile);
1181 if ((fd = open (filename, O_RDONLY)) == -1)
1183 log_write ("%s: %s", filename,
1184 pwmd_strerror (gpg_error_from_errno (errno)));
1185 goto fail;
1188 if ((xmlbuf = xmalloc (st.st_size + 1)) == NULL)
1190 close (fd);
1191 log_write ("%s(%i): %s", __FILE__, __LINE__,
1192 pwmd_strerror (GPG_ERR_ENOMEM));
1193 goto fail;
1196 if (read (fd, xmlbuf, st.st_size) == -1)
1198 rc = gpg_error_from_errno (errno);
1199 close (fd);
1200 log_write ("%s: %s", filename, pwmd_strerror (rc));
1201 goto fail;
1204 close (fd);
1205 xmlbuf[st.st_size] = 0;
1207 * Make sure the document validates.
1209 if ((doc = xmlReadDoc (xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS)) == NULL)
1211 log_write ("xmlReadDoc() failed");
1212 xfree (xmlbuf);
1213 goto fail;
1216 xfree (xmlbuf);
1217 xmlNodePtr n = xmlDocGetRootElement (doc);
1218 if (n && !xmlStrEqual (n->name, (xmlChar *) "pwmd"))
1220 log_write (_("Could not find root \"pwmd\" element."));
1221 rc = GPG_ERR_BAD_DATA;
1224 if (!rc)
1225 rc = validate_import (n ? n->children : n);
1227 if (rc)
1229 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1230 xmlFreeDoc (doc);
1231 goto fail;
1234 xmlDocDumpMemory (doc, &xml, &len);
1235 xmlFreeDoc (doc);
1236 crypto->save.s2k_count = s2k_count;
1237 crypto->save.hdr.iterations = iterations;
1238 if (!use_agent)
1240 rc = export_common (NULL, 0, crypto, xml, len, outfile, keyfile, &key,
1241 &keylen, 0, 0, no_passphrase);
1242 if (!rc)
1243 log_write (_("Success!"));
1245 #ifdef WITH_AGENT
1246 else
1248 rc = agent_set_pinentry_options (crypto->agent);
1249 if (!rc)
1250 rc = agent_export_common (crypto, keygrip, sign_keygrip, no_passphrase,
1251 xml, len, outfile, params, keyfile);
1253 #endif
1255 gcry_free (key);
1256 xmlFree (xml);
1257 if (rc)
1259 send_error (NULL, rc);
1260 goto fail;
1263 cleanup_crypto (&crypto);
1264 return 1;
1266 fail:
1267 cleanup_crypto (&crypto);
1268 return 0;
1271 static int
1272 do_cache_push (const char *filename, struct crypto_s *crypto)
1274 unsigned char md5file[16];
1275 gpg_error_t rc;
1276 char *key = NULL;
1277 size_t keylen = 0;
1278 xmlDocPtr doc;
1279 struct cache_data_s *cdata;
1280 unsigned char *crc;
1281 size_t len;
1283 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1284 filename);
1286 if (valid_filename (filename) == 0)
1288 log_write (_("%s: Invalid characters in filename"), filename);
1289 return 0;
1292 rc = decrypt_common (NULL, 0, crypto, filename, &key, &keylen);
1293 if (rc)
1294 return 0;
1296 doc = parse_doc ((char *) crypto->plaintext, crypto->plaintext_len);
1297 if (!doc)
1299 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM));
1300 xfree (key);
1301 return 0;
1304 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
1305 cdata = xcalloc (1, sizeof (struct cache_data_s));
1306 if (!cdata)
1308 xmlFreeDoc (doc);
1309 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM));
1310 xfree (key);
1311 return 0;
1314 rc = get_checksum (filename, &crc, &len);
1315 if (rc)
1317 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1318 xmlFreeDoc (doc);
1319 free_cache_data_once (cdata);
1320 xfree (key);
1321 return 0;
1324 cdata->crc = crc;
1325 rc = encrypt_xml (NULL, cache_key, cache_keysize, GCRY_CIPHER_AES,
1326 crypto->plaintext, crypto->plaintext_len, &cdata->doc,
1327 &cdata->doclen, &cache_iv, &cache_blocksize, 0);
1328 if (!rc && !IS_PKI (crypto))
1330 cdata->key = key;
1331 cdata->keylen = keylen;
1333 else
1334 xfree (key);
1336 if (rc)
1338 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1339 xmlFreeDoc (doc);
1340 free_cache_data_once (cdata);
1341 return 0;
1344 #ifdef WITH_AGENT
1345 if (use_agent && IS_PKI (crypto))
1347 gcry_sexp_build ((gcry_sexp_t *) & cdata->pubkey, NULL, "%S",
1348 crypto->pkey_sexp);
1349 gcry_sexp_build ((gcry_sexp_t *) & cdata->sigkey, NULL, "%S",
1350 crypto->sigpkey_sexp);
1352 #endif
1354 int timeout = config_get_integer (filename, "cache_timeout");
1355 cache_add_file (md5file, crypto->grip, cdata, timeout);
1356 log_write (_("Successfully added '%s' to the cache."), filename);
1357 return 1;
1360 static gpg_error_t
1361 init_client (int fd, const char *addr)
1363 gpg_error_t rc = 0;
1364 struct client_thread_s *new = xcalloc (1, sizeof (struct client_thread_s));
1366 if (!new)
1368 close (fd);
1369 return GPG_ERR_ENOMEM;
1372 MUTEX_LOCK (&cn_mutex);
1373 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
1375 if (pipe (new->status_msg_pipe) == -1)
1376 rc = gpg_error_from_errno (errno);
1378 if (!rc)
1380 fcntl (new->status_msg_pipe[0], F_SETFL, O_NONBLOCK);
1381 fcntl (new->status_msg_pipe[1], F_SETFL, O_NONBLOCK);
1382 pthread_mutex_init (&new->status_mutex, NULL);
1385 if (!rc)
1387 #ifdef WITH_GNUTLS
1388 new->remote = addr ? 1 : 0;
1389 #endif
1390 new->fd = fd;
1391 rc = create_thread (client_thread, new, &new->tid, 1);
1392 if (rc)
1394 close (new->status_msg_pipe[0]);
1395 close (new->status_msg_pipe[1]);
1396 pthread_mutex_destroy (&new->status_mutex);
1400 if (!rc)
1402 struct slist_s *list = slist_append (cn_thread_list, new);
1404 if (list)
1406 cn_thread_list = list;
1407 if (addr)
1408 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1409 (pthread_t *) new->tid, fd, addr);
1410 else
1411 log_write (_("new connection: tid=%p, fd=%i"),
1412 (pthread_t *) new->tid, fd);
1414 else
1415 rc = GPG_ERR_ENOMEM;
1418 pthread_cleanup_pop (1);
1420 if (rc)
1422 xfree (new);
1423 close (fd);
1424 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1425 pwmd_strerror (rc));
1427 return rc;
1430 static void*
1431 keepalive_thread (void *arg)
1433 #ifndef HAVE_PTHREAD_CANCEL
1434 int *n = xmalloc (sizeof (int));
1436 *n = 0;
1437 pthread_setspecific (signal_thread_key, n);
1438 INIT_THREAD_SIGNAL;
1439 #endif
1441 #ifdef HAVE_PR_SET_NAME
1442 prctl (PR_SET_NAME, "keepalive");
1443 #endif
1444 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1446 for (;;)
1448 int n = config_get_integer ("global", "keepalive_interval");
1449 struct timeval tv = { n, 0 };
1450 #ifndef HAVE_PTHREAD_CANCEL
1451 int *sigusr2;
1453 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1454 if (*sigusr2)
1455 break;
1456 #endif
1458 send_status_all (STATUS_KEEPALIVE, NULL);
1459 select (0, NULL, NULL, NULL, &tv);
1462 return NULL;
1465 #ifdef WITH_GNUTLS
1466 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1467 static void *
1468 get_in_addr (struct sockaddr *sa)
1470 if (sa->sa_family == AF_INET)
1471 return &(((struct sockaddr_in *) sa)->sin_addr);
1473 return &(((struct sockaddr_in6 *) sa)->sin6_addr);
1476 static void *
1477 tcp_accept_thread (void *arg)
1479 int sockfd = *(int *) arg;
1480 #ifndef HAVE_PTHREAD_CANCEL
1481 int *n = xmalloc (sizeof (int));
1483 *n = 0;
1484 pthread_setspecific (signal_thread_key, n);
1485 INIT_THREAD_SIGNAL;
1486 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1487 #endif
1489 #ifdef HAVE_PR_SET_NAME
1490 prctl (PR_SET_NAME, "tcp_accept");
1491 #endif
1492 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1494 for (;;)
1496 struct sockaddr_storage raddr;
1497 socklen_t slen = sizeof (raddr);
1498 int fd = -1;
1499 unsigned long n;
1500 char s[INET6_ADDRSTRLEN];
1501 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1502 #ifndef HAVE_PTHREAD_CANCEL
1503 int *sigusr2;
1505 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1506 if (*sigusr2)
1507 break;
1508 #endif
1510 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1511 if (fd == -1)
1513 if (errno == EMFILE || errno == ENFILE)
1514 log_write ("accept(): %s",
1515 pwmd_strerror (gpg_error_from_errno (errno)));
1516 else if (errno != EAGAIN)
1518 if (!quit) // probably EBADF
1519 log_write ("accept(): %s", strerror (errno));
1521 break;
1524 #ifndef HAVE_PTHREAD_CANCEL
1525 select (0, NULL, NULL, NULL, &tv);
1526 #endif
1527 continue;
1530 if (quit)
1531 break;
1533 inet_ntop (raddr.ss_family, get_in_addr ((struct sockaddr *) &raddr),
1534 s, sizeof s);
1535 (void) init_client (fd, s);
1536 n = config_get_integer ("global", "tcp_wait");
1537 if (n > 0)
1539 tv.tv_sec = (n * 100000) / 100000;
1540 tv.tv_usec = (n * 100000) % 100000;
1541 select (0, NULL, NULL, NULL, &tv);
1545 return NULL;
1548 static int
1549 start_stop_tls_with_protocol (int ipv6, int term)
1551 struct addrinfo hints, *servinfo, *p;
1552 int port = config_get_integer ("global", "tcp_port");
1553 char buf[7];
1554 int n;
1555 gpg_error_t rc;
1556 int *fd = ipv6 ? &tls6_fd : &tls_fd;
1558 if (term || config_get_boolean ("global", "enable_tcp") == 0)
1560 if (tls6_fd != -1)
1562 if (spawned_tls6)
1564 #ifdef HAVE_PTHREAD_CANCEL
1565 pthread_cancel (tls6_tid);
1566 #else
1567 pthread_kill (tls6_tid, SIGUSR2);
1568 #endif
1569 pthread_join (tls6_tid, NULL);
1572 shutdown (tls6_fd, SHUT_RDWR);
1573 close (tls6_fd);
1574 tls6_fd = -1;
1575 spawned_tls6 = 0;
1578 if (tls_fd != -1)
1580 if (spawned_tls)
1582 #ifdef HAVE_PTHREAD_CANCEL
1583 pthread_cancel (tls_tid);
1584 #else
1585 pthread_kill (tls_tid, SIGUSR2);
1586 #endif
1587 pthread_join (tls_tid, NULL);
1590 shutdown (tls_fd, SHUT_RDWR);
1591 close (tls_fd);
1592 tls_fd = -1;
1593 spawned_tls = 0;
1596 /* A client may still be connected. */
1597 if (!quit && x509_cred != NULL)
1598 tls_deinit_params ();
1600 return 1;
1603 if ((ipv6 && tls6_fd != -1) || (!ipv6 && tls_fd != -1))
1604 return 1;
1606 memset (&hints, 0, sizeof (hints));
1607 hints.ai_family = ipv6 ? AF_INET6 : AF_INET;
1608 hints.ai_socktype = SOCK_STREAM;
1609 hints.ai_flags = AI_PASSIVE;
1610 snprintf (buf, sizeof (buf), "%i", port);
1612 if ((n = getaddrinfo (NULL, buf, &hints, &servinfo)) == -1)
1614 log_write ("getaddrinfo(): %s", gai_strerror (n));
1615 return 0;
1618 for (n = 0, p = servinfo; p != NULL; p = p->ai_next)
1620 int r = 1;
1622 if ((ipv6 && p->ai_family != AF_INET6)
1623 || (!ipv6 && p->ai_family != AF_INET))
1624 continue;
1626 if ((*fd = socket (p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
1628 log_write ("socket(): %s", strerror (errno));
1629 continue;
1632 if (setsockopt (*fd, SOL_SOCKET, SO_REUSEADDR, &r, sizeof (int)) == -1)
1634 log_write ("setsockopt(): %s",
1635 pwmd_strerror (gpg_error_from_errno (errno)));
1636 freeaddrinfo (servinfo);
1637 goto fail;
1640 if (bind (*fd, p->ai_addr, p->ai_addrlen) == -1)
1642 close (*fd);
1643 log_write ("bind(): %s",
1644 pwmd_strerror (gpg_error_from_errno (errno)));
1645 continue;
1648 n++;
1649 break;
1652 freeaddrinfo (servinfo);
1654 if (!n)
1655 goto fail;
1657 #if HAVE_DECL_SO_BINDTODEVICE != 0
1658 char *tmp = config_get_string ("global", "tcp_interface");
1659 if (tmp && setsockopt (*fd, SOL_SOCKET, SO_BINDTODEVICE, tmp,
1660 strlen (tmp)) == -1)
1662 log_write ("setsockopt(): %s",
1663 pwmd_strerror (gpg_error_from_errno (errno)));
1664 xfree (tmp);
1665 goto fail;
1668 xfree (tmp);
1669 #endif
1671 if (x509_cred == NULL)
1673 rc = tls_init_params ();
1674 if (rc)
1675 goto fail;
1678 if (listen (*fd, 0) == -1)
1680 log_write ("listen(): %s", strerror (errno));
1681 goto fail;
1684 if (ipv6)
1685 rc = create_thread (tcp_accept_thread, fd, &tls6_tid, 0);
1686 else
1687 rc = create_thread (tcp_accept_thread, fd, &tls_tid, 0);
1689 if (rc)
1691 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1692 pwmd_strerror (rc));
1693 goto fail;
1696 if (ipv6)
1697 spawned_tls6 = 1;
1698 else
1699 spawned_tls = 1;
1701 return 1;
1703 fail:
1704 start_stop_tls_with_protocol (0, 1);
1705 if (tls_fd != -1)
1706 close (tls_fd);
1708 if (tls6_fd != -1)
1709 close (tls6_fd);
1711 tls_fd = -1;
1712 tls6_fd = -1;
1713 return 0;
1716 static int
1717 start_stop_tls (int term)
1719 char *s = config_get_string ("global", "tcp_bind");
1720 int b;
1722 if (!s)
1723 return 0;
1725 if (!strcmp (s, "any"))
1727 b = start_stop_tls_with_protocol (0, term);
1728 if (b)
1729 b = start_stop_tls_with_protocol (1, term);
1731 else if (!strcmp (s, "ipv4"))
1732 b = start_stop_tls_with_protocol (0, term);
1733 else if (!strcmp (s, "ipv6"))
1734 b = start_stop_tls_with_protocol (1, term);
1735 else
1736 b = 0;
1738 xfree (s);
1739 return b;
1741 #endif
1743 static void *
1744 accept_thread (void *arg)
1746 int sockfd = *(int *) arg;
1747 #ifndef HAVE_PTHREAD_CANCEL
1748 int *n = xmalloc (sizeof (int));
1750 *n = 0;
1751 pthread_setspecific (signal_thread_key, n);
1752 INIT_THREAD_SIGNAL;
1753 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1754 #endif
1756 #ifdef HAVE_PR_SET_NAME
1757 prctl (PR_SET_NAME, "accept");
1758 #endif
1759 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1761 for (;;)
1763 socklen_t slen = sizeof (struct sockaddr_un);
1764 struct sockaddr_un raddr;
1765 int fd;
1766 #ifndef HAVE_PTHREAD_CANCEL
1767 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1768 int *sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1770 if (*sigusr2)
1771 break;
1772 #endif
1774 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1775 if (fd == -1)
1777 if (errno == EMFILE || errno == ENFILE)
1778 log_write ("accept(): %s",
1779 pwmd_strerror (gpg_error_from_errno (errno)));
1780 else if (errno != EAGAIN)
1782 if (!quit) // probably EBADF
1783 log_write ("accept(): %s",
1784 pwmd_strerror (gpg_error_from_errno (errno)));
1786 break;
1789 #ifndef HAVE_PTHREAD_CANCEL
1790 select (0, NULL, NULL, NULL, &tv);
1791 #endif
1792 continue;
1795 (void) init_client (fd, NULL);
1798 /* Just in case accept() failed for some reason other than EBADF */
1799 quit = 1;
1800 return NULL;
1803 static void *
1804 cache_timer_thread (void *arg)
1806 #ifndef HAVE_PTHREAD_CANCEL
1807 int *n = xmalloc (sizeof (int));
1809 *n = 0;
1810 pthread_setspecific (signal_thread_key, n);
1811 INIT_THREAD_SIGNAL;
1812 #endif
1814 #ifdef HAVE_PR_SET_NAME
1815 prctl (PR_SET_NAME, "cache timer");
1816 #endif
1817 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1819 for (;;)
1821 struct timeval tv = { 1, 0 };
1822 #ifndef HAVE_PTHREAD_CANCEL
1823 int *n;
1825 n = (int *) pthread_getspecific (signal_thread_key);
1826 if (*n)
1827 break;
1828 #endif
1830 select (0, NULL, NULL, NULL, &tv);
1831 cache_adjust_timeout ();
1834 return NULL;
1837 static void
1838 catch_sigabrt (int sig)
1840 cache_clear (NULL);
1841 #ifndef MEM_DEBUG
1842 xpanic ();
1843 #endif
1846 static int
1847 signal_loop (sigset_t sigset)
1849 int done = 0;
1850 int siint = 0;
1854 int sig;
1856 sigwait (&sigset, &sig);
1858 if (sig != SIGQUIT)
1859 log_write (_("caught signal %i (%s)"), sig, strsignal (sig));
1861 switch (sig)
1863 case SIGHUP:
1864 pthread_cond_signal (&rcfile_cond);
1865 break;
1866 case SIGABRT:
1867 // not really handled here.
1868 catch_sigabrt (SIGABRT);
1869 break;
1870 case SIGUSR1:
1871 log_write (_("clearing file cache"));
1872 cache_clear (NULL);
1873 send_status_all (STATUS_CACHE, NULL);
1874 break;
1875 case SIGQUIT:
1876 done = 1;
1877 break;
1878 default:
1879 siint = 1;
1880 done = 1;
1881 break;
1884 while (!done);
1886 return siint;
1889 static void
1890 catchsig (int sig)
1892 log_write ("Caught SIGSEGV. Exiting.");
1893 #ifdef HAVE_BACKTRACE
1894 BACKTRACE (__FUNCTION__);
1895 #endif
1896 longjmp (jmp, 1);
1899 static void *
1900 waiting_for_exit (void *arg)
1902 int last = 0;
1903 #ifndef HAVE_PTHREAD_CANCEL
1904 int *n = xmalloc (sizeof (int));
1906 *n = 0;
1907 pthread_setspecific (signal_thread_key, n);
1908 INIT_THREAD_SIGNAL;
1909 #endif
1911 #ifdef HAVE_PR_SET_NAME
1912 prctl (PR_SET_NAME, "exiting");
1913 #endif
1914 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1915 log_write (_("waiting for all clients to disconnect"));
1916 MUTEX_LOCK (&quit_mutex);
1917 pthread_cleanup_push (cleanup_mutex_cb, &quit_mutex);
1919 for (;;)
1921 struct timespec ts;
1922 int n;
1924 MUTEX_LOCK (&cn_mutex);
1925 n = slist_length (cn_thread_list);
1926 MUTEX_UNLOCK (&cn_mutex);
1927 if (!n)
1928 break;
1930 #ifndef HAVE_PTHREAD_CANCEL
1931 int *s = (int *) pthread_getspecific (signal_thread_key);
1932 if (*s)
1933 break;
1934 #endif
1936 if (last != n)
1938 log_write (_("%i clients remain"), n);
1939 last = n;
1942 INIT_TIMESPEC (SIG_TIMEOUT, ts);
1943 pthread_cond_timedwait (&quit_cond, &quit_mutex, &ts);
1946 kill (getpid (), SIGQUIT);
1947 pthread_cleanup_pop (1);
1948 return NULL;
1951 static int
1952 server_loop (int sockfd, char **socketpath)
1954 pthread_t accept_tid;
1955 pthread_t cache_timeout_tid;
1956 int cancel_timeout_thread = 0, cancel_accept_thread = 0;
1957 int cancel_keepalive_thread = 0;
1958 sigset_t sigset;
1959 int n;
1960 int segv = 0;
1961 gpg_error_t rc;
1963 init_commands ();
1964 sigemptyset (&sigset);
1966 /* Termination */
1967 sigaddset (&sigset, SIGTERM);
1968 sigaddset (&sigset, SIGINT);
1970 /* Clears the file cache. */
1971 sigaddset (&sigset, SIGUSR1);
1973 /* Configuration file reloading. */
1974 sigaddset (&sigset, SIGHUP);
1976 /* For exiting cleanly. */
1977 sigaddset (&sigset, SIGQUIT);
1979 #ifndef HAVE_PTHREAD_CANCEL
1981 The socket, cache and rcfile threads use this signal when
1982 pthread_cancel() is unavailable. Prevent the main thread from
1983 catching this signal from another process.
1985 sigaddset (&sigset, SIGUSR2);
1986 #endif
1988 /* Clears the cache and exits when something bad happens. */
1989 signal (SIGABRT, catch_sigabrt);
1990 sigaddset (&sigset, SIGABRT);
1991 sigprocmask (SIG_BLOCK, &sigset, NULL);
1993 #ifndef HAVE_PTHREAD_CANCEL
1994 /* Remove this signal from the watched signals in signal_loop(). */
1995 sigdelset (&sigset, SIGUSR2);
1996 #endif
1998 /* Ignored everywhere. When a client disconnects abnormally this signal
1999 * gets raised. It isn't needed though because client_thread() will check
2000 * for rcs even after the client disconnects. */
2001 signal (SIGPIPE, SIG_IGN);
2003 /* Can show a backtrace of the stack in the log. */
2004 signal (SIGSEGV, catchsig);
2006 #ifdef WITH_GNUTLS
2007 /* Needs to be done after the fork(). */
2008 if (!start_stop_tls (0))
2010 segv = 1;
2011 goto done;
2013 #endif
2015 pthread_mutex_init (&quit_mutex, NULL);
2016 pthread_cond_init (&quit_cond, NULL);
2017 log_write (_("%s started for user %s"), PACKAGE_STRING, get_username ());
2019 #ifdef WITH_GNUTLS
2020 if (config_get_boolean ("global", "enable_tcp"))
2021 log_write (_("Listening on %s and TCP port %i"), *socketpath,
2022 config_get_integer ("global", "tcp_port"));
2023 else
2024 log_write (_("Listening on %s"), *socketpath);
2025 #else
2026 log_write (_("Listening on %s"), *socketpath);
2027 #endif
2029 rc = create_thread (keepalive_thread, NULL, &keepalive_tid, 0);
2030 if (rc)
2032 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2033 pwmd_strerror (rc));
2034 goto done;
2037 cancel_keepalive_thread = 1;
2038 rc = create_thread (reload_rcfile_thread, NULL, &rcfile_tid, 0);
2039 if (rc)
2041 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2042 pwmd_strerror (rc));
2043 goto done;
2046 rc = create_thread (cache_timer_thread, NULL, &cache_timeout_tid, 0);
2047 if (rc)
2049 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2050 pwmd_strerror (rc));
2051 goto done;
2054 cancel_timeout_thread = 1;
2055 rc = create_thread (accept_thread, &sockfd, &accept_tid, 0);
2056 if (rc)
2058 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2059 pwmd_strerror (rc));
2060 goto done;
2063 cancel_accept_thread = 1;
2064 if (!setjmp (jmp))
2065 signal_loop (sigset);
2066 else
2067 segv = 1;
2069 done:
2071 * We're out of the main server loop. This happens when a signal was sent
2072 * to terminate the daemon. We'll wait for all clients to disconnect
2073 * before exiting but exit immediately if another termination signal is
2074 * sent.
2076 if (cancel_accept_thread)
2078 #ifdef HAVE_PTHREAD_CANCEL
2079 int n = pthread_cancel (accept_tid);
2080 #else
2081 int n = pthread_kill (accept_tid, SIGUSR2);
2082 #endif
2083 if (!n)
2084 pthread_join (accept_tid, NULL);
2087 #ifdef WITH_GNUTLS
2088 start_stop_tls (1);
2089 #endif
2090 shutdown (sockfd, SHUT_RDWR);
2091 close (sockfd);
2092 unlink (*socketpath);
2093 xfree (*socketpath);
2094 *socketpath = NULL;
2095 MUTEX_LOCK (&cn_mutex);
2096 n = slist_length (cn_thread_list);
2097 MUTEX_UNLOCK (&cn_mutex);
2099 if (n && !segv)
2101 pthread_t tid;
2103 rc = create_thread (waiting_for_exit, NULL, &tid, 0);
2104 if (!rc)
2106 if (signal_loop (sigset))
2108 log_write (_("Received second termination request. Exiting."));
2109 #ifdef HAVE_PTHREAD_CANCEL
2110 pthread_cancel (tid);
2111 #else
2112 pthread_kill (tid, SIGUSR2);
2113 #endif
2114 pthread_join (tid, NULL);
2117 else
2118 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2119 pwmd_strerror (rc));
2122 if (cancel_timeout_thread)
2124 #ifdef HAVE_PTHREAD_CANCEL
2125 pthread_cancel (cache_timeout_tid);
2126 #else
2127 pthread_kill (cache_timeout_tid, SIGUSR2);
2128 #endif
2129 pthread_join (cache_timeout_tid, NULL);
2132 if (cancel_keepalive_thread)
2134 #ifdef HAVE_PTHREAD_CANCEL
2135 pthread_cancel (keepalive_tid);
2136 #else
2137 pthread_kill (keepalive_tid, SIGUSR2);
2138 #endif
2139 pthread_join (keepalive_tid, NULL);
2142 cleanup_all_clients (0);
2143 #ifdef WITH_GNUTLS
2144 start_stop_tls (1);
2145 #endif
2146 deinit_commands ();
2147 pthread_cond_destroy (&quit_cond);
2148 pthread_mutex_destroy (&quit_mutex);
2149 return segv ? EXIT_FAILURE : EXIT_SUCCESS;;
2152 static void
2153 startup_failure ()
2155 log_write (_
2156 ("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
2157 cache_clear (NULL);
2160 /* This is called from cache.c:clear_once(). See
2161 * command.c:clearcache_command() for details about lock checking.
2163 static gpg_error_t
2164 free_cache_data (file_cache_t * cache)
2166 gpg_error_t rc = GPG_ERR_NO_DATA;
2167 int i, t;
2168 struct client_thread_s *found = NULL;
2169 int self = 0;
2171 if (!cache->data)
2172 return 0;
2174 cache_lock ();
2175 MUTEX_LOCK (&cn_mutex);
2176 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
2177 t = slist_length (cn_thread_list);
2179 for (i = 0; i < t; i++)
2181 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2183 if (!thd->cl)
2184 continue;
2186 if (!memcmp (thd->cl->md5file, cache->filename,
2187 sizeof (cache->filename)))
2189 if (pthread_equal (pthread_self (), thd->tid))
2191 found = thd;
2192 self = 1;
2193 continue;
2196 /* Continue trying to find a client who has the same file open and
2197 * also has a lock. */
2198 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0, -1);
2199 if (!rc)
2201 self = 0;
2202 found = thd;
2203 break;
2208 if (self && (!rc || rc == GPG_ERR_NO_DATA))
2209 rc = cache_lock_mutex (found->cl->ctx, found->cl->md5file, -1, 0, -1);
2211 if (exiting || !rc || rc == GPG_ERR_NO_DATA)
2213 free_cache_data_once (cache->data);
2214 cache->data = NULL;
2215 cache->defer_clear = 0;
2216 cache->timeout = -1;
2218 if (found)
2219 cache_unlock_mutex (found->cl->md5file, 0);
2221 rc = 0;
2224 if (rc)
2225 cache->defer_clear = 1;
2227 pthread_cleanup_pop (1);
2228 cache_unlock ();
2229 return rc;
2232 static int
2233 convert_v2_datafile (const char *filename, const char *cipher,
2234 const char *keyfile, const char *keygrip,
2235 const char *sign_keygrip, int nopass,
2236 const char *outfile, const char *keyparam,
2237 unsigned long s2k_count, uint64_t iterations)
2239 gpg_error_t rc;
2240 void *data = NULL;
2241 size_t datalen;
2242 struct crypto_s *crypto = NULL;
2243 uint16_t ver;
2244 int algo;
2245 void *key = NULL;
2246 size_t keylen = 0;
2248 if (outfile[0] == '-' && outfile[1] == 0)
2249 outfile = NULL;
2251 log_write (_("Converting version 2 data file \"%s\" ..."), filename);
2252 if (access (filename, R_OK) == -1)
2254 log_write ("%s: %s", filename,
2255 pwmd_strerror (gpg_error_from_errno (errno)));
2256 return 0;
2259 if (keyfile)
2261 log_write (_("Using passphrase file \"%s\" for decryption ..."),
2262 keyfile);
2263 if (access (keyfile, R_OK) == -1)
2265 log_write ("%s: %s", keyfile,
2266 pwmd_strerror (gpg_error_from_errno (errno)));
2267 return 0;
2271 rc = read_v2_datafile (filename, keyfile, &data, &datalen, &ver, &algo);
2272 if (rc)
2274 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2275 return 0;
2278 if (cipher)
2280 algo = cipher_string_to_gcrypt (cipher);
2281 if (algo == -1)
2283 rc = GPG_ERR_CIPHER_ALGO;
2284 goto fail;
2288 if (ver < 0x212)
2290 xmlDocPtr doc = parse_doc (data, datalen);
2292 if (!doc)
2294 rc = GPG_ERR_BAD_DATA;
2295 goto fail;
2298 rc = convert_pre_212_elements (doc);
2299 gcry_free (data);
2300 data = NULL;
2301 if (!rc)
2303 xmlDocDumpFormatMemory (doc, (xmlChar **) & data, (int *) &datalen,
2305 if (!data)
2306 rc = GPG_ERR_ENOMEM;
2309 xmlFreeDoc (doc);
2310 if (rc)
2311 goto fail;
2314 rc = init_client_crypto (&crypto);
2315 if (!rc)
2317 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
2318 crypto->save.hdr.flags = set_cipher_flag (crypto->save.hdr.flags, algo);
2319 crypto->save.s2k_count = s2k_count;
2320 crypto->save.hdr.iterations = iterations;
2322 if (!use_agent)
2324 rc = export_common (NULL, 0, crypto, data, datalen, outfile, keyfile,
2325 &key, &keylen, 0, 0, nopass);
2327 #ifdef WITH_AGENT
2328 else
2330 rc = agent_set_pinentry_options (crypto->agent);
2331 if (!rc)
2332 rc = agent_export_common (crypto, keygrip, sign_keygrip, nopass,
2333 data, datalen, outfile, keyparam,
2334 no_passphrase_file ? NULL : keyfile);
2336 #endif
2337 if (!rc)
2338 log_write (_("Output written to \"%s\"."), outfile);
2341 fail:
2342 if (ver < 0x212)
2343 xmlFree (data);
2344 else
2345 gcry_free (data);
2347 gcry_free (key);
2348 cleanup_crypto (&crypto);
2350 if (rc)
2351 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2352 return rc ? 0 : 1;
2355 static void
2356 usage (const char *pn, int status)
2358 FILE *fp = status == EXIT_FAILURE ? stderr : stdout;
2360 fprintf (fp, _("Usage: %s [OPTIONS] [file1] [...]\n"
2361 " -f, --rcfile=filename load the specfied configuration file\n"
2362 " (~/.pwmd/config)\n"
2363 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2364 #ifdef WITH_AGENT
2365 " --use-agent enable use of gpg-agent\n"
2366 #endif
2367 " -n, --no-fork run as a foreground process\n"
2368 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2369 " --ignore ignore file errors during startup\n"
2370 " --debug-level=keywords log protocol output (see manual for details)\n"
2371 " -o, --outfile=filename output file when importing or converting\n"
2372 " -C, --convert=filename convert a version 2 data file to version 3\n"
2373 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2374 " -k, --passphrase-file=file for use when importing or converting\n"
2375 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2376 " converting\n"
2377 " --no-passphrase when importing or converting\n"
2378 " --keygrip=hex public key to use when encrypting\n"
2379 " --sign-keygrip=hex private key to use when signing\n"
2380 " --keyparam=s-exp custom key parameters to use (RSA-2048)\n"
2381 " --cipher=string encryption cipher (aes256)\n"
2382 " --iterations=N cipher iteration count (N+1)\n"
2383 " --s2k-count=N hash iteration count (>65536, calibrated)\n"
2384 " --help this help text\n"
2385 " --version show version and compile time features\n"),
2386 pn);
2387 exit (status);
2391 main (int argc, char *argv[])
2393 int opt;
2394 struct sockaddr_un addr;
2395 char buf[PATH_MAX];
2396 char *socketpath = NULL, *socketdir, *socketname = NULL;
2397 char *socketarg = NULL;
2398 char *datadir = NULL;
2399 int x;
2400 char *p;
2401 char **cache_push = NULL;
2402 char *import = NULL, *keygrip = NULL, *sign_keygrip = NULL;
2403 char *keyparam = NULL;
2404 int estatus = EXIT_FAILURE;
2405 int sockfd;
2406 char *outfile = NULL;
2407 int do_unlink = 0;
2408 int secure = 0;
2409 int show_version = 0;
2410 int force = 0;
2411 int no_passphrase = 0;
2412 gpg_error_t rc;
2413 char *convertfile = NULL;
2414 char *cipher = NULL;
2415 char *keyfile = NULL;
2416 unsigned long s2k_count = 0;
2417 uint64_t iterations = 0;
2418 int exists;
2419 char *debug_level_opt = NULL;
2420 int optindex;
2421 /* Must maintain the same order as longopts[] */
2422 enum
2424 OPT_VERSION, OPT_HELP,
2425 #ifdef WITH_AGENT
2426 OPT_AGENT,
2427 #endif
2428 OPT_DEBUG_LEVEL, OPT_HOMEDIR, OPT_NO_FORK, OPT_DISABLE_DUMP, OPT_IGNORE,
2429 OPT_RCFILE, OPT_CONVERT, OPT_PASSPHRASE_FILE, OPT_IMPORT, OPT_OUTFILE,
2430 OPT_NO_PASSPHRASE_FILE, OPT_KEYGRIP, OPT_SIGN_KEYGRIP, OPT_KEYPARAM,
2431 OPT_CIPHER, OPT_ITERATIONS, OPT_S2K_COUNT, OPT_NO_PASSPHRASE
2433 const char *optstring = "nf:C:k:I:o:";
2434 const struct option longopts[] = {
2435 {"version", no_argument, 0, 0},
2436 {"help", no_argument, 0, 0},
2437 #ifdef WITH_AGENT
2438 {"use-agent", no_argument, 0, 0},
2439 #endif
2440 {"debug-level", required_argument, 0, 0},
2441 {"homedir", required_argument, 0, 0},
2442 {"no-fork", no_argument, 0, 'n'},
2443 {"disable_dump", no_argument, 0, 0},
2444 {"ignore", no_argument, 0, 0},
2445 {"rcfile", required_argument, 0, 'f'},
2446 {"convert", required_argument, 0, 'C'},
2447 {"passphrase-file", required_argument, 0, 'k'},
2448 {"import", required_argument, 0, 'I'},
2449 {"outfile", required_argument, 0, 'o'},
2450 {"no-passphrase-file", no_argument, 0, 0},
2451 {"keygrip", required_argument, 0, 0},
2452 {"sign-keygrip", required_argument, 0, 0},
2453 {"keyparam", required_argument, 0, 0},
2454 {"cipher", required_argument, 0, 0},
2455 {"cipher-iterations", required_argument, 0, 0},
2456 {"s2k-count", required_argument, 0, 0},
2457 {"no-passphrase", no_argument, 0, 0},
2458 {0, 0, 0, 0}
2461 #ifndef DEBUG
2462 #ifdef HAVE_SETRLIMIT
2463 struct rlimit rl;
2465 rl.rlim_cur = rl.rlim_max = 0;
2467 if (setrlimit (RLIMIT_CORE, &rl) != 0)
2468 err (EXIT_FAILURE, "setrlimit()");
2469 #endif
2470 #endif
2472 #ifdef ENABLE_NLS
2473 setlocale (LC_ALL, "");
2474 bindtextdomain ("pwmd", LOCALEDIR);
2475 textdomain ("pwmd");
2476 #endif
2478 #ifndef MEM_DEBUG
2479 xmem_init ();
2480 #endif
2481 gpg_err_init ();
2483 if (setup_crypto ())
2484 exit (EXIT_FAILURE);
2486 #ifdef WITH_GNUTLS
2487 gnutls_global_set_mem_functions (xmalloc, xmalloc, secure_mem_check,
2488 xrealloc, xfree);
2489 gnutls_global_init ();
2490 gnutls_global_set_log_function (tls_log);
2491 gnutls_global_set_log_level (1);
2492 tls_fd = -1;
2493 tls6_fd = -1;
2494 #endif
2495 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
2496 xmlInitMemory ();
2497 xmlInitGlobals ();
2498 xmlInitParser ();
2499 xmlXPathInit ();
2500 cmdline = 1;
2501 use_agent = 0;
2503 while ((opt = getopt_long (argc, argv, optstring, longopts, &optindex))
2504 != -1)
2506 switch (opt)
2508 case 'I':
2509 import = optarg;
2510 break;
2511 case 'C':
2512 convertfile = optarg;
2513 break;
2514 case 'k':
2515 keyfile = optarg;
2516 break;
2517 case 'o':
2518 outfile = optarg;
2519 break;
2520 case 'D':
2521 secure = 1;
2522 break;
2523 case 'n':
2524 nofork = 1;
2525 break;
2526 case 'f':
2527 rcfile = str_dup (optarg);
2528 break;
2529 default:
2530 usage (argv[0], EXIT_FAILURE);
2531 break;
2532 case 0:
2533 switch (optindex)
2535 case OPT_VERSION:
2536 show_version = 1;
2537 break;
2538 case OPT_HELP:
2539 usage (argv[0], 0);
2540 break;
2541 #ifdef WITH_AGENT
2542 case OPT_AGENT:
2543 use_agent = 1;
2544 break;
2545 #endif
2546 case OPT_DEBUG_LEVEL:
2547 debug_level_opt = optarg;
2548 break;
2549 case OPT_HOMEDIR:
2550 homedir = str_dup (optarg);
2551 break;
2552 case OPT_NO_FORK:
2553 nofork = 1;
2554 break;
2555 case OPT_DISABLE_DUMP:
2556 secure = 1;
2557 break;
2558 case OPT_IGNORE:
2559 force = 1;
2560 break;
2561 case OPT_RCFILE:
2562 rcfile = str_dup (optarg);
2563 break;
2564 case OPT_CONVERT:
2565 convertfile = optarg;
2566 break;
2567 case OPT_PASSPHRASE_FILE:
2568 keyfile = optarg;
2569 break;
2570 case OPT_IMPORT:
2571 import = optarg;
2572 break;
2573 case OPT_OUTFILE:
2574 outfile = optarg;
2575 break;
2576 case OPT_NO_PASSPHRASE_FILE:
2577 no_passphrase_file = 1;
2578 break;
2579 case OPT_KEYGRIP:
2580 keygrip = optarg;
2581 break;
2582 case OPT_SIGN_KEYGRIP:
2583 sign_keygrip = optarg;
2584 break;
2585 case OPT_KEYPARAM:
2586 keyparam = optarg;
2587 break;
2588 case OPT_CIPHER:
2589 cipher = optarg;
2590 break;
2591 case OPT_ITERATIONS:
2592 iterations = strtoull (optarg, NULL, 10);
2593 break;
2594 case OPT_S2K_COUNT:
2595 s2k_count = strtoul (optarg, NULL, 10);
2596 break;
2597 case OPT_NO_PASSPHRASE:
2598 no_passphrase = 1;
2599 break;
2600 default:
2601 usage (argv[0], 1);
2606 if (show_version)
2608 printf (_("%s\n\n"
2609 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013\n"
2610 "%s\n"
2611 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2612 "Compile time features:\n%s"), PACKAGE_STRING,
2613 PACKAGE_BUGREPORT,
2614 #ifdef PWMD_HOMEDIR
2615 "+PWMD_HOMEDIR=" PWMD_HOMEDIR "\n"
2616 #endif
2617 #ifdef WITH_AGENT
2618 "+WITH_AGENT\n"
2619 #else
2620 "-WITH_AGENT\n"
2621 #endif
2622 #ifdef WITH_QUALITY
2623 "+WITH_QUALITY\n"
2624 #else
2625 "-WITH_QUALITY\n"
2626 #endif
2627 #ifdef WITH_GNUTLS
2628 "+WITH_GNUTLS\n"
2629 #else
2630 "-WITH_GNUTLS\n"
2631 #endif
2632 #ifdef WITH_LIBACL
2633 "+WITH_LIBACL\n"
2634 #else
2635 "-WITH_LIBACL\n"
2636 #endif
2637 #ifdef DEBUG
2638 "+DEBUG\n"
2639 #else
2640 "-DEBUG\n"
2641 #endif
2642 #ifdef MEM_DEBUG
2643 "+MEM_DEBUG\n"
2644 #else
2645 "-MEM_DEBUG\n"
2646 #endif
2647 #ifdef MUTEX_DEBUG
2648 "+MUTEX_DEBUG\n"
2649 #else
2650 "-MUTEX_DEBUG\n"
2651 #endif
2653 exit (EXIT_SUCCESS);
2656 if (!homedir)
2657 #ifdef PWMD_HOMEDIR
2658 homedir = str_dup(PWMD_HOMEDIR);
2659 #else
2660 homedir = str_asprintf ("%s/.pwmd", get_home_dir ());
2661 #endif
2663 if (mkdir (homedir, 0700) == -1 && errno != EEXIST)
2664 err (EXIT_FAILURE, "%s", homedir);
2666 snprintf (buf, sizeof (buf), "%s/data", homedir);
2667 if (mkdir (buf, 0700) == -1 && errno != EEXIST)
2668 err (EXIT_FAILURE, "%s", buf);
2670 datadir = str_dup (buf);
2671 pthread_mutexattr_t attr;
2672 pthread_mutexattr_init (&attr);
2673 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
2674 pthread_mutex_init (&rcfile_mutex, &attr);
2675 pthread_cond_init (&rcfile_cond, NULL);
2676 pthread_mutex_init (&cn_mutex, &attr);
2677 pthread_mutexattr_destroy (&attr);
2678 pthread_key_create (&last_error_key, free_key);
2679 #ifndef HAVE_PTHREAD_CANCEL
2680 pthread_key_create (&signal_thread_key, free_key);
2681 #endif
2683 if (!rcfile)
2684 rcfile = str_asprintf ("%s/config", homedir);
2686 global_config = config_parse (rcfile);
2687 if (!global_config)
2688 exit (EXIT_FAILURE);
2690 #ifdef WITH_AGENT
2691 if (!use_agent)
2692 use_agent = config_get_boolean ("global", "use_agent");
2693 #endif
2695 setup_logging ();
2697 if (debug_level_opt)
2698 debug_level = str_split (debug_level_opt, ",", 0);
2700 x = config_get_int_param (global_config, "global", "priority", &exists);
2701 if (exists && x != atoi(INVALID_PRIORITY))
2703 errno = 0;
2704 if (setpriority (PRIO_PROCESS, 0, x) == -1)
2706 log_write ("setpriority(): %s",
2707 pwmd_strerror (gpg_error_from_errno (errno)));
2708 goto do_exit;
2711 #ifdef HAVE_MLOCKALL
2712 if (disable_mlock == 0 && mlockall (MCL_CURRENT | MCL_FUTURE) == -1)
2714 log_write ("mlockall(): %s",
2715 pwmd_strerror (gpg_error_from_errno (errno)));
2716 goto do_exit;
2718 #endif
2720 rc = cache_init (free_cache_data);
2721 if (rc)
2723 log_write ("pwmd: ERR %i: %s", rc,
2724 gpg_err_code (rc) == GPG_ERR_UNKNOWN_VERSION
2725 ? _("incompatible gpg-agent version: 2.1.0 or later required")
2726 : pwmd_strerror (rc));
2727 goto do_exit;
2730 if (s2k_count == 0)
2731 s2k_count = config_get_ulong (NULL, "s2k_count");
2733 if (convertfile)
2735 if (!outfile)
2736 usage (argv[0], EXIT_FAILURE);
2738 estatus = convert_v2_datafile (convertfile, cipher, keyfile, keygrip,
2739 sign_keygrip, no_passphrase, outfile,
2740 keyparam, s2k_count, iterations);
2741 config_free (global_config);
2742 xfree (rcfile);
2743 exit (!estatus);
2746 if (import)
2748 if (!outfile || !*outfile)
2749 usage (argv[0], EXIT_FAILURE);
2751 if (outfile && outfile[0] == '-' && outfile[1] == 0)
2752 outfile = NULL;
2754 estatus = xml_import (import, outfile, keygrip, sign_keygrip, keyfile,
2755 no_passphrase, cipher, keyparam, s2k_count,
2756 iterations);
2757 config_free (global_config);
2758 xfree (rcfile);
2759 exit (!estatus);
2762 p = config_get_string ("global", "socket_path");
2763 if (!p)
2764 p = str_asprintf ("%s/socket", homedir);
2766 socketarg = expand_homedir (p);
2767 xfree (p);
2769 if (!secure)
2770 disable_list_and_dump = config_get_boolean ("global",
2771 "disable_list_and_dump");
2772 else
2773 disable_list_and_dump = secure;
2775 cache_push = config_get_list ("global", "cache_push");
2777 while (optind < argc)
2779 if (strv_printf (&cache_push, "%s", argv[optind++]) == 0)
2780 errx (EXIT_FAILURE, "%s", pwmd_strerror (GPG_ERR_ENOMEM));
2783 if (strchr (socketarg, '/') == NULL)
2785 socketdir = getcwd (buf, sizeof (buf));
2786 socketname = str_dup (socketarg);
2787 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2789 else
2791 socketname = str_dup (strrchr (socketarg, '/'));
2792 socketname++;
2793 socketarg[strlen (socketarg) - strlen (socketname) - 1] = 0;
2794 socketdir = str_dup (socketarg);
2795 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2798 if (chdir (datadir))
2800 log_write ("%s: %s", datadir,
2801 pwmd_strerror (gpg_error_from_errno (errno)));
2802 unlink (socketpath);
2803 goto do_exit;
2807 * Set the cache entry for a file. Prompts for the password.
2809 if (cache_push)
2811 struct crypto_s *crypto = NULL;
2812 gpg_error_t rc = init_client_crypto (&crypto);
2814 if (rc)
2816 estatus = EXIT_FAILURE;
2817 goto do_exit;
2820 #ifdef WITH_AGENT
2821 if (use_agent)
2823 rc = agent_set_pinentry_options (crypto->agent);
2824 if (rc)
2826 estatus = EXIT_FAILURE;
2827 goto do_exit;
2830 #endif
2832 for (opt = 0; cache_push[opt]; opt++)
2834 if (!do_cache_push (cache_push[opt], crypto) && !force)
2836 strv_free (cache_push);
2837 startup_failure ();
2838 estatus = EXIT_FAILURE;
2839 cleanup_crypto (&crypto);
2840 goto do_exit;
2843 cleanup_crypto_stage1 (crypto);
2846 #ifdef WITH_AGENT
2847 if (use_agent)
2848 (void) kill_scd (crypto->agent);
2849 #endif
2851 cleanup_crypto (&crypto);
2852 strv_free (cache_push);
2853 log_write (!nofork ? _("Done. Daemonizing...") :
2854 _("Done. Waiting for connections..."));
2857 config_clear_keys ();
2860 * bind() doesn't like the full pathname of the socket or any non alphanum
2861 * characters so change to the directory where the socket is wanted then
2862 * create it then change to datadir.
2864 if (chdir (socketdir))
2866 log_write ("%s: %s", socketdir,
2867 pwmd_strerror (gpg_error_from_errno (errno)));
2868 goto do_exit;
2871 xfree (socketdir);
2873 if ((sockfd = socket (PF_UNIX, SOCK_STREAM, 0)) == -1)
2875 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2876 goto do_exit;
2879 addr.sun_family = AF_UNIX;
2880 snprintf (addr.sun_path, sizeof (addr.sun_path), "%s", socketname);
2881 do_unlink = 1;
2882 if (bind (sockfd, (struct sockaddr *) &addr, sizeof (struct sockaddr)) ==
2885 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2887 if (errno == EADDRINUSE)
2889 do_unlink = 0;
2890 log_write (_("Either there is another pwmd running or '%s' is a \n"
2891 "stale socket. Please remove it manually."), socketpath);
2894 goto do_exit;
2898 char *t = config_get_string ("global", "socket_perms");
2899 mode_t mode;
2900 mode_t mask;
2902 if (t)
2904 mode = strtol (t, NULL, 8);
2905 mask = umask (0);
2906 xfree (t);
2908 if (chmod (socketname, mode) == -1)
2910 log_write ("%s: %s", socketname,
2911 pwmd_strerror (gpg_error_from_errno (errno)));
2912 close (sockfd);
2913 umask (mask);
2914 goto do_exit;
2917 umask (mask);
2921 xfree (--socketname);
2923 if (chdir (datadir))
2925 log_write ("%s: %s", datadir,
2926 pwmd_strerror (gpg_error_from_errno (errno)));
2927 close (sockfd);
2928 goto do_exit;
2931 xfree (datadir);
2933 if (listen (sockfd, 0) == -1)
2935 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2936 goto do_exit;
2939 cmdline = 0;
2941 if (!nofork)
2943 switch (fork ())
2945 case -1:
2946 log_write ("fork(): %s",
2947 pwmd_strerror (gpg_error_from_errno (errno)));
2948 goto do_exit;
2949 case 0:
2950 close (0);
2951 close (1);
2952 close (2);
2953 setsid ();
2954 break;
2955 default:
2956 _exit (EXIT_SUCCESS);
2960 pthread_key_create (&thread_name_key, free_key);
2961 pthread_setspecific (thread_name_key, str_dup ("main"));
2962 estatus = server_loop (sockfd, &socketpath);
2964 do_exit:
2965 if (socketpath && do_unlink)
2967 unlink (socketpath);
2968 xfree (socketpath);
2971 xfree (socketarg);
2972 #ifdef WITH_GNUTLS
2973 gnutls_global_deinit ();
2974 #endif
2975 if (rcfile_tid)
2977 #ifdef HAVE_PTHREAD_CANCEL
2978 pthread_cancel (rcfile_tid);
2979 #else
2980 pthread_kill (rcfile_tid, SIGUSR2);
2981 pthread_cond_signal (&rcfile_cond);
2982 #endif
2983 pthread_join (rcfile_tid, NULL);
2986 pthread_cond_destroy (&rcfile_cond);
2987 pthread_mutex_destroy (&rcfile_mutex);
2988 pthread_key_delete (last_error_key);
2989 #ifndef HAVE_PTHREAD_CANCEL
2990 pthread_key_delete (signal_thread_key);
2991 #endif
2993 if (global_config)
2994 config_free (global_config);
2996 xfree (rcfile);
2997 xfree (home_directory);
2998 xfree (homedir);
2999 xmlCleanupParser ();
3000 xmlCleanupGlobals ();
3002 if (estatus == EXIT_SUCCESS)
3003 log_write (_("pwmd exiting normally"));
3005 pthread_key_delete (thread_name_key);
3006 closelog ();
3007 #if defined(DEBUG) && !defined(MEM_DEBUG)
3008 xdump ();
3009 #endif
3010 exit (estatus);