CLEARCACHE: Reworked ACL's.
[libpwmd.git] / src / pwmd.c
blob886b48a5e3c33f6c6155746b91a05df74c71ceab
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 pthread_t keepalive_tid;
103 static int log_fd;
104 static unsigned assuan_level;
106 #ifndef HAVE_PTHREAD_CANCEL
107 static pthread_key_t signal_thread_key;
108 #endif
110 #ifdef WITH_GNUTLS
111 static int tls_fd;
112 static int tls6_fd;
113 static pthread_t tls_tid;
114 static pthread_t tls6_tid;
115 static int spawned_tls;
116 static int spawned_tls6;
118 static int start_stop_tls (int term);
119 #endif
121 static gpg_error_t do_cache_push (struct crypto_s *crypto);
122 static int signal_loop (sigset_t sigset);
124 #ifndef HAVE_PTHREAD_CANCEL
125 #define INIT_THREAD_SIGNAL do { \
126 struct sigaction act; \
127 sigset_t sigset; \
128 sigemptyset (&sigset); \
129 sigaddset (&sigset, SIGUSR2); \
130 pthread_sigmask (SIG_UNBLOCK, &sigset, NULL); \
131 memset (&act, 0, sizeof(act)); \
132 act.sa_flags = SA_SIGINFO; \
133 act.sa_mask = sigset; \
134 act.sa_sigaction = catch_thread_signal; \
135 sigaction (SIGUSR2, &act, NULL); \
136 } while (0)
138 static void
139 catch_thread_signal (int sig, siginfo_t *info, void *ctx)
141 int *n = (int *) pthread_getspecific (signal_thread_key);
143 *n = 1;
144 pthread_setspecific (signal_thread_key, n);
146 #endif
148 static void
149 setup_logging ()
151 int n = config_get_boolean ("global", "enable_logging");
153 if (n)
155 char *p = config_get_string ("global", "log_path");
157 if (!p || (logfile && p && log_fd != -1 && strcmp(p, logfile)))
159 if (log_fd != -1)
160 close (log_fd);
162 log_fd = -1;
165 xfree (logfile);
166 logfile = NULL;
167 if (p)
168 logfile = expand_homedir (p);
169 xfree (p);
171 else
173 xfree (logfile);
174 logfile = NULL;
175 if (log_fd != -1)
176 close(log_fd);
178 log_fd = -1;
179 closelog ();
182 log_syslog = config_get_boolean ("global", "syslog");
183 if (log_syslog == 1)
184 openlog ("pwmd", LOG_NDELAY | LOG_PID, LOG_DAEMON);
187 static void *
188 reload_rcfile_thread (void *arg)
190 #ifndef HAVE_PTHREAD_CANCEL
191 int *n = xmalloc (sizeof (int));
193 *n = 0;
194 pthread_setspecific (signal_thread_key, n);
195 INIT_THREAD_SIGNAL;
196 #endif
198 #ifdef HAVE_PR_SET_NAME
199 prctl (PR_SET_NAME, "reload rcfile");
200 #endif
201 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
202 MUTEX_LOCK (&rcfile_mutex);
204 for (;;)
206 struct slist_s *keep = NULL;
207 struct slist_s *config;
208 int b = disable_list_and_dump;
210 pthread_cleanup_push (cleanup_mutex_cb, &rcfile_mutex);
211 pthread_cond_wait (&rcfile_cond, &rcfile_mutex);
212 #ifndef HAVE_PTHREAD_CANCEL
213 int *cancel = (int *) pthread_getspecific (signal_thread_key);
214 if (*cancel)
215 break;
216 #endif
218 keep = config_keep_save ();
219 log_write (_("reloading configuration file '%s'"), rcfile);
221 config = config_parse (rcfile, 1);
222 if (config)
224 config_free (global_config);
225 global_config = config;
226 setup_logging ();
229 config_keep_restore (keep);
230 disable_list_and_dump = !disable_list_and_dump ? b : 1;
232 #ifdef WITH_GNUTLS
233 /* Kill existing listening threads since the configured listening
234 * protocols may have changed. */
235 start_stop_tls (1);
236 start_stop_tls (0);
237 #endif
238 crypto_set_keepalive ();
239 pthread_cleanup_pop (0);
242 MUTEX_UNLOCK (&rcfile_mutex);
243 return NULL;
246 gpg_error_t
247 send_error (assuan_context_t ctx, gpg_error_t e)
249 struct client_s *client = assuan_get_pointer (ctx);
251 if (gpg_err_source (e) == GPG_ERR_SOURCE_UNKNOWN)
252 e = gpg_error (e);
254 if (client)
255 client->last_rc = e;
257 if (!e)
258 return assuan_process_done (ctx, 0);
260 if (!ctx)
262 log_write ("ERR %i: %s", e, pwmd_strerror (e));
263 return e;
266 if (client && client->xml_error)
268 log_write ("%s", client->xml_error->message);
269 xfree (client->last_error);
270 client->last_error = NULL;
271 if (client->xml_error->message)
272 client->last_error = str_dup (client->xml_error->message);
274 e = assuan_process_done (ctx,
275 assuan_set_error (ctx, e,
276 client->xml_error->message ? client->xml_error->message : NULL));
277 xmlResetLastError ();
278 xmlResetError (client->xml_error);
279 xfree (client->xml_error);
280 client->xml_error = NULL;
281 return e;
284 return assuan_process_done (ctx,
285 assuan_set_error (ctx, e, pwmd_strerror (e)));
288 void
289 log_write (const char *fmt, ...)
291 char *args;
292 va_list ap;
293 time_t now;
294 char buf[255];
295 pthread_t tid = pthread_self ();
296 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
298 if ((!logfile && !isatty (STDERR_FILENO) && !log_syslog) || !fmt)
299 return;
301 pthread_mutex_lock (&m);
302 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock, &m);
304 if (!cmdline && logfile && log_fd == -1)
306 log_fd = open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600);
307 if (log_fd == -1)
308 warn ("%s", logfile);
311 va_start (ap, fmt);
313 if (str_vasprintf (&args, fmt, ap) != -1)
315 if (cmdline)
317 pthread_cleanup_push (xfree, args);
318 fprintf (stderr, "pwmd: %s\n", args);
319 fflush (stderr);
320 pthread_cleanup_pop (1);
322 else
324 char *name = pthread_getspecific (thread_name_key);
325 char *line;
327 pthread_cleanup_push (xfree, args);
328 snprintf (buf, sizeof (buf),
329 name && *name == '!' ? "%s: " : name ? "%s(%p): " : "%s",
330 name ? *name == '!' ? name+1 : name : "",
331 name && *name == '!' ? 0 : name ? (pthread_t *) tid : 0);
332 name = buf;
334 if (!cmdline && log_syslog && !nofork)
335 syslog (LOG_INFO, "%s%s", name, args);
337 time (&now);
338 struct tm *tm = localtime (&now);
339 char tbuf[21];
340 strftime (tbuf, sizeof (tbuf), "%b %d %Y %H:%M:%S ", tm);
341 tbuf[sizeof (tbuf) - 1] = 0;
343 if (args[strlen (args) - 1] == '\n')
344 args[strlen (args) - 1] = 0;
346 line = str_asprintf ("%s %i %s%s\n", tbuf, getpid (), name,
347 args);
348 pthread_cleanup_pop (1);
349 if (line)
351 pthread_cleanup_push (xfree, line);
352 if (logfile && log_fd != -1)
354 ssize_t ret = write (log_fd, line, strlen (line));
355 (void)ret;
356 fsync (log_fd);
359 if (nofork)
361 fprintf (stdout, "%s", line);
362 fflush (stdout);
365 pthread_cleanup_pop (1);
370 va_end (ap);
371 pthread_cleanup_pop (0);
373 if (log_fd != -1 && log_keepopen <= 0)
375 close(log_fd);
376 log_fd = -1;
379 pthread_mutex_unlock (&m);
382 static gpg_error_t
383 setup_crypto ()
385 gpg_error_t rc;
387 if (!gpgrt_check_version (REQUIRE_LIBGPGERROR_VERSION))
389 fprintf (stderr, _("gpgrt_check_version(): Incompatible libgpg-error. "
390 "Wanted %s, got %s.\n"), REQUIRE_LIBGPGERROR_VERSION,
391 gpgrt_check_version (NULL));
392 return GPG_ERR_UNKNOWN_VERSION;
395 gpgrt_init ();
396 gpgrt_set_alloc_func (xrealloc_gpgrt);
398 if (!assuan_check_version (REQUIRE_LIBASSUAN_VERSION))
400 fprintf (stderr, _("assuan_check_version(): Incompatible libassuan. "
401 "Wanted %s, got %s.\n"), REQUIRE_LIBASSUAN_VERSION,
402 assuan_check_version (NULL));
403 return GPG_ERR_UNKNOWN_VERSION;
406 if (!gcry_check_version (REQUIRE_LIBGCRYPT_VERSION))
408 fprintf (stderr, _("gcry_check_version(): Incompatible libgcrypt. "
409 "Wanted %s, got %s.\n"), REQUIRE_LIBGCRYPT_VERSION,
410 gcry_check_version (NULL));
411 return GPG_ERR_UNKNOWN_VERSION;
414 gcry_set_allocation_handler (xmalloc, xmalloc, NULL, xrealloc, xfree);
416 if (!gpgme_check_version (REQUIRE_LIBGPGME_VERSION))
418 fprintf (stderr, _("gpgme_check_version(): Incompatible libgpgme. "
419 "Wanted %s, got %s.\n"), REQUIRE_LIBGPGME_VERSION,
420 gpgme_check_version (NULL));
421 return GPG_ERR_UNKNOWN_VERSION;
424 rc = gpgme_engine_check_version (GPGME_PROTOCOL_OPENPGP);
425 if (rc)
427 fprintf (stderr, _("gpgme_engine_check_version(GPGME_PROTOCOL_OPENPGP): %s"), gpgme_strerror (rc));
428 return GPG_ERR_UNKNOWN_VERSION;
431 //gpgme_set_global_flag ("require-gnupg", REQUIRE_GNUPG_VERSION);
432 #ifdef ENABLE_NLS
433 gpgme_set_locale (NULL, LC_CTYPE, setlocale (LC_CTYPE, NULL));
434 gpgme_set_locale (NULL, LC_MESSAGES, setlocale (LC_MESSAGES, NULL));
435 #endif
437 #ifdef WITH_GNUTLS
438 if (gnutls_global_init ())
440 fprintf(stderr, _("gnutls_global_init() failed.\n"));
441 return GPG_ERR_UNKNOWN_VERSION;
444 gnutls_global_set_log_function (tls_log);
445 gnutls_global_set_audit_log_function (tls_audit_log);
446 #endif
447 return 0;
450 gpg_error_t
451 do_validate_peer (assuan_context_t ctx, const char *section,
452 assuan_peercred_t * peer)
454 char **users;
455 int allowed = 0;
456 gpg_error_t rc;
457 struct client_s *client = assuan_get_pointer (ctx);
459 if (!client)
460 return GPG_ERR_FORBIDDEN;
462 #ifdef WITH_GNUTLS
463 if (client->thd->remote)
464 return tls_validate_access (client, section);
465 #endif
467 rc = assuan_get_peercred (ctx, peer);
468 if (rc)
469 return rc;
471 users = config_get_list (section, "allowed");
472 if (users)
474 for (char **p = users; !rc && *p; p++)
476 rc = acl_check_common(client, *p, (*peer)->uid, (*peer)->gid,
477 &allowed);
480 strv_free (users);
482 else if (client->no_access_param)
483 allowed = 1;
485 return allowed && !rc ? 0 : rc ? rc : GPG_ERR_FORBIDDEN;
488 /* Test if uid is a member of group 'name'. Invert when 'not' is true. */
489 #ifdef HAVE_GETGRNAM_R
490 static gpg_error_t
491 acl_check_group (const char *name, uid_t uid, gid_t gid, int not, int *allowed)
493 char *buf;
494 struct group gr, *gresult;
495 size_t len = sysconf (_SC_GETGR_R_SIZE_MAX);
496 int err;
497 gpg_error_t rc = 0;
499 if (len == -1)
500 len = 16384;
502 buf = xmalloc (len);
503 if (!buf)
504 return GPG_ERR_ENOMEM;
506 err = getgrnam_r (name, &gr, buf, len, &gresult);
507 if (!err && gresult)
509 if (gresult->gr_gid == gid)
511 xfree (buf);
512 *allowed = !not;
513 return 0;
516 for (char **t = gresult->gr_mem; !rc && *t; t++)
518 char *tbuf;
519 struct passwd pw;
520 struct passwd *result = get_pwd_struct (*t, 0, &pw, &tbuf, &rc);
522 if (!rc && result && result->pw_uid == uid)
524 xfree (tbuf);
525 *allowed = !not;
526 break;
529 xfree (tbuf);
532 xfree (buf);
533 return rc;
535 else if (err)
536 rc = gpg_error_from_errno (err);
538 xfree (buf);
539 return rc ? rc : !gresult ? 0 : GPG_ERR_EACCES;
541 #else
542 static gpg_error_t
543 acl_check_group (const char *name, uid_t uid, gid_t gid, int not, int *allowed)
545 struct group *gresult;
546 gpg_error_t rc = 0;
548 errno = 0;
549 gresult = getgrnam (name);
550 if (!errno && gresult && gresult->gr_gid == gid)
552 *allowed = !not;
553 return 0;
555 else if (errno)
556 rc = gpg_error_from_syserror ();
557 else if (!gresult)
558 return 0;
560 for (char **t = gresult->gr_mem; !rc && *t; t++)
562 char *buf;
563 struct passwd pw;
564 struct passwd *result = get_pwd_struct (*t, 0, &pw, &buf, &rc);
566 if (!rc && result && result->pw_uid == uid)
568 xfree (buf);
569 *allowed = !not;
570 break;
573 xfree (buf);
576 return rc;
578 #endif
580 gpg_error_t
581 peer_is_invoker(struct client_s *client)
583 struct invoking_user_s *user;
584 int allowed = 0;
586 if (client->thd->state == CLIENT_STATE_UNKNOWN)
587 return GPG_ERR_EACCES;
589 for (user = invoking_users; user; user = user->next)
591 #ifdef WITH_GNUTLS
592 if (client->thd->remote)
594 if (user->type == INVOKING_TLS
595 && !strcmp(client->thd->tls->fp, user->id))
596 allowed = user->not ? 0 : 1;
598 continue;
600 #endif
602 if (user->type == INVOKING_GID)
604 gpg_error_t rc = acl_check_group (user->id,
605 client->thd->peer->uid,
606 client->thd->peer->gid,
607 user->not, &allowed);
608 if (rc)
609 return rc;
611 else if (user->type == INVOKING_UID && client->thd->peer->uid == user->uid)
612 allowed = user->not ? 0 : 1;
615 return allowed ? 0 : GPG_ERR_EACCES;
618 #ifdef HAVE_GETGRNAM_R
619 gpg_error_t
620 acl_check_common (struct client_s *client, const char *user, uid_t uid,
621 gid_t gid, int *allowed)
623 int not = 0;
624 int rw = 0;
625 int tls = 0;
626 gpg_error_t rc = 0;
628 if (!user || !*user)
629 return 0;
631 if (*user == '-' || *user == '!')
632 not = 1;
634 if (*user == '+') // not implemented yet
635 rw = 1;
637 if (*user == '#') // TLS fingerprint hash
638 tls = 1;
640 if (not || rw || tls)
641 user++;
643 if (tls)
645 #ifdef WITH_GNUTLS
646 if (client->thd->remote)
648 if (!strcasecmp (client->thd->tls->fp, user))
649 *allowed = !not;
652 return 0;
653 #else
654 return 0;
655 #endif
657 #ifdef WITH_GNUTLS
658 else if (client->thd->remote) // Remote client with no FP in the ACL
659 return 0;
660 #endif
662 if (*user == '@') // all users in group
663 return acl_check_group (user+1, uid, gid, not, allowed);
664 else
666 char *buf;
667 struct passwd pw;
668 struct passwd *pwd = get_pwd_struct (user, 0, &pw, &buf, &rc);
670 if (!rc && pwd && pwd->pw_uid == uid)
671 *allowed = !not;
673 xfree (buf);
676 return rc;
678 #else
679 gpg_error_t
680 acl_check_common (struct client_s *client, const char *user, uid_t uid,
681 gid_t gid, int *allowed)
683 gpg_error_t rc = 0;
684 int not = 0;
685 int rw = 0;
686 int tls = 0;
688 if (!user || !*user)
689 return 0;
691 if (*user == '-' || *user == '!')
692 not = 1;
694 if (*user == '+') // not implemented yet
695 rw = 1;
697 if (*user == '#') // TLS fingerprint hash
698 tls = 1;
700 if (not || rw || tls)
701 user++;
703 if (tls)
705 #ifdef WITH_GNUTLS
706 if (client->thd->remote)
708 if (!strcasecmp (client->thd->tls->fp, user))
709 *allowed = !not;
712 return 0;
713 #else
714 return 0;
715 #endif
718 if (*user == '@') // all users in group
719 return acl_check_group (user+1, uid, gid, not, allowed);
720 else
722 char *buf;
723 struct passwd pw;
724 struct passwd *result = get_pwd_struct (user, 0, &pw, &buf, &rc);
726 if (!rc && result && result->pw_uid == uid)
727 *allowed = !not;
729 xfree (buf);
732 return rc;
734 #endif
736 static gpg_error_t
737 validate_peer (struct client_s *cl)
739 gpg_error_t rc;
741 #ifdef WITH_GNUTLS
742 if (cl->thd->remote)
743 return tls_validate_access (cl, NULL);
744 #endif
746 MUTEX_LOCK (&cn_mutex);
747 rc = do_validate_peer (cl->ctx, "global", &cl->thd->peer);
748 MUTEX_UNLOCK (&cn_mutex);
749 log_write ("peer %s: uid=%i, gid=%i, pid=%i, rc=%u",
750 !rc ? _("accepted") : _("rejected"), cl->thd->peer->uid,
751 cl->thd->peer->gid, cl->thd->peer->pid, rc);
752 return rc;
755 static void
756 xml_error_cb (void *data, xmlErrorPtr e)
758 struct client_s *client = data;
761 * Keep the first reported error as the one to show in the error
762 * description. Reset in send_error().
764 if (client->xml_error)
765 return;
767 client->xml_error = xcalloc (1, sizeof(xmlError));
768 xmlCopyError (e, client->xml_error);
771 static pid_t
772 hook_waitpid (assuan_context_t ctx, pid_t pid, int action,
773 int *status, int options)
775 return waitpid (pid, status, options);
778 static ssize_t
779 hook_read (assuan_context_t ctx, assuan_fd_t fd, void *data, size_t len)
781 #ifdef WITH_GNUTLS
782 struct client_s *client = assuan_get_pointer (ctx);
784 if (client->thd->remote)
785 return tls_read_hook (ctx, (int) fd, data, len);
786 #endif
788 return read ((int) fd, data, len);
791 static ssize_t
792 hook_write (assuan_context_t ctx, assuan_fd_t fd,
793 const void *data, size_t len)
795 #ifdef WITH_GNUTLS
796 struct client_s *client = assuan_get_pointer (ctx);
798 if (client->thd->remote)
799 return tls_write_hook (ctx, (int) fd, data, len);
800 #endif
802 return write ((int) fd, data, len);
806 assuan_log_cb (assuan_context_t ctx, void *data, unsigned cat,
807 const char *msg)
809 struct client_s *client = data;
810 char *str = NULL;
812 (void)client;
814 if (!(assuan_level & cat))
815 return 0;
817 if (!msg)
818 return 1;
820 switch (cat)
822 case ASSUAN_LOG_INIT:
823 str = "ASSUAN[INIT]";
824 break;
825 case ASSUAN_LOG_CTX:
826 str = "ASSUAN[CTX]";
827 break;
828 case ASSUAN_LOG_ENGINE:
829 str = "ASSUAN[ENGINE]";
830 break;
831 case ASSUAN_LOG_DATA:
832 str = "ASSUAN[DATA]";
833 break;
834 case ASSUAN_LOG_SYSIO:
835 str = "ASSUAN[SYSIO]";
836 break;
837 case ASSUAN_LOG_CONTROL:
838 str = "ASSUAN[CONTROL]";
839 break;
840 default:
841 str = "ASSUAN[UNKNOWN]";
842 break;
845 log_write ("%s: %s", str, msg);
846 return 1;
849 static int
850 new_connection (struct client_s *cl)
852 gpg_error_t rc;
853 static struct assuan_malloc_hooks mhooks = { xmalloc, xrealloc, xfree };
854 static struct assuan_system_hooks shooks = {
855 ASSUAN_SYSTEM_HOOKS_VERSION,
856 __assuan_usleep,
857 __assuan_pipe,
858 __assuan_close,
859 hook_read,
860 hook_write,
861 //FIXME
862 NULL, //recvmsg
863 NULL, //sendmsg both are used for FD passing
864 __assuan_spawn,
865 hook_waitpid,
866 __assuan_socketpair,
867 __assuan_socket,
868 __assuan_connect
871 #ifdef WITH_GNUTLS
872 if (cl->thd->remote)
874 char *prio = config_get_string ("global", "tls_cipher_suite");
876 cl->thd->timeout = config_get_integer ("global", "tls_timeout");
877 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
878 return 0;
880 cl->thd->tls = tls_init (cl->thd->fd, cl->thd->timeout, prio);
881 xfree (prio);
882 if (!cl->thd->tls)
883 return 0;
885 #endif
887 rc = assuan_new_ext (&cl->ctx, GPG_ERR_SOURCE_DEFAULT, &mhooks,
888 assuan_log_cb, cl);
889 if (rc)
890 goto fail;
892 assuan_ctx_set_system_hooks (cl->ctx, &shooks);
893 rc = assuan_init_socket_server (cl->ctx, cl->thd->fd, 2);
894 if (rc)
895 goto fail;
897 assuan_set_pointer (cl->ctx, cl);
898 assuan_set_hello_line (cl->ctx, PACKAGE_STRING);
899 rc = register_commands (cl->ctx);
900 if (rc)
901 goto fail;
903 rc = assuan_accept (cl->ctx);
904 if (rc)
905 goto fail;
907 rc = validate_peer (cl);
908 /* May not be implemented on all platforms. */
909 if (rc && gpg_err_code (rc) != GPG_ERR_ASS_GENERAL)
910 goto fail;
912 MUTEX_LOCK (&cn_mutex);
913 cl->thd->state = CLIENT_STATE_INIT;
914 MUTEX_UNLOCK (&cn_mutex);
915 cl->lock_timeout = config_get_integer ("global", "lock_timeout");
916 xmlSetStructuredErrorFunc (cl, xml_error_cb);
917 return 1;
919 fail:
920 log_write ("%s", pwmd_strerror (rc));
921 return 0;
925 * This is called after a client_thread() terminates. Set with
926 * pthread_cleanup_push().
928 static void
929 cleanup_cb (void *arg)
931 struct client_thread_s *cn = arg;
932 struct client_s *cl = cn->cl;
934 MUTEX_LOCK (&cn_mutex);
935 cn_thread_list = slist_remove (cn_thread_list, cn);
936 MUTEX_UNLOCK (&cn_mutex);
938 if (cl)
940 unlock_flock (&cl->flock_fd);
941 cleanup_client (cl);
942 if (cl->xml_error)
943 xmlResetError (cl->xml_error);
945 xfree (cl->xml_error);
947 #ifdef WITH_GNUTLS
948 if (cn->tls)
950 gnutls_deinit (cn->tls->ses);
951 xfree (cn->tls->fp);
952 xfree (cn->tls);
954 #endif
956 if (!cn->atfork && cl->ctx)
957 assuan_release (cl->ctx);
958 else if (!cn->atfork && cl->thd && cl->thd->fd != -1)
959 close (cl->thd->fd);
961 if (cl->crypto)
962 crypto_free (cl->crypto);
964 cl->crypto = NULL;
965 xfree (cl);
967 else
969 if (cn->fd != -1)
970 close (cn->fd);
973 while (cn->msg_queue)
975 struct status_msg_s *msg = cn->msg_queue;
977 cn->msg_queue = msg->next;
978 xfree (msg->line);
979 xfree (msg);
982 if (!cn->atfork && cn->status_msg_pipe[0] != -1)
983 close (cn->status_msg_pipe[0]);
985 if (!cn->atfork && cn->status_msg_pipe[1] != -1)
986 close (cn->status_msg_pipe[1]);
988 pthread_mutex_destroy (&cn->status_mutex);
990 if (!cn->atfork)
992 log_write (_("exiting, fd=%i"), cn->fd);
993 send_status_all (STATUS_CLIENTS, NULL);
996 xfree (cn->name);
997 #ifdef WITH_GNUTLS
998 xfree (cn->peeraddr);
999 #endif
1000 xfree (cn);
1001 pthread_cond_signal (&quit_cond);
1004 void
1005 cleanup_all_clients (int atfork)
1007 /* This function may be called from pthread_atfork() which requires
1008 reinitialization. */
1009 if (atfork)
1011 pthread_mutexattr_t attr;
1013 pthread_mutexattr_init (&attr);
1014 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
1015 pthread_mutex_init (&cn_mutex, &attr);
1016 pthread_mutexattr_destroy (&attr);
1017 cache_mutex_init ();
1020 MUTEX_LOCK (&cn_mutex);
1022 while (slist_length (cn_thread_list))
1024 struct client_thread_s *thd = slist_nth_data (cn_thread_list, 0);
1026 thd->atfork = atfork;
1027 cleanup_cb (thd);
1030 exiting = 1;
1031 MUTEX_UNLOCK (&cn_mutex);
1032 cache_deinit (atfork);
1035 static gpg_error_t
1036 send_msg_queue (struct client_thread_s *thd)
1038 MUTEX_LOCK (&thd->status_mutex);
1039 gpg_error_t rc = 0;
1040 char c;
1041 ssize_t ret;
1043 ret = read (thd->status_msg_pipe[0], &c, 1);
1044 rc = gpg_error_from_syserror ();
1045 if (ret == -1 && gpg_err_code (rc) != GPG_ERR_EAGAIN)
1046 log_write ("%s (%i): %s", __FUNCTION__, __LINE__, pwmd_strerror (rc));
1047 else
1048 rc = 0;
1050 thd->wrote_status = 0;
1052 while (thd->msg_queue)
1054 struct status_msg_s *msg = thd->msg_queue;
1056 #ifndef HAVE_PTHREAD_CANCEL
1057 if (thd->fd == -1)
1058 break;
1059 #endif
1061 thd->msg_queue = thd->msg_queue->next;
1062 MUTEX_UNLOCK (&thd->status_mutex);
1063 rc = send_status (thd->cl->ctx, msg->s, msg->line);
1064 MUTEX_LOCK (&thd->status_mutex);
1065 xfree (msg->line);
1066 xfree (msg);
1068 if (rc)
1069 break;
1072 MUTEX_UNLOCK (&thd->status_mutex);
1073 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1074 log_write ("%s (%i): %s", __FUNCTION__, __LINE__, pwmd_strerror (rc));
1076 return rc;
1079 static void *
1080 client_thread (void *data)
1082 struct client_thread_s *thd = data;
1083 struct client_s *cl = xcalloc (1, sizeof (struct client_s));
1085 #ifdef HAVE_PR_SET_NAME
1086 prctl (PR_SET_NAME, "client");
1087 #endif
1088 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1090 if (!cl)
1092 log_write ("%s(%i): %s", __FILE__, __LINE__,
1093 pwmd_strerror (GPG_ERR_ENOMEM));
1094 return NULL;
1097 MUTEX_LOCK (&cn_mutex);
1098 pthread_cleanup_push (cleanup_cb, thd);
1099 thd->cl = cl;
1100 cl->thd = thd;
1101 cl->flock_fd = -1;
1102 MUTEX_UNLOCK (&cn_mutex);
1104 if (new_connection (cl))
1106 int finished = 0;
1107 gpg_error_t rc;
1108 struct pollfd fds[2];
1110 fds[0].fd = thd->fd;
1111 fds[0].events = POLLIN;
1112 fds[1].fd = thd->status_msg_pipe[0];
1113 fds[1].events = POLLIN;
1115 send_status_all (STATUS_CLIENTS, NULL);
1116 rc = send_status (cl->ctx, STATUS_CACHE, NULL);
1117 if (rc)
1119 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
1120 finished = 1;
1123 while (!finished)
1125 int n;
1126 int eof;
1128 n = poll (fds, 2, -1);
1129 if (n == -1)
1131 log_write ("%s", strerror (errno));
1132 break;
1135 if (fds[1].revents & POLLIN)
1137 rc = send_msg_queue (thd);
1138 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1139 break;
1142 #ifdef HAVE_PTHREAD_CANCEL
1143 if (!(fds[0].revents & POLLIN))
1144 #else
1145 if (thd->fd != -1 && !(fds[0].revents & POLLIN))
1146 #endif
1147 continue;
1149 rc = assuan_process_next (cl->ctx, &eof);
1150 if (rc || eof)
1152 if (gpg_err_code (rc) == GPG_ERR_EOF || eof)
1153 break;
1155 log_write ("assuan_process_next(): rc=%u %s", rc,
1156 pwmd_strerror (rc));
1157 if (rc == gpg_error (GPG_ERR_ETIMEDOUT))
1158 break;
1160 rc = send_error (cl->ctx, rc);
1161 if (rc)
1163 log_write ("assuan_process_done(): rc=%u %s", rc,
1164 pwmd_strerror (rc));
1165 break;
1169 /* Since the msg queue pipe fd's are non-blocking, check for
1170 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1171 * client has already disconnected and will be converted to
1172 * GPG_ERR_EOF during assuan_process_next().
1174 rc = send_msg_queue (thd);
1175 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1176 break;
1180 /* Don't do pthread_exit() here because any set pthread_cleanup_push
1181 * functions would be called after a command failed but then the client
1182 * exited normally which may lead to a double free. */
1183 pthread_cleanup_pop (1);
1184 return NULL;
1187 static gpg_error_t
1188 xml_import (const char *filename, const char *outfile, char **keyid,
1189 char **sign_keyid, char *keyfile, const char *keyparam,
1190 int symmetric)
1192 xmlDocPtr doc;
1193 int fd;
1194 struct stat st;
1195 int len;
1196 xmlChar *xmlbuf;
1197 gpg_error_t rc = 0;
1198 struct crypto_s *crypto = NULL;
1200 if (stat (filename, &st) == -1)
1202 rc = gpg_error_from_errno (errno);
1203 return rc;
1206 fd = open (filename, O_RDONLY);
1207 if (fd == -1)
1208 return gpg_error_from_errno (errno);
1210 xmlbuf = xmalloc (st.st_size + 1);
1211 if (!xmlbuf)
1213 close (fd);
1214 return GPG_ERR_ENOMEM;
1217 if (read (fd, xmlbuf, st.st_size) == -1)
1219 rc = gpg_error_from_errno (errno);
1220 close (fd);
1221 xfree (xmlbuf);
1222 return rc;
1225 close (fd);
1226 xmlbuf[st.st_size] = 0;
1227 // Be sure the document validates.
1228 doc = xmlReadDoc (xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS);
1229 xfree (xmlbuf);
1230 if (!doc)
1231 return GPG_ERR_BAD_DATA;
1233 xmlNodePtr n = xmlDocGetRootElement (doc);
1234 if (n && !xmlStrEqual (n->name, (xmlChar *) "pwmd"))
1235 rc = GPG_ERR_BAD_DATA;
1237 if (!rc)
1239 rc = xml_validate_import (NULL, n ? n->children : n);
1240 if (!rc)
1242 rc = crypto_init (&crypto, NULL, filename, keyfile != NULL, keyfile);
1243 if (!rc)
1245 if (keyfile)
1247 crypto->flags |= CRYPTO_FLAG_KEYFILE;
1248 crypto->keyfile = str_dup (keyfile);
1251 xmlDocDumpMemory (doc, &crypto->plaintext, &len);
1252 if (len > 0)
1253 crypto->plaintext_size = len;
1254 else
1255 rc = GPG_ERR_ENOMEM;
1260 if (!rc)
1262 if (!symmetric && (keyparam || !keyid))
1264 char *buf = NULL;
1266 if (keyparam)
1268 fd = open (keyparam, O_RDONLY);
1269 if (fd == -1)
1270 rc = gpg_error_from_errno (errno);
1272 if (!rc)
1274 if (stat (keyparam, &st) == -1)
1275 rc = gpg_error_from_errno (errno);
1277 if (!rc)
1279 buf = xmalloc (st.st_size+1);
1280 if (!buf)
1281 rc = GPG_ERR_ENOMEM;
1283 if (!rc)
1285 len = read (fd, buf, st.st_size);
1286 if (len != st.st_size)
1287 rc = gpg_error_from_errno (errno);
1289 if (!rc)
1290 buf[len] = 0;
1295 if (fd != -1)
1296 close (fd);
1298 else
1300 buf = crypto_default_key_params ();
1301 if (!buf)
1302 rc = GPG_ERR_ENOMEM;
1305 if (!rc)
1306 rc = crypto_genkey (NULL, crypto, (unsigned char *)buf);
1308 xfree (buf);
1310 else
1312 crypto->save.pubkey = strv_dup (keyid);
1313 crypto->save.sigkey = strv_dup (sign_keyid);
1316 if (!rc)
1318 crypto->flags |= symmetric ? CRYPTO_FLAG_SYMMETRIC : 0;
1319 rc = crypto_encrypt (NULL, crypto);
1323 if (!rc)
1325 if (!strcmp (outfile, "-"))
1326 outfile = NULL;
1328 xfree (crypto->plaintext);
1329 crypto->plaintext = NULL;
1330 xfree (crypto->filename);
1331 crypto->filename = outfile ? str_dup (outfile) : NULL;
1332 rc = crypto_write_file (crypto);
1335 xmlFreeDoc (doc);
1336 crypto_free (crypto);
1337 return rc;
1340 static gpg_error_t
1341 do_cache_push (struct crypto_s *crypto)
1343 gpg_error_t rc;
1344 xmlDocPtr doc;
1345 struct cache_data_s *cdata;
1346 unsigned char *crc;
1347 size_t len;
1348 int fd = -1;
1350 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1351 crypto->filename);
1353 if (valid_filename (crypto->filename) == 0)
1355 log_write (_("%s: Invalid characters in filename"), crypto->filename);
1356 return GPG_ERR_INV_VALUE;
1359 rc = lock_flock (NULL, crypto->filename, LOCK_SH, &fd);
1360 if (!rc)
1361 rc = crypto_decrypt (NULL, crypto);
1362 if (rc)
1364 unlock_flock (&fd);
1365 return rc;
1368 rc = xml_parse_doc ((char *) crypto->plaintext, crypto->plaintext_size, &doc);
1369 if (rc)
1371 unlock_flock (&fd);
1372 log_write ("%s", pwmd_strerror (rc));
1373 return rc;
1376 cdata = xcalloc (1, sizeof (struct cache_data_s));
1377 if (!cdata)
1379 unlock_flock (&fd);
1380 xmlFreeDoc (doc);
1381 return GPG_ERR_ENOMEM;
1384 rc = get_checksum (crypto->filename, &crc, &len);
1385 unlock_flock (&fd);
1386 if (rc)
1388 xmlFreeDoc (doc);
1389 free_cache_data_once (cdata);
1390 return rc;
1393 cdata->crc = crc;
1394 rc = cache_encrypt (crypto);
1395 if (!rc)
1397 cdata->doc = crypto->plaintext;
1398 cdata->size = crypto->plaintext_size;
1399 crypto->plaintext = NULL;
1400 cdata->pubkey = crypto->pubkey;
1401 cdata->sigkey = crypto->sigkey;
1402 crypto->pubkey = NULL;
1403 crypto->sigkey = NULL;
1405 else
1407 xmlFreeDoc (doc);
1408 free_cache_data_once (cdata);
1409 return rc;
1412 int timeout = config_get_integer (crypto->filename, "cache_timeout");
1413 rc = cache_add_file (crypto->filename, cdata, timeout);
1414 return rc;
1417 static gpg_error_t
1418 init_client (int fd, const char *addr)
1420 gpg_error_t rc = 0;
1421 struct client_thread_s *new = xcalloc (1, sizeof (struct client_thread_s));
1423 if (!new)
1425 close (fd);
1426 return GPG_ERR_ENOMEM;
1429 MUTEX_LOCK (&cn_mutex);
1430 new->conntime = time (NULL);
1431 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
1433 if (pipe (new->status_msg_pipe) == -1)
1434 rc = gpg_error_from_errno (errno);
1436 if (!rc)
1438 if (fcntl (new->status_msg_pipe[0], F_SETFL, O_NONBLOCK) == -1)
1439 rc = gpg_error_from_errno (errno);
1441 if (!rc)
1442 if (fcntl (new->status_msg_pipe[1], F_SETFL, O_NONBLOCK) == -1)
1443 rc = gpg_error_from_errno (errno);
1445 pthread_mutex_init (&new->status_mutex, NULL);
1448 if (!rc)
1450 #ifdef WITH_GNUTLS
1451 new->remote = addr ? 1 : 0;
1452 #endif
1453 new->fd = fd;
1454 rc = create_thread (client_thread, new, &new->tid, 1);
1455 if (rc)
1457 close (new->status_msg_pipe[0]);
1458 close (new->status_msg_pipe[1]);
1459 pthread_mutex_destroy (&new->status_mutex);
1463 if (!rc)
1465 struct slist_s *list = slist_append (cn_thread_list, new);
1467 if (list)
1469 cn_thread_list = list;
1470 if (addr)
1472 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1473 (pthread_t *) new->tid, fd, addr);
1474 #ifdef WITH_GNUTLS
1475 new->peeraddr = str_dup (addr);
1476 #endif
1478 else
1479 log_write (_("new connection: tid=%p, fd=%i"),
1480 (pthread_t *) new->tid, fd);
1482 else
1483 rc = GPG_ERR_ENOMEM;
1486 pthread_cleanup_pop (1);
1488 if (rc)
1490 xfree (new);
1491 close (fd);
1492 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1493 pwmd_strerror (rc));
1495 return rc;
1498 static void*
1499 keepalive_thread (void *arg)
1501 #ifndef HAVE_PTHREAD_CANCEL
1502 int *n = xmalloc (sizeof (int));
1504 *n = 0;
1505 pthread_setspecific (signal_thread_key, n);
1506 INIT_THREAD_SIGNAL;
1507 #endif
1509 #ifdef HAVE_PR_SET_NAME
1510 prctl (PR_SET_NAME, "keepalive");
1511 #endif
1512 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
1514 for (;;)
1516 int n = config_get_integer ("global", "keepalive_interval");
1517 struct timeval tv = { n, 0 };
1518 #ifndef HAVE_PTHREAD_CANCEL
1519 int *sigusr2;
1521 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1522 if (*sigusr2)
1523 break;
1524 #endif
1526 send_status_all (STATUS_KEEPALIVE, NULL);
1527 select (0, NULL, NULL, NULL, &tv);
1530 return NULL;
1533 #ifdef WITH_GNUTLS
1534 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1535 static void *
1536 get_in_addr (struct sockaddr *sa)
1538 if (sa->sa_family == AF_INET)
1539 return &(((struct sockaddr_in *) sa)->sin_addr);
1541 return &(((struct sockaddr_in6 *) sa)->sin6_addr);
1544 static void *
1545 tcp_accept_thread (void *arg)
1547 int sockfd = *(int *) arg;
1548 time_t init;
1549 gpg_error_t rc;
1550 int regen_interval = config_get_integer ("global", "tls_regen_interval");
1551 char *tmp = config_get_string ("global", "tls_dh_level");
1552 #ifndef HAVE_PTHREAD_CANCEL
1553 int *n = xmalloc (sizeof (int));
1555 *n = 0;
1556 pthread_setspecific (signal_thread_key, n);
1557 INIT_THREAD_SIGNAL;
1558 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1559 #endif
1561 #ifdef HAVE_PR_SET_NAME
1562 prctl (PR_SET_NAME, "tcp_accept");
1563 #endif
1564 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
1565 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1567 rc = tls_init_params (tmp);
1568 xfree (tmp);
1569 if (rc)
1570 init = 0;
1571 else
1572 init = time (NULL);
1574 for (;;)
1576 struct sockaddr_storage raddr;
1577 socklen_t slen = sizeof (raddr);
1578 int fd;
1579 unsigned long n;
1580 char s[INET6_ADDRSTRLEN];
1581 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1582 #ifndef HAVE_PTHREAD_CANCEL
1583 int *sigusr2;
1585 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1586 if (*sigusr2)
1587 break;
1588 #endif
1590 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1591 if (init == 0 || fd == -1)
1593 if ((init == 0 && (errno == EAGAIN || errno == EWOULDBLOCK))
1594 || (errno == EAGAIN || errno == EWOULDBLOCK))
1596 if (regen_interval > 0
1597 && (init == 0 || time (NULL) - init >= regen_interval))
1599 int i;
1600 int remote_client = 0;
1602 MUTEX_LOCK(&cn_mutex);
1603 for (i = 0; i < slist_length (cn_thread_list); i++)
1605 struct client_thread_s *thd =
1606 slist_nth_data (cn_thread_list, i);
1608 if (thd->remote)
1610 remote_client = 1;
1611 break;
1614 MUTEX_UNLOCK(&cn_mutex);
1616 if (!remote_client)
1618 char *tmp = config_get_string ("global", "tls_dh_level");
1619 gpg_error_t rc;
1621 rc = tls_init_params (tmp);
1622 xfree (tmp);
1623 if (!rc)
1624 init = time (NULL);
1625 else
1627 tv.tv_sec = 10;
1628 tv.tv_usec = 0;
1630 if (fd != -1)
1632 close (fd);
1633 fd = -1;
1637 else
1638 init = 0;
1641 if (fd == -1)
1643 select (0, NULL, NULL, NULL, &tv);
1644 continue;
1648 if (errno == EMFILE || errno == ENFILE)
1649 log_write ("accept(): %s",
1650 pwmd_strerror (gpg_error_from_errno (errno)));
1651 else if (errno != EAGAIN)
1653 if (!quit) // probably EBADF
1654 log_write ("accept(): %s", strerror (errno));
1656 break;
1659 #ifndef HAVE_PTHREAD_CANCEL
1660 select (0, NULL, NULL, NULL, &tv);
1661 #endif
1662 continue;
1665 if (quit)
1667 close (fd);
1668 break;
1671 inet_ntop (raddr.ss_family, get_in_addr ((struct sockaddr *) &raddr),
1672 s, sizeof s);
1673 (void) init_client (fd, s);
1674 n = config_get_integer ("global", "tcp_wait");
1675 if (n > 0)
1677 tv.tv_sec = (n * 100000) / 100000;
1678 tv.tv_usec = (n * 100000) % 100000;
1679 select (0, NULL, NULL, NULL, &tv);
1683 return NULL;
1686 static int
1687 start_stop_tls_with_protocol (int ipv6, int term)
1689 struct addrinfo hints, *servinfo, *p;
1690 int port = config_get_integer ("global", "tcp_port");
1691 char buf[7];
1692 int n;
1693 gpg_error_t rc;
1694 int *fd = ipv6 ? &tls6_fd : &tls_fd;
1696 if (term || config_get_boolean ("global", "enable_tcp") == 0)
1698 if (tls6_fd != -1)
1700 if (spawned_tls6)
1702 #ifdef HAVE_PTHREAD_CANCEL
1703 pthread_cancel (tls6_tid);
1704 #else
1705 pthread_kill (tls6_tid, SIGUSR2);
1706 #endif
1707 pthread_join (tls6_tid, NULL);
1710 shutdown (tls6_fd, SHUT_RDWR);
1711 close (tls6_fd);
1712 tls6_fd = -1;
1713 spawned_tls6 = 0;
1716 if (tls_fd != -1)
1718 if (spawned_tls)
1720 #ifdef HAVE_PTHREAD_CANCEL
1721 pthread_cancel (tls_tid);
1722 #else
1723 pthread_kill (tls_tid, SIGUSR2);
1724 #endif
1725 pthread_join (tls_tid, NULL);
1728 shutdown (tls_fd, SHUT_RDWR);
1729 close (tls_fd);
1730 tls_fd = -1;
1731 spawned_tls = 0;
1734 return 1;
1737 if ((ipv6 && tls6_fd != -1) || (!ipv6 && tls_fd != -1))
1738 return 1;
1740 memset (&hints, 0, sizeof (hints));
1741 hints.ai_family = ipv6 ? AF_INET6 : AF_INET;
1742 hints.ai_socktype = SOCK_STREAM;
1743 hints.ai_flags = AI_PASSIVE;
1744 snprintf (buf, sizeof (buf), "%i", port);
1746 if ((n = getaddrinfo (NULL, buf, &hints, &servinfo)) == -1)
1748 log_write ("getaddrinfo(): %s", gai_strerror (n));
1749 return 0;
1752 for (n = 0, p = servinfo; p != NULL; p = p->ai_next)
1754 int r = 1;
1756 if ((ipv6 && p->ai_family != AF_INET6)
1757 || (!ipv6 && p->ai_family != AF_INET))
1758 continue;
1760 if ((*fd = socket (p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
1762 log_write ("socket(): %s", strerror (errno));
1763 continue;
1766 if (setsockopt (*fd, SOL_SOCKET, SO_REUSEADDR, &r, sizeof (int)) == -1)
1768 log_write ("setsockopt(): %s",
1769 pwmd_strerror (gpg_error_from_errno (errno)));
1770 freeaddrinfo (servinfo);
1771 goto fail;
1774 if (bind (*fd, p->ai_addr, p->ai_addrlen) == -1)
1776 close (*fd);
1777 log_write ("bind(): %s",
1778 pwmd_strerror (gpg_error_from_errno (errno)));
1779 continue;
1782 n++;
1783 break;
1786 freeaddrinfo (servinfo);
1788 if (!n)
1789 goto fail;
1791 #if HAVE_DECL_SO_BINDTODEVICE != 0
1792 char *tmp = config_get_string ("global", "tcp_interface");
1793 if (tmp && setsockopt (*fd, SOL_SOCKET, SO_BINDTODEVICE, tmp,
1794 strlen (tmp)) == -1)
1796 log_write ("setsockopt(): %s",
1797 pwmd_strerror (gpg_error_from_errno (errno)));
1798 xfree (tmp);
1799 goto fail;
1802 xfree (tmp);
1803 #endif
1805 if (listen (*fd, 128) == -1)
1807 log_write ("listen(): %s", strerror (errno));
1808 goto fail;
1811 if (ipv6)
1812 rc = create_thread (tcp_accept_thread, fd, &tls6_tid, 0);
1813 else
1814 rc = create_thread (tcp_accept_thread, fd, &tls_tid, 0);
1816 if (rc)
1818 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1819 pwmd_strerror (rc));
1820 goto fail;
1823 if (ipv6)
1824 spawned_tls6 = 1;
1825 else
1826 spawned_tls = 1;
1828 return 1;
1830 fail:
1831 start_stop_tls_with_protocol (0, 1);
1832 if (tls_fd != -1)
1833 close (tls_fd);
1835 if (tls6_fd != -1)
1836 close (tls6_fd);
1838 tls_fd = -1;
1839 tls6_fd = -1;
1840 return 0;
1843 static int
1844 start_stop_tls (int term)
1846 char *s = config_get_string ("global", "tcp_bind");
1847 int b;
1849 if (!s)
1850 return 0;
1852 if (!strcmp (s, "any"))
1854 b = start_stop_tls_with_protocol (0, term);
1855 if (b)
1856 b = start_stop_tls_with_protocol (1, term);
1858 else if (!strcmp (s, "ipv4"))
1859 b = start_stop_tls_with_protocol (0, term);
1860 else if (!strcmp (s, "ipv6"))
1861 b = start_stop_tls_with_protocol (1, term);
1862 else
1863 b = 0;
1865 xfree (s);
1866 return b;
1868 #endif
1870 static void *
1871 accept_thread (void *arg)
1873 int sockfd = *(int *) arg;
1874 #ifndef HAVE_PTHREAD_CANCEL
1875 int *n = xmalloc (sizeof (int));
1877 *n = 0;
1878 pthread_setspecific (signal_thread_key, n);
1879 INIT_THREAD_SIGNAL;
1880 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1881 #endif
1883 #ifdef HAVE_PR_SET_NAME
1884 prctl (PR_SET_NAME, "accept");
1885 #endif
1886 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
1888 for (;;)
1890 socklen_t slen = sizeof (struct sockaddr_un);
1891 struct sockaddr_un raddr;
1892 int fd;
1893 #ifndef HAVE_PTHREAD_CANCEL
1894 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1895 int *sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1897 if (*sigusr2)
1898 break;
1899 #endif
1901 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1902 if (fd == -1)
1904 if (errno == EMFILE || errno == ENFILE)
1905 log_write ("accept(): %s",
1906 pwmd_strerror (gpg_error_from_errno (errno)));
1907 else if (errno != EAGAIN)
1909 if (!quit) // probably EBADF
1910 log_write ("accept(): %s",
1911 pwmd_strerror (gpg_error_from_errno (errno)));
1913 break;
1916 #ifndef HAVE_PTHREAD_CANCEL
1917 select (0, NULL, NULL, NULL, &tv);
1918 #endif
1919 continue;
1922 (void) init_client (fd, NULL);
1925 /* Just in case accept() failed for some reason other than EBADF */
1926 quit = 1;
1927 return NULL;
1930 static void *
1931 cache_timer_thread (void *arg)
1933 #ifndef HAVE_PTHREAD_CANCEL
1934 int *n = xmalloc (sizeof (int));
1936 *n = 0;
1937 pthread_setspecific (signal_thread_key, n);
1938 INIT_THREAD_SIGNAL;
1939 #endif
1941 #ifdef HAVE_PR_SET_NAME
1942 prctl (PR_SET_NAME, "cache timer");
1943 #endif
1944 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
1946 for (;;)
1948 struct timeval tv = { 1, 0 };
1949 #ifndef HAVE_PTHREAD_CANCEL
1950 int *n;
1952 n = (int *) pthread_getspecific (signal_thread_key);
1953 if (*n)
1954 break;
1955 #endif
1957 select (0, NULL, NULL, NULL, &tv);
1958 cache_adjust_timeout ();
1961 return NULL;
1964 static int
1965 signal_loop (sigset_t sigset)
1967 int done = 0;
1968 int siint = 0;
1972 int sig;
1974 sigwait (&sigset, &sig);
1976 if (sig != SIGQUIT)
1977 log_write (_("caught signal %i (%s)"), sig, strsignal (sig));
1979 switch (sig)
1981 case SIGHUP:
1982 pthread_cond_signal (&rcfile_cond);
1983 break;
1984 case SIGUSR1:
1985 log_write (_("clearing file cache"));
1986 cache_clear (NULL, NULL, 1);
1987 send_status_all (STATUS_CACHE, NULL);
1988 break;
1989 case SIGQUIT:
1990 done = 1;
1991 break;
1992 default:
1993 siint = 1;
1994 done = 1;
1995 break;
1998 while (!done);
2000 return siint;
2003 static void
2004 catchsig (int sig)
2006 log_write (_ ("Caught signal %i (%s). Exiting."), sig, strsignal (sig));
2007 #ifdef HAVE_BACKTRACE
2008 BACKTRACE (__FUNCTION__);
2009 #endif
2010 longjmp (jmp, 1);
2013 static void *
2014 waiting_for_exit (void *arg)
2016 int last = 0;
2017 #ifndef HAVE_PTHREAD_CANCEL
2018 int *n = xmalloc (sizeof (int));
2020 *n = 0;
2021 pthread_setspecific (signal_thread_key, n);
2022 INIT_THREAD_SIGNAL;
2023 #endif
2025 #ifdef HAVE_PR_SET_NAME
2026 prctl (PR_SET_NAME, "exiting");
2027 #endif
2028 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
2029 log_write (_("waiting for all clients to disconnect"));
2030 MUTEX_LOCK (&quit_mutex);
2031 pthread_cleanup_push (cleanup_mutex_cb, &quit_mutex);
2033 for (;;)
2035 struct timespec ts;
2036 int n;
2038 MUTEX_LOCK (&cn_mutex);
2039 n = slist_length (cn_thread_list);
2040 MUTEX_UNLOCK (&cn_mutex);
2041 if (!n)
2042 break;
2044 #ifndef HAVE_PTHREAD_CANCEL
2045 int *s = (int *) pthread_getspecific (signal_thread_key);
2046 if (*s)
2047 break;
2048 #endif
2050 if (last != n)
2052 log_write (_("%i clients remain"), n);
2053 last = n;
2056 INIT_TIMESPEC (SIG_TIMEOUT, ts);
2057 pthread_cond_timedwait (&quit_cond, &quit_mutex, &ts);
2060 kill (getpid (), SIGQUIT);
2061 pthread_cleanup_pop (1);
2062 return NULL;
2065 static int
2066 server_loop (int sockfd, char **socketpath)
2068 pthread_t accept_tid;
2069 pthread_t cache_timeout_tid;
2070 int cancel_timeout_thread = 0, cancel_accept_thread = 0;
2071 int cancel_keepalive_thread = 0;
2072 sigset_t sigset;
2073 int n;
2074 int segv = 0;
2075 gpg_error_t rc;
2077 init_commands ();
2078 sigemptyset (&sigset);
2080 /* Termination */
2081 sigaddset (&sigset, SIGTERM);
2082 sigaddset (&sigset, SIGINT);
2084 /* Clears the file cache. */
2085 sigaddset (&sigset, SIGUSR1);
2087 /* Configuration file reloading. */
2088 sigaddset (&sigset, SIGHUP);
2090 /* For exiting cleanly. */
2091 sigaddset (&sigset, SIGQUIT);
2093 #ifndef HAVE_PTHREAD_CANCEL
2095 The socket, cache and rcfile threads use this signal when
2096 pthread_cancel() is unavailable. Prevent the main thread from
2097 catching this signal from another process.
2099 sigaddset (&sigset, SIGUSR2);
2100 #endif
2102 /* When mem.c cannot find a pointer in the list (double free). */
2103 signal (SIGABRT, catchsig);
2104 sigaddset (&sigset, SIGABRT);
2105 sigprocmask (SIG_BLOCK, &sigset, NULL);
2107 #ifndef HAVE_PTHREAD_CANCEL
2108 /* Remove this signal from the watched signals in signal_loop(). */
2109 sigdelset (&sigset, SIGUSR2);
2110 #endif
2112 /* Can show a backtrace of the stack in the log. */
2113 signal (SIGSEGV, catchsig);
2115 #ifdef WITH_GNUTLS
2116 /* Needs to be done after the fork(). */
2117 if (!start_stop_tls (0))
2119 segv = 1;
2120 goto done;
2122 #endif
2124 pthread_mutex_init (&quit_mutex, NULL);
2125 pthread_cond_init (&quit_cond, NULL);
2126 char *p = get_username (getuid());
2127 log_write (_("%s started for user %s"), PACKAGE_STRING, p);
2128 xfree (p);
2130 #ifdef WITH_GNUTLS
2131 if (config_get_boolean ("global", "enable_tcp"))
2132 log_write (_("Listening on %s and TCP port %i"), *socketpath,
2133 config_get_integer ("global", "tcp_port"));
2134 else
2135 log_write (_("Listening on %s"), *socketpath);
2136 #else
2137 log_write (_("Listening on %s"), *socketpath);
2138 #endif
2140 rc = create_thread (keepalive_thread, NULL, &keepalive_tid, 0);
2141 if (rc)
2143 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2144 pwmd_strerror (rc));
2145 goto done;
2148 cancel_keepalive_thread = 1;
2149 rc = create_thread (reload_rcfile_thread, NULL, &rcfile_tid, 0);
2150 if (rc)
2152 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2153 pwmd_strerror (rc));
2154 goto done;
2157 rc = create_thread (cache_timer_thread, NULL, &cache_timeout_tid, 0);
2158 if (rc)
2160 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2161 pwmd_strerror (rc));
2162 goto done;
2165 cancel_timeout_thread = 1;
2166 rc = create_thread (accept_thread, &sockfd, &accept_tid, 0);
2167 if (rc)
2169 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2170 pwmd_strerror (rc));
2171 goto done;
2174 cancel_accept_thread = 1;
2175 if (!setjmp (jmp))
2176 signal_loop (sigset);
2177 else
2178 segv = 1;
2180 done:
2182 * We're out of the main server loop. This happens when a signal was sent
2183 * to terminate the daemon. We'll wait for all clients to disconnect
2184 * before exiting but exit immediately if another termination signal is
2185 * sent.
2187 if (cancel_accept_thread)
2189 #ifdef HAVE_PTHREAD_CANCEL
2190 int n = pthread_cancel (accept_tid);
2191 #else
2192 int n = pthread_kill (accept_tid, SIGUSR2);
2193 #endif
2194 if (!n)
2195 pthread_join (accept_tid, NULL);
2198 #ifdef WITH_GNUTLS
2199 start_stop_tls (1);
2200 #endif
2201 shutdown (sockfd, SHUT_RDWR);
2202 close (sockfd);
2203 unlink (*socketpath);
2204 xfree (*socketpath);
2205 *socketpath = NULL;
2206 MUTEX_LOCK (&cn_mutex);
2207 n = slist_length (cn_thread_list);
2208 MUTEX_UNLOCK (&cn_mutex);
2210 if (n && !segv)
2212 pthread_t tid;
2214 rc = create_thread (waiting_for_exit, NULL, &tid, 0);
2215 if (!rc)
2217 if (signal_loop (sigset))
2219 log_write (_("Received second termination request. Exiting."));
2220 #ifdef HAVE_PTHREAD_CANCEL
2221 pthread_cancel (tid);
2222 #else
2223 pthread_kill (tid, SIGUSR2);
2224 #endif
2225 pthread_join (tid, NULL);
2228 else
2229 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2230 pwmd_strerror (rc));
2233 if (cancel_timeout_thread)
2235 #ifdef HAVE_PTHREAD_CANCEL
2236 pthread_cancel (cache_timeout_tid);
2237 #else
2238 pthread_kill (cache_timeout_tid, SIGUSR2);
2239 #endif
2240 pthread_join (cache_timeout_tid, NULL);
2243 if (cancel_keepalive_thread)
2245 #ifdef HAVE_PTHREAD_CANCEL
2246 pthread_cancel (keepalive_tid);
2247 #else
2248 pthread_kill (keepalive_tid, SIGUSR2);
2249 #endif
2250 pthread_join (keepalive_tid, NULL);
2253 cleanup_all_clients (0);
2254 #ifdef WITH_GNUTLS
2255 start_stop_tls (1);
2256 #endif
2257 deinit_commands ();
2258 pthread_cond_destroy (&quit_cond);
2259 pthread_mutex_destroy (&quit_mutex);
2260 return segv ? EXIT_FAILURE : EXIT_SUCCESS;;
2263 static void
2264 startup_failure ()
2266 log_write (_
2267 ("Failed to add a file to the cache. Use --force to force startup. Exiting."));
2268 cache_clear (NULL, NULL, 1);
2271 static void
2272 usage (const char *pn, int status)
2274 FILE *fp = status == EXIT_FAILURE ? stderr : stdout;
2276 fprintf (fp, _("Usage: %s [OPTIONS] [file1] [...]\n"
2277 " --debug=[a:..][,g:N][,t:N] enable debugging (a:[ixedsc],g:[1-9],t:[0-N])\n"
2278 " -f, --rcfile=filename load the specfied configuration file\n"
2279 " (~/.pwmd/config)\n"
2280 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2281 " --kill terminate an existing instance of pwmd\n"
2282 " -n, --no-fork run as a foreground process\n"
2283 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2284 " --ignore, --force ignore file errors during startup\n"
2285 " -o, --outfile=filename output file when importing or converting\n"
2286 " -C, --convert=filename convert a version 2 data file to version 3\n"
2287 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2288 " -k, --passphrase-file=file for use when importing or converting\n"
2289 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2290 " converting\n"
2291 " --no-passphrase when importing or converting\n"
2292 " --keyid=keyID[,..] public key to use when encrypting\n"
2293 " --sign-keyid=fpr[,..] fingerprint of the signing key to use\n"
2294 " --symmetric use conventional encryption with optional signer\n"
2295 " --keyparam=filename custom key parameters to use (gpg default)\n"
2296 " --help this help text\n"
2297 " --version show version and compile time features\n"),
2298 pn);
2299 exit (status);
2302 static void
2303 unlink_stale_socket (const char *sock, const char *pidfile)
2305 log_write (_ ("removing stale socket %s"), sock);
2306 unlink (sock);
2307 unlink (pidfile);
2310 static int
2311 test_pidfile (const char *path, const char *sock, char *buf, size_t buflen,
2312 char **pidfile, int create, mode_t mode, int terminate)
2314 pid_t pid;
2315 int fd;
2316 size_t len;
2318 if (!create)
2320 snprintf (buf, buflen, "%s/%s.pid", homedir, sock);
2321 *pidfile = str_dup (buf);
2322 fd = open (buf, O_RDONLY);
2324 else
2325 fd = open (*pidfile, O_CREAT|O_WRONLY|O_TRUNC, mode);
2327 if (fd == -1)
2329 if (!create && errno != ENOENT)
2331 log_write ("%s: %s", buf, pwmd_strerror (errno));
2332 free (*pidfile);
2333 *pidfile = NULL;
2334 return -1;
2336 else if (!create && !terminate)
2337 return 0;
2339 log_write ("%s: %s", *pidfile, strerror (errno));
2340 return -1;
2343 if (create)
2345 snprintf (buf, buflen, "%i", getpid ());
2346 ssize_t ret = write (fd, buf, strlen (buf));
2347 if (ret == -1)
2348 log_write ("%s (%i): %s", __FUNCTION__, __LINE__,
2349 pwmd_strerror (gpg_error_from_syserror ()));
2350 close (fd);
2351 return 0;
2354 len = read (fd, buf, buflen);
2355 close (fd);
2356 if (len == 0)
2358 unlink_stale_socket (path, *pidfile);
2359 return 0;
2362 if (sscanf (buf, "%5i", &pid) != 1 || pid == 0)
2364 if (!terminate)
2366 unlink_stale_socket (path, *pidfile);
2367 return 0;
2371 if (kill (pid, 0) == -1)
2373 unlink_stale_socket (path, *pidfile);
2374 return 0;
2377 if (terminate)
2379 if (kill (pid, SIGTERM) == -1)
2380 log_write ("%s: %s", path, pwmd_strerror (errno));
2382 else
2383 log_write (_ ("an instance for socket %s is already running"), path);
2385 xfree (*pidfile);
2386 *pidfile = NULL;
2387 return 1;
2390 static unsigned
2391 parse_debug_level (const char *str, unsigned *debug, int *gpgme, int *tls)
2393 const char *p;
2394 unsigned level = 0;
2395 int gl = 0, tl = 0;
2397 for (p = str; p && *p; p++)
2399 if (*p == 'a') // assuan debug flags
2401 if (*++p != ':')
2402 return 1;
2404 while (*++p)
2406 switch (*p)
2408 case 'i':
2409 level |= ASSUAN_LOG_INIT;
2410 break;
2411 case 'x':
2412 level |= ASSUAN_LOG_CTX;
2413 break;
2414 case 'e':
2415 level |= ASSUAN_LOG_ENGINE;
2416 break;
2417 case 'd':
2418 level |= ASSUAN_LOG_DATA;
2419 break;
2420 case 's':
2421 level |= ASSUAN_LOG_SYSIO;
2422 break;
2423 case 'c':
2424 level |= ASSUAN_LOG_CONTROL;
2425 break;
2426 case ',':
2427 break;
2428 default:
2429 return 1;
2432 if (*p == ',')
2433 break;
2436 if (!*p)
2437 break;
2439 else if (*p == 'g' || *p == 't') // gpgme and TLS debug level
2441 int t = *p == 't';
2442 int n;
2444 if (*++p != ':')
2445 return 1;
2447 if (!isdigit (*++p))
2448 return 1;
2450 n = atoi (p);
2451 if (t)
2452 tl = n;
2453 else
2454 gl = n;
2456 if (tl < 0 || gl < 0 || gl > 9)
2457 return 1;
2459 while (isdigit (*p))
2460 p++;
2462 p--;
2463 if (*(p+1) && *(p+1) != ',')
2464 return 1;
2465 else if (*(p+1))
2466 p++;
2468 else
2469 return 1;
2472 if (tl)
2473 *tls = tl;
2475 if (gl)
2476 *gpgme = gl;
2478 *debug = level;
2479 return 0;
2483 main (int argc, char *argv[])
2485 int opt;
2486 struct sockaddr_un addr;
2487 char buf[PATH_MAX];
2488 char *socketpath = NULL, *socketdir, *socketname = NULL;
2489 char *socketarg = NULL;
2490 char *datadir = NULL;
2491 char *pidfile = NULL;
2492 mode_t mode = 0600;
2493 int x;
2494 char *p;
2495 char **cache_push = NULL;
2496 char *import = NULL, *keyid = NULL, *sign_keyid = NULL;
2497 char *keyparam = NULL;
2498 int estatus = EXIT_FAILURE;
2499 int sockfd;
2500 char *outfile = NULL;
2501 int do_unlink = 0;
2502 int secure = 0;
2503 int show_version = 0;
2504 int force = 0;
2505 gpg_error_t rc;
2506 char *keyfile = NULL;
2507 int exists;
2508 int optindex;
2509 int terminate = 0;
2510 int sym = 0;
2511 int gpgme_level = -1;
2512 int tls_level = -1;
2513 /* Must maintain the same order as longopts[] */
2514 enum
2516 OPT_VERSION, OPT_HELP, OPT_HOMEDIR, OPT_NO_FORK, OPT_DISABLE_DUMP,
2517 OPT_FORCE, OPT_RCFILE, OPT_PASSPHRASE_FILE, OPT_IMPORT, OPT_OUTFILE,
2518 OPT_KEYID, OPT_SIGN_KEYID, OPT_SYMMETRIC, OPT_KEYPARAM, OPT_KILL,
2519 OPT_DEBUG
2521 const char *optstring = "nf:C:k:I:o:s";
2522 const struct option longopts[] = {
2523 {"version", no_argument, 0, 0},
2524 {"help", no_argument, 0, 0},
2525 {"homedir", required_argument, 0, 0},
2526 {"no-fork", no_argument, 0, 'n'},
2527 {"disable_dump", no_argument, 0, 0},
2528 {"force", no_argument, 0, 0},
2529 {"rcfile", required_argument, 0, 'f'},
2530 {"passphrase-file", required_argument, 0, 'k'},
2531 {"import", required_argument, 0, 'I'},
2532 {"outfile", required_argument, 0, 'o'},
2533 {"keyid", required_argument, 0, 0},
2534 {"sign-keyid", required_argument, 0, 0},
2535 {"symmetric", no_argument, 0, 's'},
2536 {"keyparam", required_argument, 0, 0},
2537 {"kill", no_argument, 0, 0},
2538 {"debug", required_argument, 0, 0},
2539 {0, 0, 0, 0}
2542 log_fd = -1;
2543 cmdline = 1;
2545 #ifndef DEBUG
2546 #ifdef HAVE_SETRLIMIT
2547 struct rlimit rl;
2549 rl.rlim_cur = rl.rlim_max = 0;
2551 if (setrlimit (RLIMIT_CORE, &rl) != 0)
2552 err (EXIT_FAILURE, "setrlimit()");
2553 #endif
2555 #ifdef HAVE_PR_SET_DUMPABLE
2556 prctl (PR_SET_DUMPABLE, 0);
2557 #endif
2558 #endif
2560 #ifdef ENABLE_NLS
2561 setlocale (LC_ALL, "");
2562 bindtextdomain ("pwmd", LOCALEDIR);
2563 textdomain ("pwmd");
2564 #endif
2566 if (setup_crypto ())
2567 exit (EXIT_FAILURE);
2569 #ifdef WITH_GNUTLS
2570 tls_level = tls_level == -1 ? 1 : tls_level;
2571 gnutls_global_set_log_level (tls_level);
2572 tls_fd = -1;
2573 tls6_fd = -1;
2574 #endif
2575 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
2576 xmlInitMemory ();
2577 xmlInitGlobals ();
2578 xmlInitParser ();
2579 xmlXPathInit ();
2581 while ((opt = getopt_long (argc, argv, optstring, longopts, &optindex))
2582 != -1)
2584 switch (opt)
2586 case 'I':
2587 import = optarg;
2588 break;
2589 case 'k':
2590 keyfile = optarg;
2591 break;
2592 case 'o':
2593 outfile = optarg;
2594 break;
2595 case 'D':
2596 secure = 1;
2597 break;
2598 case 'n':
2599 nofork = 1;
2600 break;
2601 case 'f':
2602 rcfile = str_dup (optarg);
2603 break;
2604 case 's':
2605 sym = 1;
2606 break;
2607 default:
2608 usage (argv[0], EXIT_FAILURE);
2609 break;
2610 case 0:
2611 switch (optindex)
2613 case OPT_DEBUG:
2614 if (parse_debug_level (optarg, &assuan_level, &gpgme_level,
2615 &tls_level))
2616 usage (argv[0], EXIT_FAILURE);
2617 break;
2618 case OPT_SYMMETRIC:
2619 sym = 1;
2620 break;
2621 case OPT_VERSION:
2622 show_version = 1;
2623 break;
2624 case OPT_HELP:
2625 usage (argv[0], EXIT_SUCCESS);
2626 break;
2627 case OPT_HOMEDIR:
2628 homedir = str_dup (optarg);
2629 break;
2630 case OPT_NO_FORK:
2631 nofork = 1;
2632 break;
2633 case OPT_DISABLE_DUMP:
2634 secure = 1;
2635 break;
2636 case OPT_FORCE:
2637 force = 1;
2638 break;
2639 case OPT_RCFILE:
2640 rcfile = str_dup (optarg);
2641 break;
2642 case OPT_PASSPHRASE_FILE:
2643 keyfile = optarg;
2644 break;
2645 case OPT_IMPORT:
2646 import = optarg;
2647 break;
2648 case OPT_OUTFILE:
2649 outfile = optarg;
2650 break;
2651 case OPT_KEYID:
2652 keyid = optarg;
2653 break;
2654 case OPT_SIGN_KEYID:
2655 sign_keyid = optarg;
2656 break;
2657 case OPT_KEYPARAM:
2658 keyparam = optarg;
2659 break;
2660 case OPT_KILL:
2661 terminate = 1;
2662 break;
2663 default:
2664 usage (argv[0], EXIT_FAILURE);
2669 if (show_version)
2671 printf (_("%s\n\n"
2672 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016\n"
2673 "%s\n"
2674 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2675 "Compile time features:\n%s"), PACKAGE_STRING,
2676 PACKAGE_BUGREPORT,
2677 #ifdef PWMD_HOMEDIR
2678 "+PWMD_HOMEDIR=" PWMD_HOMEDIR "\n"
2679 #endif
2680 #ifdef WITH_GNUTLS
2681 "+WITH_GNUTLS\n"
2682 #else
2683 "-WITH_GNUTLS\n"
2684 #endif
2685 #ifdef WITH_LIBACL
2686 "+WITH_LIBACL\n"
2687 #else
2688 "-WITH_LIBACL\n"
2689 #endif
2690 #ifdef DEBUG
2691 "+DEBUG\n"
2692 #else
2693 "-DEBUG\n"
2694 #endif
2695 #ifdef MEM_DEBUG
2696 "+MEM_DEBUG\n"
2697 #else
2698 "-MEM_DEBUG\n"
2699 #endif
2700 #ifdef MUTEX_DEBUG
2701 "+MUTEX_DEBUG\n"
2702 #else
2703 "-MUTEX_DEBUG\n"
2704 #endif
2706 exit (EXIT_SUCCESS);
2709 if (!homedir)
2710 #ifdef PWMD_HOMEDIR
2711 homedir = str_dup(PWMD_HOMEDIR);
2712 #else
2713 homedir = str_asprintf ("%s/.pwmd", get_home_dir());
2714 #endif
2716 if (mkdir (homedir, 0700) == -1 && errno != EEXIST)
2717 err (EXIT_FAILURE, "%s", homedir);
2719 if (!rcfile)
2720 rcfile = str_asprintf ("%s/config", homedir);
2722 pthread_key_create (&last_error_key, free_key);
2723 #ifndef HAVE_PTHREAD_CANCEL
2724 pthread_key_create (&signal_thread_key, free_key);
2725 #endif
2727 pthread_mutexattr_t attr;
2728 pthread_mutexattr_init (&attr);
2729 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
2730 pthread_mutex_init (&rcfile_mutex, &attr);
2731 global_config = config_parse (rcfile, 0);
2732 if (!global_config)
2734 pthread_mutexattr_destroy (&attr);
2735 pthread_mutex_destroy (&rcfile_mutex);
2736 exit (EXIT_FAILURE);
2739 p = config_get_string ("global", "gpg_homedir");
2740 if (!p)
2741 datadir = str_asprintf ("%s/.gnupg", homedir);
2742 else
2743 datadir = expand_homedir (p);
2745 xfree (p);
2746 if (mkdir (datadir, 0700) == -1 && errno != EEXIST)
2747 err (EXIT_FAILURE, "%s", datadir);
2749 if (gpgme_level != -1)
2751 char s[2] = { gpgme_level + '0', 0 };
2753 if (getenv ("GPGME_DEBUG"))
2754 log_write (_ ("Overriding GPGME_DEBUG environment with level %u!"),
2755 gpgme_level);
2757 gpgme_set_global_flag ("debug", s);
2760 rc = gpgme_set_engine_info (GPGME_PROTOCOL_OpenPGP, NULL, datadir);
2761 xfree (datadir);
2763 snprintf (buf, sizeof (buf), "%s/data", homedir);
2764 if (mkdir (buf, 0700) == -1 && errno != EEXIST)
2765 err (EXIT_FAILURE, "%s", buf);
2767 datadir = str_dup (buf);
2768 pthread_cond_init (&rcfile_cond, NULL);
2769 pthread_mutex_init (&cn_mutex, &attr);
2770 pthread_mutexattr_destroy (&attr);
2772 setup_logging ();
2774 x = config_get_int_param (global_config, "global", "priority", &exists);
2775 if (exists && x != atoi(INVALID_PRIORITY))
2777 errno = 0;
2778 if (setpriority (PRIO_PROCESS, 0, x) == -1)
2780 log_write ("setpriority(): %s",
2781 pwmd_strerror (gpg_error_from_errno (errno)));
2782 goto do_exit;
2785 #ifdef HAVE_MLOCKALL
2786 if (disable_mlock == 0 && mlockall (MCL_CURRENT | MCL_FUTURE) == -1)
2788 log_write ("mlockall(): %s",
2789 pwmd_strerror (gpg_error_from_errno (errno)));
2790 goto do_exit;
2792 #endif
2794 rc = cache_init ();
2795 if (rc)
2797 log_write ("pwmd: ERR %i: %s", rc, pwmd_strerror (rc));
2798 exit (EXIT_FAILURE);
2801 if (import)
2803 char **keyids = NULL, **sign_keyids = NULL;
2805 if (!outfile || !*outfile || argc != optind)
2806 usage (argv[0], EXIT_FAILURE);
2808 if (keyid)
2809 keyids = str_split (keyid, ",", 0);
2810 if (sign_keyid)
2811 sign_keyids = str_split (sign_keyid, ",", 0);
2812 rc = xml_import (import, outfile, keyids, sign_keyids, keyfile, keyparam, sym);
2813 strv_free (keyids);
2814 strv_free (sign_keyids);
2815 if (rc)
2817 if (gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
2818 rc = gpg_error (rc);
2820 log_write ("%s: %u: %s", import, rc, pwmd_strerror (rc));
2823 config_free (global_config);
2824 xfree (rcfile);
2825 exit (rc ? EXIT_FAILURE : EXIT_SUCCESS);
2828 p = config_get_string ("global", "socket_path");
2829 if (!p)
2830 p = str_asprintf ("%s/socket", homedir);
2832 socketarg = expand_homedir (p);
2833 xfree (p);
2835 if (!secure)
2836 disable_list_and_dump = config_get_boolean ("global",
2837 "disable_list_and_dump");
2838 else
2839 disable_list_and_dump = secure;
2841 cache_push = config_get_list ("global", "cache_push");
2843 while (optind < argc)
2845 if (strv_printf (&cache_push, "%s", argv[optind++]) == 0)
2846 errx (EXIT_FAILURE, "%s", pwmd_strerror (GPG_ERR_ENOMEM));
2849 if (strchr (socketarg, '/') == NULL)
2851 socketdir = getcwd (buf, sizeof (buf));
2852 socketname = str_dup (socketarg);
2853 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2855 else
2857 socketname = str_dup (strrchr (socketarg, '/'));
2858 socketname++;
2859 socketarg[strlen (socketarg) - strlen (socketname) - 1] = 0;
2860 socketdir = str_dup (socketarg);
2861 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2864 if (chdir (datadir))
2866 log_write ("%s: %s", datadir,
2867 pwmd_strerror (gpg_error_from_errno (errno)));
2868 unlink (socketpath);
2869 goto do_exit;
2872 x = test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 0,
2873 mode, terminate);
2874 if (!terminate && x)
2875 goto do_exit;
2876 else if (terminate)
2878 estatus = x != 1 ? EXIT_FAILURE : EXIT_SUCCESS;
2879 goto do_exit;
2883 * bind() doesn't like the full pathname of the socket or any non alphanum
2884 * characters so change to the directory where the socket is wanted then
2885 * create it then change to datadir.
2887 if (chdir (socketdir))
2889 log_write ("%s: %s", socketdir,
2890 pwmd_strerror (gpg_error_from_errno (errno)));
2891 goto do_exit;
2894 xfree (socketdir);
2896 if ((sockfd = socket (PF_UNIX, SOCK_STREAM, 0)) == -1)
2898 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2899 goto do_exit;
2902 addr.sun_family = AF_UNIX;
2903 snprintf (addr.sun_path, sizeof (addr.sun_path), "%s", socketname);
2904 do_unlink = 1;
2905 if (bind (sockfd, (struct sockaddr *) &addr, sizeof (struct sockaddr)) ==
2908 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2910 if (errno == EADDRINUSE)
2912 do_unlink = 0;
2913 log_write (_("Either there is another pwmd running or '%s' is a \n"
2914 "stale socket. Please remove it manually."), socketpath);
2917 goto do_exit;
2921 char *t = config_get_string ("global", "socket_perms");
2922 mode_t mask;
2924 if (t)
2926 mode = strtol (t, NULL, 8);
2927 mask = umask (0);
2928 xfree (t);
2930 if (chmod (socketname, mode) == -1)
2932 log_write ("%s: %s", socketname,
2933 pwmd_strerror (gpg_error_from_errno (errno)));
2934 close (sockfd);
2935 umask (mask);
2936 goto do_exit;
2939 umask (mask);
2943 xfree (--socketname);
2945 if (chdir (datadir))
2947 log_write ("%s: %s", datadir,
2948 pwmd_strerror (gpg_error_from_errno (errno)));
2949 close (sockfd);
2950 goto do_exit;
2953 xfree (datadir);
2956 * Set the cache entry for a file. Prompts for the password.
2958 if (cache_push)
2960 for (opt = 0; cache_push[opt]; opt++)
2962 struct crypto_s *crypto = NULL;
2963 char *pw_file = config_get_string (cache_push[opt],
2964 "passphrase_file");
2965 gpg_error_t rc = crypto_init (&crypto, NULL, cache_push[opt],
2966 pw_file != NULL, pw_file);
2968 if (!rc)
2970 crypto->flags |= pw_file ? CRYPTO_FLAG_KEYFILE : 0;
2971 crypto->keyfile = pw_file;
2973 else
2974 xfree (pw_file);
2976 if (rc)
2978 estatus = EXIT_FAILURE;
2979 goto do_exit;
2982 rc = do_cache_push (crypto);
2983 if (rc && !force)
2985 log_write ("ERR %u: %s", rc, pwmd_strerror(rc));
2986 strv_free (cache_push);
2987 startup_failure ();
2988 estatus = EXIT_FAILURE;
2989 crypto_free (crypto);
2990 goto do_exit;
2992 else if (rc)
2993 log_write ("%s: %s", crypto->filename, pwmd_strerror(rc));
2994 else
2995 log_write (_("Successfully added '%s' to the cache."),
2996 crypto->filename);
2998 crypto_free (crypto);
3001 strv_free (cache_push);
3002 log_write (!nofork ? _("Done. Daemonizing...") :
3003 _("Done. Waiting for connections..."));
3006 if (listen (sockfd, 128) == -1)
3008 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
3009 goto do_exit;
3012 if (!nofork)
3014 switch (fork ())
3016 case -1:
3017 log_write ("fork(): %s",
3018 pwmd_strerror (gpg_error_from_errno (errno)));
3019 goto do_exit;
3020 case 0:
3021 close (0);
3022 close (1);
3023 close (2);
3024 setsid ();
3025 break;
3026 default:
3027 _exit (EXIT_SUCCESS);
3031 (void)test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 1,
3032 mode, 0);
3033 cmdline = 0;
3034 pthread_key_create (&thread_name_key, free_key);
3035 estatus = server_loop (sockfd, &socketpath);
3037 do_exit:
3038 if (socketpath && do_unlink)
3040 unlink (socketpath);
3041 xfree (socketpath);
3044 xfree (socketarg);
3045 #ifdef WITH_GNUTLS
3046 gnutls_global_deinit ();
3047 tls_deinit_params ();
3048 #endif
3049 if (rcfile_tid)
3051 #ifdef HAVE_PTHREAD_CANCEL
3052 pthread_cancel (rcfile_tid);
3053 #else
3054 pthread_kill (rcfile_tid, SIGUSR2);
3055 pthread_cond_signal (&rcfile_cond);
3056 #endif
3057 pthread_join (rcfile_tid, NULL);
3060 pthread_cond_destroy (&rcfile_cond);
3061 pthread_mutex_destroy (&rcfile_mutex);
3062 pthread_key_delete (last_error_key);
3063 #ifndef HAVE_PTHREAD_CANCEL
3064 pthread_key_delete (signal_thread_key);
3065 #endif
3067 if (global_config)
3068 config_free (global_config);
3070 free_invoking_users (invoking_users);
3071 xfree (rcfile);
3072 xfree (home_directory);
3073 xfree (homedir);
3074 xmlCleanupParser ();
3075 xmlCleanupGlobals ();
3077 if (pidfile)
3078 unlink (pidfile);
3079 xfree (pidfile);
3081 if (estatus == EXIT_SUCCESS && !terminate)
3082 log_write (_("pwmd exiting normally"));
3084 pthread_key_delete (thread_name_key);
3085 closelog ();
3087 if (log_fd != -1)
3088 close (log_fd);
3090 exit (estatus);
3093 gpg_error_t lock_flock (assuan_context_t ctx, const char *filename,
3094 int type, int *fd)
3096 gpg_error_t rc = 0;
3098 #ifdef HAVE_FLOCK
3099 *fd = open (filename, O_RDONLY);
3100 if (*fd == -1)
3101 return gpg_error_from_syserror ();
3103 TRY_FLOCK (ctx, *fd, type, rc);
3104 if (rc)
3106 close (*fd);
3107 *fd = -1;
3109 #endif
3111 return rc;
3114 void unlock_flock (int *fd)
3116 #ifdef HAVE_FLOCK
3117 if (*fd != -1)
3118 close (*fd);
3120 *fd = -1;
3121 #endif