Add SAVE --ask.
[pwmd.git] / src / pwmd.c
blobf82c01367fe85033abf864ce1699729f4cc89720
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 int exists;
263 char *tmp;
264 char **invoking_orig = config_get_list_param (global_config, "global",
265 "invoking_user", &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 log_write (_("reloading configuration file '%s'"), rcfile);
306 config = config_parse (rcfile, 1);
307 if (config)
309 config_free (global_config);
310 global_config = config;
311 setup_logging ();
312 cache_push_from_rcfile ();
313 config_clear_keys ();
316 tmp = strv_join (",", invoking_orig);
317 strv_free (invoking_orig);
318 config_set_list_param (&global_config, "global", "invoking_user", tmp);
319 xfree (tmp);
321 disable_list_and_dump = !disable_list_and_dump ? b : 1;
322 config_set_bool_param (&global_config, "global", "require_save_key",
323 require_save_key ? "true" : "false");
324 #ifdef WITH_GNUTLS
325 if (config_get_bool_param (global_config, "global", "tcp_require_key",
326 &exists) && exists)
327 tcp_require_key = 1;
329 config_set_bool_param (&global_config, "global", "tcp_require_key",
330 tcp_require_key ? "true" : "false");
331 #endif
333 if (allowed_users)
335 int n, t = slist_length (allowed_users);
337 for (n = 0; n < t; n++)
339 struct allowed_users_s *allowed;
340 char *tmp;
342 allowed = slist_nth_data (allowed_users, n);
343 tmp = strv_join (",", allowed->users);
344 config_set_list_param (&global_config, allowed->section,
345 "allowed", tmp);
346 xfree (tmp);
347 xfree (allowed->section);
348 strv_free (allowed->users);
349 xfree (allowed);
352 slist_free (allowed_users);
355 #ifdef WITH_GNUTLS
356 /* Kill existing listening threads since the configured listening
357 * protocols may have changed. */
358 start_stop_tls (1);
359 start_stop_tls (0);
360 #endif
363 pthread_cleanup_pop (1);
364 return NULL;
367 gpg_error_t
368 send_error (assuan_context_t ctx, gpg_error_t e)
370 struct client_s *client = assuan_get_pointer (ctx);
372 if (gpg_err_source (e) == GPG_ERR_SOURCE_UNKNOWN)
373 e = gpg_error (e);
375 if (client)
376 client->last_rc = e;
378 if (!e)
379 return assuan_process_done (ctx, 0);
381 if (!ctx)
383 log_write ("ERR %i: %s", e, pwmd_strerror (e));
384 return e;
387 if (client && client->xml_error)
389 log_write ("%s", client->xml_error->message);
390 xfree (client->last_error);
391 client->last_error = NULL;
392 if (client->xml_error->message)
393 client->last_error = str_dup (client->xml_error->message);
395 e = assuan_process_done (ctx,
396 assuan_set_error (ctx, e,
397 client->xml_error->message ? client->xml_error->message : NULL));
398 xmlResetLastError ();
399 xmlResetError (client->xml_error);
400 xfree (client->xml_error);
401 client->xml_error = NULL;
402 return e;
405 return assuan_process_done (ctx,
406 assuan_set_error (ctx, e, pwmd_strerror (e)));
410 assuan_log_cb (assuan_context_t ctx, void *data, unsigned cat,
411 const char *msg)
413 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
414 int i, t;
415 int match = 0;
417 pthread_mutex_lock (&m);
418 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock, &m);
419 t = strv_length (debug_level);
421 for (i = 0; i < t; i++)
423 if (!strcasecmp (debug_level[i], (char *) "init")
424 && cat == ASSUAN_LOG_INIT)
426 match = 1;
427 break;
430 if (!strcasecmp (debug_level[i], (char *) "ctx")
431 && cat == ASSUAN_LOG_CTX)
433 match = 1;
434 break;
437 if (!strcasecmp (debug_level[i], (char *) "engine")
438 && cat == ASSUAN_LOG_ENGINE)
440 match = 1;
441 break;
444 if (!strcasecmp (debug_level[i], (char *) "data")
445 && cat == ASSUAN_LOG_DATA)
447 match = 1;
448 break;
451 if (!strcasecmp (debug_level[i], (char *) "sysio")
452 && cat == ASSUAN_LOG_SYSIO)
454 match = 1;
455 break;
458 if (!strcasecmp (debug_level[i], (char *) "control")
459 && cat == ASSUAN_LOG_CONTROL)
461 match = 1;
462 break;
466 if (match && msg)
468 if (logfile)
470 int fd;
472 if ((fd =
473 open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600)) == -1)
474 warn ("%s", logfile);
475 else
477 pthread_cleanup_push (cleanup_fd_cb, &fd);
478 write (fd, msg, strlen (msg));
479 pthread_cleanup_pop (1);
483 if (nofork)
485 fprintf (stderr, "%s%s", data ? (char *) data : "", msg);
486 fflush (stderr);
490 pthread_cleanup_pop (1);
491 return match;
494 void
495 log_write (const char *fmt, ...)
497 char *args;
498 va_list ap;
499 time_t now;
500 char buf[255];
501 pthread_t tid = pthread_self ();
502 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
504 if ((!logfile && !isatty (STDERR_FILENO) && !log_syslog) || !fmt)
505 return;
507 pthread_mutex_lock (&m);
508 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock, &m);
510 if (!cmdline && logfile && log_fd == -1)
512 log_fd = open (logfile, O_WRONLY | O_CREAT | O_APPEND, 0600);
513 if (log_fd == -1)
514 warn ("%s", logfile);
517 va_start (ap, fmt);
519 if (str_vasprintf (&args, fmt, ap) != -1)
521 if (cmdline)
523 pthread_cleanup_push (xfree, args);
524 fprintf (stderr, "pwmd: %s\n", args);
525 fflush (stderr);
526 pthread_cleanup_pop (1);
528 else
530 char *name = pthread_getspecific (thread_name_key);
531 char *line;
533 pthread_cleanup_push (xfree, args);
534 snprintf (buf, sizeof (buf), "%s(%p): ", name ? name : _("unknown"),
535 (pthread_t *) tid);
536 name = buf;
538 if (!cmdline && log_syslog && !nofork)
539 syslog (LOG_INFO, "%s%s", name, args);
541 time (&now);
542 struct tm *tm = localtime (&now);
543 char tbuf[21];
544 strftime (tbuf, sizeof (tbuf), "%b %d %Y %H:%M:%S ", tm);
545 tbuf[sizeof (tbuf) - 1] = 0;
547 if (args[strlen (args) - 1] == '\n')
548 args[strlen (args) - 1] = 0;
550 line = str_asprintf ("%s %i %s%s\n", tbuf, getpid (), name,
551 args);
552 pthread_cleanup_pop (1);
553 if (line)
555 pthread_cleanup_push (xfree, line);
556 if (logfile && log_fd != -1)
558 write (log_fd, line, strlen (line));
559 fsync (log_fd);
562 if (nofork)
564 fprintf (stdout, "%s", line);
565 fflush (stdout);
568 pthread_cleanup_pop (1);
573 va_end (ap);
574 pthread_cleanup_pop (0);
576 if (log_fd != -1 && config_get_boolean (NULL, "log_keepopen") <= 0)
578 close(log_fd);
579 log_fd = -1;
582 pthread_mutex_unlock (&m);
585 static gpg_error_t
586 setup_crypto ()
588 gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
590 if (!gcry_check_version (GCRYPT_VERSION))
592 fprintf (stderr, _("gcry_check_version(): Incompatible libgcrypt. "
593 "Wanted %s, got %s.\n"), GCRYPT_VERSION,
594 gcry_check_version (NULL));
595 return GPG_ERR_UNKNOWN_VERSION;
598 gcry_set_allocation_handler (xmalloc, xmalloc, NULL, xrealloc, xfree);
599 return 0;
602 gpg_error_t
603 do_validate_peer (assuan_context_t ctx, const char *section,
604 assuan_peercred_t * peer)
606 char **users;
607 int allowed = 0;
608 gpg_error_t rc;
609 struct client_s *client = assuan_get_pointer (ctx);
611 if (!client)
612 return GPG_ERR_EACCES;
614 #ifdef WITH_GNUTLS
615 if (client->thd->remote)
616 return tls_validate_access (client, section);
617 #endif
619 rc = assuan_get_peercred (ctx, peer);
620 if (rc)
621 return rc;
623 users = config_get_list (section, "allowed");
624 if (users)
626 for (char **p = users; *p; p++)
628 rc = acl_check_common(client, *p, (*peer)->uid, (*peer)->gid,
629 &allowed);
632 strv_free (users);
635 return allowed ? 0 : rc ? rc : GPG_ERR_EACCES;
638 /* Test if uid is a member of group 'name'. Invert when 'not' is true. */
639 #ifdef HAVE_GETGRNAM_R
640 static gpg_error_t
641 acl_check_group (const char *name, uid_t uid, gid_t gid, int not, int *allowed)
643 char *buf;
644 struct group gr, *gresult;
645 size_t len = sysconf (_SC_GETGR_R_SIZE_MAX);
647 if (len == -1)
648 len = 16384;
650 buf = xmalloc (len);
651 if (!buf)
652 return GPG_ERR_ENOMEM;
654 if (!getgrnam_r (name, &gr, buf, len, &gresult) && gresult)
656 if (gresult->gr_gid == gid)
658 xfree (buf);
659 *allowed = !not;
660 return 0;
663 len = sysconf (_SC_GETPW_R_SIZE_MAX);
664 if (len == -1)
665 len = 16384;
667 for (char **t = gresult->gr_mem; *t; t++)
669 char *tbuf;
670 struct passwd pw;
671 struct passwd *result = get_pwd_struct (*t, 0, &pw, &tbuf);
673 if (result && result->pw_uid == uid)
675 xfree (tbuf);
676 *allowed = !not;
677 break;
680 xfree (tbuf);
683 xfree (buf);
684 return 0;
687 xfree (buf);
688 return GPG_ERR_EACCES;
690 #else
691 static gpg_error_t
692 acl_check_group (const char *name, uid_t uid, gid_t gid, int not, int *allowed)
694 struct group *gresult;
696 gresult = getgrnam (name);
697 if (gresult && gresult->gr_gid == gid)
699 *allowed = !not;
700 return 0;
703 for (char **t = gresult->gr_mem; *t; t++)
705 char *buf;
706 struct passwd pw;
707 struct passwd *result = get_pwd_struct (*t, 0, &pw, &buf);
709 if (result && result->pw_uid == uid)
711 xfree (buf);
712 *allowed = !not;
713 break;
716 xfree (buf);
719 return 0;
721 #endif
723 gpg_error_t
724 peer_is_invoker(struct client_s *client)
726 struct invoking_user_s *user;
727 int allowed = 0;
729 if (client->thd->state == CLIENT_STATE_UNKNOWN)
730 return GPG_ERR_EACCES;
732 for (user = invoking_users; user; user = user->next)
734 #ifdef WITH_GNUTLS
735 if (client->thd->remote)
737 if (user->type == INVOKING_TLS
738 && !strcmp(client->thd->tls->fp, user->id))
739 allowed = user->not ? 0 : 1;
741 continue;
743 #endif
745 if (user->type == INVOKING_GID)
747 gpg_error_t rc = acl_check_group (user->id,
748 client->thd->peer->uid,
749 client->thd->peer->gid,
750 user->not, &allowed);
751 if (rc)
752 return rc;
754 else if (user->type == INVOKING_UID && client->thd->peer->uid == user->uid)
755 allowed = user->not ? 0 : 1;
758 return allowed ? 0 : GPG_ERR_EACCES;
761 #ifdef HAVE_GETGRNAM_R
762 gpg_error_t
763 acl_check_common (struct client_s *client, const char *user, uid_t uid,
764 gid_t gid, int *allowed)
766 int not = 0;
767 int rw = 0;
768 int tls = 0;
770 if (!user || !*user)
771 return 0;
773 if (*user == '-' || *user == '!')
774 not = 1;
776 if (*user == '+') // not implemented yet
777 rw = 1;
779 if (*user == '#') // TLS fingerprint hash
780 tls = 1;
782 if (not || rw || tls)
783 user++;
785 if (tls)
787 #ifdef WITH_GNUTLS
788 if (client->thd->remote)
790 if (!strcasecmp (client->thd->tls->fp, user))
791 *allowed = !not;
794 return 0;
795 #else
796 return 0;
797 #endif
799 #ifdef WITH_GNUTLS
800 else if (client->thd->remote) // Remote client with no TLS in the ACL
801 return 0;
802 #endif
804 if (*user == '@') // all users in group
805 return acl_check_group (user+1, uid, gid, not, allowed);
806 else
808 char *buf;
809 struct passwd pw;
810 struct passwd *pwd = get_pwd_struct (user, 0, &pw, &buf);
812 if (pwd && pwd->pw_uid == uid)
813 *allowed = !not;
815 xfree (buf);
818 return 0;
820 #else
821 gpg_error_t
822 acl_check_common (struct client_s *client, const char *user, uid_t uid,
823 gid_t gid, int *allowed)
825 int not = 0;
826 int rw = 0;
827 int tls = 0;
829 if (!user || !*user)
830 return 0;
832 if (*user == '-' || *user == '!')
833 not = 1;
835 if (*user == '+') // not implemented yet
836 rw = 1;
838 if (*user == '#') // TLS fingerprint hash
839 tls = 1;
841 if (not || rw || tls)
842 user++;
844 if (tls)
846 #ifdef WITH_GNUTLS
847 if (client->thd->remote)
849 if (!strcasecmp (client->thd->tls->fp, user))
850 *allowed = !not;
853 return 0;
854 #else
855 return 0;
856 #endif
859 if (*user == '@') // all users in group
860 return acl_check_group (user+1, uid, gid, not, allowed);
861 else
863 char *buf;
864 struct passwd pw;
865 struct passwd *result = get_pwd_struct (user, 0, &pw, &buf);
867 if (result && result->pw_uid == uid)
868 *allowed = !not;
870 xfree (buf);
873 return 0;
875 #endif
877 static gpg_error_t
878 validate_peer (struct client_s *cl)
880 gpg_error_t rc;
882 #ifdef WITH_GNUTLS
883 if (cl->thd->remote)
884 return tls_validate_access (cl, NULL);
885 #endif
887 MUTEX_LOCK (&cn_mutex);
888 rc = do_validate_peer (cl->ctx, "global", &cl->thd->peer);
889 MUTEX_UNLOCK (&cn_mutex);
890 if (!rc || gpg_err_code (rc) == GPG_ERR_EACCES)
891 log_write ("peer %s: uid=%i, gid=%i, pid=%i",
892 !rc ? _("accepted") : _("rejected"), cl->thd->peer->uid,
893 cl->thd->peer->gid, cl->thd->peer->pid);
894 else if (rc)
895 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
897 return rc;
900 static void
901 xml_error_cb (void *data, xmlErrorPtr e)
903 struct client_s *client = data;
906 * Keep the first reported error as the one to show in the error
907 * description. Reset in send_error().
909 if (client->xml_error)
910 return;
912 client->xml_error = xcalloc (1, sizeof(xmlError));
913 xmlCopyError (e, client->xml_error);
916 static pid_t
917 hook_waitpid (assuan_context_t ctx, pid_t pid, int action,
918 int *status, int options)
920 return waitpid (pid, status, options);
923 static ssize_t
924 hook_read (assuan_context_t ctx, assuan_fd_t fd, void *data, size_t len)
926 #ifdef WITH_GNUTLS
927 struct client_s *client = assuan_get_pointer (ctx);
929 if (client->thd->remote)
930 return tls_read_hook (ctx, (int) fd, data, len);
931 #endif
933 return read ((int) fd, data, len);
936 static ssize_t
937 hook_write (assuan_context_t ctx, assuan_fd_t fd,
938 const void *data, size_t len)
940 #ifdef WITH_GNUTLS
941 struct client_s *client = assuan_get_pointer (ctx);
943 if (client->thd->remote)
944 return tls_write_hook (ctx, (int) fd, data, len);
945 #endif
947 return write ((int) fd, data, len);
950 static int
951 new_connection (struct client_s *cl)
953 gpg_error_t rc;
954 static struct assuan_malloc_hooks mhooks = { xmalloc, xrealloc, xfree };
955 static struct assuan_system_hooks shooks = {
956 ASSUAN_SYSTEM_HOOKS_VERSION,
957 __assuan_usleep,
958 __assuan_pipe,
959 __assuan_close,
960 hook_read,
961 hook_write,
962 //FIXME
963 NULL, //recvmsg
964 NULL, //sendmsg both are used for FD passing
965 __assuan_spawn,
966 hook_waitpid,
967 __assuan_socketpair,
968 __assuan_socket,
969 __assuan_connect
972 #ifdef WITH_GNUTLS
973 if (cl->thd->remote)
975 char *prio = config_get_string ("global", "tls_cipher_suite");
977 cl->thd->timeout = config_get_integer ("global", "tls_timeout");
978 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
979 return 0;
981 cl->thd->tls = tls_init (cl->thd->fd, cl->thd->timeout, prio);
982 xfree (prio);
983 if (!cl->thd->tls)
984 return 0;
986 #endif
988 rc = assuan_new_ext (&cl->ctx, GPG_ERR_SOURCE_DEFAULT, &mhooks,
989 debug_level ? assuan_log_cb : NULL, NULL);
990 if (rc)
991 goto fail;
993 assuan_ctx_set_system_hooks (cl->ctx, &shooks);
994 rc = assuan_init_socket_server (cl->ctx, cl->thd->fd, 2);
995 if (rc)
996 goto fail;
998 assuan_set_pointer (cl->ctx, cl);
999 assuan_set_hello_line (cl->ctx, PACKAGE_STRING);
1000 rc = register_commands (cl->ctx);
1001 if (rc)
1002 goto fail;
1004 rc = assuan_accept (cl->ctx);
1005 if (rc)
1006 goto fail;
1008 rc = validate_peer (cl);
1009 /* May not be implemented on all platforms. */
1010 if (rc && gpg_err_code (rc) != GPG_ERR_ASS_GENERAL)
1011 goto fail;
1013 MUTEX_LOCK (&cn_mutex);
1014 cl->thd->state = CLIENT_STATE_INIT;
1015 MUTEX_UNLOCK (&cn_mutex);
1016 rc = init_client_crypto (&cl->crypto);
1017 if (rc)
1018 goto fail;
1020 #ifdef WITH_AGENT
1021 if (use_agent)
1022 cl->crypto->agent->client_ctx = cl->ctx;
1023 #endif
1025 cl->crypto->client_ctx = cl->ctx;
1026 cl->lock_timeout = config_get_integer ("global", "lock_timeout");
1027 xmlSetStructuredErrorFunc (cl, xml_error_cb);
1028 return 1;
1030 fail:
1031 log_write ("%s", pwmd_strerror (rc));
1032 return 0;
1036 * This is called after a client_thread() terminates. Set with
1037 * pthread_cleanup_push().
1039 static void
1040 cleanup_cb (void *arg)
1042 struct client_thread_s *cn = arg;
1043 struct client_s *cl = cn->cl;
1045 MUTEX_LOCK (&cn_mutex);
1046 cn_thread_list = slist_remove (cn_thread_list, cn);
1047 MUTEX_UNLOCK (&cn_mutex);
1049 if (cl)
1051 cleanup_client (cl);
1052 if (cl->xml_error)
1053 xmlResetError (cl->xml_error);
1055 xfree (cl->xml_error);
1057 #ifdef WITH_GNUTLS
1058 if (cn->tls)
1060 gnutls_deinit (cn->tls->ses);
1061 xfree (cn->tls->fp);
1062 xfree (cn->tls);
1064 #endif
1066 if (!cn->atfork && cl->ctx)
1067 assuan_release (cl->ctx);
1068 else if (!cn->atfork && cl->thd && cl->thd->fd != -1)
1069 close (cl->thd->fd);
1071 if (cl->crypto)
1072 cleanup_crypto (&cl->crypto);
1074 pinentry_free_opts (&cl->pinentry_opts);
1075 xfree (cl);
1077 else
1079 if (cn->fd != -1)
1080 close (cn->fd);
1083 while (cn->msg_queue)
1085 struct status_msg_s *msg = cn->msg_queue;
1087 cn->msg_queue = msg->next;
1088 xfree (msg->line);
1089 xfree (msg);
1092 if (!cn->atfork && cn->status_msg_pipe[0] != -1)
1093 close (cn->status_msg_pipe[0]);
1095 if (!cn->atfork && cn->status_msg_pipe[1] != -1)
1096 close (cn->status_msg_pipe[1]);
1098 pthread_mutex_destroy (&cn->status_mutex);
1100 if (!cn->atfork)
1102 log_write (_("exiting, fd=%i"), cn->fd);
1103 send_status_all (STATUS_CLIENTS, NULL);
1106 xfree (cn->name);
1107 #ifdef WITH_GNUTLS
1108 xfree (cn->peeraddr);
1109 #endif
1110 xfree (cn);
1111 pthread_cond_signal (&quit_cond);
1114 void
1115 cleanup_all_clients (int atfork)
1117 /* This function may be called from pthread_atfork() which requires
1118 reinitialization. */
1119 if (atfork)
1121 pthread_mutexattr_t attr;
1123 pthread_mutexattr_init (&attr);
1124 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
1125 pthread_mutex_init (&cn_mutex, &attr);
1126 pthread_mutexattr_destroy (&attr);
1127 cache_mutex_init ();
1130 MUTEX_LOCK (&cn_mutex);
1132 while (slist_length (cn_thread_list))
1134 struct client_thread_s *thd = slist_nth_data (cn_thread_list, 0);
1136 thd->atfork = atfork;
1137 cleanup_cb (thd);
1140 exiting = 1;
1141 MUTEX_UNLOCK (&cn_mutex);
1142 cache_deinit (atfork);
1145 static gpg_error_t
1146 send_msg_queue (struct client_thread_s *thd)
1148 MUTEX_LOCK (&thd->status_mutex);
1149 gpg_error_t rc = 0;
1150 char c;
1152 read (thd->status_msg_pipe[0], &c, 1);
1153 thd->wrote_status = 0;
1155 while (thd->msg_queue)
1157 struct status_msg_s *msg = thd->msg_queue;
1159 thd->msg_queue = thd->msg_queue->next;
1160 MUTEX_UNLOCK (&thd->status_mutex);
1161 rc = send_status (thd->cl->ctx, msg->s, msg->line);
1162 MUTEX_LOCK (&thd->status_mutex);
1163 xfree (msg->line);
1164 xfree (msg);
1166 if (rc)
1167 break;
1170 MUTEX_UNLOCK (&thd->status_mutex);
1171 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1172 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
1174 return rc;
1177 static void *
1178 client_thread (void *data)
1180 struct client_thread_s *thd = data;
1181 struct client_s *cl = xcalloc (1, sizeof (struct client_s));
1183 #ifdef HAVE_PR_SET_NAME
1184 prctl (PR_SET_NAME, "client");
1185 #endif
1186 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1188 if (!cl)
1190 log_write ("%s(%i): %s", __FILE__, __LINE__,
1191 pwmd_strerror (GPG_ERR_ENOMEM));
1192 return NULL;
1195 MUTEX_LOCK (&cn_mutex);
1196 pthread_cleanup_push (cleanup_cb, thd);
1197 thd->cl = cl;
1198 cl->thd = thd;
1199 MUTEX_UNLOCK (&cn_mutex);
1201 if (new_connection (cl))
1203 int finished = 0;
1204 gpg_error_t rc;
1206 send_status_all (STATUS_CLIENTS, NULL);
1207 rc = send_status (cl->ctx, STATUS_CACHE, NULL);
1208 if (rc)
1210 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
1211 finished = 1;
1214 while (!finished)
1216 fd_set rfds;
1217 int n;
1218 int eof;
1220 FD_ZERO (&rfds);
1221 FD_SET (thd->fd, &rfds);
1222 FD_SET (thd->status_msg_pipe[0], &rfds);
1223 n = thd->fd > thd->status_msg_pipe[0]
1224 ? thd->fd : thd->status_msg_pipe[0];
1226 n = select (n + 1, &rfds, NULL, NULL, NULL);
1227 if (n == -1)
1229 log_write ("%s", strerror (errno));
1230 break;
1233 if (FD_ISSET (thd->status_msg_pipe[0], &rfds))
1235 rc = send_msg_queue (thd);
1236 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1237 break;
1240 if (!FD_ISSET (thd->fd, &rfds))
1241 continue;
1243 rc = assuan_process_next (cl->ctx, &eof);
1244 if (rc || eof)
1246 if (gpg_err_code (rc) == GPG_ERR_EOF || eof)
1247 break;
1249 log_write ("assuan_process_next(): rc=%i %s", rc,
1250 pwmd_strerror (rc));
1251 if (rc == gpg_error (GPG_ERR_ETIMEDOUT))
1252 break;
1254 rc = send_error (cl->ctx, rc);
1255 if (rc)
1257 log_write ("assuan_process_done(): rc=%i %s", rc,
1258 pwmd_strerror (rc));
1259 break;
1263 /* Since the msg queue pipe fd's are non-blocking, check for
1264 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1265 * client has already disconnected and will be converted to
1266 * GPG_ERR_EOF during assuan_process_next().
1268 rc = send_msg_queue (thd);
1269 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1270 break;
1274 /* Don't do pthread_exit() here because any set pthread_cleanup_push
1275 * functions would be called after a command failed but then the client
1276 * exited normally which may lead to a double free. */
1277 pthread_cleanup_pop (1);
1278 return NULL;
1281 static int
1282 xml_import (const char *filename, const char *outfile,
1283 const char *keygrip, const char *sign_keygrip,
1284 const char *keyfile, int no_passphrase, const char *cipher,
1285 const char *params, uint64_t iterations)
1287 xmlDocPtr doc;
1288 int fd;
1289 struct stat st;
1290 int len;
1291 xmlChar *xmlbuf;
1292 xmlChar *xml;
1293 gpg_error_t rc;
1294 struct crypto_s *crypto = NULL;
1295 void *key = NULL;
1296 size_t keylen = 0;
1297 int algo = cipher ? cipher_string_to_gcrypt ((char *) cipher) :
1298 GCRY_CIPHER_AES256;
1300 if (algo == -1)
1302 log_write ("ERR %i: %s", gpg_error (GPG_ERR_CIPHER_ALGO),
1303 pwmd_strerror (GPG_ERR_CIPHER_ALGO));
1304 return 0;
1307 if (stat (filename, &st) == -1)
1309 log_write ("%s: %s", filename,
1310 pwmd_strerror (gpg_error_from_errno (errno)));
1311 return 0;
1314 rc = init_client_crypto (&crypto);
1315 if (rc)
1316 return 0;
1318 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
1319 crypto->save.hdr.flags = set_cipher_flag (crypto->save.hdr.flags, algo);
1320 log_write (_("Importing XML from '%s'. Output will be written to '%s' ..."),
1321 filename, outfile);
1323 if ((fd = open (filename, O_RDONLY)) == -1)
1325 log_write ("%s: %s", filename,
1326 pwmd_strerror (gpg_error_from_errno (errno)));
1327 goto fail;
1330 if ((xmlbuf = xmalloc (st.st_size + 1)) == NULL)
1332 close (fd);
1333 log_write ("%s(%i): %s", __FILE__, __LINE__,
1334 pwmd_strerror (GPG_ERR_ENOMEM));
1335 goto fail;
1338 if (read (fd, xmlbuf, st.st_size) == -1)
1340 rc = gpg_error_from_errno (errno);
1341 close (fd);
1342 log_write ("%s: %s", filename, pwmd_strerror (rc));
1343 goto fail;
1346 close (fd);
1347 xmlbuf[st.st_size] = 0;
1349 * Make sure the document validates.
1351 if ((doc = xmlReadDoc (xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS)) == NULL)
1353 log_write ("xmlReadDoc() failed");
1354 xfree (xmlbuf);
1355 goto fail;
1358 xfree (xmlbuf);
1359 xmlNodePtr n = xmlDocGetRootElement (doc);
1360 if (n && !xmlStrEqual (n->name, (xmlChar *) "pwmd"))
1362 log_write (_("Could not find root \"pwmd\" element."));
1363 rc = GPG_ERR_BAD_DATA;
1366 if (!rc)
1367 rc = validate_import (NULL, n ? n->children : n);
1369 if (rc)
1371 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1372 xmlFreeDoc (doc);
1373 goto fail;
1376 xmlDocDumpMemory (doc, &xml, &len);
1377 xmlFreeDoc (doc);
1378 crypto->save.s2k_count = iterations;
1379 crypto->save.hdr.s2k_count = iterations;
1380 if (!use_agent)
1382 rc = export_common (NULL, 0, crypto, xml, len, outfile, keyfile, &key,
1383 &keylen, 0, 0, no_passphrase);
1384 if (!rc)
1385 log_write (_("Success!"));
1387 #ifdef WITH_AGENT
1388 else
1390 rc = agent_set_pinentry_options (crypto->agent);
1391 if (!rc)
1392 rc = agent_export_common (crypto, keygrip, sign_keygrip, no_passphrase,
1393 xml, len, outfile, params, keyfile);
1395 #endif
1397 gcry_free (key);
1398 xmlFree (xml);
1399 if (rc)
1401 send_error (NULL, rc);
1402 goto fail;
1405 cleanup_crypto (&crypto);
1406 return 1;
1408 fail:
1409 cleanup_crypto (&crypto);
1410 return 0;
1413 static int
1414 do_cache_push (const char *filename, struct crypto_s *crypto)
1416 unsigned char md5file[16];
1417 gpg_error_t rc;
1418 void *key = NULL;
1419 size_t keylen = 0;
1420 xmlDocPtr doc;
1421 struct cache_data_s *cdata;
1422 unsigned char *crc;
1423 size_t len;
1425 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1426 filename);
1428 if (valid_filename (filename) == 0)
1430 log_write (_("%s: Invalid characters in filename"), filename);
1431 return 0;
1434 rc = decrypt_common (NULL, 0, crypto, filename, &key, &keylen, NULL, NULL);
1435 if (rc)
1436 return 0;
1438 rc = parse_doc ((char *) crypto->plaintext, crypto->plaintext_len, &doc);
1439 if (rc)
1441 log_write ("%s", pwmd_strerror (rc));
1442 xfree (key);
1443 return 0;
1446 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
1447 cdata = xcalloc (1, sizeof (struct cache_data_s));
1448 if (!cdata)
1450 xmlFreeDoc (doc);
1451 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM));
1452 xfree (key);
1453 return 0;
1456 rc = get_checksum (filename, &crc, &len);
1457 if (rc)
1459 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1460 xmlFreeDoc (doc);
1461 free_cache_data_once (cdata);
1462 xfree (key);
1463 return 0;
1466 cdata->crc = crc;
1467 rc = encrypt_xml (NULL, cache_key, cache_keysize, GCRY_CIPHER_AES,
1468 crypto->plaintext, crypto->plaintext_len, &cdata->doc,
1469 &cdata->doclen, &cache_iv, &cache_blocksize);
1470 if (!rc && !IS_PKI (crypto))
1472 cdata->key = key;
1473 cdata->keylen = keylen;
1475 else
1476 xfree (key);
1478 if (rc)
1480 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1481 xmlFreeDoc (doc);
1482 free_cache_data_once (cdata);
1483 return 0;
1486 #ifdef WITH_AGENT
1487 if (use_agent && IS_PKI (crypto))
1489 gcry_sexp_build ((gcry_sexp_t *) & cdata->pubkey, NULL, "%S",
1490 crypto->pkey_sexp);
1491 gcry_sexp_build ((gcry_sexp_t *) & cdata->sigkey, NULL, "%S",
1492 crypto->sigpkey_sexp);
1494 #endif
1496 int timeout = config_get_integer (filename, "cache_timeout");
1497 cache_add_file (md5file, crypto->grip, cdata, timeout);
1498 log_write (_("Successfully added '%s' to the cache."), filename);
1499 return 1;
1502 static gpg_error_t
1503 init_client (int fd, const char *addr)
1505 gpg_error_t rc = 0;
1506 struct client_thread_s *new = xcalloc (1, sizeof (struct client_thread_s));
1508 if (!new)
1510 close (fd);
1511 return GPG_ERR_ENOMEM;
1514 MUTEX_LOCK (&cn_mutex);
1515 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
1517 if (pipe (new->status_msg_pipe) == -1)
1518 rc = gpg_error_from_errno (errno);
1520 if (!rc)
1522 if (fcntl (new->status_msg_pipe[0], F_SETFL, O_NONBLOCK) == -1)
1523 rc = gpg_error_from_errno (errno);
1525 if (!rc)
1526 if (fcntl (new->status_msg_pipe[1], F_SETFL, O_NONBLOCK) == -1)
1527 rc = gpg_error_from_errno (errno);
1529 pthread_mutex_init (&new->status_mutex, NULL);
1532 if (!rc)
1534 #ifdef WITH_GNUTLS
1535 new->remote = addr ? 1 : 0;
1536 #endif
1537 new->fd = fd;
1538 rc = create_thread (client_thread, new, &new->tid, 1);
1539 if (rc)
1541 close (new->status_msg_pipe[0]);
1542 close (new->status_msg_pipe[1]);
1543 pthread_mutex_destroy (&new->status_mutex);
1547 if (!rc)
1549 struct slist_s *list = slist_append (cn_thread_list, new);
1551 if (list)
1553 cn_thread_list = list;
1554 if (addr)
1556 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1557 (pthread_t *) new->tid, fd, addr);
1558 #ifdef WITH_GNUTLS
1559 new->peeraddr = str_dup (addr);
1560 #endif
1562 else
1563 log_write (_("new connection: tid=%p, fd=%i"),
1564 (pthread_t *) new->tid, fd);
1566 else
1567 rc = GPG_ERR_ENOMEM;
1570 pthread_cleanup_pop (1);
1572 if (rc)
1574 xfree (new);
1575 close (fd);
1576 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1577 pwmd_strerror (rc));
1579 return rc;
1582 static void*
1583 keepalive_thread (void *arg)
1585 #ifndef HAVE_PTHREAD_CANCEL
1586 int *n = xmalloc (sizeof (int));
1588 *n = 0;
1589 pthread_setspecific (signal_thread_key, n);
1590 INIT_THREAD_SIGNAL;
1591 #endif
1593 #ifdef HAVE_PR_SET_NAME
1594 prctl (PR_SET_NAME, "keepalive");
1595 #endif
1596 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1598 for (;;)
1600 int n = config_get_integer ("global", "keepalive_interval");
1601 struct timeval tv = { n, 0 };
1602 #ifndef HAVE_PTHREAD_CANCEL
1603 int *sigusr2;
1605 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1606 if (*sigusr2)
1607 break;
1608 #endif
1610 send_status_all (STATUS_KEEPALIVE, NULL);
1611 select (0, NULL, NULL, NULL, &tv);
1614 return NULL;
1617 #ifdef WITH_GNUTLS
1618 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1619 static void *
1620 get_in_addr (struct sockaddr *sa)
1622 if (sa->sa_family == AF_INET)
1623 return &(((struct sockaddr_in *) sa)->sin_addr);
1625 return &(((struct sockaddr_in6 *) sa)->sin6_addr);
1628 static void *
1629 tcp_accept_thread (void *arg)
1631 int sockfd = *(int *) arg;
1632 #ifndef HAVE_PTHREAD_CANCEL
1633 int *n = xmalloc (sizeof (int));
1635 *n = 0;
1636 pthread_setspecific (signal_thread_key, n);
1637 INIT_THREAD_SIGNAL;
1638 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1639 #endif
1641 #ifdef HAVE_PR_SET_NAME
1642 prctl (PR_SET_NAME, "tcp_accept");
1643 #endif
1644 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1646 for (;;)
1648 struct sockaddr_storage raddr;
1649 socklen_t slen = sizeof (raddr);
1650 int fd;
1651 unsigned long n;
1652 char s[INET6_ADDRSTRLEN];
1653 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1654 #ifndef HAVE_PTHREAD_CANCEL
1655 int *sigusr2;
1657 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1658 if (*sigusr2)
1659 break;
1660 #endif
1662 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1663 if (fd == -1)
1665 if (errno == EMFILE || errno == ENFILE)
1666 log_write ("accept(): %s",
1667 pwmd_strerror (gpg_error_from_errno (errno)));
1668 else if (errno != EAGAIN)
1670 if (!quit) // probably EBADF
1671 log_write ("accept(): %s", strerror (errno));
1673 break;
1676 #ifndef HAVE_PTHREAD_CANCEL
1677 select (0, NULL, NULL, NULL, &tv);
1678 #endif
1679 continue;
1682 if (quit)
1684 close (fd);
1685 break;
1688 inet_ntop (raddr.ss_family, get_in_addr ((struct sockaddr *) &raddr),
1689 s, sizeof s);
1690 (void) init_client (fd, s);
1691 n = config_get_integer ("global", "tcp_wait");
1692 if (n > 0)
1694 tv.tv_sec = (n * 100000) / 100000;
1695 tv.tv_usec = (n * 100000) % 100000;
1696 select (0, NULL, NULL, NULL, &tv);
1700 return NULL;
1703 static int
1704 start_stop_tls_with_protocol (int ipv6, int term)
1706 struct addrinfo hints, *servinfo, *p;
1707 int port = config_get_integer ("global", "tcp_port");
1708 char buf[7];
1709 int n;
1710 gpg_error_t rc;
1711 int *fd = ipv6 ? &tls6_fd : &tls_fd;
1713 if (term || config_get_boolean ("global", "enable_tcp") == 0)
1715 if (tls6_fd != -1)
1717 if (spawned_tls6)
1719 #ifdef HAVE_PTHREAD_CANCEL
1720 pthread_cancel (tls6_tid);
1721 #else
1722 pthread_kill (tls6_tid, SIGUSR2);
1723 #endif
1724 pthread_join (tls6_tid, NULL);
1727 shutdown (tls6_fd, SHUT_RDWR);
1728 close (tls6_fd);
1729 tls6_fd = -1;
1730 spawned_tls6 = 0;
1733 if (tls_fd != -1)
1735 if (spawned_tls)
1737 #ifdef HAVE_PTHREAD_CANCEL
1738 pthread_cancel (tls_tid);
1739 #else
1740 pthread_kill (tls_tid, SIGUSR2);
1741 #endif
1742 pthread_join (tls_tid, NULL);
1745 shutdown (tls_fd, SHUT_RDWR);
1746 close (tls_fd);
1747 tls_fd = -1;
1748 spawned_tls = 0;
1751 /* A client may still be connected. */
1752 if (!quit && x509_cred != NULL)
1753 tls_deinit_params ();
1755 return 1;
1758 if ((ipv6 && tls6_fd != -1) || (!ipv6 && tls_fd != -1))
1759 return 1;
1761 memset (&hints, 0, sizeof (hints));
1762 hints.ai_family = ipv6 ? AF_INET6 : AF_INET;
1763 hints.ai_socktype = SOCK_STREAM;
1764 hints.ai_flags = AI_PASSIVE;
1765 snprintf (buf, sizeof (buf), "%i", port);
1767 if ((n = getaddrinfo (NULL, buf, &hints, &servinfo)) == -1)
1769 log_write ("getaddrinfo(): %s", gai_strerror (n));
1770 return 0;
1773 for (n = 0, p = servinfo; p != NULL; p = p->ai_next)
1775 int r = 1;
1777 if ((ipv6 && p->ai_family != AF_INET6)
1778 || (!ipv6 && p->ai_family != AF_INET))
1779 continue;
1781 if ((*fd = socket (p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
1783 log_write ("socket(): %s", strerror (errno));
1784 continue;
1787 if (setsockopt (*fd, SOL_SOCKET, SO_REUSEADDR, &r, sizeof (int)) == -1)
1789 log_write ("setsockopt(): %s",
1790 pwmd_strerror (gpg_error_from_errno (errno)));
1791 freeaddrinfo (servinfo);
1792 goto fail;
1795 if (bind (*fd, p->ai_addr, p->ai_addrlen) == -1)
1797 close (*fd);
1798 log_write ("bind(): %s",
1799 pwmd_strerror (gpg_error_from_errno (errno)));
1800 continue;
1803 n++;
1804 break;
1807 freeaddrinfo (servinfo);
1809 if (!n)
1810 goto fail;
1812 #if HAVE_DECL_SO_BINDTODEVICE != 0
1813 char *tmp = config_get_string ("global", "tcp_interface");
1814 if (tmp && setsockopt (*fd, SOL_SOCKET, SO_BINDTODEVICE, tmp,
1815 strlen (tmp)) == -1)
1817 log_write ("setsockopt(): %s",
1818 pwmd_strerror (gpg_error_from_errno (errno)));
1819 xfree (tmp);
1820 goto fail;
1823 xfree (tmp);
1824 #endif
1826 if (x509_cred == NULL)
1828 char *tmp = config_get_string ("global", "tls_dh_level");
1830 rc = tls_init_params (tmp);
1831 xfree (tmp);
1832 if (rc)
1833 goto fail;
1836 if (listen (*fd, 0) == -1)
1838 log_write ("listen(): %s", strerror (errno));
1839 goto fail;
1842 if (ipv6)
1843 rc = create_thread (tcp_accept_thread, fd, &tls6_tid, 0);
1844 else
1845 rc = create_thread (tcp_accept_thread, fd, &tls_tid, 0);
1847 if (rc)
1849 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1850 pwmd_strerror (rc));
1851 goto fail;
1854 if (ipv6)
1855 spawned_tls6 = 1;
1856 else
1857 spawned_tls = 1;
1859 return 1;
1861 fail:
1862 start_stop_tls_with_protocol (0, 1);
1863 if (tls_fd != -1)
1864 close (tls_fd);
1866 if (tls6_fd != -1)
1867 close (tls6_fd);
1869 tls_fd = -1;
1870 tls6_fd = -1;
1871 return 0;
1874 static int
1875 start_stop_tls (int term)
1877 char *s = config_get_string ("global", "tcp_bind");
1878 int b;
1880 if (!s)
1881 return 0;
1883 if (!strcmp (s, "any"))
1885 b = start_stop_tls_with_protocol (0, term);
1886 if (b)
1887 b = start_stop_tls_with_protocol (1, term);
1889 else if (!strcmp (s, "ipv4"))
1890 b = start_stop_tls_with_protocol (0, term);
1891 else if (!strcmp (s, "ipv6"))
1892 b = start_stop_tls_with_protocol (1, term);
1893 else
1894 b = 0;
1896 xfree (s);
1897 return b;
1899 #endif
1901 static void *
1902 accept_thread (void *arg)
1904 int sockfd = *(int *) arg;
1905 #ifndef HAVE_PTHREAD_CANCEL
1906 int *n = xmalloc (sizeof (int));
1908 *n = 0;
1909 pthread_setspecific (signal_thread_key, n);
1910 INIT_THREAD_SIGNAL;
1911 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1912 #endif
1914 #ifdef HAVE_PR_SET_NAME
1915 prctl (PR_SET_NAME, "accept");
1916 #endif
1917 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1919 for (;;)
1921 socklen_t slen = sizeof (struct sockaddr_un);
1922 struct sockaddr_un raddr;
1923 int fd;
1924 #ifndef HAVE_PTHREAD_CANCEL
1925 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1926 int *sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1928 if (*sigusr2)
1929 break;
1930 #endif
1932 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1933 if (fd == -1)
1935 if (errno == EMFILE || errno == ENFILE)
1936 log_write ("accept(): %s",
1937 pwmd_strerror (gpg_error_from_errno (errno)));
1938 else if (errno != EAGAIN)
1940 if (!quit) // probably EBADF
1941 log_write ("accept(): %s",
1942 pwmd_strerror (gpg_error_from_errno (errno)));
1944 break;
1947 #ifndef HAVE_PTHREAD_CANCEL
1948 select (0, NULL, NULL, NULL, &tv);
1949 #endif
1950 continue;
1953 (void) init_client (fd, NULL);
1956 /* Just in case accept() failed for some reason other than EBADF */
1957 quit = 1;
1958 return NULL;
1961 static void *
1962 cache_timer_thread (void *arg)
1964 #ifndef HAVE_PTHREAD_CANCEL
1965 int *n = xmalloc (sizeof (int));
1967 *n = 0;
1968 pthread_setspecific (signal_thread_key, n);
1969 INIT_THREAD_SIGNAL;
1970 #endif
1972 #ifdef HAVE_PR_SET_NAME
1973 prctl (PR_SET_NAME, "cache timer");
1974 #endif
1975 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1977 for (;;)
1979 struct timeval tv = { 1, 0 };
1980 #ifndef HAVE_PTHREAD_CANCEL
1981 int *n;
1983 n = (int *) pthread_getspecific (signal_thread_key);
1984 if (*n)
1985 break;
1986 #endif
1988 select (0, NULL, NULL, NULL, &tv);
1989 cache_adjust_timeout ();
1992 return NULL;
1995 static int
1996 signal_loop (sigset_t sigset)
1998 int done = 0;
1999 int siint = 0;
2003 int sig;
2005 sigwait (&sigset, &sig);
2007 if (sig != SIGQUIT)
2008 log_write (_("caught signal %i (%s)"), sig, strsignal (sig));
2010 switch (sig)
2012 case SIGHUP:
2013 pthread_cond_signal (&rcfile_cond);
2014 break;
2015 case SIGUSR1:
2016 log_write (_("clearing file cache"));
2017 cache_clear (NULL);
2018 send_status_all (STATUS_CACHE, NULL);
2019 break;
2020 case SIGQUIT:
2021 done = 1;
2022 break;
2023 default:
2024 siint = 1;
2025 done = 1;
2026 break;
2029 while (!done);
2031 return siint;
2034 static void
2035 catchsig (int sig)
2037 log_write (_ ("Caught signal %i (%s). Exiting."), sig, strsignal (sig));
2038 #ifdef HAVE_BACKTRACE
2039 BACKTRACE (__FUNCTION__);
2040 #endif
2041 longjmp (jmp, 1);
2044 static void *
2045 waiting_for_exit (void *arg)
2047 int last = 0;
2048 #ifndef HAVE_PTHREAD_CANCEL
2049 int *n = xmalloc (sizeof (int));
2051 *n = 0;
2052 pthread_setspecific (signal_thread_key, n);
2053 INIT_THREAD_SIGNAL;
2054 #endif
2056 #ifdef HAVE_PR_SET_NAME
2057 prctl (PR_SET_NAME, "exiting");
2058 #endif
2059 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
2060 log_write (_("waiting for all clients to disconnect"));
2061 MUTEX_LOCK (&quit_mutex);
2062 pthread_cleanup_push (cleanup_mutex_cb, &quit_mutex);
2064 for (;;)
2066 struct timespec ts;
2067 int n;
2069 MUTEX_LOCK (&cn_mutex);
2070 n = slist_length (cn_thread_list);
2071 MUTEX_UNLOCK (&cn_mutex);
2072 if (!n)
2073 break;
2075 #ifndef HAVE_PTHREAD_CANCEL
2076 int *s = (int *) pthread_getspecific (signal_thread_key);
2077 if (*s)
2078 break;
2079 #endif
2081 if (last != n)
2083 log_write (_("%i clients remain"), n);
2084 last = n;
2087 INIT_TIMESPEC (SIG_TIMEOUT, ts);
2088 pthread_cond_timedwait (&quit_cond, &quit_mutex, &ts);
2091 kill (getpid (), SIGQUIT);
2092 pthread_cleanup_pop (1);
2093 return NULL;
2096 static int
2097 server_loop (int sockfd, char **socketpath)
2099 pthread_t accept_tid;
2100 pthread_t cache_timeout_tid;
2101 int cancel_timeout_thread = 0, cancel_accept_thread = 0;
2102 int cancel_keepalive_thread = 0;
2103 sigset_t sigset;
2104 int n;
2105 int segv = 0;
2106 gpg_error_t rc;
2108 init_commands ();
2109 sigemptyset (&sigset);
2111 /* Termination */
2112 sigaddset (&sigset, SIGTERM);
2113 sigaddset (&sigset, SIGINT);
2115 /* Clears the file cache. */
2116 sigaddset (&sigset, SIGUSR1);
2118 /* Configuration file reloading. */
2119 sigaddset (&sigset, SIGHUP);
2121 /* For exiting cleanly. */
2122 sigaddset (&sigset, SIGQUIT);
2124 #ifndef HAVE_PTHREAD_CANCEL
2126 The socket, cache and rcfile threads use this signal when
2127 pthread_cancel() is unavailable. Prevent the main thread from
2128 catching this signal from another process.
2130 sigaddset (&sigset, SIGUSR2);
2131 #endif
2133 /* When mem.c cannot find a pointer in the list (double free). */
2134 signal (SIGABRT, catchsig);
2135 sigaddset (&sigset, SIGABRT);
2136 sigprocmask (SIG_BLOCK, &sigset, NULL);
2138 #ifndef HAVE_PTHREAD_CANCEL
2139 /* Remove this signal from the watched signals in signal_loop(). */
2140 sigdelset (&sigset, SIGUSR2);
2141 #endif
2143 /* Ignored everywhere. When a client disconnects abnormally this signal
2144 * gets raised. It isn't needed though because client_thread() will check
2145 * for rcs even after the client disconnects. */
2146 signal (SIGPIPE, SIG_IGN);
2148 /* Can show a backtrace of the stack in the log. */
2149 signal (SIGSEGV, catchsig);
2151 #ifdef WITH_GNUTLS
2152 /* Needs to be done after the fork(). */
2153 if (!start_stop_tls (0))
2155 segv = 1;
2156 goto done;
2158 #endif
2160 pthread_mutex_init (&quit_mutex, NULL);
2161 pthread_cond_init (&quit_cond, NULL);
2162 char *p = get_username (getuid());
2163 log_write (_("%s started for user %s"), PACKAGE_STRING, p);
2164 xfree (p);
2166 #ifdef WITH_GNUTLS
2167 if (config_get_boolean ("global", "enable_tcp"))
2168 log_write (_("Listening on %s and TCP port %i"), *socketpath,
2169 config_get_integer ("global", "tcp_port"));
2170 else
2171 log_write (_("Listening on %s"), *socketpath);
2172 #else
2173 log_write (_("Listening on %s"), *socketpath);
2174 #endif
2176 rc = create_thread (keepalive_thread, NULL, &keepalive_tid, 0);
2177 if (rc)
2179 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2180 pwmd_strerror (rc));
2181 goto done;
2184 cancel_keepalive_thread = 1;
2185 rc = create_thread (reload_rcfile_thread, NULL, &rcfile_tid, 0);
2186 if (rc)
2188 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2189 pwmd_strerror (rc));
2190 goto done;
2193 rc = create_thread (cache_timer_thread, NULL, &cache_timeout_tid, 0);
2194 if (rc)
2196 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2197 pwmd_strerror (rc));
2198 goto done;
2201 cancel_timeout_thread = 1;
2202 rc = create_thread (accept_thread, &sockfd, &accept_tid, 0);
2203 if (rc)
2205 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2206 pwmd_strerror (rc));
2207 goto done;
2210 cancel_accept_thread = 1;
2211 if (!setjmp (jmp))
2212 signal_loop (sigset);
2213 else
2214 segv = 1;
2216 done:
2218 * We're out of the main server loop. This happens when a signal was sent
2219 * to terminate the daemon. We'll wait for all clients to disconnect
2220 * before exiting but exit immediately if another termination signal is
2221 * sent.
2223 if (cancel_accept_thread)
2225 #ifdef HAVE_PTHREAD_CANCEL
2226 int n = pthread_cancel (accept_tid);
2227 #else
2228 int n = pthread_kill (accept_tid, SIGUSR2);
2229 #endif
2230 if (!n)
2231 pthread_join (accept_tid, NULL);
2234 #ifdef WITH_GNUTLS
2235 start_stop_tls (1);
2236 #endif
2237 shutdown (sockfd, SHUT_RDWR);
2238 close (sockfd);
2239 unlink (*socketpath);
2240 xfree (*socketpath);
2241 *socketpath = NULL;
2242 MUTEX_LOCK (&cn_mutex);
2243 n = slist_length (cn_thread_list);
2244 MUTEX_UNLOCK (&cn_mutex);
2246 if (n && !segv)
2248 pthread_t tid;
2250 rc = create_thread (waiting_for_exit, NULL, &tid, 0);
2251 if (!rc)
2253 if (signal_loop (sigset))
2255 log_write (_("Received second termination request. Exiting."));
2256 #ifdef HAVE_PTHREAD_CANCEL
2257 pthread_cancel (tid);
2258 #else
2259 pthread_kill (tid, SIGUSR2);
2260 #endif
2261 pthread_join (tid, NULL);
2264 else
2265 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2266 pwmd_strerror (rc));
2269 if (cancel_timeout_thread)
2271 #ifdef HAVE_PTHREAD_CANCEL
2272 pthread_cancel (cache_timeout_tid);
2273 #else
2274 pthread_kill (cache_timeout_tid, SIGUSR2);
2275 #endif
2276 pthread_join (cache_timeout_tid, NULL);
2279 if (cancel_keepalive_thread)
2281 #ifdef HAVE_PTHREAD_CANCEL
2282 pthread_cancel (keepalive_tid);
2283 #else
2284 pthread_kill (keepalive_tid, SIGUSR2);
2285 #endif
2286 pthread_join (keepalive_tid, NULL);
2289 cleanup_all_clients (0);
2290 #ifdef WITH_GNUTLS
2291 start_stop_tls (1);
2292 #endif
2293 deinit_commands ();
2294 pthread_cond_destroy (&quit_cond);
2295 pthread_mutex_destroy (&quit_mutex);
2296 return segv ? EXIT_FAILURE : EXIT_SUCCESS;;
2299 static void
2300 startup_failure ()
2302 log_write (_
2303 ("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
2304 cache_clear (NULL);
2307 /* This is called from cache.c:clear_once(). See
2308 * command.c:clearcache_command() for details about lock checking.
2310 static gpg_error_t
2311 free_cache_data (file_cache_t * cache)
2313 gpg_error_t rc = GPG_ERR_NO_DATA;
2314 int i, t;
2315 struct client_thread_s *found = NULL;
2316 int self = 0;
2318 if (!cache->data)
2319 return 0;
2321 cache_lock ();
2322 MUTEX_LOCK (&cn_mutex);
2323 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
2324 t = slist_length (cn_thread_list);
2326 for (i = 0; i < t; i++)
2328 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2330 if (!thd->cl)
2331 continue;
2333 if (!memcmp (thd->cl->md5file, cache->filename,
2334 sizeof (cache->filename)))
2336 if (pthread_equal (pthread_self (), thd->tid))
2338 found = thd;
2339 self = 1;
2340 continue;
2343 /* Continue trying to find a client who has the same file open and
2344 * also has a lock. */
2345 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0, -1);
2346 if (!rc)
2348 self = 0;
2349 found = thd;
2350 break;
2355 if (self && (!rc || rc == GPG_ERR_NO_DATA))
2356 rc = cache_lock_mutex (found->cl->ctx, found->cl->md5file, -1, 0, -1);
2358 if (exiting || !rc || rc == GPG_ERR_NO_DATA)
2360 free_cache_data_once (cache->data);
2361 cache->data = NULL;
2362 cache->defer_clear = 0;
2363 cache->timeout = -1;
2365 if (found)
2366 cache_unlock_mutex (found->cl->md5file, 0);
2368 rc = 0;
2371 if (rc)
2372 cache->defer_clear = 1;
2374 pthread_cleanup_pop (1);
2375 cache_unlock ();
2376 return rc;
2379 static int
2380 convert_v2_datafile (const char *filename, const char *cipher,
2381 const char *keyfile, const char *keygrip,
2382 const char *sign_keygrip, int nopass,
2383 const char *outfile, const char *keyparam,
2384 uint64_t iterations)
2386 gpg_error_t rc;
2387 void *data = NULL;
2388 size_t datalen;
2389 struct crypto_s *crypto = NULL;
2390 uint16_t ver;
2391 int algo;
2392 void *key = NULL;
2393 size_t keylen = 0;
2395 if (outfile[0] == '-' && outfile[1] == 0)
2396 outfile = NULL;
2398 log_write (_("Converting version 2 data file \"%s\" ..."), filename);
2399 if (access (filename, R_OK) == -1)
2401 log_write ("%s: %s", filename,
2402 pwmd_strerror (gpg_error_from_errno (errno)));
2403 return 0;
2406 if (keyfile)
2408 log_write (_("Using passphrase file \"%s\" for decryption ..."),
2409 keyfile);
2410 if (access (keyfile, R_OK) == -1)
2412 log_write ("%s: %s", keyfile,
2413 pwmd_strerror (gpg_error_from_errno (errno)));
2414 return 0;
2418 rc = read_v2_datafile (filename, keyfile, &data, &datalen, &ver, &algo);
2419 if (rc)
2421 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2422 return 0;
2425 if (cipher)
2427 algo = cipher_string_to_gcrypt (cipher);
2428 if (algo == -1)
2430 rc = GPG_ERR_CIPHER_ALGO;
2431 goto fail;
2435 if (ver < 0x212)
2437 xmlDocPtr doc;
2439 rc = parse_doc (data, datalen, &doc);
2440 if (rc)
2441 goto fail;
2443 rc = convert_pre_212_elements (doc);
2444 gcry_free (data);
2445 data = NULL;
2446 if (!rc)
2448 xmlDocDumpFormatMemory (doc, (xmlChar **) & data, (int *) &datalen,
2450 if (!data)
2451 rc = GPG_ERR_ENOMEM;
2454 xmlFreeDoc (doc);
2455 if (rc)
2456 goto fail;
2459 rc = init_client_crypto (&crypto);
2460 if (!rc)
2462 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
2463 crypto->save.hdr.flags = set_cipher_flag (crypto->save.hdr.flags, algo);
2464 crypto->save.hdr.s2k_count = iterations;
2466 if (!use_agent)
2468 rc = export_common (NULL, 0, crypto, data, datalen, outfile, keyfile,
2469 &key, &keylen, 0, 0, nopass);
2471 #ifdef WITH_AGENT
2472 else
2474 rc = agent_set_pinentry_options (crypto->agent);
2475 if (!rc)
2476 rc = agent_export_common (crypto, keygrip, sign_keygrip, nopass,
2477 data, datalen, outfile, keyparam,
2478 no_passphrase_file ? NULL : keyfile);
2480 #endif
2481 if (!rc)
2482 log_write (_("Output written to \"%s\"."),
2483 outfile ? outfile : "<stdout>");
2486 fail:
2487 if (ver < 0x212)
2488 xmlFree (data);
2489 else
2490 gcry_free (data);
2492 gcry_free (key);
2493 cleanup_crypto (&crypto);
2495 if (rc)
2496 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2497 return rc ? 0 : 1;
2500 static void
2501 usage (const char *pn, int status)
2503 FILE *fp = status == EXIT_FAILURE ? stderr : stdout;
2505 fprintf (fp, _("Usage: %s [OPTIONS] [file1] [...]\n"
2506 " -f, --rcfile=filename load the specfied configuration file\n"
2507 " (~/.pwmd/config)\n"
2508 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2509 " --kill terminate an existing instance of pwmd\n"
2510 #ifdef WITH_AGENT
2511 " --use-agent[=integer] enable/disable use of gpg-agent\n"
2512 #endif
2513 " -n, --no-fork run as a foreground process\n"
2514 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2515 " --ignore, --force ignore file errors during startup\n"
2516 " --debug-level=keywords log protocol output (see manual for details)\n"
2517 " -o, --outfile=filename output file when importing or converting\n"
2518 " -C, --convert=filename convert a version 2 data file to version 3\n"
2519 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2520 " -k, --passphrase-file=file for use when importing or converting\n"
2521 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2522 " converting\n"
2523 " --no-passphrase when importing or converting\n"
2524 " --keygrip=hex public key to use when encrypting\n"
2525 " --sign-keygrip=hex private key to use when signing\n"
2526 " --keyparam=s-exp custom key parameters to use (RSA-2048)\n"
2527 " --cipher=string encryption cipher (aes256)\n"
2528 " --cipher-iterations=N cipher iteration count (alias for --s2k-count)\n"
2529 " --s2k-count=N hash iteration count (>65536, calibrated)\n"
2530 " --help this help text\n"
2531 " --version show version and compile time features\n"),
2532 pn);
2533 exit (status);
2536 static void
2537 unlink_stale_socket (const char *sock, const char *pidfile)
2539 log_write (_ ("removing stale socket %s"), sock);
2540 unlink (sock);
2541 unlink (pidfile);
2544 static int
2545 test_pidfile (const char *path, const char *sock, char *buf, size_t buflen,
2546 char **pidfile, int create, mode_t mode, int terminate)
2548 pid_t pid;
2549 int fd;
2550 size_t len;
2552 if (!create)
2554 snprintf (buf, buflen, "%s/%s.pid", homedir, sock);
2555 *pidfile = str_dup (buf);
2556 fd = open (buf, O_RDONLY);
2558 else
2559 fd = open (*pidfile, O_CREAT|O_WRONLY|O_TRUNC, mode);
2561 if (fd == -1)
2563 if (!create && errno != ENOENT)
2565 log_write ("%s: %s", buf, pwmd_strerror (errno));
2566 free (*pidfile);
2567 *pidfile = NULL;
2568 return -1;
2570 else if (!create && !terminate)
2571 return 0;
2573 log_write ("%s: %s", *pidfile, strerror (errno));
2574 return -1;
2577 if (create)
2579 snprintf (buf, buflen, "%i", getpid ());
2580 write (fd, buf, strlen (buf));
2581 close (fd);
2582 return 0;
2585 len = read (fd, buf, buflen);
2586 close (fd);
2587 if (len == 0)
2589 unlink_stale_socket (path, *pidfile);
2590 return 0;
2593 if (sscanf (buf, "%5i", &pid) != 1 || pid == 0)
2595 if (!terminate)
2597 unlink_stale_socket (path, *pidfile);
2598 return 0;
2602 if (kill (pid, 0) == -1)
2604 unlink_stale_socket (path, *pidfile);
2605 return 0;
2608 if (terminate)
2610 if (kill (pid, SIGTERM) == -1)
2611 log_write ("%s: %s", path, pwmd_strerror (errno));
2613 else
2614 log_write (_ ("an instance for socket %s is already running"), path);
2616 xfree (*pidfile);
2617 *pidfile = NULL;
2618 return 1;
2622 main (int argc, char *argv[])
2624 int opt;
2625 struct sockaddr_un addr;
2626 char buf[PATH_MAX];
2627 char *socketpath = NULL, *socketdir, *socketname = NULL;
2628 char *socketarg = NULL;
2629 char *datadir = NULL;
2630 char *pidfile = NULL;
2631 mode_t mode = 0600;
2632 int x;
2633 char *p;
2634 char **cache_push = NULL;
2635 char *import = NULL, *keygrip = NULL, *sign_keygrip = NULL;
2636 char *keyparam = NULL;
2637 int estatus = EXIT_FAILURE;
2638 int sockfd;
2639 char *outfile = NULL;
2640 int do_unlink = 0;
2641 int secure = 0;
2642 int show_version = 0;
2643 int force = 0;
2644 int no_passphrase = 0;
2645 gpg_error_t rc;
2646 char *convertfile = NULL;
2647 char *cipher = NULL;
2648 char *keyfile = NULL;
2649 uint64_t s2k_count = 0;
2650 int exists;
2651 char *debug_level_opt = NULL;
2652 int optindex;
2653 int terminate = 0;
2654 /* Must maintain the same order as longopts[] */
2655 enum
2657 OPT_VERSION, OPT_HELP,
2658 #ifdef WITH_AGENT
2659 OPT_AGENT,
2660 #endif
2661 OPT_DEBUG_LEVEL, OPT_HOMEDIR, OPT_NO_FORK, OPT_DISABLE_DUMP,
2662 OPT_IGNORE, OPT_FORCE, OPT_RCFILE, OPT_CONVERT,
2663 OPT_PASSPHRASE_FILE, OPT_IMPORT, OPT_OUTFILE,
2664 OPT_NO_PASSPHRASE_FILE, OPT_KEYGRIP, OPT_SIGN_KEYGRIP,
2665 OPT_KEYPARAM, OPT_CIPHER, OPT_ITERATIONS, OPT_S2K_COUNT,
2666 OPT_NO_PASSPHRASE, OPT_KILL
2668 const char *optstring = "nf:C:k:I:o:";
2669 const struct option longopts[] = {
2670 {"version", no_argument, 0, 0},
2671 {"help", no_argument, 0, 0},
2672 #ifdef WITH_AGENT
2673 {"use-agent", optional_argument, 0, 0},
2674 #endif
2675 {"debug-level", required_argument, 0, 0},
2676 {"homedir", required_argument, 0, 0},
2677 {"no-fork", no_argument, 0, 'n'},
2678 {"disable_dump", no_argument, 0, 0},
2679 {"ignore", no_argument, 0, 0},
2680 {"force", no_argument, 0, 0},
2681 {"rcfile", required_argument, 0, 'f'},
2682 {"convert", required_argument, 0, 'C'},
2683 {"passphrase-file", required_argument, 0, 'k'},
2684 {"import", required_argument, 0, 'I'},
2685 {"outfile", required_argument, 0, 'o'},
2686 {"no-passphrase-file", no_argument, 0, 0},
2687 {"keygrip", required_argument, 0, 0},
2688 {"sign-keygrip", required_argument, 0, 0},
2689 {"keyparam", required_argument, 0, 0},
2690 {"cipher", required_argument, 0, 0},
2691 {"cipher-iterations", required_argument, 0, 0},
2692 {"s2k-count", required_argument, 0, 0},
2693 {"no-passphrase", no_argument, 0, 0},
2694 {"kill", no_argument, 0, 0},
2695 {0, 0, 0, 0}
2698 log_fd = -1;
2700 #ifndef DEBUG
2701 #ifdef HAVE_SETRLIMIT
2702 struct rlimit rl;
2704 rl.rlim_cur = rl.rlim_max = 0;
2706 if (setrlimit (RLIMIT_CORE, &rl) != 0)
2707 err (EXIT_FAILURE, "setrlimit()");
2708 #endif
2710 #ifdef HAVE_PR_SET_DUMPABLE
2711 prctl (PR_SET_DUMPABLE, 0);
2712 #endif
2713 #endif
2715 #ifdef ENABLE_NLS
2716 setlocale (LC_ALL, "");
2717 bindtextdomain ("pwmd", LOCALEDIR);
2718 textdomain ("pwmd");
2719 #endif
2721 #ifndef MEM_DEBUG
2722 xmem_init ();
2723 #endif
2724 gpg_err_init ();
2726 if (setup_crypto ())
2727 exit (EXIT_FAILURE);
2729 #ifdef WITH_GNUTLS
2730 gnutls_global_init ();
2731 gnutls_global_set_log_function (tls_log);
2732 gnutls_global_set_log_level (1);
2733 tls_fd = -1;
2734 tls6_fd = -1;
2735 #endif
2736 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
2737 xmlInitMemory ();
2738 xmlInitGlobals ();
2739 xmlInitParser ();
2740 xmlXPathInit ();
2741 cmdline = 1;
2742 use_agent = -1;
2744 while ((opt = getopt_long (argc, argv, optstring, longopts, &optindex))
2745 != -1)
2747 switch (opt)
2749 case 'I':
2750 import = optarg;
2751 break;
2752 case 'C':
2753 convertfile = optarg;
2754 break;
2755 case 'k':
2756 keyfile = optarg;
2757 break;
2758 case 'o':
2759 outfile = optarg;
2760 break;
2761 case 'D':
2762 secure = 1;
2763 break;
2764 case 'n':
2765 nofork = 1;
2766 break;
2767 case 'f':
2768 rcfile = str_dup (optarg);
2769 break;
2770 default:
2771 usage (argv[0], EXIT_FAILURE);
2772 break;
2773 case 0:
2774 switch (optindex)
2776 case OPT_VERSION:
2777 show_version = 1;
2778 break;
2779 case OPT_HELP:
2780 usage (argv[0], 0);
2781 break;
2782 #ifdef WITH_AGENT
2783 case OPT_AGENT:
2784 use_agent = optarg && *optarg ? atoi (optarg) : 1;
2785 if (use_agent < 0 || use_agent > 1)
2786 usage (argv[0], 1);
2787 break;
2788 #endif
2789 case OPT_DEBUG_LEVEL:
2790 debug_level_opt = optarg;
2791 break;
2792 case OPT_HOMEDIR:
2793 homedir = str_dup (optarg);
2794 break;
2795 case OPT_NO_FORK:
2796 nofork = 1;
2797 break;
2798 case OPT_DISABLE_DUMP:
2799 secure = 1;
2800 break;
2801 case OPT_IGNORE:
2802 case OPT_FORCE:
2803 force = 1;
2804 break;
2805 case OPT_RCFILE:
2806 rcfile = str_dup (optarg);
2807 break;
2808 case OPT_CONVERT:
2809 convertfile = optarg;
2810 break;
2811 case OPT_PASSPHRASE_FILE:
2812 keyfile = optarg;
2813 break;
2814 case OPT_IMPORT:
2815 import = optarg;
2816 break;
2817 case OPT_OUTFILE:
2818 outfile = optarg;
2819 break;
2820 case OPT_NO_PASSPHRASE_FILE:
2821 no_passphrase_file = 1;
2822 break;
2823 case OPT_KEYGRIP:
2824 keygrip = optarg;
2825 break;
2826 case OPT_SIGN_KEYGRIP:
2827 sign_keygrip = optarg;
2828 break;
2829 case OPT_KEYPARAM:
2830 keyparam = optarg;
2831 break;
2832 case OPT_CIPHER:
2833 cipher = optarg;
2834 break;
2835 case OPT_ITERATIONS:
2836 case OPT_S2K_COUNT:
2837 s2k_count = strtoul (optarg, NULL, 10);
2838 break;
2839 case OPT_NO_PASSPHRASE:
2840 no_passphrase = 1;
2841 break;
2842 case OPT_KILL:
2843 terminate = 1;
2844 break;
2845 default:
2846 usage (argv[0], 1);
2851 if (show_version)
2853 printf (_("%s\n\n"
2854 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015\n"
2855 "%s\n"
2856 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2857 "Compile time features:\n%s"), PACKAGE_STRING,
2858 PACKAGE_BUGREPORT,
2859 #ifdef PWMD_HOMEDIR
2860 "+PWMD_HOMEDIR=" PWMD_HOMEDIR "\n"
2861 #endif
2862 #ifdef WITH_AGENT
2863 "+WITH_AGENT\n"
2864 #else
2865 "-WITH_AGENT\n"
2866 #endif
2867 #ifdef WITH_QUALITY
2868 "+WITH_QUALITY\n"
2869 #else
2870 "-WITH_QUALITY\n"
2871 #endif
2872 #ifdef WITH_GNUTLS
2873 "+WITH_GNUTLS\n"
2874 #else
2875 "-WITH_GNUTLS\n"
2876 #endif
2877 #ifdef DEBUG
2878 "+DEBUG\n"
2879 #else
2880 "-DEBUG\n"
2881 #endif
2882 #ifdef MEM_DEBUG
2883 "+MEM_DEBUG\n"
2884 #else
2885 "-MEM_DEBUG\n"
2886 #endif
2887 #ifdef MUTEX_DEBUG
2888 "+MUTEX_DEBUG\n"
2889 #else
2890 "-MUTEX_DEBUG\n"
2891 #endif
2893 exit (EXIT_SUCCESS);
2896 if (!homedir)
2897 #ifdef PWMD_HOMEDIR
2898 homedir = str_dup(PWMD_HOMEDIR);
2899 #else
2900 homedir = str_asprintf ("%s/.pwmd", get_home_dir());
2901 #endif
2903 if (mkdir (homedir, 0700) == -1 && errno != EEXIST)
2904 err (EXIT_FAILURE, "%s", homedir);
2906 snprintf (buf, sizeof (buf), "%s/data", homedir);
2907 if (mkdir (buf, 0700) == -1 && errno != EEXIST)
2908 err (EXIT_FAILURE, "%s", buf);
2910 datadir = str_dup (buf);
2911 pthread_mutexattr_t attr;
2912 pthread_mutexattr_init (&attr);
2913 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
2914 pthread_mutex_init (&rcfile_mutex, &attr);
2915 pthread_cond_init (&rcfile_cond, NULL);
2916 pthread_mutex_init (&cn_mutex, &attr);
2917 pthread_mutexattr_destroy (&attr);
2918 pthread_key_create (&last_error_key, free_key);
2919 #ifndef HAVE_PTHREAD_CANCEL
2920 pthread_key_create (&signal_thread_key, free_key);
2921 #endif
2923 if (!rcfile)
2924 rcfile = str_asprintf ("%s/config", homedir);
2926 global_config = config_parse (rcfile, 0);
2927 if (!global_config)
2928 exit (EXIT_FAILURE);
2930 #ifdef WITH_AGENT
2931 if (use_agent == -1)
2932 use_agent = config_get_boolean ("global", "use_agent");
2933 #endif
2935 setup_logging ();
2937 if (debug_level_opt)
2938 debug_level = str_split (debug_level_opt, ",", 0);
2940 x = config_get_int_param (global_config, "global", "priority", &exists);
2941 if (exists && x != atoi(INVALID_PRIORITY))
2943 errno = 0;
2944 if (setpriority (PRIO_PROCESS, 0, x) == -1)
2946 log_write ("setpriority(): %s",
2947 pwmd_strerror (gpg_error_from_errno (errno)));
2948 goto do_exit;
2951 #ifdef HAVE_MLOCKALL
2952 if (disable_mlock == 0 && mlockall (MCL_CURRENT | MCL_FUTURE) == -1)
2954 log_write ("mlockall(): %s",
2955 pwmd_strerror (gpg_error_from_errno (errno)));
2956 goto do_exit;
2958 #endif
2960 rc = cache_init (free_cache_data);
2961 if (rc)
2963 log_write ("pwmd: ERR %i: %s", rc,
2964 gpg_err_code (rc) == GPG_ERR_UNKNOWN_VERSION
2965 ? _("incompatible gpg-agent version: 2.1.0 or later required")
2966 : pwmd_strerror (rc));
2967 goto do_exit;
2970 if (s2k_count == 0)
2971 s2k_count = config_get_ulong (NULL, "s2k_count");
2973 if (convertfile)
2975 if (!outfile || !*outfile || argc != optind)
2976 usage (argv[0], EXIT_FAILURE);
2978 estatus = convert_v2_datafile (convertfile, cipher, keyfile, keygrip,
2979 sign_keygrip, no_passphrase, outfile,
2980 keyparam, s2k_count);
2981 config_free (global_config);
2982 xfree (rcfile);
2983 exit (!estatus);
2986 if (import)
2988 if (!outfile || !*outfile || argc != optind)
2989 usage (argv[0], EXIT_FAILURE);
2991 if (outfile && outfile[0] == '-' && outfile[1] == 0)
2992 outfile = NULL;
2994 estatus = xml_import (import, outfile, keygrip, sign_keygrip, keyfile,
2995 no_passphrase, cipher, keyparam, s2k_count);
2996 config_free (global_config);
2997 xfree (rcfile);
2998 exit (!estatus);
3001 p = config_get_string ("global", "socket_path");
3002 if (!p)
3003 p = str_asprintf ("%s/socket", homedir);
3005 socketarg = expand_homedir (p);
3006 xfree (p);
3008 if (!secure)
3009 disable_list_and_dump = config_get_boolean ("global",
3010 "disable_list_and_dump");
3011 else
3012 disable_list_and_dump = secure;
3014 cache_push = config_get_list ("global", "cache_push");
3016 while (optind < argc)
3018 if (strv_printf (&cache_push, "%s", argv[optind++]) == 0)
3019 errx (EXIT_FAILURE, "%s", pwmd_strerror (GPG_ERR_ENOMEM));
3022 if (strchr (socketarg, '/') == NULL)
3024 socketdir = getcwd (buf, sizeof (buf));
3025 socketname = str_dup (socketarg);
3026 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
3028 else
3030 socketname = str_dup (strrchr (socketarg, '/'));
3031 socketname++;
3032 socketarg[strlen (socketarg) - strlen (socketname) - 1] = 0;
3033 socketdir = str_dup (socketarg);
3034 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
3037 if (chdir (datadir))
3039 log_write ("%s: %s", datadir,
3040 pwmd_strerror (gpg_error_from_errno (errno)));
3041 unlink (socketpath);
3042 goto do_exit;
3045 x = test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 0,
3046 mode, terminate);
3047 if (!terminate && x)
3048 goto do_exit;
3049 else if (terminate)
3051 estatus = x != 1 ? EXIT_FAILURE : EXIT_SUCCESS;
3052 goto do_exit;
3056 * bind() doesn't like the full pathname of the socket or any non alphanum
3057 * characters so change to the directory where the socket is wanted then
3058 * create it then change to datadir.
3060 if (chdir (socketdir))
3062 log_write ("%s: %s", socketdir,
3063 pwmd_strerror (gpg_error_from_errno (errno)));
3064 goto do_exit;
3067 xfree (socketdir);
3069 if ((sockfd = socket (PF_UNIX, SOCK_STREAM, 0)) == -1)
3071 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
3072 goto do_exit;
3075 addr.sun_family = AF_UNIX;
3076 snprintf (addr.sun_path, sizeof (addr.sun_path), "%s", socketname);
3077 do_unlink = 1;
3078 if (bind (sockfd, (struct sockaddr *) &addr, sizeof (struct sockaddr)) ==
3081 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
3083 if (errno == EADDRINUSE)
3085 do_unlink = 0;
3086 log_write (_("Either there is another pwmd running or '%s' is a \n"
3087 "stale socket. Please remove it manually."), socketpath);
3090 goto do_exit;
3094 char *t = config_get_string ("global", "socket_perms");
3095 mode_t mask;
3097 if (t)
3099 mode = strtol (t, NULL, 8);
3100 mask = umask (0);
3101 xfree (t);
3103 if (chmod (socketname, mode) == -1)
3105 log_write ("%s: %s", socketname,
3106 pwmd_strerror (gpg_error_from_errno (errno)));
3107 close (sockfd);
3108 umask (mask);
3109 goto do_exit;
3112 umask (mask);
3116 xfree (--socketname);
3118 if (chdir (datadir))
3120 log_write ("%s: %s", datadir,
3121 pwmd_strerror (gpg_error_from_errno (errno)));
3122 close (sockfd);
3123 goto do_exit;
3126 xfree (datadir);
3129 * Set the cache entry for a file. Prompts for the password.
3131 if (cache_push)
3133 struct crypto_s *crypto = NULL;
3134 gpg_error_t rc = init_client_crypto (&crypto);
3136 if (rc)
3138 estatus = EXIT_FAILURE;
3139 goto do_exit;
3142 #ifdef WITH_AGENT
3143 if (use_agent)
3145 rc = agent_set_pinentry_options (crypto->agent);
3146 if (rc)
3148 estatus = EXIT_FAILURE;
3149 goto do_exit;
3152 #endif
3154 for (opt = 0; cache_push[opt]; opt++)
3156 if (!do_cache_push (cache_push[opt], crypto) && !force)
3158 strv_free (cache_push);
3159 startup_failure ();
3160 estatus = EXIT_FAILURE;
3161 cleanup_crypto (&crypto);
3162 goto do_exit;
3165 cleanup_crypto_stage1 (crypto);
3168 #ifdef WITH_AGENT
3169 if (use_agent)
3170 (void) kill_scd (crypto->agent);
3171 #endif
3173 cleanup_crypto (&crypto);
3174 strv_free (cache_push);
3175 log_write (!nofork ? _("Done. Daemonizing...") :
3176 _("Done. Waiting for connections..."));
3179 config_clear_keys ();
3181 if (listen (sockfd, 0) == -1)
3183 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
3184 goto do_exit;
3187 if (!nofork)
3189 switch (fork ())
3191 case -1:
3192 log_write ("fork(): %s",
3193 pwmd_strerror (gpg_error_from_errno (errno)));
3194 goto do_exit;
3195 case 0:
3196 close (0);
3197 close (1);
3198 close (2);
3199 setsid ();
3200 break;
3201 default:
3202 _exit (EXIT_SUCCESS);
3206 (void)test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 1,
3207 mode, 0);
3208 cmdline = 0;
3209 pthread_key_create (&thread_name_key, free_key);
3210 pthread_setspecific (thread_name_key, str_dup ("main"));
3211 estatus = server_loop (sockfd, &socketpath);
3213 do_exit:
3214 if (socketpath && do_unlink)
3216 unlink (socketpath);
3217 xfree (socketpath);
3220 xfree (socketarg);
3221 #ifdef WITH_GNUTLS
3222 gnutls_global_deinit ();
3223 #endif
3224 if (rcfile_tid)
3226 #ifdef HAVE_PTHREAD_CANCEL
3227 pthread_cancel (rcfile_tid);
3228 #else
3229 pthread_kill (rcfile_tid, SIGUSR2);
3230 pthread_cond_signal (&rcfile_cond);
3231 #endif
3232 pthread_join (rcfile_tid, NULL);
3235 pthread_cond_destroy (&rcfile_cond);
3236 pthread_mutex_destroy (&rcfile_mutex);
3237 pthread_key_delete (last_error_key);
3238 #ifndef HAVE_PTHREAD_CANCEL
3239 pthread_key_delete (signal_thread_key);
3240 #endif
3242 if (global_config)
3243 config_free (global_config);
3245 free_invoking_users (invoking_users);
3246 xfree (rcfile);
3247 xfree (home_directory);
3248 xfree (homedir);
3249 xmlCleanupParser ();
3250 xmlCleanupGlobals ();
3252 if (pidfile)
3253 unlink (pidfile);
3254 xfree (pidfile);
3256 if (estatus == EXIT_SUCCESS && !terminate)
3257 log_write (_("pwmd exiting normally"));
3259 pthread_key_delete (thread_name_key);
3260 closelog ();
3261 #if defined(DEBUG) && !defined(MEM_DEBUG)
3262 xdump ();
3263 #endif
3265 if (log_fd != -1)
3266 close (log_fd);
3268 exit (estatus);