Add configuration parameter "backlog".
[libpwmd.git] / src / pwmd.c
blob813b347a8cd0e1c4f4b168d66c630e3916c8a73d
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 for (;;)
178 struct slist_s *keep = NULL;
179 struct slist_s *config;
180 int b = disable_list_and_dump;
181 #ifdef WITH_GNUTLS
182 char *prio;
183 char *prio2 = NULL;
184 #endif
186 pthread_cleanup_push (release_mutex_cb, &rcfile_mutex);
187 pthread_cond_wait (&rcfile_cond, &rcfile_mutex);
188 TEST_CANCEL ();
189 keep = config_keep_save ();
190 log_write (_("reloading configuration file '%s'"), rcfile);
192 #ifdef WITH_GNUTLS
193 prio = config_get_string ("global", "tls_cipher_suite");
194 #endif
195 config = config_parse (rcfile, 1);
196 if (config)
198 config_free (global_config);
199 global_config = config;
200 setup_logging ();
203 config_keep_restore (keep);
204 disable_list_and_dump = !disable_list_and_dump ? b : 1;
206 #ifdef WITH_GNUTLS
207 /* Restart listening sockets since they may have changed. */
208 tls_start_stop (1);
209 tls_start_stop (0);
211 prio2 = config_get_string ("global", "tls_cipher_suite");
212 if ((prio2 && (!prio || strcmp (prio, prio2))) || (prio && !prio2))
213 tls_rehandshake ();
215 xfree (prio2);
216 xfree (prio);
217 #endif
218 crypto_set_keepalive ();
219 pthread_cleanup_pop (0);
222 MUTEX_UNLOCK (&rcfile_mutex);
223 return NULL;
226 gpg_error_t
227 send_error (assuan_context_t ctx, gpg_error_t e)
229 struct client_s *client = assuan_get_pointer (ctx);
231 if (gpg_err_source (e) == GPG_ERR_SOURCE_UNKNOWN)
232 e = gpg_error (e);
234 if (client)
235 client->last_rc = e;
237 if (!e)
238 return assuan_process_done (ctx, 0);
240 if (!ctx)
242 log_write ("ERR %i: %s", e, pwmd_strerror (e));
243 return e;
246 if (client && client->xml_error)
248 log_write ("%s", client->xml_error->message);
249 xfree (client->last_error);
250 client->last_error = NULL;
251 if (client->xml_error->message)
252 client->last_error = str_dup (client->xml_error->message);
254 e = assuan_process_done (ctx,
255 assuan_set_error (ctx, e,
256 client->xml_error->message ? client->xml_error->message : NULL));
257 xmlResetLastError ();
258 xmlResetError (client->xml_error);
259 xfree (client->xml_error);
260 client->xml_error = NULL;
261 return e;
264 return assuan_process_done (ctx,
265 assuan_set_error (ctx, e, pwmd_strerror (e)));
268 void
269 log_write (const char *fmt, ...)
271 char *args;
272 va_list ap;
273 time_t now;
274 char buf[255];
275 pthread_t tid = pthread_self ();
276 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
278 if ((!logfile && !isatty (STDERR_FILENO) && !log_syslog) || !fmt)
279 return;
281 pthread_mutex_lock (&m);
282 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock, &m);
284 if (!cmdline && logfile && log_fd == -1)
286 log_fd = open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600);
287 if (log_fd == -1)
288 warn ("%s", logfile);
291 va_start (ap, fmt);
293 if (str_vasprintf (&args, fmt, ap) != -1)
295 if (cmdline)
297 pthread_cleanup_push (xfree, args);
298 fprintf (stderr, "pwmd: %s\n", args);
299 fflush (stderr);
300 pthread_cleanup_pop (1);
302 else
304 char *name = pthread_getspecific (thread_name_key);
305 char *line;
307 pthread_cleanup_push (xfree, args);
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 pthread_cleanup_pop (1);
335 if (line)
337 pthread_cleanup_push (xfree, line);
338 if (logfile && log_fd != -1)
340 ssize_t ret = write (log_fd, line, strlen (line));
341 (void)ret;
342 fsync (log_fd);
345 if (nofork)
347 fprintf (stdout, "%s", line);
348 fflush (stdout);
351 pthread_cleanup_pop (1);
356 va_end (ap);
357 pthread_cleanup_pop (0);
359 if (log_fd != -1 && log_keepopen <= 0)
361 close(log_fd);
362 log_fd = -1;
365 pthread_mutex_unlock (&m);
368 static gpg_error_t
369 setup_crypto ()
371 gpg_error_t rc;
373 if (!gpgrt_check_version (REQUIRE_LIBGPGERROR_VERSION))
375 fprintf (stderr, _("gpgrt_check_version(): Incompatible libgpg-error. "
376 "Wanted %s, got %s.\n"), REQUIRE_LIBGPGERROR_VERSION,
377 gpgrt_check_version (NULL));
378 return GPG_ERR_UNKNOWN_VERSION;
381 gpgrt_init ();
382 //gpgrt_set_alloc_func (xrealloc_gpgrt);
384 if (!assuan_check_version (REQUIRE_LIBASSUAN_VERSION))
386 fprintf (stderr, _("assuan_check_version(): Incompatible libassuan. "
387 "Wanted %s, got %s.\n"), REQUIRE_LIBASSUAN_VERSION,
388 assuan_check_version (NULL));
389 return GPG_ERR_UNKNOWN_VERSION;
392 if (!gcry_check_version (REQUIRE_LIBGCRYPT_VERSION))
394 fprintf (stderr, _("gcry_check_version(): Incompatible libgcrypt. "
395 "Wanted %s, got %s.\n"), REQUIRE_LIBGCRYPT_VERSION,
396 gcry_check_version (NULL));
397 return GPG_ERR_UNKNOWN_VERSION;
400 gcry_set_allocation_handler (xmalloc, xmalloc, NULL, xrealloc, xfree);
402 if (!gpgme_check_version (REQUIRE_LIBGPGME_VERSION))
404 fprintf (stderr, _("gpgme_check_version(): Incompatible libgpgme. "
405 "Wanted %s, got %s.\n"), REQUIRE_LIBGPGME_VERSION,
406 gpgme_check_version (NULL));
407 return GPG_ERR_UNKNOWN_VERSION;
410 rc = gpgme_engine_check_version (GPGME_PROTOCOL_OPENPGP);
411 if (rc)
413 fprintf (stderr, _("gpgme_engine_check_version(GPGME_PROTOCOL_OPENPGP): %s"), gpgme_strerror (rc));
414 return GPG_ERR_UNKNOWN_VERSION;
417 //gpgme_set_global_flag ("require-gnupg", REQUIRE_GNUPG_VERSION);
418 #ifdef ENABLE_NLS
419 gpgme_set_locale (NULL, LC_CTYPE, setlocale (LC_CTYPE, NULL));
420 gpgme_set_locale (NULL, LC_MESSAGES, setlocale (LC_MESSAGES, NULL));
421 #endif
423 #ifdef WITH_GNUTLS
424 if (gnutls_global_init ())
426 fprintf(stderr, _("gnutls_global_init() failed.\n"));
427 return GPG_ERR_UNKNOWN_VERSION;
430 if (!gnutls_check_version (REQUIRE_LIBGNUTLS_VERSION))
432 fprintf (stderr, _("gnutls_check_version(): Incompatible libgnutls. "
433 "Wanted %s, got %s.\n"), REQUIRE_LIBGNUTLS_VERSION,
434 gnutls_check_version (NULL));
435 return GPG_ERR_UNKNOWN_VERSION;
438 gnutls_global_set_log_function (tls_log);
439 gnutls_global_set_audit_log_function (tls_audit_log);
440 #endif
441 return 0;
444 static void
445 xml_error_cb (void *data, xmlErrorPtr e)
447 struct client_s *client = data;
450 * Keep the first reported error as the one to show in the error
451 * description. Reset in send_error().
453 if (client->xml_error)
454 return;
456 client->xml_error = xcalloc (1, sizeof(xmlError));
457 xmlCopyError (e, client->xml_error);
460 static pid_t
461 hook_waitpid (assuan_context_t ctx, pid_t pid, int action,
462 int *status, int options)
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 #endif
478 return read ((int) fd, data, len);
481 static ssize_t
482 hook_write (assuan_context_t ctx, assuan_fd_t fd,
483 const void *data, size_t len)
485 TEST_CANCEL ();
486 #ifdef WITH_GNUTLS
487 struct client_s *client = assuan_get_pointer (ctx);
489 if (client->thd->remote)
490 return tls_write_hook (ctx, (int) fd, data, len);
491 #endif
493 return write ((int) fd, data, len);
497 assuan_log_cb (assuan_context_t ctx, void *data, unsigned cat,
498 const char *msg)
500 struct client_s *client = data;
501 char *str = NULL;
503 (void)client;
505 if (!(assuan_level & cat))
506 return 0;
508 if (!msg)
509 return 1;
511 switch (cat)
513 case ASSUAN_LOG_INIT:
514 str = "ASSUAN[INIT]";
515 break;
516 case ASSUAN_LOG_CTX:
517 str = "ASSUAN[CTX]";
518 break;
519 case ASSUAN_LOG_ENGINE:
520 str = "ASSUAN[ENGINE]";
521 break;
522 case ASSUAN_LOG_DATA:
523 str = "ASSUAN[DATA]";
524 break;
525 case ASSUAN_LOG_SYSIO:
526 str = "ASSUAN[SYSIO]";
527 break;
528 case ASSUAN_LOG_CONTROL:
529 str = "ASSUAN[CONTROL]";
530 break;
531 default:
532 str = "ASSUAN[UNKNOWN]";
533 break;
536 log_write ("%s: %s", str, msg);
537 return 1;
540 static int
541 new_connection (struct client_s *cl)
543 gpg_error_t rc;
544 static struct assuan_malloc_hooks mhooks = { xmalloc, xrealloc, xfree };
545 static struct assuan_system_hooks shooks = {
546 ASSUAN_SYSTEM_HOOKS_VERSION,
547 __assuan_usleep,
548 __assuan_pipe,
549 __assuan_close,
550 hook_read,
551 hook_write,
552 //FIXME
553 NULL, //recvmsg
554 NULL, //sendmsg both are used for FD passing
555 __assuan_spawn,
556 hook_waitpid,
557 __assuan_socketpair,
558 __assuan_socket,
559 __assuan_connect
562 #ifdef WITH_GNUTLS
563 if (cl->thd->remote)
565 char *prio = config_get_string ("global", "tls_cipher_suite");
567 cl->thd->timeout = config_get_integer ("global", "tls_timeout");
568 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
569 return 0;
571 cl->thd->tls = tls_init_client (cl->thd->fd, cl->thd->timeout, prio);
572 xfree (prio);
573 if (!cl->thd->tls)
574 return 0;
576 #endif
578 rc = assuan_new_ext (&cl->ctx, GPG_ERR_SOURCE_DEFAULT, &mhooks,
579 assuan_log_cb, cl);
580 if (rc)
581 goto fail;
583 assuan_ctx_set_system_hooks (cl->ctx, &shooks);
584 rc = assuan_init_socket_server (cl->ctx, cl->thd->fd, 2);
585 if (rc)
586 goto fail;
588 assuan_set_pointer (cl->ctx, cl);
589 assuan_set_hello_line (cl->ctx, PACKAGE_STRING);
590 rc = register_commands (cl->ctx);
591 if (rc)
592 goto fail;
594 rc = assuan_accept (cl->ctx);
595 if (rc)
596 goto fail;
598 rc = validate_peer (cl);
599 /* May not be implemented on all platforms. */
600 if (rc && gpg_err_code (rc) != GPG_ERR_ASS_GENERAL)
601 goto fail;
603 MUTEX_LOCK (&cn_mutex);
604 cl->thd->state = CLIENT_STATE_INIT;
605 MUTEX_UNLOCK (&cn_mutex);
606 cl->lock_timeout = config_get_integer ("global", "lock_timeout");
607 xmlSetStructuredErrorFunc (cl, xml_error_cb);
608 return 1;
610 fail:
611 log_write ("%s", pwmd_strerror (rc));
612 return 0;
616 * This is called after a client is cancelled or disconnects. Set with
617 * pthread_cleanup_push().
619 static void
620 free_client_cb (void *arg)
622 struct client_thread_s *cn = arg;
623 struct client_s *cl = cn->cl;
624 #ifndef HAVE_PTHREAD_CANCEL
625 char *tmp = pthread_getspecific (signal_thread_key);
627 xfree (tmp);
628 pthread_setspecific (signal_thread_key, NULL);
629 #endif
630 MUTEX_LOCK (&cn_mutex);
631 cn_thread_list = slist_remove (cn_thread_list, cn);
632 MUTEX_UNLOCK (&cn_mutex);
634 if (cl)
636 unlock_flock (&cl->flock_fd);
637 reset_client (cl);
638 if (cl->xml_error)
639 xmlResetError (cl->xml_error);
641 xfree (cl->xml_error);
643 #ifdef WITH_GNUTLS
644 if (cn->tls)
646 gnutls_deinit (cn->tls->ses);
647 xfree (cn->tls->fp);
648 xfree (cn->tls);
650 #endif
652 if (cl->ctx)
653 assuan_release (cl->ctx);
654 else if (cl->thd && cl->thd->fd != -1)
655 close (cl->thd->fd);
657 if (cl->crypto)
658 crypto_free (cl->crypto);
660 cl->crypto = NULL;
661 xfree (cl);
663 else
665 if (cn->fd != -1)
666 close (cn->fd);
669 while (cn->msg_queue)
671 struct status_msg_s *msg = cn->msg_queue;
673 cn->msg_queue = msg->next;
674 xfree (msg->line);
675 xfree (msg);
678 if (cn->status_msg_pipe[0] != -1)
679 close (cn->status_msg_pipe[0]);
681 if (cn->status_msg_pipe[1] != -1)
682 close (cn->status_msg_pipe[1]);
684 pthread_mutex_destroy (&cn->status_mutex);
685 log_write (_("exiting, fd=%i"), cn->fd);
686 send_status_all (STATUS_CLIENTS, NULL);
688 #ifdef WITH_GNUTLS
689 xfree (cn->peeraddr);
690 #endif
691 xfree (cn);
694 static void
695 free_all_clients ()
697 MUTEX_LOCK (&cn_mutex);
698 pthread_cleanup_push (release_mutex_cb, &cn_mutex);
700 while (slist_length (cn_thread_list))
702 struct client_thread_s *thd = slist_nth_data (cn_thread_list, 0);
704 free_client_cb (thd);
707 pthread_cleanup_pop (1);
710 static gpg_error_t
711 send_msg_queue (struct client_thread_s *thd)
713 MUTEX_LOCK (&thd->status_mutex);
714 gpg_error_t rc = 0;
715 char c;
716 ssize_t ret;
718 ret = read (thd->status_msg_pipe[0], &c, 1);
719 rc = gpg_error_from_syserror ();
720 if (ret == -1 && gpg_err_code (rc) != GPG_ERR_EAGAIN)
721 log_write ("%s (%i): %s", __FUNCTION__, __LINE__, pwmd_strerror (rc));
722 else
723 rc = 0;
725 thd->wrote_status = 0;
727 while (thd->msg_queue)
729 struct status_msg_s *msg = thd->msg_queue;
731 thd->msg_queue = thd->msg_queue->next;
732 MUTEX_UNLOCK (&thd->status_mutex);
733 pthread_cleanup_push (xfree, msg);
734 pthread_cleanup_push (xfree, msg->line);
735 rc = send_status (thd->cl->ctx, msg->s, msg->line);
736 pthread_cleanup_pop (1);
737 pthread_cleanup_pop (1);
738 MUTEX_LOCK (&thd->status_mutex);
739 if (rc)
740 break;
743 MUTEX_UNLOCK (&thd->status_mutex);
744 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
745 log_write ("%s (%i): %s", __FUNCTION__, __LINE__, pwmd_strerror (rc));
747 return rc;
750 static void *
751 client_thread (void *data)
753 struct client_thread_s *thd = data;
754 struct client_s *cl = xcalloc (1, sizeof (struct client_s));
755 struct slist_s *list;
756 gpg_error_t rc;
757 #ifndef HAVE_PTHREAD_CANCEL
758 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
759 #endif
761 #ifdef HAVE_PR_SET_NAME
762 prctl (PR_SET_NAME, "client");
763 #endif
764 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
766 if (!cl)
768 log_write ("%s(%i): %s", __FILE__, __LINE__,
769 pwmd_strerror (GPG_ERR_ENOMEM));
770 return NULL;
773 MUTEX_LOCK (&cn_mutex);
774 pthread_cleanup_push (free_client_cb, thd);
775 thd->cl = cl;
776 cl->thd = thd;
777 cl->flock_fd = -1;
779 list = slist_append (cn_thread_list, thd);
780 if (list)
781 cn_thread_list = list;
782 else
784 log_write ("%s(%i): %s", __FILE__, __LINE__,
785 pwmd_strerror (GPG_ERR_ENOMEM));
786 MUTEX_UNLOCK (&cn_mutex);
787 return NULL;
790 if (fcntl (thd->status_msg_pipe[0], F_SETFL, O_NONBLOCK) == -1)
791 rc = gpg_error_from_errno (errno);
793 if (!rc)
794 if (fcntl (thd->status_msg_pipe[1], F_SETFL, O_NONBLOCK) == -1)
795 rc = gpg_error_from_errno (errno);
797 MUTEX_UNLOCK (&cn_mutex);
799 if (rc)
801 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
802 return NULL;
805 if (new_connection (cl))
807 int finished = 0;
808 gpg_error_t rc;
809 struct pollfd fds[2];
811 fds[0].fd = thd->fd;
812 fds[0].events = POLLIN;
813 fds[1].fd = thd->status_msg_pipe[0];
814 fds[1].events = POLLIN;
816 send_status_all (STATUS_CLIENTS, NULL);
817 rc = send_status (cl->ctx, STATUS_CACHE, NULL);
818 if (rc)
820 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
821 finished = 1;
824 while (!finished)
826 int n;
827 int eof;
829 n = poll (fds, 2, 100);
830 if (n == -1)
832 log_write ("%s", strerror (errno));
833 break;
836 #ifdef WITH_GNUTLS
837 if (thd->remote && thd->tls && thd->tls->rehandshake)
839 char *prio;
840 int ret;
841 const char *e;
843 if (thd->tls->rehandshake == 1)
845 prio = config_get_string ("global", "tls_cipher_suite");
846 if (!prio)
848 thd->tls->rehandshake = 0;
849 continue;
852 ret = gnutls_priority_set_direct (thd->tls->ses, prio, &e);
853 if (ret == GNUTLS_E_SUCCESS)
855 rc = send_status (cl->ctx, STATUS_REHANDSHAKE, NULL);
856 if (!rc)
858 rc = assuan_send_data (cl->ctx, NULL, 0);
859 if (!rc)
861 ret = gnutls_rehandshake (thd->tls->ses);
862 if (ret)
864 log_write ("%s", gnutls_strerror (ret));
865 thd->tls->rehandshake = 0;
867 else
868 thd->tls->rehandshake = 2;
872 if (rc)
873 log_write ("%s", pwmd_strerror (rc));
875 else
876 log_write ("%s: %s", gnutls_strerror (ret), e);
878 xfree (prio);
879 continue;
882 #endif
884 if (!n)
885 continue;
887 if (fds[1].revents & POLLIN)
889 #ifdef WITH_GNUTLS
890 if (!thd->remote || (thd->tls && !thd->tls->rehandshake))
891 #endif
893 rc = send_msg_queue (thd);
894 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
895 break;
899 #ifdef HAVE_PTHREAD_CANCEL
900 if (!(fds[0].revents & POLLIN))
901 #else
902 if (thd->fd != -1 && !(fds[0].revents & POLLIN))
903 #endif
904 continue;
906 rc = assuan_process_next (cl->ctx, &eof);
907 if (rc || eof)
909 if (gpg_err_code (rc) == GPG_ERR_EOF || eof)
910 break;
912 log_write ("assuan_process_next(): rc=%u %s", rc,
913 pwmd_strerror (rc));
914 if (rc == gpg_error (GPG_ERR_ETIMEDOUT))
915 break;
917 rc = send_error (cl->ctx, rc);
918 if (rc)
920 log_write ("assuan_process_done(): rc=%u %s", rc,
921 pwmd_strerror (rc));
922 break;
926 /* Since the msg queue pipe fd's are non-blocking, check for
927 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
928 * client has already disconnected and will be converted to
929 * GPG_ERR_EOF during assuan_process_next().
931 #ifdef WITH_GNUTLS
932 if (!thd->remote || (thd->tls && !thd->tls->rehandshake))
933 #endif
935 rc = send_msg_queue (thd);
936 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
937 break;
942 /* Don't do pthread_exit() here because any set pthread_cleanup_push
943 * functions would be called after a command failed but then the client
944 * exited normally which may lead to a double free. */
945 pthread_cleanup_pop (1);
946 return NULL;
949 static gpg_error_t
950 xml_import (const char *filename, const char *outfile, char **keyid,
951 char **sign_keyid, char *keyfile, const char *keyparam,
952 int symmetric)
954 xmlDocPtr doc;
955 int fd;
956 struct stat st;
957 int len;
958 xmlChar *xmlbuf;
959 gpg_error_t rc = 0;
960 struct crypto_s *crypto = NULL;
962 if (stat (filename, &st) == -1)
964 rc = gpg_error_from_errno (errno);
965 return rc;
968 fd = open (filename, O_RDONLY);
969 if (fd == -1)
970 return gpg_error_from_errno (errno);
972 xmlbuf = xmalloc (st.st_size + 1);
973 if (!xmlbuf)
975 close (fd);
976 return GPG_ERR_ENOMEM;
979 if (read (fd, xmlbuf, st.st_size) == -1)
981 rc = gpg_error_from_errno (errno);
982 close (fd);
983 xfree (xmlbuf);
984 return rc;
987 close (fd);
988 xmlbuf[st.st_size] = 0;
989 // Be sure the document validates.
990 doc = xmlReadDoc (xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS);
991 xfree (xmlbuf);
992 if (!doc)
993 return GPG_ERR_BAD_DATA;
995 xmlNodePtr n = xmlDocGetRootElement (doc);
996 if (n && !xmlStrEqual (n->name, (xmlChar *) "pwmd"))
997 rc = GPG_ERR_BAD_DATA;
999 if (!rc)
1001 rc = xml_validate_import (NULL, n ? n->children : n);
1002 if (!rc)
1004 rc = crypto_init (&crypto, NULL, filename, keyfile != NULL, keyfile);
1005 if (!rc)
1007 if (keyfile)
1009 crypto->flags |= CRYPTO_FLAG_KEYFILE;
1010 crypto->keyfile = str_dup (keyfile);
1013 xmlDocDumpMemory (doc, &crypto->plaintext, &len);
1014 if (len > 0)
1015 crypto->plaintext_size = len;
1016 else
1017 rc = GPG_ERR_ENOMEM;
1022 if (!rc)
1024 if (!symmetric && (keyparam || !keyid))
1026 char *buf = NULL;
1028 if (keyparam)
1030 fd = open (keyparam, O_RDONLY);
1031 if (fd == -1)
1032 rc = gpg_error_from_errno (errno);
1034 if (!rc)
1036 if (stat (keyparam, &st) == -1)
1037 rc = gpg_error_from_errno (errno);
1039 if (!rc)
1041 buf = xmalloc (st.st_size+1);
1042 if (!buf)
1043 rc = GPG_ERR_ENOMEM;
1045 if (!rc)
1047 len = read (fd, buf, st.st_size);
1048 if (len != st.st_size)
1049 rc = gpg_error_from_errno (errno);
1051 if (!rc)
1052 buf[len] = 0;
1057 if (fd != -1)
1058 close (fd);
1060 else
1062 buf = crypto_default_key_params ();
1063 if (!buf)
1064 rc = GPG_ERR_ENOMEM;
1067 if (!rc)
1068 rc = crypto_genkey (NULL, crypto, (unsigned char *)buf);
1070 xfree (buf);
1072 else
1074 crypto->save.pubkey = strv_dup (keyid);
1075 crypto->save.sigkey = strv_dup (sign_keyid);
1078 if (!rc)
1080 crypto->flags |= symmetric ? CRYPTO_FLAG_SYMMETRIC : 0;
1081 rc = crypto_encrypt (NULL, crypto);
1085 if (!rc)
1087 if (!strcmp (outfile, "-"))
1088 outfile = NULL;
1090 xfree (crypto->plaintext);
1091 crypto->plaintext = NULL;
1092 xfree (crypto->filename);
1093 crypto->filename = outfile ? str_dup (outfile) : NULL;
1094 rc = crypto_write_file (crypto);
1097 xmlFreeDoc (doc);
1098 crypto_free (crypto);
1099 return rc;
1102 static gpg_error_t
1103 do_cache_push (struct crypto_s *crypto)
1105 gpg_error_t rc;
1106 xmlDocPtr doc;
1107 struct cache_data_s *cdata;
1108 unsigned char *crc;
1109 size_t len;
1110 int fd = -1;
1112 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1113 crypto->filename);
1115 if (valid_filename (crypto->filename) == 0)
1117 log_write (_("%s: Invalid characters in filename"), crypto->filename);
1118 return GPG_ERR_INV_VALUE;
1121 rc = lock_flock (NULL, crypto->filename, LOCK_SH, &fd);
1122 if (!rc)
1123 rc = crypto_decrypt (NULL, crypto);
1124 if (rc)
1126 unlock_flock (&fd);
1127 return rc;
1130 rc = xml_parse_doc ((char *) crypto->plaintext, crypto->plaintext_size, &doc);
1131 if (rc)
1133 unlock_flock (&fd);
1134 log_write ("%s", pwmd_strerror (rc));
1135 return rc;
1138 cdata = xcalloc (1, sizeof (struct cache_data_s));
1139 if (!cdata)
1141 unlock_flock (&fd);
1142 xmlFreeDoc (doc);
1143 return GPG_ERR_ENOMEM;
1146 rc = get_checksum (crypto->filename, &crc, &len);
1147 unlock_flock (&fd);
1148 if (rc)
1150 xmlFreeDoc (doc);
1151 cache_free_data_once (cdata);
1152 return rc;
1155 cdata->crc = crc;
1156 rc = cache_encrypt (crypto);
1157 if (!rc)
1159 cdata->doc = crypto->plaintext;
1160 cdata->size = crypto->plaintext_size;
1161 crypto->plaintext = NULL;
1162 cdata->pubkey = crypto->pubkey;
1163 cdata->sigkey = crypto->sigkey;
1164 crypto->pubkey = NULL;
1165 crypto->sigkey = NULL;
1167 else
1169 xmlFreeDoc (doc);
1170 cache_free_data_once (cdata);
1171 return rc;
1174 int timeout = config_get_integer (crypto->filename, "cache_timeout");
1175 rc = cache_add_file (crypto->filename, cdata, timeout);
1176 return rc;
1179 static gpg_error_t
1180 init_client (int fd, const char *addr)
1182 gpg_error_t rc = 0;
1183 struct client_thread_s *new = xcalloc (1, sizeof (struct client_thread_s));
1185 if (!new)
1187 close (fd);
1188 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (ENOMEM));
1189 return GPG_ERR_ENOMEM;
1192 MUTEX_LOCK (&cn_mutex);
1193 pthread_cleanup_push (release_mutex_cb, &cn_mutex);
1194 new->conntime = time (NULL);
1196 if (pipe (new->status_msg_pipe) == -1)
1197 rc = gpg_error_from_errno (errno);
1198 else
1199 pthread_mutex_init (&new->status_mutex, NULL);
1201 if (!rc)
1203 #ifdef WITH_GNUTLS
1204 new->remote = addr ? 1 : 0;
1205 if (addr)
1206 new->peeraddr = str_dup (addr);
1207 #endif
1208 new->fd = fd;
1209 rc = create_thread (client_thread, new, &new->tid, 1);
1210 if (rc)
1212 close (new->status_msg_pipe[0]);
1213 close (new->status_msg_pipe[1]);
1214 pthread_mutex_destroy (&new->status_mutex);
1218 if (!rc)
1220 if (addr)
1221 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1222 (pthread_t *) new->tid, fd, addr);
1223 else
1224 log_write (_("new connection: tid=%p, fd=%i"),
1225 (pthread_t *) new->tid, fd);
1228 pthread_cleanup_pop (1);
1230 if (rc)
1232 xfree (new);
1233 close (fd);
1234 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
1236 return rc;
1239 #ifdef WITH_GNUTLS
1240 static gpg_error_t
1241 do_tls_accept (struct pollfd *fds)
1243 struct sockaddr_storage raddr;
1244 socklen_t slen = sizeof (raddr);
1245 int fd;
1246 char s[INET6_ADDRSTRLEN];
1248 if (!(fds->revents & POLLIN))
1249 return 0;
1251 fd = accept (fds->fd, (struct sockaddr *) &raddr, &slen);
1252 if (fd == -1)
1254 int e = errno;
1256 if (errno != EAGAIN && !quit)
1257 log_write ("%s: %s", __FUNCTION__,
1258 pwmd_strerror (gpg_error_from_syserror()));
1260 return gpg_error_from_errno (e);
1263 inet_ntop (raddr.ss_family, get_in_addr ((struct sockaddr *) &raddr), s,
1264 sizeof s);
1265 (void) init_client (fd, s);
1266 return 0;
1268 #endif
1270 static void *
1271 accept_thread (void *arg)
1273 int sockfd = *(int *) arg;
1274 #ifndef HAVE_PTHREAD_CANCEL
1275 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
1276 #endif
1278 #ifdef HAVE_PR_SET_NAME
1279 prctl (PR_SET_NAME, "accept");
1280 #endif
1281 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
1283 for (;;)
1285 socklen_t slen = sizeof (struct sockaddr_un);
1286 struct sockaddr_un raddr;
1287 int fd, s = 0;
1288 struct pollfd fds[3];
1290 TEST_CANCEL ();
1291 memset (fds, 0, sizeof (fds));
1292 fds[s].fd = sockfd;
1293 fds[s++].events = POLLIN;
1295 #ifdef WITH_GNUTLS
1296 if (tls_fd != -1)
1298 fds[s].fd = tls_fd;
1299 fds[s++].events = POLLIN;
1301 else
1302 fds[s].fd = tls_fd;
1304 if (tls6_fd != -1)
1306 fds[s].fd = tls6_fd;
1307 fds[s++].events = POLLIN;
1309 else
1310 fds[s].fd = tls6_fd;
1311 #endif
1313 s = poll (fds, s, 500);
1314 if (s == -1)
1316 if (errno != EINTR)
1317 log_write ("%s", strerror (errno));
1318 break;
1320 else if (s == 0)
1321 continue;
1323 if (fds[0].revents & POLLIN)
1325 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1326 if (fd == -1)
1328 if (errno == EMFILE || errno == ENFILE)
1329 log_write ("%s: %s", __FUNCTION__,
1330 pwmd_strerror (gpg_error_from_errno (errno)));
1331 else if (errno != EAGAIN && errno != EINTR)
1333 if (!quit) // probably EBADF
1334 log_write ("%s: %s", __FUNCTION__,
1335 pwmd_strerror (gpg_error_from_errno (errno)));
1337 break;
1340 continue;
1343 (void) init_client (fd, NULL);
1346 #ifdef WITH_GNUTLS
1347 if (tls_fd != -1 && fds[1].fd == tls_fd)
1348 (void)do_tls_accept (&fds[1]);
1350 if (tls6_fd != -1 && fds[1].fd == tls6_fd)
1351 (void)do_tls_accept (&fds[1]);
1353 if (tls6_fd != -1 && fds[2].fd == tls6_fd)
1354 (void)do_tls_accept (&fds[2]);
1355 #endif
1358 /* Just in case accept() failed for some reason other than EBADF */
1359 quit = 1;
1360 return NULL;
1363 static void *
1364 cache_timer_thread (void *arg)
1366 unsigned k = 0;
1367 #ifndef HAVE_PTHREAD_CANCEL
1368 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
1369 #endif
1371 #ifdef HAVE_PR_SET_NAME
1372 prctl (PR_SET_NAME, "timer");
1373 #endif
1374 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
1376 for (;;)
1378 struct timeval tv = { 1, 0 };
1379 unsigned keepalive = config_get_integer ("global", "keepalive_interval");
1381 TEST_CANCEL ();
1382 select (0, NULL, NULL, NULL, &tv);
1383 cache_adjust_timeout ();
1385 if (keepalive && ++k >= keepalive)
1387 send_status_all (STATUS_KEEPALIVE, NULL);
1388 k = 0;
1392 return NULL;
1395 static int
1396 signal_loop (sigset_t sigset)
1398 int done = 0;
1402 int sig;
1404 sigwait (&sigset, &sig);
1405 log_write (_("caught signal %i (%s)"), sig, strsignal (sig));
1407 switch (sig)
1409 case SIGHUP:
1410 pthread_cond_signal (&rcfile_cond);
1411 break;
1412 case SIGUSR1:
1413 log_write (_("clearing file cache"));
1414 cache_clear (NULL, NULL, 1);
1415 send_status_all (STATUS_CACHE, NULL);
1416 break;
1417 default:
1418 done = 1;
1419 break;
1422 while (!done);
1424 return done;
1427 static void
1428 catchsig (int sig)
1430 log_write (_ ("Caught signal %i (%s). Exiting."), sig, strsignal (sig));
1431 #ifdef HAVE_BACKTRACE
1432 BACKTRACE (__FUNCTION__);
1433 #endif
1434 longjmp (jmp, 1);
1437 static void
1438 cancel_all_clients ()
1440 unsigned i, t;
1442 MUTEX_LOCK (&cn_mutex);
1443 t = slist_length (cn_thread_list);
1444 for (i = 0; i < t; i++)
1446 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
1448 #ifdef HAVE_PTHREAD_CANCEL
1449 pthread_cancel (thd->tid);
1450 #else
1451 pthread_kill (thd->tid, SIGUSR2);
1452 #endif
1455 while (slist_length (cn_thread_list))
1457 MUTEX_UNLOCK (&cn_mutex);
1458 usleep (50000);
1459 MUTEX_LOCK (&cn_mutex);
1462 MUTEX_UNLOCK (&cn_mutex);
1465 static int
1466 server_loop (int sockfd, char **socketpath)
1468 pthread_t cache_timeout_tid;
1469 pthread_t accept_tid;
1470 int cancel_timeout_thread = 0;
1471 int cancel_accept_thread = 0;
1472 int cancel_rcfile_thread = 0;
1473 sigset_t sigset;
1474 int n;
1475 int segv = 0;
1476 gpg_error_t rc;
1478 init_commands ();
1479 sigemptyset (&sigset);
1481 /* Termination */
1482 sigaddset (&sigset, SIGTERM);
1483 sigaddset (&sigset, SIGINT);
1485 /* Clears the file cache. */
1486 sigaddset (&sigset, SIGUSR1);
1488 /* Configuration file reloading. */
1489 sigaddset (&sigset, SIGHUP);
1491 #ifndef HAVE_PTHREAD_CANCEL
1493 The socket, cache and rcfile threads use this signal when
1494 pthread_cancel() is unavailable. Prevent the main thread from
1495 catching this signal from another process.
1497 sigaddset (&sigset, SIGUSR2);
1498 #endif
1500 /* An assertion failure. */
1501 signal (SIGABRT, catchsig);
1502 sigaddset (&sigset, SIGABRT);
1503 sigprocmask (SIG_BLOCK, &sigset, NULL);
1505 #ifndef HAVE_PTHREAD_CANCEL
1506 /* Remove this signal from the watched signals in signal_loop(). */
1507 sigdelset (&sigset, SIGUSR2);
1508 #endif
1510 /* Can show a backtrace of the stack in the log. */
1511 signal (SIGSEGV, catchsig);
1513 char *p = get_username (getuid());
1514 log_write (_("%s started for user %s"), PACKAGE_STRING, p);
1515 xfree (p);
1517 #ifdef WITH_GNUTLS
1518 if (config_get_boolean ("global", "enable_tcp"))
1519 log_write (_("Listening on %s and TCP port %i"), *socketpath,
1520 config_get_integer ("global", "tcp_port"));
1521 else
1522 log_write (_("Listening on %s"), *socketpath);
1523 #else
1524 log_write (_("Listening on %s"), *socketpath);
1525 #endif
1527 rc = create_thread (reload_rcfile_thread, NULL, &rcfile_tid, 0);
1528 if (rc)
1530 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1531 pwmd_strerror (rc));
1532 goto done;
1535 cancel_rcfile_thread = 1;
1536 rc = create_thread (cache_timer_thread, NULL, &cache_timeout_tid, 0);
1537 if (rc)
1539 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1540 pwmd_strerror (rc));
1541 goto done;
1544 cancel_timeout_thread = 1;
1545 rc = create_thread (accept_thread, &sockfd, &accept_tid, 0);
1546 if (rc)
1548 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1549 pwmd_strerror (rc));
1550 goto done;
1553 cancel_accept_thread = 1;
1554 if (!setjmp (jmp))
1555 signal_loop (sigset);
1556 else
1557 segv = 1;
1559 done:
1561 * We're out of the main server loop. This happens when a signal was sent
1562 * to terminate the daemon. Cancel all clients and exit.
1564 if (cancel_accept_thread)
1566 #ifdef HAVE_PTHREAD_CANCEL
1567 int n = pthread_cancel (accept_tid);
1568 #else
1569 int n = pthread_kill (accept_tid, SIGUSR2);
1570 #endif
1571 if (!n)
1572 pthread_join (accept_tid, NULL);
1575 if (cancel_timeout_thread)
1577 #ifdef HAVE_PTHREAD_CANCEL
1578 n = pthread_cancel (cache_timeout_tid);
1579 #else
1580 n = pthread_kill (cache_timeout_tid, SIGUSR2);
1581 #endif
1582 if (!n)
1583 pthread_join (cache_timeout_tid, NULL);
1586 #ifdef WITH_GNUTLS
1587 tls_start_stop (1);
1588 #endif
1589 shutdown (sockfd, SHUT_RDWR);
1590 close (sockfd);
1591 unlink (*socketpath);
1592 xfree (*socketpath);
1593 *socketpath = NULL;
1594 MUTEX_LOCK (&cn_mutex);
1595 n = slist_length (cn_thread_list);
1596 MUTEX_UNLOCK (&cn_mutex);
1598 if (n && !segv)
1599 cancel_all_clients ();
1600 else
1601 free_all_clients ();
1603 if (cancel_rcfile_thread)
1605 #ifdef HAVE_PTHREAD_CANCEL
1606 pthread_cancel (rcfile_tid);
1607 #else
1608 pthread_kill (rcfile_tid, SIGUSR2);
1609 pthread_cond_signal (&rcfile_cond);
1610 #endif
1611 pthread_join (rcfile_tid, NULL);
1614 cache_deinit ();
1615 deinit_commands ();
1616 return segv ? EXIT_FAILURE : EXIT_SUCCESS;
1619 static void
1620 usage (const char *pn, int status)
1622 FILE *fp = status == EXIT_FAILURE ? stderr : stdout;
1624 fprintf (fp, _("Usage: %s [OPTIONS] [file1] [...]\n"
1625 " --homedir alternate pwmd home directory (~/.pwmd)\n"
1626 " -f, --rcfile=filename load the specfied configuration file\n"
1627 " (~/.pwmd/config)\n"
1628 " --kill terminate an existing instance of pwmd\n"
1629 " -n, --no-fork run as a foreground process\n"
1630 " --disable-dump disable the LIST, XPATH and DUMP commands\n"
1631 " --ignore, --force ignore cache pushing errors during startup\n"
1632 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
1633 " -k, --passphrase-file=file for use when importing\n"
1634 " -o, --outfile=filename output file when importing\n"
1635 " --keyid=fpr[,..] public key to use when encrypting\n"
1636 " --sign-keyid=fpr[,..] fingerprint of the signing key to use\n"
1637 " -s, --symmetric use conventional encryption with optional signer\n"
1638 " --keyparam=filename custom key parameters to use (gpg default)\n"
1639 " --debug=[a:..][,g:N][,t:N] enable debugging (a:[ixedsc],g:[1-9],t:[0-N])\n"
1640 " --help this help text\n"
1641 " --version show version and compile time features\n"),
1642 pn);
1643 exit (status);
1646 static void
1647 unlink_stale_socket (const char *sock, const char *pidfile)
1649 log_write (_ ("removing stale socket %s"), sock);
1650 unlink (sock);
1651 unlink (pidfile);
1654 static int
1655 test_pidfile (const char *path, const char *sock, char *buf, size_t buflen,
1656 char **pidfile, int create, mode_t mode, int terminate)
1658 pid_t pid;
1659 int fd;
1660 size_t len;
1662 if (!create)
1664 snprintf (buf, buflen, "%s/%s.pid", homedir, sock);
1665 *pidfile = str_dup (buf);
1666 fd = open (buf, O_RDONLY);
1668 else
1669 fd = open (*pidfile, O_CREAT|O_WRONLY|O_TRUNC, mode);
1671 if (fd == -1)
1673 if (!create && errno != ENOENT)
1675 log_write ("%s: %s", buf, pwmd_strerror (errno));
1676 free (*pidfile);
1677 *pidfile = NULL;
1678 return -1;
1680 else if (!create && !terminate)
1681 return 0;
1683 log_write ("%s: %s", *pidfile, strerror (errno));
1684 return -1;
1687 if (create)
1689 snprintf (buf, buflen, "%i", getpid ());
1690 ssize_t ret = write (fd, buf, strlen (buf));
1691 if (ret == -1)
1692 log_write ("%s (%i): %s", __FUNCTION__, __LINE__,
1693 pwmd_strerror (gpg_error_from_syserror ()));
1694 close (fd);
1695 return 0;
1698 len = read (fd, buf, buflen);
1699 close (fd);
1700 if (len == 0)
1702 unlink_stale_socket (path, *pidfile);
1703 return 0;
1706 if (sscanf (buf, "%5i", &pid) != 1 || pid == 0)
1708 if (!terminate)
1710 unlink_stale_socket (path, *pidfile);
1711 return 0;
1715 if (kill (pid, 0) == -1)
1717 unlink_stale_socket (path, *pidfile);
1718 return 0;
1721 if (terminate)
1723 if (kill (pid, SIGTERM) == -1)
1724 log_write ("%s: %s", path, pwmd_strerror (errno));
1726 else
1727 log_write (_ ("an instance for socket %s is already running"), path);
1729 xfree (*pidfile);
1730 *pidfile = NULL;
1731 return 1;
1734 static unsigned
1735 parse_debug_level (const char *str, unsigned *debug, int *gpgme, int *tls)
1737 const char *p;
1738 unsigned level = 0;
1739 int gl = 0, tl = 0;
1741 for (p = str; p && *p; p++)
1743 if (*p == 'a') // assuan debug flags
1745 if (*++p != ':')
1746 return 1;
1748 while (*++p)
1750 switch (*p)
1752 case 'i':
1753 level |= ASSUAN_LOG_INIT;
1754 break;
1755 case 'x':
1756 level |= ASSUAN_LOG_CTX;
1757 break;
1758 case 'e':
1759 level |= ASSUAN_LOG_ENGINE;
1760 break;
1761 case 'd':
1762 level |= ASSUAN_LOG_DATA;
1763 break;
1764 case 's':
1765 level |= ASSUAN_LOG_SYSIO;
1766 break;
1767 case 'c':
1768 level |= ASSUAN_LOG_CONTROL;
1769 break;
1770 case ',':
1771 break;
1772 default:
1773 return 1;
1776 if (*p == ',')
1777 break;
1780 if (!*p)
1781 break;
1783 else if (*p == 'g' || *p == 't') // gpgme and TLS debug level
1785 int t = *p == 't';
1786 int n;
1788 if (*++p != ':')
1789 return 1;
1791 if (!isdigit (*++p))
1792 return 1;
1794 n = atoi (p);
1795 if (t)
1796 tl = n;
1797 else
1798 gl = n;
1800 if (tl < 0 || gl < 0 || gl > 9)
1801 return 1;
1803 while (isdigit (*p))
1804 p++;
1806 p--;
1807 if (*(p+1) && *(p+1) != ',')
1808 return 1;
1809 else if (*(p+1))
1810 p++;
1812 else
1813 return 1;
1816 if (tl)
1817 *tls = tl;
1819 if (gl)
1820 *gpgme = gl;
1822 *debug = level;
1823 return 0;
1827 main (int argc, char *argv[])
1829 int opt;
1830 struct sockaddr_un addr;
1831 char buf[PATH_MAX];
1832 char *socketpath = NULL, *socketdir, *socketname = NULL;
1833 char *socketarg = NULL;
1834 char *datadir = NULL;
1835 char *pidfile = NULL;
1836 mode_t mode = 0600;
1837 int x;
1838 char *p;
1839 char **cache_push = NULL;
1840 char *import = NULL, *keyid = NULL, *sign_keyid = NULL;
1841 char *keyparam = NULL;
1842 int estatus = EXIT_FAILURE;
1843 int sockfd;
1844 char *outfile = NULL;
1845 int do_unlink = 0;
1846 int secure = 0;
1847 int show_version = 0;
1848 int force = 0;
1849 gpg_error_t rc;
1850 char *keyfile = NULL;
1851 int exists;
1852 int optindex;
1853 int terminate = 0;
1854 int sym = 0;
1855 int gpgme_level = -1;
1856 int tls_level = -1;
1857 int backlog = 0;
1858 /* Must maintain the same order as longopts[] */
1859 enum
1861 OPT_VERSION, OPT_HELP, OPT_HOMEDIR, OPT_NO_FORK, OPT_DISABLE_DUMP,
1862 OPT_FORCE, OPT_RCFILE, OPT_PASSPHRASE_FILE, OPT_IMPORT, OPT_OUTFILE,
1863 OPT_KEYID, OPT_SIGN_KEYID, OPT_SYMMETRIC, OPT_KEYPARAM, OPT_KILL,
1864 OPT_DEBUG
1866 const char *optstring = "nf:C:k:I:o:s";
1867 const struct option longopts[] = {
1868 {"version", no_argument, 0, 0},
1869 {"help", no_argument, 0, 0},
1870 {"homedir", required_argument, 0, 0},
1871 {"no-fork", no_argument, 0, 'n'},
1872 {"disable_dump", no_argument, 0, 0},
1873 {"force", no_argument, 0, 0},
1874 {"rcfile", required_argument, 0, 'f'},
1875 {"passphrase-file", required_argument, 0, 'k'},
1876 {"import", required_argument, 0, 'I'},
1877 {"outfile", required_argument, 0, 'o'},
1878 {"keyid", required_argument, 0, 0},
1879 {"sign-keyid", required_argument, 0, 0},
1880 {"symmetric", no_argument, 0, 's'},
1881 {"keyparam", required_argument, 0, 0},
1882 {"kill", no_argument, 0, 0},
1883 {"debug", required_argument, 0, 0},
1884 {0, 0, 0, 0}
1887 log_fd = -1;
1888 cmdline = 1;
1890 #ifndef DEBUG
1891 #ifdef HAVE_SETRLIMIT
1892 struct rlimit rl;
1894 rl.rlim_cur = rl.rlim_max = 0;
1896 if (setrlimit (RLIMIT_CORE, &rl) != 0)
1897 err (EXIT_FAILURE, "setrlimit()");
1898 #endif
1900 #ifdef HAVE_PR_SET_DUMPABLE
1901 prctl (PR_SET_DUMPABLE, 0);
1902 #endif
1903 #endif
1905 #ifdef ENABLE_NLS
1906 setlocale (LC_ALL, "");
1907 bindtextdomain ("pwmd", LOCALEDIR);
1908 textdomain ("pwmd");
1909 #endif
1911 if (setup_crypto ())
1912 exit (EXIT_FAILURE);
1914 #ifdef WITH_GNUTLS
1915 tls_level = tls_level == -1 ? 1 : tls_level;
1916 gnutls_global_set_log_level (tls_level);
1917 tls_fd = -1;
1918 tls6_fd = -1;
1919 #endif
1920 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
1921 xmlInitMemory ();
1922 xmlInitGlobals ();
1923 xmlInitParser ();
1924 xmlXPathInit ();
1926 while ((opt = getopt_long (argc, argv, optstring, longopts, &optindex))
1927 != -1)
1929 switch (opt)
1931 case 'I':
1932 import = optarg;
1933 break;
1934 case 'k':
1935 keyfile = optarg;
1936 break;
1937 case 'o':
1938 outfile = optarg;
1939 break;
1940 case 'n':
1941 nofork = 1;
1942 break;
1943 case 'f':
1944 rcfile = str_dup (optarg);
1945 break;
1946 case 's':
1947 sym = 1;
1948 break;
1949 default:
1950 usage (argv[0], EXIT_FAILURE);
1951 break;
1952 case 0:
1953 switch (optindex)
1955 case OPT_DEBUG:
1956 if (parse_debug_level (optarg, &assuan_level, &gpgme_level,
1957 &tls_level))
1958 usage (argv[0], EXIT_FAILURE);
1959 break;
1960 case OPT_SYMMETRIC:
1961 sym = 1;
1962 break;
1963 case OPT_VERSION:
1964 show_version = 1;
1965 break;
1966 case OPT_HELP:
1967 usage (argv[0], EXIT_SUCCESS);
1968 break;
1969 case OPT_HOMEDIR:
1970 homedir = str_dup (optarg);
1971 break;
1972 case OPT_NO_FORK:
1973 nofork = 1;
1974 break;
1975 case OPT_DISABLE_DUMP:
1976 secure = 1;
1977 break;
1978 case OPT_FORCE:
1979 force = 1;
1980 break;
1981 case OPT_RCFILE:
1982 rcfile = str_dup (optarg);
1983 break;
1984 case OPT_PASSPHRASE_FILE:
1985 keyfile = optarg;
1986 break;
1987 case OPT_IMPORT:
1988 import = optarg;
1989 break;
1990 case OPT_OUTFILE:
1991 outfile = optarg;
1992 break;
1993 case OPT_KEYID:
1994 keyid = optarg;
1995 break;
1996 case OPT_SIGN_KEYID:
1997 sign_keyid = optarg;
1998 break;
1999 case OPT_KEYPARAM:
2000 keyparam = optarg;
2001 break;
2002 case OPT_KILL:
2003 terminate = 1;
2004 break;
2005 default:
2006 usage (argv[0], EXIT_FAILURE);
2011 if (show_version)
2013 printf (_("%s\n\n"
2014 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016\n"
2015 "%s\n"
2016 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2017 "Compile time features:\n%s"), PACKAGE_STRING,
2018 PACKAGE_BUGREPORT,
2019 #ifdef PWMD_HOMEDIR
2020 "+PWMD_HOMEDIR=" PWMD_HOMEDIR "\n"
2021 #endif
2022 #ifdef WITH_GNUTLS
2023 "+WITH_GNUTLS\n"
2024 #else
2025 "-WITH_GNUTLS\n"
2026 #endif
2027 #ifdef WITH_LIBACL
2028 "+WITH_LIBACL\n"
2029 #else
2030 "-WITH_LIBACL\n"
2031 #endif
2032 #ifdef DEBUG
2033 "+DEBUG\n"
2034 #else
2035 "-DEBUG\n"
2036 #endif
2037 #ifdef MEM_DEBUG
2038 "+MEM_DEBUG\n"
2039 #else
2040 "-MEM_DEBUG\n"
2041 #endif
2042 #ifdef MUTEX_DEBUG
2043 "+MUTEX_DEBUG\n"
2044 #else
2045 "-MUTEX_DEBUG\n"
2046 #endif
2048 exit (EXIT_SUCCESS);
2051 if (!homedir)
2052 #ifdef PWMD_HOMEDIR
2053 homedir = str_dup(PWMD_HOMEDIR);
2054 #else
2055 homedir = str_asprintf ("%s/.pwmd", get_home_dir());
2056 #endif
2058 if (mkdir (homedir, 0700) == -1 && errno != EEXIST)
2059 err (EXIT_FAILURE, "%s", homedir);
2061 if (!rcfile)
2062 rcfile = str_asprintf ("%s/config", homedir);
2064 pthread_key_create (&last_error_key, free_key);
2065 #ifndef HAVE_PTHREAD_CANCEL
2066 pthread_key_create (&signal_thread_key, free_key);
2067 #endif
2069 pthread_mutexattr_t attr;
2070 pthread_mutexattr_init (&attr);
2071 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
2072 pthread_mutex_init (&rcfile_mutex, &attr);
2073 global_config = config_parse (rcfile, 0);
2074 if (!global_config)
2076 pthread_mutexattr_destroy (&attr);
2077 pthread_mutex_destroy (&rcfile_mutex);
2078 exit (EXIT_FAILURE);
2081 p = config_get_string ("global", "gpg_homedir");
2082 if (!p)
2083 datadir = str_asprintf ("%s/.gnupg", homedir);
2084 else
2085 datadir = expand_homedir (p);
2087 xfree (p);
2088 if (mkdir (datadir, 0700) == -1 && errno != EEXIST)
2089 err (EXIT_FAILURE, "%s", datadir);
2091 if (gpgme_level != -1)
2093 char s[2] = { gpgme_level + '0', 0 };
2095 if (getenv ("GPGME_DEBUG"))
2096 log_write (_ ("Overriding GPGME_DEBUG environment with level %u!"),
2097 gpgme_level);
2099 gpgme_set_global_flag ("debug", s);
2102 rc = gpgme_set_engine_info (GPGME_PROTOCOL_OpenPGP, NULL, datadir);
2103 xfree (datadir);
2105 snprintf (buf, sizeof (buf), "%s/data", homedir);
2106 if (mkdir (buf, 0700) == -1 && errno != EEXIST)
2107 err (EXIT_FAILURE, "%s", buf);
2109 datadir = str_dup (buf);
2110 pthread_cond_init (&rcfile_cond, NULL);
2111 pthread_mutex_init (&cn_mutex, &attr);
2112 pthread_mutexattr_destroy (&attr);
2114 setup_logging ();
2116 x = config_get_int_param (global_config, "global", "priority", &exists);
2117 if (exists && x != atoi(INVALID_PRIORITY))
2119 errno = 0;
2120 if (setpriority (PRIO_PROCESS, 0, x) == -1)
2122 log_write ("setpriority(): %s",
2123 pwmd_strerror (gpg_error_from_errno (errno)));
2124 goto do_exit;
2127 #ifdef HAVE_MLOCKALL
2128 if (disable_mlock == 0 && mlockall (MCL_CURRENT | MCL_FUTURE) == -1)
2130 log_write ("mlockall(): %s",
2131 pwmd_strerror (gpg_error_from_errno (errno)));
2132 goto do_exit;
2134 #endif
2136 rc = cache_init ();
2137 if (rc)
2139 log_write ("pwmd: ERR %i: %s", rc, pwmd_strerror (rc));
2140 exit (EXIT_FAILURE);
2143 if (import)
2145 char **keyids = NULL, **sign_keyids = NULL;
2147 if (!outfile || !*outfile || argc != optind)
2148 usage (argv[0], EXIT_FAILURE);
2150 if (keyid)
2151 keyids = str_split (keyid, ",", 0);
2152 if (sign_keyid)
2153 sign_keyids = str_split (sign_keyid, ",", 0);
2154 rc = xml_import (import, outfile, keyids, sign_keyids, keyfile, keyparam, sym);
2155 strv_free (keyids);
2156 strv_free (sign_keyids);
2157 if (rc)
2159 if (gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
2160 rc = gpg_error (rc);
2162 log_write ("%s: %u: %s", import, rc, pwmd_strerror (rc));
2165 config_free (global_config);
2166 xfree (rcfile);
2167 exit (rc ? EXIT_FAILURE : EXIT_SUCCESS);
2170 p = config_get_string ("global", "socket_path");
2171 if (!p)
2172 p = str_asprintf ("%s/socket", homedir);
2174 socketarg = expand_homedir (p);
2175 xfree (p);
2177 if (!secure)
2178 disable_list_and_dump = config_get_boolean ("global",
2179 "disable_list_and_dump");
2180 else
2181 disable_list_and_dump = secure;
2183 cache_push = config_get_list ("global", "cache_push");
2185 while (optind < argc)
2187 if (strv_printf (&cache_push, "%s", argv[optind++]) == 0)
2188 errx (EXIT_FAILURE, "%s", pwmd_strerror (GPG_ERR_ENOMEM));
2191 if (strchr (socketarg, '/') == NULL)
2193 socketdir = getcwd (buf, sizeof (buf));
2194 socketname = str_dup (socketarg);
2195 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2197 else
2199 socketname = str_dup (strrchr (socketarg, '/'));
2200 socketname++;
2201 socketarg[strlen (socketarg) - strlen (socketname) - 1] = 0;
2202 socketdir = str_dup (socketarg);
2203 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2206 if (chdir (datadir))
2208 log_write ("%s: %s", datadir,
2209 pwmd_strerror (gpg_error_from_errno (errno)));
2210 unlink (socketpath);
2211 goto do_exit;
2214 x = test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 0,
2215 mode, terminate);
2216 if (!terminate && x)
2217 goto do_exit;
2218 else if (terminate)
2220 estatus = x != 1 ? EXIT_FAILURE : EXIT_SUCCESS;
2221 goto do_exit;
2225 * bind() doesn't like the full pathname of the socket or any non alphanum
2226 * characters so change to the directory where the socket is wanted then
2227 * create it then change to datadir.
2229 if (chdir (socketdir))
2231 log_write ("%s: %s", socketdir,
2232 pwmd_strerror (gpg_error_from_errno (errno)));
2233 goto do_exit;
2236 xfree (socketdir);
2238 if ((sockfd = socket (PF_UNIX, SOCK_STREAM, 0)) == -1)
2240 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2241 goto do_exit;
2244 addr.sun_family = AF_UNIX;
2245 snprintf (addr.sun_path, sizeof (addr.sun_path), "%s", socketname);
2246 do_unlink = 1;
2247 if (bind (sockfd, (struct sockaddr *) &addr, sizeof (struct sockaddr)) ==
2250 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2252 if (errno == EADDRINUSE)
2254 do_unlink = 0;
2255 log_write (_("Either there is another pwmd running or '%s' is a \n"
2256 "stale socket. Please remove it manually."), socketpath);
2259 goto do_exit;
2263 char *t = config_get_string ("global", "socket_perms");
2264 mode_t mask;
2266 if (t)
2268 mode = strtol (t, NULL, 8);
2269 mask = umask (0);
2270 xfree (t);
2272 if (chmod (socketname, mode) == -1)
2274 log_write ("%s: %s", socketname,
2275 pwmd_strerror (gpg_error_from_errno (errno)));
2276 close (sockfd);
2277 umask (mask);
2278 goto do_exit;
2281 umask (mask);
2285 xfree (--socketname);
2287 if (chdir (datadir))
2289 log_write ("%s: %s", datadir,
2290 pwmd_strerror (gpg_error_from_errno (errno)));
2291 close (sockfd);
2292 goto do_exit;
2295 xfree (datadir);
2296 #ifdef WITH_GNUTLS
2297 if (config_get_boolean ("global", "enable_tcp"))
2299 if (!tls_start_stop (0))
2301 close (sockfd);
2302 goto do_exit;
2305 #endif
2308 * Set the cache entry for a file. Prompts for the password.
2310 if (cache_push)
2312 for (opt = 0; cache_push[opt]; opt++)
2314 struct crypto_s *crypto = NULL;
2315 char *pw_file = config_get_string (cache_push[opt],
2316 "passphrase_file");
2317 gpg_error_t rc = crypto_init (&crypto, NULL, cache_push[opt],
2318 pw_file != NULL, pw_file);
2320 if (!rc)
2322 crypto->flags |= pw_file ? CRYPTO_FLAG_KEYFILE : 0;
2323 crypto->keyfile = pw_file;
2325 else
2326 xfree (pw_file);
2328 if (rc)
2330 estatus = EXIT_FAILURE;
2331 goto do_exit;
2334 rc = do_cache_push (crypto);
2335 if (rc && !force)
2337 log_write ("ERR %u: %s", rc, pwmd_strerror(rc));
2338 strv_free (cache_push);
2339 log_write (_ ("Failed to add a file to the cache. Use --force to force startup. Exiting."));
2340 cache_clear (NULL, NULL, 1);
2341 estatus = EXIT_FAILURE;
2342 crypto_free (crypto);
2343 goto do_exit;
2345 else if (rc)
2346 log_write ("%s: %s", crypto->filename, pwmd_strerror(rc));
2347 else
2348 log_write (_("Successfully added '%s' to the cache."),
2349 crypto->filename);
2351 crypto_free (crypto);
2354 strv_free (cache_push);
2355 log_write (!nofork ? _("Done. Daemonizing...") :
2356 _("Done. Waiting for connections..."));
2359 backlog = config_get_integer ("global", "backlog");
2360 if (listen (sockfd, backlog) == -1)
2362 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2363 goto do_exit;
2366 if (!nofork)
2368 switch (fork ())
2370 case -1:
2371 log_write ("fork(): %s",
2372 pwmd_strerror (gpg_error_from_errno (errno)));
2373 goto do_exit;
2374 case 0:
2375 close (0);
2376 close (1);
2377 close (2);
2378 setsid ();
2379 break;
2380 default:
2381 _exit (EXIT_SUCCESS);
2385 (void)test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 1,
2386 mode, 0);
2387 cmdline = 0;
2388 pthread_key_create (&thread_name_key, free_key);
2389 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
2390 estatus = server_loop (sockfd, &socketpath);
2392 do_exit:
2393 if (socketpath && do_unlink)
2395 unlink (socketpath);
2396 xfree (socketpath);
2399 xfree (socketarg);
2400 #ifdef WITH_GNUTLS
2401 gnutls_global_deinit ();
2402 tls_deinit_params ();
2403 #endif
2404 pthread_cond_destroy (&rcfile_cond);
2405 pthread_mutex_destroy (&rcfile_mutex);
2406 pthread_key_delete (last_error_key);
2407 #ifndef HAVE_PTHREAD_CANCEL
2408 pthread_key_delete (signal_thread_key);
2409 #endif
2411 if (global_config)
2412 config_free (global_config);
2414 free_invoking_users (invoking_users);
2415 xfree (rcfile);
2416 xfree (home_directory);
2417 xfree (homedir);
2418 xmlCleanupParser ();
2419 xmlCleanupGlobals ();
2421 if (pidfile)
2422 unlink (pidfile);
2423 xfree (pidfile);
2425 if (estatus == EXIT_SUCCESS && !terminate)
2426 log_write (_("pwmd exiting normally"));
2428 pthread_key_delete (thread_name_key);
2429 closelog ();
2431 if (log_fd != -1)
2432 close (log_fd);
2434 exit (estatus);
2437 gpg_error_t lock_flock (assuan_context_t ctx, const char *filename,
2438 int type, int *fd)
2440 gpg_error_t rc = 0;
2442 #ifdef HAVE_FLOCK
2443 *fd = open (filename, O_RDONLY);
2444 if (*fd == -1)
2445 return gpg_error_from_syserror ();
2447 TRY_FLOCK (ctx, *fd, type, rc);
2448 if (rc)
2450 close (*fd);
2451 *fd = -1;
2453 #endif
2455 return rc;
2458 void unlock_flock (int *fd)
2460 #ifdef HAVE_FLOCK
2461 if (*fd != -1)
2462 close (*fd);
2464 *fd = -1;
2465 #endif