Check for extra arguments when importing or converting.
[pwmd.git] / src / pwmd.c
blobf9b7eb914cfd19352e25c0c13f2bd9a480b175fc
1 /*
2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014
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>
50 #include <errno.h>
52 #ifdef TM_IN_SYS_TIME
53 #include <sys/time.h>
54 #else
55 #include <time.h>
56 #endif
58 #ifdef HAVE_LIMITS_H
59 #include <limits.h>
60 #endif
62 #ifdef HAVE_GETOPT_LONG
63 #ifdef HAVE_GETOPT_H
64 #include <getopt.h>
65 #endif
66 #else
67 #include "getopt_long.h"
68 #endif
70 #ifdef HAVE_PR_SET_NAME
71 #include <sys/prctl.h>
72 #endif
74 #include "pwmd-error.h"
75 #include <gcrypt.h>
77 #include "util-misc.h"
78 #include "mem.h"
79 #include "xml.h"
80 #include "common.h"
81 #include "commands.h"
82 #include "cache.h"
83 #include "util-string.h"
84 #include "mutex.h"
85 #include "rcfile.h"
86 #include "crypto.h"
87 #include "convert.h"
88 #include "pinentry.h"
90 /* In tenths of a second. */
91 #define SIG_TIMEOUT 1
93 /* For (tcp_)accept_thread (usec). */
94 #define ACCEPT_TIMEOUT 30000
96 static int quit;
97 static int exiting;
98 static int cmdline;
99 static jmp_buf jmp;
100 static int nofork;
101 static pthread_cond_t quit_cond;
102 static pthread_mutex_t quit_mutex;
103 static int no_passphrase_file = 0;
104 static pthread_t keepalive_tid;
105 static int log_fd;
107 #ifndef HAVE_PTHREAD_CANCEL
108 static pthread_key_t signal_thread_key;
109 #endif
111 #ifdef WITH_GNUTLS
112 static int tls_fd;
113 static int tls6_fd;
114 static pthread_t tls_tid;
115 static pthread_t tls6_tid;
116 static int spawned_tls;
117 static int spawned_tls6;
119 static int start_stop_tls (int term);
120 #endif
122 static int do_cache_push (const char *filename, struct crypto_s *crypto);
123 static int signal_loop (sigset_t sigset);
125 GCRY_THREAD_OPTION_PTHREAD_IMPL;
127 #ifndef HAVE_PTHREAD_CANCEL
128 #define INIT_THREAD_SIGNAL do { \
129 struct sigaction act; \
130 sigset_t sigset; \
131 sigemptyset (&sigset); \
132 sigaddset (&sigset, SIGUSR2); \
133 pthread_sigmask (SIG_UNBLOCK, &sigset, NULL); \
134 memset (&act, 0, sizeof(act)); \
135 act.sa_flags = SA_SIGINFO; \
136 act.sa_mask = sigset; \
137 act.sa_sigaction = catch_thread_signal; \
138 sigaction (SIGUSR2, &act, NULL); \
139 } while (0)
141 static void
142 catch_thread_signal (int sig, siginfo_t *info, void *ctx)
144 int *n = (int *) pthread_getspecific (signal_thread_key);
146 *n = 1;
147 pthread_setspecific (signal_thread_key, n);
149 #endif
151 static void
152 cache_push_from_rcfile ()
154 struct crypto_s *crypto = NULL;
155 char **cache_push;
156 gpg_error_t rc = init_client_crypto (&crypto);
158 if (rc)
160 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
161 return;
164 #ifdef WITH_AGENT
165 if (use_agent)
167 rc = set_agent_option (crypto->agent, "pinentry-mode", "error");
168 if (rc)
170 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
171 return;
174 #endif
176 cache_push = config_get_list ("global", "cache_push");
177 if (cache_push)
179 char **p;
181 for (p = cache_push; *p; p++)
183 (void) do_cache_push (*p, crypto);
184 cleanup_crypto_stage1 (crypto);
187 strv_free (cache_push);
190 #ifdef WITH_AGENT
191 (void) kill_scd (crypto->agent);
192 #endif
193 cleanup_crypto (&crypto);
196 static void
197 setup_logging ()
199 int n = config_get_boolean ("global", "enable_logging");
201 if (n)
203 char *p = config_get_string ("global", "log_path");
205 if (!p || (logfile && p && log_fd != -1 && strcmp(p, logfile)))
207 if (log_fd != -1)
208 close (log_fd);
210 log_fd = -1;
213 xfree (logfile);
214 logfile = expand_homedir (p);
215 xfree (p);
217 else
219 xfree (logfile);
220 logfile = NULL;
221 if (log_fd != -1)
222 close(log_fd);
224 log_fd = -1;
227 log_syslog = config_get_boolean ("global", "syslog");
228 if (log_syslog == 1)
229 openlog ("pwmd", LOG_NDELAY | LOG_PID, LOG_DAEMON);
232 static void *
233 reload_rcfile_thread (void *arg)
235 #ifndef HAVE_PTHREAD_CANCEL
236 int *n = xmalloc (sizeof (int));
238 *n = 0;
239 pthread_setspecific (signal_thread_key, n);
240 INIT_THREAD_SIGNAL;
241 #endif
243 #ifdef HAVE_PR_SET_NAME
244 prctl (PR_SET_NAME, "reload rcfile");
245 #endif
246 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
247 MUTEX_LOCK (&rcfile_mutex);
248 pthread_cleanup_push (cleanup_mutex_cb, &rcfile_mutex);
250 for (;;)
252 struct allowed_users_s
254 char *section;
255 char **users;
257 struct slist_s *allowed_users = NULL;
258 struct slist_s *config;
259 int b = disable_list_and_dump;
260 int exists;
261 int require_save_key = config_get_bool_param (global_config, "global",
262 "require_save_key",
263 &exists);
264 #ifdef WITH_GNUTLS
265 int tcp_require_key = config_get_bool_param (global_config, "global",
266 "tcp_require_key",
267 &exists);
268 #endif
270 pthread_cond_wait (&rcfile_cond, &rcfile_mutex);
271 #ifndef HAVE_PTHREAD_CANCEL
272 int *cancel = (int *) pthread_getspecific (signal_thread_key);
273 if (*cancel)
274 break;
275 #endif
277 /* Keep the "allowed" parameter across rcfile reloads to prevent
278 tampering. */
279 int n, t = slist_length (global_config);
280 for (n = 0; n < t; n++)
282 struct config_section_s *section;
283 char **users;
285 section = slist_nth_data (global_config, n);
286 users = config_get_list_param (global_config, section->name,
287 "allowed", &exists);
288 if (users)
290 struct allowed_users_s *allowed;
292 allowed = xmalloc (sizeof(struct allowed_users_s));
293 allowed->section = str_dup (section->name);
294 allowed->users = users;
295 allowed_users = slist_append (allowed_users, allowed);
299 log_write (_("reloading configuration file '%s'"), rcfile);
300 config = config_parse (rcfile);
301 if (config)
303 config_free (global_config);
304 global_config = config;
305 setup_logging ();
306 cache_push_from_rcfile ();
307 config_clear_keys ();
310 disable_list_and_dump = !disable_list_and_dump ? b : 1;
311 config_set_bool_param (&global_config, "global", "require_save_key",
312 require_save_key ? "true" : "false");
313 #ifdef WITH_GNUTLS
314 if (config_get_bool_param (global_config, "global", "tcp_require_key",
315 &exists) && exists)
316 tcp_require_key = 1;
318 config_set_bool_param (&global_config, "global", "tcp_require_key",
319 tcp_require_key ? "true" : "false");
320 #endif
322 if (allowed_users)
324 int n, t = slist_length (allowed_users);
326 for (n = 0; n < t; n++)
328 struct allowed_users_s *allowed;
329 char *tmp;
331 allowed = slist_nth_data (allowed_users, n);
332 tmp = strv_join (",", allowed->users);
333 config_set_list_param (&global_config, allowed->section,
334 "allowed", tmp);
335 xfree (tmp);
336 xfree (allowed->section);
337 strv_free (allowed->users);
338 xfree (allowed);
341 slist_free (allowed_users);
344 #ifdef WITH_GNUTLS
345 /* Kill existing listening threads since the configured listening
346 * protocols may have changed. */
347 start_stop_tls (1);
348 start_stop_tls (0);
349 #endif
352 pthread_cleanup_pop (1);
353 return NULL;
356 gpg_error_t
357 send_error (assuan_context_t ctx, gpg_error_t e)
359 struct client_s *client = assuan_get_pointer (ctx);
361 if (gpg_err_source (e) == GPG_ERR_SOURCE_UNKNOWN)
362 e = gpg_error (e);
364 if (client)
365 client->last_rc = e;
367 if (!e)
368 return assuan_process_done (ctx, 0);
370 if (!ctx)
372 log_write ("ERR %i: %s", e, pwmd_strerror (e));
373 return e;
376 if (client && client->xml_error)
378 log_write ("%s", client->xml_error->message);
379 xfree (client->last_error);
380 client->last_error = NULL;
381 if (client->xml_error->message)
382 client->last_error = str_dup (client->xml_error->message);
384 e = assuan_process_done (ctx,
385 assuan_set_error (ctx, e,
386 client->xml_error->message ? client->xml_error->message : NULL));
387 xmlResetLastError ();
388 xmlResetError (client->xml_error);
389 xfree (client->xml_error);
390 client->xml_error = NULL;
391 return e;
394 return assuan_process_done (ctx,
395 assuan_set_error (ctx, e, pwmd_strerror (e)));
399 assuan_log_cb (assuan_context_t ctx, void *data, unsigned cat,
400 const char *msg)
402 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
403 int i, t;
404 int match = 0;
406 pthread_mutex_lock (&m);
407 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock, &m);
408 t = strv_length (debug_level);
410 for (i = 0; i < t; i++)
412 if (!strcasecmp (debug_level[i], (char *) "init")
413 && cat == ASSUAN_LOG_INIT)
415 match = 1;
416 break;
419 if (!strcasecmp (debug_level[i], (char *) "ctx")
420 && cat == ASSUAN_LOG_CTX)
422 match = 1;
423 break;
426 if (!strcasecmp (debug_level[i], (char *) "engine")
427 && cat == ASSUAN_LOG_ENGINE)
429 match = 1;
430 break;
433 if (!strcasecmp (debug_level[i], (char *) "data")
434 && cat == ASSUAN_LOG_DATA)
436 match = 1;
437 break;
440 if (!strcasecmp (debug_level[i], (char *) "sysio")
441 && cat == ASSUAN_LOG_SYSIO)
443 match = 1;
444 break;
447 if (!strcasecmp (debug_level[i], (char *) "control")
448 && cat == ASSUAN_LOG_CONTROL)
450 match = 1;
451 break;
455 if (match && msg)
457 if (logfile)
459 int fd;
461 if ((fd =
462 open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600)) == -1)
463 warn ("%s", logfile);
464 else
466 pthread_cleanup_push (cleanup_fd_cb, &fd);
467 write (fd, msg, strlen (msg));
468 pthread_cleanup_pop (1);
472 if (nofork)
474 fprintf (stderr, "%s%s", data ? (char *) data : "", msg);
475 fflush (stderr);
479 pthread_cleanup_pop (1);
480 return match;
483 void
484 log_write (const char *fmt, ...)
486 char *args;
487 va_list ap;
488 time_t now;
489 char buf[255];
490 pthread_t tid = pthread_self ();
491 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
493 if ((!logfile && !isatty (STDERR_FILENO) && !log_syslog) || !fmt)
494 return;
496 pthread_mutex_lock (&m);
497 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock, &m);
499 if (!cmdline && logfile && log_fd == -1)
501 log_fd = open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600);
502 if (log_fd == -1)
503 warn ("%s", logfile);
506 va_start (ap, fmt);
508 if (str_vasprintf (&args, fmt, ap) != -1)
510 if (cmdline)
512 pthread_cleanup_push (xfree, args);
513 fprintf (stderr, "pwmd: %s\n", args);
514 fflush (stderr);
515 pthread_cleanup_pop (1);
517 else
519 char *name = pthread_getspecific (thread_name_key);
520 char *line;
522 pthread_cleanup_push (xfree, args);
523 snprintf (buf, sizeof (buf), "%s(%p): ", name ? name : _("unknown"),
524 (pthread_t *) tid);
525 name = buf;
527 if (!cmdline && log_syslog && !nofork)
528 syslog (LOG_INFO, "%s%s", name, args);
530 time (&now);
531 struct tm *tm = localtime (&now);
532 char tbuf[21];
533 strftime (tbuf, sizeof (tbuf), "%b %d %Y %H:%M:%S ", tm);
534 tbuf[sizeof (tbuf) - 1] = 0;
536 if (args[strlen (args) - 1] == '\n')
537 args[strlen (args) - 1] = 0;
539 line = str_asprintf ("%s %i %s%s\n", tbuf, getpid (), name,
540 args);
541 pthread_cleanup_pop (1);
542 if (line)
544 pthread_cleanup_push (xfree, line);
545 if (logfile && log_fd != -1)
547 write (log_fd, line, strlen (line));
548 fsync (log_fd);
551 if (nofork)
553 fprintf (stdout, "%s", line);
554 fflush (stdout);
557 pthread_cleanup_pop (1);
562 va_end (ap);
563 pthread_cleanup_pop (0);
565 if (log_fd != -1 && config_get_boolean (NULL, "log_keepopen") <= 0)
567 close(log_fd);
568 log_fd = -1;
571 pthread_mutex_unlock (&m);
574 #ifdef WITH_GNUTLS
575 static int
576 secure_mem_check (const void *arg)
578 return 1;
580 #endif
582 static gpg_error_t
583 setup_crypto ()
585 gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
587 if (!gcry_check_version (GCRYPT_VERSION))
589 fprintf (stderr, _("gcry_check_version(): Incompatible libgcrypt. "
590 "Wanted %s, got %s.\n"), GCRYPT_VERSION,
591 gcry_check_version (NULL));
592 return GPG_ERR_UNKNOWN_VERSION;
595 gcry_set_allocation_handler (xmalloc, xmalloc, NULL, xrealloc, xfree);
596 return 0;
599 #ifdef HAVE_GETGRNAM_R
600 gpg_error_t
601 do_validate_peer (assuan_context_t ctx, const char *section,
602 assuan_peercred_t * peer)
604 char **users;
605 int allowed = 0;
606 gpg_error_t rc;
607 #ifdef WITH_GNUTLS
608 struct client_s *client = assuan_get_pointer (ctx);
610 if (client && client->thd->remote)
611 return tls_validate_access (client, section);
612 #endif
614 rc = assuan_get_peercred (ctx, peer);
615 if (rc)
616 return rc;
618 users = config_get_list (section, "allowed");
619 if (users)
621 for (char **p = users; *p; p++)
623 struct passwd pw, *result;
624 struct group gr, *gresult;
625 char *buf = NULL;
626 char *user = *p;
627 int deny = (*user == '-') ? 1 : 0;
629 if (deny)
630 user++;
632 if (*user == '@') // all users in group
634 size_t len = sysconf (_SC_GETGR_R_SIZE_MAX);
636 if (len == -1)
637 len = 16384;
639 buf = xmalloc (len);
640 if (!buf)
642 strv_free (users);
643 return GPG_ERR_ENOMEM;
646 user++;
647 if (!getgrnam_r (user, &gr, buf, len, &gresult) && gresult)
649 if (gresult->gr_gid == (*peer)->gid)
651 xfree (buf);
652 allowed = !deny;
653 continue;
656 len = sysconf (_SC_GETPW_R_SIZE_MAX);
657 if (len == -1)
658 len = 16384;
660 char *tbuf = xmalloc (len);
661 for (char **t = gresult->gr_mem; *t; t++)
663 if (!getpwnam_r (*t, &pw, tbuf, len, &result) && result)
665 if (result->pw_uid == (*peer)->uid)
667 allowed = !deny;
668 break;
674 else
676 size_t len = sysconf (_SC_GETPW_R_SIZE_MAX);
678 if (len == -1)
679 len = 16384;
681 buf = xmalloc (len);
683 if (!buf)
685 strv_free (users);
686 return GPG_ERR_ENOMEM;
689 if (!getpwnam_r (user, &pw, buf, len, &result) && result)
691 if (result->pw_uid == (*peer)->uid)
692 allowed = !deny;
696 xfree (buf);
699 strv_free (users);
702 return allowed ? 0 : GPG_ERR_INV_USER_ID;
704 #else
705 gpg_error_t
706 do_validate_peer (assuan_context_t ctx, const char *section,
707 assuan_peercred_t * peer)
709 char **users;
710 int allowed = 0;
711 gpg_error_t rc;
712 #ifdef WITH_GNUTLS
713 struct client_s *client = assuan_get_pointer (ctx);
715 if (client && client->thd->remote)
716 return tls_validate_access (client, section);
717 #endif
719 rc = assuan_get_peercred (ctx, peer);
720 if (rc)
721 return rc;
723 users = config_get_list (section, "allowed");
724 if (users)
726 for (char **p = users; *p; p++)
728 struct passwd *result;
729 struct group *gresult;
730 char *user = *p;
731 int deny = (*user == '-') ? 1 : 0;
733 if (deny)
734 user++;
736 if (*user == '@') // all users in group
738 user++;
739 gresult = getgrnam (user);
740 if (gresult && gresult->gr_gid == (*peer)->gid)
742 allowed = !deny;
743 continue;
746 for (char **t = gresult->gr_mem; *t; t++)
748 result = getpwnam (*t);
749 if (result && result->pw_uid == (*peer)->uid)
751 allowed = !deny;
752 break;
756 else
758 result = getpwnam (user);
759 if (result && result->pw_uid == (*peer)->uid)
760 allowed = !deny;
764 strv_free (users);
767 return allowed ? 0 : GPG_ERR_INV_USER_ID;
769 #endif
771 static gpg_error_t
772 validate_peer (struct client_s *cl)
774 gpg_error_t rc;
775 assuan_peercred_t peer;
777 #ifdef WITH_GNUTLS
778 if (cl->thd->remote)
779 return tls_validate_access (cl, NULL);
780 #endif
782 rc = do_validate_peer (cl->ctx, "global", &peer);
783 if (!rc || gpg_err_code (rc) == GPG_ERR_INV_USER_ID)
784 log_write ("peer %s: uid=%i, gid=%i, pid=%i",
785 !rc ? _("accepted") : _("rejected"), peer->uid, peer->gid,
786 peer->pid);
787 else if (rc)
788 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
790 return rc;
793 static void
794 xml_error_cb (void *data, xmlErrorPtr e)
796 struct client_s *client = data;
799 * Keep the first reported error as the one to show in the error
800 * description. Reset in send_error().
802 if (client->xml_error)
803 return;
805 client->xml_error = xcalloc (1, sizeof(xmlError));
806 xmlCopyError (e, client->xml_error);
809 static pid_t
810 hook_waitpid (assuan_context_t ctx, pid_t pid, int action,
811 int *status, int options)
813 return waitpid (pid, status, options);
816 static ssize_t
817 hook_read (assuan_context_t ctx, assuan_fd_t fd, void *data, size_t len)
819 #ifdef WITH_GNUTLS
820 struct client_s *client = assuan_get_pointer (ctx);
822 if (client->thd->remote)
823 return tls_read_hook (ctx, (int) fd, data, len);
824 #endif
826 return read ((int) fd, data, len);
829 static ssize_t
830 hook_write (assuan_context_t ctx, assuan_fd_t fd,
831 const void *data, size_t len)
833 #ifdef WITH_GNUTLS
834 struct client_s *client = assuan_get_pointer (ctx);
836 if (client->thd->remote)
837 return tls_write_hook (ctx, (int) fd, data, len);
838 #endif
840 return write ((int) fd, data, len);
843 static int
844 new_connection (struct client_s *cl)
846 gpg_error_t rc;
847 static struct assuan_malloc_hooks mhooks = { xmalloc, xrealloc, xfree };
848 static struct assuan_system_hooks shooks = {
849 ASSUAN_SYSTEM_HOOKS_VERSION,
850 __assuan_usleep,
851 __assuan_pipe,
852 __assuan_close,
853 hook_read,
854 hook_write,
855 //FIXME
856 NULL, //recvmsg
857 NULL, //sendmsg both are used for FD passing
858 __assuan_spawn,
859 hook_waitpid,
860 __assuan_socketpair,
861 __assuan_socket,
862 __assuan_connect
865 #ifdef WITH_GNUTLS
866 if (cl->thd->remote)
868 char *prio = config_get_string ("global", "tls_cipher_suite");
870 cl->thd->tls = tls_init (cl->thd->fd, cl->thd->timeout, prio);
871 xfree (prio);
872 if (!cl->thd->tls)
873 return 0;
875 #endif
877 rc = assuan_new_ext (&cl->ctx, GPG_ERR_SOURCE_DEFAULT, &mhooks,
878 debug_level ? assuan_log_cb : NULL, NULL);
879 if (rc)
880 goto fail;
882 assuan_ctx_set_system_hooks (cl->ctx, &shooks);
883 rc = assuan_init_socket_server (cl->ctx, cl->thd->fd, 2);
884 if (rc)
885 goto fail;
887 assuan_set_pointer (cl->ctx, cl);
888 assuan_set_hello_line (cl->ctx, PACKAGE_STRING);
889 rc = register_commands (cl->ctx);
890 if (rc)
891 goto fail;
893 #ifdef WITH_GNUTLS
894 if (cl->thd->remote)
896 cl->thd->timeout = config_get_integer ("global", "tls_timeout");
897 fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK);
899 #endif
901 rc = assuan_accept (cl->ctx);
902 if (rc)
903 goto fail;
905 rc = validate_peer (cl);
906 /* May not be implemented on all platforms. */
907 if (rc && gpg_err_code (rc) != GPG_ERR_ASS_GENERAL)
908 goto fail;
910 rc = init_client_crypto (&cl->crypto);
911 if (rc)
912 goto fail;
914 #ifdef WITH_AGENT
915 if (use_agent)
916 cl->crypto->agent->client_ctx = cl->ctx;
917 #endif
919 cl->crypto->client_ctx = cl->ctx;
920 xmlSetStructuredErrorFunc (cl, xml_error_cb);
921 return 1;
923 fail:
924 log_write ("%s", pwmd_strerror (rc));
925 return 0;
929 * This is called after a client_thread() terminates. Set with
930 * pthread_cleanup_push().
932 static void
933 cleanup_cb (void *arg)
935 struct client_thread_s *cn = arg;
936 struct client_s *cl = cn->cl;
938 MUTEX_LOCK (&cn_mutex);
939 cn_thread_list = slist_remove (cn_thread_list, cn);
940 MUTEX_UNLOCK (&cn_mutex);
942 if (cl)
944 cleanup_client (cl);
945 if (cl->xml_error)
946 xmlResetError (cl->xml_error);
948 xfree (cl->xml_error);
950 #ifdef WITH_GNUTLS
951 if (cn->tls)
953 gnutls_deinit (cn->tls->ses);
954 xfree (cn->tls->fp);
955 xfree (cn->tls);
957 #endif
959 if (!cn->atfork && cl->ctx)
960 assuan_release (cl->ctx);
961 else if (!cn->atfork && cl->thd && cl->thd->fd != -1)
962 close (cl->thd->fd);
964 if (cl->crypto)
965 cleanup_crypto (&cl->crypto);
967 pinentry_free_opts (&cl->pinentry_opts);
968 xfree (cl);
970 else
972 if (cn->fd != -1)
973 close (cn->fd);
976 while (cn->msg_queue)
978 struct status_msg_s *msg = cn->msg_queue;
980 cn->msg_queue = msg->next;
981 xfree (msg->line);
982 xfree (msg);
985 if (!cn->atfork && cn->status_msg_pipe[0] != -1)
986 close (cn->status_msg_pipe[0]);
988 if (!cn->atfork && cn->status_msg_pipe[1] != -1)
989 close (cn->status_msg_pipe[1]);
991 pthread_mutex_destroy (&cn->status_mutex);
993 if (!cn->atfork)
995 log_write (_("exiting, fd=%i"), cn->fd);
996 send_status_all (STATUS_CLIENTS, NULL);
999 xfree (cn);
1000 pthread_cond_signal (&quit_cond);
1003 void
1004 cleanup_all_clients (int atfork)
1006 /* This function may be called from pthread_atfork() which requires
1007 reinitialization. */
1008 if (atfork)
1010 pthread_mutexattr_t attr;
1012 pthread_mutexattr_init (&attr);
1013 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
1014 pthread_mutex_init (&cn_mutex, &attr);
1015 pthread_mutexattr_destroy (&attr);
1016 cache_mutex_init ();
1019 MUTEX_LOCK (&cn_mutex);
1021 while (slist_length (cn_thread_list))
1023 struct client_thread_s *thd = slist_nth_data (cn_thread_list, 0);
1025 thd->atfork = atfork;
1026 cleanup_cb (thd);
1029 exiting = 1;
1030 MUTEX_UNLOCK (&cn_mutex);
1031 cache_deinit (atfork);
1034 static gpg_error_t
1035 send_msg_queue (struct client_thread_s *thd)
1037 MUTEX_LOCK (&thd->status_mutex);
1038 gpg_error_t rc = 0;
1039 char c;
1041 read (thd->status_msg_pipe[0], &c, 1);
1043 while (thd->msg_queue)
1045 struct status_msg_s *msg = thd->msg_queue;
1047 thd->msg_queue = thd->msg_queue->next;
1048 MUTEX_UNLOCK (&thd->status_mutex);
1049 rc = send_status (thd->cl->ctx, msg->s, msg->line);
1050 MUTEX_LOCK (&thd->status_mutex);
1051 xfree (msg->line);
1052 xfree (msg);
1054 if (rc)
1055 break;
1058 MUTEX_UNLOCK (&thd->status_mutex);
1059 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1060 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
1062 return rc;
1065 static void *
1066 client_thread (void *data)
1068 struct client_thread_s *thd = data;
1069 struct client_s *cl = xcalloc (1, sizeof (struct client_s));
1071 #ifdef HAVE_PR_SET_NAME
1072 prctl (PR_SET_NAME, "client");
1073 #endif
1074 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1076 if (!cl)
1078 log_write ("%s(%i): %s", __FILE__, __LINE__,
1079 pwmd_strerror (GPG_ERR_ENOMEM));
1080 return NULL;
1083 MUTEX_LOCK (&cn_mutex);
1084 pthread_cleanup_push (cleanup_cb, thd);
1085 thd->cl = cl;
1086 cl->thd = thd;
1087 MUTEX_UNLOCK (&cn_mutex);
1089 if (new_connection (cl))
1091 int finished = 0;
1092 gpg_error_t rc;
1094 send_status_all (STATUS_CLIENTS, NULL);
1095 rc = send_status (cl->ctx, STATUS_CACHE, NULL);
1096 if (rc)
1098 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
1099 finished = 1;
1102 while (!finished)
1104 fd_set rfds;
1105 int n;
1106 int eof;
1108 FD_ZERO (&rfds);
1109 FD_SET (thd->fd, &rfds);
1110 FD_SET (thd->status_msg_pipe[0], &rfds);
1111 n = thd->fd > thd->status_msg_pipe[0]
1112 ? thd->fd : thd->status_msg_pipe[0];
1114 n = select (n + 1, &rfds, NULL, NULL, NULL);
1115 if (n == -1)
1117 log_write ("%s", strerror (errno));
1118 break;
1121 if (FD_ISSET (thd->status_msg_pipe[0], &rfds))
1123 rc = send_msg_queue (thd);
1124 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1125 break;
1128 if (!FD_ISSET (thd->fd, &rfds))
1129 continue;
1131 rc = assuan_process_next (cl->ctx, &eof);
1132 if (rc || eof)
1134 if (gpg_err_code (rc) == GPG_ERR_EOF || eof)
1135 break;
1137 log_write ("assuan_process_next(): rc=%i %s", rc,
1138 pwmd_strerror (rc));
1139 if (rc == gpg_error (GPG_ERR_ETIMEDOUT))
1140 break;
1142 rc = send_error (cl->ctx, rc);
1143 if (rc)
1145 log_write ("assuan_process_done(): rc=%i %s", rc,
1146 pwmd_strerror (rc));
1147 break;
1151 /* Since the msg queue pipe fd's are non-blocking, check for
1152 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1153 * client has already disconnected and will be converted to
1154 * GPG_ERR_EOF during assuan_process_next().
1156 rc = send_msg_queue (thd);
1157 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1158 break;
1162 pthread_cleanup_pop (1);
1163 return NULL;
1166 static int
1167 xml_import (const char *filename, const char *outfile,
1168 const char *keygrip, const char *sign_keygrip,
1169 const char *keyfile, int no_passphrase, const char *cipher,
1170 const char *params, unsigned long s2k_count, uint64_t iterations)
1172 xmlDocPtr doc;
1173 int fd;
1174 struct stat st;
1175 int len;
1176 xmlChar *xmlbuf;
1177 xmlChar *xml;
1178 gpg_error_t rc;
1179 struct crypto_s *crypto = NULL;
1180 void *key = NULL;
1181 size_t keylen = 0;
1182 int algo = cipher ? cipher_string_to_gcrypt ((char *) cipher) :
1183 GCRY_CIPHER_AES256;
1185 if (algo == -1)
1187 log_write ("ERR %i: %s", gpg_error (GPG_ERR_CIPHER_ALGO),
1188 pwmd_strerror (GPG_ERR_CIPHER_ALGO));
1189 return 0;
1192 if (stat (filename, &st) == -1)
1194 log_write ("%s: %s", filename,
1195 pwmd_strerror (gpg_error_from_errno (errno)));
1196 return 0;
1199 rc = init_client_crypto (&crypto);
1200 if (rc)
1201 return 0;
1203 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
1204 crypto->save.hdr.flags = set_cipher_flag (crypto->save.hdr.flags, algo);
1205 log_write (_("Importing XML from '%s'. Output will be written to '%s' ..."),
1206 filename, outfile);
1208 if ((fd = open (filename, O_RDONLY)) == -1)
1210 log_write ("%s: %s", filename,
1211 pwmd_strerror (gpg_error_from_errno (errno)));
1212 goto fail;
1215 if ((xmlbuf = xmalloc (st.st_size + 1)) == NULL)
1217 close (fd);
1218 log_write ("%s(%i): %s", __FILE__, __LINE__,
1219 pwmd_strerror (GPG_ERR_ENOMEM));
1220 goto fail;
1223 if (read (fd, xmlbuf, st.st_size) == -1)
1225 rc = gpg_error_from_errno (errno);
1226 close (fd);
1227 log_write ("%s: %s", filename, pwmd_strerror (rc));
1228 goto fail;
1231 close (fd);
1232 xmlbuf[st.st_size] = 0;
1234 * Make sure the document validates.
1236 if ((doc = xmlReadDoc (xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS)) == NULL)
1238 log_write ("xmlReadDoc() failed");
1239 xfree (xmlbuf);
1240 goto fail;
1243 xfree (xmlbuf);
1244 xmlNodePtr n = xmlDocGetRootElement (doc);
1245 if (n && !xmlStrEqual (n->name, (xmlChar *) "pwmd"))
1247 log_write (_("Could not find root \"pwmd\" element."));
1248 rc = GPG_ERR_BAD_DATA;
1251 if (!rc)
1252 rc = validate_import (n ? n->children : n);
1254 if (rc)
1256 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1257 xmlFreeDoc (doc);
1258 goto fail;
1261 xmlDocDumpMemory (doc, &xml, &len);
1262 xmlFreeDoc (doc);
1263 crypto->save.s2k_count = s2k_count;
1264 crypto->save.hdr.iterations = iterations;
1265 if (!use_agent)
1267 rc = export_common (NULL, 0, crypto, xml, len, outfile, keyfile, &key,
1268 &keylen, 0, 0, no_passphrase);
1269 if (!rc)
1270 log_write (_("Success!"));
1272 #ifdef WITH_AGENT
1273 else
1275 rc = agent_set_pinentry_options (crypto->agent);
1276 if (!rc)
1277 rc = agent_export_common (crypto, keygrip, sign_keygrip, no_passphrase,
1278 xml, len, outfile, params, keyfile);
1280 #endif
1282 gcry_free (key);
1283 xmlFree (xml);
1284 if (rc)
1286 send_error (NULL, rc);
1287 goto fail;
1290 cleanup_crypto (&crypto);
1291 return 1;
1293 fail:
1294 cleanup_crypto (&crypto);
1295 return 0;
1298 static int
1299 do_cache_push (const char *filename, struct crypto_s *crypto)
1301 unsigned char md5file[16];
1302 gpg_error_t rc;
1303 char *key = NULL;
1304 size_t keylen = 0;
1305 xmlDocPtr doc;
1306 struct cache_data_s *cdata;
1307 unsigned char *crc;
1308 size_t len;
1310 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1311 filename);
1313 if (valid_filename (filename) == 0)
1315 log_write (_("%s: Invalid characters in filename"), filename);
1316 return 0;
1319 rc = decrypt_common (NULL, 0, crypto, filename, &key, &keylen);
1320 if (rc)
1321 return 0;
1323 rc = parse_doc ((char *) crypto->plaintext, crypto->plaintext_len, &doc);
1324 if (rc)
1326 log_write ("%s", pwmd_strerror (rc));
1327 xfree (key);
1328 return 0;
1331 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
1332 cdata = xcalloc (1, sizeof (struct cache_data_s));
1333 if (!cdata)
1335 xmlFreeDoc (doc);
1336 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM));
1337 xfree (key);
1338 return 0;
1341 rc = get_checksum (filename, &crc, &len);
1342 if (rc)
1344 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1345 xmlFreeDoc (doc);
1346 free_cache_data_once (cdata);
1347 xfree (key);
1348 return 0;
1351 cdata->crc = crc;
1352 rc = encrypt_xml (NULL, cache_key, cache_keysize, GCRY_CIPHER_AES,
1353 crypto->plaintext, crypto->plaintext_len, &cdata->doc,
1354 &cdata->doclen, &cache_iv, &cache_blocksize, 0);
1355 if (!rc && !IS_PKI (crypto))
1357 cdata->key = key;
1358 cdata->keylen = keylen;
1360 else
1361 xfree (key);
1363 if (rc)
1365 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1366 xmlFreeDoc (doc);
1367 free_cache_data_once (cdata);
1368 return 0;
1371 #ifdef WITH_AGENT
1372 if (use_agent && IS_PKI (crypto))
1374 gcry_sexp_build ((gcry_sexp_t *) & cdata->pubkey, NULL, "%S",
1375 crypto->pkey_sexp);
1376 gcry_sexp_build ((gcry_sexp_t *) & cdata->sigkey, NULL, "%S",
1377 crypto->sigpkey_sexp);
1379 #endif
1381 int timeout = config_get_integer (filename, "cache_timeout");
1382 cache_add_file (md5file, crypto->grip, cdata, timeout);
1383 log_write (_("Successfully added '%s' to the cache."), filename);
1384 return 1;
1387 static gpg_error_t
1388 init_client (int fd, const char *addr)
1390 gpg_error_t rc = 0;
1391 struct client_thread_s *new = xcalloc (1, sizeof (struct client_thread_s));
1393 if (!new)
1395 close (fd);
1396 return GPG_ERR_ENOMEM;
1399 MUTEX_LOCK (&cn_mutex);
1400 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
1402 if (pipe (new->status_msg_pipe) == -1)
1403 rc = gpg_error_from_errno (errno);
1405 if (!rc)
1407 fcntl (new->status_msg_pipe[0], F_SETFL, O_NONBLOCK);
1408 fcntl (new->status_msg_pipe[1], F_SETFL, O_NONBLOCK);
1409 pthread_mutex_init (&new->status_mutex, NULL);
1412 if (!rc)
1414 #ifdef WITH_GNUTLS
1415 new->remote = addr ? 1 : 0;
1416 #endif
1417 new->fd = fd;
1418 rc = create_thread (client_thread, new, &new->tid, 1);
1419 if (rc)
1421 close (new->status_msg_pipe[0]);
1422 close (new->status_msg_pipe[1]);
1423 pthread_mutex_destroy (&new->status_mutex);
1427 if (!rc)
1429 struct slist_s *list = slist_append (cn_thread_list, new);
1431 if (list)
1433 cn_thread_list = list;
1434 if (addr)
1435 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1436 (pthread_t *) new->tid, fd, addr);
1437 else
1438 log_write (_("new connection: tid=%p, fd=%i"),
1439 (pthread_t *) new->tid, fd);
1441 else
1442 rc = GPG_ERR_ENOMEM;
1445 pthread_cleanup_pop (1);
1447 if (rc)
1449 xfree (new);
1450 close (fd);
1451 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1452 pwmd_strerror (rc));
1454 return rc;
1457 static void*
1458 keepalive_thread (void *arg)
1460 #ifndef HAVE_PTHREAD_CANCEL
1461 int *n = xmalloc (sizeof (int));
1463 *n = 0;
1464 pthread_setspecific (signal_thread_key, n);
1465 INIT_THREAD_SIGNAL;
1466 #endif
1468 #ifdef HAVE_PR_SET_NAME
1469 prctl (PR_SET_NAME, "keepalive");
1470 #endif
1471 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1473 for (;;)
1475 int n = config_get_integer ("global", "keepalive_interval");
1476 struct timeval tv = { n, 0 };
1477 #ifndef HAVE_PTHREAD_CANCEL
1478 int *sigusr2;
1480 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1481 if (*sigusr2)
1482 break;
1483 #endif
1485 send_status_all (STATUS_KEEPALIVE, NULL);
1486 select (0, NULL, NULL, NULL, &tv);
1489 return NULL;
1492 #ifdef WITH_GNUTLS
1493 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1494 static void *
1495 get_in_addr (struct sockaddr *sa)
1497 if (sa->sa_family == AF_INET)
1498 return &(((struct sockaddr_in *) sa)->sin_addr);
1500 return &(((struct sockaddr_in6 *) sa)->sin6_addr);
1503 static void *
1504 tcp_accept_thread (void *arg)
1506 int sockfd = *(int *) arg;
1507 #ifndef HAVE_PTHREAD_CANCEL
1508 int *n = xmalloc (sizeof (int));
1510 *n = 0;
1511 pthread_setspecific (signal_thread_key, n);
1512 INIT_THREAD_SIGNAL;
1513 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1514 #endif
1516 #ifdef HAVE_PR_SET_NAME
1517 prctl (PR_SET_NAME, "tcp_accept");
1518 #endif
1519 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1521 for (;;)
1523 struct sockaddr_storage raddr;
1524 socklen_t slen = sizeof (raddr);
1525 int fd;
1526 unsigned long n;
1527 char s[INET6_ADDRSTRLEN];
1528 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1529 #ifndef HAVE_PTHREAD_CANCEL
1530 int *sigusr2;
1532 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1533 if (*sigusr2)
1534 break;
1535 #endif
1537 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1538 if (fd == -1)
1540 if (errno == EMFILE || errno == ENFILE)
1541 log_write ("accept(): %s",
1542 pwmd_strerror (gpg_error_from_errno (errno)));
1543 else if (errno != EAGAIN)
1545 if (!quit) // probably EBADF
1546 log_write ("accept(): %s", strerror (errno));
1548 break;
1551 #ifndef HAVE_PTHREAD_CANCEL
1552 select (0, NULL, NULL, NULL, &tv);
1553 #endif
1554 continue;
1557 if (quit)
1558 break;
1560 inet_ntop (raddr.ss_family, get_in_addr ((struct sockaddr *) &raddr),
1561 s, sizeof s);
1562 (void) init_client (fd, s);
1563 n = config_get_integer ("global", "tcp_wait");
1564 if (n > 0)
1566 tv.tv_sec = (n * 100000) / 100000;
1567 tv.tv_usec = (n * 100000) % 100000;
1568 select (0, NULL, NULL, NULL, &tv);
1572 return NULL;
1575 static int
1576 start_stop_tls_with_protocol (int ipv6, int term)
1578 struct addrinfo hints, *servinfo, *p;
1579 int port = config_get_integer ("global", "tcp_port");
1580 char buf[7];
1581 int n;
1582 gpg_error_t rc;
1583 int *fd = ipv6 ? &tls6_fd : &tls_fd;
1585 if (term || config_get_boolean ("global", "enable_tcp") == 0)
1587 if (tls6_fd != -1)
1589 if (spawned_tls6)
1591 #ifdef HAVE_PTHREAD_CANCEL
1592 pthread_cancel (tls6_tid);
1593 #else
1594 pthread_kill (tls6_tid, SIGUSR2);
1595 #endif
1596 pthread_join (tls6_tid, NULL);
1599 shutdown (tls6_fd, SHUT_RDWR);
1600 close (tls6_fd);
1601 tls6_fd = -1;
1602 spawned_tls6 = 0;
1605 if (tls_fd != -1)
1607 if (spawned_tls)
1609 #ifdef HAVE_PTHREAD_CANCEL
1610 pthread_cancel (tls_tid);
1611 #else
1612 pthread_kill (tls_tid, SIGUSR2);
1613 #endif
1614 pthread_join (tls_tid, NULL);
1617 shutdown (tls_fd, SHUT_RDWR);
1618 close (tls_fd);
1619 tls_fd = -1;
1620 spawned_tls = 0;
1623 /* A client may still be connected. */
1624 if (!quit && x509_cred != NULL)
1625 tls_deinit_params ();
1627 return 1;
1630 if ((ipv6 && tls6_fd != -1) || (!ipv6 && tls_fd != -1))
1631 return 1;
1633 memset (&hints, 0, sizeof (hints));
1634 hints.ai_family = ipv6 ? AF_INET6 : AF_INET;
1635 hints.ai_socktype = SOCK_STREAM;
1636 hints.ai_flags = AI_PASSIVE;
1637 snprintf (buf, sizeof (buf), "%i", port);
1639 if ((n = getaddrinfo (NULL, buf, &hints, &servinfo)) == -1)
1641 log_write ("getaddrinfo(): %s", gai_strerror (n));
1642 return 0;
1645 for (n = 0, p = servinfo; p != NULL; p = p->ai_next)
1647 int r = 1;
1649 if ((ipv6 && p->ai_family != AF_INET6)
1650 || (!ipv6 && p->ai_family != AF_INET))
1651 continue;
1653 if ((*fd = socket (p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
1655 log_write ("socket(): %s", strerror (errno));
1656 continue;
1659 if (setsockopt (*fd, SOL_SOCKET, SO_REUSEADDR, &r, sizeof (int)) == -1)
1661 log_write ("setsockopt(): %s",
1662 pwmd_strerror (gpg_error_from_errno (errno)));
1663 freeaddrinfo (servinfo);
1664 goto fail;
1667 if (bind (*fd, p->ai_addr, p->ai_addrlen) == -1)
1669 close (*fd);
1670 log_write ("bind(): %s",
1671 pwmd_strerror (gpg_error_from_errno (errno)));
1672 continue;
1675 n++;
1676 break;
1679 freeaddrinfo (servinfo);
1681 if (!n)
1682 goto fail;
1684 #if HAVE_DECL_SO_BINDTODEVICE != 0
1685 char *tmp = config_get_string ("global", "tcp_interface");
1686 if (tmp && setsockopt (*fd, SOL_SOCKET, SO_BINDTODEVICE, tmp,
1687 strlen (tmp)) == -1)
1689 log_write ("setsockopt(): %s",
1690 pwmd_strerror (gpg_error_from_errno (errno)));
1691 xfree (tmp);
1692 goto fail;
1695 xfree (tmp);
1696 #endif
1698 if (x509_cred == NULL)
1700 rc = tls_init_params ();
1701 if (rc)
1702 goto fail;
1705 if (listen (*fd, 0) == -1)
1707 log_write ("listen(): %s", strerror (errno));
1708 goto fail;
1711 if (ipv6)
1712 rc = create_thread (tcp_accept_thread, fd, &tls6_tid, 0);
1713 else
1714 rc = create_thread (tcp_accept_thread, fd, &tls_tid, 0);
1716 if (rc)
1718 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1719 pwmd_strerror (rc));
1720 goto fail;
1723 if (ipv6)
1724 spawned_tls6 = 1;
1725 else
1726 spawned_tls = 1;
1728 return 1;
1730 fail:
1731 start_stop_tls_with_protocol (0, 1);
1732 if (tls_fd != -1)
1733 close (tls_fd);
1735 if (tls6_fd != -1)
1736 close (tls6_fd);
1738 tls_fd = -1;
1739 tls6_fd = -1;
1740 return 0;
1743 static int
1744 start_stop_tls (int term)
1746 char *s = config_get_string ("global", "tcp_bind");
1747 int b;
1749 if (!s)
1750 return 0;
1752 if (!strcmp (s, "any"))
1754 b = start_stop_tls_with_protocol (0, term);
1755 if (b)
1756 b = start_stop_tls_with_protocol (1, term);
1758 else if (!strcmp (s, "ipv4"))
1759 b = start_stop_tls_with_protocol (0, term);
1760 else if (!strcmp (s, "ipv6"))
1761 b = start_stop_tls_with_protocol (1, term);
1762 else
1763 b = 0;
1765 xfree (s);
1766 return b;
1768 #endif
1770 static void *
1771 accept_thread (void *arg)
1773 int sockfd = *(int *) arg;
1774 #ifndef HAVE_PTHREAD_CANCEL
1775 int *n = xmalloc (sizeof (int));
1777 *n = 0;
1778 pthread_setspecific (signal_thread_key, n);
1779 INIT_THREAD_SIGNAL;
1780 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1781 #endif
1783 #ifdef HAVE_PR_SET_NAME
1784 prctl (PR_SET_NAME, "accept");
1785 #endif
1786 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1788 for (;;)
1790 socklen_t slen = sizeof (struct sockaddr_un);
1791 struct sockaddr_un raddr;
1792 int fd;
1793 #ifndef HAVE_PTHREAD_CANCEL
1794 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1795 int *sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1797 if (*sigusr2)
1798 break;
1799 #endif
1801 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1802 if (fd == -1)
1804 if (errno == EMFILE || errno == ENFILE)
1805 log_write ("accept(): %s",
1806 pwmd_strerror (gpg_error_from_errno (errno)));
1807 else if (errno != EAGAIN)
1809 if (!quit) // probably EBADF
1810 log_write ("accept(): %s",
1811 pwmd_strerror (gpg_error_from_errno (errno)));
1813 break;
1816 #ifndef HAVE_PTHREAD_CANCEL
1817 select (0, NULL, NULL, NULL, &tv);
1818 #endif
1819 continue;
1822 (void) init_client (fd, NULL);
1825 /* Just in case accept() failed for some reason other than EBADF */
1826 quit = 1;
1827 return NULL;
1830 static void *
1831 cache_timer_thread (void *arg)
1833 #ifndef HAVE_PTHREAD_CANCEL
1834 int *n = xmalloc (sizeof (int));
1836 *n = 0;
1837 pthread_setspecific (signal_thread_key, n);
1838 INIT_THREAD_SIGNAL;
1839 #endif
1841 #ifdef HAVE_PR_SET_NAME
1842 prctl (PR_SET_NAME, "cache timer");
1843 #endif
1844 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1846 for (;;)
1848 struct timeval tv = { 1, 0 };
1849 #ifndef HAVE_PTHREAD_CANCEL
1850 int *n;
1852 n = (int *) pthread_getspecific (signal_thread_key);
1853 if (*n)
1854 break;
1855 #endif
1857 select (0, NULL, NULL, NULL, &tv);
1858 cache_adjust_timeout ();
1861 return NULL;
1864 static int
1865 signal_loop (sigset_t sigset)
1867 int done = 0;
1868 int siint = 0;
1872 int sig;
1874 sigwait (&sigset, &sig);
1876 if (sig != SIGQUIT)
1877 log_write (_("caught signal %i (%s)"), sig, strsignal (sig));
1879 switch (sig)
1881 case SIGHUP:
1882 pthread_cond_signal (&rcfile_cond);
1883 break;
1884 case SIGUSR1:
1885 log_write (_("clearing file cache"));
1886 cache_clear (NULL);
1887 send_status_all (STATUS_CACHE, NULL);
1888 break;
1889 case SIGQUIT:
1890 done = 1;
1891 break;
1892 default:
1893 siint = 1;
1894 done = 1;
1895 break;
1898 while (!done);
1900 return siint;
1903 static void
1904 catchsig (int sig)
1906 log_write (_ ("Caught signal %i (%s). Exiting."), sig, strsignal (sig));
1907 #ifdef HAVE_BACKTRACE
1908 BACKTRACE (__FUNCTION__);
1909 #endif
1910 longjmp (jmp, 1);
1913 static void *
1914 waiting_for_exit (void *arg)
1916 int last = 0;
1917 #ifndef HAVE_PTHREAD_CANCEL
1918 int *n = xmalloc (sizeof (int));
1920 *n = 0;
1921 pthread_setspecific (signal_thread_key, n);
1922 INIT_THREAD_SIGNAL;
1923 #endif
1925 #ifdef HAVE_PR_SET_NAME
1926 prctl (PR_SET_NAME, "exiting");
1927 #endif
1928 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1929 log_write (_("waiting for all clients to disconnect"));
1930 MUTEX_LOCK (&quit_mutex);
1931 pthread_cleanup_push (cleanup_mutex_cb, &quit_mutex);
1933 for (;;)
1935 struct timespec ts;
1936 int n;
1938 MUTEX_LOCK (&cn_mutex);
1939 n = slist_length (cn_thread_list);
1940 MUTEX_UNLOCK (&cn_mutex);
1941 if (!n)
1942 break;
1944 #ifndef HAVE_PTHREAD_CANCEL
1945 int *s = (int *) pthread_getspecific (signal_thread_key);
1946 if (*s)
1947 break;
1948 #endif
1950 if (last != n)
1952 log_write (_("%i clients remain"), n);
1953 last = n;
1956 INIT_TIMESPEC (SIG_TIMEOUT, ts);
1957 pthread_cond_timedwait (&quit_cond, &quit_mutex, &ts);
1960 kill (getpid (), SIGQUIT);
1961 pthread_cleanup_pop (1);
1962 return NULL;
1965 static int
1966 server_loop (int sockfd, char **socketpath)
1968 pthread_t accept_tid;
1969 pthread_t cache_timeout_tid;
1970 int cancel_timeout_thread = 0, cancel_accept_thread = 0;
1971 int cancel_keepalive_thread = 0;
1972 sigset_t sigset;
1973 int n;
1974 int segv = 0;
1975 gpg_error_t rc;
1977 init_commands ();
1978 sigemptyset (&sigset);
1980 /* Termination */
1981 sigaddset (&sigset, SIGTERM);
1982 sigaddset (&sigset, SIGINT);
1984 /* Clears the file cache. */
1985 sigaddset (&sigset, SIGUSR1);
1987 /* Configuration file reloading. */
1988 sigaddset (&sigset, SIGHUP);
1990 /* For exiting cleanly. */
1991 sigaddset (&sigset, SIGQUIT);
1993 #ifndef HAVE_PTHREAD_CANCEL
1995 The socket, cache and rcfile threads use this signal when
1996 pthread_cancel() is unavailable. Prevent the main thread from
1997 catching this signal from another process.
1999 sigaddset (&sigset, SIGUSR2);
2000 #endif
2002 /* When mem.c cannot find a pointer in the list (double free). */
2003 signal (SIGABRT, catchsig);
2004 sigaddset (&sigset, SIGABRT);
2005 sigprocmask (SIG_BLOCK, &sigset, NULL);
2007 #ifndef HAVE_PTHREAD_CANCEL
2008 /* Remove this signal from the watched signals in signal_loop(). */
2009 sigdelset (&sigset, SIGUSR2);
2010 #endif
2012 /* Ignored everywhere. When a client disconnects abnormally this signal
2013 * gets raised. It isn't needed though because client_thread() will check
2014 * for rcs even after the client disconnects. */
2015 signal (SIGPIPE, SIG_IGN);
2017 /* Can show a backtrace of the stack in the log. */
2018 signal (SIGSEGV, catchsig);
2020 #ifdef WITH_GNUTLS
2021 /* Needs to be done after the fork(). */
2022 if (!start_stop_tls (0))
2024 segv = 1;
2025 goto done;
2027 #endif
2029 pthread_mutex_init (&quit_mutex, NULL);
2030 pthread_cond_init (&quit_cond, NULL);
2031 log_write (_("%s started for user %s"), PACKAGE_STRING, get_username ());
2033 #ifdef WITH_GNUTLS
2034 if (config_get_boolean ("global", "enable_tcp"))
2035 log_write (_("Listening on %s and TCP port %i"), *socketpath,
2036 config_get_integer ("global", "tcp_port"));
2037 else
2038 log_write (_("Listening on %s"), *socketpath);
2039 #else
2040 log_write (_("Listening on %s"), *socketpath);
2041 #endif
2043 rc = create_thread (keepalive_thread, NULL, &keepalive_tid, 0);
2044 if (rc)
2046 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2047 pwmd_strerror (rc));
2048 goto done;
2051 cancel_keepalive_thread = 1;
2052 rc = create_thread (reload_rcfile_thread, NULL, &rcfile_tid, 0);
2053 if (rc)
2055 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2056 pwmd_strerror (rc));
2057 goto done;
2060 rc = create_thread (cache_timer_thread, NULL, &cache_timeout_tid, 0);
2061 if (rc)
2063 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2064 pwmd_strerror (rc));
2065 goto done;
2068 cancel_timeout_thread = 1;
2069 rc = create_thread (accept_thread, &sockfd, &accept_tid, 0);
2070 if (rc)
2072 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2073 pwmd_strerror (rc));
2074 goto done;
2077 cancel_accept_thread = 1;
2078 if (!setjmp (jmp))
2079 signal_loop (sigset);
2080 else
2081 segv = 1;
2083 done:
2085 * We're out of the main server loop. This happens when a signal was sent
2086 * to terminate the daemon. We'll wait for all clients to disconnect
2087 * before exiting but exit immediately if another termination signal is
2088 * sent.
2090 if (cancel_accept_thread)
2092 #ifdef HAVE_PTHREAD_CANCEL
2093 int n = pthread_cancel (accept_tid);
2094 #else
2095 int n = pthread_kill (accept_tid, SIGUSR2);
2096 #endif
2097 if (!n)
2098 pthread_join (accept_tid, NULL);
2101 #ifdef WITH_GNUTLS
2102 start_stop_tls (1);
2103 #endif
2104 shutdown (sockfd, SHUT_RDWR);
2105 close (sockfd);
2106 unlink (*socketpath);
2107 xfree (*socketpath);
2108 *socketpath = NULL;
2109 MUTEX_LOCK (&cn_mutex);
2110 n = slist_length (cn_thread_list);
2111 MUTEX_UNLOCK (&cn_mutex);
2113 if (n && !segv)
2115 pthread_t tid;
2117 rc = create_thread (waiting_for_exit, NULL, &tid, 0);
2118 if (!rc)
2120 if (signal_loop (sigset))
2122 log_write (_("Received second termination request. Exiting."));
2123 #ifdef HAVE_PTHREAD_CANCEL
2124 pthread_cancel (tid);
2125 #else
2126 pthread_kill (tid, SIGUSR2);
2127 #endif
2128 pthread_join (tid, NULL);
2131 else
2132 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2133 pwmd_strerror (rc));
2136 if (cancel_timeout_thread)
2138 #ifdef HAVE_PTHREAD_CANCEL
2139 pthread_cancel (cache_timeout_tid);
2140 #else
2141 pthread_kill (cache_timeout_tid, SIGUSR2);
2142 #endif
2143 pthread_join (cache_timeout_tid, NULL);
2146 if (cancel_keepalive_thread)
2148 #ifdef HAVE_PTHREAD_CANCEL
2149 pthread_cancel (keepalive_tid);
2150 #else
2151 pthread_kill (keepalive_tid, SIGUSR2);
2152 #endif
2153 pthread_join (keepalive_tid, NULL);
2156 cleanup_all_clients (0);
2157 #ifdef WITH_GNUTLS
2158 start_stop_tls (1);
2159 #endif
2160 deinit_commands ();
2161 pthread_cond_destroy (&quit_cond);
2162 pthread_mutex_destroy (&quit_mutex);
2163 return segv ? EXIT_FAILURE : EXIT_SUCCESS;;
2166 static void
2167 startup_failure ()
2169 log_write (_
2170 ("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
2171 cache_clear (NULL);
2174 /* This is called from cache.c:clear_once(). See
2175 * command.c:clearcache_command() for details about lock checking.
2177 static gpg_error_t
2178 free_cache_data (file_cache_t * cache)
2180 gpg_error_t rc = GPG_ERR_NO_DATA;
2181 int i, t;
2182 struct client_thread_s *found = NULL;
2183 int self = 0;
2185 if (!cache->data)
2186 return 0;
2188 cache_lock ();
2189 MUTEX_LOCK (&cn_mutex);
2190 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
2191 t = slist_length (cn_thread_list);
2193 for (i = 0; i < t; i++)
2195 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2197 if (!thd->cl)
2198 continue;
2200 if (!memcmp (thd->cl->md5file, cache->filename,
2201 sizeof (cache->filename)))
2203 if (pthread_equal (pthread_self (), thd->tid))
2205 found = thd;
2206 self = 1;
2207 continue;
2210 /* Continue trying to find a client who has the same file open and
2211 * also has a lock. */
2212 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0, -1);
2213 if (!rc)
2215 self = 0;
2216 found = thd;
2217 break;
2222 if (self && (!rc || rc == GPG_ERR_NO_DATA))
2223 rc = cache_lock_mutex (found->cl->ctx, found->cl->md5file, -1, 0, -1);
2225 if (exiting || !rc || rc == GPG_ERR_NO_DATA)
2227 free_cache_data_once (cache->data);
2228 cache->data = NULL;
2229 cache->defer_clear = 0;
2230 cache->timeout = -1;
2232 if (found)
2233 cache_unlock_mutex (found->cl->md5file, 0);
2235 rc = 0;
2238 if (rc)
2239 cache->defer_clear = 1;
2241 pthread_cleanup_pop (1);
2242 cache_unlock ();
2243 return rc;
2246 static int
2247 convert_v2_datafile (const char *filename, const char *cipher,
2248 const char *keyfile, const char *keygrip,
2249 const char *sign_keygrip, int nopass,
2250 const char *outfile, const char *keyparam,
2251 unsigned long s2k_count, uint64_t iterations)
2253 gpg_error_t rc;
2254 void *data = NULL;
2255 size_t datalen;
2256 struct crypto_s *crypto = NULL;
2257 uint16_t ver;
2258 int algo;
2259 void *key = NULL;
2260 size_t keylen = 0;
2262 if (outfile[0] == '-' && outfile[1] == 0)
2263 outfile = NULL;
2265 log_write (_("Converting version 2 data file \"%s\" ..."), filename);
2266 if (access (filename, R_OK) == -1)
2268 log_write ("%s: %s", filename,
2269 pwmd_strerror (gpg_error_from_errno (errno)));
2270 return 0;
2273 if (keyfile)
2275 log_write (_("Using passphrase file \"%s\" for decryption ..."),
2276 keyfile);
2277 if (access (keyfile, R_OK) == -1)
2279 log_write ("%s: %s", keyfile,
2280 pwmd_strerror (gpg_error_from_errno (errno)));
2281 return 0;
2285 rc = read_v2_datafile (filename, keyfile, &data, &datalen, &ver, &algo);
2286 if (rc)
2288 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2289 return 0;
2292 if (cipher)
2294 algo = cipher_string_to_gcrypt (cipher);
2295 if (algo == -1)
2297 rc = GPG_ERR_CIPHER_ALGO;
2298 goto fail;
2302 if (ver < 0x212)
2304 xmlDocPtr doc;
2306 rc = parse_doc (data, datalen, &doc);
2307 if (rc)
2308 goto fail;
2310 rc = convert_pre_212_elements (doc);
2311 gcry_free (data);
2312 data = NULL;
2313 if (!rc)
2315 xmlDocDumpFormatMemory (doc, (xmlChar **) & data, (int *) &datalen,
2317 if (!data)
2318 rc = GPG_ERR_ENOMEM;
2321 xmlFreeDoc (doc);
2322 if (rc)
2323 goto fail;
2326 rc = init_client_crypto (&crypto);
2327 if (!rc)
2329 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
2330 crypto->save.hdr.flags = set_cipher_flag (crypto->save.hdr.flags, algo);
2331 crypto->save.s2k_count = s2k_count;
2332 crypto->save.hdr.iterations = iterations;
2334 if (!use_agent)
2336 rc = export_common (NULL, 0, crypto, data, datalen, outfile, keyfile,
2337 &key, &keylen, 0, 0, nopass);
2339 #ifdef WITH_AGENT
2340 else
2342 rc = agent_set_pinentry_options (crypto->agent);
2343 if (!rc)
2344 rc = agent_export_common (crypto, keygrip, sign_keygrip, nopass,
2345 data, datalen, outfile, keyparam,
2346 no_passphrase_file ? NULL : keyfile);
2348 #endif
2349 if (!rc)
2350 log_write (_("Output written to \"%s\"."), outfile);
2353 fail:
2354 if (ver < 0x212)
2355 xmlFree (data);
2356 else
2357 gcry_free (data);
2359 gcry_free (key);
2360 cleanup_crypto (&crypto);
2362 if (rc)
2363 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2364 return rc ? 0 : 1;
2367 static void
2368 usage (const char *pn, int status)
2370 FILE *fp = status == EXIT_FAILURE ? stderr : stdout;
2372 fprintf (fp, _("Usage: %s [OPTIONS] [file1] [...]\n"
2373 " -f, --rcfile=filename load the specfied configuration file\n"
2374 " (~/.pwmd/config)\n"
2375 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2376 #ifdef WITH_AGENT
2377 " --use-agent enable use of gpg-agent\n"
2378 #endif
2379 " -n, --no-fork run as a foreground process\n"
2380 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2381 " --ignore, --force ignore file errors during startup\n"
2382 " --debug-level=keywords log protocol output (see manual for details)\n"
2383 " -o, --outfile=filename output file when importing or converting\n"
2384 " -C, --convert=filename convert a version 2 data file to version 3\n"
2385 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2386 " -k, --passphrase-file=file for use when importing or converting\n"
2387 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2388 " converting\n"
2389 " --no-passphrase when importing or converting\n"
2390 " --keygrip=hex public key to use when encrypting\n"
2391 " --sign-keygrip=hex private key to use when signing\n"
2392 " --keyparam=s-exp custom key parameters to use (RSA-2048)\n"
2393 " --cipher=string encryption cipher (aes256)\n"
2394 " --iterations=N cipher iteration count (N+1)\n"
2395 " --s2k-count=N hash iteration count (>65536, calibrated)\n"
2396 " --help this help text\n"
2397 " --version show version and compile time features\n"),
2398 pn);
2399 exit (status);
2402 static void
2403 unlink_stale_socket (const char *sock, const char *pidfile)
2405 log_write (_ ("removing stale socket %s"), sock);
2406 unlink (sock);
2407 unlink (pidfile);
2410 static int
2411 test_pidfile (const char *path, const char *sock, char *buf, size_t buflen,
2412 char **pidfile, int create, mode_t mode)
2414 pid_t pid;
2415 int fd;
2416 size_t len;
2418 if (!create)
2420 snprintf (buf, buflen, "%s/%s.pid", homedir, sock);
2421 *pidfile = str_dup (buf);
2422 fd = open (buf, O_RDONLY);
2424 else
2425 fd = open (*pidfile, O_CREAT|O_WRONLY|O_TRUNC, mode);
2427 if (fd == -1)
2429 if (!create && errno != ENOENT)
2431 log_write ("%s: %s", buf, pwmd_strerror (errno));
2432 free (*pidfile);
2433 *pidfile = NULL;
2434 return -1;
2436 else if (!create)
2437 return 0;
2439 log_write ("%s: %s", *pidfile, strerror (errno));
2440 return -1;
2443 if (create)
2445 snprintf (buf, buflen, "%i", getpid ());
2446 write (fd, buf, strlen (buf));
2447 close (fd);
2448 return 0;
2451 len = read (fd, buf, sizeof(buf));
2452 close (fd);
2453 if (len == 0)
2455 unlink_stale_socket (path, *pidfile);
2456 return 0;
2459 if (sscanf (buf, "%5i", &pid) != 1 || pid == 0)
2461 unlink_stale_socket (path, *pidfile);
2462 return 0;
2465 if (kill (pid, 0) == -1)
2467 unlink_stale_socket (path, *pidfile);
2468 return 0;
2471 log_write (_ ("an instance for socket %s is already running"), path);
2472 xfree (*pidfile);
2473 *pidfile = NULL;
2474 return 1;
2478 main (int argc, char *argv[])
2480 int opt;
2481 struct sockaddr_un addr;
2482 char buf[PATH_MAX];
2483 char *socketpath = NULL, *socketdir, *socketname = NULL;
2484 char *socketarg = NULL;
2485 char *datadir = NULL;
2486 char *pidfile = NULL;
2487 mode_t mode = 0600;
2488 int x;
2489 char *p;
2490 char **cache_push = NULL;
2491 char *import = NULL, *keygrip = NULL, *sign_keygrip = NULL;
2492 char *keyparam = NULL;
2493 int estatus = EXIT_FAILURE;
2494 int sockfd;
2495 char *outfile = NULL;
2496 int do_unlink = 0;
2497 int secure = 0;
2498 int show_version = 0;
2499 int force = 0;
2500 int no_passphrase = 0;
2501 gpg_error_t rc;
2502 char *convertfile = NULL;
2503 char *cipher = NULL;
2504 char *keyfile = NULL;
2505 unsigned long s2k_count = 0;
2506 uint64_t iterations = 0;
2507 int exists;
2508 char *debug_level_opt = NULL;
2509 int optindex;
2510 /* Must maintain the same order as longopts[] */
2511 enum
2513 OPT_VERSION, OPT_HELP,
2514 #ifdef WITH_AGENT
2515 OPT_AGENT,
2516 #endif
2517 OPT_DEBUG_LEVEL, OPT_HOMEDIR, OPT_NO_FORK, OPT_DISABLE_DUMP,
2518 OPT_IGNORE, OPT_FORCE, OPT_RCFILE, OPT_CONVERT,
2519 OPT_PASSPHRASE_FILE, OPT_IMPORT, OPT_OUTFILE,
2520 OPT_NO_PASSPHRASE_FILE, OPT_KEYGRIP, OPT_SIGN_KEYGRIP,
2521 OPT_KEYPARAM, OPT_CIPHER, OPT_ITERATIONS, OPT_S2K_COUNT,
2522 OPT_NO_PASSPHRASE
2524 const char *optstring = "nf:C:k:I:o:";
2525 const struct option longopts[] = {
2526 {"version", no_argument, 0, 0},
2527 {"help", no_argument, 0, 0},
2528 #ifdef WITH_AGENT
2529 {"use-agent", no_argument, 0, 0},
2530 #endif
2531 {"debug-level", required_argument, 0, 0},
2532 {"homedir", required_argument, 0, 0},
2533 {"no-fork", no_argument, 0, 'n'},
2534 {"disable_dump", no_argument, 0, 0},
2535 {"ignore", no_argument, 0, 0},
2536 {"force", no_argument, 0, 0},
2537 {"rcfile", required_argument, 0, 'f'},
2538 {"convert", required_argument, 0, 'C'},
2539 {"passphrase-file", required_argument, 0, 'k'},
2540 {"import", required_argument, 0, 'I'},
2541 {"outfile", required_argument, 0, 'o'},
2542 {"no-passphrase-file", no_argument, 0, 0},
2543 {"keygrip", required_argument, 0, 0},
2544 {"sign-keygrip", required_argument, 0, 0},
2545 {"keyparam", required_argument, 0, 0},
2546 {"cipher", required_argument, 0, 0},
2547 {"cipher-iterations", required_argument, 0, 0},
2548 {"s2k-count", required_argument, 0, 0},
2549 {"no-passphrase", no_argument, 0, 0},
2550 {0, 0, 0, 0}
2553 log_fd = -1;
2555 #ifndef DEBUG
2556 #ifdef HAVE_SETRLIMIT
2557 struct rlimit rl;
2559 rl.rlim_cur = rl.rlim_max = 0;
2561 if (setrlimit (RLIMIT_CORE, &rl) != 0)
2562 err (EXIT_FAILURE, "setrlimit()");
2563 #endif
2564 #endif
2566 #ifdef ENABLE_NLS
2567 setlocale (LC_ALL, "");
2568 bindtextdomain ("pwmd", LOCALEDIR);
2569 textdomain ("pwmd");
2570 #endif
2572 #ifndef MEM_DEBUG
2573 xmem_init ();
2574 #endif
2575 gpg_err_init ();
2577 if (setup_crypto ())
2578 exit (EXIT_FAILURE);
2580 #ifdef WITH_GNUTLS
2581 gnutls_global_set_mem_functions (xmalloc, xmalloc, secure_mem_check,
2582 xrealloc, xfree);
2583 gnutls_global_init ();
2584 gnutls_global_set_log_function (tls_log);
2585 gnutls_global_set_log_level (1);
2586 tls_fd = -1;
2587 tls6_fd = -1;
2588 #endif
2589 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
2590 xmlInitMemory ();
2591 xmlInitGlobals ();
2592 xmlInitParser ();
2593 xmlXPathInit ();
2594 cmdline = 1;
2595 use_agent = 0;
2597 while ((opt = getopt_long (argc, argv, optstring, longopts, &optindex))
2598 != -1)
2600 switch (opt)
2602 case 'I':
2603 import = optarg;
2604 break;
2605 case 'C':
2606 convertfile = optarg;
2607 break;
2608 case 'k':
2609 keyfile = optarg;
2610 break;
2611 case 'o':
2612 outfile = optarg;
2613 break;
2614 case 'D':
2615 secure = 1;
2616 break;
2617 case 'n':
2618 nofork = 1;
2619 break;
2620 case 'f':
2621 rcfile = str_dup (optarg);
2622 break;
2623 default:
2624 usage (argv[0], EXIT_FAILURE);
2625 break;
2626 case 0:
2627 switch (optindex)
2629 case OPT_VERSION:
2630 show_version = 1;
2631 break;
2632 case OPT_HELP:
2633 usage (argv[0], 0);
2634 break;
2635 #ifdef WITH_AGENT
2636 case OPT_AGENT:
2637 use_agent = 1;
2638 break;
2639 #endif
2640 case OPT_DEBUG_LEVEL:
2641 debug_level_opt = optarg;
2642 break;
2643 case OPT_HOMEDIR:
2644 homedir = str_dup (optarg);
2645 break;
2646 case OPT_NO_FORK:
2647 nofork = 1;
2648 break;
2649 case OPT_DISABLE_DUMP:
2650 secure = 1;
2651 break;
2652 case OPT_IGNORE:
2653 case OPT_FORCE:
2654 force = 1;
2655 break;
2656 case OPT_RCFILE:
2657 rcfile = str_dup (optarg);
2658 break;
2659 case OPT_CONVERT:
2660 convertfile = optarg;
2661 break;
2662 case OPT_PASSPHRASE_FILE:
2663 keyfile = optarg;
2664 break;
2665 case OPT_IMPORT:
2666 import = optarg;
2667 break;
2668 case OPT_OUTFILE:
2669 outfile = optarg;
2670 break;
2671 case OPT_NO_PASSPHRASE_FILE:
2672 no_passphrase_file = 1;
2673 break;
2674 case OPT_KEYGRIP:
2675 keygrip = optarg;
2676 break;
2677 case OPT_SIGN_KEYGRIP:
2678 sign_keygrip = optarg;
2679 break;
2680 case OPT_KEYPARAM:
2681 keyparam = optarg;
2682 break;
2683 case OPT_CIPHER:
2684 cipher = optarg;
2685 break;
2686 case OPT_ITERATIONS:
2687 iterations = strtoull (optarg, NULL, 10);
2688 break;
2689 case OPT_S2K_COUNT:
2690 s2k_count = strtoul (optarg, NULL, 10);
2691 break;
2692 case OPT_NO_PASSPHRASE:
2693 no_passphrase = 1;
2694 break;
2695 default:
2696 usage (argv[0], 1);
2701 if (show_version)
2703 printf (_("%s\n\n"
2704 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014\n"
2705 "%s\n"
2706 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2707 "Compile time features:\n%s"), PACKAGE_STRING,
2708 PACKAGE_BUGREPORT,
2709 #ifdef PWMD_HOMEDIR
2710 "+PWMD_HOMEDIR=" PWMD_HOMEDIR "\n"
2711 #endif
2712 #ifdef WITH_AGENT
2713 "+WITH_AGENT\n"
2714 #else
2715 "-WITH_AGENT\n"
2716 #endif
2717 #ifdef WITH_QUALITY
2718 "+WITH_QUALITY\n"
2719 #else
2720 "-WITH_QUALITY\n"
2721 #endif
2722 #ifdef WITH_GNUTLS
2723 "+WITH_GNUTLS\n"
2724 #else
2725 "-WITH_GNUTLS\n"
2726 #endif
2727 #ifdef WITH_LIBACL
2728 "+WITH_LIBACL\n"
2729 #else
2730 "-WITH_LIBACL\n"
2731 #endif
2732 #ifdef DEBUG
2733 "+DEBUG\n"
2734 #else
2735 "-DEBUG\n"
2736 #endif
2737 #ifdef MEM_DEBUG
2738 "+MEM_DEBUG\n"
2739 #else
2740 "-MEM_DEBUG\n"
2741 #endif
2742 #ifdef MUTEX_DEBUG
2743 "+MUTEX_DEBUG\n"
2744 #else
2745 "-MUTEX_DEBUG\n"
2746 #endif
2748 exit (EXIT_SUCCESS);
2751 if (!homedir)
2752 #ifdef PWMD_HOMEDIR
2753 homedir = str_dup(PWMD_HOMEDIR);
2754 #else
2755 homedir = str_asprintf ("%s/.pwmd", get_home_dir ());
2756 #endif
2758 if (mkdir (homedir, 0700) == -1 && errno != EEXIST)
2759 err (EXIT_FAILURE, "%s", homedir);
2761 snprintf (buf, sizeof (buf), "%s/data", homedir);
2762 if (mkdir (buf, 0700) == -1 && errno != EEXIST)
2763 err (EXIT_FAILURE, "%s", buf);
2765 datadir = str_dup (buf);
2766 pthread_mutexattr_t attr;
2767 pthread_mutexattr_init (&attr);
2768 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
2769 pthread_mutex_init (&rcfile_mutex, &attr);
2770 pthread_cond_init (&rcfile_cond, NULL);
2771 pthread_mutex_init (&cn_mutex, &attr);
2772 pthread_mutexattr_destroy (&attr);
2773 pthread_key_create (&last_error_key, free_key);
2774 #ifndef HAVE_PTHREAD_CANCEL
2775 pthread_key_create (&signal_thread_key, free_key);
2776 #endif
2778 if (!rcfile)
2779 rcfile = str_asprintf ("%s/config", homedir);
2781 global_config = config_parse (rcfile);
2782 if (!global_config)
2783 exit (EXIT_FAILURE);
2785 #ifdef WITH_AGENT
2786 if (!use_agent)
2787 use_agent = config_get_boolean ("global", "use_agent");
2788 #endif
2790 setup_logging ();
2792 if (debug_level_opt)
2793 debug_level = str_split (debug_level_opt, ",", 0);
2795 x = config_get_int_param (global_config, "global", "priority", &exists);
2796 if (exists && x != atoi(INVALID_PRIORITY))
2798 errno = 0;
2799 if (setpriority (PRIO_PROCESS, 0, x) == -1)
2801 log_write ("setpriority(): %s",
2802 pwmd_strerror (gpg_error_from_errno (errno)));
2803 goto do_exit;
2806 #ifdef HAVE_MLOCKALL
2807 if (disable_mlock == 0 && mlockall (MCL_CURRENT | MCL_FUTURE) == -1)
2809 log_write ("mlockall(): %s",
2810 pwmd_strerror (gpg_error_from_errno (errno)));
2811 goto do_exit;
2813 #endif
2815 rc = cache_init (free_cache_data);
2816 if (rc)
2818 log_write ("pwmd: ERR %i: %s", rc,
2819 gpg_err_code (rc) == GPG_ERR_UNKNOWN_VERSION
2820 ? _("incompatible gpg-agent version: 2.1.0 or later required")
2821 : pwmd_strerror (rc));
2822 goto do_exit;
2825 if (s2k_count == 0)
2826 s2k_count = config_get_ulong (NULL, "s2k_count");
2828 if (convertfile)
2830 if (!outfile || !*outfile || argc != optind)
2831 usage (argv[0], EXIT_FAILURE);
2833 estatus = convert_v2_datafile (convertfile, cipher, keyfile, keygrip,
2834 sign_keygrip, no_passphrase, outfile,
2835 keyparam, s2k_count, iterations);
2836 config_free (global_config);
2837 xfree (rcfile);
2838 exit (!estatus);
2841 if (import)
2843 if (!outfile || !*outfile || argc != optind)
2844 usage (argv[0], EXIT_FAILURE);
2846 if (outfile && outfile[0] == '-' && outfile[1] == 0)
2847 outfile = NULL;
2849 estatus = xml_import (import, outfile, keygrip, sign_keygrip, keyfile,
2850 no_passphrase, cipher, keyparam, s2k_count,
2851 iterations);
2852 config_free (global_config);
2853 xfree (rcfile);
2854 exit (!estatus);
2857 p = config_get_string ("global", "socket_path");
2858 if (!p)
2859 p = str_asprintf ("%s/socket", homedir);
2861 socketarg = expand_homedir (p);
2862 xfree (p);
2864 if (!secure)
2865 disable_list_and_dump = config_get_boolean ("global",
2866 "disable_list_and_dump");
2867 else
2868 disable_list_and_dump = secure;
2870 cache_push = config_get_list ("global", "cache_push");
2872 while (optind < argc)
2874 if (strv_printf (&cache_push, "%s", argv[optind++]) == 0)
2875 errx (EXIT_FAILURE, "%s", pwmd_strerror (GPG_ERR_ENOMEM));
2878 if (strchr (socketarg, '/') == NULL)
2880 socketdir = getcwd (buf, sizeof (buf));
2881 socketname = str_dup (socketarg);
2882 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2884 else
2886 socketname = str_dup (strrchr (socketarg, '/'));
2887 socketname++;
2888 socketarg[strlen (socketarg) - strlen (socketname) - 1] = 0;
2889 socketdir = str_dup (socketarg);
2890 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
2893 if (chdir (datadir))
2895 log_write ("%s: %s", datadir,
2896 pwmd_strerror (gpg_error_from_errno (errno)));
2897 unlink (socketpath);
2898 goto do_exit;
2901 if (test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 0,
2902 mode))
2903 goto do_exit;
2906 * bind() doesn't like the full pathname of the socket or any non alphanum
2907 * characters so change to the directory where the socket is wanted then
2908 * create it then change to datadir.
2910 if (chdir (socketdir))
2912 log_write ("%s: %s", socketdir,
2913 pwmd_strerror (gpg_error_from_errno (errno)));
2914 goto do_exit;
2917 xfree (socketdir);
2919 if ((sockfd = socket (PF_UNIX, SOCK_STREAM, 0)) == -1)
2921 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2922 goto do_exit;
2925 addr.sun_family = AF_UNIX;
2926 snprintf (addr.sun_path, sizeof (addr.sun_path), "%s", socketname);
2927 do_unlink = 1;
2928 if (bind (sockfd, (struct sockaddr *) &addr, sizeof (struct sockaddr)) ==
2931 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
2933 if (errno == EADDRINUSE)
2935 do_unlink = 0;
2936 log_write (_("Either there is another pwmd running or '%s' is a \n"
2937 "stale socket. Please remove it manually."), socketpath);
2940 goto do_exit;
2944 char *t = config_get_string ("global", "socket_perms");
2945 mode_t mask;
2947 if (t)
2949 mode = strtol (t, NULL, 8);
2950 mask = umask (0);
2951 xfree (t);
2953 if (chmod (socketname, mode) == -1)
2955 log_write ("%s: %s", socketname,
2956 pwmd_strerror (gpg_error_from_errno (errno)));
2957 close (sockfd);
2958 umask (mask);
2959 goto do_exit;
2962 umask (mask);
2966 xfree (--socketname);
2968 if (chdir (datadir))
2970 log_write ("%s: %s", datadir,
2971 pwmd_strerror (gpg_error_from_errno (errno)));
2972 close (sockfd);
2973 goto do_exit;
2976 xfree (datadir);
2979 * Set the cache entry for a file. Prompts for the password.
2981 if (cache_push)
2983 struct crypto_s *crypto = NULL;
2984 gpg_error_t rc = init_client_crypto (&crypto);
2986 if (rc)
2988 estatus = EXIT_FAILURE;
2989 goto do_exit;
2992 #ifdef WITH_AGENT
2993 if (use_agent)
2995 rc = agent_set_pinentry_options (crypto->agent);
2996 if (rc)
2998 estatus = EXIT_FAILURE;
2999 goto do_exit;
3002 #endif
3004 for (opt = 0; cache_push[opt]; opt++)
3006 if (!do_cache_push (cache_push[opt], crypto) && !force)
3008 strv_free (cache_push);
3009 startup_failure ();
3010 estatus = EXIT_FAILURE;
3011 cleanup_crypto (&crypto);
3012 goto do_exit;
3015 cleanup_crypto_stage1 (crypto);
3018 #ifdef WITH_AGENT
3019 if (use_agent)
3020 (void) kill_scd (crypto->agent);
3021 #endif
3023 cleanup_crypto (&crypto);
3024 strv_free (cache_push);
3025 log_write (!nofork ? _("Done. Daemonizing...") :
3026 _("Done. Waiting for connections..."));
3029 config_clear_keys ();
3031 if (listen (sockfd, 0) == -1)
3033 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
3034 goto do_exit;
3037 if (!nofork)
3039 switch (fork ())
3041 case -1:
3042 log_write ("fork(): %s",
3043 pwmd_strerror (gpg_error_from_errno (errno)));
3044 goto do_exit;
3045 case 0:
3046 close (0);
3047 close (1);
3048 close (2);
3049 setsid ();
3050 break;
3051 default:
3052 _exit (EXIT_SUCCESS);
3056 (void)test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 1,
3057 mode);
3058 cmdline = 0;
3059 pthread_key_create (&thread_name_key, free_key);
3060 pthread_setspecific (thread_name_key, str_dup ("main"));
3061 estatus = server_loop (sockfd, &socketpath);
3063 do_exit:
3064 if (socketpath && do_unlink)
3066 unlink (socketpath);
3067 xfree (socketpath);
3070 xfree (socketarg);
3071 #ifdef WITH_GNUTLS
3072 gnutls_global_deinit ();
3073 #endif
3074 if (rcfile_tid)
3076 #ifdef HAVE_PTHREAD_CANCEL
3077 pthread_cancel (rcfile_tid);
3078 #else
3079 pthread_kill (rcfile_tid, SIGUSR2);
3080 pthread_cond_signal (&rcfile_cond);
3081 #endif
3082 pthread_join (rcfile_tid, NULL);
3085 pthread_cond_destroy (&rcfile_cond);
3086 pthread_mutex_destroy (&rcfile_mutex);
3087 pthread_key_delete (last_error_key);
3088 #ifndef HAVE_PTHREAD_CANCEL
3089 pthread_key_delete (signal_thread_key);
3090 #endif
3092 if (global_config)
3093 config_free (global_config);
3095 xfree (rcfile);
3096 xfree (home_directory);
3097 xfree (homedir);
3098 xmlCleanupParser ();
3099 xmlCleanupGlobals ();
3101 if (pidfile)
3102 unlink (pidfile);
3103 xfree (pidfile);
3105 if (estatus == EXIT_SUCCESS)
3106 log_write (_("pwmd exiting normally"));
3108 pthread_key_delete (thread_name_key);
3109 closelog ();
3110 #if defined(DEBUG) && !defined(MEM_DEBUG)
3111 xdump ();
3112 #endif
3114 if (log_fd != -1)
3115 close (log_fd);
3117 exit (estatus);