Allocate the priority after the condition is triggered.
[pwmd.git] / src / pwmd.c
blob03c9650ad900265f4cd4701c277721010736292c
1 /*
2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015,
3 2016
4 Ben Kibbey <bjk@luxsci.net>
6 This file is part of pwmd.
8 Pwmd is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 2 of the License, or
11 (at your option) any later version.
13 Pwmd is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
21 #ifdef HAVE_CONFIG_H
22 #include <config.h>
23 #endif
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <err.h>
29 #include <ctype.h>
30 #include <string.h>
31 #include <sys/socket.h>
32 #include <sys/un.h>
33 #include <signal.h>
34 #include <stdarg.h>
35 #include <string.h>
36 #include <sys/wait.h>
37 #include <fcntl.h>
38 #include <pwd.h>
39 #include <grp.h>
40 #include <pthread.h>
41 #include <sys/mman.h>
42 #include <termios.h>
43 #include <assert.h>
44 #include <syslog.h>
45 #include <netinet/in.h>
46 #include <arpa/inet.h>
47 #include <netdb.h>
48 #include <sys/time.h>
49 #include <sys/resource.h>
50 #include <setjmp.h>
51 #include <errno.h>
52 #include <poll.h>
54 #ifdef TM_IN_SYS_TIME
55 #include <sys/time.h>
56 #else
57 #include <time.h>
58 #endif
60 #ifdef HAVE_LIMITS_H
61 #include <limits.h>
62 #endif
64 #ifdef HAVE_GETOPT_LONG
65 #ifdef HAVE_GETOPT_H
66 #include <getopt.h>
67 #endif
68 #else
69 #include "getopt_long.h"
70 #endif
72 #ifdef HAVE_PR_SET_NAME
73 #include <sys/prctl.h>
74 #endif
76 #include "pwmd-error.h"
77 #include <gcrypt.h>
79 #include "util-misc.h"
80 #include "mem.h"
81 #include "xml.h"
82 #include "common.h"
83 #include "commands.h"
84 #include "cache.h"
85 #include "util-string.h"
86 #include "mutex.h"
87 #include "rcfile.h"
88 #include "crypto.h"
90 /* In tenths of a second. */
91 #define SIG_TIMEOUT 1
93 /* For (tcp_)accept_thread (usec). */
94 #define ACCEPT_TIMEOUT 50000
96 static int quit;
97 static int cmdline;
98 static jmp_buf jmp;
99 static int nofork;
100 static pthread_cond_t quit_cond;
101 static pthread_mutex_t quit_mutex;
102 static int log_fd;
103 static unsigned assuan_level;
105 #ifndef HAVE_PTHREAD_CANCEL
106 static pthread_key_t signal_thread_key;
107 #endif
109 pthread_t accept_tid;
110 #ifdef WITH_GNUTLS
111 static int tls_fd;
112 static int tls6_fd;
113 static int start_stop_tls (int term);
114 #endif
116 static gpg_error_t do_cache_push (struct crypto_s *crypto);
117 static int signal_loop (sigset_t sigset);
119 #ifndef HAVE_PTHREAD_CANCEL
120 #define INIT_SIGNAL(s, cb) do { \
121 struct sigaction act; \
122 sigset_t sigset; \
123 sigemptyset (&sigset); \
124 sigaddset (&sigset, s); \
125 pthread_sigmask (SIG_UNBLOCK, &sigset, NULL); \
126 memset (&act, 0, sizeof(act)); \
127 act.sa_flags = SA_SIGINFO; \
128 act.sa_mask = sigset; \
129 act.sa_sigaction = cb; \
130 sigaction (s, &act, NULL); \
131 } while (0)
133 #define TEST_CANCEL() do { \
134 int *cancel = (int *) pthread_getspecific (signal_thread_key); \
135 if (cancel && *cancel) \
136 pthread_exit (NULL); \
137 } while (0)
138 #else
139 #define TEST_CANCEL()
140 #endif
142 #ifndef HAVE_PTHREAD_CANCEL
143 static void
144 catch_thread_signal (int sig, siginfo_t *info, void *ctx)
146 int *n = (int *) pthread_getspecific (signal_thread_key);
148 *n = 1;
149 pthread_setspecific (signal_thread_key, n);
151 #endif
153 static void
154 setup_logging ()
156 int n = config_get_boolean ("global", "enable_logging");
158 if (n)
160 char *p = config_get_string ("global", "log_path");
162 if (!p || (logfile && p && log_fd != -1 && strcmp(p, logfile)))
164 if (log_fd != -1)
165 close (log_fd);
167 log_fd = -1;
170 xfree (logfile);
171 logfile = NULL;
172 if (p)
173 logfile = expand_homedir (p);
174 xfree (p);
176 else
178 xfree (logfile);
179 logfile = NULL;
180 if (log_fd != -1)
181 close(log_fd);
183 log_fd = -1;
184 closelog ();
187 log_syslog = config_get_boolean ("global", "syslog");
188 if (log_syslog == 1)
189 openlog ("pwmd", LOG_NDELAY | LOG_PID, LOG_DAEMON);
192 static void *
193 reload_rcfile_thread (void *arg)
195 #ifndef HAVE_PTHREAD_CANCEL
196 int *n = xmalloc (sizeof (int));
198 *n = 0;
199 pthread_setspecific (signal_thread_key, n);
200 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
201 #endif
203 #ifdef HAVE_PR_SET_NAME
204 prctl (PR_SET_NAME, "reload rcfile");
205 #endif
206 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
207 MUTEX_LOCK (&rcfile_mutex);
209 for (;;)
211 struct slist_s *keep = NULL;
212 struct slist_s *config;
213 int b = disable_list_and_dump;
214 #ifdef WITH_GNUTLS
215 char *prio;
216 char *prio2 = NULL;
217 #endif
219 pthread_cleanup_push (release_mutex_cb, &rcfile_mutex);
220 pthread_cond_wait (&rcfile_cond, &rcfile_mutex);
221 TEST_CANCEL ();
222 keep = config_keep_save ();
223 log_write (_("reloading configuration file '%s'"), rcfile);
225 prio = config_get_string ("global", "tls_cipher_suite");
226 config = config_parse (rcfile, 1);
227 if (config)
229 config_free (global_config);
230 global_config = config;
231 setup_logging ();
234 config_keep_restore (keep);
235 disable_list_and_dump = !disable_list_and_dump ? b : 1;
237 #ifdef WITH_GNUTLS
238 /* Restart listening sockets since they may have changed. */
239 start_stop_tls (1);
240 start_stop_tls (0);
242 prio2 = config_get_string ("global", "tls_cipher_suite");
243 if ((prio2 && (!prio || strcmp (prio, prio2))) || (prio && !prio2))
244 tls_rehandshake ();
246 xfree (prio2);
247 xfree (prio);
248 #endif
249 crypto_set_keepalive ();
250 pthread_cleanup_pop (0);
253 MUTEX_UNLOCK (&rcfile_mutex);
254 return NULL;
257 gpg_error_t
258 send_error (assuan_context_t ctx, gpg_error_t e)
260 struct client_s *client = assuan_get_pointer (ctx);
262 if (gpg_err_source (e) == GPG_ERR_SOURCE_UNKNOWN)
263 e = gpg_error (e);
265 if (client)
266 client->last_rc = e;
268 if (!e)
269 return assuan_process_done (ctx, 0);
271 if (!ctx)
273 log_write ("ERR %i: %s", e, pwmd_strerror (e));
274 return e;
277 if (client && client->xml_error)
279 log_write ("%s", client->xml_error->message);
280 xfree (client->last_error);
281 client->last_error = NULL;
282 if (client->xml_error->message)
283 client->last_error = str_dup (client->xml_error->message);
285 e = assuan_process_done (ctx,
286 assuan_set_error (ctx, e,
287 client->xml_error->message ? client->xml_error->message : NULL));
288 xmlResetLastError ();
289 xmlResetError (client->xml_error);
290 xfree (client->xml_error);
291 client->xml_error = NULL;
292 return e;
295 return assuan_process_done (ctx,
296 assuan_set_error (ctx, e, pwmd_strerror (e)));
299 void
300 log_write (const char *fmt, ...)
302 char *args;
303 va_list ap;
304 time_t now;
305 char buf[255];
306 pthread_t tid = pthread_self ();
307 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
309 if ((!logfile && !isatty (STDERR_FILENO) && !log_syslog) || !fmt)
310 return;
312 pthread_mutex_lock (&m);
313 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock, &m);
315 if (!cmdline && logfile && log_fd == -1)
317 log_fd = open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600);
318 if (log_fd == -1)
319 warn ("%s", logfile);
322 va_start (ap, fmt);
324 if (str_vasprintf (&args, fmt, ap) != -1)
326 if (cmdline)
328 pthread_cleanup_push (xfree, args);
329 fprintf (stderr, "pwmd: %s\n", args);
330 fflush (stderr);
331 pthread_cleanup_pop (1);
333 else
335 char *name = pthread_getspecific (thread_name_key);
336 char *line;
338 pthread_cleanup_push (xfree, args);
339 snprintf (buf, sizeof (buf),
340 name && *name == '!' ? "%s: " : name ? "%s(%p): " : "%s",
341 name ? *name == '!' ? name+1 : name : "",
342 name && *name == '!' ? 0 : name ? (pthread_t *) tid : 0);
343 name = buf;
345 if (!cmdline && log_syslog && !nofork)
346 syslog (LOG_INFO, "%s%s", name, args);
348 time (&now);
349 struct tm *tm = localtime (&now);
350 char tbuf[21];
351 strftime (tbuf, sizeof (tbuf), "%b %d %Y %H:%M:%S ", tm);
352 tbuf[sizeof (tbuf) - 1] = 0;
354 if (args[strlen (args) - 1] == '\n')
355 args[strlen (args) - 1] = 0;
357 line = str_asprintf ("%s %i %s%s\n", tbuf, getpid (), name,
358 args);
359 pthread_cleanup_pop (1);
360 if (line)
362 pthread_cleanup_push (xfree, line);
363 if (logfile && log_fd != -1)
365 ssize_t ret = write (log_fd, line, strlen (line));
366 (void)ret;
367 fsync (log_fd);
370 if (nofork)
372 fprintf (stdout, "%s", line);
373 fflush (stdout);
376 pthread_cleanup_pop (1);
381 va_end (ap);
382 pthread_cleanup_pop (0);
384 if (log_fd != -1 && log_keepopen <= 0)
386 close(log_fd);
387 log_fd = -1;
390 pthread_mutex_unlock (&m);
393 static gpg_error_t
394 setup_crypto ()
396 gpg_error_t rc;
398 if (!gpgrt_check_version (REQUIRE_LIBGPGERROR_VERSION))
400 fprintf (stderr, _("gpgrt_check_version(): Incompatible libgpg-error. "
401 "Wanted %s, got %s.\n"), REQUIRE_LIBGPGERROR_VERSION,
402 gpgrt_check_version (NULL));
403 return GPG_ERR_UNKNOWN_VERSION;
406 gpgrt_init ();
407 //gpgrt_set_alloc_func (xrealloc_gpgrt);
409 if (!assuan_check_version (REQUIRE_LIBASSUAN_VERSION))
411 fprintf (stderr, _("assuan_check_version(): Incompatible libassuan. "
412 "Wanted %s, got %s.\n"), REQUIRE_LIBASSUAN_VERSION,
413 assuan_check_version (NULL));
414 return GPG_ERR_UNKNOWN_VERSION;
417 if (!gcry_check_version (REQUIRE_LIBGCRYPT_VERSION))
419 fprintf (stderr, _("gcry_check_version(): Incompatible libgcrypt. "
420 "Wanted %s, got %s.\n"), REQUIRE_LIBGCRYPT_VERSION,
421 gcry_check_version (NULL));
422 return GPG_ERR_UNKNOWN_VERSION;
425 gcry_set_allocation_handler (xmalloc, xmalloc, NULL, xrealloc, xfree);
427 if (!gpgme_check_version (REQUIRE_LIBGPGME_VERSION))
429 fprintf (stderr, _("gpgme_check_version(): Incompatible libgpgme. "
430 "Wanted %s, got %s.\n"), REQUIRE_LIBGPGME_VERSION,
431 gpgme_check_version (NULL));
432 return GPG_ERR_UNKNOWN_VERSION;
435 rc = gpgme_engine_check_version (GPGME_PROTOCOL_OPENPGP);
436 if (rc)
438 fprintf (stderr, _("gpgme_engine_check_version(GPGME_PROTOCOL_OPENPGP): %s"), gpgme_strerror (rc));
439 return GPG_ERR_UNKNOWN_VERSION;
442 //gpgme_set_global_flag ("require-gnupg", REQUIRE_GNUPG_VERSION);
443 #ifdef ENABLE_NLS
444 gpgme_set_locale (NULL, LC_CTYPE, setlocale (LC_CTYPE, NULL));
445 gpgme_set_locale (NULL, LC_MESSAGES, setlocale (LC_MESSAGES, NULL));
446 #endif
448 #ifdef WITH_GNUTLS
449 if (gnutls_global_init ())
451 fprintf(stderr, _("gnutls_global_init() failed.\n"));
452 return GPG_ERR_UNKNOWN_VERSION;
455 if (!gnutls_check_version (REQUIRE_LIBGNUTLS_VERSION))
457 fprintf (stderr, _("gnutls_check_version(): Incompatible libgnutls. "
458 "Wanted %s, got %s.\n"), REQUIRE_LIBGNUTLS_VERSION,
459 gnutls_check_version (NULL));
460 return GPG_ERR_UNKNOWN_VERSION;
463 gnutls_global_set_log_function (tls_log);
464 gnutls_global_set_audit_log_function (tls_audit_log);
465 #endif
466 return 0;
469 gpg_error_t
470 do_validate_peer (assuan_context_t ctx, const char *section,
471 assuan_peercred_t * peer)
473 char **users;
474 int allowed = 0;
475 gpg_error_t rc;
476 struct client_s *client = assuan_get_pointer (ctx);
478 if (!client)
479 return GPG_ERR_FORBIDDEN;
481 #ifdef WITH_GNUTLS
482 if (client->thd->remote)
483 return tls_validate_access (client, section);
484 #endif
486 rc = assuan_get_peercred (ctx, peer);
487 if (rc)
488 return rc;
490 users = config_get_list (section, "allowed");
491 if (users)
493 for (char **p = users; !rc && *p; p++)
495 rc = acl_check_common(client, *p, (*peer)->uid, (*peer)->gid,
496 &allowed);
499 strv_free (users);
501 else if (client->no_access_param)
502 allowed = 1;
504 return allowed && !rc ? 0 : rc ? rc : GPG_ERR_FORBIDDEN;
507 /* Test if uid is a member of group 'name'. Invert when 'not' is true. */
508 #ifdef HAVE_GETGRNAM_R
509 static gpg_error_t
510 acl_check_group (const char *name, uid_t uid, gid_t gid, int not, int *allowed)
512 char *buf;
513 struct group gr, *gresult;
514 size_t len = sysconf (_SC_GETGR_R_SIZE_MAX);
515 int err;
516 gpg_error_t rc = 0;
518 if (len == -1)
519 len = 16384;
521 buf = xmalloc (len);
522 if (!buf)
523 return GPG_ERR_ENOMEM;
525 err = getgrnam_r (name, &gr, buf, len, &gresult);
526 if (!err && gresult)
528 if (gresult->gr_gid == gid)
530 xfree (buf);
531 *allowed = !not;
532 return 0;
535 for (char **t = gresult->gr_mem; !rc && *t; t++)
537 char *tbuf;
538 struct passwd pw;
539 struct passwd *result = get_pwd_struct (*t, 0, &pw, &tbuf, &rc);
541 if (!rc && result && result->pw_uid == uid)
543 xfree (tbuf);
544 *allowed = !not;
545 break;
548 xfree (tbuf);
551 xfree (buf);
552 return rc;
554 else if (err)
555 rc = gpg_error_from_errno (err);
557 xfree (buf);
558 return rc ? rc : !gresult ? 0 : GPG_ERR_EACCES;
560 #else
561 static gpg_error_t
562 acl_check_group (const char *name, uid_t uid, gid_t gid, int not, int *allowed)
564 struct group *gresult;
565 gpg_error_t rc = 0;
567 errno = 0;
568 gresult = getgrnam (name);
569 if (!errno && gresult && gresult->gr_gid == gid)
571 *allowed = !not;
572 return 0;
574 else if (errno)
575 rc = gpg_error_from_syserror ();
576 else if (!gresult)
577 return 0;
579 for (char **t = gresult->gr_mem; !rc && *t; t++)
581 char *buf;
582 struct passwd pw;
583 struct passwd *result = get_pwd_struct (*t, 0, &pw, &buf, &rc);
585 if (!rc && result && result->pw_uid == uid)
587 xfree (buf);
588 *allowed = !not;
589 break;
592 xfree (buf);
595 return rc;
597 #endif
599 gpg_error_t
600 peer_is_invoker(struct client_s *client)
602 struct invoking_user_s *user;
603 int allowed = 0;
605 if (client->thd->state == CLIENT_STATE_UNKNOWN)
606 return GPG_ERR_EACCES;
608 for (user = invoking_users; user; user = user->next)
610 #ifdef WITH_GNUTLS
611 if (client->thd->remote)
613 if (user->type == INVOKING_TLS
614 && !strcmp(client->thd->tls->fp, user->id))
615 allowed = user->not ? 0 : 1;
617 continue;
619 #endif
621 if (user->type == INVOKING_GID)
623 gpg_error_t rc = acl_check_group (user->id,
624 client->thd->peer->uid,
625 client->thd->peer->gid,
626 user->not, &allowed);
627 if (rc)
628 return rc;
630 else if (user->type == INVOKING_UID && client->thd->peer->uid == user->uid)
631 allowed = user->not ? 0 : 1;
634 return allowed ? 0 : GPG_ERR_EACCES;
637 #ifdef HAVE_GETGRNAM_R
638 gpg_error_t
639 acl_check_common (struct client_s *client, const char *user, uid_t uid,
640 gid_t gid, int *allowed)
642 int not = 0;
643 int rw = 0;
644 int tls = 0;
645 gpg_error_t rc = 0;
647 if (!user || !*user)
648 return 0;
650 if (*user == '-' || *user == '!')
651 not = 1;
653 if (*user == '+') // not implemented yet
654 rw = 1;
656 if (*user == '#') // TLS fingerprint hash
657 tls = 1;
659 if (not || rw || tls)
660 user++;
662 if (tls)
664 #ifdef WITH_GNUTLS
665 if (client->thd->remote)
667 if (!strcasecmp (client->thd->tls->fp, user))
668 *allowed = !not;
671 return 0;
672 #else
673 return 0;
674 #endif
676 #ifdef WITH_GNUTLS
677 else if (client->thd->remote) // Remote client with no FP in the ACL
678 return 0;
679 #endif
681 if (*user == '@') // all users in group
682 return acl_check_group (user+1, uid, gid, not, allowed);
683 else
685 char *buf;
686 struct passwd pw;
687 struct passwd *pwd = get_pwd_struct (user, 0, &pw, &buf, &rc);
689 if (!rc && pwd && pwd->pw_uid == uid)
690 *allowed = !not;
692 xfree (buf);
695 return rc;
697 #else
698 gpg_error_t
699 acl_check_common (struct client_s *client, const char *user, uid_t uid,
700 gid_t gid, int *allowed)
702 gpg_error_t rc = 0;
703 int not = 0;
704 int rw = 0;
705 int tls = 0;
707 if (!user || !*user)
708 return 0;
710 if (*user == '-' || *user == '!')
711 not = 1;
713 if (*user == '+') // not implemented yet
714 rw = 1;
716 if (*user == '#') // TLS fingerprint hash
717 tls = 1;
719 if (not || rw || tls)
720 user++;
722 if (tls)
724 #ifdef WITH_GNUTLS
725 if (client->thd->remote)
727 if (!strcasecmp (client->thd->tls->fp, user))
728 *allowed = !not;
731 return 0;
732 #else
733 return 0;
734 #endif
737 if (*user == '@') // all users in group
738 return acl_check_group (user+1, uid, gid, not, allowed);
739 else
741 char *buf;
742 struct passwd pw;
743 struct passwd *result = get_pwd_struct (user, 0, &pw, &buf, &rc);
745 if (!rc && result && result->pw_uid == uid)
746 *allowed = !not;
748 xfree (buf);
751 return rc;
753 #endif
755 static gpg_error_t
756 validate_peer (struct client_s *cl)
758 gpg_error_t rc;
760 #ifdef WITH_GNUTLS
761 if (cl->thd->remote)
762 return tls_validate_access (cl, NULL);
763 #endif
765 MUTEX_LOCK (&cn_mutex);
766 pthread_cleanup_push (release_mutex_cb, &cn_mutex);
767 rc = do_validate_peer (cl->ctx, "global", &cl->thd->peer);
768 pthread_cleanup_pop (1);
769 log_write ("peer %s: uid=%i, gid=%i, pid=%i, rc=%u",
770 !rc ? _("accepted") : _("rejected"), cl->thd->peer->uid,
771 cl->thd->peer->gid, cl->thd->peer->pid, rc);
772 return rc;
775 static void
776 xml_error_cb (void *data, xmlErrorPtr e)
778 struct client_s *client = data;
781 * Keep the first reported error as the one to show in the error
782 * description. Reset in send_error().
784 if (client->xml_error)
785 return;
787 client->xml_error = xcalloc (1, sizeof(xmlError));
788 xmlCopyError (e, client->xml_error);
791 static pid_t
792 hook_waitpid (assuan_context_t ctx, pid_t pid, int action,
793 int *status, int options)
795 return waitpid (pid, status, options);
798 static ssize_t
799 hook_read (assuan_context_t ctx, assuan_fd_t fd, 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_read_hook (ctx, (int) fd, data, len);
806 #endif
808 return read ((int) fd, data, len);
811 static ssize_t
812 hook_write (assuan_context_t ctx, assuan_fd_t fd,
813 const void *data, size_t len)
815 #ifdef WITH_GNUTLS
816 struct client_s *client = assuan_get_pointer (ctx);
818 if (client->thd->remote)
819 return tls_write_hook (ctx, (int) fd, data, len);
820 #endif
822 return write ((int) fd, data, len);
826 assuan_log_cb (assuan_context_t ctx, void *data, unsigned cat,
827 const char *msg)
829 struct client_s *client = data;
830 char *str = NULL;
832 (void)client;
834 if (!(assuan_level & cat))
835 return 0;
837 if (!msg)
838 return 1;
840 switch (cat)
842 case ASSUAN_LOG_INIT:
843 str = "ASSUAN[INIT]";
844 break;
845 case ASSUAN_LOG_CTX:
846 str = "ASSUAN[CTX]";
847 break;
848 case ASSUAN_LOG_ENGINE:
849 str = "ASSUAN[ENGINE]";
850 break;
851 case ASSUAN_LOG_DATA:
852 str = "ASSUAN[DATA]";
853 break;
854 case ASSUAN_LOG_SYSIO:
855 str = "ASSUAN[SYSIO]";
856 break;
857 case ASSUAN_LOG_CONTROL:
858 str = "ASSUAN[CONTROL]";
859 break;
860 default:
861 str = "ASSUAN[UNKNOWN]";
862 break;
865 log_write ("%s: %s", str, msg);
866 return 1;
869 static int
870 new_connection (struct client_s *cl)
872 gpg_error_t rc;
873 static struct assuan_malloc_hooks mhooks = { xmalloc, xrealloc, xfree };
874 static struct assuan_system_hooks shooks = {
875 ASSUAN_SYSTEM_HOOKS_VERSION,
876 __assuan_usleep,
877 __assuan_pipe,
878 __assuan_close,
879 hook_read,
880 hook_write,
881 //FIXME
882 NULL, //recvmsg
883 NULL, //sendmsg both are used for FD passing
884 __assuan_spawn,
885 hook_waitpid,
886 __assuan_socketpair,
887 __assuan_socket,
888 __assuan_connect
891 #ifdef WITH_GNUTLS
892 if (cl->thd->remote)
894 char *prio = config_get_string ("global", "tls_cipher_suite");
896 cl->thd->timeout = config_get_integer ("global", "tls_timeout");
897 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
898 return 0;
900 cl->thd->tls = tls_init_client (cl->thd->fd, cl->thd->timeout, prio);
901 xfree (prio);
902 if (!cl->thd->tls)
903 return 0;
905 #endif
907 rc = assuan_new_ext (&cl->ctx, GPG_ERR_SOURCE_DEFAULT, &mhooks,
908 assuan_log_cb, cl);
909 if (rc)
910 goto fail;
912 assuan_ctx_set_system_hooks (cl->ctx, &shooks);
913 rc = assuan_init_socket_server (cl->ctx, cl->thd->fd, 2);
914 if (rc)
915 goto fail;
917 assuan_set_pointer (cl->ctx, cl);
918 assuan_set_hello_line (cl->ctx, PACKAGE_STRING);
919 rc = register_commands (cl->ctx);
920 if (rc)
921 goto fail;
923 rc = assuan_accept (cl->ctx);
924 if (rc)
925 goto fail;
927 rc = validate_peer (cl);
928 /* May not be implemented on all platforms. */
929 if (rc && gpg_err_code (rc) != GPG_ERR_ASS_GENERAL)
930 goto fail;
932 MUTEX_LOCK (&cn_mutex);
933 cl->thd->state = CLIENT_STATE_INIT;
934 MUTEX_UNLOCK (&cn_mutex);
935 cl->lock_timeout = config_get_integer ("global", "lock_timeout");
936 xmlSetStructuredErrorFunc (cl, xml_error_cb);
937 return 1;
939 fail:
940 log_write ("%s", pwmd_strerror (rc));
941 return 0;
945 * This is called after a client_thread() terminates. Set with
946 * pthread_cleanup_push().
948 static void
949 free_client_cb (void *arg)
951 struct client_thread_s *cn = arg;
952 struct client_s *cl = cn->cl;
954 MUTEX_LOCK (&cn_mutex);
955 cn_thread_list = slist_remove (cn_thread_list, cn);
956 MUTEX_UNLOCK (&cn_mutex);
958 if (cl)
960 unlock_flock (&cl->flock_fd);
961 reset_client (cl);
962 if (cl->xml_error)
963 xmlResetError (cl->xml_error);
965 xfree (cl->xml_error);
967 #ifdef WITH_GNUTLS
968 if (cn->tls)
970 gnutls_deinit (cn->tls->ses);
971 xfree (cn->tls->fp);
972 xfree (cn->tls);
974 #endif
976 if (cl->ctx)
977 assuan_release (cl->ctx);
978 else if (cl->thd && cl->thd->fd != -1)
979 close (cl->thd->fd);
981 if (cl->crypto)
982 crypto_free (cl->crypto);
984 cl->crypto = NULL;
985 xfree (cl);
987 else
989 if (cn->fd != -1)
990 close (cn->fd);
993 while (cn->msg_queue)
995 struct status_msg_s *msg = cn->msg_queue;
997 cn->msg_queue = msg->next;
998 xfree (msg->line);
999 xfree (msg);
1002 if (cn->status_msg_pipe[0] != -1)
1003 close (cn->status_msg_pipe[0]);
1005 if (cn->status_msg_pipe[1] != -1)
1006 close (cn->status_msg_pipe[1]);
1008 pthread_mutex_destroy (&cn->status_mutex);
1009 log_write (_("exiting, fd=%i"), cn->fd);
1010 send_status_all (STATUS_CLIENTS, NULL);
1012 xfree (cn->name);
1013 #ifdef WITH_GNUTLS
1014 xfree (cn->peeraddr);
1015 #endif
1016 xfree (cn);
1017 pthread_cond_signal (&quit_cond);
1020 void
1021 free_all_clients ()
1023 MUTEX_LOCK (&cn_mutex);
1024 pthread_cleanup_push (release_mutex_cb, &cn_mutex);
1026 while (slist_length (cn_thread_list))
1028 struct client_thread_s *thd = slist_nth_data (cn_thread_list, 0);
1030 free_client_cb (thd);
1033 exiting = 1;
1034 pthread_cleanup_pop (1);
1035 cache_deinit ();
1038 static gpg_error_t
1039 send_msg_queue (struct client_thread_s *thd)
1041 MUTEX_LOCK (&thd->status_mutex);
1042 gpg_error_t rc = 0;
1043 char c;
1044 ssize_t ret;
1046 ret = read (thd->status_msg_pipe[0], &c, 1);
1047 rc = gpg_error_from_syserror ();
1048 if (ret == -1 && gpg_err_code (rc) != GPG_ERR_EAGAIN)
1049 log_write ("%s (%i): %s", __FUNCTION__, __LINE__, pwmd_strerror (rc));
1050 else
1051 rc = 0;
1053 thd->wrote_status = 0;
1055 while (thd->msg_queue)
1057 struct status_msg_s *msg = thd->msg_queue;
1059 #ifndef HAVE_PTHREAD_CANCEL
1060 if (thd->fd == -1)
1061 break;
1062 #endif
1064 thd->msg_queue = thd->msg_queue->next;
1065 MUTEX_UNLOCK (&thd->status_mutex);
1066 rc = send_status (thd->cl->ctx, msg->s, msg->line);
1067 MUTEX_LOCK (&thd->status_mutex);
1068 xfree (msg->line);
1069 xfree (msg);
1071 if (rc)
1072 break;
1075 MUTEX_UNLOCK (&thd->status_mutex);
1076 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1077 log_write ("%s (%i): %s", __FUNCTION__, __LINE__, pwmd_strerror (rc));
1079 return rc;
1082 static void *
1083 client_thread (void *data)
1085 struct client_thread_s *thd = data;
1086 struct client_s *cl = xcalloc (1, sizeof (struct client_s));
1088 #ifdef HAVE_PR_SET_NAME
1089 prctl (PR_SET_NAME, "client");
1090 #endif
1091 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1093 if (!cl)
1095 log_write ("%s(%i): %s", __FILE__, __LINE__,
1096 pwmd_strerror (GPG_ERR_ENOMEM));
1097 return NULL;
1100 MUTEX_LOCK (&cn_mutex);
1101 pthread_cleanup_push (free_client_cb, thd);
1102 thd->cl = cl;
1103 cl->thd = thd;
1104 cl->flock_fd = -1;
1105 MUTEX_UNLOCK (&cn_mutex);
1107 if (new_connection (cl))
1109 int finished = 0;
1110 gpg_error_t rc;
1111 struct pollfd fds[2];
1113 fds[0].fd = thd->fd;
1114 fds[0].events = POLLIN;
1115 fds[1].fd = thd->status_msg_pipe[0];
1116 fds[1].events = POLLIN;
1118 send_status_all (STATUS_CLIENTS, NULL);
1119 rc = send_status (cl->ctx, STATUS_CACHE, NULL);
1120 if (rc)
1122 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
1123 finished = 1;
1126 while (!finished)
1128 int n;
1129 int eof;
1131 n = poll (fds, 2, 100);
1132 if (n == -1)
1134 log_write ("%s", strerror (errno));
1135 break;
1138 #ifdef WITH_GNUTLS
1139 if (thd->remote && thd->tls && thd->tls->rehandshake)
1141 char *prio;
1142 int ret;
1143 const char *e;
1145 if (thd->tls->rehandshake == 1)
1147 prio = config_get_string ("global", "tls_cipher_suite");
1148 if (!prio)
1150 thd->tls->rehandshake = 0;
1151 continue;
1154 ret = gnutls_priority_set_direct (thd->tls->ses, prio, &e);
1155 if (ret == GNUTLS_E_SUCCESS)
1157 rc = send_status (cl->ctx, STATUS_REHANDSHAKE, NULL);
1158 if (!rc)
1160 rc = assuan_send_data (cl->ctx, NULL, 0);
1161 if (!rc)
1163 ret = gnutls_rehandshake (thd->tls->ses);
1164 if (ret)
1166 log_write ("%s", gnutls_strerror (ret));
1167 thd->tls->rehandshake = 0;
1169 else
1170 thd->tls->rehandshake = 2;
1174 if (rc)
1175 log_write ("%s", pwmd_strerror (rc));
1177 else
1178 log_write ("%s: %s", gnutls_strerror (ret), e);
1180 xfree (prio);
1181 continue;
1184 #endif
1186 if (!n)
1187 continue;
1189 if (fds[1].revents & POLLIN)
1191 #ifdef WITH_GNUTLS
1192 if (!thd->remote || (thd->tls && !thd->tls->rehandshake))
1193 #endif
1195 rc = send_msg_queue (thd);
1196 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1197 break;
1201 #ifdef HAVE_PTHREAD_CANCEL
1202 if (!(fds[0].revents & POLLIN))
1203 #else
1204 if (thd->fd != -1 && !(fds[0].revents & POLLIN))
1205 #endif
1206 continue;
1208 rc = assuan_process_next (cl->ctx, &eof);
1209 if (rc || eof)
1211 if (gpg_err_code (rc) == GPG_ERR_EOF || eof)
1212 break;
1214 log_write ("assuan_process_next(): rc=%u %s", rc,
1215 pwmd_strerror (rc));
1216 if (rc == gpg_error (GPG_ERR_ETIMEDOUT))
1217 break;
1219 rc = send_error (cl->ctx, rc);
1220 if (rc)
1222 log_write ("assuan_process_done(): rc=%u %s", rc,
1223 pwmd_strerror (rc));
1224 break;
1228 /* Since the msg queue pipe fd's are non-blocking, check for
1229 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1230 * client has already disconnected and will be converted to
1231 * GPG_ERR_EOF during assuan_process_next().
1233 #ifdef WITH_GNUTLS
1234 if (!thd->remote || (thd->tls && !thd->tls->rehandshake))
1235 #endif
1237 rc = send_msg_queue (thd);
1238 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1239 break;
1244 /* Don't do pthread_exit() here because any set pthread_cleanup_push
1245 * functions would be called after a command failed but then the client
1246 * exited normally which may lead to a double free. */
1247 pthread_cleanup_pop (1);
1248 return NULL;
1251 static gpg_error_t
1252 xml_import (const char *filename, const char *outfile, char **keyid,
1253 char **sign_keyid, char *keyfile, const char *keyparam,
1254 int symmetric)
1256 xmlDocPtr doc;
1257 int fd;
1258 struct stat st;
1259 int len;
1260 xmlChar *xmlbuf;
1261 gpg_error_t rc = 0;
1262 struct crypto_s *crypto = NULL;
1264 if (stat (filename, &st) == -1)
1266 rc = gpg_error_from_errno (errno);
1267 return rc;
1270 fd = open (filename, O_RDONLY);
1271 if (fd == -1)
1272 return gpg_error_from_errno (errno);
1274 xmlbuf = xmalloc (st.st_size + 1);
1275 if (!xmlbuf)
1277 close (fd);
1278 return GPG_ERR_ENOMEM;
1281 if (read (fd, xmlbuf, st.st_size) == -1)
1283 rc = gpg_error_from_errno (errno);
1284 close (fd);
1285 xfree (xmlbuf);
1286 return rc;
1289 close (fd);
1290 xmlbuf[st.st_size] = 0;
1291 // Be sure the document validates.
1292 doc = xmlReadDoc (xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS);
1293 xfree (xmlbuf);
1294 if (!doc)
1295 return GPG_ERR_BAD_DATA;
1297 xmlNodePtr n = xmlDocGetRootElement (doc);
1298 if (n && !xmlStrEqual (n->name, (xmlChar *) "pwmd"))
1299 rc = GPG_ERR_BAD_DATA;
1301 if (!rc)
1303 rc = xml_validate_import (NULL, n ? n->children : n);
1304 if (!rc)
1306 rc = crypto_init (&crypto, NULL, filename, keyfile != NULL, keyfile);
1307 if (!rc)
1309 if (keyfile)
1311 crypto->flags |= CRYPTO_FLAG_KEYFILE;
1312 crypto->keyfile = str_dup (keyfile);
1315 xmlDocDumpMemory (doc, &crypto->plaintext, &len);
1316 if (len > 0)
1317 crypto->plaintext_size = len;
1318 else
1319 rc = GPG_ERR_ENOMEM;
1324 if (!rc)
1326 if (!symmetric && (keyparam || !keyid))
1328 char *buf = NULL;
1330 if (keyparam)
1332 fd = open (keyparam, O_RDONLY);
1333 if (fd == -1)
1334 rc = gpg_error_from_errno (errno);
1336 if (!rc)
1338 if (stat (keyparam, &st) == -1)
1339 rc = gpg_error_from_errno (errno);
1341 if (!rc)
1343 buf = xmalloc (st.st_size+1);
1344 if (!buf)
1345 rc = GPG_ERR_ENOMEM;
1347 if (!rc)
1349 len = read (fd, buf, st.st_size);
1350 if (len != st.st_size)
1351 rc = gpg_error_from_errno (errno);
1353 if (!rc)
1354 buf[len] = 0;
1359 if (fd != -1)
1360 close (fd);
1362 else
1364 buf = crypto_default_key_params ();
1365 if (!buf)
1366 rc = GPG_ERR_ENOMEM;
1369 if (!rc)
1370 rc = crypto_genkey (NULL, crypto, (unsigned char *)buf);
1372 xfree (buf);
1374 else
1376 crypto->save.pubkey = strv_dup (keyid);
1377 crypto->save.sigkey = strv_dup (sign_keyid);
1380 if (!rc)
1382 crypto->flags |= symmetric ? CRYPTO_FLAG_SYMMETRIC : 0;
1383 rc = crypto_encrypt (NULL, crypto);
1387 if (!rc)
1389 if (!strcmp (outfile, "-"))
1390 outfile = NULL;
1392 xfree (crypto->plaintext);
1393 crypto->plaintext = NULL;
1394 xfree (crypto->filename);
1395 crypto->filename = outfile ? str_dup (outfile) : NULL;
1396 rc = crypto_write_file (crypto);
1399 xmlFreeDoc (doc);
1400 crypto_free (crypto);
1401 return rc;
1404 static gpg_error_t
1405 do_cache_push (struct crypto_s *crypto)
1407 gpg_error_t rc;
1408 xmlDocPtr doc;
1409 struct cache_data_s *cdata;
1410 unsigned char *crc;
1411 size_t len;
1412 int fd = -1;
1414 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1415 crypto->filename);
1417 if (valid_filename (crypto->filename) == 0)
1419 log_write (_("%s: Invalid characters in filename"), crypto->filename);
1420 return GPG_ERR_INV_VALUE;
1423 rc = lock_flock (NULL, crypto->filename, LOCK_SH, &fd);
1424 if (!rc)
1425 rc = crypto_decrypt (NULL, crypto);
1426 if (rc)
1428 unlock_flock (&fd);
1429 return rc;
1432 rc = xml_parse_doc ((char *) crypto->plaintext, crypto->plaintext_size, &doc);
1433 if (rc)
1435 unlock_flock (&fd);
1436 log_write ("%s", pwmd_strerror (rc));
1437 return rc;
1440 cdata = xcalloc (1, sizeof (struct cache_data_s));
1441 if (!cdata)
1443 unlock_flock (&fd);
1444 xmlFreeDoc (doc);
1445 return GPG_ERR_ENOMEM;
1448 rc = get_checksum (crypto->filename, &crc, &len);
1449 unlock_flock (&fd);
1450 if (rc)
1452 xmlFreeDoc (doc);
1453 cache_free_data_once (cdata);
1454 return rc;
1457 cdata->crc = crc;
1458 rc = cache_encrypt (crypto);
1459 if (!rc)
1461 cdata->doc = crypto->plaintext;
1462 cdata->size = crypto->plaintext_size;
1463 crypto->plaintext = NULL;
1464 cdata->pubkey = crypto->pubkey;
1465 cdata->sigkey = crypto->sigkey;
1466 crypto->pubkey = NULL;
1467 crypto->sigkey = NULL;
1469 else
1471 xmlFreeDoc (doc);
1472 cache_free_data_once (cdata);
1473 return rc;
1476 int timeout = config_get_integer (crypto->filename, "cache_timeout");
1477 rc = cache_add_file (crypto->filename, cdata, timeout);
1478 return rc;
1481 static gpg_error_t
1482 init_client (int fd, const char *addr)
1484 gpg_error_t rc = 0;
1485 struct client_thread_s *new = xcalloc (1, sizeof (struct client_thread_s));
1487 if (!new)
1489 close (fd);
1490 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (ENOMEM));
1491 return GPG_ERR_ENOMEM;
1494 MUTEX_LOCK (&cn_mutex);
1495 new->conntime = time (NULL);
1496 pthread_cleanup_push (release_mutex_cb, &cn_mutex);
1498 if (pipe (new->status_msg_pipe) == -1)
1499 rc = gpg_error_from_errno (errno);
1501 if (!rc)
1503 if (fcntl (new->status_msg_pipe[0], F_SETFL, O_NONBLOCK) == -1)
1504 rc = gpg_error_from_errno (errno);
1506 if (!rc)
1507 if (fcntl (new->status_msg_pipe[1], F_SETFL, O_NONBLOCK) == -1)
1508 rc = gpg_error_from_errno (errno);
1510 pthread_mutex_init (&new->status_mutex, NULL);
1513 if (!rc)
1515 #ifdef WITH_GNUTLS
1516 new->remote = addr ? 1 : 0;
1517 #endif
1518 new->fd = fd;
1519 rc = create_thread (client_thread, new, &new->tid, 1);
1520 if (rc)
1522 close (new->status_msg_pipe[0]);
1523 close (new->status_msg_pipe[1]);
1524 pthread_mutex_destroy (&new->status_mutex);
1528 if (!rc)
1530 struct slist_s *list = slist_append (cn_thread_list, new);
1532 if (list)
1534 cn_thread_list = list;
1535 if (addr)
1537 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1538 (pthread_t *) new->tid, fd, addr);
1539 #ifdef WITH_GNUTLS
1540 new->peeraddr = str_dup (addr);
1541 #endif
1543 else
1544 log_write (_("new connection: tid=%p, fd=%i"),
1545 (pthread_t *) new->tid, fd);
1547 else
1548 rc = GPG_ERR_ENOMEM;
1551 pthread_cleanup_pop (1);
1553 if (rc)
1555 xfree (new);
1556 close (fd);
1557 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1558 pwmd_strerror (rc));
1560 return rc;
1563 #ifdef WITH_GNUTLS
1564 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1565 static void *
1566 get_in_addr (struct sockaddr *sa)
1568 if (sa->sa_family == AF_INET)
1569 return &(((struct sockaddr_in *) sa)->sin_addr);
1571 return &(((struct sockaddr_in6 *) sa)->sin6_addr);
1574 static int
1575 start_stop_tls_with_protocol (int ipv6, int term)
1577 struct addrinfo hints, *servinfo, *p;
1578 int port = config_get_integer ("global", "tcp_port");
1579 char buf[7];
1580 int n;
1581 int *fd = ipv6 ? &tls6_fd : &tls_fd;
1583 if (term || config_get_boolean ("global", "enable_tcp") == 0)
1585 if (tls6_fd != -1)
1587 shutdown (tls6_fd, SHUT_RDWR);
1588 close (tls6_fd);
1589 tls6_fd = -1;
1592 if (tls_fd != -1)
1594 shutdown (tls_fd, SHUT_RDWR);
1595 close (tls_fd);
1596 tls_fd = -1;
1599 return 0;
1602 memset (&hints, 0, sizeof (hints));
1603 hints.ai_family = ipv6 ? AF_INET6 : AF_INET;
1604 hints.ai_socktype = SOCK_STREAM;
1605 hints.ai_flags = AI_PASSIVE;
1606 snprintf (buf, sizeof (buf), "%i", port);
1608 if ((n = getaddrinfo (NULL, buf, &hints, &servinfo)) == -1)
1610 log_write ("getaddrinfo(): %s", gai_strerror (n));
1611 return 0;
1614 for (n = 0, p = servinfo; p != NULL; p = p->ai_next)
1616 int r = 1;
1618 if ((ipv6 && p->ai_family != AF_INET6)
1619 || (!ipv6 && p->ai_family != AF_INET))
1620 continue;
1622 if ((*fd = socket (p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
1624 log_write ("socket(): %s", strerror (errno));
1625 continue;
1628 if (setsockopt (*fd, SOL_SOCKET, SO_REUSEADDR, &r, sizeof (int)) == -1)
1630 log_write ("setsockopt(): %s",
1631 pwmd_strerror (gpg_error_from_errno (errno)));
1632 freeaddrinfo (servinfo);
1633 goto fail;
1636 if (bind (*fd, p->ai_addr, p->ai_addrlen) == -1)
1638 close (*fd);
1639 log_write ("bind(): %s",
1640 pwmd_strerror (gpg_error_from_errno (errno)));
1641 continue;
1644 n++;
1645 break;
1648 freeaddrinfo (servinfo);
1650 if (!n)
1651 goto fail;
1653 #if HAVE_DECL_SO_BINDTODEVICE != 0
1654 char *tmp = config_get_string ("global", "tcp_interface");
1655 if (tmp && setsockopt (*fd, SOL_SOCKET, SO_BINDTODEVICE, tmp,
1656 strlen (tmp)) == -1)
1658 log_write ("setsockopt(): %s",
1659 pwmd_strerror (gpg_error_from_errno (errno)));
1660 xfree (tmp);
1661 goto fail;
1664 xfree (tmp);
1665 #endif
1667 if (listen (*fd, 128) == -1)
1669 log_write ("listen(): %s", strerror (errno));
1670 goto fail;
1673 return 1;
1675 fail:
1676 start_stop_tls_with_protocol (0, 1);
1677 if (tls_fd != -1)
1678 close (tls_fd);
1680 if (tls6_fd != -1)
1681 close (tls6_fd);
1683 tls_fd = -1;
1684 tls6_fd = -1;
1685 return 0;
1688 static int
1689 start_stop_tls (int term)
1691 char *s = config_get_string ("global", "tcp_bind");
1692 int b;
1694 if (!s)
1695 return 0;
1697 if (!strcmp (s, "any"))
1699 b = start_stop_tls_with_protocol (0, term);
1700 if (b)
1701 b = start_stop_tls_with_protocol (1, term);
1703 else if (!strcmp (s, "ipv4"))
1704 b = start_stop_tls_with_protocol (0, term);
1705 else if (!strcmp (s, "ipv6"))
1706 b = start_stop_tls_with_protocol (1, term);
1707 else
1708 b = 0;
1710 xfree (s);
1711 if (!term && b)
1713 gpg_error_t rc = tls_init_params ();
1714 if (rc)
1716 start_stop_tls_with_protocol (0, 1);
1717 return 0;
1721 return b;
1723 #endif
1725 #ifdef WITH_GNUTLS
1726 static gpg_error_t
1727 do_tls_accept (struct pollfd *fds)
1729 struct sockaddr_storage raddr;
1730 socklen_t slen = sizeof (raddr);
1731 int fd;
1732 char s[INET6_ADDRSTRLEN];
1734 if (!(fds->revents & POLLIN))
1735 return 0;
1737 fd = accept (fds->fd, (struct sockaddr *) &raddr, &slen);
1738 if (fd == -1)
1740 int e = errno;
1742 if (errno != EAGAIN && !quit)
1743 log_write ("%s: %s", __FUNCTION__,
1744 pwmd_strerror (gpg_error_from_syserror()));
1746 return gpg_error_from_errno (e);
1749 inet_ntop (raddr.ss_family, get_in_addr ((struct sockaddr *) &raddr), s,
1750 sizeof s);
1751 (void) init_client (fd, s);
1752 return 0;
1754 #endif
1756 static void *
1757 accept_thread (void *arg)
1759 int sockfd = *(int *) arg;
1760 #ifndef HAVE_PTHREAD_CANCEL
1761 int *n = xmalloc (sizeof (int));
1763 *n = 0;
1764 pthread_setspecific (signal_thread_key, n);
1765 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
1766 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1767 #endif
1769 #ifdef HAVE_PR_SET_NAME
1770 prctl (PR_SET_NAME, "accept");
1771 #endif
1772 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
1774 for (;;)
1776 socklen_t slen = sizeof (struct sockaddr_un);
1777 struct sockaddr_un raddr;
1778 int fd, s = 0;
1779 struct pollfd fds[3];
1781 TEST_CANCEL ();
1782 memset (fds, 0, sizeof (fds));
1783 fds[s].fd = sockfd;
1784 fds[s++].events = POLLIN;
1786 #ifdef WITH_GNUTLS
1787 if (tls_fd != -1)
1789 fds[s].fd = tls_fd;
1790 fds[s++].events = POLLIN;
1792 else
1793 fds[s].fd = tls_fd;
1795 if (tls6_fd != -1)
1797 fds[s].fd = tls6_fd;
1798 fds[s++].events = POLLIN;
1800 else
1801 fds[s].fd = tls6_fd;
1802 #endif
1804 s = poll (fds, s, 500);
1805 if (s == -1)
1807 if (errno != EINTR)
1808 log_write ("%s", strerror (errno));
1809 break;
1811 else if (s == 0)
1812 continue;
1814 if (fds[0].revents & POLLIN)
1816 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1817 if (fd == -1)
1819 if (errno == EMFILE || errno == ENFILE)
1820 log_write ("%s: %s", __FUNCTION__,
1821 pwmd_strerror (gpg_error_from_errno (errno)));
1822 else if (errno != EAGAIN && errno != EINTR)
1824 if (!quit) // probably EBADF
1825 log_write ("%s: %s", __FUNCTION__,
1826 pwmd_strerror (gpg_error_from_errno (errno)));
1828 break;
1831 continue;
1834 (void) init_client (fd, NULL);
1837 #ifdef WITH_GNUTLS
1838 if (tls_fd != -1 && fds[1].fd == tls_fd)
1839 (void)do_tls_accept (&fds[1]);
1841 if (tls6_fd != -1 && fds[1].fd == tls6_fd)
1842 (void)do_tls_accept (&fds[1]);
1844 if (tls6_fd != -1 && fds[2].fd == tls6_fd)
1845 (void)do_tls_accept (&fds[2]);
1846 #endif
1849 /* Just in case accept() failed for some reason other than EBADF */
1850 quit = 1;
1851 return NULL;
1854 static void *
1855 cache_timer_thread (void *arg)
1857 unsigned k = 0;
1858 #ifndef HAVE_PTHREAD_CANCEL
1859 int *n = xmalloc (sizeof (int));
1861 *n = 0;
1862 pthread_setspecific (signal_thread_key, n);
1863 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
1864 #endif
1866 #ifdef HAVE_PR_SET_NAME
1867 prctl (PR_SET_NAME, "timer");
1868 #endif
1869 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
1871 for (;;)
1873 struct timeval tv = { 1, 0 };
1874 unsigned keepalive = config_get_integer ("global", "keepalive_interval");
1876 TEST_CANCEL ();
1877 select (0, NULL, NULL, NULL, &tv);
1878 cache_adjust_timeout ();
1880 if (++k >= keepalive)
1882 send_status_all (STATUS_KEEPALIVE, NULL);
1883 k = 0;
1887 return NULL;
1890 static int
1891 signal_loop (sigset_t sigset)
1893 int done = 0;
1894 int siint = 0;
1898 int sig;
1900 sigwait (&sigset, &sig);
1902 if (sig != SIGQUIT)
1903 log_write (_("caught signal %i (%s)"), sig, strsignal (sig));
1905 switch (sig)
1907 case SIGHUP:
1908 pthread_cond_signal (&rcfile_cond);
1909 break;
1910 case SIGUSR1:
1911 log_write (_("clearing file cache"));
1912 cache_clear (NULL, NULL, 1);
1913 send_status_all (STATUS_CACHE, NULL);
1914 break;
1915 case SIGQUIT:
1916 done = 1;
1917 break;
1918 default:
1919 siint = 1;
1920 done = 1;
1921 break;
1924 while (!done);
1926 return siint;
1929 static void
1930 catchsig (int sig)
1932 log_write (_ ("Caught signal %i (%s). Exiting."), sig, strsignal (sig));
1933 #ifdef HAVE_BACKTRACE
1934 BACKTRACE (__FUNCTION__);
1935 #endif
1936 longjmp (jmp, 1);
1939 static void *
1940 waiting_for_exit (void *arg)
1942 int last = 0;
1943 #ifndef HAVE_PTHREAD_CANCEL
1944 int *n = xmalloc (sizeof (int));
1946 *n = 0;
1947 pthread_setspecific (signal_thread_key, n);
1948 INIT_SIGNAL (SIGUSR2, catch_thread_signal);
1949 #endif
1951 #ifdef HAVE_PR_SET_NAME
1952 prctl (PR_SET_NAME, "exiting");
1953 #endif
1954 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
1955 log_write (_("waiting for all clients to disconnect"));
1956 MUTEX_LOCK (&quit_mutex);
1957 pthread_cleanup_push (release_mutex_cb, &quit_mutex);
1959 for (;;)
1961 struct timespec ts;
1962 int n;
1964 MUTEX_LOCK (&cn_mutex);
1965 n = slist_length (cn_thread_list);
1966 MUTEX_UNLOCK (&cn_mutex);
1967 if (!n)
1968 break;
1970 TEST_CANCEL ();
1972 if (last != n)
1974 log_write (_("%i clients remain"), n);
1975 last = n;
1978 INIT_TIMESPEC (SIG_TIMEOUT, ts);
1979 pthread_cond_timedwait (&quit_cond, &quit_mutex, &ts);
1982 kill (getpid (), SIGQUIT);
1983 pthread_cleanup_pop (1);
1984 return NULL;
1987 static int
1988 server_loop (int sockfd, char **socketpath)
1990 pthread_t cache_timeout_tid;
1991 int cancel_timeout_thread = 0, cancel_accept_thread = 0;
1992 sigset_t sigset;
1993 int n;
1994 int segv = 0;
1995 gpg_error_t rc;
1997 init_commands ();
1998 sigemptyset (&sigset);
2000 /* Termination */
2001 sigaddset (&sigset, SIGTERM);
2002 sigaddset (&sigset, SIGINT);
2004 /* Clears the file cache. */
2005 sigaddset (&sigset, SIGUSR1);
2007 /* Configuration file reloading. */
2008 sigaddset (&sigset, SIGHUP);
2010 /* For exiting cleanly. */
2011 sigaddset (&sigset, SIGQUIT);
2013 #ifndef HAVE_PTHREAD_CANCEL
2015 The socket, cache and rcfile threads use this signal when
2016 pthread_cancel() is unavailable. Prevent the main thread from
2017 catching this signal from another process.
2019 sigaddset (&sigset, SIGUSR2);
2020 #endif
2022 /* An assertion failure. */
2023 signal (SIGABRT, catchsig);
2024 sigaddset (&sigset, SIGABRT);
2025 sigprocmask (SIG_BLOCK, &sigset, NULL);
2027 #ifndef HAVE_PTHREAD_CANCEL
2028 /* Remove this signal from the watched signals in signal_loop(). */
2029 sigdelset (&sigset, SIGUSR2);
2030 #endif
2032 /* Can show a backtrace of the stack in the log. */
2033 signal (SIGSEGV, catchsig);
2035 pthread_mutex_init (&quit_mutex, NULL);
2036 pthread_cond_init (&quit_cond, NULL);
2037 char *p = get_username (getuid());
2038 log_write (_("%s started for user %s"), PACKAGE_STRING, p);
2039 xfree (p);
2041 #ifdef WITH_GNUTLS
2042 if (config_get_boolean ("global", "enable_tcp"))
2043 log_write (_("Listening on %s and TCP port %i"), *socketpath,
2044 config_get_integer ("global", "tcp_port"));
2045 else
2046 log_write (_("Listening on %s"), *socketpath);
2047 #else
2048 log_write (_("Listening on %s"), *socketpath);
2049 #endif
2051 rc = create_thread (reload_rcfile_thread, NULL, &rcfile_tid, 0);
2052 if (rc)
2054 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2055 pwmd_strerror (rc));
2056 goto done;
2059 rc = create_thread (cache_timer_thread, NULL, &cache_timeout_tid, 0);
2060 if (rc)
2062 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2063 pwmd_strerror (rc));
2064 goto done;
2067 cancel_timeout_thread = 1;
2068 rc = create_thread (accept_thread, &sockfd, &accept_tid, 0);
2069 if (rc)
2071 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2072 pwmd_strerror (rc));
2073 goto done;
2076 cancel_accept_thread = 1;
2077 if (!setjmp (jmp))
2078 signal_loop (sigset);
2079 else
2080 segv = 1;
2082 done:
2084 * We're out of the main server loop. This happens when a signal was sent
2085 * to terminate the daemon. We'll wait for all clients to disconnect
2086 * before exiting but exit immediately if another termination signal is
2087 * sent.
2089 if (cancel_accept_thread)
2091 #ifdef HAVE_PTHREAD_CANCEL
2092 int n = pthread_cancel (accept_tid);
2093 #else
2094 int n = pthread_kill (accept_tid, SIGUSR2);
2095 #endif
2096 if (!n)
2097 pthread_join (accept_tid, NULL);
2100 if (cancel_timeout_thread)
2102 #ifdef HAVE_PTHREAD_CANCEL
2103 n = pthread_cancel (cache_timeout_tid);
2104 #else
2105 n = pthread_kill (cache_timeout_tid, SIGUSR2);
2106 #endif
2107 if (!n)
2108 pthread_join (cache_timeout_tid, NULL);
2111 #ifdef WITH_GNUTLS
2112 start_stop_tls (1);
2113 #endif
2114 shutdown (sockfd, SHUT_RDWR);
2115 close (sockfd);
2116 unlink (*socketpath);
2117 xfree (*socketpath);
2118 *socketpath = NULL;
2119 MUTEX_LOCK (&cn_mutex);
2120 n = slist_length (cn_thread_list);
2121 MUTEX_UNLOCK (&cn_mutex);
2123 if (n && !segv)
2125 pthread_t tid;
2127 rc = create_thread (waiting_for_exit, NULL, &tid, 0);
2128 if (!rc)
2130 if (signal_loop (sigset))
2132 log_write (_("Received second termination request. Exiting."));
2133 #ifdef HAVE_PTHREAD_CANCEL
2134 pthread_cancel (tid);
2135 #else
2136 pthread_kill (tid, SIGUSR2);
2137 #endif
2138 pthread_join (tid, NULL);
2141 else
2142 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2143 pwmd_strerror (rc));
2146 free_all_clients ();
2147 deinit_commands ();
2148 pthread_cond_destroy (&quit_cond);
2149 pthread_mutex_destroy (&quit_mutex);
2150 return segv ? EXIT_FAILURE : EXIT_SUCCESS;;
2153 static void
2154 startup_failure ()
2156 log_write (_
2157 ("Failed to add a file to the cache. Use --force to force startup. Exiting."));
2158 cache_clear (NULL, NULL, 1);
2161 static void
2162 usage (const char *pn, int status)
2164 FILE *fp = status == EXIT_FAILURE ? stderr : stdout;
2166 fprintf (fp, _("Usage: %s [OPTIONS] [file1] [...]\n"
2167 " --debug=[a:..][,g:N][,t:N] enable debugging (a:[ixedsc],g:[1-9],t:[0-N])\n"
2168 " -f, --rcfile=filename load the specfied configuration file\n"
2169 " (~/.pwmd/config)\n"
2170 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2171 " --kill terminate an existing instance of pwmd\n"
2172 " -n, --no-fork run as a foreground process\n"
2173 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2174 " --ignore, --force ignore file errors during startup\n"
2175 " -o, --outfile=filename output file when importing or converting\n"
2176 " -C, --convert=filename convert a version 2 data file to version 3\n"
2177 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2178 " -k, --passphrase-file=file for use when importing or converting\n"
2179 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2180 " converting\n"
2181 " --no-passphrase when importing or converting\n"
2182 " --keyid=keyID[,..] public key to use when encrypting\n"
2183 " --sign-keyid=fpr[,..] fingerprint of the signing key to use\n"
2184 " --symmetric use conventional encryption with optional signer\n"
2185 " --keyparam=filename custom key parameters to use (gpg default)\n"
2186 " --help this help text\n"
2187 " --version show version and compile time features\n"),
2188 pn);
2189 exit (status);
2192 static void
2193 unlink_stale_socket (const char *sock, const char *pidfile)
2195 log_write (_ ("removing stale socket %s"), sock);
2196 unlink (sock);
2197 unlink (pidfile);
2200 static int
2201 test_pidfile (const char *path, const char *sock, char *buf, size_t buflen,
2202 char **pidfile, int create, mode_t mode, int terminate)
2204 pid_t pid;
2205 int fd;
2206 size_t len;
2208 if (!create)
2210 snprintf (buf, buflen, "%s/%s.pid", homedir, sock);
2211 *pidfile = str_dup (buf);
2212 fd = open (buf, O_RDONLY);
2214 else
2215 fd = open (*pidfile, O_CREAT|O_WRONLY|O_TRUNC, mode);
2217 if (fd == -1)
2219 if (!create && errno != ENOENT)
2221 log_write ("%s: %s", buf, pwmd_strerror (errno));
2222 free (*pidfile);
2223 *pidfile = NULL;
2224 return -1;
2226 else if (!create && !terminate)
2227 return 0;
2229 log_write ("%s: %s", *pidfile, strerror (errno));
2230 return -1;
2233 if (create)
2235 snprintf (buf, buflen, "%i", getpid ());
2236 ssize_t ret = write (fd, buf, strlen (buf));
2237 if (ret == -1)
2238 log_write ("%s (%i): %s", __FUNCTION__, __LINE__,
2239 pwmd_strerror (gpg_error_from_syserror ()));
2240 close (fd);
2241 return 0;
2244 len = read (fd, buf, buflen);
2245 close (fd);
2246 if (len == 0)
2248 unlink_stale_socket (path, *pidfile);
2249 return 0;
2252 if (sscanf (buf, "%5i", &pid) != 1 || pid == 0)
2254 if (!terminate)
2256 unlink_stale_socket (path, *pidfile);
2257 return 0;
2261 if (kill (pid, 0) == -1)
2263 unlink_stale_socket (path, *pidfile);
2264 return 0;
2267 if (terminate)
2269 if (kill (pid, SIGTERM) == -1)
2270 log_write ("%s: %s", path, pwmd_strerror (errno));
2272 else
2273 log_write (_ ("an instance for socket %s is already running"), path);
2275 xfree (*pidfile);
2276 *pidfile = NULL;
2277 return 1;
2280 static unsigned
2281 parse_debug_level (const char *str, unsigned *debug, int *gpgme, int *tls)
2283 const char *p;
2284 unsigned level = 0;
2285 int gl = 0, tl = 0;
2287 for (p = str; p && *p; p++)
2289 if (*p == 'a') // assuan debug flags
2291 if (*++p != ':')
2292 return 1;
2294 while (*++p)
2296 switch (*p)
2298 case 'i':
2299 level |= ASSUAN_LOG_INIT;
2300 break;
2301 case 'x':
2302 level |= ASSUAN_LOG_CTX;
2303 break;
2304 case 'e':
2305 level |= ASSUAN_LOG_ENGINE;
2306 break;
2307 case 'd':
2308 level |= ASSUAN_LOG_DATA;
2309 break;
2310 case 's':
2311 level |= ASSUAN_LOG_SYSIO;
2312 break;
2313 case 'c':
2314 level |= ASSUAN_LOG_CONTROL;
2315 break;
2316 case ',':
2317 break;
2318 default:
2319 return 1;
2322 if (*p == ',')
2323 break;
2326 if (!*p)
2327 break;
2329 else if (*p == 'g' || *p == 't') // gpgme and TLS debug level
2331 int t = *p == 't';
2332 int n;
2334 if (*++p != ':')
2335 return 1;
2337 if (!isdigit (*++p))
2338 return 1;
2340 n = atoi (p);
2341 if (t)
2342 tl = n;
2343 else
2344 gl = n;
2346 if (tl < 0 || gl < 0 || gl > 9)
2347 return 1;
2349 while (isdigit (*p))
2350 p++;
2352 p--;
2353 if (*(p+1) && *(p+1) != ',')
2354 return 1;
2355 else if (*(p+1))
2356 p++;
2358 else
2359 return 1;
2362 if (tl)
2363 *tls = tl;
2365 if (gl)
2366 *gpgme = gl;
2368 *debug = level;
2369 return 0;
2373 main (int argc, char *argv[])
2375 int opt;
2376 struct sockaddr_un addr;
2377 char buf[PATH_MAX];
2378 char *socketpath = NULL, *socketdir, *socketname = NULL;
2379 char *socketarg = NULL;
2380 char *datadir = NULL;
2381 char *pidfile = NULL;
2382 mode_t mode = 0600;
2383 int x;
2384 char *p;
2385 char **cache_push = NULL;
2386 char *import = NULL, *keyid = NULL, *sign_keyid = NULL;
2387 char *keyparam = NULL;
2388 int estatus = EXIT_FAILURE;
2389 int sockfd;
2390 char *outfile = NULL;
2391 int do_unlink = 0;
2392 int secure = 0;
2393 int show_version = 0;
2394 int force = 0;
2395 gpg_error_t rc;
2396 char *keyfile = NULL;
2397 int exists;
2398 int optindex;
2399 int terminate = 0;
2400 int sym = 0;
2401 int gpgme_level = -1;
2402 int tls_level = -1;
2403 /* Must maintain the same order as longopts[] */
2404 enum
2406 OPT_VERSION, OPT_HELP, OPT_HOMEDIR, OPT_NO_FORK, OPT_DISABLE_DUMP,
2407 OPT_FORCE, OPT_RCFILE, OPT_PASSPHRASE_FILE, OPT_IMPORT, OPT_OUTFILE,
2408 OPT_KEYID, OPT_SIGN_KEYID, OPT_SYMMETRIC, OPT_KEYPARAM, OPT_KILL,
2409 OPT_DEBUG
2411 const char *optstring = "nf:C:k:I:o:s";
2412 const struct option longopts[] = {
2413 {"version", no_argument, 0, 0},
2414 {"help", no_argument, 0, 0},
2415 {"homedir", required_argument, 0, 0},
2416 {"no-fork", no_argument, 0, 'n'},
2417 {"disable_dump", no_argument, 0, 0},
2418 {"force", no_argument, 0, 0},
2419 {"rcfile", required_argument, 0, 'f'},
2420 {"passphrase-file", required_argument, 0, 'k'},
2421 {"import", required_argument, 0, 'I'},
2422 {"outfile", required_argument, 0, 'o'},
2423 {"keyid", required_argument, 0, 0},
2424 {"sign-keyid", required_argument, 0, 0},
2425 {"symmetric", no_argument, 0, 's'},
2426 {"keyparam", required_argument, 0, 0},
2427 {"kill", no_argument, 0, 0},
2428 {"debug", required_argument, 0, 0},
2429 {0, 0, 0, 0}
2432 log_fd = -1;
2433 cmdline = 1;
2435 #ifndef DEBUG
2436 #ifdef HAVE_SETRLIMIT
2437 struct rlimit rl;
2439 rl.rlim_cur = rl.rlim_max = 0;
2441 if (setrlimit (RLIMIT_CORE, &rl) != 0)
2442 err (EXIT_FAILURE, "setrlimit()");
2443 #endif
2445 #ifdef HAVE_PR_SET_DUMPABLE
2446 prctl (PR_SET_DUMPABLE, 0);
2447 #endif
2448 #endif
2450 #ifdef ENABLE_NLS
2451 setlocale (LC_ALL, "");
2452 bindtextdomain ("pwmd", LOCALEDIR);
2453 textdomain ("pwmd");
2454 #endif
2456 if (setup_crypto ())
2457 exit (EXIT_FAILURE);
2459 #ifdef WITH_GNUTLS
2460 tls_level = tls_level == -1 ? 1 : tls_level;
2461 gnutls_global_set_log_level (tls_level);
2462 tls_fd = -1;
2463 tls6_fd = -1;
2464 #endif
2465 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
2466 xmlInitMemory ();
2467 xmlInitGlobals ();
2468 xmlInitParser ();
2469 xmlXPathInit ();
2471 while ((opt = getopt_long (argc, argv, optstring, longopts, &optindex))
2472 != -1)
2474 switch (opt)
2476 case 'I':
2477 import = optarg;
2478 break;
2479 case 'k':
2480 keyfile = optarg;
2481 break;
2482 case 'o':
2483 outfile = optarg;
2484 break;
2485 case 'D':
2486 secure = 1;
2487 break;
2488 case 'n':
2489 nofork = 1;
2490 break;
2491 case 'f':
2492 rcfile = str_dup (optarg);
2493 break;
2494 case 's':
2495 sym = 1;
2496 break;
2497 default:
2498 usage (argv[0], EXIT_FAILURE);
2499 break;
2500 case 0:
2501 switch (optindex)
2503 case OPT_DEBUG:
2504 if (parse_debug_level (optarg, &assuan_level, &gpgme_level,
2505 &tls_level))
2506 usage (argv[0], EXIT_FAILURE);
2507 break;
2508 case OPT_SYMMETRIC:
2509 sym = 1;
2510 break;
2511 case OPT_VERSION:
2512 show_version = 1;
2513 break;
2514 case OPT_HELP:
2515 usage (argv[0], EXIT_SUCCESS);
2516 break;
2517 case OPT_HOMEDIR:
2518 homedir = str_dup (optarg);
2519 break;
2520 case OPT_NO_FORK:
2521 nofork = 1;
2522 break;
2523 case OPT_DISABLE_DUMP:
2524 secure = 1;
2525 break;
2526 case OPT_FORCE:
2527 force = 1;
2528 break;
2529 case OPT_RCFILE:
2530 rcfile = str_dup (optarg);
2531 break;
2532 case OPT_PASSPHRASE_FILE:
2533 keyfile = optarg;
2534 break;
2535 case OPT_IMPORT:
2536 import = optarg;
2537 break;
2538 case OPT_OUTFILE:
2539 outfile = optarg;
2540 break;
2541 case OPT_KEYID:
2542 keyid = optarg;
2543 break;
2544 case OPT_SIGN_KEYID:
2545 sign_keyid = optarg;
2546 break;
2547 case OPT_KEYPARAM:
2548 keyparam = optarg;
2549 break;
2550 case OPT_KILL:
2551 terminate = 1;
2552 break;
2553 default:
2554 usage (argv[0], EXIT_FAILURE);
2559 if (show_version)
2561 printf (_("%s\n\n"
2562 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016\n"
2563 "%s\n"
2564 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2565 "Compile time features:\n%s"), PACKAGE_STRING,
2566 PACKAGE_BUGREPORT,
2567 #ifdef PWMD_HOMEDIR
2568 "+PWMD_HOMEDIR=" PWMD_HOMEDIR "\n"
2569 #endif
2570 #ifdef WITH_GNUTLS
2571 "+WITH_GNUTLS\n"
2572 #else
2573 "-WITH_GNUTLS\n"
2574 #endif
2575 #ifdef WITH_LIBACL
2576 "+WITH_LIBACL\n"
2577 #else
2578 "-WITH_LIBACL\n"
2579 #endif
2580 #ifdef DEBUG
2581 "+DEBUG\n"
2582 #else
2583 "-DEBUG\n"
2584 #endif
2585 #ifdef MEM_DEBUG
2586 "+MEM_DEBUG\n"
2587 #else
2588 "-MEM_DEBUG\n"
2589 #endif
2590 #ifdef MUTEX_DEBUG
2591 "+MUTEX_DEBUG\n"
2592 #else
2593 "-MUTEX_DEBUG\n"
2594 #endif
2596 exit (EXIT_SUCCESS);
2599 if (!homedir)
2600 #ifdef PWMD_HOMEDIR
2601 homedir = str_dup(PWMD_HOMEDIR);
2602 #else
2603 homedir = str_asprintf ("%s/.pwmd", get_home_dir());
2604 #endif
2606 if (mkdir (homedir, 0700) == -1 && errno != EEXIST)
2607 err (EXIT_FAILURE, "%s", homedir);
2609 if (!rcfile)
2610 rcfile = str_asprintf ("%s/config", homedir);
2612 pthread_key_create (&last_error_key, free_key);
2613 #ifndef HAVE_PTHREAD_CANCEL
2614 pthread_key_create (&signal_thread_key, free_key);
2615 #endif
2617 pthread_mutexattr_t attr;
2618 pthread_mutexattr_init (&attr);
2619 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
2620 pthread_mutex_init (&rcfile_mutex, &attr);
2621 global_config = config_parse (rcfile, 0);
2622 if (!global_config)
2624 pthread_mutexattr_destroy (&attr);
2625 pthread_mutex_destroy (&rcfile_mutex);
2626 exit (EXIT_FAILURE);
2629 p = config_get_string ("global", "gpg_homedir");
2630 if (!p)
2631 datadir = str_asprintf ("%s/.gnupg", homedir);
2632 else
2633 datadir = expand_homedir (p);
2635 xfree (p);
2636 if (mkdir (datadir, 0700) == -1 && errno != EEXIST)
2637 err (EXIT_FAILURE, "%s", datadir);
2639 if (gpgme_level != -1)
2641 char s[2] = { gpgme_level + '0', 0 };
2643 if (getenv ("GPGME_DEBUG"))
2644 log_write (_ ("Overriding GPGME_DEBUG environment with level %u!"),
2645 gpgme_level);
2647 gpgme_set_global_flag ("debug", s);
2650 rc = gpgme_set_engine_info (GPGME_PROTOCOL_OpenPGP, NULL, datadir);
2651 xfree (datadir);
2653 snprintf (buf, sizeof (buf), "%s/data", homedir);
2654 if (mkdir (buf, 0700) == -1 && errno != EEXIST)
2655 err (EXIT_FAILURE, "%s", buf);
2657 datadir = str_dup (buf);
2658 pthread_cond_init (&rcfile_cond, NULL);
2659 pthread_mutex_init (&cn_mutex, &attr);
2660 pthread_mutexattr_destroy (&attr);
2662 setup_logging ();
2664 x = config_get_int_param (global_config, "global", "priority", &exists);
2665 if (exists && x != atoi(INVALID_PRIORITY))
2667 errno = 0;
2668 if (setpriority (PRIO_PROCESS, 0, x) == -1)
2670 log_write ("setpriority(): %s",
2671 pwmd_strerror (gpg_error_from_errno (errno)));
2672 goto do_exit;
2675 #ifdef HAVE_MLOCKALL
2676 if (disable_mlock == 0 && mlockall (MCL_CURRENT | MCL_FUTURE) == -1)
2678 log_write ("mlockall(): %s",
2679 pwmd_strerror (gpg_error_from_errno (errno)));
2680 goto do_exit;
2682 #endif
2684 rc = cache_init ();
2685 if (rc)
2687 log_write ("pwmd: ERR %i: %s", rc, pwmd_strerror (rc));
2688 exit (EXIT_FAILURE);
2691 if (import)
2693 char **keyids = NULL, **sign_keyids = NULL;
2695 if (!outfile || !*outfile || argc != optind)
2696 usage (argv[0], EXIT_FAILURE);
2698 if (keyid)
2699 keyids = str_split (keyid, ",", 0);
2700 if (sign_keyid)
2701 sign_keyids = str_split (sign_keyid, ",", 0);
2702 rc = xml_import (import, outfile, keyids, sign_keyids, keyfile, keyparam, sym);
2703 strv_free (keyids);
2704 strv_free (sign_keyids);
2705 if (rc)
2707 if (gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
2708 rc = gpg_error (rc);
2710 log_write ("%s: %u: %s", import, rc, pwmd_strerror (rc));
2713 config_free (global_config);
2714 xfree (rcfile);
2715 exit (rc ? EXIT_FAILURE : EXIT_SUCCESS);
2718 p = config_get_string ("global", "socket_path");
2719 if (!p)
2720 p = str_asprintf ("%s/socket", homedir);
2722 socketarg = expand_homedir (p);
2723 xfree (p);
2725 if (!secure)
2726 disable_list_and_dump = config_get_boolean ("global",
2727 "disable_list_and_dump");
2728 else
2729 disable_list_and_dump = secure;
2731 cache_push = config_get_list ("global", "cache_push");
2733 while (optind < argc)
2735 if (strv_printf (&cache_push, "%s", argv[optind++]) == 0)
2736 errx (EXIT_FAILURE, "%s", pwmd_strerror (GPG_ERR_ENOMEM));
2739 if (strchr (socketarg, '/') == NULL)
2741 socketdir = getcwd (buf, sizeof (buf));
2742 socketname = str_dup (socketarg);
2743 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2745 else
2747 socketname = str_dup (strrchr (socketarg, '/'));
2748 socketname++;
2749 socketarg[strlen (socketarg) - strlen (socketname) - 1] = 0;
2750 socketdir = str_dup (socketarg);
2751 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2754 if (chdir (datadir))
2756 log_write ("%s: %s", datadir,
2757 pwmd_strerror (gpg_error_from_errno (errno)));
2758 unlink (socketpath);
2759 goto do_exit;
2762 x = test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 0,
2763 mode, terminate);
2764 if (!terminate && x)
2765 goto do_exit;
2766 else if (terminate)
2768 estatus = x != 1 ? EXIT_FAILURE : EXIT_SUCCESS;
2769 goto do_exit;
2773 * bind() doesn't like the full pathname of the socket or any non alphanum
2774 * characters so change to the directory where the socket is wanted then
2775 * create it then change to datadir.
2777 if (chdir (socketdir))
2779 log_write ("%s: %s", socketdir,
2780 pwmd_strerror (gpg_error_from_errno (errno)));
2781 goto do_exit;
2784 xfree (socketdir);
2786 if ((sockfd = socket (PF_UNIX, SOCK_STREAM, 0)) == -1)
2788 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2789 goto do_exit;
2792 addr.sun_family = AF_UNIX;
2793 snprintf (addr.sun_path, sizeof (addr.sun_path), "%s", socketname);
2794 do_unlink = 1;
2795 if (bind (sockfd, (struct sockaddr *) &addr, sizeof (struct sockaddr)) ==
2798 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2800 if (errno == EADDRINUSE)
2802 do_unlink = 0;
2803 log_write (_("Either there is another pwmd running or '%s' is a \n"
2804 "stale socket. Please remove it manually."), socketpath);
2807 goto do_exit;
2811 char *t = config_get_string ("global", "socket_perms");
2812 mode_t mask;
2814 if (t)
2816 mode = strtol (t, NULL, 8);
2817 mask = umask (0);
2818 xfree (t);
2820 if (chmod (socketname, mode) == -1)
2822 log_write ("%s: %s", socketname,
2823 pwmd_strerror (gpg_error_from_errno (errno)));
2824 close (sockfd);
2825 umask (mask);
2826 goto do_exit;
2829 umask (mask);
2833 xfree (--socketname);
2835 if (chdir (datadir))
2837 log_write ("%s: %s", datadir,
2838 pwmd_strerror (gpg_error_from_errno (errno)));
2839 close (sockfd);
2840 goto do_exit;
2843 xfree (datadir);
2844 #ifdef WITH_GNUTLS
2845 if (config_get_boolean ("global", "enable_tcp"))
2847 if (!start_stop_tls (0))
2849 close (sockfd);
2850 goto do_exit;
2853 #endif
2856 * Set the cache entry for a file. Prompts for the password.
2858 if (cache_push)
2860 for (opt = 0; cache_push[opt]; opt++)
2862 struct crypto_s *crypto = NULL;
2863 char *pw_file = config_get_string (cache_push[opt],
2864 "passphrase_file");
2865 gpg_error_t rc = crypto_init (&crypto, NULL, cache_push[opt],
2866 pw_file != NULL, pw_file);
2868 if (!rc)
2870 crypto->flags |= pw_file ? CRYPTO_FLAG_KEYFILE : 0;
2871 crypto->keyfile = pw_file;
2873 else
2874 xfree (pw_file);
2876 if (rc)
2878 estatus = EXIT_FAILURE;
2879 goto do_exit;
2882 rc = do_cache_push (crypto);
2883 if (rc && !force)
2885 log_write ("ERR %u: %s", rc, pwmd_strerror(rc));
2886 strv_free (cache_push);
2887 startup_failure ();
2888 estatus = EXIT_FAILURE;
2889 crypto_free (crypto);
2890 goto do_exit;
2892 else if (rc)
2893 log_write ("%s: %s", crypto->filename, pwmd_strerror(rc));
2894 else
2895 log_write (_("Successfully added '%s' to the cache."),
2896 crypto->filename);
2898 crypto_free (crypto);
2901 strv_free (cache_push);
2902 log_write (!nofork ? _("Done. Daemonizing...") :
2903 _("Done. Waiting for connections..."));
2906 if (listen (sockfd, 128) == -1)
2908 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2909 goto do_exit;
2912 if (!nofork)
2914 switch (fork ())
2916 case -1:
2917 log_write ("fork(): %s",
2918 pwmd_strerror (gpg_error_from_errno (errno)));
2919 goto do_exit;
2920 case 0:
2921 close (0);
2922 close (1);
2923 close (2);
2924 setsid ();
2925 break;
2926 default:
2927 _exit (EXIT_SUCCESS);
2931 (void)test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 1,
2932 mode, 0);
2933 cmdline = 0;
2934 pthread_key_create (&thread_name_key, free_key);
2935 estatus = server_loop (sockfd, &socketpath);
2937 do_exit:
2938 if (socketpath && do_unlink)
2940 unlink (socketpath);
2941 xfree (socketpath);
2944 xfree (socketarg);
2945 #ifdef WITH_GNUTLS
2946 gnutls_global_deinit ();
2947 tls_deinit_params ();
2948 #endif
2949 if (rcfile_tid)
2951 #ifdef HAVE_PTHREAD_CANCEL
2952 pthread_cancel (rcfile_tid);
2953 #else
2954 pthread_kill (rcfile_tid, SIGUSR2);
2955 pthread_cond_signal (&rcfile_cond);
2956 #endif
2957 pthread_join (rcfile_tid, NULL);
2960 pthread_cond_destroy (&rcfile_cond);
2961 pthread_mutex_destroy (&rcfile_mutex);
2962 pthread_key_delete (last_error_key);
2963 #ifndef HAVE_PTHREAD_CANCEL
2964 pthread_key_delete (signal_thread_key);
2965 #endif
2967 if (global_config)
2968 config_free (global_config);
2970 free_invoking_users (invoking_users);
2971 xfree (rcfile);
2972 xfree (home_directory);
2973 xfree (homedir);
2974 xmlCleanupParser ();
2975 xmlCleanupGlobals ();
2977 if (pidfile)
2978 unlink (pidfile);
2979 xfree (pidfile);
2981 if (estatus == EXIT_SUCCESS && !terminate)
2982 log_write (_("pwmd exiting normally"));
2984 pthread_key_delete (thread_name_key);
2985 closelog ();
2987 if (log_fd != -1)
2988 close (log_fd);
2990 exit (estatus);
2993 gpg_error_t lock_flock (assuan_context_t ctx, const char *filename,
2994 int type, int *fd)
2996 gpg_error_t rc = 0;
2998 #ifdef HAVE_FLOCK
2999 *fd = open (filename, O_RDONLY);
3000 if (*fd == -1)
3001 return gpg_error_from_syserror ();
3003 TRY_FLOCK (ctx, *fd, type, rc);
3004 if (rc)
3006 close (*fd);
3007 *fd = -1;
3009 #endif
3011 return rc;
3014 void unlock_flock (int *fd)
3016 #ifdef HAVE_FLOCK
3017 if (*fd != -1)
3018 close (*fd);
3020 *fd = -1;
3021 #endif