Reindent to GNU coding style.
[pwmd.git] / src / pwmd.c
blobe79a23f407038e0fc5ac1e8dd9aadc82cbf91af5
1 /*
2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012
3 Ben Kibbey <bjk@luxsci.net>
5 This file is part of pwmd.
7 Pwmd is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 2 of the License, or
10 (at your option) any later version.
12 Pwmd is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
20 #ifdef HAVE_CONFIG_H
21 #include <config.h>
22 #endif
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <unistd.h>
27 #include <err.h>
28 #include <ctype.h>
29 #include <string.h>
30 #include <sys/socket.h>
31 #include <sys/un.h>
32 #include <signal.h>
33 #include <stdarg.h>
34 #include <string.h>
35 #include <sys/wait.h>
36 #include <fcntl.h>
37 #include <pwd.h>
38 #include <grp.h>
39 #include <pthread.h>
40 #include <sys/mman.h>
41 #include <termios.h>
42 #include <assert.h>
43 #include <syslog.h>
44 #include <netinet/in.h>
45 #include <arpa/inet.h>
46 #include <netdb.h>
47 #include <sys/time.h>
48 #include <sys/resource.h>
49 #include <setjmp.h>
51 #ifdef TM_IN_SYS_TIME
52 #include <sys/time.h>
53 #else
54 #include <time.h>
55 #endif
57 #ifdef HAVE_LIMITS_H
58 #include <limits.h>
59 #endif
61 #ifdef HAVE_GETOPT_LONG
62 #ifdef HAVE_GETOPT_H
63 #include <getopt.h>
64 #endif
65 #else
66 #include "getopt_long.h"
67 #endif
69 #ifdef HAVE_PR_SET_NAME
70 #include <sys/prctl.h>
71 #endif
73 #include "pwmd-error.h"
74 #include <gcrypt.h>
76 #include "mem.h"
77 #include "xml.h"
78 #include "common.h"
79 #include "commands.h"
80 #include "cache.h"
81 #include "util-misc.h"
82 #include "util-string.h"
83 #include "mutex.h"
84 #include "rcfile.h"
85 #include "agent.h"
86 #include "convert.h"
88 /* In tenths of a second. */
89 #define SIG_TIMEOUT 1
91 /* For (tcp_)accept_thread (usec). */
92 #define ACCEPT_TIMEOUT 30000
94 static int quit;
95 static int exiting;
96 static int cmdline;
97 static jmp_buf jmp;
98 static int nofork;
99 static pthread_cond_t quit_cond;
100 static pthread_mutex_t quit_mutex;
101 static int no_passphrase_file = 0;
103 #ifndef HAVE_PTHREAD_CANCEL
104 static pthread_key_t signal_thread_key;
105 #endif
107 #ifdef WITH_GNUTLS
108 static int tls_fd;
109 static int tls6_fd;
110 static pthread_t tls_tid;
111 static pthread_t tls6_tid;
112 static int spawned_tls;
113 static int spawned_tls6;
115 static int start_stop_tls (int term);
116 #endif
118 static int do_cache_push (const char *filename, struct crypto_s *crypto);
119 static int signal_loop (sigset_t sigset);
121 GCRY_THREAD_OPTION_PTHREAD_IMPL;
123 #ifndef HAVE_PTHREAD_CANCEL
124 static void
125 catch_thread_signal (int sig)
127 int *n = (int *) pthread_getspecific (signal_thread_key);
129 *n = 1;
130 pthread_setspecific (signal_thread_key, n);
132 #endif
134 static void
135 cache_push_from_rcfile ()
137 struct crypto_s *crypto;
138 char **cache_push;
139 gpg_error_t rc = init_client_crypto (&crypto);
141 if (rc)
143 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
144 return;
147 rc = set_agent_option (crypto->agent, "pinentry-mode", "error");
148 if (rc)
150 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
151 return;
154 cache_push = config_get_list ("global", "cache_push");
155 if (cache_push)
157 char **p;
159 for (p = cache_push; *p; p++)
161 (void) do_cache_push (*p, crypto);
162 cleanup_crypto_stage1 (crypto);
165 strv_free (cache_push);
168 (void) kill_scd (crypto->agent);
169 cleanup_crypto (&crypto);
172 static void
173 setup_logging ()
175 int n = config_get_boolean ("global", "enable_logging");
177 if (n)
179 char *p = config_get_string ("global", "log_path");
181 xfree (logfile);
182 logfile = expand_homedir (p);
183 xfree (p);
185 else
187 xfree (logfile);
188 logfile = NULL;
191 log_syslog = config_get_boolean ("global", "syslog");
192 if (log_syslog == 1)
193 openlog ("pwmd", LOG_NDELAY | LOG_PID, LOG_DAEMON);
196 static void *
197 reload_rcfile_thread (void *arg)
199 #ifndef HAVE_PTHREAD_CANCEL
200 int *n = xmalloc (sizeof (int));
202 *n = 0;
203 pthread_setspecific (signal_thread_key, n);
204 signal (SIGUSR2, catch_thread_signal);
205 #endif
207 #ifdef HAVE_PR_SET_NAME
208 prctl (PR_SET_NAME, "reload rcfile");
209 #endif
210 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
211 MUTEX_LOCK (&rcfile_mutex);
212 pthread_cleanup_push (cleanup_mutex_cb, &rcfile_mutex);
214 for (;;)
216 struct slist_s *config;
217 char **users;
218 int b = disable_list_and_dump;
219 #ifdef WITH_GNUTLS
220 int exists;
221 int tcp_require_key = config_get_bool_param (global_config, "global",
222 "tcp_require_key",
223 &exists);
224 #endif
226 pthread_cond_wait (&rcfile_cond, &rcfile_mutex);
227 #ifndef HAVE_PTHREAD_CANCEL
228 int *n = (int *) pthread_getspecific (signal_thread_key);
229 if (*n)
230 break;
231 #endif
233 users = config_get_list ("global", "allowed");
234 log_write (_("reloading configuration file '%s'"), rcfile);
235 config = config_parse (rcfile);
236 if (config)
238 config_free (global_config);
239 global_config = config;
240 setup_logging ();
241 cache_push_from_rcfile ();
242 config_clear_keys ();
245 disable_list_and_dump = !disable_list_and_dump ? b : 1;
246 #ifdef WITH_GNUTLS
247 if (config_get_bool_param (global_config, "global", "tcp_require_key",
248 &exists) && exists)
249 tcp_require_key = 1;
251 config_set_bool_param (&global_config, "global", "tcp_require_key",
252 tcp_require_key ? "true" : "false");
253 #endif
254 char *tmp = strv_join (",", users);
255 config_set_list_param (&global_config, "global", "allowed", tmp);
256 xfree (tmp);
257 strv_free (users);
258 #ifdef WITH_GNUTLS
259 /* Kill existing listening threads since the configured listening
260 * protocols may have changed. */
261 start_stop_tls (1);
262 start_stop_tls (0);
263 #endif
266 pthread_cleanup_pop (1);
267 return NULL;
270 gpg_error_t
271 send_error (assuan_context_t ctx, gpg_error_t e)
273 struct client_s *client = assuan_get_pointer (ctx);
275 if (gpg_err_source (e) == GPG_ERR_SOURCE_UNKNOWN)
276 e = gpg_error (e);
278 if (client)
279 client->last_rc = e;
281 if (!e)
282 return assuan_process_done (ctx, 0);
284 if (!ctx)
286 log_write ("%s", pwmd_strerror (e));
287 return e;
290 if (gpg_err_code (e) == GPG_ERR_BAD_DATA)
292 xmlErrorPtr xe = client->xml_error;
294 if (!xe)
295 xe = xmlGetLastError ();
296 if (xe)
298 log_write ("%s", xe->message);
299 if (client->last_error)
300 xfree (client->last_error);
302 client->last_error = str_dup (xe->message);
305 e = assuan_process_done (ctx, assuan_set_error (ctx, e,
306 xe ? xe->message :
307 NULL));
309 if (xe == client->xml_error)
310 xmlResetError (xe);
311 else
312 xmlResetLastError ();
314 client->xml_error = NULL;
315 return e;
318 return assuan_process_done (ctx,
319 assuan_set_error (ctx, e, pwmd_strerror (e)));
323 assuan_log_cb (assuan_context_t ctx, void *data, unsigned cat,
324 const char *msg)
326 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
327 int i, t;
328 int match = 0;
330 pthread_mutex_lock (&m);
331 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock, &m);
332 t = strv_length (debug_level);
334 for (i = 0; i < t; i++)
336 if (!strcasecmp (debug_level[i], (char *) "init")
337 && cat == ASSUAN_LOG_INIT)
339 match = 1;
340 break;
343 if (!strcasecmp (debug_level[i], (char *) "ctx")
344 && cat == ASSUAN_LOG_CTX)
346 match = 1;
347 break;
350 if (!strcasecmp (debug_level[i], (char *) "engine")
351 && cat == ASSUAN_LOG_ENGINE)
353 match = 1;
354 break;
357 if (!strcasecmp (debug_level[i], (char *) "data")
358 && cat == ASSUAN_LOG_DATA)
360 match = 1;
361 break;
364 if (!strcasecmp (debug_level[i], (char *) "sysio")
365 && cat == ASSUAN_LOG_SYSIO)
367 match = 1;
368 break;
371 if (!strcasecmp (debug_level[i], (char *) "control")
372 && cat == ASSUAN_LOG_CONTROL)
374 match = 1;
375 break;
379 if (match && msg)
381 if (logfile)
383 int fd;
385 if ((fd =
386 open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600)) == -1)
387 warn ("%s", logfile);
388 else
390 pthread_cleanup_push (cleanup_fd_cb, &fd);
391 write (fd, msg, strlen (msg));
392 pthread_cleanup_pop (1);
396 if (nofork)
398 fprintf (stderr, "%s%s", data ? (char *) data : "", msg);
399 fflush (stderr);
403 pthread_cleanup_pop (1);
404 return match;
407 void
408 log_write (const char *fmt, ...)
410 char *args, *line;
411 va_list ap;
412 struct tm *tm;
413 time_t now;
414 char tbuf[21];
415 int fd = -1;
416 char *name = NULL;
417 char buf[255];
418 pthread_t tid = pthread_self ();
419 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
421 if ((!logfile && !isatty (STDERR_FILENO) && !log_syslog) || !fmt)
422 return;
424 pthread_mutex_lock (&m);
425 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock, &m);
426 pthread_cleanup_push (cleanup_fd_cb, &fd);
428 if (!cmdline && logfile)
430 if ((fd = open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600)) == -1)
431 warn ("%s", logfile);
434 va_start (ap, fmt);
436 if (str_vasprintf (&args, fmt, ap) != -1)
438 if (cmdline)
440 pthread_cleanup_push (xfree, args);
441 fprintf (stderr, "%s\n", args);
442 fflush (stderr);
443 pthread_cleanup_pop (1);
445 else
447 pthread_cleanup_push (xfree, args);
448 name = pthread_getspecific (thread_name_key);
449 snprintf (buf, sizeof (buf), "%s(%p): ", name ? name : _("unknown"),
450 (pthread_t *) tid);
451 name = buf;
453 if (!cmdline && log_syslog && !nofork)
454 syslog (LOG_INFO, "%s%s", name, args);
456 time (&now);
457 tm = localtime (&now);
458 strftime (tbuf, sizeof (tbuf), "%b %d %Y %H:%M:%S ", tm);
459 tbuf[sizeof (tbuf) - 1] = 0;
461 if (args[strlen (args) - 1] == '\n')
462 args[strlen (args) - 1] = 0;
464 line = str_asprintf ("%s %i %s%s\n", tbuf, getpid (), name, args);
465 pthread_cleanup_pop (1);
466 if (line)
468 pthread_cleanup_push (xfree, line);
469 if (logfile && fd != -1)
471 write (fd, line, strlen (line));
472 fsync (fd);
475 if (nofork)
477 fprintf (stdout, "%s", line);
478 fflush (stdout);
481 pthread_cleanup_pop (1);
486 va_end (ap);
487 pthread_cleanup_pop (1);
488 pthread_cleanup_pop (0);
489 pthread_mutex_unlock (&m);
492 #ifdef WITH_GNUTLS
493 static int
494 secure_mem_check (const void *arg)
496 return 1;
498 #endif
500 static gpg_error_t
501 setup_crypto ()
503 gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
505 if (!gcry_check_version (GCRYPT_VERSION))
507 fprintf (stderr, _("gcry_check_version(): Incompatible libgcrypt. "
508 "Wanted %s, got %s.\n"), GCRYPT_VERSION,
509 gcry_check_version (NULL));
510 return GPG_ERR_UNKNOWN_VERSION;
513 gcry_set_allocation_handler (xmalloc, xmalloc, NULL, xrealloc, xfree);
514 return 0;
517 #ifdef HAVE_GETGRNAM_R
518 static gpg_error_t
519 do_validate_peer (struct client_s *cl, assuan_peercred_t * peer)
521 char **users;
522 int allowed = 0;
523 gpg_error_t rc;
525 rc = assuan_get_peercred (cl->ctx, peer);
526 if (rc)
527 return rc;
529 users = config_get_list ("global", "allowed");
530 if (users)
532 for (char **p = users; *p; p++)
534 struct passwd pw, *result;
535 struct group gr, *gresult;
536 char *buf;
538 if (*(*p) == '@')
540 size_t len = sysconf (_SC_GETGR_R_SIZE_MAX);
542 if (len == -1)
543 len = 16384;
545 buf = xmalloc (len);
546 if (!buf)
548 strv_free (users);
549 return GPG_ERR_ENOMEM;
552 if (!getgrnam_r (*(p) + 1, &gr, buf, len, &gresult) && gresult)
554 if (gresult->gr_gid == (*peer)->gid)
556 xfree (buf);
557 allowed = 1;
558 break;
561 len = sysconf (_SC_GETPW_R_SIZE_MAX);
562 if (len == -1)
563 len = 16384;
565 char *tbuf = xmalloc (len);
566 for (char **t = gresult->gr_mem; *t; t++)
568 if (!getpwnam_r (*t, &pw, tbuf, len, &result) && result)
570 if (result->pw_uid == (*peer)->uid)
572 xfree (buf);
573 allowed = 1;
574 break;
579 xfree (tbuf);
581 if (allowed)
582 break;
585 else
587 size_t len = sysconf (_SC_GETPW_R_SIZE_MAX);
589 if (len == -1)
590 len = 16384;
592 buf = xmalloc (len);
594 if (!buf)
596 strv_free (users);
597 return GPG_ERR_ENOMEM;
600 if (!getpwnam_r (*p, &pw, buf, len, &result) && result)
602 if (result->pw_uid == (*peer)->uid)
604 xfree (buf);
605 allowed = 1;
606 break;
611 xfree (buf);
614 strv_free (users);
617 return allowed ? 0 : GPG_ERR_INV_USER_ID;
619 #else
620 static gpg_error_t
621 do_validate_peer (struct client_s *cl, assuan_peercred_t * peer)
623 char **users;
624 int allowed = 0;
625 gpg_error_t rc;
627 rc = assuan_get_peercred (cl->ctx, peer);
628 if (rc)
629 return rc;
631 users = config_get_list ("global", "allowed");
632 if (users)
634 for (char **p = users; *p; p++)
636 struct passwd *result;
637 struct group *gresult;
639 if (*(*p) == '@')
641 gresult = getgrnam (*(p) + 1);
642 if (gresult && gresult->gr_gid == (*peer)->gid)
644 allowed = 1;
645 break;
648 for (char **t = gresult->gr_mem; *t; t++)
650 result = getpwnam (*t);
651 if (result && result->pw_uid == (*peer)->uid)
653 allowed = 1;
654 break;
658 else
660 result = getpwnam (*p);
661 if (result && result->pw_uid == (*peer)->uid)
663 allowed = 1;
664 break;
668 if (allowed)
669 break;
672 strv_free (users);
675 return allowed ? 0 : GPG_ERR_INV_USER_ID;
677 #endif
679 static gpg_error_t
680 validate_peer (struct client_s *cl)
682 gpg_error_t rc;
683 assuan_peercred_t peer;
685 #ifdef WITH_GNUTLS
686 if (cl->thd->remote)
687 return 0;
688 #endif
690 rc = do_validate_peer (cl, &peer);
691 log_write ("peer %s: uid=%i, gid=%i, pid=%i",
692 !rc ? _("accepted") : _("rejected"), peer->uid, peer->gid,
693 peer->pid);
694 return rc;
697 static void
698 xml_error_cb (void *data, xmlErrorPtr e)
700 struct client_s *client = data;
703 * Keep the first reported error as the one to show in the error
704 * description. Reset in send_error().
706 if (client->xml_error)
707 return;
709 xmlCopyError (e, client->xml_error);
712 static pid_t
713 hook_waitpid (assuan_context_t ctx, pid_t pid, int action,
714 int *status, int options)
716 return waitpid (pid, status, options);
719 static ssize_t
720 hook_read (assuan_context_t ctx, assuan_fd_t fd, void *data, size_t len)
722 #ifdef WITH_GNUTLS
723 struct client_s *client = assuan_get_pointer (ctx);
725 if (client->thd->remote)
726 return tls_read_hook (ctx, (int) fd, data, len);
727 #endif
729 return read ((int) fd, data, len);
732 static ssize_t
733 hook_write (assuan_context_t ctx, assuan_fd_t fd,
734 const void *data, size_t len)
736 #ifdef WITH_GNUTLS
737 struct client_s *client = assuan_get_pointer (ctx);
739 if (client->thd->remote)
740 return tls_write_hook (ctx, (int) fd, data, len);
741 #endif
743 return write ((int) fd, data, len);
746 static int
747 new_connection (struct client_s *cl)
749 gpg_error_t rc;
750 static struct assuan_malloc_hooks mhooks = { xmalloc, xrealloc, xfree };
751 static struct assuan_system_hooks shooks = {
752 ASSUAN_SYSTEM_HOOKS_VERSION,
753 __assuan_usleep,
754 __assuan_pipe,
755 __assuan_close,
756 hook_read,
757 hook_write,
758 //FIXME
759 NULL, //recvmsg
760 NULL, //sendmsg both are used for FD passing
761 __assuan_spawn,
762 hook_waitpid,
763 __assuan_socketpair,
764 __assuan_socket,
765 __assuan_connect
768 #ifdef WITH_GNUTLS
769 if (cl->thd->remote)
771 char *prio = config_get_string ("global", "tls_cipher_suite");
773 cl->thd->tls = tls_init (cl->thd->fd, prio);
774 xfree (prio);
775 if (!cl->thd->tls)
776 return 0;
778 #endif
780 rc = assuan_new_ext (&cl->ctx, GPG_ERR_SOURCE_DEFAULT, &mhooks,
781 debug_level ? assuan_log_cb : NULL, NULL);
782 if (rc)
783 goto fail;
785 assuan_ctx_set_system_hooks (cl->ctx, &shooks);
786 rc = assuan_init_socket_server (cl->ctx, cl->thd->fd, 2);
787 if (rc)
788 goto fail;
790 assuan_set_pointer (cl->ctx, cl);
791 assuan_set_hello_line (cl->ctx, PACKAGE_STRING);
792 rc = register_commands (cl->ctx);
793 if (rc)
794 goto fail;
796 rc = assuan_accept (cl->ctx);
797 if (rc)
798 goto fail;
800 rc = validate_peer (cl);
801 /* May not be implemented on all platforms. */
802 if (rc && gpg_err_code (rc) != GPG_ERR_ASS_GENERAL)
803 goto fail;
805 rc = init_client_crypto (&cl->crypto);
806 if (rc)
807 goto fail;
809 cl->crypto->agent->client_ctx = cl->ctx;
810 cl->crypto->client_ctx = cl->ctx;
811 xmlSetStructuredErrorFunc (cl, xml_error_cb);
812 return 1;
814 fail:
815 log_write ("%s", pwmd_strerror (rc));
816 return 0;
820 * This is called after a client_thread() terminates. Set with
821 * pthread_cleanup_push().
823 static void
824 cleanup_cb (void *arg)
826 struct client_thread_s *cn = arg;
827 struct client_s *cl = cn->cl;
829 MUTEX_LOCK (&cn_mutex);
830 cn_thread_list = slist_remove (cn_thread_list, cn);
831 MUTEX_UNLOCK (&cn_mutex);
833 if (cl)
835 cleanup_client (cl);
837 #ifdef WITH_GNUTLS
838 if (cn->tls)
840 gnutls_deinit (cn->tls->ses);
841 xfree (cn->tls->fp);
842 xfree (cn->tls);
844 #endif
846 if (cl->ctx)
847 assuan_release (cl->ctx);
848 else if (cl->thd && cl->thd->fd != -1)
849 close (cl->thd->fd);
851 if (cl->crypto)
852 cleanup_crypto (&cl->crypto);
854 xfree (cl);
856 else
858 if (cn->fd != -1)
859 close (cn->fd);
862 while (cn->msg_queue)
864 struct status_msg_s *msg = cn->msg_queue;
866 cn->msg_queue = msg->next;
867 xfree (msg->line);
868 xfree (msg);
871 if (cn->status_msg_pipe[0] != -1)
872 close (cn->status_msg_pipe[0]);
874 if (cn->status_msg_pipe[1] != -1)
875 close (cn->status_msg_pipe[1]);
877 pthread_mutex_destroy (&cn->status_mutex);
878 log_write (_("exiting, fd=%i"), cn->fd);
879 xfree (cn);
880 send_status_all (STATUS_CLIENTS, NULL);
881 pthread_cond_signal (&quit_cond);
884 static gpg_error_t
885 send_msg_queue (struct client_thread_s *thd)
887 MUTEX_LOCK (&thd->status_mutex);
888 gpg_error_t rc = 0;
889 char c;
891 read (thd->status_msg_pipe[0], &c, 1);
893 while (thd->msg_queue)
895 struct status_msg_s *msg = thd->msg_queue;
897 thd->msg_queue = thd->msg_queue->next;
898 MUTEX_UNLOCK (&thd->status_mutex);
899 rc = send_status (thd->cl->ctx, msg->s, msg->line);
900 MUTEX_LOCK (&thd->status_mutex);
901 xfree (msg->line);
902 xfree (msg);
904 if (rc)
905 break;
908 MUTEX_UNLOCK (&thd->status_mutex);
909 return rc;
912 static void *
913 client_thread (void *data)
915 struct client_thread_s *thd = data;
916 struct client_s *cl = xcalloc (1, sizeof (struct client_s));
918 #ifdef HAVE_PR_SET_NAME
919 prctl (PR_SET_NAME, "client");
920 #endif
921 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
923 if (!cl)
925 log_write ("%s(%i): %s", __FILE__, __LINE__,
926 pwmd_strerror (GPG_ERR_ENOMEM));
927 return NULL;
930 MUTEX_LOCK (&cn_mutex);
931 pthread_cleanup_push (cleanup_cb, thd);
932 thd->cl = cl;
933 cl->thd = thd;
934 MUTEX_UNLOCK (&cn_mutex);
936 if (new_connection (cl))
938 int finished = 0;
939 gpg_error_t rc;
941 send_status_all (STATUS_CLIENTS, NULL);
942 rc = send_status (cl->ctx, STATUS_CACHE, NULL);
943 if (rc)
945 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
946 finished = 1;
949 while (!finished)
951 fd_set rfds;
952 int n;
953 int eof;
955 FD_ZERO (&rfds);
956 FD_SET (thd->fd, &rfds);
957 FD_SET (thd->status_msg_pipe[0], &rfds);
959 thd->fd >
960 thd->status_msg_pipe[0] ? thd->fd : thd->status_msg_pipe[0];
962 n = select (n + 1, &rfds, NULL, NULL, NULL);
963 if (n == -1)
965 log_write ("%s", strerror (errno));
966 break;
969 if (FD_ISSET (thd->status_msg_pipe[0], &rfds))
971 rc = send_msg_queue (thd);
972 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
974 log_write ("%s(%i): %s", __FUNCTION__, __LINE__,
975 pwmd_strerror (rc));
976 break;
980 if (!FD_ISSET (thd->fd, &rfds))
981 continue;
983 rc = assuan_process_next (cl->ctx, &eof);
984 if (rc || eof)
986 if (gpg_err_code (rc) == GPG_ERR_EOF || eof)
987 break;
989 log_write ("assuan_process_next(): %s", pwmd_strerror (rc));
990 rc = send_error (cl->ctx, rc);
992 if (rc)
994 log_write ("assuan_process_done(): %s", pwmd_strerror (rc));
995 break;
999 /* Since the msg queue pipe fd's are non-blocking, check for
1000 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1001 * client has already disconnected and will be converted to
1002 * GPG_ERR_EOF during assuan_process_next().
1004 rc = send_msg_queue (thd);
1005 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1007 log_write ("%s(%i): %s", __FUNCTION__, __LINE__,
1008 pwmd_strerror (rc));
1009 break;
1014 pthread_cleanup_pop (1);
1015 return NULL;
1018 static int
1019 xml_import (const char *filename, const char *outfile,
1020 const char *keygrip, const char *sign_keygrip,
1021 const char *keyfile, int no_passphrase, const char *cipher,
1022 const char *params, unsigned long s2k_count, uint64_t iterations)
1024 xmlDocPtr doc;
1025 int fd;
1026 struct stat st;
1027 int len;
1028 xmlChar *xmlbuf;
1029 xmlChar *xml;
1030 gpg_error_t rc;
1031 struct crypto_s *crypto;
1032 int algo = cipher ? cipher_string_to_gcrypt ((char *) cipher) :
1033 GCRY_CIPHER_AES256;
1035 if (algo == -1)
1037 log_write ("ERR %i: %s", gpg_error (GPG_ERR_CIPHER_ALGO),
1038 pwmd_strerror (GPG_ERR_CIPHER_ALGO));
1039 return 0;
1042 if (stat (filename, &st) == -1)
1044 log_write ("%s: %s", filename,
1045 pwmd_strerror (gpg_error_from_syserror ()));
1046 return 0;
1049 rc = init_client_crypto (&crypto);
1050 if (rc)
1051 return 0;
1053 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
1054 crypto->save.hdr.flags = set_cipher_flag (crypto->save.hdr.flags, algo);
1055 log_write (_("Importing XML from '%s'. Output will be written to '%s' ..."),
1056 filename, outfile);
1058 if ((fd = open (filename, O_RDONLY)) == -1)
1060 log_write ("%s: %s", filename,
1061 pwmd_strerror (gpg_error_from_syserror ()));
1062 goto fail;
1065 if ((xmlbuf = xmalloc (st.st_size + 1)) == NULL)
1067 close (fd);
1068 log_write ("%s(%i): %s", __FILE__, __LINE__,
1069 pwmd_strerror (GPG_ERR_ENOMEM));
1070 goto fail;
1073 if (read (fd, xmlbuf, st.st_size) == -1)
1075 rc = gpg_error_from_syserror ();
1076 close (fd);
1077 log_write ("%s: %s", filename, pwmd_strerror (rc));
1078 goto fail;
1081 close (fd);
1082 xmlbuf[st.st_size] = 0;
1084 * Make sure the document validates.
1086 if ((doc = xmlReadDoc (xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS)) == NULL)
1088 log_write ("xmlReadDoc() failed");
1089 xfree (xmlbuf);
1090 goto fail;
1093 xfree (xmlbuf);
1094 xmlNodePtr n = xmlDocGetRootElement (doc);
1095 if (!xmlStrEqual (n->name, (xmlChar *) "pwmd"))
1097 log_write (_("Could not find root \"pwmd\" element."));
1098 rc = GPG_ERR_BAD_DATA;
1101 if (!rc)
1102 rc = validate_import (n ? n->children : n);
1104 if (rc)
1106 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1107 xmlFreeDoc (doc);
1108 goto fail;
1111 xmlDocDumpMemory (doc, &xml, &len);
1112 xmlFreeDoc (doc);
1113 crypto->save.s2k_count = s2k_count;
1114 crypto->save.hdr.iterations = iterations;
1115 rc = set_pinentry_options (crypto->agent);
1116 if (!rc)
1117 rc = export_common (crypto, keygrip, sign_keygrip, no_passphrase, xml,
1118 len, outfile, params, keyfile);
1120 xmlFree (xml);
1121 if (rc)
1123 send_error (NULL, rc);
1124 goto fail;
1127 cleanup_crypto (&crypto);
1128 return 1;
1130 fail:
1131 cleanup_crypto (&crypto);
1132 return 0;
1135 static int
1136 do_cache_push (const char *filename, struct crypto_s *crypto)
1138 unsigned char md5file[16];
1139 gpg_error_t rc;
1140 char *key = NULL;
1141 size_t keylen;
1142 xmlDocPtr doc;
1143 struct cache_data_s *cdata;
1144 unsigned char *crc;
1145 size_t len;
1147 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1148 filename);
1150 if (valid_filename (filename) == 0)
1152 log_write (_("%s: Invalid characters in filename"), filename);
1153 return 0;
1156 rc = read_data_file (filename, crypto);
1157 if (rc)
1159 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1160 return 0;
1163 if ((key = config_get_string (filename, "passphrase")))
1165 log_write (_("Trying the passphrase specified in config ..."));
1166 keylen = strlen (key);
1168 else if ((key = config_get_string (filename, "passphrase_file")))
1170 int fd = open ((char *) key, O_RDONLY);
1171 struct stat st;
1173 log_write (_("Trying the passphrase using file '%s' ..."), key);
1174 if (fd == -1)
1176 log_write ("%s: %s", key,
1177 pwmd_strerror (gpg_error_from_syserror ()));
1178 xfree (key);
1179 return 0;
1182 stat ((char *) key, &st);
1183 xfree (key);
1184 key = xmalloc (st.st_size);
1185 if (read (fd, key, st.st_size) != st.st_size)
1187 log_write ("short read() count");
1188 xfree (key);
1189 close (fd);
1190 return 0;
1193 keylen = st.st_size;
1196 if (key)
1198 rc = set_agent_passphrase (crypto, key, keylen);
1199 xfree (key);
1200 if (rc)
1202 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1203 return 0;
1207 crypto->filename = str_dup (filename);
1208 rc = decrypt_data (NULL, crypto);
1209 if (rc)
1211 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1212 return 0;
1215 doc = parse_doc ((char *) crypto->plaintext, crypto->plaintext_len);
1216 if (!doc)
1218 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM));
1219 return 0;
1222 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
1223 cdata = xcalloc (1, sizeof (struct cache_data_s));
1224 if (!cdata)
1226 xmlFreeDoc (doc);
1227 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM));
1228 return 0;
1231 rc = get_checksum (filename, &crc, &len);
1232 if (rc)
1234 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1235 xmlFreeDoc (doc);
1236 free_cache_data_once (cdata);
1237 return 0;
1240 cdata->crc = crc;
1241 rc = encrypt_xml (NULL, cache_key, cache_keysize, GCRY_CIPHER_AES,
1242 crypto->plaintext, crypto->plaintext_len, &cdata->doc,
1243 &cdata->doclen, &cache_iv, &cache_blocksize, 0);
1244 if (rc)
1246 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1247 xmlFreeDoc (doc);
1248 free_cache_data_once (cdata);
1249 return 0;
1252 gcry_sexp_build ((gcry_sexp_t *) & cdata->pubkey, NULL, "%S",
1253 crypto->pkey_sexp);
1254 gcry_sexp_build ((gcry_sexp_t *) & cdata->sigkey, NULL, "%S",
1255 crypto->sigpkey_sexp);
1256 int timeout = config_get_integer (filename, "cache_timeout");
1257 cache_add_file (md5file, crypto->grip, cdata, timeout);
1258 log_write (_("Successfully added '%s' to the cache."), filename);
1259 return 1;
1262 static gpg_error_t
1263 init_client (int fd, const char *addr)
1265 gpg_error_t rc = 0;
1266 struct client_thread_s *new = xcalloc (1, sizeof (struct client_thread_s));
1268 if (!new)
1270 close (fd);
1271 return GPG_ERR_ENOMEM;
1274 MUTEX_LOCK (&cn_mutex);
1275 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
1277 if (pipe (new->status_msg_pipe) == -1)
1278 rc = gpg_error_from_syserror ();
1280 if (!rc)
1282 fcntl (new->status_msg_pipe[0], F_SETFL, O_NONBLOCK);
1283 fcntl (new->status_msg_pipe[1], F_SETFL, O_NONBLOCK);
1284 pthread_mutex_init (&new->status_mutex, NULL);
1287 if (!rc)
1289 #ifdef WITH_GNUTLS
1290 new->remote = addr ? 1 : 0;
1291 #endif
1292 new->fd = fd;
1293 rc = create_thread (client_thread, new, &new->tid, 1);
1294 if (rc)
1296 close (new->status_msg_pipe[0]);
1297 close (new->status_msg_pipe[1]);
1298 pthread_mutex_destroy (&new->status_mutex);
1302 if (!rc)
1304 struct slist_s *list = slist_append (cn_thread_list, new);
1306 if (list)
1308 cn_thread_list = list;
1309 if (addr)
1310 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1311 (pthread_t *) new->tid, fd, addr);
1312 else
1313 log_write (_("new connection: tid=%p, fd=%i"),
1314 (pthread_t *) new->tid, fd);
1316 else
1317 rc = GPG_ERR_ENOMEM;
1320 pthread_cleanup_pop (1);
1322 if (rc)
1324 xfree (new);
1325 close (fd);
1326 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1327 pwmd_strerror (rc));
1329 return rc;
1332 #ifdef WITH_GNUTLS
1333 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1334 static void *
1335 get_in_addr (struct sockaddr *sa)
1337 if (sa->sa_family == AF_INET)
1338 return &(((struct sockaddr_in *) sa)->sin_addr);
1340 return &(((struct sockaddr_in6 *) sa)->sin6_addr);
1343 static void *
1344 tcp_accept_thread (void *arg)
1346 int sockfd = *(int *) arg;
1347 #ifndef HAVE_PTHREAD_CANCEL
1348 int *n = xmalloc (sizeof (int));
1350 *n = 0;
1351 pthread_setspecific (signal_thread_key, n);
1352 signal (SIGUSR2, catch_thread_signal);
1353 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1354 #endif
1356 #ifdef HAVE_PR_SET_NAME
1357 prctl (PR_SET_NAME, "tcp_accept");
1358 #endif
1359 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1361 for (;;)
1363 struct sockaddr_storage raddr;
1364 socklen_t slen = sizeof (raddr);
1365 int fd = -1;
1366 unsigned long n;
1367 char s[INET6_ADDRSTRLEN];
1368 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1369 #ifndef HAVE_PTHREAD_CANCEL
1370 int *sigusr2;
1372 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1373 if (*sigusr2)
1374 break;
1375 #endif
1377 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1378 if (fd == -1)
1380 if (errno == EMFILE || errno == ENFILE)
1381 log_write ("accept(): %s",
1382 pwmd_strerror (gpg_error_from_syserror ()));
1383 else if (errno != EAGAIN)
1385 if (!quit) // probably EBADF
1386 log_write ("accept(): %s", strerror (errno));
1388 break;
1391 #ifndef HAVE_PTHREAD_CANCEL
1392 select (0, NULL, NULL, NULL, &tv);
1393 #endif
1394 continue;
1397 if (quit)
1398 break;
1400 inet_ntop (raddr.ss_family, get_in_addr ((struct sockaddr *) &raddr),
1401 s, sizeof s);
1402 (void) init_client (fd, s);
1403 n = config_get_integer ("global", "tcp_wait");
1404 if (n > 0)
1406 tv.tv_sec = (n * 100000) / 100000;
1407 tv.tv_usec = (n * 100000) % 100000;
1408 select (0, NULL, NULL, NULL, &tv);
1412 return NULL;
1415 static int
1416 start_stop_tls_with_protocol (int ipv6, int term)
1418 struct addrinfo hints, *servinfo, *p;
1419 int port = config_get_integer ("global", "tcp_port");
1420 char buf[7];
1421 int n;
1422 gpg_error_t rc;
1423 int *fd = ipv6 ? &tls6_fd : &tls_fd;
1425 if (term || config_get_boolean ("global", "enable_tcp") == 0)
1427 if (tls6_fd != -1)
1429 if (spawned_tls6)
1431 #ifdef HAVE_PTHREAD_CANCEL
1432 pthread_cancel (tls6_tid);
1433 #else
1434 pthread_kill (tls6_tid, SIGUSR2);
1435 #endif
1436 pthread_join (tls6_tid, NULL);
1439 shutdown (tls6_fd, SHUT_RDWR);
1440 close (tls6_fd);
1441 tls6_fd = -1;
1442 spawned_tls6 = 0;
1445 if (tls_fd != -1)
1447 if (spawned_tls)
1449 #ifdef HAVE_PTHREAD_CANCEL
1450 pthread_cancel (tls_tid);
1451 #else
1452 pthread_kill (tls_tid, SIGUSR2);
1453 #endif
1454 pthread_join (tls_tid, NULL);
1457 shutdown (tls_fd, SHUT_RDWR);
1458 close (tls_fd);
1459 tls_fd = -1;
1460 spawned_tls = 0;
1463 /* A client may still be connected. */
1464 if (!quit && x509_cred != NULL)
1465 tls_deinit_params ();
1467 return 1;
1470 if ((ipv6 && tls6_fd != -1) || (!ipv6 && tls_fd != -1))
1471 return 1;
1473 memset (&hints, 0, sizeof (hints));
1474 hints.ai_family = ipv6 ? AF_INET6 : AF_INET;
1475 hints.ai_socktype = SOCK_STREAM;
1476 hints.ai_flags = AI_PASSIVE;
1477 snprintf (buf, sizeof (buf), "%i", port);
1479 if ((n = getaddrinfo (NULL, buf, &hints, &servinfo)) == -1)
1481 log_write ("getaddrinfo(): %s", gai_strerror (n));
1482 return 0;
1485 for (n = 0, p = servinfo; p != NULL; p = p->ai_next)
1487 int r = 1;
1489 if ((ipv6 && p->ai_family != AF_INET6)
1490 || (!ipv6 && p->ai_family != AF_INET))
1491 continue;
1493 if ((*fd = socket (p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
1495 log_write ("socket(): %s", strerror (errno));
1496 continue;
1499 if (setsockopt (*fd, SOL_SOCKET, SO_REUSEADDR, &r, sizeof (int)) == -1)
1501 log_write ("setsockopt(): %s",
1502 pwmd_strerror (gpg_error_from_syserror ()));
1503 freeaddrinfo (servinfo);
1504 goto fail;
1507 if (bind (*fd, p->ai_addr, p->ai_addrlen) == -1)
1509 close (*fd);
1510 log_write ("bind(): %s",
1511 pwmd_strerror (gpg_error_from_syserror ()));
1512 continue;
1515 n++;
1516 break;
1519 freeaddrinfo (servinfo);
1521 if (!n)
1522 goto fail;
1524 #ifdef HAVE_DECL_SO_BINDTODEVICE
1525 char *tmp = config_get_string ("global", "tcp_interface");
1526 if (tmp && setsockopt (*fd, SOL_SOCKET, SO_BINDTODEVICE, tmp, 1) == -1)
1528 log_write ("setsockopt(): %s",
1529 pwmd_strerror (gpg_error_from_syserror ()));
1530 xfree (tmp);
1531 goto fail;
1534 xfree (tmp);
1535 #endif
1537 if (x509_cred == NULL)
1539 rc = tls_init_params ();
1540 if (rc)
1541 goto fail;
1544 if (listen (*fd, 0) == -1)
1546 log_write ("listen(): %s", strerror (errno));
1547 goto fail;
1550 if (ipv6)
1551 rc = create_thread (tcp_accept_thread, fd, &tls6_tid, 0);
1552 else
1553 rc = create_thread (tcp_accept_thread, fd, &tls_tid, 0);
1555 if (rc)
1557 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1558 pwmd_strerror (rc));
1559 goto fail;
1562 if (ipv6)
1563 spawned_tls6 = 1;
1564 else
1565 spawned_tls = 1;
1567 return 1;
1569 fail:
1570 start_stop_tls_with_protocol (0, 1);
1571 if (tls_fd != -1)
1572 close (tls_fd);
1574 if (tls6_fd != -1)
1575 close (tls6_fd);
1577 tls_fd = -1;
1578 tls6_fd = -1;
1579 return 0;
1582 static int
1583 start_stop_tls (int term)
1585 char *s = config_get_string ("global", "tcp_bind");
1586 int b;
1588 if (!s)
1589 return 0;
1591 if (!strcmp (s, "any"))
1593 b = start_stop_tls_with_protocol (0, term);
1594 if (b)
1595 b = start_stop_tls_with_protocol (1, term);
1597 else if (!strcmp (s, "ipv4"))
1598 b = start_stop_tls_with_protocol (0, term);
1599 else if (!strcmp (s, "ipv6"))
1600 b = start_stop_tls_with_protocol (1, term);
1601 else
1602 b = 0;
1604 xfree (s);
1605 return b;
1607 #endif
1609 static void *
1610 accept_thread (void *arg)
1612 int sockfd = *(int *) arg;
1613 #ifndef HAVE_PTHREAD_CANCEL
1614 int *n = xmalloc (sizeof (int));
1616 *n = 0;
1617 pthread_setspecific (signal_thread_key, n);
1618 signal (SIGUSR2, catch_thread_signal);
1619 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1620 #endif
1622 #ifdef HAVE_PR_SET_NAME
1623 prctl (PR_SET_NAME, "accept");
1624 #endif
1625 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1627 for (;;)
1629 socklen_t slen = sizeof (struct sockaddr_un);
1630 struct sockaddr_un raddr;
1631 int fd;
1632 #ifndef HAVE_PTHREAD_CANCEL
1633 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1634 int *sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1636 if (*sigusr2)
1637 break;
1638 #endif
1640 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1641 if (fd == -1)
1643 if (errno == EMFILE || errno == ENFILE)
1644 log_write ("accept(): %s",
1645 pwmd_strerror (gpg_error_from_syserror ()));
1646 else if (errno != EAGAIN)
1648 if (!quit) // probably EBADF
1649 log_write ("accept(): %s",
1650 pwmd_strerror (gpg_error_from_syserror ()));
1652 break;
1655 #ifndef HAVE_PTHREAD_CANCEL
1656 select (0, NULL, NULL, NULL, &tv);
1657 #endif
1658 continue;
1661 (void) init_client (fd, NULL);
1664 /* Just in case accept() failed for some reason other than EBADF */
1665 quit = 1;
1666 return NULL;
1669 static void *
1670 cache_timer_thread (void *arg)
1672 #ifndef HAVE_PTHREAD_CANCEL
1673 int *n = xmalloc (sizeof (int));
1675 *n = 0;
1676 pthread_setspecific (signal_thread_key, n);
1677 signal (SIGUSR2, catch_thread_signal);
1678 #endif
1680 #ifdef HAVE_PR_SET_NAME
1681 prctl (PR_SET_NAME, "cache timer");
1682 #endif
1683 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1685 for (;;)
1687 struct timeval tv = { 1, 0 };
1688 #ifndef HAVE_PTHREAD_CANCEL
1689 int *n;
1691 n = (int *) pthread_getspecific (signal_thread_key);
1692 if (*n)
1693 break;
1694 #endif
1696 select (0, NULL, NULL, NULL, &tv);
1697 cache_adjust_timeout ();
1700 return NULL;
1703 static void
1704 catch_sigabrt (int sig)
1706 cache_clear (NULL);
1707 #ifndef MEM_DEBUG
1708 xpanic ();
1709 #endif
1712 static int
1713 signal_loop (sigset_t sigset)
1715 int done = 0;
1716 int siint = 0;
1720 struct timespec ts;
1721 int sig;
1723 INIT_TIMESPEC (SIG_TIMEOUT, ts);
1724 #ifdef HAVE_SIGTIMEDWAIT
1725 sig = sigtimedwait (&sigset, NULL, &ts);
1726 #else
1727 #ifdef __ANDROID__
1728 sig = __rt_sigtimedwait (&sigset, NULL, &ts, _NSIG / 8);
1729 #endif
1730 #endif
1731 if (sig == -1)
1733 if (errno != EAGAIN)
1734 log_write ("sigwaitinfo(): %s",
1735 pwmd_strerror (gpg_error_from_syserror ()));
1736 continue;
1739 if (sig != SIGCHLD)
1740 log_write (_("caught signal %i (%s)"), sig, strsignal (sig));
1742 switch (sig)
1744 case SIGHUP:
1745 pthread_cond_signal (&rcfile_cond);
1746 break;
1747 case SIGABRT:
1748 // not really handled here.
1749 catch_sigabrt (SIGABRT);
1750 break;
1751 case SIGUSR1:
1752 log_write (_("clearing file cache"));
1753 cache_clear (NULL);
1754 send_status_all (STATUS_CACHE, NULL);
1755 break;
1756 case SIGCHLD:
1757 done = 1;
1758 break;
1759 default:
1760 siint = 1;
1761 done = 1;
1762 break;
1765 while (!done);
1767 return siint;
1770 static void
1771 catchsig (int sig)
1773 log_write ("Caught SIGSEGV. Exiting.");
1774 #ifdef HAVE_BACKTRACE
1775 BACKTRACE (__FUNCTION__);
1776 #endif
1777 longjmp (jmp, 1);
1780 static void *
1781 waiting_for_exit (void *arg)
1783 int last = 0;
1784 #ifndef HAVE_PTHREAD_CANCEL
1785 int *n = xmalloc (sizeof (int));
1787 *n = 0;
1788 pthread_setspecific (signal_thread_key, n);
1789 signal (SIGUSR2, catch_thread_signal);
1790 #endif
1792 #ifdef HAVE_PR_SET_NAME
1793 prctl (PR_SET_NAME, "exiting");
1794 #endif
1795 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1796 log_write (_("waiting for all clients to disconnect"));
1797 MUTEX_LOCK (&quit_mutex);
1798 pthread_cleanup_push (cleanup_mutex_cb, &quit_mutex);
1800 for (;;)
1802 struct timespec ts;
1803 int n;
1805 MUTEX_LOCK (&cn_mutex);
1806 n = slist_length (cn_thread_list);
1807 MUTEX_UNLOCK (&cn_mutex);
1808 if (!n)
1809 break;
1811 #ifndef HAVE_PTHREAD_CANCEL
1812 int *s = (int *) pthread_getspecific (signal_thread_key);
1813 if (*s)
1814 break;
1815 #endif
1817 if (last != n)
1819 log_write (_("%i clients remain"), n);
1820 last = n;
1823 INIT_TIMESPEC (SIG_TIMEOUT, ts);
1824 pthread_cond_timedwait (&quit_cond, &quit_mutex, &ts);
1827 kill (getpid (), SIGCHLD);
1828 pthread_cleanup_pop (1);
1829 return NULL;
1832 static int
1833 server_loop (int sockfd, char **socketpath)
1835 pthread_t accept_tid;
1836 pthread_t cache_timeout_tid;
1837 int cancel_timeout_thread = 0, cancel_accept_thread = 0;
1838 int n, i;
1839 sigset_t sigset;
1840 int segv = 0;
1841 gpg_error_t rc;
1843 init_commands ();
1844 sigemptyset (&sigset);
1846 /* Termination */
1847 sigaddset (&sigset, SIGTERM);
1848 sigaddset (&sigset, SIGINT);
1850 /* Clears the file cache. */
1851 sigaddset (&sigset, SIGUSR1);
1853 /* Configuration file reloading. */
1854 sigaddset (&sigset, SIGHUP);
1856 /* For exiting cleanly. */
1857 sigaddset (&sigset, SIGCHLD);
1859 /* Clears the cache and exits when something bad happens. */
1860 signal (SIGABRT, catch_sigabrt);
1861 sigaddset (&sigset, SIGABRT);
1862 sigprocmask (SIG_BLOCK, &sigset, NULL);
1864 /* Ignored everywhere. When a client disconnects abnormally this signal
1865 * gets raised. It isn't needed though because client_thread() will check
1866 * for rcs even after the client disconnects. */
1867 signal (SIGPIPE, SIG_IGN);
1869 /* Can show a backtrace of the stack in the log. */
1870 signal (SIGSEGV, catchsig);
1872 #ifdef WITH_GNUTLS
1873 /* Needs to be done after the fork(). */
1874 if (!start_stop_tls (0))
1876 segv = 1;
1877 goto done;
1879 #endif
1881 pthread_mutex_init (&quit_mutex, NULL);
1882 pthread_cond_init (&quit_cond, NULL);
1883 log_write (_("%s started for user %s"), PACKAGE_STRING, get_username ());
1884 #ifndef HAVE_DECL_SO_PEERCRED
1885 log_write (_("Peer credential checking is NOT supported on this OS."));
1886 #endif
1887 #ifdef WITH_GNUTLS
1888 if (config_get_boolean ("global", "enable_tcp"))
1889 log_write (_("Listening on %s and TCP port %i"), *socketpath,
1890 config_get_integer ("global", "tcp_port"));
1891 else
1892 log_write (_("Listening on %s"), *socketpath);
1893 #else
1894 log_write (_("Listening on %s"), *socketpath);
1895 #endif
1897 rc = create_thread (reload_rcfile_thread, NULL, &rcfile_tid, 0);
1898 if (rc)
1900 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1901 pwmd_strerror (rc));
1902 goto done;
1905 rc = create_thread (cache_timer_thread, NULL, &cache_timeout_tid, 0);
1906 if (rc)
1908 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1909 pwmd_strerror (rc));
1910 goto done;
1913 cancel_timeout_thread = 1;
1914 rc = create_thread (accept_thread, &sockfd, &accept_tid, 0);
1915 if (rc)
1917 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1918 pwmd_strerror (rc));
1919 goto done;
1922 cancel_accept_thread = 1;
1923 if (!setjmp (jmp))
1924 signal_loop (sigset);
1925 else
1926 segv = 1;
1928 done:
1930 * We're out of the main server loop. This happens when a signal was sent
1931 * to terminate the daemon. We'll wait for all clients to disconnect
1932 * before exiting but exit immediately if another termination signal is
1933 * sent.
1935 if (cancel_accept_thread)
1937 #ifdef HAVE_PTHREAD_CANCEL
1938 int n = pthread_cancel (accept_tid);
1939 #else
1940 int n = pthread_kill (accept_tid, SIGUSR2);
1941 #endif
1942 if (!n)
1943 pthread_join (accept_tid, NULL);
1946 shutdown (sockfd, SHUT_RDWR);
1947 close (sockfd);
1948 unlink (*socketpath);
1949 xfree (*socketpath);
1950 *socketpath = NULL;
1951 MUTEX_LOCK (&cn_mutex);
1952 n = slist_length (cn_thread_list);
1953 MUTEX_UNLOCK (&cn_mutex);
1955 if (n && !segv)
1957 pthread_t tid;
1959 rc = create_thread (waiting_for_exit, NULL, &tid, 0);
1960 if (!rc)
1962 if (signal_loop (sigset))
1964 log_write (_("Received second termination request. Exiting."));
1965 #ifdef HAVE_PTHREAD_CANCEL
1966 pthread_cancel (tid);
1967 #else
1968 pthread_kill (tid, SIGUSR2);
1969 #endif
1970 pthread_join (tid, NULL);
1973 else
1974 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1975 pwmd_strerror (rc));
1978 if (cancel_timeout_thread)
1980 #ifdef HAVE_PTHREAD_CANCEL
1981 pthread_cancel (cache_timeout_tid);
1982 #else
1983 pthread_kill (cache_timeout_tid, SIGUSR2);
1984 #endif
1985 pthread_join (cache_timeout_tid, NULL);
1988 MUTEX_LOCK (&cn_mutex);
1989 i = 0;
1990 n = slist_length (cn_thread_list);
1992 for (i = 0; i < n; i++)
1994 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
1996 if (thd->fd != -1)
1998 close (thd->fd);
1999 thd->fd = -1;
2003 exiting = 1;
2004 MUTEX_UNLOCK (&cn_mutex);
2005 #ifdef WITH_GNUTLS
2006 start_stop_tls (1);
2007 #endif
2008 cache_deinit ();
2009 deinit_commands ();
2010 pthread_cond_destroy (&quit_cond);
2011 pthread_mutex_destroy (&quit_mutex);
2012 return segv ? EXIT_FAILURE : EXIT_SUCCESS;;
2015 static void
2016 startup_failure ()
2018 log_write (_
2019 ("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
2020 cache_clear (NULL);
2023 /* This is called from cache.c:clear_once(). See
2024 * command.c:clearcache_command() for details about lock checking.
2026 static gpg_error_t
2027 free_cache_data (file_cache_t * cache)
2029 gpg_error_t rc = GPG_ERR_NO_DATA;
2030 int i, t;
2031 struct client_thread_s *found = NULL;
2032 int self = 0;
2034 if (!cache->data)
2035 return 0;
2037 cache_lock ();
2038 MUTEX_LOCK (&cn_mutex);
2039 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
2040 t = slist_length (cn_thread_list);
2042 for (i = 0; i < t; i++)
2044 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2046 if (!thd->cl)
2047 continue;
2049 if (!memcmp (thd->cl->md5file, cache->filename,
2050 sizeof (cache->filename)))
2052 if (pthread_equal (pthread_self (), thd->tid))
2054 found = thd;
2055 self = 1;
2056 continue;
2059 /* Continue trying to find a client who has the same file open and
2060 * also has a lock. */
2061 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0, -1);
2062 if (!rc)
2064 self = 0;
2065 found = thd;
2066 break;
2071 if (self && (!rc || rc == GPG_ERR_NO_DATA))
2072 rc = cache_lock_mutex (found->cl->ctx, found->cl->md5file, -1, 0, -1);
2074 if (exiting || !rc || rc == GPG_ERR_NO_DATA)
2076 free_cache_data_once (cache->data);
2077 cache->data = NULL;
2078 cache->defer_clear = 0;
2079 cache->timeout = -1;
2081 if (found)
2082 cache_unlock_mutex (found->cl->md5file, 0);
2084 rc = 0;
2087 if (rc)
2088 cache->defer_clear = 1;
2090 pthread_cleanup_pop (1);
2091 cache_unlock ();
2092 return rc;
2095 static int
2096 convert_v2_datafile (const char *filename, const char *cipher,
2097 const char *keyfile, const char *keygrip,
2098 const char *sign_keygrip, int nopass,
2099 const char *outfile, const char *keyparam,
2100 unsigned long s2k_count, uint64_t iterations)
2102 gpg_error_t rc;
2103 void *data = NULL;
2104 size_t datalen;
2105 struct crypto_s *crypto = NULL;
2106 uint16_t ver;
2107 int algo;
2109 if (outfile[0] == '-' && outfile[1] == 0)
2110 outfile = NULL;
2112 log_write (_("Converting version 2 data file \"%s\" ..."), filename);
2113 if (access (filename, R_OK) == -1)
2115 log_write ("%s: %s", filename,
2116 pwmd_strerror (gpg_error_from_syserror ()));
2117 return 0;
2120 if (keyfile)
2122 log_write (_("Using passphrase file \"%s\" for decryption ..."),
2123 keyfile);
2124 if (access (keyfile, R_OK) == -1)
2126 log_write ("%s: %s", keyfile,
2127 pwmd_strerror (gpg_error_from_syserror ()));
2128 return 0;
2132 rc = read_v2_datafile (filename, keyfile, &data, &datalen, &ver, &algo);
2133 if (rc)
2135 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2136 return 0;
2139 if (cipher)
2141 algo = cipher_string_to_gcrypt (cipher);
2142 if (algo == -1)
2144 rc = GPG_ERR_CIPHER_ALGO;
2145 goto fail;
2149 if (ver < 0x212)
2151 xmlDocPtr doc = parse_doc (data, datalen);
2153 if (!doc)
2155 rc = GPG_ERR_BAD_DATA;
2156 goto fail;
2159 rc = convert_pre_212_elements (doc);
2160 gcry_free (data);
2161 data = NULL;
2162 if (!rc)
2164 xmlDocDumpFormatMemory (doc, (xmlChar **) & data, (int *) &datalen,
2166 if (!data)
2167 rc = GPG_ERR_ENOMEM;
2170 xmlFreeDoc (doc);
2171 if (rc)
2172 goto fail;
2175 rc = init_client_crypto (&crypto);
2176 if (!rc)
2178 rc = set_pinentry_options (crypto->agent);
2179 if (!rc)
2181 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
2182 crypto->save.hdr.flags =
2183 set_cipher_flag (crypto->save.hdr.flags, algo);
2184 crypto->save.s2k_count = s2k_count;
2185 crypto->save.hdr.iterations = iterations;
2186 rc = export_common (crypto, keygrip, sign_keygrip, nopass, data,
2187 datalen, outfile, keyparam,
2188 no_passphrase_file ? NULL : keyfile);
2189 if (!rc)
2190 log_write (_("Output written to \"%s\"."), outfile);
2194 fail:
2195 if (ver < 0x212)
2196 xmlFree (data);
2197 else
2198 gcry_free (data);
2199 cleanup_crypto (&crypto);
2201 if (rc)
2202 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2203 return rc ? 0 : 1;
2206 static void
2207 usage (const char *pn, int status)
2209 FILE *fp = status == EXIT_FAILURE ? stderr : stdout;
2211 fprintf (fp, _("Usage: %s [OPTIONS] [file1] [...]\n"
2212 " -f, --rcfile=filename load the specfied configuration file\n"
2213 " (~/.pwmd/config)\n"
2214 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2215 " -n, --no-fork run as a foreground process\n"
2216 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2217 " --ignore ignore file errors during startup\n"
2218 " --debug-level=keywords log protocol output (see manual for details)\n"
2219 " -o, --outfile=filename output file when importing or converting\n"
2220 " -C, --convert=filename convert a version 2 data file to version 3\n"
2221 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2222 " -k, --passphrase-file=file for use when importing or converting\n"
2223 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2224 " converting\n"
2225 " --no-passphrase when importing or converting\n"
2226 " --keygrip=hex public key to use when encrypting\n"
2227 " --sign-keygrip=hex private key to use when signing\n"
2228 " --keyparam=s-exp custom key parameters to use (RSA-2048)\n"
2229 " --cipher=string encryption cipher (aes256)\n"
2230 " --iterations=N cipher iteration count (N+1)\n"
2231 " --s2k-count=N hash iteration count (>65536, calibrated)\n"
2232 " --help this help text\n"
2233 " --version show version and compile time features\n"),
2234 pn);
2235 exit (status);
2239 main (int argc, char *argv[])
2241 int opt;
2242 struct sockaddr_un addr;
2243 char buf[PATH_MAX];
2244 char *socketpath = NULL, *socketdir, *socketname = NULL;
2245 char *socketarg = NULL;
2246 char *datadir = NULL;
2247 int x;
2248 char *p;
2249 char **cache_push = NULL;
2250 char *import = NULL, *keygrip = NULL, *sign_keygrip = NULL;
2251 char *keyparam = NULL;
2252 int estatus = EXIT_FAILURE;
2253 int sockfd;
2254 char *outfile = NULL;
2255 int do_unlink = 0;
2256 int secure = 0;
2257 int show_version = 0;
2258 int force = 0;
2259 int no_passphrase = 0;
2260 gpg_error_t rc;
2261 char *convertfile = NULL;
2262 char *cipher = NULL;
2263 char *keyfile = NULL;
2264 unsigned long s2k_count = 0;
2265 uint64_t iterations = 0;
2266 int exists;
2267 char *debug_level_opt = NULL;
2268 int optindex;
2269 /* Must maintain the same order as longopts[] */
2270 enum
2271 { OPT_VERSION, OPT_HELP, OPT_DEBUG_LEVEL, OPT_HOMEDIR, OPT_NO_FORK,
2272 OPT_DISABLE_DUMP, OPT_IGNORE, OPT_RCFILE, OPT_CONVERT,
2273 OPT_PASSPHRASE_FILE, OPT_IMPORT, OPT_OUTFILE, OPT_NO_PASSPHRASE_FILE,
2274 OPT_KEYGRIP, OPT_SIGN_KEYGRIP, OPT_KEYPARAM, OPT_CIPHER,
2275 OPT_ITERATIONS, OPT_S2K_COUNT, OPT_NO_PASSPHRASE
2277 const char *optstring = "nf:C:k:I:o:";
2278 const struct option longopts[] = {
2279 {"version", no_argument, 0, 0},
2280 {"help", no_argument, 0, 0},
2281 {"debug-level", required_argument, 0, 0},
2282 {"homedir", required_argument, 0, 0},
2283 {"no-fork", no_argument, 0, 'n'},
2284 {"disable_dump", no_argument, 0, 0},
2285 {"ignore", no_argument, 0, 0},
2286 {"rcfile", required_argument, 0, 'f'},
2287 {"convert", required_argument, 0, 'C'},
2288 {"passphrase-file", required_argument, 0, 'k'},
2289 {"import", required_argument, 0, 'I'},
2290 {"outfile", required_argument, 0, 'o'},
2291 {"no-passphrase-file", no_argument, 0, 0},
2292 {"keygrip", required_argument, 0, 0},
2293 {"sign-keygrip", required_argument, 0, 0},
2294 {"keyparam", required_argument, 0, 0},
2295 {"cipher", required_argument, 0, 0},
2296 {"cipher-iterations", required_argument, 0, 0},
2297 {"s2k-count", required_argument, 0, 0},
2298 {"no-passphrase", no_argument, 0, 0},
2299 {0, 0, 0, 0}
2302 #ifndef DEBUG
2303 #ifdef HAVE_SETRLIMIT
2304 struct rlimit rl;
2306 rl.rlim_cur = rl.rlim_max = 0;
2308 if (setrlimit (RLIMIT_CORE, &rl) != 0)
2309 err (EXIT_FAILURE, "setrlimit()");
2310 #endif
2311 #endif
2313 #ifdef ENABLE_NLS
2314 setlocale (LC_ALL, "");
2315 bindtextdomain ("pwmd", LOCALEDIR);
2316 textdomain ("pwmd");
2317 #endif
2319 #ifndef MEM_DEBUG
2320 xmem_init ();
2321 #endif
2322 gpg_err_init ();
2324 if (setup_crypto ())
2325 exit (EXIT_FAILURE);
2327 #ifdef WITH_GNUTLS
2328 gnutls_global_set_mem_functions (xmalloc, xmalloc, secure_mem_check,
2329 xrealloc, xfree);
2330 gnutls_global_init ();
2331 gnutls_global_set_log_function (tls_log);
2332 gnutls_global_set_log_level (1);
2333 tls_fd = -1;
2334 tls6_fd = -1;
2335 #endif
2336 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
2337 xmlInitMemory ();
2338 xmlInitGlobals ();
2339 xmlInitParser ();
2340 xmlXPathInit ();
2341 cmdline = 1;
2343 while ((opt =
2344 getopt_long (argc, argv, optstring, longopts, &optindex)) != -1)
2346 switch (opt)
2348 case 'I':
2349 import = optarg;
2350 break;
2351 case 'C':
2352 convertfile = optarg;
2353 break;
2354 case 'k':
2355 keyfile = optarg;
2356 break;
2357 case 'o':
2358 outfile = optarg;
2359 break;
2360 case 'D':
2361 secure = 1;
2362 break;
2363 case 'n':
2364 nofork = 1;
2365 break;
2366 case 'f':
2367 rcfile = str_dup (optarg);
2368 break;
2369 default:
2370 usage (argv[0], EXIT_FAILURE);
2371 break;
2372 case 0:
2373 switch (optindex)
2375 case OPT_VERSION:
2376 show_version = 1;
2377 break;
2378 case OPT_HELP:
2379 usage (argv[0], 0);
2380 break;
2381 case OPT_DEBUG_LEVEL:
2382 debug_level_opt = optarg;
2383 break;
2384 case OPT_HOMEDIR:
2385 homedir = str_dup (optarg);
2386 break;
2387 case OPT_NO_FORK:
2388 nofork = 1;
2389 break;
2390 case OPT_DISABLE_DUMP:
2391 secure = 1;
2392 break;
2393 case OPT_IGNORE:
2394 force = 1;
2395 break;
2396 case OPT_RCFILE:
2397 rcfile = str_dup (optarg);
2398 break;
2399 case OPT_CONVERT:
2400 convertfile = optarg;
2401 break;
2402 case OPT_PASSPHRASE_FILE:
2403 keyfile = optarg;
2404 break;
2405 case OPT_IMPORT:
2406 import = optarg;
2407 break;
2408 case OPT_OUTFILE:
2409 outfile = optarg;
2410 break;
2411 case OPT_NO_PASSPHRASE_FILE:
2412 no_passphrase_file = 1;
2413 break;
2414 case OPT_KEYGRIP:
2415 keygrip = optarg;
2416 break;
2417 case OPT_SIGN_KEYGRIP:
2418 sign_keygrip = optarg;
2419 break;
2420 case OPT_KEYPARAM:
2421 keyparam = optarg;
2422 break;
2423 case OPT_CIPHER:
2424 cipher = optarg;
2425 break;
2426 case OPT_ITERATIONS:
2427 iterations = strtoull (optarg, NULL, 10);
2428 break;
2429 case OPT_S2K_COUNT:
2430 s2k_count = strtoul (optarg, NULL, 10);
2431 break;
2432 case OPT_NO_PASSPHRASE:
2433 no_passphrase = 1;
2434 break;
2435 default:
2436 usage (argv[0], 1);
2441 if (show_version)
2443 printf (_("%s\n\n"
2444 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012\n"
2445 "%s\n"
2446 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2447 "Compile time features:\n%s"), PACKAGE_STRING,
2448 PACKAGE_BUGREPORT,
2449 #ifdef WITH_GNUTLS
2450 "+WITH_GNUTLS\n"
2451 #else
2452 "-WITH_GNUTLS\n"
2453 #endif
2454 #ifdef WITH_LIBACL
2455 "+WITH_LIBACL\n"
2456 #else
2457 "-WITH_LIBACL\n"
2458 #endif
2459 #ifdef DEBUG
2460 "+DEBUG\n"
2461 #else
2462 "-DEBUG\n"
2463 #endif
2464 #ifdef MEM_DEBUG
2465 "+MEM_DEBUG\n"
2466 #else
2467 "-MEM_DEBUG\n"
2468 #endif
2469 #ifdef MUTEX_DEBUG
2470 "+MUTEX_DEBUG\n"
2471 #else
2472 "-MUTEX_DEBUG\n"
2473 #endif
2475 exit (EXIT_SUCCESS);
2478 if (!homedir)
2479 homedir = str_asprintf ("%s/.pwmd", get_home_dir ());
2481 if (mkdir (homedir, 0700) == -1 && errno != EEXIST)
2482 err (EXIT_FAILURE, "%s", homedir);
2484 snprintf (buf, sizeof (buf), "%s/data", homedir);
2485 if (mkdir (buf, 0700) == -1 && errno != EEXIST)
2486 err (EXIT_FAILURE, "%s", buf);
2488 datadir = str_dup (buf);
2489 pthread_mutexattr_t attr;
2490 pthread_mutexattr_init (&attr);
2491 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
2492 pthread_mutex_init (&rcfile_mutex, &attr);
2493 pthread_cond_init (&rcfile_cond, NULL);
2494 pthread_mutex_init (&cn_mutex, &attr);
2495 pthread_mutexattr_destroy (&attr);
2496 pthread_key_create (&last_error_key, free_key);
2497 #ifndef HAVE_PTHREAD_CANCEL
2498 pthread_key_create (&signal_thread_key, free_key);
2499 #endif
2501 if (!rcfile)
2502 rcfile = str_asprintf ("%s/config", homedir);
2504 global_config = config_parse (rcfile);
2505 if (!global_config)
2506 exit (EXIT_FAILURE);
2508 setup_logging ();
2510 if (debug_level_opt)
2511 debug_level = str_split (debug_level_opt, ",", 0);
2513 x = config_get_int_param (global_config, "global", "priority", &exists);
2514 if (exists)
2516 errno = 0;
2517 if (setpriority (PRIO_PROCESS, 0, x) == -1)
2519 log_write ("setpriority(): %s",
2520 pwmd_strerror (gpg_error_from_syserror ()));
2521 goto do_exit;
2524 #ifdef HAVE_MLOCKALL
2525 if (disable_mlock == 0 && mlockall (MCL_CURRENT | MCL_FUTURE) == -1)
2527 log_write ("mlockall(): %s",
2528 pwmd_strerror (gpg_error_from_syserror ()));
2529 goto do_exit;
2531 #endif
2533 rc = cache_init (free_cache_data);
2534 if (rc)
2536 log_write ("pwmd: ERR %i: %s", rc,
2537 gpg_err_code (rc) == GPG_ERR_UNKNOWN_VERSION
2538 ? _("incompatible version: 2.1.0 or later required")
2539 : pwmd_strerror (rc));
2540 goto do_exit;
2543 if (s2k_count == 0)
2544 s2k_count = config_get_ulong (NULL, "s2k_count");
2546 if (convertfile)
2548 if (!outfile)
2549 usage (argv[0], EXIT_FAILURE);
2551 estatus = convert_v2_datafile (convertfile, cipher, keyfile, keygrip,
2552 sign_keygrip, no_passphrase, outfile,
2553 keyparam, s2k_count, iterations);
2554 config_free (global_config);
2555 xfree (rcfile);
2556 exit (!estatus);
2559 if (import)
2561 if (!outfile)
2562 usage (argv[0], EXIT_FAILURE);
2564 if (outfile[0] == '-' && outfile[1] == 0)
2565 outfile = NULL;
2567 estatus = xml_import (import, outfile, keygrip, sign_keygrip, keyfile,
2568 no_passphrase, cipher, keyparam, s2k_count,
2569 iterations);
2570 config_free (global_config);
2571 xfree (rcfile);
2572 exit (!estatus);
2575 p = config_get_string ("global", "socket_path");
2576 if (!p)
2577 p = str_asprintf ("%s/socket", homedir);
2579 socketarg = expand_homedir (p);
2580 xfree (p);
2582 if (!secure)
2583 disable_list_and_dump = config_get_boolean ("global",
2584 "disable_list_and_dump");
2585 else
2586 disable_list_and_dump = secure;
2588 cache_push = config_get_list ("global", "cache_push");
2590 while (optind < argc)
2592 if (strv_printf (&cache_push, "%s", argv[optind++]) == 0)
2593 errx (EXIT_FAILURE, "%s", pwmd_strerror (GPG_ERR_ENOMEM));
2596 if (strchr (socketarg, '/') == NULL)
2598 socketdir = getcwd (buf, sizeof (buf));
2599 socketname = str_dup (socketarg);
2600 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2602 else
2604 socketname = str_dup (strrchr (socketarg, '/'));
2605 socketname++;
2606 socketarg[strlen (socketarg) - strlen (socketname) - 1] = 0;
2607 socketdir = str_dup (socketarg);
2608 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2611 if (chdir (datadir))
2613 log_write ("%s: %s", datadir,
2614 pwmd_strerror (gpg_error_from_syserror ()));
2615 unlink (socketpath);
2616 goto do_exit;
2620 * Set the cache entry for a file. Prompts for the password.
2622 if (cache_push)
2624 struct crypto_s *crypto;
2625 gpg_error_t rc = init_client_crypto (&crypto);
2627 if (rc)
2629 estatus = EXIT_FAILURE;
2630 goto do_exit;
2633 rc = set_pinentry_options (crypto->agent);
2634 if (rc)
2636 estatus = EXIT_FAILURE;
2637 goto do_exit;
2640 for (opt = 0; cache_push[opt]; opt++)
2642 if (!do_cache_push (cache_push[opt], crypto) && !force)
2644 strv_free (cache_push);
2645 startup_failure ();
2646 estatus = EXIT_FAILURE;
2647 cleanup_crypto (&crypto);
2648 goto do_exit;
2651 cleanup_crypto_stage1 (crypto);
2654 (void) kill_scd (crypto->agent);
2655 cleanup_crypto (&crypto);
2656 strv_free (cache_push);
2657 log_write (!nofork ? _("Done. Daemonizing...") :
2658 _("Done. Waiting for connections..."));
2661 config_clear_keys ();
2664 * bind() doesn't like the full pathname of the socket or any non alphanum
2665 * characters so change to the directory where the socket is wanted then
2666 * create it then change to datadir.
2668 if (chdir (socketdir))
2670 log_write ("%s: %s", socketdir,
2671 pwmd_strerror (gpg_error_from_syserror ()));
2672 goto do_exit;
2675 xfree (socketdir);
2677 if ((sockfd = socket (PF_UNIX, SOCK_STREAM, 0)) == -1)
2679 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_syserror ()));
2680 goto do_exit;
2683 addr.sun_family = AF_UNIX;
2684 snprintf (addr.sun_path, sizeof (addr.sun_path), "%s", socketname);
2686 if (bind (sockfd, (struct sockaddr *) &addr, sizeof (struct sockaddr)) ==
2689 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_syserror ()));
2691 if (errno == EADDRINUSE)
2692 log_write (_("Either there is another pwmd running or '%s' is a \n"
2693 "stale socket. Please remove it manually."), socketpath);
2695 goto do_exit;
2698 do_unlink = 1;
2700 char *t = config_get_string ("global", "socket_perms");
2701 mode_t mode;
2702 mode_t mask;
2704 if (t)
2706 mode = strtol (t, NULL, 8);
2707 mask = umask (0);
2708 xfree (t);
2710 if (chmod (socketname, mode) == -1)
2712 log_write ("%s: %s", socketname,
2713 pwmd_strerror (gpg_error_from_syserror ()));
2714 close (sockfd);
2715 unlink (socketpath);
2716 umask (mask);
2717 goto do_exit;
2720 umask (mask);
2724 xfree (--socketname);
2726 if (chdir (datadir))
2728 log_write ("%s: %s", datadir,
2729 pwmd_strerror (gpg_error_from_syserror ()));
2730 close (sockfd);
2731 unlink (socketpath);
2732 goto do_exit;
2735 xfree (datadir);
2737 if (listen (sockfd, 0) == -1)
2739 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_syserror ()));
2740 goto do_exit;
2743 cmdline = 0;
2745 if (!nofork)
2747 switch (fork ())
2749 case -1:
2750 log_write ("fork(): %s",
2751 pwmd_strerror (gpg_error_from_syserror ()));
2752 goto do_exit;
2753 case 0:
2754 close (0);
2755 close (1);
2756 close (2);
2757 setsid ();
2758 break;
2759 default:
2760 _exit (EXIT_SUCCESS);
2764 pthread_key_create (&thread_name_key, free_key);
2765 pthread_setspecific (thread_name_key, str_dup ("main"));
2766 estatus = server_loop (sockfd, &socketpath);
2768 do_exit:
2769 if (socketpath && do_unlink)
2771 unlink (socketpath);
2772 xfree (socketpath);
2775 xfree (socketarg);
2776 #ifdef WITH_GNUTLS
2777 gnutls_global_deinit ();
2778 #endif
2779 if (rcfile_tid)
2781 #ifdef HAVE_PTHREAD_CANCEL
2782 pthread_cancel (rcfile_tid);
2783 #else
2784 pthread_kill (rcfile_tid, SIGUSR2);
2785 pthread_cond_signal (&rcfile_cond);
2786 #endif
2787 pthread_join (rcfile_tid, NULL);
2790 pthread_cond_destroy (&rcfile_cond);
2791 pthread_mutex_destroy (&rcfile_mutex);
2792 pthread_key_delete (last_error_key);
2793 #ifndef HAVE_PTHREAD_CANCEL
2794 pthread_key_delete (signal_thread_key);
2795 #endif
2797 if (global_config)
2798 config_free (global_config);
2800 xfree (rcfile);
2801 xfree (home_directory);
2802 xfree (homedir);
2803 xmlCleanupParser ();
2804 xmlCleanupGlobals ();
2806 if (estatus == EXIT_SUCCESS)
2807 log_write (_("pwmd exiting normally"));
2809 closelog ();
2810 #if defined(DEBUG) && !defined(MEM_DEBUG)
2811 xdump ();
2812 #endif
2813 exit (estatus);