Add advisory file locking.
[pwmd.git] / src / pwmd.c
blob03e01c44fc86d3d0d76769d10d882be0456ef6f6
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; *p; p++)
553 rc = acl_check_common(client, *p, (*peer)->uid, (*peer)->gid,
554 &allowed);
557 strv_free (users);
560 return allowed ? 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);
572 if (len == -1)
573 len = 16384;
575 buf = xmalloc (len);
576 if (!buf)
577 return GPG_ERR_ENOMEM;
579 if (!getgrnam_r (name, &gr, buf, len, &gresult) && gresult)
581 if (gresult->gr_gid == gid)
583 xfree (buf);
584 *allowed = !not;
585 return 0;
588 len = sysconf (_SC_GETPW_R_SIZE_MAX);
589 if (len == -1)
590 len = 16384;
592 for (char **t = gresult->gr_mem; *t; t++)
594 char *tbuf;
595 struct passwd pw;
596 struct passwd *result = get_pwd_struct (*t, 0, &pw, &tbuf);
598 if (result && result->pw_uid == uid)
600 xfree (tbuf);
601 *allowed = !not;
602 break;
605 xfree (tbuf);
608 xfree (buf);
609 return 0;
612 xfree (buf);
613 return GPG_ERR_EACCES;
615 #else
616 static gpg_error_t
617 acl_check_group (const char *name, uid_t uid, gid_t gid, int not, int *allowed)
619 struct group *gresult;
621 gresult = getgrnam (name);
622 if (gresult && gresult->gr_gid == gid)
624 *allowed = !not;
625 return 0;
628 for (char **t = gresult->gr_mem; *t; t++)
630 char *buf;
631 struct passwd pw;
632 struct passwd *result = get_pwd_struct (*t, 0, &pw, &buf);
634 if (result && result->pw_uid == uid)
636 xfree (buf);
637 *allowed = !not;
638 break;
641 xfree (buf);
644 return 0;
646 #endif
648 gpg_error_t
649 peer_is_invoker(struct client_s *client)
651 struct invoking_user_s *user;
652 int allowed = 0;
654 if (client->thd->state == CLIENT_STATE_UNKNOWN)
655 return GPG_ERR_EACCES;
657 for (user = invoking_users; user; user = user->next)
659 #ifdef WITH_GNUTLS
660 if (client->thd->remote)
662 if (user->type == INVOKING_TLS
663 && !strcmp(client->thd->tls->fp, user->id))
664 allowed = user->not ? 0 : 1;
666 continue;
668 #endif
670 if (user->type == INVOKING_GID)
672 gpg_error_t rc = acl_check_group (user->id,
673 client->thd->peer->uid,
674 client->thd->peer->gid,
675 user->not, &allowed);
676 if (rc)
677 return rc;
679 else if (user->type == INVOKING_UID && client->thd->peer->uid == user->uid)
680 allowed = user->not ? 0 : 1;
683 return allowed ? 0 : GPG_ERR_EACCES;
686 #ifdef HAVE_GETGRNAM_R
687 gpg_error_t
688 acl_check_common (struct client_s *client, const char *user, uid_t uid,
689 gid_t gid, int *allowed)
691 int not = 0;
692 int rw = 0;
693 int tls = 0;
695 if (!user || !*user)
696 return 0;
698 if (*user == '-' || *user == '!')
699 not = 1;
701 if (*user == '+') // not implemented yet
702 rw = 1;
704 if (*user == '#') // TLS fingerprint hash
705 tls = 1;
707 if (not || rw || tls)
708 user++;
710 if (tls)
712 #ifdef WITH_GNUTLS
713 if (client->thd->remote)
715 if (!strcasecmp (client->thd->tls->fp, user))
716 *allowed = !not;
719 return 0;
720 #else
721 return 0;
722 #endif
724 #ifdef WITH_GNUTLS
725 else if (client->thd->remote) // Remote client with no TLS in the ACL
726 return 0;
727 #endif
729 if (*user == '@') // all users in group
730 return acl_check_group (user+1, uid, gid, not, allowed);
731 else
733 char *buf;
734 struct passwd pw;
735 struct passwd *pwd = get_pwd_struct (user, 0, &pw, &buf);
737 if (pwd && pwd->pw_uid == uid)
738 *allowed = !not;
740 xfree (buf);
743 return 0;
745 #else
746 gpg_error_t
747 acl_check_common (struct client_s *client, const char *user, uid_t uid,
748 gid_t gid, int *allowed)
750 int not = 0;
751 int rw = 0;
752 int tls = 0;
754 if (!user || !*user)
755 return 0;
757 if (*user == '-' || *user == '!')
758 not = 1;
760 if (*user == '+') // not implemented yet
761 rw = 1;
763 if (*user == '#') // TLS fingerprint hash
764 tls = 1;
766 if (not || rw || tls)
767 user++;
769 if (tls)
771 #ifdef WITH_GNUTLS
772 if (client->thd->remote)
774 if (!strcasecmp (client->thd->tls->fp, user))
775 *allowed = !not;
778 return 0;
779 #else
780 return 0;
781 #endif
784 if (*user == '@') // all users in group
785 return acl_check_group (user+1, uid, gid, not, allowed);
786 else
788 char *buf;
789 struct passwd pw;
790 struct passwd *result = get_pwd_struct (user, 0, &pw, &buf);
792 if (result && result->pw_uid == uid)
793 *allowed = !not;
795 xfree (buf);
798 return 0;
800 #endif
802 static gpg_error_t
803 validate_peer (struct client_s *cl)
805 gpg_error_t rc;
807 #ifdef WITH_GNUTLS
808 if (cl->thd->remote)
809 return tls_validate_access (cl, NULL);
810 #endif
812 MUTEX_LOCK (&cn_mutex);
813 rc = do_validate_peer (cl->ctx, "global", &cl->thd->peer);
814 MUTEX_UNLOCK (&cn_mutex);
815 if (!rc || gpg_err_code (rc) == GPG_ERR_EACCES)
816 log_write ("peer %s: uid=%i, gid=%i, pid=%i",
817 !rc ? _("accepted") : _("rejected"), cl->thd->peer->uid,
818 cl->thd->peer->gid, cl->thd->peer->pid);
819 else if (rc)
820 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
822 return rc;
825 static void
826 xml_error_cb (void *data, xmlErrorPtr e)
828 struct client_s *client = data;
831 * Keep the first reported error as the one to show in the error
832 * description. Reset in send_error().
834 if (client->xml_error)
835 return;
837 client->xml_error = xcalloc (1, sizeof(xmlError));
838 xmlCopyError (e, client->xml_error);
841 static pid_t
842 hook_waitpid (assuan_context_t ctx, pid_t pid, int action,
843 int *status, int options)
845 return waitpid (pid, status, options);
848 static ssize_t
849 hook_read (assuan_context_t ctx, assuan_fd_t fd, void *data, size_t len)
851 #ifdef WITH_GNUTLS
852 struct client_s *client = assuan_get_pointer (ctx);
854 if (client->thd->remote)
855 return tls_read_hook (ctx, (int) fd, data, len);
856 #endif
858 return read ((int) fd, data, len);
861 static ssize_t
862 hook_write (assuan_context_t ctx, assuan_fd_t fd,
863 const void *data, size_t len)
865 #ifdef WITH_GNUTLS
866 struct client_s *client = assuan_get_pointer (ctx);
868 if (client->thd->remote)
869 return tls_write_hook (ctx, (int) fd, data, len);
870 #endif
872 return write ((int) fd, data, len);
875 static int
876 new_connection (struct client_s *cl)
878 gpg_error_t rc;
879 static struct assuan_malloc_hooks mhooks = { xmalloc, xrealloc, xfree };
880 static struct assuan_system_hooks shooks = {
881 ASSUAN_SYSTEM_HOOKS_VERSION,
882 __assuan_usleep,
883 __assuan_pipe,
884 __assuan_close,
885 hook_read,
886 hook_write,
887 //FIXME
888 NULL, //recvmsg
889 NULL, //sendmsg both are used for FD passing
890 __assuan_spawn,
891 hook_waitpid,
892 __assuan_socketpair,
893 __assuan_socket,
894 __assuan_connect
897 #ifdef WITH_GNUTLS
898 if (cl->thd->remote)
900 char *prio = config_get_string ("global", "tls_cipher_suite");
902 cl->thd->timeout = config_get_integer ("global", "tls_timeout");
903 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
904 return 0;
906 cl->thd->tls = tls_init (cl->thd->fd, cl->thd->timeout, prio);
907 xfree (prio);
908 if (!cl->thd->tls)
909 return 0;
911 #endif
913 rc = assuan_new_ext (&cl->ctx, GPG_ERR_SOURCE_DEFAULT, &mhooks,
914 debug_level ? assuan_log_cb : NULL, NULL);
915 if (rc)
916 goto fail;
918 assuan_ctx_set_system_hooks (cl->ctx, &shooks);
919 rc = assuan_init_socket_server (cl->ctx, cl->thd->fd, 2);
920 if (rc)
921 goto fail;
923 assuan_set_pointer (cl->ctx, cl);
924 assuan_set_hello_line (cl->ctx, PACKAGE_STRING);
925 rc = register_commands (cl->ctx);
926 if (rc)
927 goto fail;
929 rc = assuan_accept (cl->ctx);
930 if (rc)
931 goto fail;
933 rc = validate_peer (cl);
934 /* May not be implemented on all platforms. */
935 if (rc && gpg_err_code (rc) != GPG_ERR_ASS_GENERAL)
936 goto fail;
938 MUTEX_LOCK (&cn_mutex);
939 cl->thd->state = CLIENT_STATE_INIT;
940 MUTEX_UNLOCK (&cn_mutex);
941 rc = init_client_crypto (&cl->crypto);
942 if (rc)
943 goto fail;
945 #ifdef WITH_AGENT
946 if (use_agent)
947 cl->crypto->agent->client_ctx = cl->ctx;
948 #endif
950 cl->crypto->client_ctx = cl->ctx;
951 cl->lock_timeout = config_get_integer ("global", "lock_timeout");
952 xmlSetStructuredErrorFunc (cl, xml_error_cb);
953 return 1;
955 fail:
956 log_write ("%s", pwmd_strerror (rc));
957 return 0;
961 * This is called after a client_thread() terminates. Set with
962 * pthread_cleanup_push().
964 static void
965 cleanup_cb (void *arg)
967 struct client_thread_s *cn = arg;
968 struct client_s *cl = cn->cl;
970 MUTEX_LOCK (&cn_mutex);
971 cn_thread_list = slist_remove (cn_thread_list, cn);
972 MUTEX_UNLOCK (&cn_mutex);
974 if (cl)
976 unlock_flock (&cl->flock_fd);
977 cleanup_client (cl);
978 if (cl->xml_error)
979 xmlResetError (cl->xml_error);
981 xfree (cl->xml_error);
983 #ifdef WITH_GNUTLS
984 if (cn->tls)
986 gnutls_deinit (cn->tls->ses);
987 xfree (cn->tls->fp);
988 xfree (cn->tls);
990 #endif
992 if (!cn->atfork && cl->ctx)
993 assuan_release (cl->ctx);
994 else if (!cn->atfork && cl->thd && cl->thd->fd != -1)
995 close (cl->thd->fd);
997 if (cl->crypto)
998 cleanup_crypto (&cl->crypto);
1000 pinentry_free_opts (&cl->pinentry_opts);
1001 xfree (cl);
1003 else
1005 if (cn->fd != -1)
1006 close (cn->fd);
1009 while (cn->msg_queue)
1011 struct status_msg_s *msg = cn->msg_queue;
1013 cn->msg_queue = msg->next;
1014 xfree (msg->line);
1015 xfree (msg);
1018 if (!cn->atfork && cn->status_msg_pipe[0] != -1)
1019 close (cn->status_msg_pipe[0]);
1021 if (!cn->atfork && cn->status_msg_pipe[1] != -1)
1022 close (cn->status_msg_pipe[1]);
1024 pthread_mutex_destroy (&cn->status_mutex);
1026 if (!cn->atfork)
1028 log_write (_("exiting, fd=%i"), cn->fd);
1029 send_status_all (STATUS_CLIENTS, NULL);
1032 xfree (cn->name);
1033 #ifdef WITH_GNUTLS
1034 xfree (cn->peeraddr);
1035 #endif
1036 xfree (cn);
1037 pthread_cond_signal (&quit_cond);
1040 void
1041 cleanup_all_clients (int atfork)
1043 /* This function may be called from pthread_atfork() which requires
1044 reinitialization. */
1045 if (atfork)
1047 pthread_mutexattr_t attr;
1049 pthread_mutexattr_init (&attr);
1050 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
1051 pthread_mutex_init (&cn_mutex, &attr);
1052 pthread_mutexattr_destroy (&attr);
1053 cache_mutex_init ();
1056 MUTEX_LOCK (&cn_mutex);
1058 while (slist_length (cn_thread_list))
1060 struct client_thread_s *thd = slist_nth_data (cn_thread_list, 0);
1062 thd->atfork = atfork;
1063 cleanup_cb (thd);
1066 exiting = 1;
1067 MUTEX_UNLOCK (&cn_mutex);
1068 cache_deinit (atfork);
1071 static gpg_error_t
1072 send_msg_queue (struct client_thread_s *thd)
1074 MUTEX_LOCK (&thd->status_mutex);
1075 gpg_error_t rc = 0;
1076 char c;
1078 read (thd->status_msg_pipe[0], &c, 1);
1079 thd->wrote_status = 0;
1081 while (thd->msg_queue)
1083 struct status_msg_s *msg = thd->msg_queue;
1085 #ifndef HAVE_PTHREAD_CANCEL
1086 if (thd->fd == -1)
1087 break;
1088 #endif
1090 thd->msg_queue = thd->msg_queue->next;
1091 MUTEX_UNLOCK (&thd->status_mutex);
1092 rc = send_status (thd->cl->ctx, msg->s, msg->line);
1093 MUTEX_LOCK (&thd->status_mutex);
1094 xfree (msg->line);
1095 xfree (msg);
1097 if (rc)
1098 break;
1101 MUTEX_UNLOCK (&thd->status_mutex);
1102 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1103 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
1105 return rc;
1108 static void *
1109 client_thread (void *data)
1111 struct client_thread_s *thd = data;
1112 struct client_s *cl = xcalloc (1, sizeof (struct client_s));
1114 #ifdef HAVE_PR_SET_NAME
1115 prctl (PR_SET_NAME, "client");
1116 #endif
1117 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1119 if (!cl)
1121 log_write ("%s(%i): %s", __FILE__, __LINE__,
1122 pwmd_strerror (GPG_ERR_ENOMEM));
1123 return NULL;
1126 MUTEX_LOCK (&cn_mutex);
1127 pthread_cleanup_push (cleanup_cb, thd);
1128 thd->cl = cl;
1129 cl->thd = thd;
1130 cl->flock_fd = -1;
1131 MUTEX_UNLOCK (&cn_mutex);
1133 if (new_connection (cl))
1135 int finished = 0;
1136 gpg_error_t rc;
1137 struct pollfd fds[2];
1139 fds[0].fd = thd->fd;
1140 fds[0].events = POLLIN;
1141 fds[1].fd = thd->status_msg_pipe[0];
1142 fds[1].events = POLLIN;
1144 send_status_all (STATUS_CLIENTS, NULL);
1145 rc = send_status (cl->ctx, STATUS_CACHE, NULL);
1146 if (rc)
1148 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
1149 finished = 1;
1152 while (!finished)
1154 int n;
1155 int eof;
1157 n = poll (fds, 2, -1);
1158 if (n == -1)
1160 log_write ("%s", strerror (errno));
1161 break;
1164 if (fds[1].revents & POLLIN)
1166 rc = send_msg_queue (thd);
1167 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1168 break;
1171 #ifdef HAVE_PTHREAD_CANCEL
1172 if (!(fds[0].revents & POLLIN))
1173 #else
1174 if (thd->fd != -1 && !(fds[0].revents & POLLIN))
1175 #endif
1176 continue;
1178 rc = assuan_process_next (cl->ctx, &eof);
1179 if (rc || eof)
1181 if (gpg_err_code (rc) == GPG_ERR_EOF || eof)
1182 break;
1184 log_write ("assuan_process_next(): rc=%i %s", rc,
1185 pwmd_strerror (rc));
1186 if (rc == gpg_error (GPG_ERR_ETIMEDOUT))
1187 break;
1189 rc = send_error (cl->ctx, rc);
1190 if (rc)
1192 log_write ("assuan_process_done(): rc=%i %s", rc,
1193 pwmd_strerror (rc));
1194 break;
1198 /* Since the msg queue pipe fd's are non-blocking, check for
1199 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1200 * client has already disconnected and will be converted to
1201 * GPG_ERR_EOF during assuan_process_next().
1203 rc = send_msg_queue (thd);
1204 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1205 break;
1209 /* Don't do pthread_exit() here because any set pthread_cleanup_push
1210 * functions would be called after a command failed but then the client
1211 * exited normally which may lead to a double free. */
1212 pthread_cleanup_pop (1);
1213 return NULL;
1216 static int
1217 xml_import (const char *filename, const char *outfile,
1218 const char *keygrip, const char *sign_keygrip,
1219 const char *keyfile, int no_passphrase, const char *cipher,
1220 const char *params, uint64_t iterations)
1222 xmlDocPtr doc;
1223 int fd;
1224 struct stat st;
1225 int len;
1226 xmlChar *xmlbuf;
1227 xmlChar *xml;
1228 gpg_error_t rc;
1229 struct crypto_s *crypto = NULL;
1230 void *key = NULL;
1231 size_t keylen = 0;
1232 int algo = cipher ? cipher_string_to_gcrypt ((char *) cipher) :
1233 GCRY_CIPHER_AES256;
1235 if (algo == -1)
1237 log_write ("ERR %i: %s", gpg_error (GPG_ERR_CIPHER_ALGO),
1238 pwmd_strerror (GPG_ERR_CIPHER_ALGO));
1239 return 0;
1242 if (stat (filename, &st) == -1)
1244 log_write ("%s: %s", filename,
1245 pwmd_strerror (gpg_error_from_errno (errno)));
1246 return 0;
1249 rc = init_client_crypto (&crypto);
1250 if (rc)
1251 return 0;
1253 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
1254 crypto->save.hdr.flags = set_cipher_flag (crypto->save.hdr.flags, algo);
1255 log_write (_("Importing XML from '%s'. Output will be written to '%s' ..."),
1256 filename, outfile);
1258 if ((fd = open (filename, O_RDONLY)) == -1)
1260 log_write ("%s: %s", filename,
1261 pwmd_strerror (gpg_error_from_errno (errno)));
1262 goto fail;
1265 if ((xmlbuf = xmalloc (st.st_size + 1)) == NULL)
1267 close (fd);
1268 log_write ("%s(%i): %s", __FILE__, __LINE__,
1269 pwmd_strerror (GPG_ERR_ENOMEM));
1270 goto fail;
1273 if (read (fd, xmlbuf, st.st_size) == -1)
1275 rc = gpg_error_from_errno (errno);
1276 close (fd);
1277 log_write ("%s: %s", filename, pwmd_strerror (rc));
1278 goto fail;
1281 close (fd);
1282 xmlbuf[st.st_size] = 0;
1284 * Make sure the document validates.
1286 if ((doc = xmlReadDoc (xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS)) == NULL)
1288 log_write ("xmlReadDoc() failed");
1289 xfree (xmlbuf);
1290 goto fail;
1293 xfree (xmlbuf);
1294 xmlNodePtr n = xmlDocGetRootElement (doc);
1295 if (n && !xmlStrEqual (n->name, (xmlChar *) "pwmd"))
1297 log_write (_("Could not find root \"pwmd\" element."));
1298 rc = GPG_ERR_BAD_DATA;
1301 if (!rc)
1302 rc = validate_import (NULL, n ? n->children : n);
1304 if (rc)
1306 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1307 xmlFreeDoc (doc);
1308 goto fail;
1311 xmlDocDumpMemory (doc, &xml, &len);
1312 xmlFreeDoc (doc);
1313 crypto->save.hdr.s2k_count = iterations;
1314 if (!use_agent)
1316 rc = export_common (NULL, 0, crypto, xml, len, outfile, keyfile, &key,
1317 &keylen, 0, 0, no_passphrase);
1318 if (!rc)
1319 log_write (_("Success!"));
1321 #ifdef WITH_AGENT
1322 else
1324 rc = agent_set_pinentry_options (crypto->agent);
1325 if (!rc)
1326 rc = agent_export_common (crypto, keygrip, sign_keygrip, no_passphrase,
1327 xml, len, outfile, params, keyfile);
1329 #endif
1331 gcry_free (key);
1332 xmlFree (xml);
1333 if (rc)
1335 send_error (NULL, rc);
1336 goto fail;
1339 cleanup_crypto (&crypto);
1340 return 1;
1342 fail:
1343 cleanup_crypto (&crypto);
1344 return 0;
1347 static int
1348 do_cache_push (const char *filename, struct crypto_s *crypto)
1350 unsigned char md5file[16];
1351 gpg_error_t rc;
1352 void *key = NULL;
1353 size_t keylen = 0;
1354 xmlDocPtr doc;
1355 struct cache_data_s *cdata;
1356 unsigned char *crc;
1357 size_t len;
1358 int fd = -1;
1360 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1361 filename);
1363 if (valid_filename (filename) == 0)
1365 log_write (_("%s: Invalid characters in filename"), filename);
1366 return 0;
1369 rc = lock_flock (NULL, crypto->filename, LOCK_SH, &fd);
1370 if (!rc)
1371 rc = decrypt_common (NULL, 0, crypto, filename, &key, &keylen, NULL, NULL);
1372 if (rc)
1374 unlock_flock (&fd);
1375 return rc;
1378 rc = parse_doc ((char *) crypto->plaintext, crypto->plaintext_len, &doc);
1379 if (rc)
1381 unlock_flock (&fd);
1382 log_write ("%s", pwmd_strerror (rc));
1383 xfree (key);
1384 return 0;
1387 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
1388 cdata = xcalloc (1, sizeof (struct cache_data_s));
1389 if (!cdata)
1391 unlock_flock (&fd);
1392 xmlFreeDoc (doc);
1393 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM));
1394 xfree (key);
1395 return 0;
1398 rc = get_checksum (filename, &crc, &len);
1399 unlock_flock (&fd);
1400 if (rc)
1402 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1403 xmlFreeDoc (doc);
1404 free_cache_data_once (cdata);
1405 xfree (key);
1406 return 0;
1409 cdata->crc = crc;
1410 rc = encrypt_xml (NULL, cache_key, cache_keysize, GCRY_CIPHER_AES,
1411 crypto->plaintext, crypto->plaintext_len, &cdata->doc,
1412 &cdata->doclen, &cache_iv, &cache_blocksize);
1413 if (!rc && !IS_PKI (crypto))
1415 cdata->key = key;
1416 cdata->keylen = keylen;
1418 else
1419 xfree (key);
1421 if (rc)
1423 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1424 xmlFreeDoc (doc);
1425 free_cache_data_once (cdata);
1426 return 0;
1429 #ifdef WITH_AGENT
1430 if (use_agent && IS_PKI (crypto))
1432 gcry_sexp_build ((gcry_sexp_t *) & cdata->pubkey, NULL, "%S",
1433 crypto->pkey_sexp);
1434 gcry_sexp_build ((gcry_sexp_t *) & cdata->sigkey, NULL, "%S",
1435 crypto->sigpkey_sexp);
1437 #endif
1439 int timeout = config_get_integer (filename, "cache_timeout");
1440 cache_add_file (md5file, crypto->grip, cdata, timeout);
1441 log_write (_("Successfully added '%s' to the cache."), filename);
1442 return 1;
1445 static gpg_error_t
1446 init_client (int fd, const char *addr)
1448 gpg_error_t rc = 0;
1449 struct client_thread_s *new = xcalloc (1, sizeof (struct client_thread_s));
1451 if (!new)
1453 close (fd);
1454 return GPG_ERR_ENOMEM;
1457 MUTEX_LOCK (&cn_mutex);
1458 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
1460 if (pipe (new->status_msg_pipe) == -1)
1461 rc = gpg_error_from_errno (errno);
1463 if (!rc)
1465 if (fcntl (new->status_msg_pipe[0], F_SETFL, O_NONBLOCK) == -1)
1466 rc = gpg_error_from_errno (errno);
1468 if (!rc)
1469 if (fcntl (new->status_msg_pipe[1], F_SETFL, O_NONBLOCK) == -1)
1470 rc = gpg_error_from_errno (errno);
1472 pthread_mutex_init (&new->status_mutex, NULL);
1475 if (!rc)
1477 #ifdef WITH_GNUTLS
1478 new->remote = addr ? 1 : 0;
1479 #endif
1480 new->fd = fd;
1481 rc = create_thread (client_thread, new, &new->tid, 1);
1482 if (rc)
1484 close (new->status_msg_pipe[0]);
1485 close (new->status_msg_pipe[1]);
1486 pthread_mutex_destroy (&new->status_mutex);
1490 if (!rc)
1492 struct slist_s *list = slist_append (cn_thread_list, new);
1494 if (list)
1496 cn_thread_list = list;
1497 if (addr)
1499 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1500 (pthread_t *) new->tid, fd, addr);
1501 #ifdef WITH_GNUTLS
1502 new->peeraddr = str_dup (addr);
1503 #endif
1505 else
1506 log_write (_("new connection: tid=%p, fd=%i"),
1507 (pthread_t *) new->tid, fd);
1509 else
1510 rc = GPG_ERR_ENOMEM;
1513 pthread_cleanup_pop (1);
1515 if (rc)
1517 xfree (new);
1518 close (fd);
1519 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1520 pwmd_strerror (rc));
1522 return rc;
1525 static void*
1526 keepalive_thread (void *arg)
1528 #ifndef HAVE_PTHREAD_CANCEL
1529 int *n = xmalloc (sizeof (int));
1531 *n = 0;
1532 pthread_setspecific (signal_thread_key, n);
1533 INIT_THREAD_SIGNAL;
1534 #endif
1536 #ifdef HAVE_PR_SET_NAME
1537 prctl (PR_SET_NAME, "keepalive");
1538 #endif
1539 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1541 for (;;)
1543 int n = config_get_integer ("global", "keepalive_interval");
1544 struct timeval tv = { n, 0 };
1545 #ifndef HAVE_PTHREAD_CANCEL
1546 int *sigusr2;
1548 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1549 if (*sigusr2)
1550 break;
1551 #endif
1553 send_status_all (STATUS_KEEPALIVE, NULL);
1554 select (0, NULL, NULL, NULL, &tv);
1557 return NULL;
1560 #ifdef WITH_GNUTLS
1561 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1562 static void *
1563 get_in_addr (struct sockaddr *sa)
1565 if (sa->sa_family == AF_INET)
1566 return &(((struct sockaddr_in *) sa)->sin_addr);
1568 return &(((struct sockaddr_in6 *) sa)->sin6_addr);
1571 static void *
1572 tcp_accept_thread (void *arg)
1574 int sockfd = *(int *) arg;
1575 #ifndef HAVE_PTHREAD_CANCEL
1576 int *n = xmalloc (sizeof (int));
1578 *n = 0;
1579 pthread_setspecific (signal_thread_key, n);
1580 INIT_THREAD_SIGNAL;
1581 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1582 #endif
1584 #ifdef HAVE_PR_SET_NAME
1585 prctl (PR_SET_NAME, "tcp_accept");
1586 #endif
1587 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1589 for (;;)
1591 struct sockaddr_storage raddr;
1592 socklen_t slen = sizeof (raddr);
1593 int fd;
1594 unsigned long n;
1595 char s[INET6_ADDRSTRLEN];
1596 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1597 #ifndef HAVE_PTHREAD_CANCEL
1598 int *sigusr2;
1600 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1601 if (*sigusr2)
1602 break;
1603 #endif
1605 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1606 if (fd == -1)
1608 if (errno == EMFILE || errno == ENFILE)
1609 log_write ("accept(): %s",
1610 pwmd_strerror (gpg_error_from_errno (errno)));
1611 else if (errno != EAGAIN)
1613 if (!quit) // probably EBADF
1614 log_write ("accept(): %s", strerror (errno));
1616 break;
1619 #ifndef HAVE_PTHREAD_CANCEL
1620 select (0, NULL, NULL, NULL, &tv);
1621 #endif
1622 continue;
1625 if (quit)
1627 close (fd);
1628 break;
1631 inet_ntop (raddr.ss_family, get_in_addr ((struct sockaddr *) &raddr),
1632 s, sizeof s);
1633 (void) init_client (fd, s);
1634 n = config_get_integer ("global", "tcp_wait");
1635 if (n > 0)
1637 tv.tv_sec = (n * 100000) / 100000;
1638 tv.tv_usec = (n * 100000) % 100000;
1639 select (0, NULL, NULL, NULL, &tv);
1643 return NULL;
1646 static int
1647 start_stop_tls_with_protocol (int ipv6, int term)
1649 struct addrinfo hints, *servinfo, *p;
1650 int port = config_get_integer ("global", "tcp_port");
1651 char buf[7];
1652 int n;
1653 gpg_error_t rc;
1654 int *fd = ipv6 ? &tls6_fd : &tls_fd;
1656 if (term || config_get_boolean ("global", "enable_tcp") == 0)
1658 if (tls6_fd != -1)
1660 if (spawned_tls6)
1662 #ifdef HAVE_PTHREAD_CANCEL
1663 pthread_cancel (tls6_tid);
1664 #else
1665 pthread_kill (tls6_tid, SIGUSR2);
1666 #endif
1667 pthread_join (tls6_tid, NULL);
1670 shutdown (tls6_fd, SHUT_RDWR);
1671 close (tls6_fd);
1672 tls6_fd = -1;
1673 spawned_tls6 = 0;
1676 if (tls_fd != -1)
1678 if (spawned_tls)
1680 #ifdef HAVE_PTHREAD_CANCEL
1681 pthread_cancel (tls_tid);
1682 #else
1683 pthread_kill (tls_tid, SIGUSR2);
1684 #endif
1685 pthread_join (tls_tid, NULL);
1688 shutdown (tls_fd, SHUT_RDWR);
1689 close (tls_fd);
1690 tls_fd = -1;
1691 spawned_tls = 0;
1694 /* A client may still be connected. */
1695 if (!quit && x509_cred != NULL)
1696 tls_deinit_params ();
1698 return 1;
1701 if ((ipv6 && tls6_fd != -1) || (!ipv6 && tls_fd != -1))
1702 return 1;
1704 memset (&hints, 0, sizeof (hints));
1705 hints.ai_family = ipv6 ? AF_INET6 : AF_INET;
1706 hints.ai_socktype = SOCK_STREAM;
1707 hints.ai_flags = AI_PASSIVE;
1708 snprintf (buf, sizeof (buf), "%i", port);
1710 if ((n = getaddrinfo (NULL, buf, &hints, &servinfo)) == -1)
1712 log_write ("getaddrinfo(): %s", gai_strerror (n));
1713 return 0;
1716 for (n = 0, p = servinfo; p != NULL; p = p->ai_next)
1718 int r = 1;
1720 if ((ipv6 && p->ai_family != AF_INET6)
1721 || (!ipv6 && p->ai_family != AF_INET))
1722 continue;
1724 if ((*fd = socket (p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
1726 log_write ("socket(): %s", strerror (errno));
1727 continue;
1730 if (setsockopt (*fd, SOL_SOCKET, SO_REUSEADDR, &r, sizeof (int)) == -1)
1732 log_write ("setsockopt(): %s",
1733 pwmd_strerror (gpg_error_from_errno (errno)));
1734 freeaddrinfo (servinfo);
1735 goto fail;
1738 if (bind (*fd, p->ai_addr, p->ai_addrlen) == -1)
1740 close (*fd);
1741 log_write ("bind(): %s",
1742 pwmd_strerror (gpg_error_from_errno (errno)));
1743 continue;
1746 n++;
1747 break;
1750 freeaddrinfo (servinfo);
1752 if (!n)
1753 goto fail;
1755 #if HAVE_DECL_SO_BINDTODEVICE != 0
1756 char *tmp = config_get_string ("global", "tcp_interface");
1757 if (tmp && setsockopt (*fd, SOL_SOCKET, SO_BINDTODEVICE, tmp,
1758 strlen (tmp)) == -1)
1760 log_write ("setsockopt(): %s",
1761 pwmd_strerror (gpg_error_from_errno (errno)));
1762 xfree (tmp);
1763 goto fail;
1766 xfree (tmp);
1767 #endif
1769 if (x509_cred == NULL)
1771 char *tmp = config_get_string ("global", "tls_dh_level");
1773 rc = tls_init_params (tmp);
1774 xfree (tmp);
1775 if (rc)
1776 goto fail;
1779 if (listen (*fd, 0) == -1)
1781 log_write ("listen(): %s", strerror (errno));
1782 goto fail;
1785 if (ipv6)
1786 rc = create_thread (tcp_accept_thread, fd, &tls6_tid, 0);
1787 else
1788 rc = create_thread (tcp_accept_thread, fd, &tls_tid, 0);
1790 if (rc)
1792 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1793 pwmd_strerror (rc));
1794 goto fail;
1797 if (ipv6)
1798 spawned_tls6 = 1;
1799 else
1800 spawned_tls = 1;
1802 return 1;
1804 fail:
1805 start_stop_tls_with_protocol (0, 1);
1806 if (tls_fd != -1)
1807 close (tls_fd);
1809 if (tls6_fd != -1)
1810 close (tls6_fd);
1812 tls_fd = -1;
1813 tls6_fd = -1;
1814 return 0;
1817 static int
1818 start_stop_tls (int term)
1820 char *s = config_get_string ("global", "tcp_bind");
1821 int b;
1823 if (!s)
1824 return 0;
1826 if (!strcmp (s, "any"))
1828 b = start_stop_tls_with_protocol (0, term);
1829 if (b)
1830 b = start_stop_tls_with_protocol (1, term);
1832 else if (!strcmp (s, "ipv4"))
1833 b = start_stop_tls_with_protocol (0, term);
1834 else if (!strcmp (s, "ipv6"))
1835 b = start_stop_tls_with_protocol (1, term);
1836 else
1837 b = 0;
1839 xfree (s);
1840 return b;
1842 #endif
1844 static void *
1845 accept_thread (void *arg)
1847 int sockfd = *(int *) arg;
1848 #ifndef HAVE_PTHREAD_CANCEL
1849 int *n = xmalloc (sizeof (int));
1851 *n = 0;
1852 pthread_setspecific (signal_thread_key, n);
1853 INIT_THREAD_SIGNAL;
1854 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1855 #endif
1857 #ifdef HAVE_PR_SET_NAME
1858 prctl (PR_SET_NAME, "accept");
1859 #endif
1860 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1862 for (;;)
1864 socklen_t slen = sizeof (struct sockaddr_un);
1865 struct sockaddr_un raddr;
1866 int fd;
1867 #ifndef HAVE_PTHREAD_CANCEL
1868 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1869 int *sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1871 if (*sigusr2)
1872 break;
1873 #endif
1875 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1876 if (fd == -1)
1878 if (errno == EMFILE || errno == ENFILE)
1879 log_write ("accept(): %s",
1880 pwmd_strerror (gpg_error_from_errno (errno)));
1881 else if (errno != EAGAIN)
1883 if (!quit) // probably EBADF
1884 log_write ("accept(): %s",
1885 pwmd_strerror (gpg_error_from_errno (errno)));
1887 break;
1890 #ifndef HAVE_PTHREAD_CANCEL
1891 select (0, NULL, NULL, NULL, &tv);
1892 #endif
1893 continue;
1896 (void) init_client (fd, NULL);
1899 /* Just in case accept() failed for some reason other than EBADF */
1900 quit = 1;
1901 return NULL;
1904 static void *
1905 cache_timer_thread (void *arg)
1907 #ifndef HAVE_PTHREAD_CANCEL
1908 int *n = xmalloc (sizeof (int));
1910 *n = 0;
1911 pthread_setspecific (signal_thread_key, n);
1912 INIT_THREAD_SIGNAL;
1913 #endif
1915 #ifdef HAVE_PR_SET_NAME
1916 prctl (PR_SET_NAME, "cache timer");
1917 #endif
1918 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1920 for (;;)
1922 struct timeval tv = { 1, 0 };
1923 #ifndef HAVE_PTHREAD_CANCEL
1924 int *n;
1926 n = (int *) pthread_getspecific (signal_thread_key);
1927 if (*n)
1928 break;
1929 #endif
1931 select (0, NULL, NULL, NULL, &tv);
1932 cache_adjust_timeout ();
1935 return NULL;
1938 static int
1939 signal_loop (sigset_t sigset)
1941 int done = 0;
1942 int siint = 0;
1946 int sig;
1948 sigwait (&sigset, &sig);
1950 if (sig != SIGQUIT)
1951 log_write (_("caught signal %i (%s)"), sig, strsignal (sig));
1953 switch (sig)
1955 case SIGHUP:
1956 pthread_cond_signal (&rcfile_cond);
1957 break;
1958 case SIGUSR1:
1959 log_write (_("clearing file cache"));
1960 cache_clear (NULL);
1961 send_status_all (STATUS_CACHE, NULL);
1962 break;
1963 case SIGQUIT:
1964 done = 1;
1965 break;
1966 default:
1967 siint = 1;
1968 done = 1;
1969 break;
1972 while (!done);
1974 return siint;
1977 static void
1978 catchsig (int sig)
1980 log_write (_ ("Caught signal %i (%s). Exiting."), sig, strsignal (sig));
1981 #ifdef HAVE_BACKTRACE
1982 BACKTRACE (__FUNCTION__);
1983 #endif
1984 longjmp (jmp, 1);
1987 static void *
1988 waiting_for_exit (void *arg)
1990 int last = 0;
1991 #ifndef HAVE_PTHREAD_CANCEL
1992 int *n = xmalloc (sizeof (int));
1994 *n = 0;
1995 pthread_setspecific (signal_thread_key, n);
1996 INIT_THREAD_SIGNAL;
1997 #endif
1999 #ifdef HAVE_PR_SET_NAME
2000 prctl (PR_SET_NAME, "exiting");
2001 #endif
2002 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
2003 log_write (_("waiting for all clients to disconnect"));
2004 MUTEX_LOCK (&quit_mutex);
2005 pthread_cleanup_push (cleanup_mutex_cb, &quit_mutex);
2007 for (;;)
2009 struct timespec ts;
2010 int n;
2012 MUTEX_LOCK (&cn_mutex);
2013 n = slist_length (cn_thread_list);
2014 MUTEX_UNLOCK (&cn_mutex);
2015 if (!n)
2016 break;
2018 #ifndef HAVE_PTHREAD_CANCEL
2019 int *s = (int *) pthread_getspecific (signal_thread_key);
2020 if (*s)
2021 break;
2022 #endif
2024 if (last != n)
2026 log_write (_("%i clients remain"), n);
2027 last = n;
2030 INIT_TIMESPEC (SIG_TIMEOUT, ts);
2031 pthread_cond_timedwait (&quit_cond, &quit_mutex, &ts);
2034 kill (getpid (), SIGQUIT);
2035 pthread_cleanup_pop (1);
2036 return NULL;
2039 static int
2040 server_loop (int sockfd, char **socketpath)
2042 pthread_t accept_tid;
2043 pthread_t cache_timeout_tid;
2044 int cancel_timeout_thread = 0, cancel_accept_thread = 0;
2045 int cancel_keepalive_thread = 0;
2046 sigset_t sigset;
2047 int n;
2048 int segv = 0;
2049 gpg_error_t rc;
2051 init_commands ();
2052 sigemptyset (&sigset);
2054 /* Termination */
2055 sigaddset (&sigset, SIGTERM);
2056 sigaddset (&sigset, SIGINT);
2058 /* Clears the file cache. */
2059 sigaddset (&sigset, SIGUSR1);
2061 /* Configuration file reloading. */
2062 sigaddset (&sigset, SIGHUP);
2064 /* For exiting cleanly. */
2065 sigaddset (&sigset, SIGQUIT);
2067 #ifndef HAVE_PTHREAD_CANCEL
2069 The socket, cache and rcfile threads use this signal when
2070 pthread_cancel() is unavailable. Prevent the main thread from
2071 catching this signal from another process.
2073 sigaddset (&sigset, SIGUSR2);
2074 #endif
2076 /* When mem.c cannot find a pointer in the list (double free). */
2077 signal (SIGABRT, catchsig);
2078 sigaddset (&sigset, SIGABRT);
2079 sigprocmask (SIG_BLOCK, &sigset, NULL);
2081 #ifndef HAVE_PTHREAD_CANCEL
2082 /* Remove this signal from the watched signals in signal_loop(). */
2083 sigdelset (&sigset, SIGUSR2);
2084 #endif
2086 /* Ignored everywhere. When a client disconnects abnormally this signal
2087 * gets raised. It isn't needed though because client_thread() will check
2088 * for rcs even after the client disconnects. */
2089 signal (SIGPIPE, SIG_IGN);
2091 /* Can show a backtrace of the stack in the log. */
2092 signal (SIGSEGV, catchsig);
2094 #ifdef WITH_GNUTLS
2095 /* Needs to be done after the fork(). */
2096 if (!start_stop_tls (0))
2098 segv = 1;
2099 goto done;
2101 #endif
2103 pthread_mutex_init (&quit_mutex, NULL);
2104 pthread_cond_init (&quit_cond, NULL);
2105 char *p = get_username (getuid());
2106 log_write (_("%s started for user %s"), PACKAGE_STRING, p);
2107 xfree (p);
2109 #ifdef WITH_GNUTLS
2110 if (config_get_boolean ("global", "enable_tcp"))
2111 log_write (_("Listening on %s and TCP port %i"), *socketpath,
2112 config_get_integer ("global", "tcp_port"));
2113 else
2114 log_write (_("Listening on %s"), *socketpath);
2115 #else
2116 log_write (_("Listening on %s"), *socketpath);
2117 #endif
2119 rc = create_thread (keepalive_thread, NULL, &keepalive_tid, 0);
2120 if (rc)
2122 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2123 pwmd_strerror (rc));
2124 goto done;
2127 cancel_keepalive_thread = 1;
2128 rc = create_thread (reload_rcfile_thread, NULL, &rcfile_tid, 0);
2129 if (rc)
2131 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2132 pwmd_strerror (rc));
2133 goto done;
2136 rc = create_thread (cache_timer_thread, NULL, &cache_timeout_tid, 0);
2137 if (rc)
2139 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2140 pwmd_strerror (rc));
2141 goto done;
2144 cancel_timeout_thread = 1;
2145 rc = create_thread (accept_thread, &sockfd, &accept_tid, 0);
2146 if (rc)
2148 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2149 pwmd_strerror (rc));
2150 goto done;
2153 cancel_accept_thread = 1;
2154 if (!setjmp (jmp))
2155 signal_loop (sigset);
2156 else
2157 segv = 1;
2159 done:
2161 * We're out of the main server loop. This happens when a signal was sent
2162 * to terminate the daemon. We'll wait for all clients to disconnect
2163 * before exiting but exit immediately if another termination signal is
2164 * sent.
2166 if (cancel_accept_thread)
2168 #ifdef HAVE_PTHREAD_CANCEL
2169 int n = pthread_cancel (accept_tid);
2170 #else
2171 int n = pthread_kill (accept_tid, SIGUSR2);
2172 #endif
2173 if (!n)
2174 pthread_join (accept_tid, NULL);
2177 #ifdef WITH_GNUTLS
2178 start_stop_tls (1);
2179 #endif
2180 shutdown (sockfd, SHUT_RDWR);
2181 close (sockfd);
2182 unlink (*socketpath);
2183 xfree (*socketpath);
2184 *socketpath = NULL;
2185 MUTEX_LOCK (&cn_mutex);
2186 n = slist_length (cn_thread_list);
2187 MUTEX_UNLOCK (&cn_mutex);
2189 if (n && !segv)
2191 pthread_t tid;
2193 rc = create_thread (waiting_for_exit, NULL, &tid, 0);
2194 if (!rc)
2196 if (signal_loop (sigset))
2198 log_write (_("Received second termination request. Exiting."));
2199 #ifdef HAVE_PTHREAD_CANCEL
2200 pthread_cancel (tid);
2201 #else
2202 pthread_kill (tid, SIGUSR2);
2203 #endif
2204 pthread_join (tid, NULL);
2207 else
2208 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2209 pwmd_strerror (rc));
2212 if (cancel_timeout_thread)
2214 #ifdef HAVE_PTHREAD_CANCEL
2215 pthread_cancel (cache_timeout_tid);
2216 #else
2217 pthread_kill (cache_timeout_tid, SIGUSR2);
2218 #endif
2219 pthread_join (cache_timeout_tid, NULL);
2222 if (cancel_keepalive_thread)
2224 #ifdef HAVE_PTHREAD_CANCEL
2225 pthread_cancel (keepalive_tid);
2226 #else
2227 pthread_kill (keepalive_tid, SIGUSR2);
2228 #endif
2229 pthread_join (keepalive_tid, NULL);
2232 cleanup_all_clients (0);
2233 #ifdef WITH_GNUTLS
2234 start_stop_tls (1);
2235 #endif
2236 deinit_commands ();
2237 pthread_cond_destroy (&quit_cond);
2238 pthread_mutex_destroy (&quit_mutex);
2239 return segv ? EXIT_FAILURE : EXIT_SUCCESS;;
2242 static void
2243 startup_failure ()
2245 log_write (_
2246 ("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
2247 cache_clear (NULL);
2250 /* This is called from cache.c:clear_once(). See
2251 * command.c:clearcache_command() for details about lock checking.
2253 static gpg_error_t
2254 free_cache_data (file_cache_t * cache)
2256 gpg_error_t rc = GPG_ERR_NO_DATA;
2257 int i, t;
2258 struct client_thread_s *found = NULL;
2259 int self = 0;
2261 if (!cache->data)
2262 return 0;
2264 cache_lock ();
2265 MUTEX_LOCK (&cn_mutex);
2266 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
2267 t = slist_length (cn_thread_list);
2269 for (i = 0; i < t; i++)
2271 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2273 if (!thd->cl)
2274 continue;
2276 if (!memcmp (thd->cl->md5file, cache->filename,
2277 sizeof (cache->filename)))
2279 if (pthread_equal (pthread_self (), thd->tid))
2281 found = thd;
2282 self = 1;
2283 continue;
2286 /* Continue trying to find a client who has the same file open and
2287 * also has a lock. */
2288 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0, -1);
2289 if (!rc)
2291 self = 0;
2292 found = thd;
2293 break;
2298 if (self && (!rc || rc == GPG_ERR_NO_DATA))
2299 rc = cache_lock_mutex (found->cl->ctx, found->cl->md5file, -1, 0, -1);
2301 if (exiting || !rc || rc == GPG_ERR_NO_DATA)
2303 free_cache_data_once (cache->data);
2304 cache->data = NULL;
2305 cache->defer_clear = 0;
2306 cache->timeout = -1;
2308 if (found)
2309 cache_unlock_mutex (found->cl->md5file, 0);
2311 rc = 0;
2314 if (rc)
2315 cache->defer_clear = 1;
2317 pthread_cleanup_pop (1);
2318 cache_unlock ();
2319 return rc;
2322 static int
2323 convert_v2_datafile (const char *filename, const char *cipher,
2324 const char *keyfile, const char *keygrip,
2325 const char *sign_keygrip, int nopass,
2326 const char *outfile, const char *keyparam,
2327 uint64_t iterations)
2329 gpg_error_t rc;
2330 void *data = NULL;
2331 size_t datalen;
2332 struct crypto_s *crypto = NULL;
2333 uint16_t ver;
2334 int algo;
2335 void *key = NULL;
2336 size_t keylen = 0;
2338 if (outfile[0] == '-' && outfile[1] == 0)
2339 outfile = NULL;
2341 log_write (_("Converting version 2 data file \"%s\" ..."), filename);
2342 if (access (filename, R_OK) == -1)
2344 log_write ("%s: %s", filename,
2345 pwmd_strerror (gpg_error_from_errno (errno)));
2346 return 0;
2349 if (keyfile)
2351 log_write (_("Using passphrase file \"%s\" for decryption ..."),
2352 keyfile);
2353 if (access (keyfile, R_OK) == -1)
2355 log_write ("%s: %s", keyfile,
2356 pwmd_strerror (gpg_error_from_errno (errno)));
2357 return 0;
2361 rc = read_v2_datafile (filename, keyfile, &data, &datalen, &ver, &algo);
2362 if (rc)
2364 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2365 return 0;
2368 if (cipher)
2370 algo = cipher_string_to_gcrypt (cipher);
2371 if (algo == -1)
2373 rc = GPG_ERR_CIPHER_ALGO;
2374 goto fail;
2378 if (ver < 0x212)
2380 xmlDocPtr doc;
2382 rc = parse_doc (data, datalen, &doc);
2383 if (rc)
2384 goto fail;
2386 rc = convert_pre_212_elements (doc);
2387 gcry_free (data);
2388 data = NULL;
2389 if (!rc)
2391 xmlDocDumpFormatMemory (doc, (xmlChar **) & data, (int *) &datalen,
2393 if (!data)
2394 rc = GPG_ERR_ENOMEM;
2397 xmlFreeDoc (doc);
2398 if (rc)
2399 goto fail;
2402 rc = init_client_crypto (&crypto);
2403 if (!rc)
2405 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
2406 crypto->save.hdr.flags = set_cipher_flag (crypto->save.hdr.flags, algo);
2407 crypto->save.hdr.s2k_count = iterations;
2409 if (!use_agent)
2411 rc = export_common (NULL, 0, crypto, data, datalen, outfile, keyfile,
2412 &key, &keylen, 0, 0, nopass);
2414 #ifdef WITH_AGENT
2415 else
2417 rc = agent_set_pinentry_options (crypto->agent);
2418 if (!rc)
2419 rc = agent_export_common (crypto, keygrip, sign_keygrip, nopass,
2420 data, datalen, outfile, keyparam,
2421 no_passphrase_file ? NULL : keyfile);
2423 #endif
2424 if (!rc)
2425 log_write (_("Output written to \"%s\"."),
2426 outfile ? outfile : "<stdout>");
2429 fail:
2430 if (ver < 0x212)
2431 xmlFree (data);
2432 else
2433 gcry_free (data);
2435 gcry_free (key);
2436 cleanup_crypto (&crypto);
2438 if (rc)
2439 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2440 return rc ? 0 : 1;
2443 static void
2444 usage (const char *pn, int status)
2446 FILE *fp = status == EXIT_FAILURE ? stderr : stdout;
2448 fprintf (fp, _("Usage: %s [OPTIONS] [file1] [...]\n"
2449 " -f, --rcfile=filename load the specfied configuration file\n"
2450 " (~/.pwmd/config)\n"
2451 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2452 " --kill terminate an existing instance of pwmd\n"
2453 #ifdef WITH_AGENT
2454 " --use-agent[=integer] enable/disable use of gpg-agent\n"
2455 #endif
2456 " -n, --no-fork run as a foreground process\n"
2457 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2458 " --ignore, --force ignore file errors during startup\n"
2459 " --debug-level=keywords log protocol output (see manual for details)\n"
2460 " -o, --outfile=filename output file when importing or converting\n"
2461 " -C, --convert=filename convert a version 2 data file to version 3\n"
2462 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2463 " -k, --passphrase-file=file for use when importing or converting\n"
2464 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2465 " converting\n"
2466 " --no-passphrase when importing or converting\n"
2467 " --keygrip=hex public key to use when encrypting\n"
2468 " --sign-keygrip=hex private key to use when signing\n"
2469 " --keyparam=s-exp custom key parameters to use (RSA-2048)\n"
2470 " --cipher=string encryption cipher (aes256)\n"
2471 " --cipher-iterations=N cipher iteration count (alias for --s2k-count)\n"
2472 " --s2k-count=N hash iteration count (>65536, calibrated)\n"
2473 " --help this help text\n"
2474 " --version show version and compile time features\n"),
2475 pn);
2476 exit (status);
2479 static void
2480 unlink_stale_socket (const char *sock, const char *pidfile)
2482 log_write (_ ("removing stale socket %s"), sock);
2483 unlink (sock);
2484 unlink (pidfile);
2487 static int
2488 test_pidfile (const char *path, const char *sock, char *buf, size_t buflen,
2489 char **pidfile, int create, mode_t mode, int terminate)
2491 pid_t pid;
2492 int fd;
2493 size_t len;
2495 if (!create)
2497 snprintf (buf, buflen, "%s/%s.pid", homedir, sock);
2498 *pidfile = str_dup (buf);
2499 fd = open (buf, O_RDONLY);
2501 else
2502 fd = open (*pidfile, O_CREAT|O_WRONLY|O_TRUNC, mode);
2504 if (fd == -1)
2506 if (!create && errno != ENOENT)
2508 log_write ("%s: %s", buf, pwmd_strerror (errno));
2509 free (*pidfile);
2510 *pidfile = NULL;
2511 return -1;
2513 else if (!create && !terminate)
2514 return 0;
2516 log_write ("%s: %s", *pidfile, strerror (errno));
2517 return -1;
2520 if (create)
2522 snprintf (buf, buflen, "%i", getpid ());
2523 write (fd, buf, strlen (buf));
2524 close (fd);
2525 return 0;
2528 len = read (fd, buf, buflen);
2529 close (fd);
2530 if (len == 0)
2532 unlink_stale_socket (path, *pidfile);
2533 return 0;
2536 if (sscanf (buf, "%5i", &pid) != 1 || pid == 0)
2538 if (!terminate)
2540 unlink_stale_socket (path, *pidfile);
2541 return 0;
2545 if (kill (pid, 0) == -1)
2547 unlink_stale_socket (path, *pidfile);
2548 return 0;
2551 if (terminate)
2553 if (kill (pid, SIGTERM) == -1)
2554 log_write ("%s: %s", path, pwmd_strerror (errno));
2556 else
2557 log_write (_ ("an instance for socket %s is already running"), path);
2559 xfree (*pidfile);
2560 *pidfile = NULL;
2561 return 1;
2565 main (int argc, char *argv[])
2567 int opt;
2568 struct sockaddr_un addr;
2569 char buf[PATH_MAX];
2570 char *socketpath = NULL, *socketdir, *socketname = NULL;
2571 char *socketarg = NULL;
2572 char *datadir = NULL;
2573 char *pidfile = NULL;
2574 mode_t mode = 0600;
2575 int x;
2576 char *p;
2577 char **cache_push = NULL;
2578 char *import = NULL, *keygrip = NULL, *sign_keygrip = NULL;
2579 char *keyparam = NULL;
2580 int estatus = EXIT_FAILURE;
2581 int sockfd;
2582 char *outfile = NULL;
2583 int do_unlink = 0;
2584 int secure = 0;
2585 int show_version = 0;
2586 int force = 0;
2587 int no_passphrase = 0;
2588 gpg_error_t rc;
2589 char *convertfile = NULL;
2590 char *cipher = NULL;
2591 char *keyfile = NULL;
2592 uint64_t s2k_count = 0;
2593 int exists;
2594 char *debug_level_opt = NULL;
2595 int optindex;
2596 int terminate = 0;
2597 /* Must maintain the same order as longopts[] */
2598 enum
2600 OPT_VERSION, OPT_HELP,
2601 #ifdef WITH_AGENT
2602 OPT_AGENT,
2603 #endif
2604 OPT_DEBUG_LEVEL, OPT_HOMEDIR, OPT_NO_FORK, OPT_DISABLE_DUMP,
2605 OPT_IGNORE, OPT_FORCE, OPT_RCFILE, OPT_CONVERT,
2606 OPT_PASSPHRASE_FILE, OPT_IMPORT, OPT_OUTFILE,
2607 OPT_NO_PASSPHRASE_FILE, OPT_KEYGRIP, OPT_SIGN_KEYGRIP,
2608 OPT_KEYPARAM, OPT_CIPHER, OPT_ITERATIONS, OPT_S2K_COUNT,
2609 OPT_NO_PASSPHRASE, OPT_KILL
2611 const char *optstring = "nf:C:k:I:o:";
2612 const struct option longopts[] = {
2613 {"version", no_argument, 0, 0},
2614 {"help", no_argument, 0, 0},
2615 #ifdef WITH_AGENT
2616 {"use-agent", optional_argument, 0, 0},
2617 #endif
2618 {"debug-level", required_argument, 0, 0},
2619 {"homedir", required_argument, 0, 0},
2620 {"no-fork", no_argument, 0, 'n'},
2621 {"disable_dump", no_argument, 0, 0},
2622 {"ignore", no_argument, 0, 0},
2623 {"force", no_argument, 0, 0},
2624 {"rcfile", required_argument, 0, 'f'},
2625 {"convert", required_argument, 0, 'C'},
2626 {"passphrase-file", required_argument, 0, 'k'},
2627 {"import", required_argument, 0, 'I'},
2628 {"outfile", required_argument, 0, 'o'},
2629 {"no-passphrase-file", no_argument, 0, 0},
2630 {"keygrip", required_argument, 0, 0},
2631 {"sign-keygrip", required_argument, 0, 0},
2632 {"keyparam", required_argument, 0, 0},
2633 {"cipher", required_argument, 0, 0},
2634 {"cipher-iterations", required_argument, 0, 0},
2635 {"s2k-count", required_argument, 0, 0},
2636 {"no-passphrase", no_argument, 0, 0},
2637 {"kill", no_argument, 0, 0},
2638 {0, 0, 0, 0}
2641 log_fd = -1;
2643 #ifndef DEBUG
2644 #ifdef HAVE_SETRLIMIT
2645 struct rlimit rl;
2647 rl.rlim_cur = rl.rlim_max = 0;
2649 if (setrlimit (RLIMIT_CORE, &rl) != 0)
2650 err (EXIT_FAILURE, "setrlimit()");
2651 #endif
2653 #ifdef HAVE_PR_SET_DUMPABLE
2654 prctl (PR_SET_DUMPABLE, 0);
2655 #endif
2656 #endif
2658 #ifdef ENABLE_NLS
2659 setlocale (LC_ALL, "");
2660 bindtextdomain ("pwmd", LOCALEDIR);
2661 textdomain ("pwmd");
2662 #endif
2664 #ifndef MEM_DEBUG
2665 xmem_init ();
2666 #endif
2667 gpg_err_init ();
2669 if (setup_crypto ())
2670 exit (EXIT_FAILURE);
2672 #ifdef WITH_GNUTLS
2673 gnutls_global_init ();
2674 gnutls_global_set_log_level (1);
2675 gnutls_global_set_log_function (tls_log);
2676 gnutls_global_set_audit_log_function (tls_audit_log);
2677 tls_fd = -1;
2678 tls6_fd = -1;
2679 #endif
2680 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
2681 xmlInitMemory ();
2682 xmlInitGlobals ();
2683 xmlInitParser ();
2684 xmlXPathInit ();
2685 cmdline = 1;
2686 use_agent = -1;
2688 while ((opt = getopt_long (argc, argv, optstring, longopts, &optindex))
2689 != -1)
2691 switch (opt)
2693 case 'I':
2694 import = optarg;
2695 break;
2696 case 'C':
2697 convertfile = optarg;
2698 break;
2699 case 'k':
2700 keyfile = optarg;
2701 break;
2702 case 'o':
2703 outfile = optarg;
2704 break;
2705 case 'D':
2706 secure = 1;
2707 break;
2708 case 'n':
2709 nofork = 1;
2710 break;
2711 case 'f':
2712 rcfile = str_dup (optarg);
2713 break;
2714 default:
2715 usage (argv[0], EXIT_FAILURE);
2716 break;
2717 case 0:
2718 switch (optindex)
2720 case OPT_VERSION:
2721 show_version = 1;
2722 break;
2723 case OPT_HELP:
2724 usage (argv[0], 0);
2725 break;
2726 #ifdef WITH_AGENT
2727 case OPT_AGENT:
2728 use_agent = optarg && *optarg ? atoi (optarg) : 1;
2729 if (use_agent < 0 || use_agent > 1)
2730 usage (argv[0], 1);
2731 break;
2732 #endif
2733 case OPT_DEBUG_LEVEL:
2734 debug_level_opt = optarg;
2735 break;
2736 case OPT_HOMEDIR:
2737 homedir = str_dup (optarg);
2738 break;
2739 case OPT_NO_FORK:
2740 nofork = 1;
2741 break;
2742 case OPT_DISABLE_DUMP:
2743 secure = 1;
2744 break;
2745 case OPT_IGNORE:
2746 case OPT_FORCE:
2747 force = 1;
2748 break;
2749 case OPT_RCFILE:
2750 rcfile = str_dup (optarg);
2751 break;
2752 case OPT_CONVERT:
2753 convertfile = optarg;
2754 break;
2755 case OPT_PASSPHRASE_FILE:
2756 keyfile = optarg;
2757 break;
2758 case OPT_IMPORT:
2759 import = optarg;
2760 break;
2761 case OPT_OUTFILE:
2762 outfile = optarg;
2763 break;
2764 case OPT_NO_PASSPHRASE_FILE:
2765 no_passphrase_file = 1;
2766 break;
2767 case OPT_KEYGRIP:
2768 keygrip = optarg;
2769 break;
2770 case OPT_SIGN_KEYGRIP:
2771 sign_keygrip = optarg;
2772 break;
2773 case OPT_KEYPARAM:
2774 keyparam = optarg;
2775 break;
2776 case OPT_CIPHER:
2777 cipher = optarg;
2778 break;
2779 case OPT_ITERATIONS:
2780 case OPT_S2K_COUNT:
2781 s2k_count = strtoull (optarg, NULL, 10);
2782 break;
2783 case OPT_NO_PASSPHRASE:
2784 no_passphrase = 1;
2785 break;
2786 case OPT_KILL:
2787 terminate = 1;
2788 break;
2789 default:
2790 usage (argv[0], 1);
2795 if (show_version)
2797 printf (_("%s\n\n"
2798 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015\n"
2799 "%s\n"
2800 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2801 "Compile time features:\n%s"), PACKAGE_STRING,
2802 PACKAGE_BUGREPORT,
2803 #ifdef PWMD_HOMEDIR
2804 "+PWMD_HOMEDIR=" PWMD_HOMEDIR "\n"
2805 #endif
2806 #ifdef WITH_AGENT
2807 "+WITH_AGENT\n"
2808 #else
2809 "-WITH_AGENT\n"
2810 #endif
2811 #ifdef WITH_QUALITY
2812 "+WITH_QUALITY\n"
2813 #else
2814 "-WITH_QUALITY\n"
2815 #endif
2816 #ifdef WITH_GNUTLS
2817 "+WITH_GNUTLS\n"
2818 #else
2819 "-WITH_GNUTLS\n"
2820 #endif
2821 #ifdef DEBUG
2822 "+DEBUG\n"
2823 #else
2824 "-DEBUG\n"
2825 #endif
2826 #ifdef MEM_DEBUG
2827 "+MEM_DEBUG\n"
2828 #else
2829 "-MEM_DEBUG\n"
2830 #endif
2831 #ifdef MUTEX_DEBUG
2832 "+MUTEX_DEBUG\n"
2833 #else
2834 "-MUTEX_DEBUG\n"
2835 #endif
2837 exit (EXIT_SUCCESS);
2840 if (!homedir)
2841 #ifdef PWMD_HOMEDIR
2842 homedir = str_dup(PWMD_HOMEDIR);
2843 #else
2844 homedir = str_asprintf ("%s/.pwmd", get_home_dir());
2845 #endif
2847 if (mkdir (homedir, 0700) == -1 && errno != EEXIST)
2848 err (EXIT_FAILURE, "%s", homedir);
2850 snprintf (buf, sizeof (buf), "%s/data", homedir);
2851 if (mkdir (buf, 0700) == -1 && errno != EEXIST)
2852 err (EXIT_FAILURE, "%s", buf);
2854 datadir = str_dup (buf);
2855 pthread_mutexattr_t attr;
2856 pthread_mutexattr_init (&attr);
2857 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
2858 pthread_mutex_init (&rcfile_mutex, &attr);
2859 pthread_cond_init (&rcfile_cond, NULL);
2860 pthread_mutex_init (&cn_mutex, &attr);
2861 pthread_mutexattr_destroy (&attr);
2862 pthread_key_create (&last_error_key, free_key);
2863 #ifndef HAVE_PTHREAD_CANCEL
2864 pthread_key_create (&signal_thread_key, free_key);
2865 #endif
2867 if (!rcfile)
2868 rcfile = str_asprintf ("%s/config", homedir);
2870 global_config = config_parse (rcfile, 0);
2871 if (!global_config)
2872 exit (EXIT_FAILURE);
2874 #ifdef WITH_AGENT
2875 if (use_agent == -1)
2876 use_agent = config_get_boolean ("global", "use_agent");
2877 #endif
2879 setup_logging ();
2881 if (debug_level_opt)
2882 debug_level = str_split (debug_level_opt, ",", 0);
2884 x = config_get_int_param (global_config, "global", "priority", &exists);
2885 if (exists && x != atoi(INVALID_PRIORITY))
2887 errno = 0;
2888 if (setpriority (PRIO_PROCESS, 0, x) == -1)
2890 log_write ("setpriority(): %s",
2891 pwmd_strerror (gpg_error_from_errno (errno)));
2892 goto do_exit;
2895 #ifdef HAVE_MLOCKALL
2896 if (disable_mlock == 0 && mlockall (MCL_CURRENT | MCL_FUTURE) == -1)
2898 log_write ("mlockall(): %s",
2899 pwmd_strerror (gpg_error_from_errno (errno)));
2900 goto do_exit;
2902 #endif
2904 rc = cache_init (free_cache_data);
2905 if (rc)
2907 log_write ("pwmd: ERR %i: %s", rc,
2908 gpg_err_code (rc) == GPG_ERR_UNKNOWN_VERSION
2909 ? _("incompatible gpg-agent version: 2.1.0 or later required")
2910 : pwmd_strerror (rc));
2911 goto do_exit;
2914 if (s2k_count == 0)
2915 s2k_count = config_get_ulonglong (NULL, "s2k_count");
2917 if (convertfile)
2919 if (!outfile || !*outfile || argc != optind)
2920 usage (argv[0], EXIT_FAILURE);
2922 estatus = convert_v2_datafile (convertfile, cipher, keyfile, keygrip,
2923 sign_keygrip, no_passphrase, outfile,
2924 keyparam, s2k_count);
2925 config_free (global_config);
2926 xfree (rcfile);
2927 exit (!estatus);
2930 if (import)
2932 if (!outfile || !*outfile || argc != optind)
2933 usage (argv[0], EXIT_FAILURE);
2935 if (outfile && outfile[0] == '-' && outfile[1] == 0)
2936 outfile = NULL;
2938 estatus = xml_import (import, outfile, keygrip, sign_keygrip, keyfile,
2939 no_passphrase, cipher, keyparam, s2k_count);
2940 config_free (global_config);
2941 xfree (rcfile);
2942 exit (!estatus);
2945 p = config_get_string ("global", "socket_path");
2946 if (!p)
2947 p = str_asprintf ("%s/socket", homedir);
2949 socketarg = expand_homedir (p);
2950 xfree (p);
2952 if (!secure)
2953 disable_list_and_dump = config_get_boolean ("global",
2954 "disable_list_and_dump");
2955 else
2956 disable_list_and_dump = secure;
2958 cache_push = config_get_list ("global", "cache_push");
2960 while (optind < argc)
2962 if (strv_printf (&cache_push, "%s", argv[optind++]) == 0)
2963 errx (EXIT_FAILURE, "%s", pwmd_strerror (GPG_ERR_ENOMEM));
2966 if (strchr (socketarg, '/') == NULL)
2968 socketdir = getcwd (buf, sizeof (buf));
2969 socketname = str_dup (socketarg);
2970 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2972 else
2974 socketname = str_dup (strrchr (socketarg, '/'));
2975 socketname++;
2976 socketarg[strlen (socketarg) - strlen (socketname) - 1] = 0;
2977 socketdir = str_dup (socketarg);
2978 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2981 if (chdir (datadir))
2983 log_write ("%s: %s", datadir,
2984 pwmd_strerror (gpg_error_from_errno (errno)));
2985 unlink (socketpath);
2986 goto do_exit;
2989 x = test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 0,
2990 mode, terminate);
2991 if (!terminate && x)
2992 goto do_exit;
2993 else if (terminate)
2995 estatus = x != 1 ? EXIT_FAILURE : EXIT_SUCCESS;
2996 goto do_exit;
3000 * bind() doesn't like the full pathname of the socket or any non alphanum
3001 * characters so change to the directory where the socket is wanted then
3002 * create it then change to datadir.
3004 if (chdir (socketdir))
3006 log_write ("%s: %s", socketdir,
3007 pwmd_strerror (gpg_error_from_errno (errno)));
3008 goto do_exit;
3011 xfree (socketdir);
3013 if ((sockfd = socket (PF_UNIX, SOCK_STREAM, 0)) == -1)
3015 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
3016 goto do_exit;
3019 addr.sun_family = AF_UNIX;
3020 snprintf (addr.sun_path, sizeof (addr.sun_path), "%s", socketname);
3021 do_unlink = 1;
3022 if (bind (sockfd, (struct sockaddr *) &addr, sizeof (struct sockaddr)) ==
3025 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
3027 if (errno == EADDRINUSE)
3029 do_unlink = 0;
3030 log_write (_("Either there is another pwmd running or '%s' is a \n"
3031 "stale socket. Please remove it manually."), socketpath);
3034 goto do_exit;
3038 char *t = config_get_string ("global", "socket_perms");
3039 mode_t mask;
3041 if (t)
3043 mode = strtol (t, NULL, 8);
3044 mask = umask (0);
3045 xfree (t);
3047 if (chmod (socketname, mode) == -1)
3049 log_write ("%s: %s", socketname,
3050 pwmd_strerror (gpg_error_from_errno (errno)));
3051 close (sockfd);
3052 umask (mask);
3053 goto do_exit;
3056 umask (mask);
3060 xfree (--socketname);
3062 if (chdir (datadir))
3064 log_write ("%s: %s", datadir,
3065 pwmd_strerror (gpg_error_from_errno (errno)));
3066 close (sockfd);
3067 goto do_exit;
3070 xfree (datadir);
3073 * Set the cache entry for a file. Prompts for the password.
3075 if (cache_push)
3077 struct crypto_s *crypto = NULL;
3078 gpg_error_t rc = init_client_crypto (&crypto);
3080 if (rc)
3082 estatus = EXIT_FAILURE;
3083 goto do_exit;
3086 #ifdef WITH_AGENT
3087 if (use_agent)
3089 rc = agent_set_pinentry_options (crypto->agent);
3090 if (rc)
3092 estatus = EXIT_FAILURE;
3093 goto do_exit;
3096 #endif
3098 for (opt = 0; cache_push[opt]; opt++)
3100 if (!do_cache_push (cache_push[opt], crypto) && !force)
3102 strv_free (cache_push);
3103 startup_failure ();
3104 estatus = EXIT_FAILURE;
3105 cleanup_crypto (&crypto);
3106 goto do_exit;
3109 cleanup_crypto_stage1 (crypto);
3112 #ifdef WITH_AGENT
3113 if (use_agent)
3114 (void) kill_scd (crypto->agent);
3115 #endif
3117 cleanup_crypto (&crypto);
3118 strv_free (cache_push);
3119 log_write (!nofork ? _("Done. Daemonizing...") :
3120 _("Done. Waiting for connections..."));
3123 config_clear_keys ();
3125 if (listen (sockfd, 0) == -1)
3127 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
3128 goto do_exit;
3131 if (!nofork)
3133 switch (fork ())
3135 case -1:
3136 log_write ("fork(): %s",
3137 pwmd_strerror (gpg_error_from_errno (errno)));
3138 goto do_exit;
3139 case 0:
3140 close (0);
3141 close (1);
3142 close (2);
3143 setsid ();
3144 break;
3145 default:
3146 _exit (EXIT_SUCCESS);
3150 (void)test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 1,
3151 mode, 0);
3152 cmdline = 0;
3153 pthread_key_create (&thread_name_key, free_key);
3154 pthread_setspecific (thread_name_key, str_dup ("main"));
3155 estatus = server_loop (sockfd, &socketpath);
3157 do_exit:
3158 if (socketpath && do_unlink)
3160 unlink (socketpath);
3161 xfree (socketpath);
3164 xfree (socketarg);
3165 #ifdef WITH_GNUTLS
3166 gnutls_global_deinit ();
3167 #endif
3168 if (rcfile_tid)
3170 #ifdef HAVE_PTHREAD_CANCEL
3171 pthread_cancel (rcfile_tid);
3172 #else
3173 pthread_kill (rcfile_tid, SIGUSR2);
3174 pthread_cond_signal (&rcfile_cond);
3175 #endif
3176 pthread_join (rcfile_tid, NULL);
3179 pthread_cond_destroy (&rcfile_cond);
3180 pthread_mutex_destroy (&rcfile_mutex);
3181 pthread_key_delete (last_error_key);
3182 #ifndef HAVE_PTHREAD_CANCEL
3183 pthread_key_delete (signal_thread_key);
3184 #endif
3186 if (global_config)
3187 config_free (global_config);
3189 free_invoking_users (invoking_users);
3190 xfree (rcfile);
3191 xfree (home_directory);
3192 xfree (homedir);
3193 xmlCleanupParser ();
3194 xmlCleanupGlobals ();
3196 if (pidfile)
3197 unlink (pidfile);
3198 xfree (pidfile);
3200 if (estatus == EXIT_SUCCESS && !terminate)
3201 log_write (_("pwmd exiting normally"));
3203 pthread_key_delete (thread_name_key);
3204 closelog ();
3205 #if defined(DEBUG) && !defined(MEM_DEBUG)
3206 xdump ();
3207 #endif
3209 if (log_fd != -1)
3210 close (log_fd);
3212 exit (estatus);
3215 gpg_error_t lock_flock (assuan_context_t ctx, const char *filename,
3216 int type, int *fd)
3218 gpg_error_t rc = 0;
3220 #ifdef HAVE_FLOCK
3221 *fd = open (filename, O_RDONLY);
3222 if (*fd == -1)
3223 return gpg_error_from_syserror ();
3225 TRY_FLOCK (ctx, *fd, type, rc);
3226 if (rc)
3228 close (*fd);
3229 *fd = -1;
3231 #endif
3233 return rc;
3236 void unlock_flock (int *fd)
3238 #ifdef HAVE_FLOCK
3239 if (*fd != -1)
3240 close (*fd);
3242 *fd = -1;
3243 #endif