Add --kill command line option.
[pwmd.git] / src / pwmd.c
blob211fa38e3edd2710f57143f1efd6118eb7b2fc50
1 /*
2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015
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;
105 static int log_fd;
107 #ifndef HAVE_PTHREAD_CANCEL
108 static pthread_key_t signal_thread_key;
109 #endif
111 #ifdef WITH_GNUTLS
112 static int tls_fd;
113 static int tls6_fd;
114 static pthread_t tls_tid;
115 static pthread_t tls6_tid;
116 static int spawned_tls;
117 static int spawned_tls6;
119 static int start_stop_tls (int term);
120 #endif
122 static int do_cache_push (const char *filename, struct crypto_s *crypto);
123 static int signal_loop (sigset_t sigset);
125 GCRY_THREAD_OPTION_PTHREAD_IMPL;
127 #ifndef HAVE_PTHREAD_CANCEL
128 #define INIT_THREAD_SIGNAL do { \
129 struct sigaction act; \
130 sigset_t sigset; \
131 sigemptyset (&sigset); \
132 sigaddset (&sigset, SIGUSR2); \
133 pthread_sigmask (SIG_UNBLOCK, &sigset, NULL); \
134 memset (&act, 0, sizeof(act)); \
135 act.sa_flags = SA_SIGINFO; \
136 act.sa_mask = sigset; \
137 act.sa_sigaction = catch_thread_signal; \
138 sigaction (SIGUSR2, &act, NULL); \
139 } while (0)
141 static void
142 catch_thread_signal (int sig, siginfo_t *info, void *ctx)
144 int *n = (int *) pthread_getspecific (signal_thread_key);
146 *n = 1;
147 pthread_setspecific (signal_thread_key, n);
149 #endif
151 static void
152 cache_push_from_rcfile ()
154 struct crypto_s *crypto = NULL;
155 char **cache_push;
156 gpg_error_t rc = init_client_crypto (&crypto);
158 if (rc)
160 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
161 return;
164 #ifdef WITH_AGENT
165 if (use_agent)
167 rc = set_agent_option (crypto->agent, "pinentry-mode", "error");
168 if (rc)
170 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
171 return;
174 #endif
176 cache_push = config_get_list ("global", "cache_push");
177 if (cache_push)
179 char **p;
181 for (p = cache_push; *p; p++)
183 (void) do_cache_push (*p, crypto);
184 cleanup_crypto_stage1 (crypto);
187 strv_free (cache_push);
190 #ifdef WITH_AGENT
191 (void) kill_scd (crypto->agent);
192 #endif
193 cleanup_crypto (&crypto);
196 static void
197 setup_logging ()
199 int n = config_get_boolean ("global", "enable_logging");
201 if (n)
203 char *p = config_get_string ("global", "log_path");
205 if (!p || (logfile && p && log_fd != -1 && strcmp(p, logfile)))
207 if (log_fd != -1)
208 close (log_fd);
210 log_fd = -1;
213 xfree (logfile);
214 logfile = expand_homedir (p);
215 xfree (p);
217 else
219 xfree (logfile);
220 logfile = NULL;
221 if (log_fd != -1)
222 close(log_fd);
224 log_fd = -1;
227 log_syslog = config_get_boolean ("global", "syslog");
228 if (log_syslog == 1)
229 openlog ("pwmd", LOG_NDELAY | LOG_PID, LOG_DAEMON);
232 static void *
233 reload_rcfile_thread (void *arg)
235 #ifndef HAVE_PTHREAD_CANCEL
236 int *n = xmalloc (sizeof (int));
238 *n = 0;
239 pthread_setspecific (signal_thread_key, n);
240 INIT_THREAD_SIGNAL;
241 #endif
243 #ifdef HAVE_PR_SET_NAME
244 prctl (PR_SET_NAME, "reload rcfile");
245 #endif
246 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
247 MUTEX_LOCK (&rcfile_mutex);
248 pthread_cleanup_push (cleanup_mutex_cb, &rcfile_mutex);
250 for (;;)
252 struct allowed_users_s
254 char *section;
255 char **users;
257 struct slist_s *allowed_users = NULL;
258 struct slist_s *config;
259 int b = disable_list_and_dump;
260 uid_t invoking_uid_orig = invoking_uid;
261 gid_t invoking_gid_orig = invoking_gid;
262 char *invoking_tls_orig;
263 int exists;
264 int require_save_key = config_get_bool_param (global_config, "global",
265 "require_save_key",
266 &exists);
267 #ifdef WITH_GNUTLS
268 int tcp_require_key = config_get_bool_param (global_config, "global",
269 "tcp_require_key",
270 &exists);
271 #endif
273 pthread_cond_wait (&rcfile_cond, &rcfile_mutex);
274 #ifndef HAVE_PTHREAD_CANCEL
275 int *cancel = (int *) pthread_getspecific (signal_thread_key);
276 if (*cancel)
277 break;
278 #endif
280 /* Keep the "allowed" parameter across rcfile reloads to prevent
281 tampering. */
282 int n, t = slist_length (global_config);
283 for (n = 0; n < t; n++)
285 struct config_section_s *section;
286 char **users;
288 section = slist_nth_data (global_config, n);
289 users = config_get_list_param (global_config, section->name,
290 "allowed", &exists);
291 if (users)
293 struct allowed_users_s *allowed;
295 allowed = xmalloc (sizeof(struct allowed_users_s));
296 allowed->section = str_dup (section->name);
297 allowed->users = users;
298 allowed_users = slist_append (allowed_users, allowed);
302 invoking_tls_orig = invoking_tls ? str_dup (invoking_tls) : NULL;
303 xfree (invoking_tls);
304 invoking_tls = NULL;
305 log_write (_("reloading configuration file '%s'"), rcfile);
307 config = config_parse (rcfile);
308 if (config)
310 config_free (global_config);
311 global_config = config;
312 setup_logging ();
313 cache_push_from_rcfile ();
314 config_clear_keys ();
317 xfree (invoking_tls);
318 invoking_tls = invoking_tls_orig;
319 invoking_uid = invoking_uid_orig;
320 invoking_gid = invoking_gid_orig;
321 disable_list_and_dump = !disable_list_and_dump ? b : 1;
322 config_set_bool_param (&global_config, "global", "require_save_key",
323 require_save_key ? "true" : "false");
324 #ifdef WITH_GNUTLS
325 if (config_get_bool_param (global_config, "global", "tcp_require_key",
326 &exists) && exists)
327 tcp_require_key = 1;
329 config_set_bool_param (&global_config, "global", "tcp_require_key",
330 tcp_require_key ? "true" : "false");
331 #endif
333 if (allowed_users)
335 int n, t = slist_length (allowed_users);
337 for (n = 0; n < t; n++)
339 struct allowed_users_s *allowed;
340 char *tmp;
342 allowed = slist_nth_data (allowed_users, n);
343 tmp = strv_join (",", allowed->users);
344 config_set_list_param (&global_config, allowed->section,
345 "allowed", tmp);
346 xfree (tmp);
347 xfree (allowed->section);
348 strv_free (allowed->users);
349 xfree (allowed);
352 slist_free (allowed_users);
355 #ifdef WITH_GNUTLS
356 /* Kill existing listening threads since the configured listening
357 * protocols may have changed. */
358 start_stop_tls (1);
359 start_stop_tls (0);
360 #endif
363 pthread_cleanup_pop (1);
364 return NULL;
367 gpg_error_t
368 send_error (assuan_context_t ctx, gpg_error_t e)
370 struct client_s *client = assuan_get_pointer (ctx);
372 if (gpg_err_source (e) == GPG_ERR_SOURCE_UNKNOWN)
373 e = gpg_error (e);
375 if (client)
376 client->last_rc = e;
378 if (!e)
379 return assuan_process_done (ctx, 0);
381 if (!ctx)
383 log_write ("ERR %i: %s", e, pwmd_strerror (e));
384 return e;
387 if (client && client->xml_error)
389 log_write ("%s", client->xml_error->message);
390 xfree (client->last_error);
391 client->last_error = NULL;
392 if (client->xml_error->message)
393 client->last_error = str_dup (client->xml_error->message);
395 e = assuan_process_done (ctx,
396 assuan_set_error (ctx, e,
397 client->xml_error->message ? client->xml_error->message : NULL));
398 xmlResetLastError ();
399 xmlResetError (client->xml_error);
400 xfree (client->xml_error);
401 client->xml_error = NULL;
402 return e;
405 return assuan_process_done (ctx,
406 assuan_set_error (ctx, e, pwmd_strerror (e)));
410 assuan_log_cb (assuan_context_t ctx, void *data, unsigned cat,
411 const char *msg)
413 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
414 int i, t;
415 int match = 0;
417 pthread_mutex_lock (&m);
418 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock, &m);
419 t = strv_length (debug_level);
421 for (i = 0; i < t; i++)
423 if (!strcasecmp (debug_level[i], (char *) "init")
424 && cat == ASSUAN_LOG_INIT)
426 match = 1;
427 break;
430 if (!strcasecmp (debug_level[i], (char *) "ctx")
431 && cat == ASSUAN_LOG_CTX)
433 match = 1;
434 break;
437 if (!strcasecmp (debug_level[i], (char *) "engine")
438 && cat == ASSUAN_LOG_ENGINE)
440 match = 1;
441 break;
444 if (!strcasecmp (debug_level[i], (char *) "data")
445 && cat == ASSUAN_LOG_DATA)
447 match = 1;
448 break;
451 if (!strcasecmp (debug_level[i], (char *) "sysio")
452 && cat == ASSUAN_LOG_SYSIO)
454 match = 1;
455 break;
458 if (!strcasecmp (debug_level[i], (char *) "control")
459 && cat == ASSUAN_LOG_CONTROL)
461 match = 1;
462 break;
466 if (match && msg)
468 if (logfile)
470 int fd;
472 if ((fd =
473 open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600)) == -1)
474 warn ("%s", logfile);
475 else
477 pthread_cleanup_push (cleanup_fd_cb, &fd);
478 write (fd, msg, strlen (msg));
479 pthread_cleanup_pop (1);
483 if (nofork)
485 fprintf (stderr, "%s%s", data ? (char *) data : "", msg);
486 fflush (stderr);
490 pthread_cleanup_pop (1);
491 return match;
494 void
495 log_write (const char *fmt, ...)
497 char *args;
498 va_list ap;
499 time_t now;
500 char buf[255];
501 pthread_t tid = pthread_self ();
502 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
504 if ((!logfile && !isatty (STDERR_FILENO) && !log_syslog) || !fmt)
505 return;
507 pthread_mutex_lock (&m);
508 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock, &m);
510 if (!cmdline && logfile && log_fd == -1)
512 log_fd = open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600);
513 if (log_fd == -1)
514 warn ("%s", logfile);
517 va_start (ap, fmt);
519 if (str_vasprintf (&args, fmt, ap) != -1)
521 if (cmdline)
523 pthread_cleanup_push (xfree, args);
524 fprintf (stderr, "pwmd: %s\n", args);
525 fflush (stderr);
526 pthread_cleanup_pop (1);
528 else
530 char *name = pthread_getspecific (thread_name_key);
531 char *line;
533 pthread_cleanup_push (xfree, args);
534 snprintf (buf, sizeof (buf), "%s(%p): ", name ? name : _("unknown"),
535 (pthread_t *) tid);
536 name = buf;
538 if (!cmdline && log_syslog && !nofork)
539 syslog (LOG_INFO, "%s%s", name, args);
541 time (&now);
542 struct tm *tm = localtime (&now);
543 char tbuf[21];
544 strftime (tbuf, sizeof (tbuf), "%b %d %Y %H:%M:%S ", tm);
545 tbuf[sizeof (tbuf) - 1] = 0;
547 if (args[strlen (args) - 1] == '\n')
548 args[strlen (args) - 1] = 0;
550 line = str_asprintf ("%s %i %s%s\n", tbuf, getpid (), name,
551 args);
552 pthread_cleanup_pop (1);
553 if (line)
555 pthread_cleanup_push (xfree, line);
556 if (logfile && log_fd != -1)
558 write (log_fd, line, strlen (line));
559 fsync (log_fd);
562 if (nofork)
564 fprintf (stdout, "%s", line);
565 fflush (stdout);
568 pthread_cleanup_pop (1);
573 va_end (ap);
574 pthread_cleanup_pop (0);
576 if (log_fd != -1 && config_get_boolean (NULL, "log_keepopen") <= 0)
578 close(log_fd);
579 log_fd = -1;
582 pthread_mutex_unlock (&m);
585 #ifdef WITH_GNUTLS
586 static int
587 secure_mem_check (const void *arg)
589 return 1;
591 #endif
593 static gpg_error_t
594 setup_crypto ()
596 gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
598 if (!gcry_check_version (GCRYPT_VERSION))
600 fprintf (stderr, _("gcry_check_version(): Incompatible libgcrypt. "
601 "Wanted %s, got %s.\n"), GCRYPT_VERSION,
602 gcry_check_version (NULL));
603 return GPG_ERR_UNKNOWN_VERSION;
606 gcry_set_allocation_handler (xmalloc, xmalloc, NULL, xrealloc, xfree);
607 return 0;
610 gpg_error_t
611 do_validate_peer (assuan_context_t ctx, const char *section,
612 assuan_peercred_t * peer)
614 char **users;
615 int allowed = 0;
616 gpg_error_t rc;
617 struct client_s *client = assuan_get_pointer (ctx);
619 #ifdef WITH_GNUTLS
620 if (client && client->thd->remote)
621 return tls_validate_access (client, section);
622 #endif
624 rc = assuan_get_peercred (ctx, peer);
625 if (rc)
626 return rc;
628 users = config_get_list (section, "allowed");
629 if (users)
631 for (char **p = users; *p; p++)
633 rc = acl_check_common(client, *p, (*peer)->uid, (*peer)->gid,
634 &allowed);
637 strv_free (users);
640 return allowed ? 0 : rc ? rc : GPG_ERR_EACCES;
643 gpg_error_t
644 peer_is_invoker(struct client_s *client)
646 #ifdef WITH_GNUTLS
647 if (client->thd->remote)
649 char *p = invoking_tls;
651 if (!p || !*p || *p++ != '#')
652 return GPG_ERR_EACCES;
654 if (!strcmp(client->thd->tls->fp, p))
655 return 0;
657 return GPG_ERR_EACCES;
659 #endif
661 if (client->thd->peer->uid == invoking_uid)
662 return 0;
664 return GPG_ERR_EACCES;
667 #ifdef HAVE_GETGRNAM_R
668 gpg_error_t
669 acl_check_common (struct client_s *client, const char *user, uid_t uid,
670 gid_t gid, int *allowed)
672 struct passwd pw, *result;
673 char *buf = NULL;
674 int not = 0;
675 int rw = 0;
676 int tls = 0;
678 if (!user || !*user)
679 return 0;
681 if (*user == '-' || *user == '!')
682 not = 1;
684 if (*user == '+') // not implemented yet
685 rw = 1;
687 if (*user == '#') // TLS fingerprint hash
688 tls = 1;
690 if (not || rw || tls)
691 user++;
693 if (tls)
695 #ifdef WITH_GNUTLS
696 if (client->thd->remote)
698 if (!strcasecmp (client->thd->tls->fp, user))
699 *allowed = !not;
702 return 0;
703 #else
704 return 0;
705 #endif
707 #ifdef WITH_GNUTLS
708 else if (client->thd->remote) // Remote client with no TLS in the ACL
709 return 0;
710 #endif
712 if (*user == '@') // all users in group
714 struct group gr, *gresult;
715 size_t len = sysconf (_SC_GETGR_R_SIZE_MAX);
717 if (len == -1)
718 len = 16384;
720 buf = xmalloc (len);
721 if (!buf)
722 return GPG_ERR_ENOMEM;
724 user++;
725 if (!getgrnam_r (user, &gr, buf, len, &gresult) && gresult)
727 if (gresult->gr_gid == gid)
729 xfree (buf);
730 *allowed = !not;
731 return 0;
734 len = sysconf (_SC_GETPW_R_SIZE_MAX);
735 if (len == -1)
736 len = 16384;
738 char *tbuf = xmalloc (len);
739 for (char **t = gresult->gr_mem; *t; t++)
741 if (!getpwnam_r (*t, &pw, tbuf, len, &result) && result)
743 if (result->pw_uid == uid)
745 *allowed = !not;
746 break;
751 return 0;
754 else
756 size_t len = sysconf (_SC_GETPW_R_SIZE_MAX);
758 if (len == -1)
759 len = 16384;
761 buf = xmalloc (len);
762 if (!buf)
763 return GPG_ERR_ENOMEM;
765 if (!getpwnam_r (user, &pw, buf, len, &result) && result)
767 if (result->pw_uid == uid)
768 *allowed = !not;
771 xfree (buf);
774 return 0;
776 #else
777 gpg_error_t
778 acl_check_common (struct client_s *client, const char *user, uid_t uid,
779 gid_t gid, int *allowed)
781 struct passwd *result;
782 int not = 0;
783 int rw = 0;
784 int tls = 0;
786 if (!user || !*user)
787 return 0;
789 if (*user == '-' || *user == '!')
790 not = 1;
792 if (*user == '+') // not implemented yet
793 rw = 1;
795 if (*user == '#') // TLS fingerprint hash
796 tls = 1;
798 if (not || rw || tls)
799 user++;
801 if (tls)
803 #ifdef WITH_GNUTLS
804 if (client->thd->remote)
806 if (!strcasecmp (client->thd->tls->fp, user))
807 *allowed = !not;
810 return 0;
811 #else
812 return 0;
813 #endif
816 if (*user == '@') // all users in group
818 struct group *gresult;
820 user++;
821 gresult = getgrnam (user);
822 if (gresult && gresult->gr_gid == gid)
824 *allowed = !not;
825 return 0;
828 for (char **t = gresult->gr_mem; *t; t++)
830 result = getpwnam (*t);
831 if (result && result->pw_uid == uid)
833 *allowed = !not;
834 break;
838 return 0;
840 else
842 result = getpwnam (user);
843 if (result && result->pw_uid == uid)
844 *allowed = !not;
847 return 0;
849 #endif
851 static gpg_error_t
852 validate_peer (struct client_s *cl)
854 gpg_error_t rc;
856 #ifdef WITH_GNUTLS
857 if (cl->thd->remote)
858 return tls_validate_access (cl, NULL);
859 #endif
861 rc = do_validate_peer (cl->ctx, "global", &cl->thd->peer);
862 if (!rc || gpg_err_code (rc) == GPG_ERR_EACCES)
863 log_write ("peer %s: uid=%i, gid=%i, pid=%i",
864 !rc ? _("accepted") : _("rejected"), cl->thd->peer->uid,
865 cl->thd->peer->gid, cl->thd->peer->pid);
866 else if (rc)
867 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
869 return rc;
872 static void
873 xml_error_cb (void *data, xmlErrorPtr e)
875 struct client_s *client = data;
878 * Keep the first reported error as the one to show in the error
879 * description. Reset in send_error().
881 if (client->xml_error)
882 return;
884 client->xml_error = xcalloc (1, sizeof(xmlError));
885 xmlCopyError (e, client->xml_error);
888 static pid_t
889 hook_waitpid (assuan_context_t ctx, pid_t pid, int action,
890 int *status, int options)
892 return waitpid (pid, status, options);
895 static ssize_t
896 hook_read (assuan_context_t ctx, assuan_fd_t fd, void *data, size_t len)
898 #ifdef WITH_GNUTLS
899 struct client_s *client = assuan_get_pointer (ctx);
901 if (client->thd->remote)
902 return tls_read_hook (ctx, (int) fd, data, len);
903 #endif
905 return read ((int) fd, data, len);
908 static ssize_t
909 hook_write (assuan_context_t ctx, assuan_fd_t fd,
910 const void *data, size_t len)
912 #ifdef WITH_GNUTLS
913 struct client_s *client = assuan_get_pointer (ctx);
915 if (client->thd->remote)
916 return tls_write_hook (ctx, (int) fd, data, len);
917 #endif
919 return write ((int) fd, data, len);
922 static int
923 new_connection (struct client_s *cl)
925 gpg_error_t rc;
926 static struct assuan_malloc_hooks mhooks = { xmalloc, xrealloc, xfree };
927 static struct assuan_system_hooks shooks = {
928 ASSUAN_SYSTEM_HOOKS_VERSION,
929 __assuan_usleep,
930 __assuan_pipe,
931 __assuan_close,
932 hook_read,
933 hook_write,
934 //FIXME
935 NULL, //recvmsg
936 NULL, //sendmsg both are used for FD passing
937 __assuan_spawn,
938 hook_waitpid,
939 __assuan_socketpair,
940 __assuan_socket,
941 __assuan_connect
944 #ifdef WITH_GNUTLS
945 if (cl->thd->remote)
947 char *prio = config_get_string ("global", "tls_cipher_suite");
949 cl->thd->timeout = config_get_integer ("global", "tls_timeout");
950 fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK);
951 cl->thd->tls = tls_init (cl->thd->fd, cl->thd->timeout, prio);
952 xfree (prio);
953 if (!cl->thd->tls)
954 return 0;
956 #endif
958 rc = assuan_new_ext (&cl->ctx, GPG_ERR_SOURCE_DEFAULT, &mhooks,
959 debug_level ? assuan_log_cb : NULL, NULL);
960 if (rc)
961 goto fail;
963 assuan_ctx_set_system_hooks (cl->ctx, &shooks);
964 rc = assuan_init_socket_server (cl->ctx, cl->thd->fd, 2);
965 if (rc)
966 goto fail;
968 assuan_set_pointer (cl->ctx, cl);
969 assuan_set_hello_line (cl->ctx, PACKAGE_STRING);
970 rc = register_commands (cl->ctx);
971 if (rc)
972 goto fail;
974 rc = assuan_accept (cl->ctx);
975 if (rc)
976 goto fail;
978 rc = validate_peer (cl);
979 /* May not be implemented on all platforms. */
980 if (rc && gpg_err_code (rc) != GPG_ERR_ASS_GENERAL)
981 goto fail;
983 rc = init_client_crypto (&cl->crypto);
984 if (rc)
985 goto fail;
987 #ifdef WITH_AGENT
988 if (use_agent)
989 cl->crypto->agent->client_ctx = cl->ctx;
990 #endif
992 cl->crypto->client_ctx = cl->ctx;
993 cl->lock_timeout = config_get_integer ("global", "lock_timeout");
994 xmlSetStructuredErrorFunc (cl, xml_error_cb);
995 return 1;
997 fail:
998 log_write ("%s", pwmd_strerror (rc));
999 return 0;
1003 * This is called after a client_thread() terminates. Set with
1004 * pthread_cleanup_push().
1006 static void
1007 cleanup_cb (void *arg)
1009 struct client_thread_s *cn = arg;
1010 struct client_s *cl = cn->cl;
1012 MUTEX_LOCK (&cn_mutex);
1013 cn_thread_list = slist_remove (cn_thread_list, cn);
1014 MUTEX_UNLOCK (&cn_mutex);
1016 if (cl)
1018 cleanup_client (cl);
1019 if (cl->xml_error)
1020 xmlResetError (cl->xml_error);
1022 xfree (cl->xml_error);
1024 #ifdef WITH_GNUTLS
1025 if (cn->tls)
1027 gnutls_deinit (cn->tls->ses);
1028 xfree (cn->tls->fp);
1029 xfree (cn->tls);
1031 #endif
1033 if (!cn->atfork && cl->ctx)
1034 assuan_release (cl->ctx);
1035 else if (!cn->atfork && cl->thd && cl->thd->fd != -1)
1036 close (cl->thd->fd);
1038 if (cl->crypto)
1039 cleanup_crypto (&cl->crypto);
1041 pinentry_free_opts (&cl->pinentry_opts);
1042 xfree (cl);
1044 else
1046 if (cn->fd != -1)
1047 close (cn->fd);
1050 while (cn->msg_queue)
1052 struct status_msg_s *msg = cn->msg_queue;
1054 cn->msg_queue = msg->next;
1055 xfree (msg->line);
1056 xfree (msg);
1059 if (!cn->atfork && cn->status_msg_pipe[0] != -1)
1060 close (cn->status_msg_pipe[0]);
1062 if (!cn->atfork && cn->status_msg_pipe[1] != -1)
1063 close (cn->status_msg_pipe[1]);
1065 pthread_mutex_destroy (&cn->status_mutex);
1067 if (!cn->atfork)
1069 log_write (_("exiting, fd=%i"), cn->fd);
1070 send_status_all (STATUS_CLIENTS, NULL);
1073 xfree (cn->name);
1074 #ifdef WITH_GNUTLS
1075 xfree (cn->peeraddr);
1076 #endif
1077 xfree (cn);
1078 pthread_cond_signal (&quit_cond);
1081 void
1082 cleanup_all_clients (int atfork)
1084 /* This function may be called from pthread_atfork() which requires
1085 reinitialization. */
1086 if (atfork)
1088 pthread_mutexattr_t attr;
1090 pthread_mutexattr_init (&attr);
1091 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
1092 pthread_mutex_init (&cn_mutex, &attr);
1093 pthread_mutexattr_destroy (&attr);
1094 cache_mutex_init ();
1097 MUTEX_LOCK (&cn_mutex);
1099 while (slist_length (cn_thread_list))
1101 struct client_thread_s *thd = slist_nth_data (cn_thread_list, 0);
1103 thd->atfork = atfork;
1104 cleanup_cb (thd);
1107 exiting = 1;
1108 MUTEX_UNLOCK (&cn_mutex);
1109 cache_deinit (atfork);
1112 static gpg_error_t
1113 send_msg_queue (struct client_thread_s *thd)
1115 MUTEX_LOCK (&thd->status_mutex);
1116 gpg_error_t rc = 0;
1117 char c;
1119 read (thd->status_msg_pipe[0], &c, 1);
1121 while (thd->msg_queue)
1123 struct status_msg_s *msg = thd->msg_queue;
1125 thd->msg_queue = thd->msg_queue->next;
1126 MUTEX_UNLOCK (&thd->status_mutex);
1127 rc = send_status (thd->cl->ctx, msg->s, msg->line);
1128 MUTEX_LOCK (&thd->status_mutex);
1129 xfree (msg->line);
1130 xfree (msg);
1132 if (rc)
1133 break;
1136 MUTEX_UNLOCK (&thd->status_mutex);
1137 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1138 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
1140 return rc;
1143 static void *
1144 client_thread (void *data)
1146 struct client_thread_s *thd = data;
1147 struct client_s *cl = xcalloc (1, sizeof (struct client_s));
1149 #ifdef HAVE_PR_SET_NAME
1150 prctl (PR_SET_NAME, "client");
1151 #endif
1152 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1154 if (!cl)
1156 log_write ("%s(%i): %s", __FILE__, __LINE__,
1157 pwmd_strerror (GPG_ERR_ENOMEM));
1158 return NULL;
1161 MUTEX_LOCK (&cn_mutex);
1162 pthread_cleanup_push (cleanup_cb, thd);
1163 thd->cl = cl;
1164 cl->thd = thd;
1165 MUTEX_UNLOCK (&cn_mutex);
1167 if (new_connection (cl))
1169 int finished = 0;
1170 gpg_error_t rc;
1172 send_status_all (STATUS_CLIENTS, NULL);
1173 rc = send_status (cl->ctx, STATUS_CACHE, NULL);
1174 if (rc)
1176 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
1177 finished = 1;
1180 while (!finished)
1182 fd_set rfds;
1183 int n;
1184 int eof;
1186 FD_ZERO (&rfds);
1187 FD_SET (thd->fd, &rfds);
1188 FD_SET (thd->status_msg_pipe[0], &rfds);
1189 n = thd->fd > thd->status_msg_pipe[0]
1190 ? thd->fd : thd->status_msg_pipe[0];
1192 n = select (n + 1, &rfds, NULL, NULL, NULL);
1193 if (n == -1)
1195 log_write ("%s", strerror (errno));
1196 break;
1199 if (FD_ISSET (thd->status_msg_pipe[0], &rfds))
1201 rc = send_msg_queue (thd);
1202 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1203 break;
1206 if (!FD_ISSET (thd->fd, &rfds))
1207 continue;
1209 rc = assuan_process_next (cl->ctx, &eof);
1210 if (rc || eof)
1212 if (gpg_err_code (rc) == GPG_ERR_EOF || eof)
1213 break;
1215 log_write ("assuan_process_next(): rc=%i %s", rc,
1216 pwmd_strerror (rc));
1217 if (rc == gpg_error (GPG_ERR_ETIMEDOUT))
1218 break;
1220 rc = send_error (cl->ctx, rc);
1221 if (rc)
1223 log_write ("assuan_process_done(): rc=%i %s", rc,
1224 pwmd_strerror (rc));
1225 break;
1229 /* Since the msg queue pipe fd's are non-blocking, check for
1230 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1231 * client has already disconnected and will be converted to
1232 * GPG_ERR_EOF during assuan_process_next().
1234 rc = send_msg_queue (thd);
1235 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1236 break;
1240 /* Don't do pthread_exit() here because any set pthread_cleanup_push
1241 * functions would be called after a command failed but then the client
1242 * exited normally which may lead to a double free. */
1243 pthread_cleanup_pop (1);
1244 return NULL;
1247 static int
1248 xml_import (const char *filename, const char *outfile,
1249 const char *keygrip, const char *sign_keygrip,
1250 const char *keyfile, int no_passphrase, const char *cipher,
1251 const char *params, unsigned long s2k_count, uint64_t iterations)
1253 xmlDocPtr doc;
1254 int fd;
1255 struct stat st;
1256 int len;
1257 xmlChar *xmlbuf;
1258 xmlChar *xml;
1259 gpg_error_t rc;
1260 struct crypto_s *crypto = NULL;
1261 void *key = NULL;
1262 size_t keylen = 0;
1263 int algo = cipher ? cipher_string_to_gcrypt ((char *) cipher) :
1264 GCRY_CIPHER_AES256;
1266 if (algo == -1)
1268 log_write ("ERR %i: %s", gpg_error (GPG_ERR_CIPHER_ALGO),
1269 pwmd_strerror (GPG_ERR_CIPHER_ALGO));
1270 return 0;
1273 if (stat (filename, &st) == -1)
1275 log_write ("%s: %s", filename,
1276 pwmd_strerror (gpg_error_from_errno (errno)));
1277 return 0;
1280 rc = init_client_crypto (&crypto);
1281 if (rc)
1282 return 0;
1284 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
1285 crypto->save.hdr.flags = set_cipher_flag (crypto->save.hdr.flags, algo);
1286 log_write (_("Importing XML from '%s'. Output will be written to '%s' ..."),
1287 filename, outfile);
1289 if ((fd = open (filename, O_RDONLY)) == -1)
1291 log_write ("%s: %s", filename,
1292 pwmd_strerror (gpg_error_from_errno (errno)));
1293 goto fail;
1296 if ((xmlbuf = xmalloc (st.st_size + 1)) == NULL)
1298 close (fd);
1299 log_write ("%s(%i): %s", __FILE__, __LINE__,
1300 pwmd_strerror (GPG_ERR_ENOMEM));
1301 goto fail;
1304 if (read (fd, xmlbuf, st.st_size) == -1)
1306 rc = gpg_error_from_errno (errno);
1307 close (fd);
1308 log_write ("%s: %s", filename, pwmd_strerror (rc));
1309 goto fail;
1312 close (fd);
1313 xmlbuf[st.st_size] = 0;
1315 * Make sure the document validates.
1317 if ((doc = xmlReadDoc (xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS)) == NULL)
1319 log_write ("xmlReadDoc() failed");
1320 xfree (xmlbuf);
1321 goto fail;
1324 xfree (xmlbuf);
1325 xmlNodePtr n = xmlDocGetRootElement (doc);
1326 if (n && !xmlStrEqual (n->name, (xmlChar *) "pwmd"))
1328 log_write (_("Could not find root \"pwmd\" element."));
1329 rc = GPG_ERR_BAD_DATA;
1332 if (!rc)
1333 rc = validate_import (NULL, n ? n->children : n);
1335 if (rc)
1337 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1338 xmlFreeDoc (doc);
1339 goto fail;
1342 xmlDocDumpMemory (doc, &xml, &len);
1343 xmlFreeDoc (doc);
1344 crypto->save.s2k_count = s2k_count;
1345 crypto->save.hdr.iterations = iterations;
1346 if (!use_agent)
1348 rc = export_common (NULL, 0, crypto, xml, len, outfile, keyfile, &key,
1349 &keylen, 0, 0, no_passphrase);
1350 if (!rc)
1351 log_write (_("Success!"));
1353 #ifdef WITH_AGENT
1354 else
1356 rc = agent_set_pinentry_options (crypto->agent);
1357 if (!rc)
1358 rc = agent_export_common (crypto, keygrip, sign_keygrip, no_passphrase,
1359 xml, len, outfile, params, keyfile);
1361 #endif
1363 gcry_free (key);
1364 xmlFree (xml);
1365 if (rc)
1367 send_error (NULL, rc);
1368 goto fail;
1371 cleanup_crypto (&crypto);
1372 return 1;
1374 fail:
1375 cleanup_crypto (&crypto);
1376 return 0;
1379 static int
1380 do_cache_push (const char *filename, struct crypto_s *crypto)
1382 unsigned char md5file[16];
1383 gpg_error_t rc;
1384 char *key = NULL;
1385 size_t keylen = 0;
1386 xmlDocPtr doc;
1387 struct cache_data_s *cdata;
1388 unsigned char *crc;
1389 size_t len;
1391 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1392 filename);
1394 if (valid_filename (filename) == 0)
1396 log_write (_("%s: Invalid characters in filename"), filename);
1397 return 0;
1400 rc = decrypt_common (NULL, 0, crypto, filename, &key, &keylen);
1401 if (rc)
1402 return 0;
1404 rc = parse_doc ((char *) crypto->plaintext, crypto->plaintext_len, &doc);
1405 if (rc)
1407 log_write ("%s", pwmd_strerror (rc));
1408 xfree (key);
1409 return 0;
1412 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
1413 cdata = xcalloc (1, sizeof (struct cache_data_s));
1414 if (!cdata)
1416 xmlFreeDoc (doc);
1417 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM));
1418 xfree (key);
1419 return 0;
1422 rc = get_checksum (filename, &crc, &len);
1423 if (rc)
1425 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1426 xmlFreeDoc (doc);
1427 free_cache_data_once (cdata);
1428 xfree (key);
1429 return 0;
1432 cdata->crc = crc;
1433 rc = encrypt_xml (NULL, cache_key, cache_keysize, GCRY_CIPHER_AES,
1434 crypto->plaintext, crypto->plaintext_len, &cdata->doc,
1435 &cdata->doclen, &cache_iv, &cache_blocksize, 0);
1436 if (!rc && !IS_PKI (crypto))
1438 cdata->key = key;
1439 cdata->keylen = keylen;
1441 else
1442 xfree (key);
1444 if (rc)
1446 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1447 xmlFreeDoc (doc);
1448 free_cache_data_once (cdata);
1449 return 0;
1452 #ifdef WITH_AGENT
1453 if (use_agent && IS_PKI (crypto))
1455 gcry_sexp_build ((gcry_sexp_t *) & cdata->pubkey, NULL, "%S",
1456 crypto->pkey_sexp);
1457 gcry_sexp_build ((gcry_sexp_t *) & cdata->sigkey, NULL, "%S",
1458 crypto->sigpkey_sexp);
1460 #endif
1462 int timeout = config_get_integer (filename, "cache_timeout");
1463 cache_add_file (md5file, crypto->grip, cdata, timeout);
1464 log_write (_("Successfully added '%s' to the cache."), filename);
1465 return 1;
1468 static gpg_error_t
1469 init_client (int fd, const char *addr)
1471 gpg_error_t rc = 0;
1472 struct client_thread_s *new = xcalloc (1, sizeof (struct client_thread_s));
1474 if (!new)
1476 close (fd);
1477 return GPG_ERR_ENOMEM;
1480 MUTEX_LOCK (&cn_mutex);
1481 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
1483 if (pipe (new->status_msg_pipe) == -1)
1484 rc = gpg_error_from_errno (errno);
1486 if (!rc)
1488 fcntl (new->status_msg_pipe[0], F_SETFL, O_NONBLOCK);
1489 fcntl (new->status_msg_pipe[1], F_SETFL, O_NONBLOCK);
1490 pthread_mutex_init (&new->status_mutex, NULL);
1493 if (!rc)
1495 #ifdef WITH_GNUTLS
1496 new->remote = addr ? 1 : 0;
1497 #endif
1498 new->fd = fd;
1499 rc = create_thread (client_thread, new, &new->tid, 1);
1500 if (rc)
1502 close (new->status_msg_pipe[0]);
1503 close (new->status_msg_pipe[1]);
1504 pthread_mutex_destroy (&new->status_mutex);
1508 if (!rc)
1510 struct slist_s *list = slist_append (cn_thread_list, new);
1512 if (list)
1514 cn_thread_list = list;
1515 if (addr)
1517 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1518 (pthread_t *) new->tid, fd, addr);
1519 #ifdef WITH_GNUTLS
1520 new->peeraddr = str_dup (addr);
1521 #endif
1523 else
1524 log_write (_("new connection: tid=%p, fd=%i"),
1525 (pthread_t *) new->tid, fd);
1527 else
1528 rc = GPG_ERR_ENOMEM;
1531 pthread_cleanup_pop (1);
1533 if (rc)
1535 xfree (new);
1536 close (fd);
1537 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1538 pwmd_strerror (rc));
1540 return rc;
1543 static void*
1544 keepalive_thread (void *arg)
1546 #ifndef HAVE_PTHREAD_CANCEL
1547 int *n = xmalloc (sizeof (int));
1549 *n = 0;
1550 pthread_setspecific (signal_thread_key, n);
1551 INIT_THREAD_SIGNAL;
1552 #endif
1554 #ifdef HAVE_PR_SET_NAME
1555 prctl (PR_SET_NAME, "keepalive");
1556 #endif
1557 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1559 for (;;)
1561 int n = config_get_integer ("global", "keepalive_interval");
1562 struct timeval tv = { n, 0 };
1563 #ifndef HAVE_PTHREAD_CANCEL
1564 int *sigusr2;
1566 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1567 if (*sigusr2)
1568 break;
1569 #endif
1571 send_status_all (STATUS_KEEPALIVE, NULL);
1572 select (0, NULL, NULL, NULL, &tv);
1575 return NULL;
1578 #ifdef WITH_GNUTLS
1579 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1580 static void *
1581 get_in_addr (struct sockaddr *sa)
1583 if (sa->sa_family == AF_INET)
1584 return &(((struct sockaddr_in *) sa)->sin_addr);
1586 return &(((struct sockaddr_in6 *) sa)->sin6_addr);
1589 static void *
1590 tcp_accept_thread (void *arg)
1592 int sockfd = *(int *) arg;
1593 #ifndef HAVE_PTHREAD_CANCEL
1594 int *n = xmalloc (sizeof (int));
1596 *n = 0;
1597 pthread_setspecific (signal_thread_key, n);
1598 INIT_THREAD_SIGNAL;
1599 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1600 #endif
1602 #ifdef HAVE_PR_SET_NAME
1603 prctl (PR_SET_NAME, "tcp_accept");
1604 #endif
1605 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1607 for (;;)
1609 struct sockaddr_storage raddr;
1610 socklen_t slen = sizeof (raddr);
1611 int fd;
1612 unsigned long n;
1613 char s[INET6_ADDRSTRLEN];
1614 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1615 #ifndef HAVE_PTHREAD_CANCEL
1616 int *sigusr2;
1618 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1619 if (*sigusr2)
1620 break;
1621 #endif
1623 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1624 if (fd == -1)
1626 if (errno == EMFILE || errno == ENFILE)
1627 log_write ("accept(): %s",
1628 pwmd_strerror (gpg_error_from_errno (errno)));
1629 else if (errno != EAGAIN)
1631 if (!quit) // probably EBADF
1632 log_write ("accept(): %s", strerror (errno));
1634 break;
1637 #ifndef HAVE_PTHREAD_CANCEL
1638 select (0, NULL, NULL, NULL, &tv);
1639 #endif
1640 continue;
1643 if (quit)
1644 break;
1646 inet_ntop (raddr.ss_family, get_in_addr ((struct sockaddr *) &raddr),
1647 s, sizeof s);
1648 (void) init_client (fd, s);
1649 n = config_get_integer ("global", "tcp_wait");
1650 if (n > 0)
1652 tv.tv_sec = (n * 100000) / 100000;
1653 tv.tv_usec = (n * 100000) % 100000;
1654 select (0, NULL, NULL, NULL, &tv);
1658 return NULL;
1661 static int
1662 start_stop_tls_with_protocol (int ipv6, int term)
1664 struct addrinfo hints, *servinfo, *p;
1665 int port = config_get_integer ("global", "tcp_port");
1666 char buf[7];
1667 int n;
1668 gpg_error_t rc;
1669 int *fd = ipv6 ? &tls6_fd : &tls_fd;
1671 if (term || config_get_boolean ("global", "enable_tcp") == 0)
1673 if (tls6_fd != -1)
1675 if (spawned_tls6)
1677 #ifdef HAVE_PTHREAD_CANCEL
1678 pthread_cancel (tls6_tid);
1679 #else
1680 pthread_kill (tls6_tid, SIGUSR2);
1681 #endif
1682 pthread_join (tls6_tid, NULL);
1685 shutdown (tls6_fd, SHUT_RDWR);
1686 close (tls6_fd);
1687 tls6_fd = -1;
1688 spawned_tls6 = 0;
1691 if (tls_fd != -1)
1693 if (spawned_tls)
1695 #ifdef HAVE_PTHREAD_CANCEL
1696 pthread_cancel (tls_tid);
1697 #else
1698 pthread_kill (tls_tid, SIGUSR2);
1699 #endif
1700 pthread_join (tls_tid, NULL);
1703 shutdown (tls_fd, SHUT_RDWR);
1704 close (tls_fd);
1705 tls_fd = -1;
1706 spawned_tls = 0;
1709 /* A client may still be connected. */
1710 if (!quit && x509_cred != NULL)
1711 tls_deinit_params ();
1713 return 1;
1716 if ((ipv6 && tls6_fd != -1) || (!ipv6 && tls_fd != -1))
1717 return 1;
1719 memset (&hints, 0, sizeof (hints));
1720 hints.ai_family = ipv6 ? AF_INET6 : AF_INET;
1721 hints.ai_socktype = SOCK_STREAM;
1722 hints.ai_flags = AI_PASSIVE;
1723 snprintf (buf, sizeof (buf), "%i", port);
1725 if ((n = getaddrinfo (NULL, buf, &hints, &servinfo)) == -1)
1727 log_write ("getaddrinfo(): %s", gai_strerror (n));
1728 return 0;
1731 for (n = 0, p = servinfo; p != NULL; p = p->ai_next)
1733 int r = 1;
1735 if ((ipv6 && p->ai_family != AF_INET6)
1736 || (!ipv6 && p->ai_family != AF_INET))
1737 continue;
1739 if ((*fd = socket (p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
1741 log_write ("socket(): %s", strerror (errno));
1742 continue;
1745 if (setsockopt (*fd, SOL_SOCKET, SO_REUSEADDR, &r, sizeof (int)) == -1)
1747 log_write ("setsockopt(): %s",
1748 pwmd_strerror (gpg_error_from_errno (errno)));
1749 freeaddrinfo (servinfo);
1750 goto fail;
1753 if (bind (*fd, p->ai_addr, p->ai_addrlen) == -1)
1755 close (*fd);
1756 log_write ("bind(): %s",
1757 pwmd_strerror (gpg_error_from_errno (errno)));
1758 continue;
1761 n++;
1762 break;
1765 freeaddrinfo (servinfo);
1767 if (!n)
1768 goto fail;
1770 #if HAVE_DECL_SO_BINDTODEVICE != 0
1771 char *tmp = config_get_string ("global", "tcp_interface");
1772 if (tmp && setsockopt (*fd, SOL_SOCKET, SO_BINDTODEVICE, tmp,
1773 strlen (tmp)) == -1)
1775 log_write ("setsockopt(): %s",
1776 pwmd_strerror (gpg_error_from_errno (errno)));
1777 xfree (tmp);
1778 goto fail;
1781 xfree (tmp);
1782 #endif
1784 if (x509_cred == NULL)
1786 rc = tls_init_params ();
1787 if (rc)
1788 goto fail;
1791 if (listen (*fd, 0) == -1)
1793 log_write ("listen(): %s", strerror (errno));
1794 goto fail;
1797 if (ipv6)
1798 rc = create_thread (tcp_accept_thread, fd, &tls6_tid, 0);
1799 else
1800 rc = create_thread (tcp_accept_thread, fd, &tls_tid, 0);
1802 if (rc)
1804 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1805 pwmd_strerror (rc));
1806 goto fail;
1809 if (ipv6)
1810 spawned_tls6 = 1;
1811 else
1812 spawned_tls = 1;
1814 return 1;
1816 fail:
1817 start_stop_tls_with_protocol (0, 1);
1818 if (tls_fd != -1)
1819 close (tls_fd);
1821 if (tls6_fd != -1)
1822 close (tls6_fd);
1824 tls_fd = -1;
1825 tls6_fd = -1;
1826 return 0;
1829 static int
1830 start_stop_tls (int term)
1832 char *s = config_get_string ("global", "tcp_bind");
1833 int b;
1835 if (!s)
1836 return 0;
1838 if (!strcmp (s, "any"))
1840 b = start_stop_tls_with_protocol (0, term);
1841 if (b)
1842 b = start_stop_tls_with_protocol (1, term);
1844 else if (!strcmp (s, "ipv4"))
1845 b = start_stop_tls_with_protocol (0, term);
1846 else if (!strcmp (s, "ipv6"))
1847 b = start_stop_tls_with_protocol (1, term);
1848 else
1849 b = 0;
1851 xfree (s);
1852 return b;
1854 #endif
1856 static void *
1857 accept_thread (void *arg)
1859 int sockfd = *(int *) arg;
1860 #ifndef HAVE_PTHREAD_CANCEL
1861 int *n = xmalloc (sizeof (int));
1863 *n = 0;
1864 pthread_setspecific (signal_thread_key, n);
1865 INIT_THREAD_SIGNAL;
1866 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1867 #endif
1869 #ifdef HAVE_PR_SET_NAME
1870 prctl (PR_SET_NAME, "accept");
1871 #endif
1872 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1874 for (;;)
1876 socklen_t slen = sizeof (struct sockaddr_un);
1877 struct sockaddr_un raddr;
1878 int fd;
1879 #ifndef HAVE_PTHREAD_CANCEL
1880 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1881 int *sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1883 if (*sigusr2)
1884 break;
1885 #endif
1887 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1888 if (fd == -1)
1890 if (errno == EMFILE || errno == ENFILE)
1891 log_write ("accept(): %s",
1892 pwmd_strerror (gpg_error_from_errno (errno)));
1893 else if (errno != EAGAIN)
1895 if (!quit) // probably EBADF
1896 log_write ("accept(): %s",
1897 pwmd_strerror (gpg_error_from_errno (errno)));
1899 break;
1902 #ifndef HAVE_PTHREAD_CANCEL
1903 select (0, NULL, NULL, NULL, &tv);
1904 #endif
1905 continue;
1908 (void) init_client (fd, NULL);
1911 /* Just in case accept() failed for some reason other than EBADF */
1912 quit = 1;
1913 return NULL;
1916 static void *
1917 cache_timer_thread (void *arg)
1919 #ifndef HAVE_PTHREAD_CANCEL
1920 int *n = xmalloc (sizeof (int));
1922 *n = 0;
1923 pthread_setspecific (signal_thread_key, n);
1924 INIT_THREAD_SIGNAL;
1925 #endif
1927 #ifdef HAVE_PR_SET_NAME
1928 prctl (PR_SET_NAME, "cache timer");
1929 #endif
1930 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1932 for (;;)
1934 struct timeval tv = { 1, 0 };
1935 #ifndef HAVE_PTHREAD_CANCEL
1936 int *n;
1938 n = (int *) pthread_getspecific (signal_thread_key);
1939 if (*n)
1940 break;
1941 #endif
1943 select (0, NULL, NULL, NULL, &tv);
1944 cache_adjust_timeout ();
1947 return NULL;
1950 static int
1951 signal_loop (sigset_t sigset)
1953 int done = 0;
1954 int siint = 0;
1958 int sig;
1960 sigwait (&sigset, &sig);
1962 if (sig != SIGQUIT)
1963 log_write (_("caught signal %i (%s)"), sig, strsignal (sig));
1965 switch (sig)
1967 case SIGHUP:
1968 pthread_cond_signal (&rcfile_cond);
1969 break;
1970 case SIGUSR1:
1971 log_write (_("clearing file cache"));
1972 cache_clear (NULL);
1973 send_status_all (STATUS_CACHE, NULL);
1974 break;
1975 case SIGQUIT:
1976 done = 1;
1977 break;
1978 default:
1979 siint = 1;
1980 done = 1;
1981 break;
1984 while (!done);
1986 return siint;
1989 static void
1990 catchsig (int sig)
1992 log_write (_ ("Caught signal %i (%s). Exiting."), sig, strsignal (sig));
1993 #ifdef HAVE_BACKTRACE
1994 BACKTRACE (__FUNCTION__);
1995 #endif
1996 longjmp (jmp, 1);
1999 static void *
2000 waiting_for_exit (void *arg)
2002 int last = 0;
2003 #ifndef HAVE_PTHREAD_CANCEL
2004 int *n = xmalloc (sizeof (int));
2006 *n = 0;
2007 pthread_setspecific (signal_thread_key, n);
2008 INIT_THREAD_SIGNAL;
2009 #endif
2011 #ifdef HAVE_PR_SET_NAME
2012 prctl (PR_SET_NAME, "exiting");
2013 #endif
2014 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
2015 log_write (_("waiting for all clients to disconnect"));
2016 MUTEX_LOCK (&quit_mutex);
2017 pthread_cleanup_push (cleanup_mutex_cb, &quit_mutex);
2019 for (;;)
2021 struct timespec ts;
2022 int n;
2024 MUTEX_LOCK (&cn_mutex);
2025 n = slist_length (cn_thread_list);
2026 MUTEX_UNLOCK (&cn_mutex);
2027 if (!n)
2028 break;
2030 #ifndef HAVE_PTHREAD_CANCEL
2031 int *s = (int *) pthread_getspecific (signal_thread_key);
2032 if (*s)
2033 break;
2034 #endif
2036 if (last != n)
2038 log_write (_("%i clients remain"), n);
2039 last = n;
2042 INIT_TIMESPEC (SIG_TIMEOUT, ts);
2043 pthread_cond_timedwait (&quit_cond, &quit_mutex, &ts);
2046 kill (getpid (), SIGQUIT);
2047 pthread_cleanup_pop (1);
2048 return NULL;
2051 static int
2052 server_loop (int sockfd, char **socketpath)
2054 pthread_t accept_tid;
2055 pthread_t cache_timeout_tid;
2056 int cancel_timeout_thread = 0, cancel_accept_thread = 0;
2057 int cancel_keepalive_thread = 0;
2058 sigset_t sigset;
2059 int n;
2060 int segv = 0;
2061 gpg_error_t rc;
2063 init_commands ();
2064 sigemptyset (&sigset);
2066 /* Termination */
2067 sigaddset (&sigset, SIGTERM);
2068 sigaddset (&sigset, SIGINT);
2070 /* Clears the file cache. */
2071 sigaddset (&sigset, SIGUSR1);
2073 /* Configuration file reloading. */
2074 sigaddset (&sigset, SIGHUP);
2076 /* For exiting cleanly. */
2077 sigaddset (&sigset, SIGQUIT);
2079 #ifndef HAVE_PTHREAD_CANCEL
2081 The socket, cache and rcfile threads use this signal when
2082 pthread_cancel() is unavailable. Prevent the main thread from
2083 catching this signal from another process.
2085 sigaddset (&sigset, SIGUSR2);
2086 #endif
2088 /* When mem.c cannot find a pointer in the list (double free). */
2089 signal (SIGABRT, catchsig);
2090 sigaddset (&sigset, SIGABRT);
2091 sigprocmask (SIG_BLOCK, &sigset, NULL);
2093 #ifndef HAVE_PTHREAD_CANCEL
2094 /* Remove this signal from the watched signals in signal_loop(). */
2095 sigdelset (&sigset, SIGUSR2);
2096 #endif
2098 /* Ignored everywhere. When a client disconnects abnormally this signal
2099 * gets raised. It isn't needed though because client_thread() will check
2100 * for rcs even after the client disconnects. */
2101 signal (SIGPIPE, SIG_IGN);
2103 /* Can show a backtrace of the stack in the log. */
2104 signal (SIGSEGV, catchsig);
2106 #ifdef WITH_GNUTLS
2107 /* Needs to be done after the fork(). */
2108 if (!start_stop_tls (0))
2110 segv = 1;
2111 goto done;
2113 #endif
2115 pthread_mutex_init (&quit_mutex, NULL);
2116 pthread_cond_init (&quit_cond, NULL);
2117 char *p = get_username (getuid());
2118 log_write (_("%s started for user %s"), PACKAGE_STRING, p);
2119 xfree (p);
2121 #ifdef WITH_GNUTLS
2122 if (config_get_boolean ("global", "enable_tcp"))
2123 log_write (_("Listening on %s and TCP port %i as user %i"), *socketpath,
2124 config_get_integer ("global", "tcp_port"), invoking_uid);
2125 else
2126 log_write (_("Listening on %s"), *socketpath);
2127 #else
2128 log_write (_("Listening on %s"), *socketpath);
2129 #endif
2131 rc = create_thread (keepalive_thread, NULL, &keepalive_tid, 0);
2132 if (rc)
2134 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2135 pwmd_strerror (rc));
2136 goto done;
2139 cancel_keepalive_thread = 1;
2140 rc = create_thread (reload_rcfile_thread, NULL, &rcfile_tid, 0);
2141 if (rc)
2143 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2144 pwmd_strerror (rc));
2145 goto done;
2148 rc = create_thread (cache_timer_thread, NULL, &cache_timeout_tid, 0);
2149 if (rc)
2151 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2152 pwmd_strerror (rc));
2153 goto done;
2156 cancel_timeout_thread = 1;
2157 rc = create_thread (accept_thread, &sockfd, &accept_tid, 0);
2158 if (rc)
2160 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2161 pwmd_strerror (rc));
2162 goto done;
2165 cancel_accept_thread = 1;
2166 if (!setjmp (jmp))
2167 signal_loop (sigset);
2168 else
2169 segv = 1;
2171 done:
2173 * We're out of the main server loop. This happens when a signal was sent
2174 * to terminate the daemon. We'll wait for all clients to disconnect
2175 * before exiting but exit immediately if another termination signal is
2176 * sent.
2178 if (cancel_accept_thread)
2180 #ifdef HAVE_PTHREAD_CANCEL
2181 int n = pthread_cancel (accept_tid);
2182 #else
2183 int n = pthread_kill (accept_tid, SIGUSR2);
2184 #endif
2185 if (!n)
2186 pthread_join (accept_tid, NULL);
2189 #ifdef WITH_GNUTLS
2190 start_stop_tls (1);
2191 #endif
2192 shutdown (sockfd, SHUT_RDWR);
2193 close (sockfd);
2194 unlink (*socketpath);
2195 xfree (*socketpath);
2196 *socketpath = NULL;
2197 MUTEX_LOCK (&cn_mutex);
2198 n = slist_length (cn_thread_list);
2199 MUTEX_UNLOCK (&cn_mutex);
2201 if (n && !segv)
2203 pthread_t tid;
2205 rc = create_thread (waiting_for_exit, NULL, &tid, 0);
2206 if (!rc)
2208 if (signal_loop (sigset))
2210 log_write (_("Received second termination request. Exiting."));
2211 #ifdef HAVE_PTHREAD_CANCEL
2212 pthread_cancel (tid);
2213 #else
2214 pthread_kill (tid, SIGUSR2);
2215 #endif
2216 pthread_join (tid, NULL);
2219 else
2220 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2221 pwmd_strerror (rc));
2224 if (cancel_timeout_thread)
2226 #ifdef HAVE_PTHREAD_CANCEL
2227 pthread_cancel (cache_timeout_tid);
2228 #else
2229 pthread_kill (cache_timeout_tid, SIGUSR2);
2230 #endif
2231 pthread_join (cache_timeout_tid, NULL);
2234 if (cancel_keepalive_thread)
2236 #ifdef HAVE_PTHREAD_CANCEL
2237 pthread_cancel (keepalive_tid);
2238 #else
2239 pthread_kill (keepalive_tid, SIGUSR2);
2240 #endif
2241 pthread_join (keepalive_tid, NULL);
2244 cleanup_all_clients (0);
2245 #ifdef WITH_GNUTLS
2246 start_stop_tls (1);
2247 #endif
2248 deinit_commands ();
2249 pthread_cond_destroy (&quit_cond);
2250 pthread_mutex_destroy (&quit_mutex);
2251 return segv ? EXIT_FAILURE : EXIT_SUCCESS;;
2254 static void
2255 startup_failure ()
2257 log_write (_
2258 ("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
2259 cache_clear (NULL);
2262 /* This is called from cache.c:clear_once(). See
2263 * command.c:clearcache_command() for details about lock checking.
2265 static gpg_error_t
2266 free_cache_data (file_cache_t * cache)
2268 gpg_error_t rc = GPG_ERR_NO_DATA;
2269 int i, t;
2270 struct client_thread_s *found = NULL;
2271 int self = 0;
2273 if (!cache->data)
2274 return 0;
2276 cache_lock ();
2277 MUTEX_LOCK (&cn_mutex);
2278 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
2279 t = slist_length (cn_thread_list);
2281 for (i = 0; i < t; i++)
2283 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2285 if (!thd->cl)
2286 continue;
2288 if (!memcmp (thd->cl->md5file, cache->filename,
2289 sizeof (cache->filename)))
2291 if (pthread_equal (pthread_self (), thd->tid))
2293 found = thd;
2294 self = 1;
2295 continue;
2298 /* Continue trying to find a client who has the same file open and
2299 * also has a lock. */
2300 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0, -1);
2301 if (!rc)
2303 self = 0;
2304 found = thd;
2305 break;
2310 if (self && (!rc || rc == GPG_ERR_NO_DATA))
2311 rc = cache_lock_mutex (found->cl->ctx, found->cl->md5file, -1, 0, -1);
2313 if (exiting || !rc || rc == GPG_ERR_NO_DATA)
2315 free_cache_data_once (cache->data);
2316 cache->data = NULL;
2317 cache->defer_clear = 0;
2318 cache->timeout = -1;
2320 if (found)
2321 cache_unlock_mutex (found->cl->md5file, 0);
2323 rc = 0;
2326 if (rc)
2327 cache->defer_clear = 1;
2329 pthread_cleanup_pop (1);
2330 cache_unlock ();
2331 return rc;
2334 static int
2335 convert_v2_datafile (const char *filename, const char *cipher,
2336 const char *keyfile, const char *keygrip,
2337 const char *sign_keygrip, int nopass,
2338 const char *outfile, const char *keyparam,
2339 unsigned long s2k_count, uint64_t iterations)
2341 gpg_error_t rc;
2342 void *data = NULL;
2343 size_t datalen;
2344 struct crypto_s *crypto = NULL;
2345 uint16_t ver;
2346 int algo;
2347 void *key = NULL;
2348 size_t keylen = 0;
2350 if (outfile[0] == '-' && outfile[1] == 0)
2351 outfile = NULL;
2353 log_write (_("Converting version 2 data file \"%s\" ..."), filename);
2354 if (access (filename, R_OK) == -1)
2356 log_write ("%s: %s", filename,
2357 pwmd_strerror (gpg_error_from_errno (errno)));
2358 return 0;
2361 if (keyfile)
2363 log_write (_("Using passphrase file \"%s\" for decryption ..."),
2364 keyfile);
2365 if (access (keyfile, R_OK) == -1)
2367 log_write ("%s: %s", keyfile,
2368 pwmd_strerror (gpg_error_from_errno (errno)));
2369 return 0;
2373 rc = read_v2_datafile (filename, keyfile, &data, &datalen, &ver, &algo);
2374 if (rc)
2376 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2377 return 0;
2380 if (cipher)
2382 algo = cipher_string_to_gcrypt (cipher);
2383 if (algo == -1)
2385 rc = GPG_ERR_CIPHER_ALGO;
2386 goto fail;
2390 if (ver < 0x212)
2392 xmlDocPtr doc;
2394 rc = parse_doc (data, datalen, &doc);
2395 if (rc)
2396 goto fail;
2398 rc = convert_pre_212_elements (doc);
2399 gcry_free (data);
2400 data = NULL;
2401 if (!rc)
2403 xmlDocDumpFormatMemory (doc, (xmlChar **) & data, (int *) &datalen,
2405 if (!data)
2406 rc = GPG_ERR_ENOMEM;
2409 xmlFreeDoc (doc);
2410 if (rc)
2411 goto fail;
2414 rc = init_client_crypto (&crypto);
2415 if (!rc)
2417 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
2418 crypto->save.hdr.flags = set_cipher_flag (crypto->save.hdr.flags, algo);
2419 crypto->save.s2k_count = s2k_count;
2420 crypto->save.hdr.iterations = iterations;
2422 if (!use_agent)
2424 rc = export_common (NULL, 0, crypto, data, datalen, outfile, keyfile,
2425 &key, &keylen, 0, 0, nopass);
2427 #ifdef WITH_AGENT
2428 else
2430 rc = agent_set_pinentry_options (crypto->agent);
2431 if (!rc)
2432 rc = agent_export_common (crypto, keygrip, sign_keygrip, nopass,
2433 data, datalen, outfile, keyparam,
2434 no_passphrase_file ? NULL : keyfile);
2436 #endif
2437 if (!rc)
2438 log_write (_("Output written to \"%s\"."), outfile);
2441 fail:
2442 if (ver < 0x212)
2443 xmlFree (data);
2444 else
2445 gcry_free (data);
2447 gcry_free (key);
2448 cleanup_crypto (&crypto);
2450 if (rc)
2451 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2452 return rc ? 0 : 1;
2455 static void
2456 usage (const char *pn, int status)
2458 FILE *fp = status == EXIT_FAILURE ? stderr : stdout;
2460 fprintf (fp, _("Usage: %s [OPTIONS] [file1] [...]\n"
2461 " -f, --rcfile=filename load the specfied configuration file\n"
2462 " (~/.pwmd/config)\n"
2463 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2464 " --kill terminate an existing instance of pwmd\n"
2465 #ifdef WITH_AGENT
2466 " --use-agent enable use of gpg-agent\n"
2467 #endif
2468 " -n, --no-fork run as a foreground process\n"
2469 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2470 " --ignore, --force ignore file errors during startup\n"
2471 " --debug-level=keywords log protocol output (see manual for details)\n"
2472 " -o, --outfile=filename output file when importing or converting\n"
2473 " -C, --convert=filename convert a version 2 data file to version 3\n"
2474 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2475 " -k, --passphrase-file=file for use when importing or converting\n"
2476 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2477 " converting\n"
2478 " --no-passphrase when importing or converting\n"
2479 " --keygrip=hex public key to use when encrypting\n"
2480 " --sign-keygrip=hex private key to use when signing\n"
2481 " --keyparam=s-exp custom key parameters to use (RSA-2048)\n"
2482 " --cipher=string encryption cipher (aes256)\n"
2483 " --cipher-iterations=N cipher iteration count (N+1)\n"
2484 " --s2k-count=N hash iteration count (>65536, calibrated)\n"
2485 " --help this help text\n"
2486 " --version show version and compile time features\n"),
2487 pn);
2488 exit (status);
2491 static void
2492 unlink_stale_socket (const char *sock, const char *pidfile)
2494 log_write (_ ("removing stale socket %s"), sock);
2495 unlink (sock);
2496 unlink (pidfile);
2499 static int
2500 test_pidfile (const char *path, const char *sock, char *buf, size_t buflen,
2501 char **pidfile, int create, mode_t mode, int terminate)
2503 pid_t pid;
2504 int fd;
2505 size_t len;
2507 if (!create)
2509 snprintf (buf, buflen, "%s/%s.pid", homedir, sock);
2510 *pidfile = str_dup (buf);
2511 fd = open (buf, O_RDONLY);
2513 else
2514 fd = open (*pidfile, O_CREAT|O_WRONLY|O_TRUNC, mode);
2516 if (fd == -1)
2518 if (!create && errno != ENOENT)
2520 log_write ("%s: %s", buf, pwmd_strerror (errno));
2521 free (*pidfile);
2522 *pidfile = NULL;
2523 return -1;
2525 else if (!create && !terminate)
2526 return 0;
2528 log_write ("%s: %s", *pidfile, strerror (errno));
2529 return -1;
2532 if (create)
2534 snprintf (buf, buflen, "%i", getpid ());
2535 write (fd, buf, strlen (buf));
2536 close (fd);
2537 return 0;
2540 len = read (fd, buf, sizeof(buf));
2541 close (fd);
2542 if (len == 0)
2544 unlink_stale_socket (path, *pidfile);
2545 return 0;
2548 if (sscanf (buf, "%5i", &pid) != 1 || pid == 0)
2550 if (!terminate)
2552 unlink_stale_socket (path, *pidfile);
2553 return 0;
2557 if (kill (pid, 0) == -1)
2559 unlink_stale_socket (path, *pidfile);
2560 return 0;
2563 if (terminate)
2565 if (kill (pid, SIGTERM) == -1)
2566 log_write ("%s: %s", path, pwmd_strerror (errno));
2568 else
2569 log_write (_ ("an instance for socket %s is already running"), path);
2571 xfree (*pidfile);
2572 *pidfile = NULL;
2573 return 1;
2577 main (int argc, char *argv[])
2579 int opt;
2580 struct sockaddr_un addr;
2581 char buf[PATH_MAX];
2582 char *socketpath = NULL, *socketdir, *socketname = NULL;
2583 char *socketarg = NULL;
2584 char *datadir = NULL;
2585 char *pidfile = NULL;
2586 mode_t mode = 0600;
2587 int x;
2588 char *p;
2589 char **cache_push = NULL;
2590 char *import = NULL, *keygrip = NULL, *sign_keygrip = NULL;
2591 char *keyparam = NULL;
2592 int estatus = EXIT_FAILURE;
2593 int sockfd;
2594 char *outfile = NULL;
2595 int do_unlink = 0;
2596 int secure = 0;
2597 int show_version = 0;
2598 int force = 0;
2599 int no_passphrase = 0;
2600 gpg_error_t rc;
2601 char *convertfile = NULL;
2602 char *cipher = NULL;
2603 char *keyfile = NULL;
2604 unsigned long s2k_count = 0;
2605 uint64_t iterations = 0;
2606 int exists;
2607 char *debug_level_opt = NULL;
2608 int optindex;
2609 int terminate = 0;
2610 /* Must maintain the same order as longopts[] */
2611 enum
2613 OPT_VERSION, OPT_HELP,
2614 #ifdef WITH_AGENT
2615 OPT_AGENT,
2616 #endif
2617 OPT_DEBUG_LEVEL, OPT_HOMEDIR, OPT_NO_FORK, OPT_DISABLE_DUMP,
2618 OPT_IGNORE, OPT_FORCE, OPT_RCFILE, OPT_CONVERT,
2619 OPT_PASSPHRASE_FILE, OPT_IMPORT, OPT_OUTFILE,
2620 OPT_NO_PASSPHRASE_FILE, OPT_KEYGRIP, OPT_SIGN_KEYGRIP,
2621 OPT_KEYPARAM, OPT_CIPHER, OPT_ITERATIONS, OPT_S2K_COUNT,
2622 OPT_NO_PASSPHRASE, OPT_KILL
2624 const char *optstring = "nf:C:k:I:o:";
2625 const struct option longopts[] = {
2626 {"version", no_argument, 0, 0},
2627 {"help", no_argument, 0, 0},
2628 #ifdef WITH_AGENT
2629 {"use-agent", no_argument, 0, 0},
2630 #endif
2631 {"debug-level", required_argument, 0, 0},
2632 {"homedir", required_argument, 0, 0},
2633 {"no-fork", no_argument, 0, 'n'},
2634 {"disable_dump", no_argument, 0, 0},
2635 {"ignore", no_argument, 0, 0},
2636 {"force", no_argument, 0, 0},
2637 {"rcfile", required_argument, 0, 'f'},
2638 {"convert", required_argument, 0, 'C'},
2639 {"passphrase-file", required_argument, 0, 'k'},
2640 {"import", required_argument, 0, 'I'},
2641 {"outfile", required_argument, 0, 'o'},
2642 {"no-passphrase-file", no_argument, 0, 0},
2643 {"keygrip", required_argument, 0, 0},
2644 {"sign-keygrip", required_argument, 0, 0},
2645 {"keyparam", required_argument, 0, 0},
2646 {"cipher", required_argument, 0, 0},
2647 {"cipher-iterations", required_argument, 0, 0},
2648 {"s2k-count", required_argument, 0, 0},
2649 {"no-passphrase", no_argument, 0, 0},
2650 {"kill", no_argument, 0, 0},
2651 {0, 0, 0, 0}
2654 log_fd = -1;
2656 #ifndef DEBUG
2657 #ifdef HAVE_SETRLIMIT
2658 struct rlimit rl;
2660 rl.rlim_cur = rl.rlim_max = 0;
2662 if (setrlimit (RLIMIT_CORE, &rl) != 0)
2663 err (EXIT_FAILURE, "setrlimit()");
2664 #endif
2666 #ifdef HAVE_PR_SET_DUMPABLE
2667 prctl (PR_SET_DUMPABLE, 0);
2668 #endif
2669 #endif
2671 #ifdef ENABLE_NLS
2672 setlocale (LC_ALL, "");
2673 bindtextdomain ("pwmd", LOCALEDIR);
2674 textdomain ("pwmd");
2675 #endif
2677 #ifndef MEM_DEBUG
2678 xmem_init ();
2679 #endif
2680 gpg_err_init ();
2682 if (setup_crypto ())
2683 exit (EXIT_FAILURE);
2685 #ifdef WITH_GNUTLS
2686 gnutls_global_set_mem_functions (xmalloc, xmalloc, secure_mem_check,
2687 xrealloc, xfree);
2688 gnutls_global_init ();
2689 gnutls_global_set_log_function (tls_log);
2690 gnutls_global_set_log_level (1);
2691 tls_fd = -1;
2692 tls6_fd = -1;
2693 #endif
2694 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
2695 xmlInitMemory ();
2696 xmlInitGlobals ();
2697 xmlInitParser ();
2698 xmlXPathInit ();
2699 cmdline = 1;
2700 use_agent = 0;
2702 while ((opt = getopt_long (argc, argv, optstring, longopts, &optindex))
2703 != -1)
2705 switch (opt)
2707 case 'I':
2708 import = optarg;
2709 break;
2710 case 'C':
2711 convertfile = optarg;
2712 break;
2713 case 'k':
2714 keyfile = optarg;
2715 break;
2716 case 'o':
2717 outfile = optarg;
2718 break;
2719 case 'D':
2720 secure = 1;
2721 break;
2722 case 'n':
2723 nofork = 1;
2724 break;
2725 case 'f':
2726 rcfile = str_dup (optarg);
2727 break;
2728 default:
2729 usage (argv[0], EXIT_FAILURE);
2730 break;
2731 case 0:
2732 switch (optindex)
2734 case OPT_VERSION:
2735 show_version = 1;
2736 break;
2737 case OPT_HELP:
2738 usage (argv[0], 0);
2739 break;
2740 #ifdef WITH_AGENT
2741 case OPT_AGENT:
2742 use_agent = 1;
2743 break;
2744 #endif
2745 case OPT_DEBUG_LEVEL:
2746 debug_level_opt = optarg;
2747 break;
2748 case OPT_HOMEDIR:
2749 homedir = str_dup (optarg);
2750 break;
2751 case OPT_NO_FORK:
2752 nofork = 1;
2753 break;
2754 case OPT_DISABLE_DUMP:
2755 secure = 1;
2756 break;
2757 case OPT_IGNORE:
2758 case OPT_FORCE:
2759 force = 1;
2760 break;
2761 case OPT_RCFILE:
2762 rcfile = str_dup (optarg);
2763 break;
2764 case OPT_CONVERT:
2765 convertfile = optarg;
2766 break;
2767 case OPT_PASSPHRASE_FILE:
2768 keyfile = optarg;
2769 break;
2770 case OPT_IMPORT:
2771 import = optarg;
2772 break;
2773 case OPT_OUTFILE:
2774 outfile = optarg;
2775 break;
2776 case OPT_NO_PASSPHRASE_FILE:
2777 no_passphrase_file = 1;
2778 break;
2779 case OPT_KEYGRIP:
2780 keygrip = optarg;
2781 break;
2782 case OPT_SIGN_KEYGRIP:
2783 sign_keygrip = optarg;
2784 break;
2785 case OPT_KEYPARAM:
2786 keyparam = optarg;
2787 break;
2788 case OPT_CIPHER:
2789 cipher = optarg;
2790 break;
2791 case OPT_ITERATIONS:
2792 iterations = strtoull (optarg, NULL, 10);
2793 break;
2794 case OPT_S2K_COUNT:
2795 s2k_count = strtoul (optarg, NULL, 10);
2796 break;
2797 case OPT_NO_PASSPHRASE:
2798 no_passphrase = 1;
2799 break;
2800 case OPT_KILL:
2801 terminate = 1;
2802 break;
2803 default:
2804 usage (argv[0], 1);
2809 if (show_version)
2811 printf (_("%s\n\n"
2812 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015\n"
2813 "%s\n"
2814 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2815 "Compile time features:\n%s"), PACKAGE_STRING,
2816 PACKAGE_BUGREPORT,
2817 #ifdef PWMD_HOMEDIR
2818 "+PWMD_HOMEDIR=" PWMD_HOMEDIR "\n"
2819 #endif
2820 #ifdef WITH_AGENT
2821 "+WITH_AGENT\n"
2822 #else
2823 "-WITH_AGENT\n"
2824 #endif
2825 #ifdef WITH_QUALITY
2826 "+WITH_QUALITY\n"
2827 #else
2828 "-WITH_QUALITY\n"
2829 #endif
2830 #ifdef WITH_GNUTLS
2831 "+WITH_GNUTLS\n"
2832 #else
2833 "-WITH_GNUTLS\n"
2834 #endif
2835 #ifdef DEBUG
2836 "+DEBUG\n"
2837 #else
2838 "-DEBUG\n"
2839 #endif
2840 #ifdef MEM_DEBUG
2841 "+MEM_DEBUG\n"
2842 #else
2843 "-MEM_DEBUG\n"
2844 #endif
2845 #ifdef MUTEX_DEBUG
2846 "+MUTEX_DEBUG\n"
2847 #else
2848 "-MUTEX_DEBUG\n"
2849 #endif
2851 exit (EXIT_SUCCESS);
2854 if (!homedir)
2855 #ifdef PWMD_HOMEDIR
2856 homedir = str_dup(PWMD_HOMEDIR);
2857 #else
2858 homedir = str_asprintf ("%s/.pwmd", get_home_dir());
2859 #endif
2861 if (mkdir (homedir, 0700) == -1 && errno != EEXIST)
2862 err (EXIT_FAILURE, "%s", homedir);
2864 snprintf (buf, sizeof (buf), "%s/data", homedir);
2865 if (mkdir (buf, 0700) == -1 && errno != EEXIST)
2866 err (EXIT_FAILURE, "%s", buf);
2868 datadir = str_dup (buf);
2869 pthread_mutexattr_t attr;
2870 pthread_mutexattr_init (&attr);
2871 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
2872 pthread_mutex_init (&rcfile_mutex, &attr);
2873 pthread_cond_init (&rcfile_cond, NULL);
2874 pthread_mutex_init (&cn_mutex, &attr);
2875 pthread_mutexattr_destroy (&attr);
2876 pthread_key_create (&last_error_key, free_key);
2877 #ifndef HAVE_PTHREAD_CANCEL
2878 pthread_key_create (&signal_thread_key, free_key);
2879 #endif
2881 if (!rcfile)
2882 rcfile = str_asprintf ("%s/config", homedir);
2884 global_config = config_parse (rcfile);
2885 if (!global_config)
2886 exit (EXIT_FAILURE);
2888 #ifdef WITH_AGENT
2889 if (!use_agent)
2890 use_agent = config_get_boolean ("global", "use_agent");
2891 #endif
2893 setup_logging ();
2895 if (debug_level_opt)
2896 debug_level = str_split (debug_level_opt, ",", 0);
2898 x = config_get_int_param (global_config, "global", "priority", &exists);
2899 if (exists && x != atoi(INVALID_PRIORITY))
2901 errno = 0;
2902 if (setpriority (PRIO_PROCESS, 0, x) == -1)
2904 log_write ("setpriority(): %s",
2905 pwmd_strerror (gpg_error_from_errno (errno)));
2906 goto do_exit;
2909 #ifdef HAVE_MLOCKALL
2910 if (disable_mlock == 0 && mlockall (MCL_CURRENT | MCL_FUTURE) == -1)
2912 log_write ("mlockall(): %s",
2913 pwmd_strerror (gpg_error_from_errno (errno)));
2914 goto do_exit;
2916 #endif
2918 rc = cache_init (free_cache_data);
2919 if (rc)
2921 log_write ("pwmd: ERR %i: %s", rc,
2922 gpg_err_code (rc) == GPG_ERR_UNKNOWN_VERSION
2923 ? _("incompatible gpg-agent version: 2.1.0 or later required")
2924 : pwmd_strerror (rc));
2925 goto do_exit;
2928 if (s2k_count == 0)
2929 s2k_count = config_get_ulong (NULL, "s2k_count");
2931 if (convertfile)
2933 if (!outfile || !*outfile || argc != optind)
2934 usage (argv[0], EXIT_FAILURE);
2936 estatus = convert_v2_datafile (convertfile, cipher, keyfile, keygrip,
2937 sign_keygrip, no_passphrase, outfile,
2938 keyparam, s2k_count, iterations);
2939 config_free (global_config);
2940 xfree (rcfile);
2941 exit (!estatus);
2944 if (import)
2946 if (!outfile || !*outfile || argc != optind)
2947 usage (argv[0], EXIT_FAILURE);
2949 if (outfile && outfile[0] == '-' && outfile[1] == 0)
2950 outfile = NULL;
2952 estatus = xml_import (import, outfile, keygrip, sign_keygrip, keyfile,
2953 no_passphrase, cipher, keyparam, s2k_count,
2954 iterations);
2955 config_free (global_config);
2956 xfree (rcfile);
2957 exit (!estatus);
2960 p = config_get_string ("global", "socket_path");
2961 if (!p)
2962 p = str_asprintf ("%s/socket", homedir);
2964 socketarg = expand_homedir (p);
2965 xfree (p);
2967 if (!secure)
2968 disable_list_and_dump = config_get_boolean ("global",
2969 "disable_list_and_dump");
2970 else
2971 disable_list_and_dump = secure;
2973 cache_push = config_get_list ("global", "cache_push");
2975 while (optind < argc)
2977 if (strv_printf (&cache_push, "%s", argv[optind++]) == 0)
2978 errx (EXIT_FAILURE, "%s", pwmd_strerror (GPG_ERR_ENOMEM));
2981 if (strchr (socketarg, '/') == NULL)
2983 socketdir = getcwd (buf, sizeof (buf));
2984 socketname = str_dup (socketarg);
2985 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2987 else
2989 socketname = str_dup (strrchr (socketarg, '/'));
2990 socketname++;
2991 socketarg[strlen (socketarg) - strlen (socketname) - 1] = 0;
2992 socketdir = str_dup (socketarg);
2993 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2996 if (chdir (datadir))
2998 log_write ("%s: %s", datadir,
2999 pwmd_strerror (gpg_error_from_errno (errno)));
3000 unlink (socketpath);
3001 goto do_exit;
3004 x = test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 0,
3005 mode, terminate);
3006 if (!terminate && x)
3007 goto do_exit;
3008 else if (terminate)
3010 estatus = x != 1 ? EXIT_FAILURE : EXIT_SUCCESS;
3011 goto do_exit;
3015 * bind() doesn't like the full pathname of the socket or any non alphanum
3016 * characters so change to the directory where the socket is wanted then
3017 * create it then change to datadir.
3019 if (chdir (socketdir))
3021 log_write ("%s: %s", socketdir,
3022 pwmd_strerror (gpg_error_from_errno (errno)));
3023 goto do_exit;
3026 xfree (socketdir);
3028 if ((sockfd = socket (PF_UNIX, SOCK_STREAM, 0)) == -1)
3030 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
3031 goto do_exit;
3034 addr.sun_family = AF_UNIX;
3035 snprintf (addr.sun_path, sizeof (addr.sun_path), "%s", socketname);
3036 do_unlink = 1;
3037 if (bind (sockfd, (struct sockaddr *) &addr, sizeof (struct sockaddr)) ==
3040 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
3042 if (errno == EADDRINUSE)
3044 do_unlink = 0;
3045 log_write (_("Either there is another pwmd running or '%s' is a \n"
3046 "stale socket. Please remove it manually."), socketpath);
3049 goto do_exit;
3053 char *t = config_get_string ("global", "socket_perms");
3054 mode_t mask;
3056 if (t)
3058 mode = strtol (t, NULL, 8);
3059 mask = umask (0);
3060 xfree (t);
3062 if (chmod (socketname, mode) == -1)
3064 log_write ("%s: %s", socketname,
3065 pwmd_strerror (gpg_error_from_errno (errno)));
3066 close (sockfd);
3067 umask (mask);
3068 goto do_exit;
3071 umask (mask);
3075 xfree (--socketname);
3077 if (chdir (datadir))
3079 log_write ("%s: %s", datadir,
3080 pwmd_strerror (gpg_error_from_errno (errno)));
3081 close (sockfd);
3082 goto do_exit;
3085 xfree (datadir);
3088 * Set the cache entry for a file. Prompts for the password.
3090 if (cache_push)
3092 struct crypto_s *crypto = NULL;
3093 gpg_error_t rc = init_client_crypto (&crypto);
3095 if (rc)
3097 estatus = EXIT_FAILURE;
3098 goto do_exit;
3101 #ifdef WITH_AGENT
3102 if (use_agent)
3104 rc = agent_set_pinentry_options (crypto->agent);
3105 if (rc)
3107 estatus = EXIT_FAILURE;
3108 goto do_exit;
3111 #endif
3113 for (opt = 0; cache_push[opt]; opt++)
3115 if (!do_cache_push (cache_push[opt], crypto) && !force)
3117 strv_free (cache_push);
3118 startup_failure ();
3119 estatus = EXIT_FAILURE;
3120 cleanup_crypto (&crypto);
3121 goto do_exit;
3124 cleanup_crypto_stage1 (crypto);
3127 #ifdef WITH_AGENT
3128 if (use_agent)
3129 (void) kill_scd (crypto->agent);
3130 #endif
3132 cleanup_crypto (&crypto);
3133 strv_free (cache_push);
3134 log_write (!nofork ? _("Done. Daemonizing...") :
3135 _("Done. Waiting for connections..."));
3138 config_clear_keys ();
3140 if (listen (sockfd, 0) == -1)
3142 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
3143 goto do_exit;
3146 if (!nofork)
3148 switch (fork ())
3150 case -1:
3151 log_write ("fork(): %s",
3152 pwmd_strerror (gpg_error_from_errno (errno)));
3153 goto do_exit;
3154 case 0:
3155 close (0);
3156 close (1);
3157 close (2);
3158 setsid ();
3159 break;
3160 default:
3161 _exit (EXIT_SUCCESS);
3165 (void)test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 1,
3166 mode, 0);
3167 cmdline = 0;
3168 pthread_key_create (&thread_name_key, free_key);
3169 pthread_setspecific (thread_name_key, str_dup ("main"));
3170 estatus = server_loop (sockfd, &socketpath);
3172 do_exit:
3173 if (socketpath && do_unlink)
3175 unlink (socketpath);
3176 xfree (socketpath);
3179 xfree (socketarg);
3180 #ifdef WITH_GNUTLS
3181 gnutls_global_deinit ();
3182 xfree (invoking_tls);
3183 #endif
3184 if (rcfile_tid)
3186 #ifdef HAVE_PTHREAD_CANCEL
3187 pthread_cancel (rcfile_tid);
3188 #else
3189 pthread_kill (rcfile_tid, SIGUSR2);
3190 pthread_cond_signal (&rcfile_cond);
3191 #endif
3192 pthread_join (rcfile_tid, NULL);
3195 pthread_cond_destroy (&rcfile_cond);
3196 pthread_mutex_destroy (&rcfile_mutex);
3197 pthread_key_delete (last_error_key);
3198 #ifndef HAVE_PTHREAD_CANCEL
3199 pthread_key_delete (signal_thread_key);
3200 #endif
3202 if (global_config)
3203 config_free (global_config);
3205 xfree (rcfile);
3206 xfree (home_directory);
3207 xfree (homedir);
3208 xmlCleanupParser ();
3209 xmlCleanupGlobals ();
3211 if (pidfile)
3212 unlink (pidfile);
3213 xfree (pidfile);
3215 if (estatus == EXIT_SUCCESS && !terminate)
3216 log_write (_("pwmd exiting normally"));
3218 pthread_key_delete (thread_name_key);
3219 closelog ();
3220 #if defined(DEBUG) && !defined(MEM_DEBUG)
3221 xdump ();
3222 #endif
3224 if (log_fd != -1)
3225 close (log_fd);
3227 exit (estatus);