Add command line option --force to behave like --ignore.
[pwmd.git] / src / pwmd.c
blob1056a16f16a292d7603702d61ce00572774e1fdf
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 && client->xml_error)
364 log_write ("%s", client->xml_error->message);
365 xfree (client->last_error);
366 client->last_error = NULL;
367 if (client->xml_error->message)
368 client->last_error = str_dup (client->xml_error->message);
370 e = assuan_process_done (ctx,
371 assuan_set_error (ctx, e,
372 client->xml_error->message ? client->xml_error->message : NULL));
373 xmlResetLastError ();
374 xmlResetError (client->xml_error);
375 xfree (client->xml_error);
376 client->xml_error = NULL;
377 return e;
380 return assuan_process_done (ctx,
381 assuan_set_error (ctx, e, pwmd_strerror (e)));
385 assuan_log_cb (assuan_context_t ctx, void *data, unsigned cat,
386 const char *msg)
388 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
389 int i, t;
390 int match = 0;
392 pthread_mutex_lock (&m);
393 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock, &m);
394 t = strv_length (debug_level);
396 for (i = 0; i < t; i++)
398 if (!strcasecmp (debug_level[i], (char *) "init")
399 && cat == ASSUAN_LOG_INIT)
401 match = 1;
402 break;
405 if (!strcasecmp (debug_level[i], (char *) "ctx")
406 && cat == ASSUAN_LOG_CTX)
408 match = 1;
409 break;
412 if (!strcasecmp (debug_level[i], (char *) "engine")
413 && cat == ASSUAN_LOG_ENGINE)
415 match = 1;
416 break;
419 if (!strcasecmp (debug_level[i], (char *) "data")
420 && cat == ASSUAN_LOG_DATA)
422 match = 1;
423 break;
426 if (!strcasecmp (debug_level[i], (char *) "sysio")
427 && cat == ASSUAN_LOG_SYSIO)
429 match = 1;
430 break;
433 if (!strcasecmp (debug_level[i], (char *) "control")
434 && cat == ASSUAN_LOG_CONTROL)
436 match = 1;
437 break;
441 if (match && msg)
443 if (logfile)
445 int fd;
447 if ((fd =
448 open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600)) == -1)
449 warn ("%s", logfile);
450 else
452 pthread_cleanup_push (cleanup_fd_cb, &fd);
453 write (fd, msg, strlen (msg));
454 pthread_cleanup_pop (1);
458 if (nofork)
460 fprintf (stderr, "%s%s", data ? (char *) data : "", msg);
461 fflush (stderr);
465 pthread_cleanup_pop (1);
466 return match;
469 void
470 log_write (const char *fmt, ...)
472 char *args, *line;
473 va_list ap;
474 struct tm *tm;
475 time_t now;
476 char tbuf[21];
477 int fd = -1;
478 char *name = NULL;
479 char buf[255];
480 pthread_t tid = pthread_self ();
481 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
483 if ((!logfile && !isatty (STDERR_FILENO) && !log_syslog) || !fmt)
484 return;
486 pthread_mutex_lock (&m);
487 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock, &m);
488 pthread_cleanup_push (cleanup_fd_cb, &fd);
490 if (!cmdline && logfile)
492 if ((fd = open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600)) == -1)
493 warn ("%s", logfile);
496 va_start (ap, fmt);
498 if (str_vasprintf (&args, fmt, ap) != -1)
500 if (cmdline)
502 pthread_cleanup_push (xfree, args);
503 fprintf (stderr, "pwmd: %s\n", args);
504 fflush (stderr);
505 pthread_cleanup_pop (1);
507 else
509 pthread_cleanup_push (xfree, args);
510 name = pthread_getspecific (thread_name_key);
511 snprintf (buf, sizeof (buf), "%s(%p): ", name ? name : _("unknown"),
512 (pthread_t *) tid);
513 name = buf;
515 if (!cmdline && log_syslog && !nofork)
516 syslog (LOG_INFO, "%s%s", name, args);
518 time (&now);
519 tm = localtime (&now);
520 strftime (tbuf, sizeof (tbuf), "%b %d %Y %H:%M:%S ", tm);
521 tbuf[sizeof (tbuf) - 1] = 0;
523 if (args[strlen (args) - 1] == '\n')
524 args[strlen (args) - 1] = 0;
526 line = str_asprintf ("%s %i %s%s\n", tbuf, getpid (), name, args);
527 pthread_cleanup_pop (1);
528 if (line)
530 pthread_cleanup_push (xfree, line);
531 if (logfile && fd != -1)
533 write (fd, line, strlen (line));
534 fsync (fd);
537 if (nofork)
539 fprintf (stdout, "%s", line);
540 fflush (stdout);
543 pthread_cleanup_pop (1);
548 va_end (ap);
549 pthread_cleanup_pop (1);
550 pthread_cleanup_pop (0);
551 pthread_mutex_unlock (&m);
554 #ifdef WITH_GNUTLS
555 static int
556 secure_mem_check (const void *arg)
558 return 1;
560 #endif
562 static gpg_error_t
563 setup_crypto ()
565 gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
567 if (!gcry_check_version (GCRYPT_VERSION))
569 fprintf (stderr, _("gcry_check_version(): Incompatible libgcrypt. "
570 "Wanted %s, got %s.\n"), GCRYPT_VERSION,
571 gcry_check_version (NULL));
572 return GPG_ERR_UNKNOWN_VERSION;
575 gcry_set_allocation_handler (xmalloc, xmalloc, NULL, xrealloc, xfree);
576 return 0;
579 #ifdef HAVE_GETGRNAM_R
580 gpg_error_t
581 do_validate_peer (assuan_context_t ctx, const char *section,
582 assuan_peercred_t * peer)
584 char **users;
585 int allowed = 0;
586 gpg_error_t rc;
587 #ifdef WITH_GNUTLS
588 struct client_s *client = assuan_get_pointer (ctx);
590 if (client && client->thd->remote)
591 return tls_validate_access (client, section);
592 #endif
594 rc = assuan_get_peercred (ctx, peer);
595 if (rc)
596 return rc;
598 users = config_get_list (section, "allowed");
599 if (users)
601 for (char **p = users; *p; p++)
603 struct passwd pw, *result;
604 struct group gr, *gresult;
605 char *buf = NULL;
606 char *user = *p;
607 int deny = (*user == '-') ? 1 : 0;
609 if (deny)
610 user++;
612 if (*user == '@') // all users in group
614 size_t len = sysconf (_SC_GETGR_R_SIZE_MAX);
616 if (len == -1)
617 len = 16384;
619 buf = xmalloc (len);
620 if (!buf)
622 strv_free (users);
623 return GPG_ERR_ENOMEM;
626 user++;
627 if (!getgrnam_r (user, &gr, buf, len, &gresult) && gresult)
629 if (gresult->gr_gid == (*peer)->gid)
631 xfree (buf);
632 allowed = !deny;
633 continue;
636 len = sysconf (_SC_GETPW_R_SIZE_MAX);
637 if (len == -1)
638 len = 16384;
640 char *tbuf = xmalloc (len);
641 for (char **t = gresult->gr_mem; *t; t++)
643 if (!getpwnam_r (*t, &pw, tbuf, len, &result) && result)
645 if (result->pw_uid == (*peer)->uid)
647 allowed = !deny;
648 break;
654 else
656 size_t len = sysconf (_SC_GETPW_R_SIZE_MAX);
658 if (len == -1)
659 len = 16384;
661 buf = xmalloc (len);
663 if (!buf)
665 strv_free (users);
666 return GPG_ERR_ENOMEM;
669 if (!getpwnam_r (user, &pw, buf, len, &result) && result)
671 if (result->pw_uid == (*peer)->uid)
672 allowed = !deny;
676 xfree (buf);
679 strv_free (users);
682 return allowed ? 0 : GPG_ERR_INV_USER_ID;
684 #else
685 gpg_error_t
686 do_validate_peer (assuan_context_t ctx, const char *section,
687 assuan_peercred_t * peer)
689 char **users;
690 int allowed = 0;
691 gpg_error_t rc;
692 #ifdef WITH_GNUTLS
693 struct client_s *client = assuan_get_pointer (ctx);
695 if (client && client->thd->remote)
696 return tls_validate_access (client, section);
697 #endif
699 rc = assuan_get_peercred (ctx, peer);
700 if (rc)
701 return rc;
703 users = config_get_list (section, "allowed");
704 if (users)
706 for (char **p = users; *p; p++)
708 struct passwd *result;
709 struct group *gresult;
710 char *user = *p;
711 int deny = (*user == '-') ? 1 : 0;
713 if (deny)
714 user++;
716 if (*user == '@') // all users in group
718 user++;
719 gresult = getgrnam (user);
720 if (gresult && gresult->gr_gid == (*peer)->gid)
722 allowed = !deny;
723 continue;
726 for (char **t = gresult->gr_mem; *t; t++)
728 result = getpwnam (*t);
729 if (result && result->pw_uid == (*peer)->uid)
731 allowed = !deny;
732 break;
736 else
738 result = getpwnam (user);
739 if (result && result->pw_uid == (*peer)->uid)
740 allowed = !deny;
744 strv_free (users);
747 return allowed ? 0 : GPG_ERR_INV_USER_ID;
749 #endif
751 static gpg_error_t
752 validate_peer (struct client_s *cl)
754 gpg_error_t rc;
755 assuan_peercred_t peer;
757 #ifdef WITH_GNUTLS
758 if (cl->thd->remote)
759 return tls_validate_access (cl, NULL);
760 #endif
762 rc = do_validate_peer (cl->ctx, "global", &peer);
763 if (!rc || gpg_err_code (rc) == GPG_ERR_INV_USER_ID)
764 log_write ("peer %s: uid=%i, gid=%i, pid=%i",
765 !rc ? _("accepted") : _("rejected"), peer->uid, peer->gid,
766 peer->pid);
767 else if (rc)
768 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
770 return rc;
773 static void
774 xml_error_cb (void *data, xmlErrorPtr e)
776 struct client_s *client = data;
779 * Keep the first reported error as the one to show in the error
780 * description. Reset in send_error().
782 if (client->xml_error)
783 return;
785 client->xml_error = xcalloc (1, sizeof(xmlError));
786 xmlCopyError (e, client->xml_error);
789 static pid_t
790 hook_waitpid (assuan_context_t ctx, pid_t pid, int action,
791 int *status, int options)
793 return waitpid (pid, status, options);
796 static ssize_t
797 hook_read (assuan_context_t ctx, assuan_fd_t fd, void *data, size_t len)
799 #ifdef WITH_GNUTLS
800 struct client_s *client = assuan_get_pointer (ctx);
802 if (client->thd->remote)
803 return tls_read_hook (ctx, (int) fd, data, len);
804 #endif
806 return read ((int) fd, data, len);
809 static ssize_t
810 hook_write (assuan_context_t ctx, assuan_fd_t fd,
811 const void *data, size_t len)
813 #ifdef WITH_GNUTLS
814 struct client_s *client = assuan_get_pointer (ctx);
816 if (client->thd->remote)
817 return tls_write_hook (ctx, (int) fd, data, len);
818 #endif
820 return write ((int) fd, data, len);
823 static int
824 new_connection (struct client_s *cl)
826 gpg_error_t rc;
827 static struct assuan_malloc_hooks mhooks = { xmalloc, xrealloc, xfree };
828 static struct assuan_system_hooks shooks = {
829 ASSUAN_SYSTEM_HOOKS_VERSION,
830 __assuan_usleep,
831 __assuan_pipe,
832 __assuan_close,
833 hook_read,
834 hook_write,
835 //FIXME
836 NULL, //recvmsg
837 NULL, //sendmsg both are used for FD passing
838 __assuan_spawn,
839 hook_waitpid,
840 __assuan_socketpair,
841 __assuan_socket,
842 __assuan_connect
845 #ifdef WITH_GNUTLS
846 if (cl->thd->remote)
848 char *prio = config_get_string ("global", "tls_cipher_suite");
850 cl->thd->tls = tls_init (cl->thd->fd, cl->thd->timeout, prio);
851 xfree (prio);
852 if (!cl->thd->tls)
853 return 0;
855 #endif
857 rc = assuan_new_ext (&cl->ctx, GPG_ERR_SOURCE_DEFAULT, &mhooks,
858 debug_level ? assuan_log_cb : NULL, NULL);
859 if (rc)
860 goto fail;
862 assuan_ctx_set_system_hooks (cl->ctx, &shooks);
863 rc = assuan_init_socket_server (cl->ctx, cl->thd->fd, 2);
864 if (rc)
865 goto fail;
867 assuan_set_pointer (cl->ctx, cl);
868 assuan_set_hello_line (cl->ctx, PACKAGE_STRING);
869 rc = register_commands (cl->ctx);
870 if (rc)
871 goto fail;
873 #ifdef WITH_GNUTLS
874 if (cl->thd->remote)
876 cl->thd->timeout = config_get_integer ("global", "tls_timeout");
877 fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK);
879 #endif
881 rc = assuan_accept (cl->ctx);
882 if (rc)
883 goto fail;
885 rc = validate_peer (cl);
886 /* May not be implemented on all platforms. */
887 if (rc && gpg_err_code (rc) != GPG_ERR_ASS_GENERAL)
888 goto fail;
890 rc = init_client_crypto (&cl->crypto);
891 if (rc)
892 goto fail;
894 #ifdef WITH_AGENT
895 if (use_agent)
896 cl->crypto->agent->client_ctx = cl->ctx;
897 #endif
899 cl->crypto->client_ctx = cl->ctx;
900 xmlSetStructuredErrorFunc (cl, xml_error_cb);
901 return 1;
903 fail:
904 log_write ("%s", pwmd_strerror (rc));
905 return 0;
909 * This is called after a client_thread() terminates. Set with
910 * pthread_cleanup_push().
912 static void
913 cleanup_cb (void *arg)
915 struct client_thread_s *cn = arg;
916 struct client_s *cl = cn->cl;
918 MUTEX_LOCK (&cn_mutex);
919 cn_thread_list = slist_remove (cn_thread_list, cn);
920 MUTEX_UNLOCK (&cn_mutex);
922 if (cl)
924 cleanup_client (cl);
925 if (cl->xml_error)
926 xmlResetError (cl->xml_error);
928 xfree (cl->xml_error);
930 #ifdef WITH_GNUTLS
931 if (cn->tls)
933 gnutls_deinit (cn->tls->ses);
934 xfree (cn->tls->fp);
935 xfree (cn->tls);
937 #endif
939 if (!cn->atfork && cl->ctx)
940 assuan_release (cl->ctx);
941 else if (!cn->atfork && cl->thd && cl->thd->fd != -1)
942 close (cl->thd->fd);
944 if (cl->crypto)
945 cleanup_crypto (&cl->crypto);
947 pinentry_free_opts (&cl->pinentry_opts);
948 xfree (cl);
950 else
952 if (cn->fd != -1)
953 close (cn->fd);
956 while (cn->msg_queue)
958 struct status_msg_s *msg = cn->msg_queue;
960 cn->msg_queue = msg->next;
961 xfree (msg->line);
962 xfree (msg);
965 if (!cn->atfork && cn->status_msg_pipe[0] != -1)
966 close (cn->status_msg_pipe[0]);
968 if (!cn->atfork && cn->status_msg_pipe[1] != -1)
969 close (cn->status_msg_pipe[1]);
971 pthread_mutex_destroy (&cn->status_mutex);
973 if (!cn->atfork)
975 log_write (_("exiting, fd=%i"), cn->fd);
976 send_status_all (STATUS_CLIENTS, NULL);
979 xfree (cn);
980 pthread_cond_signal (&quit_cond);
983 void
984 cleanup_all_clients (int atfork)
986 /* This function may be called from pthread_atfork() which requires
987 reinitialization. */
988 if (atfork)
990 pthread_mutexattr_t attr;
992 pthread_mutexattr_init (&attr);
993 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
994 pthread_mutex_init (&cn_mutex, &attr);
995 pthread_mutexattr_destroy (&attr);
996 cache_mutex_init ();
999 MUTEX_LOCK (&cn_mutex);
1001 while (slist_length (cn_thread_list))
1003 struct client_thread_s *thd = slist_nth_data (cn_thread_list, 0);
1005 thd->atfork = atfork;
1006 cleanup_cb (thd);
1009 exiting = 1;
1010 MUTEX_UNLOCK (&cn_mutex);
1011 cache_deinit (atfork);
1014 static gpg_error_t
1015 send_msg_queue (struct client_thread_s *thd)
1017 MUTEX_LOCK (&thd->status_mutex);
1018 gpg_error_t rc = 0;
1019 char c;
1021 read (thd->status_msg_pipe[0], &c, 1);
1023 while (thd->msg_queue)
1025 struct status_msg_s *msg = thd->msg_queue;
1027 thd->msg_queue = thd->msg_queue->next;
1028 MUTEX_UNLOCK (&thd->status_mutex);
1029 rc = send_status (thd->cl->ctx, msg->s, msg->line);
1030 MUTEX_LOCK (&thd->status_mutex);
1031 xfree (msg->line);
1032 xfree (msg);
1034 if (rc)
1035 break;
1038 MUTEX_UNLOCK (&thd->status_mutex);
1039 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1040 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
1042 return rc;
1045 static void *
1046 client_thread (void *data)
1048 struct client_thread_s *thd = data;
1049 struct client_s *cl = xcalloc (1, sizeof (struct client_s));
1051 #ifdef HAVE_PR_SET_NAME
1052 prctl (PR_SET_NAME, "client");
1053 #endif
1054 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1056 if (!cl)
1058 log_write ("%s(%i): %s", __FILE__, __LINE__,
1059 pwmd_strerror (GPG_ERR_ENOMEM));
1060 return NULL;
1063 MUTEX_LOCK (&cn_mutex);
1064 pthread_cleanup_push (cleanup_cb, thd);
1065 thd->cl = cl;
1066 cl->thd = thd;
1067 MUTEX_UNLOCK (&cn_mutex);
1069 if (new_connection (cl))
1071 int finished = 0;
1072 gpg_error_t rc;
1074 send_status_all (STATUS_CLIENTS, NULL);
1075 rc = send_status (cl->ctx, STATUS_CACHE, NULL);
1076 if (rc)
1078 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
1079 finished = 1;
1082 while (!finished)
1084 fd_set rfds;
1085 int n;
1086 int eof;
1088 FD_ZERO (&rfds);
1089 FD_SET (thd->fd, &rfds);
1090 FD_SET (thd->status_msg_pipe[0], &rfds);
1091 n = thd->fd > thd->status_msg_pipe[0]
1092 ? thd->fd : thd->status_msg_pipe[0];
1094 n = select (n + 1, &rfds, NULL, NULL, NULL);
1095 if (n == -1)
1097 log_write ("%s", strerror (errno));
1098 break;
1101 if (FD_ISSET (thd->status_msg_pipe[0], &rfds))
1103 rc = send_msg_queue (thd);
1104 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1105 break;
1108 if (!FD_ISSET (thd->fd, &rfds))
1109 continue;
1111 rc = assuan_process_next (cl->ctx, &eof);
1112 if (rc || eof)
1114 if (gpg_err_code (rc) == GPG_ERR_EOF || eof)
1115 break;
1117 log_write ("assuan_process_next(): rc=%i %s", rc,
1118 pwmd_strerror (rc));
1119 if (rc == gpg_error (GPG_ERR_ETIMEDOUT))
1120 break;
1122 rc = send_error (cl->ctx, rc);
1123 if (rc)
1125 log_write ("assuan_process_done(): rc=%i %s", rc,
1126 pwmd_strerror (rc));
1127 break;
1131 /* Since the msg queue pipe fd's are non-blocking, check for
1132 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1133 * client has already disconnected and will be converted to
1134 * GPG_ERR_EOF during assuan_process_next().
1136 rc = send_msg_queue (thd);
1137 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1138 break;
1142 pthread_cleanup_pop (1);
1143 return NULL;
1146 static int
1147 xml_import (const char *filename, const char *outfile,
1148 const char *keygrip, const char *sign_keygrip,
1149 const char *keyfile, int no_passphrase, const char *cipher,
1150 const char *params, unsigned long s2k_count, uint64_t iterations)
1152 xmlDocPtr doc;
1153 int fd;
1154 struct stat st;
1155 int len;
1156 xmlChar *xmlbuf;
1157 xmlChar *xml;
1158 gpg_error_t rc;
1159 struct crypto_s *crypto = NULL;
1160 void *key = NULL;
1161 size_t keylen = 0;
1162 int algo = cipher ? cipher_string_to_gcrypt ((char *) cipher) :
1163 GCRY_CIPHER_AES256;
1165 if (algo == -1)
1167 log_write ("ERR %i: %s", gpg_error (GPG_ERR_CIPHER_ALGO),
1168 pwmd_strerror (GPG_ERR_CIPHER_ALGO));
1169 return 0;
1172 if (stat (filename, &st) == -1)
1174 log_write ("%s: %s", filename,
1175 pwmd_strerror (gpg_error_from_errno (errno)));
1176 return 0;
1179 rc = init_client_crypto (&crypto);
1180 if (rc)
1181 return 0;
1183 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
1184 crypto->save.hdr.flags = set_cipher_flag (crypto->save.hdr.flags, algo);
1185 log_write (_("Importing XML from '%s'. Output will be written to '%s' ..."),
1186 filename, outfile);
1188 if ((fd = open (filename, O_RDONLY)) == -1)
1190 log_write ("%s: %s", filename,
1191 pwmd_strerror (gpg_error_from_errno (errno)));
1192 goto fail;
1195 if ((xmlbuf = xmalloc (st.st_size + 1)) == NULL)
1197 close (fd);
1198 log_write ("%s(%i): %s", __FILE__, __LINE__,
1199 pwmd_strerror (GPG_ERR_ENOMEM));
1200 goto fail;
1203 if (read (fd, xmlbuf, st.st_size) == -1)
1205 rc = gpg_error_from_errno (errno);
1206 close (fd);
1207 log_write ("%s: %s", filename, pwmd_strerror (rc));
1208 goto fail;
1211 close (fd);
1212 xmlbuf[st.st_size] = 0;
1214 * Make sure the document validates.
1216 if ((doc = xmlReadDoc (xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS)) == NULL)
1218 log_write ("xmlReadDoc() failed");
1219 xfree (xmlbuf);
1220 goto fail;
1223 xfree (xmlbuf);
1224 xmlNodePtr n = xmlDocGetRootElement (doc);
1225 if (n && !xmlStrEqual (n->name, (xmlChar *) "pwmd"))
1227 log_write (_("Could not find root \"pwmd\" element."));
1228 rc = GPG_ERR_BAD_DATA;
1231 if (!rc)
1232 rc = validate_import (n ? n->children : n);
1234 if (rc)
1236 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1237 xmlFreeDoc (doc);
1238 goto fail;
1241 xmlDocDumpMemory (doc, &xml, &len);
1242 xmlFreeDoc (doc);
1243 crypto->save.s2k_count = s2k_count;
1244 crypto->save.hdr.iterations = iterations;
1245 if (!use_agent)
1247 rc = export_common (NULL, 0, crypto, xml, len, outfile, keyfile, &key,
1248 &keylen, 0, 0, no_passphrase);
1249 if (!rc)
1250 log_write (_("Success!"));
1252 #ifdef WITH_AGENT
1253 else
1255 rc = agent_set_pinentry_options (crypto->agent);
1256 if (!rc)
1257 rc = agent_export_common (crypto, keygrip, sign_keygrip, no_passphrase,
1258 xml, len, outfile, params, keyfile);
1260 #endif
1262 gcry_free (key);
1263 xmlFree (xml);
1264 if (rc)
1266 send_error (NULL, rc);
1267 goto fail;
1270 cleanup_crypto (&crypto);
1271 return 1;
1273 fail:
1274 cleanup_crypto (&crypto);
1275 return 0;
1278 static int
1279 do_cache_push (const char *filename, struct crypto_s *crypto)
1281 unsigned char md5file[16];
1282 gpg_error_t rc;
1283 char *key = NULL;
1284 size_t keylen = 0;
1285 xmlDocPtr doc;
1286 struct cache_data_s *cdata;
1287 unsigned char *crc;
1288 size_t len;
1290 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1291 filename);
1293 if (valid_filename (filename) == 0)
1295 log_write (_("%s: Invalid characters in filename"), filename);
1296 return 0;
1299 rc = decrypt_common (NULL, 0, crypto, filename, &key, &keylen);
1300 if (rc)
1301 return 0;
1303 rc = parse_doc ((char *) crypto->plaintext, crypto->plaintext_len, &doc);
1304 if (rc)
1306 log_write ("%s", pwmd_strerror (rc));
1307 xfree (key);
1308 return 0;
1311 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
1312 cdata = xcalloc (1, sizeof (struct cache_data_s));
1313 if (!cdata)
1315 xmlFreeDoc (doc);
1316 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM));
1317 xfree (key);
1318 return 0;
1321 rc = get_checksum (filename, &crc, &len);
1322 if (rc)
1324 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1325 xmlFreeDoc (doc);
1326 free_cache_data_once (cdata);
1327 xfree (key);
1328 return 0;
1331 cdata->crc = crc;
1332 rc = encrypt_xml (NULL, cache_key, cache_keysize, GCRY_CIPHER_AES,
1333 crypto->plaintext, crypto->plaintext_len, &cdata->doc,
1334 &cdata->doclen, &cache_iv, &cache_blocksize, 0);
1335 if (!rc && !IS_PKI (crypto))
1337 cdata->key = key;
1338 cdata->keylen = keylen;
1340 else
1341 xfree (key);
1343 if (rc)
1345 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1346 xmlFreeDoc (doc);
1347 free_cache_data_once (cdata);
1348 return 0;
1351 #ifdef WITH_AGENT
1352 if (use_agent && IS_PKI (crypto))
1354 gcry_sexp_build ((gcry_sexp_t *) & cdata->pubkey, NULL, "%S",
1355 crypto->pkey_sexp);
1356 gcry_sexp_build ((gcry_sexp_t *) & cdata->sigkey, NULL, "%S",
1357 crypto->sigpkey_sexp);
1359 #endif
1361 int timeout = config_get_integer (filename, "cache_timeout");
1362 cache_add_file (md5file, crypto->grip, cdata, timeout);
1363 log_write (_("Successfully added '%s' to the cache."), filename);
1364 return 1;
1367 static gpg_error_t
1368 init_client (int fd, const char *addr)
1370 gpg_error_t rc = 0;
1371 struct client_thread_s *new = xcalloc (1, sizeof (struct client_thread_s));
1373 if (!new)
1375 close (fd);
1376 return GPG_ERR_ENOMEM;
1379 MUTEX_LOCK (&cn_mutex);
1380 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
1382 if (pipe (new->status_msg_pipe) == -1)
1383 rc = gpg_error_from_errno (errno);
1385 if (!rc)
1387 fcntl (new->status_msg_pipe[0], F_SETFL, O_NONBLOCK);
1388 fcntl (new->status_msg_pipe[1], F_SETFL, O_NONBLOCK);
1389 pthread_mutex_init (&new->status_mutex, NULL);
1392 if (!rc)
1394 #ifdef WITH_GNUTLS
1395 new->remote = addr ? 1 : 0;
1396 #endif
1397 new->fd = fd;
1398 rc = create_thread (client_thread, new, &new->tid, 1);
1399 if (rc)
1401 close (new->status_msg_pipe[0]);
1402 close (new->status_msg_pipe[1]);
1403 pthread_mutex_destroy (&new->status_mutex);
1407 if (!rc)
1409 struct slist_s *list = slist_append (cn_thread_list, new);
1411 if (list)
1413 cn_thread_list = list;
1414 if (addr)
1415 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1416 (pthread_t *) new->tid, fd, addr);
1417 else
1418 log_write (_("new connection: tid=%p, fd=%i"),
1419 (pthread_t *) new->tid, fd);
1421 else
1422 rc = GPG_ERR_ENOMEM;
1425 pthread_cleanup_pop (1);
1427 if (rc)
1429 xfree (new);
1430 close (fd);
1431 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1432 pwmd_strerror (rc));
1434 return rc;
1437 static void*
1438 keepalive_thread (void *arg)
1440 #ifndef HAVE_PTHREAD_CANCEL
1441 int *n = xmalloc (sizeof (int));
1443 *n = 0;
1444 pthread_setspecific (signal_thread_key, n);
1445 INIT_THREAD_SIGNAL;
1446 #endif
1448 #ifdef HAVE_PR_SET_NAME
1449 prctl (PR_SET_NAME, "keepalive");
1450 #endif
1451 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1453 for (;;)
1455 int n = config_get_integer ("global", "keepalive_interval");
1456 struct timeval tv = { n, 0 };
1457 #ifndef HAVE_PTHREAD_CANCEL
1458 int *sigusr2;
1460 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1461 if (*sigusr2)
1462 break;
1463 #endif
1465 send_status_all (STATUS_KEEPALIVE, NULL);
1466 select (0, NULL, NULL, NULL, &tv);
1469 return NULL;
1472 #ifdef WITH_GNUTLS
1473 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1474 static void *
1475 get_in_addr (struct sockaddr *sa)
1477 if (sa->sa_family == AF_INET)
1478 return &(((struct sockaddr_in *) sa)->sin_addr);
1480 return &(((struct sockaddr_in6 *) sa)->sin6_addr);
1483 static void *
1484 tcp_accept_thread (void *arg)
1486 int sockfd = *(int *) arg;
1487 #ifndef HAVE_PTHREAD_CANCEL
1488 int *n = xmalloc (sizeof (int));
1490 *n = 0;
1491 pthread_setspecific (signal_thread_key, n);
1492 INIT_THREAD_SIGNAL;
1493 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1494 #endif
1496 #ifdef HAVE_PR_SET_NAME
1497 prctl (PR_SET_NAME, "tcp_accept");
1498 #endif
1499 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1501 for (;;)
1503 struct sockaddr_storage raddr;
1504 socklen_t slen = sizeof (raddr);
1505 int fd = -1;
1506 unsigned long n;
1507 char s[INET6_ADDRSTRLEN];
1508 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1509 #ifndef HAVE_PTHREAD_CANCEL
1510 int *sigusr2;
1512 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1513 if (*sigusr2)
1514 break;
1515 #endif
1517 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1518 if (fd == -1)
1520 if (errno == EMFILE || errno == ENFILE)
1521 log_write ("accept(): %s",
1522 pwmd_strerror (gpg_error_from_errno (errno)));
1523 else if (errno != EAGAIN)
1525 if (!quit) // probably EBADF
1526 log_write ("accept(): %s", strerror (errno));
1528 break;
1531 #ifndef HAVE_PTHREAD_CANCEL
1532 select (0, NULL, NULL, NULL, &tv);
1533 #endif
1534 continue;
1537 if (quit)
1538 break;
1540 inet_ntop (raddr.ss_family, get_in_addr ((struct sockaddr *) &raddr),
1541 s, sizeof s);
1542 (void) init_client (fd, s);
1543 n = config_get_integer ("global", "tcp_wait");
1544 if (n > 0)
1546 tv.tv_sec = (n * 100000) / 100000;
1547 tv.tv_usec = (n * 100000) % 100000;
1548 select (0, NULL, NULL, NULL, &tv);
1552 return NULL;
1555 static int
1556 start_stop_tls_with_protocol (int ipv6, int term)
1558 struct addrinfo hints, *servinfo, *p;
1559 int port = config_get_integer ("global", "tcp_port");
1560 char buf[7];
1561 int n;
1562 gpg_error_t rc;
1563 int *fd = ipv6 ? &tls6_fd : &tls_fd;
1565 if (term || config_get_boolean ("global", "enable_tcp") == 0)
1567 if (tls6_fd != -1)
1569 if (spawned_tls6)
1571 #ifdef HAVE_PTHREAD_CANCEL
1572 pthread_cancel (tls6_tid);
1573 #else
1574 pthread_kill (tls6_tid, SIGUSR2);
1575 #endif
1576 pthread_join (tls6_tid, NULL);
1579 shutdown (tls6_fd, SHUT_RDWR);
1580 close (tls6_fd);
1581 tls6_fd = -1;
1582 spawned_tls6 = 0;
1585 if (tls_fd != -1)
1587 if (spawned_tls)
1589 #ifdef HAVE_PTHREAD_CANCEL
1590 pthread_cancel (tls_tid);
1591 #else
1592 pthread_kill (tls_tid, SIGUSR2);
1593 #endif
1594 pthread_join (tls_tid, NULL);
1597 shutdown (tls_fd, SHUT_RDWR);
1598 close (tls_fd);
1599 tls_fd = -1;
1600 spawned_tls = 0;
1603 /* A client may still be connected. */
1604 if (!quit && x509_cred != NULL)
1605 tls_deinit_params ();
1607 return 1;
1610 if ((ipv6 && tls6_fd != -1) || (!ipv6 && tls_fd != -1))
1611 return 1;
1613 memset (&hints, 0, sizeof (hints));
1614 hints.ai_family = ipv6 ? AF_INET6 : AF_INET;
1615 hints.ai_socktype = SOCK_STREAM;
1616 hints.ai_flags = AI_PASSIVE;
1617 snprintf (buf, sizeof (buf), "%i", port);
1619 if ((n = getaddrinfo (NULL, buf, &hints, &servinfo)) == -1)
1621 log_write ("getaddrinfo(): %s", gai_strerror (n));
1622 return 0;
1625 for (n = 0, p = servinfo; p != NULL; p = p->ai_next)
1627 int r = 1;
1629 if ((ipv6 && p->ai_family != AF_INET6)
1630 || (!ipv6 && p->ai_family != AF_INET))
1631 continue;
1633 if ((*fd = socket (p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
1635 log_write ("socket(): %s", strerror (errno));
1636 continue;
1639 if (setsockopt (*fd, SOL_SOCKET, SO_REUSEADDR, &r, sizeof (int)) == -1)
1641 log_write ("setsockopt(): %s",
1642 pwmd_strerror (gpg_error_from_errno (errno)));
1643 freeaddrinfo (servinfo);
1644 goto fail;
1647 if (bind (*fd, p->ai_addr, p->ai_addrlen) == -1)
1649 close (*fd);
1650 log_write ("bind(): %s",
1651 pwmd_strerror (gpg_error_from_errno (errno)));
1652 continue;
1655 n++;
1656 break;
1659 freeaddrinfo (servinfo);
1661 if (!n)
1662 goto fail;
1664 #if HAVE_DECL_SO_BINDTODEVICE != 0
1665 char *tmp = config_get_string ("global", "tcp_interface");
1666 if (tmp && setsockopt (*fd, SOL_SOCKET, SO_BINDTODEVICE, tmp,
1667 strlen (tmp)) == -1)
1669 log_write ("setsockopt(): %s",
1670 pwmd_strerror (gpg_error_from_errno (errno)));
1671 xfree (tmp);
1672 goto fail;
1675 xfree (tmp);
1676 #endif
1678 if (x509_cred == NULL)
1680 rc = tls_init_params ();
1681 if (rc)
1682 goto fail;
1685 if (listen (*fd, 0) == -1)
1687 log_write ("listen(): %s", strerror (errno));
1688 goto fail;
1691 if (ipv6)
1692 rc = create_thread (tcp_accept_thread, fd, &tls6_tid, 0);
1693 else
1694 rc = create_thread (tcp_accept_thread, fd, &tls_tid, 0);
1696 if (rc)
1698 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1699 pwmd_strerror (rc));
1700 goto fail;
1703 if (ipv6)
1704 spawned_tls6 = 1;
1705 else
1706 spawned_tls = 1;
1708 return 1;
1710 fail:
1711 start_stop_tls_with_protocol (0, 1);
1712 if (tls_fd != -1)
1713 close (tls_fd);
1715 if (tls6_fd != -1)
1716 close (tls6_fd);
1718 tls_fd = -1;
1719 tls6_fd = -1;
1720 return 0;
1723 static int
1724 start_stop_tls (int term)
1726 char *s = config_get_string ("global", "tcp_bind");
1727 int b;
1729 if (!s)
1730 return 0;
1732 if (!strcmp (s, "any"))
1734 b = start_stop_tls_with_protocol (0, term);
1735 if (b)
1736 b = start_stop_tls_with_protocol (1, term);
1738 else if (!strcmp (s, "ipv4"))
1739 b = start_stop_tls_with_protocol (0, term);
1740 else if (!strcmp (s, "ipv6"))
1741 b = start_stop_tls_with_protocol (1, term);
1742 else
1743 b = 0;
1745 xfree (s);
1746 return b;
1748 #endif
1750 static void *
1751 accept_thread (void *arg)
1753 int sockfd = *(int *) arg;
1754 #ifndef HAVE_PTHREAD_CANCEL
1755 int *n = xmalloc (sizeof (int));
1757 *n = 0;
1758 pthread_setspecific (signal_thread_key, n);
1759 INIT_THREAD_SIGNAL;
1760 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1761 #endif
1763 #ifdef HAVE_PR_SET_NAME
1764 prctl (PR_SET_NAME, "accept");
1765 #endif
1766 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1768 for (;;)
1770 socklen_t slen = sizeof (struct sockaddr_un);
1771 struct sockaddr_un raddr;
1772 int fd;
1773 #ifndef HAVE_PTHREAD_CANCEL
1774 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1775 int *sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1777 if (*sigusr2)
1778 break;
1779 #endif
1781 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1782 if (fd == -1)
1784 if (errno == EMFILE || errno == ENFILE)
1785 log_write ("accept(): %s",
1786 pwmd_strerror (gpg_error_from_errno (errno)));
1787 else if (errno != EAGAIN)
1789 if (!quit) // probably EBADF
1790 log_write ("accept(): %s",
1791 pwmd_strerror (gpg_error_from_errno (errno)));
1793 break;
1796 #ifndef HAVE_PTHREAD_CANCEL
1797 select (0, NULL, NULL, NULL, &tv);
1798 #endif
1799 continue;
1802 (void) init_client (fd, NULL);
1805 /* Just in case accept() failed for some reason other than EBADF */
1806 quit = 1;
1807 return NULL;
1810 static void *
1811 cache_timer_thread (void *arg)
1813 #ifndef HAVE_PTHREAD_CANCEL
1814 int *n = xmalloc (sizeof (int));
1816 *n = 0;
1817 pthread_setspecific (signal_thread_key, n);
1818 INIT_THREAD_SIGNAL;
1819 #endif
1821 #ifdef HAVE_PR_SET_NAME
1822 prctl (PR_SET_NAME, "cache timer");
1823 #endif
1824 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1826 for (;;)
1828 struct timeval tv = { 1, 0 };
1829 #ifndef HAVE_PTHREAD_CANCEL
1830 int *n;
1832 n = (int *) pthread_getspecific (signal_thread_key);
1833 if (*n)
1834 break;
1835 #endif
1837 select (0, NULL, NULL, NULL, &tv);
1838 cache_adjust_timeout ();
1841 return NULL;
1844 static int
1845 signal_loop (sigset_t sigset)
1847 int done = 0;
1848 int siint = 0;
1852 int sig;
1854 sigwait (&sigset, &sig);
1856 if (sig != SIGQUIT)
1857 log_write (_("caught signal %i (%s)"), sig, strsignal (sig));
1859 switch (sig)
1861 case SIGHUP:
1862 pthread_cond_signal (&rcfile_cond);
1863 break;
1864 case SIGUSR1:
1865 log_write (_("clearing file cache"));
1866 cache_clear (NULL);
1867 send_status_all (STATUS_CACHE, NULL);
1868 break;
1869 case SIGQUIT:
1870 done = 1;
1871 break;
1872 default:
1873 siint = 1;
1874 done = 1;
1875 break;
1878 while (!done);
1880 return siint;
1883 static void
1884 catchsig (int sig)
1886 log_write (_ ("Caught signal %i (%s). Exiting."), sig, strsignal (sig));
1887 #ifdef HAVE_BACKTRACE
1888 BACKTRACE (__FUNCTION__);
1889 #endif
1890 longjmp (jmp, 1);
1893 static void *
1894 waiting_for_exit (void *arg)
1896 int last = 0;
1897 #ifndef HAVE_PTHREAD_CANCEL
1898 int *n = xmalloc (sizeof (int));
1900 *n = 0;
1901 pthread_setspecific (signal_thread_key, n);
1902 INIT_THREAD_SIGNAL;
1903 #endif
1905 #ifdef HAVE_PR_SET_NAME
1906 prctl (PR_SET_NAME, "exiting");
1907 #endif
1908 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1909 log_write (_("waiting for all clients to disconnect"));
1910 MUTEX_LOCK (&quit_mutex);
1911 pthread_cleanup_push (cleanup_mutex_cb, &quit_mutex);
1913 for (;;)
1915 struct timespec ts;
1916 int n;
1918 MUTEX_LOCK (&cn_mutex);
1919 n = slist_length (cn_thread_list);
1920 MUTEX_UNLOCK (&cn_mutex);
1921 if (!n)
1922 break;
1924 #ifndef HAVE_PTHREAD_CANCEL
1925 int *s = (int *) pthread_getspecific (signal_thread_key);
1926 if (*s)
1927 break;
1928 #endif
1930 if (last != n)
1932 log_write (_("%i clients remain"), n);
1933 last = n;
1936 INIT_TIMESPEC (SIG_TIMEOUT, ts);
1937 pthread_cond_timedwait (&quit_cond, &quit_mutex, &ts);
1940 kill (getpid (), SIGQUIT);
1941 pthread_cleanup_pop (1);
1942 return NULL;
1945 static int
1946 server_loop (int sockfd, char **socketpath)
1948 pthread_t accept_tid;
1949 pthread_t cache_timeout_tid;
1950 int cancel_timeout_thread = 0, cancel_accept_thread = 0;
1951 int cancel_keepalive_thread = 0;
1952 sigset_t sigset;
1953 int n;
1954 int segv = 0;
1955 gpg_error_t rc;
1957 init_commands ();
1958 sigemptyset (&sigset);
1960 /* Termination */
1961 sigaddset (&sigset, SIGTERM);
1962 sigaddset (&sigset, SIGINT);
1964 /* Clears the file cache. */
1965 sigaddset (&sigset, SIGUSR1);
1967 /* Configuration file reloading. */
1968 sigaddset (&sigset, SIGHUP);
1970 /* For exiting cleanly. */
1971 sigaddset (&sigset, SIGQUIT);
1973 #ifndef HAVE_PTHREAD_CANCEL
1975 The socket, cache and rcfile threads use this signal when
1976 pthread_cancel() is unavailable. Prevent the main thread from
1977 catching this signal from another process.
1979 sigaddset (&sigset, SIGUSR2);
1980 #endif
1982 /* When mem.c cannot find a pointer in the list (double free). */
1983 signal (SIGABRT, catchsig);
1984 sigaddset (&sigset, SIGABRT);
1985 sigprocmask (SIG_BLOCK, &sigset, NULL);
1987 #ifndef HAVE_PTHREAD_CANCEL
1988 /* Remove this signal from the watched signals in signal_loop(). */
1989 sigdelset (&sigset, SIGUSR2);
1990 #endif
1992 /* Ignored everywhere. When a client disconnects abnormally this signal
1993 * gets raised. It isn't needed though because client_thread() will check
1994 * for rcs even after the client disconnects. */
1995 signal (SIGPIPE, SIG_IGN);
1997 /* Can show a backtrace of the stack in the log. */
1998 signal (SIGSEGV, catchsig);
2000 #ifdef WITH_GNUTLS
2001 /* Needs to be done after the fork(). */
2002 if (!start_stop_tls (0))
2004 segv = 1;
2005 goto done;
2007 #endif
2009 pthread_mutex_init (&quit_mutex, NULL);
2010 pthread_cond_init (&quit_cond, NULL);
2011 log_write (_("%s started for user %s"), PACKAGE_STRING, get_username ());
2013 #ifdef WITH_GNUTLS
2014 if (config_get_boolean ("global", "enable_tcp"))
2015 log_write (_("Listening on %s and TCP port %i"), *socketpath,
2016 config_get_integer ("global", "tcp_port"));
2017 else
2018 log_write (_("Listening on %s"), *socketpath);
2019 #else
2020 log_write (_("Listening on %s"), *socketpath);
2021 #endif
2023 rc = create_thread (keepalive_thread, NULL, &keepalive_tid, 0);
2024 if (rc)
2026 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2027 pwmd_strerror (rc));
2028 goto done;
2031 cancel_keepalive_thread = 1;
2032 rc = create_thread (reload_rcfile_thread, NULL, &rcfile_tid, 0);
2033 if (rc)
2035 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2036 pwmd_strerror (rc));
2037 goto done;
2040 rc = create_thread (cache_timer_thread, NULL, &cache_timeout_tid, 0);
2041 if (rc)
2043 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2044 pwmd_strerror (rc));
2045 goto done;
2048 cancel_timeout_thread = 1;
2049 rc = create_thread (accept_thread, &sockfd, &accept_tid, 0);
2050 if (rc)
2052 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2053 pwmd_strerror (rc));
2054 goto done;
2057 cancel_accept_thread = 1;
2058 if (!setjmp (jmp))
2059 signal_loop (sigset);
2060 else
2061 segv = 1;
2063 done:
2065 * We're out of the main server loop. This happens when a signal was sent
2066 * to terminate the daemon. We'll wait for all clients to disconnect
2067 * before exiting but exit immediately if another termination signal is
2068 * sent.
2070 if (cancel_accept_thread)
2072 #ifdef HAVE_PTHREAD_CANCEL
2073 int n = pthread_cancel (accept_tid);
2074 #else
2075 int n = pthread_kill (accept_tid, SIGUSR2);
2076 #endif
2077 if (!n)
2078 pthread_join (accept_tid, NULL);
2081 #ifdef WITH_GNUTLS
2082 start_stop_tls (1);
2083 #endif
2084 shutdown (sockfd, SHUT_RDWR);
2085 close (sockfd);
2086 unlink (*socketpath);
2087 xfree (*socketpath);
2088 *socketpath = NULL;
2089 MUTEX_LOCK (&cn_mutex);
2090 n = slist_length (cn_thread_list);
2091 MUTEX_UNLOCK (&cn_mutex);
2093 if (n && !segv)
2095 pthread_t tid;
2097 rc = create_thread (waiting_for_exit, NULL, &tid, 0);
2098 if (!rc)
2100 if (signal_loop (sigset))
2102 log_write (_("Received second termination request. Exiting."));
2103 #ifdef HAVE_PTHREAD_CANCEL
2104 pthread_cancel (tid);
2105 #else
2106 pthread_kill (tid, SIGUSR2);
2107 #endif
2108 pthread_join (tid, NULL);
2111 else
2112 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2113 pwmd_strerror (rc));
2116 if (cancel_timeout_thread)
2118 #ifdef HAVE_PTHREAD_CANCEL
2119 pthread_cancel (cache_timeout_tid);
2120 #else
2121 pthread_kill (cache_timeout_tid, SIGUSR2);
2122 #endif
2123 pthread_join (cache_timeout_tid, NULL);
2126 if (cancel_keepalive_thread)
2128 #ifdef HAVE_PTHREAD_CANCEL
2129 pthread_cancel (keepalive_tid);
2130 #else
2131 pthread_kill (keepalive_tid, SIGUSR2);
2132 #endif
2133 pthread_join (keepalive_tid, NULL);
2136 cleanup_all_clients (0);
2137 #ifdef WITH_GNUTLS
2138 start_stop_tls (1);
2139 #endif
2140 deinit_commands ();
2141 pthread_cond_destroy (&quit_cond);
2142 pthread_mutex_destroy (&quit_mutex);
2143 return segv ? EXIT_FAILURE : EXIT_SUCCESS;;
2146 static void
2147 startup_failure ()
2149 log_write (_
2150 ("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
2151 cache_clear (NULL);
2154 /* This is called from cache.c:clear_once(). See
2155 * command.c:clearcache_command() for details about lock checking.
2157 static gpg_error_t
2158 free_cache_data (file_cache_t * cache)
2160 gpg_error_t rc = GPG_ERR_NO_DATA;
2161 int i, t;
2162 struct client_thread_s *found = NULL;
2163 int self = 0;
2165 if (!cache->data)
2166 return 0;
2168 cache_lock ();
2169 MUTEX_LOCK (&cn_mutex);
2170 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
2171 t = slist_length (cn_thread_list);
2173 for (i = 0; i < t; i++)
2175 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2177 if (!thd->cl)
2178 continue;
2180 if (!memcmp (thd->cl->md5file, cache->filename,
2181 sizeof (cache->filename)))
2183 if (pthread_equal (pthread_self (), thd->tid))
2185 found = thd;
2186 self = 1;
2187 continue;
2190 /* Continue trying to find a client who has the same file open and
2191 * also has a lock. */
2192 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0, -1);
2193 if (!rc)
2195 self = 0;
2196 found = thd;
2197 break;
2202 if (self && (!rc || rc == GPG_ERR_NO_DATA))
2203 rc = cache_lock_mutex (found->cl->ctx, found->cl->md5file, -1, 0, -1);
2205 if (exiting || !rc || rc == GPG_ERR_NO_DATA)
2207 free_cache_data_once (cache->data);
2208 cache->data = NULL;
2209 cache->defer_clear = 0;
2210 cache->timeout = -1;
2212 if (found)
2213 cache_unlock_mutex (found->cl->md5file, 0);
2215 rc = 0;
2218 if (rc)
2219 cache->defer_clear = 1;
2221 pthread_cleanup_pop (1);
2222 cache_unlock ();
2223 return rc;
2226 static int
2227 convert_v2_datafile (const char *filename, const char *cipher,
2228 const char *keyfile, const char *keygrip,
2229 const char *sign_keygrip, int nopass,
2230 const char *outfile, const char *keyparam,
2231 unsigned long s2k_count, uint64_t iterations)
2233 gpg_error_t rc;
2234 void *data = NULL;
2235 size_t datalen;
2236 struct crypto_s *crypto = NULL;
2237 uint16_t ver;
2238 int algo;
2239 void *key = NULL;
2240 size_t keylen = 0;
2242 if (outfile[0] == '-' && outfile[1] == 0)
2243 outfile = NULL;
2245 log_write (_("Converting version 2 data file \"%s\" ..."), filename);
2246 if (access (filename, R_OK) == -1)
2248 log_write ("%s: %s", filename,
2249 pwmd_strerror (gpg_error_from_errno (errno)));
2250 return 0;
2253 if (keyfile)
2255 log_write (_("Using passphrase file \"%s\" for decryption ..."),
2256 keyfile);
2257 if (access (keyfile, R_OK) == -1)
2259 log_write ("%s: %s", keyfile,
2260 pwmd_strerror (gpg_error_from_errno (errno)));
2261 return 0;
2265 rc = read_v2_datafile (filename, keyfile, &data, &datalen, &ver, &algo);
2266 if (rc)
2268 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2269 return 0;
2272 if (cipher)
2274 algo = cipher_string_to_gcrypt (cipher);
2275 if (algo == -1)
2277 rc = GPG_ERR_CIPHER_ALGO;
2278 goto fail;
2282 if (ver < 0x212)
2284 xmlDocPtr doc;
2286 rc = parse_doc (data, datalen, &doc);
2287 if (rc)
2288 goto fail;
2290 rc = convert_pre_212_elements (doc);
2291 gcry_free (data);
2292 data = NULL;
2293 if (!rc)
2295 xmlDocDumpFormatMemory (doc, (xmlChar **) & data, (int *) &datalen,
2297 if (!data)
2298 rc = GPG_ERR_ENOMEM;
2301 xmlFreeDoc (doc);
2302 if (rc)
2303 goto fail;
2306 rc = init_client_crypto (&crypto);
2307 if (!rc)
2309 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
2310 crypto->save.hdr.flags = set_cipher_flag (crypto->save.hdr.flags, algo);
2311 crypto->save.s2k_count = s2k_count;
2312 crypto->save.hdr.iterations = iterations;
2314 if (!use_agent)
2316 rc = export_common (NULL, 0, crypto, data, datalen, outfile, keyfile,
2317 &key, &keylen, 0, 0, nopass);
2319 #ifdef WITH_AGENT
2320 else
2322 rc = agent_set_pinentry_options (crypto->agent);
2323 if (!rc)
2324 rc = agent_export_common (crypto, keygrip, sign_keygrip, nopass,
2325 data, datalen, outfile, keyparam,
2326 no_passphrase_file ? NULL : keyfile);
2328 #endif
2329 if (!rc)
2330 log_write (_("Output written to \"%s\"."), outfile);
2333 fail:
2334 if (ver < 0x212)
2335 xmlFree (data);
2336 else
2337 gcry_free (data);
2339 gcry_free (key);
2340 cleanup_crypto (&crypto);
2342 if (rc)
2343 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2344 return rc ? 0 : 1;
2347 static void
2348 usage (const char *pn, int status)
2350 FILE *fp = status == EXIT_FAILURE ? stderr : stdout;
2352 fprintf (fp, _("Usage: %s [OPTIONS] [file1] [...]\n"
2353 " -f, --rcfile=filename load the specfied configuration file\n"
2354 " (~/.pwmd/config)\n"
2355 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2356 #ifdef WITH_AGENT
2357 " --use-agent enable use of gpg-agent\n"
2358 #endif
2359 " -n, --no-fork run as a foreground process\n"
2360 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2361 " --ignore, --force ignore file errors during startup\n"
2362 " --debug-level=keywords log protocol output (see manual for details)\n"
2363 " -o, --outfile=filename output file when importing or converting\n"
2364 " -C, --convert=filename convert a version 2 data file to version 3\n"
2365 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2366 " -k, --passphrase-file=file for use when importing or converting\n"
2367 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2368 " converting\n"
2369 " --no-passphrase when importing or converting\n"
2370 " --keygrip=hex public key to use when encrypting\n"
2371 " --sign-keygrip=hex private key to use when signing\n"
2372 " --keyparam=s-exp custom key parameters to use (RSA-2048)\n"
2373 " --cipher=string encryption cipher (aes256)\n"
2374 " --iterations=N cipher iteration count (N+1)\n"
2375 " --s2k-count=N hash iteration count (>65536, calibrated)\n"
2376 " --help this help text\n"
2377 " --version show version and compile time features\n"),
2378 pn);
2379 exit (status);
2382 static void
2383 unlink_stale_socket (const char *sock, const char *pidfile)
2385 log_write (_ ("removing stale socket %s"), sock);
2386 unlink (sock);
2387 unlink (pidfile);
2390 static int
2391 test_pidfile (const char *path, const char *sock, char *buf, size_t buflen,
2392 char **pidfile, int create, mode_t mode)
2394 pid_t pid;
2395 int fd;
2396 size_t len;
2398 if (!create)
2400 memset (buf, 0, buflen);
2401 snprintf (buf, buflen, "%s/%s.pid", homedir, sock);
2402 *pidfile = str_dup (buf);
2403 fd = open (buf, O_RDONLY);
2405 else
2406 fd = open (*pidfile, O_CREAT|O_WRONLY|O_TRUNC, mode);
2408 if (fd == -1)
2410 if (!create && errno != ENOENT)
2412 log_write ("%s: %s", buf, pwmd_strerror (errno));
2413 free (*pidfile);
2414 *pidfile = NULL;
2415 return -1;
2417 else if (!create)
2418 return 0;
2420 log_write ("%s: %s", *pidfile, strerror (errno));
2421 return -1;
2424 if (create)
2426 snprintf (buf, buflen, "%i", getpid ());
2427 write (fd, buf, strlen (buf));
2428 close (fd);
2429 return 0;
2432 len = read (fd, buf, sizeof(buf));
2433 close (fd);
2434 if (len == 0)
2436 unlink_stale_socket (path, *pidfile);
2437 return 0;
2440 if (sscanf (buf, "%i", &pid) != 1 || pid == 0)
2442 unlink_stale_socket (path, *pidfile);
2443 return 0;
2446 if (kill (pid, 0) == -1)
2448 unlink_stale_socket (path, *pidfile);
2449 return 0;
2452 log_write (_ ("an instance for socket %s is already running"), path);
2453 xfree (*pidfile);
2454 *pidfile = NULL;
2455 return 1;
2459 main (int argc, char *argv[])
2461 int opt;
2462 struct sockaddr_un addr;
2463 char buf[PATH_MAX];
2464 char *socketpath = NULL, *socketdir, *socketname = NULL;
2465 char *socketarg = NULL;
2466 char *datadir = NULL;
2467 char *pidfile = NULL;
2468 mode_t mode = 0600;
2469 int x;
2470 char *p;
2471 char **cache_push = NULL;
2472 char *import = NULL, *keygrip = NULL, *sign_keygrip = NULL;
2473 char *keyparam = NULL;
2474 int estatus = EXIT_FAILURE;
2475 int sockfd;
2476 char *outfile = NULL;
2477 int do_unlink = 0;
2478 int secure = 0;
2479 int show_version = 0;
2480 int force = 0;
2481 int no_passphrase = 0;
2482 gpg_error_t rc;
2483 char *convertfile = NULL;
2484 char *cipher = NULL;
2485 char *keyfile = NULL;
2486 unsigned long s2k_count = 0;
2487 uint64_t iterations = 0;
2488 int exists;
2489 char *debug_level_opt = NULL;
2490 int optindex;
2491 /* Must maintain the same order as longopts[] */
2492 enum
2494 OPT_VERSION, OPT_HELP,
2495 #ifdef WITH_AGENT
2496 OPT_AGENT,
2497 #endif
2498 OPT_DEBUG_LEVEL, OPT_HOMEDIR, OPT_NO_FORK, OPT_DISABLE_DUMP,
2499 OPT_IGNORE, OPT_FORCE, OPT_RCFILE, OPT_CONVERT,
2500 OPT_PASSPHRASE_FILE, OPT_IMPORT, OPT_OUTFILE,
2501 OPT_NO_PASSPHRASE_FILE, OPT_KEYGRIP, OPT_SIGN_KEYGRIP,
2502 OPT_KEYPARAM, OPT_CIPHER, OPT_ITERATIONS, OPT_S2K_COUNT,
2503 OPT_NO_PASSPHRASE
2505 const char *optstring = "nf:C:k:I:o:";
2506 const struct option longopts[] = {
2507 {"version", no_argument, 0, 0},
2508 {"help", no_argument, 0, 0},
2509 #ifdef WITH_AGENT
2510 {"use-agent", no_argument, 0, 0},
2511 #endif
2512 {"debug-level", required_argument, 0, 0},
2513 {"homedir", required_argument, 0, 0},
2514 {"no-fork", no_argument, 0, 'n'},
2515 {"disable_dump", no_argument, 0, 0},
2516 {"ignore", no_argument, 0, 0},
2517 {"force", no_argument, 0, 0},
2518 {"rcfile", required_argument, 0, 'f'},
2519 {"convert", required_argument, 0, 'C'},
2520 {"passphrase-file", required_argument, 0, 'k'},
2521 {"import", required_argument, 0, 'I'},
2522 {"outfile", required_argument, 0, 'o'},
2523 {"no-passphrase-file", no_argument, 0, 0},
2524 {"keygrip", required_argument, 0, 0},
2525 {"sign-keygrip", required_argument, 0, 0},
2526 {"keyparam", required_argument, 0, 0},
2527 {"cipher", required_argument, 0, 0},
2528 {"cipher-iterations", required_argument, 0, 0},
2529 {"s2k-count", required_argument, 0, 0},
2530 {"no-passphrase", no_argument, 0, 0},
2531 {0, 0, 0, 0}
2534 #ifndef DEBUG
2535 #ifdef HAVE_SETRLIMIT
2536 struct rlimit rl;
2538 rl.rlim_cur = rl.rlim_max = 0;
2540 if (setrlimit (RLIMIT_CORE, &rl) != 0)
2541 err (EXIT_FAILURE, "setrlimit()");
2542 #endif
2543 #endif
2545 #ifdef ENABLE_NLS
2546 setlocale (LC_ALL, "");
2547 bindtextdomain ("pwmd", LOCALEDIR);
2548 textdomain ("pwmd");
2549 #endif
2551 #ifndef MEM_DEBUG
2552 xmem_init ();
2553 #endif
2554 gpg_err_init ();
2556 if (setup_crypto ())
2557 exit (EXIT_FAILURE);
2559 #ifdef WITH_GNUTLS
2560 gnutls_global_set_mem_functions (xmalloc, xmalloc, secure_mem_check,
2561 xrealloc, xfree);
2562 gnutls_global_init ();
2563 gnutls_global_set_log_function (tls_log);
2564 gnutls_global_set_log_level (1);
2565 tls_fd = -1;
2566 tls6_fd = -1;
2567 #endif
2568 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
2569 xmlInitMemory ();
2570 xmlInitGlobals ();
2571 xmlInitParser ();
2572 xmlXPathInit ();
2573 cmdline = 1;
2574 use_agent = 0;
2576 while ((opt = getopt_long (argc, argv, optstring, longopts, &optindex))
2577 != -1)
2579 switch (opt)
2581 case 'I':
2582 import = optarg;
2583 break;
2584 case 'C':
2585 convertfile = optarg;
2586 break;
2587 case 'k':
2588 keyfile = optarg;
2589 break;
2590 case 'o':
2591 outfile = optarg;
2592 break;
2593 case 'D':
2594 secure = 1;
2595 break;
2596 case 'n':
2597 nofork = 1;
2598 break;
2599 case 'f':
2600 rcfile = str_dup (optarg);
2601 break;
2602 default:
2603 usage (argv[0], EXIT_FAILURE);
2604 break;
2605 case 0:
2606 switch (optindex)
2608 case OPT_VERSION:
2609 show_version = 1;
2610 break;
2611 case OPT_HELP:
2612 usage (argv[0], 0);
2613 break;
2614 #ifdef WITH_AGENT
2615 case OPT_AGENT:
2616 use_agent = 1;
2617 break;
2618 #endif
2619 case OPT_DEBUG_LEVEL:
2620 debug_level_opt = optarg;
2621 break;
2622 case OPT_HOMEDIR:
2623 homedir = str_dup (optarg);
2624 break;
2625 case OPT_NO_FORK:
2626 nofork = 1;
2627 break;
2628 case OPT_DISABLE_DUMP:
2629 secure = 1;
2630 break;
2631 case OPT_IGNORE:
2632 case OPT_FORCE:
2633 force = 1;
2634 break;
2635 case OPT_RCFILE:
2636 rcfile = str_dup (optarg);
2637 break;
2638 case OPT_CONVERT:
2639 convertfile = optarg;
2640 break;
2641 case OPT_PASSPHRASE_FILE:
2642 keyfile = optarg;
2643 break;
2644 case OPT_IMPORT:
2645 import = optarg;
2646 break;
2647 case OPT_OUTFILE:
2648 outfile = optarg;
2649 break;
2650 case OPT_NO_PASSPHRASE_FILE:
2651 no_passphrase_file = 1;
2652 break;
2653 case OPT_KEYGRIP:
2654 keygrip = optarg;
2655 break;
2656 case OPT_SIGN_KEYGRIP:
2657 sign_keygrip = optarg;
2658 break;
2659 case OPT_KEYPARAM:
2660 keyparam = optarg;
2661 break;
2662 case OPT_CIPHER:
2663 cipher = optarg;
2664 break;
2665 case OPT_ITERATIONS:
2666 iterations = strtoull (optarg, NULL, 10);
2667 break;
2668 case OPT_S2K_COUNT:
2669 s2k_count = strtoul (optarg, NULL, 10);
2670 break;
2671 case OPT_NO_PASSPHRASE:
2672 no_passphrase = 1;
2673 break;
2674 default:
2675 usage (argv[0], 1);
2680 if (show_version)
2682 printf (_("%s\n\n"
2683 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013\n"
2684 "%s\n"
2685 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2686 "Compile time features:\n%s"), PACKAGE_STRING,
2687 PACKAGE_BUGREPORT,
2688 #ifdef PWMD_HOMEDIR
2689 "+PWMD_HOMEDIR=" PWMD_HOMEDIR "\n"
2690 #endif
2691 #ifdef WITH_AGENT
2692 "+WITH_AGENT\n"
2693 #else
2694 "-WITH_AGENT\n"
2695 #endif
2696 #ifdef WITH_QUALITY
2697 "+WITH_QUALITY\n"
2698 #else
2699 "-WITH_QUALITY\n"
2700 #endif
2701 #ifdef WITH_GNUTLS
2702 "+WITH_GNUTLS\n"
2703 #else
2704 "-WITH_GNUTLS\n"
2705 #endif
2706 #ifdef WITH_LIBACL
2707 "+WITH_LIBACL\n"
2708 #else
2709 "-WITH_LIBACL\n"
2710 #endif
2711 #ifdef DEBUG
2712 "+DEBUG\n"
2713 #else
2714 "-DEBUG\n"
2715 #endif
2716 #ifdef MEM_DEBUG
2717 "+MEM_DEBUG\n"
2718 #else
2719 "-MEM_DEBUG\n"
2720 #endif
2721 #ifdef MUTEX_DEBUG
2722 "+MUTEX_DEBUG\n"
2723 #else
2724 "-MUTEX_DEBUG\n"
2725 #endif
2727 exit (EXIT_SUCCESS);
2730 if (!homedir)
2731 #ifdef PWMD_HOMEDIR
2732 homedir = str_dup(PWMD_HOMEDIR);
2733 #else
2734 homedir = str_asprintf ("%s/.pwmd", get_home_dir ());
2735 #endif
2737 if (mkdir (homedir, 0700) == -1 && errno != EEXIST)
2738 err (EXIT_FAILURE, "%s", homedir);
2740 snprintf (buf, sizeof (buf), "%s/data", homedir);
2741 if (mkdir (buf, 0700) == -1 && errno != EEXIST)
2742 err (EXIT_FAILURE, "%s", buf);
2744 datadir = str_dup (buf);
2745 pthread_mutexattr_t attr;
2746 pthread_mutexattr_init (&attr);
2747 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
2748 pthread_mutex_init (&rcfile_mutex, &attr);
2749 pthread_cond_init (&rcfile_cond, NULL);
2750 pthread_mutex_init (&cn_mutex, &attr);
2751 pthread_mutexattr_destroy (&attr);
2752 pthread_key_create (&last_error_key, free_key);
2753 #ifndef HAVE_PTHREAD_CANCEL
2754 pthread_key_create (&signal_thread_key, free_key);
2755 #endif
2757 if (!rcfile)
2758 rcfile = str_asprintf ("%s/config", homedir);
2760 global_config = config_parse (rcfile);
2761 if (!global_config)
2762 exit (EXIT_FAILURE);
2764 #ifdef WITH_AGENT
2765 if (!use_agent)
2766 use_agent = config_get_boolean ("global", "use_agent");
2767 #endif
2769 setup_logging ();
2771 if (debug_level_opt)
2772 debug_level = str_split (debug_level_opt, ",", 0);
2774 x = config_get_int_param (global_config, "global", "priority", &exists);
2775 if (exists && x != atoi(INVALID_PRIORITY))
2777 errno = 0;
2778 if (setpriority (PRIO_PROCESS, 0, x) == -1)
2780 log_write ("setpriority(): %s",
2781 pwmd_strerror (gpg_error_from_errno (errno)));
2782 goto do_exit;
2785 #ifdef HAVE_MLOCKALL
2786 if (disable_mlock == 0 && mlockall (MCL_CURRENT | MCL_FUTURE) == -1)
2788 log_write ("mlockall(): %s",
2789 pwmd_strerror (gpg_error_from_errno (errno)));
2790 goto do_exit;
2792 #endif
2794 rc = cache_init (free_cache_data);
2795 if (rc)
2797 log_write ("pwmd: ERR %i: %s", rc,
2798 gpg_err_code (rc) == GPG_ERR_UNKNOWN_VERSION
2799 ? _("incompatible gpg-agent version: 2.1.0 or later required")
2800 : pwmd_strerror (rc));
2801 goto do_exit;
2804 if (s2k_count == 0)
2805 s2k_count = config_get_ulong (NULL, "s2k_count");
2807 if (convertfile)
2809 if (!outfile)
2810 usage (argv[0], EXIT_FAILURE);
2812 estatus = convert_v2_datafile (convertfile, cipher, keyfile, keygrip,
2813 sign_keygrip, no_passphrase, outfile,
2814 keyparam, s2k_count, iterations);
2815 config_free (global_config);
2816 xfree (rcfile);
2817 exit (!estatus);
2820 if (import)
2822 if (!outfile || !*outfile)
2823 usage (argv[0], EXIT_FAILURE);
2825 if (outfile && outfile[0] == '-' && outfile[1] == 0)
2826 outfile = NULL;
2828 estatus = xml_import (import, outfile, keygrip, sign_keygrip, keyfile,
2829 no_passphrase, cipher, keyparam, s2k_count,
2830 iterations);
2831 config_free (global_config);
2832 xfree (rcfile);
2833 exit (!estatus);
2836 p = config_get_string ("global", "socket_path");
2837 if (!p)
2838 p = str_asprintf ("%s/socket", homedir);
2840 socketarg = expand_homedir (p);
2841 xfree (p);
2843 if (!secure)
2844 disable_list_and_dump = config_get_boolean ("global",
2845 "disable_list_and_dump");
2846 else
2847 disable_list_and_dump = secure;
2849 cache_push = config_get_list ("global", "cache_push");
2851 while (optind < argc)
2853 if (strv_printf (&cache_push, "%s", argv[optind++]) == 0)
2854 errx (EXIT_FAILURE, "%s", pwmd_strerror (GPG_ERR_ENOMEM));
2857 if (strchr (socketarg, '/') == NULL)
2859 socketdir = getcwd (buf, sizeof (buf));
2860 socketname = str_dup (socketarg);
2861 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2863 else
2865 socketname = str_dup (strrchr (socketarg, '/'));
2866 socketname++;
2867 socketarg[strlen (socketarg) - strlen (socketname) - 1] = 0;
2868 socketdir = str_dup (socketarg);
2869 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2872 if (chdir (datadir))
2874 log_write ("%s: %s", datadir,
2875 pwmd_strerror (gpg_error_from_errno (errno)));
2876 unlink (socketpath);
2877 goto do_exit;
2880 if (test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 0,
2881 mode))
2882 goto do_exit;
2885 * bind() doesn't like the full pathname of the socket or any non alphanum
2886 * characters so change to the directory where the socket is wanted then
2887 * create it then change to datadir.
2889 if (chdir (socketdir))
2891 log_write ("%s: %s", socketdir,
2892 pwmd_strerror (gpg_error_from_errno (errno)));
2893 goto do_exit;
2896 xfree (socketdir);
2898 if ((sockfd = socket (PF_UNIX, SOCK_STREAM, 0)) == -1)
2900 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2901 goto do_exit;
2904 addr.sun_family = AF_UNIX;
2905 snprintf (addr.sun_path, sizeof (addr.sun_path), "%s", socketname);
2906 do_unlink = 1;
2907 if (bind (sockfd, (struct sockaddr *) &addr, sizeof (struct sockaddr)) ==
2910 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2912 if (errno == EADDRINUSE)
2914 do_unlink = 0;
2915 log_write (_("Either there is another pwmd running or '%s' is a \n"
2916 "stale socket. Please remove it manually."), socketpath);
2919 goto do_exit;
2923 char *t = config_get_string ("global", "socket_perms");
2924 mode_t mask;
2926 if (t)
2928 mode = strtol (t, NULL, 8);
2929 mask = umask (0);
2930 xfree (t);
2932 if (chmod (socketname, mode) == -1)
2934 log_write ("%s: %s", socketname,
2935 pwmd_strerror (gpg_error_from_errno (errno)));
2936 close (sockfd);
2937 umask (mask);
2938 goto do_exit;
2941 umask (mask);
2945 xfree (--socketname);
2947 if (chdir (datadir))
2949 log_write ("%s: %s", datadir,
2950 pwmd_strerror (gpg_error_from_errno (errno)));
2951 close (sockfd);
2952 goto do_exit;
2955 xfree (datadir);
2958 * Set the cache entry for a file. Prompts for the password.
2960 if (cache_push)
2962 struct crypto_s *crypto = NULL;
2963 gpg_error_t rc = init_client_crypto (&crypto);
2965 if (rc)
2967 estatus = EXIT_FAILURE;
2968 goto do_exit;
2971 #ifdef WITH_AGENT
2972 if (use_agent)
2974 rc = agent_set_pinentry_options (crypto->agent);
2975 if (rc)
2977 estatus = EXIT_FAILURE;
2978 goto do_exit;
2981 #endif
2983 for (opt = 0; cache_push[opt]; opt++)
2985 if (!do_cache_push (cache_push[opt], crypto) && !force)
2987 strv_free (cache_push);
2988 startup_failure ();
2989 estatus = EXIT_FAILURE;
2990 cleanup_crypto (&crypto);
2991 goto do_exit;
2994 cleanup_crypto_stage1 (crypto);
2997 #ifdef WITH_AGENT
2998 if (use_agent)
2999 (void) kill_scd (crypto->agent);
3000 #endif
3002 cleanup_crypto (&crypto);
3003 strv_free (cache_push);
3004 log_write (!nofork ? _("Done. Daemonizing...") :
3005 _("Done. Waiting for connections..."));
3008 config_clear_keys ();
3010 if (listen (sockfd, 0) == -1)
3012 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
3013 goto do_exit;
3016 if (!nofork)
3018 switch (fork ())
3020 case -1:
3021 log_write ("fork(): %s",
3022 pwmd_strerror (gpg_error_from_errno (errno)));
3023 goto do_exit;
3024 case 0:
3025 close (0);
3026 close (1);
3027 close (2);
3028 setsid ();
3029 break;
3030 default:
3031 _exit (EXIT_SUCCESS);
3035 (void)test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 1,
3036 mode);
3037 cmdline = 0;
3038 pthread_key_create (&thread_name_key, free_key);
3039 pthread_setspecific (thread_name_key, str_dup ("main"));
3040 estatus = server_loop (sockfd, &socketpath);
3042 do_exit:
3043 if (socketpath && do_unlink)
3045 unlink (socketpath);
3046 xfree (socketpath);
3049 xfree (socketarg);
3050 #ifdef WITH_GNUTLS
3051 gnutls_global_deinit ();
3052 #endif
3053 if (rcfile_tid)
3055 #ifdef HAVE_PTHREAD_CANCEL
3056 pthread_cancel (rcfile_tid);
3057 #else
3058 pthread_kill (rcfile_tid, SIGUSR2);
3059 pthread_cond_signal (&rcfile_cond);
3060 #endif
3061 pthread_join (rcfile_tid, NULL);
3064 pthread_cond_destroy (&rcfile_cond);
3065 pthread_mutex_destroy (&rcfile_mutex);
3066 pthread_key_delete (last_error_key);
3067 #ifndef HAVE_PTHREAD_CANCEL
3068 pthread_key_delete (signal_thread_key);
3069 #endif
3071 if (global_config)
3072 config_free (global_config);
3074 xfree (rcfile);
3075 xfree (home_directory);
3076 xfree (homedir);
3077 xmlCleanupParser ();
3078 xmlCleanupGlobals ();
3080 if (pidfile)
3081 unlink (pidfile);
3082 xfree (pidfile);
3084 if (estatus == EXIT_SUCCESS)
3085 log_write (_("pwmd exiting normally"));
3087 pthread_key_delete (thread_name_key);
3088 closelog ();
3089 #if defined(DEBUG) && !defined(MEM_DEBUG)
3090 xdump ();
3091 #endif
3092 exit (estatus);