Move keepalive_thread to cache_timer_thread.
[libpwmd.git] / src / pwmd.c
blob30142c8c7c68b7a30c20dfbabe218dc31b8e0aa1
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 #ifdef WITH_GNUTLS
110 static int tls_fd;
111 static int tls6_fd;
112 static pthread_t tls_tid;
113 static pthread_t tls6_tid;
114 static int spawned_tls;
115 static int spawned_tls6;
117 static int start_stop_tls (int term);
118 #endif
120 static gpg_error_t do_cache_push (struct crypto_s *crypto);
121 static int signal_loop (sigset_t sigset);
123 #ifndef HAVE_PTHREAD_CANCEL
124 #define INIT_THREAD_SIGNAL do { \
125 struct sigaction act; \
126 sigset_t sigset; \
127 sigemptyset (&sigset); \
128 sigaddset (&sigset, SIGUSR2); \
129 pthread_sigmask (SIG_UNBLOCK, &sigset, NULL); \
130 memset (&act, 0, sizeof(act)); \
131 act.sa_flags = SA_SIGINFO; \
132 act.sa_mask = sigset; \
133 act.sa_sigaction = catch_thread_signal; \
134 sigaction (SIGUSR2, &act, NULL); \
135 } while (0)
137 static void
138 catch_thread_signal (int sig, siginfo_t *info, void *ctx)
140 int *n = (int *) pthread_getspecific (signal_thread_key);
142 *n = 1;
143 pthread_setspecific (signal_thread_key, n);
145 #endif
147 static void
148 setup_logging ()
150 int n = config_get_boolean ("global", "enable_logging");
152 if (n)
154 char *p = config_get_string ("global", "log_path");
156 if (!p || (logfile && p && log_fd != -1 && strcmp(p, logfile)))
158 if (log_fd != -1)
159 close (log_fd);
161 log_fd = -1;
164 xfree (logfile);
165 logfile = NULL;
166 if (p)
167 logfile = expand_homedir (p);
168 xfree (p);
170 else
172 xfree (logfile);
173 logfile = NULL;
174 if (log_fd != -1)
175 close(log_fd);
177 log_fd = -1;
178 closelog ();
181 log_syslog = config_get_boolean ("global", "syslog");
182 if (log_syslog == 1)
183 openlog ("pwmd", LOG_NDELAY | LOG_PID, LOG_DAEMON);
186 static void *
187 reload_rcfile_thread (void *arg)
189 #ifndef HAVE_PTHREAD_CANCEL
190 int *n = xmalloc (sizeof (int));
192 *n = 0;
193 pthread_setspecific (signal_thread_key, n);
194 INIT_THREAD_SIGNAL;
195 #endif
197 #ifdef HAVE_PR_SET_NAME
198 prctl (PR_SET_NAME, "reload rcfile");
199 #endif
200 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
201 MUTEX_LOCK (&rcfile_mutex);
203 for (;;)
205 struct slist_s *keep = NULL;
206 struct slist_s *config;
207 int b = disable_list_and_dump;
209 pthread_cleanup_push (cleanup_mutex_cb, &rcfile_mutex);
210 pthread_cond_wait (&rcfile_cond, &rcfile_mutex);
211 #ifndef HAVE_PTHREAD_CANCEL
212 int *cancel = (int *) pthread_getspecific (signal_thread_key);
213 if (*cancel)
214 break;
215 #endif
217 keep = config_keep_save ();
218 log_write (_("reloading configuration file '%s'"), rcfile);
220 config = config_parse (rcfile, 1);
221 if (config)
223 config_free (global_config);
224 global_config = config;
225 setup_logging ();
228 config_keep_restore (keep);
229 disable_list_and_dump = !disable_list_and_dump ? b : 1;
231 #ifdef WITH_GNUTLS
232 /* Kill existing listening threads since the configured listening
233 * protocols may have changed. */
234 start_stop_tls (1);
235 start_stop_tls (0);
236 #endif
237 crypto_set_keepalive ();
238 pthread_cleanup_pop (0);
241 MUTEX_UNLOCK (&rcfile_mutex);
242 return NULL;
245 gpg_error_t
246 send_error (assuan_context_t ctx, gpg_error_t e)
248 struct client_s *client = assuan_get_pointer (ctx);
250 if (gpg_err_source (e) == GPG_ERR_SOURCE_UNKNOWN)
251 e = gpg_error (e);
253 if (client)
254 client->last_rc = e;
256 if (!e)
257 return assuan_process_done (ctx, 0);
259 if (!ctx)
261 log_write ("ERR %i: %s", e, pwmd_strerror (e));
262 return e;
265 if (client && client->xml_error)
267 log_write ("%s", client->xml_error->message);
268 xfree (client->last_error);
269 client->last_error = NULL;
270 if (client->xml_error->message)
271 client->last_error = str_dup (client->xml_error->message);
273 e = assuan_process_done (ctx,
274 assuan_set_error (ctx, e,
275 client->xml_error->message ? client->xml_error->message : NULL));
276 xmlResetLastError ();
277 xmlResetError (client->xml_error);
278 xfree (client->xml_error);
279 client->xml_error = NULL;
280 return e;
283 return assuan_process_done (ctx,
284 assuan_set_error (ctx, e, pwmd_strerror (e)));
287 void
288 log_write (const char *fmt, ...)
290 char *args;
291 va_list ap;
292 time_t now;
293 char buf[255];
294 pthread_t tid = pthread_self ();
295 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
297 if ((!logfile && !isatty (STDERR_FILENO) && !log_syslog) || !fmt)
298 return;
300 pthread_mutex_lock (&m);
301 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock, &m);
303 if (!cmdline && logfile && log_fd == -1)
305 log_fd = open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600);
306 if (log_fd == -1)
307 warn ("%s", logfile);
310 va_start (ap, fmt);
312 if (str_vasprintf (&args, fmt, ap) != -1)
314 if (cmdline)
316 pthread_cleanup_push (xfree, args);
317 fprintf (stderr, "pwmd: %s\n", args);
318 fflush (stderr);
319 pthread_cleanup_pop (1);
321 else
323 char *name = pthread_getspecific (thread_name_key);
324 char *line;
326 pthread_cleanup_push (xfree, args);
327 snprintf (buf, sizeof (buf),
328 name && *name == '!' ? "%s: " : name ? "%s(%p): " : "%s",
329 name ? *name == '!' ? name+1 : name : "",
330 name && *name == '!' ? 0 : name ? (pthread_t *) tid : 0);
331 name = buf;
333 if (!cmdline && log_syslog && !nofork)
334 syslog (LOG_INFO, "%s%s", name, args);
336 time (&now);
337 struct tm *tm = localtime (&now);
338 char tbuf[21];
339 strftime (tbuf, sizeof (tbuf), "%b %d %Y %H:%M:%S ", tm);
340 tbuf[sizeof (tbuf) - 1] = 0;
342 if (args[strlen (args) - 1] == '\n')
343 args[strlen (args) - 1] = 0;
345 line = str_asprintf ("%s %i %s%s\n", tbuf, getpid (), name,
346 args);
347 pthread_cleanup_pop (1);
348 if (line)
350 pthread_cleanup_push (xfree, line);
351 if (logfile && log_fd != -1)
353 ssize_t ret = write (log_fd, line, strlen (line));
354 (void)ret;
355 fsync (log_fd);
358 if (nofork)
360 fprintf (stdout, "%s", line);
361 fflush (stdout);
364 pthread_cleanup_pop (1);
369 va_end (ap);
370 pthread_cleanup_pop (0);
372 if (log_fd != -1 && log_keepopen <= 0)
374 close(log_fd);
375 log_fd = -1;
378 pthread_mutex_unlock (&m);
381 static gpg_error_t
382 setup_crypto ()
384 gpg_error_t rc;
386 if (!gpgrt_check_version (REQUIRE_LIBGPGERROR_VERSION))
388 fprintf (stderr, _("gpgrt_check_version(): Incompatible libgpg-error. "
389 "Wanted %s, got %s.\n"), REQUIRE_LIBGPGERROR_VERSION,
390 gpgrt_check_version (NULL));
391 return GPG_ERR_UNKNOWN_VERSION;
394 gpgrt_init ();
395 gpgrt_set_alloc_func (xrealloc_gpgrt);
397 if (!assuan_check_version (REQUIRE_LIBASSUAN_VERSION))
399 fprintf (stderr, _("assuan_check_version(): Incompatible libassuan. "
400 "Wanted %s, got %s.\n"), REQUIRE_LIBASSUAN_VERSION,
401 assuan_check_version (NULL));
402 return GPG_ERR_UNKNOWN_VERSION;
405 if (!gcry_check_version (REQUIRE_LIBGCRYPT_VERSION))
407 fprintf (stderr, _("gcry_check_version(): Incompatible libgcrypt. "
408 "Wanted %s, got %s.\n"), REQUIRE_LIBGCRYPT_VERSION,
409 gcry_check_version (NULL));
410 return GPG_ERR_UNKNOWN_VERSION;
413 gcry_set_allocation_handler (xmalloc, xmalloc, NULL, xrealloc, xfree);
415 if (!gpgme_check_version (REQUIRE_LIBGPGME_VERSION))
417 fprintf (stderr, _("gpgme_check_version(): Incompatible libgpgme. "
418 "Wanted %s, got %s.\n"), REQUIRE_LIBGPGME_VERSION,
419 gpgme_check_version (NULL));
420 return GPG_ERR_UNKNOWN_VERSION;
423 rc = gpgme_engine_check_version (GPGME_PROTOCOL_OPENPGP);
424 if (rc)
426 fprintf (stderr, _("gpgme_engine_check_version(GPGME_PROTOCOL_OPENPGP): %s"), gpgme_strerror (rc));
427 return GPG_ERR_UNKNOWN_VERSION;
430 //gpgme_set_global_flag ("require-gnupg", REQUIRE_GNUPG_VERSION);
431 #ifdef ENABLE_NLS
432 gpgme_set_locale (NULL, LC_CTYPE, setlocale (LC_CTYPE, NULL));
433 gpgme_set_locale (NULL, LC_MESSAGES, setlocale (LC_MESSAGES, NULL));
434 #endif
436 #ifdef WITH_GNUTLS
437 if (gnutls_global_init ())
439 fprintf(stderr, _("gnutls_global_init() failed.\n"));
440 return GPG_ERR_UNKNOWN_VERSION;
443 gnutls_global_set_log_function (tls_log);
444 gnutls_global_set_audit_log_function (tls_audit_log);
445 #endif
446 return 0;
449 gpg_error_t
450 do_validate_peer (assuan_context_t ctx, const char *section,
451 assuan_peercred_t * peer)
453 char **users;
454 int allowed = 0;
455 gpg_error_t rc;
456 struct client_s *client = assuan_get_pointer (ctx);
458 if (!client)
459 return GPG_ERR_FORBIDDEN;
461 #ifdef WITH_GNUTLS
462 if (client->thd->remote)
463 return tls_validate_access (client, section);
464 #endif
466 rc = assuan_get_peercred (ctx, peer);
467 if (rc)
468 return rc;
470 users = config_get_list (section, "allowed");
471 if (users)
473 for (char **p = users; !rc && *p; p++)
475 rc = acl_check_common(client, *p, (*peer)->uid, (*peer)->gid,
476 &allowed);
479 strv_free (users);
481 else if (client->no_access_param)
482 allowed = 1;
484 return allowed && !rc ? 0 : rc ? rc : GPG_ERR_FORBIDDEN;
487 /* Test if uid is a member of group 'name'. Invert when 'not' is true. */
488 #ifdef HAVE_GETGRNAM_R
489 static gpg_error_t
490 acl_check_group (const char *name, uid_t uid, gid_t gid, int not, int *allowed)
492 char *buf;
493 struct group gr, *gresult;
494 size_t len = sysconf (_SC_GETGR_R_SIZE_MAX);
495 int err;
496 gpg_error_t rc = 0;
498 if (len == -1)
499 len = 16384;
501 buf = xmalloc (len);
502 if (!buf)
503 return GPG_ERR_ENOMEM;
505 err = getgrnam_r (name, &gr, buf, len, &gresult);
506 if (!err && gresult)
508 if (gresult->gr_gid == gid)
510 xfree (buf);
511 *allowed = !not;
512 return 0;
515 for (char **t = gresult->gr_mem; !rc && *t; t++)
517 char *tbuf;
518 struct passwd pw;
519 struct passwd *result = get_pwd_struct (*t, 0, &pw, &tbuf, &rc);
521 if (!rc && result && result->pw_uid == uid)
523 xfree (tbuf);
524 *allowed = !not;
525 break;
528 xfree (tbuf);
531 xfree (buf);
532 return rc;
534 else if (err)
535 rc = gpg_error_from_errno (err);
537 xfree (buf);
538 return rc ? rc : !gresult ? 0 : GPG_ERR_EACCES;
540 #else
541 static gpg_error_t
542 acl_check_group (const char *name, uid_t uid, gid_t gid, int not, int *allowed)
544 struct group *gresult;
545 gpg_error_t rc = 0;
547 errno = 0;
548 gresult = getgrnam (name);
549 if (!errno && gresult && gresult->gr_gid == gid)
551 *allowed = !not;
552 return 0;
554 else if (errno)
555 rc = gpg_error_from_syserror ();
556 else if (!gresult)
557 return 0;
559 for (char **t = gresult->gr_mem; !rc && *t; t++)
561 char *buf;
562 struct passwd pw;
563 struct passwd *result = get_pwd_struct (*t, 0, &pw, &buf, &rc);
565 if (!rc && result && result->pw_uid == uid)
567 xfree (buf);
568 *allowed = !not;
569 break;
572 xfree (buf);
575 return rc;
577 #endif
579 gpg_error_t
580 peer_is_invoker(struct client_s *client)
582 struct invoking_user_s *user;
583 int allowed = 0;
585 if (client->thd->state == CLIENT_STATE_UNKNOWN)
586 return GPG_ERR_EACCES;
588 for (user = invoking_users; user; user = user->next)
590 #ifdef WITH_GNUTLS
591 if (client->thd->remote)
593 if (user->type == INVOKING_TLS
594 && !strcmp(client->thd->tls->fp, user->id))
595 allowed = user->not ? 0 : 1;
597 continue;
599 #endif
601 if (user->type == INVOKING_GID)
603 gpg_error_t rc = acl_check_group (user->id,
604 client->thd->peer->uid,
605 client->thd->peer->gid,
606 user->not, &allowed);
607 if (rc)
608 return rc;
610 else if (user->type == INVOKING_UID && client->thd->peer->uid == user->uid)
611 allowed = user->not ? 0 : 1;
614 return allowed ? 0 : GPG_ERR_EACCES;
617 #ifdef HAVE_GETGRNAM_R
618 gpg_error_t
619 acl_check_common (struct client_s *client, const char *user, uid_t uid,
620 gid_t gid, int *allowed)
622 int not = 0;
623 int rw = 0;
624 int tls = 0;
625 gpg_error_t rc = 0;
627 if (!user || !*user)
628 return 0;
630 if (*user == '-' || *user == '!')
631 not = 1;
633 if (*user == '+') // not implemented yet
634 rw = 1;
636 if (*user == '#') // TLS fingerprint hash
637 tls = 1;
639 if (not || rw || tls)
640 user++;
642 if (tls)
644 #ifdef WITH_GNUTLS
645 if (client->thd->remote)
647 if (!strcasecmp (client->thd->tls->fp, user))
648 *allowed = !not;
651 return 0;
652 #else
653 return 0;
654 #endif
656 #ifdef WITH_GNUTLS
657 else if (client->thd->remote) // Remote client with no FP in the ACL
658 return 0;
659 #endif
661 if (*user == '@') // all users in group
662 return acl_check_group (user+1, uid, gid, not, allowed);
663 else
665 char *buf;
666 struct passwd pw;
667 struct passwd *pwd = get_pwd_struct (user, 0, &pw, &buf, &rc);
669 if (!rc && pwd && pwd->pw_uid == uid)
670 *allowed = !not;
672 xfree (buf);
675 return rc;
677 #else
678 gpg_error_t
679 acl_check_common (struct client_s *client, const char *user, uid_t uid,
680 gid_t gid, int *allowed)
682 gpg_error_t rc = 0;
683 int not = 0;
684 int rw = 0;
685 int tls = 0;
687 if (!user || !*user)
688 return 0;
690 if (*user == '-' || *user == '!')
691 not = 1;
693 if (*user == '+') // not implemented yet
694 rw = 1;
696 if (*user == '#') // TLS fingerprint hash
697 tls = 1;
699 if (not || rw || tls)
700 user++;
702 if (tls)
704 #ifdef WITH_GNUTLS
705 if (client->thd->remote)
707 if (!strcasecmp (client->thd->tls->fp, user))
708 *allowed = !not;
711 return 0;
712 #else
713 return 0;
714 #endif
717 if (*user == '@') // all users in group
718 return acl_check_group (user+1, uid, gid, not, allowed);
719 else
721 char *buf;
722 struct passwd pw;
723 struct passwd *result = get_pwd_struct (user, 0, &pw, &buf, &rc);
725 if (!rc && result && result->pw_uid == uid)
726 *allowed = !not;
728 xfree (buf);
731 return rc;
733 #endif
735 static gpg_error_t
736 validate_peer (struct client_s *cl)
738 gpg_error_t rc;
740 #ifdef WITH_GNUTLS
741 if (cl->thd->remote)
742 return tls_validate_access (cl, NULL);
743 #endif
745 MUTEX_LOCK (&cn_mutex);
746 rc = do_validate_peer (cl->ctx, "global", &cl->thd->peer);
747 MUTEX_UNLOCK (&cn_mutex);
748 log_write ("peer %s: uid=%i, gid=%i, pid=%i, rc=%u",
749 !rc ? _("accepted") : _("rejected"), cl->thd->peer->uid,
750 cl->thd->peer->gid, cl->thd->peer->pid, rc);
751 return rc;
754 static void
755 xml_error_cb (void *data, xmlErrorPtr e)
757 struct client_s *client = data;
760 * Keep the first reported error as the one to show in the error
761 * description. Reset in send_error().
763 if (client->xml_error)
764 return;
766 client->xml_error = xcalloc (1, sizeof(xmlError));
767 xmlCopyError (e, client->xml_error);
770 static pid_t
771 hook_waitpid (assuan_context_t ctx, pid_t pid, int action,
772 int *status, int options)
774 return waitpid (pid, status, options);
777 static ssize_t
778 hook_read (assuan_context_t ctx, assuan_fd_t fd, void *data, size_t len)
780 #ifdef WITH_GNUTLS
781 struct client_s *client = assuan_get_pointer (ctx);
783 if (client->thd->remote)
784 return tls_read_hook (ctx, (int) fd, data, len);
785 #endif
787 return read ((int) fd, data, len);
790 static ssize_t
791 hook_write (assuan_context_t ctx, assuan_fd_t fd,
792 const void *data, size_t len)
794 #ifdef WITH_GNUTLS
795 struct client_s *client = assuan_get_pointer (ctx);
797 if (client->thd->remote)
798 return tls_write_hook (ctx, (int) fd, data, len);
799 #endif
801 return write ((int) fd, data, len);
805 assuan_log_cb (assuan_context_t ctx, void *data, unsigned cat,
806 const char *msg)
808 struct client_s *client = data;
809 char *str = NULL;
811 (void)client;
813 if (!(assuan_level & cat))
814 return 0;
816 if (!msg)
817 return 1;
819 switch (cat)
821 case ASSUAN_LOG_INIT:
822 str = "ASSUAN[INIT]";
823 break;
824 case ASSUAN_LOG_CTX:
825 str = "ASSUAN[CTX]";
826 break;
827 case ASSUAN_LOG_ENGINE:
828 str = "ASSUAN[ENGINE]";
829 break;
830 case ASSUAN_LOG_DATA:
831 str = "ASSUAN[DATA]";
832 break;
833 case ASSUAN_LOG_SYSIO:
834 str = "ASSUAN[SYSIO]";
835 break;
836 case ASSUAN_LOG_CONTROL:
837 str = "ASSUAN[CONTROL]";
838 break;
839 default:
840 str = "ASSUAN[UNKNOWN]";
841 break;
844 log_write ("%s: %s", str, msg);
845 return 1;
848 static int
849 new_connection (struct client_s *cl)
851 gpg_error_t rc;
852 static struct assuan_malloc_hooks mhooks = { xmalloc, xrealloc, xfree };
853 static struct assuan_system_hooks shooks = {
854 ASSUAN_SYSTEM_HOOKS_VERSION,
855 __assuan_usleep,
856 __assuan_pipe,
857 __assuan_close,
858 hook_read,
859 hook_write,
860 //FIXME
861 NULL, //recvmsg
862 NULL, //sendmsg both are used for FD passing
863 __assuan_spawn,
864 hook_waitpid,
865 __assuan_socketpair,
866 __assuan_socket,
867 __assuan_connect
870 #ifdef WITH_GNUTLS
871 if (cl->thd->remote)
873 char *prio = config_get_string ("global", "tls_cipher_suite");
875 cl->thd->timeout = config_get_integer ("global", "tls_timeout");
876 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
877 return 0;
879 cl->thd->tls = tls_init (cl->thd->fd, cl->thd->timeout, prio);
880 xfree (prio);
881 if (!cl->thd->tls)
882 return 0;
884 #endif
886 rc = assuan_new_ext (&cl->ctx, GPG_ERR_SOURCE_DEFAULT, &mhooks,
887 assuan_log_cb, cl);
888 if (rc)
889 goto fail;
891 assuan_ctx_set_system_hooks (cl->ctx, &shooks);
892 rc = assuan_init_socket_server (cl->ctx, cl->thd->fd, 2);
893 if (rc)
894 goto fail;
896 assuan_set_pointer (cl->ctx, cl);
897 assuan_set_hello_line (cl->ctx, PACKAGE_STRING);
898 rc = register_commands (cl->ctx);
899 if (rc)
900 goto fail;
902 rc = assuan_accept (cl->ctx);
903 if (rc)
904 goto fail;
906 rc = validate_peer (cl);
907 /* May not be implemented on all platforms. */
908 if (rc && gpg_err_code (rc) != GPG_ERR_ASS_GENERAL)
909 goto fail;
911 MUTEX_LOCK (&cn_mutex);
912 cl->thd->state = CLIENT_STATE_INIT;
913 MUTEX_UNLOCK (&cn_mutex);
914 cl->lock_timeout = config_get_integer ("global", "lock_timeout");
915 xmlSetStructuredErrorFunc (cl, xml_error_cb);
916 return 1;
918 fail:
919 log_write ("%s", pwmd_strerror (rc));
920 return 0;
924 * This is called after a client_thread() terminates. Set with
925 * pthread_cleanup_push().
927 static void
928 cleanup_cb (void *arg)
930 struct client_thread_s *cn = arg;
931 struct client_s *cl = cn->cl;
933 MUTEX_LOCK (&cn_mutex);
934 cn_thread_list = slist_remove (cn_thread_list, cn);
935 MUTEX_UNLOCK (&cn_mutex);
937 if (cl)
939 unlock_flock (&cl->flock_fd);
940 cleanup_client (cl);
941 if (cl->xml_error)
942 xmlResetError (cl->xml_error);
944 xfree (cl->xml_error);
946 #ifdef WITH_GNUTLS
947 if (cn->tls)
949 gnutls_deinit (cn->tls->ses);
950 xfree (cn->tls->fp);
951 xfree (cn->tls);
953 #endif
955 if (!cn->atfork && cl->ctx)
956 assuan_release (cl->ctx);
957 else if (!cn->atfork && cl->thd && cl->thd->fd != -1)
958 close (cl->thd->fd);
960 if (cl->crypto)
961 crypto_free (cl->crypto);
963 cl->crypto = NULL;
964 xfree (cl);
966 else
968 if (cn->fd != -1)
969 close (cn->fd);
972 while (cn->msg_queue)
974 struct status_msg_s *msg = cn->msg_queue;
976 cn->msg_queue = msg->next;
977 xfree (msg->line);
978 xfree (msg);
981 if (!cn->atfork && cn->status_msg_pipe[0] != -1)
982 close (cn->status_msg_pipe[0]);
984 if (!cn->atfork && cn->status_msg_pipe[1] != -1)
985 close (cn->status_msg_pipe[1]);
987 pthread_mutex_destroy (&cn->status_mutex);
989 if (!cn->atfork)
991 log_write (_("exiting, fd=%i"), cn->fd);
992 send_status_all (STATUS_CLIENTS, NULL);
995 xfree (cn->name);
996 #ifdef WITH_GNUTLS
997 xfree (cn->peeraddr);
998 #endif
999 xfree (cn);
1000 pthread_cond_signal (&quit_cond);
1003 void
1004 cleanup_all_clients (int atfork)
1006 /* This function may be called from pthread_atfork() which requires
1007 reinitialization. */
1008 if (atfork)
1010 pthread_mutexattr_t attr;
1012 pthread_mutexattr_init (&attr);
1013 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
1014 pthread_mutex_init (&cn_mutex, &attr);
1015 pthread_mutexattr_destroy (&attr);
1016 cache_mutex_init ();
1019 MUTEX_LOCK (&cn_mutex);
1021 while (slist_length (cn_thread_list))
1023 struct client_thread_s *thd = slist_nth_data (cn_thread_list, 0);
1025 thd->atfork = atfork;
1026 cleanup_cb (thd);
1029 exiting = 1;
1030 MUTEX_UNLOCK (&cn_mutex);
1031 cache_deinit (atfork);
1034 static gpg_error_t
1035 send_msg_queue (struct client_thread_s *thd)
1037 MUTEX_LOCK (&thd->status_mutex);
1038 gpg_error_t rc = 0;
1039 char c;
1040 ssize_t ret;
1042 ret = read (thd->status_msg_pipe[0], &c, 1);
1043 rc = gpg_error_from_syserror ();
1044 if (ret == -1 && gpg_err_code (rc) != GPG_ERR_EAGAIN)
1045 log_write ("%s (%i): %s", __FUNCTION__, __LINE__, pwmd_strerror (rc));
1046 else
1047 rc = 0;
1049 thd->wrote_status = 0;
1051 while (thd->msg_queue)
1053 struct status_msg_s *msg = thd->msg_queue;
1055 #ifndef HAVE_PTHREAD_CANCEL
1056 if (thd->fd == -1)
1057 break;
1058 #endif
1060 thd->msg_queue = thd->msg_queue->next;
1061 MUTEX_UNLOCK (&thd->status_mutex);
1062 rc = send_status (thd->cl->ctx, msg->s, msg->line);
1063 MUTEX_LOCK (&thd->status_mutex);
1064 xfree (msg->line);
1065 xfree (msg);
1067 if (rc)
1068 break;
1071 MUTEX_UNLOCK (&thd->status_mutex);
1072 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1073 log_write ("%s (%i): %s", __FUNCTION__, __LINE__, pwmd_strerror (rc));
1075 return rc;
1078 static void *
1079 client_thread (void *data)
1081 struct client_thread_s *thd = data;
1082 struct client_s *cl = xcalloc (1, sizeof (struct client_s));
1084 #ifdef HAVE_PR_SET_NAME
1085 prctl (PR_SET_NAME, "client");
1086 #endif
1087 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1089 if (!cl)
1091 log_write ("%s(%i): %s", __FILE__, __LINE__,
1092 pwmd_strerror (GPG_ERR_ENOMEM));
1093 return NULL;
1096 MUTEX_LOCK (&cn_mutex);
1097 pthread_cleanup_push (cleanup_cb, thd);
1098 thd->cl = cl;
1099 cl->thd = thd;
1100 cl->flock_fd = -1;
1101 MUTEX_UNLOCK (&cn_mutex);
1103 if (new_connection (cl))
1105 int finished = 0;
1106 gpg_error_t rc;
1107 struct pollfd fds[2];
1109 fds[0].fd = thd->fd;
1110 fds[0].events = POLLIN;
1111 fds[1].fd = thd->status_msg_pipe[0];
1112 fds[1].events = POLLIN;
1114 send_status_all (STATUS_CLIENTS, NULL);
1115 rc = send_status (cl->ctx, STATUS_CACHE, NULL);
1116 if (rc)
1118 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
1119 finished = 1;
1122 while (!finished)
1124 int n;
1125 int eof;
1127 n = poll (fds, 2, -1);
1128 if (n == -1)
1130 log_write ("%s", strerror (errno));
1131 break;
1134 if (fds[1].revents & POLLIN)
1136 rc = send_msg_queue (thd);
1137 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1138 break;
1141 #ifdef HAVE_PTHREAD_CANCEL
1142 if (!(fds[0].revents & POLLIN))
1143 #else
1144 if (thd->fd != -1 && !(fds[0].revents & POLLIN))
1145 #endif
1146 continue;
1148 rc = assuan_process_next (cl->ctx, &eof);
1149 if (rc || eof)
1151 if (gpg_err_code (rc) == GPG_ERR_EOF || eof)
1152 break;
1154 log_write ("assuan_process_next(): rc=%u %s", rc,
1155 pwmd_strerror (rc));
1156 if (rc == gpg_error (GPG_ERR_ETIMEDOUT))
1157 break;
1159 rc = send_error (cl->ctx, rc);
1160 if (rc)
1162 log_write ("assuan_process_done(): rc=%u %s", rc,
1163 pwmd_strerror (rc));
1164 break;
1168 /* Since the msg queue pipe fd's are non-blocking, check for
1169 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1170 * client has already disconnected and will be converted to
1171 * GPG_ERR_EOF during assuan_process_next().
1173 rc = send_msg_queue (thd);
1174 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1175 break;
1179 /* Don't do pthread_exit() here because any set pthread_cleanup_push
1180 * functions would be called after a command failed but then the client
1181 * exited normally which may lead to a double free. */
1182 pthread_cleanup_pop (1);
1183 return NULL;
1186 static gpg_error_t
1187 xml_import (const char *filename, const char *outfile, char **keyid,
1188 char **sign_keyid, char *keyfile, const char *keyparam,
1189 int symmetric)
1191 xmlDocPtr doc;
1192 int fd;
1193 struct stat st;
1194 int len;
1195 xmlChar *xmlbuf;
1196 gpg_error_t rc = 0;
1197 struct crypto_s *crypto = NULL;
1199 if (stat (filename, &st) == -1)
1201 rc = gpg_error_from_errno (errno);
1202 return rc;
1205 fd = open (filename, O_RDONLY);
1206 if (fd == -1)
1207 return gpg_error_from_errno (errno);
1209 xmlbuf = xmalloc (st.st_size + 1);
1210 if (!xmlbuf)
1212 close (fd);
1213 return GPG_ERR_ENOMEM;
1216 if (read (fd, xmlbuf, st.st_size) == -1)
1218 rc = gpg_error_from_errno (errno);
1219 close (fd);
1220 xfree (xmlbuf);
1221 return rc;
1224 close (fd);
1225 xmlbuf[st.st_size] = 0;
1226 // Be sure the document validates.
1227 doc = xmlReadDoc (xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS);
1228 xfree (xmlbuf);
1229 if (!doc)
1230 return GPG_ERR_BAD_DATA;
1232 xmlNodePtr n = xmlDocGetRootElement (doc);
1233 if (n && !xmlStrEqual (n->name, (xmlChar *) "pwmd"))
1234 rc = GPG_ERR_BAD_DATA;
1236 if (!rc)
1238 rc = xml_validate_import (NULL, n ? n->children : n);
1239 if (!rc)
1241 rc = crypto_init (&crypto, NULL, filename, keyfile != NULL, keyfile);
1242 if (!rc)
1244 if (keyfile)
1246 crypto->flags |= CRYPTO_FLAG_KEYFILE;
1247 crypto->keyfile = str_dup (keyfile);
1250 xmlDocDumpMemory (doc, &crypto->plaintext, &len);
1251 if (len > 0)
1252 crypto->plaintext_size = len;
1253 else
1254 rc = GPG_ERR_ENOMEM;
1259 if (!rc)
1261 if (!symmetric && (keyparam || !keyid))
1263 char *buf = NULL;
1265 if (keyparam)
1267 fd = open (keyparam, O_RDONLY);
1268 if (fd == -1)
1269 rc = gpg_error_from_errno (errno);
1271 if (!rc)
1273 if (stat (keyparam, &st) == -1)
1274 rc = gpg_error_from_errno (errno);
1276 if (!rc)
1278 buf = xmalloc (st.st_size+1);
1279 if (!buf)
1280 rc = GPG_ERR_ENOMEM;
1282 if (!rc)
1284 len = read (fd, buf, st.st_size);
1285 if (len != st.st_size)
1286 rc = gpg_error_from_errno (errno);
1288 if (!rc)
1289 buf[len] = 0;
1294 if (fd != -1)
1295 close (fd);
1297 else
1299 buf = crypto_default_key_params ();
1300 if (!buf)
1301 rc = GPG_ERR_ENOMEM;
1304 if (!rc)
1305 rc = crypto_genkey (NULL, crypto, (unsigned char *)buf);
1307 xfree (buf);
1309 else
1311 crypto->save.pubkey = strv_dup (keyid);
1312 crypto->save.sigkey = strv_dup (sign_keyid);
1315 if (!rc)
1317 crypto->flags |= symmetric ? CRYPTO_FLAG_SYMMETRIC : 0;
1318 rc = crypto_encrypt (NULL, crypto);
1322 if (!rc)
1324 if (!strcmp (outfile, "-"))
1325 outfile = NULL;
1327 xfree (crypto->plaintext);
1328 crypto->plaintext = NULL;
1329 xfree (crypto->filename);
1330 crypto->filename = outfile ? str_dup (outfile) : NULL;
1331 rc = crypto_write_file (crypto);
1334 xmlFreeDoc (doc);
1335 crypto_free (crypto);
1336 return rc;
1339 static gpg_error_t
1340 do_cache_push (struct crypto_s *crypto)
1342 gpg_error_t rc;
1343 xmlDocPtr doc;
1344 struct cache_data_s *cdata;
1345 unsigned char *crc;
1346 size_t len;
1347 int fd = -1;
1349 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1350 crypto->filename);
1352 if (valid_filename (crypto->filename) == 0)
1354 log_write (_("%s: Invalid characters in filename"), crypto->filename);
1355 return GPG_ERR_INV_VALUE;
1358 rc = lock_flock (NULL, crypto->filename, LOCK_SH, &fd);
1359 if (!rc)
1360 rc = crypto_decrypt (NULL, crypto);
1361 if (rc)
1363 unlock_flock (&fd);
1364 return rc;
1367 rc = xml_parse_doc ((char *) crypto->plaintext, crypto->plaintext_size, &doc);
1368 if (rc)
1370 unlock_flock (&fd);
1371 log_write ("%s", pwmd_strerror (rc));
1372 return rc;
1375 cdata = xcalloc (1, sizeof (struct cache_data_s));
1376 if (!cdata)
1378 unlock_flock (&fd);
1379 xmlFreeDoc (doc);
1380 return GPG_ERR_ENOMEM;
1383 rc = get_checksum (crypto->filename, &crc, &len);
1384 unlock_flock (&fd);
1385 if (rc)
1387 xmlFreeDoc (doc);
1388 free_cache_data_once (cdata);
1389 return rc;
1392 cdata->crc = crc;
1393 rc = cache_encrypt (crypto);
1394 if (!rc)
1396 cdata->doc = crypto->plaintext;
1397 cdata->size = crypto->plaintext_size;
1398 crypto->plaintext = NULL;
1399 cdata->pubkey = crypto->pubkey;
1400 cdata->sigkey = crypto->sigkey;
1401 crypto->pubkey = NULL;
1402 crypto->sigkey = NULL;
1404 else
1406 xmlFreeDoc (doc);
1407 free_cache_data_once (cdata);
1408 return rc;
1411 int timeout = config_get_integer (crypto->filename, "cache_timeout");
1412 rc = cache_add_file (crypto->filename, cdata, timeout);
1413 return rc;
1416 static gpg_error_t
1417 init_client (int fd, const char *addr)
1419 gpg_error_t rc = 0;
1420 struct client_thread_s *new = xcalloc (1, sizeof (struct client_thread_s));
1422 if (!new)
1424 close (fd);
1425 return GPG_ERR_ENOMEM;
1428 MUTEX_LOCK (&cn_mutex);
1429 new->conntime = time (NULL);
1430 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
1432 if (pipe (new->status_msg_pipe) == -1)
1433 rc = gpg_error_from_errno (errno);
1435 if (!rc)
1437 if (fcntl (new->status_msg_pipe[0], F_SETFL, O_NONBLOCK) == -1)
1438 rc = gpg_error_from_errno (errno);
1440 if (!rc)
1441 if (fcntl (new->status_msg_pipe[1], F_SETFL, O_NONBLOCK) == -1)
1442 rc = gpg_error_from_errno (errno);
1444 pthread_mutex_init (&new->status_mutex, NULL);
1447 if (!rc)
1449 #ifdef WITH_GNUTLS
1450 new->remote = addr ? 1 : 0;
1451 #endif
1452 new->fd = fd;
1453 rc = create_thread (client_thread, new, &new->tid, 1);
1454 if (rc)
1456 close (new->status_msg_pipe[0]);
1457 close (new->status_msg_pipe[1]);
1458 pthread_mutex_destroy (&new->status_mutex);
1462 if (!rc)
1464 struct slist_s *list = slist_append (cn_thread_list, new);
1466 if (list)
1468 cn_thread_list = list;
1469 if (addr)
1471 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1472 (pthread_t *) new->tid, fd, addr);
1473 #ifdef WITH_GNUTLS
1474 new->peeraddr = str_dup (addr);
1475 #endif
1477 else
1478 log_write (_("new connection: tid=%p, fd=%i"),
1479 (pthread_t *) new->tid, fd);
1481 else
1482 rc = GPG_ERR_ENOMEM;
1485 pthread_cleanup_pop (1);
1487 if (rc)
1489 xfree (new);
1490 close (fd);
1491 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1492 pwmd_strerror (rc));
1494 return rc;
1497 #ifdef WITH_GNUTLS
1498 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1499 static void *
1500 get_in_addr (struct sockaddr *sa)
1502 if (sa->sa_family == AF_INET)
1503 return &(((struct sockaddr_in *) sa)->sin_addr);
1505 return &(((struct sockaddr_in6 *) sa)->sin6_addr);
1508 static void *
1509 tcp_accept_thread (void *arg)
1511 int sockfd = *(int *) arg;
1512 time_t init;
1513 gpg_error_t rc;
1514 int regen_interval = config_get_integer ("global", "tls_regen_interval");
1515 char *tmp = config_get_string ("global", "tls_dh_level");
1516 #ifndef HAVE_PTHREAD_CANCEL
1517 int *n = xmalloc (sizeof (int));
1519 *n = 0;
1520 pthread_setspecific (signal_thread_key, n);
1521 INIT_THREAD_SIGNAL;
1522 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1523 #endif
1525 #ifdef HAVE_PR_SET_NAME
1526 prctl (PR_SET_NAME, "tcp_accept");
1527 #endif
1528 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
1529 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1531 rc = tls_init_params (tmp);
1532 xfree (tmp);
1533 if (rc)
1534 init = 0;
1535 else
1536 init = time (NULL);
1538 for (;;)
1540 struct sockaddr_storage raddr;
1541 socklen_t slen = sizeof (raddr);
1542 int fd;
1543 unsigned long n;
1544 char s[INET6_ADDRSTRLEN];
1545 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1546 #ifndef HAVE_PTHREAD_CANCEL
1547 int *sigusr2;
1549 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1550 if (*sigusr2)
1551 break;
1552 #endif
1554 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1555 if (init == 0 || fd == -1)
1557 if ((init == 0 && (errno == EAGAIN || errno == EWOULDBLOCK))
1558 || (errno == EAGAIN || errno == EWOULDBLOCK))
1560 if (regen_interval > 0
1561 && (init == 0 || time (NULL) - init >= regen_interval))
1563 int i;
1564 int remote_client = 0;
1566 MUTEX_LOCK(&cn_mutex);
1567 for (i = 0; i < slist_length (cn_thread_list); i++)
1569 struct client_thread_s *thd =
1570 slist_nth_data (cn_thread_list, i);
1572 if (thd->remote)
1574 remote_client = 1;
1575 break;
1578 MUTEX_UNLOCK(&cn_mutex);
1580 if (!remote_client)
1582 char *tmp = config_get_string ("global", "tls_dh_level");
1583 gpg_error_t rc;
1585 rc = tls_init_params (tmp);
1586 xfree (tmp);
1587 if (!rc)
1588 init = time (NULL);
1589 else
1591 tv.tv_sec = 10;
1592 tv.tv_usec = 0;
1594 if (fd != -1)
1596 close (fd);
1597 fd = -1;
1601 else
1602 init = 0;
1605 if (fd == -1)
1607 select (0, NULL, NULL, NULL, &tv);
1608 continue;
1612 if (errno == EMFILE || errno == ENFILE)
1613 log_write ("accept(): %s",
1614 pwmd_strerror (gpg_error_from_errno (errno)));
1615 else if (errno != EAGAIN)
1617 if (!quit) // probably EBADF
1618 log_write ("accept(): %s", strerror (errno));
1620 break;
1623 #ifndef HAVE_PTHREAD_CANCEL
1624 select (0, NULL, NULL, NULL, &tv);
1625 #endif
1626 continue;
1629 if (quit)
1631 close (fd);
1632 break;
1635 inet_ntop (raddr.ss_family, get_in_addr ((struct sockaddr *) &raddr),
1636 s, sizeof s);
1637 (void) init_client (fd, s);
1638 n = config_get_integer ("global", "tcp_wait");
1639 if (n > 0)
1641 tv.tv_sec = (n * 100000) / 100000;
1642 tv.tv_usec = (n * 100000) % 100000;
1643 select (0, NULL, NULL, NULL, &tv);
1647 return NULL;
1650 static int
1651 start_stop_tls_with_protocol (int ipv6, int term)
1653 struct addrinfo hints, *servinfo, *p;
1654 int port = config_get_integer ("global", "tcp_port");
1655 char buf[7];
1656 int n;
1657 gpg_error_t rc;
1658 int *fd = ipv6 ? &tls6_fd : &tls_fd;
1660 if (term || config_get_boolean ("global", "enable_tcp") == 0)
1662 if (tls6_fd != -1)
1664 if (spawned_tls6)
1666 #ifdef HAVE_PTHREAD_CANCEL
1667 pthread_cancel (tls6_tid);
1668 #else
1669 pthread_kill (tls6_tid, SIGUSR2);
1670 #endif
1671 pthread_join (tls6_tid, NULL);
1674 shutdown (tls6_fd, SHUT_RDWR);
1675 close (tls6_fd);
1676 tls6_fd = -1;
1677 spawned_tls6 = 0;
1680 if (tls_fd != -1)
1682 if (spawned_tls)
1684 #ifdef HAVE_PTHREAD_CANCEL
1685 pthread_cancel (tls_tid);
1686 #else
1687 pthread_kill (tls_tid, SIGUSR2);
1688 #endif
1689 pthread_join (tls_tid, NULL);
1692 shutdown (tls_fd, SHUT_RDWR);
1693 close (tls_fd);
1694 tls_fd = -1;
1695 spawned_tls = 0;
1698 return 1;
1701 if ((ipv6 && tls6_fd != -1) || (!ipv6 && tls_fd != -1))
1702 return 1;
1704 memset (&hints, 0, sizeof (hints));
1705 hints.ai_family = ipv6 ? AF_INET6 : AF_INET;
1706 hints.ai_socktype = SOCK_STREAM;
1707 hints.ai_flags = AI_PASSIVE;
1708 snprintf (buf, sizeof (buf), "%i", port);
1710 if ((n = getaddrinfo (NULL, buf, &hints, &servinfo)) == -1)
1712 log_write ("getaddrinfo(): %s", gai_strerror (n));
1713 return 0;
1716 for (n = 0, p = servinfo; p != NULL; p = p->ai_next)
1718 int r = 1;
1720 if ((ipv6 && p->ai_family != AF_INET6)
1721 || (!ipv6 && p->ai_family != AF_INET))
1722 continue;
1724 if ((*fd = socket (p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
1726 log_write ("socket(): %s", strerror (errno));
1727 continue;
1730 if (setsockopt (*fd, SOL_SOCKET, SO_REUSEADDR, &r, sizeof (int)) == -1)
1732 log_write ("setsockopt(): %s",
1733 pwmd_strerror (gpg_error_from_errno (errno)));
1734 freeaddrinfo (servinfo);
1735 goto fail;
1738 if (bind (*fd, p->ai_addr, p->ai_addrlen) == -1)
1740 close (*fd);
1741 log_write ("bind(): %s",
1742 pwmd_strerror (gpg_error_from_errno (errno)));
1743 continue;
1746 n++;
1747 break;
1750 freeaddrinfo (servinfo);
1752 if (!n)
1753 goto fail;
1755 #if HAVE_DECL_SO_BINDTODEVICE != 0
1756 char *tmp = config_get_string ("global", "tcp_interface");
1757 if (tmp && setsockopt (*fd, SOL_SOCKET, SO_BINDTODEVICE, tmp,
1758 strlen (tmp)) == -1)
1760 log_write ("setsockopt(): %s",
1761 pwmd_strerror (gpg_error_from_errno (errno)));
1762 xfree (tmp);
1763 goto fail;
1766 xfree (tmp);
1767 #endif
1769 if (listen (*fd, 128) == -1)
1771 log_write ("listen(): %s", strerror (errno));
1772 goto fail;
1775 if (ipv6)
1776 rc = create_thread (tcp_accept_thread, fd, &tls6_tid, 0);
1777 else
1778 rc = create_thread (tcp_accept_thread, fd, &tls_tid, 0);
1780 if (rc)
1782 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1783 pwmd_strerror (rc));
1784 goto fail;
1787 if (ipv6)
1788 spawned_tls6 = 1;
1789 else
1790 spawned_tls = 1;
1792 return 1;
1794 fail:
1795 start_stop_tls_with_protocol (0, 1);
1796 if (tls_fd != -1)
1797 close (tls_fd);
1799 if (tls6_fd != -1)
1800 close (tls6_fd);
1802 tls_fd = -1;
1803 tls6_fd = -1;
1804 return 0;
1807 static int
1808 start_stop_tls (int term)
1810 char *s = config_get_string ("global", "tcp_bind");
1811 int b;
1813 if (!s)
1814 return 0;
1816 if (!strcmp (s, "any"))
1818 b = start_stop_tls_with_protocol (0, term);
1819 if (b)
1820 b = start_stop_tls_with_protocol (1, term);
1822 else if (!strcmp (s, "ipv4"))
1823 b = start_stop_tls_with_protocol (0, term);
1824 else if (!strcmp (s, "ipv6"))
1825 b = start_stop_tls_with_protocol (1, term);
1826 else
1827 b = 0;
1829 xfree (s);
1830 return b;
1832 #endif
1834 static void *
1835 accept_thread (void *arg)
1837 int sockfd = *(int *) arg;
1838 #ifndef HAVE_PTHREAD_CANCEL
1839 int *n = xmalloc (sizeof (int));
1841 *n = 0;
1842 pthread_setspecific (signal_thread_key, n);
1843 INIT_THREAD_SIGNAL;
1844 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1845 #endif
1847 #ifdef HAVE_PR_SET_NAME
1848 prctl (PR_SET_NAME, "accept");
1849 #endif
1850 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
1852 for (;;)
1854 socklen_t slen = sizeof (struct sockaddr_un);
1855 struct sockaddr_un raddr;
1856 int fd;
1857 #ifndef HAVE_PTHREAD_CANCEL
1858 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1859 int *sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1861 if (*sigusr2)
1862 break;
1863 #endif
1865 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1866 if (fd == -1)
1868 if (errno == EMFILE || errno == ENFILE)
1869 log_write ("accept(): %s",
1870 pwmd_strerror (gpg_error_from_errno (errno)));
1871 else if (errno != EAGAIN)
1873 if (!quit) // probably EBADF
1874 log_write ("accept(): %s",
1875 pwmd_strerror (gpg_error_from_errno (errno)));
1877 break;
1880 #ifndef HAVE_PTHREAD_CANCEL
1881 select (0, NULL, NULL, NULL, &tv);
1882 #endif
1883 continue;
1886 (void) init_client (fd, NULL);
1889 /* Just in case accept() failed for some reason other than EBADF */
1890 quit = 1;
1891 return NULL;
1894 static void *
1895 cache_timer_thread (void *arg)
1897 unsigned k = 0;
1898 #ifndef HAVE_PTHREAD_CANCEL
1899 int *n = xmalloc (sizeof (int));
1901 *n = 0;
1902 pthread_setspecific (signal_thread_key, n);
1903 INIT_THREAD_SIGNAL;
1904 #endif
1906 #ifdef HAVE_PR_SET_NAME
1907 prctl (PR_SET_NAME, "timer");
1908 #endif
1909 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
1911 for (;;)
1913 struct timeval tv = { 1, 0 };
1914 unsigned keepalive = config_get_integer ("global", "keepalive_interval");
1915 #ifndef HAVE_PTHREAD_CANCEL
1916 int *n;
1918 n = (int *) pthread_getspecific (signal_thread_key);
1919 if (*n)
1920 break;
1921 #endif
1923 select (0, NULL, NULL, NULL, &tv);
1924 cache_adjust_timeout ();
1926 if (++k >= keepalive)
1928 send_status_all (STATUS_KEEPALIVE, NULL);
1929 k = 0;
1933 return NULL;
1936 static int
1937 signal_loop (sigset_t sigset)
1939 int done = 0;
1940 int siint = 0;
1944 int sig;
1946 sigwait (&sigset, &sig);
1948 if (sig != SIGQUIT)
1949 log_write (_("caught signal %i (%s)"), sig, strsignal (sig));
1951 switch (sig)
1953 case SIGHUP:
1954 pthread_cond_signal (&rcfile_cond);
1955 break;
1956 case SIGUSR1:
1957 log_write (_("clearing file cache"));
1958 cache_clear (NULL, NULL, 1);
1959 send_status_all (STATUS_CACHE, NULL);
1960 break;
1961 case SIGQUIT:
1962 done = 1;
1963 break;
1964 default:
1965 siint = 1;
1966 done = 1;
1967 break;
1970 while (!done);
1972 return siint;
1975 static void
1976 catchsig (int sig)
1978 log_write (_ ("Caught signal %i (%s). Exiting."), sig, strsignal (sig));
1979 #ifdef HAVE_BACKTRACE
1980 BACKTRACE (__FUNCTION__);
1981 #endif
1982 longjmp (jmp, 1);
1985 static void *
1986 waiting_for_exit (void *arg)
1988 int last = 0;
1989 #ifndef HAVE_PTHREAD_CANCEL
1990 int *n = xmalloc (sizeof (int));
1992 *n = 0;
1993 pthread_setspecific (signal_thread_key, n);
1994 INIT_THREAD_SIGNAL;
1995 #endif
1997 #ifdef HAVE_PR_SET_NAME
1998 prctl (PR_SET_NAME, "exiting");
1999 #endif
2000 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
2001 log_write (_("waiting for all clients to disconnect"));
2002 MUTEX_LOCK (&quit_mutex);
2003 pthread_cleanup_push (cleanup_mutex_cb, &quit_mutex);
2005 for (;;)
2007 struct timespec ts;
2008 int n;
2010 MUTEX_LOCK (&cn_mutex);
2011 n = slist_length (cn_thread_list);
2012 MUTEX_UNLOCK (&cn_mutex);
2013 if (!n)
2014 break;
2016 #ifndef HAVE_PTHREAD_CANCEL
2017 int *s = (int *) pthread_getspecific (signal_thread_key);
2018 if (*s)
2019 break;
2020 #endif
2022 if (last != n)
2024 log_write (_("%i clients remain"), n);
2025 last = n;
2028 INIT_TIMESPEC (SIG_TIMEOUT, ts);
2029 pthread_cond_timedwait (&quit_cond, &quit_mutex, &ts);
2032 kill (getpid (), SIGQUIT);
2033 pthread_cleanup_pop (1);
2034 return NULL;
2037 static int
2038 server_loop (int sockfd, char **socketpath)
2040 pthread_t accept_tid;
2041 pthread_t cache_timeout_tid;
2042 int cancel_timeout_thread = 0, cancel_accept_thread = 0;
2043 sigset_t sigset;
2044 int n;
2045 int segv = 0;
2046 gpg_error_t rc;
2048 init_commands ();
2049 sigemptyset (&sigset);
2051 /* Termination */
2052 sigaddset (&sigset, SIGTERM);
2053 sigaddset (&sigset, SIGINT);
2055 /* Clears the file cache. */
2056 sigaddset (&sigset, SIGUSR1);
2058 /* Configuration file reloading. */
2059 sigaddset (&sigset, SIGHUP);
2061 /* For exiting cleanly. */
2062 sigaddset (&sigset, SIGQUIT);
2064 #ifndef HAVE_PTHREAD_CANCEL
2066 The socket, cache and rcfile threads use this signal when
2067 pthread_cancel() is unavailable. Prevent the main thread from
2068 catching this signal from another process.
2070 sigaddset (&sigset, SIGUSR2);
2071 #endif
2073 /* When mem.c cannot find a pointer in the list (double free). */
2074 signal (SIGABRT, catchsig);
2075 sigaddset (&sigset, SIGABRT);
2076 sigprocmask (SIG_BLOCK, &sigset, NULL);
2078 #ifndef HAVE_PTHREAD_CANCEL
2079 /* Remove this signal from the watched signals in signal_loop(). */
2080 sigdelset (&sigset, SIGUSR2);
2081 #endif
2083 /* Can show a backtrace of the stack in the log. */
2084 signal (SIGSEGV, catchsig);
2086 #ifdef WITH_GNUTLS
2087 /* Needs to be done after the fork(). */
2088 if (!start_stop_tls (0))
2090 segv = 1;
2091 goto done;
2093 #endif
2095 pthread_mutex_init (&quit_mutex, NULL);
2096 pthread_cond_init (&quit_cond, NULL);
2097 char *p = get_username (getuid());
2098 log_write (_("%s started for user %s"), PACKAGE_STRING, p);
2099 xfree (p);
2101 #ifdef WITH_GNUTLS
2102 if (config_get_boolean ("global", "enable_tcp"))
2103 log_write (_("Listening on %s and TCP port %i"), *socketpath,
2104 config_get_integer ("global", "tcp_port"));
2105 else
2106 log_write (_("Listening on %s"), *socketpath);
2107 #else
2108 log_write (_("Listening on %s"), *socketpath);
2109 #endif
2111 rc = create_thread (reload_rcfile_thread, NULL, &rcfile_tid, 0);
2112 if (rc)
2114 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2115 pwmd_strerror (rc));
2116 goto done;
2119 rc = create_thread (cache_timer_thread, NULL, &cache_timeout_tid, 0);
2120 if (rc)
2122 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2123 pwmd_strerror (rc));
2124 goto done;
2127 cancel_timeout_thread = 1;
2128 rc = create_thread (accept_thread, &sockfd, &accept_tid, 0);
2129 if (rc)
2131 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2132 pwmd_strerror (rc));
2133 goto done;
2136 cancel_accept_thread = 1;
2137 if (!setjmp (jmp))
2138 signal_loop (sigset);
2139 else
2140 segv = 1;
2142 done:
2144 * We're out of the main server loop. This happens when a signal was sent
2145 * to terminate the daemon. We'll wait for all clients to disconnect
2146 * before exiting but exit immediately if another termination signal is
2147 * sent.
2149 if (cancel_accept_thread)
2151 #ifdef HAVE_PTHREAD_CANCEL
2152 int n = pthread_cancel (accept_tid);
2153 #else
2154 int n = pthread_kill (accept_tid, SIGUSR2);
2155 #endif
2156 if (!n)
2157 pthread_join (accept_tid, NULL);
2160 if (cancel_timeout_thread)
2162 #ifdef HAVE_PTHREAD_CANCEL
2163 n = pthread_cancel (cache_timeout_tid);
2164 #else
2165 n = pthread_kill (cache_timeout_tid, SIGUSR2);
2166 #endif
2167 if (!n)
2168 pthread_join (cache_timeout_tid, NULL);
2171 #ifdef WITH_GNUTLS
2172 start_stop_tls (1);
2173 #endif
2174 shutdown (sockfd, SHUT_RDWR);
2175 close (sockfd);
2176 unlink (*socketpath);
2177 xfree (*socketpath);
2178 *socketpath = NULL;
2179 MUTEX_LOCK (&cn_mutex);
2180 n = slist_length (cn_thread_list);
2181 MUTEX_UNLOCK (&cn_mutex);
2183 if (n && !segv)
2185 pthread_t tid;
2187 rc = create_thread (waiting_for_exit, NULL, &tid, 0);
2188 if (!rc)
2190 if (signal_loop (sigset))
2192 log_write (_("Received second termination request. Exiting."));
2193 #ifdef HAVE_PTHREAD_CANCEL
2194 pthread_cancel (tid);
2195 #else
2196 pthread_kill (tid, SIGUSR2);
2197 #endif
2198 pthread_join (tid, NULL);
2201 else
2202 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2203 pwmd_strerror (rc));
2206 cleanup_all_clients (0);
2207 deinit_commands ();
2208 pthread_cond_destroy (&quit_cond);
2209 pthread_mutex_destroy (&quit_mutex);
2210 return segv ? EXIT_FAILURE : EXIT_SUCCESS;;
2213 static void
2214 startup_failure ()
2216 log_write (_
2217 ("Failed to add a file to the cache. Use --force to force startup. Exiting."));
2218 cache_clear (NULL, NULL, 1);
2221 static void
2222 usage (const char *pn, int status)
2224 FILE *fp = status == EXIT_FAILURE ? stderr : stdout;
2226 fprintf (fp, _("Usage: %s [OPTIONS] [file1] [...]\n"
2227 " --debug=[a:..][,g:N][,t:N] enable debugging (a:[ixedsc],g:[1-9],t:[0-N])\n"
2228 " -f, --rcfile=filename load the specfied configuration file\n"
2229 " (~/.pwmd/config)\n"
2230 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2231 " --kill terminate an existing instance of pwmd\n"
2232 " -n, --no-fork run as a foreground process\n"
2233 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2234 " --ignore, --force ignore file errors during startup\n"
2235 " -o, --outfile=filename output file when importing or converting\n"
2236 " -C, --convert=filename convert a version 2 data file to version 3\n"
2237 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2238 " -k, --passphrase-file=file for use when importing or converting\n"
2239 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2240 " converting\n"
2241 " --no-passphrase when importing or converting\n"
2242 " --keyid=keyID[,..] public key to use when encrypting\n"
2243 " --sign-keyid=fpr[,..] fingerprint of the signing key to use\n"
2244 " --symmetric use conventional encryption with optional signer\n"
2245 " --keyparam=filename custom key parameters to use (gpg default)\n"
2246 " --help this help text\n"
2247 " --version show version and compile time features\n"),
2248 pn);
2249 exit (status);
2252 static void
2253 unlink_stale_socket (const char *sock, const char *pidfile)
2255 log_write (_ ("removing stale socket %s"), sock);
2256 unlink (sock);
2257 unlink (pidfile);
2260 static int
2261 test_pidfile (const char *path, const char *sock, char *buf, size_t buflen,
2262 char **pidfile, int create, mode_t mode, int terminate)
2264 pid_t pid;
2265 int fd;
2266 size_t len;
2268 if (!create)
2270 snprintf (buf, buflen, "%s/%s.pid", homedir, sock);
2271 *pidfile = str_dup (buf);
2272 fd = open (buf, O_RDONLY);
2274 else
2275 fd = open (*pidfile, O_CREAT|O_WRONLY|O_TRUNC, mode);
2277 if (fd == -1)
2279 if (!create && errno != ENOENT)
2281 log_write ("%s: %s", buf, pwmd_strerror (errno));
2282 free (*pidfile);
2283 *pidfile = NULL;
2284 return -1;
2286 else if (!create && !terminate)
2287 return 0;
2289 log_write ("%s: %s", *pidfile, strerror (errno));
2290 return -1;
2293 if (create)
2295 snprintf (buf, buflen, "%i", getpid ());
2296 ssize_t ret = write (fd, buf, strlen (buf));
2297 if (ret == -1)
2298 log_write ("%s (%i): %s", __FUNCTION__, __LINE__,
2299 pwmd_strerror (gpg_error_from_syserror ()));
2300 close (fd);
2301 return 0;
2304 len = read (fd, buf, buflen);
2305 close (fd);
2306 if (len == 0)
2308 unlink_stale_socket (path, *pidfile);
2309 return 0;
2312 if (sscanf (buf, "%5i", &pid) != 1 || pid == 0)
2314 if (!terminate)
2316 unlink_stale_socket (path, *pidfile);
2317 return 0;
2321 if (kill (pid, 0) == -1)
2323 unlink_stale_socket (path, *pidfile);
2324 return 0;
2327 if (terminate)
2329 if (kill (pid, SIGTERM) == -1)
2330 log_write ("%s: %s", path, pwmd_strerror (errno));
2332 else
2333 log_write (_ ("an instance for socket %s is already running"), path);
2335 xfree (*pidfile);
2336 *pidfile = NULL;
2337 return 1;
2340 static unsigned
2341 parse_debug_level (const char *str, unsigned *debug, int *gpgme, int *tls)
2343 const char *p;
2344 unsigned level = 0;
2345 int gl = 0, tl = 0;
2347 for (p = str; p && *p; p++)
2349 if (*p == 'a') // assuan debug flags
2351 if (*++p != ':')
2352 return 1;
2354 while (*++p)
2356 switch (*p)
2358 case 'i':
2359 level |= ASSUAN_LOG_INIT;
2360 break;
2361 case 'x':
2362 level |= ASSUAN_LOG_CTX;
2363 break;
2364 case 'e':
2365 level |= ASSUAN_LOG_ENGINE;
2366 break;
2367 case 'd':
2368 level |= ASSUAN_LOG_DATA;
2369 break;
2370 case 's':
2371 level |= ASSUAN_LOG_SYSIO;
2372 break;
2373 case 'c':
2374 level |= ASSUAN_LOG_CONTROL;
2375 break;
2376 case ',':
2377 break;
2378 default:
2379 return 1;
2382 if (*p == ',')
2383 break;
2386 if (!*p)
2387 break;
2389 else if (*p == 'g' || *p == 't') // gpgme and TLS debug level
2391 int t = *p == 't';
2392 int n;
2394 if (*++p != ':')
2395 return 1;
2397 if (!isdigit (*++p))
2398 return 1;
2400 n = atoi (p);
2401 if (t)
2402 tl = n;
2403 else
2404 gl = n;
2406 if (tl < 0 || gl < 0 || gl > 9)
2407 return 1;
2409 while (isdigit (*p))
2410 p++;
2412 p--;
2413 if (*(p+1) && *(p+1) != ',')
2414 return 1;
2415 else if (*(p+1))
2416 p++;
2418 else
2419 return 1;
2422 if (tl)
2423 *tls = tl;
2425 if (gl)
2426 *gpgme = gl;
2428 *debug = level;
2429 return 0;
2433 main (int argc, char *argv[])
2435 int opt;
2436 struct sockaddr_un addr;
2437 char buf[PATH_MAX];
2438 char *socketpath = NULL, *socketdir, *socketname = NULL;
2439 char *socketarg = NULL;
2440 char *datadir = NULL;
2441 char *pidfile = NULL;
2442 mode_t mode = 0600;
2443 int x;
2444 char *p;
2445 char **cache_push = NULL;
2446 char *import = NULL, *keyid = NULL, *sign_keyid = NULL;
2447 char *keyparam = NULL;
2448 int estatus = EXIT_FAILURE;
2449 int sockfd;
2450 char *outfile = NULL;
2451 int do_unlink = 0;
2452 int secure = 0;
2453 int show_version = 0;
2454 int force = 0;
2455 gpg_error_t rc;
2456 char *keyfile = NULL;
2457 int exists;
2458 int optindex;
2459 int terminate = 0;
2460 int sym = 0;
2461 int gpgme_level = -1;
2462 int tls_level = -1;
2463 /* Must maintain the same order as longopts[] */
2464 enum
2466 OPT_VERSION, OPT_HELP, OPT_HOMEDIR, OPT_NO_FORK, OPT_DISABLE_DUMP,
2467 OPT_FORCE, OPT_RCFILE, OPT_PASSPHRASE_FILE, OPT_IMPORT, OPT_OUTFILE,
2468 OPT_KEYID, OPT_SIGN_KEYID, OPT_SYMMETRIC, OPT_KEYPARAM, OPT_KILL,
2469 OPT_DEBUG
2471 const char *optstring = "nf:C:k:I:o:s";
2472 const struct option longopts[] = {
2473 {"version", no_argument, 0, 0},
2474 {"help", no_argument, 0, 0},
2475 {"homedir", required_argument, 0, 0},
2476 {"no-fork", no_argument, 0, 'n'},
2477 {"disable_dump", no_argument, 0, 0},
2478 {"force", no_argument, 0, 0},
2479 {"rcfile", required_argument, 0, 'f'},
2480 {"passphrase-file", required_argument, 0, 'k'},
2481 {"import", required_argument, 0, 'I'},
2482 {"outfile", required_argument, 0, 'o'},
2483 {"keyid", required_argument, 0, 0},
2484 {"sign-keyid", required_argument, 0, 0},
2485 {"symmetric", no_argument, 0, 's'},
2486 {"keyparam", required_argument, 0, 0},
2487 {"kill", no_argument, 0, 0},
2488 {"debug", required_argument, 0, 0},
2489 {0, 0, 0, 0}
2492 log_fd = -1;
2493 cmdline = 1;
2495 #ifndef DEBUG
2496 #ifdef HAVE_SETRLIMIT
2497 struct rlimit rl;
2499 rl.rlim_cur = rl.rlim_max = 0;
2501 if (setrlimit (RLIMIT_CORE, &rl) != 0)
2502 err (EXIT_FAILURE, "setrlimit()");
2503 #endif
2505 #ifdef HAVE_PR_SET_DUMPABLE
2506 prctl (PR_SET_DUMPABLE, 0);
2507 #endif
2508 #endif
2510 #ifdef ENABLE_NLS
2511 setlocale (LC_ALL, "");
2512 bindtextdomain ("pwmd", LOCALEDIR);
2513 textdomain ("pwmd");
2514 #endif
2516 if (setup_crypto ())
2517 exit (EXIT_FAILURE);
2519 #ifdef WITH_GNUTLS
2520 tls_level = tls_level == -1 ? 1 : tls_level;
2521 gnutls_global_set_log_level (tls_level);
2522 tls_fd = -1;
2523 tls6_fd = -1;
2524 #endif
2525 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
2526 xmlInitMemory ();
2527 xmlInitGlobals ();
2528 xmlInitParser ();
2529 xmlXPathInit ();
2531 while ((opt = getopt_long (argc, argv, optstring, longopts, &optindex))
2532 != -1)
2534 switch (opt)
2536 case 'I':
2537 import = optarg;
2538 break;
2539 case 'k':
2540 keyfile = optarg;
2541 break;
2542 case 'o':
2543 outfile = optarg;
2544 break;
2545 case 'D':
2546 secure = 1;
2547 break;
2548 case 'n':
2549 nofork = 1;
2550 break;
2551 case 'f':
2552 rcfile = str_dup (optarg);
2553 break;
2554 case 's':
2555 sym = 1;
2556 break;
2557 default:
2558 usage (argv[0], EXIT_FAILURE);
2559 break;
2560 case 0:
2561 switch (optindex)
2563 case OPT_DEBUG:
2564 if (parse_debug_level (optarg, &assuan_level, &gpgme_level,
2565 &tls_level))
2566 usage (argv[0], EXIT_FAILURE);
2567 break;
2568 case OPT_SYMMETRIC:
2569 sym = 1;
2570 break;
2571 case OPT_VERSION:
2572 show_version = 1;
2573 break;
2574 case OPT_HELP:
2575 usage (argv[0], EXIT_SUCCESS);
2576 break;
2577 case OPT_HOMEDIR:
2578 homedir = str_dup (optarg);
2579 break;
2580 case OPT_NO_FORK:
2581 nofork = 1;
2582 break;
2583 case OPT_DISABLE_DUMP:
2584 secure = 1;
2585 break;
2586 case OPT_FORCE:
2587 force = 1;
2588 break;
2589 case OPT_RCFILE:
2590 rcfile = str_dup (optarg);
2591 break;
2592 case OPT_PASSPHRASE_FILE:
2593 keyfile = optarg;
2594 break;
2595 case OPT_IMPORT:
2596 import = optarg;
2597 break;
2598 case OPT_OUTFILE:
2599 outfile = optarg;
2600 break;
2601 case OPT_KEYID:
2602 keyid = optarg;
2603 break;
2604 case OPT_SIGN_KEYID:
2605 sign_keyid = optarg;
2606 break;
2607 case OPT_KEYPARAM:
2608 keyparam = optarg;
2609 break;
2610 case OPT_KILL:
2611 terminate = 1;
2612 break;
2613 default:
2614 usage (argv[0], EXIT_FAILURE);
2619 if (show_version)
2621 printf (_("%s\n\n"
2622 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016\n"
2623 "%s\n"
2624 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2625 "Compile time features:\n%s"), PACKAGE_STRING,
2626 PACKAGE_BUGREPORT,
2627 #ifdef PWMD_HOMEDIR
2628 "+PWMD_HOMEDIR=" PWMD_HOMEDIR "\n"
2629 #endif
2630 #ifdef WITH_GNUTLS
2631 "+WITH_GNUTLS\n"
2632 #else
2633 "-WITH_GNUTLS\n"
2634 #endif
2635 #ifdef WITH_LIBACL
2636 "+WITH_LIBACL\n"
2637 #else
2638 "-WITH_LIBACL\n"
2639 #endif
2640 #ifdef DEBUG
2641 "+DEBUG\n"
2642 #else
2643 "-DEBUG\n"
2644 #endif
2645 #ifdef MEM_DEBUG
2646 "+MEM_DEBUG\n"
2647 #else
2648 "-MEM_DEBUG\n"
2649 #endif
2650 #ifdef MUTEX_DEBUG
2651 "+MUTEX_DEBUG\n"
2652 #else
2653 "-MUTEX_DEBUG\n"
2654 #endif
2656 exit (EXIT_SUCCESS);
2659 if (!homedir)
2660 #ifdef PWMD_HOMEDIR
2661 homedir = str_dup(PWMD_HOMEDIR);
2662 #else
2663 homedir = str_asprintf ("%s/.pwmd", get_home_dir());
2664 #endif
2666 if (mkdir (homedir, 0700) == -1 && errno != EEXIST)
2667 err (EXIT_FAILURE, "%s", homedir);
2669 if (!rcfile)
2670 rcfile = str_asprintf ("%s/config", homedir);
2672 pthread_key_create (&last_error_key, free_key);
2673 #ifndef HAVE_PTHREAD_CANCEL
2674 pthread_key_create (&signal_thread_key, free_key);
2675 #endif
2677 pthread_mutexattr_t attr;
2678 pthread_mutexattr_init (&attr);
2679 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
2680 pthread_mutex_init (&rcfile_mutex, &attr);
2681 global_config = config_parse (rcfile, 0);
2682 if (!global_config)
2684 pthread_mutexattr_destroy (&attr);
2685 pthread_mutex_destroy (&rcfile_mutex);
2686 exit (EXIT_FAILURE);
2689 p = config_get_string ("global", "gpg_homedir");
2690 if (!p)
2691 datadir = str_asprintf ("%s/.gnupg", homedir);
2692 else
2693 datadir = expand_homedir (p);
2695 xfree (p);
2696 if (mkdir (datadir, 0700) == -1 && errno != EEXIST)
2697 err (EXIT_FAILURE, "%s", datadir);
2699 if (gpgme_level != -1)
2701 char s[2] = { gpgme_level + '0', 0 };
2703 if (getenv ("GPGME_DEBUG"))
2704 log_write (_ ("Overriding GPGME_DEBUG environment with level %u!"),
2705 gpgme_level);
2707 gpgme_set_global_flag ("debug", s);
2710 rc = gpgme_set_engine_info (GPGME_PROTOCOL_OpenPGP, NULL, datadir);
2711 xfree (datadir);
2713 snprintf (buf, sizeof (buf), "%s/data", homedir);
2714 if (mkdir (buf, 0700) == -1 && errno != EEXIST)
2715 err (EXIT_FAILURE, "%s", buf);
2717 datadir = str_dup (buf);
2718 pthread_cond_init (&rcfile_cond, NULL);
2719 pthread_mutex_init (&cn_mutex, &attr);
2720 pthread_mutexattr_destroy (&attr);
2722 setup_logging ();
2724 x = config_get_int_param (global_config, "global", "priority", &exists);
2725 if (exists && x != atoi(INVALID_PRIORITY))
2727 errno = 0;
2728 if (setpriority (PRIO_PROCESS, 0, x) == -1)
2730 log_write ("setpriority(): %s",
2731 pwmd_strerror (gpg_error_from_errno (errno)));
2732 goto do_exit;
2735 #ifdef HAVE_MLOCKALL
2736 if (disable_mlock == 0 && mlockall (MCL_CURRENT | MCL_FUTURE) == -1)
2738 log_write ("mlockall(): %s",
2739 pwmd_strerror (gpg_error_from_errno (errno)));
2740 goto do_exit;
2742 #endif
2744 rc = cache_init ();
2745 if (rc)
2747 log_write ("pwmd: ERR %i: %s", rc, pwmd_strerror (rc));
2748 exit (EXIT_FAILURE);
2751 if (import)
2753 char **keyids = NULL, **sign_keyids = NULL;
2755 if (!outfile || !*outfile || argc != optind)
2756 usage (argv[0], EXIT_FAILURE);
2758 if (keyid)
2759 keyids = str_split (keyid, ",", 0);
2760 if (sign_keyid)
2761 sign_keyids = str_split (sign_keyid, ",", 0);
2762 rc = xml_import (import, outfile, keyids, sign_keyids, keyfile, keyparam, sym);
2763 strv_free (keyids);
2764 strv_free (sign_keyids);
2765 if (rc)
2767 if (gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
2768 rc = gpg_error (rc);
2770 log_write ("%s: %u: %s", import, rc, pwmd_strerror (rc));
2773 config_free (global_config);
2774 xfree (rcfile);
2775 exit (rc ? EXIT_FAILURE : EXIT_SUCCESS);
2778 p = config_get_string ("global", "socket_path");
2779 if (!p)
2780 p = str_asprintf ("%s/socket", homedir);
2782 socketarg = expand_homedir (p);
2783 xfree (p);
2785 if (!secure)
2786 disable_list_and_dump = config_get_boolean ("global",
2787 "disable_list_and_dump");
2788 else
2789 disable_list_and_dump = secure;
2791 cache_push = config_get_list ("global", "cache_push");
2793 while (optind < argc)
2795 if (strv_printf (&cache_push, "%s", argv[optind++]) == 0)
2796 errx (EXIT_FAILURE, "%s", pwmd_strerror (GPG_ERR_ENOMEM));
2799 if (strchr (socketarg, '/') == NULL)
2801 socketdir = getcwd (buf, sizeof (buf));
2802 socketname = str_dup (socketarg);
2803 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2805 else
2807 socketname = str_dup (strrchr (socketarg, '/'));
2808 socketname++;
2809 socketarg[strlen (socketarg) - strlen (socketname) - 1] = 0;
2810 socketdir = str_dup (socketarg);
2811 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2814 if (chdir (datadir))
2816 log_write ("%s: %s", datadir,
2817 pwmd_strerror (gpg_error_from_errno (errno)));
2818 unlink (socketpath);
2819 goto do_exit;
2822 x = test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 0,
2823 mode, terminate);
2824 if (!terminate && x)
2825 goto do_exit;
2826 else if (terminate)
2828 estatus = x != 1 ? EXIT_FAILURE : EXIT_SUCCESS;
2829 goto do_exit;
2833 * bind() doesn't like the full pathname of the socket or any non alphanum
2834 * characters so change to the directory where the socket is wanted then
2835 * create it then change to datadir.
2837 if (chdir (socketdir))
2839 log_write ("%s: %s", socketdir,
2840 pwmd_strerror (gpg_error_from_errno (errno)));
2841 goto do_exit;
2844 xfree (socketdir);
2846 if ((sockfd = socket (PF_UNIX, SOCK_STREAM, 0)) == -1)
2848 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2849 goto do_exit;
2852 addr.sun_family = AF_UNIX;
2853 snprintf (addr.sun_path, sizeof (addr.sun_path), "%s", socketname);
2854 do_unlink = 1;
2855 if (bind (sockfd, (struct sockaddr *) &addr, sizeof (struct sockaddr)) ==
2858 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2860 if (errno == EADDRINUSE)
2862 do_unlink = 0;
2863 log_write (_("Either there is another pwmd running or '%s' is a \n"
2864 "stale socket. Please remove it manually."), socketpath);
2867 goto do_exit;
2871 char *t = config_get_string ("global", "socket_perms");
2872 mode_t mask;
2874 if (t)
2876 mode = strtol (t, NULL, 8);
2877 mask = umask (0);
2878 xfree (t);
2880 if (chmod (socketname, mode) == -1)
2882 log_write ("%s: %s", socketname,
2883 pwmd_strerror (gpg_error_from_errno (errno)));
2884 close (sockfd);
2885 umask (mask);
2886 goto do_exit;
2889 umask (mask);
2893 xfree (--socketname);
2895 if (chdir (datadir))
2897 log_write ("%s: %s", datadir,
2898 pwmd_strerror (gpg_error_from_errno (errno)));
2899 close (sockfd);
2900 goto do_exit;
2903 xfree (datadir);
2906 * Set the cache entry for a file. Prompts for the password.
2908 if (cache_push)
2910 for (opt = 0; cache_push[opt]; opt++)
2912 struct crypto_s *crypto = NULL;
2913 char *pw_file = config_get_string (cache_push[opt],
2914 "passphrase_file");
2915 gpg_error_t rc = crypto_init (&crypto, NULL, cache_push[opt],
2916 pw_file != NULL, pw_file);
2918 if (!rc)
2920 crypto->flags |= pw_file ? CRYPTO_FLAG_KEYFILE : 0;
2921 crypto->keyfile = pw_file;
2923 else
2924 xfree (pw_file);
2926 if (rc)
2928 estatus = EXIT_FAILURE;
2929 goto do_exit;
2932 rc = do_cache_push (crypto);
2933 if (rc && !force)
2935 log_write ("ERR %u: %s", rc, pwmd_strerror(rc));
2936 strv_free (cache_push);
2937 startup_failure ();
2938 estatus = EXIT_FAILURE;
2939 crypto_free (crypto);
2940 goto do_exit;
2942 else if (rc)
2943 log_write ("%s: %s", crypto->filename, pwmd_strerror(rc));
2944 else
2945 log_write (_("Successfully added '%s' to the cache."),
2946 crypto->filename);
2948 crypto_free (crypto);
2951 strv_free (cache_push);
2952 log_write (!nofork ? _("Done. Daemonizing...") :
2953 _("Done. Waiting for connections..."));
2956 if (listen (sockfd, 128) == -1)
2958 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2959 goto do_exit;
2962 if (!nofork)
2964 switch (fork ())
2966 case -1:
2967 log_write ("fork(): %s",
2968 pwmd_strerror (gpg_error_from_errno (errno)));
2969 goto do_exit;
2970 case 0:
2971 close (0);
2972 close (1);
2973 close (2);
2974 setsid ();
2975 break;
2976 default:
2977 _exit (EXIT_SUCCESS);
2981 (void)test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 1,
2982 mode, 0);
2983 cmdline = 0;
2984 pthread_key_create (&thread_name_key, free_key);
2985 estatus = server_loop (sockfd, &socketpath);
2987 do_exit:
2988 if (socketpath && do_unlink)
2990 unlink (socketpath);
2991 xfree (socketpath);
2994 xfree (socketarg);
2995 #ifdef WITH_GNUTLS
2996 gnutls_global_deinit ();
2997 tls_deinit_params ();
2998 #endif
2999 if (rcfile_tid)
3001 #ifdef HAVE_PTHREAD_CANCEL
3002 pthread_cancel (rcfile_tid);
3003 #else
3004 pthread_kill (rcfile_tid, SIGUSR2);
3005 pthread_cond_signal (&rcfile_cond);
3006 #endif
3007 pthread_join (rcfile_tid, NULL);
3010 pthread_cond_destroy (&rcfile_cond);
3011 pthread_mutex_destroy (&rcfile_mutex);
3012 pthread_key_delete (last_error_key);
3013 #ifndef HAVE_PTHREAD_CANCEL
3014 pthread_key_delete (signal_thread_key);
3015 #endif
3017 if (global_config)
3018 config_free (global_config);
3020 free_invoking_users (invoking_users);
3021 xfree (rcfile);
3022 xfree (home_directory);
3023 xfree (homedir);
3024 xmlCleanupParser ();
3025 xmlCleanupGlobals ();
3027 if (pidfile)
3028 unlink (pidfile);
3029 xfree (pidfile);
3031 if (estatus == EXIT_SUCCESS && !terminate)
3032 log_write (_("pwmd exiting normally"));
3034 pthread_key_delete (thread_name_key);
3035 closelog ();
3037 if (log_fd != -1)
3038 close (log_fd);
3040 exit (estatus);
3043 gpg_error_t lock_flock (assuan_context_t ctx, const char *filename,
3044 int type, int *fd)
3046 gpg_error_t rc = 0;
3048 #ifdef HAVE_FLOCK
3049 *fd = open (filename, O_RDONLY);
3050 if (*fd == -1)
3051 return gpg_error_from_syserror ();
3053 TRY_FLOCK (ctx, *fd, type, rc);
3054 if (rc)
3056 close (*fd);
3057 *fd = -1;
3059 #endif
3061 return rc;
3064 void unlock_flock (int *fd)
3066 #ifdef HAVE_FLOCK
3067 if (*fd != -1)
3068 close (*fd);
3070 *fd = -1;
3071 #endif