Version 3.0.8.
[pwmd.git] / src / pwmd.c
blob830e603193ae39fe44fa1339fe5a4520500dabd4
1 /*
2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014
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->tls = tls_init (cl->thd->fd, cl->thd->timeout, prio);
950 xfree (prio);
951 if (!cl->thd->tls)
952 return 0;
954 #endif
956 rc = assuan_new_ext (&cl->ctx, GPG_ERR_SOURCE_DEFAULT, &mhooks,
957 debug_level ? assuan_log_cb : NULL, NULL);
958 if (rc)
959 goto fail;
961 assuan_ctx_set_system_hooks (cl->ctx, &shooks);
962 rc = assuan_init_socket_server (cl->ctx, cl->thd->fd, 2);
963 if (rc)
964 goto fail;
966 assuan_set_pointer (cl->ctx, cl);
967 assuan_set_hello_line (cl->ctx, PACKAGE_STRING);
968 rc = register_commands (cl->ctx);
969 if (rc)
970 goto fail;
972 #ifdef WITH_GNUTLS
973 if (cl->thd->remote)
975 cl->thd->timeout = config_get_integer ("global", "tls_timeout");
976 fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK);
978 #endif
980 rc = assuan_accept (cl->ctx);
981 if (rc)
982 goto fail;
984 rc = validate_peer (cl);
985 /* May not be implemented on all platforms. */
986 if (rc && gpg_err_code (rc) != GPG_ERR_ASS_GENERAL)
987 goto fail;
989 rc = init_client_crypto (&cl->crypto);
990 if (rc)
991 goto fail;
993 #ifdef WITH_AGENT
994 if (use_agent)
995 cl->crypto->agent->client_ctx = cl->ctx;
996 #endif
998 cl->crypto->client_ctx = cl->ctx;
999 xmlSetStructuredErrorFunc (cl, xml_error_cb);
1000 return 1;
1002 fail:
1003 log_write ("%s", pwmd_strerror (rc));
1004 return 0;
1008 * This is called after a client_thread() terminates. Set with
1009 * pthread_cleanup_push().
1011 static void
1012 cleanup_cb (void *arg)
1014 struct client_thread_s *cn = arg;
1015 struct client_s *cl = cn->cl;
1017 MUTEX_LOCK (&cn_mutex);
1018 cn_thread_list = slist_remove (cn_thread_list, cn);
1019 MUTEX_UNLOCK (&cn_mutex);
1021 if (cl)
1023 cleanup_client (cl);
1024 if (cl->xml_error)
1025 xmlResetError (cl->xml_error);
1027 xfree (cl->xml_error);
1029 #ifdef WITH_GNUTLS
1030 if (cn->tls)
1032 gnutls_deinit (cn->tls->ses);
1033 xfree (cn->tls->fp);
1034 xfree (cn->tls);
1036 #endif
1038 if (!cn->atfork && cl->ctx)
1039 assuan_release (cl->ctx);
1040 else if (!cn->atfork && cl->thd && cl->thd->fd != -1)
1041 close (cl->thd->fd);
1043 if (cl->crypto)
1044 cleanup_crypto (&cl->crypto);
1046 pinentry_free_opts (&cl->pinentry_opts);
1047 xfree (cl);
1049 else
1051 if (cn->fd != -1)
1052 close (cn->fd);
1055 while (cn->msg_queue)
1057 struct status_msg_s *msg = cn->msg_queue;
1059 cn->msg_queue = msg->next;
1060 xfree (msg->line);
1061 xfree (msg);
1064 if (!cn->atfork && cn->status_msg_pipe[0] != -1)
1065 close (cn->status_msg_pipe[0]);
1067 if (!cn->atfork && cn->status_msg_pipe[1] != -1)
1068 close (cn->status_msg_pipe[1]);
1070 pthread_mutex_destroy (&cn->status_mutex);
1072 if (!cn->atfork)
1074 log_write (_("exiting, fd=%i"), cn->fd);
1075 send_status_all (STATUS_CLIENTS, NULL);
1078 xfree (cn);
1079 pthread_cond_signal (&quit_cond);
1082 void
1083 cleanup_all_clients (int atfork)
1085 /* This function may be called from pthread_atfork() which requires
1086 reinitialization. */
1087 if (atfork)
1089 pthread_mutexattr_t attr;
1091 pthread_mutexattr_init (&attr);
1092 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
1093 pthread_mutex_init (&cn_mutex, &attr);
1094 pthread_mutexattr_destroy (&attr);
1095 cache_mutex_init ();
1098 MUTEX_LOCK (&cn_mutex);
1100 while (slist_length (cn_thread_list))
1102 struct client_thread_s *thd = slist_nth_data (cn_thread_list, 0);
1104 thd->atfork = atfork;
1105 cleanup_cb (thd);
1108 exiting = 1;
1109 MUTEX_UNLOCK (&cn_mutex);
1110 cache_deinit (atfork);
1113 static gpg_error_t
1114 send_msg_queue (struct client_thread_s *thd)
1116 MUTEX_LOCK (&thd->status_mutex);
1117 gpg_error_t rc = 0;
1118 char c;
1120 read (thd->status_msg_pipe[0], &c, 1);
1122 while (thd->msg_queue)
1124 struct status_msg_s *msg = thd->msg_queue;
1126 thd->msg_queue = thd->msg_queue->next;
1127 MUTEX_UNLOCK (&thd->status_mutex);
1128 rc = send_status (thd->cl->ctx, msg->s, msg->line);
1129 MUTEX_LOCK (&thd->status_mutex);
1130 xfree (msg->line);
1131 xfree (msg);
1133 if (rc)
1134 break;
1137 MUTEX_UNLOCK (&thd->status_mutex);
1138 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1139 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
1141 return rc;
1144 static void *
1145 client_thread (void *data)
1147 struct client_thread_s *thd = data;
1148 struct client_s *cl = xcalloc (1, sizeof (struct client_s));
1150 #ifdef HAVE_PR_SET_NAME
1151 prctl (PR_SET_NAME, "client");
1152 #endif
1153 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1155 if (!cl)
1157 log_write ("%s(%i): %s", __FILE__, __LINE__,
1158 pwmd_strerror (GPG_ERR_ENOMEM));
1159 return NULL;
1162 MUTEX_LOCK (&cn_mutex);
1163 pthread_cleanup_push (cleanup_cb, thd);
1164 thd->cl = cl;
1165 cl->thd = thd;
1166 MUTEX_UNLOCK (&cn_mutex);
1168 if (new_connection (cl))
1170 int finished = 0;
1171 gpg_error_t rc;
1173 send_status_all (STATUS_CLIENTS, NULL);
1174 rc = send_status (cl->ctx, STATUS_CACHE, NULL);
1175 if (rc)
1177 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
1178 finished = 1;
1181 while (!finished)
1183 fd_set rfds;
1184 int n;
1185 int eof;
1187 FD_ZERO (&rfds);
1188 FD_SET (thd->fd, &rfds);
1189 FD_SET (thd->status_msg_pipe[0], &rfds);
1190 n = thd->fd > thd->status_msg_pipe[0]
1191 ? thd->fd : thd->status_msg_pipe[0];
1193 n = select (n + 1, &rfds, NULL, NULL, NULL);
1194 if (n == -1)
1196 log_write ("%s", strerror (errno));
1197 break;
1200 if (FD_ISSET (thd->status_msg_pipe[0], &rfds))
1202 rc = send_msg_queue (thd);
1203 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1204 break;
1207 if (!FD_ISSET (thd->fd, &rfds))
1208 continue;
1210 rc = assuan_process_next (cl->ctx, &eof);
1211 if (rc || eof)
1213 if (gpg_err_code (rc) == GPG_ERR_EOF || eof)
1214 break;
1216 log_write ("assuan_process_next(): rc=%i %s", rc,
1217 pwmd_strerror (rc));
1218 if (rc == gpg_error (GPG_ERR_ETIMEDOUT))
1219 break;
1221 rc = send_error (cl->ctx, rc);
1222 if (rc)
1224 log_write ("assuan_process_done(): rc=%i %s", rc,
1225 pwmd_strerror (rc));
1226 break;
1230 /* Since the msg queue pipe fd's are non-blocking, check for
1231 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1232 * client has already disconnected and will be converted to
1233 * GPG_ERR_EOF during assuan_process_next().
1235 rc = send_msg_queue (thd);
1236 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1237 break;
1241 pthread_cleanup_pop (1);
1242 return NULL;
1245 static int
1246 xml_import (const char *filename, const char *outfile,
1247 const char *keygrip, const char *sign_keygrip,
1248 const char *keyfile, int no_passphrase, const char *cipher,
1249 const char *params, unsigned long s2k_count, uint64_t iterations)
1251 xmlDocPtr doc;
1252 int fd;
1253 struct stat st;
1254 int len;
1255 xmlChar *xmlbuf;
1256 xmlChar *xml;
1257 gpg_error_t rc;
1258 struct crypto_s *crypto = NULL;
1259 void *key = NULL;
1260 size_t keylen = 0;
1261 int algo = cipher ? cipher_string_to_gcrypt ((char *) cipher) :
1262 GCRY_CIPHER_AES256;
1264 if (algo == -1)
1266 log_write ("ERR %i: %s", gpg_error (GPG_ERR_CIPHER_ALGO),
1267 pwmd_strerror (GPG_ERR_CIPHER_ALGO));
1268 return 0;
1271 if (stat (filename, &st) == -1)
1273 log_write ("%s: %s", filename,
1274 pwmd_strerror (gpg_error_from_errno (errno)));
1275 return 0;
1278 rc = init_client_crypto (&crypto);
1279 if (rc)
1280 return 0;
1282 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
1283 crypto->save.hdr.flags = set_cipher_flag (crypto->save.hdr.flags, algo);
1284 log_write (_("Importing XML from '%s'. Output will be written to '%s' ..."),
1285 filename, outfile);
1287 if ((fd = open (filename, O_RDONLY)) == -1)
1289 log_write ("%s: %s", filename,
1290 pwmd_strerror (gpg_error_from_errno (errno)));
1291 goto fail;
1294 if ((xmlbuf = xmalloc (st.st_size + 1)) == NULL)
1296 close (fd);
1297 log_write ("%s(%i): %s", __FILE__, __LINE__,
1298 pwmd_strerror (GPG_ERR_ENOMEM));
1299 goto fail;
1302 if (read (fd, xmlbuf, st.st_size) == -1)
1304 rc = gpg_error_from_errno (errno);
1305 close (fd);
1306 log_write ("%s: %s", filename, pwmd_strerror (rc));
1307 goto fail;
1310 close (fd);
1311 xmlbuf[st.st_size] = 0;
1313 * Make sure the document validates.
1315 if ((doc = xmlReadDoc (xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS)) == NULL)
1317 log_write ("xmlReadDoc() failed");
1318 xfree (xmlbuf);
1319 goto fail;
1322 xfree (xmlbuf);
1323 xmlNodePtr n = xmlDocGetRootElement (doc);
1324 if (n && !xmlStrEqual (n->name, (xmlChar *) "pwmd"))
1326 log_write (_("Could not find root \"pwmd\" element."));
1327 rc = GPG_ERR_BAD_DATA;
1330 if (!rc)
1331 rc = validate_import (NULL, n ? n->children : n);
1333 if (rc)
1335 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1336 xmlFreeDoc (doc);
1337 goto fail;
1340 xmlDocDumpMemory (doc, &xml, &len);
1341 xmlFreeDoc (doc);
1342 crypto->save.s2k_count = s2k_count;
1343 crypto->save.hdr.iterations = iterations;
1344 if (!use_agent)
1346 rc = export_common (NULL, 0, crypto, xml, len, outfile, keyfile, &key,
1347 &keylen, 0, 0, no_passphrase);
1348 if (!rc)
1349 log_write (_("Success!"));
1351 #ifdef WITH_AGENT
1352 else
1354 rc = agent_set_pinentry_options (crypto->agent);
1355 if (!rc)
1356 rc = agent_export_common (crypto, keygrip, sign_keygrip, no_passphrase,
1357 xml, len, outfile, params, keyfile);
1359 #endif
1361 gcry_free (key);
1362 xmlFree (xml);
1363 if (rc)
1365 send_error (NULL, rc);
1366 goto fail;
1369 cleanup_crypto (&crypto);
1370 return 1;
1372 fail:
1373 cleanup_crypto (&crypto);
1374 return 0;
1377 static int
1378 do_cache_push (const char *filename, struct crypto_s *crypto)
1380 unsigned char md5file[16];
1381 gpg_error_t rc;
1382 char *key = NULL;
1383 size_t keylen = 0;
1384 xmlDocPtr doc;
1385 struct cache_data_s *cdata;
1386 unsigned char *crc;
1387 size_t len;
1389 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1390 filename);
1392 if (valid_filename (filename) == 0)
1394 log_write (_("%s: Invalid characters in filename"), filename);
1395 return 0;
1398 rc = decrypt_common (NULL, 0, crypto, filename, &key, &keylen);
1399 if (rc)
1400 return 0;
1402 rc = parse_doc ((char *) crypto->plaintext, crypto->plaintext_len, &doc);
1403 if (rc)
1405 log_write ("%s", pwmd_strerror (rc));
1406 xfree (key);
1407 return 0;
1410 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
1411 cdata = xcalloc (1, sizeof (struct cache_data_s));
1412 if (!cdata)
1414 xmlFreeDoc (doc);
1415 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM));
1416 xfree (key);
1417 return 0;
1420 rc = get_checksum (filename, &crc, &len);
1421 if (rc)
1423 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1424 xmlFreeDoc (doc);
1425 free_cache_data_once (cdata);
1426 xfree (key);
1427 return 0;
1430 cdata->crc = crc;
1431 rc = encrypt_xml (NULL, cache_key, cache_keysize, GCRY_CIPHER_AES,
1432 crypto->plaintext, crypto->plaintext_len, &cdata->doc,
1433 &cdata->doclen, &cache_iv, &cache_blocksize, 0);
1434 if (!rc && !IS_PKI (crypto))
1436 cdata->key = key;
1437 cdata->keylen = keylen;
1439 else
1440 xfree (key);
1442 if (rc)
1444 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1445 xmlFreeDoc (doc);
1446 free_cache_data_once (cdata);
1447 return 0;
1450 #ifdef WITH_AGENT
1451 if (use_agent && IS_PKI (crypto))
1453 gcry_sexp_build ((gcry_sexp_t *) & cdata->pubkey, NULL, "%S",
1454 crypto->pkey_sexp);
1455 gcry_sexp_build ((gcry_sexp_t *) & cdata->sigkey, NULL, "%S",
1456 crypto->sigpkey_sexp);
1458 #endif
1460 int timeout = config_get_integer (filename, "cache_timeout");
1461 cache_add_file (md5file, crypto->grip, cdata, timeout);
1462 log_write (_("Successfully added '%s' to the cache."), filename);
1463 return 1;
1466 static gpg_error_t
1467 init_client (int fd, const char *addr)
1469 gpg_error_t rc = 0;
1470 struct client_thread_s *new = xcalloc (1, sizeof (struct client_thread_s));
1472 if (!new)
1474 close (fd);
1475 return GPG_ERR_ENOMEM;
1478 MUTEX_LOCK (&cn_mutex);
1479 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
1481 if (pipe (new->status_msg_pipe) == -1)
1482 rc = gpg_error_from_errno (errno);
1484 if (!rc)
1486 fcntl (new->status_msg_pipe[0], F_SETFL, O_NONBLOCK);
1487 fcntl (new->status_msg_pipe[1], F_SETFL, O_NONBLOCK);
1488 pthread_mutex_init (&new->status_mutex, NULL);
1491 if (!rc)
1493 #ifdef WITH_GNUTLS
1494 new->remote = addr ? 1 : 0;
1495 #endif
1496 new->fd = fd;
1497 rc = create_thread (client_thread, new, &new->tid, 1);
1498 if (rc)
1500 close (new->status_msg_pipe[0]);
1501 close (new->status_msg_pipe[1]);
1502 pthread_mutex_destroy (&new->status_mutex);
1506 if (!rc)
1508 struct slist_s *list = slist_append (cn_thread_list, new);
1510 if (list)
1512 cn_thread_list = list;
1513 if (addr)
1514 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1515 (pthread_t *) new->tid, fd, addr);
1516 else
1517 log_write (_("new connection: tid=%p, fd=%i"),
1518 (pthread_t *) new->tid, fd);
1520 else
1521 rc = GPG_ERR_ENOMEM;
1524 pthread_cleanup_pop (1);
1526 if (rc)
1528 xfree (new);
1529 close (fd);
1530 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1531 pwmd_strerror (rc));
1533 return rc;
1536 static void*
1537 keepalive_thread (void *arg)
1539 #ifndef HAVE_PTHREAD_CANCEL
1540 int *n = xmalloc (sizeof (int));
1542 *n = 0;
1543 pthread_setspecific (signal_thread_key, n);
1544 INIT_THREAD_SIGNAL;
1545 #endif
1547 #ifdef HAVE_PR_SET_NAME
1548 prctl (PR_SET_NAME, "keepalive");
1549 #endif
1550 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1552 for (;;)
1554 int n = config_get_integer ("global", "keepalive_interval");
1555 struct timeval tv = { n, 0 };
1556 #ifndef HAVE_PTHREAD_CANCEL
1557 int *sigusr2;
1559 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1560 if (*sigusr2)
1561 break;
1562 #endif
1564 send_status_all (STATUS_KEEPALIVE, NULL);
1565 select (0, NULL, NULL, NULL, &tv);
1568 return NULL;
1571 #ifdef WITH_GNUTLS
1572 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1573 static void *
1574 get_in_addr (struct sockaddr *sa)
1576 if (sa->sa_family == AF_INET)
1577 return &(((struct sockaddr_in *) sa)->sin_addr);
1579 return &(((struct sockaddr_in6 *) sa)->sin6_addr);
1582 static void *
1583 tcp_accept_thread (void *arg)
1585 int sockfd = *(int *) arg;
1586 #ifndef HAVE_PTHREAD_CANCEL
1587 int *n = xmalloc (sizeof (int));
1589 *n = 0;
1590 pthread_setspecific (signal_thread_key, n);
1591 INIT_THREAD_SIGNAL;
1592 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1593 #endif
1595 #ifdef HAVE_PR_SET_NAME
1596 prctl (PR_SET_NAME, "tcp_accept");
1597 #endif
1598 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1600 for (;;)
1602 struct sockaddr_storage raddr;
1603 socklen_t slen = sizeof (raddr);
1604 int fd;
1605 unsigned long n;
1606 char s[INET6_ADDRSTRLEN];
1607 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1608 #ifndef HAVE_PTHREAD_CANCEL
1609 int *sigusr2;
1611 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1612 if (*sigusr2)
1613 break;
1614 #endif
1616 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1617 if (fd == -1)
1619 if (errno == EMFILE || errno == ENFILE)
1620 log_write ("accept(): %s",
1621 pwmd_strerror (gpg_error_from_errno (errno)));
1622 else if (errno != EAGAIN)
1624 if (!quit) // probably EBADF
1625 log_write ("accept(): %s", strerror (errno));
1627 break;
1630 #ifndef HAVE_PTHREAD_CANCEL
1631 select (0, NULL, NULL, NULL, &tv);
1632 #endif
1633 continue;
1636 if (quit)
1637 break;
1639 inet_ntop (raddr.ss_family, get_in_addr ((struct sockaddr *) &raddr),
1640 s, sizeof s);
1641 (void) init_client (fd, s);
1642 n = config_get_integer ("global", "tcp_wait");
1643 if (n > 0)
1645 tv.tv_sec = (n * 100000) / 100000;
1646 tv.tv_usec = (n * 100000) % 100000;
1647 select (0, NULL, NULL, NULL, &tv);
1651 return NULL;
1654 static int
1655 start_stop_tls_with_protocol (int ipv6, int term)
1657 struct addrinfo hints, *servinfo, *p;
1658 int port = config_get_integer ("global", "tcp_port");
1659 char buf[7];
1660 int n;
1661 gpg_error_t rc;
1662 int *fd = ipv6 ? &tls6_fd : &tls_fd;
1664 if (term || config_get_boolean ("global", "enable_tcp") == 0)
1666 if (tls6_fd != -1)
1668 if (spawned_tls6)
1670 #ifdef HAVE_PTHREAD_CANCEL
1671 pthread_cancel (tls6_tid);
1672 #else
1673 pthread_kill (tls6_tid, SIGUSR2);
1674 #endif
1675 pthread_join (tls6_tid, NULL);
1678 shutdown (tls6_fd, SHUT_RDWR);
1679 close (tls6_fd);
1680 tls6_fd = -1;
1681 spawned_tls6 = 0;
1684 if (tls_fd != -1)
1686 if (spawned_tls)
1688 #ifdef HAVE_PTHREAD_CANCEL
1689 pthread_cancel (tls_tid);
1690 #else
1691 pthread_kill (tls_tid, SIGUSR2);
1692 #endif
1693 pthread_join (tls_tid, NULL);
1696 shutdown (tls_fd, SHUT_RDWR);
1697 close (tls_fd);
1698 tls_fd = -1;
1699 spawned_tls = 0;
1702 /* A client may still be connected. */
1703 if (!quit && x509_cred != NULL)
1704 tls_deinit_params ();
1706 return 1;
1709 if ((ipv6 && tls6_fd != -1) || (!ipv6 && tls_fd != -1))
1710 return 1;
1712 memset (&hints, 0, sizeof (hints));
1713 hints.ai_family = ipv6 ? AF_INET6 : AF_INET;
1714 hints.ai_socktype = SOCK_STREAM;
1715 hints.ai_flags = AI_PASSIVE;
1716 snprintf (buf, sizeof (buf), "%i", port);
1718 if ((n = getaddrinfo (NULL, buf, &hints, &servinfo)) == -1)
1720 log_write ("getaddrinfo(): %s", gai_strerror (n));
1721 return 0;
1724 for (n = 0, p = servinfo; p != NULL; p = p->ai_next)
1726 int r = 1;
1728 if ((ipv6 && p->ai_family != AF_INET6)
1729 || (!ipv6 && p->ai_family != AF_INET))
1730 continue;
1732 if ((*fd = socket (p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
1734 log_write ("socket(): %s", strerror (errno));
1735 continue;
1738 if (setsockopt (*fd, SOL_SOCKET, SO_REUSEADDR, &r, sizeof (int)) == -1)
1740 log_write ("setsockopt(): %s",
1741 pwmd_strerror (gpg_error_from_errno (errno)));
1742 freeaddrinfo (servinfo);
1743 goto fail;
1746 if (bind (*fd, p->ai_addr, p->ai_addrlen) == -1)
1748 close (*fd);
1749 log_write ("bind(): %s",
1750 pwmd_strerror (gpg_error_from_errno (errno)));
1751 continue;
1754 n++;
1755 break;
1758 freeaddrinfo (servinfo);
1760 if (!n)
1761 goto fail;
1763 #if HAVE_DECL_SO_BINDTODEVICE != 0
1764 char *tmp = config_get_string ("global", "tcp_interface");
1765 if (tmp && setsockopt (*fd, SOL_SOCKET, SO_BINDTODEVICE, tmp,
1766 strlen (tmp)) == -1)
1768 log_write ("setsockopt(): %s",
1769 pwmd_strerror (gpg_error_from_errno (errno)));
1770 xfree (tmp);
1771 goto fail;
1774 xfree (tmp);
1775 #endif
1777 if (x509_cred == NULL)
1779 rc = tls_init_params ();
1780 if (rc)
1781 goto fail;
1784 if (listen (*fd, 0) == -1)
1786 log_write ("listen(): %s", strerror (errno));
1787 goto fail;
1790 if (ipv6)
1791 rc = create_thread (tcp_accept_thread, fd, &tls6_tid, 0);
1792 else
1793 rc = create_thread (tcp_accept_thread, fd, &tls_tid, 0);
1795 if (rc)
1797 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1798 pwmd_strerror (rc));
1799 goto fail;
1802 if (ipv6)
1803 spawned_tls6 = 1;
1804 else
1805 spawned_tls = 1;
1807 return 1;
1809 fail:
1810 start_stop_tls_with_protocol (0, 1);
1811 if (tls_fd != -1)
1812 close (tls_fd);
1814 if (tls6_fd != -1)
1815 close (tls6_fd);
1817 tls_fd = -1;
1818 tls6_fd = -1;
1819 return 0;
1822 static int
1823 start_stop_tls (int term)
1825 char *s = config_get_string ("global", "tcp_bind");
1826 int b;
1828 if (!s)
1829 return 0;
1831 if (!strcmp (s, "any"))
1833 b = start_stop_tls_with_protocol (0, term);
1834 if (b)
1835 b = start_stop_tls_with_protocol (1, term);
1837 else if (!strcmp (s, "ipv4"))
1838 b = start_stop_tls_with_protocol (0, term);
1839 else if (!strcmp (s, "ipv6"))
1840 b = start_stop_tls_with_protocol (1, term);
1841 else
1842 b = 0;
1844 xfree (s);
1845 return b;
1847 #endif
1849 static void *
1850 accept_thread (void *arg)
1852 int sockfd = *(int *) arg;
1853 #ifndef HAVE_PTHREAD_CANCEL
1854 int *n = xmalloc (sizeof (int));
1856 *n = 0;
1857 pthread_setspecific (signal_thread_key, n);
1858 INIT_THREAD_SIGNAL;
1859 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1860 #endif
1862 #ifdef HAVE_PR_SET_NAME
1863 prctl (PR_SET_NAME, "accept");
1864 #endif
1865 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1867 for (;;)
1869 socklen_t slen = sizeof (struct sockaddr_un);
1870 struct sockaddr_un raddr;
1871 int fd;
1872 #ifndef HAVE_PTHREAD_CANCEL
1873 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1874 int *sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1876 if (*sigusr2)
1877 break;
1878 #endif
1880 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1881 if (fd == -1)
1883 if (errno == EMFILE || errno == ENFILE)
1884 log_write ("accept(): %s",
1885 pwmd_strerror (gpg_error_from_errno (errno)));
1886 else if (errno != EAGAIN)
1888 if (!quit) // probably EBADF
1889 log_write ("accept(): %s",
1890 pwmd_strerror (gpg_error_from_errno (errno)));
1892 break;
1895 #ifndef HAVE_PTHREAD_CANCEL
1896 select (0, NULL, NULL, NULL, &tv);
1897 #endif
1898 continue;
1901 (void) init_client (fd, NULL);
1904 /* Just in case accept() failed for some reason other than EBADF */
1905 quit = 1;
1906 return NULL;
1909 static void *
1910 cache_timer_thread (void *arg)
1912 #ifndef HAVE_PTHREAD_CANCEL
1913 int *n = xmalloc (sizeof (int));
1915 *n = 0;
1916 pthread_setspecific (signal_thread_key, n);
1917 INIT_THREAD_SIGNAL;
1918 #endif
1920 #ifdef HAVE_PR_SET_NAME
1921 prctl (PR_SET_NAME, "cache timer");
1922 #endif
1923 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1925 for (;;)
1927 struct timeval tv = { 1, 0 };
1928 #ifndef HAVE_PTHREAD_CANCEL
1929 int *n;
1931 n = (int *) pthread_getspecific (signal_thread_key);
1932 if (*n)
1933 break;
1934 #endif
1936 select (0, NULL, NULL, NULL, &tv);
1937 cache_adjust_timeout ();
1940 return NULL;
1943 static int
1944 signal_loop (sigset_t sigset)
1946 int done = 0;
1947 int siint = 0;
1951 int sig;
1953 sigwait (&sigset, &sig);
1955 if (sig != SIGQUIT)
1956 log_write (_("caught signal %i (%s)"), sig, strsignal (sig));
1958 switch (sig)
1960 case SIGHUP:
1961 pthread_cond_signal (&rcfile_cond);
1962 break;
1963 case SIGUSR1:
1964 log_write (_("clearing file cache"));
1965 cache_clear (NULL);
1966 send_status_all (STATUS_CACHE, NULL);
1967 break;
1968 case SIGQUIT:
1969 done = 1;
1970 break;
1971 default:
1972 siint = 1;
1973 done = 1;
1974 break;
1977 while (!done);
1979 return siint;
1982 static void
1983 catchsig (int sig)
1985 log_write (_ ("Caught signal %i (%s). Exiting."), sig, strsignal (sig));
1986 #ifdef HAVE_BACKTRACE
1987 BACKTRACE (__FUNCTION__);
1988 #endif
1989 longjmp (jmp, 1);
1992 static void *
1993 waiting_for_exit (void *arg)
1995 int last = 0;
1996 #ifndef HAVE_PTHREAD_CANCEL
1997 int *n = xmalloc (sizeof (int));
1999 *n = 0;
2000 pthread_setspecific (signal_thread_key, n);
2001 INIT_THREAD_SIGNAL;
2002 #endif
2004 #ifdef HAVE_PR_SET_NAME
2005 prctl (PR_SET_NAME, "exiting");
2006 #endif
2007 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
2008 log_write (_("waiting for all clients to disconnect"));
2009 MUTEX_LOCK (&quit_mutex);
2010 pthread_cleanup_push (cleanup_mutex_cb, &quit_mutex);
2012 for (;;)
2014 struct timespec ts;
2015 int n;
2017 MUTEX_LOCK (&cn_mutex);
2018 n = slist_length (cn_thread_list);
2019 MUTEX_UNLOCK (&cn_mutex);
2020 if (!n)
2021 break;
2023 #ifndef HAVE_PTHREAD_CANCEL
2024 int *s = (int *) pthread_getspecific (signal_thread_key);
2025 if (*s)
2026 break;
2027 #endif
2029 if (last != n)
2031 log_write (_("%i clients remain"), n);
2032 last = n;
2035 INIT_TIMESPEC (SIG_TIMEOUT, ts);
2036 pthread_cond_timedwait (&quit_cond, &quit_mutex, &ts);
2039 kill (getpid (), SIGQUIT);
2040 pthread_cleanup_pop (1);
2041 return NULL;
2044 static int
2045 server_loop (int sockfd, char **socketpath)
2047 pthread_t accept_tid;
2048 pthread_t cache_timeout_tid;
2049 int cancel_timeout_thread = 0, cancel_accept_thread = 0;
2050 int cancel_keepalive_thread = 0;
2051 sigset_t sigset;
2052 int n;
2053 int segv = 0;
2054 gpg_error_t rc;
2056 init_commands ();
2057 sigemptyset (&sigset);
2059 /* Termination */
2060 sigaddset (&sigset, SIGTERM);
2061 sigaddset (&sigset, SIGINT);
2063 /* Clears the file cache. */
2064 sigaddset (&sigset, SIGUSR1);
2066 /* Configuration file reloading. */
2067 sigaddset (&sigset, SIGHUP);
2069 /* For exiting cleanly. */
2070 sigaddset (&sigset, SIGQUIT);
2072 #ifndef HAVE_PTHREAD_CANCEL
2074 The socket, cache and rcfile threads use this signal when
2075 pthread_cancel() is unavailable. Prevent the main thread from
2076 catching this signal from another process.
2078 sigaddset (&sigset, SIGUSR2);
2079 #endif
2081 /* When mem.c cannot find a pointer in the list (double free). */
2082 signal (SIGABRT, catchsig);
2083 sigaddset (&sigset, SIGABRT);
2084 sigprocmask (SIG_BLOCK, &sigset, NULL);
2086 #ifndef HAVE_PTHREAD_CANCEL
2087 /* Remove this signal from the watched signals in signal_loop(). */
2088 sigdelset (&sigset, SIGUSR2);
2089 #endif
2091 /* Ignored everywhere. When a client disconnects abnormally this signal
2092 * gets raised. It isn't needed though because client_thread() will check
2093 * for rcs even after the client disconnects. */
2094 signal (SIGPIPE, SIG_IGN);
2096 /* Can show a backtrace of the stack in the log. */
2097 signal (SIGSEGV, catchsig);
2099 #ifdef WITH_GNUTLS
2100 /* Needs to be done after the fork(). */
2101 if (!start_stop_tls (0))
2103 segv = 1;
2104 goto done;
2106 #endif
2108 pthread_mutex_init (&quit_mutex, NULL);
2109 pthread_cond_init (&quit_cond, NULL);
2110 char *p = get_username (getuid());
2111 log_write (_("%s started for user %s"), PACKAGE_STRING, p);
2112 xfree (p);
2114 #ifdef WITH_GNUTLS
2115 if (config_get_boolean ("global", "enable_tcp"))
2116 log_write (_("Listening on %s and TCP port %i as user %i"), *socketpath,
2117 config_get_integer ("global", "tcp_port"), invoking_uid);
2118 else
2119 log_write (_("Listening on %s"), *socketpath);
2120 #else
2121 log_write (_("Listening on %s"), *socketpath);
2122 #endif
2124 rc = create_thread (keepalive_thread, NULL, &keepalive_tid, 0);
2125 if (rc)
2127 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2128 pwmd_strerror (rc));
2129 goto done;
2132 cancel_keepalive_thread = 1;
2133 rc = create_thread (reload_rcfile_thread, NULL, &rcfile_tid, 0);
2134 if (rc)
2136 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2137 pwmd_strerror (rc));
2138 goto done;
2141 rc = create_thread (cache_timer_thread, NULL, &cache_timeout_tid, 0);
2142 if (rc)
2144 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2145 pwmd_strerror (rc));
2146 goto done;
2149 cancel_timeout_thread = 1;
2150 rc = create_thread (accept_thread, &sockfd, &accept_tid, 0);
2151 if (rc)
2153 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2154 pwmd_strerror (rc));
2155 goto done;
2158 cancel_accept_thread = 1;
2159 if (!setjmp (jmp))
2160 signal_loop (sigset);
2161 else
2162 segv = 1;
2164 done:
2166 * We're out of the main server loop. This happens when a signal was sent
2167 * to terminate the daemon. We'll wait for all clients to disconnect
2168 * before exiting but exit immediately if another termination signal is
2169 * sent.
2171 if (cancel_accept_thread)
2173 #ifdef HAVE_PTHREAD_CANCEL
2174 int n = pthread_cancel (accept_tid);
2175 #else
2176 int n = pthread_kill (accept_tid, SIGUSR2);
2177 #endif
2178 if (!n)
2179 pthread_join (accept_tid, NULL);
2182 #ifdef WITH_GNUTLS
2183 start_stop_tls (1);
2184 #endif
2185 shutdown (sockfd, SHUT_RDWR);
2186 close (sockfd);
2187 unlink (*socketpath);
2188 xfree (*socketpath);
2189 *socketpath = NULL;
2190 MUTEX_LOCK (&cn_mutex);
2191 n = slist_length (cn_thread_list);
2192 MUTEX_UNLOCK (&cn_mutex);
2194 if (n && !segv)
2196 pthread_t tid;
2198 rc = create_thread (waiting_for_exit, NULL, &tid, 0);
2199 if (!rc)
2201 if (signal_loop (sigset))
2203 log_write (_("Received second termination request. Exiting."));
2204 #ifdef HAVE_PTHREAD_CANCEL
2205 pthread_cancel (tid);
2206 #else
2207 pthread_kill (tid, SIGUSR2);
2208 #endif
2209 pthread_join (tid, NULL);
2212 else
2213 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2214 pwmd_strerror (rc));
2217 if (cancel_timeout_thread)
2219 #ifdef HAVE_PTHREAD_CANCEL
2220 pthread_cancel (cache_timeout_tid);
2221 #else
2222 pthread_kill (cache_timeout_tid, SIGUSR2);
2223 #endif
2224 pthread_join (cache_timeout_tid, NULL);
2227 if (cancel_keepalive_thread)
2229 #ifdef HAVE_PTHREAD_CANCEL
2230 pthread_cancel (keepalive_tid);
2231 #else
2232 pthread_kill (keepalive_tid, SIGUSR2);
2233 #endif
2234 pthread_join (keepalive_tid, NULL);
2237 cleanup_all_clients (0);
2238 #ifdef WITH_GNUTLS
2239 start_stop_tls (1);
2240 #endif
2241 deinit_commands ();
2242 pthread_cond_destroy (&quit_cond);
2243 pthread_mutex_destroy (&quit_mutex);
2244 return segv ? EXIT_FAILURE : EXIT_SUCCESS;;
2247 static void
2248 startup_failure ()
2250 log_write (_
2251 ("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
2252 cache_clear (NULL);
2255 /* This is called from cache.c:clear_once(). See
2256 * command.c:clearcache_command() for details about lock checking.
2258 static gpg_error_t
2259 free_cache_data (file_cache_t * cache)
2261 gpg_error_t rc = GPG_ERR_NO_DATA;
2262 int i, t;
2263 struct client_thread_s *found = NULL;
2264 int self = 0;
2266 if (!cache->data)
2267 return 0;
2269 cache_lock ();
2270 MUTEX_LOCK (&cn_mutex);
2271 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
2272 t = slist_length (cn_thread_list);
2274 for (i = 0; i < t; i++)
2276 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2278 if (!thd->cl)
2279 continue;
2281 if (!memcmp (thd->cl->md5file, cache->filename,
2282 sizeof (cache->filename)))
2284 if (pthread_equal (pthread_self (), thd->tid))
2286 found = thd;
2287 self = 1;
2288 continue;
2291 /* Continue trying to find a client who has the same file open and
2292 * also has a lock. */
2293 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0, -1);
2294 if (!rc)
2296 self = 0;
2297 found = thd;
2298 break;
2303 if (self && (!rc || rc == GPG_ERR_NO_DATA))
2304 rc = cache_lock_mutex (found->cl->ctx, found->cl->md5file, -1, 0, -1);
2306 if (exiting || !rc || rc == GPG_ERR_NO_DATA)
2308 free_cache_data_once (cache->data);
2309 cache->data = NULL;
2310 cache->defer_clear = 0;
2311 cache->timeout = -1;
2313 if (found)
2314 cache_unlock_mutex (found->cl->md5file, 0);
2316 rc = 0;
2319 if (rc)
2320 cache->defer_clear = 1;
2322 pthread_cleanup_pop (1);
2323 cache_unlock ();
2324 return rc;
2327 static int
2328 convert_v2_datafile (const char *filename, const char *cipher,
2329 const char *keyfile, const char *keygrip,
2330 const char *sign_keygrip, int nopass,
2331 const char *outfile, const char *keyparam,
2332 unsigned long s2k_count, uint64_t iterations)
2334 gpg_error_t rc;
2335 void *data = NULL;
2336 size_t datalen;
2337 struct crypto_s *crypto = NULL;
2338 uint16_t ver;
2339 int algo;
2340 void *key = NULL;
2341 size_t keylen = 0;
2343 if (outfile[0] == '-' && outfile[1] == 0)
2344 outfile = NULL;
2346 log_write (_("Converting version 2 data file \"%s\" ..."), filename);
2347 if (access (filename, R_OK) == -1)
2349 log_write ("%s: %s", filename,
2350 pwmd_strerror (gpg_error_from_errno (errno)));
2351 return 0;
2354 if (keyfile)
2356 log_write (_("Using passphrase file \"%s\" for decryption ..."),
2357 keyfile);
2358 if (access (keyfile, R_OK) == -1)
2360 log_write ("%s: %s", keyfile,
2361 pwmd_strerror (gpg_error_from_errno (errno)));
2362 return 0;
2366 rc = read_v2_datafile (filename, keyfile, &data, &datalen, &ver, &algo);
2367 if (rc)
2369 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2370 return 0;
2373 if (cipher)
2375 algo = cipher_string_to_gcrypt (cipher);
2376 if (algo == -1)
2378 rc = GPG_ERR_CIPHER_ALGO;
2379 goto fail;
2383 if (ver < 0x212)
2385 xmlDocPtr doc;
2387 rc = parse_doc (data, datalen, &doc);
2388 if (rc)
2389 goto fail;
2391 rc = convert_pre_212_elements (doc);
2392 gcry_free (data);
2393 data = NULL;
2394 if (!rc)
2396 xmlDocDumpFormatMemory (doc, (xmlChar **) & data, (int *) &datalen,
2398 if (!data)
2399 rc = GPG_ERR_ENOMEM;
2402 xmlFreeDoc (doc);
2403 if (rc)
2404 goto fail;
2407 rc = init_client_crypto (&crypto);
2408 if (!rc)
2410 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
2411 crypto->save.hdr.flags = set_cipher_flag (crypto->save.hdr.flags, algo);
2412 crypto->save.s2k_count = s2k_count;
2413 crypto->save.hdr.iterations = iterations;
2415 if (!use_agent)
2417 rc = export_common (NULL, 0, crypto, data, datalen, outfile, keyfile,
2418 &key, &keylen, 0, 0, nopass);
2420 #ifdef WITH_AGENT
2421 else
2423 rc = agent_set_pinentry_options (crypto->agent);
2424 if (!rc)
2425 rc = agent_export_common (crypto, keygrip, sign_keygrip, nopass,
2426 data, datalen, outfile, keyparam,
2427 no_passphrase_file ? NULL : keyfile);
2429 #endif
2430 if (!rc)
2431 log_write (_("Output written to \"%s\"."), outfile);
2434 fail:
2435 if (ver < 0x212)
2436 xmlFree (data);
2437 else
2438 gcry_free (data);
2440 gcry_free (key);
2441 cleanup_crypto (&crypto);
2443 if (rc)
2444 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2445 return rc ? 0 : 1;
2448 static void
2449 usage (const char *pn, int status)
2451 FILE *fp = status == EXIT_FAILURE ? stderr : stdout;
2453 fprintf (fp, _("Usage: %s [OPTIONS] [file1] [...]\n"
2454 " -f, --rcfile=filename load the specfied configuration file\n"
2455 " (~/.pwmd/config)\n"
2456 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2457 #ifdef WITH_AGENT
2458 " --use-agent enable use of gpg-agent\n"
2459 #endif
2460 " -n, --no-fork run as a foreground process\n"
2461 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2462 " --ignore, --force ignore file errors during startup\n"
2463 " --debug-level=keywords log protocol output (see manual for details)\n"
2464 " -o, --outfile=filename output file when importing or converting\n"
2465 " -C, --convert=filename convert a version 2 data file to version 3\n"
2466 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2467 " -k, --passphrase-file=file for use when importing or converting\n"
2468 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2469 " converting\n"
2470 " --no-passphrase when importing or converting\n"
2471 " --keygrip=hex public key to use when encrypting\n"
2472 " --sign-keygrip=hex private key to use when signing\n"
2473 " --keyparam=s-exp custom key parameters to use (RSA-2048)\n"
2474 " --cipher=string encryption cipher (aes256)\n"
2475 " --cipher-iterations=N cipher iteration count (N+1)\n"
2476 " --s2k-count=N hash iteration count (>65536, calibrated)\n"
2477 " --help this help text\n"
2478 " --version show version and compile time features\n"),
2479 pn);
2480 exit (status);
2483 static void
2484 unlink_stale_socket (const char *sock, const char *pidfile)
2486 log_write (_ ("removing stale socket %s"), sock);
2487 unlink (sock);
2488 unlink (pidfile);
2491 static int
2492 test_pidfile (const char *path, const char *sock, char *buf, size_t buflen,
2493 char **pidfile, int create, mode_t mode)
2495 pid_t pid;
2496 int fd;
2497 size_t len;
2499 if (!create)
2501 snprintf (buf, buflen, "%s/%s.pid", homedir, sock);
2502 *pidfile = str_dup (buf);
2503 fd = open (buf, O_RDONLY);
2505 else
2506 fd = open (*pidfile, O_CREAT|O_WRONLY|O_TRUNC, mode);
2508 if (fd == -1)
2510 if (!create && errno != ENOENT)
2512 log_write ("%s: %s", buf, pwmd_strerror (errno));
2513 free (*pidfile);
2514 *pidfile = NULL;
2515 return -1;
2517 else if (!create)
2518 return 0;
2520 log_write ("%s: %s", *pidfile, strerror (errno));
2521 return -1;
2524 if (create)
2526 snprintf (buf, buflen, "%i", getpid ());
2527 write (fd, buf, strlen (buf));
2528 close (fd);
2529 return 0;
2532 len = read (fd, buf, sizeof(buf));
2533 close (fd);
2534 if (len == 0)
2536 unlink_stale_socket (path, *pidfile);
2537 return 0;
2540 if (sscanf (buf, "%5i", &pid) != 1 || pid == 0)
2542 unlink_stale_socket (path, *pidfile);
2543 return 0;
2546 if (kill (pid, 0) == -1)
2548 unlink_stale_socket (path, *pidfile);
2549 return 0;
2552 log_write (_ ("an instance for socket %s is already running"), path);
2553 xfree (*pidfile);
2554 *pidfile = NULL;
2555 return 1;
2559 main (int argc, char *argv[])
2561 int opt;
2562 struct sockaddr_un addr;
2563 char buf[PATH_MAX];
2564 char *socketpath = NULL, *socketdir, *socketname = NULL;
2565 char *socketarg = NULL;
2566 char *datadir = NULL;
2567 char *pidfile = NULL;
2568 mode_t mode = 0600;
2569 int x;
2570 char *p;
2571 char **cache_push = NULL;
2572 char *import = NULL, *keygrip = NULL, *sign_keygrip = NULL;
2573 char *keyparam = NULL;
2574 int estatus = EXIT_FAILURE;
2575 int sockfd;
2576 char *outfile = NULL;
2577 int do_unlink = 0;
2578 int secure = 0;
2579 int show_version = 0;
2580 int force = 0;
2581 int no_passphrase = 0;
2582 gpg_error_t rc;
2583 char *convertfile = NULL;
2584 char *cipher = NULL;
2585 char *keyfile = NULL;
2586 unsigned long s2k_count = 0;
2587 uint64_t iterations = 0;
2588 int exists;
2589 char *debug_level_opt = NULL;
2590 int optindex;
2591 /* Must maintain the same order as longopts[] */
2592 enum
2594 OPT_VERSION, OPT_HELP,
2595 #ifdef WITH_AGENT
2596 OPT_AGENT,
2597 #endif
2598 OPT_DEBUG_LEVEL, OPT_HOMEDIR, OPT_NO_FORK, OPT_DISABLE_DUMP,
2599 OPT_IGNORE, OPT_FORCE, OPT_RCFILE, OPT_CONVERT,
2600 OPT_PASSPHRASE_FILE, OPT_IMPORT, OPT_OUTFILE,
2601 OPT_NO_PASSPHRASE_FILE, OPT_KEYGRIP, OPT_SIGN_KEYGRIP,
2602 OPT_KEYPARAM, OPT_CIPHER, OPT_ITERATIONS, OPT_S2K_COUNT,
2603 OPT_NO_PASSPHRASE
2605 const char *optstring = "nf:C:k:I:o:";
2606 const struct option longopts[] = {
2607 {"version", no_argument, 0, 0},
2608 {"help", no_argument, 0, 0},
2609 #ifdef WITH_AGENT
2610 {"use-agent", no_argument, 0, 0},
2611 #endif
2612 {"debug-level", required_argument, 0, 0},
2613 {"homedir", required_argument, 0, 0},
2614 {"no-fork", no_argument, 0, 'n'},
2615 {"disable_dump", no_argument, 0, 0},
2616 {"ignore", no_argument, 0, 0},
2617 {"force", no_argument, 0, 0},
2618 {"rcfile", required_argument, 0, 'f'},
2619 {"convert", required_argument, 0, 'C'},
2620 {"passphrase-file", required_argument, 0, 'k'},
2621 {"import", required_argument, 0, 'I'},
2622 {"outfile", required_argument, 0, 'o'},
2623 {"no-passphrase-file", no_argument, 0, 0},
2624 {"keygrip", required_argument, 0, 0},
2625 {"sign-keygrip", required_argument, 0, 0},
2626 {"keyparam", required_argument, 0, 0},
2627 {"cipher", required_argument, 0, 0},
2628 {"cipher-iterations", required_argument, 0, 0},
2629 {"s2k-count", required_argument, 0, 0},
2630 {"no-passphrase", no_argument, 0, 0},
2631 {0, 0, 0, 0}
2634 log_fd = -1;
2636 #ifndef DEBUG
2637 #ifdef HAVE_SETRLIMIT
2638 struct rlimit rl;
2640 rl.rlim_cur = rl.rlim_max = 0;
2642 if (setrlimit (RLIMIT_CORE, &rl) != 0)
2643 err (EXIT_FAILURE, "setrlimit()");
2644 #endif
2646 #ifdef HAVE_PR_SET_DUMPABLE
2647 prctl (PR_SET_DUMPABLE, 0);
2648 #endif
2649 #endif
2651 #ifdef ENABLE_NLS
2652 setlocale (LC_ALL, "");
2653 bindtextdomain ("pwmd", LOCALEDIR);
2654 textdomain ("pwmd");
2655 #endif
2657 #ifndef MEM_DEBUG
2658 xmem_init ();
2659 #endif
2660 gpg_err_init ();
2662 if (setup_crypto ())
2663 exit (EXIT_FAILURE);
2665 #ifdef WITH_GNUTLS
2666 gnutls_global_set_mem_functions (xmalloc, xmalloc, secure_mem_check,
2667 xrealloc, xfree);
2668 gnutls_global_init ();
2669 gnutls_global_set_log_function (tls_log);
2670 gnutls_global_set_log_level (1);
2671 tls_fd = -1;
2672 tls6_fd = -1;
2673 #endif
2674 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
2675 xmlInitMemory ();
2676 xmlInitGlobals ();
2677 xmlInitParser ();
2678 xmlXPathInit ();
2679 cmdline = 1;
2680 use_agent = 0;
2682 while ((opt = getopt_long (argc, argv, optstring, longopts, &optindex))
2683 != -1)
2685 switch (opt)
2687 case 'I':
2688 import = optarg;
2689 break;
2690 case 'C':
2691 convertfile = optarg;
2692 break;
2693 case 'k':
2694 keyfile = optarg;
2695 break;
2696 case 'o':
2697 outfile = optarg;
2698 break;
2699 case 'D':
2700 secure = 1;
2701 break;
2702 case 'n':
2703 nofork = 1;
2704 break;
2705 case 'f':
2706 rcfile = str_dup (optarg);
2707 break;
2708 default:
2709 usage (argv[0], EXIT_FAILURE);
2710 break;
2711 case 0:
2712 switch (optindex)
2714 case OPT_VERSION:
2715 show_version = 1;
2716 break;
2717 case OPT_HELP:
2718 usage (argv[0], 0);
2719 break;
2720 #ifdef WITH_AGENT
2721 case OPT_AGENT:
2722 use_agent = 1;
2723 break;
2724 #endif
2725 case OPT_DEBUG_LEVEL:
2726 debug_level_opt = optarg;
2727 break;
2728 case OPT_HOMEDIR:
2729 homedir = str_dup (optarg);
2730 break;
2731 case OPT_NO_FORK:
2732 nofork = 1;
2733 break;
2734 case OPT_DISABLE_DUMP:
2735 secure = 1;
2736 break;
2737 case OPT_IGNORE:
2738 case OPT_FORCE:
2739 force = 1;
2740 break;
2741 case OPT_RCFILE:
2742 rcfile = str_dup (optarg);
2743 break;
2744 case OPT_CONVERT:
2745 convertfile = optarg;
2746 break;
2747 case OPT_PASSPHRASE_FILE:
2748 keyfile = optarg;
2749 break;
2750 case OPT_IMPORT:
2751 import = optarg;
2752 break;
2753 case OPT_OUTFILE:
2754 outfile = optarg;
2755 break;
2756 case OPT_NO_PASSPHRASE_FILE:
2757 no_passphrase_file = 1;
2758 break;
2759 case OPT_KEYGRIP:
2760 keygrip = optarg;
2761 break;
2762 case OPT_SIGN_KEYGRIP:
2763 sign_keygrip = optarg;
2764 break;
2765 case OPT_KEYPARAM:
2766 keyparam = optarg;
2767 break;
2768 case OPT_CIPHER:
2769 cipher = optarg;
2770 break;
2771 case OPT_ITERATIONS:
2772 iterations = strtoull (optarg, NULL, 10);
2773 break;
2774 case OPT_S2K_COUNT:
2775 s2k_count = strtoul (optarg, NULL, 10);
2776 break;
2777 case OPT_NO_PASSPHRASE:
2778 no_passphrase = 1;
2779 break;
2780 default:
2781 usage (argv[0], 1);
2786 if (show_version)
2788 printf (_("%s\n\n"
2789 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014\n"
2790 "%s\n"
2791 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2792 "Compile time features:\n%s"), PACKAGE_STRING,
2793 PACKAGE_BUGREPORT,
2794 #ifdef PWMD_HOMEDIR
2795 "+PWMD_HOMEDIR=" PWMD_HOMEDIR "\n"
2796 #endif
2797 #ifdef WITH_AGENT
2798 "+WITH_AGENT\n"
2799 #else
2800 "-WITH_AGENT\n"
2801 #endif
2802 #ifdef WITH_QUALITY
2803 "+WITH_QUALITY\n"
2804 #else
2805 "-WITH_QUALITY\n"
2806 #endif
2807 #ifdef WITH_GNUTLS
2808 "+WITH_GNUTLS\n"
2809 #else
2810 "-WITH_GNUTLS\n"
2811 #endif
2812 #ifdef DEBUG
2813 "+DEBUG\n"
2814 #else
2815 "-DEBUG\n"
2816 #endif
2817 #ifdef MEM_DEBUG
2818 "+MEM_DEBUG\n"
2819 #else
2820 "-MEM_DEBUG\n"
2821 #endif
2822 #ifdef MUTEX_DEBUG
2823 "+MUTEX_DEBUG\n"
2824 #else
2825 "-MUTEX_DEBUG\n"
2826 #endif
2828 exit (EXIT_SUCCESS);
2831 if (!homedir)
2832 #ifdef PWMD_HOMEDIR
2833 homedir = str_dup(PWMD_HOMEDIR);
2834 #else
2835 homedir = str_asprintf ("%s/.pwmd", get_home_dir());
2836 #endif
2838 if (mkdir (homedir, 0700) == -1 && errno != EEXIST)
2839 err (EXIT_FAILURE, "%s", homedir);
2841 snprintf (buf, sizeof (buf), "%s/data", homedir);
2842 if (mkdir (buf, 0700) == -1 && errno != EEXIST)
2843 err (EXIT_FAILURE, "%s", buf);
2845 datadir = str_dup (buf);
2846 pthread_mutexattr_t attr;
2847 pthread_mutexattr_init (&attr);
2848 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
2849 pthread_mutex_init (&rcfile_mutex, &attr);
2850 pthread_cond_init (&rcfile_cond, NULL);
2851 pthread_mutex_init (&cn_mutex, &attr);
2852 pthread_mutexattr_destroy (&attr);
2853 pthread_key_create (&last_error_key, free_key);
2854 #ifndef HAVE_PTHREAD_CANCEL
2855 pthread_key_create (&signal_thread_key, free_key);
2856 #endif
2858 if (!rcfile)
2859 rcfile = str_asprintf ("%s/config", homedir);
2861 global_config = config_parse (rcfile);
2862 if (!global_config)
2863 exit (EXIT_FAILURE);
2865 #ifdef WITH_AGENT
2866 if (!use_agent)
2867 use_agent = config_get_boolean ("global", "use_agent");
2868 #endif
2870 setup_logging ();
2872 if (debug_level_opt)
2873 debug_level = str_split (debug_level_opt, ",", 0);
2875 x = config_get_int_param (global_config, "global", "priority", &exists);
2876 if (exists && x != atoi(INVALID_PRIORITY))
2878 errno = 0;
2879 if (setpriority (PRIO_PROCESS, 0, x) == -1)
2881 log_write ("setpriority(): %s",
2882 pwmd_strerror (gpg_error_from_errno (errno)));
2883 goto do_exit;
2886 #ifdef HAVE_MLOCKALL
2887 if (disable_mlock == 0 && mlockall (MCL_CURRENT | MCL_FUTURE) == -1)
2889 log_write ("mlockall(): %s",
2890 pwmd_strerror (gpg_error_from_errno (errno)));
2891 goto do_exit;
2893 #endif
2895 rc = cache_init (free_cache_data);
2896 if (rc)
2898 log_write ("pwmd: ERR %i: %s", rc,
2899 gpg_err_code (rc) == GPG_ERR_UNKNOWN_VERSION
2900 ? _("incompatible gpg-agent version: 2.1.0 or later required")
2901 : pwmd_strerror (rc));
2902 goto do_exit;
2905 if (s2k_count == 0)
2906 s2k_count = config_get_ulong (NULL, "s2k_count");
2908 if (convertfile)
2910 if (!outfile || !*outfile || argc != optind)
2911 usage (argv[0], EXIT_FAILURE);
2913 estatus = convert_v2_datafile (convertfile, cipher, keyfile, keygrip,
2914 sign_keygrip, no_passphrase, outfile,
2915 keyparam, s2k_count, iterations);
2916 config_free (global_config);
2917 xfree (rcfile);
2918 exit (!estatus);
2921 if (import)
2923 if (!outfile || !*outfile || argc != optind)
2924 usage (argv[0], EXIT_FAILURE);
2926 if (outfile && outfile[0] == '-' && outfile[1] == 0)
2927 outfile = NULL;
2929 estatus = xml_import (import, outfile, keygrip, sign_keygrip, keyfile,
2930 no_passphrase, cipher, keyparam, s2k_count,
2931 iterations);
2932 config_free (global_config);
2933 xfree (rcfile);
2934 exit (!estatus);
2937 p = config_get_string ("global", "socket_path");
2938 if (!p)
2939 p = str_asprintf ("%s/socket", homedir);
2941 socketarg = expand_homedir (p);
2942 xfree (p);
2944 if (!secure)
2945 disable_list_and_dump = config_get_boolean ("global",
2946 "disable_list_and_dump");
2947 else
2948 disable_list_and_dump = secure;
2950 cache_push = config_get_list ("global", "cache_push");
2952 while (optind < argc)
2954 if (strv_printf (&cache_push, "%s", argv[optind++]) == 0)
2955 errx (EXIT_FAILURE, "%s", pwmd_strerror (GPG_ERR_ENOMEM));
2958 if (strchr (socketarg, '/') == NULL)
2960 socketdir = getcwd (buf, sizeof (buf));
2961 socketname = str_dup (socketarg);
2962 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2964 else
2966 socketname = str_dup (strrchr (socketarg, '/'));
2967 socketname++;
2968 socketarg[strlen (socketarg) - strlen (socketname) - 1] = 0;
2969 socketdir = str_dup (socketarg);
2970 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2973 if (chdir (datadir))
2975 log_write ("%s: %s", datadir,
2976 pwmd_strerror (gpg_error_from_errno (errno)));
2977 unlink (socketpath);
2978 goto do_exit;
2981 if (test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 0,
2982 mode))
2983 goto do_exit;
2986 * bind() doesn't like the full pathname of the socket or any non alphanum
2987 * characters so change to the directory where the socket is wanted then
2988 * create it then change to datadir.
2990 if (chdir (socketdir))
2992 log_write ("%s: %s", socketdir,
2993 pwmd_strerror (gpg_error_from_errno (errno)));
2994 goto do_exit;
2997 xfree (socketdir);
2999 if ((sockfd = socket (PF_UNIX, SOCK_STREAM, 0)) == -1)
3001 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
3002 goto do_exit;
3005 addr.sun_family = AF_UNIX;
3006 snprintf (addr.sun_path, sizeof (addr.sun_path), "%s", socketname);
3007 do_unlink = 1;
3008 if (bind (sockfd, (struct sockaddr *) &addr, sizeof (struct sockaddr)) ==
3011 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
3013 if (errno == EADDRINUSE)
3015 do_unlink = 0;
3016 log_write (_("Either there is another pwmd running or '%s' is a \n"
3017 "stale socket. Please remove it manually."), socketpath);
3020 goto do_exit;
3024 char *t = config_get_string ("global", "socket_perms");
3025 mode_t mask;
3027 if (t)
3029 mode = strtol (t, NULL, 8);
3030 mask = umask (0);
3031 xfree (t);
3033 if (chmod (socketname, mode) == -1)
3035 log_write ("%s: %s", socketname,
3036 pwmd_strerror (gpg_error_from_errno (errno)));
3037 close (sockfd);
3038 umask (mask);
3039 goto do_exit;
3042 umask (mask);
3046 xfree (--socketname);
3048 if (chdir (datadir))
3050 log_write ("%s: %s", datadir,
3051 pwmd_strerror (gpg_error_from_errno (errno)));
3052 close (sockfd);
3053 goto do_exit;
3056 xfree (datadir);
3059 * Set the cache entry for a file. Prompts for the password.
3061 if (cache_push)
3063 struct crypto_s *crypto = NULL;
3064 gpg_error_t rc = init_client_crypto (&crypto);
3066 if (rc)
3068 estatus = EXIT_FAILURE;
3069 goto do_exit;
3072 #ifdef WITH_AGENT
3073 if (use_agent)
3075 rc = agent_set_pinentry_options (crypto->agent);
3076 if (rc)
3078 estatus = EXIT_FAILURE;
3079 goto do_exit;
3082 #endif
3084 for (opt = 0; cache_push[opt]; opt++)
3086 if (!do_cache_push (cache_push[opt], crypto) && !force)
3088 strv_free (cache_push);
3089 startup_failure ();
3090 estatus = EXIT_FAILURE;
3091 cleanup_crypto (&crypto);
3092 goto do_exit;
3095 cleanup_crypto_stage1 (crypto);
3098 #ifdef WITH_AGENT
3099 if (use_agent)
3100 (void) kill_scd (crypto->agent);
3101 #endif
3103 cleanup_crypto (&crypto);
3104 strv_free (cache_push);
3105 log_write (!nofork ? _("Done. Daemonizing...") :
3106 _("Done. Waiting for connections..."));
3109 config_clear_keys ();
3111 if (listen (sockfd, 0) == -1)
3113 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
3114 goto do_exit;
3117 if (!nofork)
3119 switch (fork ())
3121 case -1:
3122 log_write ("fork(): %s",
3123 pwmd_strerror (gpg_error_from_errno (errno)));
3124 goto do_exit;
3125 case 0:
3126 close (0);
3127 close (1);
3128 close (2);
3129 setsid ();
3130 break;
3131 default:
3132 _exit (EXIT_SUCCESS);
3136 (void)test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 1,
3137 mode);
3138 cmdline = 0;
3139 pthread_key_create (&thread_name_key, free_key);
3140 pthread_setspecific (thread_name_key, str_dup ("main"));
3141 estatus = server_loop (sockfd, &socketpath);
3143 do_exit:
3144 if (socketpath && do_unlink)
3146 unlink (socketpath);
3147 xfree (socketpath);
3150 xfree (socketarg);
3151 #ifdef WITH_GNUTLS
3152 gnutls_global_deinit ();
3153 xfree (invoking_tls);
3154 #endif
3155 if (rcfile_tid)
3157 #ifdef HAVE_PTHREAD_CANCEL
3158 pthread_cancel (rcfile_tid);
3159 #else
3160 pthread_kill (rcfile_tid, SIGUSR2);
3161 pthread_cond_signal (&rcfile_cond);
3162 #endif
3163 pthread_join (rcfile_tid, NULL);
3166 pthread_cond_destroy (&rcfile_cond);
3167 pthread_mutex_destroy (&rcfile_mutex);
3168 pthread_key_delete (last_error_key);
3169 #ifndef HAVE_PTHREAD_CANCEL
3170 pthread_key_delete (signal_thread_key);
3171 #endif
3173 if (global_config)
3174 config_free (global_config);
3176 xfree (rcfile);
3177 xfree (home_directory);
3178 xfree (homedir);
3179 xmlCleanupParser ();
3180 xmlCleanupGlobals ();
3182 if (pidfile)
3183 unlink (pidfile);
3184 xfree (pidfile);
3186 if (estatus == EXIT_SUCCESS)
3187 log_write (_("pwmd exiting normally"));
3189 pthread_key_delete (thread_name_key);
3190 closelog ();
3191 #if defined(DEBUG) && !defined(MEM_DEBUG)
3192 xdump ();
3193 #endif
3195 if (log_fd != -1)
3196 close (log_fd);
3198 exit (estatus);