Also clear FLAG_ACL_ERROR after target validation.
[pwmd.git] / src / pwmd.c
blob7ec9067db0e347b55fa47e310164cb0e768fd949
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 #ifdef WITH_GNUTLS
586 static int
587 secure_mem_check (const void *arg)
589 return 1;
591 #endif
593 static gpg_error_t
594 setup_crypto ()
596 gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
598 if (!gcry_check_version (GCRYPT_VERSION))
600 fprintf (stderr, _("gcry_check_version(): Incompatible libgcrypt. "
601 "Wanted %s, got %s.\n"), GCRYPT_VERSION,
602 gcry_check_version (NULL));
603 return GPG_ERR_UNKNOWN_VERSION;
606 gcry_set_allocation_handler (xmalloc, xmalloc, NULL, xrealloc, xfree);
607 return 0;
610 gpg_error_t
611 do_validate_peer (assuan_context_t ctx, const char *section,
612 assuan_peercred_t * peer)
614 char **users;
615 int allowed = 0;
616 gpg_error_t rc;
617 struct client_s *client = assuan_get_pointer (ctx);
619 if (!client)
620 return GPG_ERR_EACCES;
622 #ifdef WITH_GNUTLS
623 if (client->thd->remote)
624 return tls_validate_access (client, section);
625 #endif
627 rc = assuan_get_peercred (ctx, peer);
628 if (rc)
629 return rc;
631 users = config_get_list (section, "allowed");
632 if (users)
634 for (char **p = users; *p; p++)
636 rc = acl_check_common(client, *p, (*peer)->uid, (*peer)->gid,
637 &allowed);
640 strv_free (users);
643 return allowed ? 0 : rc ? rc : GPG_ERR_EACCES;
646 /* Test if uid is a member of group 'name'. Invert when 'not' is true. */
647 #ifdef HAVE_GETGRNAM_R
648 static gpg_error_t
649 acl_check_group (const char *name, uid_t uid, gid_t gid, int not, int *allowed)
651 char *buf;
652 struct group gr, *gresult;
653 size_t len = sysconf (_SC_GETGR_R_SIZE_MAX);
655 if (len == -1)
656 len = 16384;
658 buf = xmalloc (len);
659 if (!buf)
660 return GPG_ERR_ENOMEM;
662 if (!getgrnam_r (name, &gr, buf, len, &gresult) && gresult)
664 if (gresult->gr_gid == gid)
666 xfree (buf);
667 *allowed = !not;
668 return 0;
671 len = sysconf (_SC_GETPW_R_SIZE_MAX);
672 if (len == -1)
673 len = 16384;
675 for (char **t = gresult->gr_mem; *t; t++)
677 char *tbuf;
678 struct passwd pw;
679 struct passwd *result = get_pwd_struct (*t, 0, &pw, &tbuf);
681 if (result && result->pw_uid == uid)
683 xfree (tbuf);
684 *allowed = !not;
685 break;
688 xfree (tbuf);
691 xfree (buf);
692 return 0;
695 xfree (buf);
696 return GPG_ERR_EACCES;
698 #else
699 static gpg_error_t
700 acl_check_group (const char *name, uid_t uid, gid_t gid, int not, int *allowed)
702 struct group *gresult;
704 gresult = getgrnam (name);
705 if (gresult && gresult->gr_gid == gid)
707 *allowed = !not;
708 return 0;
711 for (char **t = gresult->gr_mem; *t; t++)
713 char *buf;
714 struct passwd pw;
715 struct passwd *result = get_pwd_struct (*t, 0, &pw, &buf);
717 if (result && result->pw_uid == uid)
719 xfree (buf);
720 *allowed = !not;
721 break;
724 xfree (buf);
727 return 0;
729 #endif
731 gpg_error_t
732 peer_is_invoker(struct client_s *client)
734 struct invoking_user_s *user;
735 int allowed = 0;
737 if (client->thd->state == CLIENT_STATE_UNKNOWN)
738 return GPG_ERR_EACCES;
740 for (user = invoking_users; user; user = user->next)
742 #ifdef WITH_GNUTLS
743 if (client->thd->remote)
745 if (user->type == INVOKING_TLS
746 && !strcmp(client->thd->tls->fp, user->id))
747 allowed = user->not ? 0 : 1;
749 continue;
751 #endif
753 if (user->type == INVOKING_GID)
755 gpg_error_t rc = acl_check_group (user->id,
756 client->thd->peer->uid,
757 client->thd->peer->gid,
758 user->not, &allowed);
759 if (rc)
760 return rc;
762 else if (user->type == INVOKING_UID && client->thd->peer->uid == user->uid)
763 allowed = user->not ? 0 : 1;
766 return allowed ? 0 : GPG_ERR_EACCES;
769 #ifdef HAVE_GETGRNAM_R
770 gpg_error_t
771 acl_check_common (struct client_s *client, const char *user, uid_t uid,
772 gid_t gid, int *allowed)
774 int not = 0;
775 int rw = 0;
776 int tls = 0;
778 if (!user || !*user)
779 return 0;
781 if (*user == '-' || *user == '!')
782 not = 1;
784 if (*user == '+') // not implemented yet
785 rw = 1;
787 if (*user == '#') // TLS fingerprint hash
788 tls = 1;
790 if (not || rw || tls)
791 user++;
793 if (tls)
795 #ifdef WITH_GNUTLS
796 if (client->thd->remote)
798 if (!strcasecmp (client->thd->tls->fp, user))
799 *allowed = !not;
802 return 0;
803 #else
804 return 0;
805 #endif
807 #ifdef WITH_GNUTLS
808 else if (client->thd->remote) // Remote client with no TLS in the ACL
809 return 0;
810 #endif
812 if (*user == '@') // all users in group
813 return acl_check_group (user+1, uid, gid, not, allowed);
814 else
816 char *buf;
817 struct passwd pw;
818 struct passwd *pwd = get_pwd_struct (user, 0, &pw, &buf);
820 if (pwd && pwd->pw_uid == uid)
821 *allowed = !not;
823 xfree (buf);
826 return 0;
828 #else
829 gpg_error_t
830 acl_check_common (struct client_s *client, const char *user, uid_t uid,
831 gid_t gid, int *allowed)
833 int not = 0;
834 int rw = 0;
835 int tls = 0;
837 if (!user || !*user)
838 return 0;
840 if (*user == '-' || *user == '!')
841 not = 1;
843 if (*user == '+') // not implemented yet
844 rw = 1;
846 if (*user == '#') // TLS fingerprint hash
847 tls = 1;
849 if (not || rw || tls)
850 user++;
852 if (tls)
854 #ifdef WITH_GNUTLS
855 if (client->thd->remote)
857 if (!strcasecmp (client->thd->tls->fp, user))
858 *allowed = !not;
861 return 0;
862 #else
863 return 0;
864 #endif
867 if (*user == '@') // all users in group
868 return acl_check_group (user+1, uid, gid, not, allowed);
869 else
871 char *buf;
872 struct passwd pw;
873 struct passwd *result = get_pwd_struct (user, 0, &pw, &buf);
875 if (result && result->pw_uid == uid)
876 *allowed = !not;
878 xfree (buf);
881 return 0;
883 #endif
885 static gpg_error_t
886 validate_peer (struct client_s *cl)
888 gpg_error_t rc;
890 #ifdef WITH_GNUTLS
891 if (cl->thd->remote)
892 return tls_validate_access (cl, NULL);
893 #endif
895 MUTEX_LOCK (&cn_mutex);
896 rc = do_validate_peer (cl->ctx, "global", &cl->thd->peer);
897 MUTEX_UNLOCK (&cn_mutex);
898 if (!rc || gpg_err_code (rc) == GPG_ERR_EACCES)
899 log_write ("peer %s: uid=%i, gid=%i, pid=%i",
900 !rc ? _("accepted") : _("rejected"), cl->thd->peer->uid,
901 cl->thd->peer->gid, cl->thd->peer->pid);
902 else if (rc)
903 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
905 return rc;
908 static void
909 xml_error_cb (void *data, xmlErrorPtr e)
911 struct client_s *client = data;
914 * Keep the first reported error as the one to show in the error
915 * description. Reset in send_error().
917 if (client->xml_error)
918 return;
920 client->xml_error = xcalloc (1, sizeof(xmlError));
921 xmlCopyError (e, client->xml_error);
924 static pid_t
925 hook_waitpid (assuan_context_t ctx, pid_t pid, int action,
926 int *status, int options)
928 return waitpid (pid, status, options);
931 static ssize_t
932 hook_read (assuan_context_t ctx, assuan_fd_t fd, void *data, size_t len)
934 #ifdef WITH_GNUTLS
935 struct client_s *client = assuan_get_pointer (ctx);
937 if (client->thd->remote)
938 return tls_read_hook (ctx, (int) fd, data, len);
939 #endif
941 return read ((int) fd, data, len);
944 static ssize_t
945 hook_write (assuan_context_t ctx, assuan_fd_t fd,
946 const void *data, size_t len)
948 #ifdef WITH_GNUTLS
949 struct client_s *client = assuan_get_pointer (ctx);
951 if (client->thd->remote)
952 return tls_write_hook (ctx, (int) fd, data, len);
953 #endif
955 return write ((int) fd, data, len);
958 static int
959 new_connection (struct client_s *cl)
961 gpg_error_t rc;
962 static struct assuan_malloc_hooks mhooks = { xmalloc, xrealloc, xfree };
963 static struct assuan_system_hooks shooks = {
964 ASSUAN_SYSTEM_HOOKS_VERSION,
965 __assuan_usleep,
966 __assuan_pipe,
967 __assuan_close,
968 hook_read,
969 hook_write,
970 //FIXME
971 NULL, //recvmsg
972 NULL, //sendmsg both are used for FD passing
973 __assuan_spawn,
974 hook_waitpid,
975 __assuan_socketpair,
976 __assuan_socket,
977 __assuan_connect
980 #ifdef WITH_GNUTLS
981 if (cl->thd->remote)
983 char *prio = config_get_string ("global", "tls_cipher_suite");
985 cl->thd->timeout = config_get_integer ("global", "tls_timeout");
986 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
987 return 0;
989 cl->thd->tls = tls_init (cl->thd->fd, cl->thd->timeout, prio);
990 xfree (prio);
991 if (!cl->thd->tls)
992 return 0;
994 #endif
996 rc = assuan_new_ext (&cl->ctx, GPG_ERR_SOURCE_DEFAULT, &mhooks,
997 debug_level ? assuan_log_cb : NULL, NULL);
998 if (rc)
999 goto fail;
1001 assuan_ctx_set_system_hooks (cl->ctx, &shooks);
1002 rc = assuan_init_socket_server (cl->ctx, cl->thd->fd, 2);
1003 if (rc)
1004 goto fail;
1006 assuan_set_pointer (cl->ctx, cl);
1007 assuan_set_hello_line (cl->ctx, PACKAGE_STRING);
1008 rc = register_commands (cl->ctx);
1009 if (rc)
1010 goto fail;
1012 rc = assuan_accept (cl->ctx);
1013 if (rc)
1014 goto fail;
1016 rc = validate_peer (cl);
1017 /* May not be implemented on all platforms. */
1018 if (rc && gpg_err_code (rc) != GPG_ERR_ASS_GENERAL)
1019 goto fail;
1021 MUTEX_LOCK (&cn_mutex);
1022 cl->thd->state = CLIENT_STATE_INIT;
1023 MUTEX_UNLOCK (&cn_mutex);
1024 rc = init_client_crypto (&cl->crypto);
1025 if (rc)
1026 goto fail;
1028 #ifdef WITH_AGENT
1029 if (use_agent)
1030 cl->crypto->agent->client_ctx = cl->ctx;
1031 #endif
1033 cl->crypto->client_ctx = cl->ctx;
1034 cl->lock_timeout = config_get_integer ("global", "lock_timeout");
1035 xmlSetStructuredErrorFunc (cl, xml_error_cb);
1036 return 1;
1038 fail:
1039 log_write ("%s", pwmd_strerror (rc));
1040 return 0;
1044 * This is called after a client_thread() terminates. Set with
1045 * pthread_cleanup_push().
1047 static void
1048 cleanup_cb (void *arg)
1050 struct client_thread_s *cn = arg;
1051 struct client_s *cl = cn->cl;
1053 MUTEX_LOCK (&cn_mutex);
1054 cn_thread_list = slist_remove (cn_thread_list, cn);
1055 MUTEX_UNLOCK (&cn_mutex);
1057 if (cl)
1059 cleanup_client (cl);
1060 if (cl->xml_error)
1061 xmlResetError (cl->xml_error);
1063 xfree (cl->xml_error);
1065 #ifdef WITH_GNUTLS
1066 if (cn->tls)
1068 gnutls_deinit (cn->tls->ses);
1069 xfree (cn->tls->fp);
1070 xfree (cn->tls);
1072 #endif
1074 if (!cn->atfork && cl->ctx)
1075 assuan_release (cl->ctx);
1076 else if (!cn->atfork && cl->thd && cl->thd->fd != -1)
1077 close (cl->thd->fd);
1079 if (cl->crypto)
1080 cleanup_crypto (&cl->crypto);
1082 pinentry_free_opts (&cl->pinentry_opts);
1083 xfree (cl);
1085 else
1087 if (cn->fd != -1)
1088 close (cn->fd);
1091 while (cn->msg_queue)
1093 struct status_msg_s *msg = cn->msg_queue;
1095 cn->msg_queue = msg->next;
1096 xfree (msg->line);
1097 xfree (msg);
1100 if (!cn->atfork && cn->status_msg_pipe[0] != -1)
1101 close (cn->status_msg_pipe[0]);
1103 if (!cn->atfork && cn->status_msg_pipe[1] != -1)
1104 close (cn->status_msg_pipe[1]);
1106 pthread_mutex_destroy (&cn->status_mutex);
1108 if (!cn->atfork)
1110 log_write (_("exiting, fd=%i"), cn->fd);
1111 send_status_all (STATUS_CLIENTS, NULL);
1114 xfree (cn->name);
1115 #ifdef WITH_GNUTLS
1116 xfree (cn->peeraddr);
1117 #endif
1118 xfree (cn);
1119 pthread_cond_signal (&quit_cond);
1122 void
1123 cleanup_all_clients (int atfork)
1125 /* This function may be called from pthread_atfork() which requires
1126 reinitialization. */
1127 if (atfork)
1129 pthread_mutexattr_t attr;
1131 pthread_mutexattr_init (&attr);
1132 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
1133 pthread_mutex_init (&cn_mutex, &attr);
1134 pthread_mutexattr_destroy (&attr);
1135 cache_mutex_init ();
1138 MUTEX_LOCK (&cn_mutex);
1140 while (slist_length (cn_thread_list))
1142 struct client_thread_s *thd = slist_nth_data (cn_thread_list, 0);
1144 thd->atfork = atfork;
1145 cleanup_cb (thd);
1148 exiting = 1;
1149 MUTEX_UNLOCK (&cn_mutex);
1150 cache_deinit (atfork);
1153 static gpg_error_t
1154 send_msg_queue (struct client_thread_s *thd)
1156 MUTEX_LOCK (&thd->status_mutex);
1157 gpg_error_t rc = 0;
1158 char c;
1160 read (thd->status_msg_pipe[0], &c, 1);
1161 thd->wrote_status = 0;
1163 while (thd->msg_queue)
1165 struct status_msg_s *msg = thd->msg_queue;
1167 thd->msg_queue = thd->msg_queue->next;
1168 MUTEX_UNLOCK (&thd->status_mutex);
1169 rc = send_status (thd->cl->ctx, msg->s, msg->line);
1170 MUTEX_LOCK (&thd->status_mutex);
1171 xfree (msg->line);
1172 xfree (msg);
1174 if (rc)
1175 break;
1178 MUTEX_UNLOCK (&thd->status_mutex);
1179 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1180 log_write ("%s: %s", __FUNCTION__, pwmd_strerror (rc));
1182 return rc;
1185 static void *
1186 client_thread (void *data)
1188 struct client_thread_s *thd = data;
1189 struct client_s *cl = xcalloc (1, sizeof (struct client_s));
1191 #ifdef HAVE_PR_SET_NAME
1192 prctl (PR_SET_NAME, "client");
1193 #endif
1194 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1196 if (!cl)
1198 log_write ("%s(%i): %s", __FILE__, __LINE__,
1199 pwmd_strerror (GPG_ERR_ENOMEM));
1200 return NULL;
1203 MUTEX_LOCK (&cn_mutex);
1204 pthread_cleanup_push (cleanup_cb, thd);
1205 thd->cl = cl;
1206 cl->thd = thd;
1207 MUTEX_UNLOCK (&cn_mutex);
1209 if (new_connection (cl))
1211 int finished = 0;
1212 gpg_error_t rc;
1214 send_status_all (STATUS_CLIENTS, NULL);
1215 rc = send_status (cl->ctx, STATUS_CACHE, NULL);
1216 if (rc)
1218 log_write ("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror (rc));
1219 finished = 1;
1222 while (!finished)
1224 fd_set rfds;
1225 int n;
1226 int eof;
1228 FD_ZERO (&rfds);
1229 FD_SET (thd->fd, &rfds);
1230 FD_SET (thd->status_msg_pipe[0], &rfds);
1231 n = thd->fd > thd->status_msg_pipe[0]
1232 ? thd->fd : thd->status_msg_pipe[0];
1234 n = select (n + 1, &rfds, NULL, NULL, NULL);
1235 if (n == -1)
1237 log_write ("%s", strerror (errno));
1238 break;
1241 if (FD_ISSET (thd->status_msg_pipe[0], &rfds))
1243 rc = send_msg_queue (thd);
1244 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1245 break;
1248 if (!FD_ISSET (thd->fd, &rfds))
1249 continue;
1251 rc = assuan_process_next (cl->ctx, &eof);
1252 if (rc || eof)
1254 if (gpg_err_code (rc) == GPG_ERR_EOF || eof)
1255 break;
1257 log_write ("assuan_process_next(): rc=%i %s", rc,
1258 pwmd_strerror (rc));
1259 if (rc == gpg_error (GPG_ERR_ETIMEDOUT))
1260 break;
1262 rc = send_error (cl->ctx, rc);
1263 if (rc)
1265 log_write ("assuan_process_done(): rc=%i %s", rc,
1266 pwmd_strerror (rc));
1267 break;
1271 /* Since the msg queue pipe fd's are non-blocking, check for
1272 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1273 * client has already disconnected and will be converted to
1274 * GPG_ERR_EOF during assuan_process_next().
1276 rc = send_msg_queue (thd);
1277 if (rc && gpg_err_code (rc) != GPG_ERR_EPIPE)
1278 break;
1282 /* Don't do pthread_exit() here because any set pthread_cleanup_push
1283 * functions would be called after a command failed but then the client
1284 * exited normally which may lead to a double free. */
1285 pthread_cleanup_pop (1);
1286 return NULL;
1289 static int
1290 xml_import (const char *filename, const char *outfile,
1291 const char *keygrip, const char *sign_keygrip,
1292 const char *keyfile, int no_passphrase, const char *cipher,
1293 const char *params, unsigned long s2k_count, uint64_t iterations)
1295 xmlDocPtr doc;
1296 int fd;
1297 struct stat st;
1298 int len;
1299 xmlChar *xmlbuf;
1300 xmlChar *xml;
1301 gpg_error_t rc;
1302 struct crypto_s *crypto = NULL;
1303 void *key = NULL;
1304 size_t keylen = 0;
1305 int algo = cipher ? cipher_string_to_gcrypt ((char *) cipher) :
1306 GCRY_CIPHER_AES256;
1308 if (algo == -1)
1310 log_write ("ERR %i: %s", gpg_error (GPG_ERR_CIPHER_ALGO),
1311 pwmd_strerror (GPG_ERR_CIPHER_ALGO));
1312 return 0;
1315 if (stat (filename, &st) == -1)
1317 log_write ("%s: %s", filename,
1318 pwmd_strerror (gpg_error_from_errno (errno)));
1319 return 0;
1322 rc = init_client_crypto (&crypto);
1323 if (rc)
1324 return 0;
1326 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
1327 crypto->save.hdr.flags = set_cipher_flag (crypto->save.hdr.flags, algo);
1328 log_write (_("Importing XML from '%s'. Output will be written to '%s' ..."),
1329 filename, outfile);
1331 if ((fd = open (filename, O_RDONLY)) == -1)
1333 log_write ("%s: %s", filename,
1334 pwmd_strerror (gpg_error_from_errno (errno)));
1335 goto fail;
1338 if ((xmlbuf = xmalloc (st.st_size + 1)) == NULL)
1340 close (fd);
1341 log_write ("%s(%i): %s", __FILE__, __LINE__,
1342 pwmd_strerror (GPG_ERR_ENOMEM));
1343 goto fail;
1346 if (read (fd, xmlbuf, st.st_size) == -1)
1348 rc = gpg_error_from_errno (errno);
1349 close (fd);
1350 log_write ("%s: %s", filename, pwmd_strerror (rc));
1351 goto fail;
1354 close (fd);
1355 xmlbuf[st.st_size] = 0;
1357 * Make sure the document validates.
1359 if ((doc = xmlReadDoc (xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS)) == NULL)
1361 log_write ("xmlReadDoc() failed");
1362 xfree (xmlbuf);
1363 goto fail;
1366 xfree (xmlbuf);
1367 xmlNodePtr n = xmlDocGetRootElement (doc);
1368 if (n && !xmlStrEqual (n->name, (xmlChar *) "pwmd"))
1370 log_write (_("Could not find root \"pwmd\" element."));
1371 rc = GPG_ERR_BAD_DATA;
1374 if (!rc)
1375 rc = validate_import (NULL, n ? n->children : n);
1377 if (rc)
1379 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1380 xmlFreeDoc (doc);
1381 goto fail;
1384 xmlDocDumpMemory (doc, &xml, &len);
1385 xmlFreeDoc (doc);
1386 crypto->save.s2k_count = s2k_count;
1387 crypto->save.hdr.iterations = iterations;
1388 if (!use_agent)
1390 rc = export_common (NULL, 0, crypto, xml, len, outfile, keyfile, &key,
1391 &keylen, 0, 0, no_passphrase);
1392 if (!rc)
1393 log_write (_("Success!"));
1395 #ifdef WITH_AGENT
1396 else
1398 rc = agent_set_pinentry_options (crypto->agent);
1399 if (!rc)
1400 rc = agent_export_common (crypto, keygrip, sign_keygrip, no_passphrase,
1401 xml, len, outfile, params, keyfile);
1403 #endif
1405 gcry_free (key);
1406 xmlFree (xml);
1407 if (rc)
1409 send_error (NULL, rc);
1410 goto fail;
1413 cleanup_crypto (&crypto);
1414 return 1;
1416 fail:
1417 cleanup_crypto (&crypto);
1418 return 0;
1421 static int
1422 do_cache_push (const char *filename, struct crypto_s *crypto)
1424 unsigned char md5file[16];
1425 gpg_error_t rc;
1426 char *key = NULL;
1427 size_t keylen = 0;
1428 xmlDocPtr doc;
1429 struct cache_data_s *cdata;
1430 unsigned char *crc;
1431 size_t len;
1433 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1434 filename);
1436 if (valid_filename (filename) == 0)
1438 log_write (_("%s: Invalid characters in filename"), filename);
1439 return 0;
1442 rc = decrypt_common (NULL, 0, crypto, filename, &key, &keylen);
1443 if (rc)
1444 return 0;
1446 rc = parse_doc ((char *) crypto->plaintext, crypto->plaintext_len, &doc);
1447 if (rc)
1449 log_write ("%s", pwmd_strerror (rc));
1450 xfree (key);
1451 return 0;
1454 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
1455 cdata = xcalloc (1, sizeof (struct cache_data_s));
1456 if (!cdata)
1458 xmlFreeDoc (doc);
1459 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM));
1460 xfree (key);
1461 return 0;
1464 rc = get_checksum (filename, &crc, &len);
1465 if (rc)
1467 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1468 xmlFreeDoc (doc);
1469 free_cache_data_once (cdata);
1470 xfree (key);
1471 return 0;
1474 cdata->crc = crc;
1475 rc = encrypt_xml (NULL, cache_key, cache_keysize, GCRY_CIPHER_AES,
1476 crypto->plaintext, crypto->plaintext_len, &cdata->doc,
1477 &cdata->doclen, &cache_iv, &cache_blocksize, 0);
1478 if (!rc && !IS_PKI (crypto))
1480 cdata->key = key;
1481 cdata->keylen = keylen;
1483 else
1484 xfree (key);
1486 if (rc)
1488 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1489 xmlFreeDoc (doc);
1490 free_cache_data_once (cdata);
1491 return 0;
1494 #ifdef WITH_AGENT
1495 if (use_agent && IS_PKI (crypto))
1497 gcry_sexp_build ((gcry_sexp_t *) & cdata->pubkey, NULL, "%S",
1498 crypto->pkey_sexp);
1499 gcry_sexp_build ((gcry_sexp_t *) & cdata->sigkey, NULL, "%S",
1500 crypto->sigpkey_sexp);
1502 #endif
1504 int timeout = config_get_integer (filename, "cache_timeout");
1505 cache_add_file (md5file, crypto->grip, cdata, timeout);
1506 log_write (_("Successfully added '%s' to the cache."), filename);
1507 return 1;
1510 static gpg_error_t
1511 init_client (int fd, const char *addr)
1513 gpg_error_t rc = 0;
1514 struct client_thread_s *new = xcalloc (1, sizeof (struct client_thread_s));
1516 if (!new)
1518 close (fd);
1519 return GPG_ERR_ENOMEM;
1522 MUTEX_LOCK (&cn_mutex);
1523 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
1525 if (pipe (new->status_msg_pipe) == -1)
1526 rc = gpg_error_from_errno (errno);
1528 if (!rc)
1530 if (fcntl (new->status_msg_pipe[0], F_SETFL, O_NONBLOCK) == -1)
1531 rc = gpg_error_from_errno (errno);
1533 if (!rc)
1534 if (fcntl (new->status_msg_pipe[1], F_SETFL, O_NONBLOCK) == -1)
1535 rc = gpg_error_from_errno (errno);
1537 pthread_mutex_init (&new->status_mutex, NULL);
1540 if (!rc)
1542 #ifdef WITH_GNUTLS
1543 new->remote = addr ? 1 : 0;
1544 #endif
1545 new->fd = fd;
1546 rc = create_thread (client_thread, new, &new->tid, 1);
1547 if (rc)
1549 close (new->status_msg_pipe[0]);
1550 close (new->status_msg_pipe[1]);
1551 pthread_mutex_destroy (&new->status_mutex);
1555 if (!rc)
1557 struct slist_s *list = slist_append (cn_thread_list, new);
1559 if (list)
1561 cn_thread_list = list;
1562 if (addr)
1564 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1565 (pthread_t *) new->tid, fd, addr);
1566 #ifdef WITH_GNUTLS
1567 new->peeraddr = str_dup (addr);
1568 #endif
1570 else
1571 log_write (_("new connection: tid=%p, fd=%i"),
1572 (pthread_t *) new->tid, fd);
1574 else
1575 rc = GPG_ERR_ENOMEM;
1578 pthread_cleanup_pop (1);
1580 if (rc)
1582 xfree (new);
1583 close (fd);
1584 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1585 pwmd_strerror (rc));
1587 return rc;
1590 static void*
1591 keepalive_thread (void *arg)
1593 #ifndef HAVE_PTHREAD_CANCEL
1594 int *n = xmalloc (sizeof (int));
1596 *n = 0;
1597 pthread_setspecific (signal_thread_key, n);
1598 INIT_THREAD_SIGNAL;
1599 #endif
1601 #ifdef HAVE_PR_SET_NAME
1602 prctl (PR_SET_NAME, "keepalive");
1603 #endif
1604 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1606 for (;;)
1608 int n = config_get_integer ("global", "keepalive_interval");
1609 struct timeval tv = { n, 0 };
1610 #ifndef HAVE_PTHREAD_CANCEL
1611 int *sigusr2;
1613 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1614 if (*sigusr2)
1615 break;
1616 #endif
1618 send_status_all (STATUS_KEEPALIVE, NULL);
1619 select (0, NULL, NULL, NULL, &tv);
1622 return NULL;
1625 #ifdef WITH_GNUTLS
1626 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1627 static void *
1628 get_in_addr (struct sockaddr *sa)
1630 if (sa->sa_family == AF_INET)
1631 return &(((struct sockaddr_in *) sa)->sin_addr);
1633 return &(((struct sockaddr_in6 *) sa)->sin6_addr);
1636 static void *
1637 tcp_accept_thread (void *arg)
1639 int sockfd = *(int *) arg;
1640 #ifndef HAVE_PTHREAD_CANCEL
1641 int *n = xmalloc (sizeof (int));
1643 *n = 0;
1644 pthread_setspecific (signal_thread_key, n);
1645 INIT_THREAD_SIGNAL;
1646 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1647 #endif
1649 #ifdef HAVE_PR_SET_NAME
1650 prctl (PR_SET_NAME, "tcp_accept");
1651 #endif
1652 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1654 for (;;)
1656 struct sockaddr_storage raddr;
1657 socklen_t slen = sizeof (raddr);
1658 int fd;
1659 unsigned long n;
1660 char s[INET6_ADDRSTRLEN];
1661 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1662 #ifndef HAVE_PTHREAD_CANCEL
1663 int *sigusr2;
1665 sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1666 if (*sigusr2)
1667 break;
1668 #endif
1670 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1671 if (fd == -1)
1673 if (errno == EMFILE || errno == ENFILE)
1674 log_write ("accept(): %s",
1675 pwmd_strerror (gpg_error_from_errno (errno)));
1676 else if (errno != EAGAIN)
1678 if (!quit) // probably EBADF
1679 log_write ("accept(): %s", strerror (errno));
1681 break;
1684 #ifndef HAVE_PTHREAD_CANCEL
1685 select (0, NULL, NULL, NULL, &tv);
1686 #endif
1687 continue;
1690 if (quit)
1692 close (fd);
1693 break;
1696 inet_ntop (raddr.ss_family, get_in_addr ((struct sockaddr *) &raddr),
1697 s, sizeof s);
1698 (void) init_client (fd, s);
1699 n = config_get_integer ("global", "tcp_wait");
1700 if (n > 0)
1702 tv.tv_sec = (n * 100000) / 100000;
1703 tv.tv_usec = (n * 100000) % 100000;
1704 select (0, NULL, NULL, NULL, &tv);
1708 return NULL;
1711 static int
1712 start_stop_tls_with_protocol (int ipv6, int term)
1714 struct addrinfo hints, *servinfo, *p;
1715 int port = config_get_integer ("global", "tcp_port");
1716 char buf[7];
1717 int n;
1718 gpg_error_t rc;
1719 int *fd = ipv6 ? &tls6_fd : &tls_fd;
1721 if (term || config_get_boolean ("global", "enable_tcp") == 0)
1723 if (tls6_fd != -1)
1725 if (spawned_tls6)
1727 #ifdef HAVE_PTHREAD_CANCEL
1728 pthread_cancel (tls6_tid);
1729 #else
1730 pthread_kill (tls6_tid, SIGUSR2);
1731 #endif
1732 pthread_join (tls6_tid, NULL);
1735 shutdown (tls6_fd, SHUT_RDWR);
1736 close (tls6_fd);
1737 tls6_fd = -1;
1738 spawned_tls6 = 0;
1741 if (tls_fd != -1)
1743 if (spawned_tls)
1745 #ifdef HAVE_PTHREAD_CANCEL
1746 pthread_cancel (tls_tid);
1747 #else
1748 pthread_kill (tls_tid, SIGUSR2);
1749 #endif
1750 pthread_join (tls_tid, NULL);
1753 shutdown (tls_fd, SHUT_RDWR);
1754 close (tls_fd);
1755 tls_fd = -1;
1756 spawned_tls = 0;
1759 /* A client may still be connected. */
1760 if (!quit && x509_cred != NULL)
1761 tls_deinit_params ();
1763 return 1;
1766 if ((ipv6 && tls6_fd != -1) || (!ipv6 && tls_fd != -1))
1767 return 1;
1769 memset (&hints, 0, sizeof (hints));
1770 hints.ai_family = ipv6 ? AF_INET6 : AF_INET;
1771 hints.ai_socktype = SOCK_STREAM;
1772 hints.ai_flags = AI_PASSIVE;
1773 snprintf (buf, sizeof (buf), "%i", port);
1775 if ((n = getaddrinfo (NULL, buf, &hints, &servinfo)) == -1)
1777 log_write ("getaddrinfo(): %s", gai_strerror (n));
1778 return 0;
1781 for (n = 0, p = servinfo; p != NULL; p = p->ai_next)
1783 int r = 1;
1785 if ((ipv6 && p->ai_family != AF_INET6)
1786 || (!ipv6 && p->ai_family != AF_INET))
1787 continue;
1789 if ((*fd = socket (p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
1791 log_write ("socket(): %s", strerror (errno));
1792 continue;
1795 if (setsockopt (*fd, SOL_SOCKET, SO_REUSEADDR, &r, sizeof (int)) == -1)
1797 log_write ("setsockopt(): %s",
1798 pwmd_strerror (gpg_error_from_errno (errno)));
1799 freeaddrinfo (servinfo);
1800 goto fail;
1803 if (bind (*fd, p->ai_addr, p->ai_addrlen) == -1)
1805 close (*fd);
1806 log_write ("bind(): %s",
1807 pwmd_strerror (gpg_error_from_errno (errno)));
1808 continue;
1811 n++;
1812 break;
1815 freeaddrinfo (servinfo);
1817 if (!n)
1818 goto fail;
1820 #if HAVE_DECL_SO_BINDTODEVICE != 0
1821 char *tmp = config_get_string ("global", "tcp_interface");
1822 if (tmp && setsockopt (*fd, SOL_SOCKET, SO_BINDTODEVICE, tmp,
1823 strlen (tmp)) == -1)
1825 log_write ("setsockopt(): %s",
1826 pwmd_strerror (gpg_error_from_errno (errno)));
1827 xfree (tmp);
1828 goto fail;
1831 xfree (tmp);
1832 #endif
1834 if (x509_cred == NULL)
1836 char *tmp = config_get_string ("global", "tls_dh_level");
1838 rc = tls_init_params (tmp);
1839 xfree (tmp);
1840 if (rc)
1841 goto fail;
1844 if (listen (*fd, 0) == -1)
1846 log_write ("listen(): %s", strerror (errno));
1847 goto fail;
1850 if (ipv6)
1851 rc = create_thread (tcp_accept_thread, fd, &tls6_tid, 0);
1852 else
1853 rc = create_thread (tcp_accept_thread, fd, &tls_tid, 0);
1855 if (rc)
1857 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1858 pwmd_strerror (rc));
1859 goto fail;
1862 if (ipv6)
1863 spawned_tls6 = 1;
1864 else
1865 spawned_tls = 1;
1867 return 1;
1869 fail:
1870 start_stop_tls_with_protocol (0, 1);
1871 if (tls_fd != -1)
1872 close (tls_fd);
1874 if (tls6_fd != -1)
1875 close (tls6_fd);
1877 tls_fd = -1;
1878 tls6_fd = -1;
1879 return 0;
1882 static int
1883 start_stop_tls (int term)
1885 char *s = config_get_string ("global", "tcp_bind");
1886 int b;
1888 if (!s)
1889 return 0;
1891 if (!strcmp (s, "any"))
1893 b = start_stop_tls_with_protocol (0, term);
1894 if (b)
1895 b = start_stop_tls_with_protocol (1, term);
1897 else if (!strcmp (s, "ipv4"))
1898 b = start_stop_tls_with_protocol (0, term);
1899 else if (!strcmp (s, "ipv6"))
1900 b = start_stop_tls_with_protocol (1, term);
1901 else
1902 b = 0;
1904 xfree (s);
1905 return b;
1907 #endif
1909 static void *
1910 accept_thread (void *arg)
1912 int sockfd = *(int *) arg;
1913 #ifndef HAVE_PTHREAD_CANCEL
1914 int *n = xmalloc (sizeof (int));
1916 *n = 0;
1917 pthread_setspecific (signal_thread_key, n);
1918 INIT_THREAD_SIGNAL;
1919 fcntl (sockfd, F_SETFL, O_NONBLOCK);
1920 #endif
1922 #ifdef HAVE_PR_SET_NAME
1923 prctl (PR_SET_NAME, "accept");
1924 #endif
1925 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1927 for (;;)
1929 socklen_t slen = sizeof (struct sockaddr_un);
1930 struct sockaddr_un raddr;
1931 int fd;
1932 #ifndef HAVE_PTHREAD_CANCEL
1933 struct timeval tv = { 0, ACCEPT_TIMEOUT };
1934 int *sigusr2 = (int *) pthread_getspecific (signal_thread_key);
1936 if (*sigusr2)
1937 break;
1938 #endif
1940 fd = accept (sockfd, (struct sockaddr *) &raddr, &slen);
1941 if (fd == -1)
1943 if (errno == EMFILE || errno == ENFILE)
1944 log_write ("accept(): %s",
1945 pwmd_strerror (gpg_error_from_errno (errno)));
1946 else if (errno != EAGAIN)
1948 if (!quit) // probably EBADF
1949 log_write ("accept(): %s",
1950 pwmd_strerror (gpg_error_from_errno (errno)));
1952 break;
1955 #ifndef HAVE_PTHREAD_CANCEL
1956 select (0, NULL, NULL, NULL, &tv);
1957 #endif
1958 continue;
1961 (void) init_client (fd, NULL);
1964 /* Just in case accept() failed for some reason other than EBADF */
1965 quit = 1;
1966 return NULL;
1969 static void *
1970 cache_timer_thread (void *arg)
1972 #ifndef HAVE_PTHREAD_CANCEL
1973 int *n = xmalloc (sizeof (int));
1975 *n = 0;
1976 pthread_setspecific (signal_thread_key, n);
1977 INIT_THREAD_SIGNAL;
1978 #endif
1980 #ifdef HAVE_PR_SET_NAME
1981 prctl (PR_SET_NAME, "cache timer");
1982 #endif
1983 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
1985 for (;;)
1987 struct timeval tv = { 1, 0 };
1988 #ifndef HAVE_PTHREAD_CANCEL
1989 int *n;
1991 n = (int *) pthread_getspecific (signal_thread_key);
1992 if (*n)
1993 break;
1994 #endif
1996 select (0, NULL, NULL, NULL, &tv);
1997 cache_adjust_timeout ();
2000 return NULL;
2003 static int
2004 signal_loop (sigset_t sigset)
2006 int done = 0;
2007 int siint = 0;
2011 int sig;
2013 sigwait (&sigset, &sig);
2015 if (sig != SIGQUIT)
2016 log_write (_("caught signal %i (%s)"), sig, strsignal (sig));
2018 switch (sig)
2020 case SIGHUP:
2021 pthread_cond_signal (&rcfile_cond);
2022 break;
2023 case SIGUSR1:
2024 log_write (_("clearing file cache"));
2025 cache_clear (NULL);
2026 send_status_all (STATUS_CACHE, NULL);
2027 break;
2028 case SIGQUIT:
2029 done = 1;
2030 break;
2031 default:
2032 siint = 1;
2033 done = 1;
2034 break;
2037 while (!done);
2039 return siint;
2042 static void
2043 catchsig (int sig)
2045 log_write (_ ("Caught signal %i (%s). Exiting."), sig, strsignal (sig));
2046 #ifdef HAVE_BACKTRACE
2047 BACKTRACE (__FUNCTION__);
2048 #endif
2049 longjmp (jmp, 1);
2052 static void *
2053 waiting_for_exit (void *arg)
2055 int last = 0;
2056 #ifndef HAVE_PTHREAD_CANCEL
2057 int *n = xmalloc (sizeof (int));
2059 *n = 0;
2060 pthread_setspecific (signal_thread_key, n);
2061 INIT_THREAD_SIGNAL;
2062 #endif
2064 #ifdef HAVE_PR_SET_NAME
2065 prctl (PR_SET_NAME, "exiting");
2066 #endif
2067 pthread_setspecific (thread_name_key, str_dup (__FUNCTION__));
2068 log_write (_("waiting for all clients to disconnect"));
2069 MUTEX_LOCK (&quit_mutex);
2070 pthread_cleanup_push (cleanup_mutex_cb, &quit_mutex);
2072 for (;;)
2074 struct timespec ts;
2075 int n;
2077 MUTEX_LOCK (&cn_mutex);
2078 n = slist_length (cn_thread_list);
2079 MUTEX_UNLOCK (&cn_mutex);
2080 if (!n)
2081 break;
2083 #ifndef HAVE_PTHREAD_CANCEL
2084 int *s = (int *) pthread_getspecific (signal_thread_key);
2085 if (*s)
2086 break;
2087 #endif
2089 if (last != n)
2091 log_write (_("%i clients remain"), n);
2092 last = n;
2095 INIT_TIMESPEC (SIG_TIMEOUT, ts);
2096 pthread_cond_timedwait (&quit_cond, &quit_mutex, &ts);
2099 kill (getpid (), SIGQUIT);
2100 pthread_cleanup_pop (1);
2101 return NULL;
2104 static int
2105 server_loop (int sockfd, char **socketpath)
2107 pthread_t accept_tid;
2108 pthread_t cache_timeout_tid;
2109 int cancel_timeout_thread = 0, cancel_accept_thread = 0;
2110 int cancel_keepalive_thread = 0;
2111 sigset_t sigset;
2112 int n;
2113 int segv = 0;
2114 gpg_error_t rc;
2116 init_commands ();
2117 sigemptyset (&sigset);
2119 /* Termination */
2120 sigaddset (&sigset, SIGTERM);
2121 sigaddset (&sigset, SIGINT);
2123 /* Clears the file cache. */
2124 sigaddset (&sigset, SIGUSR1);
2126 /* Configuration file reloading. */
2127 sigaddset (&sigset, SIGHUP);
2129 /* For exiting cleanly. */
2130 sigaddset (&sigset, SIGQUIT);
2132 #ifndef HAVE_PTHREAD_CANCEL
2134 The socket, cache and rcfile threads use this signal when
2135 pthread_cancel() is unavailable. Prevent the main thread from
2136 catching this signal from another process.
2138 sigaddset (&sigset, SIGUSR2);
2139 #endif
2141 /* When mem.c cannot find a pointer in the list (double free). */
2142 signal (SIGABRT, catchsig);
2143 sigaddset (&sigset, SIGABRT);
2144 sigprocmask (SIG_BLOCK, &sigset, NULL);
2146 #ifndef HAVE_PTHREAD_CANCEL
2147 /* Remove this signal from the watched signals in signal_loop(). */
2148 sigdelset (&sigset, SIGUSR2);
2149 #endif
2151 /* Ignored everywhere. When a client disconnects abnormally this signal
2152 * gets raised. It isn't needed though because client_thread() will check
2153 * for rcs even after the client disconnects. */
2154 signal (SIGPIPE, SIG_IGN);
2156 /* Can show a backtrace of the stack in the log. */
2157 signal (SIGSEGV, catchsig);
2159 #ifdef WITH_GNUTLS
2160 /* Needs to be done after the fork(). */
2161 if (!start_stop_tls (0))
2163 segv = 1;
2164 goto done;
2166 #endif
2168 pthread_mutex_init (&quit_mutex, NULL);
2169 pthread_cond_init (&quit_cond, NULL);
2170 char *p = get_username (getuid());
2171 log_write (_("%s started for user %s"), PACKAGE_STRING, p);
2172 xfree (p);
2174 #ifdef WITH_GNUTLS
2175 if (config_get_boolean ("global", "enable_tcp"))
2176 log_write (_("Listening on %s and TCP port %i"), *socketpath,
2177 config_get_integer ("global", "tcp_port"));
2178 else
2179 log_write (_("Listening on %s"), *socketpath);
2180 #else
2181 log_write (_("Listening on %s"), *socketpath);
2182 #endif
2184 rc = create_thread (keepalive_thread, NULL, &keepalive_tid, 0);
2185 if (rc)
2187 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2188 pwmd_strerror (rc));
2189 goto done;
2192 cancel_keepalive_thread = 1;
2193 rc = create_thread (reload_rcfile_thread, NULL, &rcfile_tid, 0);
2194 if (rc)
2196 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2197 pwmd_strerror (rc));
2198 goto done;
2201 rc = create_thread (cache_timer_thread, NULL, &cache_timeout_tid, 0);
2202 if (rc)
2204 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2205 pwmd_strerror (rc));
2206 goto done;
2209 cancel_timeout_thread = 1;
2210 rc = create_thread (accept_thread, &sockfd, &accept_tid, 0);
2211 if (rc)
2213 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2214 pwmd_strerror (rc));
2215 goto done;
2218 cancel_accept_thread = 1;
2219 if (!setjmp (jmp))
2220 signal_loop (sigset);
2221 else
2222 segv = 1;
2224 done:
2226 * We're out of the main server loop. This happens when a signal was sent
2227 * to terminate the daemon. We'll wait for all clients to disconnect
2228 * before exiting but exit immediately if another termination signal is
2229 * sent.
2231 if (cancel_accept_thread)
2233 #ifdef HAVE_PTHREAD_CANCEL
2234 int n = pthread_cancel (accept_tid);
2235 #else
2236 int n = pthread_kill (accept_tid, SIGUSR2);
2237 #endif
2238 if (!n)
2239 pthread_join (accept_tid, NULL);
2242 #ifdef WITH_GNUTLS
2243 start_stop_tls (1);
2244 #endif
2245 shutdown (sockfd, SHUT_RDWR);
2246 close (sockfd);
2247 unlink (*socketpath);
2248 xfree (*socketpath);
2249 *socketpath = NULL;
2250 MUTEX_LOCK (&cn_mutex);
2251 n = slist_length (cn_thread_list);
2252 MUTEX_UNLOCK (&cn_mutex);
2254 if (n && !segv)
2256 pthread_t tid;
2258 rc = create_thread (waiting_for_exit, NULL, &tid, 0);
2259 if (!rc)
2261 if (signal_loop (sigset))
2263 log_write (_("Received second termination request. Exiting."));
2264 #ifdef HAVE_PTHREAD_CANCEL
2265 pthread_cancel (tid);
2266 #else
2267 pthread_kill (tid, SIGUSR2);
2268 #endif
2269 pthread_join (tid, NULL);
2272 else
2273 log_write ("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
2274 pwmd_strerror (rc));
2277 if (cancel_timeout_thread)
2279 #ifdef HAVE_PTHREAD_CANCEL
2280 pthread_cancel (cache_timeout_tid);
2281 #else
2282 pthread_kill (cache_timeout_tid, SIGUSR2);
2283 #endif
2284 pthread_join (cache_timeout_tid, NULL);
2287 if (cancel_keepalive_thread)
2289 #ifdef HAVE_PTHREAD_CANCEL
2290 pthread_cancel (keepalive_tid);
2291 #else
2292 pthread_kill (keepalive_tid, SIGUSR2);
2293 #endif
2294 pthread_join (keepalive_tid, NULL);
2297 cleanup_all_clients (0);
2298 #ifdef WITH_GNUTLS
2299 start_stop_tls (1);
2300 #endif
2301 deinit_commands ();
2302 pthread_cond_destroy (&quit_cond);
2303 pthread_mutex_destroy (&quit_mutex);
2304 return segv ? EXIT_FAILURE : EXIT_SUCCESS;;
2307 static void
2308 startup_failure ()
2310 log_write (_
2311 ("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
2312 cache_clear (NULL);
2315 /* This is called from cache.c:clear_once(). See
2316 * command.c:clearcache_command() for details about lock checking.
2318 static gpg_error_t
2319 free_cache_data (file_cache_t * cache)
2321 gpg_error_t rc = GPG_ERR_NO_DATA;
2322 int i, t;
2323 struct client_thread_s *found = NULL;
2324 int self = 0;
2326 if (!cache->data)
2327 return 0;
2329 cache_lock ();
2330 MUTEX_LOCK (&cn_mutex);
2331 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
2332 t = slist_length (cn_thread_list);
2334 for (i = 0; i < t; i++)
2336 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2338 if (!thd->cl)
2339 continue;
2341 if (!memcmp (thd->cl->md5file, cache->filename,
2342 sizeof (cache->filename)))
2344 if (pthread_equal (pthread_self (), thd->tid))
2346 found = thd;
2347 self = 1;
2348 continue;
2351 /* Continue trying to find a client who has the same file open and
2352 * also has a lock. */
2353 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0, -1);
2354 if (!rc)
2356 self = 0;
2357 found = thd;
2358 break;
2363 if (self && (!rc || rc == GPG_ERR_NO_DATA))
2364 rc = cache_lock_mutex (found->cl->ctx, found->cl->md5file, -1, 0, -1);
2366 if (exiting || !rc || rc == GPG_ERR_NO_DATA)
2368 free_cache_data_once (cache->data);
2369 cache->data = NULL;
2370 cache->defer_clear = 0;
2371 cache->timeout = -1;
2373 if (found)
2374 cache_unlock_mutex (found->cl->md5file, 0);
2376 rc = 0;
2379 if (rc)
2380 cache->defer_clear = 1;
2382 pthread_cleanup_pop (1);
2383 cache_unlock ();
2384 return rc;
2387 static int
2388 convert_v2_datafile (const char *filename, const char *cipher,
2389 const char *keyfile, const char *keygrip,
2390 const char *sign_keygrip, int nopass,
2391 const char *outfile, const char *keyparam,
2392 unsigned long s2k_count, uint64_t iterations)
2394 gpg_error_t rc;
2395 void *data = NULL;
2396 size_t datalen;
2397 struct crypto_s *crypto = NULL;
2398 uint16_t ver;
2399 int algo;
2400 void *key = NULL;
2401 size_t keylen = 0;
2403 if (outfile[0] == '-' && outfile[1] == 0)
2404 outfile = NULL;
2406 log_write (_("Converting version 2 data file \"%s\" ..."), filename);
2407 if (access (filename, R_OK) == -1)
2409 log_write ("%s: %s", filename,
2410 pwmd_strerror (gpg_error_from_errno (errno)));
2411 return 0;
2414 if (keyfile)
2416 log_write (_("Using passphrase file \"%s\" for decryption ..."),
2417 keyfile);
2418 if (access (keyfile, R_OK) == -1)
2420 log_write ("%s: %s", keyfile,
2421 pwmd_strerror (gpg_error_from_errno (errno)));
2422 return 0;
2426 rc = read_v2_datafile (filename, keyfile, &data, &datalen, &ver, &algo);
2427 if (rc)
2429 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2430 return 0;
2433 if (cipher)
2435 algo = cipher_string_to_gcrypt (cipher);
2436 if (algo == -1)
2438 rc = GPG_ERR_CIPHER_ALGO;
2439 goto fail;
2443 if (ver < 0x212)
2445 xmlDocPtr doc;
2447 rc = parse_doc (data, datalen, &doc);
2448 if (rc)
2449 goto fail;
2451 rc = convert_pre_212_elements (doc);
2452 gcry_free (data);
2453 data = NULL;
2454 if (!rc)
2456 xmlDocDumpFormatMemory (doc, (xmlChar **) & data, (int *) &datalen,
2458 if (!data)
2459 rc = GPG_ERR_ENOMEM;
2462 xmlFreeDoc (doc);
2463 if (rc)
2464 goto fail;
2467 rc = init_client_crypto (&crypto);
2468 if (!rc)
2470 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
2471 crypto->save.hdr.flags = set_cipher_flag (crypto->save.hdr.flags, algo);
2472 crypto->save.s2k_count = s2k_count;
2473 crypto->save.hdr.iterations = iterations;
2475 if (!use_agent)
2477 rc = export_common (NULL, 0, crypto, data, datalen, outfile, keyfile,
2478 &key, &keylen, 0, 0, nopass);
2480 #ifdef WITH_AGENT
2481 else
2483 rc = agent_set_pinentry_options (crypto->agent);
2484 if (!rc)
2485 rc = agent_export_common (crypto, keygrip, sign_keygrip, nopass,
2486 data, datalen, outfile, keyparam,
2487 no_passphrase_file ? NULL : keyfile);
2489 #endif
2490 if (!rc)
2491 log_write (_("Output written to \"%s\"."),
2492 outfile ? outfile : "<stdout>");
2495 fail:
2496 if (ver < 0x212)
2497 xmlFree (data);
2498 else
2499 gcry_free (data);
2501 gcry_free (key);
2502 cleanup_crypto (&crypto);
2504 if (rc)
2505 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
2506 return rc ? 0 : 1;
2509 static void
2510 usage (const char *pn, int status)
2512 FILE *fp = status == EXIT_FAILURE ? stderr : stdout;
2514 fprintf (fp, _("Usage: %s [OPTIONS] [file1] [...]\n"
2515 " -f, --rcfile=filename load the specfied configuration file\n"
2516 " (~/.pwmd/config)\n"
2517 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2518 " --kill terminate an existing instance of pwmd\n"
2519 #ifdef WITH_AGENT
2520 " --use-agent[=integer] enable/disable use of gpg-agent\n"
2521 #endif
2522 " -n, --no-fork run as a foreground process\n"
2523 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2524 " --ignore, --force ignore file errors during startup\n"
2525 " --debug-level=keywords log protocol output (see manual for details)\n"
2526 " -o, --outfile=filename output file when importing or converting\n"
2527 " -C, --convert=filename convert a version 2 data file to version 3\n"
2528 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2529 " -k, --passphrase-file=file for use when importing or converting\n"
2530 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2531 " converting\n"
2532 " --no-passphrase when importing or converting\n"
2533 " --keygrip=hex public key to use when encrypting\n"
2534 " --sign-keygrip=hex private key to use when signing\n"
2535 " --keyparam=s-exp custom key parameters to use (RSA-2048)\n"
2536 " --cipher=string encryption cipher (aes256)\n"
2537 " --cipher-iterations=N cipher iteration count (N+1)\n"
2538 " --s2k-count=N hash iteration count (>65536, calibrated)\n"
2539 " --help this help text\n"
2540 " --version show version and compile time features\n"),
2541 pn);
2542 exit (status);
2545 static void
2546 unlink_stale_socket (const char *sock, const char *pidfile)
2548 log_write (_ ("removing stale socket %s"), sock);
2549 unlink (sock);
2550 unlink (pidfile);
2553 static int
2554 test_pidfile (const char *path, const char *sock, char *buf, size_t buflen,
2555 char **pidfile, int create, mode_t mode, int terminate)
2557 pid_t pid;
2558 int fd;
2559 size_t len;
2561 if (!create)
2563 snprintf (buf, buflen, "%s/%s.pid", homedir, sock);
2564 *pidfile = str_dup (buf);
2565 fd = open (buf, O_RDONLY);
2567 else
2568 fd = open (*pidfile, O_CREAT|O_WRONLY|O_TRUNC, mode);
2570 if (fd == -1)
2572 if (!create && errno != ENOENT)
2574 log_write ("%s: %s", buf, pwmd_strerror (errno));
2575 free (*pidfile);
2576 *pidfile = NULL;
2577 return -1;
2579 else if (!create && !terminate)
2580 return 0;
2582 log_write ("%s: %s", *pidfile, strerror (errno));
2583 return -1;
2586 if (create)
2588 snprintf (buf, buflen, "%i", getpid ());
2589 write (fd, buf, strlen (buf));
2590 close (fd);
2591 return 0;
2594 len = read (fd, buf, buflen);
2595 close (fd);
2596 if (len == 0)
2598 unlink_stale_socket (path, *pidfile);
2599 return 0;
2602 if (sscanf (buf, "%5i", &pid) != 1 || pid == 0)
2604 if (!terminate)
2606 unlink_stale_socket (path, *pidfile);
2607 return 0;
2611 if (kill (pid, 0) == -1)
2613 unlink_stale_socket (path, *pidfile);
2614 return 0;
2617 if (terminate)
2619 if (kill (pid, SIGTERM) == -1)
2620 log_write ("%s: %s", path, pwmd_strerror (errno));
2622 else
2623 log_write (_ ("an instance for socket %s is already running"), path);
2625 xfree (*pidfile);
2626 *pidfile = NULL;
2627 return 1;
2631 main (int argc, char *argv[])
2633 int opt;
2634 struct sockaddr_un addr;
2635 char buf[PATH_MAX];
2636 char *socketpath = NULL, *socketdir, *socketname = NULL;
2637 char *socketarg = NULL;
2638 char *datadir = NULL;
2639 char *pidfile = NULL;
2640 mode_t mode = 0600;
2641 int x;
2642 char *p;
2643 char **cache_push = NULL;
2644 char *import = NULL, *keygrip = NULL, *sign_keygrip = NULL;
2645 char *keyparam = NULL;
2646 int estatus = EXIT_FAILURE;
2647 int sockfd;
2648 char *outfile = NULL;
2649 int do_unlink = 0;
2650 int secure = 0;
2651 int show_version = 0;
2652 int force = 0;
2653 int no_passphrase = 0;
2654 gpg_error_t rc;
2655 char *convertfile = NULL;
2656 char *cipher = NULL;
2657 char *keyfile = NULL;
2658 unsigned long s2k_count = 0;
2659 uint64_t iterations = 0;
2660 int exists;
2661 char *debug_level_opt = NULL;
2662 int optindex;
2663 int terminate = 0;
2664 /* Must maintain the same order as longopts[] */
2665 enum
2667 OPT_VERSION, OPT_HELP,
2668 #ifdef WITH_AGENT
2669 OPT_AGENT,
2670 #endif
2671 OPT_DEBUG_LEVEL, OPT_HOMEDIR, OPT_NO_FORK, OPT_DISABLE_DUMP,
2672 OPT_IGNORE, OPT_FORCE, OPT_RCFILE, OPT_CONVERT,
2673 OPT_PASSPHRASE_FILE, OPT_IMPORT, OPT_OUTFILE,
2674 OPT_NO_PASSPHRASE_FILE, OPT_KEYGRIP, OPT_SIGN_KEYGRIP,
2675 OPT_KEYPARAM, OPT_CIPHER, OPT_ITERATIONS, OPT_S2K_COUNT,
2676 OPT_NO_PASSPHRASE, OPT_KILL
2678 const char *optstring = "nf:C:k:I:o:";
2679 const struct option longopts[] = {
2680 {"version", no_argument, 0, 0},
2681 {"help", no_argument, 0, 0},
2682 #ifdef WITH_AGENT
2683 {"use-agent", optional_argument, 0, 0},
2684 #endif
2685 {"debug-level", required_argument, 0, 0},
2686 {"homedir", required_argument, 0, 0},
2687 {"no-fork", no_argument, 0, 'n'},
2688 {"disable_dump", no_argument, 0, 0},
2689 {"ignore", no_argument, 0, 0},
2690 {"force", no_argument, 0, 0},
2691 {"rcfile", required_argument, 0, 'f'},
2692 {"convert", required_argument, 0, 'C'},
2693 {"passphrase-file", required_argument, 0, 'k'},
2694 {"import", required_argument, 0, 'I'},
2695 {"outfile", required_argument, 0, 'o'},
2696 {"no-passphrase-file", no_argument, 0, 0},
2697 {"keygrip", required_argument, 0, 0},
2698 {"sign-keygrip", required_argument, 0, 0},
2699 {"keyparam", required_argument, 0, 0},
2700 {"cipher", required_argument, 0, 0},
2701 {"cipher-iterations", required_argument, 0, 0},
2702 {"s2k-count", required_argument, 0, 0},
2703 {"no-passphrase", no_argument, 0, 0},
2704 {"kill", no_argument, 0, 0},
2705 {0, 0, 0, 0}
2708 log_fd = -1;
2710 #ifndef DEBUG
2711 #ifdef HAVE_SETRLIMIT
2712 struct rlimit rl;
2714 rl.rlim_cur = rl.rlim_max = 0;
2716 if (setrlimit (RLIMIT_CORE, &rl) != 0)
2717 err (EXIT_FAILURE, "setrlimit()");
2718 #endif
2720 #ifdef HAVE_PR_SET_DUMPABLE
2721 prctl (PR_SET_DUMPABLE, 0);
2722 #endif
2723 #endif
2725 #ifdef ENABLE_NLS
2726 setlocale (LC_ALL, "");
2727 bindtextdomain ("pwmd", LOCALEDIR);
2728 textdomain ("pwmd");
2729 #endif
2731 #ifndef MEM_DEBUG
2732 xmem_init ();
2733 #endif
2734 gpg_err_init ();
2736 if (setup_crypto ())
2737 exit (EXIT_FAILURE);
2739 #ifdef WITH_GNUTLS
2740 gnutls_global_set_mem_functions (xmalloc, xmalloc, secure_mem_check,
2741 xrealloc, xfree);
2742 gnutls_global_init ();
2743 gnutls_global_set_log_function (tls_log);
2744 gnutls_global_set_log_level (1);
2745 tls_fd = -1;
2746 tls6_fd = -1;
2747 #endif
2748 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
2749 xmlInitMemory ();
2750 xmlInitGlobals ();
2751 xmlInitParser ();
2752 xmlXPathInit ();
2753 cmdline = 1;
2754 use_agent = -1;
2756 while ((opt = getopt_long (argc, argv, optstring, longopts, &optindex))
2757 != -1)
2759 switch (opt)
2761 case 'I':
2762 import = optarg;
2763 break;
2764 case 'C':
2765 convertfile = optarg;
2766 break;
2767 case 'k':
2768 keyfile = optarg;
2769 break;
2770 case 'o':
2771 outfile = optarg;
2772 break;
2773 case 'D':
2774 secure = 1;
2775 break;
2776 case 'n':
2777 nofork = 1;
2778 break;
2779 case 'f':
2780 rcfile = str_dup (optarg);
2781 break;
2782 default:
2783 usage (argv[0], EXIT_FAILURE);
2784 break;
2785 case 0:
2786 switch (optindex)
2788 case OPT_VERSION:
2789 show_version = 1;
2790 break;
2791 case OPT_HELP:
2792 usage (argv[0], 0);
2793 break;
2794 #ifdef WITH_AGENT
2795 case OPT_AGENT:
2796 use_agent = optarg && *optarg ? atoi (optarg) : 1;
2797 if (use_agent < 0 || use_agent > 1)
2798 usage (argv[0], 1);
2799 break;
2800 #endif
2801 case OPT_DEBUG_LEVEL:
2802 debug_level_opt = optarg;
2803 break;
2804 case OPT_HOMEDIR:
2805 homedir = str_dup (optarg);
2806 break;
2807 case OPT_NO_FORK:
2808 nofork = 1;
2809 break;
2810 case OPT_DISABLE_DUMP:
2811 secure = 1;
2812 break;
2813 case OPT_IGNORE:
2814 case OPT_FORCE:
2815 force = 1;
2816 break;
2817 case OPT_RCFILE:
2818 rcfile = str_dup (optarg);
2819 break;
2820 case OPT_CONVERT:
2821 convertfile = optarg;
2822 break;
2823 case OPT_PASSPHRASE_FILE:
2824 keyfile = optarg;
2825 break;
2826 case OPT_IMPORT:
2827 import = optarg;
2828 break;
2829 case OPT_OUTFILE:
2830 outfile = optarg;
2831 break;
2832 case OPT_NO_PASSPHRASE_FILE:
2833 no_passphrase_file = 1;
2834 break;
2835 case OPT_KEYGRIP:
2836 keygrip = optarg;
2837 break;
2838 case OPT_SIGN_KEYGRIP:
2839 sign_keygrip = optarg;
2840 break;
2841 case OPT_KEYPARAM:
2842 keyparam = optarg;
2843 break;
2844 case OPT_CIPHER:
2845 cipher = optarg;
2846 break;
2847 case OPT_ITERATIONS:
2848 iterations = strtoull (optarg, NULL, 10);
2849 break;
2850 case OPT_S2K_COUNT:
2851 s2k_count = strtoul (optarg, NULL, 10);
2852 break;
2853 case OPT_NO_PASSPHRASE:
2854 no_passphrase = 1;
2855 break;
2856 case OPT_KILL:
2857 terminate = 1;
2858 break;
2859 default:
2860 usage (argv[0], 1);
2865 if (show_version)
2867 printf (_("%s\n\n"
2868 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015\n"
2869 "%s\n"
2870 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2871 "Compile time features:\n%s"), PACKAGE_STRING,
2872 PACKAGE_BUGREPORT,
2873 #ifdef PWMD_HOMEDIR
2874 "+PWMD_HOMEDIR=" PWMD_HOMEDIR "\n"
2875 #endif
2876 #ifdef WITH_AGENT
2877 "+WITH_AGENT\n"
2878 #else
2879 "-WITH_AGENT\n"
2880 #endif
2881 #ifdef WITH_QUALITY
2882 "+WITH_QUALITY\n"
2883 #else
2884 "-WITH_QUALITY\n"
2885 #endif
2886 #ifdef WITH_GNUTLS
2887 "+WITH_GNUTLS\n"
2888 #else
2889 "-WITH_GNUTLS\n"
2890 #endif
2891 #ifdef DEBUG
2892 "+DEBUG\n"
2893 #else
2894 "-DEBUG\n"
2895 #endif
2896 #ifdef MEM_DEBUG
2897 "+MEM_DEBUG\n"
2898 #else
2899 "-MEM_DEBUG\n"
2900 #endif
2901 #ifdef MUTEX_DEBUG
2902 "+MUTEX_DEBUG\n"
2903 #else
2904 "-MUTEX_DEBUG\n"
2905 #endif
2907 exit (EXIT_SUCCESS);
2910 if (!homedir)
2911 #ifdef PWMD_HOMEDIR
2912 homedir = str_dup(PWMD_HOMEDIR);
2913 #else
2914 homedir = str_asprintf ("%s/.pwmd", get_home_dir());
2915 #endif
2917 if (mkdir (homedir, 0700) == -1 && errno != EEXIST)
2918 err (EXIT_FAILURE, "%s", homedir);
2920 snprintf (buf, sizeof (buf), "%s/data", homedir);
2921 if (mkdir (buf, 0700) == -1 && errno != EEXIST)
2922 err (EXIT_FAILURE, "%s", buf);
2924 datadir = str_dup (buf);
2925 pthread_mutexattr_t attr;
2926 pthread_mutexattr_init (&attr);
2927 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
2928 pthread_mutex_init (&rcfile_mutex, &attr);
2929 pthread_cond_init (&rcfile_cond, NULL);
2930 pthread_mutex_init (&cn_mutex, &attr);
2931 pthread_mutexattr_destroy (&attr);
2932 pthread_key_create (&last_error_key, free_key);
2933 #ifndef HAVE_PTHREAD_CANCEL
2934 pthread_key_create (&signal_thread_key, free_key);
2935 #endif
2937 if (!rcfile)
2938 rcfile = str_asprintf ("%s/config", homedir);
2940 global_config = config_parse (rcfile, 0);
2941 if (!global_config)
2942 exit (EXIT_FAILURE);
2944 #ifdef WITH_AGENT
2945 if (use_agent == -1)
2946 use_agent = config_get_boolean ("global", "use_agent");
2947 #endif
2949 setup_logging ();
2951 if (debug_level_opt)
2952 debug_level = str_split (debug_level_opt, ",", 0);
2954 x = config_get_int_param (global_config, "global", "priority", &exists);
2955 if (exists && x != atoi(INVALID_PRIORITY))
2957 errno = 0;
2958 if (setpriority (PRIO_PROCESS, 0, x) == -1)
2960 log_write ("setpriority(): %s",
2961 pwmd_strerror (gpg_error_from_errno (errno)));
2962 goto do_exit;
2965 #ifdef HAVE_MLOCKALL
2966 if (disable_mlock == 0 && mlockall (MCL_CURRENT | MCL_FUTURE) == -1)
2968 log_write ("mlockall(): %s",
2969 pwmd_strerror (gpg_error_from_errno (errno)));
2970 goto do_exit;
2972 #endif
2974 rc = cache_init (free_cache_data);
2975 if (rc)
2977 log_write ("pwmd: ERR %i: %s", rc,
2978 gpg_err_code (rc) == GPG_ERR_UNKNOWN_VERSION
2979 ? _("incompatible gpg-agent version: 2.1.0 or later required")
2980 : pwmd_strerror (rc));
2981 goto do_exit;
2984 if (s2k_count == 0)
2985 s2k_count = config_get_ulong (NULL, "s2k_count");
2987 if (convertfile)
2989 if (!outfile || !*outfile || argc != optind)
2990 usage (argv[0], EXIT_FAILURE);
2992 estatus = convert_v2_datafile (convertfile, cipher, keyfile, keygrip,
2993 sign_keygrip, no_passphrase, outfile,
2994 keyparam, s2k_count, iterations);
2995 config_free (global_config);
2996 xfree (rcfile);
2997 exit (!estatus);
3000 if (import)
3002 if (!outfile || !*outfile || argc != optind)
3003 usage (argv[0], EXIT_FAILURE);
3005 if (outfile && outfile[0] == '-' && outfile[1] == 0)
3006 outfile = NULL;
3008 estatus = xml_import (import, outfile, keygrip, sign_keygrip, keyfile,
3009 no_passphrase, cipher, keyparam, s2k_count,
3010 iterations);
3011 config_free (global_config);
3012 xfree (rcfile);
3013 exit (!estatus);
3016 p = config_get_string ("global", "socket_path");
3017 if (!p)
3018 p = str_asprintf ("%s/socket", homedir);
3020 socketarg = expand_homedir (p);
3021 xfree (p);
3023 if (!secure)
3024 disable_list_and_dump = config_get_boolean ("global",
3025 "disable_list_and_dump");
3026 else
3027 disable_list_and_dump = secure;
3029 cache_push = config_get_list ("global", "cache_push");
3031 while (optind < argc)
3033 if (strv_printf (&cache_push, "%s", argv[optind++]) == 0)
3034 errx (EXIT_FAILURE, "%s", pwmd_strerror (GPG_ERR_ENOMEM));
3037 if (strchr (socketarg, '/') == NULL)
3039 socketdir = getcwd (buf, sizeof (buf));
3040 socketname = str_dup (socketarg);
3041 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
3043 else
3045 socketname = str_dup (strrchr (socketarg, '/'));
3046 socketname++;
3047 socketarg[strlen (socketarg) - strlen (socketname) - 1] = 0;
3048 socketdir = str_dup (socketarg);
3049 socketpath = str_asprintf ("%s/%s", socketdir, socketname);
3052 if (chdir (datadir))
3054 log_write ("%s: %s", datadir,
3055 pwmd_strerror (gpg_error_from_errno (errno)));
3056 unlink (socketpath);
3057 goto do_exit;
3060 x = test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 0,
3061 mode, terminate);
3062 if (!terminate && x)
3063 goto do_exit;
3064 else if (terminate)
3066 estatus = x != 1 ? EXIT_FAILURE : EXIT_SUCCESS;
3067 goto do_exit;
3071 * bind() doesn't like the full pathname of the socket or any non alphanum
3072 * characters so change to the directory where the socket is wanted then
3073 * create it then change to datadir.
3075 if (chdir (socketdir))
3077 log_write ("%s: %s", socketdir,
3078 pwmd_strerror (gpg_error_from_errno (errno)));
3079 goto do_exit;
3082 xfree (socketdir);
3084 if ((sockfd = socket (PF_UNIX, SOCK_STREAM, 0)) == -1)
3086 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
3087 goto do_exit;
3090 addr.sun_family = AF_UNIX;
3091 snprintf (addr.sun_path, sizeof (addr.sun_path), "%s", socketname);
3092 do_unlink = 1;
3093 if (bind (sockfd, (struct sockaddr *) &addr, sizeof (struct sockaddr)) ==
3096 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
3098 if (errno == EADDRINUSE)
3100 do_unlink = 0;
3101 log_write (_("Either there is another pwmd running or '%s' is a \n"
3102 "stale socket. Please remove it manually."), socketpath);
3105 goto do_exit;
3109 char *t = config_get_string ("global", "socket_perms");
3110 mode_t mask;
3112 if (t)
3114 mode = strtol (t, NULL, 8);
3115 mask = umask (0);
3116 xfree (t);
3118 if (chmod (socketname, mode) == -1)
3120 log_write ("%s: %s", socketname,
3121 pwmd_strerror (gpg_error_from_errno (errno)));
3122 close (sockfd);
3123 umask (mask);
3124 goto do_exit;
3127 umask (mask);
3131 xfree (--socketname);
3133 if (chdir (datadir))
3135 log_write ("%s: %s", datadir,
3136 pwmd_strerror (gpg_error_from_errno (errno)));
3137 close (sockfd);
3138 goto do_exit;
3141 xfree (datadir);
3144 * Set the cache entry for a file. Prompts for the password.
3146 if (cache_push)
3148 struct crypto_s *crypto = NULL;
3149 gpg_error_t rc = init_client_crypto (&crypto);
3151 if (rc)
3153 estatus = EXIT_FAILURE;
3154 goto do_exit;
3157 #ifdef WITH_AGENT
3158 if (use_agent)
3160 rc = agent_set_pinentry_options (crypto->agent);
3161 if (rc)
3163 estatus = EXIT_FAILURE;
3164 goto do_exit;
3167 #endif
3169 for (opt = 0; cache_push[opt]; opt++)
3171 if (!do_cache_push (cache_push[opt], crypto) && !force)
3173 strv_free (cache_push);
3174 startup_failure ();
3175 estatus = EXIT_FAILURE;
3176 cleanup_crypto (&crypto);
3177 goto do_exit;
3180 cleanup_crypto_stage1 (crypto);
3183 #ifdef WITH_AGENT
3184 if (use_agent)
3185 (void) kill_scd (crypto->agent);
3186 #endif
3188 cleanup_crypto (&crypto);
3189 strv_free (cache_push);
3190 log_write (!nofork ? _("Done. Daemonizing...") :
3191 _("Done. Waiting for connections..."));
3194 config_clear_keys ();
3196 if (listen (sockfd, 0) == -1)
3198 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_errno (errno)));
3199 goto do_exit;
3202 if (!nofork)
3204 switch (fork ())
3206 case -1:
3207 log_write ("fork(): %s",
3208 pwmd_strerror (gpg_error_from_errno (errno)));
3209 goto do_exit;
3210 case 0:
3211 close (0);
3212 close (1);
3213 close (2);
3214 setsid ();
3215 break;
3216 default:
3217 _exit (EXIT_SUCCESS);
3221 (void)test_pidfile (socketpath, socketname, buf, sizeof(buf), &pidfile, 1,
3222 mode, 0);
3223 cmdline = 0;
3224 pthread_key_create (&thread_name_key, free_key);
3225 pthread_setspecific (thread_name_key, str_dup ("main"));
3226 estatus = server_loop (sockfd, &socketpath);
3228 do_exit:
3229 if (socketpath && do_unlink)
3231 unlink (socketpath);
3232 xfree (socketpath);
3235 xfree (socketarg);
3236 #ifdef WITH_GNUTLS
3237 gnutls_global_deinit ();
3238 #endif
3239 if (rcfile_tid)
3241 #ifdef HAVE_PTHREAD_CANCEL
3242 pthread_cancel (rcfile_tid);
3243 #else
3244 pthread_kill (rcfile_tid, SIGUSR2);
3245 pthread_cond_signal (&rcfile_cond);
3246 #endif
3247 pthread_join (rcfile_tid, NULL);
3250 pthread_cond_destroy (&rcfile_cond);
3251 pthread_mutex_destroy (&rcfile_mutex);
3252 pthread_key_delete (last_error_key);
3253 #ifndef HAVE_PTHREAD_CANCEL
3254 pthread_key_delete (signal_thread_key);
3255 #endif
3257 if (global_config)
3258 config_free (global_config);
3260 free_invoking_users (invoking_users);
3261 xfree (rcfile);
3262 xfree (home_directory);
3263 xfree (homedir);
3264 xmlCleanupParser ();
3265 xmlCleanupGlobals ();
3267 if (pidfile)
3268 unlink (pidfile);
3269 xfree (pidfile);
3271 if (estatus == EXIT_SUCCESS && !terminate)
3272 log_write (_("pwmd exiting normally"));
3274 pthread_key_delete (thread_name_key);
3275 closelog ();
3276 #if defined(DEBUG) && !defined(MEM_DEBUG)
3277 xdump ();
3278 #endif
3280 if (log_fd != -1)
3281 close (log_fd);
3283 exit (estatus);