Fix PASSWD and SAVE for symmetric encrypted files.
[pwmd.git] / src / pwmd.c
blob1a6b63852dfb13cf68765ff0736e66861306f5c7
1 /*
2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012
3 Ben Kibbey <bjk@luxsci.net>
5 This file is part of pwmd.
7 Pwmd is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 2 of the License, or
10 (at your option) any later version.
12 Pwmd is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
20 #ifdef HAVE_CONFIG_H
21 #include <config.h>
22 #endif
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <unistd.h>
27 #include <err.h>
28 #include <ctype.h>
29 #include <string.h>
30 #include <sys/socket.h>
31 #include <sys/un.h>
32 #include <signal.h>
33 #include <stdarg.h>
34 #include <string.h>
35 #include <sys/wait.h>
36 #include <fcntl.h>
37 #include <pwd.h>
38 #include <grp.h>
39 #include <pthread.h>
40 #include <sys/mman.h>
41 #include <termios.h>
42 #include <assert.h>
43 #include <syslog.h>
44 #include <netinet/in.h>
45 #include <arpa/inet.h>
46 #include <netdb.h>
47 #include <sys/time.h>
48 #include <sys/resource.h>
49 #include <setjmp.h>
51 #ifdef TM_IN_SYS_TIME
52 #include <sys/time.h>
53 #else
54 #include <time.h>
55 #endif
57 #ifdef HAVE_LIMITS_H
58 #include <limits.h>
59 #endif
61 #ifdef HAVE_GETOPT_LONG
62 #ifdef HAVE_GETOPT_H
63 #include <getopt.h>
64 #endif
65 #else
66 #include "getopt_long.h"
67 #endif
69 #ifdef HAVE_PR_SET_NAME
70 #include <sys/prctl.h>
71 #endif
73 #include "pwmd-error.h"
74 #include <gcrypt.h>
76 #include "mem.h"
77 #include "xml.h"
78 #include "common.h"
79 #include "commands.h"
80 #include "cache.h"
81 #include "util-misc.h"
82 #include "util-string.h"
83 #include "mutex.h"
84 #include "rcfile.h"
85 #include "crypto.h"
86 #include "convert.h"
87 #include "pinentry.h"
89 /* In tenths of a second. */
90 #define SIG_TIMEOUT 1
92 /* For (tcp_)accept_thread (usec). */
93 #define ACCEPT_TIMEOUT 30000
95 static int quit;
96 static int exiting;
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 no_passphrase_file = 0;
104 #ifndef HAVE_PTHREAD_CANCEL
105 static pthread_key_t signal_thread_key;
106 #endif
108 #ifdef WITH_GNUTLS
109 static int tls_fd;
110 static int tls6_fd;
111 static pthread_t tls_tid;
112 static pthread_t tls6_tid;
113 static int spawned_tls;
114 static int spawned_tls6;
116 static int start_stop_tls (int term);
117 #endif
119 static int do_cache_push (const char *filename, struct crypto_s *crypto);
120 static int signal_loop (sigset_t sigset);
122 GCRY_THREAD_OPTION_PTHREAD_IMPL;
124 #ifndef HAVE_PTHREAD_CANCEL
125 #define INIT_THREAD_SIGNAL do { \
126 struct sigaction act; \
127 sigset_t sigset; \
128 sigemptyset (&sigset); \
129 sigaddset (&sigset, SIGUSR2); \
130 pthread_sigmask (SIG_UNBLOCK, &sigset, NULL); \
131 memset (&act, 0, sizeof(act)); \
132 act.sa_flags = SA_SIGINFO; \
133 act.sa_mask = sigset; \
134 act.sa_sigaction = catch_thread_signal; \
135 sigaction (SIGUSR2, &act, NULL); \
136 } while (0)
138 static void
139 catch_thread_signal (int sig, siginfo_t *info, void *ctx)
141 int *n = (int *) pthread_getspecific (signal_thread_key);
143 *n = 1;
144 pthread_setspecific (signal_thread_key, n);
146 #endif
148 static void
149 cache_push_from_rcfile ()
151 struct crypto_s *crypto;
152 char **cache_push;
153 gpg_error_t rc = init_client_crypto (&crypto);
155 if (rc)
157 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
158 return;
161 #ifdef WITH_AGENT
162 if (use_agent)
164 rc = set_agent_option (crypto->agent, "pinentry-mode", "error");
165 if (rc)
167 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
168 return;
171 #endif
173 cache_push = config_get_list ("global", "cache_push");
174 if (cache_push)
176 char **p;
178 for (p = cache_push; *p; p++)
180 (void) do_cache_push (*p, crypto);
181 cleanup_crypto_stage1 (crypto);
184 strv_free (cache_push);
187 #ifdef WITH_AGENT
188 (void) kill_scd (crypto->agent);
189 #endif
190 cleanup_crypto (&crypto);
193 static void
194 setup_logging ()
196 int n = config_get_boolean ("global", "enable_logging");
198 if (n)
200 char *p = config_get_string ("global", "log_path");
202 xfree (logfile);
203 logfile = expand_homedir (p);
204 xfree (p);
206 else
208 xfree (logfile);
209 logfile = NULL;
212 log_syslog = config_get_boolean ("global", "syslog");
213 if (log_syslog == 1)
214 openlog ("pwmd", LOG_NDELAY | LOG_PID, LOG_DAEMON);
217 static void *
218 reload_rcfile_thread (void *arg)
220 #ifndef HAVE_PTHREAD_CANCEL
221 int *n = xmalloc (sizeof (int));
223 *n = 0;
224 pthread_setspecific (signal_thread_key, n);
225 INIT_THREAD_SIGNAL;
226 #endif
228 #ifdef HAVE_PR_SET_NAME
229 prctl (PR_SET_NAME, "reload rcfile");
230 #endif
231 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
232 MUTEX_LOCK (&rcfile_mutex);
233 pthread_cleanup_push (cleanup_mutex_cb, &rcfile_mutex);
235 for (;;)
237 struct slist_s *config;
238 char **users;
239 int b = disable_list_and_dump;
240 #ifdef WITH_GNUTLS
241 int exists;
242 int tcp_require_key = config_get_bool_param (global_config, "global",
243 "tcp_require_key",
244 &exists);
245 #endif
247 pthread_cond_wait (&rcfile_cond, &rcfile_mutex);
248 #ifndef HAVE_PTHREAD_CANCEL
249 int *n = (int *) pthread_getspecific (signal_thread_key);
250 if (*n)
251 break;
252 #endif
254 users = config_get_list ("global", "allowed");
255 log_write (_("reloading configuration file '%s'"), rcfile);
256 config = config_parse (rcfile);
257 if (config)
259 config_free (global_config);
260 global_config = config;
261 setup_logging ();
262 cache_push_from_rcfile ();
263 config_clear_keys ();
266 disable_list_and_dump = !disable_list_and_dump ? b : 1;
267 #ifdef WITH_GNUTLS
268 if (config_get_bool_param (global_config, "global", "tcp_require_key",
269 &exists) && exists)
270 tcp_require_key = 1;
272 config_set_bool_param (&global_config, "global", "tcp_require_key",
273 tcp_require_key ? "true" : "false");
274 #endif
275 char *tmp = strv_join (",", users);
276 config_set_list_param (&global_config, "global", "allowed", tmp);
277 xfree (tmp);
278 strv_free (users);
279 #ifdef WITH_GNUTLS
280 /* Kill existing listening threads since the configured listening
281 * protocols may have changed. */
282 start_stop_tls (1);
283 start_stop_tls (0);
284 #endif
287 pthread_cleanup_pop (1);
288 return NULL;
291 gpg_error_t
292 send_error (assuan_context_t ctx, gpg_error_t e)
294 struct client_s *client = assuan_get_pointer (ctx);
296 if (gpg_err_source (e) == GPG_ERR_SOURCE_UNKNOWN)
297 e = gpg_error (e);
299 if (client)
300 client->last_rc = e;
302 if (!e)
303 return assuan_process_done (ctx, 0);
305 if (!ctx)
307 log_write ("%s", pwmd_strerror (e));
308 return e;
311 if (gpg_err_code (e) == GPG_ERR_BAD_DATA)
313 xmlErrorPtr xe = client->xml_error;
315 if (!xe)
316 xe = xmlGetLastError ();
317 if (xe)
319 log_write ("%s", xe->message);
320 if (client->last_error)
321 xfree (client->last_error);
323 client->last_error = str_dup (xe->message);
326 e = assuan_process_done (ctx, assuan_set_error (ctx, e,
327 xe ? xe->message :
328 NULL));
330 if (xe == client->xml_error)
331 xmlResetError (xe);
332 else
333 xmlResetLastError ();
335 client->xml_error = NULL;
336 return e;
339 return assuan_process_done (ctx,
340 assuan_set_error (ctx, e, pwmd_strerror (e)));
344 assuan_log_cb (assuan_context_t ctx, void *data, unsigned cat,
345 const char *msg)
347 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
348 int i, t;
349 int match = 0;
351 pthread_mutex_lock (&m);
352 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock, &m);
353 t = strv_length (debug_level);
355 for (i = 0; i < t; i++)
357 if (!strcasecmp (debug_level[i], (char *) "init")
358 && cat == ASSUAN_LOG_INIT)
360 match = 1;
361 break;
364 if (!strcasecmp (debug_level[i], (char *) "ctx")
365 && cat == ASSUAN_LOG_CTX)
367 match = 1;
368 break;
371 if (!strcasecmp (debug_level[i], (char *) "engine")
372 && cat == ASSUAN_LOG_ENGINE)
374 match = 1;
375 break;
378 if (!strcasecmp (debug_level[i], (char *) "data")
379 && cat == ASSUAN_LOG_DATA)
381 match = 1;
382 break;
385 if (!strcasecmp (debug_level[i], (char *) "sysio")
386 && cat == ASSUAN_LOG_SYSIO)
388 match = 1;
389 break;
392 if (!strcasecmp (debug_level[i], (char *) "control")
393 && cat == ASSUAN_LOG_CONTROL)
395 match = 1;
396 break;
400 if (match && msg)
402 if (logfile)
404 int fd;
406 if ((fd =
407 open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600)) == -1)
408 warn ("%s", logfile);
409 else
411 pthread_cleanup_push (cleanup_fd_cb, &fd);
412 write (fd, msg, strlen (msg));
413 pthread_cleanup_pop (1);
417 if (nofork)
419 fprintf (stderr, "%s%s", data ? (char *) data : "", msg);
420 fflush (stderr);
424 pthread_cleanup_pop (1);
425 return match;
428 void
429 log_write (const char *fmt, ...)
431 char *args, *line;
432 va_list ap;
433 struct tm *tm;
434 time_t now;
435 char tbuf[21];
436 int fd = -1;
437 char *name = NULL;
438 char buf[255];
439 pthread_t tid = pthread_self ();
440 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
442 if ((!logfile && !isatty (STDERR_FILENO) && !log_syslog) || !fmt)
443 return;
445 pthread_mutex_lock (&m);
446 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock, &m);
447 pthread_cleanup_push (cleanup_fd_cb, &fd);
449 if (!cmdline && logfile)
451 if ((fd = open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600)) == -1)
452 warn ("%s", logfile);
455 va_start (ap, fmt);
457 if (str_vasprintf (&args, fmt, ap) != -1)
459 if (cmdline)
461 pthread_cleanup_push (xfree, args);
462 fprintf (stderr, "%s\n", args);
463 fflush (stderr);
464 pthread_cleanup_pop (1);
466 else
468 pthread_cleanup_push (xfree, args);
469 name = pthread_getspecific (thread_name_key);
470 snprintf (buf, sizeof (buf), "%s(%p): ", name ? name : _("unknown"),
471 (pthread_t *) tid);
472 name = buf;
474 if (!cmdline && log_syslog && !nofork)
475 syslog (LOG_INFO, "%s%s", name, args);
477 time (&now);
478 tm = localtime (&now);
479 strftime (tbuf, sizeof (tbuf), "%b %d %Y %H:%M:%S ", tm);
480 tbuf[sizeof (tbuf) - 1] = 0;
482 if (args[strlen (args) - 1] == '\n')
483 args[strlen (args) - 1] = 0;
485 line = str_asprintf ("%s %i %s%s\n", tbuf, getpid (), name, args);
486 pthread_cleanup_pop (1);
487 if (line)
489 pthread_cleanup_push (xfree, line);
490 if (logfile && fd != -1)
492 write (fd, line, strlen (line));
493 fsync (fd);
496 if (nofork)
498 fprintf (stdout, "%s", line);
499 fflush (stdout);
502 pthread_cleanup_pop (1);
507 va_end (ap);
508 pthread_cleanup_pop (1);
509 pthread_cleanup_pop (0);
510 pthread_mutex_unlock (&m);
513 #ifdef WITH_GNUTLS
514 static int
515 secure_mem_check (const void *arg)
517 return 1;
519 #endif
521 static gpg_error_t
522 setup_crypto ()
524 gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
526 if (!gcry_check_version (GCRYPT_VERSION))
528 fprintf (stderr, _("gcry_check_version(): Incompatible libgcrypt. "
529 "Wanted %s, got %s.\n"), GCRYPT_VERSION,
530 gcry_check_version (NULL));
531 return GPG_ERR_UNKNOWN_VERSION;
534 gcry_set_allocation_handler (xmalloc, xmalloc, NULL, xrealloc, xfree);
535 return 0;
538 #ifdef HAVE_GETGRNAM_R
539 static gpg_error_t
540 do_validate_peer (struct client_s *cl, assuan_peercred_t * peer)
542 char **users;
543 int allowed = 0;
544 gpg_error_t rc;
546 rc = assuan_get_peercred (cl->ctx, peer);
547 if (rc)
548 return rc;
550 users = config_get_list ("global", "allowed");
551 if (users)
553 for (char **p = users; *p; p++)
555 struct passwd pw, *result;
556 struct group gr, *gresult;
557 char *buf;
559 if (*(*p) == '@')
561 size_t len = sysconf (_SC_GETGR_R_SIZE_MAX);
563 if (len == -1)
564 len = 16384;
566 buf = xmalloc (len);
567 if (!buf)
569 strv_free (users);
570 return GPG_ERR_ENOMEM;
573 if (!getgrnam_r (*(p) + 1, &gr, buf, len, &gresult) && gresult)
575 if (gresult->gr_gid == (*peer)->gid)
577 xfree (buf);
578 allowed = 1;
579 break;
582 len = sysconf (_SC_GETPW_R_SIZE_MAX);
583 if (len == -1)
584 len = 16384;
586 char *tbuf = xmalloc (len);
587 for (char **t = gresult->gr_mem; *t; t++)
589 if (!getpwnam_r (*t, &pw, tbuf, len, &result) && result)
591 if (result->pw_uid == (*peer)->uid)
593 xfree (buf);
594 allowed = 1;
595 break;
600 xfree (tbuf);
602 if (allowed)
603 break;
606 else
608 size_t len = sysconf (_SC_GETPW_R_SIZE_MAX);
610 if (len == -1)
611 len = 16384;
613 buf = xmalloc (len);
615 if (!buf)
617 strv_free (users);
618 return GPG_ERR_ENOMEM;
621 if (!getpwnam_r (*p, &pw, buf, len, &result) && result)
623 if (result->pw_uid == (*peer)->uid)
625 xfree (buf);
626 allowed = 1;
627 break;
632 xfree (buf);
635 strv_free (users);
638 return allowed ? 0 : GPG_ERR_INV_USER_ID;
640 #else
641 static gpg_error_t
642 do_validate_peer (struct client_s *cl, assuan_peercred_t * peer)
644 char **users;
645 int allowed = 0;
646 gpg_error_t rc;
648 rc = assuan_get_peercred (cl->ctx, peer);
649 if (rc)
650 return rc;
652 users = config_get_list ("global", "allowed");
653 if (users)
655 for (char **p = users; *p; p++)
657 struct passwd *result;
658 struct group *gresult;
660 if (*(*p) == '@')
662 gresult = getgrnam (*(p) + 1);
663 if (gresult && gresult->gr_gid == (*peer)->gid)
665 allowed = 1;
666 break;
669 for (char **t = gresult->gr_mem; *t; t++)
671 result = getpwnam (*t);
672 if (result && result->pw_uid == (*peer)->uid)
674 allowed = 1;
675 break;
679 else
681 result = getpwnam (*p);
682 if (result && result->pw_uid == (*peer)->uid)
684 allowed = 1;
685 break;
689 if (allowed)
690 break;
693 strv_free (users);
696 return allowed ? 0 : GPG_ERR_INV_USER_ID;
698 #endif
700 static gpg_error_t
701 validate_peer (struct client_s *cl)
703 gpg_error_t rc;
704 assuan_peercred_t peer;
706 #ifdef WITH_GNUTLS
707 if (cl->thd->remote)
708 return 0;
709 #endif
711 rc = do_validate_peer (cl, &peer);
712 if (!rc || gpg_err_code (rc) == GPG_ERR_INV_USER_ID)
713 log_write ("peer %s: uid=%i, gid=%i, pid=%i",
714 !rc ? _("accepted") : _("rejected"), peer->uid, peer->gid,
715 peer->pid);
716 else if (rc)
717 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
719 return rc;
722 static void
723 xml_error_cb (void *data, xmlErrorPtr e)
725 struct client_s *client = data;
728 * Keep the first reported error as the one to show in the error
729 * description. Reset in send_error().
731 if (client->xml_error)
732 return;
734 xmlCopyError (e, client->xml_error);
737 static pid_t
738 hook_waitpid (assuan_context_t ctx, pid_t pid, int action,
739 int *status, int options)
741 return waitpid (pid, status, options);
744 static ssize_t
745 hook_read (assuan_context_t ctx, assuan_fd_t fd, void *data, size_t len)
747 #ifdef WITH_GNUTLS
748 struct client_s *client = assuan_get_pointer (ctx);
750 if (client->thd->remote)
751 return tls_read_hook (ctx, (int) fd, data, len);
752 #endif
754 return read ((int) fd, data, len);
757 static ssize_t
758 hook_write (assuan_context_t ctx, assuan_fd_t fd,
759 const void *data, size_t len)
761 #ifdef WITH_GNUTLS
762 struct client_s *client = assuan_get_pointer (ctx);
764 if (client->thd->remote)
765 return tls_write_hook (ctx, (int) fd, data, len);
766 #endif
768 return write ((int) fd, data, len);
771 static int
772 new_connection (struct client_s *cl)
774 gpg_error_t rc;
775 static struct assuan_malloc_hooks mhooks = { xmalloc, xrealloc, xfree };
776 static struct assuan_system_hooks shooks = {
777 ASSUAN_SYSTEM_HOOKS_VERSION,
778 __assuan_usleep,
779 __assuan_pipe,
780 __assuan_close,
781 hook_read,
782 hook_write,
783 //FIXME
784 NULL, //recvmsg
785 NULL, //sendmsg both are used for FD passing
786 __assuan_spawn,
787 hook_waitpid,
788 __assuan_socketpair,
789 __assuan_socket,
790 __assuan_connect
793 #ifdef WITH_GNUTLS
794 if (cl->thd->remote)
796 char *prio = config_get_string ("global", "tls_cipher_suite");
798 cl->thd->tls = tls_init (cl->thd->fd, prio);
799 xfree (prio);
800 if (!cl->thd->tls)
801 return 0;
803 #endif
805 rc = assuan_new_ext (&cl->ctx, GPG_ERR_SOURCE_DEFAULT, &mhooks,
806 debug_level ? assuan_log_cb : NULL, NULL);
807 if (rc)
808 goto fail;
810 assuan_ctx_set_system_hooks (cl->ctx, &shooks);
811 rc = assuan_init_socket_server (cl->ctx, cl->thd->fd, 2);
812 if (rc)
813 goto fail;
815 assuan_set_pointer (cl->ctx, cl);
816 assuan_set_hello_line (cl->ctx, PACKAGE_STRING);
817 rc = register_commands (cl->ctx);
818 if (rc)
819 goto fail;
821 rc = assuan_accept (cl->ctx);
822 if (rc)
823 goto fail;
825 rc = validate_peer (cl);
826 /* May not be implemented on all platforms. */
827 if (rc && gpg_err_code (rc) != GPG_ERR_ASS_GENERAL)
828 goto fail;
830 rc = init_client_crypto (&cl->crypto);
831 if (rc)
832 goto fail;
834 #ifdef WITH_AGENT
835 if (use_agent)
836 cl->crypto->agent->client_ctx = cl->ctx;
837 #endif
839 cl->crypto->client_ctx = cl->ctx;
840 xmlSetStructuredErrorFunc (cl, xml_error_cb);
841 return 1;
843 fail:
844 log_write ("%s", pwmd_strerror (rc));
845 return 0;
849 * This is called after a client_thread() terminates. Set with
850 * pthread_cleanup_push().
852 static void
853 cleanup_cb (void *arg)
855 struct client_thread_s *cn = arg;
856 struct client_s *cl = cn->cl;
858 MUTEX_LOCK (&cn_mutex);
859 cn_thread_list = slist_remove (cn_thread_list, cn);
860 MUTEX_UNLOCK (&cn_mutex);
862 if (cl)
864 cleanup_client (cl);
866 #ifdef WITH_GNUTLS
867 if (cn->tls)
869 gnutls_deinit (cn->tls->ses);
870 xfree (cn->tls->fp);
871 xfree (cn->tls);
873 #endif
875 if (cl->ctx)
876 assuan_release (cl->ctx);
877 else if (cl->thd && cl->thd->fd != -1)
878 close (cl->thd->fd);
880 if (cl->crypto)
881 cleanup_crypto (&cl->crypto);
883 xfree (cl);
885 else
887 if (cn->fd != -1)
888 close (cn->fd);
891 while (cn->msg_queue)
893 struct status_msg_s *msg = cn->msg_queue;
895 cn->msg_queue = msg->next;
896 xfree (msg->line);
897 xfree (msg);
900 if (cn->status_msg_pipe[0] != -1)
901 close (cn->status_msg_pipe[0]);
903 if (cn->status_msg_pipe[1] != -1)
904 close (cn->status_msg_pipe[1]);
906 pthread_mutex_destroy (&cn->status_mutex);
907 log_write (_("exiting, fd=%i"), cn->fd);
908 xfree (cn);
909 send_status_all (STATUS_CLIENTS, NULL);
910 pthread_cond_signal (&quit_cond);
913 static gpg_error_t
914 send_msg_queue (struct client_thread_s *thd)
916 MUTEX_LOCK (&thd->status_mutex);
917 gpg_error_t rc = 0;
918 char c;
920 read (thd->status_msg_pipe[0], &c, 1);
922 while (thd->msg_queue)
924 struct status_msg_s *msg = thd->msg_queue;
926 thd->msg_queue = thd->msg_queue->next;
927 MUTEX_UNLOCK (&thd->status_mutex);
928 rc = send_status (thd->cl->ctx, msg->s, msg->line);
929 MUTEX_LOCK (&thd->status_mutex);
930 xfree (msg->line);
931 xfree (msg);
933 if (rc)
934 break;
937 MUTEX_UNLOCK (&thd->status_mutex);
938 return rc;
941 static void *
942 client_thread (void *data)
944 struct client_thread_s *thd = data;
945 struct client_s *cl = xcalloc (1, sizeof (struct client_s));
947 #ifdef HAVE_PR_SET_NAME
948 prctl (PR_SET_NAME, "client");
949 #endif
950 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
952 if (!cl)
954 log_write ("%s(%i): %s", __FILE__, __LINE__,
955 pwmd_strerror (GPG_ERR_ENOMEM));
956 return NULL;
959 MUTEX_LOCK (&cn_mutex);
960 pthread_cleanup_push (cleanup_cb, thd);
961 thd->cl = cl;
962 cl->thd = thd;
963 MUTEX_UNLOCK (&cn_mutex);
965 if (new_connection (cl))
967 int finished = 0;
968 gpg_error_t rc;
970 send_status_all (STATUS_CLIENTS, NULL);
971 rc = send_status (cl->ctx, STATUS_CACHE, NULL);
972 if (rc)
974 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
975 finished = 1;
978 while (!finished)
980 fd_set rfds;
981 int n;
982 int eof;
984 FD_ZERO (&rfds);
985 FD_SET (thd->fd, &rfds);
986 FD_SET (thd->status_msg_pipe[0], &rfds);
988 thd->fd >
989 thd->status_msg_pipe[0] ? thd->fd : thd->status_msg_pipe[0];
991 n = select (n + 1, &rfds, NULL, NULL, NULL);
992 if (n == -1)
994 log_write ("%s", strerror (errno));
995 break;
998 if (FD_ISSET (thd->status_msg_pipe[0], &rfds))
1000 rc = send_msg_queue (thd);
1001 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1003 log_write ("%s(%i): %s", __FUNCTION__, __LINE__,
1004 pwmd_strerror (rc));
1005 break;
1009 if (!FD_ISSET (thd->fd, &rfds))
1010 continue;
1012 rc = assuan_process_next (cl->ctx, &eof);
1013 if (rc || eof)
1015 if (gpg_err_code (rc) == GPG_ERR_EOF || eof)
1016 break;
1018 log_write ("assuan_process_next(): %s", pwmd_strerror (rc));
1019 rc = send_error (cl->ctx, rc);
1021 if (rc)
1023 log_write ("assuan_process_done(): %s", pwmd_strerror (rc));
1024 break;
1028 /* Since the msg queue pipe fd's are non-blocking, check for
1029 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1030 * client has already disconnected and will be converted to
1031 * GPG_ERR_EOF during assuan_process_next().
1033 rc = send_msg_queue (thd);
1034 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1036 log_write ("%s(%i): %s", __FUNCTION__, __LINE__,
1037 pwmd_strerror (rc));
1038 break;
1043 pthread_cleanup_pop (1);
1044 return NULL;
1047 static int
1048 xml_import (const char *filename, const char *outfile,
1049 const char *keygrip, const char *sign_keygrip,
1050 const char *keyfile, int no_passphrase, const char *cipher,
1051 const char *params, unsigned long s2k_count, uint64_t iterations)
1053 xmlDocPtr doc;
1054 int fd;
1055 struct stat st;
1056 int len;
1057 xmlChar *xmlbuf;
1058 xmlChar *xml;
1059 gpg_error_t rc;
1060 struct crypto_s *crypto;
1061 void *key = NULL;
1062 size_t keylen = 0;
1063 int algo = cipher ? cipher_string_to_gcrypt ((char *) cipher) :
1064 GCRY_CIPHER_AES256;
1066 if (algo == -1)
1068 log_write ("ERR %i: %s", gpg_error (GPG_ERR_CIPHER_ALGO),
1069 pwmd_strerror (GPG_ERR_CIPHER_ALGO));
1070 return 0;
1073 if (stat (filename, &st) == -1)
1075 log_write ("%s: %s", filename,
1076 pwmd_strerror (gpg_error_from_syserror ()));
1077 return 0;
1080 rc = init_client_crypto (&crypto);
1081 if (rc)
1082 return 0;
1084 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
1085 crypto->save.hdr.flags = set_cipher_flag (crypto->save.hdr.flags, algo);
1086 log_write (_("Importing XML from '%s'. Output will be written to '%s' ..."),
1087 filename, outfile);
1089 if ((fd = open (filename, O_RDONLY)) == -1)
1091 log_write ("%s: %s", filename,
1092 pwmd_strerror (gpg_error_from_syserror ()));
1093 goto fail;
1096 if ((xmlbuf = xmalloc (st.st_size + 1)) == NULL)
1098 close (fd);
1099 log_write ("%s(%i): %s", __FILE__, __LINE__,
1100 pwmd_strerror (GPG_ERR_ENOMEM));
1101 goto fail;
1104 if (read (fd, xmlbuf, st.st_size) == -1)
1106 rc = gpg_error_from_syserror ();
1107 close (fd);
1108 log_write ("%s: %s", filename, pwmd_strerror (rc));
1109 goto fail;
1112 close (fd);
1113 xmlbuf[st.st_size] = 0;
1115 * Make sure the document validates.
1117 if ((doc = xmlReadDoc (xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS)) == NULL)
1119 log_write ("xmlReadDoc() failed");
1120 xfree (xmlbuf);
1121 goto fail;
1124 xfree (xmlbuf);
1125 xmlNodePtr n = xmlDocGetRootElement (doc);
1126 if (!xmlStrEqual (n->name, (xmlChar *) "pwmd"))
1128 log_write (_("Could not find root \"pwmd\" element."));
1129 rc = GPG_ERR_BAD_DATA;
1132 if (!rc)
1133 rc = validate_import (n ? n->children : n);
1135 if (rc)
1137 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1138 xmlFreeDoc (doc);
1139 goto fail;
1142 xmlDocDumpMemory (doc, &xml, &len);
1143 xmlFreeDoc (doc);
1144 crypto->save.s2k_count = s2k_count;
1145 crypto->save.hdr.iterations = iterations;
1146 if (!use_agent)
1147 rc = export_common (NULL, crypto, no_passphrase, xml, len, outfile,
1148 keyfile, &key, &keylen, 1, 0);
1149 #ifdef WITH_AGENT
1150 else
1152 rc = agent_set_pinentry_options (crypto->agent);
1153 if (!rc)
1154 rc = agent_export_common (crypto, keygrip, sign_keygrip, no_passphrase,
1155 xml, len, outfile, params, keyfile);
1157 #endif
1159 gcry_free (key);
1160 xmlFree (xml);
1161 if (rc)
1163 send_error (NULL, rc);
1164 goto fail;
1167 cleanup_crypto (&crypto);
1168 return 1;
1170 fail:
1171 cleanup_crypto (&crypto);
1172 return 0;
1175 static int
1176 do_cache_push (const char *filename, struct crypto_s *crypto)
1178 unsigned char md5file[16];
1179 gpg_error_t rc;
1180 char *key = NULL;
1181 size_t keylen = 0;
1182 xmlDocPtr doc;
1183 struct cache_data_s *cdata;
1184 unsigned char *crc;
1185 size_t len;
1187 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1188 filename);
1190 if (valid_filename (filename) == 0)
1192 log_write (_("%s: Invalid characters in filename"), filename);
1193 return 0;
1196 rc = decrypt_common (crypto, filename, &key, &keylen);
1197 if (rc)
1198 return 0;
1200 doc = parse_doc ((char *) crypto->plaintext, crypto->plaintext_len);
1201 if (!doc)
1203 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM));
1204 xfree (key);
1205 return 0;
1208 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
1209 cdata = xcalloc (1, sizeof (struct cache_data_s));
1210 if (!cdata)
1212 xmlFreeDoc (doc);
1213 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM));
1214 xfree (key);
1215 return 0;
1218 rc = get_checksum (filename, &crc, &len);
1219 if (rc)
1221 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1222 xmlFreeDoc (doc);
1223 free_cache_data_once (cdata);
1224 xfree (key);
1225 return 0;
1228 cdata->crc = crc;
1229 rc = encrypt_xml (NULL, cache_key, cache_keysize, GCRY_CIPHER_AES,
1230 crypto->plaintext, crypto->plaintext_len, &cdata->doc,
1231 &cdata->doclen, &cache_iv, &cache_blocksize, 0);
1232 if (!rc && !IS_PKCS (crypto))
1234 cdata->key = key;
1235 cdata->keylen = keylen;
1237 else
1238 xfree (key);
1240 if (rc)
1242 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1243 xmlFreeDoc (doc);
1244 free_cache_data_once (cdata);
1245 return 0;
1248 #ifdef WITH_AGENT
1249 if (use_agent)
1251 gcry_sexp_build ((gcry_sexp_t *) & cdata->pubkey, NULL, "%S",
1252 crypto->pkey_sexp);
1253 gcry_sexp_build ((gcry_sexp_t *) & cdata->sigkey, NULL, "%S",
1254 crypto->sigpkey_sexp);
1256 #endif
1258 int timeout = config_get_integer (filename, "cache_timeout");
1259 cache_add_file (md5file, crypto->grip, cdata, timeout);
1260 log_write (_("Successfully added '%s' to the cache."), filename);
1261 return 1;
1264 static gpg_error_t
1265 init_client (int fd, const char *addr)
1267 gpg_error_t rc = 0;
1268 struct client_thread_s *new = xcalloc (1, sizeof (struct client_thread_s));
1270 if (!new)
1272 close (fd);
1273 return GPG_ERR_ENOMEM;
1276 MUTEX_LOCK (&cn_mutex);
1277 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
1279 if (pipe (new->status_msg_pipe) == -1)
1280 rc = gpg_error_from_syserror ();
1282 if (!rc)
1284 fcntl (new->status_msg_pipe[0], F_SETFL, O_NONBLOCK);
1285 fcntl (new->status_msg_pipe[1], F_SETFL, O_NONBLOCK);
1286 pthread_mutex_init (&new->status_mutex, NULL);
1289 if (!rc)
1291 #ifdef WITH_GNUTLS
1292 new->remote = addr ? 1 : 0;
1293 #endif
1294 new->fd = fd;
1295 rc = create_thread (client_thread, new, &new->tid, 1);
1296 if (rc)
1298 close (new->status_msg_pipe[0]);
1299 close (new->status_msg_pipe[1]);
1300 pthread_mutex_destroy (&new->status_mutex);
1304 if (!rc)
1306 struct slist_s *list = slist_append (cn_thread_list, new);
1308 if (list)
1310 cn_thread_list = list;
1311 if (addr)
1312 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1313 (pthread_t *) new->tid, fd, addr);
1314 else
1315 log_write (_("new connection: tid=%p, fd=%i"),
1316 (pthread_t *) new->tid, fd);
1318 else
1319 rc = GPG_ERR_ENOMEM;
1322 pthread_cleanup_pop (1);
1324 if (rc)
1326 xfree (new);
1327 close (fd);
1328 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1329 pwmd_strerror (rc));
1331 return rc;
1334 #ifdef WITH_GNUTLS
1335 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1336 static void *
1337 get_in_addr (struct sockaddr *sa)
1339 if (sa->sa_family == AF_INET)
1340 return &(((struct sockaddr_in *) sa)->sin_addr);
1342 return &(((struct sockaddr_in6 *) sa)->sin6_addr);
1345 static void *
1346 tcp_accept_thread (void *arg)
1348 int sockfd = *(int *) arg;
1349 #ifndef HAVE_PTHREAD_CANCEL
1350 int *n = xmalloc (sizeof (int));
1352 *n = 0;
1353 pthread_setspecific (signal_thread_key, n);
1354 INIT_THREAD_SIGNAL;
1355 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1356 #endif
1358 #ifdef HAVE_PR_SET_NAME
1359 prctl (PR_SET_NAME, "tcp_accept");
1360 #endif
1361 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1363 for (;;)
1365 struct sockaddr_storage raddr;
1366 socklen_t slen = sizeof (raddr);
1367 int fd = -1;
1368 unsigned long n;
1369 char s[INET6_ADDRSTRLEN];
1370 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1371 #ifndef HAVE_PTHREAD_CANCEL
1372 int *sigusr2;
1374 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1375 if (*sigusr2)
1376 break;
1377 #endif
1379 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1380 if (fd == -1)
1382 if (errno == EMFILE || errno == ENFILE)
1383 log_write ("accept(): %s",
1384 pwmd_strerror (gpg_error_from_syserror ()));
1385 else if (errno != EAGAIN)
1387 if (!quit) // probably EBADF
1388 log_write ("accept(): %s", strerror (errno));
1390 break;
1393 #ifndef HAVE_PTHREAD_CANCEL
1394 select (0, NULL, NULL, NULL, &tv);
1395 #endif
1396 continue;
1399 if (quit)
1400 break;
1402 inet_ntop (raddr.ss_family, get_in_addr ((struct sockaddr *) &raddr),
1403 s, sizeof s);
1404 (void) init_client (fd, s);
1405 n = config_get_integer ("global", "tcp_wait");
1406 if (n > 0)
1408 tv.tv_sec = (n * 100000) / 100000;
1409 tv.tv_usec = (n * 100000) % 100000;
1410 select (0, NULL, NULL, NULL, &tv);
1414 return NULL;
1417 static int
1418 start_stop_tls_with_protocol (int ipv6, int term)
1420 struct addrinfo hints, *servinfo, *p;
1421 int port = config_get_integer ("global", "tcp_port");
1422 char buf[7];
1423 int n;
1424 gpg_error_t rc;
1425 int *fd = ipv6 ? &tls6_fd : &tls_fd;
1427 if (term || config_get_boolean ("global", "enable_tcp") == 0)
1429 if (tls6_fd != -1)
1431 if (spawned_tls6)
1433 #ifdef HAVE_PTHREAD_CANCEL
1434 pthread_cancel (tls6_tid);
1435 #else
1436 pthread_kill (tls6_tid, SIGUSR2);
1437 #endif
1438 pthread_join (tls6_tid, NULL);
1441 shutdown (tls6_fd, SHUT_RDWR);
1442 close (tls6_fd);
1443 tls6_fd = -1;
1444 spawned_tls6 = 0;
1447 if (tls_fd != -1)
1449 if (spawned_tls)
1451 #ifdef HAVE_PTHREAD_CANCEL
1452 pthread_cancel (tls_tid);
1453 #else
1454 pthread_kill (tls_tid, SIGUSR2);
1455 #endif
1456 pthread_join (tls_tid, NULL);
1459 shutdown (tls_fd, SHUT_RDWR);
1460 close (tls_fd);
1461 tls_fd = -1;
1462 spawned_tls = 0;
1465 /* A client may still be connected. */
1466 if (!quit && x509_cred != NULL)
1467 tls_deinit_params ();
1469 return 1;
1472 if ((ipv6 && tls6_fd != -1) || (!ipv6 && tls_fd != -1))
1473 return 1;
1475 memset (&hints, 0, sizeof (hints));
1476 hints.ai_family = ipv6 ? AF_INET6 : AF_INET;
1477 hints.ai_socktype = SOCK_STREAM;
1478 hints.ai_flags = AI_PASSIVE;
1479 snprintf (buf, sizeof (buf), "%i", port);
1481 if ((n = getaddrinfo (NULL, buf, &hints, &servinfo)) == -1)
1483 log_write ("getaddrinfo(): %s", gai_strerror (n));
1484 return 0;
1487 for (n = 0, p = servinfo; p != NULL; p = p->ai_next)
1489 int r = 1;
1491 if ((ipv6 && p->ai_family != AF_INET6)
1492 || (!ipv6 && p->ai_family != AF_INET))
1493 continue;
1495 if ((*fd = socket (p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
1497 log_write ("socket(): %s", strerror (errno));
1498 continue;
1501 if (setsockopt (*fd, SOL_SOCKET, SO_REUSEADDR, &r, sizeof (int)) == -1)
1503 log_write ("setsockopt(): %s",
1504 pwmd_strerror (gpg_error_from_syserror ()));
1505 freeaddrinfo (servinfo);
1506 goto fail;
1509 if (bind (*fd, p->ai_addr, p->ai_addrlen) == -1)
1511 close (*fd);
1512 log_write ("bind(): %s",
1513 pwmd_strerror (gpg_error_from_syserror ()));
1514 continue;
1517 n++;
1518 break;
1521 freeaddrinfo (servinfo);
1523 if (!n)
1524 goto fail;
1526 #if HAVE_DECL_SO_BINDTODEVICE != 0
1527 char *tmp = config_get_string ("global", "tcp_interface");
1528 if (tmp && setsockopt (*fd, SOL_SOCKET, SO_BINDTODEVICE, tmp, 1) == -1)
1530 log_write ("setsockopt(): %s",
1531 pwmd_strerror (gpg_error_from_syserror ()));
1532 xfree (tmp);
1533 goto fail;
1536 xfree (tmp);
1537 #endif
1539 if (x509_cred == NULL)
1541 rc = tls_init_params ();
1542 if (rc)
1543 goto fail;
1546 if (listen (*fd, 0) == -1)
1548 log_write ("listen(): %s", strerror (errno));
1549 goto fail;
1552 if (ipv6)
1553 rc = create_thread (tcp_accept_thread, fd, &tls6_tid, 0);
1554 else
1555 rc = create_thread (tcp_accept_thread, fd, &tls_tid, 0);
1557 if (rc)
1559 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1560 pwmd_strerror (rc));
1561 goto fail;
1564 if (ipv6)
1565 spawned_tls6 = 1;
1566 else
1567 spawned_tls = 1;
1569 return 1;
1571 fail:
1572 start_stop_tls_with_protocol (0, 1);
1573 if (tls_fd != -1)
1574 close (tls_fd);
1576 if (tls6_fd != -1)
1577 close (tls6_fd);
1579 tls_fd = -1;
1580 tls6_fd = -1;
1581 return 0;
1584 static int
1585 start_stop_tls (int term)
1587 char *s = config_get_string ("global", "tcp_bind");
1588 int b;
1590 if (!s)
1591 return 0;
1593 if (!strcmp (s, "any"))
1595 b = start_stop_tls_with_protocol (0, term);
1596 if (b)
1597 b = start_stop_tls_with_protocol (1, term);
1599 else if (!strcmp (s, "ipv4"))
1600 b = start_stop_tls_with_protocol (0, term);
1601 else if (!strcmp (s, "ipv6"))
1602 b = start_stop_tls_with_protocol (1, term);
1603 else
1604 b = 0;
1606 xfree (s);
1607 return b;
1609 #endif
1611 static void *
1612 accept_thread (void *arg)
1614 int sockfd = *(int *) arg;
1615 #ifndef HAVE_PTHREAD_CANCEL
1616 int *n = xmalloc (sizeof (int));
1618 *n = 0;
1619 pthread_setspecific (signal_thread_key, n);
1620 INIT_THREAD_SIGNAL;
1621 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1622 #endif
1624 #ifdef HAVE_PR_SET_NAME
1625 prctl (PR_SET_NAME, "accept");
1626 #endif
1627 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1629 for (;;)
1631 socklen_t slen = sizeof (struct sockaddr_un);
1632 struct sockaddr_un raddr;
1633 int fd;
1634 #ifndef HAVE_PTHREAD_CANCEL
1635 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1636 int *sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1638 if (*sigusr2)
1639 break;
1640 #endif
1642 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1643 if (fd == -1)
1645 if (errno == EMFILE || errno == ENFILE)
1646 log_write ("accept(): %s",
1647 pwmd_strerror (gpg_error_from_syserror ()));
1648 else if (errno != EAGAIN)
1650 if (!quit) // probably EBADF
1651 log_write ("accept(): %s",
1652 pwmd_strerror (gpg_error_from_syserror ()));
1654 break;
1657 #ifndef HAVE_PTHREAD_CANCEL
1658 select (0, NULL, NULL, NULL, &tv);
1659 #endif
1660 continue;
1663 (void) init_client (fd, NULL);
1666 /* Just in case accept() failed for some reason other than EBADF */
1667 quit = 1;
1668 return NULL;
1671 static void *
1672 cache_timer_thread (void *arg)
1674 #ifndef HAVE_PTHREAD_CANCEL
1675 int *n = xmalloc (sizeof (int));
1677 *n = 0;
1678 pthread_setspecific (signal_thread_key, n);
1679 INIT_THREAD_SIGNAL;
1680 #endif
1682 #ifdef HAVE_PR_SET_NAME
1683 prctl (PR_SET_NAME, "cache timer");
1684 #endif
1685 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1687 for (;;)
1689 struct timeval tv = { 1, 0 };
1690 #ifndef HAVE_PTHREAD_CANCEL
1691 int *n;
1693 n = (int *) pthread_getspecific (signal_thread_key);
1694 if (*n)
1695 break;
1696 #endif
1698 select (0, NULL, NULL, NULL, &tv);
1699 cache_adjust_timeout ();
1702 return NULL;
1705 static void
1706 catch_sigabrt (int sig)
1708 cache_clear (NULL);
1709 #ifndef MEM_DEBUG
1710 xpanic ();
1711 #endif
1714 static int
1715 signal_loop (sigset_t sigset)
1717 int done = 0;
1718 int siint = 0;
1722 int sig;
1724 sigwait (&sigset, &sig);
1726 if (sig != SIGQUIT)
1727 log_write (_("caught signal %i (%s)"), sig, strsignal (sig));
1729 switch (sig)
1731 case SIGHUP:
1732 pthread_cond_signal (&rcfile_cond);
1733 break;
1734 case SIGABRT:
1735 // not really handled here.
1736 catch_sigabrt (SIGABRT);
1737 break;
1738 case SIGUSR1:
1739 log_write (_("clearing file cache"));
1740 cache_clear (NULL);
1741 send_status_all (STATUS_CACHE, NULL);
1742 break;
1743 case SIGQUIT:
1744 done = 1;
1745 break;
1746 default:
1747 siint = 1;
1748 done = 1;
1749 break;
1752 while (!done);
1754 return siint;
1757 static void
1758 catchsig (int sig)
1760 log_write ("Caught SIGSEGV. Exiting.");
1761 #ifdef HAVE_BACKTRACE
1762 BACKTRACE (__FUNCTION__);
1763 #endif
1764 longjmp (jmp, 1);
1767 static void *
1768 waiting_for_exit (void *arg)
1770 int last = 0;
1771 #ifndef HAVE_PTHREAD_CANCEL
1772 int *n = xmalloc (sizeof (int));
1774 *n = 0;
1775 pthread_setspecific (signal_thread_key, n);
1776 INIT_THREAD_SIGNAL;
1777 #endif
1779 #ifdef HAVE_PR_SET_NAME
1780 prctl (PR_SET_NAME, "exiting");
1781 #endif
1782 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1783 log_write (_("waiting for all clients to disconnect"));
1784 MUTEX_LOCK (&quit_mutex);
1785 pthread_cleanup_push (cleanup_mutex_cb, &quit_mutex);
1787 for (;;)
1789 struct timespec ts;
1790 int n;
1792 MUTEX_LOCK (&cn_mutex);
1793 n = slist_length (cn_thread_list);
1794 MUTEX_UNLOCK (&cn_mutex);
1795 if (!n)
1796 break;
1798 #ifndef HAVE_PTHREAD_CANCEL
1799 int *s = (int *) pthread_getspecific (signal_thread_key);
1800 if (*s)
1801 break;
1802 #endif
1804 if (last != n)
1806 log_write (_("%i clients remain"), n);
1807 last = n;
1810 INIT_TIMESPEC (SIG_TIMEOUT, ts);
1811 pthread_cond_timedwait (&quit_cond, &quit_mutex, &ts);
1814 kill (getpid (), SIGQUIT);
1815 pthread_cleanup_pop (1);
1816 return NULL;
1819 static int
1820 server_loop (int sockfd, char **socketpath)
1822 pthread_t accept_tid;
1823 pthread_t cache_timeout_tid;
1824 int cancel_timeout_thread = 0, cancel_accept_thread = 0;
1825 int n, i;
1826 sigset_t sigset;
1827 int segv = 0;
1828 gpg_error_t rc;
1830 init_commands ();
1831 sigemptyset (&sigset);
1833 /* Termination */
1834 sigaddset (&sigset, SIGTERM);
1835 sigaddset (&sigset, SIGINT);
1837 /* Clears the file cache. */
1838 sigaddset (&sigset, SIGUSR1);
1840 /* Configuration file reloading. */
1841 sigaddset (&sigset, SIGHUP);
1843 /* For exiting cleanly. */
1844 sigaddset (&sigset, SIGQUIT);
1846 #ifndef HAVE_PTHREAD_CANCEL
1848 The socket, cache and rcfile threads use this signal when
1849 pthread_cancel() is unavailable. Prevent the main thread from
1850 catching this signal from another process.
1852 sigaddset (&sigset, SIGUSR2);
1853 #endif
1855 /* Clears the cache and exits when something bad happens. */
1856 signal (SIGABRT, catch_sigabrt);
1857 sigaddset (&sigset, SIGABRT);
1858 sigprocmask (SIG_BLOCK, &sigset, NULL);
1860 #ifndef HAVE_PTHREAD_CANCEL
1861 /* Remove this signal from the watched signals in signal_loop(). */
1862 sigdelset (&sigset, SIGUSR2);
1863 #endif
1865 /* Ignored everywhere. When a client disconnects abnormally this signal
1866 * gets raised. It isn't needed though because client_thread() will check
1867 * for rcs even after the client disconnects. */
1868 signal (SIGPIPE, SIG_IGN);
1870 /* Can show a backtrace of the stack in the log. */
1871 signal (SIGSEGV, catchsig);
1873 #ifdef WITH_GNUTLS
1874 /* Needs to be done after the fork(). */
1875 if (!start_stop_tls (0))
1877 segv = 1;
1878 goto done;
1880 #endif
1882 pthread_mutex_init (&quit_mutex, NULL);
1883 pthread_cond_init (&quit_cond, NULL);
1884 log_write (_("%s started for user %s"), PACKAGE_STRING, get_username ());
1886 #ifdef WITH_GNUTLS
1887 if (config_get_boolean ("global", "enable_tcp"))
1888 log_write (_("Listening on %s and TCP port %i"), *socketpath,
1889 config_get_integer ("global", "tcp_port"));
1890 else
1891 log_write (_("Listening on %s"), *socketpath);
1892 #else
1893 log_write (_("Listening on %s"), *socketpath);
1894 #endif
1896 rc = create_thread (reload_rcfile_thread, NULL, &rcfile_tid, 0);
1897 if (rc)
1899 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1900 pwmd_strerror (rc));
1901 goto done;
1904 rc = create_thread (cache_timer_thread, NULL, &cache_timeout_tid, 0);
1905 if (rc)
1907 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1908 pwmd_strerror (rc));
1909 goto done;
1912 cancel_timeout_thread = 1;
1913 rc = create_thread (accept_thread, &sockfd, &accept_tid, 0);
1914 if (rc)
1916 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1917 pwmd_strerror (rc));
1918 goto done;
1921 cancel_accept_thread = 1;
1922 if (!setjmp (jmp))
1923 signal_loop (sigset);
1924 else
1925 segv = 1;
1927 done:
1929 * We're out of the main server loop. This happens when a signal was sent
1930 * to terminate the daemon. We'll wait for all clients to disconnect
1931 * before exiting but exit immediately if another termination signal is
1932 * sent.
1934 if (cancel_accept_thread)
1936 #ifdef HAVE_PTHREAD_CANCEL
1937 int n = pthread_cancel (accept_tid);
1938 #else
1939 int n = pthread_kill (accept_tid, SIGUSR2);
1940 #endif
1941 if (!n)
1942 pthread_join (accept_tid, NULL);
1945 #ifdef WITH_GNUTLS
1946 start_stop_tls (1);
1947 #endif
1948 shutdown (sockfd, SHUT_RDWR);
1949 close (sockfd);
1950 unlink (*socketpath);
1951 xfree (*socketpath);
1952 *socketpath = NULL;
1953 MUTEX_LOCK (&cn_mutex);
1954 n = slist_length (cn_thread_list);
1955 MUTEX_UNLOCK (&cn_mutex);
1957 if (n && !segv)
1959 pthread_t tid;
1961 rc = create_thread (waiting_for_exit, NULL, &tid, 0);
1962 if (!rc)
1964 if (signal_loop (sigset))
1966 log_write (_("Received second termination request. Exiting."));
1967 #ifdef HAVE_PTHREAD_CANCEL
1968 pthread_cancel (tid);
1969 #else
1970 pthread_kill (tid, SIGUSR2);
1971 #endif
1972 pthread_join (tid, NULL);
1975 else
1976 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1977 pwmd_strerror (rc));
1980 if (cancel_timeout_thread)
1982 #ifdef HAVE_PTHREAD_CANCEL
1983 pthread_cancel (cache_timeout_tid);
1984 #else
1985 pthread_kill (cache_timeout_tid, SIGUSR2);
1986 #endif
1987 pthread_join (cache_timeout_tid, NULL);
1990 MUTEX_LOCK (&cn_mutex);
1991 i = 0;
1992 n = slist_length (cn_thread_list);
1994 for (i = 0; i < n; i++)
1996 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
1998 if (thd->fd != -1)
2000 close (thd->fd);
2001 thd->fd = -1;
2005 exiting = 1;
2006 MUTEX_UNLOCK (&cn_mutex);
2007 #ifdef WITH_GNUTLS
2008 start_stop_tls (1);
2009 #endif
2010 cache_deinit ();
2011 deinit_commands ();
2012 pthread_cond_destroy (&quit_cond);
2013 pthread_mutex_destroy (&quit_mutex);
2014 return segv ? EXIT_FAILURE : EXIT_SUCCESS;;
2017 static void
2018 startup_failure ()
2020 log_write (_
2021 ("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
2022 cache_clear (NULL);
2025 /* This is called from cache.c:clear_once(). See
2026 * command.c:clearcache_command() for details about lock checking.
2028 static gpg_error_t
2029 free_cache_data (file_cache_t * cache)
2031 gpg_error_t rc = GPG_ERR_NO_DATA;
2032 int i, t;
2033 struct client_thread_s *found = NULL;
2034 int self = 0;
2036 if (!cache->data)
2037 return 0;
2039 cache_lock ();
2040 MUTEX_LOCK (&cn_mutex);
2041 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
2042 t = slist_length (cn_thread_list);
2044 for (i = 0; i < t; i++)
2046 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2048 if (!thd->cl)
2049 continue;
2051 if (!memcmp (thd->cl->md5file, cache->filename,
2052 sizeof (cache->filename)))
2054 if (pthread_equal (pthread_self (), thd->tid))
2056 found = thd;
2057 self = 1;
2058 continue;
2061 /* Continue trying to find a client who has the same file open and
2062 * also has a lock. */
2063 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0, -1);
2064 if (!rc)
2066 self = 0;
2067 found = thd;
2068 break;
2073 if (self && (!rc || rc == GPG_ERR_NO_DATA))
2074 rc = cache_lock_mutex (found->cl->ctx, found->cl->md5file, -1, 0, -1);
2076 if (exiting || !rc || rc == GPG_ERR_NO_DATA)
2078 free_cache_data_once (cache->data);
2079 cache->data = NULL;
2080 cache->defer_clear = 0;
2081 cache->timeout = -1;
2083 if (found)
2084 cache_unlock_mutex (found->cl->md5file, 0);
2086 rc = 0;
2089 if (rc)
2090 cache->defer_clear = 1;
2092 pthread_cleanup_pop (1);
2093 cache_unlock ();
2094 return rc;
2097 static int
2098 convert_v2_datafile (const char *filename, const char *cipher,
2099 const char *keyfile, const char *keygrip,
2100 const char *sign_keygrip, int nopass,
2101 const char *outfile, const char *keyparam,
2102 unsigned long s2k_count, uint64_t iterations)
2104 gpg_error_t rc;
2105 void *data = NULL;
2106 size_t datalen;
2107 struct crypto_s *crypto = NULL;
2108 uint16_t ver;
2109 int algo;
2110 void *key = NULL;
2111 size_t keylen = 0;
2113 if (outfile[0] == '-' && outfile[1] == 0)
2114 outfile = NULL;
2116 log_write (_("Converting version 2 data file \"%s\" ..."), filename);
2117 if (access (filename, R_OK) == -1)
2119 log_write ("%s: %s", filename,
2120 pwmd_strerror (gpg_error_from_syserror ()));
2121 return 0;
2124 if (keyfile)
2126 log_write (_("Using passphrase file \"%s\" for decryption ..."),
2127 keyfile);
2128 if (access (keyfile, R_OK) == -1)
2130 log_write ("%s: %s", keyfile,
2131 pwmd_strerror (gpg_error_from_syserror ()));
2132 return 0;
2136 rc = read_v2_datafile (filename, keyfile, &data, &datalen, &ver, &algo);
2137 if (rc)
2139 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2140 return 0;
2143 if (cipher)
2145 algo = cipher_string_to_gcrypt (cipher);
2146 if (algo == -1)
2148 rc = GPG_ERR_CIPHER_ALGO;
2149 goto fail;
2153 if (ver < 0x212)
2155 xmlDocPtr doc = parse_doc (data, datalen);
2157 if (!doc)
2159 rc = GPG_ERR_BAD_DATA;
2160 goto fail;
2163 rc = convert_pre_212_elements (doc);
2164 gcry_free (data);
2165 data = NULL;
2166 if (!rc)
2168 xmlDocDumpFormatMemory (doc, (xmlChar **) & data, (int *) &datalen,
2170 if (!data)
2171 rc = GPG_ERR_ENOMEM;
2174 xmlFreeDoc (doc);
2175 if (rc)
2176 goto fail;
2179 rc = init_client_crypto (&crypto);
2180 if (!rc)
2182 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
2183 crypto->save.hdr.flags = set_cipher_flag (crypto->save.hdr.flags, algo);
2184 crypto->save.s2k_count = s2k_count;
2185 crypto->save.hdr.iterations = iterations;
2187 #ifdef WITH_AGENT
2188 if (use_agent)
2190 rc = agent_set_pinentry_options (crypto->agent);
2191 if (!rc)
2192 rc = agent_export_common (crypto, keygrip, sign_keygrip, nopass,
2193 data, datalen, outfile, keyparam,
2194 no_passphrase_file ? NULL : keyfile);
2196 else
2197 rc = export_common (NULL, crypto, nopass, data, datalen, outfile,
2198 keyfile, &key, &keylen, 1, 0);
2199 #else
2200 rc = export_common (NULL, crypto, nopass, data, datalen, outfile,
2201 keyfile, &key, &keylen, 1, 0);
2202 #endif
2203 if (!rc)
2204 log_write (_("Output written to \"%s\"."), outfile);
2207 fail:
2208 if (ver < 0x212)
2209 xmlFree (data);
2210 else
2211 gcry_free (data);
2213 gcry_free (key);
2214 cleanup_crypto (&crypto);
2216 if (rc)
2217 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2218 return rc ? 0 : 1;
2221 static void
2222 usage (const char *pn, int status)
2224 FILE *fp = status == EXIT_FAILURE ? stderr : stdout;
2226 fprintf (fp, _("Usage: %s [OPTIONS] [file1] [...]\n"
2227 " -f, --rcfile=filename load the specfied configuration file\n"
2228 " (~/.pwmd/config)\n"
2229 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2230 #ifdef WITH_AGENT
2231 " --no-agent disable use of gpg-agent\n"
2232 #endif
2233 " -n, --no-fork run as a foreground process\n"
2234 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2235 " --ignore ignore file errors during startup\n"
2236 " --debug-level=keywords log protocol output (see manual for details)\n"
2237 " -o, --outfile=filename output file when importing or converting\n"
2238 " -C, --convert=filename convert a version 2 data file to version 3\n"
2239 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2240 " -k, --passphrase-file=file for use when importing or converting\n"
2241 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2242 " converting\n"
2243 " --no-passphrase when importing or converting\n"
2244 " --keygrip=hex public key to use when encrypting\n"
2245 " --sign-keygrip=hex private key to use when signing\n"
2246 " --keyparam=s-exp custom key parameters to use (RSA-2048)\n"
2247 " --cipher=string encryption cipher (aes256)\n"
2248 " --iterations=N cipher iteration count (N+1)\n"
2249 " --s2k-count=N hash iteration count (>65536, calibrated)\n"
2250 " --help this help text\n"
2251 " --version show version and compile time features\n"),
2252 pn);
2253 exit (status);
2257 main (int argc, char *argv[])
2259 int opt;
2260 struct sockaddr_un addr;
2261 char buf[PATH_MAX];
2262 char *socketpath = NULL, *socketdir, *socketname = NULL;
2263 char *socketarg = NULL;
2264 char *datadir = NULL;
2265 int x;
2266 char *p;
2267 char **cache_push = NULL;
2268 char *import = NULL, *keygrip = NULL, *sign_keygrip = NULL;
2269 char *keyparam = NULL;
2270 int estatus = EXIT_FAILURE;
2271 int sockfd;
2272 char *outfile = NULL;
2273 int do_unlink = 0;
2274 int secure = 0;
2275 int show_version = 0;
2276 int force = 0;
2277 int no_passphrase = 0;
2278 gpg_error_t rc;
2279 char *convertfile = NULL;
2280 char *cipher = NULL;
2281 char *keyfile = NULL;
2282 unsigned long s2k_count = 0;
2283 uint64_t iterations = 0;
2284 int exists;
2285 char *debug_level_opt = NULL;
2286 int optindex;
2287 /* Must maintain the same order as longopts[] */
2288 enum
2289 { OPT_VERSION, OPT_HELP,
2290 #ifdef WITH_AGENT
2291 OPT_NO_AGENT,
2292 #endif
2293 OPT_DEBUG_LEVEL, OPT_HOMEDIR, OPT_NO_FORK, OPT_DISABLE_DUMP, OPT_IGNORE,
2294 OPT_RCFILE, OPT_CONVERT, OPT_PASSPHRASE_FILE, OPT_IMPORT, OPT_OUTFILE,
2295 OPT_NO_PASSPHRASE_FILE, OPT_KEYGRIP, OPT_SIGN_KEYGRIP, OPT_KEYPARAM,
2296 OPT_CIPHER, OPT_ITERATIONS, OPT_S2K_COUNT, OPT_NO_PASSPHRASE
2298 const char *optstring = "nf:C:k:I:o:";
2299 const struct option longopts[] = {
2300 {"version", no_argument, 0, 0},
2301 {"help", no_argument, 0, 0},
2302 #ifdef WITH_AGENT
2303 {"no-agent", no_argument, 0, 0},
2304 #endif
2305 {"debug-level", required_argument, 0, 0},
2306 {"homedir", required_argument, 0, 0},
2307 {"no-fork", no_argument, 0, 'n'},
2308 {"disable_dump", no_argument, 0, 0},
2309 {"ignore", no_argument, 0, 0},
2310 {"rcfile", required_argument, 0, 'f'},
2311 {"convert", required_argument, 0, 'C'},
2312 {"passphrase-file", required_argument, 0, 'k'},
2313 {"import", required_argument, 0, 'I'},
2314 {"outfile", required_argument, 0, 'o'},
2315 {"no-passphrase-file", no_argument, 0, 0},
2316 {"keygrip", required_argument, 0, 0},
2317 {"sign-keygrip", required_argument, 0, 0},
2318 {"keyparam", required_argument, 0, 0},
2319 {"cipher", required_argument, 0, 0},
2320 {"cipher-iterations", required_argument, 0, 0},
2321 {"s2k-count", required_argument, 0, 0},
2322 {"no-passphrase", no_argument, 0, 0},
2323 {0, 0, 0, 0}
2326 #ifndef DEBUG
2327 #ifdef HAVE_SETRLIMIT
2328 struct rlimit rl;
2330 rl.rlim_cur = rl.rlim_max = 0;
2332 if (setrlimit (RLIMIT_CORE, &rl) != 0)
2333 err (EXIT_FAILURE, "setrlimit()");
2334 #endif
2335 #endif
2337 #ifdef ENABLE_NLS
2338 setlocale (LC_ALL, "");
2339 bindtextdomain ("pwmd", LOCALEDIR);
2340 textdomain ("pwmd");
2341 #endif
2343 #ifndef MEM_DEBUG
2344 xmem_init ();
2345 #endif
2346 gpg_err_init ();
2348 if (setup_crypto ())
2349 exit (EXIT_FAILURE);
2351 #ifdef WITH_GNUTLS
2352 gnutls_global_set_mem_functions (xmalloc, xmalloc, secure_mem_check,
2353 xrealloc, xfree);
2354 gnutls_global_init ();
2355 gnutls_global_set_log_function (tls_log);
2356 gnutls_global_set_log_level (1);
2357 tls_fd = -1;
2358 tls6_fd = -1;
2359 #endif
2360 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
2361 xmlInitMemory ();
2362 xmlInitGlobals ();
2363 xmlInitParser ();
2364 xmlXPathInit ();
2365 cmdline = 1;
2366 #ifdef WITH_AGENT
2367 use_agent = 1;
2368 #endif
2370 while ((opt =
2371 getopt_long (argc, argv, optstring, longopts, &optindex)) != -1)
2373 switch (opt)
2375 case 'I':
2376 import = optarg;
2377 break;
2378 case 'C':
2379 convertfile = optarg;
2380 break;
2381 case 'k':
2382 keyfile = optarg;
2383 break;
2384 case 'o':
2385 outfile = optarg;
2386 break;
2387 case 'D':
2388 secure = 1;
2389 break;
2390 case 'n':
2391 nofork = 1;
2392 break;
2393 case 'f':
2394 rcfile = str_dup (optarg);
2395 break;
2396 default:
2397 usage (argv[0], EXIT_FAILURE);
2398 break;
2399 case 0:
2400 switch (optindex)
2402 case OPT_VERSION:
2403 show_version = 1;
2404 break;
2405 case OPT_HELP:
2406 usage (argv[0], 0);
2407 break;
2408 #ifdef WITH_AGENT
2409 case OPT_NO_AGENT:
2410 use_agent = 0;
2411 break;
2412 #endif
2413 case OPT_DEBUG_LEVEL:
2414 debug_level_opt = optarg;
2415 break;
2416 case OPT_HOMEDIR:
2417 homedir = str_dup (optarg);
2418 break;
2419 case OPT_NO_FORK:
2420 nofork = 1;
2421 break;
2422 case OPT_DISABLE_DUMP:
2423 secure = 1;
2424 break;
2425 case OPT_IGNORE:
2426 force = 1;
2427 break;
2428 case OPT_RCFILE:
2429 rcfile = str_dup (optarg);
2430 break;
2431 case OPT_CONVERT:
2432 convertfile = optarg;
2433 break;
2434 case OPT_PASSPHRASE_FILE:
2435 keyfile = optarg;
2436 break;
2437 case OPT_IMPORT:
2438 import = optarg;
2439 break;
2440 case OPT_OUTFILE:
2441 outfile = optarg;
2442 break;
2443 case OPT_NO_PASSPHRASE_FILE:
2444 no_passphrase_file = 1;
2445 break;
2446 case OPT_KEYGRIP:
2447 keygrip = optarg;
2448 break;
2449 case OPT_SIGN_KEYGRIP:
2450 sign_keygrip = optarg;
2451 break;
2452 case OPT_KEYPARAM:
2453 keyparam = optarg;
2454 break;
2455 case OPT_CIPHER:
2456 cipher = optarg;
2457 break;
2458 case OPT_ITERATIONS:
2459 iterations = strtoull (optarg, NULL, 10);
2460 break;
2461 case OPT_S2K_COUNT:
2462 s2k_count = strtoul (optarg, NULL, 10);
2463 break;
2464 case OPT_NO_PASSPHRASE:
2465 no_passphrase = 1;
2466 break;
2467 default:
2468 usage (argv[0], 1);
2473 if (show_version)
2475 printf (_("%s\n\n"
2476 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012\n"
2477 "%s\n"
2478 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2479 "Compile time features:\n%s"), PACKAGE_STRING,
2480 PACKAGE_BUGREPORT,
2481 #ifdef PWMD_HOMEDIR
2482 "+PWMD_HOMEDIR=" PWMD_HOMEDIR "\n"
2483 #endif
2484 #ifdef WITH_AGENT
2485 "+WITH_AGENT\n"
2486 #else
2487 "-WITH_AGENT\n"
2488 #endif
2489 #ifdef WITH_GNUTLS
2490 "+WITH_GNUTLS\n"
2491 #else
2492 "-WITH_GNUTLS\n"
2493 #endif
2494 #ifdef WITH_LIBACL
2495 "+WITH_LIBACL\n"
2496 #else
2497 "-WITH_LIBACL\n"
2498 #endif
2499 #ifdef DEBUG
2500 "+DEBUG\n"
2501 #else
2502 "-DEBUG\n"
2503 #endif
2504 #ifdef MEM_DEBUG
2505 "+MEM_DEBUG\n"
2506 #else
2507 "-MEM_DEBUG\n"
2508 #endif
2509 #ifdef MUTEX_DEBUG
2510 "+MUTEX_DEBUG\n"
2511 #else
2512 "-MUTEX_DEBUG\n"
2513 #endif
2515 exit (EXIT_SUCCESS);
2518 if (!homedir)
2519 #ifdef PWMD_HOMEDIR
2520 homedir = str_dup(PWMD_HOMEDIR);
2521 #else
2522 homedir = str_asprintf ("%s/.pwmd", get_home_dir ());
2523 #endif
2525 if (mkdir (homedir, 0700) == -1 && errno != EEXIST)
2526 err (EXIT_FAILURE, "%s", homedir);
2528 snprintf (buf, sizeof (buf), "%s/data", homedir);
2529 if (mkdir (buf, 0700) == -1 && errno != EEXIST)
2530 err (EXIT_FAILURE, "%s", buf);
2532 datadir = str_dup (buf);
2533 pthread_mutexattr_t attr;
2534 pthread_mutexattr_init (&attr);
2535 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
2536 pthread_mutex_init (&rcfile_mutex, &attr);
2537 pthread_cond_init (&rcfile_cond, NULL);
2538 pthread_mutex_init (&cn_mutex, &attr);
2539 pthread_mutexattr_destroy (&attr);
2540 pthread_key_create (&last_error_key, free_key);
2541 #ifndef HAVE_PTHREAD_CANCEL
2542 pthread_key_create (&signal_thread_key, free_key);
2543 #endif
2545 if (!rcfile)
2546 rcfile = str_asprintf ("%s/config", homedir);
2548 global_config = config_parse (rcfile);
2549 if (!global_config)
2550 exit (EXIT_FAILURE);
2552 setup_logging ();
2554 if (debug_level_opt)
2555 debug_level = str_split (debug_level_opt, ",", 0);
2557 x = config_get_int_param (global_config, "global", "priority", &exists);
2558 if (exists && x != atoi(INVALID_PRIORITY))
2560 errno = 0;
2561 if (setpriority (PRIO_PROCESS, 0, x) == -1)
2563 log_write ("setpriority(): %s",
2564 pwmd_strerror (gpg_error_from_syserror ()));
2565 goto do_exit;
2568 #ifdef HAVE_MLOCKALL
2569 if (disable_mlock == 0 && mlockall (MCL_CURRENT | MCL_FUTURE) == -1)
2571 log_write ("mlockall(): %s",
2572 pwmd_strerror (gpg_error_from_syserror ()));
2573 goto do_exit;
2575 #endif
2577 rc = cache_init (free_cache_data);
2578 if (rc)
2580 log_write ("pwmd: ERR %i: %s", rc,
2581 gpg_err_code (rc) == GPG_ERR_UNKNOWN_VERSION
2582 ? _("incompatible version: 2.1.0 or later required")
2583 : pwmd_strerror (rc));
2584 goto do_exit;
2587 if (s2k_count == 0)
2588 s2k_count = config_get_ulong (NULL, "s2k_count");
2590 if (convertfile)
2592 if (!outfile)
2593 usage (argv[0], EXIT_FAILURE);
2595 estatus = convert_v2_datafile (convertfile, cipher, keyfile, keygrip,
2596 sign_keygrip, no_passphrase, outfile,
2597 keyparam, s2k_count, iterations);
2598 config_free (global_config);
2599 xfree (rcfile);
2600 exit (!estatus);
2603 if (import)
2605 if (!outfile)
2606 usage (argv[0], EXIT_FAILURE);
2608 if (outfile[0] == '-' && outfile[1] == 0)
2609 outfile = NULL;
2611 estatus = xml_import (import, outfile, keygrip, sign_keygrip, keyfile,
2612 no_passphrase, cipher, keyparam, s2k_count,
2613 iterations);
2614 config_free (global_config);
2615 xfree (rcfile);
2616 exit (!estatus);
2619 p = config_get_string ("global", "socket_path");
2620 if (!p)
2621 p = str_asprintf ("%s/socket", homedir);
2623 socketarg = expand_homedir (p);
2624 xfree (p);
2626 if (!secure)
2627 disable_list_and_dump = config_get_boolean ("global",
2628 "disable_list_and_dump");
2629 else
2630 disable_list_and_dump = secure;
2632 cache_push = config_get_list ("global", "cache_push");
2634 while (optind < argc)
2636 if (strv_printf (&cache_push, "%s", argv[optind++]) == 0)
2637 errx (EXIT_FAILURE, "%s", pwmd_strerror (GPG_ERR_ENOMEM));
2640 if (strchr (socketarg, '/') == NULL)
2642 socketdir = getcwd (buf, sizeof (buf));
2643 socketname = str_dup (socketarg);
2644 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2646 else
2648 socketname = str_dup (strrchr (socketarg, '/'));
2649 socketname++;
2650 socketarg[strlen (socketarg) - strlen (socketname) - 1] = 0;
2651 socketdir = str_dup (socketarg);
2652 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2655 if (chdir (datadir))
2657 log_write ("%s: %s", datadir,
2658 pwmd_strerror (gpg_error_from_syserror ()));
2659 unlink (socketpath);
2660 goto do_exit;
2664 * Set the cache entry for a file. Prompts for the password.
2666 if (cache_push)
2668 struct crypto_s *crypto;
2669 gpg_error_t rc = init_client_crypto (&crypto);
2671 if (rc)
2673 estatus = EXIT_FAILURE;
2674 goto do_exit;
2677 #ifdef WITH_AGENT
2678 if (use_agent)
2680 rc = agent_set_pinentry_options (crypto->agent);
2681 if (rc)
2683 estatus = EXIT_FAILURE;
2684 goto do_exit;
2687 #endif
2689 for (opt = 0; cache_push[opt]; opt++)
2691 if (!do_cache_push (cache_push[opt], crypto) && !force)
2693 strv_free (cache_push);
2694 startup_failure ();
2695 estatus = EXIT_FAILURE;
2696 cleanup_crypto (&crypto);
2697 goto do_exit;
2700 cleanup_crypto_stage1 (crypto);
2703 #ifdef WITH_AGENT
2704 if (use_agent)
2705 (void) kill_scd (crypto->agent);
2706 #endif
2708 cleanup_crypto (&crypto);
2709 strv_free (cache_push);
2710 log_write (!nofork ? _("Done. Daemonizing...") :
2711 _("Done. Waiting for connections..."));
2714 config_clear_keys ();
2717 * bind() doesn't like the full pathname of the socket or any non alphanum
2718 * characters so change to the directory where the socket is wanted then
2719 * create it then change to datadir.
2721 if (chdir (socketdir))
2723 log_write ("%s: %s", socketdir,
2724 pwmd_strerror (gpg_error_from_syserror ()));
2725 goto do_exit;
2728 xfree (socketdir);
2730 if ((sockfd = socket (PF_UNIX, SOCK_STREAM, 0)) == -1)
2732 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_syserror ()));
2733 goto do_exit;
2736 addr.sun_family = AF_UNIX;
2737 snprintf (addr.sun_path, sizeof (addr.sun_path), "%s", socketname);
2739 if (bind (sockfd, (struct sockaddr *) &addr, sizeof (struct sockaddr)) ==
2742 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_syserror ()));
2744 if (errno == EADDRINUSE)
2745 log_write (_("Either there is another pwmd running or '%s' is a \n"
2746 "stale socket. Please remove it manually."), socketpath);
2748 goto do_exit;
2751 do_unlink = 1;
2753 char *t = config_get_string ("global", "socket_perms");
2754 mode_t mode;
2755 mode_t mask;
2757 if (t)
2759 mode = strtol (t, NULL, 8);
2760 mask = umask (0);
2761 xfree (t);
2763 if (chmod (socketname, mode) == -1)
2765 log_write ("%s: %s", socketname,
2766 pwmd_strerror (gpg_error_from_syserror ()));
2767 close (sockfd);
2768 unlink (socketpath);
2769 umask (mask);
2770 goto do_exit;
2773 umask (mask);
2777 xfree (--socketname);
2779 if (chdir (datadir))
2781 log_write ("%s: %s", datadir,
2782 pwmd_strerror (gpg_error_from_syserror ()));
2783 close (sockfd);
2784 unlink (socketpath);
2785 goto do_exit;
2788 xfree (datadir);
2790 if (listen (sockfd, 0) == -1)
2792 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_syserror ()));
2793 goto do_exit;
2796 cmdline = 0;
2798 if (!nofork)
2800 switch (fork ())
2802 case -1:
2803 log_write ("fork(): %s",
2804 pwmd_strerror (gpg_error_from_syserror ()));
2805 goto do_exit;
2806 case 0:
2807 close (0);
2808 close (1);
2809 close (2);
2810 setsid ();
2811 break;
2812 default:
2813 _exit (EXIT_SUCCESS);
2817 pthread_key_create (&thread_name_key, free_key);
2818 pthread_setspecific (thread_name_key, str_dup ("main"));
2819 estatus = server_loop (sockfd, &socketpath);
2821 do_exit:
2822 if (socketpath && do_unlink)
2824 unlink (socketpath);
2825 xfree (socketpath);
2828 xfree (socketarg);
2829 #ifdef WITH_GNUTLS
2830 gnutls_global_deinit ();
2831 #endif
2832 if (rcfile_tid)
2834 #ifdef HAVE_PTHREAD_CANCEL
2835 pthread_cancel (rcfile_tid);
2836 #else
2837 pthread_kill (rcfile_tid, SIGUSR2);
2838 pthread_cond_signal (&rcfile_cond);
2839 #endif
2840 pthread_join (rcfile_tid, NULL);
2843 pthread_cond_destroy (&rcfile_cond);
2844 pthread_mutex_destroy (&rcfile_mutex);
2845 pthread_key_delete (last_error_key);
2846 pthread_key_delete (thread_name_key);
2847 #ifndef HAVE_PTHREAD_CANCEL
2848 pthread_key_delete (signal_thread_key);
2849 #endif
2851 if (global_config)
2852 config_free (global_config);
2854 xfree (rcfile);
2855 xfree (home_directory);
2856 xfree (homedir);
2857 xmlCleanupParser ();
2858 xmlCleanupGlobals ();
2860 if (estatus == EXIT_SUCCESS)
2861 log_write (_("pwmd exiting normally"));
2863 closelog ();
2864 #if defined(DEBUG) && !defined(MEM_DEBUG)
2865 xdump ();
2866 #endif
2867 exit (estatus);