Fix Coverity issue #100339.
[libpwmd.git] / src / pwmd.c
blobcb9d379dfbf08bd2987939772a5ad0229fb0268e
1 /*
2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015
3 Ben Kibbey <bjk@luxsci.net>
5 This file is part of pwmd.
7 Pwmd is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 2 of the License, or
10 (at your option) any later version.
12 Pwmd is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
20 #ifdef HAVE_CONFIG_H
21 #include <config.h>
22 #endif
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <unistd.h>
27 #include <err.h>
28 #include <ctype.h>
29 #include <string.h>
30 #include <sys/socket.h>
31 #include <sys/un.h>
32 #include <signal.h>
33 #include <stdarg.h>
34 #include <string.h>
35 #include <sys/wait.h>
36 #include <fcntl.h>
37 #include <pwd.h>
38 #include <grp.h>
39 #include <pthread.h>
40 #include <sys/mman.h>
41 #include <termios.h>
42 #include <assert.h>
43 #include <syslog.h>
44 #include <netinet/in.h>
45 #include <arpa/inet.h>
46 #include <netdb.h>
47 #include <sys/time.h>
48 #include <sys/resource.h>
49 #include <setjmp.h>
50 #include <errno.h>
52 #ifdef TM_IN_SYS_TIME
53 #include <sys/time.h>
54 #else
55 #include <time.h>
56 #endif
58 #ifdef HAVE_LIMITS_H
59 #include <limits.h>
60 #endif
62 #ifdef HAVE_GETOPT_LONG
63 #ifdef HAVE_GETOPT_H
64 #include <getopt.h>
65 #endif
66 #else
67 #include "getopt_long.h"
68 #endif
70 #ifdef HAVE_PR_SET_NAME
71 #include <sys/prctl.h>
72 #endif
74 #include "pwmd-error.h"
75 #include <gcrypt.h>
77 #include "util-misc.h"
78 #include "mem.h"
79 #include "xml.h"
80 #include "common.h"
81 #include "commands.h"
82 #include "cache.h"
83 #include "util-string.h"
84 #include "mutex.h"
85 #include "rcfile.h"
86 #include "crypto.h"
87 #include "convert.h"
88 #include "pinentry.h"
90 /* In tenths of a second. */
91 #define SIG_TIMEOUT 1
93 /* For (tcp_)accept_thread (usec). */
94 #define ACCEPT_TIMEOUT 30000
96 static int quit;
97 static int exiting;
98 static int cmdline;
99 static jmp_buf jmp;
100 static int nofork;
101 static pthread_cond_t quit_cond;
102 static pthread_mutex_t quit_mutex;
103 static int no_passphrase_file = 0;
104 static pthread_t keepalive_tid;
105 static int log_fd;
107 #ifndef HAVE_PTHREAD_CANCEL
108 static pthread_key_t signal_thread_key;
109 #endif
111 #ifdef WITH_GNUTLS
112 static int tls_fd;
113 static int tls6_fd;
114 static pthread_t tls_tid;
115 static pthread_t tls6_tid;
116 static int spawned_tls;
117 static int spawned_tls6;
119 static int start_stop_tls (int term);
120 #endif
122 static int do_cache_push (const char *filename, struct crypto_s *crypto);
123 static int signal_loop (sigset_t sigset);
125 GCRY_THREAD_OPTION_PTHREAD_IMPL;
127 #ifndef HAVE_PTHREAD_CANCEL
128 #define INIT_THREAD_SIGNAL do { \
129 struct sigaction act; \
130 sigset_t sigset; \
131 sigemptyset (&sigset); \
132 sigaddset (&sigset, SIGUSR2); \
133 pthread_sigmask (SIG_UNBLOCK, &sigset, NULL); \
134 memset (&act, 0, sizeof(act)); \
135 act.sa_flags = SA_SIGINFO; \
136 act.sa_mask = sigset; \
137 act.sa_sigaction = catch_thread_signal; \
138 sigaction (SIGUSR2, &act, NULL); \
139 } while (0)
141 static void
142 catch_thread_signal (int sig, siginfo_t *info, void *ctx)
144 int *n = (int *) pthread_getspecific (signal_thread_key);
146 *n = 1;
147 pthread_setspecific (signal_thread_key, n);
149 #endif
151 static void
152 cache_push_from_rcfile ()
154 struct crypto_s *crypto = NULL;
155 char **cache_push;
156 gpg_error_t rc = init_client_crypto (&crypto);
158 if (rc)
160 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
161 return;
164 #ifdef WITH_AGENT
165 if (use_agent)
167 rc = set_agent_option (crypto->agent, "pinentry-mode", "error");
168 if (rc)
170 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
171 return;
174 #endif
176 cache_push = config_get_list ("global", "cache_push");
177 if (cache_push)
179 char **p;
181 for (p = cache_push; *p; p++)
183 (void) do_cache_push (*p, crypto);
184 cleanup_crypto_stage1 (crypto);
187 strv_free (cache_push);
190 #ifdef WITH_AGENT
191 (void) kill_scd (crypto->agent);
192 #endif
193 cleanup_crypto (&crypto);
196 static void
197 setup_logging ()
199 int n = config_get_boolean ("global", "enable_logging");
201 if (n)
203 char *p = config_get_string ("global", "log_path");
205 if (!p || (logfile && p && log_fd != -1 && strcmp(p, logfile)))
207 if (log_fd != -1)
208 close (log_fd);
210 log_fd = -1;
213 xfree (logfile);
214 logfile = expand_homedir (p);
215 xfree (p);
217 else
219 xfree (logfile);
220 logfile = NULL;
221 if (log_fd != -1)
222 close(log_fd);
224 log_fd = -1;
227 log_syslog = config_get_boolean ("global", "syslog");
228 if (log_syslog == 1)
229 openlog ("pwmd", LOG_NDELAY | LOG_PID, LOG_DAEMON);
232 static void *
233 reload_rcfile_thread (void *arg)
235 #ifndef HAVE_PTHREAD_CANCEL
236 int *n = xmalloc (sizeof (int));
238 *n = 0;
239 pthread_setspecific (signal_thread_key, n);
240 INIT_THREAD_SIGNAL;
241 #endif
243 #ifdef HAVE_PR_SET_NAME
244 prctl (PR_SET_NAME, "reload rcfile");
245 #endif
246 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
247 MUTEX_LOCK (&rcfile_mutex);
248 pthread_cleanup_push (cleanup_mutex_cb, &rcfile_mutex);
250 for (;;)
252 struct allowed_users_s
254 char *section;
255 char **users;
257 struct slist_s *allowed_users = NULL;
258 struct slist_s *config;
259 int b = disable_list_and_dump;
260 uid_t invoking_uid_orig = invoking_uid;
261 gid_t invoking_gid_orig = invoking_gid;
262 char *invoking_tls_orig;
263 int exists;
264 int require_save_key = config_get_bool_param (global_config, "global",
265 "require_save_key",
266 &exists);
267 #ifdef WITH_GNUTLS
268 int tcp_require_key = config_get_bool_param (global_config, "global",
269 "tcp_require_key",
270 &exists);
271 #endif
273 pthread_cond_wait (&rcfile_cond, &rcfile_mutex);
274 #ifndef HAVE_PTHREAD_CANCEL
275 int *cancel = (int *) pthread_getspecific (signal_thread_key);
276 if (*cancel)
277 break;
278 #endif
280 /* Keep the "allowed" parameter across rcfile reloads to prevent
281 tampering. */
282 int n, t = slist_length (global_config);
283 for (n = 0; n < t; n++)
285 struct config_section_s *section;
286 char **users;
288 section = slist_nth_data (global_config, n);
289 users = config_get_list_param (global_config, section->name,
290 "allowed", &exists);
291 if (users)
293 struct allowed_users_s *allowed;
295 allowed = xmalloc (sizeof(struct allowed_users_s));
296 allowed->section = str_dup (section->name);
297 allowed->users = users;
298 allowed_users = slist_append (allowed_users, allowed);
302 invoking_tls_orig = invoking_tls ? str_dup (invoking_tls) : NULL;
303 xfree (invoking_tls);
304 invoking_tls = NULL;
305 log_write (_("reloading configuration file '%s'"), rcfile);
307 config = config_parse (rcfile);
308 if (config)
310 config_free (global_config);
311 global_config = config;
312 setup_logging ();
313 cache_push_from_rcfile ();
314 config_clear_keys ();
317 xfree (invoking_tls);
318 invoking_tls = invoking_tls_orig;
319 invoking_uid = invoking_uid_orig;
320 invoking_gid = invoking_gid_orig;
321 disable_list_and_dump = !disable_list_and_dump ? b : 1;
322 config_set_bool_param (&global_config, "global", "require_save_key",
323 require_save_key ? "true" : "false");
324 #ifdef WITH_GNUTLS
325 if (config_get_bool_param (global_config, "global", "tcp_require_key",
326 &exists) && exists)
327 tcp_require_key = 1;
329 config_set_bool_param (&global_config, "global", "tcp_require_key",
330 tcp_require_key ? "true" : "false");
331 #endif
333 if (allowed_users)
335 int n, t = slist_length (allowed_users);
337 for (n = 0; n < t; n++)
339 struct allowed_users_s *allowed;
340 char *tmp;
342 allowed = slist_nth_data (allowed_users, n);
343 tmp = strv_join (",", allowed->users);
344 config_set_list_param (&global_config, allowed->section,
345 "allowed", tmp);
346 xfree (tmp);
347 xfree (allowed->section);
348 strv_free (allowed->users);
349 xfree (allowed);
352 slist_free (allowed_users);
355 #ifdef WITH_GNUTLS
356 /* Kill existing listening threads since the configured listening
357 * protocols may have changed. */
358 start_stop_tls (1);
359 start_stop_tls (0);
360 #endif
363 pthread_cleanup_pop (1);
364 return NULL;
367 gpg_error_t
368 send_error (assuan_context_t ctx, gpg_error_t e)
370 struct client_s *client = assuan_get_pointer (ctx);
372 if (gpg_err_source (e) == GPG_ERR_SOURCE_UNKNOWN)
373 e = gpg_error (e);
375 if (client)
376 client->last_rc = e;
378 if (!e)
379 return assuan_process_done (ctx, 0);
381 if (!ctx)
383 log_write ("ERR %i: %s", e, pwmd_strerror (e));
384 return e;
387 if (client && client->xml_error)
389 log_write ("%s", client->xml_error->message);
390 xfree (client->last_error);
391 client->last_error = NULL;
392 if (client->xml_error->message)
393 client->last_error = str_dup (client->xml_error->message);
395 e = assuan_process_done (ctx,
396 assuan_set_error (ctx, e,
397 client->xml_error->message ? client->xml_error->message : NULL));
398 xmlResetLastError ();
399 xmlResetError (client->xml_error);
400 xfree (client->xml_error);
401 client->xml_error = NULL;
402 return e;
405 return assuan_process_done (ctx,
406 assuan_set_error (ctx, e, pwmd_strerror (e)));
410 assuan_log_cb (assuan_context_t ctx, void *data, unsigned cat,
411 const char *msg)
413 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
414 int i, t;
415 int match = 0;
417 pthread_mutex_lock (&m);
418 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock, &m);
419 t = strv_length (debug_level);
421 for (i = 0; i < t; i++)
423 if (!strcasecmp (debug_level[i], (char *) "init")
424 && cat == ASSUAN_LOG_INIT)
426 match = 1;
427 break;
430 if (!strcasecmp (debug_level[i], (char *) "ctx")
431 && cat == ASSUAN_LOG_CTX)
433 match = 1;
434 break;
437 if (!strcasecmp (debug_level[i], (char *) "engine")
438 && cat == ASSUAN_LOG_ENGINE)
440 match = 1;
441 break;
444 if (!strcasecmp (debug_level[i], (char *) "data")
445 && cat == ASSUAN_LOG_DATA)
447 match = 1;
448 break;
451 if (!strcasecmp (debug_level[i], (char *) "sysio")
452 && cat == ASSUAN_LOG_SYSIO)
454 match = 1;
455 break;
458 if (!strcasecmp (debug_level[i], (char *) "control")
459 && cat == ASSUAN_LOG_CONTROL)
461 match = 1;
462 break;
466 if (match && msg)
468 if (logfile)
470 int fd;
472 if ((fd =
473 open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600)) == -1)
474 warn ("%s", logfile);
475 else
477 pthread_cleanup_push (cleanup_fd_cb, &fd);
478 write (fd, msg, strlen (msg));
479 pthread_cleanup_pop (1);
483 if (nofork)
485 fprintf (stderr, "%s%s", data ? (char *) data : "", msg);
486 fflush (stderr);
490 pthread_cleanup_pop (1);
491 return match;
494 void
495 log_write (const char *fmt, ...)
497 char *args;
498 va_list ap;
499 time_t now;
500 char buf[255];
501 pthread_t tid = pthread_self ();
502 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
504 if ((!logfile && !isatty (STDERR_FILENO) && !log_syslog) || !fmt)
505 return;
507 pthread_mutex_lock (&m);
508 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock, &m);
510 if (!cmdline && logfile && log_fd == -1)
512 log_fd = open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600);
513 if (log_fd == -1)
514 warn ("%s", logfile);
517 va_start (ap, fmt);
519 if (str_vasprintf (&args, fmt, ap) != -1)
521 if (cmdline)
523 pthread_cleanup_push (xfree, args);
524 fprintf (stderr, "pwmd: %s\n", args);
525 fflush (stderr);
526 pthread_cleanup_pop (1);
528 else
530 char *name = pthread_getspecific (thread_name_key);
531 char *line;
533 pthread_cleanup_push (xfree, args);
534 snprintf (buf, sizeof (buf), "%s(%p): ", name ? name : _("unknown"),
535 (pthread_t *) tid);
536 name = buf;
538 if (!cmdline && log_syslog && !nofork)
539 syslog (LOG_INFO, "%s%s", name, args);
541 time (&now);
542 struct tm *tm = localtime (&now);
543 char tbuf[21];
544 strftime (tbuf, sizeof (tbuf), "%b %d %Y %H:%M:%S ", tm);
545 tbuf[sizeof (tbuf) - 1] = 0;
547 if (args[strlen (args) - 1] == '\n')
548 args[strlen (args) - 1] = 0;
550 line = str_asprintf ("%s %i %s%s\n", tbuf, getpid (), name,
551 args);
552 pthread_cleanup_pop (1);
553 if (line)
555 pthread_cleanup_push (xfree, line);
556 if (logfile && log_fd != -1)
558 write (log_fd, line, strlen (line));
559 fsync (log_fd);
562 if (nofork)
564 fprintf (stdout, "%s", line);
565 fflush (stdout);
568 pthread_cleanup_pop (1);
573 va_end (ap);
574 pthread_cleanup_pop (0);
576 if (log_fd != -1 && config_get_boolean (NULL, "log_keepopen") <= 0)
578 close(log_fd);
579 log_fd = -1;
582 pthread_mutex_unlock (&m);
585 #ifdef WITH_GNUTLS
586 static int
587 secure_mem_check (const void *arg)
589 return 1;
591 #endif
593 static gpg_error_t
594 setup_crypto ()
596 gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
598 if (!gcry_check_version (GCRYPT_VERSION))
600 fprintf (stderr, _("gcry_check_version(): Incompatible libgcrypt. "
601 "Wanted %s, got %s.\n"), GCRYPT_VERSION,
602 gcry_check_version (NULL));
603 return GPG_ERR_UNKNOWN_VERSION;
606 gcry_set_allocation_handler (xmalloc, xmalloc, NULL, xrealloc, xfree);
607 return 0;
610 gpg_error_t
611 do_validate_peer (assuan_context_t ctx, const char *section,
612 assuan_peercred_t * peer)
614 char **users;
615 int allowed = 0;
616 gpg_error_t rc;
617 struct client_s *client = assuan_get_pointer (ctx);
619 #ifdef WITH_GNUTLS
620 if (client && client->thd->remote)
621 return tls_validate_access (client, section);
622 #endif
624 rc = assuan_get_peercred (ctx, peer);
625 if (rc)
626 return rc;
628 users = config_get_list (section, "allowed");
629 if (users)
631 for (char **p = users; *p; p++)
633 rc = acl_check_common(client, *p, (*peer)->uid, (*peer)->gid,
634 &allowed);
637 strv_free (users);
640 return allowed ? 0 : rc ? rc : GPG_ERR_EACCES;
643 gpg_error_t
644 peer_is_invoker(struct client_s *client)
646 if (client->thd->state == CLIENT_STATE_UNKNOWN)
647 return GPG_ERR_EACCES;
649 #ifdef WITH_GNUTLS
650 if (client->thd->remote)
652 char *p = invoking_tls;
654 if (!p || !*p || *p++ != '#')
655 return GPG_ERR_EACCES;
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 MUTEX_LOCK (&cn_mutex);
865 rc = do_validate_peer (cl->ctx, "global", &cl->thd->peer);
866 MUTEX_UNLOCK (&cn_mutex);
867 if (!rc || gpg_err_code (rc) == GPG_ERR_EACCES)
868 log_write ("peer %s: uid=%i, gid=%i, pid=%i",
869 !rc ? _("accepted") : _("rejected"), cl->thd->peer->uid,
870 cl->thd->peer->gid, cl->thd->peer->pid);
871 else if (rc)
872 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
874 return rc;
877 static void
878 xml_error_cb (void *data, xmlErrorPtr e)
880 struct client_s *client = data;
883 * Keep the first reported error as the one to show in the error
884 * description. Reset in send_error().
886 if (client->xml_error)
887 return;
889 client->xml_error = xcalloc (1, sizeof(xmlError));
890 xmlCopyError (e, client->xml_error);
893 static pid_t
894 hook_waitpid (assuan_context_t ctx, pid_t pid, int action,
895 int *status, int options)
897 return waitpid (pid, status, options);
900 static ssize_t
901 hook_read (assuan_context_t ctx, assuan_fd_t fd, void *data, size_t len)
903 #ifdef WITH_GNUTLS
904 struct client_s *client = assuan_get_pointer (ctx);
906 if (client->thd->remote)
907 return tls_read_hook (ctx, (int) fd, data, len);
908 #endif
910 return read ((int) fd, data, len);
913 static ssize_t
914 hook_write (assuan_context_t ctx, assuan_fd_t fd,
915 const void *data, size_t len)
917 #ifdef WITH_GNUTLS
918 struct client_s *client = assuan_get_pointer (ctx);
920 if (client->thd->remote)
921 return tls_write_hook (ctx, (int) fd, data, len);
922 #endif
924 return write ((int) fd, data, len);
927 static int
928 new_connection (struct client_s *cl)
930 gpg_error_t rc;
931 static struct assuan_malloc_hooks mhooks = { xmalloc, xrealloc, xfree };
932 static struct assuan_system_hooks shooks = {
933 ASSUAN_SYSTEM_HOOKS_VERSION,
934 __assuan_usleep,
935 __assuan_pipe,
936 __assuan_close,
937 hook_read,
938 hook_write,
939 //FIXME
940 NULL, //recvmsg
941 NULL, //sendmsg both are used for FD passing
942 __assuan_spawn,
943 hook_waitpid,
944 __assuan_socketpair,
945 __assuan_socket,
946 __assuan_connect
949 #ifdef WITH_GNUTLS
950 if (cl->thd->remote)
952 char *prio = config_get_string ("global", "tls_cipher_suite");
954 cl->thd->timeout = config_get_integer ("global", "tls_timeout");
955 fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK);
956 cl->thd->tls = tls_init (cl->thd->fd, cl->thd->timeout, prio);
957 xfree (prio);
958 if (!cl->thd->tls)
959 return 0;
961 #endif
963 rc = assuan_new_ext (&cl->ctx, GPG_ERR_SOURCE_DEFAULT, &mhooks,
964 debug_level ? assuan_log_cb : NULL, NULL);
965 if (rc)
966 goto fail;
968 assuan_ctx_set_system_hooks (cl->ctx, &shooks);
969 rc = assuan_init_socket_server (cl->ctx, cl->thd->fd, 2);
970 if (rc)
971 goto fail;
973 assuan_set_pointer (cl->ctx, cl);
974 assuan_set_hello_line (cl->ctx, PACKAGE_STRING);
975 rc = register_commands (cl->ctx);
976 if (rc)
977 goto fail;
979 rc = assuan_accept (cl->ctx);
980 if (rc)
981 goto fail;
983 rc = validate_peer (cl);
984 /* May not be implemented on all platforms. */
985 if (rc && gpg_err_code (rc) != GPG_ERR_ASS_GENERAL)
986 goto fail;
988 MUTEX_LOCK (&cn_mutex);
989 cl->thd->state = CLIENT_STATE_INIT;
990 MUTEX_UNLOCK (&cn_mutex);
991 rc = init_client_crypto (&cl->crypto);
992 if (rc)
993 goto fail;
995 #ifdef WITH_AGENT
996 if (use_agent)
997 cl->crypto->agent->client_ctx = cl->ctx;
998 #endif
1000 cl->crypto->client_ctx = cl->ctx;
1001 cl->lock_timeout = config_get_integer ("global", "lock_timeout");
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->name);
1082 #ifdef WITH_GNUTLS
1083 xfree (cn->peeraddr);
1084 #endif
1085 xfree (cn);
1086 pthread_cond_signal (&quit_cond);
1089 void
1090 cleanup_all_clients (int atfork)
1092 /* This function may be called from pthread_atfork() which requires
1093 reinitialization. */
1094 if (atfork)
1096 pthread_mutexattr_t attr;
1098 pthread_mutexattr_init (&attr);
1099 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
1100 pthread_mutex_init (&cn_mutex, &attr);
1101 pthread_mutexattr_destroy (&attr);
1102 cache_mutex_init ();
1105 MUTEX_LOCK (&cn_mutex);
1107 while (slist_length (cn_thread_list))
1109 struct client_thread_s *thd = slist_nth_data (cn_thread_list, 0);
1111 thd->atfork = atfork;
1112 cleanup_cb (thd);
1115 exiting = 1;
1116 MUTEX_UNLOCK (&cn_mutex);
1117 cache_deinit (atfork);
1120 static gpg_error_t
1121 send_msg_queue (struct client_thread_s *thd)
1123 MUTEX_LOCK (&thd->status_mutex);
1124 gpg_error_t rc = 0;
1125 char c;
1127 read (thd->status_msg_pipe[0], &c, 1);
1128 thd->wrote_status = 0;
1130 while (thd->msg_queue)
1132 struct status_msg_s *msg = thd->msg_queue;
1134 thd->msg_queue = thd->msg_queue->next;
1135 MUTEX_UNLOCK (&thd->status_mutex);
1136 rc = send_status (thd->cl->ctx, msg->s, msg->line);
1137 MUTEX_LOCK (&thd->status_mutex);
1138 xfree (msg->line);
1139 xfree (msg);
1141 if (rc)
1142 break;
1145 MUTEX_UNLOCK (&thd->status_mutex);
1146 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1147 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
1149 return rc;
1152 static void *
1153 client_thread (void *data)
1155 struct client_thread_s *thd = data;
1156 struct client_s *cl = xcalloc (1, sizeof (struct client_s));
1158 #ifdef HAVE_PR_SET_NAME
1159 prctl (PR_SET_NAME, "client");
1160 #endif
1161 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1163 if (!cl)
1165 log_write ("%s(%i): %s", __FILE__, __LINE__,
1166 pwmd_strerror (GPG_ERR_ENOMEM));
1167 return NULL;
1170 MUTEX_LOCK (&cn_mutex);
1171 pthread_cleanup_push (cleanup_cb, thd);
1172 thd->cl = cl;
1173 cl->thd = thd;
1174 MUTEX_UNLOCK (&cn_mutex);
1176 if (new_connection (cl))
1178 int finished = 0;
1179 gpg_error_t rc;
1181 send_status_all (STATUS_CLIENTS, NULL);
1182 rc = send_status (cl->ctx, STATUS_CACHE, NULL);
1183 if (rc)
1185 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
1186 finished = 1;
1189 while (!finished)
1191 fd_set rfds;
1192 int n;
1193 int eof;
1195 FD_ZERO (&rfds);
1196 FD_SET (thd->fd, &rfds);
1197 FD_SET (thd->status_msg_pipe[0], &rfds);
1198 n = thd->fd > thd->status_msg_pipe[0]
1199 ? thd->fd : thd->status_msg_pipe[0];
1201 n = select (n + 1, &rfds, NULL, NULL, NULL);
1202 if (n == -1)
1204 log_write ("%s", strerror (errno));
1205 break;
1208 if (FD_ISSET (thd->status_msg_pipe[0], &rfds))
1210 rc = send_msg_queue (thd);
1211 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1212 break;
1215 if (!FD_ISSET (thd->fd, &rfds))
1216 continue;
1218 rc = assuan_process_next (cl->ctx, &eof);
1219 if (rc || eof)
1221 if (gpg_err_code (rc) == GPG_ERR_EOF || eof)
1222 break;
1224 log_write ("assuan_process_next(): rc=%i %s", rc,
1225 pwmd_strerror (rc));
1226 if (rc == gpg_error (GPG_ERR_ETIMEDOUT))
1227 break;
1229 rc = send_error (cl->ctx, rc);
1230 if (rc)
1232 log_write ("assuan_process_done(): rc=%i %s", rc,
1233 pwmd_strerror (rc));
1234 break;
1238 /* Since the msg queue pipe fd's are non-blocking, check for
1239 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1240 * client has already disconnected and will be converted to
1241 * GPG_ERR_EOF during assuan_process_next().
1243 rc = send_msg_queue (thd);
1244 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1245 break;
1249 /* Don't do pthread_exit() here because any set pthread_cleanup_push
1250 * functions would be called after a command failed but then the client
1251 * exited normally which may lead to a double free. */
1252 pthread_cleanup_pop (1);
1253 return NULL;
1256 static int
1257 xml_import (const char *filename, const char *outfile,
1258 const char *keygrip, const char *sign_keygrip,
1259 const char *keyfile, int no_passphrase, const char *cipher,
1260 const char *params, unsigned long s2k_count, uint64_t iterations)
1262 xmlDocPtr doc;
1263 int fd;
1264 struct stat st;
1265 int len;
1266 xmlChar *xmlbuf;
1267 xmlChar *xml;
1268 gpg_error_t rc;
1269 struct crypto_s *crypto = NULL;
1270 void *key = NULL;
1271 size_t keylen = 0;
1272 int algo = cipher ? cipher_string_to_gcrypt ((char *) cipher) :
1273 GCRY_CIPHER_AES256;
1275 if (algo == -1)
1277 log_write ("ERR %i: %s", gpg_error (GPG_ERR_CIPHER_ALGO),
1278 pwmd_strerror (GPG_ERR_CIPHER_ALGO));
1279 return 0;
1282 if (stat (filename, &st) == -1)
1284 log_write ("%s: %s", filename,
1285 pwmd_strerror (gpg_error_from_errno (errno)));
1286 return 0;
1289 rc = init_client_crypto (&crypto);
1290 if (rc)
1291 return 0;
1293 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
1294 crypto->save.hdr.flags = set_cipher_flag (crypto->save.hdr.flags, algo);
1295 log_write (_("Importing XML from '%s'. Output will be written to '%s' ..."),
1296 filename, outfile);
1298 if ((fd = open (filename, O_RDONLY)) == -1)
1300 log_write ("%s: %s", filename,
1301 pwmd_strerror (gpg_error_from_errno (errno)));
1302 goto fail;
1305 if ((xmlbuf = xmalloc (st.st_size + 1)) == NULL)
1307 close (fd);
1308 log_write ("%s(%i): %s", __FILE__, __LINE__,
1309 pwmd_strerror (GPG_ERR_ENOMEM));
1310 goto fail;
1313 if (read (fd, xmlbuf, st.st_size) == -1)
1315 rc = gpg_error_from_errno (errno);
1316 close (fd);
1317 log_write ("%s: %s", filename, pwmd_strerror (rc));
1318 goto fail;
1321 close (fd);
1322 xmlbuf[st.st_size] = 0;
1324 * Make sure the document validates.
1326 if ((doc = xmlReadDoc (xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS)) == NULL)
1328 log_write ("xmlReadDoc() failed");
1329 xfree (xmlbuf);
1330 goto fail;
1333 xfree (xmlbuf);
1334 xmlNodePtr n = xmlDocGetRootElement (doc);
1335 if (n && !xmlStrEqual (n->name, (xmlChar *) "pwmd"))
1337 log_write (_("Could not find root \"pwmd\" element."));
1338 rc = GPG_ERR_BAD_DATA;
1341 if (!rc)
1342 rc = validate_import (NULL, n ? n->children : n);
1344 if (rc)
1346 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1347 xmlFreeDoc (doc);
1348 goto fail;
1351 xmlDocDumpMemory (doc, &xml, &len);
1352 xmlFreeDoc (doc);
1353 crypto->save.s2k_count = s2k_count;
1354 crypto->save.hdr.iterations = iterations;
1355 if (!use_agent)
1357 rc = export_common (NULL, 0, crypto, xml, len, outfile, keyfile, &key,
1358 &keylen, 0, 0, no_passphrase);
1359 if (!rc)
1360 log_write (_("Success!"));
1362 #ifdef WITH_AGENT
1363 else
1365 rc = agent_set_pinentry_options (crypto->agent);
1366 if (!rc)
1367 rc = agent_export_common (crypto, keygrip, sign_keygrip, no_passphrase,
1368 xml, len, outfile, params, keyfile);
1370 #endif
1372 gcry_free (key);
1373 xmlFree (xml);
1374 if (rc)
1376 send_error (NULL, rc);
1377 goto fail;
1380 cleanup_crypto (&crypto);
1381 return 1;
1383 fail:
1384 cleanup_crypto (&crypto);
1385 return 0;
1388 static int
1389 do_cache_push (const char *filename, struct crypto_s *crypto)
1391 unsigned char md5file[16];
1392 gpg_error_t rc;
1393 char *key = NULL;
1394 size_t keylen = 0;
1395 xmlDocPtr doc;
1396 struct cache_data_s *cdata;
1397 unsigned char *crc;
1398 size_t len;
1400 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1401 filename);
1403 if (valid_filename (filename) == 0)
1405 log_write (_("%s: Invalid characters in filename"), filename);
1406 return 0;
1409 rc = decrypt_common (NULL, 0, crypto, filename, &key, &keylen);
1410 if (rc)
1411 return 0;
1413 rc = parse_doc ((char *) crypto->plaintext, crypto->plaintext_len, &doc);
1414 if (rc)
1416 log_write ("%s", pwmd_strerror (rc));
1417 xfree (key);
1418 return 0;
1421 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
1422 cdata = xcalloc (1, sizeof (struct cache_data_s));
1423 if (!cdata)
1425 xmlFreeDoc (doc);
1426 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM));
1427 xfree (key);
1428 return 0;
1431 rc = get_checksum (filename, &crc, &len);
1432 if (rc)
1434 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1435 xmlFreeDoc (doc);
1436 free_cache_data_once (cdata);
1437 xfree (key);
1438 return 0;
1441 cdata->crc = crc;
1442 rc = encrypt_xml (NULL, cache_key, cache_keysize, GCRY_CIPHER_AES,
1443 crypto->plaintext, crypto->plaintext_len, &cdata->doc,
1444 &cdata->doclen, &cache_iv, &cache_blocksize, 0);
1445 if (!rc && !IS_PKI (crypto))
1447 cdata->key = key;
1448 cdata->keylen = keylen;
1450 else
1451 xfree (key);
1453 if (rc)
1455 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1456 xmlFreeDoc (doc);
1457 free_cache_data_once (cdata);
1458 return 0;
1461 #ifdef WITH_AGENT
1462 if (use_agent && IS_PKI (crypto))
1464 gcry_sexp_build ((gcry_sexp_t *) & cdata->pubkey, NULL, "%S",
1465 crypto->pkey_sexp);
1466 gcry_sexp_build ((gcry_sexp_t *) & cdata->sigkey, NULL, "%S",
1467 crypto->sigpkey_sexp);
1469 #endif
1471 int timeout = config_get_integer (filename, "cache_timeout");
1472 cache_add_file (md5file, crypto->grip, cdata, timeout);
1473 log_write (_("Successfully added '%s' to the cache."), filename);
1474 return 1;
1477 static gpg_error_t
1478 init_client (int fd, const char *addr)
1480 gpg_error_t rc = 0;
1481 struct client_thread_s *new = xcalloc (1, sizeof (struct client_thread_s));
1483 if (!new)
1485 close (fd);
1486 return GPG_ERR_ENOMEM;
1489 MUTEX_LOCK (&cn_mutex);
1490 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
1492 if (pipe (new->status_msg_pipe) == -1)
1493 rc = gpg_error_from_errno (errno);
1495 if (!rc)
1497 fcntl (new->status_msg_pipe[0], F_SETFL, O_NONBLOCK);
1498 fcntl (new->status_msg_pipe[1], F_SETFL, O_NONBLOCK);
1499 pthread_mutex_init (&new->status_mutex, NULL);
1502 if (!rc)
1504 #ifdef WITH_GNUTLS
1505 new->remote = addr ? 1 : 0;
1506 #endif
1507 new->fd = fd;
1508 rc = create_thread (client_thread, new, &new->tid, 1);
1509 if (rc)
1511 close (new->status_msg_pipe[0]);
1512 close (new->status_msg_pipe[1]);
1513 pthread_mutex_destroy (&new->status_mutex);
1517 if (!rc)
1519 struct slist_s *list = slist_append (cn_thread_list, new);
1521 if (list)
1523 cn_thread_list = list;
1524 if (addr)
1526 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1527 (pthread_t *) new->tid, fd, addr);
1528 #ifdef WITH_GNUTLS
1529 new->peeraddr = str_dup (addr);
1530 #endif
1532 else
1533 log_write (_("new connection: tid=%p, fd=%i"),
1534 (pthread_t *) new->tid, fd);
1536 else
1537 rc = GPG_ERR_ENOMEM;
1540 pthread_cleanup_pop (1);
1542 if (rc)
1544 xfree (new);
1545 close (fd);
1546 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1547 pwmd_strerror (rc));
1549 return rc;
1552 static void*
1553 keepalive_thread (void *arg)
1555 #ifndef HAVE_PTHREAD_CANCEL
1556 int *n = xmalloc (sizeof (int));
1558 *n = 0;
1559 pthread_setspecific (signal_thread_key, n);
1560 INIT_THREAD_SIGNAL;
1561 #endif
1563 #ifdef HAVE_PR_SET_NAME
1564 prctl (PR_SET_NAME, "keepalive");
1565 #endif
1566 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1568 for (;;)
1570 int n = config_get_integer ("global", "keepalive_interval");
1571 struct timeval tv = { n, 0 };
1572 #ifndef HAVE_PTHREAD_CANCEL
1573 int *sigusr2;
1575 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1576 if (*sigusr2)
1577 break;
1578 #endif
1580 send_status_all (STATUS_KEEPALIVE, NULL);
1581 select (0, NULL, NULL, NULL, &tv);
1584 return NULL;
1587 #ifdef WITH_GNUTLS
1588 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1589 static void *
1590 get_in_addr (struct sockaddr *sa)
1592 if (sa->sa_family == AF_INET)
1593 return &(((struct sockaddr_in *) sa)->sin_addr);
1595 return &(((struct sockaddr_in6 *) sa)->sin6_addr);
1598 static void *
1599 tcp_accept_thread (void *arg)
1601 int sockfd = *(int *) arg;
1602 #ifndef HAVE_PTHREAD_CANCEL
1603 int *n = xmalloc (sizeof (int));
1605 *n = 0;
1606 pthread_setspecific (signal_thread_key, n);
1607 INIT_THREAD_SIGNAL;
1608 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1609 #endif
1611 #ifdef HAVE_PR_SET_NAME
1612 prctl (PR_SET_NAME, "tcp_accept");
1613 #endif
1614 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1616 for (;;)
1618 struct sockaddr_storage raddr;
1619 socklen_t slen = sizeof (raddr);
1620 int fd;
1621 unsigned long n;
1622 char s[INET6_ADDRSTRLEN];
1623 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1624 #ifndef HAVE_PTHREAD_CANCEL
1625 int *sigusr2;
1627 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1628 if (*sigusr2)
1629 break;
1630 #endif
1632 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1633 if (fd == -1)
1635 if (errno == EMFILE || errno == ENFILE)
1636 log_write ("accept(): %s",
1637 pwmd_strerror (gpg_error_from_errno (errno)));
1638 else if (errno != EAGAIN)
1640 if (!quit) // probably EBADF
1641 log_write ("accept(): %s", strerror (errno));
1643 break;
1646 #ifndef HAVE_PTHREAD_CANCEL
1647 select (0, NULL, NULL, NULL, &tv);
1648 #endif
1649 continue;
1652 if (quit)
1654 close (fd);
1655 break;
1658 inet_ntop (raddr.ss_family, get_in_addr ((struct sockaddr *) &raddr),
1659 s, sizeof s);
1660 (void) init_client (fd, s);
1661 n = config_get_integer ("global", "tcp_wait");
1662 if (n > 0)
1664 tv.tv_sec = (n * 100000) / 100000;
1665 tv.tv_usec = (n * 100000) % 100000;
1666 select (0, NULL, NULL, NULL, &tv);
1670 return NULL;
1673 static int
1674 start_stop_tls_with_protocol (int ipv6, int term)
1676 struct addrinfo hints, *servinfo, *p;
1677 int port = config_get_integer ("global", "tcp_port");
1678 char buf[7];
1679 int n;
1680 gpg_error_t rc;
1681 int *fd = ipv6 ? &tls6_fd : &tls_fd;
1683 if (term || config_get_boolean ("global", "enable_tcp") == 0)
1685 if (tls6_fd != -1)
1687 if (spawned_tls6)
1689 #ifdef HAVE_PTHREAD_CANCEL
1690 pthread_cancel (tls6_tid);
1691 #else
1692 pthread_kill (tls6_tid, SIGUSR2);
1693 #endif
1694 pthread_join (tls6_tid, NULL);
1697 shutdown (tls6_fd, SHUT_RDWR);
1698 close (tls6_fd);
1699 tls6_fd = -1;
1700 spawned_tls6 = 0;
1703 if (tls_fd != -1)
1705 if (spawned_tls)
1707 #ifdef HAVE_PTHREAD_CANCEL
1708 pthread_cancel (tls_tid);
1709 #else
1710 pthread_kill (tls_tid, SIGUSR2);
1711 #endif
1712 pthread_join (tls_tid, NULL);
1715 shutdown (tls_fd, SHUT_RDWR);
1716 close (tls_fd);
1717 tls_fd = -1;
1718 spawned_tls = 0;
1721 /* A client may still be connected. */
1722 if (!quit && x509_cred != NULL)
1723 tls_deinit_params ();
1725 return 1;
1728 if ((ipv6 && tls6_fd != -1) || (!ipv6 && tls_fd != -1))
1729 return 1;
1731 memset (&hints, 0, sizeof (hints));
1732 hints.ai_family = ipv6 ? AF_INET6 : AF_INET;
1733 hints.ai_socktype = SOCK_STREAM;
1734 hints.ai_flags = AI_PASSIVE;
1735 snprintf (buf, sizeof (buf), "%i", port);
1737 if ((n = getaddrinfo (NULL, buf, &hints, &servinfo)) == -1)
1739 log_write ("getaddrinfo(): %s", gai_strerror (n));
1740 return 0;
1743 for (n = 0, p = servinfo; p != NULL; p = p->ai_next)
1745 int r = 1;
1747 if ((ipv6 && p->ai_family != AF_INET6)
1748 || (!ipv6 && p->ai_family != AF_INET))
1749 continue;
1751 if ((*fd = socket (p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
1753 log_write ("socket(): %s", strerror (errno));
1754 continue;
1757 if (setsockopt (*fd, SOL_SOCKET, SO_REUSEADDR, &r, sizeof (int)) == -1)
1759 log_write ("setsockopt(): %s",
1760 pwmd_strerror (gpg_error_from_errno (errno)));
1761 freeaddrinfo (servinfo);
1762 goto fail;
1765 if (bind (*fd, p->ai_addr, p->ai_addrlen) == -1)
1767 close (*fd);
1768 log_write ("bind(): %s",
1769 pwmd_strerror (gpg_error_from_errno (errno)));
1770 continue;
1773 n++;
1774 break;
1777 freeaddrinfo (servinfo);
1779 if (!n)
1780 goto fail;
1782 #if HAVE_DECL_SO_BINDTODEVICE != 0
1783 char *tmp = config_get_string ("global", "tcp_interface");
1784 if (tmp && setsockopt (*fd, SOL_SOCKET, SO_BINDTODEVICE, tmp,
1785 strlen (tmp)) == -1)
1787 log_write ("setsockopt(): %s",
1788 pwmd_strerror (gpg_error_from_errno (errno)));
1789 xfree (tmp);
1790 goto fail;
1793 xfree (tmp);
1794 #endif
1796 if (x509_cred == NULL)
1798 rc = tls_init_params ();
1799 if (rc)
1800 goto fail;
1803 if (listen (*fd, 0) == -1)
1805 log_write ("listen(): %s", strerror (errno));
1806 goto fail;
1809 if (ipv6)
1810 rc = create_thread (tcp_accept_thread, fd, &tls6_tid, 0);
1811 else
1812 rc = create_thread (tcp_accept_thread, fd, &tls_tid, 0);
1814 if (rc)
1816 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1817 pwmd_strerror (rc));
1818 goto fail;
1821 if (ipv6)
1822 spawned_tls6 = 1;
1823 else
1824 spawned_tls = 1;
1826 return 1;
1828 fail:
1829 start_stop_tls_with_protocol (0, 1);
1830 if (tls_fd != -1)
1831 close (tls_fd);
1833 if (tls6_fd != -1)
1834 close (tls6_fd);
1836 tls_fd = -1;
1837 tls6_fd = -1;
1838 return 0;
1841 static int
1842 start_stop_tls (int term)
1844 char *s = config_get_string ("global", "tcp_bind");
1845 int b;
1847 if (!s)
1848 return 0;
1850 if (!strcmp (s, "any"))
1852 b = start_stop_tls_with_protocol (0, term);
1853 if (b)
1854 b = start_stop_tls_with_protocol (1, term);
1856 else if (!strcmp (s, "ipv4"))
1857 b = start_stop_tls_with_protocol (0, term);
1858 else if (!strcmp (s, "ipv6"))
1859 b = start_stop_tls_with_protocol (1, term);
1860 else
1861 b = 0;
1863 xfree (s);
1864 return b;
1866 #endif
1868 static void *
1869 accept_thread (void *arg)
1871 int sockfd = *(int *) arg;
1872 #ifndef HAVE_PTHREAD_CANCEL
1873 int *n = xmalloc (sizeof (int));
1875 *n = 0;
1876 pthread_setspecific (signal_thread_key, n);
1877 INIT_THREAD_SIGNAL;
1878 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1879 #endif
1881 #ifdef HAVE_PR_SET_NAME
1882 prctl (PR_SET_NAME, "accept");
1883 #endif
1884 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1886 for (;;)
1888 socklen_t slen = sizeof (struct sockaddr_un);
1889 struct sockaddr_un raddr;
1890 int fd;
1891 #ifndef HAVE_PTHREAD_CANCEL
1892 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1893 int *sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1895 if (*sigusr2)
1896 break;
1897 #endif
1899 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1900 if (fd == -1)
1902 if (errno == EMFILE || errno == ENFILE)
1903 log_write ("accept(): %s",
1904 pwmd_strerror (gpg_error_from_errno (errno)));
1905 else if (errno != EAGAIN)
1907 if (!quit) // probably EBADF
1908 log_write ("accept(): %s",
1909 pwmd_strerror (gpg_error_from_errno (errno)));
1911 break;
1914 #ifndef HAVE_PTHREAD_CANCEL
1915 select (0, NULL, NULL, NULL, &tv);
1916 #endif
1917 continue;
1920 (void) init_client (fd, NULL);
1923 /* Just in case accept() failed for some reason other than EBADF */
1924 quit = 1;
1925 return NULL;
1928 static void *
1929 cache_timer_thread (void *arg)
1931 #ifndef HAVE_PTHREAD_CANCEL
1932 int *n = xmalloc (sizeof (int));
1934 *n = 0;
1935 pthread_setspecific (signal_thread_key, n);
1936 INIT_THREAD_SIGNAL;
1937 #endif
1939 #ifdef HAVE_PR_SET_NAME
1940 prctl (PR_SET_NAME, "cache timer");
1941 #endif
1942 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1944 for (;;)
1946 struct timeval tv = { 1, 0 };
1947 #ifndef HAVE_PTHREAD_CANCEL
1948 int *n;
1950 n = (int *) pthread_getspecific (signal_thread_key);
1951 if (*n)
1952 break;
1953 #endif
1955 select (0, NULL, NULL, NULL, &tv);
1956 cache_adjust_timeout ();
1959 return NULL;
1962 static int
1963 signal_loop (sigset_t sigset)
1965 int done = 0;
1966 int siint = 0;
1970 int sig;
1972 sigwait (&sigset, &sig);
1974 if (sig != SIGQUIT)
1975 log_write (_("caught signal %i (%s)"), sig, strsignal (sig));
1977 switch (sig)
1979 case SIGHUP:
1980 pthread_cond_signal (&rcfile_cond);
1981 break;
1982 case SIGUSR1:
1983 log_write (_("clearing file cache"));
1984 cache_clear (NULL);
1985 send_status_all (STATUS_CACHE, NULL);
1986 break;
1987 case SIGQUIT:
1988 done = 1;
1989 break;
1990 default:
1991 siint = 1;
1992 done = 1;
1993 break;
1996 while (!done);
1998 return siint;
2001 static void
2002 catchsig (int sig)
2004 log_write (_ ("Caught signal %i (%s). Exiting."), sig, strsignal (sig));
2005 #ifdef HAVE_BACKTRACE
2006 BACKTRACE (__FUNCTION__);
2007 #endif
2008 longjmp (jmp, 1);
2011 static void *
2012 waiting_for_exit (void *arg)
2014 int last = 0;
2015 #ifndef HAVE_PTHREAD_CANCEL
2016 int *n = xmalloc (sizeof (int));
2018 *n = 0;
2019 pthread_setspecific (signal_thread_key, n);
2020 INIT_THREAD_SIGNAL;
2021 #endif
2023 #ifdef HAVE_PR_SET_NAME
2024 prctl (PR_SET_NAME, "exiting");
2025 #endif
2026 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
2027 log_write (_("waiting for all clients to disconnect"));
2028 MUTEX_LOCK (&quit_mutex);
2029 pthread_cleanup_push (cleanup_mutex_cb, &quit_mutex);
2031 for (;;)
2033 struct timespec ts;
2034 int n;
2036 MUTEX_LOCK (&cn_mutex);
2037 n = slist_length (cn_thread_list);
2038 MUTEX_UNLOCK (&cn_mutex);
2039 if (!n)
2040 break;
2042 #ifndef HAVE_PTHREAD_CANCEL
2043 int *s = (int *) pthread_getspecific (signal_thread_key);
2044 if (*s)
2045 break;
2046 #endif
2048 if (last != n)
2050 log_write (_("%i clients remain"), n);
2051 last = n;
2054 INIT_TIMESPEC (SIG_TIMEOUT, ts);
2055 pthread_cond_timedwait (&quit_cond, &quit_mutex, &ts);
2058 kill (getpid (), SIGQUIT);
2059 pthread_cleanup_pop (1);
2060 return NULL;
2063 static int
2064 server_loop (int sockfd, char **socketpath)
2066 pthread_t accept_tid;
2067 pthread_t cache_timeout_tid;
2068 int cancel_timeout_thread = 0, cancel_accept_thread = 0;
2069 int cancel_keepalive_thread = 0;
2070 sigset_t sigset;
2071 int n;
2072 int segv = 0;
2073 gpg_error_t rc;
2075 init_commands ();
2076 sigemptyset (&sigset);
2078 /* Termination */
2079 sigaddset (&sigset, SIGTERM);
2080 sigaddset (&sigset, SIGINT);
2082 /* Clears the file cache. */
2083 sigaddset (&sigset, SIGUSR1);
2085 /* Configuration file reloading. */
2086 sigaddset (&sigset, SIGHUP);
2088 /* For exiting cleanly. */
2089 sigaddset (&sigset, SIGQUIT);
2091 #ifndef HAVE_PTHREAD_CANCEL
2093 The socket, cache and rcfile threads use this signal when
2094 pthread_cancel() is unavailable. Prevent the main thread from
2095 catching this signal from another process.
2097 sigaddset (&sigset, SIGUSR2);
2098 #endif
2100 /* When mem.c cannot find a pointer in the list (double free). */
2101 signal (SIGABRT, catchsig);
2102 sigaddset (&sigset, SIGABRT);
2103 sigprocmask (SIG_BLOCK, &sigset, NULL);
2105 #ifndef HAVE_PTHREAD_CANCEL
2106 /* Remove this signal from the watched signals in signal_loop(). */
2107 sigdelset (&sigset, SIGUSR2);
2108 #endif
2110 /* Ignored everywhere. When a client disconnects abnormally this signal
2111 * gets raised. It isn't needed though because client_thread() will check
2112 * for rcs even after the client disconnects. */
2113 signal (SIGPIPE, SIG_IGN);
2115 /* Can show a backtrace of the stack in the log. */
2116 signal (SIGSEGV, catchsig);
2118 #ifdef WITH_GNUTLS
2119 /* Needs to be done after the fork(). */
2120 if (!start_stop_tls (0))
2122 segv = 1;
2123 goto done;
2125 #endif
2127 pthread_mutex_init (&quit_mutex, NULL);
2128 pthread_cond_init (&quit_cond, NULL);
2129 char *p = get_username (getuid());
2130 log_write (_("%s started for user %s"), PACKAGE_STRING, p);
2131 xfree (p);
2133 #ifdef WITH_GNUTLS
2134 if (config_get_boolean ("global", "enable_tcp"))
2135 log_write (_("Listening on %s and TCP port %i as user %i"), *socketpath,
2136 config_get_integer ("global", "tcp_port"), invoking_uid);
2137 else
2138 log_write (_("Listening on %s"), *socketpath);
2139 #else
2140 log_write (_("Listening on %s"), *socketpath);
2141 #endif
2143 rc = create_thread (keepalive_thread, NULL, &keepalive_tid, 0);
2144 if (rc)
2146 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2147 pwmd_strerror (rc));
2148 goto done;
2151 cancel_keepalive_thread = 1;
2152 rc = create_thread (reload_rcfile_thread, NULL, &rcfile_tid, 0);
2153 if (rc)
2155 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2156 pwmd_strerror (rc));
2157 goto done;
2160 rc = create_thread (cache_timer_thread, NULL, &cache_timeout_tid, 0);
2161 if (rc)
2163 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2164 pwmd_strerror (rc));
2165 goto done;
2168 cancel_timeout_thread = 1;
2169 rc = create_thread (accept_thread, &sockfd, &accept_tid, 0);
2170 if (rc)
2172 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2173 pwmd_strerror (rc));
2174 goto done;
2177 cancel_accept_thread = 1;
2178 if (!setjmp (jmp))
2179 signal_loop (sigset);
2180 else
2181 segv = 1;
2183 done:
2185 * We're out of the main server loop. This happens when a signal was sent
2186 * to terminate the daemon. We'll wait for all clients to disconnect
2187 * before exiting but exit immediately if another termination signal is
2188 * sent.
2190 if (cancel_accept_thread)
2192 #ifdef HAVE_PTHREAD_CANCEL
2193 int n = pthread_cancel (accept_tid);
2194 #else
2195 int n = pthread_kill (accept_tid, SIGUSR2);
2196 #endif
2197 if (!n)
2198 pthread_join (accept_tid, NULL);
2201 #ifdef WITH_GNUTLS
2202 start_stop_tls (1);
2203 #endif
2204 shutdown (sockfd, SHUT_RDWR);
2205 close (sockfd);
2206 unlink (*socketpath);
2207 xfree (*socketpath);
2208 *socketpath = NULL;
2209 MUTEX_LOCK (&cn_mutex);
2210 n = slist_length (cn_thread_list);
2211 MUTEX_UNLOCK (&cn_mutex);
2213 if (n && !segv)
2215 pthread_t tid;
2217 rc = create_thread (waiting_for_exit, NULL, &tid, 0);
2218 if (!rc)
2220 if (signal_loop (sigset))
2222 log_write (_("Received second termination request. Exiting."));
2223 #ifdef HAVE_PTHREAD_CANCEL
2224 pthread_cancel (tid);
2225 #else
2226 pthread_kill (tid, SIGUSR2);
2227 #endif
2228 pthread_join (tid, NULL);
2231 else
2232 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2233 pwmd_strerror (rc));
2236 if (cancel_timeout_thread)
2238 #ifdef HAVE_PTHREAD_CANCEL
2239 pthread_cancel (cache_timeout_tid);
2240 #else
2241 pthread_kill (cache_timeout_tid, SIGUSR2);
2242 #endif
2243 pthread_join (cache_timeout_tid, NULL);
2246 if (cancel_keepalive_thread)
2248 #ifdef HAVE_PTHREAD_CANCEL
2249 pthread_cancel (keepalive_tid);
2250 #else
2251 pthread_kill (keepalive_tid, SIGUSR2);
2252 #endif
2253 pthread_join (keepalive_tid, NULL);
2256 cleanup_all_clients (0);
2257 #ifdef WITH_GNUTLS
2258 start_stop_tls (1);
2259 #endif
2260 deinit_commands ();
2261 pthread_cond_destroy (&quit_cond);
2262 pthread_mutex_destroy (&quit_mutex);
2263 return segv ? EXIT_FAILURE : EXIT_SUCCESS;;
2266 static void
2267 startup_failure ()
2269 log_write (_
2270 ("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
2271 cache_clear (NULL);
2274 /* This is called from cache.c:clear_once(). See
2275 * command.c:clearcache_command() for details about lock checking.
2277 static gpg_error_t
2278 free_cache_data (file_cache_t * cache)
2280 gpg_error_t rc = GPG_ERR_NO_DATA;
2281 int i, t;
2282 struct client_thread_s *found = NULL;
2283 int self = 0;
2285 if (!cache->data)
2286 return 0;
2288 cache_lock ();
2289 MUTEX_LOCK (&cn_mutex);
2290 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
2291 t = slist_length (cn_thread_list);
2293 for (i = 0; i < t; i++)
2295 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2297 if (!thd->cl)
2298 continue;
2300 if (!memcmp (thd->cl->md5file, cache->filename,
2301 sizeof (cache->filename)))
2303 if (pthread_equal (pthread_self (), thd->tid))
2305 found = thd;
2306 self = 1;
2307 continue;
2310 /* Continue trying to find a client who has the same file open and
2311 * also has a lock. */
2312 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0, -1);
2313 if (!rc)
2315 self = 0;
2316 found = thd;
2317 break;
2322 if (self && (!rc || rc == GPG_ERR_NO_DATA))
2323 rc = cache_lock_mutex (found->cl->ctx, found->cl->md5file, -1, 0, -1);
2325 if (exiting || !rc || rc == GPG_ERR_NO_DATA)
2327 free_cache_data_once (cache->data);
2328 cache->data = NULL;
2329 cache->defer_clear = 0;
2330 cache->timeout = -1;
2332 if (found)
2333 cache_unlock_mutex (found->cl->md5file, 0);
2335 rc = 0;
2338 if (rc)
2339 cache->defer_clear = 1;
2341 pthread_cleanup_pop (1);
2342 cache_unlock ();
2343 return rc;
2346 static int
2347 convert_v2_datafile (const char *filename, const char *cipher,
2348 const char *keyfile, const char *keygrip,
2349 const char *sign_keygrip, int nopass,
2350 const char *outfile, const char *keyparam,
2351 unsigned long s2k_count, uint64_t iterations)
2353 gpg_error_t rc;
2354 void *data = NULL;
2355 size_t datalen;
2356 struct crypto_s *crypto = NULL;
2357 uint16_t ver;
2358 int algo;
2359 void *key = NULL;
2360 size_t keylen = 0;
2362 if (outfile[0] == '-' && outfile[1] == 0)
2363 outfile = NULL;
2365 log_write (_("Converting version 2 data file \"%s\" ..."), filename);
2366 if (access (filename, R_OK) == -1)
2368 log_write ("%s: %s", filename,
2369 pwmd_strerror (gpg_error_from_errno (errno)));
2370 return 0;
2373 if (keyfile)
2375 log_write (_("Using passphrase file \"%s\" for decryption ..."),
2376 keyfile);
2377 if (access (keyfile, R_OK) == -1)
2379 log_write ("%s: %s", keyfile,
2380 pwmd_strerror (gpg_error_from_errno (errno)));
2381 return 0;
2385 rc = read_v2_datafile (filename, keyfile, &data, &datalen, &ver, &algo);
2386 if (rc)
2388 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2389 return 0;
2392 if (cipher)
2394 algo = cipher_string_to_gcrypt (cipher);
2395 if (algo == -1)
2397 rc = GPG_ERR_CIPHER_ALGO;
2398 goto fail;
2402 if (ver < 0x212)
2404 xmlDocPtr doc;
2406 rc = parse_doc (data, datalen, &doc);
2407 if (rc)
2408 goto fail;
2410 rc = convert_pre_212_elements (doc);
2411 gcry_free (data);
2412 data = NULL;
2413 if (!rc)
2415 xmlDocDumpFormatMemory (doc, (xmlChar **) & data, (int *) &datalen,
2417 if (!data)
2418 rc = GPG_ERR_ENOMEM;
2421 xmlFreeDoc (doc);
2422 if (rc)
2423 goto fail;
2426 rc = init_client_crypto (&crypto);
2427 if (!rc)
2429 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
2430 crypto->save.hdr.flags = set_cipher_flag (crypto->save.hdr.flags, algo);
2431 crypto->save.s2k_count = s2k_count;
2432 crypto->save.hdr.iterations = iterations;
2434 if (!use_agent)
2436 rc = export_common (NULL, 0, crypto, data, datalen, outfile, keyfile,
2437 &key, &keylen, 0, 0, nopass);
2439 #ifdef WITH_AGENT
2440 else
2442 rc = agent_set_pinentry_options (crypto->agent);
2443 if (!rc)
2444 rc = agent_export_common (crypto, keygrip, sign_keygrip, nopass,
2445 data, datalen, outfile, keyparam,
2446 no_passphrase_file ? NULL : keyfile);
2448 #endif
2449 if (!rc)
2450 log_write (_("Output written to \"%s\"."), outfile);
2453 fail:
2454 if (ver < 0x212)
2455 xmlFree (data);
2456 else
2457 gcry_free (data);
2459 gcry_free (key);
2460 cleanup_crypto (&crypto);
2462 if (rc)
2463 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2464 return rc ? 0 : 1;
2467 static void
2468 usage (const char *pn, int status)
2470 FILE *fp = status == EXIT_FAILURE ? stderr : stdout;
2472 fprintf (fp, _("Usage: %s [OPTIONS] [file1] [...]\n"
2473 " -f, --rcfile=filename load the specfied configuration file\n"
2474 " (~/.pwmd/config)\n"
2475 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2476 " --kill terminate an existing instance of pwmd\n"
2477 #ifdef WITH_AGENT
2478 " --use-agent enable use of gpg-agent\n"
2479 #endif
2480 " -n, --no-fork run as a foreground process\n"
2481 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2482 " --ignore, --force ignore file errors during startup\n"
2483 " --debug-level=keywords log protocol output (see manual for details)\n"
2484 " -o, --outfile=filename output file when importing or converting\n"
2485 " -C, --convert=filename convert a version 2 data file to version 3\n"
2486 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2487 " -k, --passphrase-file=file for use when importing or converting\n"
2488 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2489 " converting\n"
2490 " --no-passphrase when importing or converting\n"
2491 " --keygrip=hex public key to use when encrypting\n"
2492 " --sign-keygrip=hex private key to use when signing\n"
2493 " --keyparam=s-exp custom key parameters to use (RSA-2048)\n"
2494 " --cipher=string encryption cipher (aes256)\n"
2495 " --cipher-iterations=N cipher iteration count (N+1)\n"
2496 " --s2k-count=N hash iteration count (>65536, calibrated)\n"
2497 " --help this help text\n"
2498 " --version show version and compile time features\n"),
2499 pn);
2500 exit (status);
2503 static void
2504 unlink_stale_socket (const char *sock, const char *pidfile)
2506 log_write (_ ("removing stale socket %s"), sock);
2507 unlink (sock);
2508 unlink (pidfile);
2511 static int
2512 test_pidfile (const char *path, const char *sock, char *buf, size_t buflen,
2513 char **pidfile, int create, mode_t mode, int terminate)
2515 pid_t pid;
2516 int fd;
2517 size_t len;
2519 if (!create)
2521 snprintf (buf, buflen, "%s/%s.pid", homedir, sock);
2522 *pidfile = str_dup (buf);
2523 fd = open (buf, O_RDONLY);
2525 else
2526 fd = open (*pidfile, O_CREAT|O_WRONLY|O_TRUNC, mode);
2528 if (fd == -1)
2530 if (!create && errno != ENOENT)
2532 log_write ("%s: %s", buf, pwmd_strerror (errno));
2533 free (*pidfile);
2534 *pidfile = NULL;
2535 return -1;
2537 else if (!create && !terminate)
2538 return 0;
2540 log_write ("%s: %s", *pidfile, strerror (errno));
2541 return -1;
2544 if (create)
2546 snprintf (buf, buflen, "%i", getpid ());
2547 write (fd, buf, strlen (buf));
2548 close (fd);
2549 return 0;
2552 len = read (fd, buf, buflen);
2553 close (fd);
2554 if (len == 0)
2556 unlink_stale_socket (path, *pidfile);
2557 return 0;
2560 if (sscanf (buf, "%5i", &pid) != 1 || pid == 0)
2562 if (!terminate)
2564 unlink_stale_socket (path, *pidfile);
2565 return 0;
2569 if (kill (pid, 0) == -1)
2571 unlink_stale_socket (path, *pidfile);
2572 return 0;
2575 if (terminate)
2577 if (kill (pid, SIGTERM) == -1)
2578 log_write ("%s: %s", path, pwmd_strerror (errno));
2580 else
2581 log_write (_ ("an instance for socket %s is already running"), path);
2583 xfree (*pidfile);
2584 *pidfile = NULL;
2585 return 1;
2589 main (int argc, char *argv[])
2591 int opt;
2592 struct sockaddr_un addr;
2593 char buf[PATH_MAX];
2594 char *socketpath = NULL, *socketdir, *socketname = NULL;
2595 char *socketarg = NULL;
2596 char *datadir = NULL;
2597 char *pidfile = NULL;
2598 mode_t mode = 0600;
2599 int x;
2600 char *p;
2601 char **cache_push = NULL;
2602 char *import = NULL, *keygrip = NULL, *sign_keygrip = NULL;
2603 char *keyparam = NULL;
2604 int estatus = EXIT_FAILURE;
2605 int sockfd;
2606 char *outfile = NULL;
2607 int do_unlink = 0;
2608 int secure = 0;
2609 int show_version = 0;
2610 int force = 0;
2611 int no_passphrase = 0;
2612 gpg_error_t rc;
2613 char *convertfile = NULL;
2614 char *cipher = NULL;
2615 char *keyfile = NULL;
2616 unsigned long s2k_count = 0;
2617 uint64_t iterations = 0;
2618 int exists;
2619 char *debug_level_opt = NULL;
2620 int optindex;
2621 int terminate = 0;
2622 /* Must maintain the same order as longopts[] */
2623 enum
2625 OPT_VERSION, OPT_HELP,
2626 #ifdef WITH_AGENT
2627 OPT_AGENT,
2628 #endif
2629 OPT_DEBUG_LEVEL, OPT_HOMEDIR, OPT_NO_FORK, OPT_DISABLE_DUMP,
2630 OPT_IGNORE, OPT_FORCE, OPT_RCFILE, OPT_CONVERT,
2631 OPT_PASSPHRASE_FILE, OPT_IMPORT, OPT_OUTFILE,
2632 OPT_NO_PASSPHRASE_FILE, OPT_KEYGRIP, OPT_SIGN_KEYGRIP,
2633 OPT_KEYPARAM, OPT_CIPHER, OPT_ITERATIONS, OPT_S2K_COUNT,
2634 OPT_NO_PASSPHRASE, OPT_KILL
2636 const char *optstring = "nf:C:k:I:o:";
2637 const struct option longopts[] = {
2638 {"version", no_argument, 0, 0},
2639 {"help", no_argument, 0, 0},
2640 #ifdef WITH_AGENT
2641 {"use-agent", no_argument, 0, 0},
2642 #endif
2643 {"debug-level", required_argument, 0, 0},
2644 {"homedir", required_argument, 0, 0},
2645 {"no-fork", no_argument, 0, 'n'},
2646 {"disable_dump", no_argument, 0, 0},
2647 {"ignore", no_argument, 0, 0},
2648 {"force", no_argument, 0, 0},
2649 {"rcfile", required_argument, 0, 'f'},
2650 {"convert", required_argument, 0, 'C'},
2651 {"passphrase-file", required_argument, 0, 'k'},
2652 {"import", required_argument, 0, 'I'},
2653 {"outfile", required_argument, 0, 'o'},
2654 {"no-passphrase-file", no_argument, 0, 0},
2655 {"keygrip", required_argument, 0, 0},
2656 {"sign-keygrip", required_argument, 0, 0},
2657 {"keyparam", required_argument, 0, 0},
2658 {"cipher", required_argument, 0, 0},
2659 {"cipher-iterations", required_argument, 0, 0},
2660 {"s2k-count", required_argument, 0, 0},
2661 {"no-passphrase", no_argument, 0, 0},
2662 {"kill", no_argument, 0, 0},
2663 {0, 0, 0, 0}
2666 log_fd = -1;
2668 #ifndef DEBUG
2669 #ifdef HAVE_SETRLIMIT
2670 struct rlimit rl;
2672 rl.rlim_cur = rl.rlim_max = 0;
2674 if (setrlimit (RLIMIT_CORE, &rl) != 0)
2675 err (EXIT_FAILURE, "setrlimit()");
2676 #endif
2678 #ifdef HAVE_PR_SET_DUMPABLE
2679 prctl (PR_SET_DUMPABLE, 0);
2680 #endif
2681 #endif
2683 #ifdef ENABLE_NLS
2684 setlocale (LC_ALL, "");
2685 bindtextdomain ("pwmd", LOCALEDIR);
2686 textdomain ("pwmd");
2687 #endif
2689 #ifndef MEM_DEBUG
2690 xmem_init ();
2691 #endif
2692 gpg_err_init ();
2694 if (setup_crypto ())
2695 exit (EXIT_FAILURE);
2697 #ifdef WITH_GNUTLS
2698 gnutls_global_set_mem_functions (xmalloc, xmalloc, secure_mem_check,
2699 xrealloc, xfree);
2700 gnutls_global_init ();
2701 gnutls_global_set_log_function (tls_log);
2702 gnutls_global_set_log_level (1);
2703 tls_fd = -1;
2704 tls6_fd = -1;
2705 #endif
2706 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
2707 xmlInitMemory ();
2708 xmlInitGlobals ();
2709 xmlInitParser ();
2710 xmlXPathInit ();
2711 cmdline = 1;
2712 use_agent = 0;
2714 while ((opt = getopt_long (argc, argv, optstring, longopts, &optindex))
2715 != -1)
2717 switch (opt)
2719 case 'I':
2720 import = optarg;
2721 break;
2722 case 'C':
2723 convertfile = optarg;
2724 break;
2725 case 'k':
2726 keyfile = optarg;
2727 break;
2728 case 'o':
2729 outfile = optarg;
2730 break;
2731 case 'D':
2732 secure = 1;
2733 break;
2734 case 'n':
2735 nofork = 1;
2736 break;
2737 case 'f':
2738 rcfile = str_dup (optarg);
2739 break;
2740 default:
2741 usage (argv[0], EXIT_FAILURE);
2742 break;
2743 case 0:
2744 switch (optindex)
2746 case OPT_VERSION:
2747 show_version = 1;
2748 break;
2749 case OPT_HELP:
2750 usage (argv[0], 0);
2751 break;
2752 #ifdef WITH_AGENT
2753 case OPT_AGENT:
2754 use_agent = 1;
2755 break;
2756 #endif
2757 case OPT_DEBUG_LEVEL:
2758 debug_level_opt = optarg;
2759 break;
2760 case OPT_HOMEDIR:
2761 homedir = str_dup (optarg);
2762 break;
2763 case OPT_NO_FORK:
2764 nofork = 1;
2765 break;
2766 case OPT_DISABLE_DUMP:
2767 secure = 1;
2768 break;
2769 case OPT_IGNORE:
2770 case OPT_FORCE:
2771 force = 1;
2772 break;
2773 case OPT_RCFILE:
2774 rcfile = str_dup (optarg);
2775 break;
2776 case OPT_CONVERT:
2777 convertfile = optarg;
2778 break;
2779 case OPT_PASSPHRASE_FILE:
2780 keyfile = optarg;
2781 break;
2782 case OPT_IMPORT:
2783 import = optarg;
2784 break;
2785 case OPT_OUTFILE:
2786 outfile = optarg;
2787 break;
2788 case OPT_NO_PASSPHRASE_FILE:
2789 no_passphrase_file = 1;
2790 break;
2791 case OPT_KEYGRIP:
2792 keygrip = optarg;
2793 break;
2794 case OPT_SIGN_KEYGRIP:
2795 sign_keygrip = optarg;
2796 break;
2797 case OPT_KEYPARAM:
2798 keyparam = optarg;
2799 break;
2800 case OPT_CIPHER:
2801 cipher = optarg;
2802 break;
2803 case OPT_ITERATIONS:
2804 iterations = strtoull (optarg, NULL, 10);
2805 break;
2806 case OPT_S2K_COUNT:
2807 s2k_count = strtoul (optarg, NULL, 10);
2808 break;
2809 case OPT_NO_PASSPHRASE:
2810 no_passphrase = 1;
2811 break;
2812 case OPT_KILL:
2813 terminate = 1;
2814 break;
2815 default:
2816 usage (argv[0], 1);
2821 if (show_version)
2823 printf (_("%s\n\n"
2824 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015\n"
2825 "%s\n"
2826 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2827 "Compile time features:\n%s"), PACKAGE_STRING,
2828 PACKAGE_BUGREPORT,
2829 #ifdef PWMD_HOMEDIR
2830 "+PWMD_HOMEDIR=" PWMD_HOMEDIR "\n"
2831 #endif
2832 #ifdef WITH_AGENT
2833 "+WITH_AGENT\n"
2834 #else
2835 "-WITH_AGENT\n"
2836 #endif
2837 #ifdef WITH_QUALITY
2838 "+WITH_QUALITY\n"
2839 #else
2840 "-WITH_QUALITY\n"
2841 #endif
2842 #ifdef WITH_GNUTLS
2843 "+WITH_GNUTLS\n"
2844 #else
2845 "-WITH_GNUTLS\n"
2846 #endif
2847 #ifdef DEBUG
2848 "+DEBUG\n"
2849 #else
2850 "-DEBUG\n"
2851 #endif
2852 #ifdef MEM_DEBUG
2853 "+MEM_DEBUG\n"
2854 #else
2855 "-MEM_DEBUG\n"
2856 #endif
2857 #ifdef MUTEX_DEBUG
2858 "+MUTEX_DEBUG\n"
2859 #else
2860 "-MUTEX_DEBUG\n"
2861 #endif
2863 exit (EXIT_SUCCESS);
2866 if (!homedir)
2867 #ifdef PWMD_HOMEDIR
2868 homedir = str_dup(PWMD_HOMEDIR);
2869 #else
2870 homedir = str_asprintf ("%s/.pwmd", get_home_dir());
2871 #endif
2873 if (mkdir (homedir, 0700) == -1 && errno != EEXIST)
2874 err (EXIT_FAILURE, "%s", homedir);
2876 snprintf (buf, sizeof (buf), "%s/data", homedir);
2877 if (mkdir (buf, 0700) == -1 && errno != EEXIST)
2878 err (EXIT_FAILURE, "%s", buf);
2880 datadir = str_dup (buf);
2881 pthread_mutexattr_t attr;
2882 pthread_mutexattr_init (&attr);
2883 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
2884 pthread_mutex_init (&rcfile_mutex, &attr);
2885 pthread_cond_init (&rcfile_cond, NULL);
2886 pthread_mutex_init (&cn_mutex, &attr);
2887 pthread_mutexattr_destroy (&attr);
2888 pthread_key_create (&last_error_key, free_key);
2889 #ifndef HAVE_PTHREAD_CANCEL
2890 pthread_key_create (&signal_thread_key, free_key);
2891 #endif
2893 if (!rcfile)
2894 rcfile = str_asprintf ("%s/config", homedir);
2896 global_config = config_parse (rcfile);
2897 if (!global_config)
2898 exit (EXIT_FAILURE);
2900 #ifdef WITH_AGENT
2901 if (!use_agent)
2902 use_agent = config_get_boolean ("global", "use_agent");
2903 #endif
2905 setup_logging ();
2907 if (debug_level_opt)
2908 debug_level = str_split (debug_level_opt, ",", 0);
2910 x = config_get_int_param (global_config, "global", "priority", &exists);
2911 if (exists && x != atoi(INVALID_PRIORITY))
2913 errno = 0;
2914 if (setpriority (PRIO_PROCESS, 0, x) == -1)
2916 log_write ("setpriority(): %s",
2917 pwmd_strerror (gpg_error_from_errno (errno)));
2918 goto do_exit;
2921 #ifdef HAVE_MLOCKALL
2922 if (disable_mlock == 0 && mlockall (MCL_CURRENT | MCL_FUTURE) == -1)
2924 log_write ("mlockall(): %s",
2925 pwmd_strerror (gpg_error_from_errno (errno)));
2926 goto do_exit;
2928 #endif
2930 rc = cache_init (free_cache_data);
2931 if (rc)
2933 log_write ("pwmd: ERR %i: %s", rc,
2934 gpg_err_code (rc) == GPG_ERR_UNKNOWN_VERSION
2935 ? _("incompatible gpg-agent version: 2.1.0 or later required")
2936 : pwmd_strerror (rc));
2937 goto do_exit;
2940 if (s2k_count == 0)
2941 s2k_count = config_get_ulong (NULL, "s2k_count");
2943 if (convertfile)
2945 if (!outfile || !*outfile || argc != optind)
2946 usage (argv[0], EXIT_FAILURE);
2948 estatus = convert_v2_datafile (convertfile, cipher, keyfile, keygrip,
2949 sign_keygrip, no_passphrase, outfile,
2950 keyparam, s2k_count, iterations);
2951 config_free (global_config);
2952 xfree (rcfile);
2953 exit (!estatus);
2956 if (import)
2958 if (!outfile || !*outfile || argc != optind)
2959 usage (argv[0], EXIT_FAILURE);
2961 if (outfile && outfile[0] == '-' && outfile[1] == 0)
2962 outfile = NULL;
2964 estatus = xml_import (import, outfile, keygrip, sign_keygrip, keyfile,
2965 no_passphrase, cipher, keyparam, s2k_count,
2966 iterations);
2967 config_free (global_config);
2968 xfree (rcfile);
2969 exit (!estatus);
2972 p = config_get_string ("global", "socket_path");
2973 if (!p)
2974 p = str_asprintf ("%s/socket", homedir);
2976 socketarg = expand_homedir (p);
2977 xfree (p);
2979 if (!secure)
2980 disable_list_and_dump = config_get_boolean ("global",
2981 "disable_list_and_dump");
2982 else
2983 disable_list_and_dump = secure;
2985 cache_push = config_get_list ("global", "cache_push");
2987 while (optind < argc)
2989 if (strv_printf (&cache_push, "%s", argv[optind++]) == 0)
2990 errx (EXIT_FAILURE, "%s", pwmd_strerror (GPG_ERR_ENOMEM));
2993 if (strchr (socketarg, '/') == NULL)
2995 socketdir = getcwd (buf, sizeof (buf));
2996 socketname = str_dup (socketarg);
2997 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2999 else
3001 socketname = str_dup (strrchr (socketarg, '/'));
3002 socketname++;
3003 socketarg[strlen (socketarg) - strlen (socketname) - 1] = 0;
3004 socketdir = str_dup (socketarg);
3005 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
3008 if (chdir (datadir))
3010 log_write ("%s: %s", datadir,
3011 pwmd_strerror (gpg_error_from_errno (errno)));
3012 unlink (socketpath);
3013 goto do_exit;
3016 x = test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 0,
3017 mode, terminate);
3018 if (!terminate && x)
3019 goto do_exit;
3020 else if (terminate)
3022 estatus = x != 1 ? EXIT_FAILURE : EXIT_SUCCESS;
3023 goto do_exit;
3027 * bind() doesn't like the full pathname of the socket or any non alphanum
3028 * characters so change to the directory where the socket is wanted then
3029 * create it then change to datadir.
3031 if (chdir (socketdir))
3033 log_write ("%s: %s", socketdir,
3034 pwmd_strerror (gpg_error_from_errno (errno)));
3035 goto do_exit;
3038 xfree (socketdir);
3040 if ((sockfd = socket (PF_UNIX, SOCK_STREAM, 0)) == -1)
3042 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
3043 goto do_exit;
3046 addr.sun_family = AF_UNIX;
3047 snprintf (addr.sun_path, sizeof (addr.sun_path), "%s", socketname);
3048 do_unlink = 1;
3049 if (bind (sockfd, (struct sockaddr *) &addr, sizeof (struct sockaddr)) ==
3052 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
3054 if (errno == EADDRINUSE)
3056 do_unlink = 0;
3057 log_write (_("Either there is another pwmd running or '%s' is a \n"
3058 "stale socket. Please remove it manually."), socketpath);
3061 goto do_exit;
3065 char *t = config_get_string ("global", "socket_perms");
3066 mode_t mask;
3068 if (t)
3070 mode = strtol (t, NULL, 8);
3071 mask = umask (0);
3072 xfree (t);
3074 if (chmod (socketname, mode) == -1)
3076 log_write ("%s: %s", socketname,
3077 pwmd_strerror (gpg_error_from_errno (errno)));
3078 close (sockfd);
3079 umask (mask);
3080 goto do_exit;
3083 umask (mask);
3087 xfree (--socketname);
3089 if (chdir (datadir))
3091 log_write ("%s: %s", datadir,
3092 pwmd_strerror (gpg_error_from_errno (errno)));
3093 close (sockfd);
3094 goto do_exit;
3097 xfree (datadir);
3100 * Set the cache entry for a file. Prompts for the password.
3102 if (cache_push)
3104 struct crypto_s *crypto = NULL;
3105 gpg_error_t rc = init_client_crypto (&crypto);
3107 if (rc)
3109 estatus = EXIT_FAILURE;
3110 goto do_exit;
3113 #ifdef WITH_AGENT
3114 if (use_agent)
3116 rc = agent_set_pinentry_options (crypto->agent);
3117 if (rc)
3119 estatus = EXIT_FAILURE;
3120 goto do_exit;
3123 #endif
3125 for (opt = 0; cache_push[opt]; opt++)
3127 if (!do_cache_push (cache_push[opt], crypto) && !force)
3129 strv_free (cache_push);
3130 startup_failure ();
3131 estatus = EXIT_FAILURE;
3132 cleanup_crypto (&crypto);
3133 goto do_exit;
3136 cleanup_crypto_stage1 (crypto);
3139 #ifdef WITH_AGENT
3140 if (use_agent)
3141 (void) kill_scd (crypto->agent);
3142 #endif
3144 cleanup_crypto (&crypto);
3145 strv_free (cache_push);
3146 log_write (!nofork ? _("Done. Daemonizing...") :
3147 _("Done. Waiting for connections..."));
3150 config_clear_keys ();
3152 if (listen (sockfd, 0) == -1)
3154 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
3155 goto do_exit;
3158 if (!nofork)
3160 switch (fork ())
3162 case -1:
3163 log_write ("fork(): %s",
3164 pwmd_strerror (gpg_error_from_errno (errno)));
3165 goto do_exit;
3166 case 0:
3167 close (0);
3168 close (1);
3169 close (2);
3170 setsid ();
3171 break;
3172 default:
3173 _exit (EXIT_SUCCESS);
3177 (void)test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 1,
3178 mode, 0);
3179 cmdline = 0;
3180 pthread_key_create (&thread_name_key, free_key);
3181 pthread_setspecific (thread_name_key, str_dup ("main"));
3182 estatus = server_loop (sockfd, &socketpath);
3184 do_exit:
3185 if (socketpath && do_unlink)
3187 unlink (socketpath);
3188 xfree (socketpath);
3191 xfree (socketarg);
3192 #ifdef WITH_GNUTLS
3193 gnutls_global_deinit ();
3194 xfree (invoking_tls);
3195 #endif
3196 if (rcfile_tid)
3198 #ifdef HAVE_PTHREAD_CANCEL
3199 pthread_cancel (rcfile_tid);
3200 #else
3201 pthread_kill (rcfile_tid, SIGUSR2);
3202 pthread_cond_signal (&rcfile_cond);
3203 #endif
3204 pthread_join (rcfile_tid, NULL);
3207 pthread_cond_destroy (&rcfile_cond);
3208 pthread_mutex_destroy (&rcfile_mutex);
3209 pthread_key_delete (last_error_key);
3210 #ifndef HAVE_PTHREAD_CANCEL
3211 pthread_key_delete (signal_thread_key);
3212 #endif
3214 if (global_config)
3215 config_free (global_config);
3217 xfree (rcfile);
3218 xfree (home_directory);
3219 xfree (homedir);
3220 xmlCleanupParser ();
3221 xmlCleanupGlobals ();
3223 if (pidfile)
3224 unlink (pidfile);
3225 xfree (pidfile);
3227 if (estatus == EXIT_SUCCESS && !terminate)
3228 log_write (_("pwmd exiting normally"));
3230 pthread_key_delete (thread_name_key);
3231 closelog ();
3232 #if defined(DEBUG) && !defined(MEM_DEBUG)
3233 xdump ();
3234 #endif
3236 if (log_fd != -1)
3237 close (log_fd);
3239 exit (estatus);