Cancel all threads upon SIGTERM without waiting.
[pwmd.git] / src / pwmd.c
blobfcd45567645e4a0620a420dca90a519712e3aa83
1 /*
2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015,
3 2016
4 Ben Kibbey <bjk@luxsci.net>
6 This file is part of pwmd.
8 Pwmd is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 2 of the License, or
11 (at your option) any later version.
13 Pwmd is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
21 #ifdef HAVE_CONFIG_H
22 #include <config.h>
23 #endif
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <err.h>
29 #include <ctype.h>
30 #include <string.h>
31 #include <sys/socket.h>
32 #include <sys/un.h>
33 #include <signal.h>
34 #include <stdarg.h>
35 #include <string.h>
36 #include <sys/wait.h>
37 #include <fcntl.h>
38 #include <pwd.h>
39 #include <grp.h>
40 #include <pthread.h>
41 #include <sys/mman.h>
42 #include <termios.h>
43 #include <assert.h>
44 #include <syslog.h>
45 #include <netinet/in.h>
46 #include <arpa/inet.h>
47 #include <netdb.h>
48 #include <sys/time.h>
49 #include <sys/resource.h>
50 #include <setjmp.h>
51 #include <errno.h>
52 #include <poll.h>
54 #ifdef TM_IN_SYS_TIME
55 #include <sys/time.h>
56 #else
57 #include <time.h>
58 #endif
60 #ifdef HAVE_LIMITS_H
61 #include <limits.h>
62 #endif
64 #ifdef HAVE_GETOPT_LONG
65 #ifdef HAVE_GETOPT_H
66 #include <getopt.h>
67 #endif
68 #else
69 #include "getopt_long.h"
70 #endif
72 #ifdef HAVE_PR_SET_NAME
73 #include <sys/prctl.h>
74 #endif
76 #include "pwmd-error.h"
77 #include <gcrypt.h>
79 #include "util-misc.h"
80 #include "mem.h"
81 #include "xml.h"
82 #include "common.h"
83 #include "commands.h"
84 #include "cache.h"
85 #include "util-string.h"
86 #include "mutex.h"
87 #include "rcfile.h"
88 #include "crypto.h"
90 /* In tenths of a second. */
91 #define SIG_TIMEOUT 1
93 /* For (tcp_)accept_thread (usec). */
94 #define ACCEPT_TIMEOUT 50000
96 static int quit;
97 static int cmdline;
98 static jmp_buf jmp;
99 static int nofork;
100 static int log_fd;
101 static unsigned assuan_level;
103 pthread_t accept_tid;
104 #ifdef WITH_GNUTLS
105 static int tls_fd;
106 static int tls6_fd;
107 static int start_stop_tls (int term);
108 #endif
110 static gpg_error_t do_cache_push (struct crypto_s *crypto);
111 static int signal_loop (sigset_t sigset);
113 #ifndef HAVE_PTHREAD_CANCEL
114 #define INIT_SIGNAL(s, cb) do { \
115 int *n = xmalloc (sizeof (int)); \
116 *n = 0; \
117 pthread_setspecific (signal_thread_key, n); \
118 struct sigaction act; \
119 sigset_t sigset; \
120 sigemptyset (&sigset); \
121 sigaddset (&sigset, s); \
122 pthread_sigmask (SIG_UNBLOCK, &sigset, NULL); \
123 memset (&act, 0, sizeof(act)); \
124 act.sa_flags = SA_SIGINFO; \
125 act.sa_mask = sigset; \
126 act.sa_sigaction = cb; \
127 sigaction (s, &act, NULL); \
128 } while (0)
129 #endif
131 #ifndef HAVE_PTHREAD_CANCEL
132 static void
133 catch_thread_signal (int sig, siginfo_t *info, void *ctx)
135 int *n = (int *) pthread_getspecific (signal_thread_key);
137 *n = 1;
139 #endif
141 static void
142 setup_logging ()
144 int n = config_get_boolean ("global", "enable_logging");
146 if (n)
148 char *p = config_get_string ("global", "log_path");
150 if (!p || (logfile && p && log_fd != -1 && strcmp(p, logfile)))
152 if (log_fd != -1)
153 close (log_fd);
155 log_fd = -1;
158 xfree (logfile);
159 logfile = NULL;
160 if (p)
161 logfile = expand_homedir (p);
162 xfree (p);
164 else
166 xfree (logfile);
167 logfile = NULL;
168 if (log_fd != -1)
169 close(log_fd);
171 log_fd = -1;
172 closelog ();
175 log_syslog = config_get_boolean ("global", "syslog");
176 if (log_syslog == 1)
177 openlog ("pwmd", LOG_NDELAY | LOG_PID, LOG_DAEMON);
180 static void *
181 reload_rcfile_thread (void *arg)
183 #ifndef HAVE_PTHREAD_CANCEL
184 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
185 #endif
187 #ifdef HAVE_PR_SET_NAME
188 prctl (PR_SET_NAME, "reload rcfile");
189 #endif
190 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
191 MUTEX_LOCK (&rcfile_mutex);
193 for (;;)
195 struct slist_s *keep = NULL;
196 struct slist_s *config;
197 int b = disable_list_and_dump;
198 #ifdef WITH_GNUTLS
199 char *prio;
200 char *prio2 = NULL;
201 #endif
203 pthread_cleanup_push (release_mutex_cb, &rcfile_mutex);
204 pthread_cond_wait (&rcfile_cond, &rcfile_mutex);
205 TEST_CANCEL ();
206 keep = config_keep_save ();
207 log_write (_("reloading configuration file '%s'"), rcfile);
209 prio = config_get_string ("global", "tls_cipher_suite");
210 config = config_parse (rcfile, 1);
211 if (config)
213 config_free (global_config);
214 global_config = config;
215 setup_logging ();
218 config_keep_restore (keep);
219 disable_list_and_dump = !disable_list_and_dump ? b : 1;
221 #ifdef WITH_GNUTLS
222 /* Restart listening sockets since they may have changed. */
223 start_stop_tls (1);
224 start_stop_tls (0);
226 prio2 = config_get_string ("global", "tls_cipher_suite");
227 if ((prio2 && (!prio || strcmp (prio, prio2))) || (prio && !prio2))
228 tls_rehandshake ();
230 xfree (prio2);
231 xfree (prio);
232 #endif
233 crypto_set_keepalive ();
234 pthread_cleanup_pop (0);
237 MUTEX_UNLOCK (&rcfile_mutex);
238 return NULL;
241 gpg_error_t
242 send_error (assuan_context_t ctx, gpg_error_t e)
244 struct client_s *client = assuan_get_pointer (ctx);
246 if (gpg_err_source (e) == GPG_ERR_SOURCE_UNKNOWN)
247 e = gpg_error (e);
249 if (client)
250 client->last_rc = e;
252 if (!e)
253 return assuan_process_done (ctx, 0);
255 if (!ctx)
257 log_write ("ERR %i: %s", e, pwmd_strerror (e));
258 return e;
261 if (client && client->xml_error)
263 log_write ("%s", client->xml_error->message);
264 xfree (client->last_error);
265 client->last_error = NULL;
266 if (client->xml_error->message)
267 client->last_error = str_dup (client->xml_error->message);
269 e = assuan_process_done (ctx,
270 assuan_set_error (ctx, e,
271 client->xml_error->message ? client->xml_error->message : NULL));
272 xmlResetLastError ();
273 xmlResetError (client->xml_error);
274 xfree (client->xml_error);
275 client->xml_error = NULL;
276 return e;
279 return assuan_process_done (ctx,
280 assuan_set_error (ctx, e, pwmd_strerror (e)));
283 void
284 log_write (const char *fmt, ...)
286 char *args;
287 va_list ap;
288 time_t now;
289 char buf[255];
290 pthread_t tid = pthread_self ();
291 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
293 if ((!logfile && !isatty (STDERR_FILENO) && !log_syslog) || !fmt)
294 return;
296 pthread_mutex_lock (&m);
297 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock, &m);
299 if (!cmdline && logfile && log_fd == -1)
301 log_fd = open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600);
302 if (log_fd == -1)
303 warn ("%s", logfile);
306 va_start (ap, fmt);
308 if (str_vasprintf (&args, fmt, ap) != -1)
310 if (cmdline)
312 pthread_cleanup_push (xfree, args);
313 fprintf (stderr, "pwmd: %s\n", args);
314 fflush (stderr);
315 pthread_cleanup_pop (1);
317 else
319 char *name = pthread_getspecific (thread_name_key);
320 char *line;
322 pthread_cleanup_push (xfree, args);
323 if (name)
325 if (*name == '!')
326 snprintf (buf, sizeof (buf), "%s: ", name+1);
327 else
328 snprintf (buf, sizeof (buf), "%s(%p): ", name,
329 (pthread_t *)tid);
331 else
332 snprintf (buf, sizeof (buf), "%p: ", (pthread_t *)tid);
334 name = buf;
335 if (!cmdline && log_syslog && !nofork)
336 syslog (LOG_INFO, "%s%s", name, args);
338 time (&now);
339 struct tm *tm = localtime (&now);
340 char tbuf[21];
341 strftime (tbuf, sizeof (tbuf), "%b %d %Y %H:%M:%S ", tm);
342 tbuf[sizeof (tbuf) - 1] = 0;
344 if (args[strlen (args) - 1] == '\n')
345 args[strlen (args) - 1] = 0;
347 line = str_asprintf ("%s %i %s%s\n", tbuf, getpid (), name,
348 args);
349 pthread_cleanup_pop (1);
350 if (line)
352 pthread_cleanup_push (xfree, line);
353 if (logfile && log_fd != -1)
355 ssize_t ret = write (log_fd, line, strlen (line));
356 (void)ret;
357 fsync (log_fd);
360 if (nofork)
362 fprintf (stdout, "%s", line);
363 fflush (stdout);
366 pthread_cleanup_pop (1);
371 va_end (ap);
372 pthread_cleanup_pop (0);
374 if (log_fd != -1 && log_keepopen <= 0)
376 close(log_fd);
377 log_fd = -1;
380 pthread_mutex_unlock (&m);
383 static gpg_error_t
384 setup_crypto ()
386 gpg_error_t rc;
388 if (!gpgrt_check_version (REQUIRE_LIBGPGERROR_VERSION))
390 fprintf (stderr, _("gpgrt_check_version(): Incompatible libgpg-error. "
391 "Wanted %s, got %s.\n"), REQUIRE_LIBGPGERROR_VERSION,
392 gpgrt_check_version (NULL));
393 return GPG_ERR_UNKNOWN_VERSION;
396 gpgrt_init ();
397 //gpgrt_set_alloc_func (xrealloc_gpgrt);
399 if (!assuan_check_version (REQUIRE_LIBASSUAN_VERSION))
401 fprintf (stderr, _("assuan_check_version(): Incompatible libassuan. "
402 "Wanted %s, got %s.\n"), REQUIRE_LIBASSUAN_VERSION,
403 assuan_check_version (NULL));
404 return GPG_ERR_UNKNOWN_VERSION;
407 if (!gcry_check_version (REQUIRE_LIBGCRYPT_VERSION))
409 fprintf (stderr, _("gcry_check_version(): Incompatible libgcrypt. "
410 "Wanted %s, got %s.\n"), REQUIRE_LIBGCRYPT_VERSION,
411 gcry_check_version (NULL));
412 return GPG_ERR_UNKNOWN_VERSION;
415 gcry_set_allocation_handler (xmalloc, xmalloc, NULL, xrealloc, xfree);
417 if (!gpgme_check_version (REQUIRE_LIBGPGME_VERSION))
419 fprintf (stderr, _("gpgme_check_version(): Incompatible libgpgme. "
420 "Wanted %s, got %s.\n"), REQUIRE_LIBGPGME_VERSION,
421 gpgme_check_version (NULL));
422 return GPG_ERR_UNKNOWN_VERSION;
425 rc = gpgme_engine_check_version (GPGME_PROTOCOL_OPENPGP);
426 if (rc)
428 fprintf (stderr, _("gpgme_engine_check_version(GPGME_PROTOCOL_OPENPGP): %s"), gpgme_strerror (rc));
429 return GPG_ERR_UNKNOWN_VERSION;
432 //gpgme_set_global_flag ("require-gnupg", REQUIRE_GNUPG_VERSION);
433 #ifdef ENABLE_NLS
434 gpgme_set_locale (NULL, LC_CTYPE, setlocale (LC_CTYPE, NULL));
435 gpgme_set_locale (NULL, LC_MESSAGES, setlocale (LC_MESSAGES, NULL));
436 #endif
438 #ifdef WITH_GNUTLS
439 if (gnutls_global_init ())
441 fprintf(stderr, _("gnutls_global_init() failed.\n"));
442 return GPG_ERR_UNKNOWN_VERSION;
445 if (!gnutls_check_version (REQUIRE_LIBGNUTLS_VERSION))
447 fprintf (stderr, _("gnutls_check_version(): Incompatible libgnutls. "
448 "Wanted %s, got %s.\n"), REQUIRE_LIBGNUTLS_VERSION,
449 gnutls_check_version (NULL));
450 return GPG_ERR_UNKNOWN_VERSION;
453 gnutls_global_set_log_function (tls_log);
454 gnutls_global_set_audit_log_function (tls_audit_log);
455 #endif
456 return 0;
459 gpg_error_t
460 do_validate_peer (assuan_context_t ctx, const char *section,
461 assuan_peercred_t * peer)
463 char **users;
464 int allowed = 0;
465 gpg_error_t rc;
466 struct client_s *client = assuan_get_pointer (ctx);
468 if (!client)
469 return GPG_ERR_FORBIDDEN;
471 #ifdef WITH_GNUTLS
472 if (client->thd->remote)
473 return tls_validate_access (client, section);
474 #endif
476 rc = assuan_get_peercred (ctx, peer);
477 if (rc)
478 return rc;
480 users = config_get_list (section, "allowed");
481 if (users)
483 for (char **p = users; !rc && *p; p++)
485 rc = acl_check_common(client, *p, (*peer)->uid, (*peer)->gid,
486 &allowed);
489 strv_free (users);
491 else if (client->no_access_param)
492 allowed = 1;
494 return allowed && !rc ? 0 : rc ? rc : GPG_ERR_FORBIDDEN;
497 /* Test if uid is a member of group 'name'. Invert when 'not' is true. */
498 #ifdef HAVE_GETGRNAM_R
499 static gpg_error_t
500 acl_check_group (const char *name, uid_t uid, gid_t gid, int not, int *allowed)
502 char *buf;
503 struct group gr, *gresult;
504 size_t len = sysconf (_SC_GETGR_R_SIZE_MAX);
505 int err;
506 gpg_error_t rc = 0;
508 if (len == -1)
509 len = 16384;
511 buf = xmalloc (len);
512 if (!buf)
513 return GPG_ERR_ENOMEM;
515 err = getgrnam_r (name, &gr, buf, len, &gresult);
516 if (!err && gresult)
518 if (gresult->gr_gid == gid)
520 xfree (buf);
521 *allowed = !not;
522 return 0;
525 for (char **t = gresult->gr_mem; !rc && *t; t++)
527 char *tbuf;
528 struct passwd pw;
529 struct passwd *result = get_pwd_struct (*t, 0, &pw, &tbuf, &rc);
531 if (!rc && result && result->pw_uid == uid)
533 xfree (tbuf);
534 *allowed = !not;
535 break;
538 xfree (tbuf);
541 xfree (buf);
542 return rc;
544 else if (err)
545 rc = gpg_error_from_errno (err);
547 xfree (buf);
548 return rc ? rc : !gresult ? 0 : GPG_ERR_EACCES;
550 #else
551 static gpg_error_t
552 acl_check_group (const char *name, uid_t uid, gid_t gid, int not, int *allowed)
554 struct group *gresult;
555 gpg_error_t rc = 0;
557 errno = 0;
558 gresult = getgrnam (name);
559 if (!errno && gresult && gresult->gr_gid == gid)
561 *allowed = !not;
562 return 0;
564 else if (errno)
565 rc = gpg_error_from_syserror ();
566 else if (!gresult)
567 return 0;
569 for (char **t = gresult->gr_mem; !rc && *t; t++)
571 char *buf;
572 struct passwd pw;
573 struct passwd *result = get_pwd_struct (*t, 0, &pw, &buf, &rc);
575 if (!rc && result && result->pw_uid == uid)
577 xfree (buf);
578 *allowed = !not;
579 break;
582 xfree (buf);
585 return rc;
587 #endif
589 gpg_error_t
590 peer_is_invoker(struct client_s *client)
592 struct invoking_user_s *user;
593 int allowed = 0;
595 if (client->thd->state == CLIENT_STATE_UNKNOWN)
596 return GPG_ERR_EACCES;
598 for (user = invoking_users; user; user = user->next)
600 #ifdef WITH_GNUTLS
601 if (client->thd->remote)
603 if (user->type == INVOKING_TLS
604 && !strcmp(client->thd->tls->fp, user->id))
605 allowed = user->not ? 0 : 1;
607 continue;
609 #endif
611 if (user->type == INVOKING_GID)
613 gpg_error_t rc = acl_check_group (user->id,
614 client->thd->peer->uid,
615 client->thd->peer->gid,
616 user->not, &allowed);
617 if (rc)
618 return rc;
620 else if (user->type == INVOKING_UID && client->thd->peer->uid == user->uid)
621 allowed = user->not ? 0 : 1;
624 return allowed ? 0 : GPG_ERR_EACCES;
627 #ifdef HAVE_GETGRNAM_R
628 gpg_error_t
629 acl_check_common (struct client_s *client, const char *user, uid_t uid,
630 gid_t gid, int *allowed)
632 int not = 0;
633 int rw = 0;
634 int tls = 0;
635 gpg_error_t rc = 0;
637 if (!user || !*user)
638 return 0;
640 if (*user == '-' || *user == '!')
641 not = 1;
643 if (*user == '+') // not implemented yet
644 rw = 1;
646 if (*user == '#') // TLS fingerprint hash
647 tls = 1;
649 if (not || rw || tls)
650 user++;
652 if (tls)
654 #ifdef WITH_GNUTLS
655 if (client->thd->remote)
657 if (!strcasecmp (client->thd->tls->fp, user))
658 *allowed = !not;
661 return 0;
662 #else
663 return 0;
664 #endif
666 #ifdef WITH_GNUTLS
667 else if (client->thd->remote) // Remote client with no FP in the ACL
668 return 0;
669 #endif
671 if (*user == '@') // all users in group
672 return acl_check_group (user+1, uid, gid, not, allowed);
673 else
675 char *buf;
676 struct passwd pw;
677 struct passwd *pwd = get_pwd_struct (user, 0, &pw, &buf, &rc);
679 if (!rc && pwd && pwd->pw_uid == uid)
680 *allowed = !not;
682 xfree (buf);
685 return rc;
687 #else
688 gpg_error_t
689 acl_check_common (struct client_s *client, const char *user, uid_t uid,
690 gid_t gid, int *allowed)
692 gpg_error_t rc = 0;
693 int not = 0;
694 int rw = 0;
695 int tls = 0;
697 if (!user || !*user)
698 return 0;
700 if (*user == '-' || *user == '!')
701 not = 1;
703 if (*user == '+') // not implemented yet
704 rw = 1;
706 if (*user == '#') // TLS fingerprint hash
707 tls = 1;
709 if (not || rw || tls)
710 user++;
712 if (tls)
714 #ifdef WITH_GNUTLS
715 if (client->thd->remote)
717 if (!strcasecmp (client->thd->tls->fp, user))
718 *allowed = !not;
721 return 0;
722 #else
723 return 0;
724 #endif
727 if (*user == '@') // all users in group
728 return acl_check_group (user+1, uid, gid, not, allowed);
729 else
731 char *buf;
732 struct passwd pw;
733 struct passwd *result = get_pwd_struct (user, 0, &pw, &buf, &rc);
735 if (!rc && result && result->pw_uid == uid)
736 *allowed = !not;
738 xfree (buf);
741 return rc;
743 #endif
745 static gpg_error_t
746 validate_peer (struct client_s *cl)
748 gpg_error_t rc;
750 #ifdef WITH_GNUTLS
751 if (cl->thd->remote)
752 return tls_validate_access (cl, NULL);
753 #endif
755 MUTEX_LOCK (&cn_mutex);
756 pthread_cleanup_push (release_mutex_cb, &cn_mutex);
757 rc = do_validate_peer (cl->ctx, "global", &cl->thd->peer);
758 pthread_cleanup_pop (1);
759 log_write ("peer %s: uid=%i, gid=%i, pid=%i, rc=%u",
760 !rc ? _("accepted") : _("rejected"), cl->thd->peer->uid,
761 cl->thd->peer->gid, cl->thd->peer->pid, rc);
762 return rc;
765 static void
766 xml_error_cb (void *data, xmlErrorPtr e)
768 struct client_s *client = data;
771 * Keep the first reported error as the one to show in the error
772 * description. Reset in send_error().
774 if (client->xml_error)
775 return;
777 client->xml_error = xcalloc (1, sizeof(xmlError));
778 xmlCopyError (e, client->xml_error);
781 static pid_t
782 hook_waitpid (assuan_context_t ctx, pid_t pid, int action,
783 int *status, int options)
785 return waitpid (pid, status, options);
788 static ssize_t
789 hook_read (assuan_context_t ctx, assuan_fd_t fd, 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_read_hook (ctx, (int) fd, data, len);
796 #endif
798 return read ((int) fd, data, len);
801 static ssize_t
802 hook_write (assuan_context_t ctx, assuan_fd_t fd,
803 const void *data, size_t len)
805 #ifdef WITH_GNUTLS
806 struct client_s *client = assuan_get_pointer (ctx);
808 if (client->thd->remote)
809 return tls_write_hook (ctx, (int) fd, data, len);
810 #endif
812 return write ((int) fd, data, len);
816 assuan_log_cb (assuan_context_t ctx, void *data, unsigned cat,
817 const char *msg)
819 struct client_s *client = data;
820 char *str = NULL;
822 (void)client;
824 if (!(assuan_level & cat))
825 return 0;
827 if (!msg)
828 return 1;
830 switch (cat)
832 case ASSUAN_LOG_INIT:
833 str = "ASSUAN[INIT]";
834 break;
835 case ASSUAN_LOG_CTX:
836 str = "ASSUAN[CTX]";
837 break;
838 case ASSUAN_LOG_ENGINE:
839 str = "ASSUAN[ENGINE]";
840 break;
841 case ASSUAN_LOG_DATA:
842 str = "ASSUAN[DATA]";
843 break;
844 case ASSUAN_LOG_SYSIO:
845 str = "ASSUAN[SYSIO]";
846 break;
847 case ASSUAN_LOG_CONTROL:
848 str = "ASSUAN[CONTROL]";
849 break;
850 default:
851 str = "ASSUAN[UNKNOWN]";
852 break;
855 log_write ("%s: %s", str, msg);
856 return 1;
859 static int
860 new_connection (struct client_s *cl)
862 gpg_error_t rc;
863 static struct assuan_malloc_hooks mhooks = { xmalloc, xrealloc, xfree };
864 static struct assuan_system_hooks shooks = {
865 ASSUAN_SYSTEM_HOOKS_VERSION,
866 __assuan_usleep,
867 __assuan_pipe,
868 __assuan_close,
869 hook_read,
870 hook_write,
871 //FIXME
872 NULL, //recvmsg
873 NULL, //sendmsg both are used for FD passing
874 __assuan_spawn,
875 hook_waitpid,
876 __assuan_socketpair,
877 __assuan_socket,
878 __assuan_connect
881 #ifdef WITH_GNUTLS
882 if (cl->thd->remote)
884 char *prio = config_get_string ("global", "tls_cipher_suite");
886 cl->thd->timeout = config_get_integer ("global", "tls_timeout");
887 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
888 return 0;
890 cl->thd->tls = tls_init_client (cl->thd->fd, cl->thd->timeout, prio);
891 xfree (prio);
892 if (!cl->thd->tls)
893 return 0;
895 #endif
897 rc = assuan_new_ext (&cl->ctx, GPG_ERR_SOURCE_DEFAULT, &mhooks,
898 assuan_log_cb, cl);
899 if (rc)
900 goto fail;
902 assuan_ctx_set_system_hooks (cl->ctx, &shooks);
903 rc = assuan_init_socket_server (cl->ctx, cl->thd->fd, 2);
904 if (rc)
905 goto fail;
907 assuan_set_pointer (cl->ctx, cl);
908 assuan_set_hello_line (cl->ctx, PACKAGE_STRING);
909 rc = register_commands (cl->ctx);
910 if (rc)
911 goto fail;
913 rc = assuan_accept (cl->ctx);
914 if (rc)
915 goto fail;
917 rc = validate_peer (cl);
918 /* May not be implemented on all platforms. */
919 if (rc && gpg_err_code (rc) != GPG_ERR_ASS_GENERAL)
920 goto fail;
922 MUTEX_LOCK (&cn_mutex);
923 cl->thd->state = CLIENT_STATE_INIT;
924 MUTEX_UNLOCK (&cn_mutex);
925 cl->lock_timeout = config_get_integer ("global", "lock_timeout");
926 xmlSetStructuredErrorFunc (cl, xml_error_cb);
927 return 1;
929 fail:
930 log_write ("%s", pwmd_strerror (rc));
931 return 0;
935 * This is called after a client_thread() terminates. Set with
936 * pthread_cleanup_push().
938 static void
939 free_client_cb (void *arg)
941 struct client_thread_s *cn = arg;
942 struct client_s *cl = cn->cl;
944 MUTEX_LOCK (&cn_mutex);
945 cn_thread_list = slist_remove (cn_thread_list, cn);
946 MUTEX_UNLOCK (&cn_mutex);
948 if (cl)
950 unlock_flock (&cl->flock_fd);
951 reset_client (cl);
952 if (cl->xml_error)
953 xmlResetError (cl->xml_error);
955 xfree (cl->xml_error);
957 #ifdef WITH_GNUTLS
958 if (cn->tls)
960 gnutls_deinit (cn->tls->ses);
961 xfree (cn->tls->fp);
962 xfree (cn->tls);
964 #endif
966 if (cl->ctx)
967 assuan_release (cl->ctx);
968 else if (cl->thd && cl->thd->fd != -1)
969 close (cl->thd->fd);
971 if (cl->crypto)
972 crypto_free (cl->crypto);
974 cl->crypto = NULL;
975 xfree (cl);
977 else
979 if (cn->fd != -1)
980 close (cn->fd);
983 while (cn->msg_queue)
985 struct status_msg_s *msg = cn->msg_queue;
987 cn->msg_queue = msg->next;
988 xfree (msg->line);
989 xfree (msg);
992 if (cn->status_msg_pipe[0] != -1)
993 close (cn->status_msg_pipe[0]);
995 if (cn->status_msg_pipe[1] != -1)
996 close (cn->status_msg_pipe[1]);
998 pthread_mutex_destroy (&cn->status_mutex);
999 log_write (_("exiting, fd=%i"), cn->fd);
1000 send_status_all (STATUS_CLIENTS, NULL);
1002 #ifdef WITH_GNUTLS
1003 xfree (cn->peeraddr);
1004 #endif
1005 xfree (cn);
1008 void
1009 free_all_clients ()
1011 MUTEX_LOCK (&cn_mutex);
1012 pthread_cleanup_push (release_mutex_cb, &cn_mutex);
1014 while (slist_length (cn_thread_list))
1016 struct client_thread_s *thd = slist_nth_data (cn_thread_list, 0);
1018 free_client_cb (thd);
1021 pthread_cleanup_pop (1);
1024 static gpg_error_t
1025 send_msg_queue (struct client_thread_s *thd)
1027 MUTEX_LOCK (&thd->status_mutex);
1028 gpg_error_t rc = 0;
1029 char c;
1030 ssize_t ret;
1032 ret = read (thd->status_msg_pipe[0], &c, 1);
1033 rc = gpg_error_from_syserror ();
1034 if (ret == -1 && gpg_err_code (rc) != GPG_ERR_EAGAIN)
1035 log_write ("%s (%i): %s", __FUNCTION__, __LINE__, pwmd_strerror (rc));
1036 else
1037 rc = 0;
1039 thd->wrote_status = 0;
1041 while (thd->msg_queue)
1043 struct status_msg_s *msg = thd->msg_queue;
1045 #ifndef HAVE_PTHREAD_CANCEL
1046 if (thd->fd == -1)
1047 break;
1048 #endif
1050 thd->msg_queue = thd->msg_queue->next;
1051 MUTEX_UNLOCK (&thd->status_mutex);
1052 rc = send_status (thd->cl->ctx, msg->s, msg->line);
1053 MUTEX_LOCK (&thd->status_mutex);
1054 xfree (msg->line);
1055 xfree (msg);
1057 if (rc)
1058 break;
1061 MUTEX_UNLOCK (&thd->status_mutex);
1062 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1063 log_write ("%s (%i): %s", __FUNCTION__, __LINE__, pwmd_strerror (rc));
1065 return rc;
1068 static void *
1069 client_thread (void *data)
1071 struct client_thread_s *thd = data;
1072 struct client_s *cl = xcalloc (1, sizeof (struct client_s));
1073 struct slist_s *list;
1074 gpg_error_t rc;
1075 #ifndef HAVE_PTHREAD_CANCEL
1076 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
1077 #endif
1079 #ifdef HAVE_PR_SET_NAME
1080 prctl (PR_SET_NAME, "client");
1081 #endif
1082 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1084 if (!cl)
1086 log_write ("%s(%i): %s", __FILE__, __LINE__,
1087 pwmd_strerror (GPG_ERR_ENOMEM));
1088 return NULL;
1091 MUTEX_LOCK (&cn_mutex);
1092 pthread_cleanup_push (free_client_cb, thd);
1093 thd->cl = cl;
1094 cl->thd = thd;
1095 cl->flock_fd = -1;
1097 list = slist_append (cn_thread_list, thd);
1098 if (list)
1099 cn_thread_list = list;
1100 else
1102 log_write ("%s(%i): %s", __FILE__, __LINE__,
1103 pwmd_strerror (GPG_ERR_ENOMEM));
1104 MUTEX_UNLOCK (&cn_mutex);
1105 return NULL;
1108 if (fcntl (thd->status_msg_pipe[0], F_SETFL, O_NONBLOCK) == -1)
1109 rc = gpg_error_from_errno (errno);
1111 if (!rc)
1112 if (fcntl (thd->status_msg_pipe[1], F_SETFL, O_NONBLOCK) == -1)
1113 rc = gpg_error_from_errno (errno);
1115 MUTEX_UNLOCK (&cn_mutex);
1117 if (rc)
1119 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
1120 return NULL;
1123 if (new_connection (cl))
1125 int finished = 0;
1126 gpg_error_t rc;
1127 struct pollfd fds[2];
1129 fds[0].fd = thd->fd;
1130 fds[0].events = POLLIN;
1131 fds[1].fd = thd->status_msg_pipe[0];
1132 fds[1].events = POLLIN;
1134 send_status_all (STATUS_CLIENTS, NULL);
1135 rc = send_status (cl->ctx, STATUS_CACHE, NULL);
1136 if (rc)
1138 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
1139 finished = 1;
1142 while (!finished)
1144 int n;
1145 int eof;
1147 n = poll (fds, 2, 100);
1148 if (n == -1)
1150 log_write ("%s", strerror (errno));
1151 break;
1154 #ifdef WITH_GNUTLS
1155 if (thd->remote && thd->tls && thd->tls->rehandshake)
1157 char *prio;
1158 int ret;
1159 const char *e;
1161 if (thd->tls->rehandshake == 1)
1163 prio = config_get_string ("global", "tls_cipher_suite");
1164 if (!prio)
1166 thd->tls->rehandshake = 0;
1167 continue;
1170 ret = gnutls_priority_set_direct (thd->tls->ses, prio, &e);
1171 if (ret == GNUTLS_E_SUCCESS)
1173 rc = send_status (cl->ctx, STATUS_REHANDSHAKE, NULL);
1174 if (!rc)
1176 rc = assuan_send_data (cl->ctx, NULL, 0);
1177 if (!rc)
1179 ret = gnutls_rehandshake (thd->tls->ses);
1180 if (ret)
1182 log_write ("%s", gnutls_strerror (ret));
1183 thd->tls->rehandshake = 0;
1185 else
1186 thd->tls->rehandshake = 2;
1190 if (rc)
1191 log_write ("%s", pwmd_strerror (rc));
1193 else
1194 log_write ("%s: %s", gnutls_strerror (ret), e);
1196 xfree (prio);
1197 continue;
1200 #endif
1202 if (!n)
1203 continue;
1205 if (fds[1].revents & POLLIN)
1207 #ifdef WITH_GNUTLS
1208 if (!thd->remote || (thd->tls && !thd->tls->rehandshake))
1209 #endif
1211 rc = send_msg_queue (thd);
1212 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1213 break;
1217 #ifdef HAVE_PTHREAD_CANCEL
1218 if (!(fds[0].revents & POLLIN))
1219 #else
1220 if (thd->fd != -1 && !(fds[0].revents & POLLIN))
1221 #endif
1222 continue;
1224 rc = assuan_process_next (cl->ctx, &eof);
1225 if (rc || eof)
1227 if (gpg_err_code (rc) == GPG_ERR_EOF || eof)
1228 break;
1230 log_write ("assuan_process_next(): rc=%u %s", rc,
1231 pwmd_strerror (rc));
1232 if (rc == gpg_error (GPG_ERR_ETIMEDOUT))
1233 break;
1235 rc = send_error (cl->ctx, rc);
1236 if (rc)
1238 log_write ("assuan_process_done(): rc=%u %s", rc,
1239 pwmd_strerror (rc));
1240 break;
1244 /* Since the msg queue pipe fd's are non-blocking, check for
1245 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1246 * client has already disconnected and will be converted to
1247 * GPG_ERR_EOF during assuan_process_next().
1249 #ifdef WITH_GNUTLS
1250 if (!thd->remote || (thd->tls && !thd->tls->rehandshake))
1251 #endif
1253 rc = send_msg_queue (thd);
1254 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1255 break;
1260 /* Don't do pthread_exit() here because any set pthread_cleanup_push
1261 * functions would be called after a command failed but then the client
1262 * exited normally which may lead to a double free. */
1263 pthread_cleanup_pop (1);
1264 return NULL;
1267 static gpg_error_t
1268 xml_import (const char *filename, const char *outfile, char **keyid,
1269 char **sign_keyid, char *keyfile, const char *keyparam,
1270 int symmetric)
1272 xmlDocPtr doc;
1273 int fd;
1274 struct stat st;
1275 int len;
1276 xmlChar *xmlbuf;
1277 gpg_error_t rc = 0;
1278 struct crypto_s *crypto = NULL;
1280 if (stat (filename, &st) == -1)
1282 rc = gpg_error_from_errno (errno);
1283 return rc;
1286 fd = open (filename, O_RDONLY);
1287 if (fd == -1)
1288 return gpg_error_from_errno (errno);
1290 xmlbuf = xmalloc (st.st_size + 1);
1291 if (!xmlbuf)
1293 close (fd);
1294 return GPG_ERR_ENOMEM;
1297 if (read (fd, xmlbuf, st.st_size) == -1)
1299 rc = gpg_error_from_errno (errno);
1300 close (fd);
1301 xfree (xmlbuf);
1302 return rc;
1305 close (fd);
1306 xmlbuf[st.st_size] = 0;
1307 // Be sure the document validates.
1308 doc = xmlReadDoc (xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS);
1309 xfree (xmlbuf);
1310 if (!doc)
1311 return GPG_ERR_BAD_DATA;
1313 xmlNodePtr n = xmlDocGetRootElement (doc);
1314 if (n && !xmlStrEqual (n->name, (xmlChar *) "pwmd"))
1315 rc = GPG_ERR_BAD_DATA;
1317 if (!rc)
1319 rc = xml_validate_import (NULL, n ? n->children : n);
1320 if (!rc)
1322 rc = crypto_init (&crypto, NULL, filename, keyfile != NULL, keyfile);
1323 if (!rc)
1325 if (keyfile)
1327 crypto->flags |= CRYPTO_FLAG_KEYFILE;
1328 crypto->keyfile = str_dup (keyfile);
1331 xmlDocDumpMemory (doc, &crypto->plaintext, &len);
1332 if (len > 0)
1333 crypto->plaintext_size = len;
1334 else
1335 rc = GPG_ERR_ENOMEM;
1340 if (!rc)
1342 if (!symmetric && (keyparam || !keyid))
1344 char *buf = NULL;
1346 if (keyparam)
1348 fd = open (keyparam, O_RDONLY);
1349 if (fd == -1)
1350 rc = gpg_error_from_errno (errno);
1352 if (!rc)
1354 if (stat (keyparam, &st) == -1)
1355 rc = gpg_error_from_errno (errno);
1357 if (!rc)
1359 buf = xmalloc (st.st_size+1);
1360 if (!buf)
1361 rc = GPG_ERR_ENOMEM;
1363 if (!rc)
1365 len = read (fd, buf, st.st_size);
1366 if (len != st.st_size)
1367 rc = gpg_error_from_errno (errno);
1369 if (!rc)
1370 buf[len] = 0;
1375 if (fd != -1)
1376 close (fd);
1378 else
1380 buf = crypto_default_key_params ();
1381 if (!buf)
1382 rc = GPG_ERR_ENOMEM;
1385 if (!rc)
1386 rc = crypto_genkey (NULL, crypto, (unsigned char *)buf);
1388 xfree (buf);
1390 else
1392 crypto->save.pubkey = strv_dup (keyid);
1393 crypto->save.sigkey = strv_dup (sign_keyid);
1396 if (!rc)
1398 crypto->flags |= symmetric ? CRYPTO_FLAG_SYMMETRIC : 0;
1399 rc = crypto_encrypt (NULL, crypto);
1403 if (!rc)
1405 if (!strcmp (outfile, "-"))
1406 outfile = NULL;
1408 xfree (crypto->plaintext);
1409 crypto->plaintext = NULL;
1410 xfree (crypto->filename);
1411 crypto->filename = outfile ? str_dup (outfile) : NULL;
1412 rc = crypto_write_file (crypto);
1415 xmlFreeDoc (doc);
1416 crypto_free (crypto);
1417 return rc;
1420 static gpg_error_t
1421 do_cache_push (struct crypto_s *crypto)
1423 gpg_error_t rc;
1424 xmlDocPtr doc;
1425 struct cache_data_s *cdata;
1426 unsigned char *crc;
1427 size_t len;
1428 int fd = -1;
1430 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1431 crypto->filename);
1433 if (valid_filename (crypto->filename) == 0)
1435 log_write (_("%s: Invalid characters in filename"), crypto->filename);
1436 return GPG_ERR_INV_VALUE;
1439 rc = lock_flock (NULL, crypto->filename, LOCK_SH, &fd);
1440 if (!rc)
1441 rc = crypto_decrypt (NULL, crypto);
1442 if (rc)
1444 unlock_flock (&fd);
1445 return rc;
1448 rc = xml_parse_doc ((char *) crypto->plaintext, crypto->plaintext_size, &doc);
1449 if (rc)
1451 unlock_flock (&fd);
1452 log_write ("%s", pwmd_strerror (rc));
1453 return rc;
1456 cdata = xcalloc (1, sizeof (struct cache_data_s));
1457 if (!cdata)
1459 unlock_flock (&fd);
1460 xmlFreeDoc (doc);
1461 return GPG_ERR_ENOMEM;
1464 rc = get_checksum (crypto->filename, &crc, &len);
1465 unlock_flock (&fd);
1466 if (rc)
1468 xmlFreeDoc (doc);
1469 cache_free_data_once (cdata);
1470 return rc;
1473 cdata->crc = crc;
1474 rc = cache_encrypt (crypto);
1475 if (!rc)
1477 cdata->doc = crypto->plaintext;
1478 cdata->size = crypto->plaintext_size;
1479 crypto->plaintext = NULL;
1480 cdata->pubkey = crypto->pubkey;
1481 cdata->sigkey = crypto->sigkey;
1482 crypto->pubkey = NULL;
1483 crypto->sigkey = NULL;
1485 else
1487 xmlFreeDoc (doc);
1488 cache_free_data_once (cdata);
1489 return rc;
1492 int timeout = config_get_integer (crypto->filename, "cache_timeout");
1493 rc = cache_add_file (crypto->filename, cdata, timeout);
1494 return rc;
1497 static gpg_error_t
1498 init_client (int fd, const char *addr)
1500 gpg_error_t rc = 0;
1501 struct client_thread_s *new = xcalloc (1, sizeof (struct client_thread_s));
1503 if (!new)
1505 close (fd);
1506 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (ENOMEM));
1507 return GPG_ERR_ENOMEM;
1510 MUTEX_LOCK (&cn_mutex);
1511 pthread_cleanup_push (release_mutex_cb, &cn_mutex);
1512 new->conntime = time (NULL);
1514 if (pipe (new->status_msg_pipe) == -1)
1515 rc = gpg_error_from_errno (errno);
1516 else
1517 pthread_mutex_init (&new->status_mutex, NULL);
1519 if (!rc)
1521 #ifdef WITH_GNUTLS
1522 new->remote = addr ? 1 : 0;
1523 if (addr)
1524 new->peeraddr = str_dup (addr);
1525 #endif
1526 new->fd = fd;
1527 rc = create_thread (client_thread, new, &new->tid, 1);
1528 if (rc)
1530 close (new->status_msg_pipe[0]);
1531 close (new->status_msg_pipe[1]);
1532 pthread_mutex_destroy (&new->status_mutex);
1536 if (!rc)
1538 if (addr)
1539 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1540 (pthread_t *) new->tid, fd, addr);
1541 else
1542 log_write (_("new connection: tid=%p, fd=%i"),
1543 (pthread_t *) new->tid, fd);
1546 pthread_cleanup_pop (1);
1548 if (rc)
1550 xfree (new);
1551 close (fd);
1552 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
1554 return rc;
1557 #ifdef WITH_GNUTLS
1558 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1559 static void *
1560 get_in_addr (struct sockaddr *sa)
1562 if (sa->sa_family == AF_INET)
1563 return &(((struct sockaddr_in *) sa)->sin_addr);
1565 return &(((struct sockaddr_in6 *) sa)->sin6_addr);
1568 static int
1569 start_stop_tls_with_protocol (int ipv6, int term)
1571 struct addrinfo hints, *servinfo, *p;
1572 int port = config_get_integer ("global", "tcp_port");
1573 char buf[7];
1574 int n;
1575 int *fd = ipv6 ? &tls6_fd : &tls_fd;
1577 if (term || config_get_boolean ("global", "enable_tcp") == 0)
1579 if (tls6_fd != -1)
1581 shutdown (tls6_fd, SHUT_RDWR);
1582 close (tls6_fd);
1583 tls6_fd = -1;
1586 if (tls_fd != -1)
1588 shutdown (tls_fd, SHUT_RDWR);
1589 close (tls_fd);
1590 tls_fd = -1;
1593 return 0;
1596 memset (&hints, 0, sizeof (hints));
1597 hints.ai_family = ipv6 ? AF_INET6 : AF_INET;
1598 hints.ai_socktype = SOCK_STREAM;
1599 hints.ai_flags = AI_PASSIVE;
1600 snprintf (buf, sizeof (buf), "%i", port);
1602 if ((n = getaddrinfo (NULL, buf, &hints, &servinfo)) == -1)
1604 log_write ("getaddrinfo(): %s", gai_strerror (n));
1605 return 0;
1608 for (n = 0, p = servinfo; p != NULL; p = p->ai_next)
1610 int r = 1;
1612 if ((ipv6 && p->ai_family != AF_INET6)
1613 || (!ipv6 && p->ai_family != AF_INET))
1614 continue;
1616 if ((*fd = socket (p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
1618 log_write ("socket(): %s", strerror (errno));
1619 continue;
1622 if (setsockopt (*fd, SOL_SOCKET, SO_REUSEADDR, &r, sizeof (int)) == -1)
1624 log_write ("setsockopt(): %s",
1625 pwmd_strerror (gpg_error_from_errno (errno)));
1626 freeaddrinfo (servinfo);
1627 goto fail;
1630 if (bind (*fd, p->ai_addr, p->ai_addrlen) == -1)
1632 close (*fd);
1633 log_write ("bind(): %s",
1634 pwmd_strerror (gpg_error_from_errno (errno)));
1635 continue;
1638 n++;
1639 break;
1642 freeaddrinfo (servinfo);
1644 if (!n)
1645 goto fail;
1647 #if HAVE_DECL_SO_BINDTODEVICE != 0
1648 char *tmp = config_get_string ("global", "tcp_interface");
1649 if (tmp && setsockopt (*fd, SOL_SOCKET, SO_BINDTODEVICE, tmp,
1650 strlen (tmp)) == -1)
1652 log_write ("setsockopt(): %s",
1653 pwmd_strerror (gpg_error_from_errno (errno)));
1654 xfree (tmp);
1655 goto fail;
1658 xfree (tmp);
1659 #endif
1661 if (listen (*fd, 128) == -1)
1663 log_write ("listen(): %s", strerror (errno));
1664 goto fail;
1667 return 1;
1669 fail:
1670 start_stop_tls_with_protocol (0, 1);
1671 if (tls_fd != -1)
1672 close (tls_fd);
1674 if (tls6_fd != -1)
1675 close (tls6_fd);
1677 tls_fd = -1;
1678 tls6_fd = -1;
1679 return 0;
1682 static int
1683 start_stop_tls (int term)
1685 char *s = config_get_string ("global", "tcp_bind");
1686 int b;
1688 if (!s)
1689 return 0;
1691 if (!strcmp (s, "any"))
1693 b = start_stop_tls_with_protocol (0, term);
1694 if (b)
1695 b = start_stop_tls_with_protocol (1, term);
1697 else if (!strcmp (s, "ipv4"))
1698 b = start_stop_tls_with_protocol (0, term);
1699 else if (!strcmp (s, "ipv6"))
1700 b = start_stop_tls_with_protocol (1, term);
1701 else
1702 b = 0;
1704 xfree (s);
1705 if (!term && b)
1707 gpg_error_t rc = tls_init_params ();
1708 if (rc)
1710 start_stop_tls_with_protocol (0, 1);
1711 return 0;
1715 return b;
1717 #endif
1719 #ifdef WITH_GNUTLS
1720 static gpg_error_t
1721 do_tls_accept (struct pollfd *fds)
1723 struct sockaddr_storage raddr;
1724 socklen_t slen = sizeof (raddr);
1725 int fd;
1726 char s[INET6_ADDRSTRLEN];
1728 if (!(fds->revents & POLLIN))
1729 return 0;
1731 fd = accept (fds->fd, (struct sockaddr *) &raddr, &slen);
1732 if (fd == -1)
1734 int e = errno;
1736 if (errno != EAGAIN && !quit)
1737 log_write ("%s: %s", __FUNCTION__,
1738 pwmd_strerror (gpg_error_from_syserror()));
1740 return gpg_error_from_errno (e);
1743 inet_ntop (raddr.ss_family, get_in_addr ((struct sockaddr *) &raddr), s,
1744 sizeof s);
1745 (void) init_client (fd, s);
1746 return 0;
1748 #endif
1750 static void *
1751 accept_thread (void *arg)
1753 int sockfd = *(int *) arg;
1754 #ifndef HAVE_PTHREAD_CANCEL
1755 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
1756 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1757 #endif
1759 #ifdef HAVE_PR_SET_NAME
1760 prctl (PR_SET_NAME, "accept");
1761 #endif
1762 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
1764 for (;;)
1766 socklen_t slen = sizeof (struct sockaddr_un);
1767 struct sockaddr_un raddr;
1768 int fd, s = 0;
1769 struct pollfd fds[3];
1771 TEST_CANCEL ();
1772 memset (fds, 0, sizeof (fds));
1773 fds[s].fd = sockfd;
1774 fds[s++].events = POLLIN;
1776 #ifdef WITH_GNUTLS
1777 if (tls_fd != -1)
1779 fds[s].fd = tls_fd;
1780 fds[s++].events = POLLIN;
1782 else
1783 fds[s].fd = tls_fd;
1785 if (tls6_fd != -1)
1787 fds[s].fd = tls6_fd;
1788 fds[s++].events = POLLIN;
1790 else
1791 fds[s].fd = tls6_fd;
1792 #endif
1794 s = poll (fds, s, 500);
1795 if (s == -1)
1797 if (errno != EINTR)
1798 log_write ("%s", strerror (errno));
1799 break;
1801 else if (s == 0)
1802 continue;
1804 if (fds[0].revents & POLLIN)
1806 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1807 if (fd == -1)
1809 if (errno == EMFILE || errno == ENFILE)
1810 log_write ("%s: %s", __FUNCTION__,
1811 pwmd_strerror (gpg_error_from_errno (errno)));
1812 else if (errno != EAGAIN && errno != EINTR)
1814 if (!quit) // probably EBADF
1815 log_write ("%s: %s", __FUNCTION__,
1816 pwmd_strerror (gpg_error_from_errno (errno)));
1818 break;
1821 continue;
1824 (void) init_client (fd, NULL);
1827 #ifdef WITH_GNUTLS
1828 if (tls_fd != -1 && fds[1].fd == tls_fd)
1829 (void)do_tls_accept (&fds[1]);
1831 if (tls6_fd != -1 && fds[1].fd == tls6_fd)
1832 (void)do_tls_accept (&fds[1]);
1834 if (tls6_fd != -1 && fds[2].fd == tls6_fd)
1835 (void)do_tls_accept (&fds[2]);
1836 #endif
1839 /* Just in case accept() failed for some reason other than EBADF */
1840 quit = 1;
1841 return NULL;
1844 static void *
1845 cache_timer_thread (void *arg)
1847 unsigned k = 0;
1848 #ifndef HAVE_PTHREAD_CANCEL
1849 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
1850 #endif
1852 #ifdef HAVE_PR_SET_NAME
1853 prctl (PR_SET_NAME, "timer");
1854 #endif
1855 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
1857 for (;;)
1859 struct timeval tv = { 1, 0 };
1860 unsigned keepalive = config_get_integer ("global", "keepalive_interval");
1862 TEST_CANCEL ();
1863 select (0, NULL, NULL, NULL, &tv);
1864 cache_adjust_timeout ();
1866 if (++k >= keepalive)
1868 send_status_all (STATUS_KEEPALIVE, NULL);
1869 k = 0;
1873 return NULL;
1876 static int
1877 signal_loop (sigset_t sigset)
1879 int done = 0;
1880 int siint = 0;
1884 int sig;
1886 sigwait (&sigset, &sig);
1887 log_write (_("caught signal %i (%s)"), sig, strsignal (sig));
1889 switch (sig)
1891 case SIGHUP:
1892 pthread_cond_signal (&rcfile_cond);
1893 break;
1894 case SIGUSR1:
1895 log_write (_("clearing file cache"));
1896 cache_clear (NULL, NULL, 1);
1897 send_status_all (STATUS_CACHE, NULL);
1898 break;
1899 default:
1900 siint = 1;
1901 done = 1;
1902 break;
1905 while (!done);
1907 return siint;
1910 static void
1911 catchsig (int sig)
1913 log_write (_ ("Caught signal %i (%s). Exiting."), sig, strsignal (sig));
1914 #ifdef HAVE_BACKTRACE
1915 BACKTRACE (__FUNCTION__);
1916 #endif
1917 longjmp (jmp, 1);
1920 static void
1921 cancel_all_clients ()
1923 unsigned i, t;
1925 MUTEX_LOCK (&cn_mutex);
1926 t = slist_length (cn_thread_list);
1927 for (i = 0; i < t; i++)
1929 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
1931 #ifdef HAVE_PTHREAD_CANCEL
1932 pthread_cancel (thd->tid);
1933 #else
1934 pthread_kill (thd->tid, SIGUSR2);
1935 #endif
1938 while (slist_length (cn_thread_list))
1940 MUTEX_UNLOCK (&cn_mutex);
1941 usleep (50000);
1942 MUTEX_LOCK (&cn_mutex);
1945 MUTEX_UNLOCK (&cn_mutex);
1948 static int
1949 server_loop (int sockfd, char **socketpath)
1951 pthread_t cache_timeout_tid;
1952 int cancel_timeout_thread = 0, cancel_accept_thread = 0;
1953 sigset_t sigset;
1954 int n;
1955 int segv = 0;
1956 gpg_error_t rc;
1958 init_commands ();
1959 sigemptyset (&sigset);
1961 /* Termination */
1962 sigaddset (&sigset, SIGTERM);
1963 sigaddset (&sigset, SIGINT);
1965 /* Clears the file cache. */
1966 sigaddset (&sigset, SIGUSR1);
1968 /* Configuration file reloading. */
1969 sigaddset (&sigset, SIGHUP);
1971 #ifndef HAVE_PTHREAD_CANCEL
1973 The socket, cache and rcfile threads use this signal when
1974 pthread_cancel() is unavailable. Prevent the main thread from
1975 catching this signal from another process.
1977 sigaddset (&sigset, SIGUSR2);
1978 #endif
1980 /* An assertion failure. */
1981 signal (SIGABRT, catchsig);
1982 sigaddset (&sigset, SIGABRT);
1983 sigprocmask (SIG_BLOCK, &sigset, NULL);
1985 #ifndef HAVE_PTHREAD_CANCEL
1986 /* Remove this signal from the watched signals in signal_loop(). */
1987 sigdelset (&sigset, SIGUSR2);
1988 #endif
1990 /* Can show a backtrace of the stack in the log. */
1991 signal (SIGSEGV, catchsig);
1993 char *p = get_username (getuid());
1994 log_write (_("%s started for user %s"), PACKAGE_STRING, p);
1995 xfree (p);
1997 #ifdef WITH_GNUTLS
1998 if (config_get_boolean ("global", "enable_tcp"))
1999 log_write (_("Listening on %s and TCP port %i"), *socketpath,
2000 config_get_integer ("global", "tcp_port"));
2001 else
2002 log_write (_("Listening on %s"), *socketpath);
2003 #else
2004 log_write (_("Listening on %s"), *socketpath);
2005 #endif
2007 rc = create_thread (reload_rcfile_thread, NULL, &rcfile_tid, 0);
2008 if (rc)
2010 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2011 pwmd_strerror (rc));
2012 goto done;
2015 rc = create_thread (cache_timer_thread, NULL, &cache_timeout_tid, 0);
2016 if (rc)
2018 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2019 pwmd_strerror (rc));
2020 goto done;
2023 cancel_timeout_thread = 1;
2024 rc = create_thread (accept_thread, &sockfd, &accept_tid, 0);
2025 if (rc)
2027 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2028 pwmd_strerror (rc));
2029 goto done;
2032 cancel_accept_thread = 1;
2033 if (!setjmp (jmp))
2034 signal_loop (sigset);
2035 else
2036 segv = 1;
2038 done:
2040 * We're out of the main server loop. This happens when a signal was sent
2041 * to terminate the daemon. We'll wait for all clients to disconnect
2042 * before exiting but exit immediately if another termination signal is
2043 * sent.
2045 if (cancel_accept_thread)
2047 #ifdef HAVE_PTHREAD_CANCEL
2048 int n = pthread_cancel (accept_tid);
2049 #else
2050 int n = pthread_kill (accept_tid, SIGUSR2);
2051 #endif
2052 if (!n)
2053 pthread_join (accept_tid, NULL);
2056 if (cancel_timeout_thread)
2058 #ifdef HAVE_PTHREAD_CANCEL
2059 n = pthread_cancel (cache_timeout_tid);
2060 #else
2061 n = pthread_kill (cache_timeout_tid, SIGUSR2);
2062 #endif
2063 if (!n)
2064 pthread_join (cache_timeout_tid, NULL);
2067 #ifdef WITH_GNUTLS
2068 start_stop_tls (1);
2069 #endif
2070 shutdown (sockfd, SHUT_RDWR);
2071 close (sockfd);
2072 unlink (*socketpath);
2073 xfree (*socketpath);
2074 *socketpath = NULL;
2075 MUTEX_LOCK (&cn_mutex);
2076 n = slist_length (cn_thread_list);
2077 MUTEX_UNLOCK (&cn_mutex);
2079 if (n && !segv)
2080 cancel_all_clients ();
2081 else
2082 free_all_clients ();
2084 cache_deinit ();
2085 deinit_commands ();
2086 return segv ? EXIT_FAILURE : EXIT_SUCCESS;;
2089 static void
2090 startup_failure ()
2092 log_write (_
2093 ("Failed to add a file to the cache. Use --force to force startup. Exiting."));
2094 cache_clear (NULL, NULL, 1);
2097 static void
2098 usage (const char *pn, int status)
2100 FILE *fp = status == EXIT_FAILURE ? stderr : stdout;
2102 fprintf (fp, _("Usage: %s [OPTIONS] [file1] [...]\n"
2103 " --debug=[a:..][,g:N][,t:N] enable debugging (a:[ixedsc],g:[1-9],t:[0-N])\n"
2104 " -f, --rcfile=filename load the specfied configuration file\n"
2105 " (~/.pwmd/config)\n"
2106 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2107 " --kill terminate an existing instance of pwmd\n"
2108 " -n, --no-fork run as a foreground process\n"
2109 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2110 " --ignore, --force ignore file errors during startup\n"
2111 " -o, --outfile=filename output file when importing or converting\n"
2112 " -C, --convert=filename convert a version 2 data file to version 3\n"
2113 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2114 " -k, --passphrase-file=file for use when importing or converting\n"
2115 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2116 " converting\n"
2117 " --no-passphrase when importing or converting\n"
2118 " --keyid=keyID[,..] public key to use when encrypting\n"
2119 " --sign-keyid=fpr[,..] fingerprint of the signing key to use\n"
2120 " --symmetric use conventional encryption with optional signer\n"
2121 " --keyparam=filename custom key parameters to use (gpg default)\n"
2122 " --help this help text\n"
2123 " --version show version and compile time features\n"),
2124 pn);
2125 exit (status);
2128 static void
2129 unlink_stale_socket (const char *sock, const char *pidfile)
2131 log_write (_ ("removing stale socket %s"), sock);
2132 unlink (sock);
2133 unlink (pidfile);
2136 static int
2137 test_pidfile (const char *path, const char *sock, char *buf, size_t buflen,
2138 char **pidfile, int create, mode_t mode, int terminate)
2140 pid_t pid;
2141 int fd;
2142 size_t len;
2144 if (!create)
2146 snprintf (buf, buflen, "%s/%s.pid", homedir, sock);
2147 *pidfile = str_dup (buf);
2148 fd = open (buf, O_RDONLY);
2150 else
2151 fd = open (*pidfile, O_CREAT|O_WRONLY|O_TRUNC, mode);
2153 if (fd == -1)
2155 if (!create && errno != ENOENT)
2157 log_write ("%s: %s", buf, pwmd_strerror (errno));
2158 free (*pidfile);
2159 *pidfile = NULL;
2160 return -1;
2162 else if (!create && !terminate)
2163 return 0;
2165 log_write ("%s: %s", *pidfile, strerror (errno));
2166 return -1;
2169 if (create)
2171 snprintf (buf, buflen, "%i", getpid ());
2172 ssize_t ret = write (fd, buf, strlen (buf));
2173 if (ret == -1)
2174 log_write ("%s (%i): %s", __FUNCTION__, __LINE__,
2175 pwmd_strerror (gpg_error_from_syserror ()));
2176 close (fd);
2177 return 0;
2180 len = read (fd, buf, buflen);
2181 close (fd);
2182 if (len == 0)
2184 unlink_stale_socket (path, *pidfile);
2185 return 0;
2188 if (sscanf (buf, "%5i", &pid) != 1 || pid == 0)
2190 if (!terminate)
2192 unlink_stale_socket (path, *pidfile);
2193 return 0;
2197 if (kill (pid, 0) == -1)
2199 unlink_stale_socket (path, *pidfile);
2200 return 0;
2203 if (terminate)
2205 if (kill (pid, SIGTERM) == -1)
2206 log_write ("%s: %s", path, pwmd_strerror (errno));
2208 else
2209 log_write (_ ("an instance for socket %s is already running"), path);
2211 xfree (*pidfile);
2212 *pidfile = NULL;
2213 return 1;
2216 static unsigned
2217 parse_debug_level (const char *str, unsigned *debug, int *gpgme, int *tls)
2219 const char *p;
2220 unsigned level = 0;
2221 int gl = 0, tl = 0;
2223 for (p = str; p && *p; p++)
2225 if (*p == 'a') // assuan debug flags
2227 if (*++p != ':')
2228 return 1;
2230 while (*++p)
2232 switch (*p)
2234 case 'i':
2235 level |= ASSUAN_LOG_INIT;
2236 break;
2237 case 'x':
2238 level |= ASSUAN_LOG_CTX;
2239 break;
2240 case 'e':
2241 level |= ASSUAN_LOG_ENGINE;
2242 break;
2243 case 'd':
2244 level |= ASSUAN_LOG_DATA;
2245 break;
2246 case 's':
2247 level |= ASSUAN_LOG_SYSIO;
2248 break;
2249 case 'c':
2250 level |= ASSUAN_LOG_CONTROL;
2251 break;
2252 case ',':
2253 break;
2254 default:
2255 return 1;
2258 if (*p == ',')
2259 break;
2262 if (!*p)
2263 break;
2265 else if (*p == 'g' || *p == 't') // gpgme and TLS debug level
2267 int t = *p == 't';
2268 int n;
2270 if (*++p != ':')
2271 return 1;
2273 if (!isdigit (*++p))
2274 return 1;
2276 n = atoi (p);
2277 if (t)
2278 tl = n;
2279 else
2280 gl = n;
2282 if (tl < 0 || gl < 0 || gl > 9)
2283 return 1;
2285 while (isdigit (*p))
2286 p++;
2288 p--;
2289 if (*(p+1) && *(p+1) != ',')
2290 return 1;
2291 else if (*(p+1))
2292 p++;
2294 else
2295 return 1;
2298 if (tl)
2299 *tls = tl;
2301 if (gl)
2302 *gpgme = gl;
2304 *debug = level;
2305 return 0;
2309 main (int argc, char *argv[])
2311 int opt;
2312 struct sockaddr_un addr;
2313 char buf[PATH_MAX];
2314 char *socketpath = NULL, *socketdir, *socketname = NULL;
2315 char *socketarg = NULL;
2316 char *datadir = NULL;
2317 char *pidfile = NULL;
2318 mode_t mode = 0600;
2319 int x;
2320 char *p;
2321 char **cache_push = NULL;
2322 char *import = NULL, *keyid = NULL, *sign_keyid = NULL;
2323 char *keyparam = NULL;
2324 int estatus = EXIT_FAILURE;
2325 int sockfd;
2326 char *outfile = NULL;
2327 int do_unlink = 0;
2328 int secure = 0;
2329 int show_version = 0;
2330 int force = 0;
2331 gpg_error_t rc;
2332 char *keyfile = NULL;
2333 int exists;
2334 int optindex;
2335 int terminate = 0;
2336 int sym = 0;
2337 int gpgme_level = -1;
2338 int tls_level = -1;
2339 /* Must maintain the same order as longopts[] */
2340 enum
2342 OPT_VERSION, OPT_HELP, OPT_HOMEDIR, OPT_NO_FORK, OPT_DISABLE_DUMP,
2343 OPT_FORCE, OPT_RCFILE, OPT_PASSPHRASE_FILE, OPT_IMPORT, OPT_OUTFILE,
2344 OPT_KEYID, OPT_SIGN_KEYID, OPT_SYMMETRIC, OPT_KEYPARAM, OPT_KILL,
2345 OPT_DEBUG
2347 const char *optstring = "nf:C:k:I:o:s";
2348 const struct option longopts[] = {
2349 {"version", no_argument, 0, 0},
2350 {"help", no_argument, 0, 0},
2351 {"homedir", required_argument, 0, 0},
2352 {"no-fork", no_argument, 0, 'n'},
2353 {"disable_dump", no_argument, 0, 0},
2354 {"force", no_argument, 0, 0},
2355 {"rcfile", required_argument, 0, 'f'},
2356 {"passphrase-file", required_argument, 0, 'k'},
2357 {"import", required_argument, 0, 'I'},
2358 {"outfile", required_argument, 0, 'o'},
2359 {"keyid", required_argument, 0, 0},
2360 {"sign-keyid", required_argument, 0, 0},
2361 {"symmetric", no_argument, 0, 's'},
2362 {"keyparam", required_argument, 0, 0},
2363 {"kill", no_argument, 0, 0},
2364 {"debug", required_argument, 0, 0},
2365 {0, 0, 0, 0}
2368 log_fd = -1;
2369 cmdline = 1;
2371 #ifndef DEBUG
2372 #ifdef HAVE_SETRLIMIT
2373 struct rlimit rl;
2375 rl.rlim_cur = rl.rlim_max = 0;
2377 if (setrlimit (RLIMIT_CORE, &rl) != 0)
2378 err (EXIT_FAILURE, "setrlimit()");
2379 #endif
2381 #ifdef HAVE_PR_SET_DUMPABLE
2382 prctl (PR_SET_DUMPABLE, 0);
2383 #endif
2384 #endif
2386 #ifdef ENABLE_NLS
2387 setlocale (LC_ALL, "");
2388 bindtextdomain ("pwmd", LOCALEDIR);
2389 textdomain ("pwmd");
2390 #endif
2392 if (setup_crypto ())
2393 exit (EXIT_FAILURE);
2395 #ifdef WITH_GNUTLS
2396 tls_level = tls_level == -1 ? 1 : tls_level;
2397 gnutls_global_set_log_level (tls_level);
2398 tls_fd = -1;
2399 tls6_fd = -1;
2400 #endif
2401 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
2402 xmlInitMemory ();
2403 xmlInitGlobals ();
2404 xmlInitParser ();
2405 xmlXPathInit ();
2407 while ((opt = getopt_long (argc, argv, optstring, longopts, &optindex))
2408 != -1)
2410 switch (opt)
2412 case 'I':
2413 import = optarg;
2414 break;
2415 case 'k':
2416 keyfile = optarg;
2417 break;
2418 case 'o':
2419 outfile = optarg;
2420 break;
2421 case 'D':
2422 secure = 1;
2423 break;
2424 case 'n':
2425 nofork = 1;
2426 break;
2427 case 'f':
2428 rcfile = str_dup (optarg);
2429 break;
2430 case 's':
2431 sym = 1;
2432 break;
2433 default:
2434 usage (argv[0], EXIT_FAILURE);
2435 break;
2436 case 0:
2437 switch (optindex)
2439 case OPT_DEBUG:
2440 if (parse_debug_level (optarg, &assuan_level, &gpgme_level,
2441 &tls_level))
2442 usage (argv[0], EXIT_FAILURE);
2443 break;
2444 case OPT_SYMMETRIC:
2445 sym = 1;
2446 break;
2447 case OPT_VERSION:
2448 show_version = 1;
2449 break;
2450 case OPT_HELP:
2451 usage (argv[0], EXIT_SUCCESS);
2452 break;
2453 case OPT_HOMEDIR:
2454 homedir = str_dup (optarg);
2455 break;
2456 case OPT_NO_FORK:
2457 nofork = 1;
2458 break;
2459 case OPT_DISABLE_DUMP:
2460 secure = 1;
2461 break;
2462 case OPT_FORCE:
2463 force = 1;
2464 break;
2465 case OPT_RCFILE:
2466 rcfile = str_dup (optarg);
2467 break;
2468 case OPT_PASSPHRASE_FILE:
2469 keyfile = optarg;
2470 break;
2471 case OPT_IMPORT:
2472 import = optarg;
2473 break;
2474 case OPT_OUTFILE:
2475 outfile = optarg;
2476 break;
2477 case OPT_KEYID:
2478 keyid = optarg;
2479 break;
2480 case OPT_SIGN_KEYID:
2481 sign_keyid = optarg;
2482 break;
2483 case OPT_KEYPARAM:
2484 keyparam = optarg;
2485 break;
2486 case OPT_KILL:
2487 terminate = 1;
2488 break;
2489 default:
2490 usage (argv[0], EXIT_FAILURE);
2495 if (show_version)
2497 printf (_("%s\n\n"
2498 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016\n"
2499 "%s\n"
2500 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2501 "Compile time features:\n%s"), PACKAGE_STRING,
2502 PACKAGE_BUGREPORT,
2503 #ifdef PWMD_HOMEDIR
2504 "+PWMD_HOMEDIR=" PWMD_HOMEDIR "\n"
2505 #endif
2506 #ifdef WITH_GNUTLS
2507 "+WITH_GNUTLS\n"
2508 #else
2509 "-WITH_GNUTLS\n"
2510 #endif
2511 #ifdef WITH_LIBACL
2512 "+WITH_LIBACL\n"
2513 #else
2514 "-WITH_LIBACL\n"
2515 #endif
2516 #ifdef DEBUG
2517 "+DEBUG\n"
2518 #else
2519 "-DEBUG\n"
2520 #endif
2521 #ifdef MEM_DEBUG
2522 "+MEM_DEBUG\n"
2523 #else
2524 "-MEM_DEBUG\n"
2525 #endif
2526 #ifdef MUTEX_DEBUG
2527 "+MUTEX_DEBUG\n"
2528 #else
2529 "-MUTEX_DEBUG\n"
2530 #endif
2532 exit (EXIT_SUCCESS);
2535 if (!homedir)
2536 #ifdef PWMD_HOMEDIR
2537 homedir = str_dup(PWMD_HOMEDIR);
2538 #else
2539 homedir = str_asprintf ("%s/.pwmd", get_home_dir());
2540 #endif
2542 if (mkdir (homedir, 0700) == -1 && errno != EEXIST)
2543 err (EXIT_FAILURE, "%s", homedir);
2545 if (!rcfile)
2546 rcfile = str_asprintf ("%s/config", homedir);
2548 pthread_key_create (&last_error_key, free_key);
2549 #ifndef HAVE_PTHREAD_CANCEL
2550 pthread_key_create (&signal_thread_key, free_key);
2551 #endif
2553 pthread_mutexattr_t attr;
2554 pthread_mutexattr_init (&attr);
2555 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
2556 pthread_mutex_init (&rcfile_mutex, &attr);
2557 global_config = config_parse (rcfile, 0);
2558 if (!global_config)
2560 pthread_mutexattr_destroy (&attr);
2561 pthread_mutex_destroy (&rcfile_mutex);
2562 exit (EXIT_FAILURE);
2565 p = config_get_string ("global", "gpg_homedir");
2566 if (!p)
2567 datadir = str_asprintf ("%s/.gnupg", homedir);
2568 else
2569 datadir = expand_homedir (p);
2571 xfree (p);
2572 if (mkdir (datadir, 0700) == -1 && errno != EEXIST)
2573 err (EXIT_FAILURE, "%s", datadir);
2575 if (gpgme_level != -1)
2577 char s[2] = { gpgme_level + '0', 0 };
2579 if (getenv ("GPGME_DEBUG"))
2580 log_write (_ ("Overriding GPGME_DEBUG environment with level %u!"),
2581 gpgme_level);
2583 gpgme_set_global_flag ("debug", s);
2586 rc = gpgme_set_engine_info (GPGME_PROTOCOL_OpenPGP, NULL, datadir);
2587 xfree (datadir);
2589 snprintf (buf, sizeof (buf), "%s/data", homedir);
2590 if (mkdir (buf, 0700) == -1 && errno != EEXIST)
2591 err (EXIT_FAILURE, "%s", buf);
2593 datadir = str_dup (buf);
2594 pthread_cond_init (&rcfile_cond, NULL);
2595 pthread_mutex_init (&cn_mutex, &attr);
2596 pthread_mutexattr_destroy (&attr);
2598 setup_logging ();
2600 x = config_get_int_param (global_config, "global", "priority", &exists);
2601 if (exists && x != atoi(INVALID_PRIORITY))
2603 errno = 0;
2604 if (setpriority (PRIO_PROCESS, 0, x) == -1)
2606 log_write ("setpriority(): %s",
2607 pwmd_strerror (gpg_error_from_errno (errno)));
2608 goto do_exit;
2611 #ifdef HAVE_MLOCKALL
2612 if (disable_mlock == 0 && mlockall (MCL_CURRENT | MCL_FUTURE) == -1)
2614 log_write ("mlockall(): %s",
2615 pwmd_strerror (gpg_error_from_errno (errno)));
2616 goto do_exit;
2618 #endif
2620 rc = cache_init ();
2621 if (rc)
2623 log_write ("pwmd: ERR %i: %s", rc, pwmd_strerror (rc));
2624 exit (EXIT_FAILURE);
2627 if (import)
2629 char **keyids = NULL, **sign_keyids = NULL;
2631 if (!outfile || !*outfile || argc != optind)
2632 usage (argv[0], EXIT_FAILURE);
2634 if (keyid)
2635 keyids = str_split (keyid, ",", 0);
2636 if (sign_keyid)
2637 sign_keyids = str_split (sign_keyid, ",", 0);
2638 rc = xml_import (import, outfile, keyids, sign_keyids, keyfile, keyparam, sym);
2639 strv_free (keyids);
2640 strv_free (sign_keyids);
2641 if (rc)
2643 if (gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
2644 rc = gpg_error (rc);
2646 log_write ("%s: %u: %s", import, rc, pwmd_strerror (rc));
2649 config_free (global_config);
2650 xfree (rcfile);
2651 exit (rc ? EXIT_FAILURE : EXIT_SUCCESS);
2654 p = config_get_string ("global", "socket_path");
2655 if (!p)
2656 p = str_asprintf ("%s/socket", homedir);
2658 socketarg = expand_homedir (p);
2659 xfree (p);
2661 if (!secure)
2662 disable_list_and_dump = config_get_boolean ("global",
2663 "disable_list_and_dump");
2664 else
2665 disable_list_and_dump = secure;
2667 cache_push = config_get_list ("global", "cache_push");
2669 while (optind < argc)
2671 if (strv_printf (&cache_push, "%s", argv[optind++]) == 0)
2672 errx (EXIT_FAILURE, "%s", pwmd_strerror (GPG_ERR_ENOMEM));
2675 if (strchr (socketarg, '/') == NULL)
2677 socketdir = getcwd (buf, sizeof (buf));
2678 socketname = str_dup (socketarg);
2679 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2681 else
2683 socketname = str_dup (strrchr (socketarg, '/'));
2684 socketname++;
2685 socketarg[strlen (socketarg) - strlen (socketname) - 1] = 0;
2686 socketdir = str_dup (socketarg);
2687 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2690 if (chdir (datadir))
2692 log_write ("%s: %s", datadir,
2693 pwmd_strerror (gpg_error_from_errno (errno)));
2694 unlink (socketpath);
2695 goto do_exit;
2698 x = test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 0,
2699 mode, terminate);
2700 if (!terminate && x)
2701 goto do_exit;
2702 else if (terminate)
2704 estatus = x != 1 ? EXIT_FAILURE : EXIT_SUCCESS;
2705 goto do_exit;
2709 * bind() doesn't like the full pathname of the socket or any non alphanum
2710 * characters so change to the directory where the socket is wanted then
2711 * create it then change to datadir.
2713 if (chdir (socketdir))
2715 log_write ("%s: %s", socketdir,
2716 pwmd_strerror (gpg_error_from_errno (errno)));
2717 goto do_exit;
2720 xfree (socketdir);
2722 if ((sockfd = socket (PF_UNIX, SOCK_STREAM, 0)) == -1)
2724 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2725 goto do_exit;
2728 addr.sun_family = AF_UNIX;
2729 snprintf (addr.sun_path, sizeof (addr.sun_path), "%s", socketname);
2730 do_unlink = 1;
2731 if (bind (sockfd, (struct sockaddr *) &addr, sizeof (struct sockaddr)) ==
2734 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2736 if (errno == EADDRINUSE)
2738 do_unlink = 0;
2739 log_write (_("Either there is another pwmd running or '%s' is a \n"
2740 "stale socket. Please remove it manually."), socketpath);
2743 goto do_exit;
2747 char *t = config_get_string ("global", "socket_perms");
2748 mode_t mask;
2750 if (t)
2752 mode = strtol (t, NULL, 8);
2753 mask = umask (0);
2754 xfree (t);
2756 if (chmod (socketname, mode) == -1)
2758 log_write ("%s: %s", socketname,
2759 pwmd_strerror (gpg_error_from_errno (errno)));
2760 close (sockfd);
2761 umask (mask);
2762 goto do_exit;
2765 umask (mask);
2769 xfree (--socketname);
2771 if (chdir (datadir))
2773 log_write ("%s: %s", datadir,
2774 pwmd_strerror (gpg_error_from_errno (errno)));
2775 close (sockfd);
2776 goto do_exit;
2779 xfree (datadir);
2780 #ifdef WITH_GNUTLS
2781 if (config_get_boolean ("global", "enable_tcp"))
2783 if (!start_stop_tls (0))
2785 close (sockfd);
2786 goto do_exit;
2789 #endif
2792 * Set the cache entry for a file. Prompts for the password.
2794 if (cache_push)
2796 for (opt = 0; cache_push[opt]; opt++)
2798 struct crypto_s *crypto = NULL;
2799 char *pw_file = config_get_string (cache_push[opt],
2800 "passphrase_file");
2801 gpg_error_t rc = crypto_init (&crypto, NULL, cache_push[opt],
2802 pw_file != NULL, pw_file);
2804 if (!rc)
2806 crypto->flags |= pw_file ? CRYPTO_FLAG_KEYFILE : 0;
2807 crypto->keyfile = pw_file;
2809 else
2810 xfree (pw_file);
2812 if (rc)
2814 estatus = EXIT_FAILURE;
2815 goto do_exit;
2818 rc = do_cache_push (crypto);
2819 if (rc && !force)
2821 log_write ("ERR %u: %s", rc, pwmd_strerror(rc));
2822 strv_free (cache_push);
2823 startup_failure ();
2824 estatus = EXIT_FAILURE;
2825 crypto_free (crypto);
2826 goto do_exit;
2828 else if (rc)
2829 log_write ("%s: %s", crypto->filename, pwmd_strerror(rc));
2830 else
2831 log_write (_("Successfully added '%s' to the cache."),
2832 crypto->filename);
2834 crypto_free (crypto);
2837 strv_free (cache_push);
2838 log_write (!nofork ? _("Done. Daemonizing...") :
2839 _("Done. Waiting for connections..."));
2842 if (listen (sockfd, 128) == -1)
2844 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2845 goto do_exit;
2848 if (!nofork)
2850 switch (fork ())
2852 case -1:
2853 log_write ("fork(): %s",
2854 pwmd_strerror (gpg_error_from_errno (errno)));
2855 goto do_exit;
2856 case 0:
2857 close (0);
2858 close (1);
2859 close (2);
2860 setsid ();
2861 break;
2862 default:
2863 _exit (EXIT_SUCCESS);
2867 (void)test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 1,
2868 mode, 0);
2869 cmdline = 0;
2870 pthread_key_create (&thread_name_key, free_key);
2871 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
2872 estatus = server_loop (sockfd, &socketpath);
2874 do_exit:
2875 if (socketpath && do_unlink)
2877 unlink (socketpath);
2878 xfree (socketpath);
2881 xfree (socketarg);
2882 #ifdef WITH_GNUTLS
2883 gnutls_global_deinit ();
2884 tls_deinit_params ();
2885 #endif
2886 if (rcfile_tid)
2888 #ifdef HAVE_PTHREAD_CANCEL
2889 pthread_cancel (rcfile_tid);
2890 #else
2891 pthread_kill (rcfile_tid, SIGUSR2);
2892 pthread_cond_signal (&rcfile_cond);
2893 #endif
2894 pthread_join (rcfile_tid, NULL);
2897 pthread_cond_destroy (&rcfile_cond);
2898 pthread_mutex_destroy (&rcfile_mutex);
2899 pthread_key_delete (last_error_key);
2900 #ifndef HAVE_PTHREAD_CANCEL
2901 pthread_key_delete (signal_thread_key);
2902 #endif
2904 if (global_config)
2905 config_free (global_config);
2907 free_invoking_users (invoking_users);
2908 xfree (rcfile);
2909 xfree (home_directory);
2910 xfree (homedir);
2911 xmlCleanupParser ();
2912 xmlCleanupGlobals ();
2914 if (pidfile)
2915 unlink (pidfile);
2916 xfree (pidfile);
2918 if (estatus == EXIT_SUCCESS && !terminate)
2919 log_write (_("pwmd exiting normally"));
2921 pthread_key_delete (thread_name_key);
2922 closelog ();
2924 if (log_fd != -1)
2925 close (log_fd);
2927 exit (estatus);
2930 gpg_error_t lock_flock (assuan_context_t ctx, const char *filename,
2931 int type, int *fd)
2933 gpg_error_t rc = 0;
2935 #ifdef HAVE_FLOCK
2936 *fd = open (filename, O_RDONLY);
2937 if (*fd == -1)
2938 return gpg_error_from_syserror ();
2940 TRY_FLOCK (ctx, *fd, type, rc);
2941 if (rc)
2943 close (*fd);
2944 *fd = -1;
2946 #endif
2948 return rc;
2951 void unlock_flock (int *fd)
2953 #ifdef HAVE_FLOCK
2954 if (*fd != -1)
2955 close (*fd);
2957 *fd = -1;
2958 #endif