Keep "gpg_homedir" and list file settings across SIGHUP.
[libpwmd.git] / src / pwmd.c
blob6e2a65dfe1f5db1e1b259e2e6d137eaa99bf6516
1 /*
2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015,
3 2016
4 Ben Kibbey <bjk@luxsci.net>
6 This file is part of pwmd.
8 Pwmd is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 2 of the License, or
11 (at your option) any later version.
13 Pwmd is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
21 #ifdef HAVE_CONFIG_H
22 #include <config.h>
23 #endif
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <err.h>
29 #include <ctype.h>
30 #include <string.h>
31 #include <sys/socket.h>
32 #include <sys/un.h>
33 #include <signal.h>
34 #include <stdarg.h>
35 #include <string.h>
36 #include <sys/wait.h>
37 #include <fcntl.h>
38 #include <pwd.h>
39 #include <grp.h>
40 #include <pthread.h>
41 #include <sys/mman.h>
42 #include <termios.h>
43 #include <assert.h>
44 #include <syslog.h>
45 #include <netinet/in.h>
46 #include <arpa/inet.h>
47 #include <netdb.h>
48 #include <sys/time.h>
49 #include <sys/resource.h>
50 #include <setjmp.h>
51 #include <errno.h>
52 #include <poll.h>
54 #ifdef TM_IN_SYS_TIME
55 #include <sys/time.h>
56 #else
57 #include <time.h>
58 #endif
60 #ifdef HAVE_LIMITS_H
61 #include <limits.h>
62 #endif
64 #ifdef HAVE_GETOPT_LONG
65 #ifdef HAVE_GETOPT_H
66 #include <getopt.h>
67 #endif
68 #else
69 #include "getopt_long.h"
70 #endif
72 #ifdef HAVE_PR_SET_NAME
73 #include <sys/prctl.h>
74 #endif
76 #include "pwmd-error.h"
77 #include <gcrypt.h>
79 #include "util-misc.h"
80 #include "mem.h"
81 #include "xml.h"
82 #include "common.h"
83 #include "commands.h"
84 #include "cache.h"
85 #include "util-string.h"
86 #include "mutex.h"
87 #include "rcfile.h"
88 #include "crypto.h"
89 #include "acl.h"
91 static int quit;
92 static int cmdline;
93 static jmp_buf jmp;
94 static int nofork;
95 static int log_fd;
96 static unsigned assuan_level;
98 #ifndef HAVE_PTHREAD_CANCEL
99 #define INIT_SIGNAL(s, cb) do { \
100 int *n = xmalloc (sizeof (int)); \
101 *n = 0; \
102 pthread_setspecific (signal_thread_key, n); \
103 struct sigaction act; \
104 sigset_t sigset; \
105 sigemptyset (&sigset); \
106 sigaddset (&sigset, s); \
107 pthread_sigmask (SIG_UNBLOCK, &sigset, NULL); \
108 memset (&act, 0, sizeof(act)); \
109 act.sa_flags = SA_SIGINFO; \
110 act.sa_mask = sigset; \
111 act.sa_sigaction = cb; \
112 sigaction (s, &act, NULL); \
113 } while (0)
115 static void
116 catch_thread_signal (int sig, siginfo_t *info, void *ctx)
118 int *n = (int *) pthread_getspecific (signal_thread_key);
120 *n = 1;
122 #endif
124 static void
125 setup_logging ()
127 int n = config_get_boolean ("global", "enable_logging");
129 if (n)
131 char *p = config_get_string ("global", "log_path");
133 if (!p || (logfile && p && log_fd != -1 && strcmp(p, logfile)))
135 if (log_fd != -1)
136 close (log_fd);
138 log_fd = -1;
141 xfree (logfile);
142 logfile = NULL;
143 if (p)
144 logfile = expand_homedir (p);
145 xfree (p);
147 else
149 xfree (logfile);
150 logfile = NULL;
151 if (log_fd != -1)
152 close(log_fd);
154 log_fd = -1;
155 closelog ();
158 log_syslog = config_get_boolean ("global", "syslog");
159 if (log_syslog == 1)
160 openlog ("pwmd", LOG_NDELAY | LOG_PID, LOG_DAEMON);
163 static void *
164 reload_rcfile_thread (void *arg)
166 #ifndef HAVE_PTHREAD_CANCEL
167 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
168 #endif
170 #ifdef HAVE_PR_SET_NAME
171 prctl (PR_SET_NAME, "reload rcfile");
172 #endif
173 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
174 MUTEX_LOCK (&rcfile_mutex);
176 (void)arg;
178 for (;;)
180 struct slist_s *keep = NULL;
181 struct slist_s *config;
182 int b = disable_list_and_dump;
183 #ifdef WITH_GNUTLS
184 char *prio;
185 char *prio2 = NULL;
186 #endif
188 pthread_cleanup_push (release_mutex_cb, &rcfile_mutex);
189 pthread_cond_wait (&rcfile_cond, &rcfile_mutex);
190 TEST_CANCEL ();
191 keep = config_keep_save ();
192 log_write (_("reloading configuration file '%s'"), rcfile);
194 #ifdef WITH_GNUTLS
195 prio = config_get_string ("global", "tls_cipher_suite");
196 #endif
197 config = config_parse (rcfile, 1);
198 if (config)
200 config_free (global_config);
201 global_config = config;
202 setup_logging ();
205 config_keep_restore (keep);
206 disable_list_and_dump = !disable_list_and_dump ? b : 1;
208 #ifdef WITH_GNUTLS
209 /* Restart listening sockets since they may have changed. */
210 tls_start_stop (1);
211 tls_start_stop (0);
213 prio2 = config_get_string ("global", "tls_cipher_suite");
214 if ((prio2 && (!prio || strcmp (prio, prio2))) || (prio && !prio2))
215 tls_rehandshake ();
217 xfree (prio2);
218 xfree (prio);
219 #endif
220 crypto_set_keepalive ();
221 pthread_cleanup_pop (0);
224 MUTEX_UNLOCK (&rcfile_mutex);
225 return NULL;
228 gpg_error_t
229 send_error (assuan_context_t ctx, gpg_error_t e)
231 struct client_s *client = assuan_get_pointer (ctx);
233 if (gpg_err_source (e) == GPG_ERR_SOURCE_UNKNOWN)
234 e = gpg_error (e);
236 if (client)
237 client->last_rc = e;
239 if (!e)
240 return assuan_process_done (ctx, 0);
242 if (!ctx)
244 log_write ("ERR %i: %s", e, pwmd_strerror (e));
245 return e;
248 if (client && client->xml_error)
250 log_write ("%s", client->xml_error->message);
251 xfree (client->last_error);
252 client->last_error = NULL;
253 if (client->xml_error->message)
254 client->last_error = str_dup (client->xml_error->message);
256 e = assuan_process_done (ctx,
257 assuan_set_error (ctx, e,
258 client->xml_error->message ? client->xml_error->message : NULL));
259 xmlResetLastError ();
260 xmlResetError (client->xml_error);
261 xfree (client->xml_error);
262 client->xml_error = NULL;
263 return e;
266 return assuan_process_done (ctx,
267 assuan_set_error (ctx, e, pwmd_strerror (e)));
270 void
271 log_write (const char *fmt, ...)
273 char *args;
274 va_list ap;
275 time_t now;
276 char buf[255];
277 pthread_t tid = pthread_self ();
278 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
280 if ((!logfile && !isatty (STDERR_FILENO) && !log_syslog) || !fmt)
281 return;
283 MUTEX_LOCK (&m);
284 pthread_cleanup_push (release_mutex_cb, &m);
286 if (!cmdline && logfile && log_fd == -1)
288 log_fd = open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600);
289 if (log_fd == -1)
290 warn ("%s", logfile);
293 va_start (ap, fmt);
295 if (str_vasprintf (&args, fmt, ap) != -1)
297 pthread_cleanup_push (xfree, args);
298 if (cmdline)
300 fprintf (stderr, "pwmd: %s\n", args);
301 fflush (stderr);
303 else
305 char *name = pthread_getspecific (thread_name_key);
306 char *line;
308 if (name)
310 if (*name == '!')
311 snprintf (buf, sizeof (buf), "%s: ", name+1);
312 else
313 snprintf (buf, sizeof (buf), "%s(%p): ", name,
314 (pthread_t *)tid);
316 else
317 snprintf (buf, sizeof (buf), "%p: ", (pthread_t *)tid);
319 name = buf;
320 if (!cmdline && log_syslog && !nofork)
321 syslog (LOG_INFO, "%s%s", name, args);
323 time (&now);
324 struct tm *tm = localtime (&now);
325 char tbuf[21];
326 strftime (tbuf, sizeof (tbuf), "%b %d %Y %H:%M:%S ", tm);
327 tbuf[sizeof (tbuf) - 1] = 0;
329 if (args[strlen (args) - 1] == '\n')
330 args[strlen (args) - 1] = 0;
332 line = str_asprintf ("%s %i %s%s\n", tbuf, getpid (), name,
333 args);
334 if (line)
336 pthread_cleanup_push (xfree, line);
337 if (logfile && log_fd != -1)
339 ssize_t ret = write (log_fd, line, strlen (line));
340 (void)ret;
341 fsync (log_fd);
344 if (nofork)
346 fprintf (stdout, "%s", line);
347 fflush (stdout);
350 pthread_cleanup_pop (1);
353 pthread_cleanup_pop (1);
356 va_end (ap);
358 if (log_fd != -1 && log_keepopen <= 0)
360 close(log_fd);
361 log_fd = -1;
364 pthread_cleanup_pop (1);
367 static gpg_error_t
368 setup_crypto ()
370 gpg_error_t rc;
372 if (!gpgrt_check_version (REQUIRE_LIBGPGERROR_VERSION))
374 fprintf (stderr, _("gpgrt_check_version(): Incompatible libgpg-error. "
375 "Wanted %s, got %s.\n"), REQUIRE_LIBGPGERROR_VERSION,
376 gpgrt_check_version (NULL));
377 return GPG_ERR_UNKNOWN_VERSION;
380 gpgrt_init ();
381 //gpgrt_set_alloc_func (xrealloc_gpgrt);
383 if (!assuan_check_version (REQUIRE_LIBASSUAN_VERSION))
385 fprintf (stderr, _("assuan_check_version(): Incompatible libassuan. "
386 "Wanted %s, got %s.\n"), REQUIRE_LIBASSUAN_VERSION,
387 assuan_check_version (NULL));
388 return GPG_ERR_UNKNOWN_VERSION;
391 if (!gcry_check_version (REQUIRE_LIBGCRYPT_VERSION))
393 fprintf (stderr, _("gcry_check_version(): Incompatible libgcrypt. "
394 "Wanted %s, got %s.\n"), REQUIRE_LIBGCRYPT_VERSION,
395 gcry_check_version (NULL));
396 return GPG_ERR_UNKNOWN_VERSION;
399 gcry_set_allocation_handler (xmalloc, xmalloc, NULL, xrealloc, xfree);
401 if (!gpgme_check_version (REQUIRE_LIBGPGME_VERSION))
403 fprintf (stderr, _("gpgme_check_version(): Incompatible libgpgme. "
404 "Wanted %s, got %s.\n"), REQUIRE_LIBGPGME_VERSION,
405 gpgme_check_version (NULL));
406 return GPG_ERR_UNKNOWN_VERSION;
409 rc = gpgme_engine_check_version (GPGME_PROTOCOL_OPENPGP);
410 if (rc)
412 fprintf (stderr, _("gpgme_engine_check_version(GPGME_PROTOCOL_OPENPGP): %s"), gpgme_strerror (rc));
413 return GPG_ERR_UNKNOWN_VERSION;
416 //gpgme_set_global_flag ("require-gnupg", REQUIRE_GNUPG_VERSION);
417 #ifdef ENABLE_NLS
418 gpgme_set_locale (NULL, LC_CTYPE, setlocale (LC_CTYPE, NULL));
419 gpgme_set_locale (NULL, LC_MESSAGES, setlocale (LC_MESSAGES, NULL));
420 #endif
422 #ifdef WITH_GNUTLS
423 if (gnutls_global_init ())
425 fprintf(stderr, _("gnutls_global_init() failed.\n"));
426 return GPG_ERR_UNKNOWN_VERSION;
429 if (!gnutls_check_version (REQUIRE_LIBGNUTLS_VERSION))
431 fprintf (stderr, _("gnutls_check_version(): Incompatible libgnutls. "
432 "Wanted %s, got %s.\n"), REQUIRE_LIBGNUTLS_VERSION,
433 gnutls_check_version (NULL));
434 return GPG_ERR_UNKNOWN_VERSION;
437 gnutls_global_set_log_function (tls_log);
438 gnutls_global_set_audit_log_function (tls_audit_log);
439 #endif
440 return 0;
443 static void
444 xml_error_cb (void *data, xmlErrorPtr e)
446 struct client_s *client = data;
449 * Keep the first reported error as the one to show in the error
450 * description. Reset in send_error().
452 if (client->xml_error)
453 return;
455 client->xml_error = xcalloc (1, sizeof(xmlError));
456 xmlCopyError (e, client->xml_error);
459 static pid_t
460 hook_waitpid (assuan_context_t ctx, pid_t pid, int action,
461 int *status, int options)
463 (void)ctx;
464 (void)action;
465 return waitpid (pid, status, options);
468 static ssize_t
469 hook_read (assuan_context_t ctx, assuan_fd_t fd, void *data, size_t len)
471 TEST_CANCEL ();
472 #ifdef WITH_GNUTLS
473 struct client_s *client = assuan_get_pointer (ctx);
475 if (client->thd->remote)
476 return tls_read_hook (ctx, (int) fd, data, len);
477 #else
478 (void)ctx;
479 #endif
481 return read ((int) fd, data, len);
484 static ssize_t
485 hook_write (assuan_context_t ctx, assuan_fd_t fd,
486 const void *data, size_t len)
488 TEST_CANCEL ();
489 #ifdef WITH_GNUTLS
490 struct client_s *client = assuan_get_pointer (ctx);
492 if (client->thd->remote)
493 return tls_write_hook (ctx, (int) fd, data, len);
494 #else
495 (void)ctx;
496 #endif
498 return write ((int) fd, data, len);
502 assuan_log_cb (assuan_context_t ctx, void *data, unsigned cat,
503 const char *msg)
505 struct client_s *client = data;
506 const char *str = NULL;
508 (void)client;
509 (void)ctx;
511 if (!(assuan_level & cat))
512 return 0;
514 if (!msg)
515 return 1;
517 switch (cat)
519 case ASSUAN_LOG_INIT:
520 str = "ASSUAN[INIT]";
521 break;
522 case ASSUAN_LOG_CTX:
523 str = "ASSUAN[CTX]";
524 break;
525 case ASSUAN_LOG_ENGINE:
526 str = "ASSUAN[ENGINE]";
527 break;
528 case ASSUAN_LOG_DATA:
529 str = "ASSUAN[DATA]";
530 break;
531 case ASSUAN_LOG_SYSIO:
532 str = "ASSUAN[SYSIO]";
533 break;
534 case ASSUAN_LOG_CONTROL:
535 str = "ASSUAN[CONTROL]";
536 break;
537 default:
538 str = "ASSUAN[UNKNOWN]";
539 break;
542 log_write ("%s: %s", str, msg);
543 return 1;
546 static int
547 new_connection (struct client_s *cl)
549 gpg_error_t rc;
550 static struct assuan_malloc_hooks mhooks = { xmalloc, xrealloc, xfree };
551 static struct assuan_system_hooks shooks = {
552 ASSUAN_SYSTEM_HOOKS_VERSION,
553 __assuan_usleep,
554 __assuan_pipe,
555 __assuan_close,
556 hook_read,
557 hook_write,
558 //FIXME
559 NULL, //recvmsg
560 NULL, //sendmsg both are used for FD passing
561 __assuan_spawn,
562 hook_waitpid,
563 __assuan_socketpair,
564 __assuan_socket,
565 __assuan_connect
568 #ifdef WITH_GNUTLS
569 if (cl->thd->remote)
571 char *prio = config_get_string ("global", "tls_cipher_suite");
573 cl->thd->timeout = config_get_integer ("global", "tls_timeout");
574 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
575 return 0;
577 cl->thd->tls = tls_init_client (cl->thd->fd, cl->thd->timeout, prio);
578 xfree (prio);
579 if (!cl->thd->tls)
580 return 0;
582 #endif
584 rc = assuan_new_ext (&cl->ctx, GPG_ERR_SOURCE_DEFAULT, &mhooks,
585 assuan_log_cb, cl);
586 if (rc)
587 goto fail;
589 assuan_ctx_set_system_hooks (cl->ctx, &shooks);
590 rc = assuan_init_socket_server (cl->ctx, cl->thd->fd, 2);
591 if (rc)
592 goto fail;
594 assuan_set_pointer (cl->ctx, cl);
595 assuan_set_hello_line (cl->ctx, PACKAGE_STRING);
596 rc = register_commands (cl->ctx);
597 if (rc)
598 goto fail;
600 rc = assuan_accept (cl->ctx);
601 if (rc)
602 goto fail;
604 rc = validate_peer (cl);
605 /* May not be implemented on all platforms. */
606 if (rc && gpg_err_code (rc) != GPG_ERR_ASS_GENERAL)
607 goto fail;
609 MUTEX_LOCK (&cn_mutex);
610 cl->thd->state = CLIENT_STATE_INIT;
611 MUTEX_UNLOCK (&cn_mutex);
612 cl->lock_timeout = config_get_integer ("global", "lock_timeout");
613 xmlSetStructuredErrorFunc (cl, xml_error_cb);
614 return 1;
616 fail:
617 log_write ("%s", pwmd_strerror (rc));
618 return 0;
622 * This is called after a client is cancelled or disconnects. Set with
623 * pthread_cleanup_push().
625 static void
626 free_client_cb (void *arg)
628 struct client_thread_s *cn = arg;
629 struct client_s *cl = cn->cl;
630 #ifndef HAVE_PTHREAD_CANCEL
631 char *tmp = pthread_getspecific (signal_thread_key);
633 xfree (tmp);
634 pthread_setspecific (signal_thread_key, NULL);
635 #endif
636 MUTEX_LOCK (&cn_mutex);
637 cn_thread_list = slist_remove (cn_thread_list, cn);
638 MUTEX_UNLOCK (&cn_mutex);
640 if (cl)
642 unlock_flock (&cl->flock_fd);
643 reset_client (cl);
644 if (cl->xml_error)
645 xmlResetError (cl->xml_error);
647 xfree (cl->xml_error);
649 #ifdef WITH_GNUTLS
650 if (cn->tls)
652 gnutls_deinit (cn->tls->ses);
653 xfree (cn->tls->fp);
654 xfree (cn->tls);
656 #endif
658 if (cl->ctx)
659 assuan_release (cl->ctx);
660 else if (cl->thd && cl->thd->fd != -1)
661 close (cl->thd->fd);
663 if (cl->crypto)
664 crypto_free (cl->crypto);
666 cl->crypto = NULL;
667 xfree (cl);
669 else
671 if (cn->fd != -1)
672 close (cn->fd);
675 while (cn->msg_queue)
677 struct status_msg_s *msg = cn->msg_queue;
679 cn->msg_queue = msg->next;
680 xfree (msg->line);
681 xfree (msg);
684 if (cn->status_msg_pipe[0] != -1)
685 close (cn->status_msg_pipe[0]);
687 if (cn->status_msg_pipe[1] != -1)
688 close (cn->status_msg_pipe[1]);
690 pthread_mutex_destroy (&cn->status_mutex);
691 log_write (_("exiting, fd=%i"), cn->fd);
692 send_status_all (STATUS_CLIENTS, NULL);
694 #ifdef WITH_GNUTLS
695 xfree (cn->peeraddr);
696 #endif
697 xfree (cn);
700 static void
701 free_all_clients ()
703 MUTEX_LOCK (&cn_mutex);
704 pthread_cleanup_push (release_mutex_cb, &cn_mutex);
706 while (slist_length (cn_thread_list))
708 struct client_thread_s *thd = slist_nth_data (cn_thread_list, 0);
710 free_client_cb (thd);
713 pthread_cleanup_pop (1);
716 static gpg_error_t
717 send_msg_queue (struct client_thread_s *thd)
719 MUTEX_LOCK (&thd->status_mutex);
720 gpg_error_t rc = 0;
721 char c;
722 ssize_t ret;
724 ret = read (thd->status_msg_pipe[0], &c, 1);
725 rc = gpg_error_from_syserror ();
726 if (ret == -1 && gpg_err_code (rc) != GPG_ERR_EAGAIN)
727 log_write ("%s (%i): %s", __FUNCTION__, __LINE__, pwmd_strerror (rc));
728 else
729 rc = 0;
731 thd->wrote_status = 0;
733 while (thd->msg_queue)
735 struct status_msg_s *msg = thd->msg_queue;
737 thd->msg_queue = thd->msg_queue->next;
738 MUTEX_UNLOCK (&thd->status_mutex);
739 pthread_cleanup_push (xfree, msg);
740 pthread_cleanup_push (xfree, msg->line);
741 rc = send_status (thd->cl->ctx, msg->s, msg->line);
742 pthread_cleanup_pop (1);
743 pthread_cleanup_pop (1);
744 MUTEX_LOCK (&thd->status_mutex);
745 if (rc)
746 break;
749 MUTEX_UNLOCK (&thd->status_mutex);
750 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
751 log_write ("%s (%i): %s", __FUNCTION__, __LINE__, pwmd_strerror (rc));
753 return rc;
756 static void *
757 client_thread (void *data)
759 struct client_thread_s *thd = data;
760 struct client_s *cl = xcalloc (1, sizeof (struct client_s));
761 struct slist_s *list;
762 gpg_error_t rc = 0;
763 #ifndef HAVE_PTHREAD_CANCEL
764 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
765 #endif
767 #ifdef HAVE_PR_SET_NAME
768 prctl (PR_SET_NAME, "client");
769 #endif
770 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
772 if (!cl)
774 log_write ("%s(%i): %s", __FILE__, __LINE__,
775 pwmd_strerror (GPG_ERR_ENOMEM));
776 return NULL;
779 MUTEX_LOCK (&cn_mutex);
780 pthread_cleanup_push (free_client_cb, thd);
781 thd->cl = cl;
782 cl->thd = thd;
783 cl->flock_fd = -1;
785 list = slist_append (cn_thread_list, thd);
786 if (list)
787 cn_thread_list = list;
788 else
790 log_write ("%s(%i): %s", __FILE__, __LINE__,
791 pwmd_strerror (GPG_ERR_ENOMEM));
792 MUTEX_UNLOCK (&cn_mutex);
793 return NULL;
796 if (fcntl (thd->status_msg_pipe[0], F_SETFL, O_NONBLOCK) == -1)
797 rc = gpg_error_from_errno (errno);
799 if (!rc)
800 if (fcntl (thd->status_msg_pipe[1], F_SETFL, O_NONBLOCK) == -1)
801 rc = gpg_error_from_errno (errno);
803 MUTEX_UNLOCK (&cn_mutex);
805 if (rc)
807 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
808 return NULL;
811 if (new_connection (cl))
813 int finished = 0;
814 struct pollfd fds[2];
816 fds[0].fd = thd->fd;
817 fds[0].events = POLLIN;
818 fds[1].fd = thd->status_msg_pipe[0];
819 fds[1].events = POLLIN;
821 send_status_all (STATUS_CLIENTS, NULL);
822 rc = send_status (cl->ctx, STATUS_CACHE, NULL);
823 if (rc)
825 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
826 finished = 1;
829 while (!finished)
831 int n;
832 int eof;
834 n = poll (fds, 2, 100);
835 if (n == -1)
837 log_write ("%s", strerror (errno));
838 break;
841 #ifdef WITH_GNUTLS
842 if (thd->remote && thd->tls && thd->tls->rehandshake)
844 char *prio;
845 int ret;
846 const char *e;
848 if (thd->tls->rehandshake == 1)
850 prio = config_get_string ("global", "tls_cipher_suite");
851 if (!prio)
853 thd->tls->rehandshake = 0;
854 continue;
857 ret = gnutls_priority_set_direct (thd->tls->ses, prio, &e);
858 if (ret == GNUTLS_E_SUCCESS)
860 rc = send_status (cl->ctx, STATUS_REHANDSHAKE, NULL);
861 if (!rc)
863 rc = assuan_send_data (cl->ctx, NULL, 0);
864 if (!rc)
866 ret = gnutls_rehandshake (thd->tls->ses);
867 if (ret)
869 log_write ("%s", gnutls_strerror (ret));
870 thd->tls->rehandshake = 0;
872 else
873 thd->tls->rehandshake = 2;
877 if (rc)
878 log_write ("%s", pwmd_strerror (rc));
880 else
881 log_write ("%s: %s", gnutls_strerror (ret), e);
883 xfree (prio);
884 continue;
887 #endif
889 if (!n)
890 continue;
892 if (fds[1].revents & POLLIN)
894 #ifdef WITH_GNUTLS
895 if (!thd->remote || (thd->tls && !thd->tls->rehandshake))
896 #endif
898 rc = send_msg_queue (thd);
899 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
900 break;
904 #ifdef HAVE_PTHREAD_CANCEL
905 if (!(fds[0].revents & POLLIN))
906 #else
907 if (thd->fd != -1 && !(fds[0].revents & POLLIN))
908 #endif
909 continue;
911 rc = assuan_process_next (cl->ctx, &eof);
912 if (rc || eof)
914 if (gpg_err_code (rc) == GPG_ERR_EOF || eof)
915 break;
917 log_write ("assuan_process_next(): rc=%u %s", rc,
918 pwmd_strerror (rc));
919 if (rc == gpg_error (GPG_ERR_ETIMEDOUT))
920 break;
922 rc = send_error (cl->ctx, rc);
923 if (rc)
925 log_write ("assuan_process_done(): rc=%u %s", rc,
926 pwmd_strerror (rc));
927 break;
931 /* Since the msg queue pipe fd's are non-blocking, check for
932 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
933 * client has already disconnected and will be converted to
934 * GPG_ERR_EOF during assuan_process_next().
936 #ifdef WITH_GNUTLS
937 if (!thd->remote || (thd->tls && !thd->tls->rehandshake))
938 #endif
940 rc = send_msg_queue (thd);
941 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
942 break;
947 /* Don't do pthread_exit() here because any set pthread_cleanup_push
948 * functions would be called after a command failed but then the client
949 * exited normally which may lead to a double free. */
950 pthread_cleanup_pop (1);
951 return NULL;
954 static gpg_error_t
955 xml_import (const char *filename, const char *outfile, char **keyid,
956 char **sign_keyid, char *keyfile, const char *keyparam,
957 int symmetric)
959 xmlDocPtr doc;
960 int fd;
961 struct stat st;
962 int len;
963 xmlChar *xmlbuf;
964 gpg_error_t rc = 0;
965 struct crypto_s *crypto = NULL;
967 rc = open_check_file (filename, &fd, &st, 0);
968 if (rc)
969 return rc;
971 xmlbuf = xmalloc (st.st_size + 1);
972 if (!xmlbuf)
974 close (fd);
975 return GPG_ERR_ENOMEM;
978 if (read (fd, xmlbuf, st.st_size) == -1)
980 rc = gpg_error_from_errno (errno);
981 close (fd);
982 xfree (xmlbuf);
983 return rc;
986 close (fd);
987 xmlbuf[st.st_size] = 0;
988 // Be sure the document validates.
989 doc = xmlReadDoc (xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS);
990 xfree (xmlbuf);
991 if (!doc)
992 return GPG_ERR_BAD_DATA;
994 xmlNodePtr n = xmlDocGetRootElement (doc);
995 if (n && !xmlStrEqual (n->name, (xmlChar *) "pwmd"))
996 rc = GPG_ERR_BAD_DATA;
998 if (!rc)
1000 rc = xml_validate_import (NULL, n ? n->children : n);
1001 if (!rc)
1003 rc = crypto_init (&crypto, NULL, filename, keyfile != NULL, keyfile);
1004 if (!rc)
1006 if (keyfile)
1008 crypto->flags |= CRYPTO_FLAG_KEYFILE;
1009 crypto->keyfile = str_dup (keyfile);
1012 xmlDocDumpMemory (doc, &crypto->plaintext, &len);
1013 if (len > 0)
1014 crypto->plaintext_size = len;
1015 else
1016 rc = GPG_ERR_ENOMEM;
1021 if (!rc)
1023 if (!symmetric && (keyparam || !keyid))
1025 char *buf = NULL;
1027 if (keyparam)
1029 rc = open_check_file (keyparam, &fd, &st, 0);
1030 if (!rc)
1032 buf = xmalloc (st.st_size+1);
1033 if (!buf)
1034 rc = GPG_ERR_ENOMEM;
1036 if (!rc)
1038 len = read (fd, buf, st.st_size);
1039 if (len != st.st_size)
1040 rc = gpg_error_from_errno (errno);
1042 if (!rc)
1043 buf[len] = 0;
1046 close (fd);
1049 else
1051 buf = crypto_default_key_params ();
1052 if (!buf)
1053 rc = GPG_ERR_ENOMEM;
1056 if (!rc)
1057 rc = crypto_genkey (NULL, crypto, (unsigned char *)buf);
1059 xfree (buf);
1061 else
1063 crypto->save.pubkey = strv_dup (keyid);
1064 crypto->save.sigkey = strv_dup (sign_keyid);
1067 if (!rc)
1069 crypto->flags |= symmetric ? CRYPTO_FLAG_SYMMETRIC : 0;
1070 rc = crypto_encrypt (NULL, crypto);
1074 if (!rc)
1076 if (!strcmp (outfile, "-"))
1077 outfile = NULL;
1079 xfree (crypto->plaintext);
1080 crypto->plaintext = NULL;
1081 xfree (crypto->filename);
1082 crypto->filename = outfile ? str_dup (outfile) : NULL;
1083 rc = crypto_write_file (crypto);
1086 xmlFreeDoc (doc);
1087 crypto_free (crypto);
1088 return rc;
1091 static gpg_error_t
1092 do_cache_push (struct crypto_s *crypto)
1094 gpg_error_t rc;
1095 xmlDocPtr doc;
1096 struct cache_data_s *cdata;
1097 unsigned char *crc;
1098 size_t len;
1099 int fd = -1;
1101 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1102 crypto->filename);
1104 if (valid_filename (crypto->filename) == 0)
1106 log_write (_("%s: Invalid characters in filename"), crypto->filename);
1107 return GPG_ERR_INV_VALUE;
1110 rc = lock_flock (NULL, crypto->filename, LOCK_SH, &fd);
1111 if (!rc)
1112 rc = crypto_decrypt (NULL, crypto);
1113 if (rc)
1115 unlock_flock (&fd);
1116 return rc;
1119 rc = xml_parse_doc ((char *) crypto->plaintext, crypto->plaintext_size, &doc);
1120 if (rc)
1122 unlock_flock (&fd);
1123 log_write ("%s", pwmd_strerror (rc));
1124 return rc;
1127 cdata = xcalloc (1, sizeof (struct cache_data_s));
1128 if (!cdata)
1130 unlock_flock (&fd);
1131 xmlFreeDoc (doc);
1132 return GPG_ERR_ENOMEM;
1135 rc = get_checksum (crypto->filename, &crc, &len);
1136 unlock_flock (&fd);
1137 if (rc)
1139 xmlFreeDoc (doc);
1140 cache_free_data_once (cdata);
1141 return rc;
1144 cdata->crc = crc;
1145 rc = cache_encrypt (crypto);
1146 if (!rc)
1148 cdata->doc = crypto->plaintext;
1149 cdata->size = crypto->plaintext_size;
1150 crypto->plaintext = NULL;
1151 cdata->pubkey = crypto->pubkey;
1152 cdata->sigkey = crypto->sigkey;
1153 crypto->pubkey = NULL;
1154 crypto->sigkey = NULL;
1156 else
1158 xmlFreeDoc (doc);
1159 cache_free_data_once (cdata);
1160 return rc;
1163 int timeout = config_get_integer (crypto->filename, "cache_timeout");
1164 rc = cache_add_file (crypto->filename, cdata, timeout);
1165 return rc;
1168 static gpg_error_t
1169 init_client (int fd, const char *addr)
1171 gpg_error_t rc = 0;
1172 struct client_thread_s *new = xcalloc (1, sizeof (struct client_thread_s));
1174 if (!new)
1176 close (fd);
1177 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (ENOMEM));
1178 return GPG_ERR_ENOMEM;
1181 MUTEX_LOCK (&cn_mutex);
1182 pthread_cleanup_push (release_mutex_cb, &cn_mutex);
1183 new->conntime = time (NULL);
1185 if (pipe (new->status_msg_pipe) == -1)
1186 rc = gpg_error_from_errno (errno);
1187 else
1188 pthread_mutex_init (&new->status_mutex, NULL);
1190 if (!rc)
1192 #ifdef WITH_GNUTLS
1193 new->remote = addr ? 1 : 0;
1194 if (addr)
1195 new->peeraddr = str_dup (addr);
1196 #endif
1197 new->fd = fd;
1198 rc = create_thread (client_thread, new, &new->tid, 1);
1199 if (rc)
1201 close (new->status_msg_pipe[0]);
1202 close (new->status_msg_pipe[1]);
1203 pthread_mutex_destroy (&new->status_mutex);
1207 if (!rc)
1209 if (addr)
1210 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1211 (pthread_t *) new->tid, fd, addr);
1212 else
1213 log_write (_("new connection: tid=%p, fd=%i"),
1214 (pthread_t *) new->tid, fd);
1217 pthread_cleanup_pop (1);
1219 if (rc)
1221 xfree (new);
1222 close (fd);
1223 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
1225 return rc;
1228 #ifdef WITH_GNUTLS
1229 static gpg_error_t
1230 do_tls_accept (struct pollfd *fds)
1232 struct sockaddr_storage raddr;
1233 socklen_t slen = sizeof (raddr);
1234 int fd;
1235 char s[INET6_ADDRSTRLEN];
1237 if (!(fds->revents & POLLIN))
1238 return 0;
1240 fd = accept (fds->fd, (struct sockaddr *) &raddr, &slen);
1241 if (fd == -1)
1243 int e = errno;
1245 if (errno != EAGAIN && !quit)
1246 log_write ("%s: %s", __FUNCTION__,
1247 pwmd_strerror (gpg_error_from_syserror()));
1249 return gpg_error_from_errno (e);
1252 inet_ntop (raddr.ss_family, get_in_addr ((struct sockaddr *) &raddr), s,
1253 sizeof s);
1254 (void) init_client (fd, s);
1255 return 0;
1257 #endif
1259 static void *
1260 accept_thread (void *arg)
1262 int sockfd = *(int *) arg;
1263 #ifndef HAVE_PTHREAD_CANCEL
1264 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
1265 #endif
1267 #ifdef HAVE_PR_SET_NAME
1268 prctl (PR_SET_NAME, "accept");
1269 #endif
1270 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
1272 for (;;)
1274 socklen_t slen = sizeof (struct sockaddr_un);
1275 struct sockaddr_un raddr;
1276 int fd, s = 0;
1277 struct pollfd fds[3];
1279 TEST_CANCEL ();
1280 memset (fds, 0, sizeof (fds));
1281 fds[s].fd = sockfd;
1282 fds[s++].events = POLLIN;
1284 #ifdef WITH_GNUTLS
1285 if (tls_fd != -1)
1287 fds[s].fd = tls_fd;
1288 fds[s++].events = POLLIN;
1290 else
1291 fds[s].fd = tls_fd;
1293 if (tls6_fd != -1)
1295 fds[s].fd = tls6_fd;
1296 fds[s++].events = POLLIN;
1298 else
1299 fds[s].fd = tls6_fd;
1300 #endif
1302 s = poll (fds, s, 500);
1303 if (s == -1)
1305 if (errno != EINTR)
1306 log_write ("%s", strerror (errno));
1307 break;
1309 else if (s == 0)
1310 continue;
1312 if (fds[0].revents & POLLIN)
1314 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1315 if (fd == -1)
1317 if (errno == EMFILE || errno == ENFILE)
1318 log_write ("%s: %s", __FUNCTION__,
1319 pwmd_strerror (gpg_error_from_errno (errno)));
1320 else if (errno != EAGAIN && errno != EINTR)
1322 if (!quit) // probably EBADF
1323 log_write ("%s: %s", __FUNCTION__,
1324 pwmd_strerror (gpg_error_from_errno (errno)));
1326 break;
1329 continue;
1332 (void) init_client (fd, NULL);
1335 #ifdef WITH_GNUTLS
1336 if (tls_fd != -1 && fds[1].fd == tls_fd)
1337 (void)do_tls_accept (&fds[1]);
1339 if (tls6_fd != -1 && fds[1].fd == tls6_fd)
1340 (void)do_tls_accept (&fds[1]);
1342 if (tls6_fd != -1 && fds[2].fd == tls6_fd)
1343 (void)do_tls_accept (&fds[2]);
1344 #endif
1347 /* Just in case accept() failed for some reason other than EBADF */
1348 quit = 1;
1349 return NULL;
1352 static void *
1353 cache_timer_thread (void *arg)
1355 unsigned k = 0;
1356 #ifndef HAVE_PTHREAD_CANCEL
1357 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
1358 #endif
1360 (void)arg;
1362 #ifdef HAVE_PR_SET_NAME
1363 prctl (PR_SET_NAME, "timer");
1364 #endif
1365 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
1367 for (;;)
1369 struct timeval tv = { 1, 0 };
1370 unsigned keepalive = config_get_integer ("global", "keepalive_interval");
1372 TEST_CANCEL ();
1373 select (0, NULL, NULL, NULL, &tv);
1374 cache_adjust_timeout ();
1376 if (keepalive && ++k >= keepalive)
1378 send_status_all (STATUS_KEEPALIVE, NULL);
1379 k = 0;
1383 return NULL;
1386 static int
1387 signal_loop (sigset_t sigset)
1389 int done = 0;
1393 int sig;
1395 sigwait (&sigset, &sig);
1396 log_write (_("caught signal %i (%s)"), sig, strsignal (sig));
1398 switch (sig)
1400 case SIGHUP:
1401 pthread_cond_signal (&rcfile_cond);
1402 break;
1403 case SIGUSR1:
1404 log_write (_("clearing file cache"));
1405 cache_clear (NULL, NULL, 1);
1406 send_status_all (STATUS_CACHE, NULL);
1407 break;
1408 default:
1409 done = 1;
1410 break;
1413 while (!done);
1415 return done;
1418 static void
1419 catchsig (int sig)
1421 log_write (_ ("Caught signal %i (%s). Exiting."), sig, strsignal (sig));
1422 #ifdef HAVE_BACKTRACE
1423 BACKTRACE (__FUNCTION__);
1424 #endif
1425 longjmp (jmp, 1);
1428 static void
1429 cancel_all_clients ()
1431 unsigned i, t;
1433 MUTEX_LOCK (&cn_mutex);
1434 t = slist_length (cn_thread_list);
1435 for (i = 0; i < t; i++)
1437 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
1439 #ifdef HAVE_PTHREAD_CANCEL
1440 pthread_cancel (thd->tid);
1441 #else
1442 pthread_kill (thd->tid, SIGUSR2);
1443 #endif
1446 while (slist_length (cn_thread_list))
1448 MUTEX_UNLOCK (&cn_mutex);
1449 usleep (50000);
1450 MUTEX_LOCK (&cn_mutex);
1453 MUTEX_UNLOCK (&cn_mutex);
1456 static int
1457 server_loop (int sockfd, char **socketpath)
1459 pthread_t cache_timeout_tid;
1460 pthread_t accept_tid;
1461 int cancel_timeout_thread = 0;
1462 int cancel_accept_thread = 0;
1463 int cancel_rcfile_thread = 0;
1464 sigset_t sigset;
1465 int n;
1466 int segv = 0;
1467 gpg_error_t rc;
1469 init_commands ();
1470 sigemptyset (&sigset);
1472 /* Termination */
1473 sigaddset (&sigset, SIGTERM);
1474 sigaddset (&sigset, SIGINT);
1476 /* Clears the file cache. */
1477 sigaddset (&sigset, SIGUSR1);
1479 /* Configuration file reloading. */
1480 sigaddset (&sigset, SIGHUP);
1482 #ifndef HAVE_PTHREAD_CANCEL
1484 The socket, cache and rcfile threads use this signal when
1485 pthread_cancel() is unavailable. Prevent the main thread from
1486 catching this signal from another process.
1488 sigaddset (&sigset, SIGUSR2);
1489 #endif
1491 /* An assertion failure. */
1492 signal (SIGABRT, catchsig);
1493 sigaddset (&sigset, SIGABRT);
1494 sigprocmask (SIG_BLOCK, &sigset, NULL);
1496 #ifndef HAVE_PTHREAD_CANCEL
1497 /* Remove this signal from the watched signals in signal_loop(). */
1498 sigdelset (&sigset, SIGUSR2);
1499 #endif
1501 /* Can show a backtrace of the stack in the log. */
1502 signal (SIGSEGV, catchsig);
1504 char *p = get_username (getuid());
1505 log_write (_("%s started for user %s"), PACKAGE_STRING, p);
1506 xfree (p);
1508 #ifdef WITH_GNUTLS
1509 if (config_get_boolean ("global", "enable_tcp"))
1510 log_write (_("Listening on %s and TCP port %i"), *socketpath,
1511 config_get_integer ("global", "tcp_port"));
1512 else
1513 log_write (_("Listening on %s"), *socketpath);
1514 #else
1515 log_write (_("Listening on %s"), *socketpath);
1516 #endif
1518 rc = create_thread (reload_rcfile_thread, NULL, &rcfile_tid, 0);
1519 if (rc)
1521 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1522 pwmd_strerror (rc));
1523 goto done;
1526 cancel_rcfile_thread = 1;
1527 rc = create_thread (cache_timer_thread, NULL, &cache_timeout_tid, 0);
1528 if (rc)
1530 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1531 pwmd_strerror (rc));
1532 goto done;
1535 cancel_timeout_thread = 1;
1536 rc = create_thread (accept_thread, &sockfd, &accept_tid, 0);
1537 if (rc)
1539 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1540 pwmd_strerror (rc));
1541 goto done;
1544 cancel_accept_thread = 1;
1545 if (!setjmp (jmp))
1546 signal_loop (sigset);
1547 else
1548 segv = 1;
1550 done:
1552 * We're out of the main server loop. This happens when a signal was sent
1553 * to terminate the daemon. Cancel all clients and exit.
1555 if (cancel_accept_thread)
1557 #ifdef HAVE_PTHREAD_CANCEL
1558 n = pthread_cancel (accept_tid);
1559 #else
1560 n = pthread_kill (accept_tid, SIGUSR2);
1561 #endif
1562 if (!n)
1563 pthread_join (accept_tid, NULL);
1566 if (cancel_timeout_thread)
1568 #ifdef HAVE_PTHREAD_CANCEL
1569 n = pthread_cancel (cache_timeout_tid);
1570 #else
1571 n = pthread_kill (cache_timeout_tid, SIGUSR2);
1572 #endif
1573 if (!n)
1574 pthread_join (cache_timeout_tid, NULL);
1577 #ifdef WITH_GNUTLS
1578 tls_start_stop (1);
1579 #endif
1580 shutdown (sockfd, SHUT_RDWR);
1581 close (sockfd);
1582 unlink (*socketpath);
1583 xfree (*socketpath);
1584 *socketpath = NULL;
1585 MUTEX_LOCK (&cn_mutex);
1586 n = slist_length (cn_thread_list);
1587 MUTEX_UNLOCK (&cn_mutex);
1589 if (n && !segv)
1590 cancel_all_clients ();
1591 else
1592 free_all_clients ();
1594 if (cancel_rcfile_thread)
1596 #ifdef HAVE_PTHREAD_CANCEL
1597 pthread_cancel (rcfile_tid);
1598 #else
1599 pthread_kill (rcfile_tid, SIGUSR2);
1600 pthread_cond_signal (&rcfile_cond);
1601 #endif
1602 pthread_join (rcfile_tid, NULL);
1605 cache_deinit ();
1606 deinit_commands ();
1607 return segv ? EXIT_FAILURE : EXIT_SUCCESS;
1610 static void
1611 usage (const char *pn, int status)
1613 FILE *fp = status == EXIT_FAILURE ? stderr : stdout;
1615 fprintf (fp, _("Usage: %s [OPTIONS] [file1] [...]\n"
1616 " --homedir alternate pwmd home directory (~/.pwmd)\n"
1617 " -f, --rcfile=filename load the specfied configuration file\n"
1618 " (~/.pwmd/config)\n"
1619 " --kill terminate an existing instance of pwmd\n"
1620 " -n, --no-fork run as a foreground process\n"
1621 " --disable-dump disable the LIST, XPATH and DUMP commands\n"
1622 " --ignore, --force ignore cache pushing errors during startup\n"
1623 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
1624 " -k, --passphrase-file=file for use when importing\n"
1625 " -o, --outfile=filename output file when importing\n"
1626 " --keyid=fpr[,..] public key to use when encrypting\n"
1627 " --sign-keyid=fpr[,..] fingerprint of the signing key to use\n"
1628 " -s, --symmetric use conventional encryption with optional signer\n"
1629 " --keyparam=filename custom key parameters to use (gpg default)\n"
1630 " --debug=[a:..][,g:N][,t:N] enable debugging (a:[ixedsc],g:[1-9],t:[0-N])\n"
1631 " --help this help text\n"
1632 " --version show version and compile time features\n"),
1633 pn);
1634 exit (status);
1637 static void
1638 unlink_stale_socket (const char *sock, const char *pidfile)
1640 log_write (_ ("removing stale socket %s"), sock);
1641 unlink (sock);
1642 unlink (pidfile);
1645 static int
1646 test_pidfile (const char *path, const char *sock, char *buf, size_t buflen,
1647 char **pidfile, int create, mode_t mode, int terminate)
1649 pid_t pid;
1650 int fd;
1651 size_t len;
1653 if (!create)
1655 snprintf (buf, buflen, "%s/%s.pid", homedir, sock);
1656 *pidfile = str_dup (buf);
1657 fd = open (buf, O_RDONLY);
1659 else
1660 fd = open (*pidfile, O_CREAT|O_WRONLY|O_TRUNC, mode);
1662 if (fd == -1)
1664 if (!create && errno != ENOENT)
1666 log_write ("%s: %s", buf, pwmd_strerror (errno));
1667 xfree (*pidfile);
1668 *pidfile = NULL;
1669 return -1;
1671 else if (!create && !terminate)
1672 return 0;
1674 log_write ("%s: %s", *pidfile, strerror (errno));
1675 return -1;
1678 if (create)
1680 snprintf (buf, buflen, "%i", getpid ());
1681 ssize_t ret = write (fd, buf, strlen (buf));
1682 if (ret == -1)
1683 log_write ("%s (%i): %s", __FUNCTION__, __LINE__,
1684 pwmd_strerror (gpg_error_from_syserror ()));
1685 close (fd);
1686 return 0;
1689 len = read (fd, buf, buflen);
1690 close (fd);
1691 if (len == 0)
1693 unlink_stale_socket (path, *pidfile);
1694 return 0;
1697 if (sscanf (buf, "%5i", &pid) != 1 || pid == 0)
1699 if (!terminate)
1701 unlink_stale_socket (path, *pidfile);
1702 return 0;
1706 if (kill (pid, 0) == -1)
1708 unlink_stale_socket (path, *pidfile);
1709 return 0;
1712 if (terminate)
1714 if (kill (pid, SIGTERM) == -1)
1715 log_write ("%s: %s", path, pwmd_strerror (errno));
1717 else
1718 log_write (_ ("an instance for socket %s is already running"), path);
1720 xfree (*pidfile);
1721 *pidfile = NULL;
1722 return 1;
1725 static unsigned
1726 parse_debug_level (const char *str, unsigned *debug, int *gpgme, int *tls)
1728 const char *p;
1729 unsigned level = 0;
1730 int gl = 0, tl = 0;
1732 for (p = str; p && *p; p++)
1734 if (*p == 'a') // assuan debug flags
1736 if (*++p != ':')
1737 return 1;
1739 while (*++p)
1741 switch (*p)
1743 case 'i':
1744 level |= ASSUAN_LOG_INIT;
1745 break;
1746 case 'x':
1747 level |= ASSUAN_LOG_CTX;
1748 break;
1749 case 'e':
1750 level |= ASSUAN_LOG_ENGINE;
1751 break;
1752 case 'd':
1753 level |= ASSUAN_LOG_DATA;
1754 break;
1755 case 's':
1756 level |= ASSUAN_LOG_SYSIO;
1757 break;
1758 case 'c':
1759 level |= ASSUAN_LOG_CONTROL;
1760 break;
1761 case ',':
1762 break;
1763 default:
1764 return 1;
1767 if (*p == ',')
1768 break;
1771 if (!*p)
1772 break;
1774 else if (*p == 'g' || *p == 't') // gpgme and TLS debug level
1776 int t = *p == 't';
1777 int n;
1779 if (*++p != ':')
1780 return 1;
1782 if (!isdigit (*++p))
1783 return 1;
1785 n = atoi (p);
1786 if (t)
1787 tl = n;
1788 else
1789 gl = n;
1791 if (tl < 0 || gl < 0 || gl > 9)
1792 return 1;
1794 while (isdigit (*p))
1795 p++;
1797 p--;
1798 if (*(p+1) && *(p+1) != ',')
1799 return 1;
1800 else if (*(p+1))
1801 p++;
1803 else
1804 return 1;
1807 if (tl)
1808 *tls = tl;
1810 if (gl)
1811 *gpgme = gl;
1813 *debug = level;
1814 return 0;
1818 main (int argc, char *argv[])
1820 int opt;
1821 struct sockaddr_un addr;
1822 char buf[PATH_MAX];
1823 char *socketpath = NULL, *socketdir, *socketname = NULL;
1824 char *socketarg = NULL;
1825 char *datadir = NULL;
1826 char *pidfile = NULL;
1827 mode_t mode = 0600;
1828 int x;
1829 char *p;
1830 char **cache_push = NULL;
1831 char *import = NULL, *keyid = NULL, *sign_keyid = NULL;
1832 char *keyparam = NULL;
1833 int estatus = EXIT_FAILURE;
1834 int sockfd;
1835 char *outfile = NULL;
1836 int do_unlink = 0;
1837 int secure = 0;
1838 int show_version = 0;
1839 int force = 0;
1840 gpg_error_t rc;
1841 char *keyfile = NULL;
1842 int exists;
1843 int optindex;
1844 int terminate = 0;
1845 int sym = 0;
1846 int gpgme_level = -1;
1847 int tls_level = -1;
1848 int backlog = 0;
1849 /* Must maintain the same order as longopts[] */
1850 enum
1852 OPT_VERSION, OPT_HELP, OPT_HOMEDIR, OPT_NO_FORK, OPT_DISABLE_DUMP,
1853 OPT_FORCE, OPT_RCFILE, OPT_PASSPHRASE_FILE, OPT_IMPORT, OPT_OUTFILE,
1854 OPT_KEYID, OPT_SIGN_KEYID, OPT_SYMMETRIC, OPT_KEYPARAM, OPT_KILL,
1855 OPT_DEBUG
1857 const char *optstring = "nf:C:k:I:o:s";
1858 const struct option longopts[] = {
1859 {"version", no_argument, 0, 0},
1860 {"help", no_argument, 0, 0},
1861 {"homedir", required_argument, 0, 0},
1862 {"no-fork", no_argument, 0, 'n'},
1863 {"disable_dump", no_argument, 0, 0},
1864 {"force", no_argument, 0, 0},
1865 {"rcfile", required_argument, 0, 'f'},
1866 {"passphrase-file", required_argument, 0, 'k'},
1867 {"import", required_argument, 0, 'I'},
1868 {"outfile", required_argument, 0, 'o'},
1869 {"keyid", required_argument, 0, 0},
1870 {"sign-keyid", required_argument, 0, 0},
1871 {"symmetric", no_argument, 0, 's'},
1872 {"keyparam", required_argument, 0, 0},
1873 {"kill", no_argument, 0, 0},
1874 {"debug", required_argument, 0, 0},
1875 {0, 0, 0, 0}
1878 log_fd = -1;
1879 cmdline = 1;
1881 #ifndef DEBUG
1882 #ifdef HAVE_SETRLIMIT
1883 struct rlimit rl;
1885 rl.rlim_cur = rl.rlim_max = 0;
1887 if (setrlimit (RLIMIT_CORE, &rl) != 0)
1888 err (EXIT_FAILURE, "setrlimit()");
1889 #endif
1891 #ifdef HAVE_PR_SET_DUMPABLE
1892 prctl (PR_SET_DUMPABLE, 0);
1893 #endif
1894 #endif
1896 #ifdef ENABLE_NLS
1897 setlocale (LC_ALL, "");
1898 bindtextdomain ("pwmd", LOCALEDIR);
1899 textdomain ("pwmd");
1900 #endif
1902 while ((opt = getopt_long (argc, argv, optstring, longopts, &optindex))
1903 != -1)
1905 switch (opt)
1907 case 'I':
1908 import = optarg;
1909 break;
1910 case 'k':
1911 keyfile = optarg;
1912 break;
1913 case 'o':
1914 outfile = optarg;
1915 break;
1916 case 'n':
1917 nofork = 1;
1918 break;
1919 case 'f':
1920 rcfile = str_dup (optarg);
1921 break;
1922 case 's':
1923 sym = 1;
1924 break;
1925 default:
1926 usage (argv[0], EXIT_FAILURE);
1927 break;
1928 case 0:
1929 switch (optindex)
1931 case OPT_DEBUG:
1932 if (parse_debug_level (optarg, &assuan_level, &gpgme_level,
1933 &tls_level))
1934 usage (argv[0], EXIT_FAILURE);
1935 break;
1936 case OPT_SYMMETRIC:
1937 sym = 1;
1938 break;
1939 case OPT_VERSION:
1940 show_version = 1;
1941 break;
1942 case OPT_HELP:
1943 usage (argv[0], EXIT_SUCCESS);
1944 break;
1945 case OPT_HOMEDIR:
1946 homedir = str_dup (optarg);
1947 break;
1948 case OPT_NO_FORK:
1949 nofork = 1;
1950 break;
1951 case OPT_DISABLE_DUMP:
1952 secure = 1;
1953 break;
1954 case OPT_FORCE:
1955 force = 1;
1956 break;
1957 case OPT_RCFILE:
1958 rcfile = str_dup (optarg);
1959 break;
1960 case OPT_PASSPHRASE_FILE:
1961 keyfile = optarg;
1962 break;
1963 case OPT_IMPORT:
1964 import = optarg;
1965 break;
1966 case OPT_OUTFILE:
1967 outfile = optarg;
1968 break;
1969 case OPT_KEYID:
1970 keyid = optarg;
1971 break;
1972 case OPT_SIGN_KEYID:
1973 sign_keyid = optarg;
1974 break;
1975 case OPT_KEYPARAM:
1976 keyparam = optarg;
1977 break;
1978 case OPT_KILL:
1979 terminate = 1;
1980 break;
1981 default:
1982 usage (argv[0], EXIT_FAILURE);
1987 if (show_version)
1989 printf (_("%s\n\n"
1990 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016\n"
1991 "%s\n"
1992 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
1993 "Compile time features:\n%s"), PACKAGE_STRING,
1994 PACKAGE_BUGREPORT,
1995 #ifdef PWMD_HOMEDIR
1996 "+PWMD_HOMEDIR=" PWMD_HOMEDIR "\n"
1997 #endif
1998 #ifdef WITH_GNUTLS
1999 "+WITH_GNUTLS\n"
2000 #else
2001 "-WITH_GNUTLS\n"
2002 #endif
2003 #ifdef WITH_LIBACL
2004 "+WITH_LIBACL\n"
2005 #else
2006 "-WITH_LIBACL\n"
2007 #endif
2008 #ifdef DEBUG
2009 "+DEBUG\n"
2010 #else
2011 "-DEBUG\n"
2012 #endif
2013 #ifdef MEM_DEBUG
2014 "+MEM_DEBUG\n"
2015 #else
2016 "-MEM_DEBUG\n"
2017 #endif
2018 #ifdef MUTEX_DEBUG
2019 "+MUTEX_DEBUG\n"
2020 #else
2021 "-MUTEX_DEBUG\n"
2022 #endif
2024 exit (EXIT_SUCCESS);
2027 if (gpgme_level != -1)
2029 char s[2] = { gpgme_level + '0', 0 };
2031 if (getenv ("GPGME_DEBUG"))
2032 log_write (_ ("Overriding GPGME_DEBUG environment with level %u!"),
2033 gpgme_level);
2035 gpgme_set_global_flag ("debug", s);
2038 if (setup_crypto ())
2039 exit (EXIT_FAILURE);
2041 #ifdef WITH_GNUTLS
2042 tls_level = tls_level == -1 ? 1 : tls_level;
2043 gnutls_global_set_log_level (tls_level);
2044 tls_fd = -1;
2045 tls6_fd = -1;
2046 #endif
2047 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
2048 xmlInitMemory ();
2049 xmlInitGlobals ();
2050 xmlInitParser ();
2051 xmlXPathInit ();
2053 if (!homedir)
2054 #ifdef PWMD_HOMEDIR
2055 homedir = str_dup(PWMD_HOMEDIR);
2056 #else
2057 homedir = str_asprintf ("%s/.pwmd", get_home_dir());
2058 #endif
2060 if (mkdir (homedir, 0700) == -1 && errno != EEXIST)
2061 err (EXIT_FAILURE, "%s", homedir);
2063 if (!rcfile)
2064 rcfile = str_asprintf ("%s/config", homedir);
2066 pthread_key_create (&last_error_key, free_key);
2067 #ifndef HAVE_PTHREAD_CANCEL
2068 pthread_key_create (&signal_thread_key, free_key);
2069 #endif
2071 pthread_mutexattr_t attr;
2072 pthread_mutexattr_init (&attr);
2073 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
2074 pthread_mutex_init (&rcfile_mutex, &attr);
2075 global_config = config_parse (rcfile, 0);
2076 if (!global_config)
2078 pthread_mutexattr_destroy (&attr);
2079 pthread_mutex_destroy (&rcfile_mutex);
2080 exit (EXIT_FAILURE);
2083 p = config_get_string ("global", "gpg_homedir");
2084 if (!p)
2085 datadir = str_asprintf ("%s/.gnupg", homedir);
2086 else
2087 datadir = expand_homedir (p);
2089 xfree (p);
2090 if (mkdir (datadir, 0700) == -1 && errno != EEXIST)
2091 err (EXIT_FAILURE, "%s", datadir);
2093 rc = gpgme_set_engine_info (GPGME_PROTOCOL_OpenPGP, NULL, datadir);
2094 xfree (datadir);
2096 snprintf (buf, sizeof (buf), "%s/data", homedir);
2097 if (mkdir (buf, 0700) == -1 && errno != EEXIST)
2098 err (EXIT_FAILURE, "%s", buf);
2100 datadir = str_dup (buf);
2101 pthread_cond_init (&rcfile_cond, NULL);
2102 pthread_mutex_init (&cn_mutex, &attr);
2103 pthread_mutexattr_destroy (&attr);
2105 setup_logging ();
2107 x = config_get_int_param (global_config, "global", "priority", &exists);
2108 if (exists && x != atoi(INVALID_PRIORITY))
2110 errno = 0;
2111 if (setpriority (PRIO_PROCESS, 0, x) == -1)
2113 log_write ("setpriority(): %s",
2114 pwmd_strerror (gpg_error_from_errno (errno)));
2115 goto do_exit;
2118 #ifdef HAVE_MLOCKALL
2119 if (disable_mlock == 0 && mlockall (MCL_CURRENT | MCL_FUTURE) == -1)
2121 log_write ("mlockall(): %s",
2122 pwmd_strerror (gpg_error_from_errno (errno)));
2123 goto do_exit;
2125 #endif
2127 rc = cache_init ();
2128 if (rc)
2130 log_write ("pwmd: ERR %i: %s", rc, pwmd_strerror (rc));
2131 exit (EXIT_FAILURE);
2134 if (import)
2136 char **keyids = NULL, **sign_keyids = NULL;
2138 if (!outfile || !*outfile || argc != optind)
2139 usage (argv[0], EXIT_FAILURE);
2141 if (keyid)
2142 keyids = str_split (keyid, ",", 0);
2143 if (sign_keyid)
2144 sign_keyids = str_split (sign_keyid, ",", 0);
2145 rc = xml_import (import, outfile, keyids, sign_keyids, keyfile, keyparam, sym);
2146 strv_free (keyids);
2147 strv_free (sign_keyids);
2148 if (rc)
2150 if (gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
2151 rc = gpg_error (rc);
2153 log_write ("%s: %u: %s", import, rc, pwmd_strerror (rc));
2156 config_free (global_config);
2157 xfree (rcfile);
2158 exit (rc ? EXIT_FAILURE : EXIT_SUCCESS);
2161 p = config_get_string ("global", "socket_path");
2162 if (!p)
2163 p = str_asprintf ("%s/socket", homedir);
2165 socketarg = expand_homedir (p);
2166 xfree (p);
2168 if (!secure)
2169 disable_list_and_dump = config_get_boolean ("global",
2170 "disable_list_and_dump");
2171 else
2172 disable_list_and_dump = secure;
2174 cache_push = config_get_list ("global", "cache_push");
2176 while (optind < argc)
2178 if (strv_printf (&cache_push, "%s", argv[optind++]) == 0)
2179 errx (EXIT_FAILURE, "%s", pwmd_strerror (GPG_ERR_ENOMEM));
2182 if (strchr (socketarg, '/') == NULL)
2184 socketdir = getcwd (buf, sizeof (buf));
2185 socketname = str_dup (socketarg);
2186 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2188 else
2190 socketname = str_dup (strrchr (socketarg, '/'));
2191 socketname++;
2192 socketarg[strlen (socketarg) - strlen (socketname) - 1] = 0;
2193 socketdir = str_dup (socketarg);
2194 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2197 if (chdir (datadir))
2199 log_write ("%s: %s", datadir,
2200 pwmd_strerror (gpg_error_from_errno (errno)));
2201 unlink (socketpath);
2202 goto do_exit;
2205 x = test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 0,
2206 mode, terminate);
2207 if (!terminate && x)
2208 goto do_exit;
2209 else if (terminate)
2211 estatus = x != 1 ? EXIT_FAILURE : EXIT_SUCCESS;
2212 goto do_exit;
2216 * bind() doesn't like the full pathname of the socket or any non alphanum
2217 * characters so change to the directory where the socket is wanted then
2218 * create it then change to datadir.
2220 if (chdir (socketdir))
2222 log_write ("%s: %s", socketdir,
2223 pwmd_strerror (gpg_error_from_errno (errno)));
2224 goto do_exit;
2227 xfree (socketdir);
2229 if ((sockfd = socket (PF_UNIX, SOCK_STREAM, 0)) == -1)
2231 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2232 goto do_exit;
2235 addr.sun_family = AF_UNIX;
2236 snprintf (addr.sun_path, sizeof (addr.sun_path), "%s", socketname);
2237 do_unlink = 1;
2238 if (bind (sockfd, (struct sockaddr *) &addr, sizeof (struct sockaddr)) ==
2241 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2243 if (errno == EADDRINUSE)
2245 do_unlink = 0;
2246 log_write (_("Either there is another pwmd running or '%s' is a \n"
2247 "stale socket. Please remove it manually."), socketpath);
2250 goto do_exit;
2254 char *t = config_get_string ("global", "socket_perms");
2255 mode_t mask;
2257 if (t)
2259 mode = strtol (t, NULL, 8);
2260 mask = umask (0);
2261 xfree (t);
2263 if (chmod (socketname, mode) == -1)
2265 log_write ("%s: %s", socketname,
2266 pwmd_strerror (gpg_error_from_errno (errno)));
2267 close (sockfd);
2268 umask (mask);
2269 goto do_exit;
2272 umask (mask);
2276 xfree (--socketname);
2278 if (chdir (datadir))
2280 log_write ("%s: %s", datadir,
2281 pwmd_strerror (gpg_error_from_errno (errno)));
2282 close (sockfd);
2283 goto do_exit;
2286 xfree (datadir);
2287 #ifdef WITH_GNUTLS
2288 if (config_get_boolean ("global", "enable_tcp"))
2290 if (!tls_start_stop (0))
2292 close (sockfd);
2293 goto do_exit;
2296 #endif
2299 * Set the cache entry for a file. Prompts for the password.
2301 if (cache_push)
2303 for (opt = 0; cache_push[opt]; opt++)
2305 struct crypto_s *crypto = NULL;
2306 char *pw_file = config_get_string (cache_push[opt],
2307 "passphrase_file");
2308 rc = crypto_init (&crypto, NULL, cache_push[opt], pw_file != NULL,
2309 pw_file);
2311 if (!rc)
2313 crypto->flags |= pw_file ? CRYPTO_FLAG_KEYFILE : 0;
2314 crypto->keyfile = pw_file;
2316 else
2317 xfree (pw_file);
2319 if (rc)
2321 estatus = EXIT_FAILURE;
2322 goto do_exit;
2325 rc = do_cache_push (crypto);
2326 if (rc && !force)
2328 log_write ("ERR %u: %s", rc, pwmd_strerror(rc));
2329 strv_free (cache_push);
2330 log_write (_ ("Failed to add a file to the cache. Use --force to force startup. Exiting."));
2331 cache_clear (NULL, NULL, 1);
2332 estatus = EXIT_FAILURE;
2333 crypto_free (crypto);
2334 goto do_exit;
2336 else if (rc)
2337 log_write ("%s: %s", crypto->filename, pwmd_strerror(rc));
2338 else
2339 log_write (_("Successfully added '%s' to the cache."),
2340 crypto->filename);
2342 crypto_free (crypto);
2345 strv_free (cache_push);
2346 log_write (!nofork ? _("Done. Daemonizing...") :
2347 _("Done. Waiting for connections..."));
2350 backlog = config_get_integer ("global", "backlog");
2351 if (listen (sockfd, backlog) == -1)
2353 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2354 goto do_exit;
2357 if (!nofork)
2359 switch (fork ())
2361 case -1:
2362 log_write ("fork(): %s",
2363 pwmd_strerror (gpg_error_from_errno (errno)));
2364 goto do_exit;
2365 case 0:
2366 close (0);
2367 close (1);
2368 close (2);
2369 setsid ();
2370 break;
2371 default:
2372 _exit (EXIT_SUCCESS);
2376 (void)test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 1,
2377 mode, 0);
2378 cmdline = 0;
2379 pthread_key_create (&thread_name_key, free_key);
2380 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
2381 estatus = server_loop (sockfd, &socketpath);
2383 do_exit:
2384 if (socketpath && do_unlink)
2386 unlink (socketpath);
2387 xfree (socketpath);
2390 xfree (socketarg);
2391 #ifdef WITH_GNUTLS
2392 gnutls_global_deinit ();
2393 tls_deinit_params ();
2394 #endif
2395 pthread_cond_destroy (&rcfile_cond);
2396 pthread_mutex_destroy (&rcfile_mutex);
2397 pthread_key_delete (last_error_key);
2398 #ifndef HAVE_PTHREAD_CANCEL
2399 pthread_key_delete (signal_thread_key);
2400 #endif
2402 if (global_config)
2403 config_free (global_config);
2405 free_invoking_users (invoking_users);
2406 xfree (rcfile);
2407 xfree (home_directory);
2408 xfree (homedir);
2409 xmlCleanupParser ();
2410 xmlCleanupGlobals ();
2412 if (pidfile)
2413 unlink (pidfile);
2414 xfree (pidfile);
2416 if (estatus == EXIT_SUCCESS && !terminate)
2417 log_write (_("pwmd exiting normally"));
2419 pthread_key_delete (thread_name_key);
2420 closelog ();
2422 if (log_fd != -1)
2423 close (log_fd);
2425 exit (estatus);
2428 gpg_error_t lock_flock (assuan_context_t ctx, const char *filename,
2429 int type, int *fd)
2431 gpg_error_t rc = 0;
2433 #ifdef HAVE_FLOCK
2434 rc = open_check_file (filename, fd, NULL, 1);
2435 if (rc)
2436 return rc;
2438 TRY_FLOCK (ctx, *fd, type, rc);
2439 if (rc)
2441 close (*fd);
2442 *fd = -1;
2444 #endif
2446 return rc;
2449 void unlock_flock (int *fd)
2451 #ifdef HAVE_FLOCK
2452 if (*fd != -1)
2453 close (*fd);
2455 *fd = -1;
2456 #endif