Add and rename pinentry OPTION's.
[pwmd.git] / src / pwmd.c
blob18815e8893b9985e6d9bb7cedb7266c575d2a4b6
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 "util-misc.h"
77 #include "mem.h"
78 #include "xml.h"
79 #include "common.h"
80 #include "commands.h"
81 #include "cache.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);
884 pinentry_free_opts (&cl->pinentry_opts);
885 xfree (cl);
887 else
889 if (cn->fd != -1)
890 close (cn->fd);
893 while (cn->msg_queue)
895 struct status_msg_s *msg = cn->msg_queue;
897 cn->msg_queue = msg->next;
898 xfree (msg->line);
899 xfree (msg);
902 if (cn->status_msg_pipe[0] != -1)
903 close (cn->status_msg_pipe[0]);
905 if (cn->status_msg_pipe[1] != -1)
906 close (cn->status_msg_pipe[1]);
908 pthread_mutex_destroy (&cn->status_mutex);
909 log_write (_("exiting, fd=%i"), cn->fd);
910 xfree (cn);
911 send_status_all (STATUS_CLIENTS, NULL);
912 pthread_cond_signal (&quit_cond);
915 static gpg_error_t
916 send_msg_queue (struct client_thread_s *thd)
918 MUTEX_LOCK (&thd->status_mutex);
919 gpg_error_t rc = 0;
920 char c;
922 read (thd->status_msg_pipe[0], &c, 1);
924 while (thd->msg_queue)
926 struct status_msg_s *msg = thd->msg_queue;
928 thd->msg_queue = thd->msg_queue->next;
929 MUTEX_UNLOCK (&thd->status_mutex);
930 rc = send_status (thd->cl->ctx, msg->s, msg->line);
931 MUTEX_LOCK (&thd->status_mutex);
932 xfree (msg->line);
933 xfree (msg);
935 if (rc)
936 break;
939 MUTEX_UNLOCK (&thd->status_mutex);
940 return rc;
943 static void *
944 client_thread (void *data)
946 struct client_thread_s *thd = data;
947 struct client_s *cl = xcalloc (1, sizeof (struct client_s));
949 #ifdef HAVE_PR_SET_NAME
950 prctl (PR_SET_NAME, "client");
951 #endif
952 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
954 if (!cl)
956 log_write ("%s(%i): %s", __FILE__, __LINE__,
957 pwmd_strerror (GPG_ERR_ENOMEM));
958 return NULL;
961 MUTEX_LOCK (&cn_mutex);
962 pthread_cleanup_push (cleanup_cb, thd);
963 thd->cl = cl;
964 cl->thd = thd;
965 MUTEX_UNLOCK (&cn_mutex);
967 if (new_connection (cl))
969 int finished = 0;
970 gpg_error_t rc;
972 send_status_all (STATUS_CLIENTS, NULL);
973 rc = send_status (cl->ctx, STATUS_CACHE, NULL);
974 if (rc)
976 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
977 finished = 1;
980 while (!finished)
982 fd_set rfds;
983 int n;
984 int eof;
986 FD_ZERO (&rfds);
987 FD_SET (thd->fd, &rfds);
988 FD_SET (thd->status_msg_pipe[0], &rfds);
990 thd->fd >
991 thd->status_msg_pipe[0] ? thd->fd : thd->status_msg_pipe[0];
993 n = select (n + 1, &rfds, NULL, NULL, NULL);
994 if (n == -1)
996 log_write ("%s", strerror (errno));
997 break;
1000 if (FD_ISSET (thd->status_msg_pipe[0], &rfds))
1002 rc = send_msg_queue (thd);
1003 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1005 log_write ("%s(%i): %s", __FUNCTION__, __LINE__,
1006 pwmd_strerror (rc));
1007 break;
1011 if (!FD_ISSET (thd->fd, &rfds))
1012 continue;
1014 rc = assuan_process_next (cl->ctx, &eof);
1015 if (rc || eof)
1017 if (gpg_err_code (rc) == GPG_ERR_EOF || eof)
1018 break;
1020 log_write ("assuan_process_next(): %s", pwmd_strerror (rc));
1021 rc = send_error (cl->ctx, rc);
1023 if (rc)
1025 log_write ("assuan_process_done(): %s", pwmd_strerror (rc));
1026 break;
1030 /* Since the msg queue pipe fd's are non-blocking, check for
1031 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1032 * client has already disconnected and will be converted to
1033 * GPG_ERR_EOF during assuan_process_next().
1035 rc = send_msg_queue (thd);
1036 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1038 log_write ("%s(%i): %s", __FUNCTION__, __LINE__,
1039 pwmd_strerror (rc));
1040 break;
1045 pthread_cleanup_pop (1);
1046 return NULL;
1049 static int
1050 xml_import (const char *filename, const char *outfile,
1051 const char *keygrip, const char *sign_keygrip,
1052 const char *keyfile, int no_passphrase, const char *cipher,
1053 const char *params, unsigned long s2k_count, uint64_t iterations)
1055 xmlDocPtr doc;
1056 int fd;
1057 struct stat st;
1058 int len;
1059 xmlChar *xmlbuf;
1060 xmlChar *xml;
1061 gpg_error_t rc;
1062 struct crypto_s *crypto;
1063 void *key = NULL;
1064 size_t keylen = 0;
1065 int algo = cipher ? cipher_string_to_gcrypt ((char *) cipher) :
1066 GCRY_CIPHER_AES256;
1068 if (algo == -1)
1070 log_write ("ERR %i: %s", gpg_error (GPG_ERR_CIPHER_ALGO),
1071 pwmd_strerror (GPG_ERR_CIPHER_ALGO));
1072 return 0;
1075 if (stat (filename, &st) == -1)
1077 log_write ("%s: %s", filename,
1078 pwmd_strerror (gpg_error_from_syserror ()));
1079 return 0;
1082 rc = init_client_crypto (&crypto);
1083 if (rc)
1084 return 0;
1086 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
1087 crypto->save.hdr.flags = set_cipher_flag (crypto->save.hdr.flags, algo);
1088 log_write (_("Importing XML from '%s'. Output will be written to '%s' ..."),
1089 filename, outfile);
1091 if ((fd = open (filename, O_RDONLY)) == -1)
1093 log_write ("%s: %s", filename,
1094 pwmd_strerror (gpg_error_from_syserror ()));
1095 goto fail;
1098 if ((xmlbuf = xmalloc (st.st_size + 1)) == NULL)
1100 close (fd);
1101 log_write ("%s(%i): %s", __FILE__, __LINE__,
1102 pwmd_strerror (GPG_ERR_ENOMEM));
1103 goto fail;
1106 if (read (fd, xmlbuf, st.st_size) == -1)
1108 rc = gpg_error_from_syserror ();
1109 close (fd);
1110 log_write ("%s: %s", filename, pwmd_strerror (rc));
1111 goto fail;
1114 close (fd);
1115 xmlbuf[st.st_size] = 0;
1117 * Make sure the document validates.
1119 if ((doc = xmlReadDoc (xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS)) == NULL)
1121 log_write ("xmlReadDoc() failed");
1122 xfree (xmlbuf);
1123 goto fail;
1126 xfree (xmlbuf);
1127 xmlNodePtr n = xmlDocGetRootElement (doc);
1128 if (!xmlStrEqual (n->name, (xmlChar *) "pwmd"))
1130 log_write (_("Could not find root \"pwmd\" element."));
1131 rc = GPG_ERR_BAD_DATA;
1134 if (!rc)
1135 rc = validate_import (n ? n->children : n);
1137 if (rc)
1139 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1140 xmlFreeDoc (doc);
1141 goto fail;
1144 xmlDocDumpMemory (doc, &xml, &len);
1145 xmlFreeDoc (doc);
1146 crypto->save.s2k_count = s2k_count;
1147 crypto->save.hdr.iterations = iterations;
1148 if (!use_agent)
1150 rc = export_common (NULL, 0, crypto, xml, len, outfile, keyfile, &key,
1151 &keylen, 0, 0);
1152 if (!rc)
1153 log_write (_("Success!"));
1155 #ifdef WITH_AGENT
1156 else
1158 rc = agent_set_pinentry_options (crypto->agent);
1159 if (!rc)
1160 rc = agent_export_common (crypto, keygrip, sign_keygrip, no_passphrase,
1161 xml, len, outfile, params, keyfile);
1163 #endif
1165 gcry_free (key);
1166 xmlFree (xml);
1167 if (rc)
1169 send_error (NULL, rc);
1170 goto fail;
1173 cleanup_crypto (&crypto);
1174 return 1;
1176 fail:
1177 cleanup_crypto (&crypto);
1178 return 0;
1181 static int
1182 do_cache_push (const char *filename, struct crypto_s *crypto)
1184 unsigned char md5file[16];
1185 gpg_error_t rc;
1186 char *key = NULL;
1187 size_t keylen = 0;
1188 xmlDocPtr doc;
1189 struct cache_data_s *cdata;
1190 unsigned char *crc;
1191 size_t len;
1193 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1194 filename);
1196 if (valid_filename (filename) == 0)
1198 log_write (_("%s: Invalid characters in filename"), filename);
1199 return 0;
1202 rc = decrypt_common (NULL, 0, crypto, filename, &key, &keylen);
1203 if (rc)
1204 return 0;
1206 doc = parse_doc ((char *) crypto->plaintext, crypto->plaintext_len);
1207 if (!doc)
1209 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM));
1210 xfree (key);
1211 return 0;
1214 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
1215 cdata = xcalloc (1, sizeof (struct cache_data_s));
1216 if (!cdata)
1218 xmlFreeDoc (doc);
1219 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM));
1220 xfree (key);
1221 return 0;
1224 rc = get_checksum (filename, &crc, &len);
1225 if (rc)
1227 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1228 xmlFreeDoc (doc);
1229 free_cache_data_once (cdata);
1230 xfree (key);
1231 return 0;
1234 cdata->crc = crc;
1235 rc = encrypt_xml (NULL, cache_key, cache_keysize, GCRY_CIPHER_AES,
1236 crypto->plaintext, crypto->plaintext_len, &cdata->doc,
1237 &cdata->doclen, &cache_iv, &cache_blocksize, 0);
1238 if (!rc && !IS_PKCS (crypto))
1240 cdata->key = key;
1241 cdata->keylen = keylen;
1243 else
1244 xfree (key);
1246 if (rc)
1248 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1249 xmlFreeDoc (doc);
1250 free_cache_data_once (cdata);
1251 return 0;
1254 #ifdef WITH_AGENT
1255 if (use_agent)
1257 gcry_sexp_build ((gcry_sexp_t *) & cdata->pubkey, NULL, "%S",
1258 crypto->pkey_sexp);
1259 gcry_sexp_build ((gcry_sexp_t *) & cdata->sigkey, NULL, "%S",
1260 crypto->sigpkey_sexp);
1262 #endif
1264 int timeout = config_get_integer (filename, "cache_timeout");
1265 cache_add_file (md5file, crypto->grip, cdata, timeout);
1266 log_write (_("Successfully added '%s' to the cache."), filename);
1267 return 1;
1270 static gpg_error_t
1271 init_client (int fd, const char *addr)
1273 gpg_error_t rc = 0;
1274 struct client_thread_s *new = xcalloc (1, sizeof (struct client_thread_s));
1276 if (!new)
1278 close (fd);
1279 return GPG_ERR_ENOMEM;
1282 MUTEX_LOCK (&cn_mutex);
1283 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
1285 if (pipe (new->status_msg_pipe) == -1)
1286 rc = gpg_error_from_syserror ();
1288 if (!rc)
1290 fcntl (new->status_msg_pipe[0], F_SETFL, O_NONBLOCK);
1291 fcntl (new->status_msg_pipe[1], F_SETFL, O_NONBLOCK);
1292 pthread_mutex_init (&new->status_mutex, NULL);
1295 if (!rc)
1297 #ifdef WITH_GNUTLS
1298 new->remote = addr ? 1 : 0;
1299 #endif
1300 new->fd = fd;
1301 rc = create_thread (client_thread, new, &new->tid, 1);
1302 if (rc)
1304 close (new->status_msg_pipe[0]);
1305 close (new->status_msg_pipe[1]);
1306 pthread_mutex_destroy (&new->status_mutex);
1310 if (!rc)
1312 struct slist_s *list = slist_append (cn_thread_list, new);
1314 if (list)
1316 cn_thread_list = list;
1317 if (addr)
1318 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1319 (pthread_t *) new->tid, fd, addr);
1320 else
1321 log_write (_("new connection: tid=%p, fd=%i"),
1322 (pthread_t *) new->tid, fd);
1324 else
1325 rc = GPG_ERR_ENOMEM;
1328 pthread_cleanup_pop (1);
1330 if (rc)
1332 xfree (new);
1333 close (fd);
1334 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1335 pwmd_strerror (rc));
1337 return rc;
1340 #ifdef WITH_GNUTLS
1341 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1342 static void *
1343 get_in_addr (struct sockaddr *sa)
1345 if (sa->sa_family == AF_INET)
1346 return &(((struct sockaddr_in *) sa)->sin_addr);
1348 return &(((struct sockaddr_in6 *) sa)->sin6_addr);
1351 static void *
1352 tcp_accept_thread (void *arg)
1354 int sockfd = *(int *) arg;
1355 #ifndef HAVE_PTHREAD_CANCEL
1356 int *n = xmalloc (sizeof (int));
1358 *n = 0;
1359 pthread_setspecific (signal_thread_key, n);
1360 INIT_THREAD_SIGNAL;
1361 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1362 #endif
1364 #ifdef HAVE_PR_SET_NAME
1365 prctl (PR_SET_NAME, "tcp_accept");
1366 #endif
1367 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1369 for (;;)
1371 struct sockaddr_storage raddr;
1372 socklen_t slen = sizeof (raddr);
1373 int fd = -1;
1374 unsigned long n;
1375 char s[INET6_ADDRSTRLEN];
1376 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1377 #ifndef HAVE_PTHREAD_CANCEL
1378 int *sigusr2;
1380 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1381 if (*sigusr2)
1382 break;
1383 #endif
1385 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1386 if (fd == -1)
1388 if (errno == EMFILE || errno == ENFILE)
1389 log_write ("accept(): %s",
1390 pwmd_strerror (gpg_error_from_syserror ()));
1391 else if (errno != EAGAIN)
1393 if (!quit) // probably EBADF
1394 log_write ("accept(): %s", strerror (errno));
1396 break;
1399 #ifndef HAVE_PTHREAD_CANCEL
1400 select (0, NULL, NULL, NULL, &tv);
1401 #endif
1402 continue;
1405 if (quit)
1406 break;
1408 inet_ntop (raddr.ss_family, get_in_addr ((struct sockaddr *) &raddr),
1409 s, sizeof s);
1410 (void) init_client (fd, s);
1411 n = config_get_integer ("global", "tcp_wait");
1412 if (n > 0)
1414 tv.tv_sec = (n * 100000) / 100000;
1415 tv.tv_usec = (n * 100000) % 100000;
1416 select (0, NULL, NULL, NULL, &tv);
1420 return NULL;
1423 static int
1424 start_stop_tls_with_protocol (int ipv6, int term)
1426 struct addrinfo hints, *servinfo, *p;
1427 int port = config_get_integer ("global", "tcp_port");
1428 char buf[7];
1429 int n;
1430 gpg_error_t rc;
1431 int *fd = ipv6 ? &tls6_fd : &tls_fd;
1433 if (term || config_get_boolean ("global", "enable_tcp") == 0)
1435 if (tls6_fd != -1)
1437 if (spawned_tls6)
1439 #ifdef HAVE_PTHREAD_CANCEL
1440 pthread_cancel (tls6_tid);
1441 #else
1442 pthread_kill (tls6_tid, SIGUSR2);
1443 #endif
1444 pthread_join (tls6_tid, NULL);
1447 shutdown (tls6_fd, SHUT_RDWR);
1448 close (tls6_fd);
1449 tls6_fd = -1;
1450 spawned_tls6 = 0;
1453 if (tls_fd != -1)
1455 if (spawned_tls)
1457 #ifdef HAVE_PTHREAD_CANCEL
1458 pthread_cancel (tls_tid);
1459 #else
1460 pthread_kill (tls_tid, SIGUSR2);
1461 #endif
1462 pthread_join (tls_tid, NULL);
1465 shutdown (tls_fd, SHUT_RDWR);
1466 close (tls_fd);
1467 tls_fd = -1;
1468 spawned_tls = 0;
1471 /* A client may still be connected. */
1472 if (!quit && x509_cred != NULL)
1473 tls_deinit_params ();
1475 return 1;
1478 if ((ipv6 && tls6_fd != -1) || (!ipv6 && tls_fd != -1))
1479 return 1;
1481 memset (&hints, 0, sizeof (hints));
1482 hints.ai_family = ipv6 ? AF_INET6 : AF_INET;
1483 hints.ai_socktype = SOCK_STREAM;
1484 hints.ai_flags = AI_PASSIVE;
1485 snprintf (buf, sizeof (buf), "%i", port);
1487 if ((n = getaddrinfo (NULL, buf, &hints, &servinfo)) == -1)
1489 log_write ("getaddrinfo(): %s", gai_strerror (n));
1490 return 0;
1493 for (n = 0, p = servinfo; p != NULL; p = p->ai_next)
1495 int r = 1;
1497 if ((ipv6 && p->ai_family != AF_INET6)
1498 || (!ipv6 && p->ai_family != AF_INET))
1499 continue;
1501 if ((*fd = socket (p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
1503 log_write ("socket(): %s", strerror (errno));
1504 continue;
1507 if (setsockopt (*fd, SOL_SOCKET, SO_REUSEADDR, &r, sizeof (int)) == -1)
1509 log_write ("setsockopt(): %s",
1510 pwmd_strerror (gpg_error_from_syserror ()));
1511 freeaddrinfo (servinfo);
1512 goto fail;
1515 if (bind (*fd, p->ai_addr, p->ai_addrlen) == -1)
1517 close (*fd);
1518 log_write ("bind(): %s",
1519 pwmd_strerror (gpg_error_from_syserror ()));
1520 continue;
1523 n++;
1524 break;
1527 freeaddrinfo (servinfo);
1529 if (!n)
1530 goto fail;
1532 #if HAVE_DECL_SO_BINDTODEVICE != 0
1533 char *tmp = config_get_string ("global", "tcp_interface");
1534 if (tmp && setsockopt (*fd, SOL_SOCKET, SO_BINDTODEVICE, tmp, 1) == -1)
1536 log_write ("setsockopt(): %s",
1537 pwmd_strerror (gpg_error_from_syserror ()));
1538 xfree (tmp);
1539 goto fail;
1542 xfree (tmp);
1543 #endif
1545 if (x509_cred == NULL)
1547 rc = tls_init_params ();
1548 if (rc)
1549 goto fail;
1552 if (listen (*fd, 0) == -1)
1554 log_write ("listen(): %s", strerror (errno));
1555 goto fail;
1558 if (ipv6)
1559 rc = create_thread (tcp_accept_thread, fd, &tls6_tid, 0);
1560 else
1561 rc = create_thread (tcp_accept_thread, fd, &tls_tid, 0);
1563 if (rc)
1565 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1566 pwmd_strerror (rc));
1567 goto fail;
1570 if (ipv6)
1571 spawned_tls6 = 1;
1572 else
1573 spawned_tls = 1;
1575 return 1;
1577 fail:
1578 start_stop_tls_with_protocol (0, 1);
1579 if (tls_fd != -1)
1580 close (tls_fd);
1582 if (tls6_fd != -1)
1583 close (tls6_fd);
1585 tls_fd = -1;
1586 tls6_fd = -1;
1587 return 0;
1590 static int
1591 start_stop_tls (int term)
1593 char *s = config_get_string ("global", "tcp_bind");
1594 int b;
1596 if (!s)
1597 return 0;
1599 if (!strcmp (s, "any"))
1601 b = start_stop_tls_with_protocol (0, term);
1602 if (b)
1603 b = start_stop_tls_with_protocol (1, term);
1605 else if (!strcmp (s, "ipv4"))
1606 b = start_stop_tls_with_protocol (0, term);
1607 else if (!strcmp (s, "ipv6"))
1608 b = start_stop_tls_with_protocol (1, term);
1609 else
1610 b = 0;
1612 xfree (s);
1613 return b;
1615 #endif
1617 static void *
1618 accept_thread (void *arg)
1620 int sockfd = *(int *) arg;
1621 #ifndef HAVE_PTHREAD_CANCEL
1622 int *n = xmalloc (sizeof (int));
1624 *n = 0;
1625 pthread_setspecific (signal_thread_key, n);
1626 INIT_THREAD_SIGNAL;
1627 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1628 #endif
1630 #ifdef HAVE_PR_SET_NAME
1631 prctl (PR_SET_NAME, "accept");
1632 #endif
1633 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1635 for (;;)
1637 socklen_t slen = sizeof (struct sockaddr_un);
1638 struct sockaddr_un raddr;
1639 int fd;
1640 #ifndef HAVE_PTHREAD_CANCEL
1641 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1642 int *sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1644 if (*sigusr2)
1645 break;
1646 #endif
1648 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1649 if (fd == -1)
1651 if (errno == EMFILE || errno == ENFILE)
1652 log_write ("accept(): %s",
1653 pwmd_strerror (gpg_error_from_syserror ()));
1654 else if (errno != EAGAIN)
1656 if (!quit) // probably EBADF
1657 log_write ("accept(): %s",
1658 pwmd_strerror (gpg_error_from_syserror ()));
1660 break;
1663 #ifndef HAVE_PTHREAD_CANCEL
1664 select (0, NULL, NULL, NULL, &tv);
1665 #endif
1666 continue;
1669 (void) init_client (fd, NULL);
1672 /* Just in case accept() failed for some reason other than EBADF */
1673 quit = 1;
1674 return NULL;
1677 static void *
1678 cache_timer_thread (void *arg)
1680 #ifndef HAVE_PTHREAD_CANCEL
1681 int *n = xmalloc (sizeof (int));
1683 *n = 0;
1684 pthread_setspecific (signal_thread_key, n);
1685 INIT_THREAD_SIGNAL;
1686 #endif
1688 #ifdef HAVE_PR_SET_NAME
1689 prctl (PR_SET_NAME, "cache timer");
1690 #endif
1691 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1693 for (;;)
1695 struct timeval tv = { 1, 0 };
1696 #ifndef HAVE_PTHREAD_CANCEL
1697 int *n;
1699 n = (int *) pthread_getspecific (signal_thread_key);
1700 if (*n)
1701 break;
1702 #endif
1704 select (0, NULL, NULL, NULL, &tv);
1705 cache_adjust_timeout ();
1708 return NULL;
1711 static void
1712 catch_sigabrt (int sig)
1714 cache_clear (NULL);
1715 #ifndef MEM_DEBUG
1716 xpanic ();
1717 #endif
1720 static int
1721 signal_loop (sigset_t sigset)
1723 int done = 0;
1724 int siint = 0;
1728 int sig;
1730 sigwait (&sigset, &sig);
1732 if (sig != SIGQUIT)
1733 log_write (_("caught signal %i (%s)"), sig, strsignal (sig));
1735 switch (sig)
1737 case SIGHUP:
1738 pthread_cond_signal (&rcfile_cond);
1739 break;
1740 case SIGABRT:
1741 // not really handled here.
1742 catch_sigabrt (SIGABRT);
1743 break;
1744 case SIGUSR1:
1745 log_write (_("clearing file cache"));
1746 cache_clear (NULL);
1747 send_status_all (STATUS_CACHE, NULL);
1748 break;
1749 case SIGQUIT:
1750 done = 1;
1751 break;
1752 default:
1753 siint = 1;
1754 done = 1;
1755 break;
1758 while (!done);
1760 return siint;
1763 static void
1764 catchsig (int sig)
1766 log_write ("Caught SIGSEGV. Exiting.");
1767 #ifdef HAVE_BACKTRACE
1768 BACKTRACE (__FUNCTION__);
1769 #endif
1770 longjmp (jmp, 1);
1773 static void *
1774 waiting_for_exit (void *arg)
1776 int last = 0;
1777 #ifndef HAVE_PTHREAD_CANCEL
1778 int *n = xmalloc (sizeof (int));
1780 *n = 0;
1781 pthread_setspecific (signal_thread_key, n);
1782 INIT_THREAD_SIGNAL;
1783 #endif
1785 #ifdef HAVE_PR_SET_NAME
1786 prctl (PR_SET_NAME, "exiting");
1787 #endif
1788 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1789 log_write (_("waiting for all clients to disconnect"));
1790 MUTEX_LOCK (&quit_mutex);
1791 pthread_cleanup_push (cleanup_mutex_cb, &quit_mutex);
1793 for (;;)
1795 struct timespec ts;
1796 int n;
1798 MUTEX_LOCK (&cn_mutex);
1799 n = slist_length (cn_thread_list);
1800 MUTEX_UNLOCK (&cn_mutex);
1801 if (!n)
1802 break;
1804 #ifndef HAVE_PTHREAD_CANCEL
1805 int *s = (int *) pthread_getspecific (signal_thread_key);
1806 if (*s)
1807 break;
1808 #endif
1810 if (last != n)
1812 log_write (_("%i clients remain"), n);
1813 last = n;
1816 INIT_TIMESPEC (SIG_TIMEOUT, ts);
1817 pthread_cond_timedwait (&quit_cond, &quit_mutex, &ts);
1820 kill (getpid (), SIGQUIT);
1821 pthread_cleanup_pop (1);
1822 return NULL;
1825 static int
1826 server_loop (int sockfd, char **socketpath)
1828 pthread_t accept_tid;
1829 pthread_t cache_timeout_tid;
1830 int cancel_timeout_thread = 0, cancel_accept_thread = 0;
1831 int n, i;
1832 sigset_t sigset;
1833 int segv = 0;
1834 gpg_error_t rc;
1836 init_commands ();
1837 sigemptyset (&sigset);
1839 /* Termination */
1840 sigaddset (&sigset, SIGTERM);
1841 sigaddset (&sigset, SIGINT);
1843 /* Clears the file cache. */
1844 sigaddset (&sigset, SIGUSR1);
1846 /* Configuration file reloading. */
1847 sigaddset (&sigset, SIGHUP);
1849 /* For exiting cleanly. */
1850 sigaddset (&sigset, SIGQUIT);
1852 #ifndef HAVE_PTHREAD_CANCEL
1854 The socket, cache and rcfile threads use this signal when
1855 pthread_cancel() is unavailable. Prevent the main thread from
1856 catching this signal from another process.
1858 sigaddset (&sigset, SIGUSR2);
1859 #endif
1861 /* Clears the cache and exits when something bad happens. */
1862 signal (SIGABRT, catch_sigabrt);
1863 sigaddset (&sigset, SIGABRT);
1864 sigprocmask (SIG_BLOCK, &sigset, NULL);
1866 #ifndef HAVE_PTHREAD_CANCEL
1867 /* Remove this signal from the watched signals in signal_loop(). */
1868 sigdelset (&sigset, SIGUSR2);
1869 #endif
1871 /* Ignored everywhere. When a client disconnects abnormally this signal
1872 * gets raised. It isn't needed though because client_thread() will check
1873 * for rcs even after the client disconnects. */
1874 signal (SIGPIPE, SIG_IGN);
1876 /* Can show a backtrace of the stack in the log. */
1877 signal (SIGSEGV, catchsig);
1879 #ifdef WITH_GNUTLS
1880 /* Needs to be done after the fork(). */
1881 if (!start_stop_tls (0))
1883 segv = 1;
1884 goto done;
1886 #endif
1888 pthread_mutex_init (&quit_mutex, NULL);
1889 pthread_cond_init (&quit_cond, NULL);
1890 log_write (_("%s started for user %s"), PACKAGE_STRING, get_username ());
1892 #ifdef WITH_GNUTLS
1893 if (config_get_boolean ("global", "enable_tcp"))
1894 log_write (_("Listening on %s and TCP port %i"), *socketpath,
1895 config_get_integer ("global", "tcp_port"));
1896 else
1897 log_write (_("Listening on %s"), *socketpath);
1898 #else
1899 log_write (_("Listening on %s"), *socketpath);
1900 #endif
1902 rc = create_thread (reload_rcfile_thread, NULL, &rcfile_tid, 0);
1903 if (rc)
1905 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1906 pwmd_strerror (rc));
1907 goto done;
1910 rc = create_thread (cache_timer_thread, NULL, &cache_timeout_tid, 0);
1911 if (rc)
1913 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1914 pwmd_strerror (rc));
1915 goto done;
1918 cancel_timeout_thread = 1;
1919 rc = create_thread (accept_thread, &sockfd, &accept_tid, 0);
1920 if (rc)
1922 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1923 pwmd_strerror (rc));
1924 goto done;
1927 cancel_accept_thread = 1;
1928 if (!setjmp (jmp))
1929 signal_loop (sigset);
1930 else
1931 segv = 1;
1933 done:
1935 * We're out of the main server loop. This happens when a signal was sent
1936 * to terminate the daemon. We'll wait for all clients to disconnect
1937 * before exiting but exit immediately if another termination signal is
1938 * sent.
1940 if (cancel_accept_thread)
1942 #ifdef HAVE_PTHREAD_CANCEL
1943 int n = pthread_cancel (accept_tid);
1944 #else
1945 int n = pthread_kill (accept_tid, SIGUSR2);
1946 #endif
1947 if (!n)
1948 pthread_join (accept_tid, NULL);
1951 #ifdef WITH_GNUTLS
1952 start_stop_tls (1);
1953 #endif
1954 shutdown (sockfd, SHUT_RDWR);
1955 close (sockfd);
1956 unlink (*socketpath);
1957 xfree (*socketpath);
1958 *socketpath = NULL;
1959 MUTEX_LOCK (&cn_mutex);
1960 n = slist_length (cn_thread_list);
1961 MUTEX_UNLOCK (&cn_mutex);
1963 if (n && !segv)
1965 pthread_t tid;
1967 rc = create_thread (waiting_for_exit, NULL, &tid, 0);
1968 if (!rc)
1970 if (signal_loop (sigset))
1972 log_write (_("Received second termination request. Exiting."));
1973 #ifdef HAVE_PTHREAD_CANCEL
1974 pthread_cancel (tid);
1975 #else
1976 pthread_kill (tid, SIGUSR2);
1977 #endif
1978 pthread_join (tid, NULL);
1981 else
1982 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1983 pwmd_strerror (rc));
1986 if (cancel_timeout_thread)
1988 #ifdef HAVE_PTHREAD_CANCEL
1989 pthread_cancel (cache_timeout_tid);
1990 #else
1991 pthread_kill (cache_timeout_tid, SIGUSR2);
1992 #endif
1993 pthread_join (cache_timeout_tid, NULL);
1996 MUTEX_LOCK (&cn_mutex);
1997 i = 0;
1998 n = slist_length (cn_thread_list);
2000 for (i = 0; i < n; i++)
2002 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2004 if (thd->fd != -1)
2006 close (thd->fd);
2007 thd->fd = -1;
2011 exiting = 1;
2012 MUTEX_UNLOCK (&cn_mutex);
2013 #ifdef WITH_GNUTLS
2014 start_stop_tls (1);
2015 #endif
2016 cache_deinit ();
2017 deinit_commands ();
2018 pthread_cond_destroy (&quit_cond);
2019 pthread_mutex_destroy (&quit_mutex);
2020 return segv ? EXIT_FAILURE : EXIT_SUCCESS;;
2023 static void
2024 startup_failure ()
2026 log_write (_
2027 ("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
2028 cache_clear (NULL);
2031 /* This is called from cache.c:clear_once(). See
2032 * command.c:clearcache_command() for details about lock checking.
2034 static gpg_error_t
2035 free_cache_data (file_cache_t * cache)
2037 gpg_error_t rc = GPG_ERR_NO_DATA;
2038 int i, t;
2039 struct client_thread_s *found = NULL;
2040 int self = 0;
2042 if (!cache->data)
2043 return 0;
2045 cache_lock ();
2046 MUTEX_LOCK (&cn_mutex);
2047 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
2048 t = slist_length (cn_thread_list);
2050 for (i = 0; i < t; i++)
2052 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2054 if (!thd->cl)
2055 continue;
2057 if (!memcmp (thd->cl->md5file, cache->filename,
2058 sizeof (cache->filename)))
2060 if (pthread_equal (pthread_self (), thd->tid))
2062 found = thd;
2063 self = 1;
2064 continue;
2067 /* Continue trying to find a client who has the same file open and
2068 * also has a lock. */
2069 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0, -1);
2070 if (!rc)
2072 self = 0;
2073 found = thd;
2074 break;
2079 if (self && (!rc || rc == GPG_ERR_NO_DATA))
2080 rc = cache_lock_mutex (found->cl->ctx, found->cl->md5file, -1, 0, -1);
2082 if (exiting || !rc || rc == GPG_ERR_NO_DATA)
2084 free_cache_data_once (cache->data);
2085 cache->data = NULL;
2086 cache->defer_clear = 0;
2087 cache->timeout = -1;
2089 if (found)
2090 cache_unlock_mutex (found->cl->md5file, 0);
2092 rc = 0;
2095 if (rc)
2096 cache->defer_clear = 1;
2098 pthread_cleanup_pop (1);
2099 cache_unlock ();
2100 return rc;
2103 static int
2104 convert_v2_datafile (const char *filename, const char *cipher,
2105 const char *keyfile, const char *keygrip,
2106 const char *sign_keygrip, int nopass,
2107 const char *outfile, const char *keyparam,
2108 unsigned long s2k_count, uint64_t iterations)
2110 gpg_error_t rc;
2111 void *data = NULL;
2112 size_t datalen;
2113 struct crypto_s *crypto = NULL;
2114 uint16_t ver;
2115 int algo;
2116 void *key = NULL;
2117 size_t keylen = 0;
2119 if (outfile[0] == '-' && outfile[1] == 0)
2120 outfile = NULL;
2122 log_write (_("Converting version 2 data file \"%s\" ..."), filename);
2123 if (access (filename, R_OK) == -1)
2125 log_write ("%s: %s", filename,
2126 pwmd_strerror (gpg_error_from_syserror ()));
2127 return 0;
2130 if (keyfile)
2132 log_write (_("Using passphrase file \"%s\" for decryption ..."),
2133 keyfile);
2134 if (access (keyfile, R_OK) == -1)
2136 log_write ("%s: %s", keyfile,
2137 pwmd_strerror (gpg_error_from_syserror ()));
2138 return 0;
2142 rc = read_v2_datafile (filename, keyfile, &data, &datalen, &ver, &algo);
2143 if (rc)
2145 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2146 return 0;
2149 if (cipher)
2151 algo = cipher_string_to_gcrypt (cipher);
2152 if (algo == -1)
2154 rc = GPG_ERR_CIPHER_ALGO;
2155 goto fail;
2159 if (ver < 0x212)
2161 xmlDocPtr doc = parse_doc (data, datalen);
2163 if (!doc)
2165 rc = GPG_ERR_BAD_DATA;
2166 goto fail;
2169 rc = convert_pre_212_elements (doc);
2170 gcry_free (data);
2171 data = NULL;
2172 if (!rc)
2174 xmlDocDumpFormatMemory (doc, (xmlChar **) & data, (int *) &datalen,
2176 if (!data)
2177 rc = GPG_ERR_ENOMEM;
2180 xmlFreeDoc (doc);
2181 if (rc)
2182 goto fail;
2185 rc = init_client_crypto (&crypto);
2186 if (!rc)
2188 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
2189 crypto->save.hdr.flags = set_cipher_flag (crypto->save.hdr.flags, algo);
2190 crypto->save.s2k_count = s2k_count;
2191 crypto->save.hdr.iterations = iterations;
2193 if (!use_agent)
2195 rc = export_common (NULL, 0, crypto, data, datalen, outfile, keyfile,
2196 &key, &keylen, 0, 0);
2198 #ifdef WITH_AGENT
2199 else
2201 rc = agent_set_pinentry_options (crypto->agent);
2202 if (!rc)
2203 rc = agent_export_common (crypto, keygrip, sign_keygrip, nopass,
2204 data, datalen, outfile, keyparam,
2205 no_passphrase_file ? NULL : keyfile);
2207 #endif
2208 if (!rc)
2209 log_write (_("Output written to \"%s\"."), outfile);
2212 fail:
2213 if (ver < 0x212)
2214 xmlFree (data);
2215 else
2216 gcry_free (data);
2218 gcry_free (key);
2219 cleanup_crypto (&crypto);
2221 if (rc)
2222 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2223 return rc ? 0 : 1;
2226 static void
2227 usage (const char *pn, int status)
2229 FILE *fp = status == EXIT_FAILURE ? stderr : stdout;
2231 fprintf (fp, _("Usage: %s [OPTIONS] [file1] [...]\n"
2232 " -f, --rcfile=filename load the specfied configuration file\n"
2233 " (~/.pwmd/config)\n"
2234 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2235 #ifdef WITH_AGENT
2236 " --no-agent disable use of gpg-agent\n"
2237 #endif
2238 " -n, --no-fork run as a foreground process\n"
2239 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2240 " --ignore ignore file errors during startup\n"
2241 " --debug-level=keywords log protocol output (see manual for details)\n"
2242 " -o, --outfile=filename output file when importing or converting\n"
2243 " -C, --convert=filename convert a version 2 data file to version 3\n"
2244 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2245 " -k, --passphrase-file=file for use when importing or converting\n"
2246 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2247 " converting\n"
2248 " --no-passphrase when importing or converting\n"
2249 " --keygrip=hex public key to use when encrypting\n"
2250 " --sign-keygrip=hex private key to use when signing\n"
2251 " --keyparam=s-exp custom key parameters to use (RSA-2048)\n"
2252 " --cipher=string encryption cipher (aes256)\n"
2253 " --iterations=N cipher iteration count (N+1)\n"
2254 " --s2k-count=N hash iteration count (>65536, calibrated)\n"
2255 " --help this help text\n"
2256 " --version show version and compile time features\n"),
2257 pn);
2258 exit (status);
2262 main (int argc, char *argv[])
2264 int opt;
2265 struct sockaddr_un addr;
2266 char buf[PATH_MAX];
2267 char *socketpath = NULL, *socketdir, *socketname = NULL;
2268 char *socketarg = NULL;
2269 char *datadir = NULL;
2270 int x;
2271 char *p;
2272 char **cache_push = NULL;
2273 char *import = NULL, *keygrip = NULL, *sign_keygrip = NULL;
2274 char *keyparam = NULL;
2275 int estatus = EXIT_FAILURE;
2276 int sockfd;
2277 char *outfile = NULL;
2278 int do_unlink = 0;
2279 int secure = 0;
2280 int show_version = 0;
2281 int force = 0;
2282 int no_passphrase = 0;
2283 gpg_error_t rc;
2284 char *convertfile = NULL;
2285 char *cipher = NULL;
2286 char *keyfile = NULL;
2287 unsigned long s2k_count = 0;
2288 uint64_t iterations = 0;
2289 int exists;
2290 char *debug_level_opt = NULL;
2291 int optindex;
2292 /* Must maintain the same order as longopts[] */
2293 enum
2294 { OPT_VERSION, OPT_HELP,
2295 #ifdef WITH_AGENT
2296 OPT_NO_AGENT,
2297 #endif
2298 OPT_DEBUG_LEVEL, OPT_HOMEDIR, OPT_NO_FORK, OPT_DISABLE_DUMP, OPT_IGNORE,
2299 OPT_RCFILE, OPT_CONVERT, OPT_PASSPHRASE_FILE, OPT_IMPORT, OPT_OUTFILE,
2300 OPT_NO_PASSPHRASE_FILE, OPT_KEYGRIP, OPT_SIGN_KEYGRIP, OPT_KEYPARAM,
2301 OPT_CIPHER, OPT_ITERATIONS, OPT_S2K_COUNT, OPT_NO_PASSPHRASE
2303 const char *optstring = "nf:C:k:I:o:";
2304 const struct option longopts[] = {
2305 {"version", no_argument, 0, 0},
2306 {"help", no_argument, 0, 0},
2307 #ifdef WITH_AGENT
2308 {"no-agent", no_argument, 0, 0},
2309 #endif
2310 {"debug-level", required_argument, 0, 0},
2311 {"homedir", required_argument, 0, 0},
2312 {"no-fork", no_argument, 0, 'n'},
2313 {"disable_dump", no_argument, 0, 0},
2314 {"ignore", no_argument, 0, 0},
2315 {"rcfile", required_argument, 0, 'f'},
2316 {"convert", required_argument, 0, 'C'},
2317 {"passphrase-file", required_argument, 0, 'k'},
2318 {"import", required_argument, 0, 'I'},
2319 {"outfile", required_argument, 0, 'o'},
2320 {"no-passphrase-file", no_argument, 0, 0},
2321 {"keygrip", required_argument, 0, 0},
2322 {"sign-keygrip", required_argument, 0, 0},
2323 {"keyparam", required_argument, 0, 0},
2324 {"cipher", required_argument, 0, 0},
2325 {"cipher-iterations", required_argument, 0, 0},
2326 {"s2k-count", required_argument, 0, 0},
2327 {"no-passphrase", no_argument, 0, 0},
2328 {0, 0, 0, 0}
2331 #ifndef DEBUG
2332 #ifdef HAVE_SETRLIMIT
2333 struct rlimit rl;
2335 rl.rlim_cur = rl.rlim_max = 0;
2337 if (setrlimit (RLIMIT_CORE, &rl) != 0)
2338 err (EXIT_FAILURE, "setrlimit()");
2339 #endif
2340 #endif
2342 #ifdef ENABLE_NLS
2343 setlocale (LC_ALL, "");
2344 bindtextdomain ("pwmd", LOCALEDIR);
2345 textdomain ("pwmd");
2346 #endif
2348 #ifndef MEM_DEBUG
2349 xmem_init ();
2350 #endif
2351 gpg_err_init ();
2353 if (setup_crypto ())
2354 exit (EXIT_FAILURE);
2356 #ifdef WITH_GNUTLS
2357 gnutls_global_set_mem_functions (xmalloc, xmalloc, secure_mem_check,
2358 xrealloc, xfree);
2359 gnutls_global_init ();
2360 gnutls_global_set_log_function (tls_log);
2361 gnutls_global_set_log_level (1);
2362 tls_fd = -1;
2363 tls6_fd = -1;
2364 #endif
2365 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
2366 xmlInitMemory ();
2367 xmlInitGlobals ();
2368 xmlInitParser ();
2369 xmlXPathInit ();
2370 cmdline = 1;
2371 #ifdef WITH_AGENT
2372 use_agent = 1;
2373 #endif
2375 while ((opt =
2376 getopt_long (argc, argv, optstring, longopts, &optindex)) != -1)
2378 switch (opt)
2380 case 'I':
2381 import = optarg;
2382 break;
2383 case 'C':
2384 convertfile = optarg;
2385 break;
2386 case 'k':
2387 keyfile = optarg;
2388 break;
2389 case 'o':
2390 outfile = optarg;
2391 break;
2392 case 'D':
2393 secure = 1;
2394 break;
2395 case 'n':
2396 nofork = 1;
2397 break;
2398 case 'f':
2399 rcfile = str_dup (optarg);
2400 break;
2401 default:
2402 usage (argv[0], EXIT_FAILURE);
2403 break;
2404 case 0:
2405 switch (optindex)
2407 case OPT_VERSION:
2408 show_version = 1;
2409 break;
2410 case OPT_HELP:
2411 usage (argv[0], 0);
2412 break;
2413 #ifdef WITH_AGENT
2414 case OPT_NO_AGENT:
2415 use_agent = 0;
2416 break;
2417 #endif
2418 case OPT_DEBUG_LEVEL:
2419 debug_level_opt = optarg;
2420 break;
2421 case OPT_HOMEDIR:
2422 homedir = str_dup (optarg);
2423 break;
2424 case OPT_NO_FORK:
2425 nofork = 1;
2426 break;
2427 case OPT_DISABLE_DUMP:
2428 secure = 1;
2429 break;
2430 case OPT_IGNORE:
2431 force = 1;
2432 break;
2433 case OPT_RCFILE:
2434 rcfile = str_dup (optarg);
2435 break;
2436 case OPT_CONVERT:
2437 convertfile = optarg;
2438 break;
2439 case OPT_PASSPHRASE_FILE:
2440 keyfile = optarg;
2441 break;
2442 case OPT_IMPORT:
2443 import = optarg;
2444 break;
2445 case OPT_OUTFILE:
2446 outfile = optarg;
2447 break;
2448 case OPT_NO_PASSPHRASE_FILE:
2449 no_passphrase_file = 1;
2450 break;
2451 case OPT_KEYGRIP:
2452 keygrip = optarg;
2453 break;
2454 case OPT_SIGN_KEYGRIP:
2455 sign_keygrip = optarg;
2456 break;
2457 case OPT_KEYPARAM:
2458 keyparam = optarg;
2459 break;
2460 case OPT_CIPHER:
2461 cipher = optarg;
2462 break;
2463 case OPT_ITERATIONS:
2464 iterations = strtoull (optarg, NULL, 10);
2465 break;
2466 case OPT_S2K_COUNT:
2467 s2k_count = strtoul (optarg, NULL, 10);
2468 break;
2469 case OPT_NO_PASSPHRASE:
2470 no_passphrase = 1;
2471 break;
2472 default:
2473 usage (argv[0], 1);
2478 if (show_version)
2480 printf (_("%s\n\n"
2481 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012\n"
2482 "%s\n"
2483 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2484 "Compile time features:\n%s"), PACKAGE_STRING,
2485 PACKAGE_BUGREPORT,
2486 #ifdef PWMD_HOMEDIR
2487 "+PWMD_HOMEDIR=" PWMD_HOMEDIR "\n"
2488 #endif
2489 #ifdef WITH_AGENT
2490 "+WITH_AGENT\n"
2491 #else
2492 "-WITH_AGENT\n"
2493 #endif
2494 #ifdef WITH_QUALITY
2495 "+WITH_QUALITY\n"
2496 #else
2497 "-WITH_QUALITY\n"
2498 #endif
2499 #ifdef WITH_GNUTLS
2500 "+WITH_GNUTLS\n"
2501 #else
2502 "-WITH_GNUTLS\n"
2503 #endif
2504 #ifdef WITH_LIBACL
2505 "+WITH_LIBACL\n"
2506 #else
2507 "-WITH_LIBACL\n"
2508 #endif
2509 #ifdef DEBUG
2510 "+DEBUG\n"
2511 #else
2512 "-DEBUG\n"
2513 #endif
2514 #ifdef MEM_DEBUG
2515 "+MEM_DEBUG\n"
2516 #else
2517 "-MEM_DEBUG\n"
2518 #endif
2519 #ifdef MUTEX_DEBUG
2520 "+MUTEX_DEBUG\n"
2521 #else
2522 "-MUTEX_DEBUG\n"
2523 #endif
2525 exit (EXIT_SUCCESS);
2528 if (!homedir)
2529 #ifdef PWMD_HOMEDIR
2530 homedir = str_dup(PWMD_HOMEDIR);
2531 #else
2532 homedir = str_asprintf ("%s/.pwmd", get_home_dir ());
2533 #endif
2535 if (mkdir (homedir, 0700) == -1 && errno != EEXIST)
2536 err (EXIT_FAILURE, "%s", homedir);
2538 snprintf (buf, sizeof (buf), "%s/data", homedir);
2539 if (mkdir (buf, 0700) == -1 && errno != EEXIST)
2540 err (EXIT_FAILURE, "%s", buf);
2542 datadir = str_dup (buf);
2543 pthread_mutexattr_t attr;
2544 pthread_mutexattr_init (&attr);
2545 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
2546 pthread_mutex_init (&rcfile_mutex, &attr);
2547 pthread_cond_init (&rcfile_cond, NULL);
2548 pthread_mutex_init (&cn_mutex, &attr);
2549 pthread_mutexattr_destroy (&attr);
2550 pthread_key_create (&last_error_key, free_key);
2551 #ifndef HAVE_PTHREAD_CANCEL
2552 pthread_key_create (&signal_thread_key, free_key);
2553 #endif
2555 if (!rcfile)
2556 rcfile = str_asprintf ("%s/config", homedir);
2558 global_config = config_parse (rcfile);
2559 if (!global_config)
2560 exit (EXIT_FAILURE);
2562 setup_logging ();
2564 if (debug_level_opt)
2565 debug_level = str_split (debug_level_opt, ",", 0);
2567 x = config_get_int_param (global_config, "global", "priority", &exists);
2568 if (exists && x != atoi(INVALID_PRIORITY))
2570 errno = 0;
2571 if (setpriority (PRIO_PROCESS, 0, x) == -1)
2573 log_write ("setpriority(): %s",
2574 pwmd_strerror (gpg_error_from_syserror ()));
2575 goto do_exit;
2578 #ifdef HAVE_MLOCKALL
2579 if (disable_mlock == 0 && mlockall (MCL_CURRENT | MCL_FUTURE) == -1)
2581 log_write ("mlockall(): %s",
2582 pwmd_strerror (gpg_error_from_syserror ()));
2583 goto do_exit;
2585 #endif
2587 rc = cache_init (free_cache_data);
2588 if (rc)
2590 log_write ("pwmd: ERR %i: %s", rc,
2591 gpg_err_code (rc) == GPG_ERR_UNKNOWN_VERSION
2592 ? _("incompatible version: 2.1.0 or later required")
2593 : pwmd_strerror (rc));
2594 goto do_exit;
2597 if (s2k_count == 0)
2598 s2k_count = config_get_ulong (NULL, "s2k_count");
2600 if (convertfile)
2602 if (!outfile)
2603 usage (argv[0], EXIT_FAILURE);
2605 estatus = convert_v2_datafile (convertfile, cipher, keyfile, keygrip,
2606 sign_keygrip, no_passphrase, outfile,
2607 keyparam, s2k_count, iterations);
2608 config_free (global_config);
2609 xfree (rcfile);
2610 exit (!estatus);
2613 if (import)
2615 if (!outfile)
2616 usage (argv[0], EXIT_FAILURE);
2618 if (outfile[0] == '-' && outfile[1] == 0)
2619 outfile = NULL;
2621 estatus = xml_import (import, outfile, keygrip, sign_keygrip, keyfile,
2622 no_passphrase, cipher, keyparam, s2k_count,
2623 iterations);
2624 config_free (global_config);
2625 xfree (rcfile);
2626 exit (!estatus);
2629 p = config_get_string ("global", "socket_path");
2630 if (!p)
2631 p = str_asprintf ("%s/socket", homedir);
2633 socketarg = expand_homedir (p);
2634 xfree (p);
2636 if (!secure)
2637 disable_list_and_dump = config_get_boolean ("global",
2638 "disable_list_and_dump");
2639 else
2640 disable_list_and_dump = secure;
2642 cache_push = config_get_list ("global", "cache_push");
2644 while (optind < argc)
2646 if (strv_printf (&cache_push, "%s", argv[optind++]) == 0)
2647 errx (EXIT_FAILURE, "%s", pwmd_strerror (GPG_ERR_ENOMEM));
2650 if (strchr (socketarg, '/') == NULL)
2652 socketdir = getcwd (buf, sizeof (buf));
2653 socketname = str_dup (socketarg);
2654 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2656 else
2658 socketname = str_dup (strrchr (socketarg, '/'));
2659 socketname++;
2660 socketarg[strlen (socketarg) - strlen (socketname) - 1] = 0;
2661 socketdir = str_dup (socketarg);
2662 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2665 if (chdir (datadir))
2667 log_write ("%s: %s", datadir,
2668 pwmd_strerror (gpg_error_from_syserror ()));
2669 unlink (socketpath);
2670 goto do_exit;
2674 * Set the cache entry for a file. Prompts for the password.
2676 if (cache_push)
2678 struct crypto_s *crypto;
2679 gpg_error_t rc = init_client_crypto (&crypto);
2681 if (rc)
2683 estatus = EXIT_FAILURE;
2684 goto do_exit;
2687 #ifdef WITH_AGENT
2688 if (use_agent)
2690 rc = agent_set_pinentry_options (crypto->agent);
2691 if (rc)
2693 estatus = EXIT_FAILURE;
2694 goto do_exit;
2697 #endif
2699 for (opt = 0; cache_push[opt]; opt++)
2701 if (!do_cache_push (cache_push[opt], crypto) && !force)
2703 strv_free (cache_push);
2704 startup_failure ();
2705 estatus = EXIT_FAILURE;
2706 cleanup_crypto (&crypto);
2707 goto do_exit;
2710 cleanup_crypto_stage1 (crypto);
2713 #ifdef WITH_AGENT
2714 if (use_agent)
2715 (void) kill_scd (crypto->agent);
2716 #endif
2718 cleanup_crypto (&crypto);
2719 strv_free (cache_push);
2720 log_write (!nofork ? _("Done. Daemonizing...") :
2721 _("Done. Waiting for connections..."));
2724 config_clear_keys ();
2727 * bind() doesn't like the full pathname of the socket or any non alphanum
2728 * characters so change to the directory where the socket is wanted then
2729 * create it then change to datadir.
2731 if (chdir (socketdir))
2733 log_write ("%s: %s", socketdir,
2734 pwmd_strerror (gpg_error_from_syserror ()));
2735 goto do_exit;
2738 xfree (socketdir);
2740 if ((sockfd = socket (PF_UNIX, SOCK_STREAM, 0)) == -1)
2742 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_syserror ()));
2743 goto do_exit;
2746 addr.sun_family = AF_UNIX;
2747 snprintf (addr.sun_path, sizeof (addr.sun_path), "%s", socketname);
2749 if (bind (sockfd, (struct sockaddr *) &addr, sizeof (struct sockaddr)) ==
2752 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_syserror ()));
2754 if (errno == EADDRINUSE)
2755 log_write (_("Either there is another pwmd running or '%s' is a \n"
2756 "stale socket. Please remove it manually."), socketpath);
2758 goto do_exit;
2761 do_unlink = 1;
2763 char *t = config_get_string ("global", "socket_perms");
2764 mode_t mode;
2765 mode_t mask;
2767 if (t)
2769 mode = strtol (t, NULL, 8);
2770 mask = umask (0);
2771 xfree (t);
2773 if (chmod (socketname, mode) == -1)
2775 log_write ("%s: %s", socketname,
2776 pwmd_strerror (gpg_error_from_syserror ()));
2777 close (sockfd);
2778 unlink (socketpath);
2779 umask (mask);
2780 goto do_exit;
2783 umask (mask);
2787 xfree (--socketname);
2789 if (chdir (datadir))
2791 log_write ("%s: %s", datadir,
2792 pwmd_strerror (gpg_error_from_syserror ()));
2793 close (sockfd);
2794 unlink (socketpath);
2795 goto do_exit;
2798 xfree (datadir);
2800 if (listen (sockfd, 0) == -1)
2802 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_syserror ()));
2803 goto do_exit;
2806 cmdline = 0;
2808 if (!nofork)
2810 switch (fork ())
2812 case -1:
2813 log_write ("fork(): %s",
2814 pwmd_strerror (gpg_error_from_syserror ()));
2815 goto do_exit;
2816 case 0:
2817 close (0);
2818 close (1);
2819 close (2);
2820 setsid ();
2821 break;
2822 default:
2823 _exit (EXIT_SUCCESS);
2827 pthread_key_create (&thread_name_key, free_key);
2828 pthread_setspecific (thread_name_key, str_dup ("main"));
2829 estatus = server_loop (sockfd, &socketpath);
2831 do_exit:
2832 if (socketpath && do_unlink)
2834 unlink (socketpath);
2835 xfree (socketpath);
2838 xfree (socketarg);
2839 #ifdef WITH_GNUTLS
2840 gnutls_global_deinit ();
2841 #endif
2842 if (rcfile_tid)
2844 #ifdef HAVE_PTHREAD_CANCEL
2845 pthread_cancel (rcfile_tid);
2846 #else
2847 pthread_kill (rcfile_tid, SIGUSR2);
2848 pthread_cond_signal (&rcfile_cond);
2849 #endif
2850 pthread_join (rcfile_tid, NULL);
2853 pthread_cond_destroy (&rcfile_cond);
2854 pthread_mutex_destroy (&rcfile_mutex);
2855 pthread_key_delete (last_error_key);
2856 pthread_key_delete (thread_name_key);
2857 #ifndef HAVE_PTHREAD_CANCEL
2858 pthread_key_delete (signal_thread_key);
2859 #endif
2861 if (global_config)
2862 config_free (global_config);
2864 xfree (rcfile);
2865 xfree (home_directory);
2866 xfree (homedir);
2867 xmlCleanupParser ();
2868 xmlCleanupGlobals ();
2870 if (estatus == EXIT_SUCCESS)
2871 log_write (_("pwmd exiting normally"));
2873 closelog ();
2874 #if defined(DEBUG) && !defined(MEM_DEBUG)
2875 xdump ();
2876 #endif
2877 exit (estatus);