Add copy-on-write support.
[pwmd.git] / src / pwmd.c
blob847e095daf9f6b556f48e8fe28ee33de5987a273
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, args);
333 if (line)
335 pthread_cleanup_push (xfree, line);
336 if (logfile && log_fd != -1)
338 ssize_t ret = write (log_fd, line, strlen (line));
339 (void)ret;
340 fsync (log_fd);
343 if (nofork)
345 fprintf (stdout, "%s", line);
346 fflush (stdout);
349 pthread_cleanup_pop (1);
352 pthread_cleanup_pop (1);
355 va_end (ap);
357 if (log_fd != -1 && log_keepopen <= 0)
359 close(log_fd);
360 log_fd = -1;
363 pthread_cleanup_pop (1);
366 static gpg_error_t
367 setup_crypto ()
369 gpg_error_t rc;
371 if (!gpgrt_check_version (REQUIRE_LIBGPGERROR_VERSION))
373 fprintf (stderr, _("gpgrt_check_version(): Incompatible libgpg-error. "
374 "Wanted %s, got %s.\n"), REQUIRE_LIBGPGERROR_VERSION,
375 gpgrt_check_version (NULL));
376 return GPG_ERR_UNKNOWN_VERSION;
379 gpgrt_init ();
380 //gpgrt_set_alloc_func (xrealloc_gpgrt);
382 if (!assuan_check_version (REQUIRE_LIBASSUAN_VERSION))
384 fprintf (stderr, _("assuan_check_version(): Incompatible libassuan. "
385 "Wanted %s, got %s.\n"), REQUIRE_LIBASSUAN_VERSION,
386 assuan_check_version (NULL));
387 return GPG_ERR_UNKNOWN_VERSION;
390 if (!gcry_check_version (REQUIRE_LIBGCRYPT_VERSION))
392 fprintf (stderr, _("gcry_check_version(): Incompatible libgcrypt. "
393 "Wanted %s, got %s.\n"), REQUIRE_LIBGCRYPT_VERSION,
394 gcry_check_version (NULL));
395 return GPG_ERR_UNKNOWN_VERSION;
398 gcry_set_allocation_handler (xmalloc, xmalloc, NULL, xrealloc, xfree);
400 if (!gpgme_check_version (REQUIRE_LIBGPGME_VERSION))
402 fprintf (stderr, _("gpgme_check_version(): Incompatible libgpgme. "
403 "Wanted %s, got %s.\n"), REQUIRE_LIBGPGME_VERSION,
404 gpgme_check_version (NULL));
405 return GPG_ERR_UNKNOWN_VERSION;
408 rc = gpgme_engine_check_version (GPGME_PROTOCOL_OPENPGP);
409 if (rc)
411 fprintf (stderr, _("gpgme_engine_check_version(GPGME_PROTOCOL_OPENPGP): %s"), gpgme_strerror (rc));
412 return GPG_ERR_UNKNOWN_VERSION;
415 //gpgme_set_global_flag ("require-gnupg", REQUIRE_GNUPG_VERSION);
416 #ifdef ENABLE_NLS
417 gpgme_set_locale (NULL, LC_CTYPE, setlocale (LC_CTYPE, NULL));
418 gpgme_set_locale (NULL, LC_MESSAGES, setlocale (LC_MESSAGES, NULL));
419 #endif
421 #ifdef WITH_GNUTLS
422 if (gnutls_global_init ())
424 fprintf(stderr, _("gnutls_global_init() failed.\n"));
425 return GPG_ERR_UNKNOWN_VERSION;
428 if (!gnutls_check_version (REQUIRE_LIBGNUTLS_VERSION))
430 fprintf (stderr, _("gnutls_check_version(): Incompatible libgnutls. "
431 "Wanted %s, got %s.\n"), REQUIRE_LIBGNUTLS_VERSION,
432 gnutls_check_version (NULL));
433 return GPG_ERR_UNKNOWN_VERSION;
436 gnutls_global_set_log_function (tls_log);
437 gnutls_global_set_audit_log_function (tls_audit_log);
438 #endif
439 return 0;
442 static void
443 xml_error_cb (void *data, xmlErrorPtr e)
445 struct client_s *client = data;
448 * Keep the first reported error as the one to show in the error
449 * description. Reset in send_error().
451 if (client->xml_error)
452 return;
454 client->xml_error = xcalloc (1, sizeof(xmlError));
455 xmlCopyError (e, client->xml_error);
458 static pid_t
459 hook_waitpid (assuan_context_t ctx, pid_t pid, int action,
460 int *status, int options)
462 (void)ctx;
463 (void)action;
464 return waitpid (pid, status, options);
467 static ssize_t
468 hook_read (assuan_context_t ctx, assuan_fd_t fd, void *data, size_t len)
470 TEST_CANCEL ();
471 #ifdef WITH_GNUTLS
472 struct client_s *client = assuan_get_pointer (ctx);
474 if (client->thd->remote)
475 return tls_read_hook (ctx, (int) fd, data, len);
476 #else
477 (void)ctx;
478 #endif
480 return read ((int) fd, data, len);
483 static ssize_t
484 hook_write (assuan_context_t ctx, assuan_fd_t fd,
485 const void *data, size_t len)
487 TEST_CANCEL ();
488 #ifdef WITH_GNUTLS
489 struct client_s *client = assuan_get_pointer (ctx);
491 if (client->thd->remote)
492 return tls_write_hook (ctx, (int) fd, data, len);
493 #else
494 (void)ctx;
495 #endif
497 return write ((int) fd, data, len);
501 assuan_log_cb (assuan_context_t ctx, void *data, unsigned cat,
502 const char *msg)
504 struct client_s *client = data;
505 const char *str = NULL;
507 (void)client;
508 (void)ctx;
510 if (!(assuan_level & cat))
511 return 0;
513 if (!msg)
514 return 1;
516 switch (cat)
518 case ASSUAN_LOG_INIT:
519 str = "ASSUAN[INIT]";
520 break;
521 case ASSUAN_LOG_CTX:
522 str = "ASSUAN[CTX]";
523 break;
524 case ASSUAN_LOG_ENGINE:
525 str = "ASSUAN[ENGINE]";
526 break;
527 case ASSUAN_LOG_DATA:
528 str = "ASSUAN[DATA]";
529 break;
530 case ASSUAN_LOG_SYSIO:
531 str = "ASSUAN[SYSIO]";
532 break;
533 case ASSUAN_LOG_CONTROL:
534 str = "ASSUAN[CONTROL]";
535 break;
536 default:
537 str = "ASSUAN[UNKNOWN]";
538 break;
541 log_write ("%s: %s", str, msg);
542 return 1;
545 static int
546 new_connection (struct client_s *cl)
548 gpg_error_t rc;
549 static struct assuan_malloc_hooks mhooks = { xmalloc, xrealloc, xfree };
550 static struct assuan_system_hooks shooks = {
551 ASSUAN_SYSTEM_HOOKS_VERSION,
552 __assuan_usleep,
553 __assuan_pipe,
554 __assuan_close,
555 hook_read,
556 hook_write,
557 //FIXME
558 NULL, //recvmsg
559 NULL, //sendmsg both are used for FD passing
560 __assuan_spawn,
561 hook_waitpid,
562 __assuan_socketpair,
563 __assuan_socket,
564 __assuan_connect
567 #ifdef WITH_GNUTLS
568 if (cl->thd->remote)
570 char *prio = config_get_string ("global", "tls_cipher_suite");
572 cl->thd->timeout = config_get_integer ("global", "tls_timeout");
573 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
574 return 0;
576 cl->thd->tls = tls_init_client (cl->thd->fd, cl->thd->timeout, prio);
577 xfree (prio);
578 if (!cl->thd->tls)
579 return 0;
581 #endif
583 rc = assuan_new_ext (&cl->ctx, GPG_ERR_SOURCE_DEFAULT, &mhooks,
584 assuan_log_cb, cl);
585 if (rc)
586 goto fail;
588 assuan_ctx_set_system_hooks (cl->ctx, &shooks);
589 rc = assuan_init_socket_server (cl->ctx, cl->thd->fd, 2);
590 if (rc)
591 goto fail;
593 assuan_set_pointer (cl->ctx, cl);
594 assuan_set_hello_line (cl->ctx, PACKAGE_STRING);
595 rc = register_commands (cl->ctx);
596 if (rc)
597 goto fail;
599 rc = assuan_accept (cl->ctx);
600 if (rc)
601 goto fail;
603 rc = validate_peer (cl);
604 /* May not be implemented on all platforms. */
605 if (rc && gpg_err_code (rc) != GPG_ERR_ASS_GENERAL)
606 goto fail;
608 MUTEX_LOCK (&cn_mutex);
609 cl->thd->state = CLIENT_STATE_INIT;
610 MUTEX_UNLOCK (&cn_mutex);
611 cl->lock_timeout = config_get_integer ("global", "lock_timeout");
612 xmlSetStructuredErrorFunc (cl, xml_error_cb);
613 return 1;
615 fail:
616 log_write ("%s", pwmd_strerror (rc));
617 return 0;
621 * This is called after a client is cancelled or disconnects. Set with
622 * pthread_cleanup_push().
624 static void
625 free_client_cb (void *arg)
627 struct client_thread_s *cn = arg;
628 struct client_s *cl = cn->cl;
629 #ifndef HAVE_PTHREAD_CANCEL
630 char *tmp = pthread_getspecific (signal_thread_key);
632 xfree (tmp);
633 pthread_setspecific (signal_thread_key, NULL);
634 #endif
635 MUTEX_LOCK (&cn_mutex);
636 cn_thread_list = slist_remove (cn_thread_list, cn);
637 MUTEX_UNLOCK (&cn_mutex);
639 if (cl)
641 unlock_flock (&cl->flock_fd);
642 reset_client (cl);
643 if (cl->xml_error)
644 xmlResetError (cl->xml_error);
646 xfree (cl->xml_error);
648 #ifdef WITH_GNUTLS
649 if (cn->tls)
651 gnutls_deinit (cn->tls->ses);
652 xfree (cn->tls->fp);
653 xfree (cn->tls);
655 #endif
657 if (cl->ctx)
658 assuan_release (cl->ctx);
659 else if (cl->thd && cl->thd->fd != -1)
660 close (cl->thd->fd);
662 if (cl->crypto)
663 crypto_free (cl->crypto);
665 cl->crypto = NULL;
666 xfree (cl);
668 else
670 if (cn->fd != -1)
671 close (cn->fd);
674 while (cn->msg_queue)
676 struct status_msg_s *msg = cn->msg_queue;
678 cn->msg_queue = msg->next;
679 xfree (msg->line);
680 xfree (msg);
683 if (cn->status_msg_pipe[0] != -1)
684 close (cn->status_msg_pipe[0]);
686 if (cn->status_msg_pipe[1] != -1)
687 close (cn->status_msg_pipe[1]);
689 pthread_mutex_destroy (&cn->status_mutex);
690 log_write (_("exiting, fd=%i"), cn->fd);
691 send_status_all (STATUS_CLIENTS, NULL);
693 xfree (cn->name);
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 *userid,
957 const char *algo, long expire, int no_passphrase, int symmetric)
959 xmlDocPtr doc;
960 int fd;
961 struct stat st;
962 int len;
963 xmlChar *xmlbuf = NULL;
964 gpg_error_t rc = 0;
965 struct crypto_s *crypto = NULL;
967 if (strcmp (filename, "-"))
969 rc = open_check_file (filename, &fd, &st, 0);
970 if (rc)
971 return rc;
973 xmlbuf = xmalloc (st.st_size + 1);
974 if (!xmlbuf)
976 close (fd);
977 return GPG_ERR_ENOMEM;
980 if (read (fd, xmlbuf, st.st_size) == -1)
982 rc = gpg_error_from_errno (errno);
983 close (fd);
984 xfree (xmlbuf);
985 return rc;
988 xmlbuf[st.st_size] = 0;
989 close (fd);
991 else
993 #define BUFSIZE 8196
994 size_t size = 0, xlen = 0;
996 for (;;)
998 size_t ret;
999 xmlChar *tmp;
1001 tmp = xrealloc (xmlbuf, size+BUFSIZE+1);
1002 if (!tmp)
1004 xfree (xmlbuf);
1005 return GPG_ERR_ENOMEM;
1008 xmlbuf = tmp;
1009 size += BUFSIZE;
1010 ret = read (STDIN_FILENO, &xmlbuf[xlen], BUFSIZE);
1011 if (ret == -1)
1013 rc = gpg_error_from_syserror ();
1014 xfree (xmlbuf);
1015 return rc;
1018 xlen += ret;
1019 if (!ret || ret < BUFSIZE)
1020 break;
1023 xmlbuf[xlen] = 0;
1026 doc = xmlReadDoc (xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS);
1027 xfree (xmlbuf);
1028 if (!doc)
1029 return GPG_ERR_BAD_DATA;
1031 xmlNodePtr n = xmlDocGetRootElement (doc);
1032 if (n && !xmlStrEqual (n->name, (xmlChar *) "pwmd"))
1033 rc = GPG_ERR_BAD_DATA;
1035 if (!rc)
1037 rc = xml_validate_import (NULL, n ? n->children : n);
1038 if (!rc)
1040 rc = crypto_init (&crypto, NULL, filename, keyfile != NULL, keyfile);
1041 if (!rc)
1043 if (keyfile)
1045 crypto->flags |= CRYPTO_FLAG_KEYFILE;
1046 crypto->keyfile = str_dup (keyfile);
1049 xmlDocDumpMemory (doc, &crypto->plaintext, &len);
1050 if (len > 0)
1051 crypto->plaintext_size = len;
1052 else
1053 rc = GPG_ERR_ENOMEM;
1058 if (!rc)
1060 if (!symmetric && !keyid)
1062 crypto->save.userid = str_dup (userid);
1063 crypto->save.algo = algo ? str_dup (algo) : NULL;
1064 crypto->save.expire = expire;
1065 if (no_passphrase)
1066 crypto->save.flags |= GPGME_CREATE_NOPASSWD;
1068 rc = crypto_genkey (NULL, crypto);
1070 else
1072 if (keyid)
1073 crypto->save.pubkey = strv_dup (keyid);
1075 if (sign_keyid)
1076 crypto->save.sigkey = str_dup (sign_keyid);
1079 if (!rc)
1081 crypto->flags |= symmetric ? CRYPTO_FLAG_SYMMETRIC : 0;
1082 rc = crypto_encrypt (NULL, crypto);
1086 if (!rc)
1088 if (!strcmp (outfile, "-"))
1089 outfile = NULL;
1091 xfree (crypto->plaintext);
1092 crypto->plaintext = NULL;
1093 xfree (crypto->filename);
1094 crypto->filename = outfile ? str_dup (outfile) : NULL;
1095 rc = crypto_write_file (crypto, NULL, NULL);
1098 xmlFreeDoc (doc);
1099 crypto_free (crypto);
1100 return rc;
1103 static gpg_error_t
1104 do_cache_push (struct crypto_s *crypto)
1106 gpg_error_t rc;
1107 xmlDocPtr doc;
1108 struct cache_data_s *cdata;
1109 unsigned char *crc;
1110 size_t len;
1111 int fd = -1;
1113 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1114 crypto->filename);
1116 if (valid_filename (crypto->filename) == 0)
1118 log_write (_("%s: Invalid characters in filename"), crypto->filename);
1119 return GPG_ERR_INV_VALUE;
1122 rc = lock_flock (NULL, crypto->filename, LOCK_SH, &fd);
1123 if (!rc)
1124 rc = crypto_decrypt (NULL, crypto);
1125 if (rc)
1127 unlock_flock (&fd);
1128 return rc;
1131 rc = xml_parse_doc ((char *) crypto->plaintext, crypto->plaintext_size, &doc);
1132 if (rc)
1134 unlock_flock (&fd);
1135 log_write ("%s", pwmd_strerror (rc));
1136 return rc;
1139 cdata = xcalloc (1, sizeof (struct cache_data_s));
1140 if (!cdata)
1142 unlock_flock (&fd);
1143 xmlFreeDoc (doc);
1144 return GPG_ERR_ENOMEM;
1147 rc = get_checksum (crypto->filename, &crc, &len);
1148 unlock_flock (&fd);
1149 if (rc)
1151 xmlFreeDoc (doc);
1152 cache_free_data_once (cdata);
1153 return rc;
1156 cdata->crc = crc;
1157 rc = cache_encrypt (crypto);
1158 if (!rc)
1160 cdata->doc = crypto->plaintext;
1161 cdata->size = crypto->plaintext_size;
1162 crypto->plaintext = NULL;
1163 cdata->pubkey = crypto->pubkey;
1164 cdata->sigkey = crypto->sigkey;
1165 crypto->pubkey = NULL;
1166 crypto->sigkey = NULL;
1168 else
1170 xmlFreeDoc (doc);
1171 cache_free_data_once (cdata);
1172 return rc;
1175 long timeout = config_get_long (crypto->filename, "cache_timeout");
1176 rc = cache_add_file (crypto->filename, cdata, timeout);
1177 return rc;
1180 static gpg_error_t
1181 init_client (int fd, const char *addr)
1183 gpg_error_t rc = 0;
1184 struct client_thread_s *new = xcalloc (1, sizeof (struct client_thread_s));
1186 if (!new)
1188 close (fd);
1189 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (ENOMEM));
1190 return GPG_ERR_ENOMEM;
1193 MUTEX_LOCK (&cn_mutex);
1194 pthread_cleanup_push (release_mutex_cb, &cn_mutex);
1195 new->conntime = time (NULL);
1197 if (pipe (new->status_msg_pipe) == -1)
1198 rc = gpg_error_from_errno (errno);
1199 else
1200 pthread_mutex_init (&new->status_mutex, NULL);
1202 if (!rc)
1204 #ifdef WITH_GNUTLS
1205 new->remote = addr ? 1 : 0;
1206 if (addr)
1207 new->peeraddr = str_dup (addr);
1208 #endif
1209 new->fd = fd;
1210 rc = create_thread (client_thread, new, &new->tid, 1);
1211 if (rc)
1213 close (new->status_msg_pipe[0]);
1214 close (new->status_msg_pipe[1]);
1215 pthread_mutex_destroy (&new->status_mutex);
1219 if (!rc)
1221 if (addr)
1222 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1223 (pthread_t *) new->tid, fd, addr);
1224 else
1225 log_write (_("new connection: tid=%p, fd=%i"),
1226 (pthread_t *) new->tid, fd);
1229 pthread_cleanup_pop (1);
1231 if (rc)
1233 xfree (new);
1234 close (fd);
1235 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
1237 return rc;
1240 #ifdef WITH_GNUTLS
1241 static gpg_error_t
1242 do_tls_accept (struct pollfd *fds)
1244 struct sockaddr_storage raddr;
1245 socklen_t slen = sizeof (raddr);
1246 int fd;
1247 char s[INET6_ADDRSTRLEN];
1249 if (!(fds->revents & POLLIN))
1250 return 0;
1252 memset (&raddr, 0, sizeof (raddr));
1253 fd = accept (fds->fd, (struct sockaddr *) &raddr, &slen);
1254 if (fd == -1)
1256 int e = errno;
1258 if (errno != EAGAIN && !quit)
1259 log_write ("%s: %s", __FUNCTION__,
1260 pwmd_strerror (gpg_error_from_syserror()));
1262 return gpg_error_from_errno (e);
1265 inet_ntop (raddr.ss_family, get_in_addr ((struct sockaddr *) &raddr), s,
1266 sizeof s);
1267 (void) init_client (fd, s);
1268 return 0;
1270 #endif
1272 static void *
1273 accept_thread (void *arg)
1275 int sockfd = *(int *) arg;
1276 #ifndef HAVE_PTHREAD_CANCEL
1277 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
1278 #endif
1280 #ifdef HAVE_PR_SET_NAME
1281 prctl (PR_SET_NAME, "accept");
1282 #endif
1283 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
1285 for (;;)
1287 socklen_t slen = sizeof (struct sockaddr_un);
1288 struct sockaddr_un raddr;
1289 int fd, s = 0;
1290 struct pollfd fds[3];
1292 TEST_CANCEL ();
1293 memset (fds, 0, sizeof (fds));
1294 fds[s].fd = sockfd;
1295 fds[s++].events = POLLIN;
1297 #ifdef WITH_GNUTLS
1298 if (tls_fd != -1)
1300 fds[s].fd = tls_fd;
1301 fds[s++].events = POLLIN;
1303 else
1304 fds[s].fd = tls_fd;
1306 if (tls6_fd != -1)
1308 fds[s].fd = tls6_fd;
1309 fds[s++].events = POLLIN;
1311 else
1312 fds[s].fd = tls6_fd;
1313 #endif
1315 s = poll (fds, s, 500);
1316 if (s == -1)
1318 if (errno != EINTR)
1319 log_write ("%s", strerror (errno));
1320 break;
1322 else if (s == 0)
1323 continue;
1325 if (fds[0].revents & POLLIN)
1327 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1328 if (fd == -1)
1330 if (errno == EMFILE || errno == ENFILE)
1331 log_write ("%s: %s", __FUNCTION__,
1332 pwmd_strerror (gpg_error_from_errno (errno)));
1333 else if (errno != EAGAIN && errno != EINTR)
1335 if (!quit) // probably EBADF
1336 log_write ("%s: %s", __FUNCTION__,
1337 pwmd_strerror (gpg_error_from_errno (errno)));
1339 break;
1342 continue;
1345 (void) init_client (fd, NULL);
1348 #ifdef WITH_GNUTLS
1349 if (tls_fd != -1 && fds[1].fd == tls_fd)
1350 (void)do_tls_accept (&fds[1]);
1352 if (tls6_fd != -1 && fds[1].fd == tls6_fd)
1353 (void)do_tls_accept (&fds[1]);
1355 if (tls6_fd != -1 && fds[2].fd == tls6_fd)
1356 (void)do_tls_accept (&fds[2]);
1357 #endif
1360 /* Just in case accept() failed for some reason other than EBADF */
1361 quit = 1;
1362 return NULL;
1365 static void *
1366 cache_timer_thread (void *arg)
1368 unsigned k = 0;
1369 #ifndef HAVE_PTHREAD_CANCEL
1370 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
1371 #endif
1373 (void)arg;
1375 #ifdef HAVE_PR_SET_NAME
1376 prctl (PR_SET_NAME, "timer");
1377 #endif
1378 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
1380 for (;;)
1382 struct timeval tv = { 1, 0 };
1383 unsigned keepalive = config_get_integer ("global", "keepalive_interval");
1385 TEST_CANCEL ();
1386 select (0, NULL, NULL, NULL, &tv);
1387 cache_adjust_timeout ();
1389 if (keepalive && ++k >= keepalive)
1391 send_status_all (STATUS_KEEPALIVE, NULL);
1392 k = 0;
1396 return NULL;
1399 static int
1400 signal_loop (sigset_t sigset)
1402 int done = 0;
1406 int sig;
1408 sigwait (&sigset, &sig);
1409 log_write (_("caught signal %i (%s)"), sig, strsignal (sig));
1411 switch (sig)
1413 case SIGHUP:
1414 pthread_cond_signal (&rcfile_cond);
1415 break;
1416 case SIGUSR1:
1417 log_write (_("clearing file cache"));
1418 cache_clear (NULL, NULL, 1, 0);
1419 send_status_all (STATUS_CACHE, NULL);
1420 break;
1421 default:
1422 done = 1;
1423 break;
1426 while (!done);
1428 return done;
1431 static void
1432 catchsig (int sig)
1434 log_write (_ ("Caught signal %i (%s). Exiting."), sig, strsignal (sig));
1435 #ifdef HAVE_BACKTRACE
1436 BACKTRACE (__FUNCTION__);
1437 #endif
1438 longjmp (jmp, 1);
1441 static void
1442 cancel_all_clients ()
1444 unsigned i, t;
1446 MUTEX_LOCK (&cn_mutex);
1447 t = slist_length (cn_thread_list);
1448 for (i = 0; i < t; i++)
1450 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
1452 #ifdef HAVE_PTHREAD_CANCEL
1453 pthread_cancel (thd->tid);
1454 #else
1455 pthread_kill (thd->tid, SIGUSR2);
1456 #endif
1459 while (slist_length (cn_thread_list))
1461 MUTEX_UNLOCK (&cn_mutex);
1462 usleep (50000);
1463 MUTEX_LOCK (&cn_mutex);
1466 MUTEX_UNLOCK (&cn_mutex);
1469 static int
1470 server_loop (int sockfd, char **socketpath)
1472 pthread_t cache_timeout_tid;
1473 pthread_t accept_tid;
1474 int cancel_timeout_thread = 0;
1475 int cancel_accept_thread = 0;
1476 int cancel_rcfile_thread = 0;
1477 sigset_t sigset;
1478 int n;
1479 int segv = 0;
1480 gpg_error_t rc;
1482 init_commands ();
1483 sigemptyset (&sigset);
1485 /* Termination */
1486 sigaddset (&sigset, SIGTERM);
1487 sigaddset (&sigset, SIGINT);
1489 /* Clears the file cache. */
1490 sigaddset (&sigset, SIGUSR1);
1492 /* Configuration file reloading. */
1493 sigaddset (&sigset, SIGHUP);
1495 #ifndef HAVE_PTHREAD_CANCEL
1497 The socket, cache and rcfile threads use this signal when
1498 pthread_cancel() is unavailable. Prevent the main thread from
1499 catching this signal from another process.
1501 sigaddset (&sigset, SIGUSR2);
1502 #endif
1504 /* An assertion failure. */
1505 signal (SIGABRT, catchsig);
1506 sigaddset (&sigset, SIGABRT);
1507 sigprocmask (SIG_BLOCK, &sigset, NULL);
1509 #ifndef HAVE_PTHREAD_CANCEL
1510 /* Remove this signal from the watched signals in signal_loop(). */
1511 sigdelset (&sigset, SIGUSR2);
1512 #endif
1514 /* Can show a backtrace of the stack in the log. */
1515 signal (SIGSEGV, catchsig);
1517 char *p = get_username (getuid());
1518 log_write (_("%s started for user %s"), PACKAGE_STRING, p);
1519 xfree (p);
1521 #ifdef WITH_GNUTLS
1522 if (config_get_boolean ("global", "enable_tcp"))
1523 log_write (_("Listening on %s and TCP port %i"), *socketpath,
1524 config_get_integer ("global", "tcp_port"));
1525 else
1526 log_write (_("Listening on %s"), *socketpath);
1527 #else
1528 log_write (_("Listening on %s"), *socketpath);
1529 #endif
1531 rc = create_thread (reload_rcfile_thread, NULL, &rcfile_tid, 0);
1532 if (rc)
1534 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1535 pwmd_strerror (rc));
1536 goto done;
1539 cancel_rcfile_thread = 1;
1540 rc = create_thread (cache_timer_thread, NULL, &cache_timeout_tid, 0);
1541 if (rc)
1543 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1544 pwmd_strerror (rc));
1545 goto done;
1548 cancel_timeout_thread = 1;
1549 rc = create_thread (accept_thread, &sockfd, &accept_tid, 0);
1550 if (rc)
1552 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1553 pwmd_strerror (rc));
1554 goto done;
1557 cancel_accept_thread = 1;
1558 if (!setjmp (jmp))
1559 signal_loop (sigset);
1560 else
1561 segv = 1;
1563 done:
1565 * We're out of the main server loop. This happens when a signal was sent
1566 * to terminate the daemon. Cancel all clients and exit.
1568 if (cancel_accept_thread)
1570 #ifdef HAVE_PTHREAD_CANCEL
1571 n = pthread_cancel (accept_tid);
1572 #else
1573 n = pthread_kill (accept_tid, SIGUSR2);
1574 #endif
1575 if (!n)
1576 pthread_join (accept_tid, NULL);
1579 if (cancel_timeout_thread)
1581 #ifdef HAVE_PTHREAD_CANCEL
1582 n = pthread_cancel (cache_timeout_tid);
1583 #else
1584 n = pthread_kill (cache_timeout_tid, SIGUSR2);
1585 #endif
1586 if (!n)
1587 pthread_join (cache_timeout_tid, NULL);
1590 #ifdef WITH_GNUTLS
1591 tls_start_stop (1);
1592 #endif
1593 shutdown (sockfd, SHUT_RDWR);
1594 close (sockfd);
1595 unlink (*socketpath);
1596 xfree (*socketpath);
1597 *socketpath = NULL;
1598 MUTEX_LOCK (&cn_mutex);
1599 n = slist_length (cn_thread_list);
1600 MUTEX_UNLOCK (&cn_mutex);
1602 if (n && !segv)
1603 cancel_all_clients ();
1604 else
1605 free_all_clients ();
1607 if (cancel_rcfile_thread)
1609 #ifdef HAVE_PTHREAD_CANCEL
1610 pthread_cancel (rcfile_tid);
1611 #else
1612 pthread_kill (rcfile_tid, SIGUSR2);
1613 pthread_cond_signal (&rcfile_cond);
1614 #endif
1615 pthread_join (rcfile_tid, NULL);
1618 cache_deinit ();
1619 deinit_commands ();
1620 return segv ? EXIT_FAILURE : EXIT_SUCCESS;
1623 static void
1624 usage (const char *pn, int status)
1626 FILE *fp = status == EXIT_FAILURE ? stderr : stdout;
1628 fprintf (fp, _("Usage: %s [OPTIONS] [file1] [...]\n"
1629 " --homedir alternate pwmd home directory (~/.pwmd)\n"
1630 " -f, --rcfile=filename load the specfied configuration file\n"
1631 " (~/.pwmd/config)\n"
1632 " --kill terminate an existing instance of pwmd\n"
1633 " -n, --no-fork run as a foreground process\n"
1634 " --disable-dump disable the LIST, XPATH and DUMP commands\n"
1635 " --ignore, --force ignore cache pushing errors during startup\n"
1636 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
1637 " -k, --passphrase-file=file for use when importing\n"
1638 " -o, --outfile=filename output file when importing\n"
1639 " --keyid=fpr[,..] public key to use when encrypting\n"
1640 " --sign-keyid=fpr fingerprint of the signing key to use\n"
1641 " -s, --symmetric use conventional encryption with optional signer\n"
1642 " --userid=string name and email address to use when importing\n"
1643 " --algo=string algorithm to use when importing (engine default)\n"
1644 " --expire=seconds key expiry time when importing (3 years)\n"
1645 " --no-passphrase don't require a passphrase when importing\n"
1646 " --debug=[a:..][,g:N][,t:N] enable debugging (a:[ixedsc],g:[1-9],t:[0-N])\n"
1647 " --help this help text\n"
1648 " --version show version and compile time features\n"),
1649 pn);
1650 exit (status);
1653 static void
1654 unlink_stale_socket (const char *sock, const char *pidfile)
1656 log_write (_ ("removing stale socket %s"), sock);
1657 unlink (sock);
1658 unlink (pidfile);
1661 static int
1662 test_pidfile (const char *path, const char *sock, char *buf, size_t buflen,
1663 char **pidfile, int create, mode_t mode, int terminate)
1665 pid_t pid;
1666 int fd;
1667 size_t len;
1669 if (!create)
1671 snprintf (buf, buflen, "%s/%s.pid", homedir, sock);
1672 *pidfile = str_dup (buf);
1673 fd = open (buf, O_RDONLY);
1675 else
1676 fd = open (*pidfile, O_CREAT|O_WRONLY|O_TRUNC, mode);
1678 if (fd == -1)
1680 if (!create && errno != ENOENT)
1682 log_write ("%s: %s", buf, pwmd_strerror (errno));
1683 xfree (*pidfile);
1684 *pidfile = NULL;
1685 return -1;
1687 else if (!create && !terminate)
1688 return 0;
1690 log_write ("%s: %s", *pidfile, strerror (errno));
1691 return -1;
1694 if (create)
1696 snprintf (buf, buflen, "%i", getpid ());
1697 ssize_t ret = write (fd, buf, strlen (buf));
1698 if (ret == -1)
1699 log_write ("%s (%i): %s", __FUNCTION__, __LINE__,
1700 pwmd_strerror (gpg_error_from_syserror ()));
1701 close (fd);
1702 return 0;
1705 len = read (fd, buf, buflen);
1706 close (fd);
1707 if (len == 0)
1709 unlink_stale_socket (path, *pidfile);
1710 return 0;
1713 if (sscanf (buf, "%5i", &pid) != 1 || pid == 0)
1715 if (!terminate)
1717 unlink_stale_socket (path, *pidfile);
1718 return 0;
1722 if (kill (pid, 0) == -1)
1724 unlink_stale_socket (path, *pidfile);
1725 return 0;
1728 if (terminate)
1730 if (kill (pid, SIGTERM) == -1)
1731 log_write ("%s: %s", path, pwmd_strerror (errno));
1733 else
1734 log_write (_ ("an instance for socket %s is already running"), path);
1736 xfree (*pidfile);
1737 *pidfile = NULL;
1738 return 1;
1741 static unsigned
1742 parse_debug_level (const char *str, unsigned *debug, int *gpgme, int *tls)
1744 const char *p;
1745 unsigned level = 0;
1746 int gl = 0, tl = 0;
1748 for (p = str; p && *p; p++)
1750 if (*p == 'a') // assuan debug flags
1752 if (*++p != ':')
1753 return 1;
1755 while (*++p)
1757 switch (*p)
1759 case 'i':
1760 level |= ASSUAN_LOG_INIT;
1761 break;
1762 case 'x':
1763 level |= ASSUAN_LOG_CTX;
1764 break;
1765 case 'e':
1766 level |= ASSUAN_LOG_ENGINE;
1767 break;
1768 case 'd':
1769 level |= ASSUAN_LOG_DATA;
1770 break;
1771 case 's':
1772 level |= ASSUAN_LOG_SYSIO;
1773 break;
1774 case 'c':
1775 level |= ASSUAN_LOG_CONTROL;
1776 break;
1777 case ',':
1778 break;
1779 default:
1780 return 1;
1783 if (*p == ',')
1784 break;
1787 if (!*p)
1788 break;
1790 else if (*p == 'g' || *p == 't') // gpgme and TLS debug level
1792 int t = *p == 't';
1793 int n;
1795 if (*++p != ':')
1796 return 1;
1798 if (!isdigit (*++p))
1799 return 1;
1801 n = atoi (p);
1802 if (t)
1803 tl = n;
1804 else
1805 gl = n;
1807 if (tl < 0 || gl < 0 || gl > 9)
1808 return 1;
1810 while (isdigit (*p))
1811 p++;
1813 p--;
1814 if (*(p+1) && *(p+1) != ',')
1815 return 1;
1816 else if (*(p+1))
1817 p++;
1819 else
1820 return 1;
1823 if (tl)
1824 *tls = tl;
1826 if (gl)
1827 *gpgme = gl;
1829 *debug = level;
1830 return 0;
1834 main (int argc, char *argv[])
1836 int opt;
1837 struct sockaddr_un addr;
1838 char buf[PATH_MAX];
1839 char *socketpath = NULL, *socketdir, *socketname = NULL;
1840 char *socketarg = NULL;
1841 char *datadir = NULL;
1842 char *pidfile = NULL;
1843 mode_t mode = 0600;
1844 int x;
1845 char *p;
1846 char **cache_push = NULL;
1847 char *import = NULL, *keyid = NULL, *sign_keyid = NULL;
1848 char *userid = NULL;
1849 char *algo = NULL;
1850 long expire = 0;
1851 int no_passphrase = 0;
1852 int estatus = EXIT_FAILURE;
1853 int sockfd;
1854 char *outfile = NULL;
1855 int do_unlink = 0;
1856 int secure = 0;
1857 int show_version = 0;
1858 int force = 0;
1859 gpg_error_t rc;
1860 char *keyfile = NULL;
1861 int exists;
1862 int optindex;
1863 int terminate = 0;
1864 int sym = 0;
1865 int gpgme_level = -1;
1866 int tls_level = -1;
1867 int backlog = 0;
1868 /* Must maintain the same order as longopts[] */
1869 enum
1871 OPT_VERSION, OPT_HELP, OPT_HOMEDIR, OPT_NO_FORK, OPT_DISABLE_DUMP,
1872 OPT_FORCE, OPT_RCFILE, OPT_PASSPHRASE_FILE, OPT_IMPORT, OPT_OUTFILE,
1873 OPT_KEYID, OPT_SIGN_KEYID, OPT_SYMMETRIC, OPT_USERID, OPT_ALGO, OPT_EXPIRE,
1874 OPT_NOPASSPHRASE, OPT_KILL, OPT_DEBUG
1876 const char *optstring = "nf:C:k:I:o:s";
1877 const struct option longopts[] = {
1878 {"version", no_argument, 0, 0},
1879 {"help", no_argument, 0, 0},
1880 {"homedir", required_argument, 0, 0},
1881 {"no-fork", no_argument, 0, 'n'},
1882 {"disable_dump", no_argument, 0, 0},
1883 {"force", no_argument, 0, 0},
1884 {"rcfile", required_argument, 0, 'f'},
1885 {"passphrase-file", required_argument, 0, 'k'},
1886 {"import", required_argument, 0, 'I'},
1887 {"outfile", required_argument, 0, 'o'},
1888 {"keyid", required_argument, 0, 0},
1889 {"sign-keyid", required_argument, 0, 0},
1890 {"symmetric", no_argument, 0, 's'},
1891 {"userid", required_argument, 0, 0},
1892 {"algo", required_argument, 0, 0},
1893 {"expire", required_argument, 0, 0},
1894 {"no-passphrase", no_argument, 0, 0},
1895 {"kill", no_argument, 0, 0},
1896 {"debug", required_argument, 0, 0},
1897 {0, 0, 0, 0}
1900 log_fd = -1;
1901 cmdline = 1;
1902 expire = time (NULL) + DEFAULT_EXPIRE;
1904 #ifndef DEBUG
1905 #ifdef HAVE_SETRLIMIT
1906 struct rlimit rl;
1908 rl.rlim_cur = rl.rlim_max = 0;
1910 if (setrlimit (RLIMIT_CORE, &rl) != 0)
1911 err (EXIT_FAILURE, "setrlimit()");
1912 #endif
1914 #ifdef HAVE_PR_SET_DUMPABLE
1915 prctl (PR_SET_DUMPABLE, 0);
1916 #endif
1917 #endif
1919 #ifdef ENABLE_NLS
1920 setlocale (LC_ALL, "");
1921 bindtextdomain ("pwmd", LOCALEDIR);
1922 textdomain ("pwmd");
1923 #endif
1925 while ((opt = getopt_long (argc, argv, optstring, longopts, &optindex))
1926 != -1)
1928 switch (opt)
1930 case 'I':
1931 import = optarg;
1932 break;
1933 case 'k':
1934 keyfile = optarg;
1935 break;
1936 case 'o':
1937 outfile = optarg;
1938 break;
1939 case 'n':
1940 nofork = 1;
1941 break;
1942 case 'f':
1943 rcfile = str_dup (optarg);
1944 break;
1945 case 's':
1946 sym = 1;
1947 break;
1948 default:
1949 usage (argv[0], EXIT_FAILURE);
1950 break;
1951 case 0:
1952 switch (optindex)
1954 case OPT_DEBUG:
1955 if (parse_debug_level (optarg, &assuan_level, &gpgme_level,
1956 &tls_level))
1957 usage (argv[0], EXIT_FAILURE);
1958 break;
1959 case OPT_SYMMETRIC:
1960 sym = 1;
1961 break;
1962 case OPT_VERSION:
1963 show_version = 1;
1964 break;
1965 case OPT_HELP:
1966 usage (argv[0], EXIT_SUCCESS);
1967 break;
1968 case OPT_HOMEDIR:
1969 homedir = str_dup (optarg);
1970 break;
1971 case OPT_NO_FORK:
1972 nofork = 1;
1973 break;
1974 case OPT_DISABLE_DUMP:
1975 secure = 1;
1976 break;
1977 case OPT_FORCE:
1978 force = 1;
1979 break;
1980 case OPT_RCFILE:
1981 rcfile = str_dup (optarg);
1982 break;
1983 case OPT_PASSPHRASE_FILE:
1984 keyfile = optarg;
1985 break;
1986 case OPT_IMPORT:
1987 import = optarg;
1988 break;
1989 case OPT_OUTFILE:
1990 outfile = optarg;
1991 break;
1992 case OPT_KEYID:
1993 keyid = optarg;
1994 break;
1995 case OPT_SIGN_KEYID:
1996 sign_keyid = optarg;
1997 break;
1998 case OPT_USERID:
1999 userid = optarg;
2000 break;
2001 case OPT_ALGO:
2002 algo = optarg;
2003 break;
2004 case OPT_EXPIRE:
2005 errno = rc = 0;
2006 expire = strtoul (optarg, &p, 10);
2008 if (!errno && p && *p)
2009 rc = GPG_ERR_INV_VALUE;
2010 else if (expire == ULONG_MAX)
2011 rc = GPG_ERR_INV_VALUE;
2012 else if (errno)
2013 rc = gpg_error_from_syserror ();
2015 if (rc)
2016 usage (argv[0], EXIT_FAILURE);
2017 break;
2018 case OPT_NOPASSPHRASE:
2019 no_passphrase = 1;
2020 break;
2021 case OPT_KILL:
2022 terminate = 1;
2023 break;
2024 default:
2025 usage (argv[0], EXIT_FAILURE);
2030 if (show_version)
2032 printf (_("%s\n\n"
2033 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016\n"
2034 "%s\n"
2035 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2036 "Compile time features:\n%s"), PACKAGE_STRING,
2037 PACKAGE_BUGREPORT,
2038 #ifdef PWMD_HOMEDIR
2039 "+PWMD_HOMEDIR=" PWMD_HOMEDIR "\n"
2040 #endif
2041 #ifdef WITH_GNUTLS
2042 "+WITH_GNUTLS\n"
2043 #else
2044 "-WITH_GNUTLS\n"
2045 #endif
2046 #ifdef WITH_LIBACL
2047 "+WITH_LIBACL\n"
2048 #else
2049 "-WITH_LIBACL\n"
2050 #endif
2051 #ifdef DEBUG
2052 "+DEBUG\n"
2053 #else
2054 "-DEBUG\n"
2055 #endif
2056 #ifdef MEM_DEBUG
2057 "+MEM_DEBUG\n"
2058 #else
2059 "-MEM_DEBUG\n"
2060 #endif
2061 #ifdef MUTEX_DEBUG
2062 "+MUTEX_DEBUG\n"
2063 #else
2064 "-MUTEX_DEBUG\n"
2065 #endif
2067 exit (EXIT_SUCCESS);
2070 if (gpgme_level != -1)
2072 char s[2] = { gpgme_level + '0', 0 };
2074 if (getenv ("GPGME_DEBUG"))
2075 log_write (_ ("Overriding GPGME_DEBUG environment with level %u!"),
2076 gpgme_level);
2078 gpgme_set_global_flag ("debug", s);
2081 if (setup_crypto ())
2082 exit (EXIT_FAILURE);
2084 #ifdef WITH_GNUTLS
2085 tls_level = tls_level == -1 ? 1 : tls_level;
2086 gnutls_global_set_log_level (tls_level);
2087 tls_fd = -1;
2088 tls6_fd = -1;
2089 #endif
2090 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
2091 xmlInitMemory ();
2092 xmlInitGlobals ();
2093 xmlInitParser ();
2094 xmlXPathInit ();
2096 if (!homedir)
2097 #ifdef PWMD_HOMEDIR
2098 homedir = str_dup(PWMD_HOMEDIR);
2099 #else
2100 homedir = str_asprintf ("%s/.pwmd", get_home_dir());
2101 #endif
2103 if (mkdir (homedir, 0700) == -1 && errno != EEXIST)
2104 err (EXIT_FAILURE, "%s", homedir);
2106 if (!rcfile)
2107 rcfile = str_asprintf ("%s/config", homedir);
2109 pthread_key_create (&last_error_key, free_key);
2110 #ifndef HAVE_PTHREAD_CANCEL
2111 pthread_key_create (&signal_thread_key, free_key);
2112 #endif
2114 pthread_mutexattr_t attr;
2115 pthread_mutexattr_init (&attr);
2116 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
2117 pthread_mutex_init (&rcfile_mutex, &attr);
2118 global_config = config_parse (rcfile, 0);
2119 if (!global_config)
2121 pthread_mutexattr_destroy (&attr);
2122 pthread_mutex_destroy (&rcfile_mutex);
2123 exit (EXIT_FAILURE);
2126 p = config_get_string ("global", "gpg_homedir");
2127 if (!p)
2128 datadir = str_asprintf ("%s/.gnupg", homedir);
2129 else
2130 datadir = expand_homedir (p);
2132 xfree (p);
2133 if (mkdir (datadir, 0700) == -1 && errno != EEXIST)
2134 err (EXIT_FAILURE, "%s", datadir);
2136 rc = gpgme_set_engine_info (GPGME_PROTOCOL_OpenPGP, NULL, datadir);
2137 if (rc)
2138 errx (EXIT_FAILURE, "%s: %s", datadir, pwmd_strerror (rc));
2139 xfree (datadir);
2141 snprintf (buf, sizeof (buf), "%s/data", homedir);
2142 if (mkdir (buf, 0700) == -1 && errno != EEXIST)
2143 err (EXIT_FAILURE, "%s", buf);
2145 datadir = str_dup (buf);
2146 pthread_cond_init (&rcfile_cond, NULL);
2147 pthread_mutex_init (&cn_mutex, &attr);
2148 pthread_mutexattr_destroy (&attr);
2150 setup_logging ();
2152 x = config_get_int_param (global_config, "global", "priority", &exists);
2153 if (exists && x != atoi(INVALID_PRIORITY))
2155 errno = 0;
2156 if (setpriority (PRIO_PROCESS, 0, x) == -1)
2158 log_write ("setpriority(): %s",
2159 pwmd_strerror (gpg_error_from_errno (errno)));
2160 goto do_exit;
2163 #ifdef HAVE_MLOCKALL
2164 if (disable_mlock == 0 && mlockall (MCL_CURRENT | MCL_FUTURE) == -1)
2166 log_write ("mlockall(): %s",
2167 pwmd_strerror (gpg_error_from_errno (errno)));
2168 goto do_exit;
2170 #endif
2172 rc = cache_init ();
2173 if (rc)
2175 log_write ("pwmd: ERR %i: %s", rc, pwmd_strerror (rc));
2176 exit (EXIT_FAILURE);
2179 if (import)
2181 char **keyids = NULL;
2183 if (!outfile || !*outfile || argc != optind)
2184 usage (argv[0], EXIT_FAILURE);
2186 if (keyid)
2187 keyids = str_split (keyid, ",", 0);
2188 else if (!userid && !sym)
2189 usage (argv[0], EXIT_FAILURE);
2191 rc = xml_import (import, outfile, keyids, sign_keyid, keyfile, userid,
2192 algo, expire, no_passphrase, sym);
2193 strv_free (keyids);
2194 if (rc)
2196 if (gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
2197 rc = gpg_error (rc);
2199 log_write ("%s: %u: %s", import, rc, pwmd_strerror (rc));
2202 config_free (global_config);
2203 xfree (rcfile);
2204 exit (rc ? EXIT_FAILURE : EXIT_SUCCESS);
2207 p = config_get_string ("global", "socket_path");
2208 if (!p)
2209 p = str_asprintf ("%s/socket", homedir);
2211 socketarg = expand_homedir (p);
2212 xfree (p);
2214 if (!secure)
2215 disable_list_and_dump = config_get_boolean ("global",
2216 "disable_list_and_dump");
2217 else
2218 disable_list_and_dump = secure;
2220 cache_push = config_get_list ("global", "cache_push");
2222 while (optind < argc)
2224 if (strv_printf (&cache_push, "%s", argv[optind++]) == 0)
2225 errx (EXIT_FAILURE, "%s", pwmd_strerror (GPG_ERR_ENOMEM));
2228 if (!strchr (socketarg, '/'))
2230 socketdir = getcwd (buf, sizeof (buf));
2231 socketname = str_dup (socketarg);
2232 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2234 else
2236 socketname = str_dup (strrchr (socketarg, '/')+1);
2237 socketarg[strlen (socketarg) - strlen (socketname) - 1] = 0;
2238 socketdir = str_dup (socketarg);
2239 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2242 if (chdir (datadir))
2244 log_write ("%s: %s", datadir,
2245 pwmd_strerror (gpg_error_from_errno (errno)));
2246 unlink (socketpath);
2247 goto do_exit;
2250 x = test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 0,
2251 mode, terminate);
2252 if (!terminate && x)
2253 goto do_exit;
2254 else if (terminate)
2256 estatus = x != 1 ? EXIT_FAILURE : EXIT_SUCCESS;
2257 goto do_exit;
2261 * bind() doesn't like the full pathname of the socket or any non alphanum
2262 * characters so change to the directory where the socket is wanted then
2263 * create it then change to datadir.
2265 if (chdir (socketdir))
2267 log_write ("%s: %s", socketdir,
2268 pwmd_strerror (gpg_error_from_errno (errno)));
2269 goto do_exit;
2272 xfree (socketdir);
2274 if ((sockfd = socket (PF_UNIX, SOCK_STREAM, 0)) == -1)
2276 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2277 goto do_exit;
2280 addr.sun_family = AF_UNIX;
2281 snprintf (addr.sun_path, sizeof (addr.sun_path), "%s", socketname);
2282 do_unlink = 1;
2283 if (bind (sockfd, (struct sockaddr *) &addr, sizeof (struct sockaddr)) ==
2286 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2288 if (errno == EADDRINUSE)
2290 do_unlink = 0;
2291 log_write (_("Either there is another pwmd running or '%s' is a \n"
2292 "stale socket. Please remove it manually."), socketpath);
2295 goto do_exit;
2299 char *t = config_get_string ("global", "socket_perms");
2300 mode_t mask;
2302 if (t)
2304 mode = strtol (t, NULL, 8);
2305 mask = umask (0);
2306 xfree (t);
2308 if (chmod (socketname, mode) == -1)
2310 log_write ("%s: %s", socketname,
2311 pwmd_strerror (gpg_error_from_errno (errno)));
2312 close (sockfd);
2313 umask (mask);
2314 goto do_exit;
2317 umask (mask);
2321 if (chdir (datadir))
2323 log_write ("%s: %s", datadir,
2324 pwmd_strerror (gpg_error_from_errno (errno)));
2325 close (sockfd);
2326 goto do_exit;
2329 xfree (datadir);
2330 #ifdef WITH_GNUTLS
2331 if (config_get_boolean ("global", "enable_tcp"))
2333 if (!tls_start_stop (0))
2335 close (sockfd);
2336 goto do_exit;
2339 #endif
2342 * Set the cache entry for a file. Prompts for the password.
2344 if (cache_push)
2346 for (opt = 0; cache_push[opt]; opt++)
2348 struct crypto_s *crypto = NULL;
2349 char *pw_file = config_get_string (cache_push[opt],
2350 "passphrase_file");
2351 rc = crypto_init (&crypto, NULL, cache_push[opt], pw_file != NULL,
2352 pw_file);
2354 if (!rc)
2356 crypto->flags |= pw_file ? CRYPTO_FLAG_KEYFILE : 0;
2357 crypto->keyfile = pw_file;
2359 else
2360 xfree (pw_file);
2362 if (rc)
2364 estatus = EXIT_FAILURE;
2365 goto do_exit;
2368 rc = do_cache_push (crypto);
2369 if (rc && !force)
2371 log_write ("ERR %u: %s", rc, pwmd_strerror(rc));
2372 strv_free (cache_push);
2373 log_write (_ ("Failed to add a file to the cache. Use --force to force startup. Exiting."));
2374 cache_clear (NULL, NULL, 1, 0);
2375 estatus = EXIT_FAILURE;
2376 crypto_free (crypto);
2377 goto do_exit;
2379 else if (rc)
2380 log_write ("%s: %s", crypto->filename, pwmd_strerror(rc));
2381 else
2382 log_write (_("Successfully added '%s' to the cache."),
2383 crypto->filename);
2385 crypto_free (crypto);
2388 strv_free (cache_push);
2389 log_write (!nofork ? _("Done. Daemonizing...") :
2390 _("Done. Waiting for connections..."));
2393 backlog = config_get_integer ("global", "backlog");
2394 if (listen (sockfd, backlog) == -1)
2396 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2397 goto do_exit;
2400 if (!nofork)
2402 switch (fork ())
2404 case -1:
2405 log_write ("fork(): %s",
2406 pwmd_strerror (gpg_error_from_errno (errno)));
2407 goto do_exit;
2408 case 0:
2409 close (0);
2410 close (1);
2411 close (2);
2412 setsid ();
2413 break;
2414 default:
2415 _exit (EXIT_SUCCESS);
2419 (void)test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 1,
2420 mode, 0);
2421 xfree (socketname);
2422 cmdline = 0;
2423 pthread_key_create (&thread_name_key, free_key);
2424 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
2425 estatus = server_loop (sockfd, &socketpath);
2427 do_exit:
2428 if (socketpath && do_unlink)
2430 unlink (socketpath);
2431 xfree (socketpath);
2434 xfree (socketarg);
2435 #ifdef WITH_GNUTLS
2436 gnutls_global_deinit ();
2437 tls_deinit_params ();
2438 #endif
2439 pthread_cond_destroy (&rcfile_cond);
2440 pthread_mutex_destroy (&rcfile_mutex);
2441 pthread_key_delete (last_error_key);
2442 #ifndef HAVE_PTHREAD_CANCEL
2443 pthread_key_delete (signal_thread_key);
2444 #endif
2446 if (global_config)
2447 config_free (global_config);
2449 free_invoking_users (invoking_users);
2450 xfree (rcfile);
2451 xfree (home_directory);
2452 xfree (homedir);
2453 xmlCleanupParser ();
2454 xmlCleanupGlobals ();
2456 if (pidfile)
2457 unlink (pidfile);
2458 xfree (pidfile);
2460 if (estatus == EXIT_SUCCESS && !terminate)
2461 log_write (_("pwmd exiting normally"));
2463 pthread_key_delete (thread_name_key);
2464 closelog ();
2466 if (log_fd != -1)
2467 close (log_fd);
2469 exit (estatus);
2472 gpg_error_t lock_flock (assuan_context_t ctx, const char *filename,
2473 int type, int *fd)
2475 gpg_error_t rc = 0;
2477 #ifdef HAVE_FLOCK
2478 rc = open_check_file (filename, fd, NULL, 1);
2479 if (rc)
2480 return rc;
2482 TRY_FLOCK (ctx, *fd, type, rc);
2483 if (rc)
2485 close (*fd);
2486 *fd = -1;
2488 #endif
2490 return rc;
2493 void unlock_flock (int *fd)
2495 #ifdef HAVE_FLOCK
2496 if (*fd != -1)
2497 close (*fd);
2499 *fd = -1;
2500 #endif