Fix Coverity issue #100347.
[libpwmd.git] / src / pwmd.c
blobe8db833846ab71b08409e1356d66e1186d3b6173
1 /*
2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015
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 = NULL;
215 if (p)
216 logfile = expand_homedir (p);
217 xfree (p);
219 else
221 xfree (logfile);
222 logfile = NULL;
223 if (log_fd != -1)
224 close(log_fd);
226 log_fd = -1;
229 log_syslog = config_get_boolean ("global", "syslog");
230 if (log_syslog == 1)
231 openlog ("pwmd", LOG_NDELAY | LOG_PID, LOG_DAEMON);
234 static void *
235 reload_rcfile_thread (void *arg)
237 #ifndef HAVE_PTHREAD_CANCEL
238 int *n = xmalloc (sizeof (int));
240 *n = 0;
241 pthread_setspecific (signal_thread_key, n);
242 INIT_THREAD_SIGNAL;
243 #endif
245 #ifdef HAVE_PR_SET_NAME
246 prctl (PR_SET_NAME, "reload rcfile");
247 #endif
248 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
249 MUTEX_LOCK (&rcfile_mutex);
250 pthread_cleanup_push (cleanup_mutex_cb, &rcfile_mutex);
252 for (;;)
254 struct allowed_users_s
256 char *section;
257 char **users;
259 struct slist_s *allowed_users = NULL;
260 struct slist_s *config;
261 int b = disable_list_and_dump;
262 uid_t invoking_uid_orig = invoking_uid;
263 gid_t invoking_gid_orig = invoking_gid;
264 char *invoking_tls_orig;
265 int exists;
266 int require_save_key = config_get_bool_param (global_config, "global",
267 "require_save_key",
268 &exists);
269 #ifdef WITH_GNUTLS
270 int tcp_require_key = config_get_bool_param (global_config, "global",
271 "tcp_require_key",
272 &exists);
273 #endif
275 pthread_cond_wait (&rcfile_cond, &rcfile_mutex);
276 #ifndef HAVE_PTHREAD_CANCEL
277 int *cancel = (int *) pthread_getspecific (signal_thread_key);
278 if (*cancel)
279 break;
280 #endif
282 /* Keep the "allowed" parameter across rcfile reloads to prevent
283 tampering. */
284 int n, t = slist_length (global_config);
285 for (n = 0; n < t; n++)
287 struct config_section_s *section;
288 char **users;
290 section = slist_nth_data (global_config, n);
291 users = config_get_list_param (global_config, section->name,
292 "allowed", &exists);
293 if (users)
295 struct allowed_users_s *allowed;
297 allowed = xmalloc (sizeof(struct allowed_users_s));
298 allowed->section = str_dup (section->name);
299 allowed->users = users;
300 allowed_users = slist_append (allowed_users, allowed);
304 invoking_tls_orig = invoking_tls ? str_dup (invoking_tls) : NULL;
305 xfree (invoking_tls);
306 invoking_tls = NULL;
307 log_write (_("reloading configuration file '%s'"), rcfile);
309 config = config_parse (rcfile);
310 if (config)
312 config_free (global_config);
313 global_config = config;
314 setup_logging ();
315 cache_push_from_rcfile ();
316 config_clear_keys ();
319 xfree (invoking_tls);
320 invoking_tls = invoking_tls_orig;
321 invoking_uid = invoking_uid_orig;
322 invoking_gid = invoking_gid_orig;
323 disable_list_and_dump = !disable_list_and_dump ? b : 1;
324 config_set_bool_param (&global_config, "global", "require_save_key",
325 require_save_key ? "true" : "false");
326 #ifdef WITH_GNUTLS
327 if (config_get_bool_param (global_config, "global", "tcp_require_key",
328 &exists) && exists)
329 tcp_require_key = 1;
331 config_set_bool_param (&global_config, "global", "tcp_require_key",
332 tcp_require_key ? "true" : "false");
333 #endif
335 if (allowed_users)
337 int n, t = slist_length (allowed_users);
339 for (n = 0; n < t; n++)
341 struct allowed_users_s *allowed;
342 char *tmp;
344 allowed = slist_nth_data (allowed_users, n);
345 tmp = strv_join (",", allowed->users);
346 config_set_list_param (&global_config, allowed->section,
347 "allowed", tmp);
348 xfree (tmp);
349 xfree (allowed->section);
350 strv_free (allowed->users);
351 xfree (allowed);
354 slist_free (allowed_users);
357 #ifdef WITH_GNUTLS
358 /* Kill existing listening threads since the configured listening
359 * protocols may have changed. */
360 start_stop_tls (1);
361 start_stop_tls (0);
362 #endif
365 pthread_cleanup_pop (1);
366 return NULL;
369 gpg_error_t
370 send_error (assuan_context_t ctx, gpg_error_t e)
372 struct client_s *client = assuan_get_pointer (ctx);
374 if (gpg_err_source (e) == GPG_ERR_SOURCE_UNKNOWN)
375 e = gpg_error (e);
377 if (client)
378 client->last_rc = e;
380 if (!e)
381 return assuan_process_done (ctx, 0);
383 if (!ctx)
385 log_write ("ERR %i: %s", e, pwmd_strerror (e));
386 return e;
389 if (client && client->xml_error)
391 log_write ("%s", client->xml_error->message);
392 xfree (client->last_error);
393 client->last_error = NULL;
394 if (client->xml_error->message)
395 client->last_error = str_dup (client->xml_error->message);
397 e = assuan_process_done (ctx,
398 assuan_set_error (ctx, e,
399 client->xml_error->message ? client->xml_error->message : NULL));
400 xmlResetLastError ();
401 xmlResetError (client->xml_error);
402 xfree (client->xml_error);
403 client->xml_error = NULL;
404 return e;
407 return assuan_process_done (ctx,
408 assuan_set_error (ctx, e, pwmd_strerror (e)));
412 assuan_log_cb (assuan_context_t ctx, void *data, unsigned cat,
413 const char *msg)
415 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
416 int i, t;
417 int match = 0;
419 pthread_mutex_lock (&m);
420 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock, &m);
421 t = strv_length (debug_level);
423 for (i = 0; i < t; i++)
425 if (!strcasecmp (debug_level[i], (char *) "init")
426 && cat == ASSUAN_LOG_INIT)
428 match = 1;
429 break;
432 if (!strcasecmp (debug_level[i], (char *) "ctx")
433 && cat == ASSUAN_LOG_CTX)
435 match = 1;
436 break;
439 if (!strcasecmp (debug_level[i], (char *) "engine")
440 && cat == ASSUAN_LOG_ENGINE)
442 match = 1;
443 break;
446 if (!strcasecmp (debug_level[i], (char *) "data")
447 && cat == ASSUAN_LOG_DATA)
449 match = 1;
450 break;
453 if (!strcasecmp (debug_level[i], (char *) "sysio")
454 && cat == ASSUAN_LOG_SYSIO)
456 match = 1;
457 break;
460 if (!strcasecmp (debug_level[i], (char *) "control")
461 && cat == ASSUAN_LOG_CONTROL)
463 match = 1;
464 break;
468 if (match && msg)
470 if (logfile)
472 int fd;
474 if ((fd =
475 open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600)) == -1)
476 warn ("%s", logfile);
477 else
479 pthread_cleanup_push (cleanup_fd_cb, &fd);
480 write (fd, msg, strlen (msg));
481 pthread_cleanup_pop (1);
485 if (nofork)
487 fprintf (stderr, "%s%s", data ? (char *) data : "", msg);
488 fflush (stderr);
492 pthread_cleanup_pop (1);
493 return match;
496 void
497 log_write (const char *fmt, ...)
499 char *args;
500 va_list ap;
501 time_t now;
502 char buf[255];
503 pthread_t tid = pthread_self ();
504 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
506 if ((!logfile && !isatty (STDERR_FILENO) && !log_syslog) || !fmt)
507 return;
509 pthread_mutex_lock (&m);
510 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock, &m);
512 if (!cmdline && logfile && log_fd == -1)
514 log_fd = open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600);
515 if (log_fd == -1)
516 warn ("%s", logfile);
519 va_start (ap, fmt);
521 if (str_vasprintf (&args, fmt, ap) != -1)
523 if (cmdline)
525 pthread_cleanup_push (xfree, args);
526 fprintf (stderr, "pwmd: %s\n", args);
527 fflush (stderr);
528 pthread_cleanup_pop (1);
530 else
532 char *name = pthread_getspecific (thread_name_key);
533 char *line;
535 pthread_cleanup_push (xfree, args);
536 snprintf (buf, sizeof (buf), "%s(%p): ", name ? name : _("unknown"),
537 (pthread_t *) tid);
538 name = buf;
540 if (!cmdline && log_syslog && !nofork)
541 syslog (LOG_INFO, "%s%s", name, args);
543 time (&now);
544 struct tm *tm = localtime (&now);
545 char tbuf[21];
546 strftime (tbuf, sizeof (tbuf), "%b %d %Y %H:%M:%S ", tm);
547 tbuf[sizeof (tbuf) - 1] = 0;
549 if (args[strlen (args) - 1] == '\n')
550 args[strlen (args) - 1] = 0;
552 line = str_asprintf ("%s %i %s%s\n", tbuf, getpid (), name,
553 args);
554 pthread_cleanup_pop (1);
555 if (line)
557 pthread_cleanup_push (xfree, line);
558 if (logfile && log_fd != -1)
560 write (log_fd, line, strlen (line));
561 fsync (log_fd);
564 if (nofork)
566 fprintf (stdout, "%s", line);
567 fflush (stdout);
570 pthread_cleanup_pop (1);
575 va_end (ap);
576 pthread_cleanup_pop (0);
578 if (log_fd != -1 && config_get_boolean (NULL, "log_keepopen") <= 0)
580 close(log_fd);
581 log_fd = -1;
584 pthread_mutex_unlock (&m);
587 #ifdef WITH_GNUTLS
588 static int
589 secure_mem_check (const void *arg)
591 return 1;
593 #endif
595 static gpg_error_t
596 setup_crypto ()
598 gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
600 if (!gcry_check_version (GCRYPT_VERSION))
602 fprintf (stderr, _("gcry_check_version(): Incompatible libgcrypt. "
603 "Wanted %s, got %s.\n"), GCRYPT_VERSION,
604 gcry_check_version (NULL));
605 return GPG_ERR_UNKNOWN_VERSION;
608 gcry_set_allocation_handler (xmalloc, xmalloc, NULL, xrealloc, xfree);
609 return 0;
612 gpg_error_t
613 do_validate_peer (assuan_context_t ctx, const char *section,
614 assuan_peercred_t * peer)
616 char **users;
617 int allowed = 0;
618 gpg_error_t rc;
619 struct client_s *client = assuan_get_pointer (ctx);
621 if (!client)
622 return GPG_ERR_EACCES;
624 #ifdef WITH_GNUTLS
625 if (client->thd->remote)
626 return tls_validate_access (client, section);
627 #endif
629 rc = assuan_get_peercred (ctx, peer);
630 if (rc)
631 return rc;
633 users = config_get_list (section, "allowed");
634 if (users)
636 for (char **p = users; *p; p++)
638 rc = acl_check_common(client, *p, (*peer)->uid, (*peer)->gid,
639 &allowed);
642 strv_free (users);
645 return allowed ? 0 : rc ? rc : GPG_ERR_EACCES;
648 gpg_error_t
649 peer_is_invoker(struct client_s *client)
651 if (client->thd->state == CLIENT_STATE_UNKNOWN)
652 return GPG_ERR_EACCES;
654 #ifdef WITH_GNUTLS
655 if (client->thd->remote)
657 char *p = invoking_tls;
659 if (!p || !*p || *p++ != '#')
660 return GPG_ERR_EACCES;
662 if (!strcmp(client->thd->tls->fp, p))
663 return 0;
665 return GPG_ERR_EACCES;
667 #endif
669 if (client->thd->peer->uid == invoking_uid)
670 return 0;
672 return GPG_ERR_EACCES;
675 #ifdef HAVE_GETGRNAM_R
676 gpg_error_t
677 acl_check_common (struct client_s *client, const char *user, uid_t uid,
678 gid_t gid, int *allowed)
680 struct passwd pw, *result;
681 char *buf = NULL;
682 int not = 0;
683 int rw = 0;
684 int tls = 0;
686 if (!user || !*user)
687 return 0;
689 if (*user == '-' || *user == '!')
690 not = 1;
692 if (*user == '+') // not implemented yet
693 rw = 1;
695 if (*user == '#') // TLS fingerprint hash
696 tls = 1;
698 if (not || rw || tls)
699 user++;
701 if (tls)
703 #ifdef WITH_GNUTLS
704 if (client->thd->remote)
706 if (!strcasecmp (client->thd->tls->fp, user))
707 *allowed = !not;
710 return 0;
711 #else
712 return 0;
713 #endif
715 #ifdef WITH_GNUTLS
716 else if (client->thd->remote) // Remote client with no TLS in the ACL
717 return 0;
718 #endif
720 if (*user == '@') // all users in group
722 struct group gr, *gresult;
723 size_t len = sysconf (_SC_GETGR_R_SIZE_MAX);
725 if (len == -1)
726 len = 16384;
728 buf = xmalloc (len);
729 if (!buf)
730 return GPG_ERR_ENOMEM;
732 user++;
733 if (!getgrnam_r (user, &gr, buf, len, &gresult) && gresult)
735 if (gresult->gr_gid == gid)
737 xfree (buf);
738 *allowed = !not;
739 return 0;
742 len = sysconf (_SC_GETPW_R_SIZE_MAX);
743 if (len == -1)
744 len = 16384;
746 char *tbuf = xmalloc (len);
747 for (char **t = gresult->gr_mem; *t; t++)
749 if (!getpwnam_r (*t, &pw, tbuf, len, &result) && result)
751 if (result->pw_uid == uid)
753 *allowed = !not;
754 break;
759 return 0;
762 else
764 size_t len = sysconf (_SC_GETPW_R_SIZE_MAX);
766 if (len == -1)
767 len = 16384;
769 buf = xmalloc (len);
770 if (!buf)
771 return GPG_ERR_ENOMEM;
773 if (!getpwnam_r (user, &pw, buf, len, &result) && result)
775 if (result->pw_uid == uid)
776 *allowed = !not;
779 xfree (buf);
782 return 0;
784 #else
785 gpg_error_t
786 acl_check_common (struct client_s *client, const char *user, uid_t uid,
787 gid_t gid, int *allowed)
789 struct passwd *result;
790 int not = 0;
791 int rw = 0;
792 int tls = 0;
794 if (!user || !*user)
795 return 0;
797 if (*user == '-' || *user == '!')
798 not = 1;
800 if (*user == '+') // not implemented yet
801 rw = 1;
803 if (*user == '#') // TLS fingerprint hash
804 tls = 1;
806 if (not || rw || tls)
807 user++;
809 if (tls)
811 #ifdef WITH_GNUTLS
812 if (client->thd->remote)
814 if (!strcasecmp (client->thd->tls->fp, user))
815 *allowed = !not;
818 return 0;
819 #else
820 return 0;
821 #endif
824 if (*user == '@') // all users in group
826 struct group *gresult;
828 user++;
829 gresult = getgrnam (user);
830 if (gresult && gresult->gr_gid == gid)
832 *allowed = !not;
833 return 0;
836 for (char **t = gresult->gr_mem; *t; t++)
838 result = getpwnam (*t);
839 if (result && result->pw_uid == uid)
841 *allowed = !not;
842 break;
846 return 0;
848 else
850 result = getpwnam (user);
851 if (result && result->pw_uid == uid)
852 *allowed = !not;
855 return 0;
857 #endif
859 static gpg_error_t
860 validate_peer (struct client_s *cl)
862 gpg_error_t rc;
864 #ifdef WITH_GNUTLS
865 if (cl->thd->remote)
866 return tls_validate_access (cl, NULL);
867 #endif
869 MUTEX_LOCK (&cn_mutex);
870 rc = do_validate_peer (cl->ctx, "global", &cl->thd->peer);
871 MUTEX_UNLOCK (&cn_mutex);
872 if (!rc || gpg_err_code (rc) == GPG_ERR_EACCES)
873 log_write ("peer %s: uid=%i, gid=%i, pid=%i",
874 !rc ? _("accepted") : _("rejected"), cl->thd->peer->uid,
875 cl->thd->peer->gid, cl->thd->peer->pid);
876 else if (rc)
877 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
879 return rc;
882 static void
883 xml_error_cb (void *data, xmlErrorPtr e)
885 struct client_s *client = data;
888 * Keep the first reported error as the one to show in the error
889 * description. Reset in send_error().
891 if (client->xml_error)
892 return;
894 client->xml_error = xcalloc (1, sizeof(xmlError));
895 xmlCopyError (e, client->xml_error);
898 static pid_t
899 hook_waitpid (assuan_context_t ctx, pid_t pid, int action,
900 int *status, int options)
902 return waitpid (pid, status, options);
905 static ssize_t
906 hook_read (assuan_context_t ctx, assuan_fd_t fd, void *data, size_t len)
908 #ifdef WITH_GNUTLS
909 struct client_s *client = assuan_get_pointer (ctx);
911 if (client->thd->remote)
912 return tls_read_hook (ctx, (int) fd, data, len);
913 #endif
915 return read ((int) fd, data, len);
918 static ssize_t
919 hook_write (assuan_context_t ctx, assuan_fd_t fd,
920 const void *data, size_t len)
922 #ifdef WITH_GNUTLS
923 struct client_s *client = assuan_get_pointer (ctx);
925 if (client->thd->remote)
926 return tls_write_hook (ctx, (int) fd, data, len);
927 #endif
929 return write ((int) fd, data, len);
932 static int
933 new_connection (struct client_s *cl)
935 gpg_error_t rc;
936 static struct assuan_malloc_hooks mhooks = { xmalloc, xrealloc, xfree };
937 static struct assuan_system_hooks shooks = {
938 ASSUAN_SYSTEM_HOOKS_VERSION,
939 __assuan_usleep,
940 __assuan_pipe,
941 __assuan_close,
942 hook_read,
943 hook_write,
944 //FIXME
945 NULL, //recvmsg
946 NULL, //sendmsg both are used for FD passing
947 __assuan_spawn,
948 hook_waitpid,
949 __assuan_socketpair,
950 __assuan_socket,
951 __assuan_connect
954 #ifdef WITH_GNUTLS
955 if (cl->thd->remote)
957 char *prio = config_get_string ("global", "tls_cipher_suite");
959 cl->thd->timeout = config_get_integer ("global", "tls_timeout");
960 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
961 return 0;
963 cl->thd->tls = tls_init (cl->thd->fd, cl->thd->timeout, prio);
964 xfree (prio);
965 if (!cl->thd->tls)
966 return 0;
968 #endif
970 rc = assuan_new_ext (&cl->ctx, GPG_ERR_SOURCE_DEFAULT, &mhooks,
971 debug_level ? assuan_log_cb : NULL, NULL);
972 if (rc)
973 goto fail;
975 assuan_ctx_set_system_hooks (cl->ctx, &shooks);
976 rc = assuan_init_socket_server (cl->ctx, cl->thd->fd, 2);
977 if (rc)
978 goto fail;
980 assuan_set_pointer (cl->ctx, cl);
981 assuan_set_hello_line (cl->ctx, PACKAGE_STRING);
982 rc = register_commands (cl->ctx);
983 if (rc)
984 goto fail;
986 rc = assuan_accept (cl->ctx);
987 if (rc)
988 goto fail;
990 rc = validate_peer (cl);
991 /* May not be implemented on all platforms. */
992 if (rc && gpg_err_code (rc) != GPG_ERR_ASS_GENERAL)
993 goto fail;
995 MUTEX_LOCK (&cn_mutex);
996 cl->thd->state = CLIENT_STATE_INIT;
997 MUTEX_UNLOCK (&cn_mutex);
998 rc = init_client_crypto (&cl->crypto);
999 if (rc)
1000 goto fail;
1002 #ifdef WITH_AGENT
1003 if (use_agent)
1004 cl->crypto->agent->client_ctx = cl->ctx;
1005 #endif
1007 cl->crypto->client_ctx = cl->ctx;
1008 cl->lock_timeout = config_get_integer ("global", "lock_timeout");
1009 xmlSetStructuredErrorFunc (cl, xml_error_cb);
1010 return 1;
1012 fail:
1013 log_write ("%s", pwmd_strerror (rc));
1014 return 0;
1018 * This is called after a client_thread() terminates. Set with
1019 * pthread_cleanup_push().
1021 static void
1022 cleanup_cb (void *arg)
1024 struct client_thread_s *cn = arg;
1025 struct client_s *cl = cn->cl;
1027 MUTEX_LOCK (&cn_mutex);
1028 cn_thread_list = slist_remove (cn_thread_list, cn);
1029 MUTEX_UNLOCK (&cn_mutex);
1031 if (cl)
1033 cleanup_client (cl);
1034 if (cl->xml_error)
1035 xmlResetError (cl->xml_error);
1037 xfree (cl->xml_error);
1039 #ifdef WITH_GNUTLS
1040 if (cn->tls)
1042 gnutls_deinit (cn->tls->ses);
1043 xfree (cn->tls->fp);
1044 xfree (cn->tls);
1046 #endif
1048 if (!cn->atfork && cl->ctx)
1049 assuan_release (cl->ctx);
1050 else if (!cn->atfork && cl->thd && cl->thd->fd != -1)
1051 close (cl->thd->fd);
1053 if (cl->crypto)
1054 cleanup_crypto (&cl->crypto);
1056 pinentry_free_opts (&cl->pinentry_opts);
1057 xfree (cl);
1059 else
1061 if (cn->fd != -1)
1062 close (cn->fd);
1065 while (cn->msg_queue)
1067 struct status_msg_s *msg = cn->msg_queue;
1069 cn->msg_queue = msg->next;
1070 xfree (msg->line);
1071 xfree (msg);
1074 if (!cn->atfork && cn->status_msg_pipe[0] != -1)
1075 close (cn->status_msg_pipe[0]);
1077 if (!cn->atfork && cn->status_msg_pipe[1] != -1)
1078 close (cn->status_msg_pipe[1]);
1080 pthread_mutex_destroy (&cn->status_mutex);
1082 if (!cn->atfork)
1084 log_write (_("exiting, fd=%i"), cn->fd);
1085 send_status_all (STATUS_CLIENTS, NULL);
1088 xfree (cn->name);
1089 #ifdef WITH_GNUTLS
1090 xfree (cn->peeraddr);
1091 #endif
1092 xfree (cn);
1093 pthread_cond_signal (&quit_cond);
1096 void
1097 cleanup_all_clients (int atfork)
1099 /* This function may be called from pthread_atfork() which requires
1100 reinitialization. */
1101 if (atfork)
1103 pthread_mutexattr_t attr;
1105 pthread_mutexattr_init (&attr);
1106 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
1107 pthread_mutex_init (&cn_mutex, &attr);
1108 pthread_mutexattr_destroy (&attr);
1109 cache_mutex_init ();
1112 MUTEX_LOCK (&cn_mutex);
1114 while (slist_length (cn_thread_list))
1116 struct client_thread_s *thd = slist_nth_data (cn_thread_list, 0);
1118 thd->atfork = atfork;
1119 cleanup_cb (thd);
1122 exiting = 1;
1123 MUTEX_UNLOCK (&cn_mutex);
1124 cache_deinit (atfork);
1127 static gpg_error_t
1128 send_msg_queue (struct client_thread_s *thd)
1130 MUTEX_LOCK (&thd->status_mutex);
1131 gpg_error_t rc = 0;
1132 char c;
1134 read (thd->status_msg_pipe[0], &c, 1);
1135 thd->wrote_status = 0;
1137 while (thd->msg_queue)
1139 struct status_msg_s *msg = thd->msg_queue;
1141 thd->msg_queue = thd->msg_queue->next;
1142 MUTEX_UNLOCK (&thd->status_mutex);
1143 rc = send_status (thd->cl->ctx, msg->s, msg->line);
1144 MUTEX_LOCK (&thd->status_mutex);
1145 xfree (msg->line);
1146 xfree (msg);
1148 if (rc)
1149 break;
1152 MUTEX_UNLOCK (&thd->status_mutex);
1153 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1154 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
1156 return rc;
1159 static void *
1160 client_thread (void *data)
1162 struct client_thread_s *thd = data;
1163 struct client_s *cl = xcalloc (1, sizeof (struct client_s));
1165 #ifdef HAVE_PR_SET_NAME
1166 prctl (PR_SET_NAME, "client");
1167 #endif
1168 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1170 if (!cl)
1172 log_write ("%s(%i): %s", __FILE__, __LINE__,
1173 pwmd_strerror (GPG_ERR_ENOMEM));
1174 return NULL;
1177 MUTEX_LOCK (&cn_mutex);
1178 pthread_cleanup_push (cleanup_cb, thd);
1179 thd->cl = cl;
1180 cl->thd = thd;
1181 MUTEX_UNLOCK (&cn_mutex);
1183 if (new_connection (cl))
1185 int finished = 0;
1186 gpg_error_t rc;
1188 send_status_all (STATUS_CLIENTS, NULL);
1189 rc = send_status (cl->ctx, STATUS_CACHE, NULL);
1190 if (rc)
1192 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
1193 finished = 1;
1196 while (!finished)
1198 fd_set rfds;
1199 int n;
1200 int eof;
1202 FD_ZERO (&rfds);
1203 FD_SET (thd->fd, &rfds);
1204 FD_SET (thd->status_msg_pipe[0], &rfds);
1205 n = thd->fd > thd->status_msg_pipe[0]
1206 ? thd->fd : thd->status_msg_pipe[0];
1208 n = select (n + 1, &rfds, NULL, NULL, NULL);
1209 if (n == -1)
1211 log_write ("%s", strerror (errno));
1212 break;
1215 if (FD_ISSET (thd->status_msg_pipe[0], &rfds))
1217 rc = send_msg_queue (thd);
1218 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1219 break;
1222 if (!FD_ISSET (thd->fd, &rfds))
1223 continue;
1225 rc = assuan_process_next (cl->ctx, &eof);
1226 if (rc || eof)
1228 if (gpg_err_code (rc) == GPG_ERR_EOF || eof)
1229 break;
1231 log_write ("assuan_process_next(): rc=%i %s", rc,
1232 pwmd_strerror (rc));
1233 if (rc == gpg_error (GPG_ERR_ETIMEDOUT))
1234 break;
1236 rc = send_error (cl->ctx, rc);
1237 if (rc)
1239 log_write ("assuan_process_done(): rc=%i %s", rc,
1240 pwmd_strerror (rc));
1241 break;
1245 /* Since the msg queue pipe fd's are non-blocking, check for
1246 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1247 * client has already disconnected and will be converted to
1248 * GPG_ERR_EOF during assuan_process_next().
1250 rc = send_msg_queue (thd);
1251 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1252 break;
1256 /* Don't do pthread_exit() here because any set pthread_cleanup_push
1257 * functions would be called after a command failed but then the client
1258 * exited normally which may lead to a double free. */
1259 pthread_cleanup_pop (1);
1260 return NULL;
1263 static int
1264 xml_import (const char *filename, const char *outfile,
1265 const char *keygrip, const char *sign_keygrip,
1266 const char *keyfile, int no_passphrase, const char *cipher,
1267 const char *params, unsigned long s2k_count, uint64_t iterations)
1269 xmlDocPtr doc;
1270 int fd;
1271 struct stat st;
1272 int len;
1273 xmlChar *xmlbuf;
1274 xmlChar *xml;
1275 gpg_error_t rc;
1276 struct crypto_s *crypto = NULL;
1277 void *key = NULL;
1278 size_t keylen = 0;
1279 int algo = cipher ? cipher_string_to_gcrypt ((char *) cipher) :
1280 GCRY_CIPHER_AES256;
1282 if (algo == -1)
1284 log_write ("ERR %i: %s", gpg_error (GPG_ERR_CIPHER_ALGO),
1285 pwmd_strerror (GPG_ERR_CIPHER_ALGO));
1286 return 0;
1289 if (stat (filename, &st) == -1)
1291 log_write ("%s: %s", filename,
1292 pwmd_strerror (gpg_error_from_errno (errno)));
1293 return 0;
1296 rc = init_client_crypto (&crypto);
1297 if (rc)
1298 return 0;
1300 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
1301 crypto->save.hdr.flags = set_cipher_flag (crypto->save.hdr.flags, algo);
1302 log_write (_("Importing XML from '%s'. Output will be written to '%s' ..."),
1303 filename, outfile);
1305 if ((fd = open (filename, O_RDONLY)) == -1)
1307 log_write ("%s: %s", filename,
1308 pwmd_strerror (gpg_error_from_errno (errno)));
1309 goto fail;
1312 if ((xmlbuf = xmalloc (st.st_size + 1)) == NULL)
1314 close (fd);
1315 log_write ("%s(%i): %s", __FILE__, __LINE__,
1316 pwmd_strerror (GPG_ERR_ENOMEM));
1317 goto fail;
1320 if (read (fd, xmlbuf, st.st_size) == -1)
1322 rc = gpg_error_from_errno (errno);
1323 close (fd);
1324 log_write ("%s: %s", filename, pwmd_strerror (rc));
1325 goto fail;
1328 close (fd);
1329 xmlbuf[st.st_size] = 0;
1331 * Make sure the document validates.
1333 if ((doc = xmlReadDoc (xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS)) == NULL)
1335 log_write ("xmlReadDoc() failed");
1336 xfree (xmlbuf);
1337 goto fail;
1340 xfree (xmlbuf);
1341 xmlNodePtr n = xmlDocGetRootElement (doc);
1342 if (n && !xmlStrEqual (n->name, (xmlChar *) "pwmd"))
1344 log_write (_("Could not find root \"pwmd\" element."));
1345 rc = GPG_ERR_BAD_DATA;
1348 if (!rc)
1349 rc = validate_import (NULL, n ? n->children : n);
1351 if (rc)
1353 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1354 xmlFreeDoc (doc);
1355 goto fail;
1358 xmlDocDumpMemory (doc, &xml, &len);
1359 xmlFreeDoc (doc);
1360 crypto->save.s2k_count = s2k_count;
1361 crypto->save.hdr.iterations = iterations;
1362 if (!use_agent)
1364 rc = export_common (NULL, 0, crypto, xml, len, outfile, keyfile, &key,
1365 &keylen, 0, 0, no_passphrase);
1366 if (!rc)
1367 log_write (_("Success!"));
1369 #ifdef WITH_AGENT
1370 else
1372 rc = agent_set_pinentry_options (crypto->agent);
1373 if (!rc)
1374 rc = agent_export_common (crypto, keygrip, sign_keygrip, no_passphrase,
1375 xml, len, outfile, params, keyfile);
1377 #endif
1379 gcry_free (key);
1380 xmlFree (xml);
1381 if (rc)
1383 send_error (NULL, rc);
1384 goto fail;
1387 cleanup_crypto (&crypto);
1388 return 1;
1390 fail:
1391 cleanup_crypto (&crypto);
1392 return 0;
1395 static int
1396 do_cache_push (const char *filename, struct crypto_s *crypto)
1398 unsigned char md5file[16];
1399 gpg_error_t rc;
1400 char *key = NULL;
1401 size_t keylen = 0;
1402 xmlDocPtr doc;
1403 struct cache_data_s *cdata;
1404 unsigned char *crc;
1405 size_t len;
1407 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1408 filename);
1410 if (valid_filename (filename) == 0)
1412 log_write (_("%s: Invalid characters in filename"), filename);
1413 return 0;
1416 rc = decrypt_common (NULL, 0, crypto, filename, &key, &keylen);
1417 if (rc)
1418 return 0;
1420 rc = parse_doc ((char *) crypto->plaintext, crypto->plaintext_len, &doc);
1421 if (rc)
1423 log_write ("%s", pwmd_strerror (rc));
1424 xfree (key);
1425 return 0;
1428 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
1429 cdata = xcalloc (1, sizeof (struct cache_data_s));
1430 if (!cdata)
1432 xmlFreeDoc (doc);
1433 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM));
1434 xfree (key);
1435 return 0;
1438 rc = get_checksum (filename, &crc, &len);
1439 if (rc)
1441 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1442 xmlFreeDoc (doc);
1443 free_cache_data_once (cdata);
1444 xfree (key);
1445 return 0;
1448 cdata->crc = crc;
1449 rc = encrypt_xml (NULL, cache_key, cache_keysize, GCRY_CIPHER_AES,
1450 crypto->plaintext, crypto->plaintext_len, &cdata->doc,
1451 &cdata->doclen, &cache_iv, &cache_blocksize, 0);
1452 if (!rc && !IS_PKI (crypto))
1454 cdata->key = key;
1455 cdata->keylen = keylen;
1457 else
1458 xfree (key);
1460 if (rc)
1462 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1463 xmlFreeDoc (doc);
1464 free_cache_data_once (cdata);
1465 return 0;
1468 #ifdef WITH_AGENT
1469 if (use_agent && IS_PKI (crypto))
1471 gcry_sexp_build ((gcry_sexp_t *) & cdata->pubkey, NULL, "%S",
1472 crypto->pkey_sexp);
1473 gcry_sexp_build ((gcry_sexp_t *) & cdata->sigkey, NULL, "%S",
1474 crypto->sigpkey_sexp);
1476 #endif
1478 int timeout = config_get_integer (filename, "cache_timeout");
1479 cache_add_file (md5file, crypto->grip, cdata, timeout);
1480 log_write (_("Successfully added '%s' to the cache."), filename);
1481 return 1;
1484 static gpg_error_t
1485 init_client (int fd, const char *addr)
1487 gpg_error_t rc = 0;
1488 struct client_thread_s *new = xcalloc (1, sizeof (struct client_thread_s));
1490 if (!new)
1492 close (fd);
1493 return GPG_ERR_ENOMEM;
1496 MUTEX_LOCK (&cn_mutex);
1497 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
1499 if (pipe (new->status_msg_pipe) == -1)
1500 rc = gpg_error_from_errno (errno);
1502 if (!rc)
1504 if (fcntl (new->status_msg_pipe[0], F_SETFL, O_NONBLOCK) == -1)
1505 rc = gpg_error_from_errno (errno);
1507 if (!rc)
1508 if (fcntl (new->status_msg_pipe[1], F_SETFL, O_NONBLOCK) == -1)
1509 rc = gpg_error_from_errno (errno);
1511 pthread_mutex_init (&new->status_mutex, NULL);
1514 if (!rc)
1516 #ifdef WITH_GNUTLS
1517 new->remote = addr ? 1 : 0;
1518 #endif
1519 new->fd = fd;
1520 rc = create_thread (client_thread, new, &new->tid, 1);
1521 if (rc)
1523 close (new->status_msg_pipe[0]);
1524 close (new->status_msg_pipe[1]);
1525 pthread_mutex_destroy (&new->status_mutex);
1529 if (!rc)
1531 struct slist_s *list = slist_append (cn_thread_list, new);
1533 if (list)
1535 cn_thread_list = list;
1536 if (addr)
1538 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1539 (pthread_t *) new->tid, fd, addr);
1540 #ifdef WITH_GNUTLS
1541 new->peeraddr = str_dup (addr);
1542 #endif
1544 else
1545 log_write (_("new connection: tid=%p, fd=%i"),
1546 (pthread_t *) new->tid, fd);
1548 else
1549 rc = GPG_ERR_ENOMEM;
1552 pthread_cleanup_pop (1);
1554 if (rc)
1556 xfree (new);
1557 close (fd);
1558 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1559 pwmd_strerror (rc));
1561 return rc;
1564 static void*
1565 keepalive_thread (void *arg)
1567 #ifndef HAVE_PTHREAD_CANCEL
1568 int *n = xmalloc (sizeof (int));
1570 *n = 0;
1571 pthread_setspecific (signal_thread_key, n);
1572 INIT_THREAD_SIGNAL;
1573 #endif
1575 #ifdef HAVE_PR_SET_NAME
1576 prctl (PR_SET_NAME, "keepalive");
1577 #endif
1578 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1580 for (;;)
1582 int n = config_get_integer ("global", "keepalive_interval");
1583 struct timeval tv = { n, 0 };
1584 #ifndef HAVE_PTHREAD_CANCEL
1585 int *sigusr2;
1587 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1588 if (*sigusr2)
1589 break;
1590 #endif
1592 send_status_all (STATUS_KEEPALIVE, NULL);
1593 select (0, NULL, NULL, NULL, &tv);
1596 return NULL;
1599 #ifdef WITH_GNUTLS
1600 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1601 static void *
1602 get_in_addr (struct sockaddr *sa)
1604 if (sa->sa_family == AF_INET)
1605 return &(((struct sockaddr_in *) sa)->sin_addr);
1607 return &(((struct sockaddr_in6 *) sa)->sin6_addr);
1610 static void *
1611 tcp_accept_thread (void *arg)
1613 int sockfd = *(int *) arg;
1614 #ifndef HAVE_PTHREAD_CANCEL
1615 int *n = xmalloc (sizeof (int));
1617 *n = 0;
1618 pthread_setspecific (signal_thread_key, n);
1619 INIT_THREAD_SIGNAL;
1620 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1621 #endif
1623 #ifdef HAVE_PR_SET_NAME
1624 prctl (PR_SET_NAME, "tcp_accept");
1625 #endif
1626 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1628 for (;;)
1630 struct sockaddr_storage raddr;
1631 socklen_t slen = sizeof (raddr);
1632 int fd;
1633 unsigned long n;
1634 char s[INET6_ADDRSTRLEN];
1635 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1636 #ifndef HAVE_PTHREAD_CANCEL
1637 int *sigusr2;
1639 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1640 if (*sigusr2)
1641 break;
1642 #endif
1644 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1645 if (fd == -1)
1647 if (errno == EMFILE || errno == ENFILE)
1648 log_write ("accept(): %s",
1649 pwmd_strerror (gpg_error_from_errno (errno)));
1650 else if (errno != EAGAIN)
1652 if (!quit) // probably EBADF
1653 log_write ("accept(): %s", strerror (errno));
1655 break;
1658 #ifndef HAVE_PTHREAD_CANCEL
1659 select (0, NULL, NULL, NULL, &tv);
1660 #endif
1661 continue;
1664 if (quit)
1666 close (fd);
1667 break;
1670 inet_ntop (raddr.ss_family, get_in_addr ((struct sockaddr *) &raddr),
1671 s, sizeof s);
1672 (void) init_client (fd, s);
1673 n = config_get_integer ("global", "tcp_wait");
1674 if (n > 0)
1676 tv.tv_sec = (n * 100000) / 100000;
1677 tv.tv_usec = (n * 100000) % 100000;
1678 select (0, NULL, NULL, NULL, &tv);
1682 return NULL;
1685 static int
1686 start_stop_tls_with_protocol (int ipv6, int term)
1688 struct addrinfo hints, *servinfo, *p;
1689 int port = config_get_integer ("global", "tcp_port");
1690 char buf[7];
1691 int n;
1692 gpg_error_t rc;
1693 int *fd = ipv6 ? &tls6_fd : &tls_fd;
1695 if (term || config_get_boolean ("global", "enable_tcp") == 0)
1697 if (tls6_fd != -1)
1699 if (spawned_tls6)
1701 #ifdef HAVE_PTHREAD_CANCEL
1702 pthread_cancel (tls6_tid);
1703 #else
1704 pthread_kill (tls6_tid, SIGUSR2);
1705 #endif
1706 pthread_join (tls6_tid, NULL);
1709 shutdown (tls6_fd, SHUT_RDWR);
1710 close (tls6_fd);
1711 tls6_fd = -1;
1712 spawned_tls6 = 0;
1715 if (tls_fd != -1)
1717 if (spawned_tls)
1719 #ifdef HAVE_PTHREAD_CANCEL
1720 pthread_cancel (tls_tid);
1721 #else
1722 pthread_kill (tls_tid, SIGUSR2);
1723 #endif
1724 pthread_join (tls_tid, NULL);
1727 shutdown (tls_fd, SHUT_RDWR);
1728 close (tls_fd);
1729 tls_fd = -1;
1730 spawned_tls = 0;
1733 /* A client may still be connected. */
1734 if (!quit && x509_cred != NULL)
1735 tls_deinit_params ();
1737 return 1;
1740 if ((ipv6 && tls6_fd != -1) || (!ipv6 && tls_fd != -1))
1741 return 1;
1743 memset (&hints, 0, sizeof (hints));
1744 hints.ai_family = ipv6 ? AF_INET6 : AF_INET;
1745 hints.ai_socktype = SOCK_STREAM;
1746 hints.ai_flags = AI_PASSIVE;
1747 snprintf (buf, sizeof (buf), "%i", port);
1749 if ((n = getaddrinfo (NULL, buf, &hints, &servinfo)) == -1)
1751 log_write ("getaddrinfo(): %s", gai_strerror (n));
1752 return 0;
1755 for (n = 0, p = servinfo; p != NULL; p = p->ai_next)
1757 int r = 1;
1759 if ((ipv6 && p->ai_family != AF_INET6)
1760 || (!ipv6 && p->ai_family != AF_INET))
1761 continue;
1763 if ((*fd = socket (p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
1765 log_write ("socket(): %s", strerror (errno));
1766 continue;
1769 if (setsockopt (*fd, SOL_SOCKET, SO_REUSEADDR, &r, sizeof (int)) == -1)
1771 log_write ("setsockopt(): %s",
1772 pwmd_strerror (gpg_error_from_errno (errno)));
1773 freeaddrinfo (servinfo);
1774 goto fail;
1777 if (bind (*fd, p->ai_addr, p->ai_addrlen) == -1)
1779 close (*fd);
1780 log_write ("bind(): %s",
1781 pwmd_strerror (gpg_error_from_errno (errno)));
1782 continue;
1785 n++;
1786 break;
1789 freeaddrinfo (servinfo);
1791 if (!n)
1792 goto fail;
1794 #if HAVE_DECL_SO_BINDTODEVICE != 0
1795 char *tmp = config_get_string ("global", "tcp_interface");
1796 if (tmp && setsockopt (*fd, SOL_SOCKET, SO_BINDTODEVICE, tmp,
1797 strlen (tmp)) == -1)
1799 log_write ("setsockopt(): %s",
1800 pwmd_strerror (gpg_error_from_errno (errno)));
1801 xfree (tmp);
1802 goto fail;
1805 xfree (tmp);
1806 #endif
1808 if (x509_cred == NULL)
1810 rc = tls_init_params ();
1811 if (rc)
1812 goto fail;
1815 if (listen (*fd, 0) == -1)
1817 log_write ("listen(): %s", strerror (errno));
1818 goto fail;
1821 if (ipv6)
1822 rc = create_thread (tcp_accept_thread, fd, &tls6_tid, 0);
1823 else
1824 rc = create_thread (tcp_accept_thread, fd, &tls_tid, 0);
1826 if (rc)
1828 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1829 pwmd_strerror (rc));
1830 goto fail;
1833 if (ipv6)
1834 spawned_tls6 = 1;
1835 else
1836 spawned_tls = 1;
1838 return 1;
1840 fail:
1841 start_stop_tls_with_protocol (0, 1);
1842 if (tls_fd != -1)
1843 close (tls_fd);
1845 if (tls6_fd != -1)
1846 close (tls6_fd);
1848 tls_fd = -1;
1849 tls6_fd = -1;
1850 return 0;
1853 static int
1854 start_stop_tls (int term)
1856 char *s = config_get_string ("global", "tcp_bind");
1857 int b;
1859 if (!s)
1860 return 0;
1862 if (!strcmp (s, "any"))
1864 b = start_stop_tls_with_protocol (0, term);
1865 if (b)
1866 b = start_stop_tls_with_protocol (1, term);
1868 else if (!strcmp (s, "ipv4"))
1869 b = start_stop_tls_with_protocol (0, term);
1870 else if (!strcmp (s, "ipv6"))
1871 b = start_stop_tls_with_protocol (1, term);
1872 else
1873 b = 0;
1875 xfree (s);
1876 return b;
1878 #endif
1880 static void *
1881 accept_thread (void *arg)
1883 int sockfd = *(int *) arg;
1884 #ifndef HAVE_PTHREAD_CANCEL
1885 int *n = xmalloc (sizeof (int));
1887 *n = 0;
1888 pthread_setspecific (signal_thread_key, n);
1889 INIT_THREAD_SIGNAL;
1890 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1891 #endif
1893 #ifdef HAVE_PR_SET_NAME
1894 prctl (PR_SET_NAME, "accept");
1895 #endif
1896 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1898 for (;;)
1900 socklen_t slen = sizeof (struct sockaddr_un);
1901 struct sockaddr_un raddr;
1902 int fd;
1903 #ifndef HAVE_PTHREAD_CANCEL
1904 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1905 int *sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1907 if (*sigusr2)
1908 break;
1909 #endif
1911 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1912 if (fd == -1)
1914 if (errno == EMFILE || errno == ENFILE)
1915 log_write ("accept(): %s",
1916 pwmd_strerror (gpg_error_from_errno (errno)));
1917 else if (errno != EAGAIN)
1919 if (!quit) // probably EBADF
1920 log_write ("accept(): %s",
1921 pwmd_strerror (gpg_error_from_errno (errno)));
1923 break;
1926 #ifndef HAVE_PTHREAD_CANCEL
1927 select (0, NULL, NULL, NULL, &tv);
1928 #endif
1929 continue;
1932 (void) init_client (fd, NULL);
1935 /* Just in case accept() failed for some reason other than EBADF */
1936 quit = 1;
1937 return NULL;
1940 static void *
1941 cache_timer_thread (void *arg)
1943 #ifndef HAVE_PTHREAD_CANCEL
1944 int *n = xmalloc (sizeof (int));
1946 *n = 0;
1947 pthread_setspecific (signal_thread_key, n);
1948 INIT_THREAD_SIGNAL;
1949 #endif
1951 #ifdef HAVE_PR_SET_NAME
1952 prctl (PR_SET_NAME, "cache timer");
1953 #endif
1954 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1956 for (;;)
1958 struct timeval tv = { 1, 0 };
1959 #ifndef HAVE_PTHREAD_CANCEL
1960 int *n;
1962 n = (int *) pthread_getspecific (signal_thread_key);
1963 if (*n)
1964 break;
1965 #endif
1967 select (0, NULL, NULL, NULL, &tv);
1968 cache_adjust_timeout ();
1971 return NULL;
1974 static int
1975 signal_loop (sigset_t sigset)
1977 int done = 0;
1978 int siint = 0;
1982 int sig;
1984 sigwait (&sigset, &sig);
1986 if (sig != SIGQUIT)
1987 log_write (_("caught signal %i (%s)"), sig, strsignal (sig));
1989 switch (sig)
1991 case SIGHUP:
1992 pthread_cond_signal (&rcfile_cond);
1993 break;
1994 case SIGUSR1:
1995 log_write (_("clearing file cache"));
1996 cache_clear (NULL);
1997 send_status_all (STATUS_CACHE, NULL);
1998 break;
1999 case SIGQUIT:
2000 done = 1;
2001 break;
2002 default:
2003 siint = 1;
2004 done = 1;
2005 break;
2008 while (!done);
2010 return siint;
2013 static void
2014 catchsig (int sig)
2016 log_write (_ ("Caught signal %i (%s). Exiting."), sig, strsignal (sig));
2017 #ifdef HAVE_BACKTRACE
2018 BACKTRACE (__FUNCTION__);
2019 #endif
2020 longjmp (jmp, 1);
2023 static void *
2024 waiting_for_exit (void *arg)
2026 int last = 0;
2027 #ifndef HAVE_PTHREAD_CANCEL
2028 int *n = xmalloc (sizeof (int));
2030 *n = 0;
2031 pthread_setspecific (signal_thread_key, n);
2032 INIT_THREAD_SIGNAL;
2033 #endif
2035 #ifdef HAVE_PR_SET_NAME
2036 prctl (PR_SET_NAME, "exiting");
2037 #endif
2038 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
2039 log_write (_("waiting for all clients to disconnect"));
2040 MUTEX_LOCK (&quit_mutex);
2041 pthread_cleanup_push (cleanup_mutex_cb, &quit_mutex);
2043 for (;;)
2045 struct timespec ts;
2046 int n;
2048 MUTEX_LOCK (&cn_mutex);
2049 n = slist_length (cn_thread_list);
2050 MUTEX_UNLOCK (&cn_mutex);
2051 if (!n)
2052 break;
2054 #ifndef HAVE_PTHREAD_CANCEL
2055 int *s = (int *) pthread_getspecific (signal_thread_key);
2056 if (*s)
2057 break;
2058 #endif
2060 if (last != n)
2062 log_write (_("%i clients remain"), n);
2063 last = n;
2066 INIT_TIMESPEC (SIG_TIMEOUT, ts);
2067 pthread_cond_timedwait (&quit_cond, &quit_mutex, &ts);
2070 kill (getpid (), SIGQUIT);
2071 pthread_cleanup_pop (1);
2072 return NULL;
2075 static int
2076 server_loop (int sockfd, char **socketpath)
2078 pthread_t accept_tid;
2079 pthread_t cache_timeout_tid;
2080 int cancel_timeout_thread = 0, cancel_accept_thread = 0;
2081 int cancel_keepalive_thread = 0;
2082 sigset_t sigset;
2083 int n;
2084 int segv = 0;
2085 gpg_error_t rc;
2087 init_commands ();
2088 sigemptyset (&sigset);
2090 /* Termination */
2091 sigaddset (&sigset, SIGTERM);
2092 sigaddset (&sigset, SIGINT);
2094 /* Clears the file cache. */
2095 sigaddset (&sigset, SIGUSR1);
2097 /* Configuration file reloading. */
2098 sigaddset (&sigset, SIGHUP);
2100 /* For exiting cleanly. */
2101 sigaddset (&sigset, SIGQUIT);
2103 #ifndef HAVE_PTHREAD_CANCEL
2105 The socket, cache and rcfile threads use this signal when
2106 pthread_cancel() is unavailable. Prevent the main thread from
2107 catching this signal from another process.
2109 sigaddset (&sigset, SIGUSR2);
2110 #endif
2112 /* When mem.c cannot find a pointer in the list (double free). */
2113 signal (SIGABRT, catchsig);
2114 sigaddset (&sigset, SIGABRT);
2115 sigprocmask (SIG_BLOCK, &sigset, NULL);
2117 #ifndef HAVE_PTHREAD_CANCEL
2118 /* Remove this signal from the watched signals in signal_loop(). */
2119 sigdelset (&sigset, SIGUSR2);
2120 #endif
2122 /* Ignored everywhere. When a client disconnects abnormally this signal
2123 * gets raised. It isn't needed though because client_thread() will check
2124 * for rcs even after the client disconnects. */
2125 signal (SIGPIPE, SIG_IGN);
2127 /* Can show a backtrace of the stack in the log. */
2128 signal (SIGSEGV, catchsig);
2130 #ifdef WITH_GNUTLS
2131 /* Needs to be done after the fork(). */
2132 if (!start_stop_tls (0))
2134 segv = 1;
2135 goto done;
2137 #endif
2139 pthread_mutex_init (&quit_mutex, NULL);
2140 pthread_cond_init (&quit_cond, NULL);
2141 char *p = get_username (getuid());
2142 log_write (_("%s started for user %s"), PACKAGE_STRING, p);
2143 xfree (p);
2145 #ifdef WITH_GNUTLS
2146 if (config_get_boolean ("global", "enable_tcp"))
2147 log_write (_("Listening on %s and TCP port %i as user %i"), *socketpath,
2148 config_get_integer ("global", "tcp_port"), invoking_uid);
2149 else
2150 log_write (_("Listening on %s"), *socketpath);
2151 #else
2152 log_write (_("Listening on %s"), *socketpath);
2153 #endif
2155 rc = create_thread (keepalive_thread, NULL, &keepalive_tid, 0);
2156 if (rc)
2158 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2159 pwmd_strerror (rc));
2160 goto done;
2163 cancel_keepalive_thread = 1;
2164 rc = create_thread (reload_rcfile_thread, NULL, &rcfile_tid, 0);
2165 if (rc)
2167 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2168 pwmd_strerror (rc));
2169 goto done;
2172 rc = create_thread (cache_timer_thread, NULL, &cache_timeout_tid, 0);
2173 if (rc)
2175 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2176 pwmd_strerror (rc));
2177 goto done;
2180 cancel_timeout_thread = 1;
2181 rc = create_thread (accept_thread, &sockfd, &accept_tid, 0);
2182 if (rc)
2184 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2185 pwmd_strerror (rc));
2186 goto done;
2189 cancel_accept_thread = 1;
2190 if (!setjmp (jmp))
2191 signal_loop (sigset);
2192 else
2193 segv = 1;
2195 done:
2197 * We're out of the main server loop. This happens when a signal was sent
2198 * to terminate the daemon. We'll wait for all clients to disconnect
2199 * before exiting but exit immediately if another termination signal is
2200 * sent.
2202 if (cancel_accept_thread)
2204 #ifdef HAVE_PTHREAD_CANCEL
2205 int n = pthread_cancel (accept_tid);
2206 #else
2207 int n = pthread_kill (accept_tid, SIGUSR2);
2208 #endif
2209 if (!n)
2210 pthread_join (accept_tid, NULL);
2213 #ifdef WITH_GNUTLS
2214 start_stop_tls (1);
2215 #endif
2216 shutdown (sockfd, SHUT_RDWR);
2217 close (sockfd);
2218 unlink (*socketpath);
2219 xfree (*socketpath);
2220 *socketpath = NULL;
2221 MUTEX_LOCK (&cn_mutex);
2222 n = slist_length (cn_thread_list);
2223 MUTEX_UNLOCK (&cn_mutex);
2225 if (n && !segv)
2227 pthread_t tid;
2229 rc = create_thread (waiting_for_exit, NULL, &tid, 0);
2230 if (!rc)
2232 if (signal_loop (sigset))
2234 log_write (_("Received second termination request. Exiting."));
2235 #ifdef HAVE_PTHREAD_CANCEL
2236 pthread_cancel (tid);
2237 #else
2238 pthread_kill (tid, SIGUSR2);
2239 #endif
2240 pthread_join (tid, NULL);
2243 else
2244 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2245 pwmd_strerror (rc));
2248 if (cancel_timeout_thread)
2250 #ifdef HAVE_PTHREAD_CANCEL
2251 pthread_cancel (cache_timeout_tid);
2252 #else
2253 pthread_kill (cache_timeout_tid, SIGUSR2);
2254 #endif
2255 pthread_join (cache_timeout_tid, NULL);
2258 if (cancel_keepalive_thread)
2260 #ifdef HAVE_PTHREAD_CANCEL
2261 pthread_cancel (keepalive_tid);
2262 #else
2263 pthread_kill (keepalive_tid, SIGUSR2);
2264 #endif
2265 pthread_join (keepalive_tid, NULL);
2268 cleanup_all_clients (0);
2269 #ifdef WITH_GNUTLS
2270 start_stop_tls (1);
2271 #endif
2272 deinit_commands ();
2273 pthread_cond_destroy (&quit_cond);
2274 pthread_mutex_destroy (&quit_mutex);
2275 return segv ? EXIT_FAILURE : EXIT_SUCCESS;;
2278 static void
2279 startup_failure ()
2281 log_write (_
2282 ("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
2283 cache_clear (NULL);
2286 /* This is called from cache.c:clear_once(). See
2287 * command.c:clearcache_command() for details about lock checking.
2289 static gpg_error_t
2290 free_cache_data (file_cache_t * cache)
2292 gpg_error_t rc = GPG_ERR_NO_DATA;
2293 int i, t;
2294 struct client_thread_s *found = NULL;
2295 int self = 0;
2297 if (!cache->data)
2298 return 0;
2300 cache_lock ();
2301 MUTEX_LOCK (&cn_mutex);
2302 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
2303 t = slist_length (cn_thread_list);
2305 for (i = 0; i < t; i++)
2307 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2309 if (!thd->cl)
2310 continue;
2312 if (!memcmp (thd->cl->md5file, cache->filename,
2313 sizeof (cache->filename)))
2315 if (pthread_equal (pthread_self (), thd->tid))
2317 found = thd;
2318 self = 1;
2319 continue;
2322 /* Continue trying to find a client who has the same file open and
2323 * also has a lock. */
2324 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0, -1);
2325 if (!rc)
2327 self = 0;
2328 found = thd;
2329 break;
2334 if (self && (!rc || rc == GPG_ERR_NO_DATA))
2335 rc = cache_lock_mutex (found->cl->ctx, found->cl->md5file, -1, 0, -1);
2337 if (exiting || !rc || rc == GPG_ERR_NO_DATA)
2339 free_cache_data_once (cache->data);
2340 cache->data = NULL;
2341 cache->defer_clear = 0;
2342 cache->timeout = -1;
2344 if (found)
2345 cache_unlock_mutex (found->cl->md5file, 0);
2347 rc = 0;
2350 if (rc)
2351 cache->defer_clear = 1;
2353 pthread_cleanup_pop (1);
2354 cache_unlock ();
2355 return rc;
2358 static int
2359 convert_v2_datafile (const char *filename, const char *cipher,
2360 const char *keyfile, const char *keygrip,
2361 const char *sign_keygrip, int nopass,
2362 const char *outfile, const char *keyparam,
2363 unsigned long s2k_count, uint64_t iterations)
2365 gpg_error_t rc;
2366 void *data = NULL;
2367 size_t datalen;
2368 struct crypto_s *crypto = NULL;
2369 uint16_t ver;
2370 int algo;
2371 void *key = NULL;
2372 size_t keylen = 0;
2374 if (outfile[0] == '-' && outfile[1] == 0)
2375 outfile = NULL;
2377 log_write (_("Converting version 2 data file \"%s\" ..."), filename);
2378 if (access (filename, R_OK) == -1)
2380 log_write ("%s: %s", filename,
2381 pwmd_strerror (gpg_error_from_errno (errno)));
2382 return 0;
2385 if (keyfile)
2387 log_write (_("Using passphrase file \"%s\" for decryption ..."),
2388 keyfile);
2389 if (access (keyfile, R_OK) == -1)
2391 log_write ("%s: %s", keyfile,
2392 pwmd_strerror (gpg_error_from_errno (errno)));
2393 return 0;
2397 rc = read_v2_datafile (filename, keyfile, &data, &datalen, &ver, &algo);
2398 if (rc)
2400 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2401 return 0;
2404 if (cipher)
2406 algo = cipher_string_to_gcrypt (cipher);
2407 if (algo == -1)
2409 rc = GPG_ERR_CIPHER_ALGO;
2410 goto fail;
2414 if (ver < 0x212)
2416 xmlDocPtr doc;
2418 rc = parse_doc (data, datalen, &doc);
2419 if (rc)
2420 goto fail;
2422 rc = convert_pre_212_elements (doc);
2423 gcry_free (data);
2424 data = NULL;
2425 if (!rc)
2427 xmlDocDumpFormatMemory (doc, (xmlChar **) & data, (int *) &datalen,
2429 if (!data)
2430 rc = GPG_ERR_ENOMEM;
2433 xmlFreeDoc (doc);
2434 if (rc)
2435 goto fail;
2438 rc = init_client_crypto (&crypto);
2439 if (!rc)
2441 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
2442 crypto->save.hdr.flags = set_cipher_flag (crypto->save.hdr.flags, algo);
2443 crypto->save.s2k_count = s2k_count;
2444 crypto->save.hdr.iterations = iterations;
2446 if (!use_agent)
2448 rc = export_common (NULL, 0, crypto, data, datalen, outfile, keyfile,
2449 &key, &keylen, 0, 0, nopass);
2451 #ifdef WITH_AGENT
2452 else
2454 rc = agent_set_pinentry_options (crypto->agent);
2455 if (!rc)
2456 rc = agent_export_common (crypto, keygrip, sign_keygrip, nopass,
2457 data, datalen, outfile, keyparam,
2458 no_passphrase_file ? NULL : keyfile);
2460 #endif
2461 if (!rc)
2462 log_write (_("Output written to \"%s\"."), outfile);
2465 fail:
2466 if (ver < 0x212)
2467 xmlFree (data);
2468 else
2469 gcry_free (data);
2471 gcry_free (key);
2472 cleanup_crypto (&crypto);
2474 if (rc)
2475 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2476 return rc ? 0 : 1;
2479 static void
2480 usage (const char *pn, int status)
2482 FILE *fp = status == EXIT_FAILURE ? stderr : stdout;
2484 fprintf (fp, _("Usage: %s [OPTIONS] [file1] [...]\n"
2485 " -f, --rcfile=filename load the specfied configuration file\n"
2486 " (~/.pwmd/config)\n"
2487 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2488 " --kill terminate an existing instance of pwmd\n"
2489 #ifdef WITH_AGENT
2490 " --use-agent enable use of gpg-agent\n"
2491 #endif
2492 " -n, --no-fork run as a foreground process\n"
2493 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2494 " --ignore, --force ignore file errors during startup\n"
2495 " --debug-level=keywords log protocol output (see manual for details)\n"
2496 " -o, --outfile=filename output file when importing or converting\n"
2497 " -C, --convert=filename convert a version 2 data file to version 3\n"
2498 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2499 " -k, --passphrase-file=file for use when importing or converting\n"
2500 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2501 " converting\n"
2502 " --no-passphrase when importing or converting\n"
2503 " --keygrip=hex public key to use when encrypting\n"
2504 " --sign-keygrip=hex private key to use when signing\n"
2505 " --keyparam=s-exp custom key parameters to use (RSA-2048)\n"
2506 " --cipher=string encryption cipher (aes256)\n"
2507 " --cipher-iterations=N cipher iteration count (N+1)\n"
2508 " --s2k-count=N hash iteration count (>65536, calibrated)\n"
2509 " --help this help text\n"
2510 " --version show version and compile time features\n"),
2511 pn);
2512 exit (status);
2515 static void
2516 unlink_stale_socket (const char *sock, const char *pidfile)
2518 log_write (_ ("removing stale socket %s"), sock);
2519 unlink (sock);
2520 unlink (pidfile);
2523 static int
2524 test_pidfile (const char *path, const char *sock, char *buf, size_t buflen,
2525 char **pidfile, int create, mode_t mode, int terminate)
2527 pid_t pid;
2528 int fd;
2529 size_t len;
2531 if (!create)
2533 snprintf (buf, buflen, "%s/%s.pid", homedir, sock);
2534 *pidfile = str_dup (buf);
2535 fd = open (buf, O_RDONLY);
2537 else
2538 fd = open (*pidfile, O_CREAT|O_WRONLY|O_TRUNC, mode);
2540 if (fd == -1)
2542 if (!create && errno != ENOENT)
2544 log_write ("%s: %s", buf, pwmd_strerror (errno));
2545 free (*pidfile);
2546 *pidfile = NULL;
2547 return -1;
2549 else if (!create && !terminate)
2550 return 0;
2552 log_write ("%s: %s", *pidfile, strerror (errno));
2553 return -1;
2556 if (create)
2558 snprintf (buf, buflen, "%i", getpid ());
2559 write (fd, buf, strlen (buf));
2560 close (fd);
2561 return 0;
2564 len = read (fd, buf, buflen);
2565 close (fd);
2566 if (len == 0)
2568 unlink_stale_socket (path, *pidfile);
2569 return 0;
2572 if (sscanf (buf, "%5i", &pid) != 1 || pid == 0)
2574 if (!terminate)
2576 unlink_stale_socket (path, *pidfile);
2577 return 0;
2581 if (kill (pid, 0) == -1)
2583 unlink_stale_socket (path, *pidfile);
2584 return 0;
2587 if (terminate)
2589 if (kill (pid, SIGTERM) == -1)
2590 log_write ("%s: %s", path, pwmd_strerror (errno));
2592 else
2593 log_write (_ ("an instance for socket %s is already running"), path);
2595 xfree (*pidfile);
2596 *pidfile = NULL;
2597 return 1;
2601 main (int argc, char *argv[])
2603 int opt;
2604 struct sockaddr_un addr;
2605 char buf[PATH_MAX];
2606 char *socketpath = NULL, *socketdir, *socketname = NULL;
2607 char *socketarg = NULL;
2608 char *datadir = NULL;
2609 char *pidfile = NULL;
2610 mode_t mode = 0600;
2611 int x;
2612 char *p;
2613 char **cache_push = NULL;
2614 char *import = NULL, *keygrip = NULL, *sign_keygrip = NULL;
2615 char *keyparam = NULL;
2616 int estatus = EXIT_FAILURE;
2617 int sockfd;
2618 char *outfile = NULL;
2619 int do_unlink = 0;
2620 int secure = 0;
2621 int show_version = 0;
2622 int force = 0;
2623 int no_passphrase = 0;
2624 gpg_error_t rc;
2625 char *convertfile = NULL;
2626 char *cipher = NULL;
2627 char *keyfile = NULL;
2628 unsigned long s2k_count = 0;
2629 uint64_t iterations = 0;
2630 int exists;
2631 char *debug_level_opt = NULL;
2632 int optindex;
2633 int terminate = 0;
2634 /* Must maintain the same order as longopts[] */
2635 enum
2637 OPT_VERSION, OPT_HELP,
2638 #ifdef WITH_AGENT
2639 OPT_AGENT,
2640 #endif
2641 OPT_DEBUG_LEVEL, OPT_HOMEDIR, OPT_NO_FORK, OPT_DISABLE_DUMP,
2642 OPT_IGNORE, OPT_FORCE, OPT_RCFILE, OPT_CONVERT,
2643 OPT_PASSPHRASE_FILE, OPT_IMPORT, OPT_OUTFILE,
2644 OPT_NO_PASSPHRASE_FILE, OPT_KEYGRIP, OPT_SIGN_KEYGRIP,
2645 OPT_KEYPARAM, OPT_CIPHER, OPT_ITERATIONS, OPT_S2K_COUNT,
2646 OPT_NO_PASSPHRASE, OPT_KILL
2648 const char *optstring = "nf:C:k:I:o:";
2649 const struct option longopts[] = {
2650 {"version", no_argument, 0, 0},
2651 {"help", no_argument, 0, 0},
2652 #ifdef WITH_AGENT
2653 {"use-agent", no_argument, 0, 0},
2654 #endif
2655 {"debug-level", required_argument, 0, 0},
2656 {"homedir", required_argument, 0, 0},
2657 {"no-fork", no_argument, 0, 'n'},
2658 {"disable_dump", no_argument, 0, 0},
2659 {"ignore", no_argument, 0, 0},
2660 {"force", no_argument, 0, 0},
2661 {"rcfile", required_argument, 0, 'f'},
2662 {"convert", required_argument, 0, 'C'},
2663 {"passphrase-file", required_argument, 0, 'k'},
2664 {"import", required_argument, 0, 'I'},
2665 {"outfile", required_argument, 0, 'o'},
2666 {"no-passphrase-file", no_argument, 0, 0},
2667 {"keygrip", required_argument, 0, 0},
2668 {"sign-keygrip", required_argument, 0, 0},
2669 {"keyparam", required_argument, 0, 0},
2670 {"cipher", required_argument, 0, 0},
2671 {"cipher-iterations", required_argument, 0, 0},
2672 {"s2k-count", required_argument, 0, 0},
2673 {"no-passphrase", no_argument, 0, 0},
2674 {"kill", no_argument, 0, 0},
2675 {0, 0, 0, 0}
2678 log_fd = -1;
2680 #ifndef DEBUG
2681 #ifdef HAVE_SETRLIMIT
2682 struct rlimit rl;
2684 rl.rlim_cur = rl.rlim_max = 0;
2686 if (setrlimit (RLIMIT_CORE, &rl) != 0)
2687 err (EXIT_FAILURE, "setrlimit()");
2688 #endif
2690 #ifdef HAVE_PR_SET_DUMPABLE
2691 prctl (PR_SET_DUMPABLE, 0);
2692 #endif
2693 #endif
2695 #ifdef ENABLE_NLS
2696 setlocale (LC_ALL, "");
2697 bindtextdomain ("pwmd", LOCALEDIR);
2698 textdomain ("pwmd");
2699 #endif
2701 #ifndef MEM_DEBUG
2702 xmem_init ();
2703 #endif
2704 gpg_err_init ();
2706 if (setup_crypto ())
2707 exit (EXIT_FAILURE);
2709 #ifdef WITH_GNUTLS
2710 gnutls_global_set_mem_functions (xmalloc, xmalloc, secure_mem_check,
2711 xrealloc, xfree);
2712 gnutls_global_init ();
2713 gnutls_global_set_log_function (tls_log);
2714 gnutls_global_set_log_level (1);
2715 tls_fd = -1;
2716 tls6_fd = -1;
2717 #endif
2718 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
2719 xmlInitMemory ();
2720 xmlInitGlobals ();
2721 xmlInitParser ();
2722 xmlXPathInit ();
2723 cmdline = 1;
2724 use_agent = 0;
2726 while ((opt = getopt_long (argc, argv, optstring, longopts, &optindex))
2727 != -1)
2729 switch (opt)
2731 case 'I':
2732 import = optarg;
2733 break;
2734 case 'C':
2735 convertfile = optarg;
2736 break;
2737 case 'k':
2738 keyfile = optarg;
2739 break;
2740 case 'o':
2741 outfile = optarg;
2742 break;
2743 case 'D':
2744 secure = 1;
2745 break;
2746 case 'n':
2747 nofork = 1;
2748 break;
2749 case 'f':
2750 rcfile = str_dup (optarg);
2751 break;
2752 default:
2753 usage (argv[0], EXIT_FAILURE);
2754 break;
2755 case 0:
2756 switch (optindex)
2758 case OPT_VERSION:
2759 show_version = 1;
2760 break;
2761 case OPT_HELP:
2762 usage (argv[0], 0);
2763 break;
2764 #ifdef WITH_AGENT
2765 case OPT_AGENT:
2766 use_agent = 1;
2767 break;
2768 #endif
2769 case OPT_DEBUG_LEVEL:
2770 debug_level_opt = optarg;
2771 break;
2772 case OPT_HOMEDIR:
2773 homedir = str_dup (optarg);
2774 break;
2775 case OPT_NO_FORK:
2776 nofork = 1;
2777 break;
2778 case OPT_DISABLE_DUMP:
2779 secure = 1;
2780 break;
2781 case OPT_IGNORE:
2782 case OPT_FORCE:
2783 force = 1;
2784 break;
2785 case OPT_RCFILE:
2786 rcfile = str_dup (optarg);
2787 break;
2788 case OPT_CONVERT:
2789 convertfile = optarg;
2790 break;
2791 case OPT_PASSPHRASE_FILE:
2792 keyfile = optarg;
2793 break;
2794 case OPT_IMPORT:
2795 import = optarg;
2796 break;
2797 case OPT_OUTFILE:
2798 outfile = optarg;
2799 break;
2800 case OPT_NO_PASSPHRASE_FILE:
2801 no_passphrase_file = 1;
2802 break;
2803 case OPT_KEYGRIP:
2804 keygrip = optarg;
2805 break;
2806 case OPT_SIGN_KEYGRIP:
2807 sign_keygrip = optarg;
2808 break;
2809 case OPT_KEYPARAM:
2810 keyparam = optarg;
2811 break;
2812 case OPT_CIPHER:
2813 cipher = optarg;
2814 break;
2815 case OPT_ITERATIONS:
2816 iterations = strtoull (optarg, NULL, 10);
2817 break;
2818 case OPT_S2K_COUNT:
2819 s2k_count = strtoul (optarg, NULL, 10);
2820 break;
2821 case OPT_NO_PASSPHRASE:
2822 no_passphrase = 1;
2823 break;
2824 case OPT_KILL:
2825 terminate = 1;
2826 break;
2827 default:
2828 usage (argv[0], 1);
2833 if (show_version)
2835 printf (_("%s\n\n"
2836 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015\n"
2837 "%s\n"
2838 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2839 "Compile time features:\n%s"), PACKAGE_STRING,
2840 PACKAGE_BUGREPORT,
2841 #ifdef PWMD_HOMEDIR
2842 "+PWMD_HOMEDIR=" PWMD_HOMEDIR "\n"
2843 #endif
2844 #ifdef WITH_AGENT
2845 "+WITH_AGENT\n"
2846 #else
2847 "-WITH_AGENT\n"
2848 #endif
2849 #ifdef WITH_QUALITY
2850 "+WITH_QUALITY\n"
2851 #else
2852 "-WITH_QUALITY\n"
2853 #endif
2854 #ifdef WITH_GNUTLS
2855 "+WITH_GNUTLS\n"
2856 #else
2857 "-WITH_GNUTLS\n"
2858 #endif
2859 #ifdef DEBUG
2860 "+DEBUG\n"
2861 #else
2862 "-DEBUG\n"
2863 #endif
2864 #ifdef MEM_DEBUG
2865 "+MEM_DEBUG\n"
2866 #else
2867 "-MEM_DEBUG\n"
2868 #endif
2869 #ifdef MUTEX_DEBUG
2870 "+MUTEX_DEBUG\n"
2871 #else
2872 "-MUTEX_DEBUG\n"
2873 #endif
2875 exit (EXIT_SUCCESS);
2878 if (!homedir)
2879 #ifdef PWMD_HOMEDIR
2880 homedir = str_dup(PWMD_HOMEDIR);
2881 #else
2882 homedir = str_asprintf ("%s/.pwmd", get_home_dir());
2883 #endif
2885 if (mkdir (homedir, 0700) == -1 && errno != EEXIST)
2886 err (EXIT_FAILURE, "%s", homedir);
2888 snprintf (buf, sizeof (buf), "%s/data", homedir);
2889 if (mkdir (buf, 0700) == -1 && errno != EEXIST)
2890 err (EXIT_FAILURE, "%s", buf);
2892 datadir = str_dup (buf);
2893 pthread_mutexattr_t attr;
2894 pthread_mutexattr_init (&attr);
2895 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
2896 pthread_mutex_init (&rcfile_mutex, &attr);
2897 pthread_cond_init (&rcfile_cond, NULL);
2898 pthread_mutex_init (&cn_mutex, &attr);
2899 pthread_mutexattr_destroy (&attr);
2900 pthread_key_create (&last_error_key, free_key);
2901 #ifndef HAVE_PTHREAD_CANCEL
2902 pthread_key_create (&signal_thread_key, free_key);
2903 #endif
2905 if (!rcfile)
2906 rcfile = str_asprintf ("%s/config", homedir);
2908 global_config = config_parse (rcfile);
2909 if (!global_config)
2910 exit (EXIT_FAILURE);
2912 #ifdef WITH_AGENT
2913 if (!use_agent)
2914 use_agent = config_get_boolean ("global", "use_agent");
2915 #endif
2917 setup_logging ();
2919 if (debug_level_opt)
2920 debug_level = str_split (debug_level_opt, ",", 0);
2922 x = config_get_int_param (global_config, "global", "priority", &exists);
2923 if (exists && x != atoi(INVALID_PRIORITY))
2925 errno = 0;
2926 if (setpriority (PRIO_PROCESS, 0, x) == -1)
2928 log_write ("setpriority(): %s",
2929 pwmd_strerror (gpg_error_from_errno (errno)));
2930 goto do_exit;
2933 #ifdef HAVE_MLOCKALL
2934 if (disable_mlock == 0 && mlockall (MCL_CURRENT | MCL_FUTURE) == -1)
2936 log_write ("mlockall(): %s",
2937 pwmd_strerror (gpg_error_from_errno (errno)));
2938 goto do_exit;
2940 #endif
2942 rc = cache_init (free_cache_data);
2943 if (rc)
2945 log_write ("pwmd: ERR %i: %s", rc,
2946 gpg_err_code (rc) == GPG_ERR_UNKNOWN_VERSION
2947 ? _("incompatible gpg-agent version: 2.1.0 or later required")
2948 : pwmd_strerror (rc));
2949 goto do_exit;
2952 if (s2k_count == 0)
2953 s2k_count = config_get_ulong (NULL, "s2k_count");
2955 if (convertfile)
2957 if (!outfile || !*outfile || argc != optind)
2958 usage (argv[0], EXIT_FAILURE);
2960 estatus = convert_v2_datafile (convertfile, cipher, keyfile, keygrip,
2961 sign_keygrip, no_passphrase, outfile,
2962 keyparam, s2k_count, iterations);
2963 config_free (global_config);
2964 xfree (rcfile);
2965 exit (!estatus);
2968 if (import)
2970 if (!outfile || !*outfile || argc != optind)
2971 usage (argv[0], EXIT_FAILURE);
2973 if (outfile && outfile[0] == '-' && outfile[1] == 0)
2974 outfile = NULL;
2976 estatus = xml_import (import, outfile, keygrip, sign_keygrip, keyfile,
2977 no_passphrase, cipher, keyparam, s2k_count,
2978 iterations);
2979 config_free (global_config);
2980 xfree (rcfile);
2981 exit (!estatus);
2984 p = config_get_string ("global", "socket_path");
2985 if (!p)
2986 p = str_asprintf ("%s/socket", homedir);
2988 socketarg = expand_homedir (p);
2989 xfree (p);
2991 if (!secure)
2992 disable_list_and_dump = config_get_boolean ("global",
2993 "disable_list_and_dump");
2994 else
2995 disable_list_and_dump = secure;
2997 cache_push = config_get_list ("global", "cache_push");
2999 while (optind < argc)
3001 if (strv_printf (&cache_push, "%s", argv[optind++]) == 0)
3002 errx (EXIT_FAILURE, "%s", pwmd_strerror (GPG_ERR_ENOMEM));
3005 if (strchr (socketarg, '/') == NULL)
3007 socketdir = getcwd (buf, sizeof (buf));
3008 socketname = str_dup (socketarg);
3009 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
3011 else
3013 socketname = str_dup (strrchr (socketarg, '/'));
3014 socketname++;
3015 socketarg[strlen (socketarg) - strlen (socketname) - 1] = 0;
3016 socketdir = str_dup (socketarg);
3017 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
3020 if (chdir (datadir))
3022 log_write ("%s: %s", datadir,
3023 pwmd_strerror (gpg_error_from_errno (errno)));
3024 unlink (socketpath);
3025 goto do_exit;
3028 x = test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 0,
3029 mode, terminate);
3030 if (!terminate && x)
3031 goto do_exit;
3032 else if (terminate)
3034 estatus = x != 1 ? EXIT_FAILURE : EXIT_SUCCESS;
3035 goto do_exit;
3039 * bind() doesn't like the full pathname of the socket or any non alphanum
3040 * characters so change to the directory where the socket is wanted then
3041 * create it then change to datadir.
3043 if (chdir (socketdir))
3045 log_write ("%s: %s", socketdir,
3046 pwmd_strerror (gpg_error_from_errno (errno)));
3047 goto do_exit;
3050 xfree (socketdir);
3052 if ((sockfd = socket (PF_UNIX, SOCK_STREAM, 0)) == -1)
3054 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
3055 goto do_exit;
3058 addr.sun_family = AF_UNIX;
3059 snprintf (addr.sun_path, sizeof (addr.sun_path), "%s", socketname);
3060 do_unlink = 1;
3061 if (bind (sockfd, (struct sockaddr *) &addr, sizeof (struct sockaddr)) ==
3064 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
3066 if (errno == EADDRINUSE)
3068 do_unlink = 0;
3069 log_write (_("Either there is another pwmd running or '%s' is a \n"
3070 "stale socket. Please remove it manually."), socketpath);
3073 goto do_exit;
3077 char *t = config_get_string ("global", "socket_perms");
3078 mode_t mask;
3080 if (t)
3082 mode = strtol (t, NULL, 8);
3083 mask = umask (0);
3084 xfree (t);
3086 if (chmod (socketname, mode) == -1)
3088 log_write ("%s: %s", socketname,
3089 pwmd_strerror (gpg_error_from_errno (errno)));
3090 close (sockfd);
3091 umask (mask);
3092 goto do_exit;
3095 umask (mask);
3099 xfree (--socketname);
3101 if (chdir (datadir))
3103 log_write ("%s: %s", datadir,
3104 pwmd_strerror (gpg_error_from_errno (errno)));
3105 close (sockfd);
3106 goto do_exit;
3109 xfree (datadir);
3112 * Set the cache entry for a file. Prompts for the password.
3114 if (cache_push)
3116 struct crypto_s *crypto = NULL;
3117 gpg_error_t rc = init_client_crypto (&crypto);
3119 if (rc)
3121 estatus = EXIT_FAILURE;
3122 goto do_exit;
3125 #ifdef WITH_AGENT
3126 if (use_agent)
3128 rc = agent_set_pinentry_options (crypto->agent);
3129 if (rc)
3131 estatus = EXIT_FAILURE;
3132 goto do_exit;
3135 #endif
3137 for (opt = 0; cache_push[opt]; opt++)
3139 if (!do_cache_push (cache_push[opt], crypto) && !force)
3141 strv_free (cache_push);
3142 startup_failure ();
3143 estatus = EXIT_FAILURE;
3144 cleanup_crypto (&crypto);
3145 goto do_exit;
3148 cleanup_crypto_stage1 (crypto);
3151 #ifdef WITH_AGENT
3152 if (use_agent)
3153 (void) kill_scd (crypto->agent);
3154 #endif
3156 cleanup_crypto (&crypto);
3157 strv_free (cache_push);
3158 log_write (!nofork ? _("Done. Daemonizing...") :
3159 _("Done. Waiting for connections..."));
3162 config_clear_keys ();
3164 if (listen (sockfd, 0) == -1)
3166 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
3167 goto do_exit;
3170 if (!nofork)
3172 switch (fork ())
3174 case -1:
3175 log_write ("fork(): %s",
3176 pwmd_strerror (gpg_error_from_errno (errno)));
3177 goto do_exit;
3178 case 0:
3179 close (0);
3180 close (1);
3181 close (2);
3182 setsid ();
3183 break;
3184 default:
3185 _exit (EXIT_SUCCESS);
3189 (void)test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 1,
3190 mode, 0);
3191 cmdline = 0;
3192 pthread_key_create (&thread_name_key, free_key);
3193 pthread_setspecific (thread_name_key, str_dup ("main"));
3194 estatus = server_loop (sockfd, &socketpath);
3196 do_exit:
3197 if (socketpath && do_unlink)
3199 unlink (socketpath);
3200 xfree (socketpath);
3203 xfree (socketarg);
3204 #ifdef WITH_GNUTLS
3205 gnutls_global_deinit ();
3206 xfree (invoking_tls);
3207 #endif
3208 if (rcfile_tid)
3210 #ifdef HAVE_PTHREAD_CANCEL
3211 pthread_cancel (rcfile_tid);
3212 #else
3213 pthread_kill (rcfile_tid, SIGUSR2);
3214 pthread_cond_signal (&rcfile_cond);
3215 #endif
3216 pthread_join (rcfile_tid, NULL);
3219 pthread_cond_destroy (&rcfile_cond);
3220 pthread_mutex_destroy (&rcfile_mutex);
3221 pthread_key_delete (last_error_key);
3222 #ifndef HAVE_PTHREAD_CANCEL
3223 pthread_key_delete (signal_thread_key);
3224 #endif
3226 if (global_config)
3227 config_free (global_config);
3229 xfree (rcfile);
3230 xfree (home_directory);
3231 xfree (homedir);
3232 xmlCleanupParser ();
3233 xmlCleanupGlobals ();
3235 if (pidfile)
3236 unlink (pidfile);
3237 xfree (pidfile);
3239 if (estatus == EXIT_SUCCESS && !terminate)
3240 log_write (_("pwmd exiting normally"));
3242 pthread_key_delete (thread_name_key);
3243 closelog ();
3244 #if defined(DEBUG) && !defined(MEM_DEBUG)
3245 xdump ();
3246 #endif
3248 if (log_fd != -1)
3249 close (log_fd);
3251 exit (estatus);