Cleanup INIT_SIGNAL.
[libpwmd.git] / src / pwmd.c
blobb3d503b5d6396909c3afe9c1a71106d8f97e0076
1 /*
2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015,
3 2016
4 Ben Kibbey <bjk@luxsci.net>
6 This file is part of pwmd.
8 Pwmd is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 2 of the License, or
11 (at your option) any later version.
13 Pwmd is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
21 #ifdef HAVE_CONFIG_H
22 #include <config.h>
23 #endif
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <err.h>
29 #include <ctype.h>
30 #include <string.h>
31 #include <sys/socket.h>
32 #include <sys/un.h>
33 #include <signal.h>
34 #include <stdarg.h>
35 #include <string.h>
36 #include <sys/wait.h>
37 #include <fcntl.h>
38 #include <pwd.h>
39 #include <grp.h>
40 #include <pthread.h>
41 #include <sys/mman.h>
42 #include <termios.h>
43 #include <assert.h>
44 #include <syslog.h>
45 #include <netinet/in.h>
46 #include <arpa/inet.h>
47 #include <netdb.h>
48 #include <sys/time.h>
49 #include <sys/resource.h>
50 #include <setjmp.h>
51 #include <errno.h>
52 #include <poll.h>
54 #ifdef TM_IN_SYS_TIME
55 #include <sys/time.h>
56 #else
57 #include <time.h>
58 #endif
60 #ifdef HAVE_LIMITS_H
61 #include <limits.h>
62 #endif
64 #ifdef HAVE_GETOPT_LONG
65 #ifdef HAVE_GETOPT_H
66 #include <getopt.h>
67 #endif
68 #else
69 #include "getopt_long.h"
70 #endif
72 #ifdef HAVE_PR_SET_NAME
73 #include <sys/prctl.h>
74 #endif
76 #include "pwmd-error.h"
77 #include <gcrypt.h>
79 #include "util-misc.h"
80 #include "mem.h"
81 #include "xml.h"
82 #include "common.h"
83 #include "commands.h"
84 #include "cache.h"
85 #include "util-string.h"
86 #include "mutex.h"
87 #include "rcfile.h"
88 #include "crypto.h"
90 /* In tenths of a second. */
91 #define SIG_TIMEOUT 1
93 /* For (tcp_)accept_thread (usec). */
94 #define ACCEPT_TIMEOUT 50000
96 static int quit;
97 static int cmdline;
98 static jmp_buf jmp;
99 static int nofork;
100 static pthread_cond_t quit_cond;
101 static pthread_mutex_t quit_mutex;
102 static int log_fd;
103 static unsigned assuan_level;
105 #ifndef HAVE_PTHREAD_CANCEL
106 static pthread_key_t signal_thread_key;
107 #endif
109 pthread_t accept_tid;
110 #ifdef WITH_GNUTLS
111 static int tls_fd;
112 static int tls6_fd;
113 static int start_stop_tls (int term);
114 #endif
116 static gpg_error_t do_cache_push (struct crypto_s *crypto);
117 static int signal_loop (sigset_t sigset);
119 #ifndef HAVE_PTHREAD_CANCEL
120 #define INIT_SIGNAL(s, cb) do { \
121 struct sigaction act; \
122 sigset_t sigset; \
123 sigemptyset (&sigset); \
124 sigaddset (&sigset, s); \
125 pthread_sigmask (SIG_UNBLOCK, &sigset, NULL); \
126 memset (&act, 0, sizeof(act)); \
127 act.sa_flags = SA_SIGINFO; \
128 act.sa_mask = sigset; \
129 act.sa_sigaction = cb; \
130 sigaction (s, &act, NULL); \
131 } while (0)
132 #endif
134 #ifndef HAVE_PTHREAD_CANCEL
135 static void
136 catch_thread_signal (int sig, siginfo_t *info, void *ctx)
138 int *n = (int *) pthread_getspecific (signal_thread_key);
140 *n = 1;
141 pthread_setspecific (signal_thread_key, n);
143 #endif
145 static void
146 setup_logging ()
148 int n = config_get_boolean ("global", "enable_logging");
150 if (n)
152 char *p = config_get_string ("global", "log_path");
154 if (!p || (logfile && p && log_fd != -1 && strcmp(p, logfile)))
156 if (log_fd != -1)
157 close (log_fd);
159 log_fd = -1;
162 xfree (logfile);
163 logfile = NULL;
164 if (p)
165 logfile = expand_homedir (p);
166 xfree (p);
168 else
170 xfree (logfile);
171 logfile = NULL;
172 if (log_fd != -1)
173 close(log_fd);
175 log_fd = -1;
176 closelog ();
179 log_syslog = config_get_boolean ("global", "syslog");
180 if (log_syslog == 1)
181 openlog ("pwmd", LOG_NDELAY | LOG_PID, LOG_DAEMON);
184 static void *
185 reload_rcfile_thread (void *arg)
187 #ifndef HAVE_PTHREAD_CANCEL
188 int *n = xmalloc (sizeof (int));
190 *n = 0;
191 pthread_setspecific (signal_thread_key, n);
192 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
193 #endif
195 #ifdef HAVE_PR_SET_NAME
196 prctl (PR_SET_NAME, "reload rcfile");
197 #endif
198 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
199 MUTEX_LOCK (&rcfile_mutex);
201 for (;;)
203 struct slist_s *keep = NULL;
204 struct slist_s *config;
205 int b = disable_list_and_dump;
207 pthread_cleanup_push (cleanup_mutex_cb, &rcfile_mutex);
208 pthread_cond_wait (&rcfile_cond, &rcfile_mutex);
209 #ifndef HAVE_PTHREAD_CANCEL
210 int *cancel = (int *) pthread_getspecific (signal_thread_key);
211 if (*cancel)
212 pthread_exit (NULL);
213 #endif
215 keep = config_keep_save ();
216 log_write (_("reloading configuration file '%s'"), rcfile);
218 config = config_parse (rcfile, 1);
219 if (config)
221 config_free (global_config);
222 global_config = config;
223 setup_logging ();
226 config_keep_restore (keep);
227 disable_list_and_dump = !disable_list_and_dump ? b : 1;
229 #ifdef WITH_GNUTLS
230 /* Restart listening sockets since they may have changed. */
231 start_stop_tls (1);
232 start_stop_tls (0);
233 #endif
234 crypto_set_keepalive ();
235 pthread_cleanup_pop (0);
238 MUTEX_UNLOCK (&rcfile_mutex);
239 return NULL;
242 gpg_error_t
243 send_error (assuan_context_t ctx, gpg_error_t e)
245 struct client_s *client = assuan_get_pointer (ctx);
247 if (gpg_err_source (e) == GPG_ERR_SOURCE_UNKNOWN)
248 e = gpg_error (e);
250 if (client)
251 client->last_rc = e;
253 if (!e)
254 return assuan_process_done (ctx, 0);
256 if (!ctx)
258 log_write ("ERR %i: %s", e, pwmd_strerror (e));
259 return e;
262 if (client && client->xml_error)
264 log_write ("%s", client->xml_error->message);
265 xfree (client->last_error);
266 client->last_error = NULL;
267 if (client->xml_error->message)
268 client->last_error = str_dup (client->xml_error->message);
270 e = assuan_process_done (ctx,
271 assuan_set_error (ctx, e,
272 client->xml_error->message ? client->xml_error->message : NULL));
273 xmlResetLastError ();
274 xmlResetError (client->xml_error);
275 xfree (client->xml_error);
276 client->xml_error = NULL;
277 return e;
280 return assuan_process_done (ctx,
281 assuan_set_error (ctx, e, pwmd_strerror (e)));
284 void
285 log_write (const char *fmt, ...)
287 char *args;
288 va_list ap;
289 time_t now;
290 char buf[255];
291 pthread_t tid = pthread_self ();
292 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
294 if ((!logfile && !isatty (STDERR_FILENO) && !log_syslog) || !fmt)
295 return;
297 pthread_mutex_lock (&m);
298 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock, &m);
300 if (!cmdline && logfile && log_fd == -1)
302 log_fd = open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600);
303 if (log_fd == -1)
304 warn ("%s", logfile);
307 va_start (ap, fmt);
309 if (str_vasprintf (&args, fmt, ap) != -1)
311 if (cmdline)
313 pthread_cleanup_push (xfree, args);
314 fprintf (stderr, "pwmd: %s\n", args);
315 fflush (stderr);
316 pthread_cleanup_pop (1);
318 else
320 char *name = pthread_getspecific (thread_name_key);
321 char *line;
323 pthread_cleanup_push (xfree, args);
324 snprintf (buf, sizeof (buf),
325 name && *name == '!' ? "%s: " : name ? "%s(%p): " : "%s",
326 name ? *name == '!' ? name+1 : name : "",
327 name && *name == '!' ? 0 : name ? (pthread_t *) tid : 0);
328 name = buf;
330 if (!cmdline && log_syslog && !nofork)
331 syslog (LOG_INFO, "%s%s", name, args);
333 time (&now);
334 struct tm *tm = localtime (&now);
335 char tbuf[21];
336 strftime (tbuf, sizeof (tbuf), "%b %d %Y %H:%M:%S ", tm);
337 tbuf[sizeof (tbuf) - 1] = 0;
339 if (args[strlen (args) - 1] == '\n')
340 args[strlen (args) - 1] = 0;
342 line = str_asprintf ("%s %i %s%s\n", tbuf, getpid (), name,
343 args);
344 pthread_cleanup_pop (1);
345 if (line)
347 pthread_cleanup_push (xfree, line);
348 if (logfile && log_fd != -1)
350 ssize_t ret = write (log_fd, line, strlen (line));
351 (void)ret;
352 fsync (log_fd);
355 if (nofork)
357 fprintf (stdout, "%s", line);
358 fflush (stdout);
361 pthread_cleanup_pop (1);
366 va_end (ap);
367 pthread_cleanup_pop (0);
369 if (log_fd != -1 && log_keepopen <= 0)
371 close(log_fd);
372 log_fd = -1;
375 pthread_mutex_unlock (&m);
378 static gpg_error_t
379 setup_crypto ()
381 gpg_error_t rc;
383 if (!gpgrt_check_version (REQUIRE_LIBGPGERROR_VERSION))
385 fprintf (stderr, _("gpgrt_check_version(): Incompatible libgpg-error. "
386 "Wanted %s, got %s.\n"), REQUIRE_LIBGPGERROR_VERSION,
387 gpgrt_check_version (NULL));
388 return GPG_ERR_UNKNOWN_VERSION;
391 gpgrt_init ();
392 gpgrt_set_alloc_func (xrealloc_gpgrt);
394 if (!assuan_check_version (REQUIRE_LIBASSUAN_VERSION))
396 fprintf (stderr, _("assuan_check_version(): Incompatible libassuan. "
397 "Wanted %s, got %s.\n"), REQUIRE_LIBASSUAN_VERSION,
398 assuan_check_version (NULL));
399 return GPG_ERR_UNKNOWN_VERSION;
402 if (!gcry_check_version (REQUIRE_LIBGCRYPT_VERSION))
404 fprintf (stderr, _("gcry_check_version(): Incompatible libgcrypt. "
405 "Wanted %s, got %s.\n"), REQUIRE_LIBGCRYPT_VERSION,
406 gcry_check_version (NULL));
407 return GPG_ERR_UNKNOWN_VERSION;
410 gcry_set_allocation_handler (xmalloc, xmalloc, NULL, xrealloc, xfree);
412 if (!gpgme_check_version (REQUIRE_LIBGPGME_VERSION))
414 fprintf (stderr, _("gpgme_check_version(): Incompatible libgpgme. "
415 "Wanted %s, got %s.\n"), REQUIRE_LIBGPGME_VERSION,
416 gpgme_check_version (NULL));
417 return GPG_ERR_UNKNOWN_VERSION;
420 rc = gpgme_engine_check_version (GPGME_PROTOCOL_OPENPGP);
421 if (rc)
423 fprintf (stderr, _("gpgme_engine_check_version(GPGME_PROTOCOL_OPENPGP): %s"), gpgme_strerror (rc));
424 return GPG_ERR_UNKNOWN_VERSION;
427 //gpgme_set_global_flag ("require-gnupg", REQUIRE_GNUPG_VERSION);
428 #ifdef ENABLE_NLS
429 gpgme_set_locale (NULL, LC_CTYPE, setlocale (LC_CTYPE, NULL));
430 gpgme_set_locale (NULL, LC_MESSAGES, setlocale (LC_MESSAGES, NULL));
431 #endif
433 #ifdef WITH_GNUTLS
434 if (gnutls_global_init ())
436 fprintf(stderr, _("gnutls_global_init() failed.\n"));
437 return GPG_ERR_UNKNOWN_VERSION;
440 gnutls_global_set_log_function (tls_log);
441 gnutls_global_set_audit_log_function (tls_audit_log);
442 #endif
443 return 0;
446 gpg_error_t
447 do_validate_peer (assuan_context_t ctx, const char *section,
448 assuan_peercred_t * peer)
450 char **users;
451 int allowed = 0;
452 gpg_error_t rc;
453 struct client_s *client = assuan_get_pointer (ctx);
455 if (!client)
456 return GPG_ERR_FORBIDDEN;
458 #ifdef WITH_GNUTLS
459 if (client->thd->remote)
460 return tls_validate_access (client, section);
461 #endif
463 rc = assuan_get_peercred (ctx, peer);
464 if (rc)
465 return rc;
467 users = config_get_list (section, "allowed");
468 if (users)
470 for (char **p = users; !rc && *p; p++)
472 rc = acl_check_common(client, *p, (*peer)->uid, (*peer)->gid,
473 &allowed);
476 strv_free (users);
478 else if (client->no_access_param)
479 allowed = 1;
481 return allowed && !rc ? 0 : rc ? rc : GPG_ERR_FORBIDDEN;
484 /* Test if uid is a member of group 'name'. Invert when 'not' is true. */
485 #ifdef HAVE_GETGRNAM_R
486 static gpg_error_t
487 acl_check_group (const char *name, uid_t uid, gid_t gid, int not, int *allowed)
489 char *buf;
490 struct group gr, *gresult;
491 size_t len = sysconf (_SC_GETGR_R_SIZE_MAX);
492 int err;
493 gpg_error_t rc = 0;
495 if (len == -1)
496 len = 16384;
498 buf = xmalloc (len);
499 if (!buf)
500 return GPG_ERR_ENOMEM;
502 err = getgrnam_r (name, &gr, buf, len, &gresult);
503 if (!err && gresult)
505 if (gresult->gr_gid == gid)
507 xfree (buf);
508 *allowed = !not;
509 return 0;
512 for (char **t = gresult->gr_mem; !rc && *t; t++)
514 char *tbuf;
515 struct passwd pw;
516 struct passwd *result = get_pwd_struct (*t, 0, &pw, &tbuf, &rc);
518 if (!rc && result && result->pw_uid == uid)
520 xfree (tbuf);
521 *allowed = !not;
522 break;
525 xfree (tbuf);
528 xfree (buf);
529 return rc;
531 else if (err)
532 rc = gpg_error_from_errno (err);
534 xfree (buf);
535 return rc ? rc : !gresult ? 0 : GPG_ERR_EACCES;
537 #else
538 static gpg_error_t
539 acl_check_group (const char *name, uid_t uid, gid_t gid, int not, int *allowed)
541 struct group *gresult;
542 gpg_error_t rc = 0;
544 errno = 0;
545 gresult = getgrnam (name);
546 if (!errno && gresult && gresult->gr_gid == gid)
548 *allowed = !not;
549 return 0;
551 else if (errno)
552 rc = gpg_error_from_syserror ();
553 else if (!gresult)
554 return 0;
556 for (char **t = gresult->gr_mem; !rc && *t; t++)
558 char *buf;
559 struct passwd pw;
560 struct passwd *result = get_pwd_struct (*t, 0, &pw, &buf, &rc);
562 if (!rc && result && result->pw_uid == uid)
564 xfree (buf);
565 *allowed = !not;
566 break;
569 xfree (buf);
572 return rc;
574 #endif
576 gpg_error_t
577 peer_is_invoker(struct client_s *client)
579 struct invoking_user_s *user;
580 int allowed = 0;
582 if (client->thd->state == CLIENT_STATE_UNKNOWN)
583 return GPG_ERR_EACCES;
585 for (user = invoking_users; user; user = user->next)
587 #ifdef WITH_GNUTLS
588 if (client->thd->remote)
590 if (user->type == INVOKING_TLS
591 && !strcmp(client->thd->tls->fp, user->id))
592 allowed = user->not ? 0 : 1;
594 continue;
596 #endif
598 if (user->type == INVOKING_GID)
600 gpg_error_t rc = acl_check_group (user->id,
601 client->thd->peer->uid,
602 client->thd->peer->gid,
603 user->not, &allowed);
604 if (rc)
605 return rc;
607 else if (user->type == INVOKING_UID && client->thd->peer->uid == user->uid)
608 allowed = user->not ? 0 : 1;
611 return allowed ? 0 : GPG_ERR_EACCES;
614 #ifdef HAVE_GETGRNAM_R
615 gpg_error_t
616 acl_check_common (struct client_s *client, const char *user, uid_t uid,
617 gid_t gid, int *allowed)
619 int not = 0;
620 int rw = 0;
621 int tls = 0;
622 gpg_error_t rc = 0;
624 if (!user || !*user)
625 return 0;
627 if (*user == '-' || *user == '!')
628 not = 1;
630 if (*user == '+') // not implemented yet
631 rw = 1;
633 if (*user == '#') // TLS fingerprint hash
634 tls = 1;
636 if (not || rw || tls)
637 user++;
639 if (tls)
641 #ifdef WITH_GNUTLS
642 if (client->thd->remote)
644 if (!strcasecmp (client->thd->tls->fp, user))
645 *allowed = !not;
648 return 0;
649 #else
650 return 0;
651 #endif
653 #ifdef WITH_GNUTLS
654 else if (client->thd->remote) // Remote client with no FP in the ACL
655 return 0;
656 #endif
658 if (*user == '@') // all users in group
659 return acl_check_group (user+1, uid, gid, not, allowed);
660 else
662 char *buf;
663 struct passwd pw;
664 struct passwd *pwd = get_pwd_struct (user, 0, &pw, &buf, &rc);
666 if (!rc && pwd && pwd->pw_uid == uid)
667 *allowed = !not;
669 xfree (buf);
672 return rc;
674 #else
675 gpg_error_t
676 acl_check_common (struct client_s *client, const char *user, uid_t uid,
677 gid_t gid, int *allowed)
679 gpg_error_t rc = 0;
680 int not = 0;
681 int rw = 0;
682 int tls = 0;
684 if (!user || !*user)
685 return 0;
687 if (*user == '-' || *user == '!')
688 not = 1;
690 if (*user == '+') // not implemented yet
691 rw = 1;
693 if (*user == '#') // TLS fingerprint hash
694 tls = 1;
696 if (not || rw || tls)
697 user++;
699 if (tls)
701 #ifdef WITH_GNUTLS
702 if (client->thd->remote)
704 if (!strcasecmp (client->thd->tls->fp, user))
705 *allowed = !not;
708 return 0;
709 #else
710 return 0;
711 #endif
714 if (*user == '@') // all users in group
715 return acl_check_group (user+1, uid, gid, not, allowed);
716 else
718 char *buf;
719 struct passwd pw;
720 struct passwd *result = get_pwd_struct (user, 0, &pw, &buf, &rc);
722 if (!rc && result && result->pw_uid == uid)
723 *allowed = !not;
725 xfree (buf);
728 return rc;
730 #endif
732 static gpg_error_t
733 validate_peer (struct client_s *cl)
735 gpg_error_t rc;
737 #ifdef WITH_GNUTLS
738 if (cl->thd->remote)
739 return tls_validate_access (cl, NULL);
740 #endif
742 MUTEX_LOCK (&cn_mutex);
743 rc = do_validate_peer (cl->ctx, "global", &cl->thd->peer);
744 MUTEX_UNLOCK (&cn_mutex);
745 log_write ("peer %s: uid=%i, gid=%i, pid=%i, rc=%u",
746 !rc ? _("accepted") : _("rejected"), cl->thd->peer->uid,
747 cl->thd->peer->gid, cl->thd->peer->pid, rc);
748 return rc;
751 static void
752 xml_error_cb (void *data, xmlErrorPtr e)
754 struct client_s *client = data;
757 * Keep the first reported error as the one to show in the error
758 * description. Reset in send_error().
760 if (client->xml_error)
761 return;
763 client->xml_error = xcalloc (1, sizeof(xmlError));
764 xmlCopyError (e, client->xml_error);
767 static pid_t
768 hook_waitpid (assuan_context_t ctx, pid_t pid, int action,
769 int *status, int options)
771 return waitpid (pid, status, options);
774 static ssize_t
775 hook_read (assuan_context_t ctx, assuan_fd_t fd, void *data, size_t len)
777 #ifdef WITH_GNUTLS
778 struct client_s *client = assuan_get_pointer (ctx);
780 if (client->thd->remote)
781 return tls_read_hook (ctx, (int) fd, data, len);
782 #endif
784 return read ((int) fd, data, len);
787 static ssize_t
788 hook_write (assuan_context_t ctx, assuan_fd_t fd,
789 const void *data, size_t len)
791 #ifdef WITH_GNUTLS
792 struct client_s *client = assuan_get_pointer (ctx);
794 if (client->thd->remote)
795 return tls_write_hook (ctx, (int) fd, data, len);
796 #endif
798 return write ((int) fd, data, len);
802 assuan_log_cb (assuan_context_t ctx, void *data, unsigned cat,
803 const char *msg)
805 struct client_s *client = data;
806 char *str = NULL;
808 (void)client;
810 if (!(assuan_level & cat))
811 return 0;
813 if (!msg)
814 return 1;
816 switch (cat)
818 case ASSUAN_LOG_INIT:
819 str = "ASSUAN[INIT]";
820 break;
821 case ASSUAN_LOG_CTX:
822 str = "ASSUAN[CTX]";
823 break;
824 case ASSUAN_LOG_ENGINE:
825 str = "ASSUAN[ENGINE]";
826 break;
827 case ASSUAN_LOG_DATA:
828 str = "ASSUAN[DATA]";
829 break;
830 case ASSUAN_LOG_SYSIO:
831 str = "ASSUAN[SYSIO]";
832 break;
833 case ASSUAN_LOG_CONTROL:
834 str = "ASSUAN[CONTROL]";
835 break;
836 default:
837 str = "ASSUAN[UNKNOWN]";
838 break;
841 log_write ("%s: %s", str, msg);
842 return 1;
845 static int
846 new_connection (struct client_s *cl)
848 gpg_error_t rc;
849 static struct assuan_malloc_hooks mhooks = { xmalloc, xrealloc, xfree };
850 static struct assuan_system_hooks shooks = {
851 ASSUAN_SYSTEM_HOOKS_VERSION,
852 __assuan_usleep,
853 __assuan_pipe,
854 __assuan_close,
855 hook_read,
856 hook_write,
857 //FIXME
858 NULL, //recvmsg
859 NULL, //sendmsg both are used for FD passing
860 __assuan_spawn,
861 hook_waitpid,
862 __assuan_socketpair,
863 __assuan_socket,
864 __assuan_connect
867 #ifdef WITH_GNUTLS
868 if (cl->thd->remote)
870 char *prio = config_get_string ("global", "tls_cipher_suite");
872 cl->thd->timeout = config_get_integer ("global", "tls_timeout");
873 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
874 return 0;
876 cl->thd->tls = tls_init_client (cl->thd->fd, cl->thd->timeout, prio);
877 xfree (prio);
878 if (!cl->thd->tls)
879 return 0;
881 #endif
883 rc = assuan_new_ext (&cl->ctx, GPG_ERR_SOURCE_DEFAULT, &mhooks,
884 assuan_log_cb, cl);
885 if (rc)
886 goto fail;
888 assuan_ctx_set_system_hooks (cl->ctx, &shooks);
889 rc = assuan_init_socket_server (cl->ctx, cl->thd->fd, 2);
890 if (rc)
891 goto fail;
893 assuan_set_pointer (cl->ctx, cl);
894 assuan_set_hello_line (cl->ctx, PACKAGE_STRING);
895 rc = register_commands (cl->ctx);
896 if (rc)
897 goto fail;
899 rc = assuan_accept (cl->ctx);
900 if (rc)
901 goto fail;
903 rc = validate_peer (cl);
904 /* May not be implemented on all platforms. */
905 if (rc && gpg_err_code (rc) != GPG_ERR_ASS_GENERAL)
906 goto fail;
908 MUTEX_LOCK (&cn_mutex);
909 cl->thd->state = CLIENT_STATE_INIT;
910 MUTEX_UNLOCK (&cn_mutex);
911 cl->lock_timeout = config_get_integer ("global", "lock_timeout");
912 xmlSetStructuredErrorFunc (cl, xml_error_cb);
913 return 1;
915 fail:
916 log_write ("%s", pwmd_strerror (rc));
917 return 0;
921 * This is called after a client_thread() terminates. Set with
922 * pthread_cleanup_push().
924 static void
925 cleanup_cb (void *arg)
927 struct client_thread_s *cn = arg;
928 struct client_s *cl = cn->cl;
930 MUTEX_LOCK (&cn_mutex);
931 cn_thread_list = slist_remove (cn_thread_list, cn);
932 MUTEX_UNLOCK (&cn_mutex);
934 if (cl)
936 unlock_flock (&cl->flock_fd);
937 cleanup_client (cl);
938 if (cl->xml_error)
939 xmlResetError (cl->xml_error);
941 xfree (cl->xml_error);
943 #ifdef WITH_GNUTLS
944 if (cn->tls)
946 gnutls_deinit (cn->tls->ses);
947 xfree (cn->tls->fp);
948 xfree (cn->tls);
950 #endif
952 if (!cn->atfork && cl->ctx)
953 assuan_release (cl->ctx);
954 else if (!cn->atfork && cl->thd && cl->thd->fd != -1)
955 close (cl->thd->fd);
957 if (cl->crypto)
958 crypto_free (cl->crypto);
960 cl->crypto = NULL;
961 xfree (cl);
963 else
965 if (cn->fd != -1)
966 close (cn->fd);
969 while (cn->msg_queue)
971 struct status_msg_s *msg = cn->msg_queue;
973 cn->msg_queue = msg->next;
974 xfree (msg->line);
975 xfree (msg);
978 if (!cn->atfork && cn->status_msg_pipe[0] != -1)
979 close (cn->status_msg_pipe[0]);
981 if (!cn->atfork && cn->status_msg_pipe[1] != -1)
982 close (cn->status_msg_pipe[1]);
984 pthread_mutex_destroy (&cn->status_mutex);
986 if (!cn->atfork)
988 log_write (_("exiting, fd=%i"), cn->fd);
989 send_status_all (STATUS_CLIENTS, NULL);
992 xfree (cn->name);
993 #ifdef WITH_GNUTLS
994 xfree (cn->peeraddr);
995 #endif
996 xfree (cn);
997 pthread_cond_signal (&quit_cond);
1000 void
1001 cleanup_all_clients (int atfork)
1003 /* This function may be called from pthread_atfork() which requires
1004 reinitialization. */
1005 if (atfork)
1007 pthread_mutexattr_t attr;
1009 pthread_mutexattr_init (&attr);
1010 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
1011 pthread_mutex_init (&cn_mutex, &attr);
1012 pthread_mutexattr_destroy (&attr);
1013 cache_mutex_init ();
1016 MUTEX_LOCK (&cn_mutex);
1018 while (slist_length (cn_thread_list))
1020 struct client_thread_s *thd = slist_nth_data (cn_thread_list, 0);
1022 thd->atfork = atfork;
1023 cleanup_cb (thd);
1026 exiting = 1;
1027 MUTEX_UNLOCK (&cn_mutex);
1028 cache_deinit (atfork);
1031 static gpg_error_t
1032 send_msg_queue (struct client_thread_s *thd)
1034 MUTEX_LOCK (&thd->status_mutex);
1035 gpg_error_t rc = 0;
1036 char c;
1037 ssize_t ret;
1039 ret = read (thd->status_msg_pipe[0], &c, 1);
1040 rc = gpg_error_from_syserror ();
1041 if (ret == -1 && gpg_err_code (rc) != GPG_ERR_EAGAIN)
1042 log_write ("%s (%i): %s", __FUNCTION__, __LINE__, pwmd_strerror (rc));
1043 else
1044 rc = 0;
1046 thd->wrote_status = 0;
1048 while (thd->msg_queue)
1050 struct status_msg_s *msg = thd->msg_queue;
1052 #ifndef HAVE_PTHREAD_CANCEL
1053 if (thd->fd == -1)
1054 break;
1055 #endif
1057 thd->msg_queue = thd->msg_queue->next;
1058 MUTEX_UNLOCK (&thd->status_mutex);
1059 rc = send_status (thd->cl->ctx, msg->s, msg->line);
1060 MUTEX_LOCK (&thd->status_mutex);
1061 xfree (msg->line);
1062 xfree (msg);
1064 if (rc)
1065 break;
1068 MUTEX_UNLOCK (&thd->status_mutex);
1069 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1070 log_write ("%s (%i): %s", __FUNCTION__, __LINE__, pwmd_strerror (rc));
1072 return rc;
1075 static void *
1076 client_thread (void *data)
1078 struct client_thread_s *thd = data;
1079 struct client_s *cl = xcalloc (1, sizeof (struct client_s));
1081 #ifdef HAVE_PR_SET_NAME
1082 prctl (PR_SET_NAME, "client");
1083 #endif
1084 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1086 if (!cl)
1088 log_write ("%s(%i): %s", __FILE__, __LINE__,
1089 pwmd_strerror (GPG_ERR_ENOMEM));
1090 return NULL;
1093 MUTEX_LOCK (&cn_mutex);
1094 pthread_cleanup_push (cleanup_cb, thd);
1095 thd->cl = cl;
1096 cl->thd = thd;
1097 cl->flock_fd = -1;
1098 MUTEX_UNLOCK (&cn_mutex);
1100 if (new_connection (cl))
1102 int finished = 0;
1103 gpg_error_t rc;
1104 struct pollfd fds[2];
1106 fds[0].fd = thd->fd;
1107 fds[0].events = POLLIN;
1108 fds[1].fd = thd->status_msg_pipe[0];
1109 fds[1].events = POLLIN;
1111 send_status_all (STATUS_CLIENTS, NULL);
1112 rc = send_status (cl->ctx, STATUS_CACHE, NULL);
1113 if (rc)
1115 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
1116 finished = 1;
1119 while (!finished)
1121 int n;
1122 int eof;
1124 n = poll (fds, 2, -1);
1125 if (n == -1)
1127 log_write ("%s", strerror (errno));
1128 break;
1131 if (fds[1].revents & POLLIN)
1133 rc = send_msg_queue (thd);
1134 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1135 break;
1138 #ifdef HAVE_PTHREAD_CANCEL
1139 if (!(fds[0].revents & POLLIN))
1140 #else
1141 if (thd->fd != -1 && !(fds[0].revents & POLLIN))
1142 #endif
1143 continue;
1145 rc = assuan_process_next (cl->ctx, &eof);
1146 if (rc || eof)
1148 if (gpg_err_code (rc) == GPG_ERR_EOF || eof)
1149 break;
1151 log_write ("assuan_process_next(): rc=%u %s", rc,
1152 pwmd_strerror (rc));
1153 if (rc == gpg_error (GPG_ERR_ETIMEDOUT))
1154 break;
1156 rc = send_error (cl->ctx, rc);
1157 if (rc)
1159 log_write ("assuan_process_done(): rc=%u %s", rc,
1160 pwmd_strerror (rc));
1161 break;
1165 /* Since the msg queue pipe fd's are non-blocking, check for
1166 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1167 * client has already disconnected and will be converted to
1168 * GPG_ERR_EOF during assuan_process_next().
1170 rc = send_msg_queue (thd);
1171 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1172 break;
1176 /* Don't do pthread_exit() here because any set pthread_cleanup_push
1177 * functions would be called after a command failed but then the client
1178 * exited normally which may lead to a double free. */
1179 pthread_cleanup_pop (1);
1180 return NULL;
1183 static gpg_error_t
1184 xml_import (const char *filename, const char *outfile, char **keyid,
1185 char **sign_keyid, char *keyfile, const char *keyparam,
1186 int symmetric)
1188 xmlDocPtr doc;
1189 int fd;
1190 struct stat st;
1191 int len;
1192 xmlChar *xmlbuf;
1193 gpg_error_t rc = 0;
1194 struct crypto_s *crypto = NULL;
1196 if (stat (filename, &st) == -1)
1198 rc = gpg_error_from_errno (errno);
1199 return rc;
1202 fd = open (filename, O_RDONLY);
1203 if (fd == -1)
1204 return gpg_error_from_errno (errno);
1206 xmlbuf = xmalloc (st.st_size + 1);
1207 if (!xmlbuf)
1209 close (fd);
1210 return GPG_ERR_ENOMEM;
1213 if (read (fd, xmlbuf, st.st_size) == -1)
1215 rc = gpg_error_from_errno (errno);
1216 close (fd);
1217 xfree (xmlbuf);
1218 return rc;
1221 close (fd);
1222 xmlbuf[st.st_size] = 0;
1223 // Be sure the document validates.
1224 doc = xmlReadDoc (xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS);
1225 xfree (xmlbuf);
1226 if (!doc)
1227 return GPG_ERR_BAD_DATA;
1229 xmlNodePtr n = xmlDocGetRootElement (doc);
1230 if (n && !xmlStrEqual (n->name, (xmlChar *) "pwmd"))
1231 rc = GPG_ERR_BAD_DATA;
1233 if (!rc)
1235 rc = xml_validate_import (NULL, n ? n->children : n);
1236 if (!rc)
1238 rc = crypto_init (&crypto, NULL, filename, keyfile != NULL, keyfile);
1239 if (!rc)
1241 if (keyfile)
1243 crypto->flags |= CRYPTO_FLAG_KEYFILE;
1244 crypto->keyfile = str_dup (keyfile);
1247 xmlDocDumpMemory (doc, &crypto->plaintext, &len);
1248 if (len > 0)
1249 crypto->plaintext_size = len;
1250 else
1251 rc = GPG_ERR_ENOMEM;
1256 if (!rc)
1258 if (!symmetric && (keyparam || !keyid))
1260 char *buf = NULL;
1262 if (keyparam)
1264 fd = open (keyparam, O_RDONLY);
1265 if (fd == -1)
1266 rc = gpg_error_from_errno (errno);
1268 if (!rc)
1270 if (stat (keyparam, &st) == -1)
1271 rc = gpg_error_from_errno (errno);
1273 if (!rc)
1275 buf = xmalloc (st.st_size+1);
1276 if (!buf)
1277 rc = GPG_ERR_ENOMEM;
1279 if (!rc)
1281 len = read (fd, buf, st.st_size);
1282 if (len != st.st_size)
1283 rc = gpg_error_from_errno (errno);
1285 if (!rc)
1286 buf[len] = 0;
1291 if (fd != -1)
1292 close (fd);
1294 else
1296 buf = crypto_default_key_params ();
1297 if (!buf)
1298 rc = GPG_ERR_ENOMEM;
1301 if (!rc)
1302 rc = crypto_genkey (NULL, crypto, (unsigned char *)buf);
1304 xfree (buf);
1306 else
1308 crypto->save.pubkey = strv_dup (keyid);
1309 crypto->save.sigkey = strv_dup (sign_keyid);
1312 if (!rc)
1314 crypto->flags |= symmetric ? CRYPTO_FLAG_SYMMETRIC : 0;
1315 rc = crypto_encrypt (NULL, crypto);
1319 if (!rc)
1321 if (!strcmp (outfile, "-"))
1322 outfile = NULL;
1324 xfree (crypto->plaintext);
1325 crypto->plaintext = NULL;
1326 xfree (crypto->filename);
1327 crypto->filename = outfile ? str_dup (outfile) : NULL;
1328 rc = crypto_write_file (crypto);
1331 xmlFreeDoc (doc);
1332 crypto_free (crypto);
1333 return rc;
1336 static gpg_error_t
1337 do_cache_push (struct crypto_s *crypto)
1339 gpg_error_t rc;
1340 xmlDocPtr doc;
1341 struct cache_data_s *cdata;
1342 unsigned char *crc;
1343 size_t len;
1344 int fd = -1;
1346 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1347 crypto->filename);
1349 if (valid_filename (crypto->filename) == 0)
1351 log_write (_("%s: Invalid characters in filename"), crypto->filename);
1352 return GPG_ERR_INV_VALUE;
1355 rc = lock_flock (NULL, crypto->filename, LOCK_SH, &fd);
1356 if (!rc)
1357 rc = crypto_decrypt (NULL, crypto);
1358 if (rc)
1360 unlock_flock (&fd);
1361 return rc;
1364 rc = xml_parse_doc ((char *) crypto->plaintext, crypto->plaintext_size, &doc);
1365 if (rc)
1367 unlock_flock (&fd);
1368 log_write ("%s", pwmd_strerror (rc));
1369 return rc;
1372 cdata = xcalloc (1, sizeof (struct cache_data_s));
1373 if (!cdata)
1375 unlock_flock (&fd);
1376 xmlFreeDoc (doc);
1377 return GPG_ERR_ENOMEM;
1380 rc = get_checksum (crypto->filename, &crc, &len);
1381 unlock_flock (&fd);
1382 if (rc)
1384 xmlFreeDoc (doc);
1385 free_cache_data_once (cdata);
1386 return rc;
1389 cdata->crc = crc;
1390 rc = cache_encrypt (crypto);
1391 if (!rc)
1393 cdata->doc = crypto->plaintext;
1394 cdata->size = crypto->plaintext_size;
1395 crypto->plaintext = NULL;
1396 cdata->pubkey = crypto->pubkey;
1397 cdata->sigkey = crypto->sigkey;
1398 crypto->pubkey = NULL;
1399 crypto->sigkey = NULL;
1401 else
1403 xmlFreeDoc (doc);
1404 free_cache_data_once (cdata);
1405 return rc;
1408 int timeout = config_get_integer (crypto->filename, "cache_timeout");
1409 rc = cache_add_file (crypto->filename, cdata, timeout);
1410 return rc;
1413 static gpg_error_t
1414 init_client (int fd, const char *addr)
1416 gpg_error_t rc = 0;
1417 struct client_thread_s *new = xcalloc (1, sizeof (struct client_thread_s));
1419 if (!new)
1421 close (fd);
1422 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (ENOMEM));
1423 return GPG_ERR_ENOMEM;
1426 MUTEX_LOCK (&cn_mutex);
1427 new->conntime = time (NULL);
1428 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
1430 if (pipe (new->status_msg_pipe) == -1)
1431 rc = gpg_error_from_errno (errno);
1433 if (!rc)
1435 if (fcntl (new->status_msg_pipe[0], F_SETFL, O_NONBLOCK) == -1)
1436 rc = gpg_error_from_errno (errno);
1438 if (!rc)
1439 if (fcntl (new->status_msg_pipe[1], F_SETFL, O_NONBLOCK) == -1)
1440 rc = gpg_error_from_errno (errno);
1442 pthread_mutex_init (&new->status_mutex, NULL);
1445 if (!rc)
1447 #ifdef WITH_GNUTLS
1448 new->remote = addr ? 1 : 0;
1449 #endif
1450 new->fd = fd;
1451 rc = create_thread (client_thread, new, &new->tid, 1);
1452 if (rc)
1454 close (new->status_msg_pipe[0]);
1455 close (new->status_msg_pipe[1]);
1456 pthread_mutex_destroy (&new->status_mutex);
1460 if (!rc)
1462 struct slist_s *list = slist_append (cn_thread_list, new);
1464 if (list)
1466 cn_thread_list = list;
1467 if (addr)
1469 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1470 (pthread_t *) new->tid, fd, addr);
1471 #ifdef WITH_GNUTLS
1472 new->peeraddr = str_dup (addr);
1473 #endif
1475 else
1476 log_write (_("new connection: tid=%p, fd=%i"),
1477 (pthread_t *) new->tid, fd);
1479 else
1480 rc = GPG_ERR_ENOMEM;
1483 pthread_cleanup_pop (1);
1485 if (rc)
1487 xfree (new);
1488 close (fd);
1489 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1490 pwmd_strerror (rc));
1492 return rc;
1495 #ifdef WITH_GNUTLS
1496 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1497 static void *
1498 get_in_addr (struct sockaddr *sa)
1500 if (sa->sa_family == AF_INET)
1501 return &(((struct sockaddr_in *) sa)->sin_addr);
1503 return &(((struct sockaddr_in6 *) sa)->sin6_addr);
1506 static int
1507 start_stop_tls_with_protocol (int ipv6, int term)
1509 struct addrinfo hints, *servinfo, *p;
1510 int port = config_get_integer ("global", "tcp_port");
1511 char buf[7];
1512 int n;
1513 int *fd = ipv6 ? &tls6_fd : &tls_fd;
1515 if (term || config_get_boolean ("global", "enable_tcp") == 0)
1517 if (tls6_fd != -1)
1519 shutdown (tls6_fd, SHUT_RDWR);
1520 close (tls6_fd);
1521 tls6_fd = -1;
1524 if (tls_fd != -1)
1526 shutdown (tls_fd, SHUT_RDWR);
1527 close (tls_fd);
1528 tls_fd = -1;
1531 return 0;
1534 memset (&hints, 0, sizeof (hints));
1535 hints.ai_family = ipv6 ? AF_INET6 : AF_INET;
1536 hints.ai_socktype = SOCK_STREAM;
1537 hints.ai_flags = AI_PASSIVE;
1538 snprintf (buf, sizeof (buf), "%i", port);
1540 if ((n = getaddrinfo (NULL, buf, &hints, &servinfo)) == -1)
1542 log_write ("getaddrinfo(): %s", gai_strerror (n));
1543 return 0;
1546 for (n = 0, p = servinfo; p != NULL; p = p->ai_next)
1548 int r = 1;
1550 if ((ipv6 && p->ai_family != AF_INET6)
1551 || (!ipv6 && p->ai_family != AF_INET))
1552 continue;
1554 if ((*fd = socket (p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
1556 log_write ("socket(): %s", strerror (errno));
1557 continue;
1560 if (setsockopt (*fd, SOL_SOCKET, SO_REUSEADDR, &r, sizeof (int)) == -1)
1562 log_write ("setsockopt(): %s",
1563 pwmd_strerror (gpg_error_from_errno (errno)));
1564 freeaddrinfo (servinfo);
1565 goto fail;
1568 if (bind (*fd, p->ai_addr, p->ai_addrlen) == -1)
1570 close (*fd);
1571 log_write ("bind(): %s",
1572 pwmd_strerror (gpg_error_from_errno (errno)));
1573 continue;
1576 n++;
1577 break;
1580 freeaddrinfo (servinfo);
1582 if (!n)
1583 goto fail;
1585 #if HAVE_DECL_SO_BINDTODEVICE != 0
1586 char *tmp = config_get_string ("global", "tcp_interface");
1587 if (tmp && setsockopt (*fd, SOL_SOCKET, SO_BINDTODEVICE, tmp,
1588 strlen (tmp)) == -1)
1590 log_write ("setsockopt(): %s",
1591 pwmd_strerror (gpg_error_from_errno (errno)));
1592 xfree (tmp);
1593 goto fail;
1596 xfree (tmp);
1597 #endif
1599 if (listen (*fd, 128) == -1)
1601 log_write ("listen(): %s", strerror (errno));
1602 goto fail;
1605 return 1;
1607 fail:
1608 start_stop_tls_with_protocol (0, 1);
1609 if (tls_fd != -1)
1610 close (tls_fd);
1612 if (tls6_fd != -1)
1613 close (tls6_fd);
1615 tls_fd = -1;
1616 tls6_fd = -1;
1617 return 0;
1620 static int
1621 start_stop_tls (int term)
1623 char *s = config_get_string ("global", "tcp_bind");
1624 int b;
1626 if (!s)
1627 return 0;
1629 if (!strcmp (s, "any"))
1631 b = start_stop_tls_with_protocol (0, term);
1632 if (b)
1633 b = start_stop_tls_with_protocol (1, term);
1635 else if (!strcmp (s, "ipv4"))
1636 b = start_stop_tls_with_protocol (0, term);
1637 else if (!strcmp (s, "ipv6"))
1638 b = start_stop_tls_with_protocol (1, term);
1639 else
1640 b = 0;
1642 xfree (s);
1643 if (!term && b)
1645 if (!x509_cred)
1647 char *tmp = config_get_string ("global", "tls_dh_level");
1648 gpg_error_t rc;
1650 rc = tls_init_params (tmp);
1651 xfree (tmp);
1652 if (rc)
1654 start_stop_tls_with_protocol (0, 1);
1655 return 0;
1659 return 1;
1662 return b;
1664 #endif
1666 #ifdef WITH_GNUTLS
1667 static gpg_error_t
1668 do_tls_accept (time_t *init, struct pollfd *fds)
1670 int regen_interval;
1671 struct sockaddr_storage raddr;
1672 socklen_t slen = sizeof (raddr);
1673 int fd;
1674 char s[INET6_ADDRSTRLEN];
1675 static time_t last;
1677 if (!(fds->revents & POLLIN))
1678 return 0;
1680 regen_interval = config_get_integer ("global", "tls_regen_interval");
1682 fd = accept (fds->fd, (struct sockaddr *) &raddr, &slen);
1683 if (regen_interval > 0
1684 && (*init == 0 || time (NULL) - *init >= regen_interval))
1686 /* Wait 10 seconds before trying key regeneration again. */
1687 if (last && time (NULL) - last < 10)
1689 if (fd != -1)
1691 close (fd);
1692 fd = -1;
1693 errno = 0;
1696 else
1698 gpg_error_t rc;
1700 rc = tls_regenerate ();
1701 if (rc)
1703 if (fd != -1)
1704 close (fd);
1705 last = time (NULL);
1707 else
1709 last = 0;
1710 *init = time (NULL);
1715 if (fd == -1)
1717 int e = errno;
1719 if (errno == EMFILE || errno == ENFILE)
1720 log_write ("%s: %s", __FUNCTION__,
1721 pwmd_strerror (gpg_error_from_syserror()));
1722 else if (errno && errno != EAGAIN)
1725 if (!quit) // probably EBADF
1726 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (e));
1729 return e;
1732 inet_ntop (raddr.ss_family, get_in_addr ((struct sockaddr *) &raddr), s,
1733 sizeof s);
1734 (void) init_client (fd, s);
1735 return 0;
1737 #endif
1739 static void *
1740 accept_thread (void *arg)
1742 int sockfd = *(int *) arg;
1743 #ifdef WITH_GNUTLS
1744 time_t init = 0;
1745 gpg_error_t rc;
1746 #endif
1747 #ifndef HAVE_PTHREAD_CANCEL
1748 int *n = xmalloc (sizeof (int));
1750 *n = 0;
1751 pthread_setspecific (signal_thread_key, n);
1752 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
1753 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1754 #endif
1756 #ifdef WITH_GNUTLS
1757 if (start_stop_tls (0))
1758 init = time (NULL);
1759 #endif
1761 #ifdef HAVE_PR_SET_NAME
1762 prctl (PR_SET_NAME, "accept");
1763 #endif
1764 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
1766 for (;;)
1768 socklen_t slen = sizeof (struct sockaddr_un);
1769 struct sockaddr_un raddr;
1770 int fd, s = 0;
1771 struct pollfd fds[3];
1772 #ifndef HAVE_PTHREAD_CANCEL
1773 int *sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1775 if (*sigusr2)
1776 break;
1777 #endif
1779 memset (fds, 0, sizeof (fds));
1780 fds[s].fd = sockfd;
1781 fds[s++].events = POLLIN;
1783 #ifdef WITH_GNUTLS
1784 if (tls_fd != -1)
1786 fds[s].fd = tls_fd;
1787 fds[s++].events = POLLIN;
1789 else
1790 fds[s].fd = tls_fd;
1792 if (tls6_fd != -1)
1794 fds[s].fd = tls6_fd;
1795 fds[s++].events = POLLIN;
1797 else
1798 fds[s].fd = tls6_fd;
1799 #endif
1801 s = poll (fds, s, 500);
1802 if (s == -1)
1804 if (errno != EINTR)
1805 log_write ("%s", strerror (errno));
1806 break;
1808 else if (s == 0)
1809 continue;
1811 if (fds[0].revents & POLLIN)
1813 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1814 if (fd == -1)
1816 if (errno == EMFILE || errno == ENFILE)
1817 log_write ("%s: %s", __FUNCTION__,
1818 pwmd_strerror (gpg_error_from_errno (errno)));
1819 else if (errno != EAGAIN && errno != EINTR)
1821 if (!quit) // probably EBADF
1822 log_write ("%s: %s", __FUNCTION__,
1823 pwmd_strerror (gpg_error_from_errno (errno)));
1825 break;
1828 continue;
1831 (void) init_client (fd, NULL);
1834 #ifdef WITH_GNUTLS
1835 if (tls_fd != -1 && fds[1].fd == tls_fd)
1836 rc = do_tls_accept (&init, &fds[1]);
1838 if (tls6_fd != -1 && fds[1].fd == tls6_fd)
1839 rc = do_tls_accept (&init, &fds[1]);
1841 if (tls6_fd != -1 && fds[2].fd == tls6_fd)
1842 rc = do_tls_accept (&init, &fds[2]);
1843 #endif
1846 /* Just in case accept() failed for some reason other than EBADF */
1847 quit = 1;
1848 return NULL;
1851 static void *
1852 cache_timer_thread (void *arg)
1854 unsigned k = 0;
1855 #ifndef HAVE_PTHREAD_CANCEL
1856 int *n = xmalloc (sizeof (int));
1858 *n = 0;
1859 pthread_setspecific (signal_thread_key, n);
1860 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
1861 #endif
1863 #ifdef HAVE_PR_SET_NAME
1864 prctl (PR_SET_NAME, "timer");
1865 #endif
1866 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
1868 for (;;)
1870 struct timeval tv = { 1, 0 };
1871 unsigned keepalive = config_get_integer ("global", "keepalive_interval");
1872 #ifndef HAVE_PTHREAD_CANCEL
1873 int *n;
1875 n = (int *) pthread_getspecific (signal_thread_key);
1876 if (*n)
1877 break;
1878 #endif
1880 select (0, NULL, NULL, NULL, &tv);
1881 cache_adjust_timeout ();
1883 if (++k >= keepalive)
1885 send_status_all (STATUS_KEEPALIVE, NULL);
1886 k = 0;
1890 return NULL;
1893 static int
1894 signal_loop (sigset_t sigset)
1896 int done = 0;
1897 int siint = 0;
1901 int sig;
1903 sigwait (&sigset, &sig);
1905 if (sig != SIGQUIT)
1906 log_write (_("caught signal %i (%s)"), sig, strsignal (sig));
1908 switch (sig)
1910 case SIGHUP:
1911 pthread_cond_signal (&rcfile_cond);
1912 break;
1913 case SIGUSR1:
1914 log_write (_("clearing file cache"));
1915 cache_clear (NULL, NULL, 1);
1916 send_status_all (STATUS_CACHE, NULL);
1917 break;
1918 case SIGQUIT:
1919 done = 1;
1920 break;
1921 default:
1922 siint = 1;
1923 done = 1;
1924 break;
1927 while (!done);
1929 return siint;
1932 static void
1933 catchsig (int sig)
1935 log_write (_ ("Caught signal %i (%s). Exiting."), sig, strsignal (sig));
1936 #ifdef HAVE_BACKTRACE
1937 BACKTRACE (__FUNCTION__);
1938 #endif
1939 longjmp (jmp, 1);
1942 static void *
1943 waiting_for_exit (void *arg)
1945 int last = 0;
1946 #ifndef HAVE_PTHREAD_CANCEL
1947 int *n = xmalloc (sizeof (int));
1949 *n = 0;
1950 pthread_setspecific (signal_thread_key, n);
1951 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
1952 #endif
1954 #ifdef HAVE_PR_SET_NAME
1955 prctl (PR_SET_NAME, "exiting");
1956 #endif
1957 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
1958 log_write (_("waiting for all clients to disconnect"));
1959 MUTEX_LOCK (&quit_mutex);
1960 pthread_cleanup_push (cleanup_mutex_cb, &quit_mutex);
1962 for (;;)
1964 struct timespec ts;
1965 int n;
1967 MUTEX_LOCK (&cn_mutex);
1968 n = slist_length (cn_thread_list);
1969 MUTEX_UNLOCK (&cn_mutex);
1970 if (!n)
1971 break;
1973 #ifndef HAVE_PTHREAD_CANCEL
1974 int *s = (int *) pthread_getspecific (signal_thread_key);
1975 if (*s)
1976 break;
1977 #endif
1979 if (last != n)
1981 log_write (_("%i clients remain"), n);
1982 last = n;
1985 INIT_TIMESPEC (SIG_TIMEOUT, ts);
1986 pthread_cond_timedwait (&quit_cond, &quit_mutex, &ts);
1989 kill (getpid (), SIGQUIT);
1990 pthread_cleanup_pop (1);
1991 return NULL;
1994 static int
1995 server_loop (int sockfd, char **socketpath)
1997 pthread_t cache_timeout_tid;
1998 int cancel_timeout_thread = 0, cancel_accept_thread = 0;
1999 sigset_t sigset;
2000 int n;
2001 int segv = 0;
2002 gpg_error_t rc;
2004 init_commands ();
2005 sigemptyset (&sigset);
2007 /* Termination */
2008 sigaddset (&sigset, SIGTERM);
2009 sigaddset (&sigset, SIGINT);
2011 /* Clears the file cache. */
2012 sigaddset (&sigset, SIGUSR1);
2014 /* Configuration file reloading. */
2015 sigaddset (&sigset, SIGHUP);
2017 /* For exiting cleanly. */
2018 sigaddset (&sigset, SIGQUIT);
2020 #ifndef HAVE_PTHREAD_CANCEL
2022 The socket, cache and rcfile threads use this signal when
2023 pthread_cancel() is unavailable. Prevent the main thread from
2024 catching this signal from another process.
2026 sigaddset (&sigset, SIGUSR2);
2027 #endif
2029 /* An assertion failure. */
2030 signal (SIGABRT, catchsig);
2031 sigaddset (&sigset, SIGABRT);
2032 sigprocmask (SIG_BLOCK, &sigset, NULL);
2034 #ifndef HAVE_PTHREAD_CANCEL
2035 /* Remove this signal from the watched signals in signal_loop(). */
2036 sigdelset (&sigset, SIGUSR2);
2037 #endif
2039 /* Can show a backtrace of the stack in the log. */
2040 signal (SIGSEGV, catchsig);
2042 pthread_mutex_init (&quit_mutex, NULL);
2043 pthread_cond_init (&quit_cond, NULL);
2044 char *p = get_username (getuid());
2045 log_write (_("%s started for user %s"), PACKAGE_STRING, p);
2046 xfree (p);
2048 #ifdef WITH_GNUTLS
2049 if (config_get_boolean ("global", "enable_tcp"))
2050 log_write (_("Listening on %s and TCP port %i"), *socketpath,
2051 config_get_integer ("global", "tcp_port"));
2052 else
2053 log_write (_("Listening on %s"), *socketpath);
2054 #else
2055 log_write (_("Listening on %s"), *socketpath);
2056 #endif
2058 rc = create_thread (reload_rcfile_thread, NULL, &rcfile_tid, 0);
2059 if (rc)
2061 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2062 pwmd_strerror (rc));
2063 goto done;
2066 rc = create_thread (cache_timer_thread, NULL, &cache_timeout_tid, 0);
2067 if (rc)
2069 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2070 pwmd_strerror (rc));
2071 goto done;
2074 cancel_timeout_thread = 1;
2075 rc = create_thread (accept_thread, &sockfd, &accept_tid, 0);
2076 if (rc)
2078 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2079 pwmd_strerror (rc));
2080 goto done;
2083 cancel_accept_thread = 1;
2084 if (!setjmp (jmp))
2085 signal_loop (sigset);
2086 else
2087 segv = 1;
2089 done:
2091 * We're out of the main server loop. This happens when a signal was sent
2092 * to terminate the daemon. We'll wait for all clients to disconnect
2093 * before exiting but exit immediately if another termination signal is
2094 * sent.
2096 if (cancel_accept_thread)
2098 #ifdef HAVE_PTHREAD_CANCEL
2099 int n = pthread_cancel (accept_tid);
2100 #else
2101 int n = pthread_kill (accept_tid, SIGUSR2);
2102 #endif
2103 if (!n)
2104 pthread_join (accept_tid, NULL);
2107 if (cancel_timeout_thread)
2109 #ifdef HAVE_PTHREAD_CANCEL
2110 n = pthread_cancel (cache_timeout_tid);
2111 #else
2112 n = pthread_kill (cache_timeout_tid, SIGUSR2);
2113 #endif
2114 if (!n)
2115 pthread_join (cache_timeout_tid, NULL);
2118 #ifdef WITH_GNUTLS
2119 start_stop_tls (1);
2120 #endif
2121 shutdown (sockfd, SHUT_RDWR);
2122 close (sockfd);
2123 unlink (*socketpath);
2124 xfree (*socketpath);
2125 *socketpath = NULL;
2126 MUTEX_LOCK (&cn_mutex);
2127 n = slist_length (cn_thread_list);
2128 MUTEX_UNLOCK (&cn_mutex);
2130 if (n && !segv)
2132 pthread_t tid;
2134 rc = create_thread (waiting_for_exit, NULL, &tid, 0);
2135 if (!rc)
2137 if (signal_loop (sigset))
2139 log_write (_("Received second termination request. Exiting."));
2140 #ifdef HAVE_PTHREAD_CANCEL
2141 pthread_cancel (tid);
2142 #else
2143 pthread_kill (tid, SIGUSR2);
2144 #endif
2145 pthread_join (tid, NULL);
2148 else
2149 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2150 pwmd_strerror (rc));
2153 cleanup_all_clients (0);
2154 deinit_commands ();
2155 pthread_cond_destroy (&quit_cond);
2156 pthread_mutex_destroy (&quit_mutex);
2157 return segv ? EXIT_FAILURE : EXIT_SUCCESS;;
2160 static void
2161 startup_failure ()
2163 log_write (_
2164 ("Failed to add a file to the cache. Use --force to force startup. Exiting."));
2165 cache_clear (NULL, NULL, 1);
2168 static void
2169 usage (const char *pn, int status)
2171 FILE *fp = status == EXIT_FAILURE ? stderr : stdout;
2173 fprintf (fp, _("Usage: %s [OPTIONS] [file1] [...]\n"
2174 " --debug=[a:..][,g:N][,t:N] enable debugging (a:[ixedsc],g:[1-9],t:[0-N])\n"
2175 " -f, --rcfile=filename load the specfied configuration file\n"
2176 " (~/.pwmd/config)\n"
2177 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2178 " --kill terminate an existing instance of pwmd\n"
2179 " -n, --no-fork run as a foreground process\n"
2180 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2181 " --ignore, --force ignore file errors during startup\n"
2182 " -o, --outfile=filename output file when importing or converting\n"
2183 " -C, --convert=filename convert a version 2 data file to version 3\n"
2184 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2185 " -k, --passphrase-file=file for use when importing or converting\n"
2186 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2187 " converting\n"
2188 " --no-passphrase when importing or converting\n"
2189 " --keyid=keyID[,..] public key to use when encrypting\n"
2190 " --sign-keyid=fpr[,..] fingerprint of the signing key to use\n"
2191 " --symmetric use conventional encryption with optional signer\n"
2192 " --keyparam=filename custom key parameters to use (gpg default)\n"
2193 " --help this help text\n"
2194 " --version show version and compile time features\n"),
2195 pn);
2196 exit (status);
2199 static void
2200 unlink_stale_socket (const char *sock, const char *pidfile)
2202 log_write (_ ("removing stale socket %s"), sock);
2203 unlink (sock);
2204 unlink (pidfile);
2207 static int
2208 test_pidfile (const char *path, const char *sock, char *buf, size_t buflen,
2209 char **pidfile, int create, mode_t mode, int terminate)
2211 pid_t pid;
2212 int fd;
2213 size_t len;
2215 if (!create)
2217 snprintf (buf, buflen, "%s/%s.pid", homedir, sock);
2218 *pidfile = str_dup (buf);
2219 fd = open (buf, O_RDONLY);
2221 else
2222 fd = open (*pidfile, O_CREAT|O_WRONLY|O_TRUNC, mode);
2224 if (fd == -1)
2226 if (!create && errno != ENOENT)
2228 log_write ("%s: %s", buf, pwmd_strerror (errno));
2229 free (*pidfile);
2230 *pidfile = NULL;
2231 return -1;
2233 else if (!create && !terminate)
2234 return 0;
2236 log_write ("%s: %s", *pidfile, strerror (errno));
2237 return -1;
2240 if (create)
2242 snprintf (buf, buflen, "%i", getpid ());
2243 ssize_t ret = write (fd, buf, strlen (buf));
2244 if (ret == -1)
2245 log_write ("%s (%i): %s", __FUNCTION__, __LINE__,
2246 pwmd_strerror (gpg_error_from_syserror ()));
2247 close (fd);
2248 return 0;
2251 len = read (fd, buf, buflen);
2252 close (fd);
2253 if (len == 0)
2255 unlink_stale_socket (path, *pidfile);
2256 return 0;
2259 if (sscanf (buf, "%5i", &pid) != 1 || pid == 0)
2261 if (!terminate)
2263 unlink_stale_socket (path, *pidfile);
2264 return 0;
2268 if (kill (pid, 0) == -1)
2270 unlink_stale_socket (path, *pidfile);
2271 return 0;
2274 if (terminate)
2276 if (kill (pid, SIGTERM) == -1)
2277 log_write ("%s: %s", path, pwmd_strerror (errno));
2279 else
2280 log_write (_ ("an instance for socket %s is already running"), path);
2282 xfree (*pidfile);
2283 *pidfile = NULL;
2284 return 1;
2287 static unsigned
2288 parse_debug_level (const char *str, unsigned *debug, int *gpgme, int *tls)
2290 const char *p;
2291 unsigned level = 0;
2292 int gl = 0, tl = 0;
2294 for (p = str; p && *p; p++)
2296 if (*p == 'a') // assuan debug flags
2298 if (*++p != ':')
2299 return 1;
2301 while (*++p)
2303 switch (*p)
2305 case 'i':
2306 level |= ASSUAN_LOG_INIT;
2307 break;
2308 case 'x':
2309 level |= ASSUAN_LOG_CTX;
2310 break;
2311 case 'e':
2312 level |= ASSUAN_LOG_ENGINE;
2313 break;
2314 case 'd':
2315 level |= ASSUAN_LOG_DATA;
2316 break;
2317 case 's':
2318 level |= ASSUAN_LOG_SYSIO;
2319 break;
2320 case 'c':
2321 level |= ASSUAN_LOG_CONTROL;
2322 break;
2323 case ',':
2324 break;
2325 default:
2326 return 1;
2329 if (*p == ',')
2330 break;
2333 if (!*p)
2334 break;
2336 else if (*p == 'g' || *p == 't') // gpgme and TLS debug level
2338 int t = *p == 't';
2339 int n;
2341 if (*++p != ':')
2342 return 1;
2344 if (!isdigit (*++p))
2345 return 1;
2347 n = atoi (p);
2348 if (t)
2349 tl = n;
2350 else
2351 gl = n;
2353 if (tl < 0 || gl < 0 || gl > 9)
2354 return 1;
2356 while (isdigit (*p))
2357 p++;
2359 p--;
2360 if (*(p+1) && *(p+1) != ',')
2361 return 1;
2362 else if (*(p+1))
2363 p++;
2365 else
2366 return 1;
2369 if (tl)
2370 *tls = tl;
2372 if (gl)
2373 *gpgme = gl;
2375 *debug = level;
2376 return 0;
2380 main (int argc, char *argv[])
2382 int opt;
2383 struct sockaddr_un addr;
2384 char buf[PATH_MAX];
2385 char *socketpath = NULL, *socketdir, *socketname = NULL;
2386 char *socketarg = NULL;
2387 char *datadir = NULL;
2388 char *pidfile = NULL;
2389 mode_t mode = 0600;
2390 int x;
2391 char *p;
2392 char **cache_push = NULL;
2393 char *import = NULL, *keyid = NULL, *sign_keyid = NULL;
2394 char *keyparam = NULL;
2395 int estatus = EXIT_FAILURE;
2396 int sockfd;
2397 char *outfile = NULL;
2398 int do_unlink = 0;
2399 int secure = 0;
2400 int show_version = 0;
2401 int force = 0;
2402 gpg_error_t rc;
2403 char *keyfile = NULL;
2404 int exists;
2405 int optindex;
2406 int terminate = 0;
2407 int sym = 0;
2408 int gpgme_level = -1;
2409 int tls_level = -1;
2410 /* Must maintain the same order as longopts[] */
2411 enum
2413 OPT_VERSION, OPT_HELP, OPT_HOMEDIR, OPT_NO_FORK, OPT_DISABLE_DUMP,
2414 OPT_FORCE, OPT_RCFILE, OPT_PASSPHRASE_FILE, OPT_IMPORT, OPT_OUTFILE,
2415 OPT_KEYID, OPT_SIGN_KEYID, OPT_SYMMETRIC, OPT_KEYPARAM, OPT_KILL,
2416 OPT_DEBUG
2418 const char *optstring = "nf:C:k:I:o:s";
2419 const struct option longopts[] = {
2420 {"version", no_argument, 0, 0},
2421 {"help", no_argument, 0, 0},
2422 {"homedir", required_argument, 0, 0},
2423 {"no-fork", no_argument, 0, 'n'},
2424 {"disable_dump", no_argument, 0, 0},
2425 {"force", no_argument, 0, 0},
2426 {"rcfile", required_argument, 0, 'f'},
2427 {"passphrase-file", required_argument, 0, 'k'},
2428 {"import", required_argument, 0, 'I'},
2429 {"outfile", required_argument, 0, 'o'},
2430 {"keyid", required_argument, 0, 0},
2431 {"sign-keyid", required_argument, 0, 0},
2432 {"symmetric", no_argument, 0, 's'},
2433 {"keyparam", required_argument, 0, 0},
2434 {"kill", no_argument, 0, 0},
2435 {"debug", required_argument, 0, 0},
2436 {0, 0, 0, 0}
2439 log_fd = -1;
2440 cmdline = 1;
2442 #ifndef DEBUG
2443 #ifdef HAVE_SETRLIMIT
2444 struct rlimit rl;
2446 rl.rlim_cur = rl.rlim_max = 0;
2448 if (setrlimit (RLIMIT_CORE, &rl) != 0)
2449 err (EXIT_FAILURE, "setrlimit()");
2450 #endif
2452 #ifdef HAVE_PR_SET_DUMPABLE
2453 prctl (PR_SET_DUMPABLE, 0);
2454 #endif
2455 #endif
2457 #ifdef ENABLE_NLS
2458 setlocale (LC_ALL, "");
2459 bindtextdomain ("pwmd", LOCALEDIR);
2460 textdomain ("pwmd");
2461 #endif
2463 if (setup_crypto ())
2464 exit (EXIT_FAILURE);
2466 #ifdef WITH_GNUTLS
2467 tls_level = tls_level == -1 ? 1 : tls_level;
2468 gnutls_global_set_log_level (tls_level);
2469 tls_fd = -1;
2470 tls6_fd = -1;
2471 #endif
2472 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
2473 xmlInitMemory ();
2474 xmlInitGlobals ();
2475 xmlInitParser ();
2476 xmlXPathInit ();
2478 while ((opt = getopt_long (argc, argv, optstring, longopts, &optindex))
2479 != -1)
2481 switch (opt)
2483 case 'I':
2484 import = optarg;
2485 break;
2486 case 'k':
2487 keyfile = optarg;
2488 break;
2489 case 'o':
2490 outfile = optarg;
2491 break;
2492 case 'D':
2493 secure = 1;
2494 break;
2495 case 'n':
2496 nofork = 1;
2497 break;
2498 case 'f':
2499 rcfile = str_dup (optarg);
2500 break;
2501 case 's':
2502 sym = 1;
2503 break;
2504 default:
2505 usage (argv[0], EXIT_FAILURE);
2506 break;
2507 case 0:
2508 switch (optindex)
2510 case OPT_DEBUG:
2511 if (parse_debug_level (optarg, &assuan_level, &gpgme_level,
2512 &tls_level))
2513 usage (argv[0], EXIT_FAILURE);
2514 break;
2515 case OPT_SYMMETRIC:
2516 sym = 1;
2517 break;
2518 case OPT_VERSION:
2519 show_version = 1;
2520 break;
2521 case OPT_HELP:
2522 usage (argv[0], EXIT_SUCCESS);
2523 break;
2524 case OPT_HOMEDIR:
2525 homedir = str_dup (optarg);
2526 break;
2527 case OPT_NO_FORK:
2528 nofork = 1;
2529 break;
2530 case OPT_DISABLE_DUMP:
2531 secure = 1;
2532 break;
2533 case OPT_FORCE:
2534 force = 1;
2535 break;
2536 case OPT_RCFILE:
2537 rcfile = str_dup (optarg);
2538 break;
2539 case OPT_PASSPHRASE_FILE:
2540 keyfile = optarg;
2541 break;
2542 case OPT_IMPORT:
2543 import = optarg;
2544 break;
2545 case OPT_OUTFILE:
2546 outfile = optarg;
2547 break;
2548 case OPT_KEYID:
2549 keyid = optarg;
2550 break;
2551 case OPT_SIGN_KEYID:
2552 sign_keyid = optarg;
2553 break;
2554 case OPT_KEYPARAM:
2555 keyparam = optarg;
2556 break;
2557 case OPT_KILL:
2558 terminate = 1;
2559 break;
2560 default:
2561 usage (argv[0], EXIT_FAILURE);
2566 if (show_version)
2568 printf (_("%s\n\n"
2569 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016\n"
2570 "%s\n"
2571 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2572 "Compile time features:\n%s"), PACKAGE_STRING,
2573 PACKAGE_BUGREPORT,
2574 #ifdef PWMD_HOMEDIR
2575 "+PWMD_HOMEDIR=" PWMD_HOMEDIR "\n"
2576 #endif
2577 #ifdef WITH_GNUTLS
2578 "+WITH_GNUTLS\n"
2579 #else
2580 "-WITH_GNUTLS\n"
2581 #endif
2582 #ifdef WITH_LIBACL
2583 "+WITH_LIBACL\n"
2584 #else
2585 "-WITH_LIBACL\n"
2586 #endif
2587 #ifdef DEBUG
2588 "+DEBUG\n"
2589 #else
2590 "-DEBUG\n"
2591 #endif
2592 #ifdef MEM_DEBUG
2593 "+MEM_DEBUG\n"
2594 #else
2595 "-MEM_DEBUG\n"
2596 #endif
2597 #ifdef MUTEX_DEBUG
2598 "+MUTEX_DEBUG\n"
2599 #else
2600 "-MUTEX_DEBUG\n"
2601 #endif
2603 exit (EXIT_SUCCESS);
2606 if (!homedir)
2607 #ifdef PWMD_HOMEDIR
2608 homedir = str_dup(PWMD_HOMEDIR);
2609 #else
2610 homedir = str_asprintf ("%s/.pwmd", get_home_dir());
2611 #endif
2613 if (mkdir (homedir, 0700) == -1 && errno != EEXIST)
2614 err (EXIT_FAILURE, "%s", homedir);
2616 if (!rcfile)
2617 rcfile = str_asprintf ("%s/config", homedir);
2619 pthread_key_create (&last_error_key, free_key);
2620 #ifndef HAVE_PTHREAD_CANCEL
2621 pthread_key_create (&signal_thread_key, free_key);
2622 #endif
2624 pthread_mutexattr_t attr;
2625 pthread_mutexattr_init (&attr);
2626 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
2627 pthread_mutex_init (&rcfile_mutex, &attr);
2628 global_config = config_parse (rcfile, 0);
2629 if (!global_config)
2631 pthread_mutexattr_destroy (&attr);
2632 pthread_mutex_destroy (&rcfile_mutex);
2633 exit (EXIT_FAILURE);
2636 p = config_get_string ("global", "gpg_homedir");
2637 if (!p)
2638 datadir = str_asprintf ("%s/.gnupg", homedir);
2639 else
2640 datadir = expand_homedir (p);
2642 xfree (p);
2643 if (mkdir (datadir, 0700) == -1 && errno != EEXIST)
2644 err (EXIT_FAILURE, "%s", datadir);
2646 if (gpgme_level != -1)
2648 char s[2] = { gpgme_level + '0', 0 };
2650 if (getenv ("GPGME_DEBUG"))
2651 log_write (_ ("Overriding GPGME_DEBUG environment with level %u!"),
2652 gpgme_level);
2654 gpgme_set_global_flag ("debug", s);
2657 rc = gpgme_set_engine_info (GPGME_PROTOCOL_OpenPGP, NULL, datadir);
2658 xfree (datadir);
2660 snprintf (buf, sizeof (buf), "%s/data", homedir);
2661 if (mkdir (buf, 0700) == -1 && errno != EEXIST)
2662 err (EXIT_FAILURE, "%s", buf);
2664 datadir = str_dup (buf);
2665 pthread_cond_init (&rcfile_cond, NULL);
2666 pthread_mutex_init (&cn_mutex, &attr);
2667 pthread_mutexattr_destroy (&attr);
2669 setup_logging ();
2671 x = config_get_int_param (global_config, "global", "priority", &exists);
2672 if (exists && x != atoi(INVALID_PRIORITY))
2674 errno = 0;
2675 if (setpriority (PRIO_PROCESS, 0, x) == -1)
2677 log_write ("setpriority(): %s",
2678 pwmd_strerror (gpg_error_from_errno (errno)));
2679 goto do_exit;
2682 #ifdef HAVE_MLOCKALL
2683 if (disable_mlock == 0 && mlockall (MCL_CURRENT | MCL_FUTURE) == -1)
2685 log_write ("mlockall(): %s",
2686 pwmd_strerror (gpg_error_from_errno (errno)));
2687 goto do_exit;
2689 #endif
2691 rc = cache_init ();
2692 if (rc)
2694 log_write ("pwmd: ERR %i: %s", rc, pwmd_strerror (rc));
2695 exit (EXIT_FAILURE);
2698 if (import)
2700 char **keyids = NULL, **sign_keyids = NULL;
2702 if (!outfile || !*outfile || argc != optind)
2703 usage (argv[0], EXIT_FAILURE);
2705 if (keyid)
2706 keyids = str_split (keyid, ",", 0);
2707 if (sign_keyid)
2708 sign_keyids = str_split (sign_keyid, ",", 0);
2709 rc = xml_import (import, outfile, keyids, sign_keyids, keyfile, keyparam, sym);
2710 strv_free (keyids);
2711 strv_free (sign_keyids);
2712 if (rc)
2714 if (gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
2715 rc = gpg_error (rc);
2717 log_write ("%s: %u: %s", import, rc, pwmd_strerror (rc));
2720 config_free (global_config);
2721 xfree (rcfile);
2722 exit (rc ? EXIT_FAILURE : EXIT_SUCCESS);
2725 p = config_get_string ("global", "socket_path");
2726 if (!p)
2727 p = str_asprintf ("%s/socket", homedir);
2729 socketarg = expand_homedir (p);
2730 xfree (p);
2732 if (!secure)
2733 disable_list_and_dump = config_get_boolean ("global",
2734 "disable_list_and_dump");
2735 else
2736 disable_list_and_dump = secure;
2738 cache_push = config_get_list ("global", "cache_push");
2740 while (optind < argc)
2742 if (strv_printf (&cache_push, "%s", argv[optind++]) == 0)
2743 errx (EXIT_FAILURE, "%s", pwmd_strerror (GPG_ERR_ENOMEM));
2746 if (strchr (socketarg, '/') == NULL)
2748 socketdir = getcwd (buf, sizeof (buf));
2749 socketname = str_dup (socketarg);
2750 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2752 else
2754 socketname = str_dup (strrchr (socketarg, '/'));
2755 socketname++;
2756 socketarg[strlen (socketarg) - strlen (socketname) - 1] = 0;
2757 socketdir = str_dup (socketarg);
2758 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2761 if (chdir (datadir))
2763 log_write ("%s: %s", datadir,
2764 pwmd_strerror (gpg_error_from_errno (errno)));
2765 unlink (socketpath);
2766 goto do_exit;
2769 x = test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 0,
2770 mode, terminate);
2771 if (!terminate && x)
2772 goto do_exit;
2773 else if (terminate)
2775 estatus = x != 1 ? EXIT_FAILURE : EXIT_SUCCESS;
2776 goto do_exit;
2780 * bind() doesn't like the full pathname of the socket or any non alphanum
2781 * characters so change to the directory where the socket is wanted then
2782 * create it then change to datadir.
2784 if (chdir (socketdir))
2786 log_write ("%s: %s", socketdir,
2787 pwmd_strerror (gpg_error_from_errno (errno)));
2788 goto do_exit;
2791 xfree (socketdir);
2793 if ((sockfd = socket (PF_UNIX, SOCK_STREAM, 0)) == -1)
2795 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2796 goto do_exit;
2799 addr.sun_family = AF_UNIX;
2800 snprintf (addr.sun_path, sizeof (addr.sun_path), "%s", socketname);
2801 do_unlink = 1;
2802 if (bind (sockfd, (struct sockaddr *) &addr, sizeof (struct sockaddr)) ==
2805 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2807 if (errno == EADDRINUSE)
2809 do_unlink = 0;
2810 log_write (_("Either there is another pwmd running or '%s' is a \n"
2811 "stale socket. Please remove it manually."), socketpath);
2814 goto do_exit;
2818 char *t = config_get_string ("global", "socket_perms");
2819 mode_t mask;
2821 if (t)
2823 mode = strtol (t, NULL, 8);
2824 mask = umask (0);
2825 xfree (t);
2827 if (chmod (socketname, mode) == -1)
2829 log_write ("%s: %s", socketname,
2830 pwmd_strerror (gpg_error_from_errno (errno)));
2831 close (sockfd);
2832 umask (mask);
2833 goto do_exit;
2836 umask (mask);
2840 xfree (--socketname);
2842 if (chdir (datadir))
2844 log_write ("%s: %s", datadir,
2845 pwmd_strerror (gpg_error_from_errno (errno)));
2846 close (sockfd);
2847 goto do_exit;
2850 xfree (datadir);
2853 * Set the cache entry for a file. Prompts for the password.
2855 if (cache_push)
2857 for (opt = 0; cache_push[opt]; opt++)
2859 struct crypto_s *crypto = NULL;
2860 char *pw_file = config_get_string (cache_push[opt],
2861 "passphrase_file");
2862 gpg_error_t rc = crypto_init (&crypto, NULL, cache_push[opt],
2863 pw_file != NULL, pw_file);
2865 if (!rc)
2867 crypto->flags |= pw_file ? CRYPTO_FLAG_KEYFILE : 0;
2868 crypto->keyfile = pw_file;
2870 else
2871 xfree (pw_file);
2873 if (rc)
2875 estatus = EXIT_FAILURE;
2876 goto do_exit;
2879 rc = do_cache_push (crypto);
2880 if (rc && !force)
2882 log_write ("ERR %u: %s", rc, pwmd_strerror(rc));
2883 strv_free (cache_push);
2884 startup_failure ();
2885 estatus = EXIT_FAILURE;
2886 crypto_free (crypto);
2887 goto do_exit;
2889 else if (rc)
2890 log_write ("%s: %s", crypto->filename, pwmd_strerror(rc));
2891 else
2892 log_write (_("Successfully added '%s' to the cache."),
2893 crypto->filename);
2895 crypto_free (crypto);
2898 strv_free (cache_push);
2899 log_write (!nofork ? _("Done. Daemonizing...") :
2900 _("Done. Waiting for connections..."));
2903 if (listen (sockfd, 128) == -1)
2905 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2906 goto do_exit;
2909 if (!nofork)
2911 switch (fork ())
2913 case -1:
2914 log_write ("fork(): %s",
2915 pwmd_strerror (gpg_error_from_errno (errno)));
2916 goto do_exit;
2917 case 0:
2918 close (0);
2919 close (1);
2920 close (2);
2921 setsid ();
2922 break;
2923 default:
2924 _exit (EXIT_SUCCESS);
2928 (void)test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 1,
2929 mode, 0);
2930 cmdline = 0;
2931 pthread_key_create (&thread_name_key, free_key);
2932 estatus = server_loop (sockfd, &socketpath);
2934 do_exit:
2935 if (socketpath && do_unlink)
2937 unlink (socketpath);
2938 xfree (socketpath);
2941 xfree (socketarg);
2942 #ifdef WITH_GNUTLS
2943 gnutls_global_deinit ();
2944 tls_deinit_params ();
2945 #endif
2946 if (rcfile_tid)
2948 #ifdef HAVE_PTHREAD_CANCEL
2949 pthread_cancel (rcfile_tid);
2950 #else
2951 pthread_kill (rcfile_tid, SIGUSR2);
2952 pthread_cond_signal (&rcfile_cond);
2953 #endif
2954 pthread_join (rcfile_tid, NULL);
2957 pthread_cond_destroy (&rcfile_cond);
2958 pthread_mutex_destroy (&rcfile_mutex);
2959 pthread_key_delete (last_error_key);
2960 #ifndef HAVE_PTHREAD_CANCEL
2961 pthread_key_delete (signal_thread_key);
2962 #endif
2964 if (global_config)
2965 config_free (global_config);
2967 free_invoking_users (invoking_users);
2968 xfree (rcfile);
2969 xfree (home_directory);
2970 xfree (homedir);
2971 xmlCleanupParser ();
2972 xmlCleanupGlobals ();
2974 if (pidfile)
2975 unlink (pidfile);
2976 xfree (pidfile);
2978 if (estatus == EXIT_SUCCESS && !terminate)
2979 log_write (_("pwmd exiting normally"));
2981 pthread_key_delete (thread_name_key);
2982 closelog ();
2984 if (log_fd != -1)
2985 close (log_fd);
2987 exit (estatus);
2990 gpg_error_t lock_flock (assuan_context_t ctx, const char *filename,
2991 int type, int *fd)
2993 gpg_error_t rc = 0;
2995 #ifdef HAVE_FLOCK
2996 *fd = open (filename, O_RDONLY);
2997 if (*fd == -1)
2998 return gpg_error_from_syserror ();
3000 TRY_FLOCK (ctx, *fd, type, rc);
3001 if (rc)
3003 close (*fd);
3004 *fd = -1;
3006 #endif
3008 return rc;
3011 void unlock_flock (int *fd)
3013 #ifdef HAVE_FLOCK
3014 if (*fd != -1)
3015 close (*fd);
3017 *fd = -1;
3018 #endif