Set the TLS audit log callback.
[pwmd.git] / src / pwmd.c
blob68188993889fc48664f5dab8d4aac44ac27c5f12
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 = NULL;
215 if (p)
216 logfile = expand_homedir (p);
217 xfree (p);
219 else
221 xfree (logfile);
222 logfile = NULL;
223 if (log_fd != -1)
224 close(log_fd);
226 log_fd = -1;
229 log_syslog = config_get_boolean ("global", "syslog");
230 if (log_syslog == 1)
231 openlog ("pwmd", LOG_NDELAY | LOG_PID, LOG_DAEMON);
234 static void *
235 reload_rcfile_thread (void *arg)
237 #ifndef HAVE_PTHREAD_CANCEL
238 int *n = xmalloc (sizeof (int));
240 *n = 0;
241 pthread_setspecific (signal_thread_key, n);
242 INIT_THREAD_SIGNAL;
243 #endif
245 #ifdef HAVE_PR_SET_NAME
246 prctl (PR_SET_NAME, "reload rcfile");
247 #endif
248 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
249 MUTEX_LOCK (&rcfile_mutex);
250 pthread_cleanup_push (cleanup_mutex_cb, &rcfile_mutex);
252 for (;;)
254 struct slist_s *keep = NULL;
255 struct slist_s *config;
256 int b = disable_list_and_dump;
258 pthread_cond_wait (&rcfile_cond, &rcfile_mutex);
259 #ifndef HAVE_PTHREAD_CANCEL
260 int *cancel = (int *) pthread_getspecific (signal_thread_key);
261 if (*cancel)
262 break;
263 #endif
265 pthread_cleanup_push (cleanup_mutex_cb, &rcfile_mutex);
266 keep = config_keep_save ();
267 log_write (_("reloading configuration file '%s'"), rcfile);
269 config = config_parse (rcfile, 1);
270 if (config)
272 config_free (global_config);
273 global_config = config;
274 setup_logging ();
275 cache_push_from_rcfile ();
276 config_clear_keys ();
279 config_keep_restore (keep);
280 disable_list_and_dump = !disable_list_and_dump ? b : 1;
282 #ifdef WITH_GNUTLS
283 /* Kill existing listening threads since the configured listening
284 * protocols may have changed. */
285 start_stop_tls (1);
286 start_stop_tls (0);
287 #endif
288 pthread_cleanup_pop (0);
291 pthread_cleanup_pop (1);
292 return NULL;
295 gpg_error_t
296 send_error (assuan_context_t ctx, gpg_error_t e)
298 struct client_s *client = assuan_get_pointer (ctx);
300 if (gpg_err_source (e) == GPG_ERR_SOURCE_UNKNOWN)
301 e = gpg_error (e);
303 if (client)
304 client->last_rc = e;
306 if (!e)
307 return assuan_process_done (ctx, 0);
309 if (!ctx)
311 log_write ("ERR %i: %s", e, pwmd_strerror (e));
312 return e;
315 if (client && client->xml_error)
317 log_write ("%s", client->xml_error->message);
318 xfree (client->last_error);
319 client->last_error = NULL;
320 if (client->xml_error->message)
321 client->last_error = str_dup (client->xml_error->message);
323 e = assuan_process_done (ctx,
324 assuan_set_error (ctx, e,
325 client->xml_error->message ? client->xml_error->message : NULL));
326 xmlResetLastError ();
327 xmlResetError (client->xml_error);
328 xfree (client->xml_error);
329 client->xml_error = NULL;
330 return e;
333 return assuan_process_done (ctx,
334 assuan_set_error (ctx, e, pwmd_strerror (e)));
338 assuan_log_cb (assuan_context_t ctx, void *data, unsigned cat,
339 const char *msg)
341 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
342 int i, t;
343 int match = 0;
345 pthread_mutex_lock (&m);
346 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock, &m);
347 t = strv_length (debug_level);
349 for (i = 0; i < t; i++)
351 if (!strcasecmp (debug_level[i], (char *) "init")
352 && cat == ASSUAN_LOG_INIT)
354 match = 1;
355 break;
358 if (!strcasecmp (debug_level[i], (char *) "ctx")
359 && cat == ASSUAN_LOG_CTX)
361 match = 1;
362 break;
365 if (!strcasecmp (debug_level[i], (char *) "engine")
366 && cat == ASSUAN_LOG_ENGINE)
368 match = 1;
369 break;
372 if (!strcasecmp (debug_level[i], (char *) "data")
373 && cat == ASSUAN_LOG_DATA)
375 match = 1;
376 break;
379 if (!strcasecmp (debug_level[i], (char *) "sysio")
380 && cat == ASSUAN_LOG_SYSIO)
382 match = 1;
383 break;
386 if (!strcasecmp (debug_level[i], (char *) "control")
387 && cat == ASSUAN_LOG_CONTROL)
389 match = 1;
390 break;
394 if (match && msg)
396 if (logfile)
398 int fd;
400 if ((fd =
401 open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600)) == -1)
402 warn ("%s", logfile);
403 else
405 pthread_cleanup_push (cleanup_fd_cb, &fd);
406 write (fd, msg, strlen (msg));
407 pthread_cleanup_pop (1);
411 if (nofork)
413 fprintf (stderr, "%s%s", data ? (char *) data : "", msg);
414 fflush (stderr);
418 pthread_cleanup_pop (1);
419 return match;
422 void
423 log_write (const char *fmt, ...)
425 char *args;
426 va_list ap;
427 time_t now;
428 char buf[255];
429 pthread_t tid = pthread_self ();
430 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
432 if ((!logfile && !isatty (STDERR_FILENO) && !log_syslog) || !fmt)
433 return;
435 pthread_mutex_lock (&m);
436 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock, &m);
438 if (!cmdline && logfile && log_fd == -1)
440 log_fd = open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600);
441 if (log_fd == -1)
442 warn ("%s", logfile);
445 va_start (ap, fmt);
447 if (str_vasprintf (&args, fmt, ap) != -1)
449 if (cmdline)
451 pthread_cleanup_push (xfree, args);
452 fprintf (stderr, "pwmd: %s\n", args);
453 fflush (stderr);
454 pthread_cleanup_pop (1);
456 else
458 char *name = pthread_getspecific (thread_name_key);
459 char *line;
461 pthread_cleanup_push (xfree, args);
462 snprintf (buf, sizeof (buf), "%s(%p): ", name ? name : _("unknown"),
463 (pthread_t *) tid);
464 name = buf;
466 if (!cmdline && log_syslog && !nofork)
467 syslog (LOG_INFO, "%s%s", name, args);
469 time (&now);
470 struct tm *tm = localtime (&now);
471 char tbuf[21];
472 strftime (tbuf, sizeof (tbuf), "%b %d %Y %H:%M:%S ", tm);
473 tbuf[sizeof (tbuf) - 1] = 0;
475 if (args[strlen (args) - 1] == '\n')
476 args[strlen (args) - 1] = 0;
478 line = str_asprintf ("%s %i %s%s\n", tbuf, getpid (), name,
479 args);
480 pthread_cleanup_pop (1);
481 if (line)
483 pthread_cleanup_push (xfree, line);
484 if (logfile && log_fd != -1)
486 write (log_fd, line, strlen (line));
487 fsync (log_fd);
490 if (nofork)
492 fprintf (stdout, "%s", line);
493 fflush (stdout);
496 pthread_cleanup_pop (1);
501 va_end (ap);
502 pthread_cleanup_pop (0);
504 if (log_fd != -1 && config_get_boolean (NULL, "log_keepopen") <= 0)
506 close(log_fd);
507 log_fd = -1;
510 pthread_mutex_unlock (&m);
513 static gpg_error_t
514 setup_crypto ()
516 gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
518 if (!gcry_check_version (GCRYPT_VERSION))
520 fprintf (stderr, _("gcry_check_version(): Incompatible libgcrypt. "
521 "Wanted %s, got %s.\n"), GCRYPT_VERSION,
522 gcry_check_version (NULL));
523 return GPG_ERR_UNKNOWN_VERSION;
526 gcry_set_allocation_handler (xmalloc, xmalloc, NULL, xrealloc, xfree);
527 return 0;
530 gpg_error_t
531 do_validate_peer (assuan_context_t ctx, const char *section,
532 assuan_peercred_t * peer)
534 char **users;
535 int allowed = 0;
536 gpg_error_t rc;
537 struct client_s *client = assuan_get_pointer (ctx);
539 if (!client)
540 return GPG_ERR_EACCES;
542 #ifdef WITH_GNUTLS
543 if (client->thd->remote)
544 return tls_validate_access (client, section);
545 #endif
547 rc = assuan_get_peercred (ctx, peer);
548 if (rc)
549 return rc;
551 users = config_get_list (section, "allowed");
552 if (users)
554 for (char **p = users; *p; p++)
556 rc = acl_check_common(client, *p, (*peer)->uid, (*peer)->gid,
557 &allowed);
560 strv_free (users);
563 return allowed ? 0 : rc ? rc : GPG_ERR_EACCES;
566 /* Test if uid is a member of group 'name'. Invert when 'not' is true. */
567 #ifdef HAVE_GETGRNAM_R
568 static gpg_error_t
569 acl_check_group (const char *name, uid_t uid, gid_t gid, int not, int *allowed)
571 char *buf;
572 struct group gr, *gresult;
573 size_t len = sysconf (_SC_GETGR_R_SIZE_MAX);
575 if (len == -1)
576 len = 16384;
578 buf = xmalloc (len);
579 if (!buf)
580 return GPG_ERR_ENOMEM;
582 if (!getgrnam_r (name, &gr, buf, len, &gresult) && gresult)
584 if (gresult->gr_gid == gid)
586 xfree (buf);
587 *allowed = !not;
588 return 0;
591 len = sysconf (_SC_GETPW_R_SIZE_MAX);
592 if (len == -1)
593 len = 16384;
595 for (char **t = gresult->gr_mem; *t; t++)
597 char *tbuf;
598 struct passwd pw;
599 struct passwd *result = get_pwd_struct (*t, 0, &pw, &tbuf);
601 if (result && result->pw_uid == uid)
603 xfree (tbuf);
604 *allowed = !not;
605 break;
608 xfree (tbuf);
611 xfree (buf);
612 return 0;
615 xfree (buf);
616 return GPG_ERR_EACCES;
618 #else
619 static gpg_error_t
620 acl_check_group (const char *name, uid_t uid, gid_t gid, int not, int *allowed)
622 struct group *gresult;
624 gresult = getgrnam (name);
625 if (gresult && gresult->gr_gid == gid)
627 *allowed = !not;
628 return 0;
631 for (char **t = gresult->gr_mem; *t; t++)
633 char *buf;
634 struct passwd pw;
635 struct passwd *result = get_pwd_struct (*t, 0, &pw, &buf);
637 if (result && result->pw_uid == uid)
639 xfree (buf);
640 *allowed = !not;
641 break;
644 xfree (buf);
647 return 0;
649 #endif
651 gpg_error_t
652 peer_is_invoker(struct client_s *client)
654 struct invoking_user_s *user;
655 int allowed = 0;
657 if (client->thd->state == CLIENT_STATE_UNKNOWN)
658 return GPG_ERR_EACCES;
660 for (user = invoking_users; user; user = user->next)
662 #ifdef WITH_GNUTLS
663 if (client->thd->remote)
665 if (user->type == INVOKING_TLS
666 && !strcmp(client->thd->tls->fp, user->id))
667 allowed = user->not ? 0 : 1;
669 continue;
671 #endif
673 if (user->type == INVOKING_GID)
675 gpg_error_t rc = acl_check_group (user->id,
676 client->thd->peer->uid,
677 client->thd->peer->gid,
678 user->not, &allowed);
679 if (rc)
680 return rc;
682 else if (user->type == INVOKING_UID && client->thd->peer->uid == user->uid)
683 allowed = user->not ? 0 : 1;
686 return allowed ? 0 : GPG_ERR_EACCES;
689 #ifdef HAVE_GETGRNAM_R
690 gpg_error_t
691 acl_check_common (struct client_s *client, const char *user, uid_t uid,
692 gid_t gid, int *allowed)
694 int not = 0;
695 int rw = 0;
696 int tls = 0;
698 if (!user || !*user)
699 return 0;
701 if (*user == '-' || *user == '!')
702 not = 1;
704 if (*user == '+') // not implemented yet
705 rw = 1;
707 if (*user == '#') // TLS fingerprint hash
708 tls = 1;
710 if (not || rw || tls)
711 user++;
713 if (tls)
715 #ifdef WITH_GNUTLS
716 if (client->thd->remote)
718 if (!strcasecmp (client->thd->tls->fp, user))
719 *allowed = !not;
722 return 0;
723 #else
724 return 0;
725 #endif
727 #ifdef WITH_GNUTLS
728 else if (client->thd->remote) // Remote client with no TLS in the ACL
729 return 0;
730 #endif
732 if (*user == '@') // all users in group
733 return acl_check_group (user+1, uid, gid, not, allowed);
734 else
736 char *buf;
737 struct passwd pw;
738 struct passwd *pwd = get_pwd_struct (user, 0, &pw, &buf);
740 if (pwd && pwd->pw_uid == uid)
741 *allowed = !not;
743 xfree (buf);
746 return 0;
748 #else
749 gpg_error_t
750 acl_check_common (struct client_s *client, const char *user, uid_t uid,
751 gid_t gid, int *allowed)
753 int not = 0;
754 int rw = 0;
755 int tls = 0;
757 if (!user || !*user)
758 return 0;
760 if (*user == '-' || *user == '!')
761 not = 1;
763 if (*user == '+') // not implemented yet
764 rw = 1;
766 if (*user == '#') // TLS fingerprint hash
767 tls = 1;
769 if (not || rw || tls)
770 user++;
772 if (tls)
774 #ifdef WITH_GNUTLS
775 if (client->thd->remote)
777 if (!strcasecmp (client->thd->tls->fp, user))
778 *allowed = !not;
781 return 0;
782 #else
783 return 0;
784 #endif
787 if (*user == '@') // all users in group
788 return acl_check_group (user+1, uid, gid, not, allowed);
789 else
791 char *buf;
792 struct passwd pw;
793 struct passwd *result = get_pwd_struct (user, 0, &pw, &buf);
795 if (result && result->pw_uid == uid)
796 *allowed = !not;
798 xfree (buf);
801 return 0;
803 #endif
805 static gpg_error_t
806 validate_peer (struct client_s *cl)
808 gpg_error_t rc;
810 #ifdef WITH_GNUTLS
811 if (cl->thd->remote)
812 return tls_validate_access (cl, NULL);
813 #endif
815 MUTEX_LOCK (&cn_mutex);
816 rc = do_validate_peer (cl->ctx, "global", &cl->thd->peer);
817 MUTEX_UNLOCK (&cn_mutex);
818 if (!rc || gpg_err_code (rc) == GPG_ERR_EACCES)
819 log_write ("peer %s: uid=%i, gid=%i, pid=%i",
820 !rc ? _("accepted") : _("rejected"), cl->thd->peer->uid,
821 cl->thd->peer->gid, cl->thd->peer->pid);
822 else if (rc)
823 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
825 return rc;
828 static void
829 xml_error_cb (void *data, xmlErrorPtr e)
831 struct client_s *client = data;
834 * Keep the first reported error as the one to show in the error
835 * description. Reset in send_error().
837 if (client->xml_error)
838 return;
840 client->xml_error = xcalloc (1, sizeof(xmlError));
841 xmlCopyError (e, client->xml_error);
844 static pid_t
845 hook_waitpid (assuan_context_t ctx, pid_t pid, int action,
846 int *status, int options)
848 return waitpid (pid, status, options);
851 static ssize_t
852 hook_read (assuan_context_t ctx, assuan_fd_t fd, void *data, size_t len)
854 #ifdef WITH_GNUTLS
855 struct client_s *client = assuan_get_pointer (ctx);
857 if (client->thd->remote)
858 return tls_read_hook (ctx, (int) fd, data, len);
859 #endif
861 return read ((int) fd, data, len);
864 static ssize_t
865 hook_write (assuan_context_t ctx, assuan_fd_t fd,
866 const void *data, size_t len)
868 #ifdef WITH_GNUTLS
869 struct client_s *client = assuan_get_pointer (ctx);
871 if (client->thd->remote)
872 return tls_write_hook (ctx, (int) fd, data, len);
873 #endif
875 return write ((int) fd, data, len);
878 static int
879 new_connection (struct client_s *cl)
881 gpg_error_t rc;
882 static struct assuan_malloc_hooks mhooks = { xmalloc, xrealloc, xfree };
883 static struct assuan_system_hooks shooks = {
884 ASSUAN_SYSTEM_HOOKS_VERSION,
885 __assuan_usleep,
886 __assuan_pipe,
887 __assuan_close,
888 hook_read,
889 hook_write,
890 //FIXME
891 NULL, //recvmsg
892 NULL, //sendmsg both are used for FD passing
893 __assuan_spawn,
894 hook_waitpid,
895 __assuan_socketpair,
896 __assuan_socket,
897 __assuan_connect
900 #ifdef WITH_GNUTLS
901 if (cl->thd->remote)
903 char *prio = config_get_string ("global", "tls_cipher_suite");
905 cl->thd->timeout = config_get_integer ("global", "tls_timeout");
906 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
907 return 0;
909 cl->thd->tls = tls_init (cl->thd->fd, cl->thd->timeout, prio);
910 xfree (prio);
911 if (!cl->thd->tls)
912 return 0;
914 #endif
916 rc = assuan_new_ext (&cl->ctx, GPG_ERR_SOURCE_DEFAULT, &mhooks,
917 debug_level ? assuan_log_cb : NULL, NULL);
918 if (rc)
919 goto fail;
921 assuan_ctx_set_system_hooks (cl->ctx, &shooks);
922 rc = assuan_init_socket_server (cl->ctx, cl->thd->fd, 2);
923 if (rc)
924 goto fail;
926 assuan_set_pointer (cl->ctx, cl);
927 assuan_set_hello_line (cl->ctx, PACKAGE_STRING);
928 rc = register_commands (cl->ctx);
929 if (rc)
930 goto fail;
932 rc = assuan_accept (cl->ctx);
933 if (rc)
934 goto fail;
936 rc = validate_peer (cl);
937 /* May not be implemented on all platforms. */
938 if (rc && gpg_err_code (rc) != GPG_ERR_ASS_GENERAL)
939 goto fail;
941 MUTEX_LOCK (&cn_mutex);
942 cl->thd->state = CLIENT_STATE_INIT;
943 MUTEX_UNLOCK (&cn_mutex);
944 rc = init_client_crypto (&cl->crypto);
945 if (rc)
946 goto fail;
948 #ifdef WITH_AGENT
949 if (use_agent)
950 cl->crypto->agent->client_ctx = cl->ctx;
951 #endif
953 cl->crypto->client_ctx = cl->ctx;
954 cl->lock_timeout = config_get_integer ("global", "lock_timeout");
955 xmlSetStructuredErrorFunc (cl, xml_error_cb);
956 return 1;
958 fail:
959 log_write ("%s", pwmd_strerror (rc));
960 return 0;
964 * This is called after a client_thread() terminates. Set with
965 * pthread_cleanup_push().
967 static void
968 cleanup_cb (void *arg)
970 struct client_thread_s *cn = arg;
971 struct client_s *cl = cn->cl;
973 MUTEX_LOCK (&cn_mutex);
974 cn_thread_list = slist_remove (cn_thread_list, cn);
975 MUTEX_UNLOCK (&cn_mutex);
977 if (cl)
979 cleanup_client (cl);
980 if (cl->xml_error)
981 xmlResetError (cl->xml_error);
983 xfree (cl->xml_error);
985 #ifdef WITH_GNUTLS
986 if (cn->tls)
988 gnutls_deinit (cn->tls->ses);
989 xfree (cn->tls->fp);
990 xfree (cn->tls);
992 #endif
994 if (!cn->atfork && cl->ctx)
995 assuan_release (cl->ctx);
996 else if (!cn->atfork && cl->thd && cl->thd->fd != -1)
997 close (cl->thd->fd);
999 if (cl->crypto)
1000 cleanup_crypto (&cl->crypto);
1002 pinentry_free_opts (&cl->pinentry_opts);
1003 xfree (cl);
1005 else
1007 if (cn->fd != -1)
1008 close (cn->fd);
1011 while (cn->msg_queue)
1013 struct status_msg_s *msg = cn->msg_queue;
1015 cn->msg_queue = msg->next;
1016 xfree (msg->line);
1017 xfree (msg);
1020 if (!cn->atfork && cn->status_msg_pipe[0] != -1)
1021 close (cn->status_msg_pipe[0]);
1023 if (!cn->atfork && cn->status_msg_pipe[1] != -1)
1024 close (cn->status_msg_pipe[1]);
1026 pthread_mutex_destroy (&cn->status_mutex);
1028 if (!cn->atfork)
1030 log_write (_("exiting, fd=%i"), cn->fd);
1031 send_status_all (STATUS_CLIENTS, NULL);
1034 xfree (cn->name);
1035 #ifdef WITH_GNUTLS
1036 xfree (cn->peeraddr);
1037 #endif
1038 xfree (cn);
1039 pthread_cond_signal (&quit_cond);
1042 void
1043 cleanup_all_clients (int atfork)
1045 /* This function may be called from pthread_atfork() which requires
1046 reinitialization. */
1047 if (atfork)
1049 pthread_mutexattr_t attr;
1051 pthread_mutexattr_init (&attr);
1052 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
1053 pthread_mutex_init (&cn_mutex, &attr);
1054 pthread_mutexattr_destroy (&attr);
1055 cache_mutex_init ();
1058 MUTEX_LOCK (&cn_mutex);
1060 while (slist_length (cn_thread_list))
1062 struct client_thread_s *thd = slist_nth_data (cn_thread_list, 0);
1064 thd->atfork = atfork;
1065 cleanup_cb (thd);
1068 exiting = 1;
1069 MUTEX_UNLOCK (&cn_mutex);
1070 cache_deinit (atfork);
1073 static gpg_error_t
1074 send_msg_queue (struct client_thread_s *thd)
1076 MUTEX_LOCK (&thd->status_mutex);
1077 gpg_error_t rc = 0;
1078 char c;
1080 read (thd->status_msg_pipe[0], &c, 1);
1081 thd->wrote_status = 0;
1083 while (thd->msg_queue)
1085 struct status_msg_s *msg = thd->msg_queue;
1087 thd->msg_queue = thd->msg_queue->next;
1088 MUTEX_UNLOCK (&thd->status_mutex);
1089 rc = send_status (thd->cl->ctx, msg->s, msg->line);
1090 MUTEX_LOCK (&thd->status_mutex);
1091 xfree (msg->line);
1092 xfree (msg);
1094 if (rc)
1095 break;
1098 MUTEX_UNLOCK (&thd->status_mutex);
1099 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1100 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
1102 return rc;
1105 static void *
1106 client_thread (void *data)
1108 struct client_thread_s *thd = data;
1109 struct client_s *cl = xcalloc (1, sizeof (struct client_s));
1111 #ifdef HAVE_PR_SET_NAME
1112 prctl (PR_SET_NAME, "client");
1113 #endif
1114 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1116 if (!cl)
1118 log_write ("%s(%i): %s", __FILE__, __LINE__,
1119 pwmd_strerror (GPG_ERR_ENOMEM));
1120 return NULL;
1123 MUTEX_LOCK (&cn_mutex);
1124 pthread_cleanup_push (cleanup_cb, thd);
1125 thd->cl = cl;
1126 cl->thd = thd;
1127 MUTEX_UNLOCK (&cn_mutex);
1129 if (new_connection (cl))
1131 int finished = 0;
1132 gpg_error_t rc;
1134 send_status_all (STATUS_CLIENTS, NULL);
1135 rc = send_status (cl->ctx, STATUS_CACHE, NULL);
1136 if (rc)
1138 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
1139 finished = 1;
1142 while (!finished)
1144 fd_set rfds;
1145 int n;
1146 int eof;
1148 FD_ZERO (&rfds);
1149 FD_SET (thd->fd, &rfds);
1150 FD_SET (thd->status_msg_pipe[0], &rfds);
1151 n = thd->fd > thd->status_msg_pipe[0]
1152 ? thd->fd : thd->status_msg_pipe[0];
1154 n = select (n + 1, &rfds, NULL, NULL, NULL);
1155 if (n == -1)
1157 log_write ("%s", strerror (errno));
1158 break;
1161 if (FD_ISSET (thd->status_msg_pipe[0], &rfds))
1163 rc = send_msg_queue (thd);
1164 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1165 break;
1168 if (!FD_ISSET (thd->fd, &rfds))
1169 continue;
1171 rc = assuan_process_next (cl->ctx, &eof);
1172 if (rc || eof)
1174 if (gpg_err_code (rc) == GPG_ERR_EOF || eof)
1175 break;
1177 log_write ("assuan_process_next(): rc=%i %s", rc,
1178 pwmd_strerror (rc));
1179 if (rc == gpg_error (GPG_ERR_ETIMEDOUT))
1180 break;
1182 rc = send_error (cl->ctx, rc);
1183 if (rc)
1185 log_write ("assuan_process_done(): rc=%i %s", rc,
1186 pwmd_strerror (rc));
1187 break;
1191 /* Since the msg queue pipe fd's are non-blocking, check for
1192 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1193 * client has already disconnected and will be converted to
1194 * GPG_ERR_EOF during assuan_process_next().
1196 rc = send_msg_queue (thd);
1197 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1198 break;
1202 /* Don't do pthread_exit() here because any set pthread_cleanup_push
1203 * functions would be called after a command failed but then the client
1204 * exited normally which may lead to a double free. */
1205 pthread_cleanup_pop (1);
1206 return NULL;
1209 static int
1210 xml_import (const char *filename, const char *outfile,
1211 const char *keygrip, const char *sign_keygrip,
1212 const char *keyfile, int no_passphrase, const char *cipher,
1213 const char *params, uint64_t iterations)
1215 xmlDocPtr doc;
1216 int fd;
1217 struct stat st;
1218 int len;
1219 xmlChar *xmlbuf;
1220 xmlChar *xml;
1221 gpg_error_t rc;
1222 struct crypto_s *crypto = NULL;
1223 void *key = NULL;
1224 size_t keylen = 0;
1225 int algo = cipher ? cipher_string_to_gcrypt ((char *) cipher) :
1226 GCRY_CIPHER_AES256;
1228 if (algo == -1)
1230 log_write ("ERR %i: %s", gpg_error (GPG_ERR_CIPHER_ALGO),
1231 pwmd_strerror (GPG_ERR_CIPHER_ALGO));
1232 return 0;
1235 if (stat (filename, &st) == -1)
1237 log_write ("%s: %s", filename,
1238 pwmd_strerror (gpg_error_from_errno (errno)));
1239 return 0;
1242 rc = init_client_crypto (&crypto);
1243 if (rc)
1244 return 0;
1246 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
1247 crypto->save.hdr.flags = set_cipher_flag (crypto->save.hdr.flags, algo);
1248 log_write (_("Importing XML from '%s'. Output will be written to '%s' ..."),
1249 filename, outfile);
1251 if ((fd = open (filename, O_RDONLY)) == -1)
1253 log_write ("%s: %s", filename,
1254 pwmd_strerror (gpg_error_from_errno (errno)));
1255 goto fail;
1258 if ((xmlbuf = xmalloc (st.st_size + 1)) == NULL)
1260 close (fd);
1261 log_write ("%s(%i): %s", __FILE__, __LINE__,
1262 pwmd_strerror (GPG_ERR_ENOMEM));
1263 goto fail;
1266 if (read (fd, xmlbuf, st.st_size) == -1)
1268 rc = gpg_error_from_errno (errno);
1269 close (fd);
1270 log_write ("%s: %s", filename, pwmd_strerror (rc));
1271 goto fail;
1274 close (fd);
1275 xmlbuf[st.st_size] = 0;
1277 * Make sure the document validates.
1279 if ((doc = xmlReadDoc (xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS)) == NULL)
1281 log_write ("xmlReadDoc() failed");
1282 xfree (xmlbuf);
1283 goto fail;
1286 xfree (xmlbuf);
1287 xmlNodePtr n = xmlDocGetRootElement (doc);
1288 if (n && !xmlStrEqual (n->name, (xmlChar *) "pwmd"))
1290 log_write (_("Could not find root \"pwmd\" element."));
1291 rc = GPG_ERR_BAD_DATA;
1294 if (!rc)
1295 rc = validate_import (NULL, n ? n->children : n);
1297 if (rc)
1299 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1300 xmlFreeDoc (doc);
1301 goto fail;
1304 xmlDocDumpMemory (doc, &xml, &len);
1305 xmlFreeDoc (doc);
1306 crypto->save.hdr.s2k_count = iterations;
1307 if (!use_agent)
1309 rc = export_common (NULL, 0, crypto, xml, len, outfile, keyfile, &key,
1310 &keylen, 0, 0, no_passphrase);
1311 if (!rc)
1312 log_write (_("Success!"));
1314 #ifdef WITH_AGENT
1315 else
1317 rc = agent_set_pinentry_options (crypto->agent);
1318 if (!rc)
1319 rc = agent_export_common (crypto, keygrip, sign_keygrip, no_passphrase,
1320 xml, len, outfile, params, keyfile);
1322 #endif
1324 gcry_free (key);
1325 xmlFree (xml);
1326 if (rc)
1328 send_error (NULL, rc);
1329 goto fail;
1332 cleanup_crypto (&crypto);
1333 return 1;
1335 fail:
1336 cleanup_crypto (&crypto);
1337 return 0;
1340 static int
1341 do_cache_push (const char *filename, struct crypto_s *crypto)
1343 unsigned char md5file[16];
1344 gpg_error_t rc;
1345 void *key = NULL;
1346 size_t keylen = 0;
1347 xmlDocPtr doc;
1348 struct cache_data_s *cdata;
1349 unsigned char *crc;
1350 size_t len;
1352 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1353 filename);
1355 if (valid_filename (filename) == 0)
1357 log_write (_("%s: Invalid characters in filename"), filename);
1358 return 0;
1361 rc = decrypt_common (NULL, 0, crypto, filename, &key, &keylen, NULL, NULL);
1362 if (rc)
1363 return 0;
1365 rc = parse_doc ((char *) crypto->plaintext, crypto->plaintext_len, &doc);
1366 if (rc)
1368 log_write ("%s", pwmd_strerror (rc));
1369 xfree (key);
1370 return 0;
1373 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
1374 cdata = xcalloc (1, sizeof (struct cache_data_s));
1375 if (!cdata)
1377 xmlFreeDoc (doc);
1378 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM));
1379 xfree (key);
1380 return 0;
1383 rc = get_checksum (filename, &crc, &len);
1384 if (rc)
1386 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1387 xmlFreeDoc (doc);
1388 free_cache_data_once (cdata);
1389 xfree (key);
1390 return 0;
1393 cdata->crc = crc;
1394 rc = encrypt_xml (NULL, cache_key, cache_keysize, GCRY_CIPHER_AES,
1395 crypto->plaintext, crypto->plaintext_len, &cdata->doc,
1396 &cdata->doclen, &cache_iv, &cache_blocksize);
1397 if (!rc && !IS_PKI (crypto))
1399 cdata->key = key;
1400 cdata->keylen = keylen;
1402 else
1403 xfree (key);
1405 if (rc)
1407 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1408 xmlFreeDoc (doc);
1409 free_cache_data_once (cdata);
1410 return 0;
1413 #ifdef WITH_AGENT
1414 if (use_agent && IS_PKI (crypto))
1416 gcry_sexp_build ((gcry_sexp_t *) & cdata->pubkey, NULL, "%S",
1417 crypto->pkey_sexp);
1418 gcry_sexp_build ((gcry_sexp_t *) & cdata->sigkey, NULL, "%S",
1419 crypto->sigpkey_sexp);
1421 #endif
1423 int timeout = config_get_integer (filename, "cache_timeout");
1424 cache_add_file (md5file, crypto->grip, cdata, timeout);
1425 log_write (_("Successfully added '%s' to the cache."), filename);
1426 return 1;
1429 static gpg_error_t
1430 init_client (int fd, const char *addr)
1432 gpg_error_t rc = 0;
1433 struct client_thread_s *new = xcalloc (1, sizeof (struct client_thread_s));
1435 if (!new)
1437 close (fd);
1438 return GPG_ERR_ENOMEM;
1441 MUTEX_LOCK (&cn_mutex);
1442 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
1444 if (pipe (new->status_msg_pipe) == -1)
1445 rc = gpg_error_from_errno (errno);
1447 if (!rc)
1449 if (fcntl (new->status_msg_pipe[0], F_SETFL, O_NONBLOCK) == -1)
1450 rc = gpg_error_from_errno (errno);
1452 if (!rc)
1453 if (fcntl (new->status_msg_pipe[1], F_SETFL, O_NONBLOCK) == -1)
1454 rc = gpg_error_from_errno (errno);
1456 pthread_mutex_init (&new->status_mutex, NULL);
1459 if (!rc)
1461 #ifdef WITH_GNUTLS
1462 new->remote = addr ? 1 : 0;
1463 #endif
1464 new->fd = fd;
1465 rc = create_thread (client_thread, new, &new->tid, 1);
1466 if (rc)
1468 close (new->status_msg_pipe[0]);
1469 close (new->status_msg_pipe[1]);
1470 pthread_mutex_destroy (&new->status_mutex);
1474 if (!rc)
1476 struct slist_s *list = slist_append (cn_thread_list, new);
1478 if (list)
1480 cn_thread_list = list;
1481 if (addr)
1483 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1484 (pthread_t *) new->tid, fd, addr);
1485 #ifdef WITH_GNUTLS
1486 new->peeraddr = str_dup (addr);
1487 #endif
1489 else
1490 log_write (_("new connection: tid=%p, fd=%i"),
1491 (pthread_t *) new->tid, fd);
1493 else
1494 rc = GPG_ERR_ENOMEM;
1497 pthread_cleanup_pop (1);
1499 if (rc)
1501 xfree (new);
1502 close (fd);
1503 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1504 pwmd_strerror (rc));
1506 return rc;
1509 static void*
1510 keepalive_thread (void *arg)
1512 #ifndef HAVE_PTHREAD_CANCEL
1513 int *n = xmalloc (sizeof (int));
1515 *n = 0;
1516 pthread_setspecific (signal_thread_key, n);
1517 INIT_THREAD_SIGNAL;
1518 #endif
1520 #ifdef HAVE_PR_SET_NAME
1521 prctl (PR_SET_NAME, "keepalive");
1522 #endif
1523 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1525 for (;;)
1527 int n = config_get_integer ("global", "keepalive_interval");
1528 struct timeval tv = { n, 0 };
1529 #ifndef HAVE_PTHREAD_CANCEL
1530 int *sigusr2;
1532 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1533 if (*sigusr2)
1534 break;
1535 #endif
1537 send_status_all (STATUS_KEEPALIVE, NULL);
1538 select (0, NULL, NULL, NULL, &tv);
1541 return NULL;
1544 #ifdef WITH_GNUTLS
1545 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1546 static void *
1547 get_in_addr (struct sockaddr *sa)
1549 if (sa->sa_family == AF_INET)
1550 return &(((struct sockaddr_in *) sa)->sin_addr);
1552 return &(((struct sockaddr_in6 *) sa)->sin6_addr);
1555 static void *
1556 tcp_accept_thread (void *arg)
1558 int sockfd = *(int *) arg;
1559 #ifndef HAVE_PTHREAD_CANCEL
1560 int *n = xmalloc (sizeof (int));
1562 *n = 0;
1563 pthread_setspecific (signal_thread_key, n);
1564 INIT_THREAD_SIGNAL;
1565 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1566 #endif
1568 #ifdef HAVE_PR_SET_NAME
1569 prctl (PR_SET_NAME, "tcp_accept");
1570 #endif
1571 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1573 for (;;)
1575 struct sockaddr_storage raddr;
1576 socklen_t slen = sizeof (raddr);
1577 int fd;
1578 unsigned long n;
1579 char s[INET6_ADDRSTRLEN];
1580 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1581 #ifndef HAVE_PTHREAD_CANCEL
1582 int *sigusr2;
1584 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1585 if (*sigusr2)
1586 break;
1587 #endif
1589 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1590 if (fd == -1)
1592 if (errno == EMFILE || errno == ENFILE)
1593 log_write ("accept(): %s",
1594 pwmd_strerror (gpg_error_from_errno (errno)));
1595 else if (errno != EAGAIN)
1597 if (!quit) // probably EBADF
1598 log_write ("accept(): %s", strerror (errno));
1600 break;
1603 #ifndef HAVE_PTHREAD_CANCEL
1604 select (0, NULL, NULL, NULL, &tv);
1605 #endif
1606 continue;
1609 if (quit)
1611 close (fd);
1612 break;
1615 inet_ntop (raddr.ss_family, get_in_addr ((struct sockaddr *) &raddr),
1616 s, sizeof s);
1617 (void) init_client (fd, s);
1618 n = config_get_integer ("global", "tcp_wait");
1619 if (n > 0)
1621 tv.tv_sec = (n * 100000) / 100000;
1622 tv.tv_usec = (n * 100000) % 100000;
1623 select (0, NULL, NULL, NULL, &tv);
1627 return NULL;
1630 static int
1631 start_stop_tls_with_protocol (int ipv6, int term)
1633 struct addrinfo hints, *servinfo, *p;
1634 int port = config_get_integer ("global", "tcp_port");
1635 char buf[7];
1636 int n;
1637 gpg_error_t rc;
1638 int *fd = ipv6 ? &tls6_fd : &tls_fd;
1640 if (term || config_get_boolean ("global", "enable_tcp") == 0)
1642 if (tls6_fd != -1)
1644 if (spawned_tls6)
1646 #ifdef HAVE_PTHREAD_CANCEL
1647 pthread_cancel (tls6_tid);
1648 #else
1649 pthread_kill (tls6_tid, SIGUSR2);
1650 #endif
1651 pthread_join (tls6_tid, NULL);
1654 shutdown (tls6_fd, SHUT_RDWR);
1655 close (tls6_fd);
1656 tls6_fd = -1;
1657 spawned_tls6 = 0;
1660 if (tls_fd != -1)
1662 if (spawned_tls)
1664 #ifdef HAVE_PTHREAD_CANCEL
1665 pthread_cancel (tls_tid);
1666 #else
1667 pthread_kill (tls_tid, SIGUSR2);
1668 #endif
1669 pthread_join (tls_tid, NULL);
1672 shutdown (tls_fd, SHUT_RDWR);
1673 close (tls_fd);
1674 tls_fd = -1;
1675 spawned_tls = 0;
1678 /* A client may still be connected. */
1679 if (!quit && x509_cred != NULL)
1680 tls_deinit_params ();
1682 return 1;
1685 if ((ipv6 && tls6_fd != -1) || (!ipv6 && tls_fd != -1))
1686 return 1;
1688 memset (&hints, 0, sizeof (hints));
1689 hints.ai_family = ipv6 ? AF_INET6 : AF_INET;
1690 hints.ai_socktype = SOCK_STREAM;
1691 hints.ai_flags = AI_PASSIVE;
1692 snprintf (buf, sizeof (buf), "%i", port);
1694 if ((n = getaddrinfo (NULL, buf, &hints, &servinfo)) == -1)
1696 log_write ("getaddrinfo(): %s", gai_strerror (n));
1697 return 0;
1700 for (n = 0, p = servinfo; p != NULL; p = p->ai_next)
1702 int r = 1;
1704 if ((ipv6 && p->ai_family != AF_INET6)
1705 || (!ipv6 && p->ai_family != AF_INET))
1706 continue;
1708 if ((*fd = socket (p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
1710 log_write ("socket(): %s", strerror (errno));
1711 continue;
1714 if (setsockopt (*fd, SOL_SOCKET, SO_REUSEADDR, &r, sizeof (int)) == -1)
1716 log_write ("setsockopt(): %s",
1717 pwmd_strerror (gpg_error_from_errno (errno)));
1718 freeaddrinfo (servinfo);
1719 goto fail;
1722 if (bind (*fd, p->ai_addr, p->ai_addrlen) == -1)
1724 close (*fd);
1725 log_write ("bind(): %s",
1726 pwmd_strerror (gpg_error_from_errno (errno)));
1727 continue;
1730 n++;
1731 break;
1734 freeaddrinfo (servinfo);
1736 if (!n)
1737 goto fail;
1739 #if HAVE_DECL_SO_BINDTODEVICE != 0
1740 char *tmp = config_get_string ("global", "tcp_interface");
1741 if (tmp && setsockopt (*fd, SOL_SOCKET, SO_BINDTODEVICE, tmp,
1742 strlen (tmp)) == -1)
1744 log_write ("setsockopt(): %s",
1745 pwmd_strerror (gpg_error_from_errno (errno)));
1746 xfree (tmp);
1747 goto fail;
1750 xfree (tmp);
1751 #endif
1753 if (x509_cred == NULL)
1755 char *tmp = config_get_string ("global", "tls_dh_level");
1757 rc = tls_init_params (tmp);
1758 xfree (tmp);
1759 if (rc)
1760 goto fail;
1763 if (listen (*fd, 0) == -1)
1765 log_write ("listen(): %s", strerror (errno));
1766 goto fail;
1769 if (ipv6)
1770 rc = create_thread (tcp_accept_thread, fd, &tls6_tid, 0);
1771 else
1772 rc = create_thread (tcp_accept_thread, fd, &tls_tid, 0);
1774 if (rc)
1776 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1777 pwmd_strerror (rc));
1778 goto fail;
1781 if (ipv6)
1782 spawned_tls6 = 1;
1783 else
1784 spawned_tls = 1;
1786 return 1;
1788 fail:
1789 start_stop_tls_with_protocol (0, 1);
1790 if (tls_fd != -1)
1791 close (tls_fd);
1793 if (tls6_fd != -1)
1794 close (tls6_fd);
1796 tls_fd = -1;
1797 tls6_fd = -1;
1798 return 0;
1801 static int
1802 start_stop_tls (int term)
1804 char *s = config_get_string ("global", "tcp_bind");
1805 int b;
1807 if (!s)
1808 return 0;
1810 if (!strcmp (s, "any"))
1812 b = start_stop_tls_with_protocol (0, term);
1813 if (b)
1814 b = start_stop_tls_with_protocol (1, term);
1816 else if (!strcmp (s, "ipv4"))
1817 b = start_stop_tls_with_protocol (0, term);
1818 else if (!strcmp (s, "ipv6"))
1819 b = start_stop_tls_with_protocol (1, term);
1820 else
1821 b = 0;
1823 xfree (s);
1824 return b;
1826 #endif
1828 static void *
1829 accept_thread (void *arg)
1831 int sockfd = *(int *) arg;
1832 #ifndef HAVE_PTHREAD_CANCEL
1833 int *n = xmalloc (sizeof (int));
1835 *n = 0;
1836 pthread_setspecific (signal_thread_key, n);
1837 INIT_THREAD_SIGNAL;
1838 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1839 #endif
1841 #ifdef HAVE_PR_SET_NAME
1842 prctl (PR_SET_NAME, "accept");
1843 #endif
1844 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1846 for (;;)
1848 socklen_t slen = sizeof (struct sockaddr_un);
1849 struct sockaddr_un raddr;
1850 int fd;
1851 #ifndef HAVE_PTHREAD_CANCEL
1852 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1853 int *sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1855 if (*sigusr2)
1856 break;
1857 #endif
1859 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1860 if (fd == -1)
1862 if (errno == EMFILE || errno == ENFILE)
1863 log_write ("accept(): %s",
1864 pwmd_strerror (gpg_error_from_errno (errno)));
1865 else if (errno != EAGAIN)
1867 if (!quit) // probably EBADF
1868 log_write ("accept(): %s",
1869 pwmd_strerror (gpg_error_from_errno (errno)));
1871 break;
1874 #ifndef HAVE_PTHREAD_CANCEL
1875 select (0, NULL, NULL, NULL, &tv);
1876 #endif
1877 continue;
1880 (void) init_client (fd, NULL);
1883 /* Just in case accept() failed for some reason other than EBADF */
1884 quit = 1;
1885 return NULL;
1888 static void *
1889 cache_timer_thread (void *arg)
1891 #ifndef HAVE_PTHREAD_CANCEL
1892 int *n = xmalloc (sizeof (int));
1894 *n = 0;
1895 pthread_setspecific (signal_thread_key, n);
1896 INIT_THREAD_SIGNAL;
1897 #endif
1899 #ifdef HAVE_PR_SET_NAME
1900 prctl (PR_SET_NAME, "cache timer");
1901 #endif
1902 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1904 for (;;)
1906 struct timeval tv = { 1, 0 };
1907 #ifndef HAVE_PTHREAD_CANCEL
1908 int *n;
1910 n = (int *) pthread_getspecific (signal_thread_key);
1911 if (*n)
1912 break;
1913 #endif
1915 select (0, NULL, NULL, NULL, &tv);
1916 cache_adjust_timeout ();
1919 return NULL;
1922 static int
1923 signal_loop (sigset_t sigset)
1925 int done = 0;
1926 int siint = 0;
1930 int sig;
1932 sigwait (&sigset, &sig);
1934 if (sig != SIGQUIT)
1935 log_write (_("caught signal %i (%s)"), sig, strsignal (sig));
1937 switch (sig)
1939 case SIGHUP:
1940 pthread_cond_signal (&rcfile_cond);
1941 break;
1942 case SIGUSR1:
1943 log_write (_("clearing file cache"));
1944 cache_clear (NULL);
1945 send_status_all (STATUS_CACHE, NULL);
1946 break;
1947 case SIGQUIT:
1948 done = 1;
1949 break;
1950 default:
1951 siint = 1;
1952 done = 1;
1953 break;
1956 while (!done);
1958 return siint;
1961 static void
1962 catchsig (int sig)
1964 log_write (_ ("Caught signal %i (%s). Exiting."), sig, strsignal (sig));
1965 #ifdef HAVE_BACKTRACE
1966 BACKTRACE (__FUNCTION__);
1967 #endif
1968 longjmp (jmp, 1);
1971 static void *
1972 waiting_for_exit (void *arg)
1974 int last = 0;
1975 #ifndef HAVE_PTHREAD_CANCEL
1976 int *n = xmalloc (sizeof (int));
1978 *n = 0;
1979 pthread_setspecific (signal_thread_key, n);
1980 INIT_THREAD_SIGNAL;
1981 #endif
1983 #ifdef HAVE_PR_SET_NAME
1984 prctl (PR_SET_NAME, "exiting");
1985 #endif
1986 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1987 log_write (_("waiting for all clients to disconnect"));
1988 MUTEX_LOCK (&quit_mutex);
1989 pthread_cleanup_push (cleanup_mutex_cb, &quit_mutex);
1991 for (;;)
1993 struct timespec ts;
1994 int n;
1996 MUTEX_LOCK (&cn_mutex);
1997 n = slist_length (cn_thread_list);
1998 MUTEX_UNLOCK (&cn_mutex);
1999 if (!n)
2000 break;
2002 #ifndef HAVE_PTHREAD_CANCEL
2003 int *s = (int *) pthread_getspecific (signal_thread_key);
2004 if (*s)
2005 break;
2006 #endif
2008 if (last != n)
2010 log_write (_("%i clients remain"), n);
2011 last = n;
2014 INIT_TIMESPEC (SIG_TIMEOUT, ts);
2015 pthread_cond_timedwait (&quit_cond, &quit_mutex, &ts);
2018 kill (getpid (), SIGQUIT);
2019 pthread_cleanup_pop (1);
2020 return NULL;
2023 static int
2024 server_loop (int sockfd, char **socketpath)
2026 pthread_t accept_tid;
2027 pthread_t cache_timeout_tid;
2028 int cancel_timeout_thread = 0, cancel_accept_thread = 0;
2029 int cancel_keepalive_thread = 0;
2030 sigset_t sigset;
2031 int n;
2032 int segv = 0;
2033 gpg_error_t rc;
2035 init_commands ();
2036 sigemptyset (&sigset);
2038 /* Termination */
2039 sigaddset (&sigset, SIGTERM);
2040 sigaddset (&sigset, SIGINT);
2042 /* Clears the file cache. */
2043 sigaddset (&sigset, SIGUSR1);
2045 /* Configuration file reloading. */
2046 sigaddset (&sigset, SIGHUP);
2048 /* For exiting cleanly. */
2049 sigaddset (&sigset, SIGQUIT);
2051 #ifndef HAVE_PTHREAD_CANCEL
2053 The socket, cache and rcfile threads use this signal when
2054 pthread_cancel() is unavailable. Prevent the main thread from
2055 catching this signal from another process.
2057 sigaddset (&sigset, SIGUSR2);
2058 #endif
2060 /* When mem.c cannot find a pointer in the list (double free). */
2061 signal (SIGABRT, catchsig);
2062 sigaddset (&sigset, SIGABRT);
2063 sigprocmask (SIG_BLOCK, &sigset, NULL);
2065 #ifndef HAVE_PTHREAD_CANCEL
2066 /* Remove this signal from the watched signals in signal_loop(). */
2067 sigdelset (&sigset, SIGUSR2);
2068 #endif
2070 /* Ignored everywhere. When a client disconnects abnormally this signal
2071 * gets raised. It isn't needed though because client_thread() will check
2072 * for rcs even after the client disconnects. */
2073 signal (SIGPIPE, SIG_IGN);
2075 /* Can show a backtrace of the stack in the log. */
2076 signal (SIGSEGV, catchsig);
2078 #ifdef WITH_GNUTLS
2079 /* Needs to be done after the fork(). */
2080 if (!start_stop_tls (0))
2082 segv = 1;
2083 goto done;
2085 #endif
2087 pthread_mutex_init (&quit_mutex, NULL);
2088 pthread_cond_init (&quit_cond, NULL);
2089 char *p = get_username (getuid());
2090 log_write (_("%s started for user %s"), PACKAGE_STRING, p);
2091 xfree (p);
2093 #ifdef WITH_GNUTLS
2094 if (config_get_boolean ("global", "enable_tcp"))
2095 log_write (_("Listening on %s and TCP port %i"), *socketpath,
2096 config_get_integer ("global", "tcp_port"));
2097 else
2098 log_write (_("Listening on %s"), *socketpath);
2099 #else
2100 log_write (_("Listening on %s"), *socketpath);
2101 #endif
2103 rc = create_thread (keepalive_thread, NULL, &keepalive_tid, 0);
2104 if (rc)
2106 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2107 pwmd_strerror (rc));
2108 goto done;
2111 cancel_keepalive_thread = 1;
2112 rc = create_thread (reload_rcfile_thread, NULL, &rcfile_tid, 0);
2113 if (rc)
2115 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2116 pwmd_strerror (rc));
2117 goto done;
2120 rc = create_thread (cache_timer_thread, NULL, &cache_timeout_tid, 0);
2121 if (rc)
2123 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2124 pwmd_strerror (rc));
2125 goto done;
2128 cancel_timeout_thread = 1;
2129 rc = create_thread (accept_thread, &sockfd, &accept_tid, 0);
2130 if (rc)
2132 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2133 pwmd_strerror (rc));
2134 goto done;
2137 cancel_accept_thread = 1;
2138 if (!setjmp (jmp))
2139 signal_loop (sigset);
2140 else
2141 segv = 1;
2143 done:
2145 * We're out of the main server loop. This happens when a signal was sent
2146 * to terminate the daemon. We'll wait for all clients to disconnect
2147 * before exiting but exit immediately if another termination signal is
2148 * sent.
2150 if (cancel_accept_thread)
2152 #ifdef HAVE_PTHREAD_CANCEL
2153 int n = pthread_cancel (accept_tid);
2154 #else
2155 int n = pthread_kill (accept_tid, SIGUSR2);
2156 #endif
2157 if (!n)
2158 pthread_join (accept_tid, NULL);
2161 #ifdef WITH_GNUTLS
2162 start_stop_tls (1);
2163 #endif
2164 shutdown (sockfd, SHUT_RDWR);
2165 close (sockfd);
2166 unlink (*socketpath);
2167 xfree (*socketpath);
2168 *socketpath = NULL;
2169 MUTEX_LOCK (&cn_mutex);
2170 n = slist_length (cn_thread_list);
2171 MUTEX_UNLOCK (&cn_mutex);
2173 if (n && !segv)
2175 pthread_t tid;
2177 rc = create_thread (waiting_for_exit, NULL, &tid, 0);
2178 if (!rc)
2180 if (signal_loop (sigset))
2182 log_write (_("Received second termination request. Exiting."));
2183 #ifdef HAVE_PTHREAD_CANCEL
2184 pthread_cancel (tid);
2185 #else
2186 pthread_kill (tid, SIGUSR2);
2187 #endif
2188 pthread_join (tid, NULL);
2191 else
2192 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2193 pwmd_strerror (rc));
2196 if (cancel_timeout_thread)
2198 #ifdef HAVE_PTHREAD_CANCEL
2199 pthread_cancel (cache_timeout_tid);
2200 #else
2201 pthread_kill (cache_timeout_tid, SIGUSR2);
2202 #endif
2203 pthread_join (cache_timeout_tid, NULL);
2206 if (cancel_keepalive_thread)
2208 #ifdef HAVE_PTHREAD_CANCEL
2209 pthread_cancel (keepalive_tid);
2210 #else
2211 pthread_kill (keepalive_tid, SIGUSR2);
2212 #endif
2213 pthread_join (keepalive_tid, NULL);
2216 cleanup_all_clients (0);
2217 #ifdef WITH_GNUTLS
2218 start_stop_tls (1);
2219 #endif
2220 deinit_commands ();
2221 pthread_cond_destroy (&quit_cond);
2222 pthread_mutex_destroy (&quit_mutex);
2223 return segv ? EXIT_FAILURE : EXIT_SUCCESS;;
2226 static void
2227 startup_failure ()
2229 log_write (_
2230 ("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
2231 cache_clear (NULL);
2234 /* This is called from cache.c:clear_once(). See
2235 * command.c:clearcache_command() for details about lock checking.
2237 static gpg_error_t
2238 free_cache_data (file_cache_t * cache)
2240 gpg_error_t rc = GPG_ERR_NO_DATA;
2241 int i, t;
2242 struct client_thread_s *found = NULL;
2243 int self = 0;
2245 if (!cache->data)
2246 return 0;
2248 cache_lock ();
2249 MUTEX_LOCK (&cn_mutex);
2250 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
2251 t = slist_length (cn_thread_list);
2253 for (i = 0; i < t; i++)
2255 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2257 if (!thd->cl)
2258 continue;
2260 if (!memcmp (thd->cl->md5file, cache->filename,
2261 sizeof (cache->filename)))
2263 if (pthread_equal (pthread_self (), thd->tid))
2265 found = thd;
2266 self = 1;
2267 continue;
2270 /* Continue trying to find a client who has the same file open and
2271 * also has a lock. */
2272 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0, -1);
2273 if (!rc)
2275 self = 0;
2276 found = thd;
2277 break;
2282 if (self && (!rc || rc == GPG_ERR_NO_DATA))
2283 rc = cache_lock_mutex (found->cl->ctx, found->cl->md5file, -1, 0, -1);
2285 if (exiting || !rc || rc == GPG_ERR_NO_DATA)
2287 free_cache_data_once (cache->data);
2288 cache->data = NULL;
2289 cache->defer_clear = 0;
2290 cache->timeout = -1;
2292 if (found)
2293 cache_unlock_mutex (found->cl->md5file, 0);
2295 rc = 0;
2298 if (rc)
2299 cache->defer_clear = 1;
2301 pthread_cleanup_pop (1);
2302 cache_unlock ();
2303 return rc;
2306 static int
2307 convert_v2_datafile (const char *filename, const char *cipher,
2308 const char *keyfile, const char *keygrip,
2309 const char *sign_keygrip, int nopass,
2310 const char *outfile, const char *keyparam,
2311 uint64_t iterations)
2313 gpg_error_t rc;
2314 void *data = NULL;
2315 size_t datalen;
2316 struct crypto_s *crypto = NULL;
2317 uint16_t ver;
2318 int algo;
2319 void *key = NULL;
2320 size_t keylen = 0;
2322 if (outfile[0] == '-' && outfile[1] == 0)
2323 outfile = NULL;
2325 log_write (_("Converting version 2 data file \"%s\" ..."), filename);
2326 if (access (filename, R_OK) == -1)
2328 log_write ("%s: %s", filename,
2329 pwmd_strerror (gpg_error_from_errno (errno)));
2330 return 0;
2333 if (keyfile)
2335 log_write (_("Using passphrase file \"%s\" for decryption ..."),
2336 keyfile);
2337 if (access (keyfile, R_OK) == -1)
2339 log_write ("%s: %s", keyfile,
2340 pwmd_strerror (gpg_error_from_errno (errno)));
2341 return 0;
2345 rc = read_v2_datafile (filename, keyfile, &data, &datalen, &ver, &algo);
2346 if (rc)
2348 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2349 return 0;
2352 if (cipher)
2354 algo = cipher_string_to_gcrypt (cipher);
2355 if (algo == -1)
2357 rc = GPG_ERR_CIPHER_ALGO;
2358 goto fail;
2362 if (ver < 0x212)
2364 xmlDocPtr doc;
2366 rc = parse_doc (data, datalen, &doc);
2367 if (rc)
2368 goto fail;
2370 rc = convert_pre_212_elements (doc);
2371 gcry_free (data);
2372 data = NULL;
2373 if (!rc)
2375 xmlDocDumpFormatMemory (doc, (xmlChar **) & data, (int *) &datalen,
2377 if (!data)
2378 rc = GPG_ERR_ENOMEM;
2381 xmlFreeDoc (doc);
2382 if (rc)
2383 goto fail;
2386 rc = init_client_crypto (&crypto);
2387 if (!rc)
2389 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
2390 crypto->save.hdr.flags = set_cipher_flag (crypto->save.hdr.flags, algo);
2391 crypto->save.hdr.s2k_count = iterations;
2393 if (!use_agent)
2395 rc = export_common (NULL, 0, crypto, data, datalen, outfile, keyfile,
2396 &key, &keylen, 0, 0, nopass);
2398 #ifdef WITH_AGENT
2399 else
2401 rc = agent_set_pinentry_options (crypto->agent);
2402 if (!rc)
2403 rc = agent_export_common (crypto, keygrip, sign_keygrip, nopass,
2404 data, datalen, outfile, keyparam,
2405 no_passphrase_file ? NULL : keyfile);
2407 #endif
2408 if (!rc)
2409 log_write (_("Output written to \"%s\"."),
2410 outfile ? outfile : "<stdout>");
2413 fail:
2414 if (ver < 0x212)
2415 xmlFree (data);
2416 else
2417 gcry_free (data);
2419 gcry_free (key);
2420 cleanup_crypto (&crypto);
2422 if (rc)
2423 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2424 return rc ? 0 : 1;
2427 static void
2428 usage (const char *pn, int status)
2430 FILE *fp = status == EXIT_FAILURE ? stderr : stdout;
2432 fprintf (fp, _("Usage: %s [OPTIONS] [file1] [...]\n"
2433 " -f, --rcfile=filename load the specfied configuration file\n"
2434 " (~/.pwmd/config)\n"
2435 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2436 " --kill terminate an existing instance of pwmd\n"
2437 #ifdef WITH_AGENT
2438 " --use-agent[=integer] enable/disable use of gpg-agent\n"
2439 #endif
2440 " -n, --no-fork run as a foreground process\n"
2441 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2442 " --ignore, --force ignore file errors during startup\n"
2443 " --debug-level=keywords log protocol output (see manual for details)\n"
2444 " -o, --outfile=filename output file when importing or converting\n"
2445 " -C, --convert=filename convert a version 2 data file to version 3\n"
2446 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2447 " -k, --passphrase-file=file for use when importing or converting\n"
2448 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2449 " converting\n"
2450 " --no-passphrase when importing or converting\n"
2451 " --keygrip=hex public key to use when encrypting\n"
2452 " --sign-keygrip=hex private key to use when signing\n"
2453 " --keyparam=s-exp custom key parameters to use (RSA-2048)\n"
2454 " --cipher=string encryption cipher (aes256)\n"
2455 " --cipher-iterations=N cipher iteration count (alias for --s2k-count)\n"
2456 " --s2k-count=N hash iteration count (>65536, calibrated)\n"
2457 " --help this help text\n"
2458 " --version show version and compile time features\n"),
2459 pn);
2460 exit (status);
2463 static void
2464 unlink_stale_socket (const char *sock, const char *pidfile)
2466 log_write (_ ("removing stale socket %s"), sock);
2467 unlink (sock);
2468 unlink (pidfile);
2471 static int
2472 test_pidfile (const char *path, const char *sock, char *buf, size_t buflen,
2473 char **pidfile, int create, mode_t mode, int terminate)
2475 pid_t pid;
2476 int fd;
2477 size_t len;
2479 if (!create)
2481 snprintf (buf, buflen, "%s/%s.pid", homedir, sock);
2482 *pidfile = str_dup (buf);
2483 fd = open (buf, O_RDONLY);
2485 else
2486 fd = open (*pidfile, O_CREAT|O_WRONLY|O_TRUNC, mode);
2488 if (fd == -1)
2490 if (!create && errno != ENOENT)
2492 log_write ("%s: %s", buf, pwmd_strerror (errno));
2493 free (*pidfile);
2494 *pidfile = NULL;
2495 return -1;
2497 else if (!create && !terminate)
2498 return 0;
2500 log_write ("%s: %s", *pidfile, strerror (errno));
2501 return -1;
2504 if (create)
2506 snprintf (buf, buflen, "%i", getpid ());
2507 write (fd, buf, strlen (buf));
2508 close (fd);
2509 return 0;
2512 len = read (fd, buf, buflen);
2513 close (fd);
2514 if (len == 0)
2516 unlink_stale_socket (path, *pidfile);
2517 return 0;
2520 if (sscanf (buf, "%5i", &pid) != 1 || pid == 0)
2522 if (!terminate)
2524 unlink_stale_socket (path, *pidfile);
2525 return 0;
2529 if (kill (pid, 0) == -1)
2531 unlink_stale_socket (path, *pidfile);
2532 return 0;
2535 if (terminate)
2537 if (kill (pid, SIGTERM) == -1)
2538 log_write ("%s: %s", path, pwmd_strerror (errno));
2540 else
2541 log_write (_ ("an instance for socket %s is already running"), path);
2543 xfree (*pidfile);
2544 *pidfile = NULL;
2545 return 1;
2549 main (int argc, char *argv[])
2551 int opt;
2552 struct sockaddr_un addr;
2553 char buf[PATH_MAX];
2554 char *socketpath = NULL, *socketdir, *socketname = NULL;
2555 char *socketarg = NULL;
2556 char *datadir = NULL;
2557 char *pidfile = NULL;
2558 mode_t mode = 0600;
2559 int x;
2560 char *p;
2561 char **cache_push = NULL;
2562 char *import = NULL, *keygrip = NULL, *sign_keygrip = NULL;
2563 char *keyparam = NULL;
2564 int estatus = EXIT_FAILURE;
2565 int sockfd;
2566 char *outfile = NULL;
2567 int do_unlink = 0;
2568 int secure = 0;
2569 int show_version = 0;
2570 int force = 0;
2571 int no_passphrase = 0;
2572 gpg_error_t rc;
2573 char *convertfile = NULL;
2574 char *cipher = NULL;
2575 char *keyfile = NULL;
2576 uint64_t s2k_count = 0;
2577 int exists;
2578 char *debug_level_opt = NULL;
2579 int optindex;
2580 int terminate = 0;
2581 /* Must maintain the same order as longopts[] */
2582 enum
2584 OPT_VERSION, OPT_HELP,
2585 #ifdef WITH_AGENT
2586 OPT_AGENT,
2587 #endif
2588 OPT_DEBUG_LEVEL, OPT_HOMEDIR, OPT_NO_FORK, OPT_DISABLE_DUMP,
2589 OPT_IGNORE, OPT_FORCE, OPT_RCFILE, OPT_CONVERT,
2590 OPT_PASSPHRASE_FILE, OPT_IMPORT, OPT_OUTFILE,
2591 OPT_NO_PASSPHRASE_FILE, OPT_KEYGRIP, OPT_SIGN_KEYGRIP,
2592 OPT_KEYPARAM, OPT_CIPHER, OPT_ITERATIONS, OPT_S2K_COUNT,
2593 OPT_NO_PASSPHRASE, OPT_KILL
2595 const char *optstring = "nf:C:k:I:o:";
2596 const struct option longopts[] = {
2597 {"version", no_argument, 0, 0},
2598 {"help", no_argument, 0, 0},
2599 #ifdef WITH_AGENT
2600 {"use-agent", optional_argument, 0, 0},
2601 #endif
2602 {"debug-level", required_argument, 0, 0},
2603 {"homedir", required_argument, 0, 0},
2604 {"no-fork", no_argument, 0, 'n'},
2605 {"disable_dump", no_argument, 0, 0},
2606 {"ignore", no_argument, 0, 0},
2607 {"force", no_argument, 0, 0},
2608 {"rcfile", required_argument, 0, 'f'},
2609 {"convert", required_argument, 0, 'C'},
2610 {"passphrase-file", required_argument, 0, 'k'},
2611 {"import", required_argument, 0, 'I'},
2612 {"outfile", required_argument, 0, 'o'},
2613 {"no-passphrase-file", no_argument, 0, 0},
2614 {"keygrip", required_argument, 0, 0},
2615 {"sign-keygrip", required_argument, 0, 0},
2616 {"keyparam", required_argument, 0, 0},
2617 {"cipher", required_argument, 0, 0},
2618 {"cipher-iterations", required_argument, 0, 0},
2619 {"s2k-count", required_argument, 0, 0},
2620 {"no-passphrase", no_argument, 0, 0},
2621 {"kill", no_argument, 0, 0},
2622 {0, 0, 0, 0}
2625 log_fd = -1;
2627 #ifndef DEBUG
2628 #ifdef HAVE_SETRLIMIT
2629 struct rlimit rl;
2631 rl.rlim_cur = rl.rlim_max = 0;
2633 if (setrlimit (RLIMIT_CORE, &rl) != 0)
2634 err (EXIT_FAILURE, "setrlimit()");
2635 #endif
2637 #ifdef HAVE_PR_SET_DUMPABLE
2638 prctl (PR_SET_DUMPABLE, 0);
2639 #endif
2640 #endif
2642 #ifdef ENABLE_NLS
2643 setlocale (LC_ALL, "");
2644 bindtextdomain ("pwmd", LOCALEDIR);
2645 textdomain ("pwmd");
2646 #endif
2648 #ifndef MEM_DEBUG
2649 xmem_init ();
2650 #endif
2651 gpg_err_init ();
2653 if (setup_crypto ())
2654 exit (EXIT_FAILURE);
2656 #ifdef WITH_GNUTLS
2657 gnutls_global_init ();
2658 gnutls_global_set_log_level (1);
2659 gnutls_global_set_log_function (tls_log);
2660 gnutls_global_set_audit_log_function (tls_audit_log);
2661 tls_fd = -1;
2662 tls6_fd = -1;
2663 #endif
2664 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
2665 xmlInitMemory ();
2666 xmlInitGlobals ();
2667 xmlInitParser ();
2668 xmlXPathInit ();
2669 cmdline = 1;
2670 use_agent = -1;
2672 while ((opt = getopt_long (argc, argv, optstring, longopts, &optindex))
2673 != -1)
2675 switch (opt)
2677 case 'I':
2678 import = optarg;
2679 break;
2680 case 'C':
2681 convertfile = optarg;
2682 break;
2683 case 'k':
2684 keyfile = optarg;
2685 break;
2686 case 'o':
2687 outfile = optarg;
2688 break;
2689 case 'D':
2690 secure = 1;
2691 break;
2692 case 'n':
2693 nofork = 1;
2694 break;
2695 case 'f':
2696 rcfile = str_dup (optarg);
2697 break;
2698 default:
2699 usage (argv[0], EXIT_FAILURE);
2700 break;
2701 case 0:
2702 switch (optindex)
2704 case OPT_VERSION:
2705 show_version = 1;
2706 break;
2707 case OPT_HELP:
2708 usage (argv[0], 0);
2709 break;
2710 #ifdef WITH_AGENT
2711 case OPT_AGENT:
2712 use_agent = optarg && *optarg ? atoi (optarg) : 1;
2713 if (use_agent < 0 || use_agent > 1)
2714 usage (argv[0], 1);
2715 break;
2716 #endif
2717 case OPT_DEBUG_LEVEL:
2718 debug_level_opt = optarg;
2719 break;
2720 case OPT_HOMEDIR:
2721 homedir = str_dup (optarg);
2722 break;
2723 case OPT_NO_FORK:
2724 nofork = 1;
2725 break;
2726 case OPT_DISABLE_DUMP:
2727 secure = 1;
2728 break;
2729 case OPT_IGNORE:
2730 case OPT_FORCE:
2731 force = 1;
2732 break;
2733 case OPT_RCFILE:
2734 rcfile = str_dup (optarg);
2735 break;
2736 case OPT_CONVERT:
2737 convertfile = optarg;
2738 break;
2739 case OPT_PASSPHRASE_FILE:
2740 keyfile = optarg;
2741 break;
2742 case OPT_IMPORT:
2743 import = optarg;
2744 break;
2745 case OPT_OUTFILE:
2746 outfile = optarg;
2747 break;
2748 case OPT_NO_PASSPHRASE_FILE:
2749 no_passphrase_file = 1;
2750 break;
2751 case OPT_KEYGRIP:
2752 keygrip = optarg;
2753 break;
2754 case OPT_SIGN_KEYGRIP:
2755 sign_keygrip = optarg;
2756 break;
2757 case OPT_KEYPARAM:
2758 keyparam = optarg;
2759 break;
2760 case OPT_CIPHER:
2761 cipher = optarg;
2762 break;
2763 case OPT_ITERATIONS:
2764 case OPT_S2K_COUNT:
2765 s2k_count = strtoull (optarg, NULL, 10);
2766 break;
2767 case OPT_NO_PASSPHRASE:
2768 no_passphrase = 1;
2769 break;
2770 case OPT_KILL:
2771 terminate = 1;
2772 break;
2773 default:
2774 usage (argv[0], 1);
2779 if (show_version)
2781 printf (_("%s\n\n"
2782 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015\n"
2783 "%s\n"
2784 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2785 "Compile time features:\n%s"), PACKAGE_STRING,
2786 PACKAGE_BUGREPORT,
2787 #ifdef PWMD_HOMEDIR
2788 "+PWMD_HOMEDIR=" PWMD_HOMEDIR "\n"
2789 #endif
2790 #ifdef WITH_AGENT
2791 "+WITH_AGENT\n"
2792 #else
2793 "-WITH_AGENT\n"
2794 #endif
2795 #ifdef WITH_QUALITY
2796 "+WITH_QUALITY\n"
2797 #else
2798 "-WITH_QUALITY\n"
2799 #endif
2800 #ifdef WITH_GNUTLS
2801 "+WITH_GNUTLS\n"
2802 #else
2803 "-WITH_GNUTLS\n"
2804 #endif
2805 #ifdef DEBUG
2806 "+DEBUG\n"
2807 #else
2808 "-DEBUG\n"
2809 #endif
2810 #ifdef MEM_DEBUG
2811 "+MEM_DEBUG\n"
2812 #else
2813 "-MEM_DEBUG\n"
2814 #endif
2815 #ifdef MUTEX_DEBUG
2816 "+MUTEX_DEBUG\n"
2817 #else
2818 "-MUTEX_DEBUG\n"
2819 #endif
2821 exit (EXIT_SUCCESS);
2824 if (!homedir)
2825 #ifdef PWMD_HOMEDIR
2826 homedir = str_dup(PWMD_HOMEDIR);
2827 #else
2828 homedir = str_asprintf ("%s/.pwmd", get_home_dir());
2829 #endif
2831 if (mkdir (homedir, 0700) == -1 && errno != EEXIST)
2832 err (EXIT_FAILURE, "%s", homedir);
2834 snprintf (buf, sizeof (buf), "%s/data", homedir);
2835 if (mkdir (buf, 0700) == -1 && errno != EEXIST)
2836 err (EXIT_FAILURE, "%s", buf);
2838 datadir = str_dup (buf);
2839 pthread_mutexattr_t attr;
2840 pthread_mutexattr_init (&attr);
2841 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
2842 pthread_mutex_init (&rcfile_mutex, &attr);
2843 pthread_cond_init (&rcfile_cond, NULL);
2844 pthread_mutex_init (&cn_mutex, &attr);
2845 pthread_mutexattr_destroy (&attr);
2846 pthread_key_create (&last_error_key, free_key);
2847 #ifndef HAVE_PTHREAD_CANCEL
2848 pthread_key_create (&signal_thread_key, free_key);
2849 #endif
2851 if (!rcfile)
2852 rcfile = str_asprintf ("%s/config", homedir);
2854 global_config = config_parse (rcfile, 0);
2855 if (!global_config)
2856 exit (EXIT_FAILURE);
2858 #ifdef WITH_AGENT
2859 if (use_agent == -1)
2860 use_agent = config_get_boolean ("global", "use_agent");
2861 #endif
2863 setup_logging ();
2865 if (debug_level_opt)
2866 debug_level = str_split (debug_level_opt, ",", 0);
2868 x = config_get_int_param (global_config, "global", "priority", &exists);
2869 if (exists && x != atoi(INVALID_PRIORITY))
2871 errno = 0;
2872 if (setpriority (PRIO_PROCESS, 0, x) == -1)
2874 log_write ("setpriority(): %s",
2875 pwmd_strerror (gpg_error_from_errno (errno)));
2876 goto do_exit;
2879 #ifdef HAVE_MLOCKALL
2880 if (disable_mlock == 0 && mlockall (MCL_CURRENT | MCL_FUTURE) == -1)
2882 log_write ("mlockall(): %s",
2883 pwmd_strerror (gpg_error_from_errno (errno)));
2884 goto do_exit;
2886 #endif
2888 rc = cache_init (free_cache_data);
2889 if (rc)
2891 log_write ("pwmd: ERR %i: %s", rc,
2892 gpg_err_code (rc) == GPG_ERR_UNKNOWN_VERSION
2893 ? _("incompatible gpg-agent version: 2.1.0 or later required")
2894 : pwmd_strerror (rc));
2895 goto do_exit;
2898 if (s2k_count == 0)
2899 s2k_count = config_get_ulonglong (NULL, "s2k_count");
2901 if (convertfile)
2903 if (!outfile || !*outfile || argc != optind)
2904 usage (argv[0], EXIT_FAILURE);
2906 estatus = convert_v2_datafile (convertfile, cipher, keyfile, keygrip,
2907 sign_keygrip, no_passphrase, outfile,
2908 keyparam, s2k_count);
2909 config_free (global_config);
2910 xfree (rcfile);
2911 exit (!estatus);
2914 if (import)
2916 if (!outfile || !*outfile || argc != optind)
2917 usage (argv[0], EXIT_FAILURE);
2919 if (outfile && outfile[0] == '-' && outfile[1] == 0)
2920 outfile = NULL;
2922 estatus = xml_import (import, outfile, keygrip, sign_keygrip, keyfile,
2923 no_passphrase, cipher, keyparam, s2k_count);
2924 config_free (global_config);
2925 xfree (rcfile);
2926 exit (!estatus);
2929 p = config_get_string ("global", "socket_path");
2930 if (!p)
2931 p = str_asprintf ("%s/socket", homedir);
2933 socketarg = expand_homedir (p);
2934 xfree (p);
2936 if (!secure)
2937 disable_list_and_dump = config_get_boolean ("global",
2938 "disable_list_and_dump");
2939 else
2940 disable_list_and_dump = secure;
2942 cache_push = config_get_list ("global", "cache_push");
2944 while (optind < argc)
2946 if (strv_printf (&cache_push, "%s", argv[optind++]) == 0)
2947 errx (EXIT_FAILURE, "%s", pwmd_strerror (GPG_ERR_ENOMEM));
2950 if (strchr (socketarg, '/') == NULL)
2952 socketdir = getcwd (buf, sizeof (buf));
2953 socketname = str_dup (socketarg);
2954 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2956 else
2958 socketname = str_dup (strrchr (socketarg, '/'));
2959 socketname++;
2960 socketarg[strlen (socketarg) - strlen (socketname) - 1] = 0;
2961 socketdir = str_dup (socketarg);
2962 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2965 if (chdir (datadir))
2967 log_write ("%s: %s", datadir,
2968 pwmd_strerror (gpg_error_from_errno (errno)));
2969 unlink (socketpath);
2970 goto do_exit;
2973 x = test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 0,
2974 mode, terminate);
2975 if (!terminate && x)
2976 goto do_exit;
2977 else if (terminate)
2979 estatus = x != 1 ? EXIT_FAILURE : EXIT_SUCCESS;
2980 goto do_exit;
2984 * bind() doesn't like the full pathname of the socket or any non alphanum
2985 * characters so change to the directory where the socket is wanted then
2986 * create it then change to datadir.
2988 if (chdir (socketdir))
2990 log_write ("%s: %s", socketdir,
2991 pwmd_strerror (gpg_error_from_errno (errno)));
2992 goto do_exit;
2995 xfree (socketdir);
2997 if ((sockfd = socket (PF_UNIX, SOCK_STREAM, 0)) == -1)
2999 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
3000 goto do_exit;
3003 addr.sun_family = AF_UNIX;
3004 snprintf (addr.sun_path, sizeof (addr.sun_path), "%s", socketname);
3005 do_unlink = 1;
3006 if (bind (sockfd, (struct sockaddr *) &addr, sizeof (struct sockaddr)) ==
3009 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
3011 if (errno == EADDRINUSE)
3013 do_unlink = 0;
3014 log_write (_("Either there is another pwmd running or '%s' is a \n"
3015 "stale socket. Please remove it manually."), socketpath);
3018 goto do_exit;
3022 char *t = config_get_string ("global", "socket_perms");
3023 mode_t mask;
3025 if (t)
3027 mode = strtol (t, NULL, 8);
3028 mask = umask (0);
3029 xfree (t);
3031 if (chmod (socketname, mode) == -1)
3033 log_write ("%s: %s", socketname,
3034 pwmd_strerror (gpg_error_from_errno (errno)));
3035 close (sockfd);
3036 umask (mask);
3037 goto do_exit;
3040 umask (mask);
3044 xfree (--socketname);
3046 if (chdir (datadir))
3048 log_write ("%s: %s", datadir,
3049 pwmd_strerror (gpg_error_from_errno (errno)));
3050 close (sockfd);
3051 goto do_exit;
3054 xfree (datadir);
3057 * Set the cache entry for a file. Prompts for the password.
3059 if (cache_push)
3061 struct crypto_s *crypto = NULL;
3062 gpg_error_t rc = init_client_crypto (&crypto);
3064 if (rc)
3066 estatus = EXIT_FAILURE;
3067 goto do_exit;
3070 #ifdef WITH_AGENT
3071 if (use_agent)
3073 rc = agent_set_pinentry_options (crypto->agent);
3074 if (rc)
3076 estatus = EXIT_FAILURE;
3077 goto do_exit;
3080 #endif
3082 for (opt = 0; cache_push[opt]; opt++)
3084 if (!do_cache_push (cache_push[opt], crypto) && !force)
3086 strv_free (cache_push);
3087 startup_failure ();
3088 estatus = EXIT_FAILURE;
3089 cleanup_crypto (&crypto);
3090 goto do_exit;
3093 cleanup_crypto_stage1 (crypto);
3096 #ifdef WITH_AGENT
3097 if (use_agent)
3098 (void) kill_scd (crypto->agent);
3099 #endif
3101 cleanup_crypto (&crypto);
3102 strv_free (cache_push);
3103 log_write (!nofork ? _("Done. Daemonizing...") :
3104 _("Done. Waiting for connections..."));
3107 config_clear_keys ();
3109 if (listen (sockfd, 0) == -1)
3111 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
3112 goto do_exit;
3115 if (!nofork)
3117 switch (fork ())
3119 case -1:
3120 log_write ("fork(): %s",
3121 pwmd_strerror (gpg_error_from_errno (errno)));
3122 goto do_exit;
3123 case 0:
3124 close (0);
3125 close (1);
3126 close (2);
3127 setsid ();
3128 break;
3129 default:
3130 _exit (EXIT_SUCCESS);
3134 (void)test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 1,
3135 mode, 0);
3136 cmdline = 0;
3137 pthread_key_create (&thread_name_key, free_key);
3138 pthread_setspecific (thread_name_key, str_dup ("main"));
3139 estatus = server_loop (sockfd, &socketpath);
3141 do_exit:
3142 if (socketpath && do_unlink)
3144 unlink (socketpath);
3145 xfree (socketpath);
3148 xfree (socketarg);
3149 #ifdef WITH_GNUTLS
3150 gnutls_global_deinit ();
3151 #endif
3152 if (rcfile_tid)
3154 #ifdef HAVE_PTHREAD_CANCEL
3155 pthread_cancel (rcfile_tid);
3156 #else
3157 pthread_kill (rcfile_tid, SIGUSR2);
3158 pthread_cond_signal (&rcfile_cond);
3159 #endif
3160 pthread_join (rcfile_tid, NULL);
3163 pthread_cond_destroy (&rcfile_cond);
3164 pthread_mutex_destroy (&rcfile_mutex);
3165 pthread_key_delete (last_error_key);
3166 #ifndef HAVE_PTHREAD_CANCEL
3167 pthread_key_delete (signal_thread_key);
3168 #endif
3170 if (global_config)
3171 config_free (global_config);
3173 free_invoking_users (invoking_users);
3174 xfree (rcfile);
3175 xfree (home_directory);
3176 xfree (homedir);
3177 xmlCleanupParser ();
3178 xmlCleanupGlobals ();
3180 if (pidfile)
3181 unlink (pidfile);
3182 xfree (pidfile);
3184 if (estatus == EXIT_SUCCESS && !terminate)
3185 log_write (_("pwmd exiting normally"));
3187 pthread_key_delete (thread_name_key);
3188 closelog ();
3189 #if defined(DEBUG) && !defined(MEM_DEBUG)
3190 xdump ();
3191 #endif
3193 if (log_fd != -1)
3194 close (log_fd);
3196 exit (estatus);