KILL: Test TLS client state.
[pwmd.git] / src / pwmd.c
blob7e564b11d94d67f477d7fd0f42895d23e3530f75
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 pthread_t accept_tid;
106 #ifdef WITH_GNUTLS
107 static int tls_fd;
108 static int tls6_fd;
109 static int start_stop_tls (int term);
110 #endif
112 static gpg_error_t do_cache_push (struct crypto_s *crypto);
113 static int signal_loop (sigset_t sigset);
115 #ifndef HAVE_PTHREAD_CANCEL
116 #define INIT_SIGNAL(s, cb) do { \
117 int *n = xmalloc (sizeof (int)); \
118 *n = 0; \
119 pthread_setspecific (signal_thread_key, n); \
120 struct sigaction act; \
121 sigset_t sigset; \
122 sigemptyset (&sigset); \
123 sigaddset (&sigset, s); \
124 pthread_sigmask (SIG_UNBLOCK, &sigset, NULL); \
125 memset (&act, 0, sizeof(act)); \
126 act.sa_flags = SA_SIGINFO; \
127 act.sa_mask = sigset; \
128 act.sa_sigaction = cb; \
129 sigaction (s, &act, NULL); \
130 } while (0)
131 #endif
133 #ifndef HAVE_PTHREAD_CANCEL
134 static void
135 catch_thread_signal (int sig, siginfo_t *info, void *ctx)
137 int *n = (int *) pthread_getspecific (signal_thread_key);
139 *n = 1;
141 #endif
143 static void
144 setup_logging ()
146 int n = config_get_boolean ("global", "enable_logging");
148 if (n)
150 char *p = config_get_string ("global", "log_path");
152 if (!p || (logfile && p && log_fd != -1 && strcmp(p, logfile)))
154 if (log_fd != -1)
155 close (log_fd);
157 log_fd = -1;
160 xfree (logfile);
161 logfile = NULL;
162 if (p)
163 logfile = expand_homedir (p);
164 xfree (p);
166 else
168 xfree (logfile);
169 logfile = NULL;
170 if (log_fd != -1)
171 close(log_fd);
173 log_fd = -1;
174 closelog ();
177 log_syslog = config_get_boolean ("global", "syslog");
178 if (log_syslog == 1)
179 openlog ("pwmd", LOG_NDELAY | LOG_PID, LOG_DAEMON);
182 static void *
183 reload_rcfile_thread (void *arg)
185 #ifndef HAVE_PTHREAD_CANCEL
186 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
187 #endif
189 #ifdef HAVE_PR_SET_NAME
190 prctl (PR_SET_NAME, "reload rcfile");
191 #endif
192 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
193 MUTEX_LOCK (&rcfile_mutex);
195 for (;;)
197 struct slist_s *keep = NULL;
198 struct slist_s *config;
199 int b = disable_list_and_dump;
200 #ifdef WITH_GNUTLS
201 char *prio;
202 char *prio2 = NULL;
203 #endif
205 pthread_cleanup_push (release_mutex_cb, &rcfile_mutex);
206 pthread_cond_wait (&rcfile_cond, &rcfile_mutex);
207 TEST_CANCEL ();
208 keep = config_keep_save ();
209 log_write (_("reloading configuration file '%s'"), rcfile);
211 prio = config_get_string ("global", "tls_cipher_suite");
212 config = config_parse (rcfile, 1);
213 if (config)
215 config_free (global_config);
216 global_config = config;
217 setup_logging ();
220 config_keep_restore (keep);
221 disable_list_and_dump = !disable_list_and_dump ? b : 1;
223 #ifdef WITH_GNUTLS
224 /* Restart listening sockets since they may have changed. */
225 start_stop_tls (1);
226 start_stop_tls (0);
228 prio2 = config_get_string ("global", "tls_cipher_suite");
229 if ((prio2 && (!prio || strcmp (prio, prio2))) || (prio && !prio2))
230 tls_rehandshake ();
232 xfree (prio2);
233 xfree (prio);
234 #endif
235 crypto_set_keepalive ();
236 pthread_cleanup_pop (0);
239 MUTEX_UNLOCK (&rcfile_mutex);
240 return NULL;
243 gpg_error_t
244 send_error (assuan_context_t ctx, gpg_error_t e)
246 struct client_s *client = assuan_get_pointer (ctx);
248 if (gpg_err_source (e) == GPG_ERR_SOURCE_UNKNOWN)
249 e = gpg_error (e);
251 if (client)
252 client->last_rc = e;
254 if (!e)
255 return assuan_process_done (ctx, 0);
257 if (!ctx)
259 log_write ("ERR %i: %s", e, pwmd_strerror (e));
260 return e;
263 if (client && client->xml_error)
265 log_write ("%s", client->xml_error->message);
266 xfree (client->last_error);
267 client->last_error = NULL;
268 if (client->xml_error->message)
269 client->last_error = str_dup (client->xml_error->message);
271 e = assuan_process_done (ctx,
272 assuan_set_error (ctx, e,
273 client->xml_error->message ? client->xml_error->message : NULL));
274 xmlResetLastError ();
275 xmlResetError (client->xml_error);
276 xfree (client->xml_error);
277 client->xml_error = NULL;
278 return e;
281 return assuan_process_done (ctx,
282 assuan_set_error (ctx, e, pwmd_strerror (e)));
285 void
286 log_write (const char *fmt, ...)
288 char *args;
289 va_list ap;
290 time_t now;
291 char buf[255];
292 pthread_t tid = pthread_self ();
293 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
295 if ((!logfile && !isatty (STDERR_FILENO) && !log_syslog) || !fmt)
296 return;
298 pthread_mutex_lock (&m);
299 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock, &m);
301 if (!cmdline && logfile && log_fd == -1)
303 log_fd = open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600);
304 if (log_fd == -1)
305 warn ("%s", logfile);
308 va_start (ap, fmt);
310 if (str_vasprintf (&args, fmt, ap) != -1)
312 if (cmdline)
314 pthread_cleanup_push (xfree, args);
315 fprintf (stderr, "pwmd: %s\n", args);
316 fflush (stderr);
317 pthread_cleanup_pop (1);
319 else
321 char *name = pthread_getspecific (thread_name_key);
322 char *line;
324 pthread_cleanup_push (xfree, args);
325 snprintf (buf, sizeof (buf),
326 name && *name == '!' ? "%s: " : name ? "%s(%p): " : "%s",
327 name ? *name == '!' ? name+1 : name : "",
328 name && *name == '!' ? 0 : name ? (pthread_t *) tid : 0);
329 name = buf;
331 if (!cmdline && log_syslog && !nofork)
332 syslog (LOG_INFO, "%s%s", name, args);
334 time (&now);
335 struct tm *tm = localtime (&now);
336 char tbuf[21];
337 strftime (tbuf, sizeof (tbuf), "%b %d %Y %H:%M:%S ", tm);
338 tbuf[sizeof (tbuf) - 1] = 0;
340 if (args[strlen (args) - 1] == '\n')
341 args[strlen (args) - 1] = 0;
343 line = str_asprintf ("%s %i %s%s\n", tbuf, getpid (), name,
344 args);
345 pthread_cleanup_pop (1);
346 if (line)
348 pthread_cleanup_push (xfree, line);
349 if (logfile && log_fd != -1)
351 ssize_t ret = write (log_fd, line, strlen (line));
352 (void)ret;
353 fsync (log_fd);
356 if (nofork)
358 fprintf (stdout, "%s", line);
359 fflush (stdout);
362 pthread_cleanup_pop (1);
367 va_end (ap);
368 pthread_cleanup_pop (0);
370 if (log_fd != -1 && log_keepopen <= 0)
372 close(log_fd);
373 log_fd = -1;
376 pthread_mutex_unlock (&m);
379 static gpg_error_t
380 setup_crypto ()
382 gpg_error_t rc;
384 if (!gpgrt_check_version (REQUIRE_LIBGPGERROR_VERSION))
386 fprintf (stderr, _("gpgrt_check_version(): Incompatible libgpg-error. "
387 "Wanted %s, got %s.\n"), REQUIRE_LIBGPGERROR_VERSION,
388 gpgrt_check_version (NULL));
389 return GPG_ERR_UNKNOWN_VERSION;
392 gpgrt_init ();
393 //gpgrt_set_alloc_func (xrealloc_gpgrt);
395 if (!assuan_check_version (REQUIRE_LIBASSUAN_VERSION))
397 fprintf (stderr, _("assuan_check_version(): Incompatible libassuan. "
398 "Wanted %s, got %s.\n"), REQUIRE_LIBASSUAN_VERSION,
399 assuan_check_version (NULL));
400 return GPG_ERR_UNKNOWN_VERSION;
403 if (!gcry_check_version (REQUIRE_LIBGCRYPT_VERSION))
405 fprintf (stderr, _("gcry_check_version(): Incompatible libgcrypt. "
406 "Wanted %s, got %s.\n"), REQUIRE_LIBGCRYPT_VERSION,
407 gcry_check_version (NULL));
408 return GPG_ERR_UNKNOWN_VERSION;
411 gcry_set_allocation_handler (xmalloc, xmalloc, NULL, xrealloc, xfree);
413 if (!gpgme_check_version (REQUIRE_LIBGPGME_VERSION))
415 fprintf (stderr, _("gpgme_check_version(): Incompatible libgpgme. "
416 "Wanted %s, got %s.\n"), REQUIRE_LIBGPGME_VERSION,
417 gpgme_check_version (NULL));
418 return GPG_ERR_UNKNOWN_VERSION;
421 rc = gpgme_engine_check_version (GPGME_PROTOCOL_OPENPGP);
422 if (rc)
424 fprintf (stderr, _("gpgme_engine_check_version(GPGME_PROTOCOL_OPENPGP): %s"), gpgme_strerror (rc));
425 return GPG_ERR_UNKNOWN_VERSION;
428 //gpgme_set_global_flag ("require-gnupg", REQUIRE_GNUPG_VERSION);
429 #ifdef ENABLE_NLS
430 gpgme_set_locale (NULL, LC_CTYPE, setlocale (LC_CTYPE, NULL));
431 gpgme_set_locale (NULL, LC_MESSAGES, setlocale (LC_MESSAGES, NULL));
432 #endif
434 #ifdef WITH_GNUTLS
435 if (gnutls_global_init ())
437 fprintf(stderr, _("gnutls_global_init() failed.\n"));
438 return GPG_ERR_UNKNOWN_VERSION;
441 if (!gnutls_check_version (REQUIRE_LIBGNUTLS_VERSION))
443 fprintf (stderr, _("gnutls_check_version(): Incompatible libgnutls. "
444 "Wanted %s, got %s.\n"), REQUIRE_LIBGNUTLS_VERSION,
445 gnutls_check_version (NULL));
446 return GPG_ERR_UNKNOWN_VERSION;
449 gnutls_global_set_log_function (tls_log);
450 gnutls_global_set_audit_log_function (tls_audit_log);
451 #endif
452 return 0;
455 gpg_error_t
456 do_validate_peer (assuan_context_t ctx, const char *section,
457 assuan_peercred_t * peer)
459 char **users;
460 int allowed = 0;
461 gpg_error_t rc;
462 struct client_s *client = assuan_get_pointer (ctx);
464 if (!client)
465 return GPG_ERR_FORBIDDEN;
467 #ifdef WITH_GNUTLS
468 if (client->thd->remote)
469 return tls_validate_access (client, section);
470 #endif
472 rc = assuan_get_peercred (ctx, peer);
473 if (rc)
474 return rc;
476 users = config_get_list (section, "allowed");
477 if (users)
479 for (char **p = users; !rc && *p; p++)
481 rc = acl_check_common(client, *p, (*peer)->uid, (*peer)->gid,
482 &allowed);
485 strv_free (users);
487 else if (client->no_access_param)
488 allowed = 1;
490 return allowed && !rc ? 0 : rc ? rc : GPG_ERR_FORBIDDEN;
493 /* Test if uid is a member of group 'name'. Invert when 'not' is true. */
494 #ifdef HAVE_GETGRNAM_R
495 static gpg_error_t
496 acl_check_group (const char *name, uid_t uid, gid_t gid, int not, int *allowed)
498 char *buf;
499 struct group gr, *gresult;
500 size_t len = sysconf (_SC_GETGR_R_SIZE_MAX);
501 int err;
502 gpg_error_t rc = 0;
504 if (len == -1)
505 len = 16384;
507 buf = xmalloc (len);
508 if (!buf)
509 return GPG_ERR_ENOMEM;
511 err = getgrnam_r (name, &gr, buf, len, &gresult);
512 if (!err && gresult)
514 if (gresult->gr_gid == gid)
516 xfree (buf);
517 *allowed = !not;
518 return 0;
521 for (char **t = gresult->gr_mem; !rc && *t; t++)
523 char *tbuf;
524 struct passwd pw;
525 struct passwd *result = get_pwd_struct (*t, 0, &pw, &tbuf, &rc);
527 if (!rc && result && result->pw_uid == uid)
529 xfree (tbuf);
530 *allowed = !not;
531 break;
534 xfree (tbuf);
537 xfree (buf);
538 return rc;
540 else if (err)
541 rc = gpg_error_from_errno (err);
543 xfree (buf);
544 return rc ? rc : !gresult ? 0 : GPG_ERR_EACCES;
546 #else
547 static gpg_error_t
548 acl_check_group (const char *name, uid_t uid, gid_t gid, int not, int *allowed)
550 struct group *gresult;
551 gpg_error_t rc = 0;
553 errno = 0;
554 gresult = getgrnam (name);
555 if (!errno && gresult && gresult->gr_gid == gid)
557 *allowed = !not;
558 return 0;
560 else if (errno)
561 rc = gpg_error_from_syserror ();
562 else if (!gresult)
563 return 0;
565 for (char **t = gresult->gr_mem; !rc && *t; t++)
567 char *buf;
568 struct passwd pw;
569 struct passwd *result = get_pwd_struct (*t, 0, &pw, &buf, &rc);
571 if (!rc && result && result->pw_uid == uid)
573 xfree (buf);
574 *allowed = !not;
575 break;
578 xfree (buf);
581 return rc;
583 #endif
585 gpg_error_t
586 peer_is_invoker(struct client_s *client)
588 struct invoking_user_s *user;
589 int allowed = 0;
591 if (client->thd->state == CLIENT_STATE_UNKNOWN)
592 return GPG_ERR_EACCES;
594 for (user = invoking_users; user; user = user->next)
596 #ifdef WITH_GNUTLS
597 if (client->thd->remote)
599 if (user->type == INVOKING_TLS
600 && !strcmp(client->thd->tls->fp, user->id))
601 allowed = user->not ? 0 : 1;
603 continue;
605 #endif
607 if (user->type == INVOKING_GID)
609 gpg_error_t rc = acl_check_group (user->id,
610 client->thd->peer->uid,
611 client->thd->peer->gid,
612 user->not, &allowed);
613 if (rc)
614 return rc;
616 else if (user->type == INVOKING_UID && client->thd->peer->uid == user->uid)
617 allowed = user->not ? 0 : 1;
620 return allowed ? 0 : GPG_ERR_EACCES;
623 #ifdef HAVE_GETGRNAM_R
624 gpg_error_t
625 acl_check_common (struct client_s *client, const char *user, uid_t uid,
626 gid_t gid, int *allowed)
628 int not = 0;
629 int rw = 0;
630 int tls = 0;
631 gpg_error_t rc = 0;
633 if (!user || !*user)
634 return 0;
636 if (*user == '-' || *user == '!')
637 not = 1;
639 if (*user == '+') // not implemented yet
640 rw = 1;
642 if (*user == '#') // TLS fingerprint hash
643 tls = 1;
645 if (not || rw || tls)
646 user++;
648 if (tls)
650 #ifdef WITH_GNUTLS
651 if (client->thd->remote)
653 if (!strcasecmp (client->thd->tls->fp, user))
654 *allowed = !not;
657 return 0;
658 #else
659 return 0;
660 #endif
662 #ifdef WITH_GNUTLS
663 else if (client->thd->remote) // Remote client with no FP in the ACL
664 return 0;
665 #endif
667 if (*user == '@') // all users in group
668 return acl_check_group (user+1, uid, gid, not, allowed);
669 else
671 char *buf;
672 struct passwd pw;
673 struct passwd *pwd = get_pwd_struct (user, 0, &pw, &buf, &rc);
675 if (!rc && pwd && pwd->pw_uid == uid)
676 *allowed = !not;
678 xfree (buf);
681 return rc;
683 #else
684 gpg_error_t
685 acl_check_common (struct client_s *client, const char *user, uid_t uid,
686 gid_t gid, int *allowed)
688 gpg_error_t rc = 0;
689 int not = 0;
690 int rw = 0;
691 int tls = 0;
693 if (!user || !*user)
694 return 0;
696 if (*user == '-' || *user == '!')
697 not = 1;
699 if (*user == '+') // not implemented yet
700 rw = 1;
702 if (*user == '#') // TLS fingerprint hash
703 tls = 1;
705 if (not || rw || tls)
706 user++;
708 if (tls)
710 #ifdef WITH_GNUTLS
711 if (client->thd->remote)
713 if (!strcasecmp (client->thd->tls->fp, user))
714 *allowed = !not;
717 return 0;
718 #else
719 return 0;
720 #endif
723 if (*user == '@') // all users in group
724 return acl_check_group (user+1, uid, gid, not, allowed);
725 else
727 char *buf;
728 struct passwd pw;
729 struct passwd *result = get_pwd_struct (user, 0, &pw, &buf, &rc);
731 if (!rc && result && result->pw_uid == uid)
732 *allowed = !not;
734 xfree (buf);
737 return rc;
739 #endif
741 static gpg_error_t
742 validate_peer (struct client_s *cl)
744 gpg_error_t rc;
746 #ifdef WITH_GNUTLS
747 if (cl->thd->remote)
748 return tls_validate_access (cl, NULL);
749 #endif
751 MUTEX_LOCK (&cn_mutex);
752 pthread_cleanup_push (release_mutex_cb, &cn_mutex);
753 rc = do_validate_peer (cl->ctx, "global", &cl->thd->peer);
754 pthread_cleanup_pop (1);
755 log_write ("peer %s: uid=%i, gid=%i, pid=%i, rc=%u",
756 !rc ? _("accepted") : _("rejected"), cl->thd->peer->uid,
757 cl->thd->peer->gid, cl->thd->peer->pid, rc);
758 return rc;
761 static void
762 xml_error_cb (void *data, xmlErrorPtr e)
764 struct client_s *client = data;
767 * Keep the first reported error as the one to show in the error
768 * description. Reset in send_error().
770 if (client->xml_error)
771 return;
773 client->xml_error = xcalloc (1, sizeof(xmlError));
774 xmlCopyError (e, client->xml_error);
777 static pid_t
778 hook_waitpid (assuan_context_t ctx, pid_t pid, int action,
779 int *status, int options)
781 return waitpid (pid, status, options);
784 static ssize_t
785 hook_read (assuan_context_t ctx, assuan_fd_t fd, void *data, size_t len)
787 #ifdef WITH_GNUTLS
788 struct client_s *client = assuan_get_pointer (ctx);
790 if (client->thd->remote)
791 return tls_read_hook (ctx, (int) fd, data, len);
792 #endif
794 return read ((int) fd, data, len);
797 static ssize_t
798 hook_write (assuan_context_t ctx, assuan_fd_t fd,
799 const void *data, size_t len)
801 #ifdef WITH_GNUTLS
802 struct client_s *client = assuan_get_pointer (ctx);
804 if (client->thd->remote)
805 return tls_write_hook (ctx, (int) fd, data, len);
806 #endif
808 return write ((int) fd, data, len);
812 assuan_log_cb (assuan_context_t ctx, void *data, unsigned cat,
813 const char *msg)
815 struct client_s *client = data;
816 char *str = NULL;
818 (void)client;
820 if (!(assuan_level & cat))
821 return 0;
823 if (!msg)
824 return 1;
826 switch (cat)
828 case ASSUAN_LOG_INIT:
829 str = "ASSUAN[INIT]";
830 break;
831 case ASSUAN_LOG_CTX:
832 str = "ASSUAN[CTX]";
833 break;
834 case ASSUAN_LOG_ENGINE:
835 str = "ASSUAN[ENGINE]";
836 break;
837 case ASSUAN_LOG_DATA:
838 str = "ASSUAN[DATA]";
839 break;
840 case ASSUAN_LOG_SYSIO:
841 str = "ASSUAN[SYSIO]";
842 break;
843 case ASSUAN_LOG_CONTROL:
844 str = "ASSUAN[CONTROL]";
845 break;
846 default:
847 str = "ASSUAN[UNKNOWN]";
848 break;
851 log_write ("%s: %s", str, msg);
852 return 1;
855 static int
856 new_connection (struct client_s *cl)
858 gpg_error_t rc;
859 static struct assuan_malloc_hooks mhooks = { xmalloc, xrealloc, xfree };
860 static struct assuan_system_hooks shooks = {
861 ASSUAN_SYSTEM_HOOKS_VERSION,
862 __assuan_usleep,
863 __assuan_pipe,
864 __assuan_close,
865 hook_read,
866 hook_write,
867 //FIXME
868 NULL, //recvmsg
869 NULL, //sendmsg both are used for FD passing
870 __assuan_spawn,
871 hook_waitpid,
872 __assuan_socketpair,
873 __assuan_socket,
874 __assuan_connect
877 #ifdef WITH_GNUTLS
878 if (cl->thd->remote)
880 char *prio = config_get_string ("global", "tls_cipher_suite");
882 cl->thd->timeout = config_get_integer ("global", "tls_timeout");
883 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
884 return 0;
886 cl->thd->tls = tls_init_client (cl->thd->fd, cl->thd->timeout, prio);
887 xfree (prio);
888 if (!cl->thd->tls)
889 return 0;
891 #endif
893 rc = assuan_new_ext (&cl->ctx, GPG_ERR_SOURCE_DEFAULT, &mhooks,
894 assuan_log_cb, cl);
895 if (rc)
896 goto fail;
898 assuan_ctx_set_system_hooks (cl->ctx, &shooks);
899 rc = assuan_init_socket_server (cl->ctx, cl->thd->fd, 2);
900 if (rc)
901 goto fail;
903 assuan_set_pointer (cl->ctx, cl);
904 assuan_set_hello_line (cl->ctx, PACKAGE_STRING);
905 rc = register_commands (cl->ctx);
906 if (rc)
907 goto fail;
909 rc = assuan_accept (cl->ctx);
910 if (rc)
911 goto fail;
913 rc = validate_peer (cl);
914 /* May not be implemented on all platforms. */
915 if (rc && gpg_err_code (rc) != GPG_ERR_ASS_GENERAL)
916 goto fail;
918 MUTEX_LOCK (&cn_mutex);
919 cl->thd->state = CLIENT_STATE_INIT;
920 MUTEX_UNLOCK (&cn_mutex);
921 cl->lock_timeout = config_get_integer ("global", "lock_timeout");
922 xmlSetStructuredErrorFunc (cl, xml_error_cb);
923 return 1;
925 fail:
926 log_write ("%s", pwmd_strerror (rc));
927 return 0;
931 * This is called after a client_thread() terminates. Set with
932 * pthread_cleanup_push().
934 static void
935 free_client_cb (void *arg)
937 struct client_thread_s *cn = arg;
938 struct client_s *cl = cn->cl;
940 MUTEX_LOCK (&cn_mutex);
941 cn_thread_list = slist_remove (cn_thread_list, cn);
942 MUTEX_UNLOCK (&cn_mutex);
944 if (cl)
946 unlock_flock (&cl->flock_fd);
947 reset_client (cl);
948 if (cl->xml_error)
949 xmlResetError (cl->xml_error);
951 xfree (cl->xml_error);
953 #ifdef WITH_GNUTLS
954 if (cn->tls)
956 gnutls_deinit (cn->tls->ses);
957 xfree (cn->tls->fp);
958 xfree (cn->tls);
960 #endif
962 if (cl->ctx)
963 assuan_release (cl->ctx);
964 else if (cl->thd && cl->thd->fd != -1)
965 close (cl->thd->fd);
967 if (cl->crypto)
968 crypto_free (cl->crypto);
970 cl->crypto = NULL;
971 xfree (cl);
973 else
975 if (cn->fd != -1)
976 close (cn->fd);
979 while (cn->msg_queue)
981 struct status_msg_s *msg = cn->msg_queue;
983 cn->msg_queue = msg->next;
984 xfree (msg->line);
985 xfree (msg);
988 if (cn->status_msg_pipe[0] != -1)
989 close (cn->status_msg_pipe[0]);
991 if (cn->status_msg_pipe[1] != -1)
992 close (cn->status_msg_pipe[1]);
994 pthread_mutex_destroy (&cn->status_mutex);
995 log_write (_("exiting, fd=%i"), cn->fd);
996 send_status_all (STATUS_CLIENTS, NULL);
998 xfree (cn->name);
999 #ifdef WITH_GNUTLS
1000 xfree (cn->peeraddr);
1001 #endif
1002 xfree (cn);
1003 pthread_cond_signal (&quit_cond);
1006 void
1007 free_all_clients ()
1009 MUTEX_LOCK (&cn_mutex);
1010 pthread_cleanup_push (release_mutex_cb, &cn_mutex);
1012 while (slist_length (cn_thread_list))
1014 struct client_thread_s *thd = slist_nth_data (cn_thread_list, 0);
1016 free_client_cb (thd);
1019 exiting = 1;
1020 pthread_cleanup_pop (1);
1021 cache_deinit ();
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 #ifndef HAVE_PTHREAD_CANCEL
1074 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
1075 #endif
1077 #ifdef HAVE_PR_SET_NAME
1078 prctl (PR_SET_NAME, "client");
1079 #endif
1080 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1082 if (!cl)
1084 log_write ("%s(%i): %s", __FILE__, __LINE__,
1085 pwmd_strerror (GPG_ERR_ENOMEM));
1086 return NULL;
1089 MUTEX_LOCK (&cn_mutex);
1090 pthread_cleanup_push (free_client_cb, thd);
1091 thd->cl = cl;
1092 cl->thd = thd;
1093 cl->flock_fd = -1;
1094 MUTEX_UNLOCK (&cn_mutex);
1096 if (new_connection (cl))
1098 int finished = 0;
1099 gpg_error_t rc;
1100 struct pollfd fds[2];
1102 fds[0].fd = thd->fd;
1103 fds[0].events = POLLIN;
1104 fds[1].fd = thd->status_msg_pipe[0];
1105 fds[1].events = POLLIN;
1107 send_status_all (STATUS_CLIENTS, NULL);
1108 rc = send_status (cl->ctx, STATUS_CACHE, NULL);
1109 if (rc)
1111 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
1112 finished = 1;
1115 while (!finished)
1117 int n;
1118 int eof;
1120 n = poll (fds, 2, 100);
1121 if (n == -1)
1123 log_write ("%s", strerror (errno));
1124 break;
1127 #ifdef WITH_GNUTLS
1128 if (thd->remote && thd->tls && thd->tls->rehandshake)
1130 char *prio;
1131 int ret;
1132 const char *e;
1134 if (thd->tls->rehandshake == 1)
1136 prio = config_get_string ("global", "tls_cipher_suite");
1137 if (!prio)
1139 thd->tls->rehandshake = 0;
1140 continue;
1143 ret = gnutls_priority_set_direct (thd->tls->ses, prio, &e);
1144 if (ret == GNUTLS_E_SUCCESS)
1146 rc = send_status (cl->ctx, STATUS_REHANDSHAKE, NULL);
1147 if (!rc)
1149 rc = assuan_send_data (cl->ctx, NULL, 0);
1150 if (!rc)
1152 ret = gnutls_rehandshake (thd->tls->ses);
1153 if (ret)
1155 log_write ("%s", gnutls_strerror (ret));
1156 thd->tls->rehandshake = 0;
1158 else
1159 thd->tls->rehandshake = 2;
1163 if (rc)
1164 log_write ("%s", pwmd_strerror (rc));
1166 else
1167 log_write ("%s: %s", gnutls_strerror (ret), e);
1169 xfree (prio);
1170 continue;
1173 #endif
1175 if (!n)
1176 continue;
1178 if (fds[1].revents & POLLIN)
1180 #ifdef WITH_GNUTLS
1181 if (!thd->remote || (thd->tls && !thd->tls->rehandshake))
1182 #endif
1184 rc = send_msg_queue (thd);
1185 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1186 break;
1190 #ifdef HAVE_PTHREAD_CANCEL
1191 if (!(fds[0].revents & POLLIN))
1192 #else
1193 if (thd->fd != -1 && !(fds[0].revents & POLLIN))
1194 #endif
1195 continue;
1197 rc = assuan_process_next (cl->ctx, &eof);
1198 if (rc || eof)
1200 if (gpg_err_code (rc) == GPG_ERR_EOF || eof)
1201 break;
1203 log_write ("assuan_process_next(): rc=%u %s", rc,
1204 pwmd_strerror (rc));
1205 if (rc == gpg_error (GPG_ERR_ETIMEDOUT))
1206 break;
1208 rc = send_error (cl->ctx, rc);
1209 if (rc)
1211 log_write ("assuan_process_done(): rc=%u %s", rc,
1212 pwmd_strerror (rc));
1213 break;
1217 /* Since the msg queue pipe fd's are non-blocking, check for
1218 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1219 * client has already disconnected and will be converted to
1220 * GPG_ERR_EOF during assuan_process_next().
1222 #ifdef WITH_GNUTLS
1223 if (!thd->remote || (thd->tls && !thd->tls->rehandshake))
1224 #endif
1226 rc = send_msg_queue (thd);
1227 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1228 break;
1233 /* Don't do pthread_exit() here because any set pthread_cleanup_push
1234 * functions would be called after a command failed but then the client
1235 * exited normally which may lead to a double free. */
1236 pthread_cleanup_pop (1);
1237 return NULL;
1240 static gpg_error_t
1241 xml_import (const char *filename, const char *outfile, char **keyid,
1242 char **sign_keyid, char *keyfile, const char *keyparam,
1243 int symmetric)
1245 xmlDocPtr doc;
1246 int fd;
1247 struct stat st;
1248 int len;
1249 xmlChar *xmlbuf;
1250 gpg_error_t rc = 0;
1251 struct crypto_s *crypto = NULL;
1253 if (stat (filename, &st) == -1)
1255 rc = gpg_error_from_errno (errno);
1256 return rc;
1259 fd = open (filename, O_RDONLY);
1260 if (fd == -1)
1261 return gpg_error_from_errno (errno);
1263 xmlbuf = xmalloc (st.st_size + 1);
1264 if (!xmlbuf)
1266 close (fd);
1267 return GPG_ERR_ENOMEM;
1270 if (read (fd, xmlbuf, st.st_size) == -1)
1272 rc = gpg_error_from_errno (errno);
1273 close (fd);
1274 xfree (xmlbuf);
1275 return rc;
1278 close (fd);
1279 xmlbuf[st.st_size] = 0;
1280 // Be sure the document validates.
1281 doc = xmlReadDoc (xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS);
1282 xfree (xmlbuf);
1283 if (!doc)
1284 return GPG_ERR_BAD_DATA;
1286 xmlNodePtr n = xmlDocGetRootElement (doc);
1287 if (n && !xmlStrEqual (n->name, (xmlChar *) "pwmd"))
1288 rc = GPG_ERR_BAD_DATA;
1290 if (!rc)
1292 rc = xml_validate_import (NULL, n ? n->children : n);
1293 if (!rc)
1295 rc = crypto_init (&crypto, NULL, filename, keyfile != NULL, keyfile);
1296 if (!rc)
1298 if (keyfile)
1300 crypto->flags |= CRYPTO_FLAG_KEYFILE;
1301 crypto->keyfile = str_dup (keyfile);
1304 xmlDocDumpMemory (doc, &crypto->plaintext, &len);
1305 if (len > 0)
1306 crypto->plaintext_size = len;
1307 else
1308 rc = GPG_ERR_ENOMEM;
1313 if (!rc)
1315 if (!symmetric && (keyparam || !keyid))
1317 char *buf = NULL;
1319 if (keyparam)
1321 fd = open (keyparam, O_RDONLY);
1322 if (fd == -1)
1323 rc = gpg_error_from_errno (errno);
1325 if (!rc)
1327 if (stat (keyparam, &st) == -1)
1328 rc = gpg_error_from_errno (errno);
1330 if (!rc)
1332 buf = xmalloc (st.st_size+1);
1333 if (!buf)
1334 rc = GPG_ERR_ENOMEM;
1336 if (!rc)
1338 len = read (fd, buf, st.st_size);
1339 if (len != st.st_size)
1340 rc = gpg_error_from_errno (errno);
1342 if (!rc)
1343 buf[len] = 0;
1348 if (fd != -1)
1349 close (fd);
1351 else
1353 buf = crypto_default_key_params ();
1354 if (!buf)
1355 rc = GPG_ERR_ENOMEM;
1358 if (!rc)
1359 rc = crypto_genkey (NULL, crypto, (unsigned char *)buf);
1361 xfree (buf);
1363 else
1365 crypto->save.pubkey = strv_dup (keyid);
1366 crypto->save.sigkey = strv_dup (sign_keyid);
1369 if (!rc)
1371 crypto->flags |= symmetric ? CRYPTO_FLAG_SYMMETRIC : 0;
1372 rc = crypto_encrypt (NULL, crypto);
1376 if (!rc)
1378 if (!strcmp (outfile, "-"))
1379 outfile = NULL;
1381 xfree (crypto->plaintext);
1382 crypto->plaintext = NULL;
1383 xfree (crypto->filename);
1384 crypto->filename = outfile ? str_dup (outfile) : NULL;
1385 rc = crypto_write_file (crypto);
1388 xmlFreeDoc (doc);
1389 crypto_free (crypto);
1390 return rc;
1393 static gpg_error_t
1394 do_cache_push (struct crypto_s *crypto)
1396 gpg_error_t rc;
1397 xmlDocPtr doc;
1398 struct cache_data_s *cdata;
1399 unsigned char *crc;
1400 size_t len;
1401 int fd = -1;
1403 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1404 crypto->filename);
1406 if (valid_filename (crypto->filename) == 0)
1408 log_write (_("%s: Invalid characters in filename"), crypto->filename);
1409 return GPG_ERR_INV_VALUE;
1412 rc = lock_flock (NULL, crypto->filename, LOCK_SH, &fd);
1413 if (!rc)
1414 rc = crypto_decrypt (NULL, crypto);
1415 if (rc)
1417 unlock_flock (&fd);
1418 return rc;
1421 rc = xml_parse_doc ((char *) crypto->plaintext, crypto->plaintext_size, &doc);
1422 if (rc)
1424 unlock_flock (&fd);
1425 log_write ("%s", pwmd_strerror (rc));
1426 return rc;
1429 cdata = xcalloc (1, sizeof (struct cache_data_s));
1430 if (!cdata)
1432 unlock_flock (&fd);
1433 xmlFreeDoc (doc);
1434 return GPG_ERR_ENOMEM;
1437 rc = get_checksum (crypto->filename, &crc, &len);
1438 unlock_flock (&fd);
1439 if (rc)
1441 xmlFreeDoc (doc);
1442 cache_free_data_once (cdata);
1443 return rc;
1446 cdata->crc = crc;
1447 rc = cache_encrypt (crypto);
1448 if (!rc)
1450 cdata->doc = crypto->plaintext;
1451 cdata->size = crypto->plaintext_size;
1452 crypto->plaintext = NULL;
1453 cdata->pubkey = crypto->pubkey;
1454 cdata->sigkey = crypto->sigkey;
1455 crypto->pubkey = NULL;
1456 crypto->sigkey = NULL;
1458 else
1460 xmlFreeDoc (doc);
1461 cache_free_data_once (cdata);
1462 return rc;
1465 int timeout = config_get_integer (crypto->filename, "cache_timeout");
1466 rc = cache_add_file (crypto->filename, cdata, timeout);
1467 return rc;
1470 static gpg_error_t
1471 init_client (int fd, const char *addr)
1473 gpg_error_t rc = 0;
1474 struct client_thread_s *new = xcalloc (1, sizeof (struct client_thread_s));
1476 if (!new)
1478 close (fd);
1479 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (ENOMEM));
1480 return GPG_ERR_ENOMEM;
1483 MUTEX_LOCK (&cn_mutex);
1484 new->conntime = time (NULL);
1485 pthread_cleanup_push (release_mutex_cb, &cn_mutex);
1487 if (pipe (new->status_msg_pipe) == -1)
1488 rc = gpg_error_from_errno (errno);
1490 if (!rc)
1492 if (fcntl (new->status_msg_pipe[0], F_SETFL, O_NONBLOCK) == -1)
1493 rc = gpg_error_from_errno (errno);
1495 if (!rc)
1496 if (fcntl (new->status_msg_pipe[1], F_SETFL, O_NONBLOCK) == -1)
1497 rc = gpg_error_from_errno (errno);
1499 pthread_mutex_init (&new->status_mutex, NULL);
1502 if (!rc)
1504 #ifdef WITH_GNUTLS
1505 new->remote = addr ? 1 : 0;
1506 #endif
1507 new->fd = fd;
1508 rc = create_thread (client_thread, new, &new->tid, 1);
1509 if (rc)
1511 close (new->status_msg_pipe[0]);
1512 close (new->status_msg_pipe[1]);
1513 pthread_mutex_destroy (&new->status_mutex);
1517 if (!rc)
1519 struct slist_s *list = slist_append (cn_thread_list, new);
1521 if (list)
1523 cn_thread_list = list;
1524 if (addr)
1526 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1527 (pthread_t *) new->tid, fd, addr);
1528 #ifdef WITH_GNUTLS
1529 new->peeraddr = str_dup (addr);
1530 #endif
1532 else
1533 log_write (_("new connection: tid=%p, fd=%i"),
1534 (pthread_t *) new->tid, fd);
1536 else
1537 rc = GPG_ERR_ENOMEM;
1540 pthread_cleanup_pop (1);
1542 if (rc)
1544 xfree (new);
1545 close (fd);
1546 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1547 pwmd_strerror (rc));
1549 return rc;
1552 #ifdef WITH_GNUTLS
1553 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1554 static void *
1555 get_in_addr (struct sockaddr *sa)
1557 if (sa->sa_family == AF_INET)
1558 return &(((struct sockaddr_in *) sa)->sin_addr);
1560 return &(((struct sockaddr_in6 *) sa)->sin6_addr);
1563 static int
1564 start_stop_tls_with_protocol (int ipv6, int term)
1566 struct addrinfo hints, *servinfo, *p;
1567 int port = config_get_integer ("global", "tcp_port");
1568 char buf[7];
1569 int n;
1570 int *fd = ipv6 ? &tls6_fd : &tls_fd;
1572 if (term || config_get_boolean ("global", "enable_tcp") == 0)
1574 if (tls6_fd != -1)
1576 shutdown (tls6_fd, SHUT_RDWR);
1577 close (tls6_fd);
1578 tls6_fd = -1;
1581 if (tls_fd != -1)
1583 shutdown (tls_fd, SHUT_RDWR);
1584 close (tls_fd);
1585 tls_fd = -1;
1588 return 0;
1591 memset (&hints, 0, sizeof (hints));
1592 hints.ai_family = ipv6 ? AF_INET6 : AF_INET;
1593 hints.ai_socktype = SOCK_STREAM;
1594 hints.ai_flags = AI_PASSIVE;
1595 snprintf (buf, sizeof (buf), "%i", port);
1597 if ((n = getaddrinfo (NULL, buf, &hints, &servinfo)) == -1)
1599 log_write ("getaddrinfo(): %s", gai_strerror (n));
1600 return 0;
1603 for (n = 0, p = servinfo; p != NULL; p = p->ai_next)
1605 int r = 1;
1607 if ((ipv6 && p->ai_family != AF_INET6)
1608 || (!ipv6 && p->ai_family != AF_INET))
1609 continue;
1611 if ((*fd = socket (p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
1613 log_write ("socket(): %s", strerror (errno));
1614 continue;
1617 if (setsockopt (*fd, SOL_SOCKET, SO_REUSEADDR, &r, sizeof (int)) == -1)
1619 log_write ("setsockopt(): %s",
1620 pwmd_strerror (gpg_error_from_errno (errno)));
1621 freeaddrinfo (servinfo);
1622 goto fail;
1625 if (bind (*fd, p->ai_addr, p->ai_addrlen) == -1)
1627 close (*fd);
1628 log_write ("bind(): %s",
1629 pwmd_strerror (gpg_error_from_errno (errno)));
1630 continue;
1633 n++;
1634 break;
1637 freeaddrinfo (servinfo);
1639 if (!n)
1640 goto fail;
1642 #if HAVE_DECL_SO_BINDTODEVICE != 0
1643 char *tmp = config_get_string ("global", "tcp_interface");
1644 if (tmp && setsockopt (*fd, SOL_SOCKET, SO_BINDTODEVICE, tmp,
1645 strlen (tmp)) == -1)
1647 log_write ("setsockopt(): %s",
1648 pwmd_strerror (gpg_error_from_errno (errno)));
1649 xfree (tmp);
1650 goto fail;
1653 xfree (tmp);
1654 #endif
1656 if (listen (*fd, 128) == -1)
1658 log_write ("listen(): %s", strerror (errno));
1659 goto fail;
1662 return 1;
1664 fail:
1665 start_stop_tls_with_protocol (0, 1);
1666 if (tls_fd != -1)
1667 close (tls_fd);
1669 if (tls6_fd != -1)
1670 close (tls6_fd);
1672 tls_fd = -1;
1673 tls6_fd = -1;
1674 return 0;
1677 static int
1678 start_stop_tls (int term)
1680 char *s = config_get_string ("global", "tcp_bind");
1681 int b;
1683 if (!s)
1684 return 0;
1686 if (!strcmp (s, "any"))
1688 b = start_stop_tls_with_protocol (0, term);
1689 if (b)
1690 b = start_stop_tls_with_protocol (1, term);
1692 else if (!strcmp (s, "ipv4"))
1693 b = start_stop_tls_with_protocol (0, term);
1694 else if (!strcmp (s, "ipv6"))
1695 b = start_stop_tls_with_protocol (1, term);
1696 else
1697 b = 0;
1699 xfree (s);
1700 if (!term && b)
1702 gpg_error_t rc = tls_init_params ();
1703 if (rc)
1705 start_stop_tls_with_protocol (0, 1);
1706 return 0;
1710 return b;
1712 #endif
1714 #ifdef WITH_GNUTLS
1715 static gpg_error_t
1716 do_tls_accept (struct pollfd *fds)
1718 struct sockaddr_storage raddr;
1719 socklen_t slen = sizeof (raddr);
1720 int fd;
1721 char s[INET6_ADDRSTRLEN];
1723 if (!(fds->revents & POLLIN))
1724 return 0;
1726 fd = accept (fds->fd, (struct sockaddr *) &raddr, &slen);
1727 if (fd == -1)
1729 int e = errno;
1731 if (errno != EAGAIN && !quit)
1732 log_write ("%s: %s", __FUNCTION__,
1733 pwmd_strerror (gpg_error_from_syserror()));
1735 return gpg_error_from_errno (e);
1738 inet_ntop (raddr.ss_family, get_in_addr ((struct sockaddr *) &raddr), s,
1739 sizeof s);
1740 (void) init_client (fd, s);
1741 return 0;
1743 #endif
1745 static void *
1746 accept_thread (void *arg)
1748 int sockfd = *(int *) arg;
1749 #ifndef HAVE_PTHREAD_CANCEL
1750 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
1751 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1752 #endif
1754 #ifdef HAVE_PR_SET_NAME
1755 prctl (PR_SET_NAME, "accept");
1756 #endif
1757 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
1759 for (;;)
1761 socklen_t slen = sizeof (struct sockaddr_un);
1762 struct sockaddr_un raddr;
1763 int fd, s = 0;
1764 struct pollfd fds[3];
1766 TEST_CANCEL ();
1767 memset (fds, 0, sizeof (fds));
1768 fds[s].fd = sockfd;
1769 fds[s++].events = POLLIN;
1771 #ifdef WITH_GNUTLS
1772 if (tls_fd != -1)
1774 fds[s].fd = tls_fd;
1775 fds[s++].events = POLLIN;
1777 else
1778 fds[s].fd = tls_fd;
1780 if (tls6_fd != -1)
1782 fds[s].fd = tls6_fd;
1783 fds[s++].events = POLLIN;
1785 else
1786 fds[s].fd = tls6_fd;
1787 #endif
1789 s = poll (fds, s, 500);
1790 if (s == -1)
1792 if (errno != EINTR)
1793 log_write ("%s", strerror (errno));
1794 break;
1796 else if (s == 0)
1797 continue;
1799 if (fds[0].revents & POLLIN)
1801 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1802 if (fd == -1)
1804 if (errno == EMFILE || errno == ENFILE)
1805 log_write ("%s: %s", __FUNCTION__,
1806 pwmd_strerror (gpg_error_from_errno (errno)));
1807 else if (errno != EAGAIN && errno != EINTR)
1809 if (!quit) // probably EBADF
1810 log_write ("%s: %s", __FUNCTION__,
1811 pwmd_strerror (gpg_error_from_errno (errno)));
1813 break;
1816 continue;
1819 (void) init_client (fd, NULL);
1822 #ifdef WITH_GNUTLS
1823 if (tls_fd != -1 && fds[1].fd == tls_fd)
1824 (void)do_tls_accept (&fds[1]);
1826 if (tls6_fd != -1 && fds[1].fd == tls6_fd)
1827 (void)do_tls_accept (&fds[1]);
1829 if (tls6_fd != -1 && fds[2].fd == tls6_fd)
1830 (void)do_tls_accept (&fds[2]);
1831 #endif
1834 /* Just in case accept() failed for some reason other than EBADF */
1835 quit = 1;
1836 return NULL;
1839 static void *
1840 cache_timer_thread (void *arg)
1842 unsigned k = 0;
1843 #ifndef HAVE_PTHREAD_CANCEL
1844 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
1845 #endif
1847 #ifdef HAVE_PR_SET_NAME
1848 prctl (PR_SET_NAME, "timer");
1849 #endif
1850 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
1852 for (;;)
1854 struct timeval tv = { 1, 0 };
1855 unsigned keepalive = config_get_integer ("global", "keepalive_interval");
1857 TEST_CANCEL ();
1858 select (0, NULL, NULL, NULL, &tv);
1859 cache_adjust_timeout ();
1861 if (++k >= keepalive)
1863 send_status_all (STATUS_KEEPALIVE, NULL);
1864 k = 0;
1868 return NULL;
1871 static int
1872 signal_loop (sigset_t sigset)
1874 int done = 0;
1875 int siint = 0;
1879 int sig;
1881 sigwait (&sigset, &sig);
1883 if (sig != SIGQUIT)
1884 log_write (_("caught signal %i (%s)"), sig, strsignal (sig));
1886 switch (sig)
1888 case SIGHUP:
1889 pthread_cond_signal (&rcfile_cond);
1890 break;
1891 case SIGUSR1:
1892 log_write (_("clearing file cache"));
1893 cache_clear (NULL, NULL, 1);
1894 send_status_all (STATUS_CACHE, NULL);
1895 break;
1896 case SIGQUIT:
1897 done = 1;
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 waiting_for_exit (void *arg)
1923 int last = 0;
1924 #ifndef HAVE_PTHREAD_CANCEL
1925 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
1926 #endif
1928 #ifdef HAVE_PR_SET_NAME
1929 prctl (PR_SET_NAME, "exiting");
1930 #endif
1931 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
1932 log_write (_("waiting for all clients to disconnect"));
1933 MUTEX_LOCK (&quit_mutex);
1934 pthread_cleanup_push (release_mutex_cb, &quit_mutex);
1936 for (;;)
1938 struct timespec ts;
1939 int n;
1941 MUTEX_LOCK (&cn_mutex);
1942 n = slist_length (cn_thread_list);
1943 MUTEX_UNLOCK (&cn_mutex);
1944 if (!n)
1945 break;
1947 TEST_CANCEL ();
1949 if (last != n)
1951 log_write (_("%i clients remain"), n);
1952 last = n;
1955 INIT_TIMESPEC (SIG_TIMEOUT, ts);
1956 pthread_cond_timedwait (&quit_cond, &quit_mutex, &ts);
1959 kill (getpid (), SIGQUIT);
1960 pthread_cleanup_pop (1);
1961 return NULL;
1964 static int
1965 server_loop (int sockfd, char **socketpath)
1967 pthread_t cache_timeout_tid;
1968 int cancel_timeout_thread = 0, cancel_accept_thread = 0;
1969 sigset_t sigset;
1970 int n;
1971 int segv = 0;
1972 gpg_error_t rc;
1974 init_commands ();
1975 sigemptyset (&sigset);
1977 /* Termination */
1978 sigaddset (&sigset, SIGTERM);
1979 sigaddset (&sigset, SIGINT);
1981 /* Clears the file cache. */
1982 sigaddset (&sigset, SIGUSR1);
1984 /* Configuration file reloading. */
1985 sigaddset (&sigset, SIGHUP);
1987 /* For exiting cleanly. */
1988 sigaddset (&sigset, SIGQUIT);
1990 #ifndef HAVE_PTHREAD_CANCEL
1992 The socket, cache and rcfile threads use this signal when
1993 pthread_cancel() is unavailable. Prevent the main thread from
1994 catching this signal from another process.
1996 sigaddset (&sigset, SIGUSR2);
1997 #endif
1999 /* An assertion failure. */
2000 signal (SIGABRT, catchsig);
2001 sigaddset (&sigset, SIGABRT);
2002 sigprocmask (SIG_BLOCK, &sigset, NULL);
2004 #ifndef HAVE_PTHREAD_CANCEL
2005 /* Remove this signal from the watched signals in signal_loop(). */
2006 sigdelset (&sigset, SIGUSR2);
2007 #endif
2009 /* Can show a backtrace of the stack in the log. */
2010 signal (SIGSEGV, catchsig);
2012 pthread_mutex_init (&quit_mutex, NULL);
2013 pthread_cond_init (&quit_cond, NULL);
2014 char *p = get_username (getuid());
2015 log_write (_("%s started for user %s"), PACKAGE_STRING, p);
2016 xfree (p);
2018 #ifdef WITH_GNUTLS
2019 if (config_get_boolean ("global", "enable_tcp"))
2020 log_write (_("Listening on %s and TCP port %i"), *socketpath,
2021 config_get_integer ("global", "tcp_port"));
2022 else
2023 log_write (_("Listening on %s"), *socketpath);
2024 #else
2025 log_write (_("Listening on %s"), *socketpath);
2026 #endif
2028 rc = create_thread (reload_rcfile_thread, NULL, &rcfile_tid, 0);
2029 if (rc)
2031 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2032 pwmd_strerror (rc));
2033 goto done;
2036 rc = create_thread (cache_timer_thread, NULL, &cache_timeout_tid, 0);
2037 if (rc)
2039 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2040 pwmd_strerror (rc));
2041 goto done;
2044 cancel_timeout_thread = 1;
2045 rc = create_thread (accept_thread, &sockfd, &accept_tid, 0);
2046 if (rc)
2048 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2049 pwmd_strerror (rc));
2050 goto done;
2053 cancel_accept_thread = 1;
2054 if (!setjmp (jmp))
2055 signal_loop (sigset);
2056 else
2057 segv = 1;
2059 done:
2061 * We're out of the main server loop. This happens when a signal was sent
2062 * to terminate the daemon. We'll wait for all clients to disconnect
2063 * before exiting but exit immediately if another termination signal is
2064 * sent.
2066 if (cancel_accept_thread)
2068 #ifdef HAVE_PTHREAD_CANCEL
2069 int n = pthread_cancel (accept_tid);
2070 #else
2071 int n = pthread_kill (accept_tid, SIGUSR2);
2072 #endif
2073 if (!n)
2074 pthread_join (accept_tid, NULL);
2077 if (cancel_timeout_thread)
2079 #ifdef HAVE_PTHREAD_CANCEL
2080 n = pthread_cancel (cache_timeout_tid);
2081 #else
2082 n = pthread_kill (cache_timeout_tid, SIGUSR2);
2083 #endif
2084 if (!n)
2085 pthread_join (cache_timeout_tid, NULL);
2088 #ifdef WITH_GNUTLS
2089 start_stop_tls (1);
2090 #endif
2091 shutdown (sockfd, SHUT_RDWR);
2092 close (sockfd);
2093 unlink (*socketpath);
2094 xfree (*socketpath);
2095 *socketpath = NULL;
2096 MUTEX_LOCK (&cn_mutex);
2097 n = slist_length (cn_thread_list);
2098 MUTEX_UNLOCK (&cn_mutex);
2100 if (n && !segv)
2102 pthread_t tid;
2104 rc = create_thread (waiting_for_exit, NULL, &tid, 0);
2105 if (!rc)
2107 if (signal_loop (sigset))
2109 log_write (_("Received second termination request. Exiting."));
2110 #ifdef HAVE_PTHREAD_CANCEL
2111 pthread_cancel (tid);
2112 #else
2113 pthread_kill (tid, SIGUSR2);
2114 #endif
2115 pthread_join (tid, NULL);
2118 else
2119 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2120 pwmd_strerror (rc));
2123 free_all_clients ();
2124 deinit_commands ();
2125 pthread_cond_destroy (&quit_cond);
2126 pthread_mutex_destroy (&quit_mutex);
2127 return segv ? EXIT_FAILURE : EXIT_SUCCESS;;
2130 static void
2131 startup_failure ()
2133 log_write (_
2134 ("Failed to add a file to the cache. Use --force to force startup. Exiting."));
2135 cache_clear (NULL, NULL, 1);
2138 static void
2139 usage (const char *pn, int status)
2141 FILE *fp = status == EXIT_FAILURE ? stderr : stdout;
2143 fprintf (fp, _("Usage: %s [OPTIONS] [file1] [...]\n"
2144 " --debug=[a:..][,g:N][,t:N] enable debugging (a:[ixedsc],g:[1-9],t:[0-N])\n"
2145 " -f, --rcfile=filename load the specfied configuration file\n"
2146 " (~/.pwmd/config)\n"
2147 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2148 " --kill terminate an existing instance of pwmd\n"
2149 " -n, --no-fork run as a foreground process\n"
2150 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2151 " --ignore, --force ignore file errors during startup\n"
2152 " -o, --outfile=filename output file when importing or converting\n"
2153 " -C, --convert=filename convert a version 2 data file to version 3\n"
2154 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2155 " -k, --passphrase-file=file for use when importing or converting\n"
2156 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2157 " converting\n"
2158 " --no-passphrase when importing or converting\n"
2159 " --keyid=keyID[,..] public key to use when encrypting\n"
2160 " --sign-keyid=fpr[,..] fingerprint of the signing key to use\n"
2161 " --symmetric use conventional encryption with optional signer\n"
2162 " --keyparam=filename custom key parameters to use (gpg default)\n"
2163 " --help this help text\n"
2164 " --version show version and compile time features\n"),
2165 pn);
2166 exit (status);
2169 static void
2170 unlink_stale_socket (const char *sock, const char *pidfile)
2172 log_write (_ ("removing stale socket %s"), sock);
2173 unlink (sock);
2174 unlink (pidfile);
2177 static int
2178 test_pidfile (const char *path, const char *sock, char *buf, size_t buflen,
2179 char **pidfile, int create, mode_t mode, int terminate)
2181 pid_t pid;
2182 int fd;
2183 size_t len;
2185 if (!create)
2187 snprintf (buf, buflen, "%s/%s.pid", homedir, sock);
2188 *pidfile = str_dup (buf);
2189 fd = open (buf, O_RDONLY);
2191 else
2192 fd = open (*pidfile, O_CREAT|O_WRONLY|O_TRUNC, mode);
2194 if (fd == -1)
2196 if (!create && errno != ENOENT)
2198 log_write ("%s: %s", buf, pwmd_strerror (errno));
2199 free (*pidfile);
2200 *pidfile = NULL;
2201 return -1;
2203 else if (!create && !terminate)
2204 return 0;
2206 log_write ("%s: %s", *pidfile, strerror (errno));
2207 return -1;
2210 if (create)
2212 snprintf (buf, buflen, "%i", getpid ());
2213 ssize_t ret = write (fd, buf, strlen (buf));
2214 if (ret == -1)
2215 log_write ("%s (%i): %s", __FUNCTION__, __LINE__,
2216 pwmd_strerror (gpg_error_from_syserror ()));
2217 close (fd);
2218 return 0;
2221 len = read (fd, buf, buflen);
2222 close (fd);
2223 if (len == 0)
2225 unlink_stale_socket (path, *pidfile);
2226 return 0;
2229 if (sscanf (buf, "%5i", &pid) != 1 || pid == 0)
2231 if (!terminate)
2233 unlink_stale_socket (path, *pidfile);
2234 return 0;
2238 if (kill (pid, 0) == -1)
2240 unlink_stale_socket (path, *pidfile);
2241 return 0;
2244 if (terminate)
2246 if (kill (pid, SIGTERM) == -1)
2247 log_write ("%s: %s", path, pwmd_strerror (errno));
2249 else
2250 log_write (_ ("an instance for socket %s is already running"), path);
2252 xfree (*pidfile);
2253 *pidfile = NULL;
2254 return 1;
2257 static unsigned
2258 parse_debug_level (const char *str, unsigned *debug, int *gpgme, int *tls)
2260 const char *p;
2261 unsigned level = 0;
2262 int gl = 0, tl = 0;
2264 for (p = str; p && *p; p++)
2266 if (*p == 'a') // assuan debug flags
2268 if (*++p != ':')
2269 return 1;
2271 while (*++p)
2273 switch (*p)
2275 case 'i':
2276 level |= ASSUAN_LOG_INIT;
2277 break;
2278 case 'x':
2279 level |= ASSUAN_LOG_CTX;
2280 break;
2281 case 'e':
2282 level |= ASSUAN_LOG_ENGINE;
2283 break;
2284 case 'd':
2285 level |= ASSUAN_LOG_DATA;
2286 break;
2287 case 's':
2288 level |= ASSUAN_LOG_SYSIO;
2289 break;
2290 case 'c':
2291 level |= ASSUAN_LOG_CONTROL;
2292 break;
2293 case ',':
2294 break;
2295 default:
2296 return 1;
2299 if (*p == ',')
2300 break;
2303 if (!*p)
2304 break;
2306 else if (*p == 'g' || *p == 't') // gpgme and TLS debug level
2308 int t = *p == 't';
2309 int n;
2311 if (*++p != ':')
2312 return 1;
2314 if (!isdigit (*++p))
2315 return 1;
2317 n = atoi (p);
2318 if (t)
2319 tl = n;
2320 else
2321 gl = n;
2323 if (tl < 0 || gl < 0 || gl > 9)
2324 return 1;
2326 while (isdigit (*p))
2327 p++;
2329 p--;
2330 if (*(p+1) && *(p+1) != ',')
2331 return 1;
2332 else if (*(p+1))
2333 p++;
2335 else
2336 return 1;
2339 if (tl)
2340 *tls = tl;
2342 if (gl)
2343 *gpgme = gl;
2345 *debug = level;
2346 return 0;
2350 main (int argc, char *argv[])
2352 int opt;
2353 struct sockaddr_un addr;
2354 char buf[PATH_MAX];
2355 char *socketpath = NULL, *socketdir, *socketname = NULL;
2356 char *socketarg = NULL;
2357 char *datadir = NULL;
2358 char *pidfile = NULL;
2359 mode_t mode = 0600;
2360 int x;
2361 char *p;
2362 char **cache_push = NULL;
2363 char *import = NULL, *keyid = NULL, *sign_keyid = NULL;
2364 char *keyparam = NULL;
2365 int estatus = EXIT_FAILURE;
2366 int sockfd;
2367 char *outfile = NULL;
2368 int do_unlink = 0;
2369 int secure = 0;
2370 int show_version = 0;
2371 int force = 0;
2372 gpg_error_t rc;
2373 char *keyfile = NULL;
2374 int exists;
2375 int optindex;
2376 int terminate = 0;
2377 int sym = 0;
2378 int gpgme_level = -1;
2379 int tls_level = -1;
2380 /* Must maintain the same order as longopts[] */
2381 enum
2383 OPT_VERSION, OPT_HELP, OPT_HOMEDIR, OPT_NO_FORK, OPT_DISABLE_DUMP,
2384 OPT_FORCE, OPT_RCFILE, OPT_PASSPHRASE_FILE, OPT_IMPORT, OPT_OUTFILE,
2385 OPT_KEYID, OPT_SIGN_KEYID, OPT_SYMMETRIC, OPT_KEYPARAM, OPT_KILL,
2386 OPT_DEBUG
2388 const char *optstring = "nf:C:k:I:o:s";
2389 const struct option longopts[] = {
2390 {"version", no_argument, 0, 0},
2391 {"help", no_argument, 0, 0},
2392 {"homedir", required_argument, 0, 0},
2393 {"no-fork", no_argument, 0, 'n'},
2394 {"disable_dump", no_argument, 0, 0},
2395 {"force", no_argument, 0, 0},
2396 {"rcfile", required_argument, 0, 'f'},
2397 {"passphrase-file", required_argument, 0, 'k'},
2398 {"import", required_argument, 0, 'I'},
2399 {"outfile", required_argument, 0, 'o'},
2400 {"keyid", required_argument, 0, 0},
2401 {"sign-keyid", required_argument, 0, 0},
2402 {"symmetric", no_argument, 0, 's'},
2403 {"keyparam", required_argument, 0, 0},
2404 {"kill", no_argument, 0, 0},
2405 {"debug", required_argument, 0, 0},
2406 {0, 0, 0, 0}
2409 log_fd = -1;
2410 cmdline = 1;
2412 #ifndef DEBUG
2413 #ifdef HAVE_SETRLIMIT
2414 struct rlimit rl;
2416 rl.rlim_cur = rl.rlim_max = 0;
2418 if (setrlimit (RLIMIT_CORE, &rl) != 0)
2419 err (EXIT_FAILURE, "setrlimit()");
2420 #endif
2422 #ifdef HAVE_PR_SET_DUMPABLE
2423 prctl (PR_SET_DUMPABLE, 0);
2424 #endif
2425 #endif
2427 #ifdef ENABLE_NLS
2428 setlocale (LC_ALL, "");
2429 bindtextdomain ("pwmd", LOCALEDIR);
2430 textdomain ("pwmd");
2431 #endif
2433 if (setup_crypto ())
2434 exit (EXIT_FAILURE);
2436 #ifdef WITH_GNUTLS
2437 tls_level = tls_level == -1 ? 1 : tls_level;
2438 gnutls_global_set_log_level (tls_level);
2439 tls_fd = -1;
2440 tls6_fd = -1;
2441 #endif
2442 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
2443 xmlInitMemory ();
2444 xmlInitGlobals ();
2445 xmlInitParser ();
2446 xmlXPathInit ();
2448 while ((opt = getopt_long (argc, argv, optstring, longopts, &optindex))
2449 != -1)
2451 switch (opt)
2453 case 'I':
2454 import = optarg;
2455 break;
2456 case 'k':
2457 keyfile = optarg;
2458 break;
2459 case 'o':
2460 outfile = optarg;
2461 break;
2462 case 'D':
2463 secure = 1;
2464 break;
2465 case 'n':
2466 nofork = 1;
2467 break;
2468 case 'f':
2469 rcfile = str_dup (optarg);
2470 break;
2471 case 's':
2472 sym = 1;
2473 break;
2474 default:
2475 usage (argv[0], EXIT_FAILURE);
2476 break;
2477 case 0:
2478 switch (optindex)
2480 case OPT_DEBUG:
2481 if (parse_debug_level (optarg, &assuan_level, &gpgme_level,
2482 &tls_level))
2483 usage (argv[0], EXIT_FAILURE);
2484 break;
2485 case OPT_SYMMETRIC:
2486 sym = 1;
2487 break;
2488 case OPT_VERSION:
2489 show_version = 1;
2490 break;
2491 case OPT_HELP:
2492 usage (argv[0], EXIT_SUCCESS);
2493 break;
2494 case OPT_HOMEDIR:
2495 homedir = str_dup (optarg);
2496 break;
2497 case OPT_NO_FORK:
2498 nofork = 1;
2499 break;
2500 case OPT_DISABLE_DUMP:
2501 secure = 1;
2502 break;
2503 case OPT_FORCE:
2504 force = 1;
2505 break;
2506 case OPT_RCFILE:
2507 rcfile = str_dup (optarg);
2508 break;
2509 case OPT_PASSPHRASE_FILE:
2510 keyfile = optarg;
2511 break;
2512 case OPT_IMPORT:
2513 import = optarg;
2514 break;
2515 case OPT_OUTFILE:
2516 outfile = optarg;
2517 break;
2518 case OPT_KEYID:
2519 keyid = optarg;
2520 break;
2521 case OPT_SIGN_KEYID:
2522 sign_keyid = optarg;
2523 break;
2524 case OPT_KEYPARAM:
2525 keyparam = optarg;
2526 break;
2527 case OPT_KILL:
2528 terminate = 1;
2529 break;
2530 default:
2531 usage (argv[0], EXIT_FAILURE);
2536 if (show_version)
2538 printf (_("%s\n\n"
2539 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016\n"
2540 "%s\n"
2541 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2542 "Compile time features:\n%s"), PACKAGE_STRING,
2543 PACKAGE_BUGREPORT,
2544 #ifdef PWMD_HOMEDIR
2545 "+PWMD_HOMEDIR=" PWMD_HOMEDIR "\n"
2546 #endif
2547 #ifdef WITH_GNUTLS
2548 "+WITH_GNUTLS\n"
2549 #else
2550 "-WITH_GNUTLS\n"
2551 #endif
2552 #ifdef WITH_LIBACL
2553 "+WITH_LIBACL\n"
2554 #else
2555 "-WITH_LIBACL\n"
2556 #endif
2557 #ifdef DEBUG
2558 "+DEBUG\n"
2559 #else
2560 "-DEBUG\n"
2561 #endif
2562 #ifdef MEM_DEBUG
2563 "+MEM_DEBUG\n"
2564 #else
2565 "-MEM_DEBUG\n"
2566 #endif
2567 #ifdef MUTEX_DEBUG
2568 "+MUTEX_DEBUG\n"
2569 #else
2570 "-MUTEX_DEBUG\n"
2571 #endif
2573 exit (EXIT_SUCCESS);
2576 if (!homedir)
2577 #ifdef PWMD_HOMEDIR
2578 homedir = str_dup(PWMD_HOMEDIR);
2579 #else
2580 homedir = str_asprintf ("%s/.pwmd", get_home_dir());
2581 #endif
2583 if (mkdir (homedir, 0700) == -1 && errno != EEXIST)
2584 err (EXIT_FAILURE, "%s", homedir);
2586 if (!rcfile)
2587 rcfile = str_asprintf ("%s/config", homedir);
2589 pthread_key_create (&last_error_key, free_key);
2590 #ifndef HAVE_PTHREAD_CANCEL
2591 pthread_key_create (&signal_thread_key, free_key);
2592 #endif
2594 pthread_mutexattr_t attr;
2595 pthread_mutexattr_init (&attr);
2596 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
2597 pthread_mutex_init (&rcfile_mutex, &attr);
2598 global_config = config_parse (rcfile, 0);
2599 if (!global_config)
2601 pthread_mutexattr_destroy (&attr);
2602 pthread_mutex_destroy (&rcfile_mutex);
2603 exit (EXIT_FAILURE);
2606 p = config_get_string ("global", "gpg_homedir");
2607 if (!p)
2608 datadir = str_asprintf ("%s/.gnupg", homedir);
2609 else
2610 datadir = expand_homedir (p);
2612 xfree (p);
2613 if (mkdir (datadir, 0700) == -1 && errno != EEXIST)
2614 err (EXIT_FAILURE, "%s", datadir);
2616 if (gpgme_level != -1)
2618 char s[2] = { gpgme_level + '0', 0 };
2620 if (getenv ("GPGME_DEBUG"))
2621 log_write (_ ("Overriding GPGME_DEBUG environment with level %u!"),
2622 gpgme_level);
2624 gpgme_set_global_flag ("debug", s);
2627 rc = gpgme_set_engine_info (GPGME_PROTOCOL_OpenPGP, NULL, datadir);
2628 xfree (datadir);
2630 snprintf (buf, sizeof (buf), "%s/data", homedir);
2631 if (mkdir (buf, 0700) == -1 && errno != EEXIST)
2632 err (EXIT_FAILURE, "%s", buf);
2634 datadir = str_dup (buf);
2635 pthread_cond_init (&rcfile_cond, NULL);
2636 pthread_mutex_init (&cn_mutex, &attr);
2637 pthread_mutexattr_destroy (&attr);
2639 setup_logging ();
2641 x = config_get_int_param (global_config, "global", "priority", &exists);
2642 if (exists && x != atoi(INVALID_PRIORITY))
2644 errno = 0;
2645 if (setpriority (PRIO_PROCESS, 0, x) == -1)
2647 log_write ("setpriority(): %s",
2648 pwmd_strerror (gpg_error_from_errno (errno)));
2649 goto do_exit;
2652 #ifdef HAVE_MLOCKALL
2653 if (disable_mlock == 0 && mlockall (MCL_CURRENT | MCL_FUTURE) == -1)
2655 log_write ("mlockall(): %s",
2656 pwmd_strerror (gpg_error_from_errno (errno)));
2657 goto do_exit;
2659 #endif
2661 rc = cache_init ();
2662 if (rc)
2664 log_write ("pwmd: ERR %i: %s", rc, pwmd_strerror (rc));
2665 exit (EXIT_FAILURE);
2668 if (import)
2670 char **keyids = NULL, **sign_keyids = NULL;
2672 if (!outfile || !*outfile || argc != optind)
2673 usage (argv[0], EXIT_FAILURE);
2675 if (keyid)
2676 keyids = str_split (keyid, ",", 0);
2677 if (sign_keyid)
2678 sign_keyids = str_split (sign_keyid, ",", 0);
2679 rc = xml_import (import, outfile, keyids, sign_keyids, keyfile, keyparam, sym);
2680 strv_free (keyids);
2681 strv_free (sign_keyids);
2682 if (rc)
2684 if (gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
2685 rc = gpg_error (rc);
2687 log_write ("%s: %u: %s", import, rc, pwmd_strerror (rc));
2690 config_free (global_config);
2691 xfree (rcfile);
2692 exit (rc ? EXIT_FAILURE : EXIT_SUCCESS);
2695 p = config_get_string ("global", "socket_path");
2696 if (!p)
2697 p = str_asprintf ("%s/socket", homedir);
2699 socketarg = expand_homedir (p);
2700 xfree (p);
2702 if (!secure)
2703 disable_list_and_dump = config_get_boolean ("global",
2704 "disable_list_and_dump");
2705 else
2706 disable_list_and_dump = secure;
2708 cache_push = config_get_list ("global", "cache_push");
2710 while (optind < argc)
2712 if (strv_printf (&cache_push, "%s", argv[optind++]) == 0)
2713 errx (EXIT_FAILURE, "%s", pwmd_strerror (GPG_ERR_ENOMEM));
2716 if (strchr (socketarg, '/') == NULL)
2718 socketdir = getcwd (buf, sizeof (buf));
2719 socketname = str_dup (socketarg);
2720 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2722 else
2724 socketname = str_dup (strrchr (socketarg, '/'));
2725 socketname++;
2726 socketarg[strlen (socketarg) - strlen (socketname) - 1] = 0;
2727 socketdir = str_dup (socketarg);
2728 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2731 if (chdir (datadir))
2733 log_write ("%s: %s", datadir,
2734 pwmd_strerror (gpg_error_from_errno (errno)));
2735 unlink (socketpath);
2736 goto do_exit;
2739 x = test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 0,
2740 mode, terminate);
2741 if (!terminate && x)
2742 goto do_exit;
2743 else if (terminate)
2745 estatus = x != 1 ? EXIT_FAILURE : EXIT_SUCCESS;
2746 goto do_exit;
2750 * bind() doesn't like the full pathname of the socket or any non alphanum
2751 * characters so change to the directory where the socket is wanted then
2752 * create it then change to datadir.
2754 if (chdir (socketdir))
2756 log_write ("%s: %s", socketdir,
2757 pwmd_strerror (gpg_error_from_errno (errno)));
2758 goto do_exit;
2761 xfree (socketdir);
2763 if ((sockfd = socket (PF_UNIX, SOCK_STREAM, 0)) == -1)
2765 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2766 goto do_exit;
2769 addr.sun_family = AF_UNIX;
2770 snprintf (addr.sun_path, sizeof (addr.sun_path), "%s", socketname);
2771 do_unlink = 1;
2772 if (bind (sockfd, (struct sockaddr *) &addr, sizeof (struct sockaddr)) ==
2775 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2777 if (errno == EADDRINUSE)
2779 do_unlink = 0;
2780 log_write (_("Either there is another pwmd running or '%s' is a \n"
2781 "stale socket. Please remove it manually."), socketpath);
2784 goto do_exit;
2788 char *t = config_get_string ("global", "socket_perms");
2789 mode_t mask;
2791 if (t)
2793 mode = strtol (t, NULL, 8);
2794 mask = umask (0);
2795 xfree (t);
2797 if (chmod (socketname, mode) == -1)
2799 log_write ("%s: %s", socketname,
2800 pwmd_strerror (gpg_error_from_errno (errno)));
2801 close (sockfd);
2802 umask (mask);
2803 goto do_exit;
2806 umask (mask);
2810 xfree (--socketname);
2812 if (chdir (datadir))
2814 log_write ("%s: %s", datadir,
2815 pwmd_strerror (gpg_error_from_errno (errno)));
2816 close (sockfd);
2817 goto do_exit;
2820 xfree (datadir);
2821 #ifdef WITH_GNUTLS
2822 if (config_get_boolean ("global", "enable_tcp"))
2824 if (!start_stop_tls (0))
2826 close (sockfd);
2827 goto do_exit;
2830 #endif
2833 * Set the cache entry for a file. Prompts for the password.
2835 if (cache_push)
2837 for (opt = 0; cache_push[opt]; opt++)
2839 struct crypto_s *crypto = NULL;
2840 char *pw_file = config_get_string (cache_push[opt],
2841 "passphrase_file");
2842 gpg_error_t rc = crypto_init (&crypto, NULL, cache_push[opt],
2843 pw_file != NULL, pw_file);
2845 if (!rc)
2847 crypto->flags |= pw_file ? CRYPTO_FLAG_KEYFILE : 0;
2848 crypto->keyfile = pw_file;
2850 else
2851 xfree (pw_file);
2853 if (rc)
2855 estatus = EXIT_FAILURE;
2856 goto do_exit;
2859 rc = do_cache_push (crypto);
2860 if (rc && !force)
2862 log_write ("ERR %u: %s", rc, pwmd_strerror(rc));
2863 strv_free (cache_push);
2864 startup_failure ();
2865 estatus = EXIT_FAILURE;
2866 crypto_free (crypto);
2867 goto do_exit;
2869 else if (rc)
2870 log_write ("%s: %s", crypto->filename, pwmd_strerror(rc));
2871 else
2872 log_write (_("Successfully added '%s' to the cache."),
2873 crypto->filename);
2875 crypto_free (crypto);
2878 strv_free (cache_push);
2879 log_write (!nofork ? _("Done. Daemonizing...") :
2880 _("Done. Waiting for connections..."));
2883 if (listen (sockfd, 128) == -1)
2885 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2886 goto do_exit;
2889 if (!nofork)
2891 switch (fork ())
2893 case -1:
2894 log_write ("fork(): %s",
2895 pwmd_strerror (gpg_error_from_errno (errno)));
2896 goto do_exit;
2897 case 0:
2898 close (0);
2899 close (1);
2900 close (2);
2901 setsid ();
2902 break;
2903 default:
2904 _exit (EXIT_SUCCESS);
2908 (void)test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 1,
2909 mode, 0);
2910 cmdline = 0;
2911 pthread_key_create (&thread_name_key, free_key);
2912 estatus = server_loop (sockfd, &socketpath);
2914 do_exit:
2915 if (socketpath && do_unlink)
2917 unlink (socketpath);
2918 xfree (socketpath);
2921 xfree (socketarg);
2922 #ifdef WITH_GNUTLS
2923 gnutls_global_deinit ();
2924 tls_deinit_params ();
2925 #endif
2926 if (rcfile_tid)
2928 #ifdef HAVE_PTHREAD_CANCEL
2929 pthread_cancel (rcfile_tid);
2930 #else
2931 pthread_kill (rcfile_tid, SIGUSR2);
2932 pthread_cond_signal (&rcfile_cond);
2933 #endif
2934 pthread_join (rcfile_tid, NULL);
2937 pthread_cond_destroy (&rcfile_cond);
2938 pthread_mutex_destroy (&rcfile_mutex);
2939 pthread_key_delete (last_error_key);
2940 #ifndef HAVE_PTHREAD_CANCEL
2941 pthread_key_delete (signal_thread_key);
2942 #endif
2944 if (global_config)
2945 config_free (global_config);
2947 free_invoking_users (invoking_users);
2948 xfree (rcfile);
2949 xfree (home_directory);
2950 xfree (homedir);
2951 xmlCleanupParser ();
2952 xmlCleanupGlobals ();
2954 if (pidfile)
2955 unlink (pidfile);
2956 xfree (pidfile);
2958 if (estatus == EXIT_SUCCESS && !terminate)
2959 log_write (_("pwmd exiting normally"));
2961 pthread_key_delete (thread_name_key);
2962 closelog ();
2964 if (log_fd != -1)
2965 close (log_fd);
2967 exit (estatus);
2970 gpg_error_t lock_flock (assuan_context_t ctx, const char *filename,
2971 int type, int *fd)
2973 gpg_error_t rc = 0;
2975 #ifdef HAVE_FLOCK
2976 *fd = open (filename, O_RDONLY);
2977 if (*fd == -1)
2978 return gpg_error_from_syserror ();
2980 TRY_FLOCK (ctx, *fd, type, rc);
2981 if (rc)
2983 close (*fd);
2984 *fd = -1;
2986 #endif
2988 return rc;
2991 void unlock_flock (int *fd)
2993 #ifdef HAVE_FLOCK
2994 if (*fd != -1)
2995 close (*fd);
2997 *fd = -1;
2998 #endif