Fix cache pushing.
[pwmd.git] / src / pwmd.c
blob8cc825a41aa1bc051da096ebfd698701282314dd
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>
51 #include <poll.h>
53 #ifdef TM_IN_SYS_TIME
54 #include <sys/time.h>
55 #else
56 #include <time.h>
57 #endif
59 #ifdef HAVE_LIMITS_H
60 #include <limits.h>
61 #endif
63 #ifdef HAVE_GETOPT_LONG
64 #ifdef HAVE_GETOPT_H
65 #include <getopt.h>
66 #endif
67 #else
68 #include "getopt_long.h"
69 #endif
71 #ifdef HAVE_PR_SET_NAME
72 #include <sys/prctl.h>
73 #endif
75 #include "pwmd-error.h"
76 #include <gcrypt.h>
78 #include "util-misc.h"
79 #include "mem.h"
80 #include "xml.h"
81 #include "common.h"
82 #include "commands.h"
83 #include "cache.h"
84 #include "util-string.h"
85 #include "mutex.h"
86 #include "rcfile.h"
87 #include "crypto.h"
88 #include "convert.h"
89 #include "pinentry.h"
91 /* In tenths of a second. */
92 #define SIG_TIMEOUT 1
94 /* For (tcp_)accept_thread (usec). */
95 #define ACCEPT_TIMEOUT 30000
97 static int quit;
98 static int exiting;
99 static int cmdline;
100 static jmp_buf jmp;
101 static int nofork;
102 static pthread_cond_t quit_cond;
103 static pthread_mutex_t quit_mutex;
104 static int no_passphrase_file = 0;
105 static pthread_t keepalive_tid;
106 static int log_fd;
108 #ifndef HAVE_PTHREAD_CANCEL
109 static pthread_key_t signal_thread_key;
110 #endif
112 #ifdef WITH_GNUTLS
113 static int tls_fd;
114 static int tls6_fd;
115 static pthread_t tls_tid;
116 static pthread_t tls6_tid;
117 static int spawned_tls;
118 static int spawned_tls6;
120 static int start_stop_tls (int term);
121 #endif
123 static int do_cache_push (const char *filename, struct crypto_s *crypto);
124 static int signal_loop (sigset_t sigset);
126 #ifndef HAVE_PTHREAD_CANCEL
127 #define INIT_THREAD_SIGNAL do { \
128 struct sigaction act; \
129 sigset_t sigset; \
130 sigemptyset (&sigset); \
131 sigaddset (&sigset, SIGUSR2); \
132 pthread_sigmask (SIG_UNBLOCK, &sigset, NULL); \
133 memset (&act, 0, sizeof(act)); \
134 act.sa_flags = SA_SIGINFO; \
135 act.sa_mask = sigset; \
136 act.sa_sigaction = catch_thread_signal; \
137 sigaction (SIGUSR2, &act, NULL); \
138 } while (0)
140 static void
141 catch_thread_signal (int sig, siginfo_t *info, void *ctx)
143 int *n = (int *) pthread_getspecific (signal_thread_key);
145 *n = 1;
146 pthread_setspecific (signal_thread_key, n);
148 #endif
150 static void
151 cache_push_from_rcfile ()
153 struct crypto_s *crypto = NULL;
154 char **cache_push;
155 gpg_error_t rc = init_client_crypto (&crypto);
157 if (rc)
159 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
160 return;
163 #ifdef WITH_AGENT
164 if (use_agent)
166 rc = set_agent_option (crypto->agent, "pinentry-mode", "error");
167 if (rc)
169 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
170 return;
173 #endif
175 cache_push = config_get_list ("global", "cache_push");
176 if (cache_push)
178 char **p;
180 for (p = cache_push; *p; p++)
182 (void) do_cache_push (*p, crypto);
183 cleanup_crypto_stage1 (crypto);
186 strv_free (cache_push);
189 #ifdef WITH_AGENT
190 (void) kill_scd (crypto->agent);
191 #endif
192 cleanup_crypto (&crypto);
195 static void
196 setup_logging ()
198 int n = config_get_boolean ("global", "enable_logging");
200 if (n)
202 char *p = config_get_string ("global", "log_path");
204 if (!p || (logfile && p && log_fd != -1 && strcmp(p, logfile)))
206 if (log_fd != -1)
207 close (log_fd);
209 log_fd = -1;
212 xfree (logfile);
213 logfile = NULL;
214 if (p)
215 logfile = expand_homedir (p);
216 xfree (p);
218 else
220 xfree (logfile);
221 logfile = NULL;
222 if (log_fd != -1)
223 close(log_fd);
225 log_fd = -1;
228 log_syslog = config_get_boolean ("global", "syslog");
229 if (log_syslog == 1)
230 openlog ("pwmd", LOG_NDELAY | LOG_PID, LOG_DAEMON);
233 static void *
234 reload_rcfile_thread (void *arg)
236 #ifndef HAVE_PTHREAD_CANCEL
237 int *n = xmalloc (sizeof (int));
239 *n = 0;
240 pthread_setspecific (signal_thread_key, n);
241 INIT_THREAD_SIGNAL;
242 #endif
244 #ifdef HAVE_PR_SET_NAME
245 prctl (PR_SET_NAME, "reload rcfile");
246 #endif
247 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
248 MUTEX_LOCK (&rcfile_mutex);
249 pthread_cleanup_push (cleanup_mutex_cb, &rcfile_mutex);
251 for (;;)
253 struct slist_s *keep = NULL;
254 struct slist_s *config;
255 int b = disable_list_and_dump;
257 pthread_cond_wait (&rcfile_cond, &rcfile_mutex);
258 #ifndef HAVE_PTHREAD_CANCEL
259 int *cancel = (int *) pthread_getspecific (signal_thread_key);
260 if (*cancel)
261 break;
262 #endif
264 pthread_cleanup_push (cleanup_mutex_cb, &rcfile_mutex);
265 keep = config_keep_save ();
266 log_write (_("reloading configuration file '%s'"), rcfile);
268 config = config_parse (rcfile, 1);
269 if (config)
271 config_free (global_config);
272 global_config = config;
273 setup_logging ();
274 cache_push_from_rcfile ();
275 config_clear_keys ();
278 config_keep_restore (keep);
279 disable_list_and_dump = !disable_list_and_dump ? b : 1;
281 #ifdef WITH_GNUTLS
282 /* Kill existing listening threads since the configured listening
283 * protocols may have changed. */
284 start_stop_tls (1);
285 start_stop_tls (0);
286 #endif
287 pthread_cleanup_pop (0);
290 pthread_cleanup_pop (1);
291 return NULL;
294 gpg_error_t
295 send_error (assuan_context_t ctx, gpg_error_t e)
297 struct client_s *client = assuan_get_pointer (ctx);
299 if (gpg_err_source (e) == GPG_ERR_SOURCE_UNKNOWN)
300 e = gpg_error (e);
302 if (client)
303 client->last_rc = e;
305 if (!e)
306 return assuan_process_done (ctx, 0);
308 if (!ctx)
310 log_write ("ERR %i: %s", e, pwmd_strerror (e));
311 return e;
314 if (client && client->xml_error)
316 log_write ("%s", client->xml_error->message);
317 xfree (client->last_error);
318 client->last_error = NULL;
319 if (client->xml_error->message)
320 client->last_error = str_dup (client->xml_error->message);
322 e = assuan_process_done (ctx,
323 assuan_set_error (ctx, e,
324 client->xml_error->message ? client->xml_error->message : NULL));
325 xmlResetLastError ();
326 xmlResetError (client->xml_error);
327 xfree (client->xml_error);
328 client->xml_error = NULL;
329 return e;
332 return assuan_process_done (ctx,
333 assuan_set_error (ctx, e, pwmd_strerror (e)));
337 assuan_log_cb (assuan_context_t ctx, void *data, unsigned cat,
338 const char *msg)
340 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
341 int i, t;
342 int match = 0;
344 pthread_mutex_lock (&m);
345 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock, &m);
346 t = strv_length (debug_level);
348 for (i = 0; i < t; i++)
350 if (!strcasecmp (debug_level[i], (char *) "init")
351 && cat == ASSUAN_LOG_INIT)
353 match = 1;
354 break;
357 if (!strcasecmp (debug_level[i], (char *) "ctx")
358 && cat == ASSUAN_LOG_CTX)
360 match = 1;
361 break;
364 if (!strcasecmp (debug_level[i], (char *) "engine")
365 && cat == ASSUAN_LOG_ENGINE)
367 match = 1;
368 break;
371 if (!strcasecmp (debug_level[i], (char *) "data")
372 && cat == ASSUAN_LOG_DATA)
374 match = 1;
375 break;
378 if (!strcasecmp (debug_level[i], (char *) "sysio")
379 && cat == ASSUAN_LOG_SYSIO)
381 match = 1;
382 break;
385 if (!strcasecmp (debug_level[i], (char *) "control")
386 && cat == ASSUAN_LOG_CONTROL)
388 match = 1;
389 break;
393 if (match && msg)
395 if (logfile)
397 int fd;
399 if ((fd =
400 open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600)) == -1)
401 warn ("%s", logfile);
402 else
404 pthread_cleanup_push (cleanup_fd_cb, &fd);
405 write (fd, msg, strlen (msg));
406 pthread_cleanup_pop (1);
410 if (nofork)
412 fprintf (stderr, "%s%s", data ? (char *) data : "", msg);
413 fflush (stderr);
417 pthread_cleanup_pop (1);
418 return match;
421 void
422 log_write (const char *fmt, ...)
424 char *args;
425 va_list ap;
426 time_t now;
427 char buf[255];
428 pthread_t tid = pthread_self ();
429 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
431 if ((!logfile && !isatty (STDERR_FILENO) && !log_syslog) || !fmt)
432 return;
434 pthread_mutex_lock (&m);
435 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock, &m);
437 if (!cmdline && logfile && log_fd == -1)
439 log_fd = open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600);
440 if (log_fd == -1)
441 warn ("%s", logfile);
444 va_start (ap, fmt);
446 if (str_vasprintf (&args, fmt, ap) != -1)
448 if (cmdline)
450 pthread_cleanup_push (xfree, args);
451 fprintf (stderr, "pwmd: %s\n", args);
452 fflush (stderr);
453 pthread_cleanup_pop (1);
455 else
457 char *name = pthread_getspecific (thread_name_key);
458 char *line;
460 pthread_cleanup_push (xfree, args);
461 snprintf (buf, sizeof (buf), "%s(%p): ", name ? name : _("unknown"),
462 (pthread_t *) tid);
463 name = buf;
465 if (!cmdline && log_syslog && !nofork)
466 syslog (LOG_INFO, "%s%s", name, args);
468 time (&now);
469 struct tm *tm = localtime (&now);
470 char tbuf[21];
471 strftime (tbuf, sizeof (tbuf), "%b %d %Y %H:%M:%S ", tm);
472 tbuf[sizeof (tbuf) - 1] = 0;
474 if (args[strlen (args) - 1] == '\n')
475 args[strlen (args) - 1] = 0;
477 line = str_asprintf ("%s %i %s%s\n", tbuf, getpid (), name,
478 args);
479 pthread_cleanup_pop (1);
480 if (line)
482 pthread_cleanup_push (xfree, line);
483 if (logfile && log_fd != -1)
485 write (log_fd, line, strlen (line));
486 fsync (log_fd);
489 if (nofork)
491 fprintf (stdout, "%s", line);
492 fflush (stdout);
495 pthread_cleanup_pop (1);
500 va_end (ap);
501 pthread_cleanup_pop (0);
503 if (log_fd != -1 && log_keepopen <= 0)
505 close(log_fd);
506 log_fd = -1;
509 pthread_mutex_unlock (&m);
512 static gpg_error_t
513 setup_crypto ()
515 if (!gcry_check_version (GCRYPT_VERSION))
517 fprintf (stderr, _("gcry_check_version(): Incompatible libgcrypt. "
518 "Wanted %s, got %s.\n"), GCRYPT_VERSION,
519 gcry_check_version (NULL));
520 return GPG_ERR_UNKNOWN_VERSION;
523 gcry_set_allocation_handler (xmalloc, xmalloc, NULL, xrealloc, xfree);
524 return 0;
527 gpg_error_t
528 do_validate_peer (assuan_context_t ctx, const char *section,
529 assuan_peercred_t * peer)
531 char **users;
532 int allowed = 0;
533 gpg_error_t rc;
534 struct client_s *client = assuan_get_pointer (ctx);
536 if (!client)
537 return GPG_ERR_EACCES;
539 #ifdef WITH_GNUTLS
540 if (client->thd->remote)
541 return tls_validate_access (client, section);
542 #endif
544 rc = assuan_get_peercred (ctx, peer);
545 if (rc)
546 return rc;
548 users = config_get_list (section, "allowed");
549 if (users)
551 for (char **p = users; !rc && *p; p++)
553 rc = acl_check_common(client, *p, (*peer)->uid, (*peer)->gid,
554 &allowed);
557 strv_free (users);
560 return allowed && !rc ? 0 : rc ? rc : GPG_ERR_EACCES;
563 /* Test if uid is a member of group 'name'. Invert when 'not' is true. */
564 #ifdef HAVE_GETGRNAM_R
565 static gpg_error_t
566 acl_check_group (const char *name, uid_t uid, gid_t gid, int not, int *allowed)
568 char *buf;
569 struct group gr, *gresult;
570 size_t len = sysconf (_SC_GETGR_R_SIZE_MAX);
571 int err;
572 gpg_error_t rc = 0;
574 if (len == -1)
575 len = 16384;
577 buf = xmalloc (len);
578 if (!buf)
579 return GPG_ERR_ENOMEM;
581 err = getgrnam_r (name, &gr, buf, len, &gresult);
582 if (!err && 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; !rc && *t; t++)
597 char *tbuf;
598 struct passwd pw;
599 struct passwd *result = get_pwd_struct (*t, 0, &pw, &tbuf, &rc);
601 if (!rc && result && result->pw_uid == uid)
603 xfree (tbuf);
604 *allowed = !not;
605 break;
608 xfree (tbuf);
611 xfree (buf);
612 return rc;
614 else if (err)
615 rc = gpg_error_from_errno (err);
617 xfree (buf);
618 return rc ? rc : GPG_ERR_EACCES;
620 #else
621 static gpg_error_t
622 acl_check_group (const char *name, uid_t uid, gid_t gid, int not, int *allowed)
624 struct group *gresult;
625 gpg_error_t rc = 0;
627 errno = 0;
628 gresult = getgrnam (name);
629 if (!errno && gresult && gresult->gr_gid == gid)
631 *allowed = !not;
632 return 0;
634 else if (errno)
635 rc = gpg_error_from_syserror ();
637 for (char **t = gresult->gr_mem; !rc && *t; t++)
639 char *buf;
640 struct passwd pw;
641 struct passwd *result = get_pwd_struct (*t, 0, &pw, &buf, &rc);
643 if (!rc && result && result->pw_uid == uid)
645 xfree (buf);
646 *allowed = !not;
647 break;
650 xfree (buf);
653 return rc;
655 #endif
657 gpg_error_t
658 peer_is_invoker(struct client_s *client)
660 struct invoking_user_s *user;
661 int allowed = 0;
663 if (client->thd->state == CLIENT_STATE_UNKNOWN)
664 return GPG_ERR_EACCES;
666 for (user = invoking_users; user; user = user->next)
668 #ifdef WITH_GNUTLS
669 if (client->thd->remote)
671 if (user->type == INVOKING_TLS
672 && !strcmp(client->thd->tls->fp, user->id))
673 allowed = user->not ? 0 : 1;
675 continue;
677 #endif
679 if (user->type == INVOKING_GID)
681 gpg_error_t rc = acl_check_group (user->id,
682 client->thd->peer->uid,
683 client->thd->peer->gid,
684 user->not, &allowed);
685 if (rc)
686 return rc;
688 else if (user->type == INVOKING_UID && client->thd->peer->uid == user->uid)
689 allowed = user->not ? 0 : 1;
692 return allowed ? 0 : GPG_ERR_EACCES;
695 #ifdef HAVE_GETGRNAM_R
696 gpg_error_t
697 acl_check_common (struct client_s *client, const char *user, uid_t uid,
698 gid_t gid, int *allowed)
700 int not = 0;
701 int rw = 0;
702 int tls = 0;
703 gpg_error_t rc = 0;
705 if (!user || !*user)
706 return 0;
708 if (*user == '-' || *user == '!')
709 not = 1;
711 if (*user == '+') // not implemented yet
712 rw = 1;
714 if (*user == '#') // TLS fingerprint hash
715 tls = 1;
717 if (not || rw || tls)
718 user++;
720 if (tls)
722 #ifdef WITH_GNUTLS
723 if (client->thd->remote)
725 if (!strcasecmp (client->thd->tls->fp, user))
726 *allowed = !not;
729 return 0;
730 #else
731 return 0;
732 #endif
734 #ifdef WITH_GNUTLS
735 else if (client->thd->remote) // Remote client with no TLS in the ACL
736 return 0;
737 #endif
739 if (*user == '@') // all users in group
740 return acl_check_group (user+1, uid, gid, not, allowed);
741 else
743 char *buf;
744 struct passwd pw;
745 struct passwd *pwd = get_pwd_struct (user, 0, &pw, &buf, &rc);
747 if (!rc && pwd && pwd->pw_uid == uid)
748 *allowed = !not;
750 xfree (buf);
753 return rc;
755 #else
756 gpg_error_t
757 acl_check_common (struct client_s *client, const char *user, uid_t uid,
758 gid_t gid, int *allowed)
760 gpg_error_t rc = 0;
761 int not = 0;
762 int rw = 0;
763 int tls = 0;
765 if (!user || !*user)
766 return 0;
768 if (*user == '-' || *user == '!')
769 not = 1;
771 if (*user == '+') // not implemented yet
772 rw = 1;
774 if (*user == '#') // TLS fingerprint hash
775 tls = 1;
777 if (not || rw || tls)
778 user++;
780 if (tls)
782 #ifdef WITH_GNUTLS
783 if (client->thd->remote)
785 if (!strcasecmp (client->thd->tls->fp, user))
786 *allowed = !not;
789 return 0;
790 #else
791 return 0;
792 #endif
795 if (*user == '@') // all users in group
796 return acl_check_group (user+1, uid, gid, not, allowed);
797 else
799 char *buf;
800 struct passwd pw;
801 struct passwd *result = get_pwd_struct (user, 0, &pw, &buf, &rc);
803 if (!rc && result && result->pw_uid == uid)
804 *allowed = !not;
806 xfree (buf);
809 return rc;
811 #endif
813 static gpg_error_t
814 validate_peer (struct client_s *cl)
816 gpg_error_t rc;
818 #ifdef WITH_GNUTLS
819 if (cl->thd->remote)
820 return tls_validate_access (cl, NULL);
821 #endif
823 MUTEX_LOCK (&cn_mutex);
824 rc = do_validate_peer (cl->ctx, "global", &cl->thd->peer);
825 MUTEX_UNLOCK (&cn_mutex);
826 log_write ("peer %s: uid=%i, gid=%i, pid=%i, rc=%u",
827 !rc ? _("accepted") : _("rejected"), cl->thd->peer->uid,
828 cl->thd->peer->gid, cl->thd->peer->pid, rc);
829 return rc;
832 static void
833 xml_error_cb (void *data, xmlErrorPtr e)
835 struct client_s *client = data;
838 * Keep the first reported error as the one to show in the error
839 * description. Reset in send_error().
841 if (client->xml_error)
842 return;
844 client->xml_error = xcalloc (1, sizeof(xmlError));
845 xmlCopyError (e, client->xml_error);
848 static pid_t
849 hook_waitpid (assuan_context_t ctx, pid_t pid, int action,
850 int *status, int options)
852 return waitpid (pid, status, options);
855 static ssize_t
856 hook_read (assuan_context_t ctx, assuan_fd_t fd, void *data, size_t len)
858 #ifdef WITH_GNUTLS
859 struct client_s *client = assuan_get_pointer (ctx);
861 if (client->thd->remote)
862 return tls_read_hook (ctx, (int) fd, data, len);
863 #endif
865 return read ((int) fd, data, len);
868 static ssize_t
869 hook_write (assuan_context_t ctx, assuan_fd_t fd,
870 const void *data, size_t len)
872 #ifdef WITH_GNUTLS
873 struct client_s *client = assuan_get_pointer (ctx);
875 if (client->thd->remote)
876 return tls_write_hook (ctx, (int) fd, data, len);
877 #endif
879 return write ((int) fd, data, len);
882 static int
883 new_connection (struct client_s *cl)
885 gpg_error_t rc;
886 static struct assuan_malloc_hooks mhooks = { xmalloc, xrealloc, xfree };
887 static struct assuan_system_hooks shooks = {
888 ASSUAN_SYSTEM_HOOKS_VERSION,
889 __assuan_usleep,
890 __assuan_pipe,
891 __assuan_close,
892 hook_read,
893 hook_write,
894 //FIXME
895 NULL, //recvmsg
896 NULL, //sendmsg both are used for FD passing
897 __assuan_spawn,
898 hook_waitpid,
899 __assuan_socketpair,
900 __assuan_socket,
901 __assuan_connect
904 #ifdef WITH_GNUTLS
905 if (cl->thd->remote)
907 char *prio = config_get_string ("global", "tls_cipher_suite");
909 cl->thd->timeout = config_get_integer ("global", "tls_timeout");
910 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
911 return 0;
913 cl->thd->tls = tls_init (cl->thd->fd, cl->thd->timeout, prio);
914 xfree (prio);
915 if (!cl->thd->tls)
916 return 0;
918 #endif
920 rc = assuan_new_ext (&cl->ctx, GPG_ERR_SOURCE_DEFAULT, &mhooks,
921 debug_level ? assuan_log_cb : NULL, NULL);
922 if (rc)
923 goto fail;
925 assuan_ctx_set_system_hooks (cl->ctx, &shooks);
926 rc = assuan_init_socket_server (cl->ctx, cl->thd->fd, 2);
927 if (rc)
928 goto fail;
930 assuan_set_pointer (cl->ctx, cl);
931 assuan_set_hello_line (cl->ctx, PACKAGE_STRING);
932 rc = register_commands (cl->ctx);
933 if (rc)
934 goto fail;
936 rc = assuan_accept (cl->ctx);
937 if (rc)
938 goto fail;
940 rc = validate_peer (cl);
941 /* May not be implemented on all platforms. */
942 if (rc && gpg_err_code (rc) != GPG_ERR_ASS_GENERAL)
943 goto fail;
945 MUTEX_LOCK (&cn_mutex);
946 cl->thd->state = CLIENT_STATE_INIT;
947 MUTEX_UNLOCK (&cn_mutex);
948 rc = init_client_crypto (&cl->crypto);
949 if (rc)
950 goto fail;
952 #ifdef WITH_AGENT
953 if (use_agent)
954 cl->crypto->agent->client_ctx = cl->ctx;
955 #endif
957 cl->crypto->client_ctx = cl->ctx;
958 cl->lock_timeout = config_get_integer ("global", "lock_timeout");
959 xmlSetStructuredErrorFunc (cl, xml_error_cb);
960 return 1;
962 fail:
963 log_write ("%s", pwmd_strerror (rc));
964 return 0;
968 * This is called after a client_thread() terminates. Set with
969 * pthread_cleanup_push().
971 static void
972 cleanup_cb (void *arg)
974 struct client_thread_s *cn = arg;
975 struct client_s *cl = cn->cl;
977 MUTEX_LOCK (&cn_mutex);
978 cn_thread_list = slist_remove (cn_thread_list, cn);
979 MUTEX_UNLOCK (&cn_mutex);
981 if (cl)
983 unlock_flock (&cl->flock_fd);
984 cleanup_client (cl);
985 if (cl->xml_error)
986 xmlResetError (cl->xml_error);
988 xfree (cl->xml_error);
990 #ifdef WITH_GNUTLS
991 if (cn->tls)
993 gnutls_deinit (cn->tls->ses);
994 xfree (cn->tls->fp);
995 xfree (cn->tls);
997 #endif
999 if (!cn->atfork && cl->ctx)
1000 assuan_release (cl->ctx);
1001 else if (!cn->atfork && cl->thd && cl->thd->fd != -1)
1002 close (cl->thd->fd);
1004 if (cl->crypto)
1005 cleanup_crypto (&cl->crypto);
1007 pinentry_free_opts (&cl->pinentry_opts);
1008 xfree (cl);
1010 else
1012 if (cn->fd != -1)
1013 close (cn->fd);
1016 while (cn->msg_queue)
1018 struct status_msg_s *msg = cn->msg_queue;
1020 cn->msg_queue = msg->next;
1021 xfree (msg->line);
1022 xfree (msg);
1025 if (!cn->atfork && cn->status_msg_pipe[0] != -1)
1026 close (cn->status_msg_pipe[0]);
1028 if (!cn->atfork && cn->status_msg_pipe[1] != -1)
1029 close (cn->status_msg_pipe[1]);
1031 pthread_mutex_destroy (&cn->status_mutex);
1033 if (!cn->atfork)
1035 log_write (_("exiting, fd=%i"), cn->fd);
1036 send_status_all (STATUS_CLIENTS, NULL);
1039 xfree (cn->name);
1040 #ifdef WITH_GNUTLS
1041 xfree (cn->peeraddr);
1042 #endif
1043 xfree (cn);
1044 pthread_cond_signal (&quit_cond);
1047 void
1048 cleanup_all_clients (int atfork)
1050 /* This function may be called from pthread_atfork() which requires
1051 reinitialization. */
1052 if (atfork)
1054 pthread_mutexattr_t attr;
1056 pthread_mutexattr_init (&attr);
1057 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
1058 pthread_mutex_init (&cn_mutex, &attr);
1059 pthread_mutexattr_destroy (&attr);
1060 cache_mutex_init ();
1063 MUTEX_LOCK (&cn_mutex);
1065 while (slist_length (cn_thread_list))
1067 struct client_thread_s *thd = slist_nth_data (cn_thread_list, 0);
1069 thd->atfork = atfork;
1070 cleanup_cb (thd);
1073 exiting = 1;
1074 MUTEX_UNLOCK (&cn_mutex);
1075 cache_deinit (atfork);
1078 static gpg_error_t
1079 send_msg_queue (struct client_thread_s *thd)
1081 MUTEX_LOCK (&thd->status_mutex);
1082 gpg_error_t rc = 0;
1083 char c;
1085 read (thd->status_msg_pipe[0], &c, 1);
1086 thd->wrote_status = 0;
1088 while (thd->msg_queue)
1090 struct status_msg_s *msg = thd->msg_queue;
1092 #ifndef HAVE_PTHREAD_CANCEL
1093 if (thd->fd == -1)
1094 break;
1095 #endif
1097 thd->msg_queue = thd->msg_queue->next;
1098 MUTEX_UNLOCK (&thd->status_mutex);
1099 rc = send_status (thd->cl->ctx, msg->s, msg->line);
1100 MUTEX_LOCK (&thd->status_mutex);
1101 xfree (msg->line);
1102 xfree (msg);
1104 if (rc)
1105 break;
1108 MUTEX_UNLOCK (&thd->status_mutex);
1109 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1110 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
1112 return rc;
1115 static void *
1116 client_thread (void *data)
1118 struct client_thread_s *thd = data;
1119 struct client_s *cl = xcalloc (1, sizeof (struct client_s));
1121 #ifdef HAVE_PR_SET_NAME
1122 prctl (PR_SET_NAME, "client");
1123 #endif
1124 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1126 if (!cl)
1128 log_write ("%s(%i): %s", __FILE__, __LINE__,
1129 pwmd_strerror (GPG_ERR_ENOMEM));
1130 return NULL;
1133 MUTEX_LOCK (&cn_mutex);
1134 pthread_cleanup_push (cleanup_cb, thd);
1135 thd->cl = cl;
1136 cl->thd = thd;
1137 cl->flock_fd = -1;
1138 MUTEX_UNLOCK (&cn_mutex);
1140 if (new_connection (cl))
1142 int finished = 0;
1143 gpg_error_t rc;
1144 struct pollfd fds[2];
1146 fds[0].fd = thd->fd;
1147 fds[0].events = POLLIN;
1148 fds[1].fd = thd->status_msg_pipe[0];
1149 fds[1].events = POLLIN;
1151 send_status_all (STATUS_CLIENTS, NULL);
1152 rc = send_status (cl->ctx, STATUS_CACHE, NULL);
1153 if (rc)
1155 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
1156 finished = 1;
1159 while (!finished)
1161 int n;
1162 int eof;
1164 n = poll (fds, 2, -1);
1165 if (n == -1)
1167 log_write ("%s", strerror (errno));
1168 break;
1171 if (fds[1].revents & POLLIN)
1173 rc = send_msg_queue (thd);
1174 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1175 break;
1178 #ifdef HAVE_PTHREAD_CANCEL
1179 if (!(fds[0].revents & POLLIN))
1180 #else
1181 if (thd->fd != -1 && !(fds[0].revents & POLLIN))
1182 #endif
1183 continue;
1185 rc = assuan_process_next (cl->ctx, &eof);
1186 if (rc || eof)
1188 if (gpg_err_code (rc) == GPG_ERR_EOF || eof)
1189 break;
1191 log_write ("assuan_process_next(): rc=%i %s", rc,
1192 pwmd_strerror (rc));
1193 if (rc == gpg_error (GPG_ERR_ETIMEDOUT))
1194 break;
1196 rc = send_error (cl->ctx, rc);
1197 if (rc)
1199 log_write ("assuan_process_done(): rc=%i %s", rc,
1200 pwmd_strerror (rc));
1201 break;
1205 /* Since the msg queue pipe fd's are non-blocking, check for
1206 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1207 * client has already disconnected and will be converted to
1208 * GPG_ERR_EOF during assuan_process_next().
1210 rc = send_msg_queue (thd);
1211 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1212 break;
1216 /* Don't do pthread_exit() here because any set pthread_cleanup_push
1217 * functions would be called after a command failed but then the client
1218 * exited normally which may lead to a double free. */
1219 pthread_cleanup_pop (1);
1220 return NULL;
1223 static int
1224 xml_import (const char *filename, const char *outfile,
1225 const char *keygrip, const char *sign_keygrip,
1226 const char *keyfile, int no_passphrase, const char *cipher,
1227 const char *params, uint64_t iterations)
1229 xmlDocPtr doc;
1230 int fd;
1231 struct stat st;
1232 int len;
1233 xmlChar *xmlbuf;
1234 xmlChar *xml;
1235 gpg_error_t rc;
1236 struct crypto_s *crypto = NULL;
1237 void *key = NULL;
1238 size_t keylen = 0;
1239 int algo = cipher ? cipher_string_to_gcrypt ((char *) cipher) :
1240 GCRY_CIPHER_AES256;
1242 if (algo == -1)
1244 log_write ("ERR %i: %s", gpg_error (GPG_ERR_CIPHER_ALGO),
1245 pwmd_strerror (GPG_ERR_CIPHER_ALGO));
1246 return 0;
1249 if (stat (filename, &st) == -1)
1251 log_write ("%s: %s", filename,
1252 pwmd_strerror (gpg_error_from_errno (errno)));
1253 return 0;
1256 rc = init_client_crypto (&crypto);
1257 if (rc)
1258 return 0;
1260 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
1261 crypto->save.hdr.flags = set_cipher_flag (crypto->save.hdr.flags, algo);
1262 log_write (_("Importing XML from '%s'. Output will be written to '%s' ..."),
1263 filename, outfile);
1265 if ((fd = open (filename, O_RDONLY)) == -1)
1267 log_write ("%s: %s", filename,
1268 pwmd_strerror (gpg_error_from_errno (errno)));
1269 goto fail;
1272 if ((xmlbuf = xmalloc (st.st_size + 1)) == NULL)
1274 close (fd);
1275 log_write ("%s(%i): %s", __FILE__, __LINE__,
1276 pwmd_strerror (GPG_ERR_ENOMEM));
1277 goto fail;
1280 if (read (fd, xmlbuf, st.st_size) == -1)
1282 rc = gpg_error_from_errno (errno);
1283 close (fd);
1284 log_write ("%s: %s", filename, pwmd_strerror (rc));
1285 goto fail;
1288 close (fd);
1289 xmlbuf[st.st_size] = 0;
1291 * Make sure the document validates.
1293 if ((doc = xmlReadDoc (xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS)) == NULL)
1295 log_write ("xmlReadDoc() failed");
1296 xfree (xmlbuf);
1297 goto fail;
1300 xfree (xmlbuf);
1301 xmlNodePtr n = xmlDocGetRootElement (doc);
1302 if (n && !xmlStrEqual (n->name, (xmlChar *) "pwmd"))
1304 log_write (_("Could not find root \"pwmd\" element."));
1305 rc = GPG_ERR_BAD_DATA;
1308 if (!rc)
1309 rc = validate_import (NULL, n ? n->children : n);
1311 if (rc)
1313 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1314 xmlFreeDoc (doc);
1315 goto fail;
1318 xmlDocDumpMemory (doc, &xml, &len);
1319 xmlFreeDoc (doc);
1320 crypto->save.hdr.s2k_count = iterations;
1321 if (!use_agent)
1323 rc = export_common (NULL, 0, crypto, xml, len, outfile, keyfile, &key,
1324 &keylen, 0, 0, no_passphrase);
1325 if (!rc)
1326 log_write (_("Success!"));
1328 #ifdef WITH_AGENT
1329 else
1331 rc = agent_set_pinentry_options (crypto->agent);
1332 if (!rc)
1333 rc = agent_export_common (crypto, keygrip, sign_keygrip, no_passphrase,
1334 xml, len, outfile, params, keyfile);
1336 #endif
1338 gcry_free (key);
1339 xmlFree (xml);
1340 if (rc)
1342 send_error (NULL, rc);
1343 goto fail;
1346 cleanup_crypto (&crypto);
1347 return 1;
1349 fail:
1350 cleanup_crypto (&crypto);
1351 return 0;
1354 static int
1355 do_cache_push (const char *filename, struct crypto_s *crypto)
1357 unsigned char md5file[16];
1358 gpg_error_t rc;
1359 void *key = NULL;
1360 size_t keylen = 0;
1361 xmlDocPtr doc;
1362 struct cache_data_s *cdata;
1363 unsigned char *crc;
1364 size_t len;
1365 int fd = -1;
1367 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1368 filename);
1370 if (valid_filename (filename) == 0)
1372 log_write (_("%s: Invalid characters in filename"), filename);
1373 return 0;
1376 rc = lock_flock (NULL, filename, LOCK_SH, &fd);
1377 if (!rc)
1378 rc = decrypt_common (NULL, 0, crypto, filename, &key, &keylen, NULL, NULL);
1379 if (rc)
1380 goto fail;
1382 rc = parse_doc ((char *) crypto->plaintext, crypto->plaintext_len, &doc);
1383 if (rc)
1385 xfree (key);
1386 goto fail;
1389 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
1390 cdata = xcalloc (1, sizeof (struct cache_data_s));
1391 if (!cdata)
1393 xmlFreeDoc (doc);
1394 xfree (key);
1395 goto fail;
1398 rc = get_checksum (filename, &crc, &len);
1399 unlock_flock (&fd);
1400 if (rc)
1402 xmlFreeDoc (doc);
1403 free_cache_data_once (cdata);
1404 goto fail;
1407 cdata->crc = crc;
1408 rc = encrypt_xml (NULL, cache_key, cache_keysize, GCRY_CIPHER_AES,
1409 crypto->plaintext, crypto->plaintext_len, &cdata->doc,
1410 &cdata->doclen, &cache_iv, &cache_blocksize);
1411 if (!rc && !IS_PKI (crypto))
1413 cdata->key = key;
1414 cdata->keylen = keylen;
1416 else
1417 xfree (key);
1419 if (rc)
1421 xmlFreeDoc (doc);
1422 free_cache_data_once (cdata);
1423 goto fail;
1426 #ifdef WITH_AGENT
1427 if (use_agent && IS_PKI (crypto))
1429 gcry_sexp_build ((gcry_sexp_t *) & cdata->pubkey, NULL, "%S",
1430 crypto->pkey_sexp);
1431 gcry_sexp_build ((gcry_sexp_t *) & cdata->sigkey, NULL, "%S",
1432 crypto->sigpkey_sexp);
1434 #endif
1436 unlock_flock (&fd);
1437 int timeout = config_get_integer (filename, "cache_timeout");
1438 cache_add_file (md5file, crypto->grip, cdata, timeout);
1439 log_write (_("Successfully added '%s' to the cache."), filename);
1440 return 1;
1442 fail:
1443 unlock_flock (&fd);
1444 log_write ("ERR %u: %s: %s", rc, filename, pwmd_strerror (rc));
1445 return 0;
1448 static gpg_error_t
1449 init_client (int fd, const char *addr)
1451 gpg_error_t rc = 0;
1452 struct client_thread_s *new = xcalloc (1, sizeof (struct client_thread_s));
1454 if (!new)
1456 close (fd);
1457 return GPG_ERR_ENOMEM;
1460 MUTEX_LOCK (&cn_mutex);
1461 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
1463 if (pipe (new->status_msg_pipe) == -1)
1464 rc = gpg_error_from_errno (errno);
1466 if (!rc)
1468 if (fcntl (new->status_msg_pipe[0], F_SETFL, O_NONBLOCK) == -1)
1469 rc = gpg_error_from_errno (errno);
1471 if (!rc)
1472 if (fcntl (new->status_msg_pipe[1], F_SETFL, O_NONBLOCK) == -1)
1473 rc = gpg_error_from_errno (errno);
1475 pthread_mutex_init (&new->status_mutex, NULL);
1478 if (!rc)
1480 #ifdef WITH_GNUTLS
1481 new->remote = addr ? 1 : 0;
1482 #endif
1483 new->fd = fd;
1484 rc = create_thread (client_thread, new, &new->tid, 1);
1485 if (rc)
1487 close (new->status_msg_pipe[0]);
1488 close (new->status_msg_pipe[1]);
1489 pthread_mutex_destroy (&new->status_mutex);
1493 if (!rc)
1495 struct slist_s *list = slist_append (cn_thread_list, new);
1497 if (list)
1499 cn_thread_list = list;
1500 if (addr)
1502 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1503 (pthread_t *) new->tid, fd, addr);
1504 #ifdef WITH_GNUTLS
1505 new->peeraddr = str_dup (addr);
1506 #endif
1508 else
1509 log_write (_("new connection: tid=%p, fd=%i"),
1510 (pthread_t *) new->tid, fd);
1512 else
1513 rc = GPG_ERR_ENOMEM;
1516 pthread_cleanup_pop (1);
1518 if (rc)
1520 xfree (new);
1521 close (fd);
1522 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1523 pwmd_strerror (rc));
1525 return rc;
1528 static void*
1529 keepalive_thread (void *arg)
1531 #ifndef HAVE_PTHREAD_CANCEL
1532 int *n = xmalloc (sizeof (int));
1534 *n = 0;
1535 pthread_setspecific (signal_thread_key, n);
1536 INIT_THREAD_SIGNAL;
1537 #endif
1539 #ifdef HAVE_PR_SET_NAME
1540 prctl (PR_SET_NAME, "keepalive");
1541 #endif
1542 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1544 for (;;)
1546 int n = config_get_integer ("global", "keepalive_interval");
1547 struct timeval tv = { n, 0 };
1548 #ifndef HAVE_PTHREAD_CANCEL
1549 int *sigusr2;
1551 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1552 if (*sigusr2)
1553 break;
1554 #endif
1556 send_status_all (STATUS_KEEPALIVE, NULL);
1557 select (0, NULL, NULL, NULL, &tv);
1560 return NULL;
1563 #ifdef WITH_GNUTLS
1564 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1565 static void *
1566 get_in_addr (struct sockaddr *sa)
1568 if (sa->sa_family == AF_INET)
1569 return &(((struct sockaddr_in *) sa)->sin_addr);
1571 return &(((struct sockaddr_in6 *) sa)->sin6_addr);
1574 static void *
1575 tcp_accept_thread (void *arg)
1577 int sockfd = *(int *) arg;
1578 #ifndef HAVE_PTHREAD_CANCEL
1579 int *n = xmalloc (sizeof (int));
1581 *n = 0;
1582 pthread_setspecific (signal_thread_key, n);
1583 INIT_THREAD_SIGNAL;
1584 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1585 #endif
1587 #ifdef HAVE_PR_SET_NAME
1588 prctl (PR_SET_NAME, "tcp_accept");
1589 #endif
1590 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1592 for (;;)
1594 struct sockaddr_storage raddr;
1595 socklen_t slen = sizeof (raddr);
1596 int fd;
1597 unsigned long n;
1598 char s[INET6_ADDRSTRLEN];
1599 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1600 #ifndef HAVE_PTHREAD_CANCEL
1601 int *sigusr2;
1603 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1604 if (*sigusr2)
1605 break;
1606 #endif
1608 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1609 if (fd == -1)
1611 if (errno == EMFILE || errno == ENFILE)
1612 log_write ("accept(): %s",
1613 pwmd_strerror (gpg_error_from_errno (errno)));
1614 else if (errno != EAGAIN)
1616 if (!quit) // probably EBADF
1617 log_write ("accept(): %s", strerror (errno));
1619 break;
1622 #ifndef HAVE_PTHREAD_CANCEL
1623 select (0, NULL, NULL, NULL, &tv);
1624 #endif
1625 continue;
1628 if (quit)
1630 close (fd);
1631 break;
1634 inet_ntop (raddr.ss_family, get_in_addr ((struct sockaddr *) &raddr),
1635 s, sizeof s);
1636 (void) init_client (fd, s);
1637 n = config_get_integer ("global", "tcp_wait");
1638 if (n > 0)
1640 tv.tv_sec = (n * 100000) / 100000;
1641 tv.tv_usec = (n * 100000) % 100000;
1642 select (0, NULL, NULL, NULL, &tv);
1646 return NULL;
1649 static int
1650 start_stop_tls_with_protocol (int ipv6, int term)
1652 struct addrinfo hints, *servinfo, *p;
1653 int port = config_get_integer ("global", "tcp_port");
1654 char buf[7];
1655 int n;
1656 gpg_error_t rc;
1657 int *fd = ipv6 ? &tls6_fd : &tls_fd;
1659 if (term || config_get_boolean ("global", "enable_tcp") == 0)
1661 if (tls6_fd != -1)
1663 if (spawned_tls6)
1665 #ifdef HAVE_PTHREAD_CANCEL
1666 pthread_cancel (tls6_tid);
1667 #else
1668 pthread_kill (tls6_tid, SIGUSR2);
1669 #endif
1670 pthread_join (tls6_tid, NULL);
1673 shutdown (tls6_fd, SHUT_RDWR);
1674 close (tls6_fd);
1675 tls6_fd = -1;
1676 spawned_tls6 = 0;
1679 if (tls_fd != -1)
1681 if (spawned_tls)
1683 #ifdef HAVE_PTHREAD_CANCEL
1684 pthread_cancel (tls_tid);
1685 #else
1686 pthread_kill (tls_tid, SIGUSR2);
1687 #endif
1688 pthread_join (tls_tid, NULL);
1691 shutdown (tls_fd, SHUT_RDWR);
1692 close (tls_fd);
1693 tls_fd = -1;
1694 spawned_tls = 0;
1697 /* A client may still be connected. */
1698 if (!quit && x509_cred != NULL)
1699 tls_deinit_params ();
1701 return 1;
1704 if ((ipv6 && tls6_fd != -1) || (!ipv6 && tls_fd != -1))
1705 return 1;
1707 memset (&hints, 0, sizeof (hints));
1708 hints.ai_family = ipv6 ? AF_INET6 : AF_INET;
1709 hints.ai_socktype = SOCK_STREAM;
1710 hints.ai_flags = AI_PASSIVE;
1711 snprintf (buf, sizeof (buf), "%i", port);
1713 if ((n = getaddrinfo (NULL, buf, &hints, &servinfo)) == -1)
1715 log_write ("getaddrinfo(): %s", gai_strerror (n));
1716 return 0;
1719 for (n = 0, p = servinfo; p != NULL; p = p->ai_next)
1721 int r = 1;
1723 if ((ipv6 && p->ai_family != AF_INET6)
1724 || (!ipv6 && p->ai_family != AF_INET))
1725 continue;
1727 if ((*fd = socket (p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
1729 log_write ("socket(): %s", strerror (errno));
1730 continue;
1733 if (setsockopt (*fd, SOL_SOCKET, SO_REUSEADDR, &r, sizeof (int)) == -1)
1735 log_write ("setsockopt(): %s",
1736 pwmd_strerror (gpg_error_from_errno (errno)));
1737 freeaddrinfo (servinfo);
1738 goto fail;
1741 if (bind (*fd, p->ai_addr, p->ai_addrlen) == -1)
1743 close (*fd);
1744 log_write ("bind(): %s",
1745 pwmd_strerror (gpg_error_from_errno (errno)));
1746 continue;
1749 n++;
1750 break;
1753 freeaddrinfo (servinfo);
1755 if (!n)
1756 goto fail;
1758 #if HAVE_DECL_SO_BINDTODEVICE != 0
1759 char *tmp = config_get_string ("global", "tcp_interface");
1760 if (tmp && setsockopt (*fd, SOL_SOCKET, SO_BINDTODEVICE, tmp,
1761 strlen (tmp)) == -1)
1763 log_write ("setsockopt(): %s",
1764 pwmd_strerror (gpg_error_from_errno (errno)));
1765 xfree (tmp);
1766 goto fail;
1769 xfree (tmp);
1770 #endif
1772 if (x509_cred == NULL)
1774 char *tmp = config_get_string ("global", "tls_dh_level");
1776 rc = tls_init_params (tmp);
1777 xfree (tmp);
1778 if (rc)
1779 goto fail;
1782 if (listen (*fd, 0) == -1)
1784 log_write ("listen(): %s", strerror (errno));
1785 goto fail;
1788 if (ipv6)
1789 rc = create_thread (tcp_accept_thread, fd, &tls6_tid, 0);
1790 else
1791 rc = create_thread (tcp_accept_thread, fd, &tls_tid, 0);
1793 if (rc)
1795 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1796 pwmd_strerror (rc));
1797 goto fail;
1800 if (ipv6)
1801 spawned_tls6 = 1;
1802 else
1803 spawned_tls = 1;
1805 return 1;
1807 fail:
1808 start_stop_tls_with_protocol (0, 1);
1809 if (tls_fd != -1)
1810 close (tls_fd);
1812 if (tls6_fd != -1)
1813 close (tls6_fd);
1815 tls_fd = -1;
1816 tls6_fd = -1;
1817 return 0;
1820 static int
1821 start_stop_tls (int term)
1823 char *s = config_get_string ("global", "tcp_bind");
1824 int b;
1826 if (!s)
1827 return 0;
1829 if (!strcmp (s, "any"))
1831 b = start_stop_tls_with_protocol (0, term);
1832 if (b)
1833 b = start_stop_tls_with_protocol (1, term);
1835 else if (!strcmp (s, "ipv4"))
1836 b = start_stop_tls_with_protocol (0, term);
1837 else if (!strcmp (s, "ipv6"))
1838 b = start_stop_tls_with_protocol (1, term);
1839 else
1840 b = 0;
1842 xfree (s);
1843 return b;
1845 #endif
1847 static void *
1848 accept_thread (void *arg)
1850 int sockfd = *(int *) arg;
1851 #ifndef HAVE_PTHREAD_CANCEL
1852 int *n = xmalloc (sizeof (int));
1854 *n = 0;
1855 pthread_setspecific (signal_thread_key, n);
1856 INIT_THREAD_SIGNAL;
1857 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1858 #endif
1860 #ifdef HAVE_PR_SET_NAME
1861 prctl (PR_SET_NAME, "accept");
1862 #endif
1863 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1865 for (;;)
1867 socklen_t slen = sizeof (struct sockaddr_un);
1868 struct sockaddr_un raddr;
1869 int fd;
1870 #ifndef HAVE_PTHREAD_CANCEL
1871 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1872 int *sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1874 if (*sigusr2)
1875 break;
1876 #endif
1878 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1879 if (fd == -1)
1881 if (errno == EMFILE || errno == ENFILE)
1882 log_write ("accept(): %s",
1883 pwmd_strerror (gpg_error_from_errno (errno)));
1884 else if (errno != EAGAIN)
1886 if (!quit) // probably EBADF
1887 log_write ("accept(): %s",
1888 pwmd_strerror (gpg_error_from_errno (errno)));
1890 break;
1893 #ifndef HAVE_PTHREAD_CANCEL
1894 select (0, NULL, NULL, NULL, &tv);
1895 #endif
1896 continue;
1899 (void) init_client (fd, NULL);
1902 /* Just in case accept() failed for some reason other than EBADF */
1903 quit = 1;
1904 return NULL;
1907 static void *
1908 cache_timer_thread (void *arg)
1910 #ifndef HAVE_PTHREAD_CANCEL
1911 int *n = xmalloc (sizeof (int));
1913 *n = 0;
1914 pthread_setspecific (signal_thread_key, n);
1915 INIT_THREAD_SIGNAL;
1916 #endif
1918 #ifdef HAVE_PR_SET_NAME
1919 prctl (PR_SET_NAME, "cache timer");
1920 #endif
1921 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1923 for (;;)
1925 struct timeval tv = { 1, 0 };
1926 #ifndef HAVE_PTHREAD_CANCEL
1927 int *n;
1929 n = (int *) pthread_getspecific (signal_thread_key);
1930 if (*n)
1931 break;
1932 #endif
1934 select (0, NULL, NULL, NULL, &tv);
1935 cache_adjust_timeout ();
1938 return NULL;
1941 static int
1942 signal_loop (sigset_t sigset)
1944 int done = 0;
1945 int siint = 0;
1949 int sig;
1951 sigwait (&sigset, &sig);
1953 if (sig != SIGQUIT)
1954 log_write (_("caught signal %i (%s)"), sig, strsignal (sig));
1956 switch (sig)
1958 case SIGHUP:
1959 pthread_cond_signal (&rcfile_cond);
1960 break;
1961 case SIGUSR1:
1962 log_write (_("clearing file cache"));
1963 cache_clear (NULL);
1964 send_status_all (STATUS_CACHE, NULL);
1965 break;
1966 case SIGQUIT:
1967 done = 1;
1968 break;
1969 default:
1970 siint = 1;
1971 done = 1;
1972 break;
1975 while (!done);
1977 return siint;
1980 static void
1981 catchsig (int sig)
1983 log_write (_ ("Caught signal %i (%s). Exiting."), sig, strsignal (sig));
1984 #ifdef HAVE_BACKTRACE
1985 BACKTRACE (__FUNCTION__);
1986 #endif
1987 longjmp (jmp, 1);
1990 static void *
1991 waiting_for_exit (void *arg)
1993 int last = 0;
1994 #ifndef HAVE_PTHREAD_CANCEL
1995 int *n = xmalloc (sizeof (int));
1997 *n = 0;
1998 pthread_setspecific (signal_thread_key, n);
1999 INIT_THREAD_SIGNAL;
2000 #endif
2002 #ifdef HAVE_PR_SET_NAME
2003 prctl (PR_SET_NAME, "exiting");
2004 #endif
2005 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
2006 log_write (_("waiting for all clients to disconnect"));
2007 MUTEX_LOCK (&quit_mutex);
2008 pthread_cleanup_push (cleanup_mutex_cb, &quit_mutex);
2010 for (;;)
2012 struct timespec ts;
2013 int n;
2015 MUTEX_LOCK (&cn_mutex);
2016 n = slist_length (cn_thread_list);
2017 MUTEX_UNLOCK (&cn_mutex);
2018 if (!n)
2019 break;
2021 #ifndef HAVE_PTHREAD_CANCEL
2022 int *s = (int *) pthread_getspecific (signal_thread_key);
2023 if (*s)
2024 break;
2025 #endif
2027 if (last != n)
2029 log_write (_("%i clients remain"), n);
2030 last = n;
2033 INIT_TIMESPEC (SIG_TIMEOUT, ts);
2034 pthread_cond_timedwait (&quit_cond, &quit_mutex, &ts);
2037 kill (getpid (), SIGQUIT);
2038 pthread_cleanup_pop (1);
2039 return NULL;
2042 static int
2043 server_loop (int sockfd, char **socketpath)
2045 pthread_t accept_tid;
2046 pthread_t cache_timeout_tid;
2047 int cancel_timeout_thread = 0, cancel_accept_thread = 0;
2048 int cancel_keepalive_thread = 0;
2049 sigset_t sigset;
2050 int n;
2051 int segv = 0;
2052 gpg_error_t rc;
2054 init_commands ();
2055 sigemptyset (&sigset);
2057 /* Termination */
2058 sigaddset (&sigset, SIGTERM);
2059 sigaddset (&sigset, SIGINT);
2061 /* Clears the file cache. */
2062 sigaddset (&sigset, SIGUSR1);
2064 /* Configuration file reloading. */
2065 sigaddset (&sigset, SIGHUP);
2067 /* For exiting cleanly. */
2068 sigaddset (&sigset, SIGQUIT);
2070 #ifndef HAVE_PTHREAD_CANCEL
2072 The socket, cache and rcfile threads use this signal when
2073 pthread_cancel() is unavailable. Prevent the main thread from
2074 catching this signal from another process.
2076 sigaddset (&sigset, SIGUSR2);
2077 #endif
2079 /* When mem.c cannot find a pointer in the list (double free). */
2080 signal (SIGABRT, catchsig);
2081 sigaddset (&sigset, SIGABRT);
2082 sigprocmask (SIG_BLOCK, &sigset, NULL);
2084 #ifndef HAVE_PTHREAD_CANCEL
2085 /* Remove this signal from the watched signals in signal_loop(). */
2086 sigdelset (&sigset, SIGUSR2);
2087 #endif
2089 /* Ignored everywhere. When a client disconnects abnormally this signal
2090 * gets raised. It isn't needed though because client_thread() will check
2091 * for rcs even after the client disconnects. */
2092 signal (SIGPIPE, SIG_IGN);
2094 /* Can show a backtrace of the stack in the log. */
2095 signal (SIGSEGV, catchsig);
2097 #ifdef WITH_GNUTLS
2098 /* Needs to be done after the fork(). */
2099 if (!start_stop_tls (0))
2101 segv = 1;
2102 goto done;
2104 #endif
2106 pthread_mutex_init (&quit_mutex, NULL);
2107 pthread_cond_init (&quit_cond, NULL);
2108 char *p = get_username (getuid());
2109 log_write (_("%s started for user %s"), PACKAGE_STRING, p);
2110 xfree (p);
2112 #ifdef WITH_GNUTLS
2113 if (config_get_boolean ("global", "enable_tcp"))
2114 log_write (_("Listening on %s and TCP port %i"), *socketpath,
2115 config_get_integer ("global", "tcp_port"));
2116 else
2117 log_write (_("Listening on %s"), *socketpath);
2118 #else
2119 log_write (_("Listening on %s"), *socketpath);
2120 #endif
2122 rc = create_thread (keepalive_thread, NULL, &keepalive_tid, 0);
2123 if (rc)
2125 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2126 pwmd_strerror (rc));
2127 goto done;
2130 cancel_keepalive_thread = 1;
2131 rc = create_thread (reload_rcfile_thread, NULL, &rcfile_tid, 0);
2132 if (rc)
2134 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2135 pwmd_strerror (rc));
2136 goto done;
2139 rc = create_thread (cache_timer_thread, NULL, &cache_timeout_tid, 0);
2140 if (rc)
2142 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2143 pwmd_strerror (rc));
2144 goto done;
2147 cancel_timeout_thread = 1;
2148 rc = create_thread (accept_thread, &sockfd, &accept_tid, 0);
2149 if (rc)
2151 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2152 pwmd_strerror (rc));
2153 goto done;
2156 cancel_accept_thread = 1;
2157 if (!setjmp (jmp))
2158 signal_loop (sigset);
2159 else
2160 segv = 1;
2162 done:
2164 * We're out of the main server loop. This happens when a signal was sent
2165 * to terminate the daemon. We'll wait for all clients to disconnect
2166 * before exiting but exit immediately if another termination signal is
2167 * sent.
2169 if (cancel_accept_thread)
2171 #ifdef HAVE_PTHREAD_CANCEL
2172 int n = pthread_cancel (accept_tid);
2173 #else
2174 int n = pthread_kill (accept_tid, SIGUSR2);
2175 #endif
2176 if (!n)
2177 pthread_join (accept_tid, NULL);
2180 #ifdef WITH_GNUTLS
2181 start_stop_tls (1);
2182 #endif
2183 shutdown (sockfd, SHUT_RDWR);
2184 close (sockfd);
2185 unlink (*socketpath);
2186 xfree (*socketpath);
2187 *socketpath = NULL;
2188 MUTEX_LOCK (&cn_mutex);
2189 n = slist_length (cn_thread_list);
2190 MUTEX_UNLOCK (&cn_mutex);
2192 if (n && !segv)
2194 pthread_t tid;
2196 rc = create_thread (waiting_for_exit, NULL, &tid, 0);
2197 if (!rc)
2199 if (signal_loop (sigset))
2201 log_write (_("Received second termination request. Exiting."));
2202 #ifdef HAVE_PTHREAD_CANCEL
2203 pthread_cancel (tid);
2204 #else
2205 pthread_kill (tid, SIGUSR2);
2206 #endif
2207 pthread_join (tid, NULL);
2210 else
2211 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2212 pwmd_strerror (rc));
2215 if (cancel_timeout_thread)
2217 #ifdef HAVE_PTHREAD_CANCEL
2218 pthread_cancel (cache_timeout_tid);
2219 #else
2220 pthread_kill (cache_timeout_tid, SIGUSR2);
2221 #endif
2222 pthread_join (cache_timeout_tid, NULL);
2225 if (cancel_keepalive_thread)
2227 #ifdef HAVE_PTHREAD_CANCEL
2228 pthread_cancel (keepalive_tid);
2229 #else
2230 pthread_kill (keepalive_tid, SIGUSR2);
2231 #endif
2232 pthread_join (keepalive_tid, NULL);
2235 cleanup_all_clients (0);
2236 #ifdef WITH_GNUTLS
2237 start_stop_tls (1);
2238 #endif
2239 deinit_commands ();
2240 pthread_cond_destroy (&quit_cond);
2241 pthread_mutex_destroy (&quit_mutex);
2242 return segv ? EXIT_FAILURE : EXIT_SUCCESS;;
2245 static void
2246 startup_failure ()
2248 log_write (_
2249 ("Failed to add a file to the cache. Use --force to force startup. Exiting."));
2250 cache_clear (NULL);
2253 /* This is called from cache.c:clear_once(). See
2254 * command.c:clearcache_command() for details about lock checking.
2256 static gpg_error_t
2257 free_cache_data (file_cache_t * cache)
2259 gpg_error_t rc = GPG_ERR_NO_DATA;
2260 int i, t;
2261 struct client_thread_s *found = NULL;
2262 int self = 0;
2264 if (!cache->data)
2265 return 0;
2267 cache_lock ();
2268 MUTEX_LOCK (&cn_mutex);
2269 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
2270 t = slist_length (cn_thread_list);
2272 for (i = 0; i < t; i++)
2274 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2276 if (!thd->cl)
2277 continue;
2279 if (!memcmp (thd->cl->md5file, cache->filename,
2280 sizeof (cache->filename)))
2282 if (pthread_equal (pthread_self (), thd->tid))
2284 found = thd;
2285 self = 1;
2286 continue;
2289 /* Continue trying to find a client who has the same file open and
2290 * also has a lock. */
2291 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0, -1);
2292 if (!rc)
2294 self = 0;
2295 found = thd;
2296 break;
2301 if (self && (!rc || rc == GPG_ERR_NO_DATA))
2302 rc = cache_lock_mutex (found->cl->ctx, found->cl->md5file, -1, 0, -1);
2304 if (exiting || !rc || rc == GPG_ERR_NO_DATA)
2306 free_cache_data_once (cache->data);
2307 cache->data = NULL;
2308 cache->defer_clear = 0;
2309 cache->timeout = -1;
2311 if (found)
2312 cache_unlock_mutex (found->cl->md5file, 0);
2314 rc = 0;
2317 if (rc)
2318 cache->defer_clear = 1;
2320 pthread_cleanup_pop (1);
2321 cache_unlock ();
2322 return rc;
2325 static int
2326 convert_v2_datafile (const char *filename, const char *cipher,
2327 const char *keyfile, const char *keygrip,
2328 const char *sign_keygrip, int nopass,
2329 const char *outfile, const char *keyparam,
2330 uint64_t iterations)
2332 gpg_error_t rc;
2333 void *data = NULL;
2334 size_t datalen;
2335 struct crypto_s *crypto = NULL;
2336 uint16_t ver;
2337 int algo;
2338 void *key = NULL;
2339 size_t keylen = 0;
2341 if (outfile[0] == '-' && outfile[1] == 0)
2342 outfile = NULL;
2344 log_write (_("Converting version 2 data file \"%s\" ..."), filename);
2345 if (access (filename, R_OK) == -1)
2347 log_write ("%s: %s", filename,
2348 pwmd_strerror (gpg_error_from_errno (errno)));
2349 return 0;
2352 if (keyfile)
2354 log_write (_("Using passphrase file \"%s\" for decryption ..."),
2355 keyfile);
2356 if (access (keyfile, R_OK) == -1)
2358 log_write ("%s: %s", keyfile,
2359 pwmd_strerror (gpg_error_from_errno (errno)));
2360 return 0;
2364 rc = read_v2_datafile (filename, keyfile, &data, &datalen, &ver, &algo);
2365 if (rc)
2367 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2368 return 0;
2371 if (cipher)
2373 algo = cipher_string_to_gcrypt (cipher);
2374 if (algo == -1)
2376 rc = GPG_ERR_CIPHER_ALGO;
2377 goto fail;
2381 if (ver < 0x212)
2383 xmlDocPtr doc;
2385 rc = parse_doc (data, datalen, &doc);
2386 if (rc)
2387 goto fail;
2389 rc = convert_pre_212_elements (doc);
2390 gcry_free (data);
2391 data = NULL;
2392 if (!rc)
2394 xmlDocDumpFormatMemory (doc, (xmlChar **) & data, (int *) &datalen,
2396 if (!data)
2397 rc = GPG_ERR_ENOMEM;
2400 xmlFreeDoc (doc);
2401 if (rc)
2402 goto fail;
2405 rc = init_client_crypto (&crypto);
2406 if (!rc)
2408 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
2409 crypto->save.hdr.flags = set_cipher_flag (crypto->save.hdr.flags, algo);
2410 crypto->save.hdr.s2k_count = iterations;
2412 if (!use_agent)
2414 rc = export_common (NULL, 0, crypto, data, datalen, outfile, keyfile,
2415 &key, &keylen, 0, 0, nopass);
2417 #ifdef WITH_AGENT
2418 else
2420 rc = agent_set_pinentry_options (crypto->agent);
2421 if (!rc)
2422 rc = agent_export_common (crypto, keygrip, sign_keygrip, nopass,
2423 data, datalen, outfile, keyparam,
2424 no_passphrase_file ? NULL : keyfile);
2426 #endif
2427 if (!rc)
2428 log_write (_("Output written to \"%s\"."),
2429 outfile ? outfile : "<stdout>");
2432 fail:
2433 if (ver < 0x212)
2434 xmlFree (data);
2435 else
2436 gcry_free (data);
2438 gcry_free (key);
2439 cleanup_crypto (&crypto);
2441 if (rc)
2442 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2443 return rc ? 0 : 1;
2446 static void
2447 usage (const char *pn, int status)
2449 FILE *fp = status == EXIT_FAILURE ? stderr : stdout;
2451 fprintf (fp, _("Usage: %s [OPTIONS] [file1] [...]\n"
2452 " -f, --rcfile=filename load the specfied configuration file\n"
2453 " (~/.pwmd/config)\n"
2454 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2455 " --kill terminate an existing instance of pwmd\n"
2456 #ifdef WITH_AGENT
2457 " --use-agent[=integer] enable/disable use of gpg-agent\n"
2458 #endif
2459 " -n, --no-fork run as a foreground process\n"
2460 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2461 " --force ignore file errors during startup\n"
2462 " --debug-level=keywords log protocol output (see manual for details)\n"
2463 " -o, --outfile=filename output file when importing or converting\n"
2464 " -C, --convert=filename convert a version 2 data file to version 3\n"
2465 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2466 " -k, --passphrase-file=file for use when importing or converting\n"
2467 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2468 " converting\n"
2469 " --no-passphrase when importing or converting\n"
2470 " --keygrip=hex public key to use when encrypting\n"
2471 " --sign-keygrip=hex private key to use when signing\n"
2472 " --keyparam=s-exp custom key parameters to use (RSA-2048)\n"
2473 " --cipher=string encryption cipher (aes256)\n"
2474 " --cipher-iterations=N cipher iteration count (alias for --s2k-count)\n"
2475 " --s2k-count=N hash iteration count (>65536, calibrated)\n"
2476 " --help this help text\n"
2477 " --version show version and compile time features\n"),
2478 pn);
2479 exit (status);
2482 static void
2483 unlink_stale_socket (const char *sock, const char *pidfile)
2485 log_write (_ ("removing stale socket %s"), sock);
2486 unlink (sock);
2487 unlink (pidfile);
2490 static int
2491 test_pidfile (const char *path, const char *sock, char *buf, size_t buflen,
2492 char **pidfile, int create, mode_t mode, int terminate)
2494 pid_t pid;
2495 int fd;
2496 size_t len;
2498 if (!create)
2500 snprintf (buf, buflen, "%s/%s.pid", homedir, sock);
2501 *pidfile = str_dup (buf);
2502 fd = open (buf, O_RDONLY);
2504 else
2505 fd = open (*pidfile, O_CREAT|O_WRONLY|O_TRUNC, mode);
2507 if (fd == -1)
2509 if (!create && errno != ENOENT)
2511 log_write ("%s: %s", buf, pwmd_strerror (errno));
2512 free (*pidfile);
2513 *pidfile = NULL;
2514 return -1;
2516 else if (!create && !terminate)
2517 return 0;
2519 log_write ("%s: %s", *pidfile, strerror (errno));
2520 return -1;
2523 if (create)
2525 snprintf (buf, buflen, "%i", getpid ());
2526 write (fd, buf, strlen (buf));
2527 close (fd);
2528 return 0;
2531 len = read (fd, buf, buflen);
2532 close (fd);
2533 if (len == 0)
2535 unlink_stale_socket (path, *pidfile);
2536 return 0;
2539 if (sscanf (buf, "%5i", &pid) != 1 || pid == 0)
2541 if (!terminate)
2543 unlink_stale_socket (path, *pidfile);
2544 return 0;
2548 if (kill (pid, 0) == -1)
2550 unlink_stale_socket (path, *pidfile);
2551 return 0;
2554 if (terminate)
2556 if (kill (pid, SIGTERM) == -1)
2557 log_write ("%s: %s", path, pwmd_strerror (errno));
2559 else
2560 log_write (_ ("an instance for socket %s is already running"), path);
2562 xfree (*pidfile);
2563 *pidfile = NULL;
2564 return 1;
2568 main (int argc, char *argv[])
2570 int opt;
2571 struct sockaddr_un addr;
2572 char buf[PATH_MAX];
2573 char *socketpath = NULL, *socketdir, *socketname = NULL;
2574 char *socketarg = NULL;
2575 char *datadir = NULL;
2576 char *pidfile = NULL;
2577 mode_t mode = 0600;
2578 int x;
2579 char *p;
2580 char **cache_push = NULL;
2581 char *import = NULL, *keygrip = NULL, *sign_keygrip = NULL;
2582 char *keyparam = NULL;
2583 int estatus = EXIT_FAILURE;
2584 int sockfd;
2585 char *outfile = NULL;
2586 int do_unlink = 0;
2587 int secure = 0;
2588 int show_version = 0;
2589 int force = 0;
2590 int no_passphrase = 0;
2591 gpg_error_t rc;
2592 char *convertfile = NULL;
2593 char *cipher = NULL;
2594 char *keyfile = NULL;
2595 uint64_t s2k_count = 0;
2596 int exists;
2597 char *debug_level_opt = NULL;
2598 int optindex;
2599 int terminate = 0;
2600 /* Must maintain the same order as longopts[] */
2601 enum
2603 OPT_VERSION, OPT_HELP,
2604 #ifdef WITH_AGENT
2605 OPT_AGENT,
2606 #endif
2607 OPT_DEBUG_LEVEL, OPT_HOMEDIR, OPT_NO_FORK, OPT_DISABLE_DUMP,
2608 OPT_IGNORE, OPT_FORCE, OPT_RCFILE, OPT_CONVERT,
2609 OPT_PASSPHRASE_FILE, OPT_IMPORT, OPT_OUTFILE,
2610 OPT_NO_PASSPHRASE_FILE, OPT_KEYGRIP, OPT_SIGN_KEYGRIP,
2611 OPT_KEYPARAM, OPT_CIPHER, OPT_ITERATIONS, OPT_S2K_COUNT,
2612 OPT_NO_PASSPHRASE, OPT_KILL
2614 const char *optstring = "nf:C:k:I:o:";
2615 const struct option longopts[] = {
2616 {"version", no_argument, 0, 0},
2617 {"help", no_argument, 0, 0},
2618 #ifdef WITH_AGENT
2619 {"use-agent", optional_argument, 0, 0},
2620 #endif
2621 {"debug-level", required_argument, 0, 0},
2622 {"homedir", required_argument, 0, 0},
2623 {"no-fork", no_argument, 0, 'n'},
2624 {"disable_dump", no_argument, 0, 0},
2625 {"ignore", no_argument, 0, 0},
2626 {"force", no_argument, 0, 0},
2627 {"rcfile", required_argument, 0, 'f'},
2628 {"convert", required_argument, 0, 'C'},
2629 {"passphrase-file", required_argument, 0, 'k'},
2630 {"import", required_argument, 0, 'I'},
2631 {"outfile", required_argument, 0, 'o'},
2632 {"no-passphrase-file", no_argument, 0, 0},
2633 {"keygrip", required_argument, 0, 0},
2634 {"sign-keygrip", required_argument, 0, 0},
2635 {"keyparam", required_argument, 0, 0},
2636 {"cipher", required_argument, 0, 0},
2637 {"cipher-iterations", required_argument, 0, 0},
2638 {"s2k-count", required_argument, 0, 0},
2639 {"no-passphrase", no_argument, 0, 0},
2640 {"kill", no_argument, 0, 0},
2641 {0, 0, 0, 0}
2644 log_fd = -1;
2646 #ifndef DEBUG
2647 #ifdef HAVE_SETRLIMIT
2648 struct rlimit rl;
2650 rl.rlim_cur = rl.rlim_max = 0;
2652 if (setrlimit (RLIMIT_CORE, &rl) != 0)
2653 err (EXIT_FAILURE, "setrlimit()");
2654 #endif
2656 #ifdef HAVE_PR_SET_DUMPABLE
2657 prctl (PR_SET_DUMPABLE, 0);
2658 #endif
2659 #endif
2661 #ifdef ENABLE_NLS
2662 setlocale (LC_ALL, "");
2663 bindtextdomain ("pwmd", LOCALEDIR);
2664 textdomain ("pwmd");
2665 #endif
2667 #ifndef MEM_DEBUG
2668 xmem_init ();
2669 #endif
2670 gpg_err_init ();
2672 if (setup_crypto ())
2673 exit (EXIT_FAILURE);
2675 #ifdef WITH_GNUTLS
2676 gnutls_global_init ();
2677 gnutls_global_set_log_level (1);
2678 gnutls_global_set_log_function (tls_log);
2679 gnutls_global_set_audit_log_function (tls_audit_log);
2680 tls_fd = -1;
2681 tls6_fd = -1;
2682 #endif
2683 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
2684 xmlInitMemory ();
2685 xmlInitGlobals ();
2686 xmlInitParser ();
2687 xmlXPathInit ();
2688 cmdline = 1;
2689 use_agent = -1;
2691 while ((opt = getopt_long (argc, argv, optstring, longopts, &optindex))
2692 != -1)
2694 switch (opt)
2696 case 'I':
2697 import = optarg;
2698 break;
2699 case 'C':
2700 convertfile = optarg;
2701 break;
2702 case 'k':
2703 keyfile = optarg;
2704 break;
2705 case 'o':
2706 outfile = optarg;
2707 break;
2708 case 'D':
2709 secure = 1;
2710 break;
2711 case 'n':
2712 nofork = 1;
2713 break;
2714 case 'f':
2715 rcfile = str_dup (optarg);
2716 break;
2717 default:
2718 usage (argv[0], EXIT_FAILURE);
2719 break;
2720 case 0:
2721 switch (optindex)
2723 case OPT_VERSION:
2724 show_version = 1;
2725 break;
2726 case OPT_HELP:
2727 usage (argv[0], 0);
2728 break;
2729 #ifdef WITH_AGENT
2730 case OPT_AGENT:
2731 use_agent = optarg && *optarg ? atoi (optarg) : 1;
2732 if (use_agent < 0 || use_agent > 1)
2733 usage (argv[0], 1);
2734 break;
2735 #endif
2736 case OPT_DEBUG_LEVEL:
2737 debug_level_opt = optarg;
2738 break;
2739 case OPT_HOMEDIR:
2740 homedir = str_dup (optarg);
2741 break;
2742 case OPT_NO_FORK:
2743 nofork = 1;
2744 break;
2745 case OPT_DISABLE_DUMP:
2746 secure = 1;
2747 break;
2748 case OPT_IGNORE:
2749 case OPT_FORCE:
2750 force = 1;
2751 break;
2752 case OPT_RCFILE:
2753 rcfile = str_dup (optarg);
2754 break;
2755 case OPT_CONVERT:
2756 convertfile = optarg;
2757 break;
2758 case OPT_PASSPHRASE_FILE:
2759 keyfile = optarg;
2760 break;
2761 case OPT_IMPORT:
2762 import = optarg;
2763 break;
2764 case OPT_OUTFILE:
2765 outfile = optarg;
2766 break;
2767 case OPT_NO_PASSPHRASE_FILE:
2768 no_passphrase_file = 1;
2769 break;
2770 case OPT_KEYGRIP:
2771 keygrip = optarg;
2772 break;
2773 case OPT_SIGN_KEYGRIP:
2774 sign_keygrip = optarg;
2775 break;
2776 case OPT_KEYPARAM:
2777 keyparam = optarg;
2778 break;
2779 case OPT_CIPHER:
2780 cipher = optarg;
2781 break;
2782 case OPT_ITERATIONS:
2783 case OPT_S2K_COUNT:
2784 s2k_count = strtoull (optarg, NULL, 10);
2785 break;
2786 case OPT_NO_PASSPHRASE:
2787 no_passphrase = 1;
2788 break;
2789 case OPT_KILL:
2790 terminate = 1;
2791 break;
2792 default:
2793 usage (argv[0], 1);
2798 if (show_version)
2800 printf (_("%s\n\n"
2801 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015\n"
2802 "%s\n"
2803 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2804 "Compile time features:\n%s"), PACKAGE_STRING,
2805 PACKAGE_BUGREPORT,
2806 #ifdef PWMD_HOMEDIR
2807 "+PWMD_HOMEDIR=" PWMD_HOMEDIR "\n"
2808 #endif
2809 #ifdef WITH_AGENT
2810 "+WITH_AGENT\n"
2811 #else
2812 "-WITH_AGENT\n"
2813 #endif
2814 #ifdef WITH_QUALITY
2815 "+WITH_QUALITY\n"
2816 #else
2817 "-WITH_QUALITY\n"
2818 #endif
2819 #ifdef WITH_GNUTLS
2820 "+WITH_GNUTLS\n"
2821 #else
2822 "-WITH_GNUTLS\n"
2823 #endif
2824 #ifdef WITH_LIBACL
2825 "+WITH_LIBACL\n"
2826 #else
2827 "-WITH_LIBACL\n"
2828 #endif
2829 #ifdef DEBUG
2830 "+DEBUG\n"
2831 #else
2832 "-DEBUG\n"
2833 #endif
2834 #ifdef MEM_DEBUG
2835 "+MEM_DEBUG\n"
2836 #else
2837 "-MEM_DEBUG\n"
2838 #endif
2839 #ifdef MUTEX_DEBUG
2840 "+MUTEX_DEBUG\n"
2841 #else
2842 "-MUTEX_DEBUG\n"
2843 #endif
2845 exit (EXIT_SUCCESS);
2848 if (!homedir)
2849 #ifdef PWMD_HOMEDIR
2850 homedir = str_dup(PWMD_HOMEDIR);
2851 #else
2852 homedir = str_asprintf ("%s/.pwmd", get_home_dir());
2853 #endif
2855 if (mkdir (homedir, 0700) == -1 && errno != EEXIST)
2856 err (EXIT_FAILURE, "%s", homedir);
2858 snprintf (buf, sizeof (buf), "%s/data", homedir);
2859 if (mkdir (buf, 0700) == -1 && errno != EEXIST)
2860 err (EXIT_FAILURE, "%s", buf);
2862 datadir = str_dup (buf);
2863 pthread_mutexattr_t attr;
2864 pthread_mutexattr_init (&attr);
2865 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
2866 pthread_mutex_init (&rcfile_mutex, &attr);
2867 pthread_cond_init (&rcfile_cond, NULL);
2868 pthread_mutex_init (&cn_mutex, &attr);
2869 pthread_mutexattr_destroy (&attr);
2870 pthread_key_create (&last_error_key, free_key);
2871 #ifndef HAVE_PTHREAD_CANCEL
2872 pthread_key_create (&signal_thread_key, free_key);
2873 #endif
2875 if (!rcfile)
2876 rcfile = str_asprintf ("%s/config", homedir);
2878 global_config = config_parse (rcfile, 0);
2879 if (!global_config)
2880 exit (EXIT_FAILURE);
2882 #ifdef WITH_AGENT
2883 if (use_agent == -1)
2884 use_agent = config_get_boolean ("global", "use_agent");
2885 #endif
2887 setup_logging ();
2889 if (debug_level_opt)
2890 debug_level = str_split (debug_level_opt, ",", 0);
2892 x = config_get_int_param (global_config, "global", "priority", &exists);
2893 if (exists && x != atoi(INVALID_PRIORITY))
2895 errno = 0;
2896 if (setpriority (PRIO_PROCESS, 0, x) == -1)
2898 log_write ("setpriority(): %s",
2899 pwmd_strerror (gpg_error_from_errno (errno)));
2900 goto do_exit;
2903 #ifdef HAVE_MLOCKALL
2904 if (disable_mlock == 0 && mlockall (MCL_CURRENT | MCL_FUTURE) == -1)
2906 log_write ("mlockall(): %s",
2907 pwmd_strerror (gpg_error_from_errno (errno)));
2908 goto do_exit;
2910 #endif
2912 rc = cache_init (free_cache_data);
2913 if (rc)
2915 log_write ("pwmd: ERR %i: %s", rc,
2916 gpg_err_code (rc) == GPG_ERR_UNKNOWN_VERSION
2917 ? _("incompatible gpg-agent version: 2.1.0 or later required")
2918 : pwmd_strerror (rc));
2919 goto do_exit;
2922 if (s2k_count == 0)
2923 s2k_count = config_get_ulonglong (NULL, "s2k_count");
2925 if (convertfile)
2927 if (!outfile || !*outfile || argc != optind)
2928 usage (argv[0], EXIT_FAILURE);
2930 estatus = convert_v2_datafile (convertfile, cipher, keyfile, keygrip,
2931 sign_keygrip, no_passphrase, outfile,
2932 keyparam, s2k_count);
2933 config_free (global_config);
2934 xfree (rcfile);
2935 exit (!estatus);
2938 if (import)
2940 if (!outfile || !*outfile || argc != optind)
2941 usage (argv[0], EXIT_FAILURE);
2943 if (outfile && outfile[0] == '-' && outfile[1] == 0)
2944 outfile = NULL;
2946 estatus = xml_import (import, outfile, keygrip, sign_keygrip, keyfile,
2947 no_passphrase, cipher, keyparam, s2k_count);
2948 config_free (global_config);
2949 xfree (rcfile);
2950 exit (!estatus);
2953 p = config_get_string ("global", "socket_path");
2954 if (!p)
2955 p = str_asprintf ("%s/socket", homedir);
2957 socketarg = expand_homedir (p);
2958 xfree (p);
2960 if (!secure)
2961 disable_list_and_dump = config_get_boolean ("global",
2962 "disable_list_and_dump");
2963 else
2964 disable_list_and_dump = secure;
2966 cache_push = config_get_list ("global", "cache_push");
2968 while (optind < argc)
2970 if (strv_printf (&cache_push, "%s", argv[optind++]) == 0)
2971 errx (EXIT_FAILURE, "%s", pwmd_strerror (GPG_ERR_ENOMEM));
2974 if (strchr (socketarg, '/') == NULL)
2976 socketdir = getcwd (buf, sizeof (buf));
2977 socketname = str_dup (socketarg);
2978 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2980 else
2982 socketname = str_dup (strrchr (socketarg, '/'));
2983 socketname++;
2984 socketarg[strlen (socketarg) - strlen (socketname) - 1] = 0;
2985 socketdir = str_dup (socketarg);
2986 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2989 if (chdir (datadir))
2991 log_write ("%s: %s", datadir,
2992 pwmd_strerror (gpg_error_from_errno (errno)));
2993 unlink (socketpath);
2994 goto do_exit;
2997 x = test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 0,
2998 mode, terminate);
2999 if (!terminate && x)
3000 goto do_exit;
3001 else if (terminate)
3003 estatus = x != 1 ? EXIT_FAILURE : EXIT_SUCCESS;
3004 goto do_exit;
3008 * bind() doesn't like the full pathname of the socket or any non alphanum
3009 * characters so change to the directory where the socket is wanted then
3010 * create it then change to datadir.
3012 if (chdir (socketdir))
3014 log_write ("%s: %s", socketdir,
3015 pwmd_strerror (gpg_error_from_errno (errno)));
3016 goto do_exit;
3019 xfree (socketdir);
3021 if ((sockfd = socket (PF_UNIX, SOCK_STREAM, 0)) == -1)
3023 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
3024 goto do_exit;
3027 addr.sun_family = AF_UNIX;
3028 snprintf (addr.sun_path, sizeof (addr.sun_path), "%s", socketname);
3029 do_unlink = 1;
3030 if (bind (sockfd, (struct sockaddr *) &addr, sizeof (struct sockaddr)) ==
3033 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
3035 if (errno == EADDRINUSE)
3037 do_unlink = 0;
3038 log_write (_("Either there is another pwmd running or '%s' is a \n"
3039 "stale socket. Please remove it manually."), socketpath);
3042 goto do_exit;
3046 char *t = config_get_string ("global", "socket_perms");
3047 mode_t mask;
3049 if (t)
3051 mode = strtol (t, NULL, 8);
3052 mask = umask (0);
3053 xfree (t);
3055 if (chmod (socketname, mode) == -1)
3057 log_write ("%s: %s", socketname,
3058 pwmd_strerror (gpg_error_from_errno (errno)));
3059 close (sockfd);
3060 umask (mask);
3061 goto do_exit;
3064 umask (mask);
3068 xfree (--socketname);
3070 if (chdir (datadir))
3072 log_write ("%s: %s", datadir,
3073 pwmd_strerror (gpg_error_from_errno (errno)));
3074 close (sockfd);
3075 goto do_exit;
3078 xfree (datadir);
3081 * Set the cache entry for a file. Prompts for the password.
3083 if (cache_push)
3085 struct crypto_s *crypto = NULL;
3086 gpg_error_t rc = init_client_crypto (&crypto);
3088 if (rc)
3090 estatus = EXIT_FAILURE;
3091 goto do_exit;
3094 #ifdef WITH_AGENT
3095 if (use_agent)
3097 rc = agent_set_pinentry_options (crypto->agent);
3098 if (rc)
3100 estatus = EXIT_FAILURE;
3101 goto do_exit;
3104 #endif
3106 for (opt = 0; cache_push[opt]; opt++)
3108 if (!do_cache_push (cache_push[opt], crypto) && !force)
3110 strv_free (cache_push);
3111 startup_failure ();
3112 estatus = EXIT_FAILURE;
3113 cleanup_crypto (&crypto);
3114 goto do_exit;
3117 cleanup_crypto_stage1 (crypto);
3120 #ifdef WITH_AGENT
3121 if (use_agent)
3122 (void) kill_scd (crypto->agent);
3123 #endif
3125 cleanup_crypto (&crypto);
3126 strv_free (cache_push);
3127 log_write (!nofork ? _("Done. Daemonizing...") :
3128 _("Done. Waiting for connections..."));
3131 config_clear_keys ();
3133 if (listen (sockfd, 0) == -1)
3135 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
3136 goto do_exit;
3139 if (!nofork)
3141 switch (fork ())
3143 case -1:
3144 log_write ("fork(): %s",
3145 pwmd_strerror (gpg_error_from_errno (errno)));
3146 goto do_exit;
3147 case 0:
3148 close (0);
3149 close (1);
3150 close (2);
3151 setsid ();
3152 break;
3153 default:
3154 _exit (EXIT_SUCCESS);
3158 (void)test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 1,
3159 mode, 0);
3160 cmdline = 0;
3161 pthread_key_create (&thread_name_key, free_key);
3162 pthread_setspecific (thread_name_key, str_dup ("main"));
3163 estatus = server_loop (sockfd, &socketpath);
3165 do_exit:
3166 if (socketpath && do_unlink)
3168 unlink (socketpath);
3169 xfree (socketpath);
3172 xfree (socketarg);
3173 #ifdef WITH_GNUTLS
3174 gnutls_global_deinit ();
3175 #endif
3176 if (rcfile_tid)
3178 #ifdef HAVE_PTHREAD_CANCEL
3179 pthread_cancel (rcfile_tid);
3180 #else
3181 pthread_kill (rcfile_tid, SIGUSR2);
3182 pthread_cond_signal (&rcfile_cond);
3183 #endif
3184 pthread_join (rcfile_tid, NULL);
3187 pthread_cond_destroy (&rcfile_cond);
3188 pthread_mutex_destroy (&rcfile_mutex);
3189 pthread_key_delete (last_error_key);
3190 #ifndef HAVE_PTHREAD_CANCEL
3191 pthread_key_delete (signal_thread_key);
3192 #endif
3194 if (global_config)
3195 config_free (global_config);
3197 free_invoking_users (invoking_users);
3198 xfree (rcfile);
3199 xfree (home_directory);
3200 xfree (homedir);
3201 xmlCleanupParser ();
3202 xmlCleanupGlobals ();
3204 if (pidfile)
3205 unlink (pidfile);
3206 xfree (pidfile);
3208 if (estatus == EXIT_SUCCESS && !terminate)
3209 log_write (_("pwmd exiting normally"));
3211 pthread_key_delete (thread_name_key);
3212 closelog ();
3213 #if defined(DEBUG) && !defined(MEM_DEBUG)
3214 xdump ();
3215 #endif
3217 if (log_fd != -1)
3218 close (log_fd);
3220 exit (estatus);
3223 gpg_error_t lock_flock (assuan_context_t ctx, const char *filename,
3224 int type, int *fd)
3226 gpg_error_t rc = 0;
3228 #ifdef HAVE_FLOCK
3229 *fd = open (filename, O_RDONLY);
3230 if (*fd == -1)
3231 return gpg_error_from_syserror ();
3233 TRY_FLOCK (ctx, *fd, type, rc);
3234 if (rc)
3236 close (*fd);
3237 *fd = -1;
3239 #endif
3241 return rc;
3244 void unlock_flock (int *fd)
3246 #ifdef HAVE_FLOCK
3247 if (*fd != -1)
3248 close (*fd);
3250 *fd = -1;
3251 #endif