Potential overwriting of the original error code.
[pwmd.git] / src / pwmd.c
blob0bc5f42b603226b6f35720b5203c840c7741a130
1 /*
2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013
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;
103 static pthread_t keepalive_tid;
105 #ifndef HAVE_PTHREAD_CANCEL
106 static pthread_key_t signal_thread_key;
107 #endif
109 #ifdef WITH_GNUTLS
110 static int tls_fd;
111 static int tls6_fd;
112 static pthread_t tls_tid;
113 static pthread_t tls6_tid;
114 static int spawned_tls;
115 static int spawned_tls6;
117 static int start_stop_tls (int term);
118 #endif
120 static int do_cache_push (const char *filename, struct crypto_s *crypto);
121 static int signal_loop (sigset_t sigset);
123 GCRY_THREAD_OPTION_PTHREAD_IMPL;
125 #ifndef HAVE_PTHREAD_CANCEL
126 #define INIT_THREAD_SIGNAL do { \
127 struct sigaction act; \
128 sigset_t sigset; \
129 sigemptyset (&sigset); \
130 sigaddset (&sigset, SIGUSR2); \
131 pthread_sigmask (SIG_UNBLOCK, &sigset, NULL); \
132 memset (&act, 0, sizeof(act)); \
133 act.sa_flags = SA_SIGINFO; \
134 act.sa_mask = sigset; \
135 act.sa_sigaction = catch_thread_signal; \
136 sigaction (SIGUSR2, &act, NULL); \
137 } while (0)
139 static void
140 catch_thread_signal (int sig, siginfo_t *info, void *ctx)
142 int *n = (int *) pthread_getspecific (signal_thread_key);
144 *n = 1;
145 pthread_setspecific (signal_thread_key, n);
147 #endif
149 static void
150 cache_push_from_rcfile ()
152 struct crypto_s *crypto = NULL;
153 char **cache_push;
154 gpg_error_t rc = init_client_crypto (&crypto);
156 if (rc)
158 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
159 return;
162 #ifdef WITH_AGENT
163 if (use_agent)
165 rc = set_agent_option (crypto->agent, "pinentry-mode", "error");
166 if (rc)
168 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
169 return;
172 #endif
174 cache_push = config_get_list ("global", "cache_push");
175 if (cache_push)
177 char **p;
179 for (p = cache_push; *p; p++)
181 (void) do_cache_push (*p, crypto);
182 cleanup_crypto_stage1 (crypto);
185 strv_free (cache_push);
188 #ifdef WITH_AGENT
189 (void) kill_scd (crypto->agent);
190 #endif
191 cleanup_crypto (&crypto);
194 static void
195 setup_logging ()
197 int n = config_get_boolean ("global", "enable_logging");
199 if (n)
201 char *p = config_get_string ("global", "log_path");
203 xfree (logfile);
204 logfile = expand_homedir (p);
205 xfree (p);
207 else
209 xfree (logfile);
210 logfile = NULL;
213 log_syslog = config_get_boolean ("global", "syslog");
214 if (log_syslog == 1)
215 openlog ("pwmd", LOG_NDELAY | LOG_PID, LOG_DAEMON);
218 static void *
219 reload_rcfile_thread (void *arg)
221 #ifndef HAVE_PTHREAD_CANCEL
222 int *n = xmalloc (sizeof (int));
224 *n = 0;
225 pthread_setspecific (signal_thread_key, n);
226 INIT_THREAD_SIGNAL;
227 #endif
229 #ifdef HAVE_PR_SET_NAME
230 prctl (PR_SET_NAME, "reload rcfile");
231 #endif
232 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
233 MUTEX_LOCK (&rcfile_mutex);
234 pthread_cleanup_push (cleanup_mutex_cb, &rcfile_mutex);
236 for (;;)
238 struct slist_s *config;
239 char **users;
240 int b = disable_list_and_dump;
241 int exists;
242 int require_save_key = config_get_bool_param (global_config, "global",
243 "require_save_key",
244 &exists);
245 #ifdef WITH_GNUTLS
246 int tcp_require_key = config_get_bool_param (global_config, "global",
247 "tcp_require_key",
248 &exists);
249 #endif
251 pthread_cond_wait (&rcfile_cond, &rcfile_mutex);
252 #ifndef HAVE_PTHREAD_CANCEL
253 int *n = (int *) pthread_getspecific (signal_thread_key);
254 if (*n)
255 break;
256 #endif
258 users = config_get_list ("global", "allowed");
259 log_write (_("reloading configuration file '%s'"), rcfile);
260 config = config_parse (rcfile);
261 if (config)
263 config_free (global_config);
264 global_config = config;
265 setup_logging ();
266 cache_push_from_rcfile ();
267 config_clear_keys ();
270 disable_list_and_dump = !disable_list_and_dump ? b : 1;
271 config_set_bool_param (&global_config, "global", "require_save_key",
272 require_save_key ? "true" : "false");
273 #ifdef WITH_GNUTLS
274 if (config_get_bool_param (global_config, "global", "tcp_require_key",
275 &exists) && exists)
276 tcp_require_key = 1;
278 config_set_bool_param (&global_config, "global", "tcp_require_key",
279 tcp_require_key ? "true" : "false");
280 #endif
281 char *tmp = strv_join (",", users);
282 config_set_list_param (&global_config, "global", "allowed", tmp);
283 xfree (tmp);
284 strv_free (users);
285 #ifdef WITH_GNUTLS
286 /* Kill existing listening threads since the configured listening
287 * protocols may have changed. */
288 start_stop_tls (1);
289 start_stop_tls (0);
290 #endif
293 pthread_cleanup_pop (1);
294 return NULL;
297 gpg_error_t
298 send_error (assuan_context_t ctx, gpg_error_t e)
300 struct client_s *client = assuan_get_pointer (ctx);
302 if (gpg_err_source (e) == GPG_ERR_SOURCE_UNKNOWN)
303 e = gpg_error (e);
305 if (client)
306 client->last_rc = e;
308 if (!e)
309 return assuan_process_done (ctx, 0);
311 if (!ctx)
313 log_write ("ERR %i: %s", e, pwmd_strerror (e));
314 return e;
317 if (client && gpg_err_code (e) == GPG_ERR_BAD_DATA)
319 xmlErrorPtr xe = client->xml_error;
321 if (!xe)
322 xe = xmlGetLastError ();
323 if (xe)
325 log_write ("%s", xe->message);
326 if (client->last_error)
327 xfree (client->last_error);
329 client->last_error = str_dup (xe->message);
332 e = assuan_process_done (ctx, assuan_set_error (ctx, e,
333 xe ? xe->message :
334 NULL));
336 if (xe == client->xml_error)
337 xmlResetError (xe);
338 else
339 xmlResetLastError ();
341 client->xml_error = NULL;
342 return e;
345 return assuan_process_done (ctx,
346 assuan_set_error (ctx, e, pwmd_strerror (e)));
350 assuan_log_cb (assuan_context_t ctx, void *data, unsigned cat,
351 const char *msg)
353 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
354 int i, t;
355 int match = 0;
357 pthread_mutex_lock (&m);
358 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock, &m);
359 t = strv_length (debug_level);
361 for (i = 0; i < t; i++)
363 if (!strcasecmp (debug_level[i], (char *) "init")
364 && cat == ASSUAN_LOG_INIT)
366 match = 1;
367 break;
370 if (!strcasecmp (debug_level[i], (char *) "ctx")
371 && cat == ASSUAN_LOG_CTX)
373 match = 1;
374 break;
377 if (!strcasecmp (debug_level[i], (char *) "engine")
378 && cat == ASSUAN_LOG_ENGINE)
380 match = 1;
381 break;
384 if (!strcasecmp (debug_level[i], (char *) "data")
385 && cat == ASSUAN_LOG_DATA)
387 match = 1;
388 break;
391 if (!strcasecmp (debug_level[i], (char *) "sysio")
392 && cat == ASSUAN_LOG_SYSIO)
394 match = 1;
395 break;
398 if (!strcasecmp (debug_level[i], (char *) "control")
399 && cat == ASSUAN_LOG_CONTROL)
401 match = 1;
402 break;
406 if (match && msg)
408 if (logfile)
410 int fd;
412 if ((fd =
413 open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600)) == -1)
414 warn ("%s", logfile);
415 else
417 pthread_cleanup_push (cleanup_fd_cb, &fd);
418 write (fd, msg, strlen (msg));
419 pthread_cleanup_pop (1);
423 if (nofork)
425 fprintf (stderr, "%s%s", data ? (char *) data : "", msg);
426 fflush (stderr);
430 pthread_cleanup_pop (1);
431 return match;
434 void
435 log_write (const char *fmt, ...)
437 char *args, *line;
438 va_list ap;
439 struct tm *tm;
440 time_t now;
441 char tbuf[21];
442 int fd = -1;
443 char *name = NULL;
444 char buf[255];
445 pthread_t tid = pthread_self ();
446 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
448 if ((!logfile && !isatty (STDERR_FILENO) && !log_syslog) || !fmt)
449 return;
451 pthread_mutex_lock (&m);
452 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock, &m);
453 pthread_cleanup_push (cleanup_fd_cb, &fd);
455 if (!cmdline && logfile)
457 if ((fd = open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600)) == -1)
458 warn ("%s", logfile);
461 va_start (ap, fmt);
463 if (str_vasprintf (&args, fmt, ap) != -1)
465 if (cmdline)
467 pthread_cleanup_push (xfree, args);
468 fprintf (stderr, "%s\n", args);
469 fflush (stderr);
470 pthread_cleanup_pop (1);
472 else
474 pthread_cleanup_push (xfree, args);
475 name = pthread_getspecific (thread_name_key);
476 snprintf (buf, sizeof (buf), "%s(%p): ", name ? name : _("unknown"),
477 (pthread_t *) tid);
478 name = buf;
480 if (!cmdline && log_syslog && !nofork)
481 syslog (LOG_INFO, "%s%s", name, args);
483 time (&now);
484 tm = localtime (&now);
485 strftime (tbuf, sizeof (tbuf), "%b %d %Y %H:%M:%S ", tm);
486 tbuf[sizeof (tbuf) - 1] = 0;
488 if (args[strlen (args) - 1] == '\n')
489 args[strlen (args) - 1] = 0;
491 line = str_asprintf ("%s %i %s%s\n", tbuf, getpid (), name, args);
492 pthread_cleanup_pop (1);
493 if (line)
495 pthread_cleanup_push (xfree, line);
496 if (logfile && fd != -1)
498 write (fd, line, strlen (line));
499 fsync (fd);
502 if (nofork)
504 fprintf (stdout, "%s", line);
505 fflush (stdout);
508 pthread_cleanup_pop (1);
513 va_end (ap);
514 pthread_cleanup_pop (1);
515 pthread_cleanup_pop (0);
516 pthread_mutex_unlock (&m);
519 #ifdef WITH_GNUTLS
520 static int
521 secure_mem_check (const void *arg)
523 return 1;
525 #endif
527 static gpg_error_t
528 setup_crypto ()
530 gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
532 if (!gcry_check_version (GCRYPT_VERSION))
534 fprintf (stderr, _("gcry_check_version(): Incompatible libgcrypt. "
535 "Wanted %s, got %s.\n"), GCRYPT_VERSION,
536 gcry_check_version (NULL));
537 return GPG_ERR_UNKNOWN_VERSION;
540 gcry_set_allocation_handler (xmalloc, xmalloc, NULL, xrealloc, xfree);
541 return 0;
544 #ifdef HAVE_GETGRNAM_R
545 static gpg_error_t
546 do_validate_peer (struct client_s *cl, assuan_peercred_t * peer)
548 char **users;
549 int allowed = 0;
550 gpg_error_t rc;
552 rc = assuan_get_peercred (cl->ctx, peer);
553 if (rc)
554 return rc;
556 users = config_get_list ("global", "allowed");
557 if (users)
559 for (char **p = users; *p; p++)
561 struct passwd pw, *result;
562 struct group gr, *gresult;
563 char *buf;
565 if (*(*p) == '@')
567 size_t len = sysconf (_SC_GETGR_R_SIZE_MAX);
569 if (len == -1)
570 len = 16384;
572 buf = xmalloc (len);
573 if (!buf)
575 strv_free (users);
576 return GPG_ERR_ENOMEM;
579 if (!getgrnam_r (*(p) + 1, &gr, buf, len, &gresult) && gresult)
581 if (gresult->gr_gid == (*peer)->gid)
583 xfree (buf);
584 allowed = 1;
585 break;
588 len = sysconf (_SC_GETPW_R_SIZE_MAX);
589 if (len == -1)
590 len = 16384;
592 char *tbuf = xmalloc (len);
593 for (char **t = gresult->gr_mem; *t; t++)
595 if (!getpwnam_r (*t, &pw, tbuf, len, &result) && result)
597 if (result->pw_uid == (*peer)->uid)
599 xfree (buf);
600 allowed = 1;
601 break;
606 xfree (tbuf);
608 if (allowed)
609 break;
612 else
614 size_t len = sysconf (_SC_GETPW_R_SIZE_MAX);
616 if (len == -1)
617 len = 16384;
619 buf = xmalloc (len);
621 if (!buf)
623 strv_free (users);
624 return GPG_ERR_ENOMEM;
627 if (!getpwnam_r (*p, &pw, buf, len, &result) && result)
629 if (result->pw_uid == (*peer)->uid)
631 xfree (buf);
632 allowed = 1;
633 break;
638 xfree (buf);
641 strv_free (users);
644 return allowed ? 0 : GPG_ERR_INV_USER_ID;
646 #else
647 static gpg_error_t
648 do_validate_peer (struct client_s *cl, assuan_peercred_t * peer)
650 char **users;
651 int allowed = 0;
652 gpg_error_t rc;
654 rc = assuan_get_peercred (cl->ctx, peer);
655 if (rc)
656 return rc;
658 users = config_get_list ("global", "allowed");
659 if (users)
661 for (char **p = users; *p; p++)
663 struct passwd *result;
664 struct group *gresult;
666 if (*(*p) == '@')
668 gresult = getgrnam (*(p) + 1);
669 if (gresult && gresult->gr_gid == (*peer)->gid)
671 allowed = 1;
672 break;
675 for (char **t = gresult->gr_mem; *t; t++)
677 result = getpwnam (*t);
678 if (result && result->pw_uid == (*peer)->uid)
680 allowed = 1;
681 break;
685 else
687 result = getpwnam (*p);
688 if (result && result->pw_uid == (*peer)->uid)
690 allowed = 1;
691 break;
695 if (allowed)
696 break;
699 strv_free (users);
702 return allowed ? 0 : GPG_ERR_INV_USER_ID;
704 #endif
706 static gpg_error_t
707 validate_peer (struct client_s *cl)
709 gpg_error_t rc;
710 assuan_peercred_t peer;
712 #ifdef WITH_GNUTLS
713 if (cl->thd->remote)
714 return tls_validate_access (cl, NULL);
715 #endif
717 rc = do_validate_peer (cl, &peer);
718 if (!rc || gpg_err_code (rc) == GPG_ERR_INV_USER_ID)
719 log_write ("peer %s: uid=%i, gid=%i, pid=%i",
720 !rc ? _("accepted") : _("rejected"), peer->uid, peer->gid,
721 peer->pid);
722 else if (rc)
723 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
725 return rc;
728 static void
729 xml_error_cb (void *data, xmlErrorPtr e)
731 struct client_s *client = data;
734 * Keep the first reported error as the one to show in the error
735 * description. Reset in send_error().
737 if (client->xml_error)
738 return;
740 xmlCopyError (e, client->xml_error);
743 static pid_t
744 hook_waitpid (assuan_context_t ctx, pid_t pid, int action,
745 int *status, int options)
747 return waitpid (pid, status, options);
750 static ssize_t
751 hook_read (assuan_context_t ctx, assuan_fd_t fd, void *data, size_t len)
753 #ifdef WITH_GNUTLS
754 struct client_s *client = assuan_get_pointer (ctx);
756 if (client->thd->remote)
757 return tls_read_hook (ctx, (int) fd, data, len);
758 #endif
760 return read ((int) fd, data, len);
763 static ssize_t
764 hook_write (assuan_context_t ctx, assuan_fd_t fd,
765 const void *data, size_t len)
767 #ifdef WITH_GNUTLS
768 struct client_s *client = assuan_get_pointer (ctx);
770 if (client->thd->remote)
771 return tls_write_hook (ctx, (int) fd, data, len);
772 #endif
774 return write ((int) fd, data, len);
777 static int
778 new_connection (struct client_s *cl)
780 gpg_error_t rc;
781 static struct assuan_malloc_hooks mhooks = { xmalloc, xrealloc, xfree };
782 static struct assuan_system_hooks shooks = {
783 ASSUAN_SYSTEM_HOOKS_VERSION,
784 __assuan_usleep,
785 __assuan_pipe,
786 __assuan_close,
787 hook_read,
788 hook_write,
789 //FIXME
790 NULL, //recvmsg
791 NULL, //sendmsg both are used for FD passing
792 __assuan_spawn,
793 hook_waitpid,
794 __assuan_socketpair,
795 __assuan_socket,
796 __assuan_connect
799 #ifdef WITH_GNUTLS
800 if (cl->thd->remote)
802 char *prio = config_get_string ("global", "tls_cipher_suite");
804 cl->thd->tls = tls_init (cl->thd->fd, cl->thd->timeout, prio);
805 xfree (prio);
806 if (!cl->thd->tls)
807 return 0;
809 #endif
811 rc = assuan_new_ext (&cl->ctx, GPG_ERR_SOURCE_DEFAULT, &mhooks,
812 debug_level ? assuan_log_cb : NULL, NULL);
813 if (rc)
814 goto fail;
816 assuan_ctx_set_system_hooks (cl->ctx, &shooks);
817 rc = assuan_init_socket_server (cl->ctx, cl->thd->fd, 2);
818 if (rc)
819 goto fail;
821 assuan_set_pointer (cl->ctx, cl);
822 assuan_set_hello_line (cl->ctx, PACKAGE_STRING);
823 rc = register_commands (cl->ctx);
824 if (rc)
825 goto fail;
827 #ifdef WITH_GNUTLS
828 if (cl->thd->remote)
830 cl->thd->timeout = config_get_integer ("global", "tls_timeout");
831 fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK);
833 #endif
835 rc = assuan_accept (cl->ctx);
836 if (rc)
837 goto fail;
839 rc = validate_peer (cl);
840 /* May not be implemented on all platforms. */
841 if (rc && gpg_err_code (rc) != GPG_ERR_ASS_GENERAL)
842 goto fail;
844 rc = init_client_crypto (&cl->crypto);
845 if (rc)
846 goto fail;
848 #ifdef WITH_AGENT
849 if (use_agent)
850 cl->crypto->agent->client_ctx = cl->ctx;
851 #endif
853 cl->crypto->client_ctx = cl->ctx;
854 xmlSetStructuredErrorFunc (cl, xml_error_cb);
855 return 1;
857 fail:
858 log_write ("%s", pwmd_strerror (rc));
859 return 0;
863 * This is called after a client_thread() terminates. Set with
864 * pthread_cleanup_push().
866 static void
867 cleanup_cb (void *arg)
869 struct client_thread_s *cn = arg;
870 struct client_s *cl = cn->cl;
872 MUTEX_LOCK (&cn_mutex);
873 cn_thread_list = slist_remove (cn_thread_list, cn);
874 MUTEX_UNLOCK (&cn_mutex);
876 if (cl)
878 cleanup_client (cl);
880 #ifdef WITH_GNUTLS
881 if (cn->tls)
883 gnutls_deinit (cn->tls->ses);
884 xfree (cn->tls->fp);
885 xfree (cn->tls);
887 #endif
889 if (!cn->atfork && cl->ctx)
890 assuan_release (cl->ctx);
891 else if (!cn->atfork && cl->thd && cl->thd->fd != -1)
892 close (cl->thd->fd);
894 if (cl->crypto)
895 cleanup_crypto (&cl->crypto);
897 pinentry_free_opts (&cl->pinentry_opts);
898 xfree (cl);
900 else
902 if (cn->fd != -1)
903 close (cn->fd);
906 while (cn->msg_queue)
908 struct status_msg_s *msg = cn->msg_queue;
910 cn->msg_queue = msg->next;
911 xfree (msg->line);
912 xfree (msg);
915 if (!cn->atfork && cn->status_msg_pipe[0] != -1)
916 close (cn->status_msg_pipe[0]);
918 if (!cn->atfork && cn->status_msg_pipe[1] != -1)
919 close (cn->status_msg_pipe[1]);
921 pthread_mutex_destroy (&cn->status_mutex);
923 if (!cn->atfork)
925 log_write (_("exiting, fd=%i"), cn->fd);
926 send_status_all (STATUS_CLIENTS, NULL);
929 xfree (cn);
930 pthread_cond_signal (&quit_cond);
933 void
934 cleanup_all_clients (int atfork)
936 /* This function may be called from pthread_atfork() which requires
937 reinitialization. */
938 if (atfork)
940 pthread_mutexattr_t attr;
942 pthread_mutexattr_init (&attr);
943 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
944 pthread_mutex_init (&cn_mutex, &attr);
945 pthread_mutexattr_destroy (&attr);
946 cache_mutex_init ();
949 MUTEX_LOCK (&cn_mutex);
951 while (slist_length (cn_thread_list))
953 struct client_thread_s *thd = slist_nth_data (cn_thread_list, 0);
955 thd->atfork = atfork;
956 cleanup_cb (thd);
959 exiting = 1;
960 cache_deinit (atfork);
961 MUTEX_UNLOCK (&cn_mutex);
964 static gpg_error_t
965 send_msg_queue (struct client_thread_s *thd)
967 MUTEX_LOCK (&thd->status_mutex);
968 gpg_error_t rc = 0;
969 char c;
971 read (thd->status_msg_pipe[0], &c, 1);
973 while (thd->msg_queue)
975 struct status_msg_s *msg = thd->msg_queue;
977 thd->msg_queue = thd->msg_queue->next;
978 MUTEX_UNLOCK (&thd->status_mutex);
979 rc = send_status (thd->cl->ctx, msg->s, msg->line);
980 MUTEX_LOCK (&thd->status_mutex);
981 xfree (msg->line);
982 xfree (msg);
984 if (rc)
985 break;
988 MUTEX_UNLOCK (&thd->status_mutex);
989 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
990 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
992 return rc;
995 static void *
996 client_thread (void *data)
998 struct client_thread_s *thd = data;
999 struct client_s *cl = xcalloc (1, sizeof (struct client_s));
1001 #ifdef HAVE_PR_SET_NAME
1002 prctl (PR_SET_NAME, "client");
1003 #endif
1004 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1006 if (!cl)
1008 log_write ("%s(%i): %s", __FILE__, __LINE__,
1009 pwmd_strerror (GPG_ERR_ENOMEM));
1010 return NULL;
1013 MUTEX_LOCK (&cn_mutex);
1014 pthread_cleanup_push (cleanup_cb, thd);
1015 thd->cl = cl;
1016 cl->thd = thd;
1017 MUTEX_UNLOCK (&cn_mutex);
1019 if (new_connection (cl))
1021 int finished = 0;
1022 gpg_error_t rc;
1024 send_status_all (STATUS_CLIENTS, NULL);
1025 rc = send_status (cl->ctx, STATUS_CACHE, NULL);
1026 if (rc)
1028 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
1029 finished = 1;
1032 while (!finished)
1034 fd_set rfds;
1035 int n;
1036 int eof;
1038 FD_ZERO (&rfds);
1039 FD_SET (thd->fd, &rfds);
1040 FD_SET (thd->status_msg_pipe[0], &rfds);
1041 n = thd->fd > thd->status_msg_pipe[0]
1042 ? thd->fd : thd->status_msg_pipe[0];
1044 n = select (n + 1, &rfds, NULL, NULL, NULL);
1045 if (n == -1)
1047 log_write ("%s", strerror (errno));
1048 break;
1051 if (FD_ISSET (thd->status_msg_pipe[0], &rfds))
1053 rc = send_msg_queue (thd);
1054 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1055 break;
1058 if (!FD_ISSET (thd->fd, &rfds))
1059 continue;
1061 rc = assuan_process_next (cl->ctx, &eof);
1062 if (rc || eof)
1064 if (gpg_err_code (rc) == GPG_ERR_EOF || eof)
1065 break;
1067 log_write ("assuan_process_next(): rc=%i %s", rc,
1068 pwmd_strerror (rc));
1069 if (rc == gpg_error (GPG_ERR_ETIMEDOUT))
1070 break;
1072 rc = send_error (cl->ctx, rc);
1073 if (rc)
1075 log_write ("assuan_process_done(): rc=%i %s", rc,
1076 pwmd_strerror (rc));
1077 break;
1081 /* Since the msg queue pipe fd's are non-blocking, check for
1082 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1083 * client has already disconnected and will be converted to
1084 * GPG_ERR_EOF during assuan_process_next().
1086 rc = send_msg_queue (thd);
1087 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1088 break;
1092 pthread_cleanup_pop (1);
1093 return NULL;
1096 static int
1097 xml_import (const char *filename, const char *outfile,
1098 const char *keygrip, const char *sign_keygrip,
1099 const char *keyfile, int no_passphrase, const char *cipher,
1100 const char *params, unsigned long s2k_count, uint64_t iterations)
1102 xmlDocPtr doc;
1103 int fd;
1104 struct stat st;
1105 int len;
1106 xmlChar *xmlbuf;
1107 xmlChar *xml;
1108 gpg_error_t rc;
1109 struct crypto_s *crypto = NULL;
1110 void *key = NULL;
1111 size_t keylen = 0;
1112 int algo = cipher ? cipher_string_to_gcrypt ((char *) cipher) :
1113 GCRY_CIPHER_AES256;
1115 if (algo == -1)
1117 log_write ("ERR %i: %s", gpg_error (GPG_ERR_CIPHER_ALGO),
1118 pwmd_strerror (GPG_ERR_CIPHER_ALGO));
1119 return 0;
1122 if (stat (filename, &st) == -1)
1124 log_write ("%s: %s", filename,
1125 pwmd_strerror (gpg_error_from_syserror ()));
1126 return 0;
1129 rc = init_client_crypto (&crypto);
1130 if (rc)
1131 return 0;
1133 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
1134 crypto->save.hdr.flags = set_cipher_flag (crypto->save.hdr.flags, algo);
1135 log_write (_("Importing XML from '%s'. Output will be written to '%s' ..."),
1136 filename, outfile);
1138 if ((fd = open (filename, O_RDONLY)) == -1)
1140 log_write ("%s: %s", filename,
1141 pwmd_strerror (gpg_error_from_syserror ()));
1142 goto fail;
1145 if ((xmlbuf = xmalloc (st.st_size + 1)) == NULL)
1147 close (fd);
1148 log_write ("%s(%i): %s", __FILE__, __LINE__,
1149 pwmd_strerror (GPG_ERR_ENOMEM));
1150 goto fail;
1153 if (read (fd, xmlbuf, st.st_size) == -1)
1155 rc = gpg_error_from_syserror ();
1156 close (fd);
1157 log_write ("%s: %s", filename, pwmd_strerror (rc));
1158 goto fail;
1161 close (fd);
1162 xmlbuf[st.st_size] = 0;
1164 * Make sure the document validates.
1166 if ((doc = xmlReadDoc (xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS)) == NULL)
1168 log_write ("xmlReadDoc() failed");
1169 xfree (xmlbuf);
1170 goto fail;
1173 xfree (xmlbuf);
1174 xmlNodePtr n = xmlDocGetRootElement (doc);
1175 if (n && !xmlStrEqual (n->name, (xmlChar *) "pwmd"))
1177 log_write (_("Could not find root \"pwmd\" element."));
1178 rc = GPG_ERR_BAD_DATA;
1181 if (!rc)
1182 rc = validate_import (n ? n->children : n);
1184 if (rc)
1186 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1187 xmlFreeDoc (doc);
1188 goto fail;
1191 xmlDocDumpMemory (doc, &xml, &len);
1192 xmlFreeDoc (doc);
1193 crypto->save.s2k_count = s2k_count;
1194 crypto->save.hdr.iterations = iterations;
1195 if (!use_agent)
1197 rc = export_common (NULL, 0, crypto, xml, len, outfile, keyfile, &key,
1198 &keylen, 0, 0);
1199 if (!rc)
1200 log_write (_("Success!"));
1202 #ifdef WITH_AGENT
1203 else
1205 rc = agent_set_pinentry_options (crypto->agent);
1206 if (!rc)
1207 rc = agent_export_common (crypto, keygrip, sign_keygrip, no_passphrase,
1208 xml, len, outfile, params, keyfile);
1210 #endif
1212 gcry_free (key);
1213 xmlFree (xml);
1214 if (rc)
1216 send_error (NULL, rc);
1217 goto fail;
1220 cleanup_crypto (&crypto);
1221 return 1;
1223 fail:
1224 cleanup_crypto (&crypto);
1225 return 0;
1228 static int
1229 do_cache_push (const char *filename, struct crypto_s *crypto)
1231 unsigned char md5file[16];
1232 gpg_error_t rc;
1233 char *key = NULL;
1234 size_t keylen = 0;
1235 xmlDocPtr doc;
1236 struct cache_data_s *cdata;
1237 unsigned char *crc;
1238 size_t len;
1240 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1241 filename);
1243 if (valid_filename (filename) == 0)
1245 log_write (_("%s: Invalid characters in filename"), filename);
1246 return 0;
1249 rc = decrypt_common (NULL, 0, crypto, filename, &key, &keylen);
1250 if (rc)
1251 return 0;
1253 doc = parse_doc ((char *) crypto->plaintext, crypto->plaintext_len);
1254 if (!doc)
1256 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM));
1257 xfree (key);
1258 return 0;
1261 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
1262 cdata = xcalloc (1, sizeof (struct cache_data_s));
1263 if (!cdata)
1265 xmlFreeDoc (doc);
1266 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM));
1267 xfree (key);
1268 return 0;
1271 rc = get_checksum (filename, &crc, &len);
1272 if (rc)
1274 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1275 xmlFreeDoc (doc);
1276 free_cache_data_once (cdata);
1277 xfree (key);
1278 return 0;
1281 cdata->crc = crc;
1282 rc = encrypt_xml (NULL, cache_key, cache_keysize, GCRY_CIPHER_AES,
1283 crypto->plaintext, crypto->plaintext_len, &cdata->doc,
1284 &cdata->doclen, &cache_iv, &cache_blocksize, 0);
1285 if (!rc && !IS_PKI (crypto))
1287 cdata->key = key;
1288 cdata->keylen = keylen;
1290 else
1291 xfree (key);
1293 if (rc)
1295 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1296 xmlFreeDoc (doc);
1297 free_cache_data_once (cdata);
1298 return 0;
1301 #ifdef WITH_AGENT
1302 if (use_agent && IS_PKI (crypto))
1304 gcry_sexp_build ((gcry_sexp_t *) & cdata->pubkey, NULL, "%S",
1305 crypto->pkey_sexp);
1306 gcry_sexp_build ((gcry_sexp_t *) & cdata->sigkey, NULL, "%S",
1307 crypto->sigpkey_sexp);
1309 #endif
1311 int timeout = config_get_integer (filename, "cache_timeout");
1312 cache_add_file (md5file, crypto->grip, cdata, timeout);
1313 log_write (_("Successfully added '%s' to the cache."), filename);
1314 return 1;
1317 static gpg_error_t
1318 init_client (int fd, const char *addr)
1320 gpg_error_t rc = 0;
1321 struct client_thread_s *new = xcalloc (1, sizeof (struct client_thread_s));
1323 if (!new)
1325 close (fd);
1326 return GPG_ERR_ENOMEM;
1329 MUTEX_LOCK (&cn_mutex);
1330 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
1332 if (pipe (new->status_msg_pipe) == -1)
1333 rc = gpg_error_from_syserror ();
1335 if (!rc)
1337 fcntl (new->status_msg_pipe[0], F_SETFL, O_NONBLOCK);
1338 fcntl (new->status_msg_pipe[1], F_SETFL, O_NONBLOCK);
1339 pthread_mutex_init (&new->status_mutex, NULL);
1342 if (!rc)
1344 #ifdef WITH_GNUTLS
1345 new->remote = addr ? 1 : 0;
1346 #endif
1347 new->fd = fd;
1348 rc = create_thread (client_thread, new, &new->tid, 1);
1349 if (rc)
1351 close (new->status_msg_pipe[0]);
1352 close (new->status_msg_pipe[1]);
1353 pthread_mutex_destroy (&new->status_mutex);
1357 if (!rc)
1359 struct slist_s *list = slist_append (cn_thread_list, new);
1361 if (list)
1363 cn_thread_list = list;
1364 if (addr)
1365 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1366 (pthread_t *) new->tid, fd, addr);
1367 else
1368 log_write (_("new connection: tid=%p, fd=%i"),
1369 (pthread_t *) new->tid, fd);
1371 else
1372 rc = GPG_ERR_ENOMEM;
1375 pthread_cleanup_pop (1);
1377 if (rc)
1379 xfree (new);
1380 close (fd);
1381 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1382 pwmd_strerror (rc));
1384 return rc;
1387 static void*
1388 keepalive_thread (void *arg)
1390 #ifndef HAVE_PTHREAD_CANCEL
1391 int *n = xmalloc (sizeof (int));
1393 *n = 0;
1394 pthread_setspecific (signal_thread_key, n);
1395 INIT_THREAD_SIGNAL;
1396 #endif
1398 #ifdef HAVE_PR_SET_NAME
1399 prctl (PR_SET_NAME, "keepalive");
1400 #endif
1401 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1403 for (;;)
1405 int n = config_get_integer ("global", "keepalive_interval");
1406 struct timeval tv = { n, 0 };
1407 #ifndef HAVE_PTHREAD_CANCEL
1408 int *sigusr2;
1410 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1411 if (*sigusr2)
1412 break;
1413 #endif
1415 send_status_all (STATUS_KEEPALIVE, NULL);
1416 select (0, NULL, NULL, NULL, &tv);
1419 return NULL;
1422 #ifdef WITH_GNUTLS
1423 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1424 static void *
1425 get_in_addr (struct sockaddr *sa)
1427 if (sa->sa_family == AF_INET)
1428 return &(((struct sockaddr_in *) sa)->sin_addr);
1430 return &(((struct sockaddr_in6 *) sa)->sin6_addr);
1433 static void *
1434 tcp_accept_thread (void *arg)
1436 int sockfd = *(int *) arg;
1437 #ifndef HAVE_PTHREAD_CANCEL
1438 int *n = xmalloc (sizeof (int));
1440 *n = 0;
1441 pthread_setspecific (signal_thread_key, n);
1442 INIT_THREAD_SIGNAL;
1443 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1444 #endif
1446 #ifdef HAVE_PR_SET_NAME
1447 prctl (PR_SET_NAME, "tcp_accept");
1448 #endif
1449 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1451 for (;;)
1453 struct sockaddr_storage raddr;
1454 socklen_t slen = sizeof (raddr);
1455 int fd = -1;
1456 unsigned long n;
1457 char s[INET6_ADDRSTRLEN];
1458 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1459 #ifndef HAVE_PTHREAD_CANCEL
1460 int *sigusr2;
1462 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1463 if (*sigusr2)
1464 break;
1465 #endif
1467 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1468 if (fd == -1)
1470 if (errno == EMFILE || errno == ENFILE)
1471 log_write ("accept(): %s",
1472 pwmd_strerror (gpg_error_from_syserror ()));
1473 else if (errno != EAGAIN)
1475 if (!quit) // probably EBADF
1476 log_write ("accept(): %s", strerror (errno));
1478 break;
1481 #ifndef HAVE_PTHREAD_CANCEL
1482 select (0, NULL, NULL, NULL, &tv);
1483 #endif
1484 continue;
1487 if (quit)
1488 break;
1490 inet_ntop (raddr.ss_family, get_in_addr ((struct sockaddr *) &raddr),
1491 s, sizeof s);
1492 (void) init_client (fd, s);
1493 n = config_get_integer ("global", "tcp_wait");
1494 if (n > 0)
1496 tv.tv_sec = (n * 100000) / 100000;
1497 tv.tv_usec = (n * 100000) % 100000;
1498 select (0, NULL, NULL, NULL, &tv);
1502 return NULL;
1505 static int
1506 start_stop_tls_with_protocol (int ipv6, int term)
1508 struct addrinfo hints, *servinfo, *p;
1509 int port = config_get_integer ("global", "tcp_port");
1510 char buf[7];
1511 int n;
1512 gpg_error_t rc;
1513 int *fd = ipv6 ? &tls6_fd : &tls_fd;
1515 if (term || config_get_boolean ("global", "enable_tcp") == 0)
1517 if (tls6_fd != -1)
1519 if (spawned_tls6)
1521 #ifdef HAVE_PTHREAD_CANCEL
1522 pthread_cancel (tls6_tid);
1523 #else
1524 pthread_kill (tls6_tid, SIGUSR2);
1525 #endif
1526 pthread_join (tls6_tid, NULL);
1529 shutdown (tls6_fd, SHUT_RDWR);
1530 close (tls6_fd);
1531 tls6_fd = -1;
1532 spawned_tls6 = 0;
1535 if (tls_fd != -1)
1537 if (spawned_tls)
1539 #ifdef HAVE_PTHREAD_CANCEL
1540 pthread_cancel (tls_tid);
1541 #else
1542 pthread_kill (tls_tid, SIGUSR2);
1543 #endif
1544 pthread_join (tls_tid, NULL);
1547 shutdown (tls_fd, SHUT_RDWR);
1548 close (tls_fd);
1549 tls_fd = -1;
1550 spawned_tls = 0;
1553 /* A client may still be connected. */
1554 if (!quit && x509_cred != NULL)
1555 tls_deinit_params ();
1557 return 1;
1560 if ((ipv6 && tls6_fd != -1) || (!ipv6 && tls_fd != -1))
1561 return 1;
1563 memset (&hints, 0, sizeof (hints));
1564 hints.ai_family = ipv6 ? AF_INET6 : AF_INET;
1565 hints.ai_socktype = SOCK_STREAM;
1566 hints.ai_flags = AI_PASSIVE;
1567 snprintf (buf, sizeof (buf), "%i", port);
1569 if ((n = getaddrinfo (NULL, buf, &hints, &servinfo)) == -1)
1571 log_write ("getaddrinfo(): %s", gai_strerror (n));
1572 return 0;
1575 for (n = 0, p = servinfo; p != NULL; p = p->ai_next)
1577 int r = 1;
1579 if ((ipv6 && p->ai_family != AF_INET6)
1580 || (!ipv6 && p->ai_family != AF_INET))
1581 continue;
1583 if ((*fd = socket (p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
1585 log_write ("socket(): %s", strerror (errno));
1586 continue;
1589 if (setsockopt (*fd, SOL_SOCKET, SO_REUSEADDR, &r, sizeof (int)) == -1)
1591 log_write ("setsockopt(): %s",
1592 pwmd_strerror (gpg_error_from_syserror ()));
1593 freeaddrinfo (servinfo);
1594 goto fail;
1597 if (bind (*fd, p->ai_addr, p->ai_addrlen) == -1)
1599 close (*fd);
1600 log_write ("bind(): %s",
1601 pwmd_strerror (gpg_error_from_syserror ()));
1602 continue;
1605 n++;
1606 break;
1609 freeaddrinfo (servinfo);
1611 if (!n)
1612 goto fail;
1614 #if HAVE_DECL_SO_BINDTODEVICE != 0
1615 char *tmp = config_get_string ("global", "tcp_interface");
1616 if (tmp && setsockopt (*fd, SOL_SOCKET, SO_BINDTODEVICE, tmp,
1617 strlen (tmp)) == -1)
1619 log_write ("setsockopt(): %s",
1620 pwmd_strerror (gpg_error_from_syserror ()));
1621 xfree (tmp);
1622 goto fail;
1625 xfree (tmp);
1626 #endif
1628 if (x509_cred == NULL)
1630 rc = tls_init_params ();
1631 if (rc)
1632 goto fail;
1635 if (listen (*fd, 0) == -1)
1637 log_write ("listen(): %s", strerror (errno));
1638 goto fail;
1641 if (ipv6)
1642 rc = create_thread (tcp_accept_thread, fd, &tls6_tid, 0);
1643 else
1644 rc = create_thread (tcp_accept_thread, fd, &tls_tid, 0);
1646 if (rc)
1648 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1649 pwmd_strerror (rc));
1650 goto fail;
1653 if (ipv6)
1654 spawned_tls6 = 1;
1655 else
1656 spawned_tls = 1;
1658 return 1;
1660 fail:
1661 start_stop_tls_with_protocol (0, 1);
1662 if (tls_fd != -1)
1663 close (tls_fd);
1665 if (tls6_fd != -1)
1666 close (tls6_fd);
1668 tls_fd = -1;
1669 tls6_fd = -1;
1670 return 0;
1673 static int
1674 start_stop_tls (int term)
1676 char *s = config_get_string ("global", "tcp_bind");
1677 int b;
1679 if (!s)
1680 return 0;
1682 if (!strcmp (s, "any"))
1684 b = start_stop_tls_with_protocol (0, term);
1685 if (b)
1686 b = start_stop_tls_with_protocol (1, term);
1688 else if (!strcmp (s, "ipv4"))
1689 b = start_stop_tls_with_protocol (0, term);
1690 else if (!strcmp (s, "ipv6"))
1691 b = start_stop_tls_with_protocol (1, term);
1692 else
1693 b = 0;
1695 xfree (s);
1696 return b;
1698 #endif
1700 static void *
1701 accept_thread (void *arg)
1703 int sockfd = *(int *) arg;
1704 #ifndef HAVE_PTHREAD_CANCEL
1705 int *n = xmalloc (sizeof (int));
1707 *n = 0;
1708 pthread_setspecific (signal_thread_key, n);
1709 INIT_THREAD_SIGNAL;
1710 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1711 #endif
1713 #ifdef HAVE_PR_SET_NAME
1714 prctl (PR_SET_NAME, "accept");
1715 #endif
1716 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1718 for (;;)
1720 socklen_t slen = sizeof (struct sockaddr_un);
1721 struct sockaddr_un raddr;
1722 int fd;
1723 #ifndef HAVE_PTHREAD_CANCEL
1724 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1725 int *sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1727 if (*sigusr2)
1728 break;
1729 #endif
1731 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1732 if (fd == -1)
1734 if (errno == EMFILE || errno == ENFILE)
1735 log_write ("accept(): %s",
1736 pwmd_strerror (gpg_error_from_syserror ()));
1737 else if (errno != EAGAIN)
1739 if (!quit) // probably EBADF
1740 log_write ("accept(): %s",
1741 pwmd_strerror (gpg_error_from_syserror ()));
1743 break;
1746 #ifndef HAVE_PTHREAD_CANCEL
1747 select (0, NULL, NULL, NULL, &tv);
1748 #endif
1749 continue;
1752 (void) init_client (fd, NULL);
1755 /* Just in case accept() failed for some reason other than EBADF */
1756 quit = 1;
1757 return NULL;
1760 static void *
1761 cache_timer_thread (void *arg)
1763 #ifndef HAVE_PTHREAD_CANCEL
1764 int *n = xmalloc (sizeof (int));
1766 *n = 0;
1767 pthread_setspecific (signal_thread_key, n);
1768 INIT_THREAD_SIGNAL;
1769 #endif
1771 #ifdef HAVE_PR_SET_NAME
1772 prctl (PR_SET_NAME, "cache timer");
1773 #endif
1774 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1776 for (;;)
1778 struct timeval tv = { 1, 0 };
1779 #ifndef HAVE_PTHREAD_CANCEL
1780 int *n;
1782 n = (int *) pthread_getspecific (signal_thread_key);
1783 if (*n)
1784 break;
1785 #endif
1787 select (0, NULL, NULL, NULL, &tv);
1788 cache_adjust_timeout ();
1791 return NULL;
1794 static void
1795 catch_sigabrt (int sig)
1797 cache_clear (NULL);
1798 #ifndef MEM_DEBUG
1799 xpanic ();
1800 #endif
1803 static int
1804 signal_loop (sigset_t sigset)
1806 int done = 0;
1807 int siint = 0;
1811 int sig;
1813 sigwait (&sigset, &sig);
1815 if (sig != SIGQUIT)
1816 log_write (_("caught signal %i (%s)"), sig, strsignal (sig));
1818 switch (sig)
1820 case SIGHUP:
1821 pthread_cond_signal (&rcfile_cond);
1822 break;
1823 case SIGABRT:
1824 // not really handled here.
1825 catch_sigabrt (SIGABRT);
1826 break;
1827 case SIGUSR1:
1828 log_write (_("clearing file cache"));
1829 cache_clear (NULL);
1830 send_status_all (STATUS_CACHE, NULL);
1831 break;
1832 case SIGQUIT:
1833 done = 1;
1834 break;
1835 default:
1836 siint = 1;
1837 done = 1;
1838 break;
1841 while (!done);
1843 return siint;
1846 static void
1847 catchsig (int sig)
1849 log_write ("Caught SIGSEGV. Exiting.");
1850 #ifdef HAVE_BACKTRACE
1851 BACKTRACE (__FUNCTION__);
1852 #endif
1853 longjmp (jmp, 1);
1856 static void *
1857 waiting_for_exit (void *arg)
1859 int last = 0;
1860 #ifndef HAVE_PTHREAD_CANCEL
1861 int *n = xmalloc (sizeof (int));
1863 *n = 0;
1864 pthread_setspecific (signal_thread_key, n);
1865 INIT_THREAD_SIGNAL;
1866 #endif
1868 #ifdef HAVE_PR_SET_NAME
1869 prctl (PR_SET_NAME, "exiting");
1870 #endif
1871 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1872 log_write (_("waiting for all clients to disconnect"));
1873 MUTEX_LOCK (&quit_mutex);
1874 pthread_cleanup_push (cleanup_mutex_cb, &quit_mutex);
1876 for (;;)
1878 struct timespec ts;
1879 int n;
1881 MUTEX_LOCK (&cn_mutex);
1882 n = slist_length (cn_thread_list);
1883 MUTEX_UNLOCK (&cn_mutex);
1884 if (!n)
1885 break;
1887 #ifndef HAVE_PTHREAD_CANCEL
1888 int *s = (int *) pthread_getspecific (signal_thread_key);
1889 if (*s)
1890 break;
1891 #endif
1893 if (last != n)
1895 log_write (_("%i clients remain"), n);
1896 last = n;
1899 INIT_TIMESPEC (SIG_TIMEOUT, ts);
1900 pthread_cond_timedwait (&quit_cond, &quit_mutex, &ts);
1903 kill (getpid (), SIGQUIT);
1904 pthread_cleanup_pop (1);
1905 return NULL;
1908 static int
1909 server_loop (int sockfd, char **socketpath)
1911 pthread_t accept_tid;
1912 pthread_t cache_timeout_tid;
1913 int cancel_timeout_thread = 0, cancel_accept_thread = 0;
1914 int cancel_keepalive_thread = 0;
1915 sigset_t sigset;
1916 int n;
1917 int segv = 0;
1918 gpg_error_t rc;
1920 init_commands ();
1921 sigemptyset (&sigset);
1923 /* Termination */
1924 sigaddset (&sigset, SIGTERM);
1925 sigaddset (&sigset, SIGINT);
1927 /* Clears the file cache. */
1928 sigaddset (&sigset, SIGUSR1);
1930 /* Configuration file reloading. */
1931 sigaddset (&sigset, SIGHUP);
1933 /* For exiting cleanly. */
1934 sigaddset (&sigset, SIGQUIT);
1936 #ifndef HAVE_PTHREAD_CANCEL
1938 The socket, cache and rcfile threads use this signal when
1939 pthread_cancel() is unavailable. Prevent the main thread from
1940 catching this signal from another process.
1942 sigaddset (&sigset, SIGUSR2);
1943 #endif
1945 /* Clears the cache and exits when something bad happens. */
1946 signal (SIGABRT, catch_sigabrt);
1947 sigaddset (&sigset, SIGABRT);
1948 sigprocmask (SIG_BLOCK, &sigset, NULL);
1950 #ifndef HAVE_PTHREAD_CANCEL
1951 /* Remove this signal from the watched signals in signal_loop(). */
1952 sigdelset (&sigset, SIGUSR2);
1953 #endif
1955 /* Ignored everywhere. When a client disconnects abnormally this signal
1956 * gets raised. It isn't needed though because client_thread() will check
1957 * for rcs even after the client disconnects. */
1958 signal (SIGPIPE, SIG_IGN);
1960 /* Can show a backtrace of the stack in the log. */
1961 signal (SIGSEGV, catchsig);
1963 #ifdef WITH_GNUTLS
1964 /* Needs to be done after the fork(). */
1965 if (!start_stop_tls (0))
1967 segv = 1;
1968 goto done;
1970 #endif
1972 pthread_mutex_init (&quit_mutex, NULL);
1973 pthread_cond_init (&quit_cond, NULL);
1974 log_write (_("%s started for user %s"), PACKAGE_STRING, get_username ());
1976 #ifdef WITH_GNUTLS
1977 if (config_get_boolean ("global", "enable_tcp"))
1978 log_write (_("Listening on %s and TCP port %i"), *socketpath,
1979 config_get_integer ("global", "tcp_port"));
1980 else
1981 log_write (_("Listening on %s"), *socketpath);
1982 #else
1983 log_write (_("Listening on %s"), *socketpath);
1984 #endif
1986 rc = create_thread (keepalive_thread, NULL, &keepalive_tid, 0);
1987 if (rc)
1989 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1990 pwmd_strerror (rc));
1991 goto done;
1994 cancel_keepalive_thread = 1;
1995 rc = create_thread (reload_rcfile_thread, NULL, &rcfile_tid, 0);
1996 if (rc)
1998 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1999 pwmd_strerror (rc));
2000 goto done;
2003 rc = create_thread (cache_timer_thread, NULL, &cache_timeout_tid, 0);
2004 if (rc)
2006 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2007 pwmd_strerror (rc));
2008 goto done;
2011 cancel_timeout_thread = 1;
2012 rc = create_thread (accept_thread, &sockfd, &accept_tid, 0);
2013 if (rc)
2015 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2016 pwmd_strerror (rc));
2017 goto done;
2020 cancel_accept_thread = 1;
2021 if (!setjmp (jmp))
2022 signal_loop (sigset);
2023 else
2024 segv = 1;
2026 done:
2028 * We're out of the main server loop. This happens when a signal was sent
2029 * to terminate the daemon. We'll wait for all clients to disconnect
2030 * before exiting but exit immediately if another termination signal is
2031 * sent.
2033 if (cancel_accept_thread)
2035 #ifdef HAVE_PTHREAD_CANCEL
2036 int n = pthread_cancel (accept_tid);
2037 #else
2038 int n = pthread_kill (accept_tid, SIGUSR2);
2039 #endif
2040 if (!n)
2041 pthread_join (accept_tid, NULL);
2044 #ifdef WITH_GNUTLS
2045 start_stop_tls (1);
2046 #endif
2047 shutdown (sockfd, SHUT_RDWR);
2048 close (sockfd);
2049 unlink (*socketpath);
2050 xfree (*socketpath);
2051 *socketpath = NULL;
2052 MUTEX_LOCK (&cn_mutex);
2053 n = slist_length (cn_thread_list);
2054 MUTEX_UNLOCK (&cn_mutex);
2056 if (n && !segv)
2058 pthread_t tid;
2060 rc = create_thread (waiting_for_exit, NULL, &tid, 0);
2061 if (!rc)
2063 if (signal_loop (sigset))
2065 log_write (_("Received second termination request. Exiting."));
2066 #ifdef HAVE_PTHREAD_CANCEL
2067 pthread_cancel (tid);
2068 #else
2069 pthread_kill (tid, SIGUSR2);
2070 #endif
2071 pthread_join (tid, NULL);
2074 else
2075 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2076 pwmd_strerror (rc));
2079 if (cancel_timeout_thread)
2081 #ifdef HAVE_PTHREAD_CANCEL
2082 pthread_cancel (cache_timeout_tid);
2083 #else
2084 pthread_kill (cache_timeout_tid, SIGUSR2);
2085 #endif
2086 pthread_join (cache_timeout_tid, NULL);
2089 if (cancel_keepalive_thread)
2091 #ifdef HAVE_PTHREAD_CANCEL
2092 pthread_cancel (keepalive_tid);
2093 #else
2094 pthread_kill (keepalive_tid, SIGUSR2);
2095 #endif
2096 pthread_join (keepalive_tid, NULL);
2099 cleanup_all_clients (0);
2100 #ifdef WITH_GNUTLS
2101 start_stop_tls (1);
2102 #endif
2103 deinit_commands ();
2104 pthread_cond_destroy (&quit_cond);
2105 pthread_mutex_destroy (&quit_mutex);
2106 return segv ? EXIT_FAILURE : EXIT_SUCCESS;;
2109 static void
2110 startup_failure ()
2112 log_write (_
2113 ("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
2114 cache_clear (NULL);
2117 /* This is called from cache.c:clear_once(). See
2118 * command.c:clearcache_command() for details about lock checking.
2120 static gpg_error_t
2121 free_cache_data (file_cache_t * cache)
2123 gpg_error_t rc = GPG_ERR_NO_DATA;
2124 int i, t;
2125 struct client_thread_s *found = NULL;
2126 int self = 0;
2128 if (!cache->data)
2129 return 0;
2131 cache_lock ();
2132 MUTEX_LOCK (&cn_mutex);
2133 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
2134 t = slist_length (cn_thread_list);
2136 for (i = 0; i < t; i++)
2138 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2140 if (!thd->cl)
2141 continue;
2143 if (!memcmp (thd->cl->md5file, cache->filename,
2144 sizeof (cache->filename)))
2146 if (pthread_equal (pthread_self (), thd->tid))
2148 found = thd;
2149 self = 1;
2150 continue;
2153 /* Continue trying to find a client who has the same file open and
2154 * also has a lock. */
2155 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0, -1);
2156 if (!rc)
2158 self = 0;
2159 found = thd;
2160 break;
2165 if (self && (!rc || rc == GPG_ERR_NO_DATA))
2166 rc = cache_lock_mutex (found->cl->ctx, found->cl->md5file, -1, 0, -1);
2168 if (exiting || !rc || rc == GPG_ERR_NO_DATA)
2170 free_cache_data_once (cache->data);
2171 cache->data = NULL;
2172 cache->defer_clear = 0;
2173 cache->timeout = -1;
2175 if (found)
2176 cache_unlock_mutex (found->cl->md5file, 0);
2178 rc = 0;
2181 if (rc)
2182 cache->defer_clear = 1;
2184 pthread_cleanup_pop (1);
2185 cache_unlock ();
2186 return rc;
2189 static int
2190 convert_v2_datafile (const char *filename, const char *cipher,
2191 const char *keyfile, const char *keygrip,
2192 const char *sign_keygrip, int nopass,
2193 const char *outfile, const char *keyparam,
2194 unsigned long s2k_count, uint64_t iterations)
2196 gpg_error_t rc;
2197 void *data = NULL;
2198 size_t datalen;
2199 struct crypto_s *crypto = NULL;
2200 uint16_t ver;
2201 int algo;
2202 void *key = NULL;
2203 size_t keylen = 0;
2205 if (outfile[0] == '-' && outfile[1] == 0)
2206 outfile = NULL;
2208 log_write (_("Converting version 2 data file \"%s\" ..."), filename);
2209 if (access (filename, R_OK) == -1)
2211 log_write ("%s: %s", filename,
2212 pwmd_strerror (gpg_error_from_syserror ()));
2213 return 0;
2216 if (keyfile)
2218 log_write (_("Using passphrase file \"%s\" for decryption ..."),
2219 keyfile);
2220 if (access (keyfile, R_OK) == -1)
2222 log_write ("%s: %s", keyfile,
2223 pwmd_strerror (gpg_error_from_syserror ()));
2224 return 0;
2228 rc = read_v2_datafile (filename, keyfile, &data, &datalen, &ver, &algo);
2229 if (rc)
2231 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2232 return 0;
2235 if (cipher)
2237 algo = cipher_string_to_gcrypt (cipher);
2238 if (algo == -1)
2240 rc = GPG_ERR_CIPHER_ALGO;
2241 goto fail;
2245 if (ver < 0x212)
2247 xmlDocPtr doc = parse_doc (data, datalen);
2249 if (!doc)
2251 rc = GPG_ERR_BAD_DATA;
2252 goto fail;
2255 rc = convert_pre_212_elements (doc);
2256 gcry_free (data);
2257 data = NULL;
2258 if (!rc)
2260 xmlDocDumpFormatMemory (doc, (xmlChar **) & data, (int *) &datalen,
2262 if (!data)
2263 rc = GPG_ERR_ENOMEM;
2266 xmlFreeDoc (doc);
2267 if (rc)
2268 goto fail;
2271 rc = init_client_crypto (&crypto);
2272 if (!rc)
2274 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
2275 crypto->save.hdr.flags = set_cipher_flag (crypto->save.hdr.flags, algo);
2276 crypto->save.s2k_count = s2k_count;
2277 crypto->save.hdr.iterations = iterations;
2279 if (!use_agent)
2281 rc = export_common (NULL, 0, crypto, data, datalen, outfile, keyfile,
2282 &key, &keylen, 0, 0);
2284 #ifdef WITH_AGENT
2285 else
2287 rc = agent_set_pinentry_options (crypto->agent);
2288 if (!rc)
2289 rc = agent_export_common (crypto, keygrip, sign_keygrip, nopass,
2290 data, datalen, outfile, keyparam,
2291 no_passphrase_file ? NULL : keyfile);
2293 #endif
2294 if (!rc)
2295 log_write (_("Output written to \"%s\"."), outfile);
2298 fail:
2299 if (ver < 0x212)
2300 xmlFree (data);
2301 else
2302 gcry_free (data);
2304 gcry_free (key);
2305 cleanup_crypto (&crypto);
2307 if (rc)
2308 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2309 return rc ? 0 : 1;
2312 static void
2313 usage (const char *pn, int status)
2315 FILE *fp = status == EXIT_FAILURE ? stderr : stdout;
2317 fprintf (fp, _("Usage: %s [OPTIONS] [file1] [...]\n"
2318 " -f, --rcfile=filename load the specfied configuration file\n"
2319 " (~/.pwmd/config)\n"
2320 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2321 #ifdef WITH_AGENT
2322 " --use-agent enable use of gpg-agent\n"
2323 #endif
2324 " -n, --no-fork run as a foreground process\n"
2325 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2326 " --ignore ignore file errors during startup\n"
2327 " --debug-level=keywords log protocol output (see manual for details)\n"
2328 " -o, --outfile=filename output file when importing or converting\n"
2329 " -C, --convert=filename convert a version 2 data file to version 3\n"
2330 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2331 " -k, --passphrase-file=file for use when importing or converting\n"
2332 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2333 " converting\n"
2334 " --no-passphrase when importing or converting\n"
2335 " --keygrip=hex public key to use when encrypting\n"
2336 " --sign-keygrip=hex private key to use when signing\n"
2337 " --keyparam=s-exp custom key parameters to use (RSA-2048)\n"
2338 " --cipher=string encryption cipher (aes256)\n"
2339 " --iterations=N cipher iteration count (N+1)\n"
2340 " --s2k-count=N hash iteration count (>65536, calibrated)\n"
2341 " --help this help text\n"
2342 " --version show version and compile time features\n"),
2343 pn);
2344 exit (status);
2348 main (int argc, char *argv[])
2350 int opt;
2351 struct sockaddr_un addr;
2352 char buf[PATH_MAX];
2353 char *socketpath = NULL, *socketdir, *socketname = NULL;
2354 char *socketarg = NULL;
2355 char *datadir = NULL;
2356 int x;
2357 char *p;
2358 char **cache_push = NULL;
2359 char *import = NULL, *keygrip = NULL, *sign_keygrip = NULL;
2360 char *keyparam = NULL;
2361 int estatus = EXIT_FAILURE;
2362 int sockfd;
2363 char *outfile = NULL;
2364 int do_unlink = 0;
2365 int secure = 0;
2366 int show_version = 0;
2367 int force = 0;
2368 int no_passphrase = 0;
2369 gpg_error_t rc;
2370 char *convertfile = NULL;
2371 char *cipher = NULL;
2372 char *keyfile = NULL;
2373 unsigned long s2k_count = 0;
2374 uint64_t iterations = 0;
2375 int exists;
2376 char *debug_level_opt = NULL;
2377 int optindex;
2378 /* Must maintain the same order as longopts[] */
2379 enum
2381 OPT_VERSION, OPT_HELP,
2382 #ifdef WITH_AGENT
2383 OPT_AGENT,
2384 #endif
2385 OPT_DEBUG_LEVEL, OPT_HOMEDIR, OPT_NO_FORK, OPT_DISABLE_DUMP, OPT_IGNORE,
2386 OPT_RCFILE, OPT_CONVERT, OPT_PASSPHRASE_FILE, OPT_IMPORT, OPT_OUTFILE,
2387 OPT_NO_PASSPHRASE_FILE, OPT_KEYGRIP, OPT_SIGN_KEYGRIP, OPT_KEYPARAM,
2388 OPT_CIPHER, OPT_ITERATIONS, OPT_S2K_COUNT, OPT_NO_PASSPHRASE
2390 const char *optstring = "nf:C:k:I:o:";
2391 const struct option longopts[] = {
2392 {"version", no_argument, 0, 0},
2393 {"help", no_argument, 0, 0},
2394 #ifdef WITH_AGENT
2395 {"use-agent", no_argument, 0, 0},
2396 #endif
2397 {"debug-level", required_argument, 0, 0},
2398 {"homedir", required_argument, 0, 0},
2399 {"no-fork", no_argument, 0, 'n'},
2400 {"disable_dump", no_argument, 0, 0},
2401 {"ignore", no_argument, 0, 0},
2402 {"rcfile", required_argument, 0, 'f'},
2403 {"convert", required_argument, 0, 'C'},
2404 {"passphrase-file", required_argument, 0, 'k'},
2405 {"import", required_argument, 0, 'I'},
2406 {"outfile", required_argument, 0, 'o'},
2407 {"no-passphrase-file", no_argument, 0, 0},
2408 {"keygrip", required_argument, 0, 0},
2409 {"sign-keygrip", required_argument, 0, 0},
2410 {"keyparam", required_argument, 0, 0},
2411 {"cipher", required_argument, 0, 0},
2412 {"cipher-iterations", required_argument, 0, 0},
2413 {"s2k-count", required_argument, 0, 0},
2414 {"no-passphrase", no_argument, 0, 0},
2415 {0, 0, 0, 0}
2418 #ifndef DEBUG
2419 #ifdef HAVE_SETRLIMIT
2420 struct rlimit rl;
2422 rl.rlim_cur = rl.rlim_max = 0;
2424 if (setrlimit (RLIMIT_CORE, &rl) != 0)
2425 err (EXIT_FAILURE, "setrlimit()");
2426 #endif
2427 #endif
2429 #ifdef ENABLE_NLS
2430 setlocale (LC_ALL, "");
2431 bindtextdomain ("pwmd", LOCALEDIR);
2432 textdomain ("pwmd");
2433 #endif
2435 #ifndef MEM_DEBUG
2436 xmem_init ();
2437 #endif
2438 gpg_err_init ();
2440 if (setup_crypto ())
2441 exit (EXIT_FAILURE);
2443 #ifdef WITH_GNUTLS
2444 gnutls_global_set_mem_functions (xmalloc, xmalloc, secure_mem_check,
2445 xrealloc, xfree);
2446 gnutls_global_init ();
2447 gnutls_global_set_log_function (tls_log);
2448 gnutls_global_set_log_level (1);
2449 tls_fd = -1;
2450 tls6_fd = -1;
2451 #endif
2452 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
2453 xmlInitMemory ();
2454 xmlInitGlobals ();
2455 xmlInitParser ();
2456 xmlXPathInit ();
2457 cmdline = 1;
2458 use_agent = 0;
2460 while ((opt = getopt_long (argc, argv, optstring, longopts, &optindex))
2461 != -1)
2463 switch (opt)
2465 case 'I':
2466 import = optarg;
2467 break;
2468 case 'C':
2469 convertfile = optarg;
2470 break;
2471 case 'k':
2472 keyfile = optarg;
2473 break;
2474 case 'o':
2475 outfile = optarg;
2476 break;
2477 case 'D':
2478 secure = 1;
2479 break;
2480 case 'n':
2481 nofork = 1;
2482 break;
2483 case 'f':
2484 rcfile = str_dup (optarg);
2485 break;
2486 default:
2487 usage (argv[0], EXIT_FAILURE);
2488 break;
2489 case 0:
2490 switch (optindex)
2492 case OPT_VERSION:
2493 show_version = 1;
2494 break;
2495 case OPT_HELP:
2496 usage (argv[0], 0);
2497 break;
2498 #ifdef WITH_AGENT
2499 case OPT_AGENT:
2500 use_agent = 1;
2501 break;
2502 #endif
2503 case OPT_DEBUG_LEVEL:
2504 debug_level_opt = optarg;
2505 break;
2506 case OPT_HOMEDIR:
2507 homedir = str_dup (optarg);
2508 break;
2509 case OPT_NO_FORK:
2510 nofork = 1;
2511 break;
2512 case OPT_DISABLE_DUMP:
2513 secure = 1;
2514 break;
2515 case OPT_IGNORE:
2516 force = 1;
2517 break;
2518 case OPT_RCFILE:
2519 rcfile = str_dup (optarg);
2520 break;
2521 case OPT_CONVERT:
2522 convertfile = optarg;
2523 break;
2524 case OPT_PASSPHRASE_FILE:
2525 keyfile = optarg;
2526 break;
2527 case OPT_IMPORT:
2528 import = optarg;
2529 break;
2530 case OPT_OUTFILE:
2531 outfile = optarg;
2532 break;
2533 case OPT_NO_PASSPHRASE_FILE:
2534 no_passphrase_file = 1;
2535 break;
2536 case OPT_KEYGRIP:
2537 keygrip = optarg;
2538 break;
2539 case OPT_SIGN_KEYGRIP:
2540 sign_keygrip = optarg;
2541 break;
2542 case OPT_KEYPARAM:
2543 keyparam = optarg;
2544 break;
2545 case OPT_CIPHER:
2546 cipher = optarg;
2547 break;
2548 case OPT_ITERATIONS:
2549 iterations = strtoull (optarg, NULL, 10);
2550 break;
2551 case OPT_S2K_COUNT:
2552 s2k_count = strtoul (optarg, NULL, 10);
2553 break;
2554 case OPT_NO_PASSPHRASE:
2555 no_passphrase = 1;
2556 break;
2557 default:
2558 usage (argv[0], 1);
2563 if (show_version)
2565 printf (_("%s\n\n"
2566 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013\n"
2567 "%s\n"
2568 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2569 "Compile time features:\n%s"), PACKAGE_STRING,
2570 PACKAGE_BUGREPORT,
2571 #ifdef PWMD_HOMEDIR
2572 "+PWMD_HOMEDIR=" PWMD_HOMEDIR "\n"
2573 #endif
2574 #ifdef WITH_AGENT
2575 "+WITH_AGENT\n"
2576 #else
2577 "-WITH_AGENT\n"
2578 #endif
2579 #ifdef WITH_QUALITY
2580 "+WITH_QUALITY\n"
2581 #else
2582 "-WITH_QUALITY\n"
2583 #endif
2584 #ifdef WITH_GNUTLS
2585 "+WITH_GNUTLS\n"
2586 #else
2587 "-WITH_GNUTLS\n"
2588 #endif
2589 #ifdef WITH_LIBACL
2590 "+WITH_LIBACL\n"
2591 #else
2592 "-WITH_LIBACL\n"
2593 #endif
2594 #ifdef DEBUG
2595 "+DEBUG\n"
2596 #else
2597 "-DEBUG\n"
2598 #endif
2599 #ifdef MEM_DEBUG
2600 "+MEM_DEBUG\n"
2601 #else
2602 "-MEM_DEBUG\n"
2603 #endif
2604 #ifdef MUTEX_DEBUG
2605 "+MUTEX_DEBUG\n"
2606 #else
2607 "-MUTEX_DEBUG\n"
2608 #endif
2610 exit (EXIT_SUCCESS);
2613 if (!homedir)
2614 #ifdef PWMD_HOMEDIR
2615 homedir = str_dup(PWMD_HOMEDIR);
2616 #else
2617 homedir = str_asprintf ("%s/.pwmd", get_home_dir ());
2618 #endif
2620 if (mkdir (homedir, 0700) == -1 && errno != EEXIST)
2621 err (EXIT_FAILURE, "%s", homedir);
2623 snprintf (buf, sizeof (buf), "%s/data", homedir);
2624 if (mkdir (buf, 0700) == -1 && errno != EEXIST)
2625 err (EXIT_FAILURE, "%s", buf);
2627 datadir = str_dup (buf);
2628 pthread_mutexattr_t attr;
2629 pthread_mutexattr_init (&attr);
2630 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
2631 pthread_mutex_init (&rcfile_mutex, &attr);
2632 pthread_cond_init (&rcfile_cond, NULL);
2633 pthread_mutex_init (&cn_mutex, &attr);
2634 pthread_mutexattr_destroy (&attr);
2635 pthread_key_create (&last_error_key, free_key);
2636 #ifndef HAVE_PTHREAD_CANCEL
2637 pthread_key_create (&signal_thread_key, free_key);
2638 #endif
2640 if (!rcfile)
2641 rcfile = str_asprintf ("%s/config", homedir);
2643 global_config = config_parse (rcfile);
2644 if (!global_config)
2645 exit (EXIT_FAILURE);
2647 #ifdef WITH_AGENT
2648 if (!use_agent)
2649 use_agent = config_get_boolean ("global", "use_agent");
2650 #endif
2652 setup_logging ();
2654 if (debug_level_opt)
2655 debug_level = str_split (debug_level_opt, ",", 0);
2657 x = config_get_int_param (global_config, "global", "priority", &exists);
2658 if (exists && x != atoi(INVALID_PRIORITY))
2660 errno = 0;
2661 if (setpriority (PRIO_PROCESS, 0, x) == -1)
2663 log_write ("setpriority(): %s",
2664 pwmd_strerror (gpg_error_from_syserror ()));
2665 goto do_exit;
2668 #ifdef HAVE_MLOCKALL
2669 if (disable_mlock == 0 && mlockall (MCL_CURRENT | MCL_FUTURE) == -1)
2671 log_write ("mlockall(): %s",
2672 pwmd_strerror (gpg_error_from_syserror ()));
2673 goto do_exit;
2675 #endif
2677 rc = cache_init (free_cache_data);
2678 if (rc)
2680 log_write ("pwmd: ERR %i: %s", rc,
2681 gpg_err_code (rc) == GPG_ERR_UNKNOWN_VERSION
2682 ? _("incompatible gpg-agent version: 2.1.0 or later required")
2683 : pwmd_strerror (rc));
2684 goto do_exit;
2687 if (s2k_count == 0)
2688 s2k_count = config_get_ulong (NULL, "s2k_count");
2690 if (convertfile)
2692 if (!outfile)
2693 usage (argv[0], EXIT_FAILURE);
2695 estatus = convert_v2_datafile (convertfile, cipher, keyfile, keygrip,
2696 sign_keygrip, no_passphrase, outfile,
2697 keyparam, s2k_count, iterations);
2698 config_free (global_config);
2699 xfree (rcfile);
2700 exit (!estatus);
2703 if (import)
2705 if (!outfile || !*outfile)
2706 usage (argv[0], EXIT_FAILURE);
2708 if (outfile && outfile[0] == '-' && outfile[1] == 0)
2709 outfile = NULL;
2711 estatus = xml_import (import, outfile, keygrip, sign_keygrip, keyfile,
2712 no_passphrase, cipher, keyparam, s2k_count,
2713 iterations);
2714 config_free (global_config);
2715 xfree (rcfile);
2716 exit (!estatus);
2719 p = config_get_string ("global", "socket_path");
2720 if (!p)
2721 p = str_asprintf ("%s/socket", homedir);
2723 socketarg = expand_homedir (p);
2724 xfree (p);
2726 if (!secure)
2727 disable_list_and_dump = config_get_boolean ("global",
2728 "disable_list_and_dump");
2729 else
2730 disable_list_and_dump = secure;
2732 cache_push = config_get_list ("global", "cache_push");
2734 while (optind < argc)
2736 if (strv_printf (&cache_push, "%s", argv[optind++]) == 0)
2737 errx (EXIT_FAILURE, "%s", pwmd_strerror (GPG_ERR_ENOMEM));
2740 if (strchr (socketarg, '/') == NULL)
2742 socketdir = getcwd (buf, sizeof (buf));
2743 socketname = str_dup (socketarg);
2744 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2746 else
2748 socketname = str_dup (strrchr (socketarg, '/'));
2749 socketname++;
2750 socketarg[strlen (socketarg) - strlen (socketname) - 1] = 0;
2751 socketdir = str_dup (socketarg);
2752 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2755 if (chdir (datadir))
2757 log_write ("%s: %s", datadir,
2758 pwmd_strerror (gpg_error_from_syserror ()));
2759 unlink (socketpath);
2760 goto do_exit;
2764 * Set the cache entry for a file. Prompts for the password.
2766 if (cache_push)
2768 struct crypto_s *crypto = NULL;
2769 gpg_error_t rc = init_client_crypto (&crypto);
2771 if (rc)
2773 estatus = EXIT_FAILURE;
2774 goto do_exit;
2777 #ifdef WITH_AGENT
2778 if (use_agent)
2780 rc = agent_set_pinentry_options (crypto->agent);
2781 if (rc)
2783 estatus = EXIT_FAILURE;
2784 goto do_exit;
2787 #endif
2789 for (opt = 0; cache_push[opt]; opt++)
2791 if (!do_cache_push (cache_push[opt], crypto) && !force)
2793 strv_free (cache_push);
2794 startup_failure ();
2795 estatus = EXIT_FAILURE;
2796 cleanup_crypto (&crypto);
2797 goto do_exit;
2800 cleanup_crypto_stage1 (crypto);
2803 #ifdef WITH_AGENT
2804 if (use_agent)
2805 (void) kill_scd (crypto->agent);
2806 #endif
2808 cleanup_crypto (&crypto);
2809 strv_free (cache_push);
2810 log_write (!nofork ? _("Done. Daemonizing...") :
2811 _("Done. Waiting for connections..."));
2814 config_clear_keys ();
2817 * bind() doesn't like the full pathname of the socket or any non alphanum
2818 * characters so change to the directory where the socket is wanted then
2819 * create it then change to datadir.
2821 if (chdir (socketdir))
2823 log_write ("%s: %s", socketdir,
2824 pwmd_strerror (gpg_error_from_syserror ()));
2825 goto do_exit;
2828 xfree (socketdir);
2830 if ((sockfd = socket (PF_UNIX, SOCK_STREAM, 0)) == -1)
2832 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_syserror ()));
2833 goto do_exit;
2836 addr.sun_family = AF_UNIX;
2837 snprintf (addr.sun_path, sizeof (addr.sun_path), "%s", socketname);
2838 do_unlink = 1;
2839 if (bind (sockfd, (struct sockaddr *) &addr, sizeof (struct sockaddr)) ==
2842 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_syserror ()));
2844 if (errno == EADDRINUSE)
2846 do_unlink = 0;
2847 log_write (_("Either there is another pwmd running or '%s' is a \n"
2848 "stale socket. Please remove it manually."), socketpath);
2851 goto do_exit;
2855 char *t = config_get_string ("global", "socket_perms");
2856 mode_t mode;
2857 mode_t mask;
2859 if (t)
2861 mode = strtol (t, NULL, 8);
2862 mask = umask (0);
2863 xfree (t);
2865 if (chmod (socketname, mode) == -1)
2867 log_write ("%s: %s", socketname,
2868 pwmd_strerror (gpg_error_from_syserror ()));
2869 close (sockfd);
2870 umask (mask);
2871 goto do_exit;
2874 umask (mask);
2878 xfree (--socketname);
2880 if (chdir (datadir))
2882 log_write ("%s: %s", datadir,
2883 pwmd_strerror (gpg_error_from_syserror ()));
2884 close (sockfd);
2885 goto do_exit;
2888 xfree (datadir);
2890 if (listen (sockfd, 0) == -1)
2892 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_syserror ()));
2893 goto do_exit;
2896 cmdline = 0;
2898 if (!nofork)
2900 switch (fork ())
2902 case -1:
2903 log_write ("fork(): %s",
2904 pwmd_strerror (gpg_error_from_syserror ()));
2905 goto do_exit;
2906 case 0:
2907 close (0);
2908 close (1);
2909 close (2);
2910 setsid ();
2911 break;
2912 default:
2913 _exit (EXIT_SUCCESS);
2917 pthread_key_create (&thread_name_key, free_key);
2918 pthread_setspecific (thread_name_key, str_dup ("main"));
2919 estatus = server_loop (sockfd, &socketpath);
2921 do_exit:
2922 if (socketpath && do_unlink)
2924 unlink (socketpath);
2925 xfree (socketpath);
2928 xfree (socketarg);
2929 #ifdef WITH_GNUTLS
2930 gnutls_global_deinit ();
2931 #endif
2932 if (rcfile_tid)
2934 #ifdef HAVE_PTHREAD_CANCEL
2935 pthread_cancel (rcfile_tid);
2936 #else
2937 pthread_kill (rcfile_tid, SIGUSR2);
2938 pthread_cond_signal (&rcfile_cond);
2939 #endif
2940 pthread_join (rcfile_tid, NULL);
2943 pthread_cond_destroy (&rcfile_cond);
2944 pthread_mutex_destroy (&rcfile_mutex);
2945 pthread_key_delete (last_error_key);
2946 #ifndef HAVE_PTHREAD_CANCEL
2947 pthread_key_delete (signal_thread_key);
2948 #endif
2950 if (global_config)
2951 config_free (global_config);
2953 xfree (rcfile);
2954 xfree (home_directory);
2955 xfree (homedir);
2956 xmlCleanupParser ();
2957 xmlCleanupGlobals ();
2959 if (estatus == EXIT_SUCCESS)
2960 log_write (_("pwmd exiting normally"));
2962 pthread_key_delete (thread_name_key);
2963 closelog ();
2964 #if defined(DEBUG) && !defined(MEM_DEBUG)
2965 xdump ();
2966 #endif
2967 exit (estatus);