Reset signal_thread_key upon cancellation.
[libpwmd.git] / src / pwmd.c
blobdfa7c2ab12f28afc48b0a5918aa129c10b8927dc
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 int log_fd;
101 static unsigned assuan_level;
103 pthread_t accept_tid;
104 #ifdef WITH_GNUTLS
105 static int tls_fd;
106 static int tls6_fd;
107 static int start_stop_tls (int term);
108 #endif
110 static gpg_error_t do_cache_push (struct crypto_s *crypto);
111 static int signal_loop (sigset_t sigset);
113 #ifndef HAVE_PTHREAD_CANCEL
114 #define INIT_SIGNAL(s, cb) do { \
115 int *n = xmalloc (sizeof (int)); \
116 *n = 0; \
117 pthread_setspecific (signal_thread_key, n); \
118 struct sigaction act; \
119 sigset_t sigset; \
120 sigemptyset (&sigset); \
121 sigaddset (&sigset, s); \
122 pthread_sigmask (SIG_UNBLOCK, &sigset, NULL); \
123 memset (&act, 0, sizeof(act)); \
124 act.sa_flags = SA_SIGINFO; \
125 act.sa_mask = sigset; \
126 act.sa_sigaction = cb; \
127 sigaction (s, &act, NULL); \
128 } while (0)
129 #endif
131 #ifndef HAVE_PTHREAD_CANCEL
132 static void
133 catch_thread_signal (int sig, siginfo_t *info, void *ctx)
135 int *n = (int *) pthread_getspecific (signal_thread_key);
137 *n = 1;
139 #endif
141 static void
142 setup_logging ()
144 int n = config_get_boolean ("global", "enable_logging");
146 if (n)
148 char *p = config_get_string ("global", "log_path");
150 if (!p || (logfile && p && log_fd != -1 && strcmp(p, logfile)))
152 if (log_fd != -1)
153 close (log_fd);
155 log_fd = -1;
158 xfree (logfile);
159 logfile = NULL;
160 if (p)
161 logfile = expand_homedir (p);
162 xfree (p);
164 else
166 xfree (logfile);
167 logfile = NULL;
168 if (log_fd != -1)
169 close(log_fd);
171 log_fd = -1;
172 closelog ();
175 log_syslog = config_get_boolean ("global", "syslog");
176 if (log_syslog == 1)
177 openlog ("pwmd", LOG_NDELAY | LOG_PID, LOG_DAEMON);
180 static void *
181 reload_rcfile_thread (void *arg)
183 #ifndef HAVE_PTHREAD_CANCEL
184 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
185 #endif
187 #ifdef HAVE_PR_SET_NAME
188 prctl (PR_SET_NAME, "reload rcfile");
189 #endif
190 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
191 MUTEX_LOCK (&rcfile_mutex);
193 for (;;)
195 struct slist_s *keep = NULL;
196 struct slist_s *config;
197 int b = disable_list_and_dump;
198 #ifdef WITH_GNUTLS
199 char *prio;
200 char *prio2 = NULL;
201 #endif
203 pthread_cleanup_push (release_mutex_cb, &rcfile_mutex);
204 pthread_cond_wait (&rcfile_cond, &rcfile_mutex);
205 TEST_CANCEL ();
206 keep = config_keep_save ();
207 log_write (_("reloading configuration file '%s'"), rcfile);
209 #ifdef WITH_GNUTLS
210 prio = config_get_string ("global", "tls_cipher_suite");
211 #endif
212 config = config_parse (rcfile, 1);
213 if (config)
215 config_free (global_config);
216 global_config = config;
217 setup_logging ();
220 config_keep_restore (keep);
221 disable_list_and_dump = !disable_list_and_dump ? b : 1;
223 #ifdef WITH_GNUTLS
224 /* Restart listening sockets since they may have changed. */
225 start_stop_tls (1);
226 start_stop_tls (0);
228 prio2 = config_get_string ("global", "tls_cipher_suite");
229 if ((prio2 && (!prio || strcmp (prio, prio2))) || (prio && !prio2))
230 tls_rehandshake ();
232 xfree (prio2);
233 xfree (prio);
234 #endif
235 crypto_set_keepalive ();
236 pthread_cleanup_pop (0);
239 MUTEX_UNLOCK (&rcfile_mutex);
240 return NULL;
243 gpg_error_t
244 send_error (assuan_context_t ctx, gpg_error_t e)
246 struct client_s *client = assuan_get_pointer (ctx);
248 if (gpg_err_source (e) == GPG_ERR_SOURCE_UNKNOWN)
249 e = gpg_error (e);
251 if (client)
252 client->last_rc = e;
254 if (!e)
255 return assuan_process_done (ctx, 0);
257 if (!ctx)
259 log_write ("ERR %i: %s", e, pwmd_strerror (e));
260 return e;
263 if (client && client->xml_error)
265 log_write ("%s", client->xml_error->message);
266 xfree (client->last_error);
267 client->last_error = NULL;
268 if (client->xml_error->message)
269 client->last_error = str_dup (client->xml_error->message);
271 e = assuan_process_done (ctx,
272 assuan_set_error (ctx, e,
273 client->xml_error->message ? client->xml_error->message : NULL));
274 xmlResetLastError ();
275 xmlResetError (client->xml_error);
276 xfree (client->xml_error);
277 client->xml_error = NULL;
278 return e;
281 return assuan_process_done (ctx,
282 assuan_set_error (ctx, e, pwmd_strerror (e)));
285 void
286 log_write (const char *fmt, ...)
288 char *args;
289 va_list ap;
290 time_t now;
291 char buf[255];
292 pthread_t tid = pthread_self ();
293 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
295 if ((!logfile && !isatty (STDERR_FILENO) && !log_syslog) || !fmt)
296 return;
298 pthread_mutex_lock (&m);
299 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock, &m);
301 if (!cmdline && logfile && log_fd == -1)
303 log_fd = open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600);
304 if (log_fd == -1)
305 warn ("%s", logfile);
308 va_start (ap, fmt);
310 if (str_vasprintf (&args, fmt, ap) != -1)
312 if (cmdline)
314 pthread_cleanup_push (xfree, args);
315 fprintf (stderr, "pwmd: %s\n", args);
316 fflush (stderr);
317 pthread_cleanup_pop (1);
319 else
321 char *name = pthread_getspecific (thread_name_key);
322 char *line;
324 pthread_cleanup_push (xfree, args);
325 if (name)
327 if (*name == '!')
328 snprintf (buf, sizeof (buf), "%s: ", name+1);
329 else
330 snprintf (buf, sizeof (buf), "%s(%p): ", name,
331 (pthread_t *)tid);
333 else
334 snprintf (buf, sizeof (buf), "%p: ", (pthread_t *)tid);
336 name = buf;
337 if (!cmdline && log_syslog && !nofork)
338 syslog (LOG_INFO, "%s%s", name, args);
340 time (&now);
341 struct tm *tm = localtime (&now);
342 char tbuf[21];
343 strftime (tbuf, sizeof (tbuf), "%b %d %Y %H:%M:%S ", tm);
344 tbuf[sizeof (tbuf) - 1] = 0;
346 if (args[strlen (args) - 1] == '\n')
347 args[strlen (args) - 1] = 0;
349 line = str_asprintf ("%s %i %s%s\n", tbuf, getpid (), name,
350 args);
351 pthread_cleanup_pop (1);
352 if (line)
354 pthread_cleanup_push (xfree, line);
355 if (logfile && log_fd != -1)
357 ssize_t ret = write (log_fd, line, strlen (line));
358 (void)ret;
359 fsync (log_fd);
362 if (nofork)
364 fprintf (stdout, "%s", line);
365 fflush (stdout);
368 pthread_cleanup_pop (1);
373 va_end (ap);
374 pthread_cleanup_pop (0);
376 if (log_fd != -1 && log_keepopen <= 0)
378 close(log_fd);
379 log_fd = -1;
382 pthread_mutex_unlock (&m);
385 static gpg_error_t
386 setup_crypto ()
388 gpg_error_t rc;
390 if (!gpgrt_check_version (REQUIRE_LIBGPGERROR_VERSION))
392 fprintf (stderr, _("gpgrt_check_version(): Incompatible libgpg-error. "
393 "Wanted %s, got %s.\n"), REQUIRE_LIBGPGERROR_VERSION,
394 gpgrt_check_version (NULL));
395 return GPG_ERR_UNKNOWN_VERSION;
398 gpgrt_init ();
399 //gpgrt_set_alloc_func (xrealloc_gpgrt);
401 if (!assuan_check_version (REQUIRE_LIBASSUAN_VERSION))
403 fprintf (stderr, _("assuan_check_version(): Incompatible libassuan. "
404 "Wanted %s, got %s.\n"), REQUIRE_LIBASSUAN_VERSION,
405 assuan_check_version (NULL));
406 return GPG_ERR_UNKNOWN_VERSION;
409 if (!gcry_check_version (REQUIRE_LIBGCRYPT_VERSION))
411 fprintf (stderr, _("gcry_check_version(): Incompatible libgcrypt. "
412 "Wanted %s, got %s.\n"), REQUIRE_LIBGCRYPT_VERSION,
413 gcry_check_version (NULL));
414 return GPG_ERR_UNKNOWN_VERSION;
417 gcry_set_allocation_handler (xmalloc, xmalloc, NULL, xrealloc, xfree);
419 if (!gpgme_check_version (REQUIRE_LIBGPGME_VERSION))
421 fprintf (stderr, _("gpgme_check_version(): Incompatible libgpgme. "
422 "Wanted %s, got %s.\n"), REQUIRE_LIBGPGME_VERSION,
423 gpgme_check_version (NULL));
424 return GPG_ERR_UNKNOWN_VERSION;
427 rc = gpgme_engine_check_version (GPGME_PROTOCOL_OPENPGP);
428 if (rc)
430 fprintf (stderr, _("gpgme_engine_check_version(GPGME_PROTOCOL_OPENPGP): %s"), gpgme_strerror (rc));
431 return GPG_ERR_UNKNOWN_VERSION;
434 //gpgme_set_global_flag ("require-gnupg", REQUIRE_GNUPG_VERSION);
435 #ifdef ENABLE_NLS
436 gpgme_set_locale (NULL, LC_CTYPE, setlocale (LC_CTYPE, NULL));
437 gpgme_set_locale (NULL, LC_MESSAGES, setlocale (LC_MESSAGES, NULL));
438 #endif
440 #ifdef WITH_GNUTLS
441 if (gnutls_global_init ())
443 fprintf(stderr, _("gnutls_global_init() failed.\n"));
444 return GPG_ERR_UNKNOWN_VERSION;
447 if (!gnutls_check_version (REQUIRE_LIBGNUTLS_VERSION))
449 fprintf (stderr, _("gnutls_check_version(): Incompatible libgnutls. "
450 "Wanted %s, got %s.\n"), REQUIRE_LIBGNUTLS_VERSION,
451 gnutls_check_version (NULL));
452 return GPG_ERR_UNKNOWN_VERSION;
455 gnutls_global_set_log_function (tls_log);
456 gnutls_global_set_audit_log_function (tls_audit_log);
457 #endif
458 return 0;
461 gpg_error_t
462 do_validate_peer (assuan_context_t ctx, const char *section,
463 assuan_peercred_t * peer)
465 char **users;
466 int allowed = 0;
467 gpg_error_t rc;
468 struct client_s *client = assuan_get_pointer (ctx);
470 if (!client)
471 return GPG_ERR_FORBIDDEN;
473 #ifdef WITH_GNUTLS
474 if (client->thd->remote)
475 return tls_validate_access (client, section);
476 #endif
478 rc = assuan_get_peercred (ctx, peer);
479 if (rc)
480 return rc;
482 users = config_get_list (section, "allowed");
483 if (users)
485 for (char **p = users; !rc && *p; p++)
487 rc = acl_check_common(client, *p, (*peer)->uid, (*peer)->gid,
488 &allowed);
491 strv_free (users);
493 else if (client->no_access_param)
494 allowed = 1;
496 return allowed && !rc ? 0 : rc ? rc : GPG_ERR_FORBIDDEN;
499 /* Test if uid is a member of group 'name'. Invert when 'not' is true. */
500 #ifdef HAVE_GETGRNAM_R
501 static gpg_error_t
502 acl_check_group (const char *name, uid_t uid, gid_t gid, int not, int *allowed)
504 char *buf;
505 struct group gr, *gresult;
506 size_t len = sysconf (_SC_GETGR_R_SIZE_MAX);
507 int err;
508 gpg_error_t rc = 0;
510 if (len == -1)
511 len = 16384;
513 buf = xmalloc (len);
514 if (!buf)
515 return GPG_ERR_ENOMEM;
517 err = getgrnam_r (name, &gr, buf, len, &gresult);
518 if (!err && gresult)
520 if (gresult->gr_gid == gid)
522 xfree (buf);
523 *allowed = !not;
524 return 0;
527 for (char **t = gresult->gr_mem; !rc && *t; t++)
529 char *tbuf;
530 struct passwd pw;
531 struct passwd *result = get_pwd_struct (*t, 0, &pw, &tbuf, &rc);
533 if (!rc && result && result->pw_uid == uid)
535 xfree (tbuf);
536 *allowed = !not;
537 break;
540 xfree (tbuf);
543 xfree (buf);
544 return rc;
546 else if (err)
547 rc = gpg_error_from_errno (err);
549 xfree (buf);
550 return rc ? rc : !gresult ? 0 : GPG_ERR_EACCES;
552 #else
553 static gpg_error_t
554 acl_check_group (const char *name, uid_t uid, gid_t gid, int not, int *allowed)
556 struct group *gresult;
557 gpg_error_t rc = 0;
559 errno = 0;
560 gresult = getgrnam (name);
561 if (!errno && gresult && gresult->gr_gid == gid)
563 *allowed = !not;
564 return 0;
566 else if (errno)
567 rc = gpg_error_from_syserror ();
568 else if (!gresult)
569 return 0;
571 for (char **t = gresult->gr_mem; !rc && *t; t++)
573 char *buf;
574 struct passwd pw;
575 struct passwd *result = get_pwd_struct (*t, 0, &pw, &buf, &rc);
577 if (!rc && result && result->pw_uid == uid)
579 xfree (buf);
580 *allowed = !not;
581 break;
584 xfree (buf);
587 return rc;
589 #endif
591 gpg_error_t
592 peer_is_invoker(struct client_s *client)
594 struct invoking_user_s *user;
595 int allowed = 0;
597 if (client->thd->state == CLIENT_STATE_UNKNOWN)
598 return GPG_ERR_EACCES;
600 for (user = invoking_users; user; user = user->next)
602 #ifdef WITH_GNUTLS
603 if (client->thd->remote)
605 if (user->type == INVOKING_TLS
606 && !strcmp(client->thd->tls->fp, user->id))
607 allowed = user->not ? 0 : 1;
609 continue;
611 #endif
613 if (user->type == INVOKING_GID)
615 gpg_error_t rc = acl_check_group (user->id,
616 client->thd->peer->uid,
617 client->thd->peer->gid,
618 user->not, &allowed);
619 if (rc)
620 return rc;
622 else if (user->type == INVOKING_UID && client->thd->peer->uid == user->uid)
623 allowed = user->not ? 0 : 1;
626 return allowed ? 0 : GPG_ERR_EACCES;
629 #ifdef HAVE_GETGRNAM_R
630 gpg_error_t
631 acl_check_common (struct client_s *client, const char *user, uid_t uid,
632 gid_t gid, int *allowed)
634 int not = 0;
635 int rw = 0;
636 int tls = 0;
637 gpg_error_t rc = 0;
639 if (!user || !*user)
640 return 0;
642 if (*user == '-' || *user == '!')
643 not = 1;
645 if (*user == '+') // not implemented yet
646 rw = 1;
648 if (*user == '#') // TLS fingerprint hash
649 tls = 1;
651 if (not || rw || tls)
652 user++;
654 if (tls)
656 #ifdef WITH_GNUTLS
657 if (client->thd->remote)
659 if (!strcasecmp (client->thd->tls->fp, user))
660 *allowed = !not;
663 return 0;
664 #else
665 return 0;
666 #endif
668 #ifdef WITH_GNUTLS
669 else if (client->thd->remote) // Remote client with no FP in the ACL
670 return 0;
671 #endif
673 if (*user == '@') // all users in group
674 return acl_check_group (user+1, uid, gid, not, allowed);
675 else
677 char *buf;
678 struct passwd pw;
679 struct passwd *pwd = get_pwd_struct (user, 0, &pw, &buf, &rc);
681 if (!rc && pwd && pwd->pw_uid == uid)
682 *allowed = !not;
684 xfree (buf);
687 return rc;
689 #else
690 gpg_error_t
691 acl_check_common (struct client_s *client, const char *user, uid_t uid,
692 gid_t gid, int *allowed)
694 gpg_error_t rc = 0;
695 int not = 0;
696 int rw = 0;
697 int tls = 0;
699 if (!user || !*user)
700 return 0;
702 if (*user == '-' || *user == '!')
703 not = 1;
705 if (*user == '+') // not implemented yet
706 rw = 1;
708 if (*user == '#') // TLS fingerprint hash
709 tls = 1;
711 if (not || rw || tls)
712 user++;
714 if (tls)
716 #ifdef WITH_GNUTLS
717 if (client->thd->remote)
719 if (!strcasecmp (client->thd->tls->fp, user))
720 *allowed = !not;
723 return 0;
724 #else
725 return 0;
726 #endif
729 if (*user == '@') // all users in group
730 return acl_check_group (user+1, uid, gid, not, allowed);
731 else
733 char *buf;
734 struct passwd pw;
735 struct passwd *result = get_pwd_struct (user, 0, &pw, &buf, &rc);
737 if (!rc && result && result->pw_uid == uid)
738 *allowed = !not;
740 xfree (buf);
743 return rc;
745 #endif
747 static gpg_error_t
748 validate_peer (struct client_s *cl)
750 gpg_error_t rc;
752 #ifdef WITH_GNUTLS
753 if (cl->thd->remote)
754 return tls_validate_access (cl, NULL);
755 #endif
757 MUTEX_LOCK (&cn_mutex);
758 pthread_cleanup_push (release_mutex_cb, &cn_mutex);
759 rc = do_validate_peer (cl->ctx, "global", &cl->thd->peer);
760 pthread_cleanup_pop (1);
761 log_write ("peer %s: uid=%i, gid=%i, pid=%i, rc=%u",
762 !rc ? _("accepted") : _("rejected"), cl->thd->peer->uid,
763 cl->thd->peer->gid, cl->thd->peer->pid, rc);
764 return rc;
767 static void
768 xml_error_cb (void *data, xmlErrorPtr e)
770 struct client_s *client = data;
773 * Keep the first reported error as the one to show in the error
774 * description. Reset in send_error().
776 if (client->xml_error)
777 return;
779 client->xml_error = xcalloc (1, sizeof(xmlError));
780 xmlCopyError (e, client->xml_error);
783 static pid_t
784 hook_waitpid (assuan_context_t ctx, pid_t pid, int action,
785 int *status, int options)
787 return waitpid (pid, status, options);
790 static ssize_t
791 hook_read (assuan_context_t ctx, assuan_fd_t fd, void *data, size_t len)
793 #ifdef WITH_GNUTLS
794 struct client_s *client = assuan_get_pointer (ctx);
796 if (client->thd->remote)
797 return tls_read_hook (ctx, (int) fd, data, len);
798 #endif
800 return read ((int) fd, data, len);
803 static ssize_t
804 hook_write (assuan_context_t ctx, assuan_fd_t fd,
805 const void *data, size_t len)
807 #ifdef WITH_GNUTLS
808 struct client_s *client = assuan_get_pointer (ctx);
810 if (client->thd->remote)
811 return tls_write_hook (ctx, (int) fd, data, len);
812 #endif
814 return write ((int) fd, data, len);
818 assuan_log_cb (assuan_context_t ctx, void *data, unsigned cat,
819 const char *msg)
821 struct client_s *client = data;
822 char *str = NULL;
824 (void)client;
826 if (!(assuan_level & cat))
827 return 0;
829 if (!msg)
830 return 1;
832 switch (cat)
834 case ASSUAN_LOG_INIT:
835 str = "ASSUAN[INIT]";
836 break;
837 case ASSUAN_LOG_CTX:
838 str = "ASSUAN[CTX]";
839 break;
840 case ASSUAN_LOG_ENGINE:
841 str = "ASSUAN[ENGINE]";
842 break;
843 case ASSUAN_LOG_DATA:
844 str = "ASSUAN[DATA]";
845 break;
846 case ASSUAN_LOG_SYSIO:
847 str = "ASSUAN[SYSIO]";
848 break;
849 case ASSUAN_LOG_CONTROL:
850 str = "ASSUAN[CONTROL]";
851 break;
852 default:
853 str = "ASSUAN[UNKNOWN]";
854 break;
857 log_write ("%s: %s", str, msg);
858 return 1;
861 static int
862 new_connection (struct client_s *cl)
864 gpg_error_t rc;
865 static struct assuan_malloc_hooks mhooks = { xmalloc, xrealloc, xfree };
866 static struct assuan_system_hooks shooks = {
867 ASSUAN_SYSTEM_HOOKS_VERSION,
868 __assuan_usleep,
869 __assuan_pipe,
870 __assuan_close,
871 hook_read,
872 hook_write,
873 //FIXME
874 NULL, //recvmsg
875 NULL, //sendmsg both are used for FD passing
876 __assuan_spawn,
877 hook_waitpid,
878 __assuan_socketpair,
879 __assuan_socket,
880 __assuan_connect
883 #ifdef WITH_GNUTLS
884 if (cl->thd->remote)
886 char *prio = config_get_string ("global", "tls_cipher_suite");
888 cl->thd->timeout = config_get_integer ("global", "tls_timeout");
889 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
890 return 0;
892 cl->thd->tls = tls_init_client (cl->thd->fd, cl->thd->timeout, prio);
893 xfree (prio);
894 if (!cl->thd->tls)
895 return 0;
897 #endif
899 rc = assuan_new_ext (&cl->ctx, GPG_ERR_SOURCE_DEFAULT, &mhooks,
900 assuan_log_cb, cl);
901 if (rc)
902 goto fail;
904 assuan_ctx_set_system_hooks (cl->ctx, &shooks);
905 rc = assuan_init_socket_server (cl->ctx, cl->thd->fd, 2);
906 if (rc)
907 goto fail;
909 assuan_set_pointer (cl->ctx, cl);
910 assuan_set_hello_line (cl->ctx, PACKAGE_STRING);
911 rc = register_commands (cl->ctx);
912 if (rc)
913 goto fail;
915 rc = assuan_accept (cl->ctx);
916 if (rc)
917 goto fail;
919 rc = validate_peer (cl);
920 /* May not be implemented on all platforms. */
921 if (rc && gpg_err_code (rc) != GPG_ERR_ASS_GENERAL)
922 goto fail;
924 MUTEX_LOCK (&cn_mutex);
925 cl->thd->state = CLIENT_STATE_INIT;
926 MUTEX_UNLOCK (&cn_mutex);
927 cl->lock_timeout = config_get_integer ("global", "lock_timeout");
928 xmlSetStructuredErrorFunc (cl, xml_error_cb);
929 return 1;
931 fail:
932 log_write ("%s", pwmd_strerror (rc));
933 return 0;
937 * This is called after a client_thread() terminates. Set with
938 * pthread_cleanup_push().
940 static void
941 free_client_cb (void *arg)
943 struct client_thread_s *cn = arg;
944 struct client_s *cl = cn->cl;
945 #ifndef HAVE_PTHREAD_CANCEL
946 char *tmp = pthread_getspecific (signal_thread_key);
948 xfree (tmp);
949 pthread_setspecific (signal_thread_key, NULL);
950 #endif
951 MUTEX_LOCK (&cn_mutex);
952 cn_thread_list = slist_remove (cn_thread_list, cn);
953 MUTEX_UNLOCK (&cn_mutex);
955 if (cl)
957 unlock_flock (&cl->flock_fd);
958 reset_client (cl);
959 if (cl->xml_error)
960 xmlResetError (cl->xml_error);
962 xfree (cl->xml_error);
964 #ifdef WITH_GNUTLS
965 if (cn->tls)
967 gnutls_deinit (cn->tls->ses);
968 xfree (cn->tls->fp);
969 xfree (cn->tls);
971 #endif
973 if (cl->ctx)
974 assuan_release (cl->ctx);
975 else if (cl->thd && cl->thd->fd != -1)
976 close (cl->thd->fd);
978 if (cl->crypto)
979 crypto_free (cl->crypto);
981 cl->crypto = NULL;
982 xfree (cl);
984 else
986 if (cn->fd != -1)
987 close (cn->fd);
990 while (cn->msg_queue)
992 struct status_msg_s *msg = cn->msg_queue;
994 cn->msg_queue = msg->next;
995 xfree (msg->line);
996 xfree (msg);
999 if (cn->status_msg_pipe[0] != -1)
1000 close (cn->status_msg_pipe[0]);
1002 if (cn->status_msg_pipe[1] != -1)
1003 close (cn->status_msg_pipe[1]);
1005 pthread_mutex_destroy (&cn->status_mutex);
1006 log_write (_("exiting, fd=%i"), cn->fd);
1007 send_status_all (STATUS_CLIENTS, NULL);
1009 #ifdef WITH_GNUTLS
1010 xfree (cn->peeraddr);
1011 #endif
1012 xfree (cn);
1015 void
1016 free_all_clients ()
1018 MUTEX_LOCK (&cn_mutex);
1019 pthread_cleanup_push (release_mutex_cb, &cn_mutex);
1021 while (slist_length (cn_thread_list))
1023 struct client_thread_s *thd = slist_nth_data (cn_thread_list, 0);
1025 free_client_cb (thd);
1028 pthread_cleanup_pop (1);
1031 static gpg_error_t
1032 send_msg_queue (struct client_thread_s *thd)
1034 MUTEX_LOCK (&thd->status_mutex);
1035 gpg_error_t rc = 0;
1036 char c;
1037 ssize_t ret;
1039 ret = read (thd->status_msg_pipe[0], &c, 1);
1040 rc = gpg_error_from_syserror ();
1041 if (ret == -1 && gpg_err_code (rc) != GPG_ERR_EAGAIN)
1042 log_write ("%s (%i): %s", __FUNCTION__, __LINE__, pwmd_strerror (rc));
1043 else
1044 rc = 0;
1046 thd->wrote_status = 0;
1048 while (thd->msg_queue)
1050 struct status_msg_s *msg = thd->msg_queue;
1052 #ifndef HAVE_PTHREAD_CANCEL
1053 if (thd->fd == -1)
1054 break;
1055 #endif
1057 thd->msg_queue = thd->msg_queue->next;
1058 MUTEX_UNLOCK (&thd->status_mutex);
1059 rc = send_status (thd->cl->ctx, msg->s, msg->line);
1060 MUTEX_LOCK (&thd->status_mutex);
1061 xfree (msg->line);
1062 xfree (msg);
1064 if (rc)
1065 break;
1068 MUTEX_UNLOCK (&thd->status_mutex);
1069 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1070 log_write ("%s (%i): %s", __FUNCTION__, __LINE__, pwmd_strerror (rc));
1072 return rc;
1075 static void *
1076 client_thread (void *data)
1078 struct client_thread_s *thd = data;
1079 struct client_s *cl = xcalloc (1, sizeof (struct client_s));
1080 struct slist_s *list;
1081 gpg_error_t rc;
1082 #ifndef HAVE_PTHREAD_CANCEL
1083 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
1084 #endif
1086 #ifdef HAVE_PR_SET_NAME
1087 prctl (PR_SET_NAME, "client");
1088 #endif
1089 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1091 if (!cl)
1093 log_write ("%s(%i): %s", __FILE__, __LINE__,
1094 pwmd_strerror (GPG_ERR_ENOMEM));
1095 return NULL;
1098 MUTEX_LOCK (&cn_mutex);
1099 pthread_cleanup_push (free_client_cb, thd);
1100 thd->cl = cl;
1101 cl->thd = thd;
1102 cl->flock_fd = -1;
1104 list = slist_append (cn_thread_list, thd);
1105 if (list)
1106 cn_thread_list = list;
1107 else
1109 log_write ("%s(%i): %s", __FILE__, __LINE__,
1110 pwmd_strerror (GPG_ERR_ENOMEM));
1111 MUTEX_UNLOCK (&cn_mutex);
1112 return NULL;
1115 if (fcntl (thd->status_msg_pipe[0], F_SETFL, O_NONBLOCK) == -1)
1116 rc = gpg_error_from_errno (errno);
1118 if (!rc)
1119 if (fcntl (thd->status_msg_pipe[1], F_SETFL, O_NONBLOCK) == -1)
1120 rc = gpg_error_from_errno (errno);
1122 MUTEX_UNLOCK (&cn_mutex);
1124 if (rc)
1126 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
1127 return NULL;
1130 if (new_connection (cl))
1132 int finished = 0;
1133 gpg_error_t rc;
1134 struct pollfd fds[2];
1136 fds[0].fd = thd->fd;
1137 fds[0].events = POLLIN;
1138 fds[1].fd = thd->status_msg_pipe[0];
1139 fds[1].events = POLLIN;
1141 send_status_all (STATUS_CLIENTS, NULL);
1142 rc = send_status (cl->ctx, STATUS_CACHE, NULL);
1143 if (rc)
1145 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
1146 finished = 1;
1149 while (!finished)
1151 int n;
1152 int eof;
1154 n = poll (fds, 2, 100);
1155 if (n == -1)
1157 log_write ("%s", strerror (errno));
1158 break;
1161 #ifdef WITH_GNUTLS
1162 if (thd->remote && thd->tls && thd->tls->rehandshake)
1164 char *prio;
1165 int ret;
1166 const char *e;
1168 if (thd->tls->rehandshake == 1)
1170 prio = config_get_string ("global", "tls_cipher_suite");
1171 if (!prio)
1173 thd->tls->rehandshake = 0;
1174 continue;
1177 ret = gnutls_priority_set_direct (thd->tls->ses, prio, &e);
1178 if (ret == GNUTLS_E_SUCCESS)
1180 rc = send_status (cl->ctx, STATUS_REHANDSHAKE, NULL);
1181 if (!rc)
1183 rc = assuan_send_data (cl->ctx, NULL, 0);
1184 if (!rc)
1186 ret = gnutls_rehandshake (thd->tls->ses);
1187 if (ret)
1189 log_write ("%s", gnutls_strerror (ret));
1190 thd->tls->rehandshake = 0;
1192 else
1193 thd->tls->rehandshake = 2;
1197 if (rc)
1198 log_write ("%s", pwmd_strerror (rc));
1200 else
1201 log_write ("%s: %s", gnutls_strerror (ret), e);
1203 xfree (prio);
1204 continue;
1207 #endif
1209 if (!n)
1210 continue;
1212 if (fds[1].revents & POLLIN)
1214 #ifdef WITH_GNUTLS
1215 if (!thd->remote || (thd->tls && !thd->tls->rehandshake))
1216 #endif
1218 rc = send_msg_queue (thd);
1219 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1220 break;
1224 #ifdef HAVE_PTHREAD_CANCEL
1225 if (!(fds[0].revents & POLLIN))
1226 #else
1227 if (thd->fd != -1 && !(fds[0].revents & POLLIN))
1228 #endif
1229 continue;
1231 rc = assuan_process_next (cl->ctx, &eof);
1232 if (rc || eof)
1234 if (gpg_err_code (rc) == GPG_ERR_EOF || eof)
1235 break;
1237 log_write ("assuan_process_next(): rc=%u %s", rc,
1238 pwmd_strerror (rc));
1239 if (rc == gpg_error (GPG_ERR_ETIMEDOUT))
1240 break;
1242 rc = send_error (cl->ctx, rc);
1243 if (rc)
1245 log_write ("assuan_process_done(): rc=%u %s", rc,
1246 pwmd_strerror (rc));
1247 break;
1251 /* Since the msg queue pipe fd's are non-blocking, check for
1252 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1253 * client has already disconnected and will be converted to
1254 * GPG_ERR_EOF during assuan_process_next().
1256 #ifdef WITH_GNUTLS
1257 if (!thd->remote || (thd->tls && !thd->tls->rehandshake))
1258 #endif
1260 rc = send_msg_queue (thd);
1261 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1262 break;
1267 /* Don't do pthread_exit() here because any set pthread_cleanup_push
1268 * functions would be called after a command failed but then the client
1269 * exited normally which may lead to a double free. */
1270 pthread_cleanup_pop (1);
1271 return NULL;
1274 static gpg_error_t
1275 xml_import (const char *filename, const char *outfile, char **keyid,
1276 char **sign_keyid, char *keyfile, const char *keyparam,
1277 int symmetric)
1279 xmlDocPtr doc;
1280 int fd;
1281 struct stat st;
1282 int len;
1283 xmlChar *xmlbuf;
1284 gpg_error_t rc = 0;
1285 struct crypto_s *crypto = NULL;
1287 if (stat (filename, &st) == -1)
1289 rc = gpg_error_from_errno (errno);
1290 return rc;
1293 fd = open (filename, O_RDONLY);
1294 if (fd == -1)
1295 return gpg_error_from_errno (errno);
1297 xmlbuf = xmalloc (st.st_size + 1);
1298 if (!xmlbuf)
1300 close (fd);
1301 return GPG_ERR_ENOMEM;
1304 if (read (fd, xmlbuf, st.st_size) == -1)
1306 rc = gpg_error_from_errno (errno);
1307 close (fd);
1308 xfree (xmlbuf);
1309 return rc;
1312 close (fd);
1313 xmlbuf[st.st_size] = 0;
1314 // Be sure the document validates.
1315 doc = xmlReadDoc (xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS);
1316 xfree (xmlbuf);
1317 if (!doc)
1318 return GPG_ERR_BAD_DATA;
1320 xmlNodePtr n = xmlDocGetRootElement (doc);
1321 if (n && !xmlStrEqual (n->name, (xmlChar *) "pwmd"))
1322 rc = GPG_ERR_BAD_DATA;
1324 if (!rc)
1326 rc = xml_validate_import (NULL, n ? n->children : n);
1327 if (!rc)
1329 rc = crypto_init (&crypto, NULL, filename, keyfile != NULL, keyfile);
1330 if (!rc)
1332 if (keyfile)
1334 crypto->flags |= CRYPTO_FLAG_KEYFILE;
1335 crypto->keyfile = str_dup (keyfile);
1338 xmlDocDumpMemory (doc, &crypto->plaintext, &len);
1339 if (len > 0)
1340 crypto->plaintext_size = len;
1341 else
1342 rc = GPG_ERR_ENOMEM;
1347 if (!rc)
1349 if (!symmetric && (keyparam || !keyid))
1351 char *buf = NULL;
1353 if (keyparam)
1355 fd = open (keyparam, O_RDONLY);
1356 if (fd == -1)
1357 rc = gpg_error_from_errno (errno);
1359 if (!rc)
1361 if (stat (keyparam, &st) == -1)
1362 rc = gpg_error_from_errno (errno);
1364 if (!rc)
1366 buf = xmalloc (st.st_size+1);
1367 if (!buf)
1368 rc = GPG_ERR_ENOMEM;
1370 if (!rc)
1372 len = read (fd, buf, st.st_size);
1373 if (len != st.st_size)
1374 rc = gpg_error_from_errno (errno);
1376 if (!rc)
1377 buf[len] = 0;
1382 if (fd != -1)
1383 close (fd);
1385 else
1387 buf = crypto_default_key_params ();
1388 if (!buf)
1389 rc = GPG_ERR_ENOMEM;
1392 if (!rc)
1393 rc = crypto_genkey (NULL, crypto, (unsigned char *)buf);
1395 xfree (buf);
1397 else
1399 crypto->save.pubkey = strv_dup (keyid);
1400 crypto->save.sigkey = strv_dup (sign_keyid);
1403 if (!rc)
1405 crypto->flags |= symmetric ? CRYPTO_FLAG_SYMMETRIC : 0;
1406 rc = crypto_encrypt (NULL, crypto);
1410 if (!rc)
1412 if (!strcmp (outfile, "-"))
1413 outfile = NULL;
1415 xfree (crypto->plaintext);
1416 crypto->plaintext = NULL;
1417 xfree (crypto->filename);
1418 crypto->filename = outfile ? str_dup (outfile) : NULL;
1419 rc = crypto_write_file (crypto);
1422 xmlFreeDoc (doc);
1423 crypto_free (crypto);
1424 return rc;
1427 static gpg_error_t
1428 do_cache_push (struct crypto_s *crypto)
1430 gpg_error_t rc;
1431 xmlDocPtr doc;
1432 struct cache_data_s *cdata;
1433 unsigned char *crc;
1434 size_t len;
1435 int fd = -1;
1437 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1438 crypto->filename);
1440 if (valid_filename (crypto->filename) == 0)
1442 log_write (_("%s: Invalid characters in filename"), crypto->filename);
1443 return GPG_ERR_INV_VALUE;
1446 rc = lock_flock (NULL, crypto->filename, LOCK_SH, &fd);
1447 if (!rc)
1448 rc = crypto_decrypt (NULL, crypto);
1449 if (rc)
1451 unlock_flock (&fd);
1452 return rc;
1455 rc = xml_parse_doc ((char *) crypto->plaintext, crypto->plaintext_size, &doc);
1456 if (rc)
1458 unlock_flock (&fd);
1459 log_write ("%s", pwmd_strerror (rc));
1460 return rc;
1463 cdata = xcalloc (1, sizeof (struct cache_data_s));
1464 if (!cdata)
1466 unlock_flock (&fd);
1467 xmlFreeDoc (doc);
1468 return GPG_ERR_ENOMEM;
1471 rc = get_checksum (crypto->filename, &crc, &len);
1472 unlock_flock (&fd);
1473 if (rc)
1475 xmlFreeDoc (doc);
1476 cache_free_data_once (cdata);
1477 return rc;
1480 cdata->crc = crc;
1481 rc = cache_encrypt (crypto);
1482 if (!rc)
1484 cdata->doc = crypto->plaintext;
1485 cdata->size = crypto->plaintext_size;
1486 crypto->plaintext = NULL;
1487 cdata->pubkey = crypto->pubkey;
1488 cdata->sigkey = crypto->sigkey;
1489 crypto->pubkey = NULL;
1490 crypto->sigkey = NULL;
1492 else
1494 xmlFreeDoc (doc);
1495 cache_free_data_once (cdata);
1496 return rc;
1499 int timeout = config_get_integer (crypto->filename, "cache_timeout");
1500 rc = cache_add_file (crypto->filename, cdata, timeout);
1501 return rc;
1504 static gpg_error_t
1505 init_client (int fd, const char *addr)
1507 gpg_error_t rc = 0;
1508 struct client_thread_s *new = xcalloc (1, sizeof (struct client_thread_s));
1510 if (!new)
1512 close (fd);
1513 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (ENOMEM));
1514 return GPG_ERR_ENOMEM;
1517 MUTEX_LOCK (&cn_mutex);
1518 pthread_cleanup_push (release_mutex_cb, &cn_mutex);
1519 new->conntime = time (NULL);
1521 if (pipe (new->status_msg_pipe) == -1)
1522 rc = gpg_error_from_errno (errno);
1523 else
1524 pthread_mutex_init (&new->status_mutex, NULL);
1526 if (!rc)
1528 #ifdef WITH_GNUTLS
1529 new->remote = addr ? 1 : 0;
1530 if (addr)
1531 new->peeraddr = str_dup (addr);
1532 #endif
1533 new->fd = fd;
1534 rc = create_thread (client_thread, new, &new->tid, 1);
1535 if (rc)
1537 close (new->status_msg_pipe[0]);
1538 close (new->status_msg_pipe[1]);
1539 pthread_mutex_destroy (&new->status_mutex);
1543 if (!rc)
1545 if (addr)
1546 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1547 (pthread_t *) new->tid, fd, addr);
1548 else
1549 log_write (_("new connection: tid=%p, fd=%i"),
1550 (pthread_t *) new->tid, fd);
1553 pthread_cleanup_pop (1);
1555 if (rc)
1557 xfree (new);
1558 close (fd);
1559 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
1561 return rc;
1564 #ifdef WITH_GNUTLS
1565 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1566 static void *
1567 get_in_addr (struct sockaddr *sa)
1569 if (sa->sa_family == AF_INET)
1570 return &(((struct sockaddr_in *) sa)->sin_addr);
1572 return &(((struct sockaddr_in6 *) sa)->sin6_addr);
1575 static int
1576 start_stop_tls_with_protocol (int ipv6, int term)
1578 struct addrinfo hints, *servinfo, *p;
1579 int port = config_get_integer ("global", "tcp_port");
1580 char buf[7];
1581 int n;
1582 int *fd = ipv6 ? &tls6_fd : &tls_fd;
1584 if (term || config_get_boolean ("global", "enable_tcp") == 0)
1586 if (tls6_fd != -1)
1588 shutdown (tls6_fd, SHUT_RDWR);
1589 close (tls6_fd);
1590 tls6_fd = -1;
1593 if (tls_fd != -1)
1595 shutdown (tls_fd, SHUT_RDWR);
1596 close (tls_fd);
1597 tls_fd = -1;
1600 return 0;
1603 memset (&hints, 0, sizeof (hints));
1604 hints.ai_family = ipv6 ? AF_INET6 : AF_INET;
1605 hints.ai_socktype = SOCK_STREAM;
1606 hints.ai_flags = AI_PASSIVE;
1607 snprintf (buf, sizeof (buf), "%i", port);
1609 if ((n = getaddrinfo (NULL, buf, &hints, &servinfo)) == -1)
1611 log_write ("getaddrinfo(): %s", gai_strerror (n));
1612 return 0;
1615 for (n = 0, p = servinfo; p != NULL; p = p->ai_next)
1617 int r = 1;
1619 if ((ipv6 && p->ai_family != AF_INET6)
1620 || (!ipv6 && p->ai_family != AF_INET))
1621 continue;
1623 if ((*fd = socket (p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
1625 log_write ("socket(): %s", strerror (errno));
1626 continue;
1629 if (setsockopt (*fd, SOL_SOCKET, SO_REUSEADDR, &r, sizeof (int)) == -1)
1631 log_write ("setsockopt(): %s",
1632 pwmd_strerror (gpg_error_from_errno (errno)));
1633 freeaddrinfo (servinfo);
1634 goto fail;
1637 if (bind (*fd, p->ai_addr, p->ai_addrlen) == -1)
1639 close (*fd);
1640 log_write ("bind(): %s",
1641 pwmd_strerror (gpg_error_from_errno (errno)));
1642 continue;
1645 n++;
1646 break;
1649 freeaddrinfo (servinfo);
1651 if (!n)
1652 goto fail;
1654 #if HAVE_DECL_SO_BINDTODEVICE != 0
1655 char *tmp = config_get_string ("global", "tcp_interface");
1656 if (tmp && setsockopt (*fd, SOL_SOCKET, SO_BINDTODEVICE, tmp,
1657 strlen (tmp)) == -1)
1659 log_write ("setsockopt(): %s",
1660 pwmd_strerror (gpg_error_from_errno (errno)));
1661 xfree (tmp);
1662 goto fail;
1665 xfree (tmp);
1666 #endif
1668 if (listen (*fd, 128) == -1)
1670 log_write ("listen(): %s", strerror (errno));
1671 goto fail;
1674 return 1;
1676 fail:
1677 start_stop_tls_with_protocol (0, 1);
1678 if (tls_fd != -1)
1679 close (tls_fd);
1681 if (tls6_fd != -1)
1682 close (tls6_fd);
1684 tls_fd = -1;
1685 tls6_fd = -1;
1686 return 0;
1689 static int
1690 start_stop_tls (int term)
1692 char *s = config_get_string ("global", "tcp_bind");
1693 int b;
1695 if (!s)
1696 return 0;
1698 if (!strcmp (s, "any"))
1700 b = start_stop_tls_with_protocol (0, term);
1701 if (b)
1702 b = start_stop_tls_with_protocol (1, term);
1704 else if (!strcmp (s, "ipv4"))
1705 b = start_stop_tls_with_protocol (0, term);
1706 else if (!strcmp (s, "ipv6"))
1707 b = start_stop_tls_with_protocol (1, term);
1708 else
1709 b = 0;
1711 xfree (s);
1712 if (!term && b)
1714 gpg_error_t rc = tls_init_params ();
1715 if (rc)
1717 start_stop_tls_with_protocol (0, 1);
1718 return 0;
1722 return b;
1724 #endif
1726 #ifdef WITH_GNUTLS
1727 static gpg_error_t
1728 do_tls_accept (struct pollfd *fds)
1730 struct sockaddr_storage raddr;
1731 socklen_t slen = sizeof (raddr);
1732 int fd;
1733 char s[INET6_ADDRSTRLEN];
1735 if (!(fds->revents & POLLIN))
1736 return 0;
1738 fd = accept (fds->fd, (struct sockaddr *) &raddr, &slen);
1739 if (fd == -1)
1741 int e = errno;
1743 if (errno != EAGAIN && !quit)
1744 log_write ("%s: %s", __FUNCTION__,
1745 pwmd_strerror (gpg_error_from_syserror()));
1747 return gpg_error_from_errno (e);
1750 inet_ntop (raddr.ss_family, get_in_addr ((struct sockaddr *) &raddr), s,
1751 sizeof s);
1752 (void) init_client (fd, s);
1753 return 0;
1755 #endif
1757 static void *
1758 accept_thread (void *arg)
1760 int sockfd = *(int *) arg;
1761 #ifndef HAVE_PTHREAD_CANCEL
1762 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
1763 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1764 #endif
1766 #ifdef HAVE_PR_SET_NAME
1767 prctl (PR_SET_NAME, "accept");
1768 #endif
1769 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
1771 for (;;)
1773 socklen_t slen = sizeof (struct sockaddr_un);
1774 struct sockaddr_un raddr;
1775 int fd, s = 0;
1776 struct pollfd fds[3];
1778 TEST_CANCEL ();
1779 memset (fds, 0, sizeof (fds));
1780 fds[s].fd = sockfd;
1781 fds[s++].events = POLLIN;
1783 #ifdef WITH_GNUTLS
1784 if (tls_fd != -1)
1786 fds[s].fd = tls_fd;
1787 fds[s++].events = POLLIN;
1789 else
1790 fds[s].fd = tls_fd;
1792 if (tls6_fd != -1)
1794 fds[s].fd = tls6_fd;
1795 fds[s++].events = POLLIN;
1797 else
1798 fds[s].fd = tls6_fd;
1799 #endif
1801 s = poll (fds, s, 500);
1802 if (s == -1)
1804 if (errno != EINTR)
1805 log_write ("%s", strerror (errno));
1806 break;
1808 else if (s == 0)
1809 continue;
1811 if (fds[0].revents & POLLIN)
1813 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1814 if (fd == -1)
1816 if (errno == EMFILE || errno == ENFILE)
1817 log_write ("%s: %s", __FUNCTION__,
1818 pwmd_strerror (gpg_error_from_errno (errno)));
1819 else if (errno != EAGAIN && errno != EINTR)
1821 if (!quit) // probably EBADF
1822 log_write ("%s: %s", __FUNCTION__,
1823 pwmd_strerror (gpg_error_from_errno (errno)));
1825 break;
1828 continue;
1831 (void) init_client (fd, NULL);
1834 #ifdef WITH_GNUTLS
1835 if (tls_fd != -1 && fds[1].fd == tls_fd)
1836 (void)do_tls_accept (&fds[1]);
1838 if (tls6_fd != -1 && fds[1].fd == tls6_fd)
1839 (void)do_tls_accept (&fds[1]);
1841 if (tls6_fd != -1 && fds[2].fd == tls6_fd)
1842 (void)do_tls_accept (&fds[2]);
1843 #endif
1846 /* Just in case accept() failed for some reason other than EBADF */
1847 quit = 1;
1848 return NULL;
1851 static void *
1852 cache_timer_thread (void *arg)
1854 unsigned k = 0;
1855 #ifndef HAVE_PTHREAD_CANCEL
1856 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
1857 #endif
1859 #ifdef HAVE_PR_SET_NAME
1860 prctl (PR_SET_NAME, "timer");
1861 #endif
1862 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
1864 for (;;)
1866 struct timeval tv = { 1, 0 };
1867 unsigned keepalive = config_get_integer ("global", "keepalive_interval");
1869 TEST_CANCEL ();
1870 select (0, NULL, NULL, NULL, &tv);
1871 cache_adjust_timeout ();
1873 if (++k >= keepalive)
1875 send_status_all (STATUS_KEEPALIVE, NULL);
1876 k = 0;
1880 return NULL;
1883 static int
1884 signal_loop (sigset_t sigset)
1886 int done = 0;
1887 int siint = 0;
1891 int sig;
1893 sigwait (&sigset, &sig);
1894 log_write (_("caught signal %i (%s)"), sig, strsignal (sig));
1896 switch (sig)
1898 case SIGHUP:
1899 pthread_cond_signal (&rcfile_cond);
1900 break;
1901 case SIGUSR1:
1902 log_write (_("clearing file cache"));
1903 cache_clear (NULL, NULL, 1);
1904 send_status_all (STATUS_CACHE, NULL);
1905 break;
1906 default:
1907 siint = 1;
1908 done = 1;
1909 break;
1912 while (!done);
1914 return siint;
1917 static void
1918 catchsig (int sig)
1920 log_write (_ ("Caught signal %i (%s). Exiting."), sig, strsignal (sig));
1921 #ifdef HAVE_BACKTRACE
1922 BACKTRACE (__FUNCTION__);
1923 #endif
1924 longjmp (jmp, 1);
1927 static void
1928 cancel_all_clients ()
1930 unsigned i, t;
1932 MUTEX_LOCK (&cn_mutex);
1933 t = slist_length (cn_thread_list);
1934 for (i = 0; i < t; i++)
1936 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
1938 #ifdef HAVE_PTHREAD_CANCEL
1939 pthread_cancel (thd->tid);
1940 #else
1941 pthread_kill (thd->tid, SIGUSR2);
1942 #endif
1945 while (slist_length (cn_thread_list))
1947 MUTEX_UNLOCK (&cn_mutex);
1948 usleep (50000);
1949 MUTEX_LOCK (&cn_mutex);
1952 MUTEX_UNLOCK (&cn_mutex);
1955 static int
1956 server_loop (int sockfd, char **socketpath)
1958 pthread_t cache_timeout_tid;
1959 int cancel_timeout_thread = 0, cancel_accept_thread = 0;
1960 sigset_t sigset;
1961 int n;
1962 int segv = 0;
1963 gpg_error_t rc;
1965 init_commands ();
1966 sigemptyset (&sigset);
1968 /* Termination */
1969 sigaddset (&sigset, SIGTERM);
1970 sigaddset (&sigset, SIGINT);
1972 /* Clears the file cache. */
1973 sigaddset (&sigset, SIGUSR1);
1975 /* Configuration file reloading. */
1976 sigaddset (&sigset, SIGHUP);
1978 #ifndef HAVE_PTHREAD_CANCEL
1980 The socket, cache and rcfile threads use this signal when
1981 pthread_cancel() is unavailable. Prevent the main thread from
1982 catching this signal from another process.
1984 sigaddset (&sigset, SIGUSR2);
1985 #endif
1987 /* An assertion failure. */
1988 signal (SIGABRT, catchsig);
1989 sigaddset (&sigset, SIGABRT);
1990 sigprocmask (SIG_BLOCK, &sigset, NULL);
1992 #ifndef HAVE_PTHREAD_CANCEL
1993 /* Remove this signal from the watched signals in signal_loop(). */
1994 sigdelset (&sigset, SIGUSR2);
1995 #endif
1997 /* Can show a backtrace of the stack in the log. */
1998 signal (SIGSEGV, catchsig);
2000 char *p = get_username (getuid());
2001 log_write (_("%s started for user %s"), PACKAGE_STRING, p);
2002 xfree (p);
2004 #ifdef WITH_GNUTLS
2005 if (config_get_boolean ("global", "enable_tcp"))
2006 log_write (_("Listening on %s and TCP port %i"), *socketpath,
2007 config_get_integer ("global", "tcp_port"));
2008 else
2009 log_write (_("Listening on %s"), *socketpath);
2010 #else
2011 log_write (_("Listening on %s"), *socketpath);
2012 #endif
2014 rc = create_thread (reload_rcfile_thread, NULL, &rcfile_tid, 0);
2015 if (rc)
2017 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2018 pwmd_strerror (rc));
2019 goto done;
2022 rc = create_thread (cache_timer_thread, NULL, &cache_timeout_tid, 0);
2023 if (rc)
2025 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2026 pwmd_strerror (rc));
2027 goto done;
2030 cancel_timeout_thread = 1;
2031 rc = create_thread (accept_thread, &sockfd, &accept_tid, 0);
2032 if (rc)
2034 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2035 pwmd_strerror (rc));
2036 goto done;
2039 cancel_accept_thread = 1;
2040 if (!setjmp (jmp))
2041 signal_loop (sigset);
2042 else
2043 segv = 1;
2045 done:
2047 * We're out of the main server loop. This happens when a signal was sent
2048 * to terminate the daemon. We'll wait for all clients to disconnect
2049 * before exiting but exit immediately if another termination signal is
2050 * sent.
2052 if (cancel_accept_thread)
2054 #ifdef HAVE_PTHREAD_CANCEL
2055 int n = pthread_cancel (accept_tid);
2056 #else
2057 int n = pthread_kill (accept_tid, SIGUSR2);
2058 #endif
2059 if (!n)
2060 pthread_join (accept_tid, NULL);
2063 if (cancel_timeout_thread)
2065 #ifdef HAVE_PTHREAD_CANCEL
2066 n = pthread_cancel (cache_timeout_tid);
2067 #else
2068 n = pthread_kill (cache_timeout_tid, SIGUSR2);
2069 #endif
2070 if (!n)
2071 pthread_join (cache_timeout_tid, NULL);
2074 #ifdef WITH_GNUTLS
2075 start_stop_tls (1);
2076 #endif
2077 shutdown (sockfd, SHUT_RDWR);
2078 close (sockfd);
2079 unlink (*socketpath);
2080 xfree (*socketpath);
2081 *socketpath = NULL;
2082 MUTEX_LOCK (&cn_mutex);
2083 n = slist_length (cn_thread_list);
2084 MUTEX_UNLOCK (&cn_mutex);
2086 if (n && !segv)
2087 cancel_all_clients ();
2088 else
2089 free_all_clients ();
2091 cache_deinit ();
2092 deinit_commands ();
2093 return segv ? EXIT_FAILURE : EXIT_SUCCESS;;
2096 static void
2097 startup_failure ()
2099 log_write (_
2100 ("Failed to add a file to the cache. Use --force to force startup. Exiting."));
2101 cache_clear (NULL, NULL, 1);
2104 static void
2105 usage (const char *pn, int status)
2107 FILE *fp = status == EXIT_FAILURE ? stderr : stdout;
2109 fprintf (fp, _("Usage: %s [OPTIONS] [file1] [...]\n"
2110 " --debug=[a:..][,g:N][,t:N] enable debugging (a:[ixedsc],g:[1-9],t:[0-N])\n"
2111 " -f, --rcfile=filename load the specfied configuration file\n"
2112 " (~/.pwmd/config)\n"
2113 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2114 " --kill terminate an existing instance of pwmd\n"
2115 " -n, --no-fork run as a foreground process\n"
2116 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2117 " --ignore, --force ignore file errors during startup\n"
2118 " -o, --outfile=filename output file when importing or converting\n"
2119 " -C, --convert=filename convert a version 2 data file to version 3\n"
2120 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2121 " -k, --passphrase-file=file for use when importing or converting\n"
2122 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2123 " converting\n"
2124 " --no-passphrase when importing or converting\n"
2125 " --keyid=keyID[,..] public key to use when encrypting\n"
2126 " --sign-keyid=fpr[,..] fingerprint of the signing key to use\n"
2127 " --symmetric use conventional encryption with optional signer\n"
2128 " --keyparam=filename custom key parameters to use (gpg default)\n"
2129 " --help this help text\n"
2130 " --version show version and compile time features\n"),
2131 pn);
2132 exit (status);
2135 static void
2136 unlink_stale_socket (const char *sock, const char *pidfile)
2138 log_write (_ ("removing stale socket %s"), sock);
2139 unlink (sock);
2140 unlink (pidfile);
2143 static int
2144 test_pidfile (const char *path, const char *sock, char *buf, size_t buflen,
2145 char **pidfile, int create, mode_t mode, int terminate)
2147 pid_t pid;
2148 int fd;
2149 size_t len;
2151 if (!create)
2153 snprintf (buf, buflen, "%s/%s.pid", homedir, sock);
2154 *pidfile = str_dup (buf);
2155 fd = open (buf, O_RDONLY);
2157 else
2158 fd = open (*pidfile, O_CREAT|O_WRONLY|O_TRUNC, mode);
2160 if (fd == -1)
2162 if (!create && errno != ENOENT)
2164 log_write ("%s: %s", buf, pwmd_strerror (errno));
2165 free (*pidfile);
2166 *pidfile = NULL;
2167 return -1;
2169 else if (!create && !terminate)
2170 return 0;
2172 log_write ("%s: %s", *pidfile, strerror (errno));
2173 return -1;
2176 if (create)
2178 snprintf (buf, buflen, "%i", getpid ());
2179 ssize_t ret = write (fd, buf, strlen (buf));
2180 if (ret == -1)
2181 log_write ("%s (%i): %s", __FUNCTION__, __LINE__,
2182 pwmd_strerror (gpg_error_from_syserror ()));
2183 close (fd);
2184 return 0;
2187 len = read (fd, buf, buflen);
2188 close (fd);
2189 if (len == 0)
2191 unlink_stale_socket (path, *pidfile);
2192 return 0;
2195 if (sscanf (buf, "%5i", &pid) != 1 || pid == 0)
2197 if (!terminate)
2199 unlink_stale_socket (path, *pidfile);
2200 return 0;
2204 if (kill (pid, 0) == -1)
2206 unlink_stale_socket (path, *pidfile);
2207 return 0;
2210 if (terminate)
2212 if (kill (pid, SIGTERM) == -1)
2213 log_write ("%s: %s", path, pwmd_strerror (errno));
2215 else
2216 log_write (_ ("an instance for socket %s is already running"), path);
2218 xfree (*pidfile);
2219 *pidfile = NULL;
2220 return 1;
2223 static unsigned
2224 parse_debug_level (const char *str, unsigned *debug, int *gpgme, int *tls)
2226 const char *p;
2227 unsigned level = 0;
2228 int gl = 0, tl = 0;
2230 for (p = str; p && *p; p++)
2232 if (*p == 'a') // assuan debug flags
2234 if (*++p != ':')
2235 return 1;
2237 while (*++p)
2239 switch (*p)
2241 case 'i':
2242 level |= ASSUAN_LOG_INIT;
2243 break;
2244 case 'x':
2245 level |= ASSUAN_LOG_CTX;
2246 break;
2247 case 'e':
2248 level |= ASSUAN_LOG_ENGINE;
2249 break;
2250 case 'd':
2251 level |= ASSUAN_LOG_DATA;
2252 break;
2253 case 's':
2254 level |= ASSUAN_LOG_SYSIO;
2255 break;
2256 case 'c':
2257 level |= ASSUAN_LOG_CONTROL;
2258 break;
2259 case ',':
2260 break;
2261 default:
2262 return 1;
2265 if (*p == ',')
2266 break;
2269 if (!*p)
2270 break;
2272 else if (*p == 'g' || *p == 't') // gpgme and TLS debug level
2274 int t = *p == 't';
2275 int n;
2277 if (*++p != ':')
2278 return 1;
2280 if (!isdigit (*++p))
2281 return 1;
2283 n = atoi (p);
2284 if (t)
2285 tl = n;
2286 else
2287 gl = n;
2289 if (tl < 0 || gl < 0 || gl > 9)
2290 return 1;
2292 while (isdigit (*p))
2293 p++;
2295 p--;
2296 if (*(p+1) && *(p+1) != ',')
2297 return 1;
2298 else if (*(p+1))
2299 p++;
2301 else
2302 return 1;
2305 if (tl)
2306 *tls = tl;
2308 if (gl)
2309 *gpgme = gl;
2311 *debug = level;
2312 return 0;
2316 main (int argc, char *argv[])
2318 int opt;
2319 struct sockaddr_un addr;
2320 char buf[PATH_MAX];
2321 char *socketpath = NULL, *socketdir, *socketname = NULL;
2322 char *socketarg = NULL;
2323 char *datadir = NULL;
2324 char *pidfile = NULL;
2325 mode_t mode = 0600;
2326 int x;
2327 char *p;
2328 char **cache_push = NULL;
2329 char *import = NULL, *keyid = NULL, *sign_keyid = NULL;
2330 char *keyparam = NULL;
2331 int estatus = EXIT_FAILURE;
2332 int sockfd;
2333 char *outfile = NULL;
2334 int do_unlink = 0;
2335 int secure = 0;
2336 int show_version = 0;
2337 int force = 0;
2338 gpg_error_t rc;
2339 char *keyfile = NULL;
2340 int exists;
2341 int optindex;
2342 int terminate = 0;
2343 int sym = 0;
2344 int gpgme_level = -1;
2345 int tls_level = -1;
2346 /* Must maintain the same order as longopts[] */
2347 enum
2349 OPT_VERSION, OPT_HELP, OPT_HOMEDIR, OPT_NO_FORK, OPT_DISABLE_DUMP,
2350 OPT_FORCE, OPT_RCFILE, OPT_PASSPHRASE_FILE, OPT_IMPORT, OPT_OUTFILE,
2351 OPT_KEYID, OPT_SIGN_KEYID, OPT_SYMMETRIC, OPT_KEYPARAM, OPT_KILL,
2352 OPT_DEBUG
2354 const char *optstring = "nf:C:k:I:o:s";
2355 const struct option longopts[] = {
2356 {"version", no_argument, 0, 0},
2357 {"help", no_argument, 0, 0},
2358 {"homedir", required_argument, 0, 0},
2359 {"no-fork", no_argument, 0, 'n'},
2360 {"disable_dump", no_argument, 0, 0},
2361 {"force", no_argument, 0, 0},
2362 {"rcfile", required_argument, 0, 'f'},
2363 {"passphrase-file", required_argument, 0, 'k'},
2364 {"import", required_argument, 0, 'I'},
2365 {"outfile", required_argument, 0, 'o'},
2366 {"keyid", required_argument, 0, 0},
2367 {"sign-keyid", required_argument, 0, 0},
2368 {"symmetric", no_argument, 0, 's'},
2369 {"keyparam", required_argument, 0, 0},
2370 {"kill", no_argument, 0, 0},
2371 {"debug", required_argument, 0, 0},
2372 {0, 0, 0, 0}
2375 log_fd = -1;
2376 cmdline = 1;
2378 #ifndef DEBUG
2379 #ifdef HAVE_SETRLIMIT
2380 struct rlimit rl;
2382 rl.rlim_cur = rl.rlim_max = 0;
2384 if (setrlimit (RLIMIT_CORE, &rl) != 0)
2385 err (EXIT_FAILURE, "setrlimit()");
2386 #endif
2388 #ifdef HAVE_PR_SET_DUMPABLE
2389 prctl (PR_SET_DUMPABLE, 0);
2390 #endif
2391 #endif
2393 #ifdef ENABLE_NLS
2394 setlocale (LC_ALL, "");
2395 bindtextdomain ("pwmd", LOCALEDIR);
2396 textdomain ("pwmd");
2397 #endif
2399 if (setup_crypto ())
2400 exit (EXIT_FAILURE);
2402 #ifdef WITH_GNUTLS
2403 tls_level = tls_level == -1 ? 1 : tls_level;
2404 gnutls_global_set_log_level (tls_level);
2405 tls_fd = -1;
2406 tls6_fd = -1;
2407 #endif
2408 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
2409 xmlInitMemory ();
2410 xmlInitGlobals ();
2411 xmlInitParser ();
2412 xmlXPathInit ();
2414 while ((opt = getopt_long (argc, argv, optstring, longopts, &optindex))
2415 != -1)
2417 switch (opt)
2419 case 'I':
2420 import = optarg;
2421 break;
2422 case 'k':
2423 keyfile = optarg;
2424 break;
2425 case 'o':
2426 outfile = optarg;
2427 break;
2428 case 'D':
2429 secure = 1;
2430 break;
2431 case 'n':
2432 nofork = 1;
2433 break;
2434 case 'f':
2435 rcfile = str_dup (optarg);
2436 break;
2437 case 's':
2438 sym = 1;
2439 break;
2440 default:
2441 usage (argv[0], EXIT_FAILURE);
2442 break;
2443 case 0:
2444 switch (optindex)
2446 case OPT_DEBUG:
2447 if (parse_debug_level (optarg, &assuan_level, &gpgme_level,
2448 &tls_level))
2449 usage (argv[0], EXIT_FAILURE);
2450 break;
2451 case OPT_SYMMETRIC:
2452 sym = 1;
2453 break;
2454 case OPT_VERSION:
2455 show_version = 1;
2456 break;
2457 case OPT_HELP:
2458 usage (argv[0], EXIT_SUCCESS);
2459 break;
2460 case OPT_HOMEDIR:
2461 homedir = str_dup (optarg);
2462 break;
2463 case OPT_NO_FORK:
2464 nofork = 1;
2465 break;
2466 case OPT_DISABLE_DUMP:
2467 secure = 1;
2468 break;
2469 case OPT_FORCE:
2470 force = 1;
2471 break;
2472 case OPT_RCFILE:
2473 rcfile = str_dup (optarg);
2474 break;
2475 case OPT_PASSPHRASE_FILE:
2476 keyfile = optarg;
2477 break;
2478 case OPT_IMPORT:
2479 import = optarg;
2480 break;
2481 case OPT_OUTFILE:
2482 outfile = optarg;
2483 break;
2484 case OPT_KEYID:
2485 keyid = optarg;
2486 break;
2487 case OPT_SIGN_KEYID:
2488 sign_keyid = optarg;
2489 break;
2490 case OPT_KEYPARAM:
2491 keyparam = optarg;
2492 break;
2493 case OPT_KILL:
2494 terminate = 1;
2495 break;
2496 default:
2497 usage (argv[0], EXIT_FAILURE);
2502 if (show_version)
2504 printf (_("%s\n\n"
2505 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016\n"
2506 "%s\n"
2507 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2508 "Compile time features:\n%s"), PACKAGE_STRING,
2509 PACKAGE_BUGREPORT,
2510 #ifdef PWMD_HOMEDIR
2511 "+PWMD_HOMEDIR=" PWMD_HOMEDIR "\n"
2512 #endif
2513 #ifdef WITH_GNUTLS
2514 "+WITH_GNUTLS\n"
2515 #else
2516 "-WITH_GNUTLS\n"
2517 #endif
2518 #ifdef WITH_LIBACL
2519 "+WITH_LIBACL\n"
2520 #else
2521 "-WITH_LIBACL\n"
2522 #endif
2523 #ifdef DEBUG
2524 "+DEBUG\n"
2525 #else
2526 "-DEBUG\n"
2527 #endif
2528 #ifdef MEM_DEBUG
2529 "+MEM_DEBUG\n"
2530 #else
2531 "-MEM_DEBUG\n"
2532 #endif
2533 #ifdef MUTEX_DEBUG
2534 "+MUTEX_DEBUG\n"
2535 #else
2536 "-MUTEX_DEBUG\n"
2537 #endif
2539 exit (EXIT_SUCCESS);
2542 if (!homedir)
2543 #ifdef PWMD_HOMEDIR
2544 homedir = str_dup(PWMD_HOMEDIR);
2545 #else
2546 homedir = str_asprintf ("%s/.pwmd", get_home_dir());
2547 #endif
2549 if (mkdir (homedir, 0700) == -1 && errno != EEXIST)
2550 err (EXIT_FAILURE, "%s", homedir);
2552 if (!rcfile)
2553 rcfile = str_asprintf ("%s/config", homedir);
2555 pthread_key_create (&last_error_key, free_key);
2556 #ifndef HAVE_PTHREAD_CANCEL
2557 pthread_key_create (&signal_thread_key, free_key);
2558 #endif
2560 pthread_mutexattr_t attr;
2561 pthread_mutexattr_init (&attr);
2562 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
2563 pthread_mutex_init (&rcfile_mutex, &attr);
2564 global_config = config_parse (rcfile, 0);
2565 if (!global_config)
2567 pthread_mutexattr_destroy (&attr);
2568 pthread_mutex_destroy (&rcfile_mutex);
2569 exit (EXIT_FAILURE);
2572 p = config_get_string ("global", "gpg_homedir");
2573 if (!p)
2574 datadir = str_asprintf ("%s/.gnupg", homedir);
2575 else
2576 datadir = expand_homedir (p);
2578 xfree (p);
2579 if (mkdir (datadir, 0700) == -1 && errno != EEXIST)
2580 err (EXIT_FAILURE, "%s", datadir);
2582 if (gpgme_level != -1)
2584 char s[2] = { gpgme_level + '0', 0 };
2586 if (getenv ("GPGME_DEBUG"))
2587 log_write (_ ("Overriding GPGME_DEBUG environment with level %u!"),
2588 gpgme_level);
2590 gpgme_set_global_flag ("debug", s);
2593 rc = gpgme_set_engine_info (GPGME_PROTOCOL_OpenPGP, NULL, datadir);
2594 xfree (datadir);
2596 snprintf (buf, sizeof (buf), "%s/data", homedir);
2597 if (mkdir (buf, 0700) == -1 && errno != EEXIST)
2598 err (EXIT_FAILURE, "%s", buf);
2600 datadir = str_dup (buf);
2601 pthread_cond_init (&rcfile_cond, NULL);
2602 pthread_mutex_init (&cn_mutex, &attr);
2603 pthread_mutexattr_destroy (&attr);
2605 setup_logging ();
2607 x = config_get_int_param (global_config, "global", "priority", &exists);
2608 if (exists && x != atoi(INVALID_PRIORITY))
2610 errno = 0;
2611 if (setpriority (PRIO_PROCESS, 0, x) == -1)
2613 log_write ("setpriority(): %s",
2614 pwmd_strerror (gpg_error_from_errno (errno)));
2615 goto do_exit;
2618 #ifdef HAVE_MLOCKALL
2619 if (disable_mlock == 0 && mlockall (MCL_CURRENT | MCL_FUTURE) == -1)
2621 log_write ("mlockall(): %s",
2622 pwmd_strerror (gpg_error_from_errno (errno)));
2623 goto do_exit;
2625 #endif
2627 rc = cache_init ();
2628 if (rc)
2630 log_write ("pwmd: ERR %i: %s", rc, pwmd_strerror (rc));
2631 exit (EXIT_FAILURE);
2634 if (import)
2636 char **keyids = NULL, **sign_keyids = NULL;
2638 if (!outfile || !*outfile || argc != optind)
2639 usage (argv[0], EXIT_FAILURE);
2641 if (keyid)
2642 keyids = str_split (keyid, ",", 0);
2643 if (sign_keyid)
2644 sign_keyids = str_split (sign_keyid, ",", 0);
2645 rc = xml_import (import, outfile, keyids, sign_keyids, keyfile, keyparam, sym);
2646 strv_free (keyids);
2647 strv_free (sign_keyids);
2648 if (rc)
2650 if (gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
2651 rc = gpg_error (rc);
2653 log_write ("%s: %u: %s", import, rc, pwmd_strerror (rc));
2656 config_free (global_config);
2657 xfree (rcfile);
2658 exit (rc ? EXIT_FAILURE : EXIT_SUCCESS);
2661 p = config_get_string ("global", "socket_path");
2662 if (!p)
2663 p = str_asprintf ("%s/socket", homedir);
2665 socketarg = expand_homedir (p);
2666 xfree (p);
2668 if (!secure)
2669 disable_list_and_dump = config_get_boolean ("global",
2670 "disable_list_and_dump");
2671 else
2672 disable_list_and_dump = secure;
2674 cache_push = config_get_list ("global", "cache_push");
2676 while (optind < argc)
2678 if (strv_printf (&cache_push, "%s", argv[optind++]) == 0)
2679 errx (EXIT_FAILURE, "%s", pwmd_strerror (GPG_ERR_ENOMEM));
2682 if (strchr (socketarg, '/') == NULL)
2684 socketdir = getcwd (buf, sizeof (buf));
2685 socketname = str_dup (socketarg);
2686 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2688 else
2690 socketname = str_dup (strrchr (socketarg, '/'));
2691 socketname++;
2692 socketarg[strlen (socketarg) - strlen (socketname) - 1] = 0;
2693 socketdir = str_dup (socketarg);
2694 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2697 if (chdir (datadir))
2699 log_write ("%s: %s", datadir,
2700 pwmd_strerror (gpg_error_from_errno (errno)));
2701 unlink (socketpath);
2702 goto do_exit;
2705 x = test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 0,
2706 mode, terminate);
2707 if (!terminate && x)
2708 goto do_exit;
2709 else if (terminate)
2711 estatus = x != 1 ? EXIT_FAILURE : EXIT_SUCCESS;
2712 goto do_exit;
2716 * bind() doesn't like the full pathname of the socket or any non alphanum
2717 * characters so change to the directory where the socket is wanted then
2718 * create it then change to datadir.
2720 if (chdir (socketdir))
2722 log_write ("%s: %s", socketdir,
2723 pwmd_strerror (gpg_error_from_errno (errno)));
2724 goto do_exit;
2727 xfree (socketdir);
2729 if ((sockfd = socket (PF_UNIX, SOCK_STREAM, 0)) == -1)
2731 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2732 goto do_exit;
2735 addr.sun_family = AF_UNIX;
2736 snprintf (addr.sun_path, sizeof (addr.sun_path), "%s", socketname);
2737 do_unlink = 1;
2738 if (bind (sockfd, (struct sockaddr *) &addr, sizeof (struct sockaddr)) ==
2741 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2743 if (errno == EADDRINUSE)
2745 do_unlink = 0;
2746 log_write (_("Either there is another pwmd running or '%s' is a \n"
2747 "stale socket. Please remove it manually."), socketpath);
2750 goto do_exit;
2754 char *t = config_get_string ("global", "socket_perms");
2755 mode_t mask;
2757 if (t)
2759 mode = strtol (t, NULL, 8);
2760 mask = umask (0);
2761 xfree (t);
2763 if (chmod (socketname, mode) == -1)
2765 log_write ("%s: %s", socketname,
2766 pwmd_strerror (gpg_error_from_errno (errno)));
2767 close (sockfd);
2768 umask (mask);
2769 goto do_exit;
2772 umask (mask);
2776 xfree (--socketname);
2778 if (chdir (datadir))
2780 log_write ("%s: %s", datadir,
2781 pwmd_strerror (gpg_error_from_errno (errno)));
2782 close (sockfd);
2783 goto do_exit;
2786 xfree (datadir);
2787 #ifdef WITH_GNUTLS
2788 if (config_get_boolean ("global", "enable_tcp"))
2790 if (!start_stop_tls (0))
2792 close (sockfd);
2793 goto do_exit;
2796 #endif
2799 * Set the cache entry for a file. Prompts for the password.
2801 if (cache_push)
2803 for (opt = 0; cache_push[opt]; opt++)
2805 struct crypto_s *crypto = NULL;
2806 char *pw_file = config_get_string (cache_push[opt],
2807 "passphrase_file");
2808 gpg_error_t rc = crypto_init (&crypto, NULL, cache_push[opt],
2809 pw_file != NULL, pw_file);
2811 if (!rc)
2813 crypto->flags |= pw_file ? CRYPTO_FLAG_KEYFILE : 0;
2814 crypto->keyfile = pw_file;
2816 else
2817 xfree (pw_file);
2819 if (rc)
2821 estatus = EXIT_FAILURE;
2822 goto do_exit;
2825 rc = do_cache_push (crypto);
2826 if (rc && !force)
2828 log_write ("ERR %u: %s", rc, pwmd_strerror(rc));
2829 strv_free (cache_push);
2830 startup_failure ();
2831 estatus = EXIT_FAILURE;
2832 crypto_free (crypto);
2833 goto do_exit;
2835 else if (rc)
2836 log_write ("%s: %s", crypto->filename, pwmd_strerror(rc));
2837 else
2838 log_write (_("Successfully added '%s' to the cache."),
2839 crypto->filename);
2841 crypto_free (crypto);
2844 strv_free (cache_push);
2845 log_write (!nofork ? _("Done. Daemonizing...") :
2846 _("Done. Waiting for connections..."));
2849 if (listen (sockfd, 128) == -1)
2851 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2852 goto do_exit;
2855 if (!nofork)
2857 switch (fork ())
2859 case -1:
2860 log_write ("fork(): %s",
2861 pwmd_strerror (gpg_error_from_errno (errno)));
2862 goto do_exit;
2863 case 0:
2864 close (0);
2865 close (1);
2866 close (2);
2867 setsid ();
2868 break;
2869 default:
2870 _exit (EXIT_SUCCESS);
2874 (void)test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 1,
2875 mode, 0);
2876 cmdline = 0;
2877 pthread_key_create (&thread_name_key, free_key);
2878 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
2879 estatus = server_loop (sockfd, &socketpath);
2881 do_exit:
2882 if (socketpath && do_unlink)
2884 unlink (socketpath);
2885 xfree (socketpath);
2888 xfree (socketarg);
2889 #ifdef WITH_GNUTLS
2890 gnutls_global_deinit ();
2891 tls_deinit_params ();
2892 #endif
2893 if (rcfile_tid)
2895 #ifdef HAVE_PTHREAD_CANCEL
2896 pthread_cancel (rcfile_tid);
2897 #else
2898 pthread_kill (rcfile_tid, SIGUSR2);
2899 pthread_cond_signal (&rcfile_cond);
2900 #endif
2901 pthread_join (rcfile_tid, NULL);
2904 pthread_cond_destroy (&rcfile_cond);
2905 pthread_mutex_destroy (&rcfile_mutex);
2906 pthread_key_delete (last_error_key);
2907 #ifndef HAVE_PTHREAD_CANCEL
2908 pthread_key_delete (signal_thread_key);
2909 #endif
2911 if (global_config)
2912 config_free (global_config);
2914 free_invoking_users (invoking_users);
2915 xfree (rcfile);
2916 xfree (home_directory);
2917 xfree (homedir);
2918 xmlCleanupParser ();
2919 xmlCleanupGlobals ();
2921 if (pidfile)
2922 unlink (pidfile);
2923 xfree (pidfile);
2925 if (estatus == EXIT_SUCCESS && !terminate)
2926 log_write (_("pwmd exiting normally"));
2928 pthread_key_delete (thread_name_key);
2929 closelog ();
2931 if (log_fd != -1)
2932 close (log_fd);
2934 exit (estatus);
2937 gpg_error_t lock_flock (assuan_context_t ctx, const char *filename,
2938 int type, int *fd)
2940 gpg_error_t rc = 0;
2942 #ifdef HAVE_FLOCK
2943 *fd = open (filename, O_RDONLY);
2944 if (*fd == -1)
2945 return gpg_error_from_syserror ();
2947 TRY_FLOCK (ctx, *fd, type, rc);
2948 if (rc)
2950 close (*fd);
2951 *fd = -1;
2953 #endif
2955 return rc;
2958 void unlock_flock (int *fd)
2960 #ifdef HAVE_FLOCK
2961 if (*fd != -1)
2962 close (*fd);
2964 *fd = -1;
2965 #endif