TLS: Support rehandshake upon SIGHUP.
[libpwmd.git] / src / pwmd.c
blobe27c0b320a97f9552e2cea20373ada2590efcb12
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"
90 /* In tenths of a second. */
91 #define SIG_TIMEOUT 1
93 /* For (tcp_)accept_thread (usec). */
94 #define ACCEPT_TIMEOUT 50000
96 static int quit;
97 static int cmdline;
98 static jmp_buf jmp;
99 static int nofork;
100 static pthread_cond_t quit_cond;
101 static pthread_mutex_t quit_mutex;
102 static int log_fd;
103 static unsigned assuan_level;
105 #ifndef HAVE_PTHREAD_CANCEL
106 static pthread_key_t signal_thread_key;
107 #endif
109 pthread_t accept_tid;
110 #ifdef WITH_GNUTLS
111 static int tls_fd;
112 static int tls6_fd;
113 static int start_stop_tls (int term);
114 #endif
116 static gpg_error_t do_cache_push (struct crypto_s *crypto);
117 static int signal_loop (sigset_t sigset);
119 #ifndef HAVE_PTHREAD_CANCEL
120 #define INIT_SIGNAL(s, cb) do { \
121 struct sigaction act; \
122 sigset_t sigset; \
123 sigemptyset (&sigset); \
124 sigaddset (&sigset, s); \
125 pthread_sigmask (SIG_UNBLOCK, &sigset, NULL); \
126 memset (&act, 0, sizeof(act)); \
127 act.sa_flags = SA_SIGINFO; \
128 act.sa_mask = sigset; \
129 act.sa_sigaction = cb; \
130 sigaction (s, &act, NULL); \
131 } while (0)
132 #endif
134 #ifndef HAVE_PTHREAD_CANCEL
135 static void
136 catch_thread_signal (int sig, siginfo_t *info, void *ctx)
138 int *n = (int *) pthread_getspecific (signal_thread_key);
140 *n = 1;
141 pthread_setspecific (signal_thread_key, n);
143 #endif
145 static void
146 setup_logging ()
148 int n = config_get_boolean ("global", "enable_logging");
150 if (n)
152 char *p = config_get_string ("global", "log_path");
154 if (!p || (logfile && p && log_fd != -1 && strcmp(p, logfile)))
156 if (log_fd != -1)
157 close (log_fd);
159 log_fd = -1;
162 xfree (logfile);
163 logfile = NULL;
164 if (p)
165 logfile = expand_homedir (p);
166 xfree (p);
168 else
170 xfree (logfile);
171 logfile = NULL;
172 if (log_fd != -1)
173 close(log_fd);
175 log_fd = -1;
176 closelog ();
179 log_syslog = config_get_boolean ("global", "syslog");
180 if (log_syslog == 1)
181 openlog ("pwmd", LOG_NDELAY | LOG_PID, LOG_DAEMON);
184 static void *
185 reload_rcfile_thread (void *arg)
187 #ifndef HAVE_PTHREAD_CANCEL
188 int *n = xmalloc (sizeof (int));
190 *n = 0;
191 pthread_setspecific (signal_thread_key, n);
192 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
193 #endif
195 #ifdef HAVE_PR_SET_NAME
196 prctl (PR_SET_NAME, "reload rcfile");
197 #endif
198 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
199 MUTEX_LOCK (&rcfile_mutex);
201 for (;;)
203 struct slist_s *keep = NULL;
204 struct slist_s *config;
205 int b = disable_list_and_dump;
206 #ifdef WITH_GNUTLS
207 char *prio = config_get_string ("global", "tls_cipher_suite");
208 char *prio2 = NULL;
209 #endif
211 pthread_cleanup_push (cleanup_mutex_cb, &rcfile_mutex);
212 pthread_cond_wait (&rcfile_cond, &rcfile_mutex);
213 #ifndef HAVE_PTHREAD_CANCEL
214 int *cancel = (int *) pthread_getspecific (signal_thread_key);
215 if (*cancel)
216 pthread_exit (NULL);
217 #endif
219 keep = config_keep_save ();
220 log_write (_("reloading configuration file '%s'"), rcfile);
222 config = config_parse (rcfile, 1);
223 if (config)
225 config_free (global_config);
226 global_config = config;
227 setup_logging ();
230 config_keep_restore (keep);
231 disable_list_and_dump = !disable_list_and_dump ? b : 1;
233 #ifdef WITH_GNUTLS
234 /* Restart listening sockets since they may have changed. */
235 start_stop_tls (1);
236 start_stop_tls (0);
238 prio2 = config_get_string ("global", "tls_cipher_suite");
239 if ((prio2 && (!prio || strcmp (prio, prio2))) || (prio && !prio2))
240 tls_rehandshake ();
242 xfree (prio2);
243 xfree (prio);
244 #endif
245 crypto_set_keepalive ();
246 pthread_cleanup_pop (0);
249 MUTEX_UNLOCK (&rcfile_mutex);
250 return NULL;
253 gpg_error_t
254 send_error (assuan_context_t ctx, gpg_error_t e)
256 struct client_s *client = assuan_get_pointer (ctx);
258 if (gpg_err_source (e) == GPG_ERR_SOURCE_UNKNOWN)
259 e = gpg_error (e);
261 if (client)
262 client->last_rc = e;
264 if (!e)
265 return assuan_process_done (ctx, 0);
267 if (!ctx)
269 log_write ("ERR %i: %s", e, pwmd_strerror (e));
270 return e;
273 if (client && client->xml_error)
275 log_write ("%s", client->xml_error->message);
276 xfree (client->last_error);
277 client->last_error = NULL;
278 if (client->xml_error->message)
279 client->last_error = str_dup (client->xml_error->message);
281 e = assuan_process_done (ctx,
282 assuan_set_error (ctx, e,
283 client->xml_error->message ? client->xml_error->message : NULL));
284 xmlResetLastError ();
285 xmlResetError (client->xml_error);
286 xfree (client->xml_error);
287 client->xml_error = NULL;
288 return e;
291 return assuan_process_done (ctx,
292 assuan_set_error (ctx, e, pwmd_strerror (e)));
295 void
296 log_write (const char *fmt, ...)
298 char *args;
299 va_list ap;
300 time_t now;
301 char buf[255];
302 pthread_t tid = pthread_self ();
303 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
305 if ((!logfile && !isatty (STDERR_FILENO) && !log_syslog) || !fmt)
306 return;
308 pthread_mutex_lock (&m);
309 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock, &m);
311 if (!cmdline && logfile && log_fd == -1)
313 log_fd = open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600);
314 if (log_fd == -1)
315 warn ("%s", logfile);
318 va_start (ap, fmt);
320 if (str_vasprintf (&args, fmt, ap) != -1)
322 if (cmdline)
324 pthread_cleanup_push (xfree, args);
325 fprintf (stderr, "pwmd: %s\n", args);
326 fflush (stderr);
327 pthread_cleanup_pop (1);
329 else
331 char *name = pthread_getspecific (thread_name_key);
332 char *line;
334 pthread_cleanup_push (xfree, args);
335 snprintf (buf, sizeof (buf),
336 name && *name == '!' ? "%s: " : name ? "%s(%p): " : "%s",
337 name ? *name == '!' ? name+1 : name : "",
338 name && *name == '!' ? 0 : name ? (pthread_t *) tid : 0);
339 name = buf;
341 if (!cmdline && log_syslog && !nofork)
342 syslog (LOG_INFO, "%s%s", name, args);
344 time (&now);
345 struct tm *tm = localtime (&now);
346 char tbuf[21];
347 strftime (tbuf, sizeof (tbuf), "%b %d %Y %H:%M:%S ", tm);
348 tbuf[sizeof (tbuf) - 1] = 0;
350 if (args[strlen (args) - 1] == '\n')
351 args[strlen (args) - 1] = 0;
353 line = str_asprintf ("%s %i %s%s\n", tbuf, getpid (), name,
354 args);
355 pthread_cleanup_pop (1);
356 if (line)
358 pthread_cleanup_push (xfree, line);
359 if (logfile && log_fd != -1)
361 ssize_t ret = write (log_fd, line, strlen (line));
362 (void)ret;
363 fsync (log_fd);
366 if (nofork)
368 fprintf (stdout, "%s", line);
369 fflush (stdout);
372 pthread_cleanup_pop (1);
377 va_end (ap);
378 pthread_cleanup_pop (0);
380 if (log_fd != -1 && log_keepopen <= 0)
382 close(log_fd);
383 log_fd = -1;
386 pthread_mutex_unlock (&m);
389 static gpg_error_t
390 setup_crypto ()
392 gpg_error_t rc;
394 if (!gpgrt_check_version (REQUIRE_LIBGPGERROR_VERSION))
396 fprintf (stderr, _("gpgrt_check_version(): Incompatible libgpg-error. "
397 "Wanted %s, got %s.\n"), REQUIRE_LIBGPGERROR_VERSION,
398 gpgrt_check_version (NULL));
399 return GPG_ERR_UNKNOWN_VERSION;
402 gpgrt_init ();
403 gpgrt_set_alloc_func (xrealloc_gpgrt);
405 if (!assuan_check_version (REQUIRE_LIBASSUAN_VERSION))
407 fprintf (stderr, _("assuan_check_version(): Incompatible libassuan. "
408 "Wanted %s, got %s.\n"), REQUIRE_LIBASSUAN_VERSION,
409 assuan_check_version (NULL));
410 return GPG_ERR_UNKNOWN_VERSION;
413 if (!gcry_check_version (REQUIRE_LIBGCRYPT_VERSION))
415 fprintf (stderr, _("gcry_check_version(): Incompatible libgcrypt. "
416 "Wanted %s, got %s.\n"), REQUIRE_LIBGCRYPT_VERSION,
417 gcry_check_version (NULL));
418 return GPG_ERR_UNKNOWN_VERSION;
421 gcry_set_allocation_handler (xmalloc, xmalloc, NULL, xrealloc, xfree);
423 if (!gpgme_check_version (REQUIRE_LIBGPGME_VERSION))
425 fprintf (stderr, _("gpgme_check_version(): Incompatible libgpgme. "
426 "Wanted %s, got %s.\n"), REQUIRE_LIBGPGME_VERSION,
427 gpgme_check_version (NULL));
428 return GPG_ERR_UNKNOWN_VERSION;
431 rc = gpgme_engine_check_version (GPGME_PROTOCOL_OPENPGP);
432 if (rc)
434 fprintf (stderr, _("gpgme_engine_check_version(GPGME_PROTOCOL_OPENPGP): %s"), gpgme_strerror (rc));
435 return GPG_ERR_UNKNOWN_VERSION;
438 //gpgme_set_global_flag ("require-gnupg", REQUIRE_GNUPG_VERSION);
439 #ifdef ENABLE_NLS
440 gpgme_set_locale (NULL, LC_CTYPE, setlocale (LC_CTYPE, NULL));
441 gpgme_set_locale (NULL, LC_MESSAGES, setlocale (LC_MESSAGES, NULL));
442 #endif
444 #ifdef WITH_GNUTLS
445 if (gnutls_global_init ())
447 fprintf(stderr, _("gnutls_global_init() failed.\n"));
448 return GPG_ERR_UNKNOWN_VERSION;
451 if (!gnutls_check_version (REQUIRE_LIBGNUTLS_VERSION))
453 fprintf (stderr, _("gnutls_check_version(): Incompatible libgnutls. "
454 "Wanted %s, got %s.\n"), REQUIRE_LIBGNUTLS_VERSION,
455 gnutls_check_version (NULL));
456 return GPG_ERR_UNKNOWN_VERSION;
459 gnutls_global_set_log_function (tls_log);
460 gnutls_global_set_audit_log_function (tls_audit_log);
461 #endif
462 return 0;
465 gpg_error_t
466 do_validate_peer (assuan_context_t ctx, const char *section,
467 assuan_peercred_t * peer)
469 char **users;
470 int allowed = 0;
471 gpg_error_t rc;
472 struct client_s *client = assuan_get_pointer (ctx);
474 if (!client)
475 return GPG_ERR_FORBIDDEN;
477 #ifdef WITH_GNUTLS
478 if (client->thd->remote)
479 return tls_validate_access (client, section);
480 #endif
482 rc = assuan_get_peercred (ctx, peer);
483 if (rc)
484 return rc;
486 users = config_get_list (section, "allowed");
487 if (users)
489 for (char **p = users; !rc && *p; p++)
491 rc = acl_check_common(client, *p, (*peer)->uid, (*peer)->gid,
492 &allowed);
495 strv_free (users);
497 else if (client->no_access_param)
498 allowed = 1;
500 return allowed && !rc ? 0 : rc ? rc : GPG_ERR_FORBIDDEN;
503 /* Test if uid is a member of group 'name'. Invert when 'not' is true. */
504 #ifdef HAVE_GETGRNAM_R
505 static gpg_error_t
506 acl_check_group (const char *name, uid_t uid, gid_t gid, int not, int *allowed)
508 char *buf;
509 struct group gr, *gresult;
510 size_t len = sysconf (_SC_GETGR_R_SIZE_MAX);
511 int err;
512 gpg_error_t rc = 0;
514 if (len == -1)
515 len = 16384;
517 buf = xmalloc (len);
518 if (!buf)
519 return GPG_ERR_ENOMEM;
521 err = getgrnam_r (name, &gr, buf, len, &gresult);
522 if (!err && gresult)
524 if (gresult->gr_gid == gid)
526 xfree (buf);
527 *allowed = !not;
528 return 0;
531 for (char **t = gresult->gr_mem; !rc && *t; t++)
533 char *tbuf;
534 struct passwd pw;
535 struct passwd *result = get_pwd_struct (*t, 0, &pw, &tbuf, &rc);
537 if (!rc && result && result->pw_uid == uid)
539 xfree (tbuf);
540 *allowed = !not;
541 break;
544 xfree (tbuf);
547 xfree (buf);
548 return rc;
550 else if (err)
551 rc = gpg_error_from_errno (err);
553 xfree (buf);
554 return rc ? rc : !gresult ? 0 : GPG_ERR_EACCES;
556 #else
557 static gpg_error_t
558 acl_check_group (const char *name, uid_t uid, gid_t gid, int not, int *allowed)
560 struct group *gresult;
561 gpg_error_t rc = 0;
563 errno = 0;
564 gresult = getgrnam (name);
565 if (!errno && gresult && gresult->gr_gid == gid)
567 *allowed = !not;
568 return 0;
570 else if (errno)
571 rc = gpg_error_from_syserror ();
572 else if (!gresult)
573 return 0;
575 for (char **t = gresult->gr_mem; !rc && *t; t++)
577 char *buf;
578 struct passwd pw;
579 struct passwd *result = get_pwd_struct (*t, 0, &pw, &buf, &rc);
581 if (!rc && result && result->pw_uid == uid)
583 xfree (buf);
584 *allowed = !not;
585 break;
588 xfree (buf);
591 return rc;
593 #endif
595 gpg_error_t
596 peer_is_invoker(struct client_s *client)
598 struct invoking_user_s *user;
599 int allowed = 0;
601 if (client->thd->state == CLIENT_STATE_UNKNOWN)
602 return GPG_ERR_EACCES;
604 for (user = invoking_users; user; user = user->next)
606 #ifdef WITH_GNUTLS
607 if (client->thd->remote)
609 if (user->type == INVOKING_TLS
610 && !strcmp(client->thd->tls->fp, user->id))
611 allowed = user->not ? 0 : 1;
613 continue;
615 #endif
617 if (user->type == INVOKING_GID)
619 gpg_error_t rc = acl_check_group (user->id,
620 client->thd->peer->uid,
621 client->thd->peer->gid,
622 user->not, &allowed);
623 if (rc)
624 return rc;
626 else if (user->type == INVOKING_UID && client->thd->peer->uid == user->uid)
627 allowed = user->not ? 0 : 1;
630 return allowed ? 0 : GPG_ERR_EACCES;
633 #ifdef HAVE_GETGRNAM_R
634 gpg_error_t
635 acl_check_common (struct client_s *client, const char *user, uid_t uid,
636 gid_t gid, int *allowed)
638 int not = 0;
639 int rw = 0;
640 int tls = 0;
641 gpg_error_t rc = 0;
643 if (!user || !*user)
644 return 0;
646 if (*user == '-' || *user == '!')
647 not = 1;
649 if (*user == '+') // not implemented yet
650 rw = 1;
652 if (*user == '#') // TLS fingerprint hash
653 tls = 1;
655 if (not || rw || tls)
656 user++;
658 if (tls)
660 #ifdef WITH_GNUTLS
661 if (client->thd->remote)
663 if (!strcasecmp (client->thd->tls->fp, user))
664 *allowed = !not;
667 return 0;
668 #else
669 return 0;
670 #endif
672 #ifdef WITH_GNUTLS
673 else if (client->thd->remote) // Remote client with no FP in the ACL
674 return 0;
675 #endif
677 if (*user == '@') // all users in group
678 return acl_check_group (user+1, uid, gid, not, allowed);
679 else
681 char *buf;
682 struct passwd pw;
683 struct passwd *pwd = get_pwd_struct (user, 0, &pw, &buf, &rc);
685 if (!rc && pwd && pwd->pw_uid == uid)
686 *allowed = !not;
688 xfree (buf);
691 return rc;
693 #else
694 gpg_error_t
695 acl_check_common (struct client_s *client, const char *user, uid_t uid,
696 gid_t gid, int *allowed)
698 gpg_error_t rc = 0;
699 int not = 0;
700 int rw = 0;
701 int tls = 0;
703 if (!user || !*user)
704 return 0;
706 if (*user == '-' || *user == '!')
707 not = 1;
709 if (*user == '+') // not implemented yet
710 rw = 1;
712 if (*user == '#') // TLS fingerprint hash
713 tls = 1;
715 if (not || rw || tls)
716 user++;
718 if (tls)
720 #ifdef WITH_GNUTLS
721 if (client->thd->remote)
723 if (!strcasecmp (client->thd->tls->fp, user))
724 *allowed = !not;
727 return 0;
728 #else
729 return 0;
730 #endif
733 if (*user == '@') // all users in group
734 return acl_check_group (user+1, uid, gid, not, allowed);
735 else
737 char *buf;
738 struct passwd pw;
739 struct passwd *result = get_pwd_struct (user, 0, &pw, &buf, &rc);
741 if (!rc && result && result->pw_uid == uid)
742 *allowed = !not;
744 xfree (buf);
747 return rc;
749 #endif
751 static gpg_error_t
752 validate_peer (struct client_s *cl)
754 gpg_error_t rc;
756 #ifdef WITH_GNUTLS
757 if (cl->thd->remote)
758 return tls_validate_access (cl, NULL);
759 #endif
761 MUTEX_LOCK (&cn_mutex);
762 rc = do_validate_peer (cl->ctx, "global", &cl->thd->peer);
763 MUTEX_UNLOCK (&cn_mutex);
764 log_write ("peer %s: uid=%i, gid=%i, pid=%i, rc=%u",
765 !rc ? _("accepted") : _("rejected"), cl->thd->peer->uid,
766 cl->thd->peer->gid, cl->thd->peer->pid, rc);
767 return rc;
770 static void
771 xml_error_cb (void *data, xmlErrorPtr e)
773 struct client_s *client = data;
776 * Keep the first reported error as the one to show in the error
777 * description. Reset in send_error().
779 if (client->xml_error)
780 return;
782 client->xml_error = xcalloc (1, sizeof(xmlError));
783 xmlCopyError (e, client->xml_error);
786 static pid_t
787 hook_waitpid (assuan_context_t ctx, pid_t pid, int action,
788 int *status, int options)
790 return waitpid (pid, status, options);
793 static ssize_t
794 hook_read (assuan_context_t ctx, assuan_fd_t fd, void *data, size_t len)
796 #ifdef WITH_GNUTLS
797 struct client_s *client = assuan_get_pointer (ctx);
799 if (client->thd->remote)
800 return tls_read_hook (ctx, (int) fd, data, len);
801 #endif
803 return read ((int) fd, data, len);
806 static ssize_t
807 hook_write (assuan_context_t ctx, assuan_fd_t fd,
808 const void *data, size_t len)
810 #ifdef WITH_GNUTLS
811 struct client_s *client = assuan_get_pointer (ctx);
813 if (client->thd->remote)
814 return tls_write_hook (ctx, (int) fd, data, len);
815 #endif
817 return write ((int) fd, data, len);
821 assuan_log_cb (assuan_context_t ctx, void *data, unsigned cat,
822 const char *msg)
824 struct client_s *client = data;
825 char *str = NULL;
827 (void)client;
829 if (!(assuan_level & cat))
830 return 0;
832 if (!msg)
833 return 1;
835 switch (cat)
837 case ASSUAN_LOG_INIT:
838 str = "ASSUAN[INIT]";
839 break;
840 case ASSUAN_LOG_CTX:
841 str = "ASSUAN[CTX]";
842 break;
843 case ASSUAN_LOG_ENGINE:
844 str = "ASSUAN[ENGINE]";
845 break;
846 case ASSUAN_LOG_DATA:
847 str = "ASSUAN[DATA]";
848 break;
849 case ASSUAN_LOG_SYSIO:
850 str = "ASSUAN[SYSIO]";
851 break;
852 case ASSUAN_LOG_CONTROL:
853 str = "ASSUAN[CONTROL]";
854 break;
855 default:
856 str = "ASSUAN[UNKNOWN]";
857 break;
860 log_write ("%s: %s", str, msg);
861 return 1;
864 static int
865 new_connection (struct client_s *cl)
867 gpg_error_t rc;
868 static struct assuan_malloc_hooks mhooks = { xmalloc, xrealloc, xfree };
869 static struct assuan_system_hooks shooks = {
870 ASSUAN_SYSTEM_HOOKS_VERSION,
871 __assuan_usleep,
872 __assuan_pipe,
873 __assuan_close,
874 hook_read,
875 hook_write,
876 //FIXME
877 NULL, //recvmsg
878 NULL, //sendmsg both are used for FD passing
879 __assuan_spawn,
880 hook_waitpid,
881 __assuan_socketpair,
882 __assuan_socket,
883 __assuan_connect
886 #ifdef WITH_GNUTLS
887 if (cl->thd->remote)
889 char *prio = config_get_string ("global", "tls_cipher_suite");
891 cl->thd->timeout = config_get_integer ("global", "tls_timeout");
892 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
893 return 0;
895 cl->thd->tls = tls_init_client (cl->thd->fd, cl->thd->timeout, prio);
896 xfree (prio);
897 if (!cl->thd->tls)
898 return 0;
900 #endif
902 rc = assuan_new_ext (&cl->ctx, GPG_ERR_SOURCE_DEFAULT, &mhooks,
903 assuan_log_cb, cl);
904 if (rc)
905 goto fail;
907 assuan_ctx_set_system_hooks (cl->ctx, &shooks);
908 rc = assuan_init_socket_server (cl->ctx, cl->thd->fd, 2);
909 if (rc)
910 goto fail;
912 assuan_set_pointer (cl->ctx, cl);
913 assuan_set_hello_line (cl->ctx, PACKAGE_STRING);
914 rc = register_commands (cl->ctx);
915 if (rc)
916 goto fail;
918 rc = assuan_accept (cl->ctx);
919 if (rc)
920 goto fail;
922 rc = validate_peer (cl);
923 /* May not be implemented on all platforms. */
924 if (rc && gpg_err_code (rc) != GPG_ERR_ASS_GENERAL)
925 goto fail;
927 MUTEX_LOCK (&cn_mutex);
928 cl->thd->state = CLIENT_STATE_INIT;
929 MUTEX_UNLOCK (&cn_mutex);
930 cl->lock_timeout = config_get_integer ("global", "lock_timeout");
931 xmlSetStructuredErrorFunc (cl, xml_error_cb);
932 return 1;
934 fail:
935 log_write ("%s", pwmd_strerror (rc));
936 return 0;
940 * This is called after a client_thread() terminates. Set with
941 * pthread_cleanup_push().
943 static void
944 cleanup_cb (void *arg)
946 struct client_thread_s *cn = arg;
947 struct client_s *cl = cn->cl;
949 MUTEX_LOCK (&cn_mutex);
950 cn_thread_list = slist_remove (cn_thread_list, cn);
951 MUTEX_UNLOCK (&cn_mutex);
953 if (cl)
955 unlock_flock (&cl->flock_fd);
956 cleanup_client (cl);
957 if (cl->xml_error)
958 xmlResetError (cl->xml_error);
960 xfree (cl->xml_error);
962 #ifdef WITH_GNUTLS
963 if (cn->tls)
965 gnutls_deinit (cn->tls->ses);
966 xfree (cn->tls->fp);
967 xfree (cn->tls);
969 #endif
971 if (!cn->atfork && cl->ctx)
972 assuan_release (cl->ctx);
973 else if (!cn->atfork && cl->thd && cl->thd->fd != -1)
974 close (cl->thd->fd);
976 if (cl->crypto)
977 crypto_free (cl->crypto);
979 cl->crypto = NULL;
980 xfree (cl);
982 else
984 if (cn->fd != -1)
985 close (cn->fd);
988 while (cn->msg_queue)
990 struct status_msg_s *msg = cn->msg_queue;
992 cn->msg_queue = msg->next;
993 xfree (msg->line);
994 xfree (msg);
997 if (!cn->atfork && cn->status_msg_pipe[0] != -1)
998 close (cn->status_msg_pipe[0]);
1000 if (!cn->atfork && cn->status_msg_pipe[1] != -1)
1001 close (cn->status_msg_pipe[1]);
1003 pthread_mutex_destroy (&cn->status_mutex);
1005 if (!cn->atfork)
1007 log_write (_("exiting, fd=%i"), cn->fd);
1008 send_status_all (STATUS_CLIENTS, NULL);
1011 xfree (cn->name);
1012 #ifdef WITH_GNUTLS
1013 xfree (cn->peeraddr);
1014 #endif
1015 xfree (cn);
1016 pthread_cond_signal (&quit_cond);
1019 void
1020 cleanup_all_clients (int atfork)
1022 /* This function may be called from pthread_atfork() which requires
1023 reinitialization. */
1024 if (atfork)
1026 pthread_mutexattr_t attr;
1028 pthread_mutexattr_init (&attr);
1029 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
1030 pthread_mutex_init (&cn_mutex, &attr);
1031 pthread_mutexattr_destroy (&attr);
1032 cache_mutex_init ();
1035 MUTEX_LOCK (&cn_mutex);
1037 while (slist_length (cn_thread_list))
1039 struct client_thread_s *thd = slist_nth_data (cn_thread_list, 0);
1041 thd->atfork = atfork;
1042 cleanup_cb (thd);
1045 exiting = 1;
1046 MUTEX_UNLOCK (&cn_mutex);
1047 cache_deinit (atfork);
1050 static gpg_error_t
1051 send_msg_queue (struct client_thread_s *thd)
1053 MUTEX_LOCK (&thd->status_mutex);
1054 gpg_error_t rc = 0;
1055 char c;
1056 ssize_t ret;
1058 ret = read (thd->status_msg_pipe[0], &c, 1);
1059 rc = gpg_error_from_syserror ();
1060 if (ret == -1 && gpg_err_code (rc) != GPG_ERR_EAGAIN)
1061 log_write ("%s (%i): %s", __FUNCTION__, __LINE__, pwmd_strerror (rc));
1062 else
1063 rc = 0;
1065 thd->wrote_status = 0;
1067 while (thd->msg_queue)
1069 struct status_msg_s *msg = thd->msg_queue;
1071 #ifndef HAVE_PTHREAD_CANCEL
1072 if (thd->fd == -1)
1073 break;
1074 #endif
1076 thd->msg_queue = thd->msg_queue->next;
1077 MUTEX_UNLOCK (&thd->status_mutex);
1078 rc = send_status (thd->cl->ctx, msg->s, msg->line);
1079 MUTEX_LOCK (&thd->status_mutex);
1080 xfree (msg->line);
1081 xfree (msg);
1083 if (rc)
1084 break;
1087 MUTEX_UNLOCK (&thd->status_mutex);
1088 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1089 log_write ("%s (%i): %s", __FUNCTION__, __LINE__, pwmd_strerror (rc));
1091 return rc;
1094 static void *
1095 client_thread (void *data)
1097 struct client_thread_s *thd = data;
1098 struct client_s *cl = xcalloc (1, sizeof (struct client_s));
1100 #ifdef HAVE_PR_SET_NAME
1101 prctl (PR_SET_NAME, "client");
1102 #endif
1103 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1105 if (!cl)
1107 log_write ("%s(%i): %s", __FILE__, __LINE__,
1108 pwmd_strerror (GPG_ERR_ENOMEM));
1109 return NULL;
1112 MUTEX_LOCK (&cn_mutex);
1113 pthread_cleanup_push (cleanup_cb, thd);
1114 thd->cl = cl;
1115 cl->thd = thd;
1116 cl->flock_fd = -1;
1117 MUTEX_UNLOCK (&cn_mutex);
1119 if (new_connection (cl))
1121 int finished = 0;
1122 gpg_error_t rc;
1123 struct pollfd fds[2];
1125 fds[0].fd = thd->fd;
1126 fds[0].events = POLLIN;
1127 fds[1].fd = thd->status_msg_pipe[0];
1128 fds[1].events = POLLIN;
1130 send_status_all (STATUS_CLIENTS, NULL);
1131 rc = send_status (cl->ctx, STATUS_CACHE, NULL);
1132 if (rc)
1134 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
1135 finished = 1;
1138 while (!finished)
1140 int n;
1141 int eof;
1143 n = poll (fds, 2, 100);
1144 if (n == -1)
1146 log_write ("%s", strerror (errno));
1147 break;
1150 #ifdef WITH_GNUTLS
1151 if (thd->remote && thd->tls && thd->tls->rehandshake)
1153 char *prio;
1154 int ret;
1155 const char *e;
1157 if (thd->tls->rehandshake == 1)
1159 prio = config_get_string ("global", "tls_cipher_suite");
1160 if (!prio)
1162 thd->tls->rehandshake = 0;
1163 continue;
1166 ret = gnutls_priority_set_direct (thd->tls->ses, prio, &e);
1167 if (ret == GNUTLS_E_SUCCESS)
1169 rc = send_status (cl->ctx, STATUS_REHANDSHAKE, NULL);
1170 if (!rc)
1172 rc = assuan_send_data (cl->ctx, NULL, 0);
1173 if (!rc)
1175 ret = gnutls_rehandshake (thd->tls->ses);
1176 if (ret)
1178 log_write ("%s", gnutls_strerror (ret));
1179 thd->tls->rehandshake = 0;
1181 else
1182 thd->tls->rehandshake = 2;
1186 if (rc)
1187 log_write ("%s", pwmd_strerror (rc));
1189 else
1190 log_write ("%s: %s", gnutls_strerror (ret), e);
1192 xfree (prio);
1193 continue;
1196 #endif
1198 if (!n)
1199 continue;
1201 if (fds[1].revents & POLLIN)
1203 #ifdef WITH_GNUTLS
1204 if (!thd->remote || (thd->tls && !thd->tls->rehandshake))
1205 #endif
1207 rc = send_msg_queue (thd);
1208 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1209 break;
1213 #ifdef HAVE_PTHREAD_CANCEL
1214 if (!(fds[0].revents & POLLIN))
1215 #else
1216 if (thd->fd != -1 && !(fds[0].revents & POLLIN))
1217 #endif
1218 continue;
1220 rc = assuan_process_next (cl->ctx, &eof);
1221 if (rc || eof)
1223 if (gpg_err_code (rc) == GPG_ERR_EOF || eof)
1224 break;
1226 log_write ("assuan_process_next(): rc=%u %s", rc,
1227 pwmd_strerror (rc));
1228 if (rc == gpg_error (GPG_ERR_ETIMEDOUT))
1229 break;
1231 rc = send_error (cl->ctx, rc);
1232 if (rc)
1234 log_write ("assuan_process_done(): rc=%u %s", rc,
1235 pwmd_strerror (rc));
1236 break;
1240 /* Since the msg queue pipe fd's are non-blocking, check for
1241 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1242 * client has already disconnected and will be converted to
1243 * GPG_ERR_EOF during assuan_process_next().
1245 #ifdef WITH_GNUTLS
1246 if (!thd->remote || (thd->tls && !thd->tls->rehandshake))
1247 #endif
1249 rc = send_msg_queue (thd);
1250 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1251 break;
1256 /* Don't do pthread_exit() here because any set pthread_cleanup_push
1257 * functions would be called after a command failed but then the client
1258 * exited normally which may lead to a double free. */
1259 pthread_cleanup_pop (1);
1260 return NULL;
1263 static gpg_error_t
1264 xml_import (const char *filename, const char *outfile, char **keyid,
1265 char **sign_keyid, char *keyfile, const char *keyparam,
1266 int symmetric)
1268 xmlDocPtr doc;
1269 int fd;
1270 struct stat st;
1271 int len;
1272 xmlChar *xmlbuf;
1273 gpg_error_t rc = 0;
1274 struct crypto_s *crypto = NULL;
1276 if (stat (filename, &st) == -1)
1278 rc = gpg_error_from_errno (errno);
1279 return rc;
1282 fd = open (filename, O_RDONLY);
1283 if (fd == -1)
1284 return gpg_error_from_errno (errno);
1286 xmlbuf = xmalloc (st.st_size + 1);
1287 if (!xmlbuf)
1289 close (fd);
1290 return GPG_ERR_ENOMEM;
1293 if (read (fd, xmlbuf, st.st_size) == -1)
1295 rc = gpg_error_from_errno (errno);
1296 close (fd);
1297 xfree (xmlbuf);
1298 return rc;
1301 close (fd);
1302 xmlbuf[st.st_size] = 0;
1303 // Be sure the document validates.
1304 doc = xmlReadDoc (xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS);
1305 xfree (xmlbuf);
1306 if (!doc)
1307 return GPG_ERR_BAD_DATA;
1309 xmlNodePtr n = xmlDocGetRootElement (doc);
1310 if (n && !xmlStrEqual (n->name, (xmlChar *) "pwmd"))
1311 rc = GPG_ERR_BAD_DATA;
1313 if (!rc)
1315 rc = xml_validate_import (NULL, n ? n->children : n);
1316 if (!rc)
1318 rc = crypto_init (&crypto, NULL, filename, keyfile != NULL, keyfile);
1319 if (!rc)
1321 if (keyfile)
1323 crypto->flags |= CRYPTO_FLAG_KEYFILE;
1324 crypto->keyfile = str_dup (keyfile);
1327 xmlDocDumpMemory (doc, &crypto->plaintext, &len);
1328 if (len > 0)
1329 crypto->plaintext_size = len;
1330 else
1331 rc = GPG_ERR_ENOMEM;
1336 if (!rc)
1338 if (!symmetric && (keyparam || !keyid))
1340 char *buf = NULL;
1342 if (keyparam)
1344 fd = open (keyparam, O_RDONLY);
1345 if (fd == -1)
1346 rc = gpg_error_from_errno (errno);
1348 if (!rc)
1350 if (stat (keyparam, &st) == -1)
1351 rc = gpg_error_from_errno (errno);
1353 if (!rc)
1355 buf = xmalloc (st.st_size+1);
1356 if (!buf)
1357 rc = GPG_ERR_ENOMEM;
1359 if (!rc)
1361 len = read (fd, buf, st.st_size);
1362 if (len != st.st_size)
1363 rc = gpg_error_from_errno (errno);
1365 if (!rc)
1366 buf[len] = 0;
1371 if (fd != -1)
1372 close (fd);
1374 else
1376 buf = crypto_default_key_params ();
1377 if (!buf)
1378 rc = GPG_ERR_ENOMEM;
1381 if (!rc)
1382 rc = crypto_genkey (NULL, crypto, (unsigned char *)buf);
1384 xfree (buf);
1386 else
1388 crypto->save.pubkey = strv_dup (keyid);
1389 crypto->save.sigkey = strv_dup (sign_keyid);
1392 if (!rc)
1394 crypto->flags |= symmetric ? CRYPTO_FLAG_SYMMETRIC : 0;
1395 rc = crypto_encrypt (NULL, crypto);
1399 if (!rc)
1401 if (!strcmp (outfile, "-"))
1402 outfile = NULL;
1404 xfree (crypto->plaintext);
1405 crypto->plaintext = NULL;
1406 xfree (crypto->filename);
1407 crypto->filename = outfile ? str_dup (outfile) : NULL;
1408 rc = crypto_write_file (crypto);
1411 xmlFreeDoc (doc);
1412 crypto_free (crypto);
1413 return rc;
1416 static gpg_error_t
1417 do_cache_push (struct crypto_s *crypto)
1419 gpg_error_t rc;
1420 xmlDocPtr doc;
1421 struct cache_data_s *cdata;
1422 unsigned char *crc;
1423 size_t len;
1424 int fd = -1;
1426 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1427 crypto->filename);
1429 if (valid_filename (crypto->filename) == 0)
1431 log_write (_("%s: Invalid characters in filename"), crypto->filename);
1432 return GPG_ERR_INV_VALUE;
1435 rc = lock_flock (NULL, crypto->filename, LOCK_SH, &fd);
1436 if (!rc)
1437 rc = crypto_decrypt (NULL, crypto);
1438 if (rc)
1440 unlock_flock (&fd);
1441 return rc;
1444 rc = xml_parse_doc ((char *) crypto->plaintext, crypto->plaintext_size, &doc);
1445 if (rc)
1447 unlock_flock (&fd);
1448 log_write ("%s", pwmd_strerror (rc));
1449 return rc;
1452 cdata = xcalloc (1, sizeof (struct cache_data_s));
1453 if (!cdata)
1455 unlock_flock (&fd);
1456 xmlFreeDoc (doc);
1457 return GPG_ERR_ENOMEM;
1460 rc = get_checksum (crypto->filename, &crc, &len);
1461 unlock_flock (&fd);
1462 if (rc)
1464 xmlFreeDoc (doc);
1465 free_cache_data_once (cdata);
1466 return rc;
1469 cdata->crc = crc;
1470 rc = cache_encrypt (crypto);
1471 if (!rc)
1473 cdata->doc = crypto->plaintext;
1474 cdata->size = crypto->plaintext_size;
1475 crypto->plaintext = NULL;
1476 cdata->pubkey = crypto->pubkey;
1477 cdata->sigkey = crypto->sigkey;
1478 crypto->pubkey = NULL;
1479 crypto->sigkey = NULL;
1481 else
1483 xmlFreeDoc (doc);
1484 free_cache_data_once (cdata);
1485 return rc;
1488 int timeout = config_get_integer (crypto->filename, "cache_timeout");
1489 rc = cache_add_file (crypto->filename, cdata, timeout);
1490 return rc;
1493 static gpg_error_t
1494 init_client (int fd, const char *addr)
1496 gpg_error_t rc = 0;
1497 struct client_thread_s *new = xcalloc (1, sizeof (struct client_thread_s));
1499 if (!new)
1501 close (fd);
1502 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (ENOMEM));
1503 return GPG_ERR_ENOMEM;
1506 MUTEX_LOCK (&cn_mutex);
1507 new->conntime = time (NULL);
1508 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
1510 if (pipe (new->status_msg_pipe) == -1)
1511 rc = gpg_error_from_errno (errno);
1513 if (!rc)
1515 if (fcntl (new->status_msg_pipe[0], F_SETFL, O_NONBLOCK) == -1)
1516 rc = gpg_error_from_errno (errno);
1518 if (!rc)
1519 if (fcntl (new->status_msg_pipe[1], F_SETFL, O_NONBLOCK) == -1)
1520 rc = gpg_error_from_errno (errno);
1522 pthread_mutex_init (&new->status_mutex, NULL);
1525 if (!rc)
1527 #ifdef WITH_GNUTLS
1528 new->remote = addr ? 1 : 0;
1529 #endif
1530 new->fd = fd;
1531 rc = create_thread (client_thread, new, &new->tid, 1);
1532 if (rc)
1534 close (new->status_msg_pipe[0]);
1535 close (new->status_msg_pipe[1]);
1536 pthread_mutex_destroy (&new->status_mutex);
1540 if (!rc)
1542 struct slist_s *list = slist_append (cn_thread_list, new);
1544 if (list)
1546 cn_thread_list = list;
1547 if (addr)
1549 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1550 (pthread_t *) new->tid, fd, addr);
1551 #ifdef WITH_GNUTLS
1552 new->peeraddr = str_dup (addr);
1553 #endif
1555 else
1556 log_write (_("new connection: tid=%p, fd=%i"),
1557 (pthread_t *) new->tid, fd);
1559 else
1560 rc = GPG_ERR_ENOMEM;
1563 pthread_cleanup_pop (1);
1565 if (rc)
1567 xfree (new);
1568 close (fd);
1569 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1570 pwmd_strerror (rc));
1572 return rc;
1575 #ifdef WITH_GNUTLS
1576 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1577 static void *
1578 get_in_addr (struct sockaddr *sa)
1580 if (sa->sa_family == AF_INET)
1581 return &(((struct sockaddr_in *) sa)->sin_addr);
1583 return &(((struct sockaddr_in6 *) sa)->sin6_addr);
1586 static int
1587 start_stop_tls_with_protocol (int ipv6, int term)
1589 struct addrinfo hints, *servinfo, *p;
1590 int port = config_get_integer ("global", "tcp_port");
1591 char buf[7];
1592 int n;
1593 int *fd = ipv6 ? &tls6_fd : &tls_fd;
1595 if (term || config_get_boolean ("global", "enable_tcp") == 0)
1597 if (tls6_fd != -1)
1599 shutdown (tls6_fd, SHUT_RDWR);
1600 close (tls6_fd);
1601 tls6_fd = -1;
1604 if (tls_fd != -1)
1606 shutdown (tls_fd, SHUT_RDWR);
1607 close (tls_fd);
1608 tls_fd = -1;
1611 return 0;
1614 memset (&hints, 0, sizeof (hints));
1615 hints.ai_family = ipv6 ? AF_INET6 : AF_INET;
1616 hints.ai_socktype = SOCK_STREAM;
1617 hints.ai_flags = AI_PASSIVE;
1618 snprintf (buf, sizeof (buf), "%i", port);
1620 if ((n = getaddrinfo (NULL, buf, &hints, &servinfo)) == -1)
1622 log_write ("getaddrinfo(): %s", gai_strerror (n));
1623 return 0;
1626 for (n = 0, p = servinfo; p != NULL; p = p->ai_next)
1628 int r = 1;
1630 if ((ipv6 && p->ai_family != AF_INET6)
1631 || (!ipv6 && p->ai_family != AF_INET))
1632 continue;
1634 if ((*fd = socket (p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
1636 log_write ("socket(): %s", strerror (errno));
1637 continue;
1640 if (setsockopt (*fd, SOL_SOCKET, SO_REUSEADDR, &r, sizeof (int)) == -1)
1642 log_write ("setsockopt(): %s",
1643 pwmd_strerror (gpg_error_from_errno (errno)));
1644 freeaddrinfo (servinfo);
1645 goto fail;
1648 if (bind (*fd, p->ai_addr, p->ai_addrlen) == -1)
1650 close (*fd);
1651 log_write ("bind(): %s",
1652 pwmd_strerror (gpg_error_from_errno (errno)));
1653 continue;
1656 n++;
1657 break;
1660 freeaddrinfo (servinfo);
1662 if (!n)
1663 goto fail;
1665 #if HAVE_DECL_SO_BINDTODEVICE != 0
1666 char *tmp = config_get_string ("global", "tcp_interface");
1667 if (tmp && setsockopt (*fd, SOL_SOCKET, SO_BINDTODEVICE, tmp,
1668 strlen (tmp)) == -1)
1670 log_write ("setsockopt(): %s",
1671 pwmd_strerror (gpg_error_from_errno (errno)));
1672 xfree (tmp);
1673 goto fail;
1676 xfree (tmp);
1677 #endif
1679 if (listen (*fd, 128) == -1)
1681 log_write ("listen(): %s", strerror (errno));
1682 goto fail;
1685 return 1;
1687 fail:
1688 start_stop_tls_with_protocol (0, 1);
1689 if (tls_fd != -1)
1690 close (tls_fd);
1692 if (tls6_fd != -1)
1693 close (tls6_fd);
1695 tls_fd = -1;
1696 tls6_fd = -1;
1697 return 0;
1700 static int
1701 start_stop_tls (int term)
1703 char *s = config_get_string ("global", "tcp_bind");
1704 int b;
1706 if (!s)
1707 return 0;
1709 if (!strcmp (s, "any"))
1711 b = start_stop_tls_with_protocol (0, term);
1712 if (b)
1713 b = start_stop_tls_with_protocol (1, term);
1715 else if (!strcmp (s, "ipv4"))
1716 b = start_stop_tls_with_protocol (0, term);
1717 else if (!strcmp (s, "ipv6"))
1718 b = start_stop_tls_with_protocol (1, term);
1719 else
1720 b = 0;
1722 xfree (s);
1723 if (!term && b)
1725 gpg_error_t rc = tls_init_params ();
1726 if (rc)
1728 start_stop_tls_with_protocol (0, 1);
1729 return 0;
1733 return b;
1735 #endif
1737 #ifdef WITH_GNUTLS
1738 static gpg_error_t
1739 do_tls_accept (struct pollfd *fds)
1741 struct sockaddr_storage raddr;
1742 socklen_t slen = sizeof (raddr);
1743 int fd;
1744 char s[INET6_ADDRSTRLEN];
1746 if (!(fds->revents & POLLIN))
1747 return 0;
1749 fd = accept (fds->fd, (struct sockaddr *) &raddr, &slen);
1750 if (fd == -1)
1752 int e = errno;
1754 if (errno != EAGAIN && !quit)
1755 log_write ("%s: %s", __FUNCTION__,
1756 pwmd_strerror (gpg_error_from_syserror()));
1758 return gpg_error_from_errno (e);
1761 inet_ntop (raddr.ss_family, get_in_addr ((struct sockaddr *) &raddr), s,
1762 sizeof s);
1763 (void) init_client (fd, s);
1764 return 0;
1766 #endif
1768 static void *
1769 accept_thread (void *arg)
1771 int sockfd = *(int *) arg;
1772 #ifndef HAVE_PTHREAD_CANCEL
1773 int *n = xmalloc (sizeof (int));
1775 *n = 0;
1776 pthread_setspecific (signal_thread_key, n);
1777 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
1778 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1779 #endif
1781 #ifdef HAVE_PR_SET_NAME
1782 prctl (PR_SET_NAME, "accept");
1783 #endif
1784 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
1786 for (;;)
1788 socklen_t slen = sizeof (struct sockaddr_un);
1789 struct sockaddr_un raddr;
1790 int fd, s = 0;
1791 struct pollfd fds[3];
1792 #ifndef HAVE_PTHREAD_CANCEL
1793 int *sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1795 if (*sigusr2)
1796 break;
1797 #endif
1799 memset (fds, 0, sizeof (fds));
1800 fds[s].fd = sockfd;
1801 fds[s++].events = POLLIN;
1803 #ifdef WITH_GNUTLS
1804 if (tls_fd != -1)
1806 fds[s].fd = tls_fd;
1807 fds[s++].events = POLLIN;
1809 else
1810 fds[s].fd = tls_fd;
1812 if (tls6_fd != -1)
1814 fds[s].fd = tls6_fd;
1815 fds[s++].events = POLLIN;
1817 else
1818 fds[s].fd = tls6_fd;
1819 #endif
1821 s = poll (fds, s, 500);
1822 if (s == -1)
1824 if (errno != EINTR)
1825 log_write ("%s", strerror (errno));
1826 break;
1828 else if (s == 0)
1829 continue;
1831 if (fds[0].revents & POLLIN)
1833 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1834 if (fd == -1)
1836 if (errno == EMFILE || errno == ENFILE)
1837 log_write ("%s: %s", __FUNCTION__,
1838 pwmd_strerror (gpg_error_from_errno (errno)));
1839 else if (errno != EAGAIN && errno != EINTR)
1841 if (!quit) // probably EBADF
1842 log_write ("%s: %s", __FUNCTION__,
1843 pwmd_strerror (gpg_error_from_errno (errno)));
1845 break;
1848 continue;
1851 (void) init_client (fd, NULL);
1854 #ifdef WITH_GNUTLS
1855 if (tls_fd != -1 && fds[1].fd == tls_fd)
1856 (void)do_tls_accept (&fds[1]);
1858 if (tls6_fd != -1 && fds[1].fd == tls6_fd)
1859 (void)do_tls_accept (&fds[1]);
1861 if (tls6_fd != -1 && fds[2].fd == tls6_fd)
1862 (void)do_tls_accept (&fds[2]);
1863 #endif
1866 /* Just in case accept() failed for some reason other than EBADF */
1867 quit = 1;
1868 return NULL;
1871 static void *
1872 cache_timer_thread (void *arg)
1874 unsigned k = 0;
1875 #ifndef HAVE_PTHREAD_CANCEL
1876 int *n = xmalloc (sizeof (int));
1878 *n = 0;
1879 pthread_setspecific (signal_thread_key, n);
1880 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
1881 #endif
1883 #ifdef HAVE_PR_SET_NAME
1884 prctl (PR_SET_NAME, "timer");
1885 #endif
1886 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
1888 for (;;)
1890 struct timeval tv = { 1, 0 };
1891 unsigned keepalive = config_get_integer ("global", "keepalive_interval");
1892 #ifndef HAVE_PTHREAD_CANCEL
1893 int *n;
1895 n = (int *) pthread_getspecific (signal_thread_key);
1896 if (*n)
1897 break;
1898 #endif
1900 select (0, NULL, NULL, NULL, &tv);
1901 cache_adjust_timeout ();
1903 if (++k >= keepalive)
1905 send_status_all (STATUS_KEEPALIVE, NULL);
1906 k = 0;
1910 return NULL;
1913 static int
1914 signal_loop (sigset_t sigset)
1916 int done = 0;
1917 int siint = 0;
1921 int sig;
1923 sigwait (&sigset, &sig);
1925 if (sig != SIGQUIT)
1926 log_write (_("caught signal %i (%s)"), sig, strsignal (sig));
1928 switch (sig)
1930 case SIGHUP:
1931 pthread_cond_signal (&rcfile_cond);
1932 break;
1933 case SIGUSR1:
1934 log_write (_("clearing file cache"));
1935 cache_clear (NULL, NULL, 1);
1936 send_status_all (STATUS_CACHE, NULL);
1937 break;
1938 case SIGQUIT:
1939 done = 1;
1940 break;
1941 default:
1942 siint = 1;
1943 done = 1;
1944 break;
1947 while (!done);
1949 return siint;
1952 static void
1953 catchsig (int sig)
1955 log_write (_ ("Caught signal %i (%s). Exiting."), sig, strsignal (sig));
1956 #ifdef HAVE_BACKTRACE
1957 BACKTRACE (__FUNCTION__);
1958 #endif
1959 longjmp (jmp, 1);
1962 static void *
1963 waiting_for_exit (void *arg)
1965 int last = 0;
1966 #ifndef HAVE_PTHREAD_CANCEL
1967 int *n = xmalloc (sizeof (int));
1969 *n = 0;
1970 pthread_setspecific (signal_thread_key, n);
1971 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
1972 #endif
1974 #ifdef HAVE_PR_SET_NAME
1975 prctl (PR_SET_NAME, "exiting");
1976 #endif
1977 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
1978 log_write (_("waiting for all clients to disconnect"));
1979 MUTEX_LOCK (&quit_mutex);
1980 pthread_cleanup_push (cleanup_mutex_cb, &quit_mutex);
1982 for (;;)
1984 struct timespec ts;
1985 int n;
1987 MUTEX_LOCK (&cn_mutex);
1988 n = slist_length (cn_thread_list);
1989 MUTEX_UNLOCK (&cn_mutex);
1990 if (!n)
1991 break;
1993 #ifndef HAVE_PTHREAD_CANCEL
1994 int *s = (int *) pthread_getspecific (signal_thread_key);
1995 if (*s)
1996 break;
1997 #endif
1999 if (last != n)
2001 log_write (_("%i clients remain"), n);
2002 last = n;
2005 INIT_TIMESPEC (SIG_TIMEOUT, ts);
2006 pthread_cond_timedwait (&quit_cond, &quit_mutex, &ts);
2009 kill (getpid (), SIGQUIT);
2010 pthread_cleanup_pop (1);
2011 return NULL;
2014 static int
2015 server_loop (int sockfd, char **socketpath)
2017 pthread_t cache_timeout_tid;
2018 int cancel_timeout_thread = 0, cancel_accept_thread = 0;
2019 sigset_t sigset;
2020 int n;
2021 int segv = 0;
2022 gpg_error_t rc;
2024 init_commands ();
2025 sigemptyset (&sigset);
2027 /* Termination */
2028 sigaddset (&sigset, SIGTERM);
2029 sigaddset (&sigset, SIGINT);
2031 /* Clears the file cache. */
2032 sigaddset (&sigset, SIGUSR1);
2034 /* Configuration file reloading. */
2035 sigaddset (&sigset, SIGHUP);
2037 /* For exiting cleanly. */
2038 sigaddset (&sigset, SIGQUIT);
2040 #ifndef HAVE_PTHREAD_CANCEL
2042 The socket, cache and rcfile threads use this signal when
2043 pthread_cancel() is unavailable. Prevent the main thread from
2044 catching this signal from another process.
2046 sigaddset (&sigset, SIGUSR2);
2047 #endif
2049 /* An assertion failure. */
2050 signal (SIGABRT, catchsig);
2051 sigaddset (&sigset, SIGABRT);
2052 sigprocmask (SIG_BLOCK, &sigset, NULL);
2054 #ifndef HAVE_PTHREAD_CANCEL
2055 /* Remove this signal from the watched signals in signal_loop(). */
2056 sigdelset (&sigset, SIGUSR2);
2057 #endif
2059 /* Can show a backtrace of the stack in the log. */
2060 signal (SIGSEGV, catchsig);
2062 pthread_mutex_init (&quit_mutex, NULL);
2063 pthread_cond_init (&quit_cond, NULL);
2064 char *p = get_username (getuid());
2065 log_write (_("%s started for user %s"), PACKAGE_STRING, p);
2066 xfree (p);
2068 #ifdef WITH_GNUTLS
2069 if (config_get_boolean ("global", "enable_tcp"))
2070 log_write (_("Listening on %s and TCP port %i"), *socketpath,
2071 config_get_integer ("global", "tcp_port"));
2072 else
2073 log_write (_("Listening on %s"), *socketpath);
2074 #else
2075 log_write (_("Listening on %s"), *socketpath);
2076 #endif
2078 rc = create_thread (reload_rcfile_thread, NULL, &rcfile_tid, 0);
2079 if (rc)
2081 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2082 pwmd_strerror (rc));
2083 goto done;
2086 rc = create_thread (cache_timer_thread, NULL, &cache_timeout_tid, 0);
2087 if (rc)
2089 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2090 pwmd_strerror (rc));
2091 goto done;
2094 cancel_timeout_thread = 1;
2095 rc = create_thread (accept_thread, &sockfd, &accept_tid, 0);
2096 if (rc)
2098 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2099 pwmd_strerror (rc));
2100 goto done;
2103 cancel_accept_thread = 1;
2104 if (!setjmp (jmp))
2105 signal_loop (sigset);
2106 else
2107 segv = 1;
2109 done:
2111 * We're out of the main server loop. This happens when a signal was sent
2112 * to terminate the daemon. We'll wait for all clients to disconnect
2113 * before exiting but exit immediately if another termination signal is
2114 * sent.
2116 if (cancel_accept_thread)
2118 #ifdef HAVE_PTHREAD_CANCEL
2119 int n = pthread_cancel (accept_tid);
2120 #else
2121 int n = pthread_kill (accept_tid, SIGUSR2);
2122 #endif
2123 if (!n)
2124 pthread_join (accept_tid, NULL);
2127 if (cancel_timeout_thread)
2129 #ifdef HAVE_PTHREAD_CANCEL
2130 n = pthread_cancel (cache_timeout_tid);
2131 #else
2132 n = pthread_kill (cache_timeout_tid, SIGUSR2);
2133 #endif
2134 if (!n)
2135 pthread_join (cache_timeout_tid, NULL);
2138 #ifdef WITH_GNUTLS
2139 start_stop_tls (1);
2140 #endif
2141 shutdown (sockfd, SHUT_RDWR);
2142 close (sockfd);
2143 unlink (*socketpath);
2144 xfree (*socketpath);
2145 *socketpath = NULL;
2146 MUTEX_LOCK (&cn_mutex);
2147 n = slist_length (cn_thread_list);
2148 MUTEX_UNLOCK (&cn_mutex);
2150 if (n && !segv)
2152 pthread_t tid;
2154 rc = create_thread (waiting_for_exit, NULL, &tid, 0);
2155 if (!rc)
2157 if (signal_loop (sigset))
2159 log_write (_("Received second termination request. Exiting."));
2160 #ifdef HAVE_PTHREAD_CANCEL
2161 pthread_cancel (tid);
2162 #else
2163 pthread_kill (tid, SIGUSR2);
2164 #endif
2165 pthread_join (tid, NULL);
2168 else
2169 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2170 pwmd_strerror (rc));
2173 cleanup_all_clients (0);
2174 deinit_commands ();
2175 pthread_cond_destroy (&quit_cond);
2176 pthread_mutex_destroy (&quit_mutex);
2177 return segv ? EXIT_FAILURE : EXIT_SUCCESS;;
2180 static void
2181 startup_failure ()
2183 log_write (_
2184 ("Failed to add a file to the cache. Use --force to force startup. Exiting."));
2185 cache_clear (NULL, NULL, 1);
2188 static void
2189 usage (const char *pn, int status)
2191 FILE *fp = status == EXIT_FAILURE ? stderr : stdout;
2193 fprintf (fp, _("Usage: %s [OPTIONS] [file1] [...]\n"
2194 " --debug=[a:..][,g:N][,t:N] enable debugging (a:[ixedsc],g:[1-9],t:[0-N])\n"
2195 " -f, --rcfile=filename load the specfied configuration file\n"
2196 " (~/.pwmd/config)\n"
2197 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2198 " --kill terminate an existing instance of pwmd\n"
2199 " -n, --no-fork run as a foreground process\n"
2200 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2201 " --ignore, --force ignore file errors during startup\n"
2202 " -o, --outfile=filename output file when importing or converting\n"
2203 " -C, --convert=filename convert a version 2 data file to version 3\n"
2204 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2205 " -k, --passphrase-file=file for use when importing or converting\n"
2206 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2207 " converting\n"
2208 " --no-passphrase when importing or converting\n"
2209 " --keyid=keyID[,..] public key to use when encrypting\n"
2210 " --sign-keyid=fpr[,..] fingerprint of the signing key to use\n"
2211 " --symmetric use conventional encryption with optional signer\n"
2212 " --keyparam=filename custom key parameters to use (gpg default)\n"
2213 " --help this help text\n"
2214 " --version show version and compile time features\n"),
2215 pn);
2216 exit (status);
2219 static void
2220 unlink_stale_socket (const char *sock, const char *pidfile)
2222 log_write (_ ("removing stale socket %s"), sock);
2223 unlink (sock);
2224 unlink (pidfile);
2227 static int
2228 test_pidfile (const char *path, const char *sock, char *buf, size_t buflen,
2229 char **pidfile, int create, mode_t mode, int terminate)
2231 pid_t pid;
2232 int fd;
2233 size_t len;
2235 if (!create)
2237 snprintf (buf, buflen, "%s/%s.pid", homedir, sock);
2238 *pidfile = str_dup (buf);
2239 fd = open (buf, O_RDONLY);
2241 else
2242 fd = open (*pidfile, O_CREAT|O_WRONLY|O_TRUNC, mode);
2244 if (fd == -1)
2246 if (!create && errno != ENOENT)
2248 log_write ("%s: %s", buf, pwmd_strerror (errno));
2249 free (*pidfile);
2250 *pidfile = NULL;
2251 return -1;
2253 else if (!create && !terminate)
2254 return 0;
2256 log_write ("%s: %s", *pidfile, strerror (errno));
2257 return -1;
2260 if (create)
2262 snprintf (buf, buflen, "%i", getpid ());
2263 ssize_t ret = write (fd, buf, strlen (buf));
2264 if (ret == -1)
2265 log_write ("%s (%i): %s", __FUNCTION__, __LINE__,
2266 pwmd_strerror (gpg_error_from_syserror ()));
2267 close (fd);
2268 return 0;
2271 len = read (fd, buf, buflen);
2272 close (fd);
2273 if (len == 0)
2275 unlink_stale_socket (path, *pidfile);
2276 return 0;
2279 if (sscanf (buf, "%5i", &pid) != 1 || pid == 0)
2281 if (!terminate)
2283 unlink_stale_socket (path, *pidfile);
2284 return 0;
2288 if (kill (pid, 0) == -1)
2290 unlink_stale_socket (path, *pidfile);
2291 return 0;
2294 if (terminate)
2296 if (kill (pid, SIGTERM) == -1)
2297 log_write ("%s: %s", path, pwmd_strerror (errno));
2299 else
2300 log_write (_ ("an instance for socket %s is already running"), path);
2302 xfree (*pidfile);
2303 *pidfile = NULL;
2304 return 1;
2307 static unsigned
2308 parse_debug_level (const char *str, unsigned *debug, int *gpgme, int *tls)
2310 const char *p;
2311 unsigned level = 0;
2312 int gl = 0, tl = 0;
2314 for (p = str; p && *p; p++)
2316 if (*p == 'a') // assuan debug flags
2318 if (*++p != ':')
2319 return 1;
2321 while (*++p)
2323 switch (*p)
2325 case 'i':
2326 level |= ASSUAN_LOG_INIT;
2327 break;
2328 case 'x':
2329 level |= ASSUAN_LOG_CTX;
2330 break;
2331 case 'e':
2332 level |= ASSUAN_LOG_ENGINE;
2333 break;
2334 case 'd':
2335 level |= ASSUAN_LOG_DATA;
2336 break;
2337 case 's':
2338 level |= ASSUAN_LOG_SYSIO;
2339 break;
2340 case 'c':
2341 level |= ASSUAN_LOG_CONTROL;
2342 break;
2343 case ',':
2344 break;
2345 default:
2346 return 1;
2349 if (*p == ',')
2350 break;
2353 if (!*p)
2354 break;
2356 else if (*p == 'g' || *p == 't') // gpgme and TLS debug level
2358 int t = *p == 't';
2359 int n;
2361 if (*++p != ':')
2362 return 1;
2364 if (!isdigit (*++p))
2365 return 1;
2367 n = atoi (p);
2368 if (t)
2369 tl = n;
2370 else
2371 gl = n;
2373 if (tl < 0 || gl < 0 || gl > 9)
2374 return 1;
2376 while (isdigit (*p))
2377 p++;
2379 p--;
2380 if (*(p+1) && *(p+1) != ',')
2381 return 1;
2382 else if (*(p+1))
2383 p++;
2385 else
2386 return 1;
2389 if (tl)
2390 *tls = tl;
2392 if (gl)
2393 *gpgme = gl;
2395 *debug = level;
2396 return 0;
2400 main (int argc, char *argv[])
2402 int opt;
2403 struct sockaddr_un addr;
2404 char buf[PATH_MAX];
2405 char *socketpath = NULL, *socketdir, *socketname = NULL;
2406 char *socketarg = NULL;
2407 char *datadir = NULL;
2408 char *pidfile = NULL;
2409 mode_t mode = 0600;
2410 int x;
2411 char *p;
2412 char **cache_push = NULL;
2413 char *import = NULL, *keyid = NULL, *sign_keyid = NULL;
2414 char *keyparam = NULL;
2415 int estatus = EXIT_FAILURE;
2416 int sockfd;
2417 char *outfile = NULL;
2418 int do_unlink = 0;
2419 int secure = 0;
2420 int show_version = 0;
2421 int force = 0;
2422 gpg_error_t rc;
2423 char *keyfile = NULL;
2424 int exists;
2425 int optindex;
2426 int terminate = 0;
2427 int sym = 0;
2428 int gpgme_level = -1;
2429 int tls_level = -1;
2430 /* Must maintain the same order as longopts[] */
2431 enum
2433 OPT_VERSION, OPT_HELP, OPT_HOMEDIR, OPT_NO_FORK, OPT_DISABLE_DUMP,
2434 OPT_FORCE, OPT_RCFILE, OPT_PASSPHRASE_FILE, OPT_IMPORT, OPT_OUTFILE,
2435 OPT_KEYID, OPT_SIGN_KEYID, OPT_SYMMETRIC, OPT_KEYPARAM, OPT_KILL,
2436 OPT_DEBUG
2438 const char *optstring = "nf:C:k:I:o:s";
2439 const struct option longopts[] = {
2440 {"version", no_argument, 0, 0},
2441 {"help", no_argument, 0, 0},
2442 {"homedir", required_argument, 0, 0},
2443 {"no-fork", no_argument, 0, 'n'},
2444 {"disable_dump", no_argument, 0, 0},
2445 {"force", no_argument, 0, 0},
2446 {"rcfile", required_argument, 0, 'f'},
2447 {"passphrase-file", required_argument, 0, 'k'},
2448 {"import", required_argument, 0, 'I'},
2449 {"outfile", required_argument, 0, 'o'},
2450 {"keyid", required_argument, 0, 0},
2451 {"sign-keyid", required_argument, 0, 0},
2452 {"symmetric", no_argument, 0, 's'},
2453 {"keyparam", required_argument, 0, 0},
2454 {"kill", no_argument, 0, 0},
2455 {"debug", required_argument, 0, 0},
2456 {0, 0, 0, 0}
2459 log_fd = -1;
2460 cmdline = 1;
2462 #ifndef DEBUG
2463 #ifdef HAVE_SETRLIMIT
2464 struct rlimit rl;
2466 rl.rlim_cur = rl.rlim_max = 0;
2468 if (setrlimit (RLIMIT_CORE, &rl) != 0)
2469 err (EXIT_FAILURE, "setrlimit()");
2470 #endif
2472 #ifdef HAVE_PR_SET_DUMPABLE
2473 prctl (PR_SET_DUMPABLE, 0);
2474 #endif
2475 #endif
2477 #ifdef ENABLE_NLS
2478 setlocale (LC_ALL, "");
2479 bindtextdomain ("pwmd", LOCALEDIR);
2480 textdomain ("pwmd");
2481 #endif
2483 if (setup_crypto ())
2484 exit (EXIT_FAILURE);
2486 #ifdef WITH_GNUTLS
2487 tls_level = tls_level == -1 ? 1 : tls_level;
2488 gnutls_global_set_log_level (tls_level);
2489 tls_fd = -1;
2490 tls6_fd = -1;
2491 #endif
2492 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
2493 xmlInitMemory ();
2494 xmlInitGlobals ();
2495 xmlInitParser ();
2496 xmlXPathInit ();
2498 while ((opt = getopt_long (argc, argv, optstring, longopts, &optindex))
2499 != -1)
2501 switch (opt)
2503 case 'I':
2504 import = optarg;
2505 break;
2506 case 'k':
2507 keyfile = optarg;
2508 break;
2509 case 'o':
2510 outfile = optarg;
2511 break;
2512 case 'D':
2513 secure = 1;
2514 break;
2515 case 'n':
2516 nofork = 1;
2517 break;
2518 case 'f':
2519 rcfile = str_dup (optarg);
2520 break;
2521 case 's':
2522 sym = 1;
2523 break;
2524 default:
2525 usage (argv[0], EXIT_FAILURE);
2526 break;
2527 case 0:
2528 switch (optindex)
2530 case OPT_DEBUG:
2531 if (parse_debug_level (optarg, &assuan_level, &gpgme_level,
2532 &tls_level))
2533 usage (argv[0], EXIT_FAILURE);
2534 break;
2535 case OPT_SYMMETRIC:
2536 sym = 1;
2537 break;
2538 case OPT_VERSION:
2539 show_version = 1;
2540 break;
2541 case OPT_HELP:
2542 usage (argv[0], EXIT_SUCCESS);
2543 break;
2544 case OPT_HOMEDIR:
2545 homedir = str_dup (optarg);
2546 break;
2547 case OPT_NO_FORK:
2548 nofork = 1;
2549 break;
2550 case OPT_DISABLE_DUMP:
2551 secure = 1;
2552 break;
2553 case OPT_FORCE:
2554 force = 1;
2555 break;
2556 case OPT_RCFILE:
2557 rcfile = str_dup (optarg);
2558 break;
2559 case OPT_PASSPHRASE_FILE:
2560 keyfile = optarg;
2561 break;
2562 case OPT_IMPORT:
2563 import = optarg;
2564 break;
2565 case OPT_OUTFILE:
2566 outfile = optarg;
2567 break;
2568 case OPT_KEYID:
2569 keyid = optarg;
2570 break;
2571 case OPT_SIGN_KEYID:
2572 sign_keyid = optarg;
2573 break;
2574 case OPT_KEYPARAM:
2575 keyparam = optarg;
2576 break;
2577 case OPT_KILL:
2578 terminate = 1;
2579 break;
2580 default:
2581 usage (argv[0], EXIT_FAILURE);
2586 if (show_version)
2588 printf (_("%s\n\n"
2589 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016\n"
2590 "%s\n"
2591 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2592 "Compile time features:\n%s"), PACKAGE_STRING,
2593 PACKAGE_BUGREPORT,
2594 #ifdef PWMD_HOMEDIR
2595 "+PWMD_HOMEDIR=" PWMD_HOMEDIR "\n"
2596 #endif
2597 #ifdef WITH_GNUTLS
2598 "+WITH_GNUTLS\n"
2599 #else
2600 "-WITH_GNUTLS\n"
2601 #endif
2602 #ifdef WITH_LIBACL
2603 "+WITH_LIBACL\n"
2604 #else
2605 "-WITH_LIBACL\n"
2606 #endif
2607 #ifdef DEBUG
2608 "+DEBUG\n"
2609 #else
2610 "-DEBUG\n"
2611 #endif
2612 #ifdef MEM_DEBUG
2613 "+MEM_DEBUG\n"
2614 #else
2615 "-MEM_DEBUG\n"
2616 #endif
2617 #ifdef MUTEX_DEBUG
2618 "+MUTEX_DEBUG\n"
2619 #else
2620 "-MUTEX_DEBUG\n"
2621 #endif
2623 exit (EXIT_SUCCESS);
2626 if (!homedir)
2627 #ifdef PWMD_HOMEDIR
2628 homedir = str_dup(PWMD_HOMEDIR);
2629 #else
2630 homedir = str_asprintf ("%s/.pwmd", get_home_dir());
2631 #endif
2633 if (mkdir (homedir, 0700) == -1 && errno != EEXIST)
2634 err (EXIT_FAILURE, "%s", homedir);
2636 if (!rcfile)
2637 rcfile = str_asprintf ("%s/config", homedir);
2639 pthread_key_create (&last_error_key, free_key);
2640 #ifndef HAVE_PTHREAD_CANCEL
2641 pthread_key_create (&signal_thread_key, free_key);
2642 #endif
2644 pthread_mutexattr_t attr;
2645 pthread_mutexattr_init (&attr);
2646 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
2647 pthread_mutex_init (&rcfile_mutex, &attr);
2648 global_config = config_parse (rcfile, 0);
2649 if (!global_config)
2651 pthread_mutexattr_destroy (&attr);
2652 pthread_mutex_destroy (&rcfile_mutex);
2653 exit (EXIT_FAILURE);
2656 p = config_get_string ("global", "gpg_homedir");
2657 if (!p)
2658 datadir = str_asprintf ("%s/.gnupg", homedir);
2659 else
2660 datadir = expand_homedir (p);
2662 xfree (p);
2663 if (mkdir (datadir, 0700) == -1 && errno != EEXIST)
2664 err (EXIT_FAILURE, "%s", datadir);
2666 if (gpgme_level != -1)
2668 char s[2] = { gpgme_level + '0', 0 };
2670 if (getenv ("GPGME_DEBUG"))
2671 log_write (_ ("Overriding GPGME_DEBUG environment with level %u!"),
2672 gpgme_level);
2674 gpgme_set_global_flag ("debug", s);
2677 rc = gpgme_set_engine_info (GPGME_PROTOCOL_OpenPGP, NULL, datadir);
2678 xfree (datadir);
2680 snprintf (buf, sizeof (buf), "%s/data", homedir);
2681 if (mkdir (buf, 0700) == -1 && errno != EEXIST)
2682 err (EXIT_FAILURE, "%s", buf);
2684 datadir = str_dup (buf);
2685 pthread_cond_init (&rcfile_cond, NULL);
2686 pthread_mutex_init (&cn_mutex, &attr);
2687 pthread_mutexattr_destroy (&attr);
2689 setup_logging ();
2691 x = config_get_int_param (global_config, "global", "priority", &exists);
2692 if (exists && x != atoi(INVALID_PRIORITY))
2694 errno = 0;
2695 if (setpriority (PRIO_PROCESS, 0, x) == -1)
2697 log_write ("setpriority(): %s",
2698 pwmd_strerror (gpg_error_from_errno (errno)));
2699 goto do_exit;
2702 #ifdef HAVE_MLOCKALL
2703 if (disable_mlock == 0 && mlockall (MCL_CURRENT | MCL_FUTURE) == -1)
2705 log_write ("mlockall(): %s",
2706 pwmd_strerror (gpg_error_from_errno (errno)));
2707 goto do_exit;
2709 #endif
2711 rc = cache_init ();
2712 if (rc)
2714 log_write ("pwmd: ERR %i: %s", rc, pwmd_strerror (rc));
2715 exit (EXIT_FAILURE);
2718 if (import)
2720 char **keyids = NULL, **sign_keyids = NULL;
2722 if (!outfile || !*outfile || argc != optind)
2723 usage (argv[0], EXIT_FAILURE);
2725 if (keyid)
2726 keyids = str_split (keyid, ",", 0);
2727 if (sign_keyid)
2728 sign_keyids = str_split (sign_keyid, ",", 0);
2729 rc = xml_import (import, outfile, keyids, sign_keyids, keyfile, keyparam, sym);
2730 strv_free (keyids);
2731 strv_free (sign_keyids);
2732 if (rc)
2734 if (gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
2735 rc = gpg_error (rc);
2737 log_write ("%s: %u: %s", import, rc, pwmd_strerror (rc));
2740 config_free (global_config);
2741 xfree (rcfile);
2742 exit (rc ? EXIT_FAILURE : EXIT_SUCCESS);
2745 p = config_get_string ("global", "socket_path");
2746 if (!p)
2747 p = str_asprintf ("%s/socket", homedir);
2749 socketarg = expand_homedir (p);
2750 xfree (p);
2752 if (!secure)
2753 disable_list_and_dump = config_get_boolean ("global",
2754 "disable_list_and_dump");
2755 else
2756 disable_list_and_dump = secure;
2758 cache_push = config_get_list ("global", "cache_push");
2760 while (optind < argc)
2762 if (strv_printf (&cache_push, "%s", argv[optind++]) == 0)
2763 errx (EXIT_FAILURE, "%s", pwmd_strerror (GPG_ERR_ENOMEM));
2766 if (strchr (socketarg, '/') == NULL)
2768 socketdir = getcwd (buf, sizeof (buf));
2769 socketname = str_dup (socketarg);
2770 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2772 else
2774 socketname = str_dup (strrchr (socketarg, '/'));
2775 socketname++;
2776 socketarg[strlen (socketarg) - strlen (socketname) - 1] = 0;
2777 socketdir = str_dup (socketarg);
2778 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2781 if (chdir (datadir))
2783 log_write ("%s: %s", datadir,
2784 pwmd_strerror (gpg_error_from_errno (errno)));
2785 unlink (socketpath);
2786 goto do_exit;
2789 x = test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 0,
2790 mode, terminate);
2791 if (!terminate && x)
2792 goto do_exit;
2793 else if (terminate)
2795 estatus = x != 1 ? EXIT_FAILURE : EXIT_SUCCESS;
2796 goto do_exit;
2800 * bind() doesn't like the full pathname of the socket or any non alphanum
2801 * characters so change to the directory where the socket is wanted then
2802 * create it then change to datadir.
2804 if (chdir (socketdir))
2806 log_write ("%s: %s", socketdir,
2807 pwmd_strerror (gpg_error_from_errno (errno)));
2808 goto do_exit;
2811 xfree (socketdir);
2813 if ((sockfd = socket (PF_UNIX, SOCK_STREAM, 0)) == -1)
2815 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2816 goto do_exit;
2819 addr.sun_family = AF_UNIX;
2820 snprintf (addr.sun_path, sizeof (addr.sun_path), "%s", socketname);
2821 do_unlink = 1;
2822 if (bind (sockfd, (struct sockaddr *) &addr, sizeof (struct sockaddr)) ==
2825 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2827 if (errno == EADDRINUSE)
2829 do_unlink = 0;
2830 log_write (_("Either there is another pwmd running or '%s' is a \n"
2831 "stale socket. Please remove it manually."), socketpath);
2834 goto do_exit;
2838 char *t = config_get_string ("global", "socket_perms");
2839 mode_t mask;
2841 if (t)
2843 mode = strtol (t, NULL, 8);
2844 mask = umask (0);
2845 xfree (t);
2847 if (chmod (socketname, mode) == -1)
2849 log_write ("%s: %s", socketname,
2850 pwmd_strerror (gpg_error_from_errno (errno)));
2851 close (sockfd);
2852 umask (mask);
2853 goto do_exit;
2856 umask (mask);
2860 xfree (--socketname);
2862 if (chdir (datadir))
2864 log_write ("%s: %s", datadir,
2865 pwmd_strerror (gpg_error_from_errno (errno)));
2866 close (sockfd);
2867 goto do_exit;
2870 xfree (datadir);
2871 #ifdef WITH_GNUTLS
2872 if (config_get_boolean ("global", "enable_tcp"))
2874 if (!start_stop_tls (0))
2876 close (sockfd);
2877 goto do_exit;
2880 #endif
2883 * Set the cache entry for a file. Prompts for the password.
2885 if (cache_push)
2887 for (opt = 0; cache_push[opt]; opt++)
2889 struct crypto_s *crypto = NULL;
2890 char *pw_file = config_get_string (cache_push[opt],
2891 "passphrase_file");
2892 gpg_error_t rc = crypto_init (&crypto, NULL, cache_push[opt],
2893 pw_file != NULL, pw_file);
2895 if (!rc)
2897 crypto->flags |= pw_file ? CRYPTO_FLAG_KEYFILE : 0;
2898 crypto->keyfile = pw_file;
2900 else
2901 xfree (pw_file);
2903 if (rc)
2905 estatus = EXIT_FAILURE;
2906 goto do_exit;
2909 rc = do_cache_push (crypto);
2910 if (rc && !force)
2912 log_write ("ERR %u: %s", rc, pwmd_strerror(rc));
2913 strv_free (cache_push);
2914 startup_failure ();
2915 estatus = EXIT_FAILURE;
2916 crypto_free (crypto);
2917 goto do_exit;
2919 else if (rc)
2920 log_write ("%s: %s", crypto->filename, pwmd_strerror(rc));
2921 else
2922 log_write (_("Successfully added '%s' to the cache."),
2923 crypto->filename);
2925 crypto_free (crypto);
2928 strv_free (cache_push);
2929 log_write (!nofork ? _("Done. Daemonizing...") :
2930 _("Done. Waiting for connections..."));
2933 if (listen (sockfd, 128) == -1)
2935 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2936 goto do_exit;
2939 if (!nofork)
2941 switch (fork ())
2943 case -1:
2944 log_write ("fork(): %s",
2945 pwmd_strerror (gpg_error_from_errno (errno)));
2946 goto do_exit;
2947 case 0:
2948 close (0);
2949 close (1);
2950 close (2);
2951 setsid ();
2952 break;
2953 default:
2954 _exit (EXIT_SUCCESS);
2958 (void)test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 1,
2959 mode, 0);
2960 cmdline = 0;
2961 pthread_key_create (&thread_name_key, free_key);
2962 estatus = server_loop (sockfd, &socketpath);
2964 do_exit:
2965 if (socketpath && do_unlink)
2967 unlink (socketpath);
2968 xfree (socketpath);
2971 xfree (socketarg);
2972 #ifdef WITH_GNUTLS
2973 gnutls_global_deinit ();
2974 tls_deinit_params ();
2975 #endif
2976 if (rcfile_tid)
2978 #ifdef HAVE_PTHREAD_CANCEL
2979 pthread_cancel (rcfile_tid);
2980 #else
2981 pthread_kill (rcfile_tid, SIGUSR2);
2982 pthread_cond_signal (&rcfile_cond);
2983 #endif
2984 pthread_join (rcfile_tid, NULL);
2987 pthread_cond_destroy (&rcfile_cond);
2988 pthread_mutex_destroy (&rcfile_mutex);
2989 pthread_key_delete (last_error_key);
2990 #ifndef HAVE_PTHREAD_CANCEL
2991 pthread_key_delete (signal_thread_key);
2992 #endif
2994 if (global_config)
2995 config_free (global_config);
2997 free_invoking_users (invoking_users);
2998 xfree (rcfile);
2999 xfree (home_directory);
3000 xfree (homedir);
3001 xmlCleanupParser ();
3002 xmlCleanupGlobals ();
3004 if (pidfile)
3005 unlink (pidfile);
3006 xfree (pidfile);
3008 if (estatus == EXIT_SUCCESS && !terminate)
3009 log_write (_("pwmd exiting normally"));
3011 pthread_key_delete (thread_name_key);
3012 closelog ();
3014 if (log_fd != -1)
3015 close (log_fd);
3017 exit (estatus);
3020 gpg_error_t lock_flock (assuan_context_t ctx, const char *filename,
3021 int type, int *fd)
3023 gpg_error_t rc = 0;
3025 #ifdef HAVE_FLOCK
3026 *fd = open (filename, O_RDONLY);
3027 if (*fd == -1)
3028 return gpg_error_from_syserror ();
3030 TRY_FLOCK (ctx, *fd, type, rc);
3031 if (rc)
3033 close (*fd);
3034 *fd = -1;
3036 #endif
3038 return rc;
3041 void unlock_flock (int *fd)
3043 #ifdef HAVE_FLOCK
3044 if (*fd != -1)
3045 close (*fd);
3047 *fd = -1;
3048 #endif