Fix potentially returning the wrong RC.
[pwmd.git] / src / pwmd.c
blobf576b7b79250977d09ace47075c3d03e5ec71903
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 (_("reload_origing 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_INV_USER_ID;
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)
652 return GPG_ERR_EACCES;
654 if (*p == '#') // to avoid confusion with ACLs, accept the prefix
655 p++;
657 if (!strcmp(client->thd->tls->fp, p))
658 return 0;
660 return GPG_ERR_EACCES;
662 #endif
664 if (client->thd->peer->uid == invoking_uid)
665 return 0;
667 return GPG_ERR_EACCES;
670 #ifdef HAVE_GETGRNAM_R
671 gpg_error_t
672 acl_check_common (struct client_s *client, const char *user, uid_t uid,
673 gid_t gid, int *allowed)
675 struct passwd pw, *result;
676 char *buf = NULL;
677 int not = 0;
678 int rw = 0;
679 int tls = 0;
681 if (!user || !*user)
682 return 0;
684 if (*user == '-' || *user == '!')
685 not = 1;
687 if (*user == '+') // not implemented yet
688 rw = 1;
690 if (*user == '#') // TLS fingerprint hash
691 tls = 1;
693 if (not || rw || tls)
694 user++;
696 if (tls)
698 #ifdef WITH_GNUTLS
699 if (client->thd->remote)
701 if (!strcasecmp (client->thd->tls->fp, user))
702 *allowed = !not;
705 return 0;
706 #else
707 return 0;
708 #endif
710 #ifdef WITH_GNUTLS
711 else if (client->thd->remote) // Remote client with no TLS in the ACL
712 return 0;
713 #endif
715 if (*user == '@') // all users in group
717 struct group gr, *gresult;
718 size_t len = sysconf (_SC_GETGR_R_SIZE_MAX);
720 if (len == -1)
721 len = 16384;
723 buf = xmalloc (len);
724 if (!buf)
725 return GPG_ERR_ENOMEM;
727 user++;
728 if (!getgrnam_r (user, &gr, buf, len, &gresult) && gresult)
730 if (gresult->gr_gid == gid)
732 xfree (buf);
733 *allowed = !not;
734 return 0;
737 len = sysconf (_SC_GETPW_R_SIZE_MAX);
738 if (len == -1)
739 len = 16384;
741 char *tbuf = xmalloc (len);
742 for (char **t = gresult->gr_mem; *t; t++)
744 if (!getpwnam_r (*t, &pw, tbuf, len, &result) && result)
746 if (result->pw_uid == uid)
748 *allowed = !not;
749 break;
754 return 0;
757 else
759 size_t len = sysconf (_SC_GETPW_R_SIZE_MAX);
761 if (len == -1)
762 len = 16384;
764 buf = xmalloc (len);
765 if (!buf)
766 return GPG_ERR_ENOMEM;
768 if (!getpwnam_r (user, &pw, buf, len, &result) && result)
770 if (result->pw_uid == uid)
771 *allowed = !not;
774 xfree (buf);
777 return 0;
779 #else
780 gpg_error_t
781 acl_check_common (struct client_s *client, const char *user, uid_t uid,
782 gid_t gid, int *allowed)
784 struct passwd *result;
785 int not = 0;
786 int rw = 0;
787 int tls = 0;
789 if (!user || !*user)
790 return 0;
792 if (*user == '-' || *user == '!')
793 not = 1;
795 if (*user == '+') // not implemented yet
796 rw = 1;
798 if (*user == '#') // TLS fingerprint hash
799 tls = 1;
801 if (not || rw || tls)
802 user++;
804 if (tls)
806 #ifdef WITH_GNUTLS
807 if (client->thd->remote)
809 if (!strcasecmp (client->thd->tls->fp, user))
810 *allowed = !not;
813 return 0;
814 #else
815 return 0;
816 #endif
819 if (*user == '@') // all users in group
821 struct group *gresult;
823 user++;
824 gresult = getgrnam (user);
825 if (gresult && gresult->gr_gid == gid)
827 *allowed = !not;
828 return 0;
831 for (char **t = gresult->gr_mem; *t; t++)
833 result = getpwnam (*t);
834 if (result && result->pw_uid == uid)
836 *allowed = !not;
837 break;
841 return 0;
843 else
845 result = getpwnam (user);
846 if (result && result->pw_uid == uid)
847 *allowed = !not;
850 return 0;
852 #endif
854 static gpg_error_t
855 validate_peer (struct client_s *cl)
857 gpg_error_t rc;
859 #ifdef WITH_GNUTLS
860 if (cl->thd->remote)
861 return tls_validate_access (cl, NULL);
862 #endif
864 rc = do_validate_peer (cl->ctx, "global", &cl->thd->peer);
865 if (!rc || gpg_err_code (rc) == GPG_ERR_INV_USER_ID)
866 log_write ("peer %s: uid=%i, gid=%i, pid=%i",
867 !rc ? _("accepted") : _("rejected"), cl->thd->peer->uid,
868 cl->thd->peer->gid, cl->thd->peer->pid);
869 else if (rc)
870 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
872 return rc;
875 static void
876 xml_error_cb (void *data, xmlErrorPtr e)
878 struct client_s *client = data;
881 * Keep the first reported error as the one to show in the error
882 * description. Reset in send_error().
884 if (client->xml_error)
885 return;
887 client->xml_error = xcalloc (1, sizeof(xmlError));
888 xmlCopyError (e, client->xml_error);
891 static pid_t
892 hook_waitpid (assuan_context_t ctx, pid_t pid, int action,
893 int *status, int options)
895 return waitpid (pid, status, options);
898 static ssize_t
899 hook_read (assuan_context_t ctx, assuan_fd_t fd, void *data, size_t len)
901 #ifdef WITH_GNUTLS
902 struct client_s *client = assuan_get_pointer (ctx);
904 if (client->thd->remote)
905 return tls_read_hook (ctx, (int) fd, data, len);
906 #endif
908 return read ((int) fd, data, len);
911 static ssize_t
912 hook_write (assuan_context_t ctx, assuan_fd_t fd,
913 const void *data, size_t len)
915 #ifdef WITH_GNUTLS
916 struct client_s *client = assuan_get_pointer (ctx);
918 if (client->thd->remote)
919 return tls_write_hook (ctx, (int) fd, data, len);
920 #endif
922 return write ((int) fd, data, len);
925 static int
926 new_connection (struct client_s *cl)
928 gpg_error_t rc;
929 static struct assuan_malloc_hooks mhooks = { xmalloc, xrealloc, xfree };
930 static struct assuan_system_hooks shooks = {
931 ASSUAN_SYSTEM_HOOKS_VERSION,
932 __assuan_usleep,
933 __assuan_pipe,
934 __assuan_close,
935 hook_read,
936 hook_write,
937 //FIXME
938 NULL, //recvmsg
939 NULL, //sendmsg both are used for FD passing
940 __assuan_spawn,
941 hook_waitpid,
942 __assuan_socketpair,
943 __assuan_socket,
944 __assuan_connect
947 #ifdef WITH_GNUTLS
948 if (cl->thd->remote)
950 char *prio = config_get_string ("global", "tls_cipher_suite");
952 cl->thd->tls = tls_init (cl->thd->fd, cl->thd->timeout, prio);
953 xfree (prio);
954 if (!cl->thd->tls)
955 return 0;
957 #endif
959 rc = assuan_new_ext (&cl->ctx, GPG_ERR_SOURCE_DEFAULT, &mhooks,
960 debug_level ? assuan_log_cb : NULL, NULL);
961 if (rc)
962 goto fail;
964 assuan_ctx_set_system_hooks (cl->ctx, &shooks);
965 rc = assuan_init_socket_server (cl->ctx, cl->thd->fd, 2);
966 if (rc)
967 goto fail;
969 assuan_set_pointer (cl->ctx, cl);
970 assuan_set_hello_line (cl->ctx, PACKAGE_STRING);
971 rc = register_commands (cl->ctx);
972 if (rc)
973 goto fail;
975 #ifdef WITH_GNUTLS
976 if (cl->thd->remote)
978 cl->thd->timeout = config_get_integer ("global", "tls_timeout");
979 fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK);
981 #endif
983 rc = assuan_accept (cl->ctx);
984 if (rc)
985 goto fail;
987 rc = validate_peer (cl);
988 /* May not be implemented on all platforms. */
989 if (rc && gpg_err_code (rc) != GPG_ERR_ASS_GENERAL)
990 goto fail;
992 rc = init_client_crypto (&cl->crypto);
993 if (rc)
994 goto fail;
996 #ifdef WITH_AGENT
997 if (use_agent)
998 cl->crypto->agent->client_ctx = cl->ctx;
999 #endif
1001 cl->crypto->client_ctx = cl->ctx;
1002 xmlSetStructuredErrorFunc (cl, xml_error_cb);
1003 return 1;
1005 fail:
1006 log_write ("%s", pwmd_strerror (rc));
1007 return 0;
1011 * This is called after a client_thread() terminates. Set with
1012 * pthread_cleanup_push().
1014 static void
1015 cleanup_cb (void *arg)
1017 struct client_thread_s *cn = arg;
1018 struct client_s *cl = cn->cl;
1020 MUTEX_LOCK (&cn_mutex);
1021 cn_thread_list = slist_remove (cn_thread_list, cn);
1022 MUTEX_UNLOCK (&cn_mutex);
1024 if (cl)
1026 cleanup_client (cl);
1027 if (cl->xml_error)
1028 xmlResetError (cl->xml_error);
1030 xfree (cl->xml_error);
1032 #ifdef WITH_GNUTLS
1033 if (cn->tls)
1035 gnutls_deinit (cn->tls->ses);
1036 xfree (cn->tls->fp);
1037 xfree (cn->tls);
1039 #endif
1041 if (!cn->atfork && cl->ctx)
1042 assuan_release (cl->ctx);
1043 else if (!cn->atfork && cl->thd && cl->thd->fd != -1)
1044 close (cl->thd->fd);
1046 if (cl->crypto)
1047 cleanup_crypto (&cl->crypto);
1049 pinentry_free_opts (&cl->pinentry_opts);
1050 xfree (cl);
1052 else
1054 if (cn->fd != -1)
1055 close (cn->fd);
1058 while (cn->msg_queue)
1060 struct status_msg_s *msg = cn->msg_queue;
1062 cn->msg_queue = msg->next;
1063 xfree (msg->line);
1064 xfree (msg);
1067 if (!cn->atfork && cn->status_msg_pipe[0] != -1)
1068 close (cn->status_msg_pipe[0]);
1070 if (!cn->atfork && cn->status_msg_pipe[1] != -1)
1071 close (cn->status_msg_pipe[1]);
1073 pthread_mutex_destroy (&cn->status_mutex);
1075 if (!cn->atfork)
1077 log_write (_("exiting, fd=%i"), cn->fd);
1078 send_status_all (STATUS_CLIENTS, NULL);
1081 xfree (cn);
1082 pthread_cond_signal (&quit_cond);
1085 void
1086 cleanup_all_clients (int atfork)
1088 /* This function may be called from pthread_atfork() which requires
1089 reinitialization. */
1090 if (atfork)
1092 pthread_mutexattr_t attr;
1094 pthread_mutexattr_init (&attr);
1095 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
1096 pthread_mutex_init (&cn_mutex, &attr);
1097 pthread_mutexattr_destroy (&attr);
1098 cache_mutex_init ();
1101 MUTEX_LOCK (&cn_mutex);
1103 while (slist_length (cn_thread_list))
1105 struct client_thread_s *thd = slist_nth_data (cn_thread_list, 0);
1107 thd->atfork = atfork;
1108 cleanup_cb (thd);
1111 exiting = 1;
1112 MUTEX_UNLOCK (&cn_mutex);
1113 cache_deinit (atfork);
1116 static gpg_error_t
1117 send_msg_queue (struct client_thread_s *thd)
1119 MUTEX_LOCK (&thd->status_mutex);
1120 gpg_error_t rc = 0;
1121 char c;
1123 read (thd->status_msg_pipe[0], &c, 1);
1125 while (thd->msg_queue)
1127 struct status_msg_s *msg = thd->msg_queue;
1129 thd->msg_queue = thd->msg_queue->next;
1130 MUTEX_UNLOCK (&thd->status_mutex);
1131 rc = send_status (thd->cl->ctx, msg->s, msg->line);
1132 MUTEX_LOCK (&thd->status_mutex);
1133 xfree (msg->line);
1134 xfree (msg);
1136 if (rc)
1137 break;
1140 MUTEX_UNLOCK (&thd->status_mutex);
1141 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1142 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
1144 return rc;
1147 static void *
1148 client_thread (void *data)
1150 struct client_thread_s *thd = data;
1151 struct client_s *cl = xcalloc (1, sizeof (struct client_s));
1153 #ifdef HAVE_PR_SET_NAME
1154 prctl (PR_SET_NAME, "client");
1155 #endif
1156 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1158 if (!cl)
1160 log_write ("%s(%i): %s", __FILE__, __LINE__,
1161 pwmd_strerror (GPG_ERR_ENOMEM));
1162 return NULL;
1165 MUTEX_LOCK (&cn_mutex);
1166 pthread_cleanup_push (cleanup_cb, thd);
1167 thd->cl = cl;
1168 cl->thd = thd;
1169 MUTEX_UNLOCK (&cn_mutex);
1171 if (new_connection (cl))
1173 int finished = 0;
1174 gpg_error_t rc;
1176 send_status_all (STATUS_CLIENTS, NULL);
1177 rc = send_status (cl->ctx, STATUS_CACHE, NULL);
1178 if (rc)
1180 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
1181 finished = 1;
1184 while (!finished)
1186 fd_set rfds;
1187 int n;
1188 int eof;
1190 FD_ZERO (&rfds);
1191 FD_SET (thd->fd, &rfds);
1192 FD_SET (thd->status_msg_pipe[0], &rfds);
1193 n = thd->fd > thd->status_msg_pipe[0]
1194 ? thd->fd : thd->status_msg_pipe[0];
1196 n = select (n + 1, &rfds, NULL, NULL, NULL);
1197 if (n == -1)
1199 log_write ("%s", strerror (errno));
1200 break;
1203 if (FD_ISSET (thd->status_msg_pipe[0], &rfds))
1205 rc = send_msg_queue (thd);
1206 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1207 break;
1210 if (!FD_ISSET (thd->fd, &rfds))
1211 continue;
1213 rc = assuan_process_next (cl->ctx, &eof);
1214 if (rc || eof)
1216 if (gpg_err_code (rc) == GPG_ERR_EOF || eof)
1217 break;
1219 log_write ("assuan_process_next(): rc=%i %s", rc,
1220 pwmd_strerror (rc));
1221 if (rc == gpg_error (GPG_ERR_ETIMEDOUT))
1222 break;
1224 rc = send_error (cl->ctx, rc);
1225 if (rc)
1227 log_write ("assuan_process_done(): rc=%i %s", rc,
1228 pwmd_strerror (rc));
1229 break;
1233 /* Since the msg queue pipe fd's are non-blocking, check for
1234 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1235 * client has already disconnected and will be converted to
1236 * GPG_ERR_EOF during assuan_process_next().
1238 rc = send_msg_queue (thd);
1239 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1240 break;
1244 pthread_cleanup_pop (1);
1245 return NULL;
1248 static int
1249 xml_import (const char *filename, const char *outfile,
1250 const char *keygrip, const char *sign_keygrip,
1251 const char *keyfile, int no_passphrase, const char *cipher,
1252 const char *params, unsigned long s2k_count, uint64_t iterations)
1254 xmlDocPtr doc;
1255 int fd;
1256 struct stat st;
1257 int len;
1258 xmlChar *xmlbuf;
1259 xmlChar *xml;
1260 gpg_error_t rc;
1261 struct crypto_s *crypto = NULL;
1262 void *key = NULL;
1263 size_t keylen = 0;
1264 int algo = cipher ? cipher_string_to_gcrypt ((char *) cipher) :
1265 GCRY_CIPHER_AES256;
1267 if (algo == -1)
1269 log_write ("ERR %i: %s", gpg_error (GPG_ERR_CIPHER_ALGO),
1270 pwmd_strerror (GPG_ERR_CIPHER_ALGO));
1271 return 0;
1274 if (stat (filename, &st) == -1)
1276 log_write ("%s: %s", filename,
1277 pwmd_strerror (gpg_error_from_errno (errno)));
1278 return 0;
1281 rc = init_client_crypto (&crypto);
1282 if (rc)
1283 return 0;
1285 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
1286 crypto->save.hdr.flags = set_cipher_flag (crypto->save.hdr.flags, algo);
1287 log_write (_("Importing XML from '%s'. Output will be written to '%s' ..."),
1288 filename, outfile);
1290 if ((fd = open (filename, O_RDONLY)) == -1)
1292 log_write ("%s: %s", filename,
1293 pwmd_strerror (gpg_error_from_errno (errno)));
1294 goto fail;
1297 if ((xmlbuf = xmalloc (st.st_size + 1)) == NULL)
1299 close (fd);
1300 log_write ("%s(%i): %s", __FILE__, __LINE__,
1301 pwmd_strerror (GPG_ERR_ENOMEM));
1302 goto fail;
1305 if (read (fd, xmlbuf, st.st_size) == -1)
1307 rc = gpg_error_from_errno (errno);
1308 close (fd);
1309 log_write ("%s: %s", filename, pwmd_strerror (rc));
1310 goto fail;
1313 close (fd);
1314 xmlbuf[st.st_size] = 0;
1316 * Make sure the document validates.
1318 if ((doc = xmlReadDoc (xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS)) == NULL)
1320 log_write ("xmlReadDoc() failed");
1321 xfree (xmlbuf);
1322 goto fail;
1325 xfree (xmlbuf);
1326 xmlNodePtr n = xmlDocGetRootElement (doc);
1327 if (n && !xmlStrEqual (n->name, (xmlChar *) "pwmd"))
1329 log_write (_("Could not find root \"pwmd\" element."));
1330 rc = GPG_ERR_BAD_DATA;
1333 if (!rc)
1334 rc = validate_import (n ? n->children : n);
1336 if (rc)
1338 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1339 xmlFreeDoc (doc);
1340 goto fail;
1343 xmlDocDumpMemory (doc, &xml, &len);
1344 xmlFreeDoc (doc);
1345 crypto->save.s2k_count = s2k_count;
1346 crypto->save.hdr.iterations = iterations;
1347 if (!use_agent)
1349 rc = export_common (NULL, 0, crypto, xml, len, outfile, keyfile, &key,
1350 &keylen, 0, 0, no_passphrase);
1351 if (!rc)
1352 log_write (_("Success!"));
1354 #ifdef WITH_AGENT
1355 else
1357 rc = agent_set_pinentry_options (crypto->agent);
1358 if (!rc)
1359 rc = agent_export_common (crypto, keygrip, sign_keygrip, no_passphrase,
1360 xml, len, outfile, params, keyfile);
1362 #endif
1364 gcry_free (key);
1365 xmlFree (xml);
1366 if (rc)
1368 send_error (NULL, rc);
1369 goto fail;
1372 cleanup_crypto (&crypto);
1373 return 1;
1375 fail:
1376 cleanup_crypto (&crypto);
1377 return 0;
1380 static int
1381 do_cache_push (const char *filename, struct crypto_s *crypto)
1383 unsigned char md5file[16];
1384 gpg_error_t rc;
1385 char *key = NULL;
1386 size_t keylen = 0;
1387 xmlDocPtr doc;
1388 struct cache_data_s *cdata;
1389 unsigned char *crc;
1390 size_t len;
1392 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1393 filename);
1395 if (valid_filename (filename) == 0)
1397 log_write (_("%s: Invalid characters in filename"), filename);
1398 return 0;
1401 rc = decrypt_common (NULL, 0, crypto, filename, &key, &keylen);
1402 if (rc)
1403 return 0;
1405 rc = parse_doc ((char *) crypto->plaintext, crypto->plaintext_len, &doc);
1406 if (rc)
1408 log_write ("%s", pwmd_strerror (rc));
1409 xfree (key);
1410 return 0;
1413 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
1414 cdata = xcalloc (1, sizeof (struct cache_data_s));
1415 if (!cdata)
1417 xmlFreeDoc (doc);
1418 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM));
1419 xfree (key);
1420 return 0;
1423 rc = get_checksum (filename, &crc, &len);
1424 if (rc)
1426 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1427 xmlFreeDoc (doc);
1428 free_cache_data_once (cdata);
1429 xfree (key);
1430 return 0;
1433 cdata->crc = crc;
1434 rc = encrypt_xml (NULL, cache_key, cache_keysize, GCRY_CIPHER_AES,
1435 crypto->plaintext, crypto->plaintext_len, &cdata->doc,
1436 &cdata->doclen, &cache_iv, &cache_blocksize, 0);
1437 if (!rc && !IS_PKI (crypto))
1439 cdata->key = key;
1440 cdata->keylen = keylen;
1442 else
1443 xfree (key);
1445 if (rc)
1447 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1448 xmlFreeDoc (doc);
1449 free_cache_data_once (cdata);
1450 return 0;
1453 #ifdef WITH_AGENT
1454 if (use_agent && IS_PKI (crypto))
1456 gcry_sexp_build ((gcry_sexp_t *) & cdata->pubkey, NULL, "%S",
1457 crypto->pkey_sexp);
1458 gcry_sexp_build ((gcry_sexp_t *) & cdata->sigkey, NULL, "%S",
1459 crypto->sigpkey_sexp);
1461 #endif
1463 int timeout = config_get_integer (filename, "cache_timeout");
1464 cache_add_file (md5file, crypto->grip, cdata, timeout);
1465 log_write (_("Successfully added '%s' to the cache."), filename);
1466 return 1;
1469 static gpg_error_t
1470 init_client (int fd, const char *addr)
1472 gpg_error_t rc = 0;
1473 struct client_thread_s *new = xcalloc (1, sizeof (struct client_thread_s));
1475 if (!new)
1477 close (fd);
1478 return GPG_ERR_ENOMEM;
1481 MUTEX_LOCK (&cn_mutex);
1482 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
1484 if (pipe (new->status_msg_pipe) == -1)
1485 rc = gpg_error_from_errno (errno);
1487 if (!rc)
1489 fcntl (new->status_msg_pipe[0], F_SETFL, O_NONBLOCK);
1490 fcntl (new->status_msg_pipe[1], F_SETFL, O_NONBLOCK);
1491 pthread_mutex_init (&new->status_mutex, NULL);
1494 if (!rc)
1496 #ifdef WITH_GNUTLS
1497 new->remote = addr ? 1 : 0;
1498 #endif
1499 new->fd = fd;
1500 rc = create_thread (client_thread, new, &new->tid, 1);
1501 if (rc)
1503 close (new->status_msg_pipe[0]);
1504 close (new->status_msg_pipe[1]);
1505 pthread_mutex_destroy (&new->status_mutex);
1509 if (!rc)
1511 struct slist_s *list = slist_append (cn_thread_list, new);
1513 if (list)
1515 cn_thread_list = list;
1516 if (addr)
1517 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1518 (pthread_t *) new->tid, fd, addr);
1519 else
1520 log_write (_("new connection: tid=%p, fd=%i"),
1521 (pthread_t *) new->tid, fd);
1523 else
1524 rc = GPG_ERR_ENOMEM;
1527 pthread_cleanup_pop (1);
1529 if (rc)
1531 xfree (new);
1532 close (fd);
1533 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1534 pwmd_strerror (rc));
1536 return rc;
1539 static void*
1540 keepalive_thread (void *arg)
1542 #ifndef HAVE_PTHREAD_CANCEL
1543 int *n = xmalloc (sizeof (int));
1545 *n = 0;
1546 pthread_setspecific (signal_thread_key, n);
1547 INIT_THREAD_SIGNAL;
1548 #endif
1550 #ifdef HAVE_PR_SET_NAME
1551 prctl (PR_SET_NAME, "keepalive");
1552 #endif
1553 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1555 for (;;)
1557 int n = config_get_integer ("global", "keepalive_interval");
1558 struct timeval tv = { n, 0 };
1559 #ifndef HAVE_PTHREAD_CANCEL
1560 int *sigusr2;
1562 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1563 if (*sigusr2)
1564 break;
1565 #endif
1567 send_status_all (STATUS_KEEPALIVE, NULL);
1568 select (0, NULL, NULL, NULL, &tv);
1571 return NULL;
1574 #ifdef WITH_GNUTLS
1575 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1576 static void *
1577 get_in_addr (struct sockaddr *sa)
1579 if (sa->sa_family == AF_INET)
1580 return &(((struct sockaddr_in *) sa)->sin_addr);
1582 return &(((struct sockaddr_in6 *) sa)->sin6_addr);
1585 static void *
1586 tcp_accept_thread (void *arg)
1588 int sockfd = *(int *) arg;
1589 #ifndef HAVE_PTHREAD_CANCEL
1590 int *n = xmalloc (sizeof (int));
1592 *n = 0;
1593 pthread_setspecific (signal_thread_key, n);
1594 INIT_THREAD_SIGNAL;
1595 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1596 #endif
1598 #ifdef HAVE_PR_SET_NAME
1599 prctl (PR_SET_NAME, "tcp_accept");
1600 #endif
1601 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1603 for (;;)
1605 struct sockaddr_storage raddr;
1606 socklen_t slen = sizeof (raddr);
1607 int fd;
1608 unsigned long n;
1609 char s[INET6_ADDRSTRLEN];
1610 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1611 #ifndef HAVE_PTHREAD_CANCEL
1612 int *sigusr2;
1614 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1615 if (*sigusr2)
1616 break;
1617 #endif
1619 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1620 if (fd == -1)
1622 if (errno == EMFILE || errno == ENFILE)
1623 log_write ("accept(): %s",
1624 pwmd_strerror (gpg_error_from_errno (errno)));
1625 else if (errno != EAGAIN)
1627 if (!quit) // probably EBADF
1628 log_write ("accept(): %s", strerror (errno));
1630 break;
1633 #ifndef HAVE_PTHREAD_CANCEL
1634 select (0, NULL, NULL, NULL, &tv);
1635 #endif
1636 continue;
1639 if (quit)
1640 break;
1642 inet_ntop (raddr.ss_family, get_in_addr ((struct sockaddr *) &raddr),
1643 s, sizeof s);
1644 (void) init_client (fd, s);
1645 n = config_get_integer ("global", "tcp_wait");
1646 if (n > 0)
1648 tv.tv_sec = (n * 100000) / 100000;
1649 tv.tv_usec = (n * 100000) % 100000;
1650 select (0, NULL, NULL, NULL, &tv);
1654 return NULL;
1657 static int
1658 start_stop_tls_with_protocol (int ipv6, int term)
1660 struct addrinfo hints, *servinfo, *p;
1661 int port = config_get_integer ("global", "tcp_port");
1662 char buf[7];
1663 int n;
1664 gpg_error_t rc;
1665 int *fd = ipv6 ? &tls6_fd : &tls_fd;
1667 if (term || config_get_boolean ("global", "enable_tcp") == 0)
1669 if (tls6_fd != -1)
1671 if (spawned_tls6)
1673 #ifdef HAVE_PTHREAD_CANCEL
1674 pthread_cancel (tls6_tid);
1675 #else
1676 pthread_kill (tls6_tid, SIGUSR2);
1677 #endif
1678 pthread_join (tls6_tid, NULL);
1681 shutdown (tls6_fd, SHUT_RDWR);
1682 close (tls6_fd);
1683 tls6_fd = -1;
1684 spawned_tls6 = 0;
1687 if (tls_fd != -1)
1689 if (spawned_tls)
1691 #ifdef HAVE_PTHREAD_CANCEL
1692 pthread_cancel (tls_tid);
1693 #else
1694 pthread_kill (tls_tid, SIGUSR2);
1695 #endif
1696 pthread_join (tls_tid, NULL);
1699 shutdown (tls_fd, SHUT_RDWR);
1700 close (tls_fd);
1701 tls_fd = -1;
1702 spawned_tls = 0;
1705 /* A client may still be connected. */
1706 if (!quit && x509_cred != NULL)
1707 tls_deinit_params ();
1709 return 1;
1712 if ((ipv6 && tls6_fd != -1) || (!ipv6 && tls_fd != -1))
1713 return 1;
1715 memset (&hints, 0, sizeof (hints));
1716 hints.ai_family = ipv6 ? AF_INET6 : AF_INET;
1717 hints.ai_socktype = SOCK_STREAM;
1718 hints.ai_flags = AI_PASSIVE;
1719 snprintf (buf, sizeof (buf), "%i", port);
1721 if ((n = getaddrinfo (NULL, buf, &hints, &servinfo)) == -1)
1723 log_write ("getaddrinfo(): %s", gai_strerror (n));
1724 return 0;
1727 for (n = 0, p = servinfo; p != NULL; p = p->ai_next)
1729 int r = 1;
1731 if ((ipv6 && p->ai_family != AF_INET6)
1732 || (!ipv6 && p->ai_family != AF_INET))
1733 continue;
1735 if ((*fd = socket (p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
1737 log_write ("socket(): %s", strerror (errno));
1738 continue;
1741 if (setsockopt (*fd, SOL_SOCKET, SO_REUSEADDR, &r, sizeof (int)) == -1)
1743 log_write ("setsockopt(): %s",
1744 pwmd_strerror (gpg_error_from_errno (errno)));
1745 freeaddrinfo (servinfo);
1746 goto fail;
1749 if (bind (*fd, p->ai_addr, p->ai_addrlen) == -1)
1751 close (*fd);
1752 log_write ("bind(): %s",
1753 pwmd_strerror (gpg_error_from_errno (errno)));
1754 continue;
1757 n++;
1758 break;
1761 freeaddrinfo (servinfo);
1763 if (!n)
1764 goto fail;
1766 #if HAVE_DECL_SO_BINDTODEVICE != 0
1767 char *tmp = config_get_string ("global", "tcp_interface");
1768 if (tmp && setsockopt (*fd, SOL_SOCKET, SO_BINDTODEVICE, tmp,
1769 strlen (tmp)) == -1)
1771 log_write ("setsockopt(): %s",
1772 pwmd_strerror (gpg_error_from_errno (errno)));
1773 xfree (tmp);
1774 goto fail;
1777 xfree (tmp);
1778 #endif
1780 if (x509_cred == NULL)
1782 rc = tls_init_params ();
1783 if (rc)
1784 goto fail;
1787 if (listen (*fd, 0) == -1)
1789 log_write ("listen(): %s", strerror (errno));
1790 goto fail;
1793 if (ipv6)
1794 rc = create_thread (tcp_accept_thread, fd, &tls6_tid, 0);
1795 else
1796 rc = create_thread (tcp_accept_thread, fd, &tls_tid, 0);
1798 if (rc)
1800 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1801 pwmd_strerror (rc));
1802 goto fail;
1805 if (ipv6)
1806 spawned_tls6 = 1;
1807 else
1808 spawned_tls = 1;
1810 return 1;
1812 fail:
1813 start_stop_tls_with_protocol (0, 1);
1814 if (tls_fd != -1)
1815 close (tls_fd);
1817 if (tls6_fd != -1)
1818 close (tls6_fd);
1820 tls_fd = -1;
1821 tls6_fd = -1;
1822 return 0;
1825 static int
1826 start_stop_tls (int term)
1828 char *s = config_get_string ("global", "tcp_bind");
1829 int b;
1831 if (!s)
1832 return 0;
1834 if (!strcmp (s, "any"))
1836 b = start_stop_tls_with_protocol (0, term);
1837 if (b)
1838 b = start_stop_tls_with_protocol (1, term);
1840 else if (!strcmp (s, "ipv4"))
1841 b = start_stop_tls_with_protocol (0, term);
1842 else if (!strcmp (s, "ipv6"))
1843 b = start_stop_tls_with_protocol (1, term);
1844 else
1845 b = 0;
1847 xfree (s);
1848 return b;
1850 #endif
1852 static void *
1853 accept_thread (void *arg)
1855 int sockfd = *(int *) arg;
1856 #ifndef HAVE_PTHREAD_CANCEL
1857 int *n = xmalloc (sizeof (int));
1859 *n = 0;
1860 pthread_setspecific (signal_thread_key, n);
1861 INIT_THREAD_SIGNAL;
1862 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1863 #endif
1865 #ifdef HAVE_PR_SET_NAME
1866 prctl (PR_SET_NAME, "accept");
1867 #endif
1868 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1870 for (;;)
1872 socklen_t slen = sizeof (struct sockaddr_un);
1873 struct sockaddr_un raddr;
1874 int fd;
1875 #ifndef HAVE_PTHREAD_CANCEL
1876 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1877 int *sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1879 if (*sigusr2)
1880 break;
1881 #endif
1883 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1884 if (fd == -1)
1886 if (errno == EMFILE || errno == ENFILE)
1887 log_write ("accept(): %s",
1888 pwmd_strerror (gpg_error_from_errno (errno)));
1889 else if (errno != EAGAIN)
1891 if (!quit) // probably EBADF
1892 log_write ("accept(): %s",
1893 pwmd_strerror (gpg_error_from_errno (errno)));
1895 break;
1898 #ifndef HAVE_PTHREAD_CANCEL
1899 select (0, NULL, NULL, NULL, &tv);
1900 #endif
1901 continue;
1904 (void) init_client (fd, NULL);
1907 /* Just in case accept() failed for some reason other than EBADF */
1908 quit = 1;
1909 return NULL;
1912 static void *
1913 cache_timer_thread (void *arg)
1915 #ifndef HAVE_PTHREAD_CANCEL
1916 int *n = xmalloc (sizeof (int));
1918 *n = 0;
1919 pthread_setspecific (signal_thread_key, n);
1920 INIT_THREAD_SIGNAL;
1921 #endif
1923 #ifdef HAVE_PR_SET_NAME
1924 prctl (PR_SET_NAME, "cache timer");
1925 #endif
1926 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1928 for (;;)
1930 struct timeval tv = { 1, 0 };
1931 #ifndef HAVE_PTHREAD_CANCEL
1932 int *n;
1934 n = (int *) pthread_getspecific (signal_thread_key);
1935 if (*n)
1936 break;
1937 #endif
1939 select (0, NULL, NULL, NULL, &tv);
1940 cache_adjust_timeout ();
1943 return NULL;
1946 static int
1947 signal_loop (sigset_t sigset)
1949 int done = 0;
1950 int siint = 0;
1954 int sig;
1956 sigwait (&sigset, &sig);
1958 if (sig != SIGQUIT)
1959 log_write (_("caught signal %i (%s)"), sig, strsignal (sig));
1961 switch (sig)
1963 case SIGHUP:
1964 pthread_cond_signal (&rcfile_cond);
1965 break;
1966 case SIGUSR1:
1967 log_write (_("clearing file cache"));
1968 cache_clear (NULL);
1969 send_status_all (STATUS_CACHE, NULL);
1970 break;
1971 case SIGQUIT:
1972 done = 1;
1973 break;
1974 default:
1975 siint = 1;
1976 done = 1;
1977 break;
1980 while (!done);
1982 return siint;
1985 static void
1986 catchsig (int sig)
1988 log_write (_ ("Caught signal %i (%s). Exiting."), sig, strsignal (sig));
1989 #ifdef HAVE_BACKTRACE
1990 BACKTRACE (__FUNCTION__);
1991 #endif
1992 longjmp (jmp, 1);
1995 static void *
1996 waiting_for_exit (void *arg)
1998 int last = 0;
1999 #ifndef HAVE_PTHREAD_CANCEL
2000 int *n = xmalloc (sizeof (int));
2002 *n = 0;
2003 pthread_setspecific (signal_thread_key, n);
2004 INIT_THREAD_SIGNAL;
2005 #endif
2007 #ifdef HAVE_PR_SET_NAME
2008 prctl (PR_SET_NAME, "exiting");
2009 #endif
2010 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
2011 log_write (_("waiting for all clients to disconnect"));
2012 MUTEX_LOCK (&quit_mutex);
2013 pthread_cleanup_push (cleanup_mutex_cb, &quit_mutex);
2015 for (;;)
2017 struct timespec ts;
2018 int n;
2020 MUTEX_LOCK (&cn_mutex);
2021 n = slist_length (cn_thread_list);
2022 MUTEX_UNLOCK (&cn_mutex);
2023 if (!n)
2024 break;
2026 #ifndef HAVE_PTHREAD_CANCEL
2027 int *s = (int *) pthread_getspecific (signal_thread_key);
2028 if (*s)
2029 break;
2030 #endif
2032 if (last != n)
2034 log_write (_("%i clients remain"), n);
2035 last = n;
2038 INIT_TIMESPEC (SIG_TIMEOUT, ts);
2039 pthread_cond_timedwait (&quit_cond, &quit_mutex, &ts);
2042 kill (getpid (), SIGQUIT);
2043 pthread_cleanup_pop (1);
2044 return NULL;
2047 static int
2048 server_loop (int sockfd, char **socketpath)
2050 pthread_t accept_tid;
2051 pthread_t cache_timeout_tid;
2052 int cancel_timeout_thread = 0, cancel_accept_thread = 0;
2053 int cancel_keepalive_thread = 0;
2054 sigset_t sigset;
2055 int n;
2056 int segv = 0;
2057 gpg_error_t rc;
2059 init_commands ();
2060 sigemptyset (&sigset);
2062 /* Termination */
2063 sigaddset (&sigset, SIGTERM);
2064 sigaddset (&sigset, SIGINT);
2066 /* Clears the file cache. */
2067 sigaddset (&sigset, SIGUSR1);
2069 /* Configuration file reloading. */
2070 sigaddset (&sigset, SIGHUP);
2072 /* For exiting cleanly. */
2073 sigaddset (&sigset, SIGQUIT);
2075 #ifndef HAVE_PTHREAD_CANCEL
2077 The socket, cache and rcfile threads use this signal when
2078 pthread_cancel() is unavailable. Prevent the main thread from
2079 catching this signal from another process.
2081 sigaddset (&sigset, SIGUSR2);
2082 #endif
2084 /* When mem.c cannot find a pointer in the list (double free). */
2085 signal (SIGABRT, catchsig);
2086 sigaddset (&sigset, SIGABRT);
2087 sigprocmask (SIG_BLOCK, &sigset, NULL);
2089 #ifndef HAVE_PTHREAD_CANCEL
2090 /* Remove this signal from the watched signals in signal_loop(). */
2091 sigdelset (&sigset, SIGUSR2);
2092 #endif
2094 /* Ignored everywhere. When a client disconnects abnormally this signal
2095 * gets raised. It isn't needed though because client_thread() will check
2096 * for rcs even after the client disconnects. */
2097 signal (SIGPIPE, SIG_IGN);
2099 /* Can show a backtrace of the stack in the log. */
2100 signal (SIGSEGV, catchsig);
2102 #ifdef WITH_GNUTLS
2103 /* Needs to be done after the fork(). */
2104 if (!start_stop_tls (0))
2106 segv = 1;
2107 goto done;
2109 #endif
2111 pthread_mutex_init (&quit_mutex, NULL);
2112 pthread_cond_init (&quit_cond, NULL);
2113 char *p = get_username (getuid());
2114 log_write (_("%s started for user %s"), PACKAGE_STRING, p);
2115 xfree (p);
2117 #ifdef WITH_GNUTLS
2118 if (config_get_boolean ("global", "enable_tcp"))
2119 log_write (_("Listening on %s and TCP port %i as user %i"), *socketpath,
2120 config_get_integer ("global", "tcp_port"), invoking_uid);
2121 else
2122 log_write (_("Listening on %s"), *socketpath);
2123 #else
2124 log_write (_("Listening on %s"), *socketpath);
2125 #endif
2127 rc = create_thread (keepalive_thread, NULL, &keepalive_tid, 0);
2128 if (rc)
2130 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2131 pwmd_strerror (rc));
2132 goto done;
2135 cancel_keepalive_thread = 1;
2136 rc = create_thread (reload_rcfile_thread, NULL, &rcfile_tid, 0);
2137 if (rc)
2139 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2140 pwmd_strerror (rc));
2141 goto done;
2144 rc = create_thread (cache_timer_thread, NULL, &cache_timeout_tid, 0);
2145 if (rc)
2147 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2148 pwmd_strerror (rc));
2149 goto done;
2152 cancel_timeout_thread = 1;
2153 rc = create_thread (accept_thread, &sockfd, &accept_tid, 0);
2154 if (rc)
2156 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2157 pwmd_strerror (rc));
2158 goto done;
2161 cancel_accept_thread = 1;
2162 if (!setjmp (jmp))
2163 signal_loop (sigset);
2164 else
2165 segv = 1;
2167 done:
2169 * We're out of the main server loop. This happens when a signal was sent
2170 * to terminate the daemon. We'll wait for all clients to disconnect
2171 * before exiting but exit immediately if another termination signal is
2172 * sent.
2174 if (cancel_accept_thread)
2176 #ifdef HAVE_PTHREAD_CANCEL
2177 int n = pthread_cancel (accept_tid);
2178 #else
2179 int n = pthread_kill (accept_tid, SIGUSR2);
2180 #endif
2181 if (!n)
2182 pthread_join (accept_tid, NULL);
2185 #ifdef WITH_GNUTLS
2186 start_stop_tls (1);
2187 #endif
2188 shutdown (sockfd, SHUT_RDWR);
2189 close (sockfd);
2190 unlink (*socketpath);
2191 xfree (*socketpath);
2192 *socketpath = NULL;
2193 MUTEX_LOCK (&cn_mutex);
2194 n = slist_length (cn_thread_list);
2195 MUTEX_UNLOCK (&cn_mutex);
2197 if (n && !segv)
2199 pthread_t tid;
2201 rc = create_thread (waiting_for_exit, NULL, &tid, 0);
2202 if (!rc)
2204 if (signal_loop (sigset))
2206 log_write (_("Received second termination request. Exiting."));
2207 #ifdef HAVE_PTHREAD_CANCEL
2208 pthread_cancel (tid);
2209 #else
2210 pthread_kill (tid, SIGUSR2);
2211 #endif
2212 pthread_join (tid, NULL);
2215 else
2216 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2217 pwmd_strerror (rc));
2220 if (cancel_timeout_thread)
2222 #ifdef HAVE_PTHREAD_CANCEL
2223 pthread_cancel (cache_timeout_tid);
2224 #else
2225 pthread_kill (cache_timeout_tid, SIGUSR2);
2226 #endif
2227 pthread_join (cache_timeout_tid, NULL);
2230 if (cancel_keepalive_thread)
2232 #ifdef HAVE_PTHREAD_CANCEL
2233 pthread_cancel (keepalive_tid);
2234 #else
2235 pthread_kill (keepalive_tid, SIGUSR2);
2236 #endif
2237 pthread_join (keepalive_tid, NULL);
2240 cleanup_all_clients (0);
2241 #ifdef WITH_GNUTLS
2242 start_stop_tls (1);
2243 #endif
2244 deinit_commands ();
2245 pthread_cond_destroy (&quit_cond);
2246 pthread_mutex_destroy (&quit_mutex);
2247 return segv ? EXIT_FAILURE : EXIT_SUCCESS;;
2250 static void
2251 startup_failure ()
2253 log_write (_
2254 ("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
2255 cache_clear (NULL);
2258 /* This is called from cache.c:clear_once(). See
2259 * command.c:clearcache_command() for details about lock checking.
2261 static gpg_error_t
2262 free_cache_data (file_cache_t * cache)
2264 gpg_error_t rc = GPG_ERR_NO_DATA;
2265 int i, t;
2266 struct client_thread_s *found = NULL;
2267 int self = 0;
2269 if (!cache->data)
2270 return 0;
2272 cache_lock ();
2273 MUTEX_LOCK (&cn_mutex);
2274 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
2275 t = slist_length (cn_thread_list);
2277 for (i = 0; i < t; i++)
2279 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2281 if (!thd->cl)
2282 continue;
2284 if (!memcmp (thd->cl->md5file, cache->filename,
2285 sizeof (cache->filename)))
2287 if (pthread_equal (pthread_self (), thd->tid))
2289 found = thd;
2290 self = 1;
2291 continue;
2294 /* Continue trying to find a client who has the same file open and
2295 * also has a lock. */
2296 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0, -1);
2297 if (!rc)
2299 self = 0;
2300 found = thd;
2301 break;
2306 if (self && (!rc || rc == GPG_ERR_NO_DATA))
2307 rc = cache_lock_mutex (found->cl->ctx, found->cl->md5file, -1, 0, -1);
2309 if (exiting || !rc || rc == GPG_ERR_NO_DATA)
2311 free_cache_data_once (cache->data);
2312 cache->data = NULL;
2313 cache->defer_clear = 0;
2314 cache->timeout = -1;
2316 if (found)
2317 cache_unlock_mutex (found->cl->md5file, 0);
2319 rc = 0;
2322 if (rc)
2323 cache->defer_clear = 1;
2325 pthread_cleanup_pop (1);
2326 cache_unlock ();
2327 return rc;
2330 static int
2331 convert_v2_datafile (const char *filename, const char *cipher,
2332 const char *keyfile, const char *keygrip,
2333 const char *sign_keygrip, int nopass,
2334 const char *outfile, const char *keyparam,
2335 unsigned long s2k_count, uint64_t iterations)
2337 gpg_error_t rc;
2338 void *data = NULL;
2339 size_t datalen;
2340 struct crypto_s *crypto = NULL;
2341 uint16_t ver;
2342 int algo;
2343 void *key = NULL;
2344 size_t keylen = 0;
2346 if (outfile[0] == '-' && outfile[1] == 0)
2347 outfile = NULL;
2349 log_write (_("Converting version 2 data file \"%s\" ..."), filename);
2350 if (access (filename, R_OK) == -1)
2352 log_write ("%s: %s", filename,
2353 pwmd_strerror (gpg_error_from_errno (errno)));
2354 return 0;
2357 if (keyfile)
2359 log_write (_("Using passphrase file \"%s\" for decryption ..."),
2360 keyfile);
2361 if (access (keyfile, R_OK) == -1)
2363 log_write ("%s: %s", keyfile,
2364 pwmd_strerror (gpg_error_from_errno (errno)));
2365 return 0;
2369 rc = read_v2_datafile (filename, keyfile, &data, &datalen, &ver, &algo);
2370 if (rc)
2372 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2373 return 0;
2376 if (cipher)
2378 algo = cipher_string_to_gcrypt (cipher);
2379 if (algo == -1)
2381 rc = GPG_ERR_CIPHER_ALGO;
2382 goto fail;
2386 if (ver < 0x212)
2388 xmlDocPtr doc;
2390 rc = parse_doc (data, datalen, &doc);
2391 if (rc)
2392 goto fail;
2394 rc = convert_pre_212_elements (doc);
2395 gcry_free (data);
2396 data = NULL;
2397 if (!rc)
2399 xmlDocDumpFormatMemory (doc, (xmlChar **) & data, (int *) &datalen,
2401 if (!data)
2402 rc = GPG_ERR_ENOMEM;
2405 xmlFreeDoc (doc);
2406 if (rc)
2407 goto fail;
2410 rc = init_client_crypto (&crypto);
2411 if (!rc)
2413 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
2414 crypto->save.hdr.flags = set_cipher_flag (crypto->save.hdr.flags, algo);
2415 crypto->save.s2k_count = s2k_count;
2416 crypto->save.hdr.iterations = iterations;
2418 if (!use_agent)
2420 rc = export_common (NULL, 0, crypto, data, datalen, outfile, keyfile,
2421 &key, &keylen, 0, 0, nopass);
2423 #ifdef WITH_AGENT
2424 else
2426 rc = agent_set_pinentry_options (crypto->agent);
2427 if (!rc)
2428 rc = agent_export_common (crypto, keygrip, sign_keygrip, nopass,
2429 data, datalen, outfile, keyparam,
2430 no_passphrase_file ? NULL : keyfile);
2432 #endif
2433 if (!rc)
2434 log_write (_("Output written to \"%s\"."), outfile);
2437 fail:
2438 if (ver < 0x212)
2439 xmlFree (data);
2440 else
2441 gcry_free (data);
2443 gcry_free (key);
2444 cleanup_crypto (&crypto);
2446 if (rc)
2447 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2448 return rc ? 0 : 1;
2451 static void
2452 usage (const char *pn, int status)
2454 FILE *fp = status == EXIT_FAILURE ? stderr : stdout;
2456 fprintf (fp, _("Usage: %s [OPTIONS] [file1] [...]\n"
2457 " -f, --rcfile=filename load the specfied configuration file\n"
2458 " (~/.pwmd/config)\n"
2459 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2460 #ifdef WITH_AGENT
2461 " --use-agent enable use of gpg-agent\n"
2462 #endif
2463 " -n, --no-fork run as a foreground process\n"
2464 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2465 " --ignore, --force ignore file errors during startup\n"
2466 " --debug-level=keywords log protocol output (see manual for details)\n"
2467 " -o, --outfile=filename output file when importing or converting\n"
2468 " -C, --convert=filename convert a version 2 data file to version 3\n"
2469 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2470 " -k, --passphrase-file=file for use when importing or converting\n"
2471 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2472 " converting\n"
2473 " --no-passphrase when importing or converting\n"
2474 " --keygrip=hex public key to use when encrypting\n"
2475 " --sign-keygrip=hex private key to use when signing\n"
2476 " --keyparam=s-exp custom key parameters to use (RSA-2048)\n"
2477 " --cipher=string encryption cipher (aes256)\n"
2478 " --cipher-iterations=N cipher iteration count (N+1)\n"
2479 " --s2k-count=N hash iteration count (>65536, calibrated)\n"
2480 " --help this help text\n"
2481 " --version show version and compile time features\n"),
2482 pn);
2483 exit (status);
2486 static void
2487 unlink_stale_socket (const char *sock, const char *pidfile)
2489 log_write (_ ("removing stale socket %s"), sock);
2490 unlink (sock);
2491 unlink (pidfile);
2494 static int
2495 test_pidfile (const char *path, const char *sock, char *buf, size_t buflen,
2496 char **pidfile, int create, mode_t mode)
2498 pid_t pid;
2499 int fd;
2500 size_t len;
2502 if (!create)
2504 snprintf (buf, buflen, "%s/%s.pid", homedir, sock);
2505 *pidfile = str_dup (buf);
2506 fd = open (buf, O_RDONLY);
2508 else
2509 fd = open (*pidfile, O_CREAT|O_WRONLY|O_TRUNC, mode);
2511 if (fd == -1)
2513 if (!create && errno != ENOENT)
2515 log_write ("%s: %s", buf, pwmd_strerror (errno));
2516 free (*pidfile);
2517 *pidfile = NULL;
2518 return -1;
2520 else if (!create)
2521 return 0;
2523 log_write ("%s: %s", *pidfile, strerror (errno));
2524 return -1;
2527 if (create)
2529 snprintf (buf, buflen, "%i", getpid ());
2530 write (fd, buf, strlen (buf));
2531 close (fd);
2532 return 0;
2535 len = read (fd, buf, sizeof(buf));
2536 close (fd);
2537 if (len == 0)
2539 unlink_stale_socket (path, *pidfile);
2540 return 0;
2543 if (sscanf (buf, "%5i", &pid) != 1 || pid == 0)
2545 unlink_stale_socket (path, *pidfile);
2546 return 0;
2549 if (kill (pid, 0) == -1)
2551 unlink_stale_socket (path, *pidfile);
2552 return 0;
2555 log_write (_ ("an instance for socket %s is already running"), path);
2556 xfree (*pidfile);
2557 *pidfile = NULL;
2558 return 1;
2562 main (int argc, char *argv[])
2564 int opt;
2565 struct sockaddr_un addr;
2566 char buf[PATH_MAX];
2567 char *socketpath = NULL, *socketdir, *socketname = NULL;
2568 char *socketarg = NULL;
2569 char *datadir = NULL;
2570 char *pidfile = NULL;
2571 mode_t mode = 0600;
2572 int x;
2573 char *p;
2574 char **cache_push = NULL;
2575 char *import = NULL, *keygrip = NULL, *sign_keygrip = NULL;
2576 char *keyparam = NULL;
2577 int estatus = EXIT_FAILURE;
2578 int sockfd;
2579 char *outfile = NULL;
2580 int do_unlink = 0;
2581 int secure = 0;
2582 int show_version = 0;
2583 int force = 0;
2584 int no_passphrase = 0;
2585 gpg_error_t rc;
2586 char *convertfile = NULL;
2587 char *cipher = NULL;
2588 char *keyfile = NULL;
2589 unsigned long s2k_count = 0;
2590 uint64_t iterations = 0;
2591 int exists;
2592 char *debug_level_opt = NULL;
2593 int optindex;
2594 /* Must maintain the same order as longopts[] */
2595 enum
2597 OPT_VERSION, OPT_HELP,
2598 #ifdef WITH_AGENT
2599 OPT_AGENT,
2600 #endif
2601 OPT_DEBUG_LEVEL, OPT_HOMEDIR, OPT_NO_FORK, OPT_DISABLE_DUMP,
2602 OPT_IGNORE, OPT_FORCE, OPT_RCFILE, OPT_CONVERT,
2603 OPT_PASSPHRASE_FILE, OPT_IMPORT, OPT_OUTFILE,
2604 OPT_NO_PASSPHRASE_FILE, OPT_KEYGRIP, OPT_SIGN_KEYGRIP,
2605 OPT_KEYPARAM, OPT_CIPHER, OPT_ITERATIONS, OPT_S2K_COUNT,
2606 OPT_NO_PASSPHRASE
2608 const char *optstring = "nf:C:k:I:o:";
2609 const struct option longopts[] = {
2610 {"version", no_argument, 0, 0},
2611 {"help", no_argument, 0, 0},
2612 #ifdef WITH_AGENT
2613 {"use-agent", no_argument, 0, 0},
2614 #endif
2615 {"debug-level", required_argument, 0, 0},
2616 {"homedir", required_argument, 0, 0},
2617 {"no-fork", no_argument, 0, 'n'},
2618 {"disable_dump", no_argument, 0, 0},
2619 {"ignore", no_argument, 0, 0},
2620 {"force", no_argument, 0, 0},
2621 {"rcfile", required_argument, 0, 'f'},
2622 {"convert", required_argument, 0, 'C'},
2623 {"passphrase-file", required_argument, 0, 'k'},
2624 {"import", required_argument, 0, 'I'},
2625 {"outfile", required_argument, 0, 'o'},
2626 {"no-passphrase-file", no_argument, 0, 0},
2627 {"keygrip", required_argument, 0, 0},
2628 {"sign-keygrip", required_argument, 0, 0},
2629 {"keyparam", required_argument, 0, 0},
2630 {"cipher", required_argument, 0, 0},
2631 {"cipher-iterations", required_argument, 0, 0},
2632 {"s2k-count", required_argument, 0, 0},
2633 {"no-passphrase", no_argument, 0, 0},
2634 {0, 0, 0, 0}
2637 log_fd = -1;
2639 #ifndef DEBUG
2640 #ifdef HAVE_SETRLIMIT
2641 struct rlimit rl;
2643 rl.rlim_cur = rl.rlim_max = 0;
2645 if (setrlimit (RLIMIT_CORE, &rl) != 0)
2646 err (EXIT_FAILURE, "setrlimit()");
2647 #endif
2648 #endif
2650 #ifdef ENABLE_NLS
2651 setlocale (LC_ALL, "");
2652 bindtextdomain ("pwmd", LOCALEDIR);
2653 textdomain ("pwmd");
2654 #endif
2656 #ifndef MEM_DEBUG
2657 xmem_init ();
2658 #endif
2659 gpg_err_init ();
2661 if (setup_crypto ())
2662 exit (EXIT_FAILURE);
2664 #ifdef WITH_GNUTLS
2665 gnutls_global_set_mem_functions (xmalloc, xmalloc, secure_mem_check,
2666 xrealloc, xfree);
2667 gnutls_global_init ();
2668 gnutls_global_set_log_function (tls_log);
2669 gnutls_global_set_log_level (1);
2670 tls_fd = -1;
2671 tls6_fd = -1;
2672 #endif
2673 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
2674 xmlInitMemory ();
2675 xmlInitGlobals ();
2676 xmlInitParser ();
2677 xmlXPathInit ();
2678 cmdline = 1;
2679 use_agent = 0;
2681 while ((opt = getopt_long (argc, argv, optstring, longopts, &optindex))
2682 != -1)
2684 switch (opt)
2686 case 'I':
2687 import = optarg;
2688 break;
2689 case 'C':
2690 convertfile = optarg;
2691 break;
2692 case 'k':
2693 keyfile = optarg;
2694 break;
2695 case 'o':
2696 outfile = optarg;
2697 break;
2698 case 'D':
2699 secure = 1;
2700 break;
2701 case 'n':
2702 nofork = 1;
2703 break;
2704 case 'f':
2705 rcfile = str_dup (optarg);
2706 break;
2707 default:
2708 usage (argv[0], EXIT_FAILURE);
2709 break;
2710 case 0:
2711 switch (optindex)
2713 case OPT_VERSION:
2714 show_version = 1;
2715 break;
2716 case OPT_HELP:
2717 usage (argv[0], 0);
2718 break;
2719 #ifdef WITH_AGENT
2720 case OPT_AGENT:
2721 use_agent = 1;
2722 break;
2723 #endif
2724 case OPT_DEBUG_LEVEL:
2725 debug_level_opt = optarg;
2726 break;
2727 case OPT_HOMEDIR:
2728 homedir = str_dup (optarg);
2729 break;
2730 case OPT_NO_FORK:
2731 nofork = 1;
2732 break;
2733 case OPT_DISABLE_DUMP:
2734 secure = 1;
2735 break;
2736 case OPT_IGNORE:
2737 case OPT_FORCE:
2738 force = 1;
2739 break;
2740 case OPT_RCFILE:
2741 rcfile = str_dup (optarg);
2742 break;
2743 case OPT_CONVERT:
2744 convertfile = optarg;
2745 break;
2746 case OPT_PASSPHRASE_FILE:
2747 keyfile = optarg;
2748 break;
2749 case OPT_IMPORT:
2750 import = optarg;
2751 break;
2752 case OPT_OUTFILE:
2753 outfile = optarg;
2754 break;
2755 case OPT_NO_PASSPHRASE_FILE:
2756 no_passphrase_file = 1;
2757 break;
2758 case OPT_KEYGRIP:
2759 keygrip = optarg;
2760 break;
2761 case OPT_SIGN_KEYGRIP:
2762 sign_keygrip = optarg;
2763 break;
2764 case OPT_KEYPARAM:
2765 keyparam = optarg;
2766 break;
2767 case OPT_CIPHER:
2768 cipher = optarg;
2769 break;
2770 case OPT_ITERATIONS:
2771 iterations = strtoull (optarg, NULL, 10);
2772 break;
2773 case OPT_S2K_COUNT:
2774 s2k_count = strtoul (optarg, NULL, 10);
2775 break;
2776 case OPT_NO_PASSPHRASE:
2777 no_passphrase = 1;
2778 break;
2779 default:
2780 usage (argv[0], 1);
2785 if (show_version)
2787 printf (_("%s\n\n"
2788 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014\n"
2789 "%s\n"
2790 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2791 "Compile time features:\n%s"), PACKAGE_STRING,
2792 PACKAGE_BUGREPORT,
2793 #ifdef PWMD_HOMEDIR
2794 "+PWMD_HOMEDIR=" PWMD_HOMEDIR "\n"
2795 #endif
2796 #ifdef WITH_AGENT
2797 "+WITH_AGENT\n"
2798 #else
2799 "-WITH_AGENT\n"
2800 #endif
2801 #ifdef WITH_QUALITY
2802 "+WITH_QUALITY\n"
2803 #else
2804 "-WITH_QUALITY\n"
2805 #endif
2806 #ifdef WITH_GNUTLS
2807 "+WITH_GNUTLS\n"
2808 #else
2809 "-WITH_GNUTLS\n"
2810 #endif
2811 #ifdef DEBUG
2812 "+DEBUG\n"
2813 #else
2814 "-DEBUG\n"
2815 #endif
2816 #ifdef MEM_DEBUG
2817 "+MEM_DEBUG\n"
2818 #else
2819 "-MEM_DEBUG\n"
2820 #endif
2821 #ifdef MUTEX_DEBUG
2822 "+MUTEX_DEBUG\n"
2823 #else
2824 "-MUTEX_DEBUG\n"
2825 #endif
2827 exit (EXIT_SUCCESS);
2830 if (!homedir)
2831 #ifdef PWMD_HOMEDIR
2832 homedir = str_dup(PWMD_HOMEDIR);
2833 #else
2834 homedir = str_asprintf ("%s/.pwmd", get_home_dir());
2835 #endif
2837 if (mkdir (homedir, 0700) == -1 && errno != EEXIST)
2838 err (EXIT_FAILURE, "%s", homedir);
2840 snprintf (buf, sizeof (buf), "%s/data", homedir);
2841 if (mkdir (buf, 0700) == -1 && errno != EEXIST)
2842 err (EXIT_FAILURE, "%s", buf);
2844 datadir = str_dup (buf);
2845 pthread_mutexattr_t attr;
2846 pthread_mutexattr_init (&attr);
2847 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
2848 pthread_mutex_init (&rcfile_mutex, &attr);
2849 pthread_cond_init (&rcfile_cond, NULL);
2850 pthread_mutex_init (&cn_mutex, &attr);
2851 pthread_mutexattr_destroy (&attr);
2852 pthread_key_create (&last_error_key, free_key);
2853 #ifndef HAVE_PTHREAD_CANCEL
2854 pthread_key_create (&signal_thread_key, free_key);
2855 #endif
2857 if (!rcfile)
2858 rcfile = str_asprintf ("%s/config", homedir);
2860 global_config = config_parse (rcfile);
2861 if (!global_config)
2862 exit (EXIT_FAILURE);
2864 #ifdef WITH_AGENT
2865 if (!use_agent)
2866 use_agent = config_get_boolean ("global", "use_agent");
2867 #endif
2869 setup_logging ();
2871 if (debug_level_opt)
2872 debug_level = str_split (debug_level_opt, ",", 0);
2874 x = config_get_int_param (global_config, "global", "priority", &exists);
2875 if (exists && x != atoi(INVALID_PRIORITY))
2877 errno = 0;
2878 if (setpriority (PRIO_PROCESS, 0, x) == -1)
2880 log_write ("setpriority(): %s",
2881 pwmd_strerror (gpg_error_from_errno (errno)));
2882 goto do_exit;
2885 #ifdef HAVE_MLOCKALL
2886 if (disable_mlock == 0 && mlockall (MCL_CURRENT | MCL_FUTURE) == -1)
2888 log_write ("mlockall(): %s",
2889 pwmd_strerror (gpg_error_from_errno (errno)));
2890 goto do_exit;
2892 #endif
2894 rc = cache_init (free_cache_data);
2895 if (rc)
2897 log_write ("pwmd: ERR %i: %s", rc,
2898 gpg_err_code (rc) == GPG_ERR_UNKNOWN_VERSION
2899 ? _("incompatible gpg-agent version: 2.1.0 or later required")
2900 : pwmd_strerror (rc));
2901 goto do_exit;
2904 if (s2k_count == 0)
2905 s2k_count = config_get_ulong (NULL, "s2k_count");
2907 if (convertfile)
2909 if (!outfile || !*outfile || argc != optind)
2910 usage (argv[0], EXIT_FAILURE);
2912 estatus = convert_v2_datafile (convertfile, cipher, keyfile, keygrip,
2913 sign_keygrip, no_passphrase, outfile,
2914 keyparam, s2k_count, iterations);
2915 config_free (global_config);
2916 xfree (rcfile);
2917 exit (!estatus);
2920 if (import)
2922 if (!outfile || !*outfile || argc != optind)
2923 usage (argv[0], EXIT_FAILURE);
2925 if (outfile && outfile[0] == '-' && outfile[1] == 0)
2926 outfile = NULL;
2928 estatus = xml_import (import, outfile, keygrip, sign_keygrip, keyfile,
2929 no_passphrase, cipher, keyparam, s2k_count,
2930 iterations);
2931 config_free (global_config);
2932 xfree (rcfile);
2933 exit (!estatus);
2936 p = config_get_string ("global", "socket_path");
2937 if (!p)
2938 p = str_asprintf ("%s/socket", homedir);
2940 socketarg = expand_homedir (p);
2941 xfree (p);
2943 if (!secure)
2944 disable_list_and_dump = config_get_boolean ("global",
2945 "disable_list_and_dump");
2946 else
2947 disable_list_and_dump = secure;
2949 cache_push = config_get_list ("global", "cache_push");
2951 while (optind < argc)
2953 if (strv_printf (&cache_push, "%s", argv[optind++]) == 0)
2954 errx (EXIT_FAILURE, "%s", pwmd_strerror (GPG_ERR_ENOMEM));
2957 if (strchr (socketarg, '/') == NULL)
2959 socketdir = getcwd (buf, sizeof (buf));
2960 socketname = str_dup (socketarg);
2961 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2963 else
2965 socketname = str_dup (strrchr (socketarg, '/'));
2966 socketname++;
2967 socketarg[strlen (socketarg) - strlen (socketname) - 1] = 0;
2968 socketdir = str_dup (socketarg);
2969 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2972 if (chdir (datadir))
2974 log_write ("%s: %s", datadir,
2975 pwmd_strerror (gpg_error_from_errno (errno)));
2976 unlink (socketpath);
2977 goto do_exit;
2980 if (test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 0,
2981 mode))
2982 goto do_exit;
2985 * bind() doesn't like the full pathname of the socket or any non alphanum
2986 * characters so change to the directory where the socket is wanted then
2987 * create it then change to datadir.
2989 if (chdir (socketdir))
2991 log_write ("%s: %s", socketdir,
2992 pwmd_strerror (gpg_error_from_errno (errno)));
2993 goto do_exit;
2996 xfree (socketdir);
2998 if ((sockfd = socket (PF_UNIX, SOCK_STREAM, 0)) == -1)
3000 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
3001 goto do_exit;
3004 addr.sun_family = AF_UNIX;
3005 snprintf (addr.sun_path, sizeof (addr.sun_path), "%s", socketname);
3006 do_unlink = 1;
3007 if (bind (sockfd, (struct sockaddr *) &addr, sizeof (struct sockaddr)) ==
3010 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
3012 if (errno == EADDRINUSE)
3014 do_unlink = 0;
3015 log_write (_("Either there is another pwmd running or '%s' is a \n"
3016 "stale socket. Please remove it manually."), socketpath);
3019 goto do_exit;
3023 char *t = config_get_string ("global", "socket_perms");
3024 mode_t mask;
3026 if (t)
3028 mode = strtol (t, NULL, 8);
3029 mask = umask (0);
3030 xfree (t);
3032 if (chmod (socketname, mode) == -1)
3034 log_write ("%s: %s", socketname,
3035 pwmd_strerror (gpg_error_from_errno (errno)));
3036 close (sockfd);
3037 umask (mask);
3038 goto do_exit;
3041 umask (mask);
3045 xfree (--socketname);
3047 if (chdir (datadir))
3049 log_write ("%s: %s", datadir,
3050 pwmd_strerror (gpg_error_from_errno (errno)));
3051 close (sockfd);
3052 goto do_exit;
3055 xfree (datadir);
3058 * Set the cache entry for a file. Prompts for the password.
3060 if (cache_push)
3062 struct crypto_s *crypto = NULL;
3063 gpg_error_t rc = init_client_crypto (&crypto);
3065 if (rc)
3067 estatus = EXIT_FAILURE;
3068 goto do_exit;
3071 #ifdef WITH_AGENT
3072 if (use_agent)
3074 rc = agent_set_pinentry_options (crypto->agent);
3075 if (rc)
3077 estatus = EXIT_FAILURE;
3078 goto do_exit;
3081 #endif
3083 for (opt = 0; cache_push[opt]; opt++)
3085 if (!do_cache_push (cache_push[opt], crypto) && !force)
3087 strv_free (cache_push);
3088 startup_failure ();
3089 estatus = EXIT_FAILURE;
3090 cleanup_crypto (&crypto);
3091 goto do_exit;
3094 cleanup_crypto_stage1 (crypto);
3097 #ifdef WITH_AGENT
3098 if (use_agent)
3099 (void) kill_scd (crypto->agent);
3100 #endif
3102 cleanup_crypto (&crypto);
3103 strv_free (cache_push);
3104 log_write (!nofork ? _("Done. Daemonizing...") :
3105 _("Done. Waiting for connections..."));
3108 config_clear_keys ();
3110 if (listen (sockfd, 0) == -1)
3112 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
3113 goto do_exit;
3116 if (!nofork)
3118 switch (fork ())
3120 case -1:
3121 log_write ("fork(): %s",
3122 pwmd_strerror (gpg_error_from_errno (errno)));
3123 goto do_exit;
3124 case 0:
3125 close (0);
3126 close (1);
3127 close (2);
3128 setsid ();
3129 break;
3130 default:
3131 _exit (EXIT_SUCCESS);
3135 (void)test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 1,
3136 mode);
3137 cmdline = 0;
3138 pthread_key_create (&thread_name_key, free_key);
3139 pthread_setspecific (thread_name_key, str_dup ("main"));
3140 estatus = server_loop (sockfd, &socketpath);
3142 do_exit:
3143 if (socketpath && do_unlink)
3145 unlink (socketpath);
3146 xfree (socketpath);
3149 xfree (socketarg);
3150 #ifdef WITH_GNUTLS
3151 gnutls_global_deinit ();
3152 xfree (invoking_tls);
3153 #endif
3154 if (rcfile_tid)
3156 #ifdef HAVE_PTHREAD_CANCEL
3157 pthread_cancel (rcfile_tid);
3158 #else
3159 pthread_kill (rcfile_tid, SIGUSR2);
3160 pthread_cond_signal (&rcfile_cond);
3161 #endif
3162 pthread_join (rcfile_tid, NULL);
3165 pthread_cond_destroy (&rcfile_cond);
3166 pthread_mutex_destroy (&rcfile_mutex);
3167 pthread_key_delete (last_error_key);
3168 #ifndef HAVE_PTHREAD_CANCEL
3169 pthread_key_delete (signal_thread_key);
3170 #endif
3172 if (global_config)
3173 config_free (global_config);
3175 xfree (rcfile);
3176 xfree (home_directory);
3177 xfree (homedir);
3178 xmlCleanupParser ();
3179 xmlCleanupGlobals ();
3181 if (pidfile)
3182 unlink (pidfile);
3183 xfree (pidfile);
3185 if (estatus == EXIT_SUCCESS)
3186 log_write (_("pwmd exiting normally"));
3188 pthread_key_delete (thread_name_key);
3189 closelog ();
3190 #if defined(DEBUG) && !defined(MEM_DEBUG)
3191 xdump ();
3192 #endif
3194 if (log_fd != -1)
3195 close (log_fd);
3197 exit (estatus);