Merge branch 'agent-cache-checking'
[pwmd.git] / src / pwmd.c
blob2bfda9890409ebfde1aec78882ce9d51ed0fc641
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 exiting;
98 static int cmdline;
99 static jmp_buf jmp;
100 static int nofork;
101 static pthread_cond_t quit_cond;
102 static pthread_mutex_t quit_mutex;
103 static pthread_t keepalive_tid;
104 static int log_fd;
105 static unsigned assuan_level;
107 #ifndef HAVE_PTHREAD_CANCEL
108 static pthread_key_t signal_thread_key;
109 #endif
111 #ifdef WITH_GNUTLS
112 static int tls_fd;
113 static int tls6_fd;
114 static pthread_t tls_tid;
115 static pthread_t tls6_tid;
116 static int spawned_tls;
117 static int spawned_tls6;
119 static int start_stop_tls (int term);
120 #endif
122 static gpg_error_t do_cache_push (struct crypto_s *crypto);
123 static int signal_loop (sigset_t sigset);
125 #ifndef HAVE_PTHREAD_CANCEL
126 #define INIT_THREAD_SIGNAL do { \
127 struct sigaction act; \
128 sigset_t sigset; \
129 sigemptyset (&sigset); \
130 sigaddset (&sigset, SIGUSR2); \
131 pthread_sigmask (SIG_UNBLOCK, &sigset, NULL); \
132 memset (&act, 0, sizeof(act)); \
133 act.sa_flags = SA_SIGINFO; \
134 act.sa_mask = sigset; \
135 act.sa_sigaction = catch_thread_signal; \
136 sigaction (SIGUSR2, &act, NULL); \
137 } while (0)
139 static void
140 catch_thread_signal (int sig, siginfo_t *info, void *ctx)
142 int *n = (int *) pthread_getspecific (signal_thread_key);
144 *n = 1;
145 pthread_setspecific (signal_thread_key, n);
147 #endif
149 static void
150 setup_logging ()
152 int n = config_get_boolean ("global", "enable_logging");
154 if (n)
156 char *p = config_get_string ("global", "log_path");
158 if (!p || (logfile && p && log_fd != -1 && strcmp(p, logfile)))
160 if (log_fd != -1)
161 close (log_fd);
163 log_fd = -1;
166 xfree (logfile);
167 logfile = NULL;
168 if (p)
169 logfile = expand_homedir (p);
170 xfree (p);
172 else
174 xfree (logfile);
175 logfile = NULL;
176 if (log_fd != -1)
177 close(log_fd);
179 log_fd = -1;
180 closelog ();
183 log_syslog = config_get_boolean ("global", "syslog");
184 if (log_syslog == 1)
185 openlog ("pwmd", LOG_NDELAY | LOG_PID, LOG_DAEMON);
188 static void *
189 reload_rcfile_thread (void *arg)
191 #ifndef HAVE_PTHREAD_CANCEL
192 int *n = xmalloc (sizeof (int));
194 *n = 0;
195 pthread_setspecific (signal_thread_key, n);
196 INIT_THREAD_SIGNAL;
197 #endif
199 #ifdef HAVE_PR_SET_NAME
200 prctl (PR_SET_NAME, "reload rcfile");
201 #endif
202 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
203 MUTEX_LOCK (&rcfile_mutex);
205 for (;;)
207 struct slist_s *keep = NULL;
208 struct slist_s *config;
209 int b = disable_list_and_dump;
211 pthread_cleanup_push (cleanup_mutex_cb, &rcfile_mutex);
212 pthread_cond_wait (&rcfile_cond, &rcfile_mutex);
213 #ifndef HAVE_PTHREAD_CANCEL
214 int *cancel = (int *) pthread_getspecific (signal_thread_key);
215 if (*cancel)
216 break;
217 #endif
219 keep = config_keep_save ();
220 log_write (_("reloading configuration file '%s'"), rcfile);
222 config = config_parse (rcfile, 1);
223 if (config)
225 config_free (global_config);
226 global_config = config;
227 setup_logging ();
230 config_keep_restore (keep);
231 disable_list_and_dump = !disable_list_and_dump ? b : 1;
233 #ifdef WITH_GNUTLS
234 /* Kill existing listening threads since the configured listening
235 * protocols may have changed. */
236 start_stop_tls (1);
237 start_stop_tls (0);
238 #endif
239 crypto_set_keepalive ();
240 pthread_cleanup_pop (0);
243 MUTEX_UNLOCK (&rcfile_mutex);
244 return NULL;
247 gpg_error_t
248 send_error (assuan_context_t ctx, gpg_error_t e)
250 struct client_s *client = assuan_get_pointer (ctx);
252 if (gpg_err_source (e) == GPG_ERR_SOURCE_UNKNOWN)
253 e = gpg_error (e);
255 if (client)
256 client->last_rc = e;
258 if (!e)
259 return assuan_process_done (ctx, 0);
261 if (!ctx)
263 log_write ("ERR %i: %s", e, pwmd_strerror (e));
264 return e;
267 if (client && client->xml_error)
269 log_write ("%s", client->xml_error->message);
270 xfree (client->last_error);
271 client->last_error = NULL;
272 if (client->xml_error->message)
273 client->last_error = str_dup (client->xml_error->message);
275 e = assuan_process_done (ctx,
276 assuan_set_error (ctx, e,
277 client->xml_error->message ? client->xml_error->message : NULL));
278 xmlResetLastError ();
279 xmlResetError (client->xml_error);
280 xfree (client->xml_error);
281 client->xml_error = NULL;
282 return e;
285 return assuan_process_done (ctx,
286 assuan_set_error (ctx, e, pwmd_strerror (e)));
289 void
290 log_write (const char *fmt, ...)
292 char *args;
293 va_list ap;
294 time_t now;
295 char buf[255];
296 pthread_t tid = pthread_self ();
297 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
299 if ((!logfile && !isatty (STDERR_FILENO) && !log_syslog) || !fmt)
300 return;
302 pthread_mutex_lock (&m);
303 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock, &m);
305 if (!cmdline && logfile && log_fd == -1)
307 log_fd = open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600);
308 if (log_fd == -1)
309 warn ("%s", logfile);
312 va_start (ap, fmt);
314 if (str_vasprintf (&args, fmt, ap) != -1)
316 if (cmdline)
318 pthread_cleanup_push (xfree, args);
319 fprintf (stderr, "pwmd: %s\n", args);
320 fflush (stderr);
321 pthread_cleanup_pop (1);
323 else
325 char *name = pthread_getspecific (thread_name_key);
326 char *line;
328 pthread_cleanup_push (xfree, args);
329 snprintf (buf, sizeof (buf),
330 name && *name == '!' ? "%s: " : name ? "%s(%p): " : "%s",
331 name ? *name == '!' ? name+1 : name : "",
332 name && *name == '!' ? 0 : name ? (pthread_t *) tid : 0);
333 name = buf;
335 if (!cmdline && log_syslog && !nofork)
336 syslog (LOG_INFO, "%s%s", name, args);
338 time (&now);
339 struct tm *tm = localtime (&now);
340 char tbuf[21];
341 strftime (tbuf, sizeof (tbuf), "%b %d %Y %H:%M:%S ", tm);
342 tbuf[sizeof (tbuf) - 1] = 0;
344 if (args[strlen (args) - 1] == '\n')
345 args[strlen (args) - 1] = 0;
347 line = str_asprintf ("%s %i %s%s\n", tbuf, getpid (), name,
348 args);
349 pthread_cleanup_pop (1);
350 if (line)
352 pthread_cleanup_push (xfree, line);
353 if (logfile && log_fd != -1)
355 ssize_t ret = write (log_fd, line, strlen (line));
356 (void)ret;
357 fsync (log_fd);
360 if (nofork)
362 fprintf (stdout, "%s", line);
363 fflush (stdout);
366 pthread_cleanup_pop (1);
371 va_end (ap);
372 pthread_cleanup_pop (0);
374 if (log_fd != -1 && log_keepopen <= 0)
376 close(log_fd);
377 log_fd = -1;
380 pthread_mutex_unlock (&m);
383 static gpg_error_t
384 setup_crypto ()
386 if (!gcry_check_version (GCRYPT_VERSION))
388 fprintf (stderr, _("gcry_check_version(): Incompatible libgcrypt. "
389 "Wanted %s, got %s.\n"), GCRYPT_VERSION,
390 gcry_check_version (NULL));
391 return GPG_ERR_UNKNOWN_VERSION;
394 gcry_set_allocation_handler (xmalloc, xmalloc, NULL, xrealloc, xfree);
395 return 0;
398 gpg_error_t
399 do_validate_peer (assuan_context_t ctx, const char *section,
400 assuan_peercred_t * peer)
402 char **users;
403 int allowed = 0;
404 gpg_error_t rc;
405 struct client_s *client = assuan_get_pointer (ctx);
407 if (!client)
408 return GPG_ERR_FORBIDDEN;
410 #ifdef WITH_GNUTLS
411 if (client->thd->remote)
412 return tls_validate_access (client, section);
413 #endif
415 rc = assuan_get_peercred (ctx, peer);
416 if (rc)
417 return rc;
419 users = config_get_list (section, "allowed");
420 if (users)
422 for (char **p = users; !rc && *p; p++)
424 rc = acl_check_common(client, *p, (*peer)->uid, (*peer)->gid,
425 &allowed);
428 strv_free (users);
431 return allowed && !rc ? 0 : rc ? rc : GPG_ERR_FORBIDDEN;
434 /* Test if uid is a member of group 'name'. Invert when 'not' is true. */
435 #ifdef HAVE_GETGRNAM_R
436 static gpg_error_t
437 acl_check_group (const char *name, uid_t uid, gid_t gid, int not, int *allowed)
439 char *buf;
440 struct group gr, *gresult;
441 size_t len = sysconf (_SC_GETGR_R_SIZE_MAX);
442 int err;
443 gpg_error_t rc = 0;
445 if (len == -1)
446 len = 16384;
448 buf = xmalloc (len);
449 if (!buf)
450 return GPG_ERR_ENOMEM;
452 err = getgrnam_r (name, &gr, buf, len, &gresult);
453 if (!err && gresult)
455 if (gresult->gr_gid == gid)
457 xfree (buf);
458 *allowed = !not;
459 return 0;
462 for (char **t = gresult->gr_mem; !rc && *t; t++)
464 char *tbuf;
465 struct passwd pw;
466 struct passwd *result = get_pwd_struct (*t, 0, &pw, &tbuf, &rc);
468 if (!rc && result && result->pw_uid == uid)
470 xfree (tbuf);
471 *allowed = !not;
472 break;
475 xfree (tbuf);
478 xfree (buf);
479 return rc;
481 else if (err)
482 rc = gpg_error_from_errno (err);
484 xfree (buf);
485 return rc ? rc : !gresult ? 0 : GPG_ERR_EACCES;
487 #else
488 static gpg_error_t
489 acl_check_group (const char *name, uid_t uid, gid_t gid, int not, int *allowed)
491 struct group *gresult;
492 gpg_error_t rc = 0;
494 errno = 0;
495 gresult = getgrnam (name);
496 if (!errno && gresult && gresult->gr_gid == gid)
498 *allowed = !not;
499 return 0;
501 else if (errno)
502 rc = gpg_error_from_syserror ();
503 else if (!gresult)
504 return 0;
506 for (char **t = gresult->gr_mem; !rc && *t; t++)
508 char *buf;
509 struct passwd pw;
510 struct passwd *result = get_pwd_struct (*t, 0, &pw, &buf, &rc);
512 if (!rc && result && result->pw_uid == uid)
514 xfree (buf);
515 *allowed = !not;
516 break;
519 xfree (buf);
522 return rc;
524 #endif
526 gpg_error_t
527 peer_is_invoker(struct client_s *client)
529 struct invoking_user_s *user;
530 int allowed = 0;
532 if (client->thd->state == CLIENT_STATE_UNKNOWN)
533 return GPG_ERR_EACCES;
535 for (user = invoking_users; user; user = user->next)
537 #ifdef WITH_GNUTLS
538 if (client->thd->remote)
540 if (user->type == INVOKING_TLS
541 && !strcmp(client->thd->tls->fp, user->id))
542 allowed = user->not ? 0 : 1;
544 continue;
546 #endif
548 if (user->type == INVOKING_GID)
550 gpg_error_t rc = acl_check_group (user->id,
551 client->thd->peer->uid,
552 client->thd->peer->gid,
553 user->not, &allowed);
554 if (rc)
555 return rc;
557 else if (user->type == INVOKING_UID && client->thd->peer->uid == user->uid)
558 allowed = user->not ? 0 : 1;
561 return allowed ? 0 : GPG_ERR_EACCES;
564 #ifdef HAVE_GETGRNAM_R
565 gpg_error_t
566 acl_check_common (struct client_s *client, const char *user, uid_t uid,
567 gid_t gid, int *allowed)
569 int not = 0;
570 int rw = 0;
571 int tls = 0;
572 gpg_error_t rc = 0;
574 if (!user || !*user)
575 return 0;
577 if (*user == '-' || *user == '!')
578 not = 1;
580 if (*user == '+') // not implemented yet
581 rw = 1;
583 if (*user == '#') // TLS fingerprint hash
584 tls = 1;
586 if (not || rw || tls)
587 user++;
589 if (tls)
591 #ifdef WITH_GNUTLS
592 if (client->thd->remote)
594 if (!strcasecmp (client->thd->tls->fp, user))
595 *allowed = !not;
598 return 0;
599 #else
600 return 0;
601 #endif
603 #ifdef WITH_GNUTLS
604 else if (client->thd->remote) // Remote client with no FP in the ACL
605 return 0;
606 #endif
608 if (*user == '@') // all users in group
609 return acl_check_group (user+1, uid, gid, not, allowed);
610 else
612 char *buf;
613 struct passwd pw;
614 struct passwd *pwd = get_pwd_struct (user, 0, &pw, &buf, &rc);
616 if (!rc && pwd && pwd->pw_uid == uid)
617 *allowed = !not;
619 xfree (buf);
622 return rc;
624 #else
625 gpg_error_t
626 acl_check_common (struct client_s *client, const char *user, uid_t uid,
627 gid_t gid, int *allowed)
629 gpg_error_t rc = 0;
630 int not = 0;
631 int rw = 0;
632 int tls = 0;
634 if (!user || !*user)
635 return 0;
637 if (*user == '-' || *user == '!')
638 not = 1;
640 if (*user == '+') // not implemented yet
641 rw = 1;
643 if (*user == '#') // TLS fingerprint hash
644 tls = 1;
646 if (not || rw || tls)
647 user++;
649 if (tls)
651 #ifdef WITH_GNUTLS
652 if (client->thd->remote)
654 if (!strcasecmp (client->thd->tls->fp, user))
655 *allowed = !not;
658 return 0;
659 #else
660 return 0;
661 #endif
664 if (*user == '@') // all users in group
665 return acl_check_group (user+1, uid, gid, not, allowed);
666 else
668 char *buf;
669 struct passwd pw;
670 struct passwd *result = get_pwd_struct (user, 0, &pw, &buf, &rc);
672 if (!rc && result && result->pw_uid == uid)
673 *allowed = !not;
675 xfree (buf);
678 return rc;
680 #endif
682 static gpg_error_t
683 validate_peer (struct client_s *cl)
685 gpg_error_t rc;
687 #ifdef WITH_GNUTLS
688 if (cl->thd->remote)
689 return tls_validate_access (cl, NULL);
690 #endif
692 MUTEX_LOCK (&cn_mutex);
693 rc = do_validate_peer (cl->ctx, "global", &cl->thd->peer);
694 MUTEX_UNLOCK (&cn_mutex);
695 log_write ("peer %s: uid=%i, gid=%i, pid=%i, rc=%u",
696 !rc ? _("accepted") : _("rejected"), cl->thd->peer->uid,
697 cl->thd->peer->gid, cl->thd->peer->pid, rc);
698 return rc;
701 static void
702 xml_error_cb (void *data, xmlErrorPtr e)
704 struct client_s *client = data;
707 * Keep the first reported error as the one to show in the error
708 * description. Reset in send_error().
710 if (client->xml_error)
711 return;
713 client->xml_error = xcalloc (1, sizeof(xmlError));
714 xmlCopyError (e, client->xml_error);
717 static pid_t
718 hook_waitpid (assuan_context_t ctx, pid_t pid, int action,
719 int *status, int options)
721 return waitpid (pid, status, options);
724 static ssize_t
725 hook_read (assuan_context_t ctx, assuan_fd_t fd, void *data, size_t len)
727 #ifdef WITH_GNUTLS
728 struct client_s *client = assuan_get_pointer (ctx);
730 if (client->thd->remote)
731 return tls_read_hook (ctx, (int) fd, data, len);
732 #endif
734 return read ((int) fd, data, len);
737 static ssize_t
738 hook_write (assuan_context_t ctx, assuan_fd_t fd,
739 const void *data, size_t len)
741 #ifdef WITH_GNUTLS
742 struct client_s *client = assuan_get_pointer (ctx);
744 if (client->thd->remote)
745 return tls_write_hook (ctx, (int) fd, data, len);
746 #endif
748 return write ((int) fd, data, len);
752 assuan_log_cb (assuan_context_t ctx, void *data, unsigned cat,
753 const char *msg)
755 struct client_s *client = data;
756 char *str = NULL;
758 (void)client;
760 if (!(assuan_level & cat))
761 return 0;
763 if (!msg)
764 return 1;
766 switch (cat)
768 case ASSUAN_LOG_INIT:
769 str = "ASSUAN[INIT]";
770 break;
771 case ASSUAN_LOG_CTX:
772 str = "ASSUAN[CTX]";
773 break;
774 case ASSUAN_LOG_ENGINE:
775 str = "ASSUAN[ENGINE]";
776 break;
777 case ASSUAN_LOG_DATA:
778 str = "ASSUAN[DATA]";
779 break;
780 case ASSUAN_LOG_SYSIO:
781 str = "ASSUAN[SYSIO]";
782 break;
783 case ASSUAN_LOG_CONTROL:
784 str = "ASSUAN[CONTROL]";
785 break;
786 default:
787 str = "ASSUAN[UNKNOWN]";
788 break;
791 log_write ("%s: %s", str, msg);
792 return 1;
795 static int
796 new_connection (struct client_s *cl)
798 gpg_error_t rc;
799 static struct assuan_malloc_hooks mhooks = { xmalloc, xrealloc, xfree };
800 static struct assuan_system_hooks shooks = {
801 ASSUAN_SYSTEM_HOOKS_VERSION,
802 __assuan_usleep,
803 __assuan_pipe,
804 __assuan_close,
805 hook_read,
806 hook_write,
807 //FIXME
808 NULL, //recvmsg
809 NULL, //sendmsg both are used for FD passing
810 __assuan_spawn,
811 hook_waitpid,
812 __assuan_socketpair,
813 __assuan_socket,
814 __assuan_connect
817 #ifdef WITH_GNUTLS
818 if (cl->thd->remote)
820 char *prio = config_get_string ("global", "tls_cipher_suite");
822 cl->thd->timeout = config_get_integer ("global", "tls_timeout");
823 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
824 return 0;
826 cl->thd->tls = tls_init (cl->thd->fd, cl->thd->timeout, prio);
827 xfree (prio);
828 if (!cl->thd->tls)
829 return 0;
831 #endif
833 rc = assuan_new_ext (&cl->ctx, GPG_ERR_SOURCE_DEFAULT, &mhooks,
834 assuan_log_cb, cl);
835 if (rc)
836 goto fail;
838 assuan_ctx_set_system_hooks (cl->ctx, &shooks);
839 rc = assuan_init_socket_server (cl->ctx, cl->thd->fd, 2);
840 if (rc)
841 goto fail;
843 assuan_set_pointer (cl->ctx, cl);
844 assuan_set_hello_line (cl->ctx, PACKAGE_STRING);
845 rc = register_commands (cl->ctx);
846 if (rc)
847 goto fail;
849 rc = assuan_accept (cl->ctx);
850 if (rc)
851 goto fail;
853 rc = validate_peer (cl);
854 /* May not be implemented on all platforms. */
855 if (rc && gpg_err_code (rc) != GPG_ERR_ASS_GENERAL)
856 goto fail;
858 MUTEX_LOCK (&cn_mutex);
859 cl->thd->state = CLIENT_STATE_INIT;
860 MUTEX_UNLOCK (&cn_mutex);
861 cl->lock_timeout = config_get_integer ("global", "lock_timeout");
862 xmlSetStructuredErrorFunc (cl, xml_error_cb);
863 return 1;
865 fail:
866 log_write ("%s", pwmd_strerror (rc));
867 return 0;
871 * This is called after a client_thread() terminates. Set with
872 * pthread_cleanup_push().
874 static void
875 cleanup_cb (void *arg)
877 struct client_thread_s *cn = arg;
878 struct client_s *cl = cn->cl;
880 MUTEX_LOCK (&cn_mutex);
881 cn_thread_list = slist_remove (cn_thread_list, cn);
882 MUTEX_UNLOCK (&cn_mutex);
884 if (cl)
886 unlock_flock (&cl->flock_fd);
887 cleanup_client (cl);
888 if (cl->xml_error)
889 xmlResetError (cl->xml_error);
891 xfree (cl->xml_error);
893 #ifdef WITH_GNUTLS
894 if (cn->tls)
896 gnutls_deinit (cn->tls->ses);
897 xfree (cn->tls->fp);
898 xfree (cn->tls);
900 #endif
902 if (!cn->atfork && cl->ctx)
903 assuan_release (cl->ctx);
904 else if (!cn->atfork && cl->thd && cl->thd->fd != -1)
905 close (cl->thd->fd);
907 if (cl->crypto)
908 crypto_free (cl->crypto);
910 cl->crypto = NULL;
911 xfree (cl);
913 else
915 if (cn->fd != -1)
916 close (cn->fd);
919 while (cn->msg_queue)
921 struct status_msg_s *msg = cn->msg_queue;
923 cn->msg_queue = msg->next;
924 xfree (msg->line);
925 xfree (msg);
928 if (!cn->atfork && cn->status_msg_pipe[0] != -1)
929 close (cn->status_msg_pipe[0]);
931 if (!cn->atfork && cn->status_msg_pipe[1] != -1)
932 close (cn->status_msg_pipe[1]);
934 pthread_mutex_destroy (&cn->status_mutex);
936 if (!cn->atfork)
938 log_write (_("exiting, fd=%i"), cn->fd);
939 send_status_all (STATUS_CLIENTS, NULL);
942 xfree (cn->name);
943 #ifdef WITH_GNUTLS
944 xfree (cn->peeraddr);
945 #endif
946 xfree (cn);
947 pthread_cond_signal (&quit_cond);
950 void
951 cleanup_all_clients (int atfork)
953 /* This function may be called from pthread_atfork() which requires
954 reinitialization. */
955 if (atfork)
957 pthread_mutexattr_t attr;
959 pthread_mutexattr_init (&attr);
960 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
961 pthread_mutex_init (&cn_mutex, &attr);
962 pthread_mutexattr_destroy (&attr);
963 cache_mutex_init ();
966 MUTEX_LOCK (&cn_mutex);
968 while (slist_length (cn_thread_list))
970 struct client_thread_s *thd = slist_nth_data (cn_thread_list, 0);
972 thd->atfork = atfork;
973 cleanup_cb (thd);
976 exiting = 1;
977 MUTEX_UNLOCK (&cn_mutex);
978 cache_deinit (atfork);
981 static gpg_error_t
982 send_msg_queue (struct client_thread_s *thd)
984 MUTEX_LOCK (&thd->status_mutex);
985 gpg_error_t rc = 0;
986 char c;
987 ssize_t ret;
989 ret = read (thd->status_msg_pipe[0], &c, 1);
990 rc = gpg_error_from_syserror ();
991 if (ret == -1 && gpg_err_code (rc) != GPG_ERR_EAGAIN)
992 log_write ("%s (%i): %s", __FUNCTION__, __LINE__, pwmd_strerror (rc));
993 else
994 rc = 0;
996 thd->wrote_status = 0;
998 while (thd->msg_queue)
1000 struct status_msg_s *msg = thd->msg_queue;
1002 #ifndef HAVE_PTHREAD_CANCEL
1003 if (thd->fd == -1)
1004 break;
1005 #endif
1007 thd->msg_queue = thd->msg_queue->next;
1008 MUTEX_UNLOCK (&thd->status_mutex);
1009 rc = send_status (thd->cl->ctx, msg->s, msg->line);
1010 MUTEX_LOCK (&thd->status_mutex);
1011 xfree (msg->line);
1012 xfree (msg);
1014 if (rc)
1015 break;
1018 MUTEX_UNLOCK (&thd->status_mutex);
1019 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1020 log_write ("%s (%i): %s", __FUNCTION__, __LINE__, pwmd_strerror (rc));
1022 return rc;
1025 static void *
1026 client_thread (void *data)
1028 struct client_thread_s *thd = data;
1029 struct client_s *cl = xcalloc (1, sizeof (struct client_s));
1031 #ifdef HAVE_PR_SET_NAME
1032 prctl (PR_SET_NAME, "client");
1033 #endif
1034 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1036 if (!cl)
1038 log_write ("%s(%i): %s", __FILE__, __LINE__,
1039 pwmd_strerror (GPG_ERR_ENOMEM));
1040 return NULL;
1043 MUTEX_LOCK (&cn_mutex);
1044 pthread_cleanup_push (cleanup_cb, thd);
1045 thd->cl = cl;
1046 cl->thd = thd;
1047 cl->flock_fd = -1;
1048 MUTEX_UNLOCK (&cn_mutex);
1050 if (new_connection (cl))
1052 int finished = 0;
1053 gpg_error_t rc;
1054 struct pollfd fds[2];
1056 fds[0].fd = thd->fd;
1057 fds[0].events = POLLIN;
1058 fds[1].fd = thd->status_msg_pipe[0];
1059 fds[1].events = POLLIN;
1061 send_status_all (STATUS_CLIENTS, NULL);
1062 rc = send_status (cl->ctx, STATUS_CACHE, NULL);
1063 if (rc)
1065 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
1066 finished = 1;
1069 while (!finished)
1071 int n;
1072 int eof;
1074 n = poll (fds, 2, -1);
1075 if (n == -1)
1077 log_write ("%s", strerror (errno));
1078 break;
1081 if (fds[1].revents & POLLIN)
1083 rc = send_msg_queue (thd);
1084 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1085 break;
1088 #ifdef HAVE_PTHREAD_CANCEL
1089 if (!(fds[0].revents & POLLIN))
1090 #else
1091 if (thd->fd != -1 && !(fds[0].revents & POLLIN))
1092 #endif
1093 continue;
1095 rc = assuan_process_next (cl->ctx, &eof);
1096 if (rc || eof)
1098 if (gpg_err_code (rc) == GPG_ERR_EOF || eof)
1099 break;
1101 log_write ("assuan_process_next(): rc=%i %s", rc,
1102 pwmd_strerror (rc));
1103 if (rc == gpg_error (GPG_ERR_ETIMEDOUT))
1104 break;
1106 rc = send_error (cl->ctx, rc);
1107 if (rc)
1109 log_write ("assuan_process_done(): rc=%i %s", rc,
1110 pwmd_strerror (rc));
1111 break;
1115 /* Since the msg queue pipe fd's are non-blocking, check for
1116 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1117 * client has already disconnected and will be converted to
1118 * GPG_ERR_EOF during assuan_process_next().
1120 rc = send_msg_queue (thd);
1121 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1122 break;
1126 /* Don't do pthread_exit() here because any set pthread_cleanup_push
1127 * functions would be called after a command failed but then the client
1128 * exited normally which may lead to a double free. */
1129 pthread_cleanup_pop (1);
1130 return NULL;
1133 static gpg_error_t
1134 xml_import (const char *filename, const char *outfile, char **keyid,
1135 char **sign_keyid, const char *keyfile, const char *keyparam,
1136 int symmetric)
1138 xmlDocPtr doc;
1139 int fd;
1140 struct stat st;
1141 int len;
1142 xmlChar *xmlbuf;
1143 gpg_error_t rc = 0;
1144 struct crypto_s *crypto = NULL;
1146 if (stat (filename, &st) == -1)
1148 rc = gpg_error_from_errno (errno);
1149 return rc;
1152 fd = open (filename, O_RDONLY);
1153 if (fd == -1)
1154 return gpg_error_from_errno (errno);
1156 xmlbuf = xmalloc (st.st_size + 1);
1157 if (!xmlbuf)
1159 close (fd);
1160 return GPG_ERR_ENOMEM;
1163 if (read (fd, xmlbuf, st.st_size) == -1)
1165 rc = gpg_error_from_errno (errno);
1166 close (fd);
1167 xfree (xmlbuf);
1168 return rc;
1171 close (fd);
1172 xmlbuf[st.st_size] = 0;
1173 // Be sure the document validates.
1174 doc = xmlReadDoc (xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS);
1175 xfree (xmlbuf);
1176 if (!doc)
1177 return GPG_ERR_BAD_DATA;
1179 xmlNodePtr n = xmlDocGetRootElement (doc);
1180 if (n && !xmlStrEqual (n->name, (xmlChar *) "pwmd"))
1181 rc = GPG_ERR_BAD_DATA;
1183 if (!rc)
1185 rc = xml_validate_import (NULL, n ? n->children : n);
1186 if (!rc)
1188 rc = crypto_init (&crypto, NULL, filename, keyfile != NULL);
1189 if (!rc)
1191 if (keyfile)
1193 crypto->flags |= CRYPTO_FLAG_KEYFILE;
1194 crypto->keyfile = str_dup (keyfile);
1197 xmlDocDumpMemory (doc, &crypto->plaintext, &len);
1198 if (len > 0)
1199 crypto->plaintext_size = len;
1200 else
1201 rc = GPG_ERR_ENOMEM;
1206 if (!rc)
1208 if (!symmetric && (keyparam || !keyid))
1210 char *buf = NULL;
1212 if (keyparam)
1214 fd = open (keyparam, O_RDONLY);
1215 if (fd == -1)
1216 rc = gpg_error_from_errno (errno);
1218 if (!rc)
1220 if (stat (keyparam, &st) == -1)
1221 rc = gpg_error_from_errno (errno);
1223 if (!rc)
1225 buf = xmalloc (st.st_size+1);
1226 if (!buf)
1227 rc = GPG_ERR_ENOMEM;
1229 if (!rc)
1231 len = read (fd, buf, st.st_size);
1232 if (len != st.st_size)
1233 rc = gpg_error_from_errno (errno);
1235 if (!rc)
1236 buf[len] = 0;
1241 if (fd != -1)
1242 close (fd);
1244 else
1246 buf = crypto_default_key_params ();
1247 if (!buf)
1248 rc = GPG_ERR_ENOMEM;
1251 if (!rc)
1252 rc = crypto_genkey (NULL, crypto, (unsigned char *)buf);
1254 xfree (buf);
1256 else
1258 crypto->save.pubkey = strv_dup (keyid);
1259 crypto->save.sigkey = strv_dup (sign_keyid);
1262 if (!rc)
1264 crypto->flags |= symmetric ? CRYPTO_FLAG_SYMMETRIC : 0;
1265 rc = crypto_encrypt (NULL, crypto);
1269 if (!rc)
1271 if (!strcmp (outfile, "-"))
1272 outfile = NULL;
1274 xfree (crypto->plaintext);
1275 crypto->plaintext = NULL;
1276 xfree (crypto->filename);
1277 crypto->filename = outfile ? str_dup (outfile) : NULL;
1278 rc = crypto_write_file (crypto);
1281 xmlFreeDoc (doc);
1282 crypto_free (crypto);
1283 return rc;
1286 static gpg_error_t
1287 do_cache_push (struct crypto_s *crypto)
1289 unsigned char md5file[16];
1290 gpg_error_t rc;
1291 xmlDocPtr doc;
1292 struct cache_data_s *cdata;
1293 unsigned char *crc;
1294 size_t len;
1295 int fd = -1;
1297 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1298 crypto->filename);
1300 if (valid_filename (crypto->filename) == 0)
1302 log_write (_("%s: Invalid characters in filename"), crypto->filename);
1303 return GPG_ERR_INV_VALUE;
1306 rc = lock_flock (NULL, crypto->filename, LOCK_SH, &fd);
1307 if (!rc)
1308 rc = crypto_decrypt (NULL, crypto);
1309 if (rc)
1311 unlock_flock (&fd);
1312 return rc;
1315 rc = xml_parse_doc ((char *) crypto->plaintext, crypto->plaintext_size, &doc);
1316 if (rc)
1318 unlock_flock (&fd);
1319 log_write ("%s", pwmd_strerror (rc));
1320 return rc;
1323 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, crypto->filename,
1324 strlen (crypto->filename));
1325 cdata = xcalloc (1, sizeof (struct cache_data_s));
1326 if (!cdata)
1328 unlock_flock (&fd);
1329 xmlFreeDoc (doc);
1330 return GPG_ERR_ENOMEM;
1333 rc = get_checksum (crypto->filename, &crc, &len);
1334 unlock_flock (&fd);
1335 if (rc)
1337 xmlFreeDoc (doc);
1338 free_cache_data_once (cdata);
1339 return rc;
1342 cdata->crc = crc;
1343 rc = cache_encrypt (crypto);
1344 if (!rc)
1346 cdata->doc = crypto->plaintext;
1347 cdata->size = crypto->plaintext_size;
1348 crypto->plaintext = NULL;
1349 cdata->pubkey = crypto->pubkey;
1350 cdata->sigkey = crypto->sigkey;
1351 crypto->pubkey = NULL;
1352 crypto->sigkey = NULL;
1354 else
1356 xmlFreeDoc (doc);
1357 free_cache_data_once (cdata);
1358 return rc;
1361 int timeout = config_get_integer (crypto->filename, "cache_timeout");
1362 rc = cache_add_file (md5file, cdata, timeout);
1363 return rc;
1366 static gpg_error_t
1367 init_client (int fd, const char *addr)
1369 gpg_error_t rc = 0;
1370 struct client_thread_s *new = xcalloc (1, sizeof (struct client_thread_s));
1372 if (!new)
1374 close (fd);
1375 return GPG_ERR_ENOMEM;
1378 MUTEX_LOCK (&cn_mutex);
1379 new->conntime = time (NULL);
1380 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
1382 if (pipe (new->status_msg_pipe) == -1)
1383 rc = gpg_error_from_errno (errno);
1385 if (!rc)
1387 if (fcntl (new->status_msg_pipe[0], F_SETFL, O_NONBLOCK) == -1)
1388 rc = gpg_error_from_errno (errno);
1390 if (!rc)
1391 if (fcntl (new->status_msg_pipe[1], F_SETFL, O_NONBLOCK) == -1)
1392 rc = gpg_error_from_errno (errno);
1394 pthread_mutex_init (&new->status_mutex, NULL);
1397 if (!rc)
1399 #ifdef WITH_GNUTLS
1400 new->remote = addr ? 1 : 0;
1401 #endif
1402 new->fd = fd;
1403 rc = create_thread (client_thread, new, &new->tid, 1);
1404 if (rc)
1406 close (new->status_msg_pipe[0]);
1407 close (new->status_msg_pipe[1]);
1408 pthread_mutex_destroy (&new->status_mutex);
1412 if (!rc)
1414 struct slist_s *list = slist_append (cn_thread_list, new);
1416 if (list)
1418 cn_thread_list = list;
1419 if (addr)
1421 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1422 (pthread_t *) new->tid, fd, addr);
1423 #ifdef WITH_GNUTLS
1424 new->peeraddr = str_dup (addr);
1425 #endif
1427 else
1428 log_write (_("new connection: tid=%p, fd=%i"),
1429 (pthread_t *) new->tid, fd);
1431 else
1432 rc = GPG_ERR_ENOMEM;
1435 pthread_cleanup_pop (1);
1437 if (rc)
1439 xfree (new);
1440 close (fd);
1441 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1442 pwmd_strerror (rc));
1444 return rc;
1447 static void*
1448 keepalive_thread (void *arg)
1450 #ifndef HAVE_PTHREAD_CANCEL
1451 int *n = xmalloc (sizeof (int));
1453 *n = 0;
1454 pthread_setspecific (signal_thread_key, n);
1455 INIT_THREAD_SIGNAL;
1456 #endif
1458 #ifdef HAVE_PR_SET_NAME
1459 prctl (PR_SET_NAME, "keepalive");
1460 #endif
1461 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
1463 for (;;)
1465 int n = config_get_integer ("global", "keepalive_interval");
1466 struct timeval tv = { n, 0 };
1467 #ifndef HAVE_PTHREAD_CANCEL
1468 int *sigusr2;
1470 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1471 if (*sigusr2)
1472 break;
1473 #endif
1475 send_status_all (STATUS_KEEPALIVE, NULL);
1476 select (0, NULL, NULL, NULL, &tv);
1479 return NULL;
1482 #ifdef WITH_GNUTLS
1483 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1484 static void *
1485 get_in_addr (struct sockaddr *sa)
1487 if (sa->sa_family == AF_INET)
1488 return &(((struct sockaddr_in *) sa)->sin_addr);
1490 return &(((struct sockaddr_in6 *) sa)->sin6_addr);
1493 static void *
1494 tcp_accept_thread (void *arg)
1496 int sockfd = *(int *) arg;
1497 time_t init;
1498 gpg_error_t rc;
1499 int regen_interval = config_get_integer ("global", "tls_regen_interval");
1500 char *tmp = config_get_string ("global", "tls_dh_level");
1501 #ifndef HAVE_PTHREAD_CANCEL
1502 int *n = xmalloc (sizeof (int));
1504 *n = 0;
1505 pthread_setspecific (signal_thread_key, n);
1506 INIT_THREAD_SIGNAL;
1507 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1508 #endif
1510 #ifdef HAVE_PR_SET_NAME
1511 prctl (PR_SET_NAME, "tcp_accept");
1512 #endif
1513 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
1514 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1516 rc = tls_init_params (tmp);
1517 xfree (tmp);
1518 if (rc)
1519 init = 0;
1520 else
1521 init = time (NULL);
1523 for (;;)
1525 struct sockaddr_storage raddr;
1526 socklen_t slen = sizeof (raddr);
1527 int fd;
1528 unsigned long n;
1529 char s[INET6_ADDRSTRLEN];
1530 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1531 #ifndef HAVE_PTHREAD_CANCEL
1532 int *sigusr2;
1534 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1535 if (*sigusr2)
1536 break;
1537 #endif
1539 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1540 if (init == 0 || fd == -1)
1542 if ((init == 0 && (errno == EAGAIN || errno == EWOULDBLOCK))
1543 || (errno == EAGAIN || errno == EWOULDBLOCK))
1545 if (regen_interval > 0
1546 && (init == 0 || time (NULL) - init >= regen_interval))
1548 int i;
1549 int remote_client = 0;
1551 MUTEX_LOCK(&cn_mutex);
1552 for (i = 0; i < slist_length (cn_thread_list); i++)
1554 struct client_thread_s *thd =
1555 slist_nth_data (cn_thread_list, i);
1557 if (thd->remote)
1559 remote_client = 1;
1560 break;
1563 MUTEX_UNLOCK(&cn_mutex);
1565 if (!remote_client)
1567 char *tmp = config_get_string ("global", "tls_dh_level");
1568 gpg_error_t rc;
1570 rc = tls_init_params (tmp);
1571 xfree (tmp);
1572 if (!rc)
1573 init = time (NULL);
1574 else
1576 tv.tv_sec = 10;
1577 tv.tv_usec = 0;
1579 if (fd != -1)
1581 close (fd);
1582 fd = -1;
1586 else
1587 init = 0;
1590 if (fd == -1)
1592 select (0, NULL, NULL, NULL, &tv);
1593 continue;
1597 if (errno == EMFILE || errno == ENFILE)
1598 log_write ("accept(): %s",
1599 pwmd_strerror (gpg_error_from_errno (errno)));
1600 else if (errno != EAGAIN)
1602 if (!quit) // probably EBADF
1603 log_write ("accept(): %s", strerror (errno));
1605 break;
1608 #ifndef HAVE_PTHREAD_CANCEL
1609 select (0, NULL, NULL, NULL, &tv);
1610 #endif
1611 continue;
1614 if (quit)
1616 close (fd);
1617 break;
1620 inet_ntop (raddr.ss_family, get_in_addr ((struct sockaddr *) &raddr),
1621 s, sizeof s);
1622 (void) init_client (fd, s);
1623 n = config_get_integer ("global", "tcp_wait");
1624 if (n > 0)
1626 tv.tv_sec = (n * 100000) / 100000;
1627 tv.tv_usec = (n * 100000) % 100000;
1628 select (0, NULL, NULL, NULL, &tv);
1632 return NULL;
1635 static int
1636 start_stop_tls_with_protocol (int ipv6, int term)
1638 struct addrinfo hints, *servinfo, *p;
1639 int port = config_get_integer ("global", "tcp_port");
1640 char buf[7];
1641 int n;
1642 gpg_error_t rc;
1643 int *fd = ipv6 ? &tls6_fd : &tls_fd;
1645 if (term || config_get_boolean ("global", "enable_tcp") == 0)
1647 if (tls6_fd != -1)
1649 if (spawned_tls6)
1651 #ifdef HAVE_PTHREAD_CANCEL
1652 pthread_cancel (tls6_tid);
1653 #else
1654 pthread_kill (tls6_tid, SIGUSR2);
1655 #endif
1656 pthread_join (tls6_tid, NULL);
1659 shutdown (tls6_fd, SHUT_RDWR);
1660 close (tls6_fd);
1661 tls6_fd = -1;
1662 spawned_tls6 = 0;
1665 if (tls_fd != -1)
1667 if (spawned_tls)
1669 #ifdef HAVE_PTHREAD_CANCEL
1670 pthread_cancel (tls_tid);
1671 #else
1672 pthread_kill (tls_tid, SIGUSR2);
1673 #endif
1674 pthread_join (tls_tid, NULL);
1677 shutdown (tls_fd, SHUT_RDWR);
1678 close (tls_fd);
1679 tls_fd = -1;
1680 spawned_tls = 0;
1683 return 1;
1686 if ((ipv6 && tls6_fd != -1) || (!ipv6 && tls_fd != -1))
1687 return 1;
1689 memset (&hints, 0, sizeof (hints));
1690 hints.ai_family = ipv6 ? AF_INET6 : AF_INET;
1691 hints.ai_socktype = SOCK_STREAM;
1692 hints.ai_flags = AI_PASSIVE;
1693 snprintf (buf, sizeof (buf), "%i", port);
1695 if ((n = getaddrinfo (NULL, buf, &hints, &servinfo)) == -1)
1697 log_write ("getaddrinfo(): %s", gai_strerror (n));
1698 return 0;
1701 for (n = 0, p = servinfo; p != NULL; p = p->ai_next)
1703 int r = 1;
1705 if ((ipv6 && p->ai_family != AF_INET6)
1706 || (!ipv6 && p->ai_family != AF_INET))
1707 continue;
1709 if ((*fd = socket (p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
1711 log_write ("socket(): %s", strerror (errno));
1712 continue;
1715 if (setsockopt (*fd, SOL_SOCKET, SO_REUSEADDR, &r, sizeof (int)) == -1)
1717 log_write ("setsockopt(): %s",
1718 pwmd_strerror (gpg_error_from_errno (errno)));
1719 freeaddrinfo (servinfo);
1720 goto fail;
1723 if (bind (*fd, p->ai_addr, p->ai_addrlen) == -1)
1725 close (*fd);
1726 log_write ("bind(): %s",
1727 pwmd_strerror (gpg_error_from_errno (errno)));
1728 continue;
1731 n++;
1732 break;
1735 freeaddrinfo (servinfo);
1737 if (!n)
1738 goto fail;
1740 #if HAVE_DECL_SO_BINDTODEVICE != 0
1741 char *tmp = config_get_string ("global", "tcp_interface");
1742 if (tmp && setsockopt (*fd, SOL_SOCKET, SO_BINDTODEVICE, tmp,
1743 strlen (tmp)) == -1)
1745 log_write ("setsockopt(): %s",
1746 pwmd_strerror (gpg_error_from_errno (errno)));
1747 xfree (tmp);
1748 goto fail;
1751 xfree (tmp);
1752 #endif
1754 if (listen (*fd, 128) == -1)
1756 log_write ("listen(): %s", strerror (errno));
1757 goto fail;
1760 if (ipv6)
1761 rc = create_thread (tcp_accept_thread, fd, &tls6_tid, 0);
1762 else
1763 rc = create_thread (tcp_accept_thread, fd, &tls_tid, 0);
1765 if (rc)
1767 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1768 pwmd_strerror (rc));
1769 goto fail;
1772 if (ipv6)
1773 spawned_tls6 = 1;
1774 else
1775 spawned_tls = 1;
1777 return 1;
1779 fail:
1780 start_stop_tls_with_protocol (0, 1);
1781 if (tls_fd != -1)
1782 close (tls_fd);
1784 if (tls6_fd != -1)
1785 close (tls6_fd);
1787 tls_fd = -1;
1788 tls6_fd = -1;
1789 return 0;
1792 static int
1793 start_stop_tls (int term)
1795 char *s = config_get_string ("global", "tcp_bind");
1796 int b;
1798 if (!s)
1799 return 0;
1801 if (!strcmp (s, "any"))
1803 b = start_stop_tls_with_protocol (0, term);
1804 if (b)
1805 b = start_stop_tls_with_protocol (1, term);
1807 else if (!strcmp (s, "ipv4"))
1808 b = start_stop_tls_with_protocol (0, term);
1809 else if (!strcmp (s, "ipv6"))
1810 b = start_stop_tls_with_protocol (1, term);
1811 else
1812 b = 0;
1814 xfree (s);
1815 return b;
1817 #endif
1819 static void *
1820 accept_thread (void *arg)
1822 int sockfd = *(int *) arg;
1823 #ifndef HAVE_PTHREAD_CANCEL
1824 int *n = xmalloc (sizeof (int));
1826 *n = 0;
1827 pthread_setspecific (signal_thread_key, n);
1828 INIT_THREAD_SIGNAL;
1829 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1830 #endif
1832 #ifdef HAVE_PR_SET_NAME
1833 prctl (PR_SET_NAME, "accept");
1834 #endif
1835 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
1837 for (;;)
1839 socklen_t slen = sizeof (struct sockaddr_un);
1840 struct sockaddr_un raddr;
1841 int fd;
1842 #ifndef HAVE_PTHREAD_CANCEL
1843 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1844 int *sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1846 if (*sigusr2)
1847 break;
1848 #endif
1850 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1851 if (fd == -1)
1853 if (errno == EMFILE || errno == ENFILE)
1854 log_write ("accept(): %s",
1855 pwmd_strerror (gpg_error_from_errno (errno)));
1856 else if (errno != EAGAIN)
1858 if (!quit) // probably EBADF
1859 log_write ("accept(): %s",
1860 pwmd_strerror (gpg_error_from_errno (errno)));
1862 break;
1865 #ifndef HAVE_PTHREAD_CANCEL
1866 select (0, NULL, NULL, NULL, &tv);
1867 #endif
1868 continue;
1871 (void) init_client (fd, NULL);
1874 /* Just in case accept() failed for some reason other than EBADF */
1875 quit = 1;
1876 return NULL;
1879 static void *
1880 cache_timer_thread (void *arg)
1882 #ifndef HAVE_PTHREAD_CANCEL
1883 int *n = xmalloc (sizeof (int));
1885 *n = 0;
1886 pthread_setspecific (signal_thread_key, n);
1887 INIT_THREAD_SIGNAL;
1888 #endif
1890 #ifdef HAVE_PR_SET_NAME
1891 prctl (PR_SET_NAME, "cache timer");
1892 #endif
1893 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
1895 for (;;)
1897 struct timeval tv = { 1, 0 };
1898 #ifndef HAVE_PTHREAD_CANCEL
1899 int *n;
1901 n = (int *) pthread_getspecific (signal_thread_key);
1902 if (*n)
1903 break;
1904 #endif
1906 select (0, NULL, NULL, NULL, &tv);
1907 cache_adjust_timeout ();
1910 return NULL;
1913 static int
1914 signal_loop (sigset_t sigset)
1916 int done = 0;
1917 int siint = 0;
1921 int sig;
1923 sigwait (&sigset, &sig);
1925 if (sig != SIGQUIT)
1926 log_write (_("caught signal %i (%s)"), sig, strsignal (sig));
1928 switch (sig)
1930 case SIGHUP:
1931 pthread_cond_signal (&rcfile_cond);
1932 break;
1933 case SIGUSR1:
1934 log_write (_("clearing file cache"));
1935 cache_clear (NULL, 1);
1936 send_status_all (STATUS_CACHE, NULL);
1937 break;
1938 case SIGQUIT:
1939 done = 1;
1940 break;
1941 default:
1942 siint = 1;
1943 done = 1;
1944 break;
1947 while (!done);
1949 return siint;
1952 static void
1953 catchsig (int sig)
1955 log_write (_ ("Caught signal %i (%s). Exiting."), sig, strsignal (sig));
1956 #ifdef HAVE_BACKTRACE
1957 BACKTRACE (__FUNCTION__);
1958 #endif
1959 longjmp (jmp, 1);
1962 static void *
1963 waiting_for_exit (void *arg)
1965 int last = 0;
1966 #ifndef HAVE_PTHREAD_CANCEL
1967 int *n = xmalloc (sizeof (int));
1969 *n = 0;
1970 pthread_setspecific (signal_thread_key, n);
1971 INIT_THREAD_SIGNAL;
1972 #endif
1974 #ifdef HAVE_PR_SET_NAME
1975 prctl (PR_SET_NAME, "exiting");
1976 #endif
1977 pthread_setspecific (thread_name_key, str_asprintf ("!%s", __FUNCTION__));
1978 log_write (_("waiting for all clients to disconnect"));
1979 MUTEX_LOCK (&quit_mutex);
1980 pthread_cleanup_push (cleanup_mutex_cb, &quit_mutex);
1982 for (;;)
1984 struct timespec ts;
1985 int n;
1987 MUTEX_LOCK (&cn_mutex);
1988 n = slist_length (cn_thread_list);
1989 MUTEX_UNLOCK (&cn_mutex);
1990 if (!n)
1991 break;
1993 #ifndef HAVE_PTHREAD_CANCEL
1994 int *s = (int *) pthread_getspecific (signal_thread_key);
1995 if (*s)
1996 break;
1997 #endif
1999 if (last != n)
2001 log_write (_("%i clients remain"), n);
2002 last = n;
2005 INIT_TIMESPEC (SIG_TIMEOUT, ts);
2006 pthread_cond_timedwait (&quit_cond, &quit_mutex, &ts);
2009 kill (getpid (), SIGQUIT);
2010 pthread_cleanup_pop (1);
2011 return NULL;
2014 static int
2015 server_loop (int sockfd, char **socketpath)
2017 pthread_t accept_tid;
2018 pthread_t cache_timeout_tid;
2019 int cancel_timeout_thread = 0, cancel_accept_thread = 0;
2020 int cancel_keepalive_thread = 0;
2021 sigset_t sigset;
2022 int n;
2023 int segv = 0;
2024 gpg_error_t rc;
2026 init_commands ();
2027 sigemptyset (&sigset);
2029 /* Termination */
2030 sigaddset (&sigset, SIGTERM);
2031 sigaddset (&sigset, SIGINT);
2033 /* Clears the file cache. */
2034 sigaddset (&sigset, SIGUSR1);
2036 /* Configuration file reloading. */
2037 sigaddset (&sigset, SIGHUP);
2039 /* For exiting cleanly. */
2040 sigaddset (&sigset, SIGQUIT);
2042 #ifndef HAVE_PTHREAD_CANCEL
2044 The socket, cache and rcfile threads use this signal when
2045 pthread_cancel() is unavailable. Prevent the main thread from
2046 catching this signal from another process.
2048 sigaddset (&sigset, SIGUSR2);
2049 #endif
2051 /* When mem.c cannot find a pointer in the list (double free). */
2052 signal (SIGABRT, catchsig);
2053 sigaddset (&sigset, SIGABRT);
2054 sigprocmask (SIG_BLOCK, &sigset, NULL);
2056 #ifndef HAVE_PTHREAD_CANCEL
2057 /* Remove this signal from the watched signals in signal_loop(). */
2058 sigdelset (&sigset, SIGUSR2);
2059 #endif
2061 /* Can show a backtrace of the stack in the log. */
2062 signal (SIGSEGV, catchsig);
2064 #ifdef WITH_GNUTLS
2065 /* Needs to be done after the fork(). */
2066 if (!start_stop_tls (0))
2068 segv = 1;
2069 goto done;
2071 #endif
2073 pthread_mutex_init (&quit_mutex, NULL);
2074 pthread_cond_init (&quit_cond, NULL);
2075 char *p = get_username (getuid());
2076 log_write (_("%s started for user %s"), PACKAGE_STRING, p);
2077 xfree (p);
2079 #ifdef WITH_GNUTLS
2080 if (config_get_boolean ("global", "enable_tcp"))
2081 log_write (_("Listening on %s and TCP port %i"), *socketpath,
2082 config_get_integer ("global", "tcp_port"));
2083 else
2084 log_write (_("Listening on %s"), *socketpath);
2085 #else
2086 log_write (_("Listening on %s"), *socketpath);
2087 #endif
2089 rc = create_thread (keepalive_thread, NULL, &keepalive_tid, 0);
2090 if (rc)
2092 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2093 pwmd_strerror (rc));
2094 goto done;
2097 cancel_keepalive_thread = 1;
2098 rc = create_thread (reload_rcfile_thread, NULL, &rcfile_tid, 0);
2099 if (rc)
2101 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2102 pwmd_strerror (rc));
2103 goto done;
2106 rc = create_thread (cache_timer_thread, NULL, &cache_timeout_tid, 0);
2107 if (rc)
2109 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2110 pwmd_strerror (rc));
2111 goto done;
2114 cancel_timeout_thread = 1;
2115 rc = create_thread (accept_thread, &sockfd, &accept_tid, 0);
2116 if (rc)
2118 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2119 pwmd_strerror (rc));
2120 goto done;
2123 cancel_accept_thread = 1;
2124 if (!setjmp (jmp))
2125 signal_loop (sigset);
2126 else
2127 segv = 1;
2129 done:
2131 * We're out of the main server loop. This happens when a signal was sent
2132 * to terminate the daemon. We'll wait for all clients to disconnect
2133 * before exiting but exit immediately if another termination signal is
2134 * sent.
2136 if (cancel_accept_thread)
2138 #ifdef HAVE_PTHREAD_CANCEL
2139 int n = pthread_cancel (accept_tid);
2140 #else
2141 int n = pthread_kill (accept_tid, SIGUSR2);
2142 #endif
2143 if (!n)
2144 pthread_join (accept_tid, NULL);
2147 #ifdef WITH_GNUTLS
2148 start_stop_tls (1);
2149 #endif
2150 shutdown (sockfd, SHUT_RDWR);
2151 close (sockfd);
2152 unlink (*socketpath);
2153 xfree (*socketpath);
2154 *socketpath = NULL;
2155 MUTEX_LOCK (&cn_mutex);
2156 n = slist_length (cn_thread_list);
2157 MUTEX_UNLOCK (&cn_mutex);
2159 if (n && !segv)
2161 pthread_t tid;
2163 rc = create_thread (waiting_for_exit, NULL, &tid, 0);
2164 if (!rc)
2166 if (signal_loop (sigset))
2168 log_write (_("Received second termination request. Exiting."));
2169 #ifdef HAVE_PTHREAD_CANCEL
2170 pthread_cancel (tid);
2171 #else
2172 pthread_kill (tid, SIGUSR2);
2173 #endif
2174 pthread_join (tid, NULL);
2177 else
2178 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2179 pwmd_strerror (rc));
2182 if (cancel_timeout_thread)
2184 #ifdef HAVE_PTHREAD_CANCEL
2185 pthread_cancel (cache_timeout_tid);
2186 #else
2187 pthread_kill (cache_timeout_tid, SIGUSR2);
2188 #endif
2189 pthread_join (cache_timeout_tid, NULL);
2192 if (cancel_keepalive_thread)
2194 #ifdef HAVE_PTHREAD_CANCEL
2195 pthread_cancel (keepalive_tid);
2196 #else
2197 pthread_kill (keepalive_tid, SIGUSR2);
2198 #endif
2199 pthread_join (keepalive_tid, NULL);
2202 cleanup_all_clients (0);
2203 #ifdef WITH_GNUTLS
2204 start_stop_tls (1);
2205 #endif
2206 deinit_commands ();
2207 pthread_cond_destroy (&quit_cond);
2208 pthread_mutex_destroy (&quit_mutex);
2209 return segv ? EXIT_FAILURE : EXIT_SUCCESS;;
2212 static void
2213 startup_failure ()
2215 log_write (_
2216 ("Failed to add a file to the cache. Use --force to force startup. Exiting."));
2217 cache_clear (NULL, 1);
2220 /* This is called from cache.c:clear_once(). See
2221 * command.c:clearcache_command() for details about lock checking.
2223 static gpg_error_t
2224 free_cache_data (file_cache_t * cache)
2226 gpg_error_t rc = GPG_ERR_NO_DATA;
2227 int i, t;
2228 struct client_thread_s *found = NULL;
2229 int self = 0;
2231 if (!cache->data)
2232 return 0;
2234 cache_lock ();
2235 MUTEX_LOCK (&cn_mutex);
2236 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
2237 t = slist_length (cn_thread_list);
2239 for (i = 0; i < t; i++)
2241 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2243 if (!thd->cl)
2244 continue;
2246 if (!memcmp (thd->cl->md5file, cache->filename,
2247 sizeof (cache->filename)))
2249 if (pthread_equal (pthread_self (), thd->tid))
2251 found = thd;
2252 self = 1;
2253 continue;
2256 /* Continue trying to find a client who has the same file open and
2257 * also has a lock. */
2258 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0, -1);
2259 if (!rc)
2261 self = 0;
2262 found = thd;
2263 break;
2268 if (self && (!rc || rc == GPG_ERR_NO_DATA))
2269 rc = cache_lock_mutex (found->cl->ctx, found->cl->md5file, -1, 0, -1);
2271 if (exiting || !rc || rc == GPG_ERR_NO_DATA)
2273 free_cache_data_once (cache->data);
2274 cache->data = NULL;
2275 cache->defer_clear = 0;
2276 cache->timeout = -1;
2278 if (found)
2279 cache_unlock_mutex (found->cl->md5file, 0);
2281 rc = 0;
2284 if (rc)
2285 cache->defer_clear = 1;
2287 pthread_cleanup_pop (1);
2288 cache_unlock ();
2289 return rc;
2292 static void
2293 usage (const char *pn, int status)
2295 FILE *fp = status == EXIT_FAILURE ? stderr : stdout;
2297 fprintf (fp, _("Usage: %s [OPTIONS] [file1] [...]\n"
2298 " --debug=[a:..][,g:N][,t:N] enable debugging (a:[ixedsc],g:[1-9],t:[0-N])\n"
2299 " -f, --rcfile=filename load the specfied configuration file\n"
2300 " (~/.pwmd/config)\n"
2301 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2302 " --kill terminate an existing instance of pwmd\n"
2303 " -n, --no-fork run as a foreground process\n"
2304 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2305 " --ignore, --force ignore file errors during startup\n"
2306 " -o, --outfile=filename output file when importing or converting\n"
2307 " -C, --convert=filename convert a version 2 data file to version 3\n"
2308 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2309 " -k, --passphrase-file=file for use when importing or converting\n"
2310 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2311 " converting\n"
2312 " --no-passphrase when importing or converting\n"
2313 " --keyid=keyID[,..] public key to use when encrypting\n"
2314 " --sign-keyid=fpr[,..] fingerprint of the signing key to use\n"
2315 " --symmetric use conventional encryption with optional signer\n"
2316 " --keyparam=filename custom key parameters to use (gpg default)\n"
2317 " --help this help text\n"
2318 " --version show version and compile time features\n"),
2319 pn);
2320 exit (status);
2323 static void
2324 unlink_stale_socket (const char *sock, const char *pidfile)
2326 log_write (_ ("removing stale socket %s"), sock);
2327 unlink (sock);
2328 unlink (pidfile);
2331 static int
2332 test_pidfile (const char *path, const char *sock, char *buf, size_t buflen,
2333 char **pidfile, int create, mode_t mode, int terminate)
2335 pid_t pid;
2336 int fd;
2337 size_t len;
2339 if (!create)
2341 snprintf (buf, buflen, "%s/%s.pid", homedir, sock);
2342 *pidfile = str_dup (buf);
2343 fd = open (buf, O_RDONLY);
2345 else
2346 fd = open (*pidfile, O_CREAT|O_WRONLY|O_TRUNC, mode);
2348 if (fd == -1)
2350 if (!create && errno != ENOENT)
2352 log_write ("%s: %s", buf, pwmd_strerror (errno));
2353 free (*pidfile);
2354 *pidfile = NULL;
2355 return -1;
2357 else if (!create && !terminate)
2358 return 0;
2360 log_write ("%s: %s", *pidfile, strerror (errno));
2361 return -1;
2364 if (create)
2366 snprintf (buf, buflen, "%i", getpid ());
2367 ssize_t ret = write (fd, buf, strlen (buf));
2368 if (ret == -1)
2369 log_write ("%s (%i): %s", __FUNCTION__, __LINE__,
2370 pwmd_strerror (gpg_error_from_syserror ()));
2371 close (fd);
2372 return 0;
2375 len = read (fd, buf, buflen);
2376 close (fd);
2377 if (len == 0)
2379 unlink_stale_socket (path, *pidfile);
2380 return 0;
2383 if (sscanf (buf, "%5i", &pid) != 1 || pid == 0)
2385 if (!terminate)
2387 unlink_stale_socket (path, *pidfile);
2388 return 0;
2392 if (kill (pid, 0) == -1)
2394 unlink_stale_socket (path, *pidfile);
2395 return 0;
2398 if (terminate)
2400 if (kill (pid, SIGTERM) == -1)
2401 log_write ("%s: %s", path, pwmd_strerror (errno));
2403 else
2404 log_write (_ ("an instance for socket %s is already running"), path);
2406 xfree (*pidfile);
2407 *pidfile = NULL;
2408 return 1;
2411 static unsigned
2412 parse_debug_level (const char *str, unsigned *debug, int *gpgme, int *tls)
2414 const char *p;
2415 unsigned level = 0;
2416 int gl = 0, tl = 0;
2418 for (p = str; p && *p; p++)
2420 if (*p == 'a') // assuan debug flags
2422 if (*++p != ':')
2423 return 1;
2425 while (*++p)
2427 switch (*p)
2429 case 'i':
2430 level |= ASSUAN_LOG_INIT;
2431 break;
2432 case 'x':
2433 level |= ASSUAN_LOG_CTX;
2434 break;
2435 case 'e':
2436 level |= ASSUAN_LOG_ENGINE;
2437 break;
2438 case 'd':
2439 level |= ASSUAN_LOG_DATA;
2440 break;
2441 case 's':
2442 level |= ASSUAN_LOG_SYSIO;
2443 break;
2444 case 'c':
2445 level |= ASSUAN_LOG_CONTROL;
2446 break;
2447 case ',':
2448 break;
2449 default:
2450 return 1;
2453 if (*p == ',')
2454 break;
2457 if (!*p)
2458 break;
2460 else if (*p == 'g' || *p == 't') // gpgme and TLS debug level
2462 int t = *p == 't';
2463 int n;
2465 if (*++p != ':')
2466 return 1;
2468 if (!isdigit (*++p))
2469 return 1;
2471 n = atoi (p);
2472 if (t)
2473 tl = n;
2474 else
2475 gl = n;
2477 if (tl < 0 || gl < 0 || gl > 9)
2478 return 1;
2480 while (isdigit (*p))
2481 p++;
2483 p--;
2484 if (*(p+1) && *(p+1) != ',')
2485 return 1;
2486 else if (*(p+1))
2487 p++;
2489 else
2490 return 1;
2493 if (tl)
2494 *tls = tl;
2496 if (gl)
2497 *gpgme = gl;
2499 *debug = level;
2500 return 0;
2504 main (int argc, char *argv[])
2506 int opt;
2507 struct sockaddr_un addr;
2508 char buf[PATH_MAX];
2509 char *socketpath = NULL, *socketdir, *socketname = NULL;
2510 char *socketarg = NULL;
2511 char *datadir = NULL;
2512 char *pidfile = NULL;
2513 mode_t mode = 0600;
2514 int x;
2515 char *p;
2516 char **cache_push = NULL;
2517 char *import = NULL, *keyid = NULL, *sign_keyid = NULL;
2518 char *keyparam = NULL;
2519 int estatus = EXIT_FAILURE;
2520 int sockfd;
2521 char *outfile = NULL;
2522 int do_unlink = 0;
2523 int secure = 0;
2524 int show_version = 0;
2525 int force = 0;
2526 gpg_error_t rc;
2527 gpgme_error_t grc;
2528 char *keyfile = NULL;
2529 int exists;
2530 int optindex;
2531 int terminate = 0;
2532 int sym = 0;
2533 int gpgme_level = -1;
2534 int tls_level = -1;
2535 /* Must maintain the same order as longopts[] */
2536 enum
2538 OPT_VERSION, OPT_HELP, OPT_HOMEDIR, OPT_NO_FORK, OPT_DISABLE_DUMP,
2539 OPT_FORCE, OPT_RCFILE, OPT_PASSPHRASE_FILE, OPT_IMPORT, OPT_OUTFILE,
2540 OPT_KEYID, OPT_SIGN_KEYID, OPT_SYMMETRIC, OPT_KEYPARAM, OPT_KILL,
2541 OPT_DEBUG
2543 const char *optstring = "nf:C:k:I:o:s";
2544 const struct option longopts[] = {
2545 {"version", no_argument, 0, 0},
2546 {"help", no_argument, 0, 0},
2547 {"homedir", required_argument, 0, 0},
2548 {"no-fork", no_argument, 0, 'n'},
2549 {"disable_dump", no_argument, 0, 0},
2550 {"force", no_argument, 0, 0},
2551 {"rcfile", required_argument, 0, 'f'},
2552 {"passphrase-file", required_argument, 0, 'k'},
2553 {"import", required_argument, 0, 'I'},
2554 {"outfile", required_argument, 0, 'o'},
2555 {"keyid", required_argument, 0, 0},
2556 {"sign-keyid", required_argument, 0, 0},
2557 {"symmetric", no_argument, 0, 's'},
2558 {"keyparam", required_argument, 0, 0},
2559 {"kill", no_argument, 0, 0},
2560 {"debug", required_argument, 0, 0},
2561 {0, 0, 0, 0}
2564 log_fd = -1;
2565 cmdline = 1;
2567 #ifndef DEBUG
2568 #ifdef HAVE_SETRLIMIT
2569 struct rlimit rl;
2571 rl.rlim_cur = rl.rlim_max = 0;
2573 if (setrlimit (RLIMIT_CORE, &rl) != 0)
2574 err (EXIT_FAILURE, "setrlimit()");
2575 #endif
2577 #ifdef HAVE_PR_SET_DUMPABLE
2578 prctl (PR_SET_DUMPABLE, 0);
2579 #endif
2580 #endif
2582 #ifdef ENABLE_NLS
2583 setlocale (LC_ALL, "");
2584 bindtextdomain ("pwmd", LOCALEDIR);
2585 textdomain ("pwmd");
2586 #endif
2588 #ifndef MEM_DEBUG
2589 xmem_init ();
2590 #endif
2591 gpg_err_init ();
2593 if (setup_crypto ())
2594 exit (EXIT_FAILURE);
2596 #ifdef WITH_GNUTLS
2597 gnutls_global_init ();
2598 tls_level = tls_level == -1 ? 1 : tls_level;
2599 gnutls_global_set_log_level (tls_level);
2600 gnutls_global_set_log_function (tls_log);
2601 gnutls_global_set_audit_log_function (tls_audit_log);
2602 tls_fd = -1;
2603 tls6_fd = -1;
2604 #endif
2605 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
2606 xmlInitMemory ();
2607 xmlInitGlobals ();
2608 xmlInitParser ();
2609 xmlXPathInit ();
2611 while ((opt = getopt_long (argc, argv, optstring, longopts, &optindex))
2612 != -1)
2614 switch (opt)
2616 case 'I':
2617 import = optarg;
2618 break;
2619 case 'k':
2620 keyfile = optarg;
2621 break;
2622 case 'o':
2623 outfile = optarg;
2624 break;
2625 case 'D':
2626 secure = 1;
2627 break;
2628 case 'n':
2629 nofork = 1;
2630 break;
2631 case 'f':
2632 rcfile = str_dup (optarg);
2633 break;
2634 case 's':
2635 sym = 1;
2636 break;
2637 default:
2638 usage (argv[0], EXIT_FAILURE);
2639 break;
2640 case 0:
2641 switch (optindex)
2643 case OPT_DEBUG:
2644 if (parse_debug_level (optarg, &assuan_level, &gpgme_level,
2645 &tls_level))
2646 usage (argv[0], EXIT_FAILURE);
2647 break;
2648 case OPT_SYMMETRIC:
2649 sym = 1;
2650 break;
2651 case OPT_VERSION:
2652 show_version = 1;
2653 break;
2654 case OPT_HELP:
2655 usage (argv[0], EXIT_SUCCESS);
2656 break;
2657 case OPT_HOMEDIR:
2658 homedir = str_dup (optarg);
2659 break;
2660 case OPT_NO_FORK:
2661 nofork = 1;
2662 break;
2663 case OPT_DISABLE_DUMP:
2664 secure = 1;
2665 break;
2666 case OPT_FORCE:
2667 force = 1;
2668 break;
2669 case OPT_RCFILE:
2670 rcfile = str_dup (optarg);
2671 break;
2672 case OPT_PASSPHRASE_FILE:
2673 keyfile = optarg;
2674 break;
2675 case OPT_IMPORT:
2676 import = optarg;
2677 break;
2678 case OPT_OUTFILE:
2679 outfile = optarg;
2680 break;
2681 case OPT_KEYID:
2682 keyid = optarg;
2683 break;
2684 case OPT_SIGN_KEYID:
2685 sign_keyid = optarg;
2686 break;
2687 case OPT_KEYPARAM:
2688 keyparam = optarg;
2689 break;
2690 case OPT_KILL:
2691 terminate = 1;
2692 break;
2693 default:
2694 usage (argv[0], EXIT_FAILURE);
2699 if (show_version)
2701 printf (_("%s\n\n"
2702 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016\n"
2703 "%s\n"
2704 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2705 "Compile time features:\n%s"), PACKAGE_STRING,
2706 PACKAGE_BUGREPORT,
2707 #ifdef PWMD_HOMEDIR
2708 "+PWMD_HOMEDIR=" PWMD_HOMEDIR "\n"
2709 #endif
2710 #ifdef WITH_GNUTLS
2711 "+WITH_GNUTLS\n"
2712 #else
2713 "-WITH_GNUTLS\n"
2714 #endif
2715 #ifdef WITH_LIBACL
2716 "+WITH_LIBACL\n"
2717 #else
2718 "-WITH_LIBACL\n"
2719 #endif
2720 #ifdef DEBUG
2721 "+DEBUG\n"
2722 #else
2723 "-DEBUG\n"
2724 #endif
2725 #ifdef MEM_DEBUG
2726 "+MEM_DEBUG\n"
2727 #else
2728 "-MEM_DEBUG\n"
2729 #endif
2730 #ifdef MUTEX_DEBUG
2731 "+MUTEX_DEBUG\n"
2732 #else
2733 "-MUTEX_DEBUG\n"
2734 #endif
2736 exit (EXIT_SUCCESS);
2739 if (!homedir)
2740 #ifdef PWMD_HOMEDIR
2741 homedir = str_dup(PWMD_HOMEDIR);
2742 #else
2743 homedir = str_asprintf ("%s/.pwmd", get_home_dir());
2744 #endif
2746 if (mkdir (homedir, 0700) == -1 && errno != EEXIST)
2747 err (EXIT_FAILURE, "%s", homedir);
2749 if (!rcfile)
2750 rcfile = str_asprintf ("%s/config", homedir);
2752 pthread_key_create (&last_error_key, free_key);
2753 #ifndef HAVE_PTHREAD_CANCEL
2754 pthread_key_create (&signal_thread_key, free_key);
2755 #endif
2757 pthread_mutexattr_t attr;
2758 pthread_mutexattr_init (&attr);
2759 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
2760 pthread_mutex_init (&rcfile_mutex, &attr);
2761 global_config = config_parse (rcfile, 0);
2762 if (!global_config)
2764 pthread_mutexattr_destroy (&attr);
2765 pthread_mutex_destroy (&rcfile_mutex);
2766 exit (EXIT_FAILURE);
2769 p = config_get_string ("global", "gpg_homedir");
2770 if (!p)
2771 datadir = str_asprintf ("%s/.gnupg", homedir);
2772 else
2773 datadir = expand_homedir (p);
2775 xfree (p);
2776 if (mkdir (datadir, 0700) == -1 && errno != EEXIST)
2777 err (EXIT_FAILURE, "%s", datadir);
2779 if (gpgme_level != -1)
2781 char s[2] = { gpgme_level + '0', 0 };
2783 if (getenv ("GPGME_DEBUG"))
2784 log_write (_ ("Overriding GPGME_DEBUG environment with level %u!"),
2785 gpgme_level);
2787 gpgme_set_global_flag ("debug", s);
2790 if (!gpgme_check_version (NULL))
2792 log_write ("gpgme_check_version() failed");
2793 exit (EXIT_FAILURE);
2796 grc = gpgme_engine_check_version (GPGME_PROTOCOL_OPENPGP);
2797 if (grc)
2799 log_write ("%u: %s", grc, gpgme_strerror (grc));
2800 exit (EXIT_FAILURE);
2803 #ifdef ENABLE_NLS
2804 gpgme_set_locale (NULL, LC_CTYPE, setlocale (LC_CTYPE, NULL));
2805 gpgme_set_locale (NULL, LC_MESSAGES, setlocale (LC_MESSAGES, NULL));
2806 #endif
2807 rc = gpgme_set_engine_info (GPGME_PROTOCOL_OpenPGP, NULL, datadir);
2808 xfree (datadir);
2810 snprintf (buf, sizeof (buf), "%s/data", homedir);
2811 if (mkdir (buf, 0700) == -1 && errno != EEXIST)
2812 err (EXIT_FAILURE, "%s", buf);
2814 datadir = str_dup (buf);
2815 pthread_cond_init (&rcfile_cond, NULL);
2816 pthread_mutex_init (&cn_mutex, &attr);
2817 pthread_mutexattr_destroy (&attr);
2819 setup_logging ();
2821 x = config_get_int_param (global_config, "global", "priority", &exists);
2822 if (exists && x != atoi(INVALID_PRIORITY))
2824 errno = 0;
2825 if (setpriority (PRIO_PROCESS, 0, x) == -1)
2827 log_write ("setpriority(): %s",
2828 pwmd_strerror (gpg_error_from_errno (errno)));
2829 goto do_exit;
2832 #ifdef HAVE_MLOCKALL
2833 if (disable_mlock == 0 && mlockall (MCL_CURRENT | MCL_FUTURE) == -1)
2835 log_write ("mlockall(): %s",
2836 pwmd_strerror (gpg_error_from_errno (errno)));
2837 goto do_exit;
2839 #endif
2841 rc = cache_init (free_cache_data);
2842 if (rc)
2844 log_write ("pwmd: ERR %i: %s", rc, pwmd_strerror (rc));
2845 exit (EXIT_FAILURE);
2848 if (import)
2850 char **keyids = NULL, **sign_keyids = NULL;
2852 if (!outfile || !*outfile || argc != optind)
2853 usage (argv[0], EXIT_FAILURE);
2855 if (keyid)
2856 keyids = str_split (keyid, ",", 0);
2857 if (sign_keyid)
2858 sign_keyids = str_split (sign_keyid, ",", 0);
2859 rc = xml_import (import, outfile, keyids, sign_keyids, keyfile, keyparam, sym);
2860 strv_free (keyids);
2861 strv_free (sign_keyids);
2862 if (rc)
2864 if (gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
2865 rc = gpg_error (rc);
2867 log_write ("%s: %u: %s", import, rc, pwmd_strerror (rc));
2870 config_free (global_config);
2871 xfree (rcfile);
2872 exit (rc ? EXIT_FAILURE : EXIT_SUCCESS);
2875 p = config_get_string ("global", "socket_path");
2876 if (!p)
2877 p = str_asprintf ("%s/socket", homedir);
2879 socketarg = expand_homedir (p);
2880 xfree (p);
2882 if (!secure)
2883 disable_list_and_dump = config_get_boolean ("global",
2884 "disable_list_and_dump");
2885 else
2886 disable_list_and_dump = secure;
2888 cache_push = config_get_list ("global", "cache_push");
2890 while (optind < argc)
2892 if (strv_printf (&cache_push, "%s", argv[optind++]) == 0)
2893 errx (EXIT_FAILURE, "%s", pwmd_strerror (GPG_ERR_ENOMEM));
2896 if (strchr (socketarg, '/') == NULL)
2898 socketdir = getcwd (buf, sizeof (buf));
2899 socketname = str_dup (socketarg);
2900 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2902 else
2904 socketname = str_dup (strrchr (socketarg, '/'));
2905 socketname++;
2906 socketarg[strlen (socketarg) - strlen (socketname) - 1] = 0;
2907 socketdir = str_dup (socketarg);
2908 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2911 if (chdir (datadir))
2913 log_write ("%s: %s", datadir,
2914 pwmd_strerror (gpg_error_from_errno (errno)));
2915 unlink (socketpath);
2916 goto do_exit;
2919 x = test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 0,
2920 mode, terminate);
2921 if (!terminate && x)
2922 goto do_exit;
2923 else if (terminate)
2925 estatus = x != 1 ? EXIT_FAILURE : EXIT_SUCCESS;
2926 goto do_exit;
2930 * bind() doesn't like the full pathname of the socket or any non alphanum
2931 * characters so change to the directory where the socket is wanted then
2932 * create it then change to datadir.
2934 if (chdir (socketdir))
2936 log_write ("%s: %s", socketdir,
2937 pwmd_strerror (gpg_error_from_errno (errno)));
2938 goto do_exit;
2941 xfree (socketdir);
2943 if ((sockfd = socket (PF_UNIX, SOCK_STREAM, 0)) == -1)
2945 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2946 goto do_exit;
2949 addr.sun_family = AF_UNIX;
2950 snprintf (addr.sun_path, sizeof (addr.sun_path), "%s", socketname);
2951 do_unlink = 1;
2952 if (bind (sockfd, (struct sockaddr *) &addr, sizeof (struct sockaddr)) ==
2955 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2957 if (errno == EADDRINUSE)
2959 do_unlink = 0;
2960 log_write (_("Either there is another pwmd running or '%s' is a \n"
2961 "stale socket. Please remove it manually."), socketpath);
2964 goto do_exit;
2968 char *t = config_get_string ("global", "socket_perms");
2969 mode_t mask;
2971 if (t)
2973 mode = strtol (t, NULL, 8);
2974 mask = umask (0);
2975 xfree (t);
2977 if (chmod (socketname, mode) == -1)
2979 log_write ("%s: %s", socketname,
2980 pwmd_strerror (gpg_error_from_errno (errno)));
2981 close (sockfd);
2982 umask (mask);
2983 goto do_exit;
2986 umask (mask);
2990 xfree (--socketname);
2992 if (chdir (datadir))
2994 log_write ("%s: %s", datadir,
2995 pwmd_strerror (gpg_error_from_errno (errno)));
2996 close (sockfd);
2997 goto do_exit;
3000 xfree (datadir);
3003 * Set the cache entry for a file. Prompts for the password.
3005 if (cache_push)
3007 for (opt = 0; cache_push[opt]; opt++)
3009 struct crypto_s *crypto = NULL;
3010 char *pw_file = config_get_string (cache_push[opt],
3011 "passphrase_file");
3012 gpg_error_t rc = crypto_init (&crypto, NULL, cache_push[opt],
3013 pw_file != NULL);
3015 if (!rc)
3017 crypto->flags |= pw_file ? CRYPTO_FLAG_KEYFILE : 0;
3018 crypto->keyfile = pw_file;
3020 else
3021 xfree (pw_file);
3023 if (rc)
3025 estatus = EXIT_FAILURE;
3026 goto do_exit;
3029 rc = do_cache_push (crypto);
3030 if (rc && !force)
3032 log_write ("ERR %u: %s", rc, pwmd_strerror(rc));
3033 strv_free (cache_push);
3034 startup_failure ();
3035 estatus = EXIT_FAILURE;
3036 crypto_free (crypto);
3037 goto do_exit;
3039 else if (rc)
3040 log_write ("%s: %s", crypto->filename, pwmd_strerror(rc));
3041 else
3042 log_write (_("Successfully added '%s' to the cache."),
3043 crypto->filename);
3045 crypto_free (crypto);
3048 strv_free (cache_push);
3049 log_write (!nofork ? _("Done. Daemonizing...") :
3050 _("Done. Waiting for connections..."));
3053 if (listen (sockfd, 128) == -1)
3055 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
3056 goto do_exit;
3059 if (!nofork)
3061 switch (fork ())
3063 case -1:
3064 log_write ("fork(): %s",
3065 pwmd_strerror (gpg_error_from_errno (errno)));
3066 goto do_exit;
3067 case 0:
3068 close (0);
3069 close (1);
3070 close (2);
3071 setsid ();
3072 break;
3073 default:
3074 _exit (EXIT_SUCCESS);
3078 (void)test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 1,
3079 mode, 0);
3080 cmdline = 0;
3081 pthread_key_create (&thread_name_key, free_key);
3082 estatus = server_loop (sockfd, &socketpath);
3084 do_exit:
3085 if (socketpath && do_unlink)
3087 unlink (socketpath);
3088 xfree (socketpath);
3091 xfree (socketarg);
3092 #ifdef WITH_GNUTLS
3093 gnutls_global_deinit ();
3094 tls_deinit_params ();
3095 #endif
3096 if (rcfile_tid)
3098 #ifdef HAVE_PTHREAD_CANCEL
3099 pthread_cancel (rcfile_tid);
3100 #else
3101 pthread_kill (rcfile_tid, SIGUSR2);
3102 pthread_cond_signal (&rcfile_cond);
3103 #endif
3104 pthread_join (rcfile_tid, NULL);
3107 pthread_cond_destroy (&rcfile_cond);
3108 pthread_mutex_destroy (&rcfile_mutex);
3109 pthread_key_delete (last_error_key);
3110 #ifndef HAVE_PTHREAD_CANCEL
3111 pthread_key_delete (signal_thread_key);
3112 #endif
3114 if (global_config)
3115 config_free (global_config);
3117 free_invoking_users (invoking_users);
3118 xfree (rcfile);
3119 xfree (home_directory);
3120 xfree (homedir);
3121 xmlCleanupParser ();
3122 xmlCleanupGlobals ();
3124 if (pidfile)
3125 unlink (pidfile);
3126 xfree (pidfile);
3128 if (estatus == EXIT_SUCCESS && !terminate)
3129 log_write (_("pwmd exiting normally"));
3131 pthread_key_delete (thread_name_key);
3132 closelog ();
3133 #if defined(DEBUG) && !defined(MEM_DEBUG)
3134 xdump ();
3135 #endif
3137 if (log_fd != -1)
3138 close (log_fd);
3140 exit (estatus);
3143 gpg_error_t lock_flock (assuan_context_t ctx, const char *filename,
3144 int type, int *fd)
3146 gpg_error_t rc = 0;
3148 #ifdef HAVE_FLOCK
3149 *fd = open (filename, O_RDONLY);
3150 if (*fd == -1)
3151 return gpg_error_from_syserror ();
3153 TRY_FLOCK (ctx, *fd, type, rc);
3154 if (rc)
3156 close (*fd);
3157 *fd = -1;
3159 #endif
3161 return rc;
3164 void unlock_flock (int *fd)
3166 #ifdef HAVE_FLOCK
3167 if (*fd != -1)
3168 close (*fd);
3170 *fd = -1;
3171 #endif