Version 3.0.12.
[pwmd.git] / src / pwmd.c
blobf874f02d9e8394c0b2bb376df22b8cf9a8fc927a
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->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 xmlSetStructuredErrorFunc (cl, xml_error_cb);
994 return 1;
996 fail:
997 log_write ("%s", pwmd_strerror (rc));
998 return 0;
1002 * This is called after a client_thread() terminates. Set with
1003 * pthread_cleanup_push().
1005 static void
1006 cleanup_cb (void *arg)
1008 struct client_thread_s *cn = arg;
1009 struct client_s *cl = cn->cl;
1011 MUTEX_LOCK (&cn_mutex);
1012 cn_thread_list = slist_remove (cn_thread_list, cn);
1013 MUTEX_UNLOCK (&cn_mutex);
1015 if (cl)
1017 cleanup_client (cl);
1018 if (cl->xml_error)
1019 xmlResetError (cl->xml_error);
1021 xfree (cl->xml_error);
1023 #ifdef WITH_GNUTLS
1024 if (cn->tls)
1026 gnutls_deinit (cn->tls->ses);
1027 xfree (cn->tls->fp);
1028 xfree (cn->tls);
1030 #endif
1032 if (!cn->atfork && cl->ctx)
1033 assuan_release (cl->ctx);
1034 else if (!cn->atfork && cl->thd && cl->thd->fd != -1)
1035 close (cl->thd->fd);
1037 if (cl->crypto)
1038 cleanup_crypto (&cl->crypto);
1040 pinentry_free_opts (&cl->pinentry_opts);
1041 xfree (cl);
1043 else
1045 if (cn->fd != -1)
1046 close (cn->fd);
1049 while (cn->msg_queue)
1051 struct status_msg_s *msg = cn->msg_queue;
1053 cn->msg_queue = msg->next;
1054 xfree (msg->line);
1055 xfree (msg);
1058 if (!cn->atfork && cn->status_msg_pipe[0] != -1)
1059 close (cn->status_msg_pipe[0]);
1061 if (!cn->atfork && cn->status_msg_pipe[1] != -1)
1062 close (cn->status_msg_pipe[1]);
1064 pthread_mutex_destroy (&cn->status_mutex);
1066 if (!cn->atfork)
1068 log_write (_("exiting, fd=%i"), cn->fd);
1069 send_status_all (STATUS_CLIENTS, NULL);
1072 xfree (cn);
1073 pthread_cond_signal (&quit_cond);
1076 void
1077 cleanup_all_clients (int atfork)
1079 /* This function may be called from pthread_atfork() which requires
1080 reinitialization. */
1081 if (atfork)
1083 pthread_mutexattr_t attr;
1085 pthread_mutexattr_init (&attr);
1086 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
1087 pthread_mutex_init (&cn_mutex, &attr);
1088 pthread_mutexattr_destroy (&attr);
1089 cache_mutex_init ();
1092 MUTEX_LOCK (&cn_mutex);
1094 while (slist_length (cn_thread_list))
1096 struct client_thread_s *thd = slist_nth_data (cn_thread_list, 0);
1098 thd->atfork = atfork;
1099 cleanup_cb (thd);
1102 exiting = 1;
1103 MUTEX_UNLOCK (&cn_mutex);
1104 cache_deinit (atfork);
1107 static gpg_error_t
1108 send_msg_queue (struct client_thread_s *thd)
1110 MUTEX_LOCK (&thd->status_mutex);
1111 gpg_error_t rc = 0;
1112 char c;
1114 read (thd->status_msg_pipe[0], &c, 1);
1116 while (thd->msg_queue)
1118 struct status_msg_s *msg = thd->msg_queue;
1120 thd->msg_queue = thd->msg_queue->next;
1121 MUTEX_UNLOCK (&thd->status_mutex);
1122 rc = send_status (thd->cl->ctx, msg->s, msg->line);
1123 MUTEX_LOCK (&thd->status_mutex);
1124 xfree (msg->line);
1125 xfree (msg);
1127 if (rc)
1128 break;
1131 MUTEX_UNLOCK (&thd->status_mutex);
1132 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1133 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
1135 return rc;
1138 static void *
1139 client_thread (void *data)
1141 struct client_thread_s *thd = data;
1142 struct client_s *cl = xcalloc (1, sizeof (struct client_s));
1144 #ifdef HAVE_PR_SET_NAME
1145 prctl (PR_SET_NAME, "client");
1146 #endif
1147 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1149 if (!cl)
1151 log_write ("%s(%i): %s", __FILE__, __LINE__,
1152 pwmd_strerror (GPG_ERR_ENOMEM));
1153 return NULL;
1156 MUTEX_LOCK (&cn_mutex);
1157 pthread_cleanup_push (cleanup_cb, thd);
1158 thd->cl = cl;
1159 cl->thd = thd;
1160 MUTEX_UNLOCK (&cn_mutex);
1162 if (new_connection (cl))
1164 int finished = 0;
1165 gpg_error_t rc;
1167 send_status_all (STATUS_CLIENTS, NULL);
1168 rc = send_status (cl->ctx, STATUS_CACHE, NULL);
1169 if (rc)
1171 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
1172 finished = 1;
1175 while (!finished)
1177 fd_set rfds;
1178 int n;
1179 int eof;
1181 FD_ZERO (&rfds);
1182 FD_SET (thd->fd, &rfds);
1183 FD_SET (thd->status_msg_pipe[0], &rfds);
1184 n = thd->fd > thd->status_msg_pipe[0]
1185 ? thd->fd : thd->status_msg_pipe[0];
1187 n = select (n + 1, &rfds, NULL, NULL, NULL);
1188 if (n == -1)
1190 log_write ("%s", strerror (errno));
1191 break;
1194 if (FD_ISSET (thd->status_msg_pipe[0], &rfds))
1196 rc = send_msg_queue (thd);
1197 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1198 break;
1201 if (!FD_ISSET (thd->fd, &rfds))
1202 continue;
1204 rc = assuan_process_next (cl->ctx, &eof);
1205 if (rc || eof)
1207 if (gpg_err_code (rc) == GPG_ERR_EOF || eof)
1208 break;
1210 log_write ("assuan_process_next(): rc=%i %s", rc,
1211 pwmd_strerror (rc));
1212 if (rc == gpg_error (GPG_ERR_ETIMEDOUT))
1213 break;
1215 rc = send_error (cl->ctx, rc);
1216 if (rc)
1218 log_write ("assuan_process_done(): rc=%i %s", rc,
1219 pwmd_strerror (rc));
1220 break;
1224 /* Since the msg queue pipe fd's are non-blocking, check for
1225 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1226 * client has already disconnected and will be converted to
1227 * GPG_ERR_EOF during assuan_process_next().
1229 rc = send_msg_queue (thd);
1230 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1231 break;
1235 pthread_cleanup_pop (1);
1236 return NULL;
1239 static int
1240 xml_import (const char *filename, const char *outfile,
1241 const char *keygrip, const char *sign_keygrip,
1242 const char *keyfile, int no_passphrase, const char *cipher,
1243 const char *params, unsigned long s2k_count, uint64_t iterations)
1245 xmlDocPtr doc;
1246 int fd;
1247 struct stat st;
1248 int len;
1249 xmlChar *xmlbuf;
1250 xmlChar *xml;
1251 gpg_error_t rc;
1252 struct crypto_s *crypto = NULL;
1253 void *key = NULL;
1254 size_t keylen = 0;
1255 int algo = cipher ? cipher_string_to_gcrypt ((char *) cipher) :
1256 GCRY_CIPHER_AES256;
1258 if (algo == -1)
1260 log_write ("ERR %i: %s", gpg_error (GPG_ERR_CIPHER_ALGO),
1261 pwmd_strerror (GPG_ERR_CIPHER_ALGO));
1262 return 0;
1265 if (stat (filename, &st) == -1)
1267 log_write ("%s: %s", filename,
1268 pwmd_strerror (gpg_error_from_errno (errno)));
1269 return 0;
1272 rc = init_client_crypto (&crypto);
1273 if (rc)
1274 return 0;
1276 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
1277 crypto->save.hdr.flags = set_cipher_flag (crypto->save.hdr.flags, algo);
1278 log_write (_("Importing XML from '%s'. Output will be written to '%s' ..."),
1279 filename, outfile);
1281 if ((fd = open (filename, O_RDONLY)) == -1)
1283 log_write ("%s: %s", filename,
1284 pwmd_strerror (gpg_error_from_errno (errno)));
1285 goto fail;
1288 if ((xmlbuf = xmalloc (st.st_size + 1)) == NULL)
1290 close (fd);
1291 log_write ("%s(%i): %s", __FILE__, __LINE__,
1292 pwmd_strerror (GPG_ERR_ENOMEM));
1293 goto fail;
1296 if (read (fd, xmlbuf, st.st_size) == -1)
1298 rc = gpg_error_from_errno (errno);
1299 close (fd);
1300 log_write ("%s: %s", filename, pwmd_strerror (rc));
1301 goto fail;
1304 close (fd);
1305 xmlbuf[st.st_size] = 0;
1307 * Make sure the document validates.
1309 if ((doc = xmlReadDoc (xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS)) == NULL)
1311 log_write ("xmlReadDoc() failed");
1312 xfree (xmlbuf);
1313 goto fail;
1316 xfree (xmlbuf);
1317 xmlNodePtr n = xmlDocGetRootElement (doc);
1318 if (n && !xmlStrEqual (n->name, (xmlChar *) "pwmd"))
1320 log_write (_("Could not find root \"pwmd\" element."));
1321 rc = GPG_ERR_BAD_DATA;
1324 if (!rc)
1325 rc = validate_import (NULL, n ? n->children : n);
1327 if (rc)
1329 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1330 xmlFreeDoc (doc);
1331 goto fail;
1334 xmlDocDumpMemory (doc, &xml, &len);
1335 xmlFreeDoc (doc);
1336 crypto->save.s2k_count = s2k_count;
1337 crypto->save.hdr.iterations = iterations;
1338 if (!use_agent)
1340 rc = export_common (NULL, 0, crypto, xml, len, outfile, keyfile, &key,
1341 &keylen, 0, 0, no_passphrase);
1342 if (!rc)
1343 log_write (_("Success!"));
1345 #ifdef WITH_AGENT
1346 else
1348 rc = agent_set_pinentry_options (crypto->agent);
1349 if (!rc)
1350 rc = agent_export_common (crypto, keygrip, sign_keygrip, no_passphrase,
1351 xml, len, outfile, params, keyfile);
1353 #endif
1355 gcry_free (key);
1356 xmlFree (xml);
1357 if (rc)
1359 send_error (NULL, rc);
1360 goto fail;
1363 cleanup_crypto (&crypto);
1364 return 1;
1366 fail:
1367 cleanup_crypto (&crypto);
1368 return 0;
1371 static int
1372 do_cache_push (const char *filename, struct crypto_s *crypto)
1374 unsigned char md5file[16];
1375 gpg_error_t rc;
1376 char *key = NULL;
1377 size_t keylen = 0;
1378 xmlDocPtr doc;
1379 struct cache_data_s *cdata;
1380 unsigned char *crc;
1381 size_t len;
1383 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1384 filename);
1386 if (valid_filename (filename) == 0)
1388 log_write (_("%s: Invalid characters in filename"), filename);
1389 return 0;
1392 rc = decrypt_common (NULL, 0, crypto, filename, &key, &keylen);
1393 if (rc)
1394 return 0;
1396 rc = parse_doc ((char *) crypto->plaintext, crypto->plaintext_len, &doc);
1397 if (rc)
1399 log_write ("%s", pwmd_strerror (rc));
1400 xfree (key);
1401 return 0;
1404 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
1405 cdata = xcalloc (1, sizeof (struct cache_data_s));
1406 if (!cdata)
1408 xmlFreeDoc (doc);
1409 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM));
1410 xfree (key);
1411 return 0;
1414 rc = get_checksum (filename, &crc, &len);
1415 if (rc)
1417 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1418 xmlFreeDoc (doc);
1419 free_cache_data_once (cdata);
1420 xfree (key);
1421 return 0;
1424 cdata->crc = crc;
1425 rc = encrypt_xml (NULL, cache_key, cache_keysize, GCRY_CIPHER_AES,
1426 crypto->plaintext, crypto->plaintext_len, &cdata->doc,
1427 &cdata->doclen, &cache_iv, &cache_blocksize, 0);
1428 if (!rc && !IS_PKI (crypto))
1430 cdata->key = key;
1431 cdata->keylen = keylen;
1433 else
1434 xfree (key);
1436 if (rc)
1438 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1439 xmlFreeDoc (doc);
1440 free_cache_data_once (cdata);
1441 return 0;
1444 #ifdef WITH_AGENT
1445 if (use_agent && IS_PKI (crypto))
1447 gcry_sexp_build ((gcry_sexp_t *) & cdata->pubkey, NULL, "%S",
1448 crypto->pkey_sexp);
1449 gcry_sexp_build ((gcry_sexp_t *) & cdata->sigkey, NULL, "%S",
1450 crypto->sigpkey_sexp);
1452 #endif
1454 int timeout = config_get_integer (filename, "cache_timeout");
1455 cache_add_file (md5file, crypto->grip, cdata, timeout);
1456 log_write (_("Successfully added '%s' to the cache."), filename);
1457 return 1;
1460 static gpg_error_t
1461 init_client (int fd, const char *addr)
1463 gpg_error_t rc = 0;
1464 struct client_thread_s *new = xcalloc (1, sizeof (struct client_thread_s));
1466 if (!new)
1468 close (fd);
1469 return GPG_ERR_ENOMEM;
1472 MUTEX_LOCK (&cn_mutex);
1473 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
1475 if (pipe (new->status_msg_pipe) == -1)
1476 rc = gpg_error_from_errno (errno);
1478 if (!rc)
1480 fcntl (new->status_msg_pipe[0], F_SETFL, O_NONBLOCK);
1481 fcntl (new->status_msg_pipe[1], F_SETFL, O_NONBLOCK);
1482 pthread_mutex_init (&new->status_mutex, NULL);
1485 if (!rc)
1487 #ifdef WITH_GNUTLS
1488 new->remote = addr ? 1 : 0;
1489 #endif
1490 new->fd = fd;
1491 rc = create_thread (client_thread, new, &new->tid, 1);
1492 if (rc)
1494 close (new->status_msg_pipe[0]);
1495 close (new->status_msg_pipe[1]);
1496 pthread_mutex_destroy (&new->status_mutex);
1500 if (!rc)
1502 struct slist_s *list = slist_append (cn_thread_list, new);
1504 if (list)
1506 cn_thread_list = list;
1507 if (addr)
1508 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1509 (pthread_t *) new->tid, fd, addr);
1510 else
1511 log_write (_("new connection: tid=%p, fd=%i"),
1512 (pthread_t *) new->tid, fd);
1514 else
1515 rc = GPG_ERR_ENOMEM;
1518 pthread_cleanup_pop (1);
1520 if (rc)
1522 xfree (new);
1523 close (fd);
1524 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1525 pwmd_strerror (rc));
1527 return rc;
1530 static void*
1531 keepalive_thread (void *arg)
1533 #ifndef HAVE_PTHREAD_CANCEL
1534 int *n = xmalloc (sizeof (int));
1536 *n = 0;
1537 pthread_setspecific (signal_thread_key, n);
1538 INIT_THREAD_SIGNAL;
1539 #endif
1541 #ifdef HAVE_PR_SET_NAME
1542 prctl (PR_SET_NAME, "keepalive");
1543 #endif
1544 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1546 for (;;)
1548 int n = config_get_integer ("global", "keepalive_interval");
1549 struct timeval tv = { n, 0 };
1550 #ifndef HAVE_PTHREAD_CANCEL
1551 int *sigusr2;
1553 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1554 if (*sigusr2)
1555 break;
1556 #endif
1558 send_status_all (STATUS_KEEPALIVE, NULL);
1559 select (0, NULL, NULL, NULL, &tv);
1562 return NULL;
1565 #ifdef WITH_GNUTLS
1566 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1567 static void *
1568 get_in_addr (struct sockaddr *sa)
1570 if (sa->sa_family == AF_INET)
1571 return &(((struct sockaddr_in *) sa)->sin_addr);
1573 return &(((struct sockaddr_in6 *) sa)->sin6_addr);
1576 static void *
1577 tcp_accept_thread (void *arg)
1579 int sockfd = *(int *) arg;
1580 #ifndef HAVE_PTHREAD_CANCEL
1581 int *n = xmalloc (sizeof (int));
1583 *n = 0;
1584 pthread_setspecific (signal_thread_key, n);
1585 INIT_THREAD_SIGNAL;
1586 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1587 #endif
1589 #ifdef HAVE_PR_SET_NAME
1590 prctl (PR_SET_NAME, "tcp_accept");
1591 #endif
1592 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1594 for (;;)
1596 struct sockaddr_storage raddr;
1597 socklen_t slen = sizeof (raddr);
1598 int fd;
1599 unsigned long n;
1600 char s[INET6_ADDRSTRLEN];
1601 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1602 #ifndef HAVE_PTHREAD_CANCEL
1603 int *sigusr2;
1605 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1606 if (*sigusr2)
1607 break;
1608 #endif
1610 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1611 if (fd == -1)
1613 if (errno == EMFILE || errno == ENFILE)
1614 log_write ("accept(): %s",
1615 pwmd_strerror (gpg_error_from_errno (errno)));
1616 else if (errno != EAGAIN)
1618 if (!quit) // probably EBADF
1619 log_write ("accept(): %s", strerror (errno));
1621 break;
1624 #ifndef HAVE_PTHREAD_CANCEL
1625 select (0, NULL, NULL, NULL, &tv);
1626 #endif
1627 continue;
1630 if (quit)
1631 break;
1633 inet_ntop (raddr.ss_family, get_in_addr ((struct sockaddr *) &raddr),
1634 s, sizeof s);
1635 (void) init_client (fd, s);
1636 n = config_get_integer ("global", "tcp_wait");
1637 if (n > 0)
1639 tv.tv_sec = (n * 100000) / 100000;
1640 tv.tv_usec = (n * 100000) % 100000;
1641 select (0, NULL, NULL, NULL, &tv);
1645 return NULL;
1648 static int
1649 start_stop_tls_with_protocol (int ipv6, int term)
1651 struct addrinfo hints, *servinfo, *p;
1652 int port = config_get_integer ("global", "tcp_port");
1653 char buf[7];
1654 int n;
1655 gpg_error_t rc;
1656 int *fd = ipv6 ? &tls6_fd : &tls_fd;
1658 if (term || config_get_boolean ("global", "enable_tcp") == 0)
1660 if (tls6_fd != -1)
1662 if (spawned_tls6)
1664 #ifdef HAVE_PTHREAD_CANCEL
1665 pthread_cancel (tls6_tid);
1666 #else
1667 pthread_kill (tls6_tid, SIGUSR2);
1668 #endif
1669 pthread_join (tls6_tid, NULL);
1672 shutdown (tls6_fd, SHUT_RDWR);
1673 close (tls6_fd);
1674 tls6_fd = -1;
1675 spawned_tls6 = 0;
1678 if (tls_fd != -1)
1680 if (spawned_tls)
1682 #ifdef HAVE_PTHREAD_CANCEL
1683 pthread_cancel (tls_tid);
1684 #else
1685 pthread_kill (tls_tid, SIGUSR2);
1686 #endif
1687 pthread_join (tls_tid, NULL);
1690 shutdown (tls_fd, SHUT_RDWR);
1691 close (tls_fd);
1692 tls_fd = -1;
1693 spawned_tls = 0;
1696 /* A client may still be connected. */
1697 if (!quit && x509_cred != NULL)
1698 tls_deinit_params ();
1700 return 1;
1703 if ((ipv6 && tls6_fd != -1) || (!ipv6 && tls_fd != -1))
1704 return 1;
1706 memset (&hints, 0, sizeof (hints));
1707 hints.ai_family = ipv6 ? AF_INET6 : AF_INET;
1708 hints.ai_socktype = SOCK_STREAM;
1709 hints.ai_flags = AI_PASSIVE;
1710 snprintf (buf, sizeof (buf), "%i", port);
1712 if ((n = getaddrinfo (NULL, buf, &hints, &servinfo)) == -1)
1714 log_write ("getaddrinfo(): %s", gai_strerror (n));
1715 return 0;
1718 for (n = 0, p = servinfo; p != NULL; p = p->ai_next)
1720 int r = 1;
1722 if ((ipv6 && p->ai_family != AF_INET6)
1723 || (!ipv6 && p->ai_family != AF_INET))
1724 continue;
1726 if ((*fd = socket (p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
1728 log_write ("socket(): %s", strerror (errno));
1729 continue;
1732 if (setsockopt (*fd, SOL_SOCKET, SO_REUSEADDR, &r, sizeof (int)) == -1)
1734 log_write ("setsockopt(): %s",
1735 pwmd_strerror (gpg_error_from_errno (errno)));
1736 freeaddrinfo (servinfo);
1737 goto fail;
1740 if (bind (*fd, p->ai_addr, p->ai_addrlen) == -1)
1742 close (*fd);
1743 log_write ("bind(): %s",
1744 pwmd_strerror (gpg_error_from_errno (errno)));
1745 continue;
1748 n++;
1749 break;
1752 freeaddrinfo (servinfo);
1754 if (!n)
1755 goto fail;
1757 #if HAVE_DECL_SO_BINDTODEVICE != 0
1758 char *tmp = config_get_string ("global", "tcp_interface");
1759 if (tmp && setsockopt (*fd, SOL_SOCKET, SO_BINDTODEVICE, tmp,
1760 strlen (tmp)) == -1)
1762 log_write ("setsockopt(): %s",
1763 pwmd_strerror (gpg_error_from_errno (errno)));
1764 xfree (tmp);
1765 goto fail;
1768 xfree (tmp);
1769 #endif
1771 if (x509_cred == NULL)
1773 rc = tls_init_params ();
1774 if (rc)
1775 goto fail;
1778 if (listen (*fd, 0) == -1)
1780 log_write ("listen(): %s", strerror (errno));
1781 goto fail;
1784 if (ipv6)
1785 rc = create_thread (tcp_accept_thread, fd, &tls6_tid, 0);
1786 else
1787 rc = create_thread (tcp_accept_thread, fd, &tls_tid, 0);
1789 if (rc)
1791 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1792 pwmd_strerror (rc));
1793 goto fail;
1796 if (ipv6)
1797 spawned_tls6 = 1;
1798 else
1799 spawned_tls = 1;
1801 return 1;
1803 fail:
1804 start_stop_tls_with_protocol (0, 1);
1805 if (tls_fd != -1)
1806 close (tls_fd);
1808 if (tls6_fd != -1)
1809 close (tls6_fd);
1811 tls_fd = -1;
1812 tls6_fd = -1;
1813 return 0;
1816 static int
1817 start_stop_tls (int term)
1819 char *s = config_get_string ("global", "tcp_bind");
1820 int b;
1822 if (!s)
1823 return 0;
1825 if (!strcmp (s, "any"))
1827 b = start_stop_tls_with_protocol (0, term);
1828 if (b)
1829 b = start_stop_tls_with_protocol (1, term);
1831 else if (!strcmp (s, "ipv4"))
1832 b = start_stop_tls_with_protocol (0, term);
1833 else if (!strcmp (s, "ipv6"))
1834 b = start_stop_tls_with_protocol (1, term);
1835 else
1836 b = 0;
1838 xfree (s);
1839 return b;
1841 #endif
1843 static void *
1844 accept_thread (void *arg)
1846 int sockfd = *(int *) arg;
1847 #ifndef HAVE_PTHREAD_CANCEL
1848 int *n = xmalloc (sizeof (int));
1850 *n = 0;
1851 pthread_setspecific (signal_thread_key, n);
1852 INIT_THREAD_SIGNAL;
1853 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1854 #endif
1856 #ifdef HAVE_PR_SET_NAME
1857 prctl (PR_SET_NAME, "accept");
1858 #endif
1859 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1861 for (;;)
1863 socklen_t slen = sizeof (struct sockaddr_un);
1864 struct sockaddr_un raddr;
1865 int fd;
1866 #ifndef HAVE_PTHREAD_CANCEL
1867 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1868 int *sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1870 if (*sigusr2)
1871 break;
1872 #endif
1874 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1875 if (fd == -1)
1877 if (errno == EMFILE || errno == ENFILE)
1878 log_write ("accept(): %s",
1879 pwmd_strerror (gpg_error_from_errno (errno)));
1880 else if (errno != EAGAIN)
1882 if (!quit) // probably EBADF
1883 log_write ("accept(): %s",
1884 pwmd_strerror (gpg_error_from_errno (errno)));
1886 break;
1889 #ifndef HAVE_PTHREAD_CANCEL
1890 select (0, NULL, NULL, NULL, &tv);
1891 #endif
1892 continue;
1895 (void) init_client (fd, NULL);
1898 /* Just in case accept() failed for some reason other than EBADF */
1899 quit = 1;
1900 return NULL;
1903 static void *
1904 cache_timer_thread (void *arg)
1906 #ifndef HAVE_PTHREAD_CANCEL
1907 int *n = xmalloc (sizeof (int));
1909 *n = 0;
1910 pthread_setspecific (signal_thread_key, n);
1911 INIT_THREAD_SIGNAL;
1912 #endif
1914 #ifdef HAVE_PR_SET_NAME
1915 prctl (PR_SET_NAME, "cache timer");
1916 #endif
1917 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1919 for (;;)
1921 struct timeval tv = { 1, 0 };
1922 #ifndef HAVE_PTHREAD_CANCEL
1923 int *n;
1925 n = (int *) pthread_getspecific (signal_thread_key);
1926 if (*n)
1927 break;
1928 #endif
1930 select (0, NULL, NULL, NULL, &tv);
1931 cache_adjust_timeout ();
1934 return NULL;
1937 static int
1938 signal_loop (sigset_t sigset)
1940 int done = 0;
1941 int siint = 0;
1945 int sig;
1947 sigwait (&sigset, &sig);
1949 if (sig != SIGQUIT)
1950 log_write (_("caught signal %i (%s)"), sig, strsignal (sig));
1952 switch (sig)
1954 case SIGHUP:
1955 pthread_cond_signal (&rcfile_cond);
1956 break;
1957 case SIGUSR1:
1958 log_write (_("clearing file cache"));
1959 cache_clear (NULL);
1960 send_status_all (STATUS_CACHE, NULL);
1961 break;
1962 case SIGQUIT:
1963 done = 1;
1964 break;
1965 default:
1966 siint = 1;
1967 done = 1;
1968 break;
1971 while (!done);
1973 return siint;
1976 static void
1977 catchsig (int sig)
1979 log_write (_ ("Caught signal %i (%s). Exiting."), sig, strsignal (sig));
1980 #ifdef HAVE_BACKTRACE
1981 BACKTRACE (__FUNCTION__);
1982 #endif
1983 longjmp (jmp, 1);
1986 static void *
1987 waiting_for_exit (void *arg)
1989 int last = 0;
1990 #ifndef HAVE_PTHREAD_CANCEL
1991 int *n = xmalloc (sizeof (int));
1993 *n = 0;
1994 pthread_setspecific (signal_thread_key, n);
1995 INIT_THREAD_SIGNAL;
1996 #endif
1998 #ifdef HAVE_PR_SET_NAME
1999 prctl (PR_SET_NAME, "exiting");
2000 #endif
2001 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
2002 log_write (_("waiting for all clients to disconnect"));
2003 MUTEX_LOCK (&quit_mutex);
2004 pthread_cleanup_push (cleanup_mutex_cb, &quit_mutex);
2006 for (;;)
2008 struct timespec ts;
2009 int n;
2011 MUTEX_LOCK (&cn_mutex);
2012 n = slist_length (cn_thread_list);
2013 MUTEX_UNLOCK (&cn_mutex);
2014 if (!n)
2015 break;
2017 #ifndef HAVE_PTHREAD_CANCEL
2018 int *s = (int *) pthread_getspecific (signal_thread_key);
2019 if (*s)
2020 break;
2021 #endif
2023 if (last != n)
2025 log_write (_("%i clients remain"), n);
2026 last = n;
2029 INIT_TIMESPEC (SIG_TIMEOUT, ts);
2030 pthread_cond_timedwait (&quit_cond, &quit_mutex, &ts);
2033 kill (getpid (), SIGQUIT);
2034 pthread_cleanup_pop (1);
2035 return NULL;
2038 static int
2039 server_loop (int sockfd, char **socketpath)
2041 pthread_t accept_tid;
2042 pthread_t cache_timeout_tid;
2043 int cancel_timeout_thread = 0, cancel_accept_thread = 0;
2044 int cancel_keepalive_thread = 0;
2045 sigset_t sigset;
2046 int n;
2047 int segv = 0;
2048 gpg_error_t rc;
2050 init_commands ();
2051 sigemptyset (&sigset);
2053 /* Termination */
2054 sigaddset (&sigset, SIGTERM);
2055 sigaddset (&sigset, SIGINT);
2057 /* Clears the file cache. */
2058 sigaddset (&sigset, SIGUSR1);
2060 /* Configuration file reloading. */
2061 sigaddset (&sigset, SIGHUP);
2063 /* For exiting cleanly. */
2064 sigaddset (&sigset, SIGQUIT);
2066 #ifndef HAVE_PTHREAD_CANCEL
2068 The socket, cache and rcfile threads use this signal when
2069 pthread_cancel() is unavailable. Prevent the main thread from
2070 catching this signal from another process.
2072 sigaddset (&sigset, SIGUSR2);
2073 #endif
2075 /* When mem.c cannot find a pointer in the list (double free). */
2076 signal (SIGABRT, catchsig);
2077 sigaddset (&sigset, SIGABRT);
2078 sigprocmask (SIG_BLOCK, &sigset, NULL);
2080 #ifndef HAVE_PTHREAD_CANCEL
2081 /* Remove this signal from the watched signals in signal_loop(). */
2082 sigdelset (&sigset, SIGUSR2);
2083 #endif
2085 /* Ignored everywhere. When a client disconnects abnormally this signal
2086 * gets raised. It isn't needed though because client_thread() will check
2087 * for rcs even after the client disconnects. */
2088 signal (SIGPIPE, SIG_IGN);
2090 /* Can show a backtrace of the stack in the log. */
2091 signal (SIGSEGV, catchsig);
2093 #ifdef WITH_GNUTLS
2094 /* Needs to be done after the fork(). */
2095 if (!start_stop_tls (0))
2097 segv = 1;
2098 goto done;
2100 #endif
2102 pthread_mutex_init (&quit_mutex, NULL);
2103 pthread_cond_init (&quit_cond, NULL);
2104 char *p = get_username (getuid());
2105 log_write (_("%s started for user %s"), PACKAGE_STRING, p);
2106 xfree (p);
2108 #ifdef WITH_GNUTLS
2109 if (config_get_boolean ("global", "enable_tcp"))
2110 log_write (_("Listening on %s and TCP port %i as user %i"), *socketpath,
2111 config_get_integer ("global", "tcp_port"), invoking_uid);
2112 else
2113 log_write (_("Listening on %s"), *socketpath);
2114 #else
2115 log_write (_("Listening on %s"), *socketpath);
2116 #endif
2118 rc = create_thread (keepalive_thread, NULL, &keepalive_tid, 0);
2119 if (rc)
2121 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2122 pwmd_strerror (rc));
2123 goto done;
2126 cancel_keepalive_thread = 1;
2127 rc = create_thread (reload_rcfile_thread, NULL, &rcfile_tid, 0);
2128 if (rc)
2130 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2131 pwmd_strerror (rc));
2132 goto done;
2135 rc = create_thread (cache_timer_thread, NULL, &cache_timeout_tid, 0);
2136 if (rc)
2138 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2139 pwmd_strerror (rc));
2140 goto done;
2143 cancel_timeout_thread = 1;
2144 rc = create_thread (accept_thread, &sockfd, &accept_tid, 0);
2145 if (rc)
2147 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2148 pwmd_strerror (rc));
2149 goto done;
2152 cancel_accept_thread = 1;
2153 if (!setjmp (jmp))
2154 signal_loop (sigset);
2155 else
2156 segv = 1;
2158 done:
2160 * We're out of the main server loop. This happens when a signal was sent
2161 * to terminate the daemon. We'll wait for all clients to disconnect
2162 * before exiting but exit immediately if another termination signal is
2163 * sent.
2165 if (cancel_accept_thread)
2167 #ifdef HAVE_PTHREAD_CANCEL
2168 int n = pthread_cancel (accept_tid);
2169 #else
2170 int n = pthread_kill (accept_tid, SIGUSR2);
2171 #endif
2172 if (!n)
2173 pthread_join (accept_tid, NULL);
2176 #ifdef WITH_GNUTLS
2177 start_stop_tls (1);
2178 #endif
2179 shutdown (sockfd, SHUT_RDWR);
2180 close (sockfd);
2181 unlink (*socketpath);
2182 xfree (*socketpath);
2183 *socketpath = NULL;
2184 MUTEX_LOCK (&cn_mutex);
2185 n = slist_length (cn_thread_list);
2186 MUTEX_UNLOCK (&cn_mutex);
2188 if (n && !segv)
2190 pthread_t tid;
2192 rc = create_thread (waiting_for_exit, NULL, &tid, 0);
2193 if (!rc)
2195 if (signal_loop (sigset))
2197 log_write (_("Received second termination request. Exiting."));
2198 #ifdef HAVE_PTHREAD_CANCEL
2199 pthread_cancel (tid);
2200 #else
2201 pthread_kill (tid, SIGUSR2);
2202 #endif
2203 pthread_join (tid, NULL);
2206 else
2207 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2208 pwmd_strerror (rc));
2211 if (cancel_timeout_thread)
2213 #ifdef HAVE_PTHREAD_CANCEL
2214 pthread_cancel (cache_timeout_tid);
2215 #else
2216 pthread_kill (cache_timeout_tid, SIGUSR2);
2217 #endif
2218 pthread_join (cache_timeout_tid, NULL);
2221 if (cancel_keepalive_thread)
2223 #ifdef HAVE_PTHREAD_CANCEL
2224 pthread_cancel (keepalive_tid);
2225 #else
2226 pthread_kill (keepalive_tid, SIGUSR2);
2227 #endif
2228 pthread_join (keepalive_tid, NULL);
2231 cleanup_all_clients (0);
2232 #ifdef WITH_GNUTLS
2233 start_stop_tls (1);
2234 #endif
2235 deinit_commands ();
2236 pthread_cond_destroy (&quit_cond);
2237 pthread_mutex_destroy (&quit_mutex);
2238 return segv ? EXIT_FAILURE : EXIT_SUCCESS;;
2241 static void
2242 startup_failure ()
2244 log_write (_
2245 ("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
2246 cache_clear (NULL);
2249 /* This is called from cache.c:clear_once(). See
2250 * command.c:clearcache_command() for details about lock checking.
2252 static gpg_error_t
2253 free_cache_data (file_cache_t * cache)
2255 gpg_error_t rc = GPG_ERR_NO_DATA;
2256 int i, t;
2257 struct client_thread_s *found = NULL;
2258 int self = 0;
2260 if (!cache->data)
2261 return 0;
2263 cache_lock ();
2264 MUTEX_LOCK (&cn_mutex);
2265 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
2266 t = slist_length (cn_thread_list);
2268 for (i = 0; i < t; i++)
2270 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2272 if (!thd->cl)
2273 continue;
2275 if (!memcmp (thd->cl->md5file, cache->filename,
2276 sizeof (cache->filename)))
2278 if (pthread_equal (pthread_self (), thd->tid))
2280 found = thd;
2281 self = 1;
2282 continue;
2285 /* Continue trying to find a client who has the same file open and
2286 * also has a lock. */
2287 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0, -1);
2288 if (!rc)
2290 self = 0;
2291 found = thd;
2292 break;
2297 if (self && (!rc || rc == GPG_ERR_NO_DATA))
2298 rc = cache_lock_mutex (found->cl->ctx, found->cl->md5file, -1, 0, -1);
2300 if (exiting || !rc || rc == GPG_ERR_NO_DATA)
2302 free_cache_data_once (cache->data);
2303 cache->data = NULL;
2304 cache->defer_clear = 0;
2305 cache->timeout = -1;
2307 if (found)
2308 cache_unlock_mutex (found->cl->md5file, 0);
2310 rc = 0;
2313 if (rc)
2314 cache->defer_clear = 1;
2316 pthread_cleanup_pop (1);
2317 cache_unlock ();
2318 return rc;
2321 static int
2322 convert_v2_datafile (const char *filename, const char *cipher,
2323 const char *keyfile, const char *keygrip,
2324 const char *sign_keygrip, int nopass,
2325 const char *outfile, const char *keyparam,
2326 unsigned long s2k_count, uint64_t iterations)
2328 gpg_error_t rc;
2329 void *data = NULL;
2330 size_t datalen;
2331 struct crypto_s *crypto = NULL;
2332 uint16_t ver;
2333 int algo;
2334 void *key = NULL;
2335 size_t keylen = 0;
2337 if (outfile[0] == '-' && outfile[1] == 0)
2338 outfile = NULL;
2340 log_write (_("Converting version 2 data file \"%s\" ..."), filename);
2341 if (access (filename, R_OK) == -1)
2343 log_write ("%s: %s", filename,
2344 pwmd_strerror (gpg_error_from_errno (errno)));
2345 return 0;
2348 if (keyfile)
2350 log_write (_("Using passphrase file \"%s\" for decryption ..."),
2351 keyfile);
2352 if (access (keyfile, R_OK) == -1)
2354 log_write ("%s: %s", keyfile,
2355 pwmd_strerror (gpg_error_from_errno (errno)));
2356 return 0;
2360 rc = read_v2_datafile (filename, keyfile, &data, &datalen, &ver, &algo);
2361 if (rc)
2363 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2364 return 0;
2367 if (cipher)
2369 algo = cipher_string_to_gcrypt (cipher);
2370 if (algo == -1)
2372 rc = GPG_ERR_CIPHER_ALGO;
2373 goto fail;
2377 if (ver < 0x212)
2379 xmlDocPtr doc;
2381 rc = parse_doc (data, datalen, &doc);
2382 if (rc)
2383 goto fail;
2385 rc = convert_pre_212_elements (doc);
2386 gcry_free (data);
2387 data = NULL;
2388 if (!rc)
2390 xmlDocDumpFormatMemory (doc, (xmlChar **) & data, (int *) &datalen,
2392 if (!data)
2393 rc = GPG_ERR_ENOMEM;
2396 xmlFreeDoc (doc);
2397 if (rc)
2398 goto fail;
2401 rc = init_client_crypto (&crypto);
2402 if (!rc)
2404 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
2405 crypto->save.hdr.flags = set_cipher_flag (crypto->save.hdr.flags, algo);
2406 crypto->save.s2k_count = s2k_count;
2407 crypto->save.hdr.iterations = iterations;
2409 if (!use_agent)
2411 rc = export_common (NULL, 0, crypto, data, datalen, outfile, keyfile,
2412 &key, &keylen, 0, 0, nopass);
2414 #ifdef WITH_AGENT
2415 else
2417 rc = agent_set_pinentry_options (crypto->agent);
2418 if (!rc)
2419 rc = agent_export_common (crypto, keygrip, sign_keygrip, nopass,
2420 data, datalen, outfile, keyparam,
2421 no_passphrase_file ? NULL : keyfile);
2423 #endif
2424 if (!rc)
2425 log_write (_("Output written to \"%s\"."), outfile);
2428 fail:
2429 if (ver < 0x212)
2430 xmlFree (data);
2431 else
2432 gcry_free (data);
2434 gcry_free (key);
2435 cleanup_crypto (&crypto);
2437 if (rc)
2438 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2439 return rc ? 0 : 1;
2442 static void
2443 usage (const char *pn, int status)
2445 FILE *fp = status == EXIT_FAILURE ? stderr : stdout;
2447 fprintf (fp, _("Usage: %s [OPTIONS] [file1] [...]\n"
2448 " -f, --rcfile=filename load the specfied configuration file\n"
2449 " (~/.pwmd/config)\n"
2450 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2451 #ifdef WITH_AGENT
2452 " --use-agent enable use of gpg-agent\n"
2453 #endif
2454 " -n, --no-fork run as a foreground process\n"
2455 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2456 " --ignore, --force ignore file errors during startup\n"
2457 " --debug-level=keywords log protocol output (see manual for details)\n"
2458 " -o, --outfile=filename output file when importing or converting\n"
2459 " -C, --convert=filename convert a version 2 data file to version 3\n"
2460 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2461 " -k, --passphrase-file=file for use when importing or converting\n"
2462 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2463 " converting\n"
2464 " --no-passphrase when importing or converting\n"
2465 " --keygrip=hex public key to use when encrypting\n"
2466 " --sign-keygrip=hex private key to use when signing\n"
2467 " --keyparam=s-exp custom key parameters to use (RSA-2048)\n"
2468 " --cipher=string encryption cipher (aes256)\n"
2469 " --cipher-iterations=N cipher iteration count (N+1)\n"
2470 " --s2k-count=N hash iteration count (>65536, calibrated)\n"
2471 " --help this help text\n"
2472 " --version show version and compile time features\n"),
2473 pn);
2474 exit (status);
2477 static void
2478 unlink_stale_socket (const char *sock, const char *pidfile)
2480 log_write (_ ("removing stale socket %s"), sock);
2481 unlink (sock);
2482 unlink (pidfile);
2485 static int
2486 test_pidfile (const char *path, const char *sock, char *buf, size_t buflen,
2487 char **pidfile, int create, mode_t mode)
2489 pid_t pid;
2490 int fd;
2491 size_t len;
2493 if (!create)
2495 snprintf (buf, buflen, "%s/%s.pid", homedir, sock);
2496 *pidfile = str_dup (buf);
2497 fd = open (buf, O_RDONLY);
2499 else
2500 fd = open (*pidfile, O_CREAT|O_WRONLY|O_TRUNC, mode);
2502 if (fd == -1)
2504 if (!create && errno != ENOENT)
2506 log_write ("%s: %s", buf, pwmd_strerror (errno));
2507 free (*pidfile);
2508 *pidfile = NULL;
2509 return -1;
2511 else if (!create)
2512 return 0;
2514 log_write ("%s: %s", *pidfile, strerror (errno));
2515 return -1;
2518 if (create)
2520 snprintf (buf, buflen, "%i", getpid ());
2521 write (fd, buf, strlen (buf));
2522 close (fd);
2523 return 0;
2526 len = read (fd, buf, sizeof(buf));
2527 close (fd);
2528 if (len == 0)
2530 unlink_stale_socket (path, *pidfile);
2531 return 0;
2534 if (sscanf (buf, "%5i", &pid) != 1 || pid == 0)
2536 unlink_stale_socket (path, *pidfile);
2537 return 0;
2540 if (kill (pid, 0) == -1)
2542 unlink_stale_socket (path, *pidfile);
2543 return 0;
2546 log_write (_ ("an instance for socket %s is already running"), path);
2547 xfree (*pidfile);
2548 *pidfile = NULL;
2549 return 1;
2553 main (int argc, char *argv[])
2555 int opt;
2556 struct sockaddr_un addr;
2557 char buf[PATH_MAX];
2558 char *socketpath = NULL, *socketdir, *socketname = NULL;
2559 char *socketarg = NULL;
2560 char *datadir = NULL;
2561 char *pidfile = NULL;
2562 mode_t mode = 0600;
2563 int x;
2564 char *p;
2565 char **cache_push = NULL;
2566 char *import = NULL, *keygrip = NULL, *sign_keygrip = NULL;
2567 char *keyparam = NULL;
2568 int estatus = EXIT_FAILURE;
2569 int sockfd;
2570 char *outfile = NULL;
2571 int do_unlink = 0;
2572 int secure = 0;
2573 int show_version = 0;
2574 int force = 0;
2575 int no_passphrase = 0;
2576 gpg_error_t rc;
2577 char *convertfile = NULL;
2578 char *cipher = NULL;
2579 char *keyfile = NULL;
2580 unsigned long s2k_count = 0;
2581 uint64_t iterations = 0;
2582 int exists;
2583 char *debug_level_opt = NULL;
2584 int optindex;
2585 /* Must maintain the same order as longopts[] */
2586 enum
2588 OPT_VERSION, OPT_HELP,
2589 #ifdef WITH_AGENT
2590 OPT_AGENT,
2591 #endif
2592 OPT_DEBUG_LEVEL, OPT_HOMEDIR, OPT_NO_FORK, OPT_DISABLE_DUMP,
2593 OPT_IGNORE, OPT_FORCE, OPT_RCFILE, OPT_CONVERT,
2594 OPT_PASSPHRASE_FILE, OPT_IMPORT, OPT_OUTFILE,
2595 OPT_NO_PASSPHRASE_FILE, OPT_KEYGRIP, OPT_SIGN_KEYGRIP,
2596 OPT_KEYPARAM, OPT_CIPHER, OPT_ITERATIONS, OPT_S2K_COUNT,
2597 OPT_NO_PASSPHRASE
2599 const char *optstring = "nf:C:k:I:o:";
2600 const struct option longopts[] = {
2601 {"version", no_argument, 0, 0},
2602 {"help", no_argument, 0, 0},
2603 #ifdef WITH_AGENT
2604 {"use-agent", no_argument, 0, 0},
2605 #endif
2606 {"debug-level", required_argument, 0, 0},
2607 {"homedir", required_argument, 0, 0},
2608 {"no-fork", no_argument, 0, 'n'},
2609 {"disable_dump", no_argument, 0, 0},
2610 {"ignore", no_argument, 0, 0},
2611 {"force", no_argument, 0, 0},
2612 {"rcfile", required_argument, 0, 'f'},
2613 {"convert", required_argument, 0, 'C'},
2614 {"passphrase-file", required_argument, 0, 'k'},
2615 {"import", required_argument, 0, 'I'},
2616 {"outfile", required_argument, 0, 'o'},
2617 {"no-passphrase-file", no_argument, 0, 0},
2618 {"keygrip", required_argument, 0, 0},
2619 {"sign-keygrip", required_argument, 0, 0},
2620 {"keyparam", required_argument, 0, 0},
2621 {"cipher", required_argument, 0, 0},
2622 {"cipher-iterations", required_argument, 0, 0},
2623 {"s2k-count", required_argument, 0, 0},
2624 {"no-passphrase", no_argument, 0, 0},
2625 {0, 0, 0, 0}
2628 log_fd = -1;
2630 #ifndef DEBUG
2631 #ifdef HAVE_SETRLIMIT
2632 struct rlimit rl;
2634 rl.rlim_cur = rl.rlim_max = 0;
2636 if (setrlimit (RLIMIT_CORE, &rl) != 0)
2637 err (EXIT_FAILURE, "setrlimit()");
2638 #endif
2640 #ifdef HAVE_PR_SET_DUMPABLE
2641 prctl (PR_SET_DUMPABLE, 0);
2642 #endif
2643 #endif
2645 #ifdef ENABLE_NLS
2646 setlocale (LC_ALL, "");
2647 bindtextdomain ("pwmd", LOCALEDIR);
2648 textdomain ("pwmd");
2649 #endif
2651 #ifndef MEM_DEBUG
2652 xmem_init ();
2653 #endif
2654 gpg_err_init ();
2656 if (setup_crypto ())
2657 exit (EXIT_FAILURE);
2659 #ifdef WITH_GNUTLS
2660 gnutls_global_set_mem_functions (xmalloc, xmalloc, secure_mem_check,
2661 xrealloc, xfree);
2662 gnutls_global_init ();
2663 gnutls_global_set_log_function (tls_log);
2664 gnutls_global_set_log_level (1);
2665 tls_fd = -1;
2666 tls6_fd = -1;
2667 #endif
2668 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
2669 xmlInitMemory ();
2670 xmlInitGlobals ();
2671 xmlInitParser ();
2672 xmlXPathInit ();
2673 cmdline = 1;
2674 use_agent = 0;
2676 while ((opt = getopt_long (argc, argv, optstring, longopts, &optindex))
2677 != -1)
2679 switch (opt)
2681 case 'I':
2682 import = optarg;
2683 break;
2684 case 'C':
2685 convertfile = optarg;
2686 break;
2687 case 'k':
2688 keyfile = optarg;
2689 break;
2690 case 'o':
2691 outfile = optarg;
2692 break;
2693 case 'D':
2694 secure = 1;
2695 break;
2696 case 'n':
2697 nofork = 1;
2698 break;
2699 case 'f':
2700 rcfile = str_dup (optarg);
2701 break;
2702 default:
2703 usage (argv[0], EXIT_FAILURE);
2704 break;
2705 case 0:
2706 switch (optindex)
2708 case OPT_VERSION:
2709 show_version = 1;
2710 break;
2711 case OPT_HELP:
2712 usage (argv[0], 0);
2713 break;
2714 #ifdef WITH_AGENT
2715 case OPT_AGENT:
2716 use_agent = 1;
2717 break;
2718 #endif
2719 case OPT_DEBUG_LEVEL:
2720 debug_level_opt = optarg;
2721 break;
2722 case OPT_HOMEDIR:
2723 homedir = str_dup (optarg);
2724 break;
2725 case OPT_NO_FORK:
2726 nofork = 1;
2727 break;
2728 case OPT_DISABLE_DUMP:
2729 secure = 1;
2730 break;
2731 case OPT_IGNORE:
2732 case OPT_FORCE:
2733 force = 1;
2734 break;
2735 case OPT_RCFILE:
2736 rcfile = str_dup (optarg);
2737 break;
2738 case OPT_CONVERT:
2739 convertfile = optarg;
2740 break;
2741 case OPT_PASSPHRASE_FILE:
2742 keyfile = optarg;
2743 break;
2744 case OPT_IMPORT:
2745 import = optarg;
2746 break;
2747 case OPT_OUTFILE:
2748 outfile = optarg;
2749 break;
2750 case OPT_NO_PASSPHRASE_FILE:
2751 no_passphrase_file = 1;
2752 break;
2753 case OPT_KEYGRIP:
2754 keygrip = optarg;
2755 break;
2756 case OPT_SIGN_KEYGRIP:
2757 sign_keygrip = optarg;
2758 break;
2759 case OPT_KEYPARAM:
2760 keyparam = optarg;
2761 break;
2762 case OPT_CIPHER:
2763 cipher = optarg;
2764 break;
2765 case OPT_ITERATIONS:
2766 iterations = strtoull (optarg, NULL, 10);
2767 break;
2768 case OPT_S2K_COUNT:
2769 s2k_count = strtoul (optarg, NULL, 10);
2770 break;
2771 case OPT_NO_PASSPHRASE:
2772 no_passphrase = 1;
2773 break;
2774 default:
2775 usage (argv[0], 1);
2780 if (show_version)
2782 printf (_("%s\n\n"
2783 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014\n"
2784 "%s\n"
2785 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2786 "Compile time features:\n%s"), PACKAGE_STRING,
2787 PACKAGE_BUGREPORT,
2788 #ifdef PWMD_HOMEDIR
2789 "+PWMD_HOMEDIR=" PWMD_HOMEDIR "\n"
2790 #endif
2791 #ifdef WITH_AGENT
2792 "+WITH_AGENT\n"
2793 #else
2794 "-WITH_AGENT\n"
2795 #endif
2796 #ifdef WITH_QUALITY
2797 "+WITH_QUALITY\n"
2798 #else
2799 "-WITH_QUALITY\n"
2800 #endif
2801 #ifdef WITH_GNUTLS
2802 "+WITH_GNUTLS\n"
2803 #else
2804 "-WITH_GNUTLS\n"
2805 #endif
2806 #ifdef DEBUG
2807 "+DEBUG\n"
2808 #else
2809 "-DEBUG\n"
2810 #endif
2811 #ifdef MEM_DEBUG
2812 "+MEM_DEBUG\n"
2813 #else
2814 "-MEM_DEBUG\n"
2815 #endif
2816 #ifdef MUTEX_DEBUG
2817 "+MUTEX_DEBUG\n"
2818 #else
2819 "-MUTEX_DEBUG\n"
2820 #endif
2822 exit (EXIT_SUCCESS);
2825 if (!homedir)
2826 #ifdef PWMD_HOMEDIR
2827 homedir = str_dup(PWMD_HOMEDIR);
2828 #else
2829 homedir = str_asprintf ("%s/.pwmd", get_home_dir());
2830 #endif
2832 if (mkdir (homedir, 0700) == -1 && errno != EEXIST)
2833 err (EXIT_FAILURE, "%s", homedir);
2835 snprintf (buf, sizeof (buf), "%s/data", homedir);
2836 if (mkdir (buf, 0700) == -1 && errno != EEXIST)
2837 err (EXIT_FAILURE, "%s", buf);
2839 datadir = str_dup (buf);
2840 pthread_mutexattr_t attr;
2841 pthread_mutexattr_init (&attr);
2842 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
2843 pthread_mutex_init (&rcfile_mutex, &attr);
2844 pthread_cond_init (&rcfile_cond, NULL);
2845 pthread_mutex_init (&cn_mutex, &attr);
2846 pthread_mutexattr_destroy (&attr);
2847 pthread_key_create (&last_error_key, free_key);
2848 #ifndef HAVE_PTHREAD_CANCEL
2849 pthread_key_create (&signal_thread_key, free_key);
2850 #endif
2852 if (!rcfile)
2853 rcfile = str_asprintf ("%s/config", homedir);
2855 global_config = config_parse (rcfile);
2856 if (!global_config)
2857 exit (EXIT_FAILURE);
2859 #ifdef WITH_AGENT
2860 if (!use_agent)
2861 use_agent = config_get_boolean ("global", "use_agent");
2862 #endif
2864 setup_logging ();
2866 if (debug_level_opt)
2867 debug_level = str_split (debug_level_opt, ",", 0);
2869 x = config_get_int_param (global_config, "global", "priority", &exists);
2870 if (exists && x != atoi(INVALID_PRIORITY))
2872 errno = 0;
2873 if (setpriority (PRIO_PROCESS, 0, x) == -1)
2875 log_write ("setpriority(): %s",
2876 pwmd_strerror (gpg_error_from_errno (errno)));
2877 goto do_exit;
2880 #ifdef HAVE_MLOCKALL
2881 if (disable_mlock == 0 && mlockall (MCL_CURRENT | MCL_FUTURE) == -1)
2883 log_write ("mlockall(): %s",
2884 pwmd_strerror (gpg_error_from_errno (errno)));
2885 goto do_exit;
2887 #endif
2889 rc = cache_init (free_cache_data);
2890 if (rc)
2892 log_write ("pwmd: ERR %i: %s", rc,
2893 gpg_err_code (rc) == GPG_ERR_UNKNOWN_VERSION
2894 ? _("incompatible gpg-agent version: 2.1.0 or later required")
2895 : pwmd_strerror (rc));
2896 goto do_exit;
2899 if (s2k_count == 0)
2900 s2k_count = config_get_ulong (NULL, "s2k_count");
2902 if (convertfile)
2904 if (!outfile || !*outfile || argc != optind)
2905 usage (argv[0], EXIT_FAILURE);
2907 estatus = convert_v2_datafile (convertfile, cipher, keyfile, keygrip,
2908 sign_keygrip, no_passphrase, outfile,
2909 keyparam, s2k_count, iterations);
2910 config_free (global_config);
2911 xfree (rcfile);
2912 exit (!estatus);
2915 if (import)
2917 if (!outfile || !*outfile || argc != optind)
2918 usage (argv[0], EXIT_FAILURE);
2920 if (outfile && outfile[0] == '-' && outfile[1] == 0)
2921 outfile = NULL;
2923 estatus = xml_import (import, outfile, keygrip, sign_keygrip, keyfile,
2924 no_passphrase, cipher, keyparam, s2k_count,
2925 iterations);
2926 config_free (global_config);
2927 xfree (rcfile);
2928 exit (!estatus);
2931 p = config_get_string ("global", "socket_path");
2932 if (!p)
2933 p = str_asprintf ("%s/socket", homedir);
2935 socketarg = expand_homedir (p);
2936 xfree (p);
2938 if (!secure)
2939 disable_list_and_dump = config_get_boolean ("global",
2940 "disable_list_and_dump");
2941 else
2942 disable_list_and_dump = secure;
2944 cache_push = config_get_list ("global", "cache_push");
2946 while (optind < argc)
2948 if (strv_printf (&cache_push, "%s", argv[optind++]) == 0)
2949 errx (EXIT_FAILURE, "%s", pwmd_strerror (GPG_ERR_ENOMEM));
2952 if (strchr (socketarg, '/') == NULL)
2954 socketdir = getcwd (buf, sizeof (buf));
2955 socketname = str_dup (socketarg);
2956 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2958 else
2960 socketname = str_dup (strrchr (socketarg, '/'));
2961 socketname++;
2962 socketarg[strlen (socketarg) - strlen (socketname) - 1] = 0;
2963 socketdir = str_dup (socketarg);
2964 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2967 if (chdir (datadir))
2969 log_write ("%s: %s", datadir,
2970 pwmd_strerror (gpg_error_from_errno (errno)));
2971 unlink (socketpath);
2972 goto do_exit;
2975 if (test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 0,
2976 mode))
2977 goto do_exit;
2980 * bind() doesn't like the full pathname of the socket or any non alphanum
2981 * characters so change to the directory where the socket is wanted then
2982 * create it then change to datadir.
2984 if (chdir (socketdir))
2986 log_write ("%s: %s", socketdir,
2987 pwmd_strerror (gpg_error_from_errno (errno)));
2988 goto do_exit;
2991 xfree (socketdir);
2993 if ((sockfd = socket (PF_UNIX, SOCK_STREAM, 0)) == -1)
2995 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2996 goto do_exit;
2999 addr.sun_family = AF_UNIX;
3000 snprintf (addr.sun_path, sizeof (addr.sun_path), "%s", socketname);
3001 do_unlink = 1;
3002 if (bind (sockfd, (struct sockaddr *) &addr, sizeof (struct sockaddr)) ==
3005 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
3007 if (errno == EADDRINUSE)
3009 do_unlink = 0;
3010 log_write (_("Either there is another pwmd running or '%s' is a \n"
3011 "stale socket. Please remove it manually."), socketpath);
3014 goto do_exit;
3018 char *t = config_get_string ("global", "socket_perms");
3019 mode_t mask;
3021 if (t)
3023 mode = strtol (t, NULL, 8);
3024 mask = umask (0);
3025 xfree (t);
3027 if (chmod (socketname, mode) == -1)
3029 log_write ("%s: %s", socketname,
3030 pwmd_strerror (gpg_error_from_errno (errno)));
3031 close (sockfd);
3032 umask (mask);
3033 goto do_exit;
3036 umask (mask);
3040 xfree (--socketname);
3042 if (chdir (datadir))
3044 log_write ("%s: %s", datadir,
3045 pwmd_strerror (gpg_error_from_errno (errno)));
3046 close (sockfd);
3047 goto do_exit;
3050 xfree (datadir);
3053 * Set the cache entry for a file. Prompts for the password.
3055 if (cache_push)
3057 struct crypto_s *crypto = NULL;
3058 gpg_error_t rc = init_client_crypto (&crypto);
3060 if (rc)
3062 estatus = EXIT_FAILURE;
3063 goto do_exit;
3066 #ifdef WITH_AGENT
3067 if (use_agent)
3069 rc = agent_set_pinentry_options (crypto->agent);
3070 if (rc)
3072 estatus = EXIT_FAILURE;
3073 goto do_exit;
3076 #endif
3078 for (opt = 0; cache_push[opt]; opt++)
3080 if (!do_cache_push (cache_push[opt], crypto) && !force)
3082 strv_free (cache_push);
3083 startup_failure ();
3084 estatus = EXIT_FAILURE;
3085 cleanup_crypto (&crypto);
3086 goto do_exit;
3089 cleanup_crypto_stage1 (crypto);
3092 #ifdef WITH_AGENT
3093 if (use_agent)
3094 (void) kill_scd (crypto->agent);
3095 #endif
3097 cleanup_crypto (&crypto);
3098 strv_free (cache_push);
3099 log_write (!nofork ? _("Done. Daemonizing...") :
3100 _("Done. Waiting for connections..."));
3103 config_clear_keys ();
3105 if (listen (sockfd, 0) == -1)
3107 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
3108 goto do_exit;
3111 if (!nofork)
3113 switch (fork ())
3115 case -1:
3116 log_write ("fork(): %s",
3117 pwmd_strerror (gpg_error_from_errno (errno)));
3118 goto do_exit;
3119 case 0:
3120 close (0);
3121 close (1);
3122 close (2);
3123 setsid ();
3124 break;
3125 default:
3126 _exit (EXIT_SUCCESS);
3130 (void)test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 1,
3131 mode);
3132 cmdline = 0;
3133 pthread_key_create (&thread_name_key, free_key);
3134 pthread_setspecific (thread_name_key, str_dup ("main"));
3135 estatus = server_loop (sockfd, &socketpath);
3137 do_exit:
3138 if (socketpath && do_unlink)
3140 unlink (socketpath);
3141 xfree (socketpath);
3144 xfree (socketarg);
3145 #ifdef WITH_GNUTLS
3146 gnutls_global_deinit ();
3147 xfree (invoking_tls);
3148 #endif
3149 if (rcfile_tid)
3151 #ifdef HAVE_PTHREAD_CANCEL
3152 pthread_cancel (rcfile_tid);
3153 #else
3154 pthread_kill (rcfile_tid, SIGUSR2);
3155 pthread_cond_signal (&rcfile_cond);
3156 #endif
3157 pthread_join (rcfile_tid, NULL);
3160 pthread_cond_destroy (&rcfile_cond);
3161 pthread_mutex_destroy (&rcfile_mutex);
3162 pthread_key_delete (last_error_key);
3163 #ifndef HAVE_PTHREAD_CANCEL
3164 pthread_key_delete (signal_thread_key);
3165 #endif
3167 if (global_config)
3168 config_free (global_config);
3170 xfree (rcfile);
3171 xfree (home_directory);
3172 xfree (homedir);
3173 xmlCleanupParser ();
3174 xmlCleanupGlobals ();
3176 if (pidfile)
3177 unlink (pidfile);
3178 xfree (pidfile);
3180 if (estatus == EXIT_SUCCESS)
3181 log_write (_("pwmd exiting normally"));
3183 pthread_key_delete (thread_name_key);
3184 closelog ();
3185 #if defined(DEBUG) && !defined(MEM_DEBUG)
3186 xdump ();
3187 #endif
3189 if (log_fd != -1)
3190 close (log_fd);
3192 exit (estatus);