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