Fix --debug.
[libpwmd.git] / src / pwmd.c
blob7b1eda473be74c5aec8d0e82b3f9aff5fd4b78f8
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 #endif
479 return read ((int) fd, data, len);
482 static ssize_t
483 hook_write (assuan_context_t ctx, assuan_fd_t fd,
484 const void *data, size_t len)
486 TEST_CANCEL ();
487 #ifdef WITH_GNUTLS
488 struct client_s *client = assuan_get_pointer (ctx);
490 if (client->thd->remote)
491 return tls_write_hook (ctx, (int) fd, data, len);
492 #endif
494 return write ((int) fd, data, len);
498 assuan_log_cb (assuan_context_t ctx, void *data, unsigned cat,
499 const char *msg)
501 struct client_s *client = data;
502 const char *str = NULL;
504 (void)client;
505 (void)ctx;
507 if (!(assuan_level & cat))
508 return 0;
510 if (!msg)
511 return 1;
513 switch (cat)
515 case ASSUAN_LOG_INIT:
516 str = "ASSUAN[INIT]";
517 break;
518 case ASSUAN_LOG_CTX:
519 str = "ASSUAN[CTX]";
520 break;
521 case ASSUAN_LOG_ENGINE:
522 str = "ASSUAN[ENGINE]";
523 break;
524 case ASSUAN_LOG_DATA:
525 str = "ASSUAN[DATA]";
526 break;
527 case ASSUAN_LOG_SYSIO:
528 str = "ASSUAN[SYSIO]";
529 break;
530 case ASSUAN_LOG_CONTROL:
531 str = "ASSUAN[CONTROL]";
532 break;
533 default:
534 str = "ASSUAN[UNKNOWN]";
535 break;
538 log_write ("%s: %s", str, msg);
539 return 1;
542 static int
543 new_connection (struct client_s *cl)
545 gpg_error_t rc;
546 static struct assuan_malloc_hooks mhooks = { xmalloc, xrealloc, xfree };
547 static struct assuan_system_hooks shooks = {
548 ASSUAN_SYSTEM_HOOKS_VERSION,
549 __assuan_usleep,
550 __assuan_pipe,
551 __assuan_close,
552 hook_read,
553 hook_write,
554 //FIXME
555 NULL, //recvmsg
556 NULL, //sendmsg both are used for FD passing
557 __assuan_spawn,
558 hook_waitpid,
559 __assuan_socketpair,
560 __assuan_socket,
561 __assuan_connect
564 #ifdef WITH_GNUTLS
565 if (cl->thd->remote)
567 char *prio = config_get_string ("global", "tls_cipher_suite");
569 cl->thd->timeout = config_get_integer ("global", "tls_timeout");
570 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
571 return 0;
573 cl->thd->tls = tls_init_client (cl->thd->fd, cl->thd->timeout, prio);
574 xfree (prio);
575 if (!cl->thd->tls)
576 return 0;
578 #endif
580 rc = assuan_new_ext (&cl->ctx, GPG_ERR_SOURCE_DEFAULT, &mhooks,
581 assuan_log_cb, cl);
582 if (rc)
583 goto fail;
585 assuan_ctx_set_system_hooks (cl->ctx, &shooks);
586 rc = assuan_init_socket_server (cl->ctx, cl->thd->fd, 2);
587 if (rc)
588 goto fail;
590 assuan_set_pointer (cl->ctx, cl);
591 assuan_set_hello_line (cl->ctx, PACKAGE_STRING);
592 rc = register_commands (cl->ctx);
593 if (rc)
594 goto fail;
596 rc = assuan_accept (cl->ctx);
597 if (rc)
598 goto fail;
600 rc = validate_peer (cl);
601 /* May not be implemented on all platforms. */
602 if (rc && gpg_err_code (rc) != GPG_ERR_ASS_GENERAL)
603 goto fail;
605 MUTEX_LOCK (&cn_mutex);
606 cl->thd->state = CLIENT_STATE_INIT;
607 MUTEX_UNLOCK (&cn_mutex);
608 cl->lock_timeout = config_get_integer ("global", "lock_timeout");
609 xmlSetStructuredErrorFunc (cl, xml_error_cb);
610 return 1;
612 fail:
613 log_write ("%s", pwmd_strerror (rc));
614 return 0;
618 * This is called after a client is cancelled or disconnects. Set with
619 * pthread_cleanup_push().
621 static void
622 free_client_cb (void *arg)
624 struct client_thread_s *cn = arg;
625 struct client_s *cl = cn->cl;
626 #ifndef HAVE_PTHREAD_CANCEL
627 char *tmp = pthread_getspecific (signal_thread_key);
629 xfree (tmp);
630 pthread_setspecific (signal_thread_key, NULL);
631 #endif
632 MUTEX_LOCK (&cn_mutex);
633 cn_thread_list = slist_remove (cn_thread_list, cn);
634 MUTEX_UNLOCK (&cn_mutex);
636 if (cl)
638 unlock_flock (&cl->flock_fd);
639 reset_client (cl);
640 if (cl->xml_error)
641 xmlResetError (cl->xml_error);
643 xfree (cl->xml_error);
645 #ifdef WITH_GNUTLS
646 if (cn->tls)
648 gnutls_deinit (cn->tls->ses);
649 xfree (cn->tls->fp);
650 xfree (cn->tls);
652 #endif
654 if (cl->ctx)
655 assuan_release (cl->ctx);
656 else if (cl->thd && cl->thd->fd != -1)
657 close (cl->thd->fd);
659 if (cl->crypto)
660 crypto_free (cl->crypto);
662 cl->crypto = NULL;
663 xfree (cl);
665 else
667 if (cn->fd != -1)
668 close (cn->fd);
671 while (cn->msg_queue)
673 struct status_msg_s *msg = cn->msg_queue;
675 cn->msg_queue = msg->next;
676 xfree (msg->line);
677 xfree (msg);
680 if (cn->status_msg_pipe[0] != -1)
681 close (cn->status_msg_pipe[0]);
683 if (cn->status_msg_pipe[1] != -1)
684 close (cn->status_msg_pipe[1]);
686 pthread_mutex_destroy (&cn->status_mutex);
687 log_write (_("exiting, fd=%i"), cn->fd);
688 send_status_all (STATUS_CLIENTS, NULL);
690 #ifdef WITH_GNUTLS
691 xfree (cn->peeraddr);
692 #endif
693 xfree (cn);
696 static void
697 free_all_clients ()
699 MUTEX_LOCK (&cn_mutex);
700 pthread_cleanup_push (release_mutex_cb, &cn_mutex);
702 while (slist_length (cn_thread_list))
704 struct client_thread_s *thd = slist_nth_data (cn_thread_list, 0);
706 free_client_cb (thd);
709 pthread_cleanup_pop (1);
712 static gpg_error_t
713 send_msg_queue (struct client_thread_s *thd)
715 MUTEX_LOCK (&thd->status_mutex);
716 gpg_error_t rc = 0;
717 char c;
718 ssize_t ret;
720 ret = read (thd->status_msg_pipe[0], &c, 1);
721 rc = gpg_error_from_syserror ();
722 if (ret == -1 && gpg_err_code (rc) != GPG_ERR_EAGAIN)
723 log_write ("%s (%i): %s", __FUNCTION__, __LINE__, pwmd_strerror (rc));
724 else
725 rc = 0;
727 thd->wrote_status = 0;
729 while (thd->msg_queue)
731 struct status_msg_s *msg = thd->msg_queue;
733 thd->msg_queue = thd->msg_queue->next;
734 MUTEX_UNLOCK (&thd->status_mutex);
735 pthread_cleanup_push (xfree, msg);
736 pthread_cleanup_push (xfree, msg->line);
737 rc = send_status (thd->cl->ctx, msg->s, msg->line);
738 pthread_cleanup_pop (1);
739 pthread_cleanup_pop (1);
740 MUTEX_LOCK (&thd->status_mutex);
741 if (rc)
742 break;
745 MUTEX_UNLOCK (&thd->status_mutex);
746 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
747 log_write ("%s (%i): %s", __FUNCTION__, __LINE__, pwmd_strerror (rc));
749 return rc;
752 static void *
753 client_thread (void *data)
755 struct client_thread_s *thd = data;
756 struct client_s *cl = xcalloc (1, sizeof (struct client_s));
757 struct slist_s *list;
758 gpg_error_t rc = 0;
759 #ifndef HAVE_PTHREAD_CANCEL
760 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
761 #endif
763 #ifdef HAVE_PR_SET_NAME
764 prctl (PR_SET_NAME, "client");
765 #endif
766 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
768 if (!cl)
770 log_write ("%s(%i): %s", __FILE__, __LINE__,
771 pwmd_strerror (GPG_ERR_ENOMEM));
772 return NULL;
775 MUTEX_LOCK (&cn_mutex);
776 pthread_cleanup_push (free_client_cb, thd);
777 thd->cl = cl;
778 cl->thd = thd;
779 cl->flock_fd = -1;
781 list = slist_append (cn_thread_list, thd);
782 if (list)
783 cn_thread_list = list;
784 else
786 log_write ("%s(%i): %s", __FILE__, __LINE__,
787 pwmd_strerror (GPG_ERR_ENOMEM));
788 MUTEX_UNLOCK (&cn_mutex);
789 return NULL;
792 if (fcntl (thd->status_msg_pipe[0], F_SETFL, O_NONBLOCK) == -1)
793 rc = gpg_error_from_errno (errno);
795 if (!rc)
796 if (fcntl (thd->status_msg_pipe[1], F_SETFL, O_NONBLOCK) == -1)
797 rc = gpg_error_from_errno (errno);
799 MUTEX_UNLOCK (&cn_mutex);
801 if (rc)
803 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
804 return NULL;
807 if (new_connection (cl))
809 int finished = 0;
810 struct pollfd fds[2];
812 fds[0].fd = thd->fd;
813 fds[0].events = POLLIN;
814 fds[1].fd = thd->status_msg_pipe[0];
815 fds[1].events = POLLIN;
817 send_status_all (STATUS_CLIENTS, NULL);
818 rc = send_status (cl->ctx, STATUS_CACHE, NULL);
819 if (rc)
821 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
822 finished = 1;
825 while (!finished)
827 int n;
828 int eof;
830 n = poll (fds, 2, 100);
831 if (n == -1)
833 log_write ("%s", strerror (errno));
834 break;
837 #ifdef WITH_GNUTLS
838 if (thd->remote && thd->tls && thd->tls->rehandshake)
840 char *prio;
841 int ret;
842 const char *e;
844 if (thd->tls->rehandshake == 1)
846 prio = config_get_string ("global", "tls_cipher_suite");
847 if (!prio)
849 thd->tls->rehandshake = 0;
850 continue;
853 ret = gnutls_priority_set_direct (thd->tls->ses, prio, &e);
854 if (ret == GNUTLS_E_SUCCESS)
856 rc = send_status (cl->ctx, STATUS_REHANDSHAKE, NULL);
857 if (!rc)
859 rc = assuan_send_data (cl->ctx, NULL, 0);
860 if (!rc)
862 ret = gnutls_rehandshake (thd->tls->ses);
863 if (ret)
865 log_write ("%s", gnutls_strerror (ret));
866 thd->tls->rehandshake = 0;
868 else
869 thd->tls->rehandshake = 2;
873 if (rc)
874 log_write ("%s", pwmd_strerror (rc));
876 else
877 log_write ("%s: %s", gnutls_strerror (ret), e);
879 xfree (prio);
880 continue;
883 #endif
885 if (!n)
886 continue;
888 if (fds[1].revents & POLLIN)
890 #ifdef WITH_GNUTLS
891 if (!thd->remote || (thd->tls && !thd->tls->rehandshake))
892 #endif
894 rc = send_msg_queue (thd);
895 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
896 break;
900 #ifdef HAVE_PTHREAD_CANCEL
901 if (!(fds[0].revents & POLLIN))
902 #else
903 if (thd->fd != -1 && !(fds[0].revents & POLLIN))
904 #endif
905 continue;
907 rc = assuan_process_next (cl->ctx, &eof);
908 if (rc || eof)
910 if (gpg_err_code (rc) == GPG_ERR_EOF || eof)
911 break;
913 log_write ("assuan_process_next(): rc=%u %s", rc,
914 pwmd_strerror (rc));
915 if (rc == gpg_error (GPG_ERR_ETIMEDOUT))
916 break;
918 rc = send_error (cl->ctx, rc);
919 if (rc)
921 log_write ("assuan_process_done(): rc=%u %s", rc,
922 pwmd_strerror (rc));
923 break;
927 /* Since the msg queue pipe fd's are non-blocking, check for
928 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
929 * client has already disconnected and will be converted to
930 * GPG_ERR_EOF during assuan_process_next().
932 #ifdef WITH_GNUTLS
933 if (!thd->remote || (thd->tls && !thd->tls->rehandshake))
934 #endif
936 rc = send_msg_queue (thd);
937 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
938 break;
943 /* Don't do pthread_exit() here because any set pthread_cleanup_push
944 * functions would be called after a command failed but then the client
945 * exited normally which may lead to a double free. */
946 pthread_cleanup_pop (1);
947 return NULL;
950 static gpg_error_t
951 xml_import (const char *filename, const char *outfile, char **keyid,
952 char **sign_keyid, char *keyfile, const char *keyparam,
953 int symmetric)
955 xmlDocPtr doc;
956 int fd;
957 struct stat st;
958 int len;
959 xmlChar *xmlbuf;
960 gpg_error_t rc = 0;
961 struct crypto_s *crypto = NULL;
963 if (stat (filename, &st) == -1)
965 rc = gpg_error_from_errno (errno);
966 return rc;
969 fd = open (filename, O_RDONLY);
970 if (fd == -1)
971 return gpg_error_from_errno (errno);
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 close (fd);
989 xmlbuf[st.st_size] = 0;
990 // Be sure the document validates.
991 doc = xmlReadDoc (xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS);
992 xfree (xmlbuf);
993 if (!doc)
994 return GPG_ERR_BAD_DATA;
996 xmlNodePtr n = xmlDocGetRootElement (doc);
997 if (n && !xmlStrEqual (n->name, (xmlChar *) "pwmd"))
998 rc = GPG_ERR_BAD_DATA;
1000 if (!rc)
1002 rc = xml_validate_import (NULL, n ? n->children : n);
1003 if (!rc)
1005 rc = crypto_init (&crypto, NULL, filename, keyfile != NULL, keyfile);
1006 if (!rc)
1008 if (keyfile)
1010 crypto->flags |= CRYPTO_FLAG_KEYFILE;
1011 crypto->keyfile = str_dup (keyfile);
1014 xmlDocDumpMemory (doc, &crypto->plaintext, &len);
1015 if (len > 0)
1016 crypto->plaintext_size = len;
1017 else
1018 rc = GPG_ERR_ENOMEM;
1023 if (!rc)
1025 if (!symmetric && (keyparam || !keyid))
1027 char *buf = NULL;
1029 if (keyparam)
1031 fd = open (keyparam, O_RDONLY);
1032 if (fd == -1)
1033 rc = gpg_error_from_errno (errno);
1035 if (!rc)
1037 if (stat (keyparam, &st) == -1)
1038 rc = gpg_error_from_errno (errno);
1040 if (!rc)
1042 buf = xmalloc (st.st_size+1);
1043 if (!buf)
1044 rc = GPG_ERR_ENOMEM;
1046 if (!rc)
1048 len = read (fd, buf, st.st_size);
1049 if (len != st.st_size)
1050 rc = gpg_error_from_errno (errno);
1052 if (!rc)
1053 buf[len] = 0;
1058 if (fd != -1)
1059 close (fd);
1061 else
1063 buf = crypto_default_key_params ();
1064 if (!buf)
1065 rc = GPG_ERR_ENOMEM;
1068 if (!rc)
1069 rc = crypto_genkey (NULL, crypto, (unsigned char *)buf);
1071 xfree (buf);
1073 else
1075 crypto->save.pubkey = strv_dup (keyid);
1076 crypto->save.sigkey = strv_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);
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 int timeout = config_get_integer (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 fd = accept (fds->fd, (struct sockaddr *) &raddr, &slen);
1253 if (fd == -1)
1255 int e = errno;
1257 if (errno != EAGAIN && !quit)
1258 log_write ("%s: %s", __FUNCTION__,
1259 pwmd_strerror (gpg_error_from_syserror()));
1261 return gpg_error_from_errno (e);
1264 inet_ntop (raddr.ss_family, get_in_addr ((struct sockaddr *) &raddr), s,
1265 sizeof s);
1266 (void) init_client (fd, s);
1267 return 0;
1269 #endif
1271 static void *
1272 accept_thread (void *arg)
1274 int sockfd = *(int *) arg;
1275 #ifndef HAVE_PTHREAD_CANCEL
1276 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
1277 #endif
1279 #ifdef HAVE_PR_SET_NAME
1280 prctl (PR_SET_NAME, "accept");
1281 #endif
1282 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
1284 for (;;)
1286 socklen_t slen = sizeof (struct sockaddr_un);
1287 struct sockaddr_un raddr;
1288 int fd, s = 0;
1289 struct pollfd fds[3];
1291 TEST_CANCEL ();
1292 memset (fds, 0, sizeof (fds));
1293 fds[s].fd = sockfd;
1294 fds[s++].events = POLLIN;
1296 #ifdef WITH_GNUTLS
1297 if (tls_fd != -1)
1299 fds[s].fd = tls_fd;
1300 fds[s++].events = POLLIN;
1302 else
1303 fds[s].fd = tls_fd;
1305 if (tls6_fd != -1)
1307 fds[s].fd = tls6_fd;
1308 fds[s++].events = POLLIN;
1310 else
1311 fds[s].fd = tls6_fd;
1312 #endif
1314 s = poll (fds, s, 500);
1315 if (s == -1)
1317 if (errno != EINTR)
1318 log_write ("%s", strerror (errno));
1319 break;
1321 else if (s == 0)
1322 continue;
1324 if (fds[0].revents & POLLIN)
1326 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1327 if (fd == -1)
1329 if (errno == EMFILE || errno == ENFILE)
1330 log_write ("%s: %s", __FUNCTION__,
1331 pwmd_strerror (gpg_error_from_errno (errno)));
1332 else if (errno != EAGAIN && errno != EINTR)
1334 if (!quit) // probably EBADF
1335 log_write ("%s: %s", __FUNCTION__,
1336 pwmd_strerror (gpg_error_from_errno (errno)));
1338 break;
1341 continue;
1344 (void) init_client (fd, NULL);
1347 #ifdef WITH_GNUTLS
1348 if (tls_fd != -1 && fds[1].fd == tls_fd)
1349 (void)do_tls_accept (&fds[1]);
1351 if (tls6_fd != -1 && fds[1].fd == tls6_fd)
1352 (void)do_tls_accept (&fds[1]);
1354 if (tls6_fd != -1 && fds[2].fd == tls6_fd)
1355 (void)do_tls_accept (&fds[2]);
1356 #endif
1359 /* Just in case accept() failed for some reason other than EBADF */
1360 quit = 1;
1361 return NULL;
1364 static void *
1365 cache_timer_thread (void *arg)
1367 unsigned k = 0;
1368 #ifndef HAVE_PTHREAD_CANCEL
1369 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
1370 #endif
1372 (void)arg;
1374 #ifdef HAVE_PR_SET_NAME
1375 prctl (PR_SET_NAME, "timer");
1376 #endif
1377 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
1379 for (;;)
1381 struct timeval tv = { 1, 0 };
1382 unsigned keepalive = config_get_integer ("global", "keepalive_interval");
1384 TEST_CANCEL ();
1385 select (0, NULL, NULL, NULL, &tv);
1386 cache_adjust_timeout ();
1388 if (keepalive && ++k >= keepalive)
1390 send_status_all (STATUS_KEEPALIVE, NULL);
1391 k = 0;
1395 return NULL;
1398 static int
1399 signal_loop (sigset_t sigset)
1401 int done = 0;
1405 int sig;
1407 sigwait (&sigset, &sig);
1408 log_write (_("caught signal %i (%s)"), sig, strsignal (sig));
1410 switch (sig)
1412 case SIGHUP:
1413 pthread_cond_signal (&rcfile_cond);
1414 break;
1415 case SIGUSR1:
1416 log_write (_("clearing file cache"));
1417 cache_clear (NULL, NULL, 1);
1418 send_status_all (STATUS_CACHE, NULL);
1419 break;
1420 default:
1421 done = 1;
1422 break;
1425 while (!done);
1427 return done;
1430 static void
1431 catchsig (int sig)
1433 log_write (_ ("Caught signal %i (%s). Exiting."), sig, strsignal (sig));
1434 #ifdef HAVE_BACKTRACE
1435 BACKTRACE (__FUNCTION__);
1436 #endif
1437 longjmp (jmp, 1);
1440 static void
1441 cancel_all_clients ()
1443 unsigned i, t;
1445 MUTEX_LOCK (&cn_mutex);
1446 t = slist_length (cn_thread_list);
1447 for (i = 0; i < t; i++)
1449 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
1451 #ifdef HAVE_PTHREAD_CANCEL
1452 pthread_cancel (thd->tid);
1453 #else
1454 pthread_kill (thd->tid, SIGUSR2);
1455 #endif
1458 while (slist_length (cn_thread_list))
1460 MUTEX_UNLOCK (&cn_mutex);
1461 usleep (50000);
1462 MUTEX_LOCK (&cn_mutex);
1465 MUTEX_UNLOCK (&cn_mutex);
1468 static int
1469 server_loop (int sockfd, char **socketpath)
1471 pthread_t cache_timeout_tid;
1472 pthread_t accept_tid;
1473 int cancel_timeout_thread = 0;
1474 int cancel_accept_thread = 0;
1475 int cancel_rcfile_thread = 0;
1476 sigset_t sigset;
1477 int n;
1478 int segv = 0;
1479 gpg_error_t rc;
1481 init_commands ();
1482 sigemptyset (&sigset);
1484 /* Termination */
1485 sigaddset (&sigset, SIGTERM);
1486 sigaddset (&sigset, SIGINT);
1488 /* Clears the file cache. */
1489 sigaddset (&sigset, SIGUSR1);
1491 /* Configuration file reloading. */
1492 sigaddset (&sigset, SIGHUP);
1494 #ifndef HAVE_PTHREAD_CANCEL
1496 The socket, cache and rcfile threads use this signal when
1497 pthread_cancel() is unavailable. Prevent the main thread from
1498 catching this signal from another process.
1500 sigaddset (&sigset, SIGUSR2);
1501 #endif
1503 /* An assertion failure. */
1504 signal (SIGABRT, catchsig);
1505 sigaddset (&sigset, SIGABRT);
1506 sigprocmask (SIG_BLOCK, &sigset, NULL);
1508 #ifndef HAVE_PTHREAD_CANCEL
1509 /* Remove this signal from the watched signals in signal_loop(). */
1510 sigdelset (&sigset, SIGUSR2);
1511 #endif
1513 /* Can show a backtrace of the stack in the log. */
1514 signal (SIGSEGV, catchsig);
1516 char *p = get_username (getuid());
1517 log_write (_("%s started for user %s"), PACKAGE_STRING, p);
1518 xfree (p);
1520 #ifdef WITH_GNUTLS
1521 if (config_get_boolean ("global", "enable_tcp"))
1522 log_write (_("Listening on %s and TCP port %i"), *socketpath,
1523 config_get_integer ("global", "tcp_port"));
1524 else
1525 log_write (_("Listening on %s"), *socketpath);
1526 #else
1527 log_write (_("Listening on %s"), *socketpath);
1528 #endif
1530 rc = create_thread (reload_rcfile_thread, NULL, &rcfile_tid, 0);
1531 if (rc)
1533 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1534 pwmd_strerror (rc));
1535 goto done;
1538 cancel_rcfile_thread = 1;
1539 rc = create_thread (cache_timer_thread, NULL, &cache_timeout_tid, 0);
1540 if (rc)
1542 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1543 pwmd_strerror (rc));
1544 goto done;
1547 cancel_timeout_thread = 1;
1548 rc = create_thread (accept_thread, &sockfd, &accept_tid, 0);
1549 if (rc)
1551 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1552 pwmd_strerror (rc));
1553 goto done;
1556 cancel_accept_thread = 1;
1557 if (!setjmp (jmp))
1558 signal_loop (sigset);
1559 else
1560 segv = 1;
1562 done:
1564 * We're out of the main server loop. This happens when a signal was sent
1565 * to terminate the daemon. Cancel all clients and exit.
1567 if (cancel_accept_thread)
1569 #ifdef HAVE_PTHREAD_CANCEL
1570 n = pthread_cancel (accept_tid);
1571 #else
1572 n = pthread_kill (accept_tid, SIGUSR2);
1573 #endif
1574 if (!n)
1575 pthread_join (accept_tid, NULL);
1578 if (cancel_timeout_thread)
1580 #ifdef HAVE_PTHREAD_CANCEL
1581 n = pthread_cancel (cache_timeout_tid);
1582 #else
1583 n = pthread_kill (cache_timeout_tid, SIGUSR2);
1584 #endif
1585 if (!n)
1586 pthread_join (cache_timeout_tid, NULL);
1589 #ifdef WITH_GNUTLS
1590 tls_start_stop (1);
1591 #endif
1592 shutdown (sockfd, SHUT_RDWR);
1593 close (sockfd);
1594 unlink (*socketpath);
1595 xfree (*socketpath);
1596 *socketpath = NULL;
1597 MUTEX_LOCK (&cn_mutex);
1598 n = slist_length (cn_thread_list);
1599 MUTEX_UNLOCK (&cn_mutex);
1601 if (n && !segv)
1602 cancel_all_clients ();
1603 else
1604 free_all_clients ();
1606 if (cancel_rcfile_thread)
1608 #ifdef HAVE_PTHREAD_CANCEL
1609 pthread_cancel (rcfile_tid);
1610 #else
1611 pthread_kill (rcfile_tid, SIGUSR2);
1612 pthread_cond_signal (&rcfile_cond);
1613 #endif
1614 pthread_join (rcfile_tid, NULL);
1617 cache_deinit ();
1618 deinit_commands ();
1619 return segv ? EXIT_FAILURE : EXIT_SUCCESS;
1622 static void
1623 usage (const char *pn, int status)
1625 FILE *fp = status == EXIT_FAILURE ? stderr : stdout;
1627 fprintf (fp, _("Usage: %s [OPTIONS] [file1] [...]\n"
1628 " --homedir alternate pwmd home directory (~/.pwmd)\n"
1629 " -f, --rcfile=filename load the specfied configuration file\n"
1630 " (~/.pwmd/config)\n"
1631 " --kill terminate an existing instance of pwmd\n"
1632 " -n, --no-fork run as a foreground process\n"
1633 " --disable-dump disable the LIST, XPATH and DUMP commands\n"
1634 " --ignore, --force ignore cache pushing errors during startup\n"
1635 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
1636 " -k, --passphrase-file=file for use when importing\n"
1637 " -o, --outfile=filename output file when importing\n"
1638 " --keyid=fpr[,..] public key to use when encrypting\n"
1639 " --sign-keyid=fpr[,..] fingerprint of the signing key to use\n"
1640 " -s, --symmetric use conventional encryption with optional signer\n"
1641 " --keyparam=filename custom key parameters to use (gpg default)\n"
1642 " --debug=[a:..][,g:N][,t:N] enable debugging (a:[ixedsc],g:[1-9],t:[0-N])\n"
1643 " --help this help text\n"
1644 " --version show version and compile time features\n"),
1645 pn);
1646 exit (status);
1649 static void
1650 unlink_stale_socket (const char *sock, const char *pidfile)
1652 log_write (_ ("removing stale socket %s"), sock);
1653 unlink (sock);
1654 unlink (pidfile);
1657 static int
1658 test_pidfile (const char *path, const char *sock, char *buf, size_t buflen,
1659 char **pidfile, int create, mode_t mode, int terminate)
1661 pid_t pid;
1662 int fd;
1663 size_t len;
1665 if (!create)
1667 snprintf (buf, buflen, "%s/%s.pid", homedir, sock);
1668 *pidfile = str_dup (buf);
1669 fd = open (buf, O_RDONLY);
1671 else
1672 fd = open (*pidfile, O_CREAT|O_WRONLY|O_TRUNC, mode);
1674 if (fd == -1)
1676 if (!create && errno != ENOENT)
1678 log_write ("%s: %s", buf, pwmd_strerror (errno));
1679 free (*pidfile);
1680 *pidfile = NULL;
1681 return -1;
1683 else if (!create && !terminate)
1684 return 0;
1686 log_write ("%s: %s", *pidfile, strerror (errno));
1687 return -1;
1690 if (create)
1692 snprintf (buf, buflen, "%i", getpid ());
1693 ssize_t ret = write (fd, buf, strlen (buf));
1694 if (ret == -1)
1695 log_write ("%s (%i): %s", __FUNCTION__, __LINE__,
1696 pwmd_strerror (gpg_error_from_syserror ()));
1697 close (fd);
1698 return 0;
1701 len = read (fd, buf, buflen);
1702 close (fd);
1703 if (len == 0)
1705 unlink_stale_socket (path, *pidfile);
1706 return 0;
1709 if (sscanf (buf, "%5i", &pid) != 1 || pid == 0)
1711 if (!terminate)
1713 unlink_stale_socket (path, *pidfile);
1714 return 0;
1718 if (kill (pid, 0) == -1)
1720 unlink_stale_socket (path, *pidfile);
1721 return 0;
1724 if (terminate)
1726 if (kill (pid, SIGTERM) == -1)
1727 log_write ("%s: %s", path, pwmd_strerror (errno));
1729 else
1730 log_write (_ ("an instance for socket %s is already running"), path);
1732 xfree (*pidfile);
1733 *pidfile = NULL;
1734 return 1;
1737 static unsigned
1738 parse_debug_level (const char *str, unsigned *debug, int *gpgme, int *tls)
1740 const char *p;
1741 unsigned level = 0;
1742 int gl = 0, tl = 0;
1744 for (p = str; p && *p; p++)
1746 if (*p == 'a') // assuan debug flags
1748 if (*++p != ':')
1749 return 1;
1751 while (*++p)
1753 switch (*p)
1755 case 'i':
1756 level |= ASSUAN_LOG_INIT;
1757 break;
1758 case 'x':
1759 level |= ASSUAN_LOG_CTX;
1760 break;
1761 case 'e':
1762 level |= ASSUAN_LOG_ENGINE;
1763 break;
1764 case 'd':
1765 level |= ASSUAN_LOG_DATA;
1766 break;
1767 case 's':
1768 level |= ASSUAN_LOG_SYSIO;
1769 break;
1770 case 'c':
1771 level |= ASSUAN_LOG_CONTROL;
1772 break;
1773 case ',':
1774 break;
1775 default:
1776 return 1;
1779 if (*p == ',')
1780 break;
1783 if (!*p)
1784 break;
1786 else if (*p == 'g' || *p == 't') // gpgme and TLS debug level
1788 int t = *p == 't';
1789 int n;
1791 if (*++p != ':')
1792 return 1;
1794 if (!isdigit (*++p))
1795 return 1;
1797 n = atoi (p);
1798 if (t)
1799 tl = n;
1800 else
1801 gl = n;
1803 if (tl < 0 || gl < 0 || gl > 9)
1804 return 1;
1806 while (isdigit (*p))
1807 p++;
1809 p--;
1810 if (*(p+1) && *(p+1) != ',')
1811 return 1;
1812 else if (*(p+1))
1813 p++;
1815 else
1816 return 1;
1819 if (tl)
1820 *tls = tl;
1822 if (gl)
1823 *gpgme = gl;
1825 *debug = level;
1826 return 0;
1830 main (int argc, char *argv[])
1832 int opt;
1833 struct sockaddr_un addr;
1834 char buf[PATH_MAX];
1835 char *socketpath = NULL, *socketdir, *socketname = NULL;
1836 char *socketarg = NULL;
1837 char *datadir = NULL;
1838 char *pidfile = NULL;
1839 mode_t mode = 0600;
1840 int x;
1841 char *p;
1842 char **cache_push = NULL;
1843 char *import = NULL, *keyid = NULL, *sign_keyid = NULL;
1844 char *keyparam = NULL;
1845 int estatus = EXIT_FAILURE;
1846 int sockfd;
1847 char *outfile = NULL;
1848 int do_unlink = 0;
1849 int secure = 0;
1850 int show_version = 0;
1851 int force = 0;
1852 gpg_error_t rc;
1853 char *keyfile = NULL;
1854 int exists;
1855 int optindex;
1856 int terminate = 0;
1857 int sym = 0;
1858 int gpgme_level = -1;
1859 int tls_level = -1;
1860 int backlog = 0;
1861 /* Must maintain the same order as longopts[] */
1862 enum
1864 OPT_VERSION, OPT_HELP, OPT_HOMEDIR, OPT_NO_FORK, OPT_DISABLE_DUMP,
1865 OPT_FORCE, OPT_RCFILE, OPT_PASSPHRASE_FILE, OPT_IMPORT, OPT_OUTFILE,
1866 OPT_KEYID, OPT_SIGN_KEYID, OPT_SYMMETRIC, OPT_KEYPARAM, OPT_KILL,
1867 OPT_DEBUG
1869 const char *optstring = "nf:C:k:I:o:s";
1870 const struct option longopts[] = {
1871 {"version", no_argument, 0, 0},
1872 {"help", no_argument, 0, 0},
1873 {"homedir", required_argument, 0, 0},
1874 {"no-fork", no_argument, 0, 'n'},
1875 {"disable_dump", no_argument, 0, 0},
1876 {"force", no_argument, 0, 0},
1877 {"rcfile", required_argument, 0, 'f'},
1878 {"passphrase-file", required_argument, 0, 'k'},
1879 {"import", required_argument, 0, 'I'},
1880 {"outfile", required_argument, 0, 'o'},
1881 {"keyid", required_argument, 0, 0},
1882 {"sign-keyid", required_argument, 0, 0},
1883 {"symmetric", no_argument, 0, 's'},
1884 {"keyparam", required_argument, 0, 0},
1885 {"kill", no_argument, 0, 0},
1886 {"debug", required_argument, 0, 0},
1887 {0, 0, 0, 0}
1890 log_fd = -1;
1891 cmdline = 1;
1893 #ifndef DEBUG
1894 #ifdef HAVE_SETRLIMIT
1895 struct rlimit rl;
1897 rl.rlim_cur = rl.rlim_max = 0;
1899 if (setrlimit (RLIMIT_CORE, &rl) != 0)
1900 err (EXIT_FAILURE, "setrlimit()");
1901 #endif
1903 #ifdef HAVE_PR_SET_DUMPABLE
1904 prctl (PR_SET_DUMPABLE, 0);
1905 #endif
1906 #endif
1908 #ifdef ENABLE_NLS
1909 setlocale (LC_ALL, "");
1910 bindtextdomain ("pwmd", LOCALEDIR);
1911 textdomain ("pwmd");
1912 #endif
1914 while ((opt = getopt_long (argc, argv, optstring, longopts, &optindex))
1915 != -1)
1917 switch (opt)
1919 case 'I':
1920 import = optarg;
1921 break;
1922 case 'k':
1923 keyfile = optarg;
1924 break;
1925 case 'o':
1926 outfile = optarg;
1927 break;
1928 case 'n':
1929 nofork = 1;
1930 break;
1931 case 'f':
1932 rcfile = str_dup (optarg);
1933 break;
1934 case 's':
1935 sym = 1;
1936 break;
1937 default:
1938 usage (argv[0], EXIT_FAILURE);
1939 break;
1940 case 0:
1941 switch (optindex)
1943 case OPT_DEBUG:
1944 if (parse_debug_level (optarg, &assuan_level, &gpgme_level,
1945 &tls_level))
1946 usage (argv[0], EXIT_FAILURE);
1947 break;
1948 case OPT_SYMMETRIC:
1949 sym = 1;
1950 break;
1951 case OPT_VERSION:
1952 show_version = 1;
1953 break;
1954 case OPT_HELP:
1955 usage (argv[0], EXIT_SUCCESS);
1956 break;
1957 case OPT_HOMEDIR:
1958 homedir = str_dup (optarg);
1959 break;
1960 case OPT_NO_FORK:
1961 nofork = 1;
1962 break;
1963 case OPT_DISABLE_DUMP:
1964 secure = 1;
1965 break;
1966 case OPT_FORCE:
1967 force = 1;
1968 break;
1969 case OPT_RCFILE:
1970 rcfile = str_dup (optarg);
1971 break;
1972 case OPT_PASSPHRASE_FILE:
1973 keyfile = optarg;
1974 break;
1975 case OPT_IMPORT:
1976 import = optarg;
1977 break;
1978 case OPT_OUTFILE:
1979 outfile = optarg;
1980 break;
1981 case OPT_KEYID:
1982 keyid = optarg;
1983 break;
1984 case OPT_SIGN_KEYID:
1985 sign_keyid = optarg;
1986 break;
1987 case OPT_KEYPARAM:
1988 keyparam = optarg;
1989 break;
1990 case OPT_KILL:
1991 terminate = 1;
1992 break;
1993 default:
1994 usage (argv[0], EXIT_FAILURE);
1999 if (show_version)
2001 printf (_("%s\n\n"
2002 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016\n"
2003 "%s\n"
2004 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2005 "Compile time features:\n%s"), PACKAGE_STRING,
2006 PACKAGE_BUGREPORT,
2007 #ifdef PWMD_HOMEDIR
2008 "+PWMD_HOMEDIR=" PWMD_HOMEDIR "\n"
2009 #endif
2010 #ifdef WITH_GNUTLS
2011 "+WITH_GNUTLS\n"
2012 #else
2013 "-WITH_GNUTLS\n"
2014 #endif
2015 #ifdef WITH_LIBACL
2016 "+WITH_LIBACL\n"
2017 #else
2018 "-WITH_LIBACL\n"
2019 #endif
2020 #ifdef DEBUG
2021 "+DEBUG\n"
2022 #else
2023 "-DEBUG\n"
2024 #endif
2025 #ifdef MEM_DEBUG
2026 "+MEM_DEBUG\n"
2027 #else
2028 "-MEM_DEBUG\n"
2029 #endif
2030 #ifdef MUTEX_DEBUG
2031 "+MUTEX_DEBUG\n"
2032 #else
2033 "-MUTEX_DEBUG\n"
2034 #endif
2036 exit (EXIT_SUCCESS);
2039 if (gpgme_level != -1)
2041 char s[2] = { gpgme_level + '0', 0 };
2043 if (getenv ("GPGME_DEBUG"))
2044 log_write (_ ("Overriding GPGME_DEBUG environment with level %u!"),
2045 gpgme_level);
2047 gpgme_set_global_flag ("debug", s);
2050 if (setup_crypto ())
2051 exit (EXIT_FAILURE);
2053 #ifdef WITH_GNUTLS
2054 tls_level = tls_level == -1 ? 1 : tls_level;
2055 gnutls_global_set_log_level (tls_level);
2056 tls_fd = -1;
2057 tls6_fd = -1;
2058 #endif
2059 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
2060 xmlInitMemory ();
2061 xmlInitGlobals ();
2062 xmlInitParser ();
2063 xmlXPathInit ();
2065 if (!homedir)
2066 #ifdef PWMD_HOMEDIR
2067 homedir = str_dup(PWMD_HOMEDIR);
2068 #else
2069 homedir = str_asprintf ("%s/.pwmd", get_home_dir());
2070 #endif
2072 if (mkdir (homedir, 0700) == -1 && errno != EEXIST)
2073 err (EXIT_FAILURE, "%s", homedir);
2075 if (!rcfile)
2076 rcfile = str_asprintf ("%s/config", homedir);
2078 pthread_key_create (&last_error_key, free_key);
2079 #ifndef HAVE_PTHREAD_CANCEL
2080 pthread_key_create (&signal_thread_key, free_key);
2081 #endif
2083 pthread_mutexattr_t attr;
2084 pthread_mutexattr_init (&attr);
2085 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
2086 pthread_mutex_init (&rcfile_mutex, &attr);
2087 global_config = config_parse (rcfile, 0);
2088 if (!global_config)
2090 pthread_mutexattr_destroy (&attr);
2091 pthread_mutex_destroy (&rcfile_mutex);
2092 exit (EXIT_FAILURE);
2095 p = config_get_string ("global", "gpg_homedir");
2096 if (!p)
2097 datadir = str_asprintf ("%s/.gnupg", homedir);
2098 else
2099 datadir = expand_homedir (p);
2101 xfree (p);
2102 if (mkdir (datadir, 0700) == -1 && errno != EEXIST)
2103 err (EXIT_FAILURE, "%s", datadir);
2105 rc = gpgme_set_engine_info (GPGME_PROTOCOL_OpenPGP, NULL, datadir);
2106 xfree (datadir);
2108 snprintf (buf, sizeof (buf), "%s/data", homedir);
2109 if (mkdir (buf, 0700) == -1 && errno != EEXIST)
2110 err (EXIT_FAILURE, "%s", buf);
2112 datadir = str_dup (buf);
2113 pthread_cond_init (&rcfile_cond, NULL);
2114 pthread_mutex_init (&cn_mutex, &attr);
2115 pthread_mutexattr_destroy (&attr);
2117 setup_logging ();
2119 x = config_get_int_param (global_config, "global", "priority", &exists);
2120 if (exists && x != atoi(INVALID_PRIORITY))
2122 errno = 0;
2123 if (setpriority (PRIO_PROCESS, 0, x) == -1)
2125 log_write ("setpriority(): %s",
2126 pwmd_strerror (gpg_error_from_errno (errno)));
2127 goto do_exit;
2130 #ifdef HAVE_MLOCKALL
2131 if (disable_mlock == 0 && mlockall (MCL_CURRENT | MCL_FUTURE) == -1)
2133 log_write ("mlockall(): %s",
2134 pwmd_strerror (gpg_error_from_errno (errno)));
2135 goto do_exit;
2137 #endif
2139 rc = cache_init ();
2140 if (rc)
2142 log_write ("pwmd: ERR %i: %s", rc, pwmd_strerror (rc));
2143 exit (EXIT_FAILURE);
2146 if (import)
2148 char **keyids = NULL, **sign_keyids = NULL;
2150 if (!outfile || !*outfile || argc != optind)
2151 usage (argv[0], EXIT_FAILURE);
2153 if (keyid)
2154 keyids = str_split (keyid, ",", 0);
2155 if (sign_keyid)
2156 sign_keyids = str_split (sign_keyid, ",", 0);
2157 rc = xml_import (import, outfile, keyids, sign_keyids, keyfile, keyparam, sym);
2158 strv_free (keyids);
2159 strv_free (sign_keyids);
2160 if (rc)
2162 if (gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
2163 rc = gpg_error (rc);
2165 log_write ("%s: %u: %s", import, rc, pwmd_strerror (rc));
2168 config_free (global_config);
2169 xfree (rcfile);
2170 exit (rc ? EXIT_FAILURE : EXIT_SUCCESS);
2173 p = config_get_string ("global", "socket_path");
2174 if (!p)
2175 p = str_asprintf ("%s/socket", homedir);
2177 socketarg = expand_homedir (p);
2178 xfree (p);
2180 if (!secure)
2181 disable_list_and_dump = config_get_boolean ("global",
2182 "disable_list_and_dump");
2183 else
2184 disable_list_and_dump = secure;
2186 cache_push = config_get_list ("global", "cache_push");
2188 while (optind < argc)
2190 if (strv_printf (&cache_push, "%s", argv[optind++]) == 0)
2191 errx (EXIT_FAILURE, "%s", pwmd_strerror (GPG_ERR_ENOMEM));
2194 if (strchr (socketarg, '/') == NULL)
2196 socketdir = getcwd (buf, sizeof (buf));
2197 socketname = str_dup (socketarg);
2198 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2200 else
2202 socketname = str_dup (strrchr (socketarg, '/'));
2203 socketname++;
2204 socketarg[strlen (socketarg) - strlen (socketname) - 1] = 0;
2205 socketdir = str_dup (socketarg);
2206 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2209 if (chdir (datadir))
2211 log_write ("%s: %s", datadir,
2212 pwmd_strerror (gpg_error_from_errno (errno)));
2213 unlink (socketpath);
2214 goto do_exit;
2217 x = test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 0,
2218 mode, terminate);
2219 if (!terminate && x)
2220 goto do_exit;
2221 else if (terminate)
2223 estatus = x != 1 ? EXIT_FAILURE : EXIT_SUCCESS;
2224 goto do_exit;
2228 * bind() doesn't like the full pathname of the socket or any non alphanum
2229 * characters so change to the directory where the socket is wanted then
2230 * create it then change to datadir.
2232 if (chdir (socketdir))
2234 log_write ("%s: %s", socketdir,
2235 pwmd_strerror (gpg_error_from_errno (errno)));
2236 goto do_exit;
2239 xfree (socketdir);
2241 if ((sockfd = socket (PF_UNIX, SOCK_STREAM, 0)) == -1)
2243 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2244 goto do_exit;
2247 addr.sun_family = AF_UNIX;
2248 snprintf (addr.sun_path, sizeof (addr.sun_path), "%s", socketname);
2249 do_unlink = 1;
2250 if (bind (sockfd, (struct sockaddr *) &addr, sizeof (struct sockaddr)) ==
2253 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2255 if (errno == EADDRINUSE)
2257 do_unlink = 0;
2258 log_write (_("Either there is another pwmd running or '%s' is a \n"
2259 "stale socket. Please remove it manually."), socketpath);
2262 goto do_exit;
2266 char *t = config_get_string ("global", "socket_perms");
2267 mode_t mask;
2269 if (t)
2271 mode = strtol (t, NULL, 8);
2272 mask = umask (0);
2273 xfree (t);
2275 if (chmod (socketname, mode) == -1)
2277 log_write ("%s: %s", socketname,
2278 pwmd_strerror (gpg_error_from_errno (errno)));
2279 close (sockfd);
2280 umask (mask);
2281 goto do_exit;
2284 umask (mask);
2288 xfree (--socketname);
2290 if (chdir (datadir))
2292 log_write ("%s: %s", datadir,
2293 pwmd_strerror (gpg_error_from_errno (errno)));
2294 close (sockfd);
2295 goto do_exit;
2298 xfree (datadir);
2299 #ifdef WITH_GNUTLS
2300 if (config_get_boolean ("global", "enable_tcp"))
2302 if (!tls_start_stop (0))
2304 close (sockfd);
2305 goto do_exit;
2308 #endif
2311 * Set the cache entry for a file. Prompts for the password.
2313 if (cache_push)
2315 for (opt = 0; cache_push[opt]; opt++)
2317 struct crypto_s *crypto = NULL;
2318 char *pw_file = config_get_string (cache_push[opt],
2319 "passphrase_file");
2320 rc = crypto_init (&crypto, NULL, cache_push[opt], pw_file != NULL,
2321 pw_file);
2323 if (!rc)
2325 crypto->flags |= pw_file ? CRYPTO_FLAG_KEYFILE : 0;
2326 crypto->keyfile = pw_file;
2328 else
2329 xfree (pw_file);
2331 if (rc)
2333 estatus = EXIT_FAILURE;
2334 goto do_exit;
2337 rc = do_cache_push (crypto);
2338 if (rc && !force)
2340 log_write ("ERR %u: %s", rc, pwmd_strerror(rc));
2341 strv_free (cache_push);
2342 log_write (_ ("Failed to add a file to the cache. Use --force to force startup. Exiting."));
2343 cache_clear (NULL, NULL, 1);
2344 estatus = EXIT_FAILURE;
2345 crypto_free (crypto);
2346 goto do_exit;
2348 else if (rc)
2349 log_write ("%s: %s", crypto->filename, pwmd_strerror(rc));
2350 else
2351 log_write (_("Successfully added '%s' to the cache."),
2352 crypto->filename);
2354 crypto_free (crypto);
2357 strv_free (cache_push);
2358 log_write (!nofork ? _("Done. Daemonizing...") :
2359 _("Done. Waiting for connections..."));
2362 backlog = config_get_integer ("global", "backlog");
2363 if (listen (sockfd, backlog) == -1)
2365 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2366 goto do_exit;
2369 if (!nofork)
2371 switch (fork ())
2373 case -1:
2374 log_write ("fork(): %s",
2375 pwmd_strerror (gpg_error_from_errno (errno)));
2376 goto do_exit;
2377 case 0:
2378 close (0);
2379 close (1);
2380 close (2);
2381 setsid ();
2382 break;
2383 default:
2384 _exit (EXIT_SUCCESS);
2388 (void)test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 1,
2389 mode, 0);
2390 cmdline = 0;
2391 pthread_key_create (&thread_name_key, free_key);
2392 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
2393 estatus = server_loop (sockfd, &socketpath);
2395 do_exit:
2396 if (socketpath && do_unlink)
2398 unlink (socketpath);
2399 xfree (socketpath);
2402 xfree (socketarg);
2403 #ifdef WITH_GNUTLS
2404 gnutls_global_deinit ();
2405 tls_deinit_params ();
2406 #endif
2407 pthread_cond_destroy (&rcfile_cond);
2408 pthread_mutex_destroy (&rcfile_mutex);
2409 pthread_key_delete (last_error_key);
2410 #ifndef HAVE_PTHREAD_CANCEL
2411 pthread_key_delete (signal_thread_key);
2412 #endif
2414 if (global_config)
2415 config_free (global_config);
2417 free_invoking_users (invoking_users);
2418 xfree (rcfile);
2419 xfree (home_directory);
2420 xfree (homedir);
2421 xmlCleanupParser ();
2422 xmlCleanupGlobals ();
2424 if (pidfile)
2425 unlink (pidfile);
2426 xfree (pidfile);
2428 if (estatus == EXIT_SUCCESS && !terminate)
2429 log_write (_("pwmd exiting normally"));
2431 pthread_key_delete (thread_name_key);
2432 closelog ();
2434 if (log_fd != -1)
2435 close (log_fd);
2437 exit (estatus);
2440 gpg_error_t lock_flock (assuan_context_t ctx, const char *filename,
2441 int type, int *fd)
2443 gpg_error_t rc = 0;
2445 #ifdef HAVE_FLOCK
2446 *fd = open (filename, O_RDONLY);
2447 if (*fd == -1)
2448 return gpg_error_from_syserror ();
2450 TRY_FLOCK (ctx, *fd, type, rc);
2451 if (rc)
2453 close (*fd);
2454 *fd = -1;
2456 #endif
2458 return rc;
2461 void unlock_flock (int *fd)
2463 #ifdef HAVE_FLOCK
2464 if (*fd != -1)
2465 close (*fd);
2467 *fd = -1;
2468 #endif