Unlock the rcfile mutex upon exit.
[pwmd.git] / src / pwmd.c
blobb29724fd4b5731e25bb76d5740ef774a9e86abeb
1 /* vim:tw=78:ts=8:sw=4:set ft=c: */
2 /*
3 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012
4 Ben Kibbey <bjk@luxsci.net>
6 This file is part of pwmd.
8 Pwmd is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 2 of the License, or
11 (at your option) any later version.
13 Pwmd is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
21 #ifdef HAVE_CONFIG_H
22 #include <config.h>
23 #endif
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <err.h>
29 #include <ctype.h>
30 #include <string.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 <glib.h>
41 #include <glib/gprintf.h>
42 #include <sys/mman.h>
43 #include <termios.h>
44 #include <assert.h>
45 #include <syslog.h>
46 #include <netinet/in.h>
47 #include <arpa/inet.h>
48 #include <netdb.h>
49 #include <sys/time.h>
50 #include <sys/resource.h>
51 #include <setjmp.h>
53 #ifdef TM_IN_SYS_TIME
54 #include <sys/time.h>
55 #else
56 #include <time.h>
57 #endif
59 #ifdef HAVE_PR_SET_NAME
60 #include <sys/prctl.h>
61 #endif
63 #include "pwmd-error.h"
64 #include <gcrypt.h>
66 #include "mem.h"
67 #include "xml.h"
68 #include "common.h"
69 #include "commands.h"
70 #include "cache.h"
71 #include "misc.h"
72 #include "mutex.h"
73 #include "rcfile.h"
74 #include "agent.h"
75 #include "convert.h"
77 static gboolean quit;
78 static gboolean exiting;
79 static gboolean cmdline;
80 static jmp_buf jmp;
81 static gboolean nofork;
82 static pthread_cond_t quit_cond;
83 static pthread_mutex_t quit_mutex;
84 static gboolean no_passphrase_file = FALSE;
85 #ifdef WITH_GNUTLS
86 static gint tls_fd;
87 static gint tls6_fd;
88 static pthread_t tls_tid;
89 static pthread_t tls6_tid;
91 static gboolean start_stop_tls(gboolean term);
92 #endif
94 static gboolean do_cache_push(const gchar *filename, struct crypto_s *crypto);
95 static gboolean signal_loop(sigset_t sigset);
97 GCRY_THREAD_OPTION_PTHREAD_IMPL;
99 static void cache_push_from_rcfile()
101 struct crypto_s *crypto;
102 gpg_error_t rc = init_client_crypto(&crypto);
104 if (rc) {
105 log_write("%s: %s", __FUNCTION__, pwmd_strerror(rc));
106 return;
109 rc = set_agent_option(crypto->agent, "pinentry-mode", "error");
110 if (rc) {
111 log_write("%s: %s", __FUNCTION__, pwmd_strerror(rc));
112 return;
115 if (g_key_file_has_key(keyfileh, "global", "cache_push", NULL)) {
116 gchar **cache_push = g_key_file_get_string_list(keyfileh, "global",
117 "cache_push", NULL, NULL);
118 gchar **p;
120 for (p = cache_push; *p; p++) {
121 (void)do_cache_push(*p, crypto);
122 cleanup_crypto_stage1(crypto);
125 g_strfreev(cache_push);
128 (void)kill_scd(crypto->agent);
129 cleanup_crypto(&crypto);
132 static void *reload_rcfile_thread(void *arg)
134 #ifdef HAVE_PR_SET_NAME
135 prctl(PR_SET_NAME, "reload rcfile");
136 #endif
137 pthread_setspecific(thread_name_key, g_strdup(__FUNCTION__));
138 MUTEX_LOCK(&rcfile_mutex);
139 pthread_cleanup_push(cleanup_mutex_cb, &rcfile_mutex);
141 for (;;) {
142 gboolean b = disable_list_and_dump;
143 gchar **users;
144 GKeyFile *k;
146 pthread_cond_wait(&rcfile_cond, &rcfile_mutex);
147 users = g_key_file_get_string_list(keyfileh, "global", "allowed", NULL, NULL);
148 log_write(_("reloading configuration file '%s'"), rcfile);
149 k = parse_rcfile(FALSE, cmdline);
150 if (k) {
151 g_key_file_free(keyfileh);
152 keyfileh = k;
153 cache_push_from_rcfile();
154 clear_rcfile_keys();
157 disable_list_and_dump = !disable_list_and_dump ? b : TRUE;
158 g_key_file_set_string_list(keyfileh, "global", "allowed",
159 (const gchar **)users, g_strv_length(users));
160 g_strfreev(users);
161 #ifdef WITH_GNUTLS
162 /* Kill existing listening threads since the configured listening
163 * protocols may have changed. */
164 start_stop_tls(TRUE);
165 start_stop_tls(FALSE);
166 #endif
169 pthread_cleanup_pop(1);
170 return NULL;
173 gpg_error_t send_error(assuan_context_t ctx, gpg_error_t e)
175 struct client_s *client = assuan_get_pointer(ctx);
177 if (gpg_err_source(e) == GPG_ERR_SOURCE_UNKNOWN)
178 e = gpg_error(e);
180 if (client)
181 client->last_rc = e;
183 if (!e)
184 return assuan_process_done(ctx, 0);
186 if (!ctx) {
187 log_write("%s", pwmd_strerror(e));
188 return e;
191 if (gpg_err_code(e) == GPG_ERR_BAD_DATA) {
192 xmlErrorPtr xe = client->xml_error;
194 if (!xe)
195 xe = xmlGetLastError();
196 if (xe) {
197 log_write("%s", xe->message);
198 if (client->last_error)
199 g_free(client->last_error);
201 client->last_error = g_strdup(xe->message);
204 e = assuan_process_done(ctx, assuan_set_error(ctx, e,
205 xe ? xe->message : NULL));
207 if (xe == client->xml_error)
208 xmlResetError(xe);
209 else
210 xmlResetLastError();
212 client->xml_error = NULL;
213 return e;
216 return assuan_process_done(ctx, assuan_set_error(ctx, e, pwmd_strerror(e)));
219 int assuan_log_cb(assuan_context_t ctx, void *data, unsigned cat,
220 const char *msg)
222 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
223 int i, t;
224 gboolean match = FALSE;
226 pthread_mutex_lock(&m);
227 pthread_cleanup_push((void (*)(void *))pthread_mutex_unlock, &m);
228 t = g_strv_length(debug_level);
230 for (i = 0; i < t; i++) {
231 if (!g_ascii_strcasecmp(debug_level[i], (gchar *)"init")
232 && cat == ASSUAN_LOG_INIT) {
233 match = TRUE;
234 break;
237 if (!g_ascii_strcasecmp(debug_level[i], (gchar *)"ctx")
238 && cat == ASSUAN_LOG_CTX) {
239 match = TRUE;
240 break;
243 if (!g_ascii_strcasecmp(debug_level[i], (gchar *)"engine")
244 && cat == ASSUAN_LOG_ENGINE) {
245 match = TRUE;
246 break;
249 if (!g_ascii_strcasecmp(debug_level[i], (gchar *)"data")
250 && cat == ASSUAN_LOG_DATA) {
251 match = TRUE;
252 break;
255 if (!g_ascii_strcasecmp(debug_level[i], (gchar *)"sysio")
256 && cat == ASSUAN_LOG_SYSIO) {
257 match = TRUE;
258 break;
261 if (!g_ascii_strcasecmp(debug_level[i], (gchar *)"control")
262 && cat == ASSUAN_LOG_CONTROL) {
263 match = TRUE;
264 break;
268 if (match && msg) {
269 if (logfile) {
270 int fd;
272 if ((fd = open(logfile, O_WRONLY|O_CREAT|O_APPEND, 0600)) == -1)
273 warn("%s", logfile);
274 else {
275 pthread_cleanup_push(cleanup_fd_cb, &fd);
276 write(fd, msg, strlen(msg));
277 pthread_cleanup_pop(1);
281 if (nofork) {
282 fprintf(stderr, "%s%s", data ? (gchar *)data : "", msg);
283 fflush(stderr);
287 pthread_cleanup_pop(1);
288 return match;
291 void log_write(const gchar *fmt, ...)
293 gchar *args, *line;
294 va_list ap;
295 struct tm *tm;
296 time_t now;
297 gchar tbuf[21];
298 gint fd = -1;
299 gchar *name = NULL;
300 gchar buf[255];
301 pthread_t tid = pthread_self();
302 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
304 if ((!logfile && !isatty(STDERR_FILENO) && !log_syslog) || !fmt)
305 return;
307 pthread_mutex_lock(&m);
308 pthread_cleanup_push((void (*)(void *))pthread_mutex_unlock, &m);
309 pthread_cleanup_push(cleanup_fd_cb, &fd);
311 if (!cmdline && logfile) {
312 if ((fd = open(logfile, O_WRONLY|O_CREAT|O_APPEND, 0600)) == -1)
313 warn("%s", logfile);
316 va_start(ap, fmt);
318 if (g_vasprintf(&args, fmt, ap) != -1) {
319 if (cmdline) {
320 pthread_cleanup_push(g_free, args);
321 fprintf(stderr, "%s\n", args);
322 fflush(stderr);
323 pthread_cleanup_pop(1);
325 else {
326 pthread_cleanup_push(g_free, args);
327 name = pthread_getspecific(thread_name_key);
328 name = print_fmt(buf, sizeof(buf), "%s(%p): ",
329 name ? name : _("unknown"), (pthread_t *)tid);
331 if (!cmdline && log_syslog && !nofork)
332 syslog(LOG_INFO, "%s%s", name, args);
334 time(&now);
335 tm = localtime(&now);
336 strftime(tbuf, sizeof(tbuf), "%b %d %Y %H:%M:%S ", tm);
337 tbuf[sizeof(tbuf) - 1] = 0;
339 if (args[strlen(args)-1] == '\n')
340 args[strlen(args)-1] = 0;
342 line = g_strdup_printf("%s %i %s%s\n", tbuf, getpid(), name,
343 args);
344 pthread_cleanup_pop(1);
345 if (line) {
346 pthread_cleanup_push(g_free, line);
347 if (logfile && fd != -1) {
348 write(fd, line, strlen(line));
349 fsync(fd);
352 if (nofork) {
353 fprintf(stdout, "%s", line);
354 fflush(stdout);
357 pthread_cleanup_pop(1);
362 va_end(ap);
363 pthread_cleanup_pop(1);
364 pthread_cleanup_pop(0);
365 pthread_mutex_unlock(&m);
368 #ifdef WITH_GNUTLS
369 static gint secure_mem_check(const void *arg)
371 return 1;
373 #endif
375 static gpg_error_t setup_crypto()
377 gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
379 if (!gcry_check_version(GCRYPT_VERSION)) {
380 fprintf(stderr, _("gcry_check_version(): Incompatible libgcrypt. "
381 "Wanted %s, got %s.\n"), GCRYPT_VERSION,
382 gcry_check_version(NULL));
383 return GPG_ERR_UNKNOWN_VERSION;
386 gcry_set_allocation_handler(g_malloc, g_malloc, NULL, g_realloc, g_free);
387 return 0;
390 static gpg_error_t validate_peer(struct client_s *cl)
392 gchar **users;
393 gboolean allowed = FALSE;
394 assuan_peercred_t peercred;
395 gpg_error_t rc;
397 #ifdef WITH_GNUTLS
398 if (cl->thd->remote)
399 return 0;
400 #endif
402 rc = assuan_get_peercred(cl->ctx, &peercred);
403 if (rc)
404 return rc;
406 users = g_key_file_get_string_list(keyfileh, "global", "allowed", NULL, NULL);
408 if (users) {
409 for (gchar **p = users; *p; p++) {
410 struct passwd pw, *result;
411 struct group gr, *gresult;
412 char *buf;
414 if (*(*p) == '@') {
415 size_t len = sysconf(_SC_GETGR_R_SIZE_MAX);
417 if (len == -1)
418 len = 16384;
420 buf = g_malloc(len);
422 if (!buf) {
423 g_strfreev(users);
424 return GPG_ERR_ENOMEM;
427 if (!getgrnam_r(*(p)+1, &gr, buf, len, &gresult) && gresult) {
428 if (gresult->gr_gid == peercred->gid) {
429 g_free(buf);
430 allowed = TRUE;
431 break;
434 len = sysconf(_SC_GETPW_R_SIZE_MAX);
436 if (len == -1)
437 len = 16384;
439 gchar *tbuf = g_malloc(len);
441 for (gchar **t = gresult->gr_mem; *t; t++) {
442 if (!getpwnam_r(*t, &pw, tbuf, len, &result) && result) {
443 if (result->pw_uid == peercred->uid) {
444 g_free(buf);
445 allowed = TRUE;
446 break;
451 g_free(tbuf);
453 if (allowed)
454 break;
457 else {
458 size_t len = sysconf(_SC_GETPW_R_SIZE_MAX);
460 if (len == -1)
461 len = 16384;
463 buf = g_malloc(len);
465 if (!buf) {
466 g_strfreev(users);
467 return GPG_ERR_ENOMEM;
470 if (!getpwnam_r(*p, &pw, buf, len, &result) && result) {
471 if (result->pw_uid == peercred->uid) {
472 g_free(buf);
473 allowed = TRUE;
474 break;
479 g_free(buf);
482 g_strfreev(users);
485 log_write("peer %s: uid=%i, gid=%i, pid=%i",
486 allowed ? _("accepted") : _("rejected"), peercred->uid,
487 peercred->gid, peercred->pid);
488 return allowed ? 0 : GPG_ERR_INV_USER_ID;
491 static void xml_error_cb(void *data, xmlErrorPtr e)
493 struct client_s *client = data;
496 * Keep the first reported error as the one to show in the error
497 * description. Reset in send_error().
499 if (client->xml_error)
500 return;
502 xmlCopyError(e, client->xml_error);
505 static pid_t hook_waitpid(assuan_context_t ctx, pid_t pid, int action,
506 int *status, int options)
508 return waitpid(pid, status, options);
511 static ssize_t hook_read(assuan_context_t ctx, assuan_fd_t fd, void *data,
512 size_t len)
514 #ifdef WITH_GNUTLS
515 struct client_s *client = assuan_get_pointer(ctx);
517 if (client->thd->remote)
518 return tls_read_hook(ctx, (gint)fd, data, len);
519 #endif
521 return read((gint)fd, data, len);
524 static ssize_t hook_write(assuan_context_t ctx, assuan_fd_t fd,
525 const void *data, size_t len)
527 #ifdef WITH_GNUTLS
528 struct client_s *client = assuan_get_pointer(ctx);
530 if (client->thd->remote)
531 return tls_write_hook(ctx, (gint)fd, data, len);
532 #endif
534 return write((gint)fd, data, len);
537 static gboolean new_connection(struct client_s *cl)
539 gpg_error_t rc;
540 static struct assuan_malloc_hooks mhooks = { g_malloc, g_realloc, g_free };
541 static struct assuan_system_hooks shooks = {
542 ASSUAN_SYSTEM_HOOKS_VERSION,
543 __assuan_usleep,
544 __assuan_pipe,
545 __assuan_close,
546 hook_read,
547 hook_write,
548 //FIXME
549 NULL, //recvmsg
550 NULL, //sendmsg both are used for FD passing
551 __assuan_spawn,
552 hook_waitpid,
553 __assuan_socketpair,
554 __assuan_socket,
555 __assuan_connect
558 #ifdef WITH_GNUTLS
559 if (cl->thd->remote) {
560 gchar *prio = get_key_file_string("global", "tls_cipher_suite");
562 cl->thd->tls = tls_init(cl->thd->fd, prio);
563 g_free(prio);
564 if (!cl->thd->tls)
565 return FALSE;
567 #endif
569 rc = assuan_new_ext(&cl->ctx, GPG_ERR_SOURCE_DEFAULT, &mhooks,
570 debug_level ? assuan_log_cb : NULL, NULL);
571 if (rc)
572 goto fail;
574 assuan_ctx_set_system_hooks(cl->ctx, &shooks);
575 rc = assuan_init_socket_server(cl->ctx, cl->thd->fd, 2);
576 if (rc)
577 goto fail;
579 assuan_set_pointer(cl->ctx, cl);
580 assuan_set_hello_line(cl->ctx, PACKAGE_STRING);
581 rc = register_commands(cl->ctx);
582 if (rc)
583 goto fail;
585 rc = assuan_accept(cl->ctx);
586 if (rc)
587 goto fail;
589 rc = validate_peer(cl);
590 /* May not be implemented on all platforms. */
591 if (rc && gpg_err_code(rc) != GPG_ERR_ASS_GENERAL)
592 goto fail;
594 rc = init_client_crypto(&cl->crypto);
595 if (rc)
596 goto fail;
598 cl->crypto->agent->client_ctx = cl->ctx;
599 cl->crypto->client_ctx = cl->ctx;
600 xmlSetStructuredErrorFunc(cl, xml_error_cb);
601 return TRUE;
603 fail:
604 log_write("%s", pwmd_strerror(rc));
605 return FALSE;
609 * This is called after a client_thread() terminates. Set with
610 * pthread_cleanup_push().
612 static void cleanup_cb(void *arg)
614 struct client_thread_s *cn = arg;
615 struct client_s *cl = cn->cl;
617 MUTEX_LOCK(&cn_mutex);
618 cn_thread_list = g_slist_remove(cn_thread_list, cn);
619 MUTEX_UNLOCK(&cn_mutex);
621 if (cl) {
622 cleanup_client(cl);
624 #ifdef WITH_GNUTLS
625 if (cn->tls) {
626 gnutls_deinit(cn->tls->ses);
627 g_free(cn->tls->fp);
628 g_free(cn->tls);
630 #endif
632 if (cl->ctx)
633 assuan_release(cl->ctx);
634 else if (cl->thd && cl->thd->fd != -1)
635 close(cl->thd->fd);
637 if (cl->crypto)
638 cleanup_crypto(&cl->crypto);
640 g_free(cl);
642 else {
643 if (cn->fd != -1)
644 close(cn->fd);
647 while (cn->msg_queue) {
648 struct status_msg_s *msg = cn->msg_queue;
650 cn->msg_queue = msg->next;
651 g_free(msg->line);
652 g_free(msg);
655 if (cn->status_msg_pipe[0] != -1)
656 close(cn->status_msg_pipe[0]);
658 if (cn->status_msg_pipe[1] != -1)
659 close(cn->status_msg_pipe[1]);
661 pthread_mutex_destroy(&cn->status_mutex);
662 log_write(_("exiting, fd=%i"), cn->fd);
663 g_free(cn);
664 send_status_all(STATUS_CLIENTS, NULL);
665 pthread_cond_signal(&quit_cond);
668 static gpg_error_t send_msg_queue(struct client_thread_s *thd)
670 MUTEX_LOCK(&thd->status_mutex);
671 gpg_error_t rc = 0;
672 gchar c;
674 read(thd->status_msg_pipe[0], &c, 1);
676 while (thd->msg_queue) {
677 struct status_msg_s *msg = thd->msg_queue;
679 thd->msg_queue = thd->msg_queue->next;
680 MUTEX_UNLOCK(&thd->status_mutex);
681 rc = send_status(thd->cl->ctx, msg->s, msg->line);
682 MUTEX_LOCK(&thd->status_mutex);
683 g_free(msg->line);
684 g_free(msg);
686 if (rc)
687 break;
690 MUTEX_UNLOCK(&thd->status_mutex);
691 return rc;
694 static void *client_thread(void *data)
696 struct client_thread_s *thd = data;
697 struct client_s *cl = g_malloc0(sizeof(struct client_s));
699 #ifdef HAVE_PR_SET_NAME
700 prctl(PR_SET_NAME, "client");
701 #endif
702 pthread_setspecific(thread_name_key, g_strdup(__FUNCTION__));
704 if (!cl) {
705 log_write("%s(%i): %s", __FILE__, __LINE__,
706 pwmd_strerror(GPG_ERR_ENOMEM));
707 return NULL;
710 MUTEX_LOCK(&cn_mutex);
711 pthread_cleanup_push(cleanup_cb, thd);
712 thd->cl = cl;
713 cl->thd = thd;
714 MUTEX_UNLOCK(&cn_mutex);
716 if (new_connection(cl)) {
717 gboolean finished = FALSE;
718 gpg_error_t rc;
720 send_status_all(STATUS_CLIENTS, NULL);
721 rc = send_status(cl->ctx, STATUS_CACHE, NULL);
722 if (rc) {
723 log_write("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror(rc));
724 finished = TRUE;
727 while (!finished) {
728 fd_set rfds;
729 gint n;
730 gint eof;
732 FD_ZERO(&rfds);
733 FD_SET(thd->fd, &rfds);
734 FD_SET(thd->status_msg_pipe[0], &rfds);
735 n = thd->fd > thd->status_msg_pipe[0] ? thd->fd : thd->status_msg_pipe[0];
737 n = select(n+1, &rfds, NULL, NULL, NULL);
738 if (n == -1) {
739 log_write("%s", strerror(errno));
740 break;
743 if (FD_ISSET(thd->status_msg_pipe[0], &rfds)) {
744 rc = send_msg_queue(thd);
745 if (rc && gpg_err_code(rc) != GPG_ERR_EPIPE) {
746 log_write("%s(%i): %s", __FUNCTION__, __LINE__,
747 pwmd_strerror(rc));
748 break;
752 if (!FD_ISSET(thd->fd, &rfds))
753 continue;
755 rc = assuan_process_next(cl->ctx, &eof);
756 if (rc || eof) {
757 if (gpg_err_code(rc) == GPG_ERR_EOF || eof)
758 break;
760 log_write("assuan_process_next(): %s", pwmd_strerror(rc));
761 rc = send_error(cl->ctx, rc);
763 if (rc) {
764 log_write("assuan_process_done(): %s", pwmd_strerror(rc));
765 break;
769 /* Since the msg queue pipe fd's are non-blocking, check for
770 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
771 * client has already disconnected and will be converted to
772 * GPG_ERR_EOF during assuan_process_next().
774 rc = send_msg_queue(thd);
775 if (rc && gpg_err_code(rc) != GPG_ERR_EPIPE) {
776 log_write("%s(%i): %s", __FUNCTION__, __LINE__,
777 pwmd_strerror(rc));
778 break;
783 pthread_cleanup_pop(1);
784 return NULL;
787 static gboolean xml_import(const gchar *filename, const gchar *outfile,
788 const gchar *keygrip, const char *sign_keygrip, const gchar *keyfile,
789 gboolean no_passphrase, const gchar *cipher, const gchar *params,
790 gulong s2k_count, guint64 iterations)
792 xmlDocPtr doc;
793 gint fd;
794 struct stat st;
795 gint len;
796 xmlChar *xmlbuf;
797 xmlChar *xml;
798 gpg_error_t rc;
799 struct crypto_s *crypto;
800 gint algo = cipher ? cipher_string_to_gcrypt((gchar *)cipher) :
801 GCRY_CIPHER_AES256;
803 if (algo == -1) {
804 log_write("%s", pwmd_strerror(GPG_ERR_CIPHER_ALGO));
805 return FALSE;
808 if (stat(filename, &st) == -1) {
809 log_write("%s: %s", filename, pwmd_strerror(gpg_error_from_syserror()));
810 return FALSE;
813 rc = init_client_crypto(&crypto);
814 if (rc)
815 return FALSE;
817 memcpy(&crypto->save.hdr, &crypto->hdr, sizeof(file_header_t));
818 crypto->save.hdr.flags = set_cipher_flag(crypto->save.hdr.flags, algo);
819 log_write(_("Importing XML from '%s'. Output will be written to '%s' ..."),
820 filename, outfile);
822 if ((fd = open(filename, O_RDONLY)) == -1) {
823 log_write("%s: %s", filename, pwmd_strerror(gpg_error_from_syserror()));
824 goto fail;
827 if ((xmlbuf = xmalloc(st.st_size+1)) == NULL) {
828 close(fd);
829 log_write("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror(GPG_ERR_ENOMEM));
830 goto fail;
833 if (read(fd, xmlbuf, st.st_size) == -1) {
834 rc = gpg_error_from_syserror();
835 close(fd);
836 log_write("%s: %s", filename, pwmd_strerror(rc));
837 goto fail;
840 close(fd);
841 xmlbuf[st.st_size] = 0;
843 * Make sure the document validates.
845 if ((doc = xmlReadDoc(xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS)) == NULL) {
846 log_write("xmlReadDoc() failed");
847 xfree(xmlbuf);
848 goto fail;
851 xfree(xmlbuf);
852 xmlNodePtr n = xmlDocGetRootElement(doc);
853 if (!xmlStrEqual(n->name, (xmlChar *)"pwmd")) {
854 log_write(_("Could not find root \"pwmd\" element."));
855 rc = GPG_ERR_BAD_DATA;
858 if (!rc)
859 rc = validate_import(n ? n->children : n);
861 if (rc) {
862 log_write("%s", pwmd_strerror(rc));
863 xmlFreeDoc(doc);
864 goto fail;
867 xmlDocDumpMemory(doc, &xml, &len);
868 xmlFreeDoc(doc);
869 crypto->save.s2k_count = (gulong)s2k_count;
870 crypto->save.hdr.iterations = iterations;
871 rc = set_pinentry_options(crypto->agent);
872 if (!rc)
873 rc = export_common(crypto, keygrip, sign_keygrip, no_passphrase, xml,
874 len, outfile, params, keyfile);
876 xmlFree(xml);
877 if (rc) {
878 send_error(NULL, rc);
879 goto fail;
882 cleanup_crypto(&crypto);
883 return TRUE;
885 fail:
886 cleanup_crypto(&crypto);
887 return FALSE;
890 static gboolean do_cache_push(const gchar *filename, struct crypto_s *crypto)
892 guchar md5file[16];
893 gpg_error_t rc;
894 gchar *key = NULL;
895 gsize keylen;
896 xmlDocPtr doc;
897 struct cache_data_s *cdata;
898 guchar *crc;
899 gsize len;
901 log_write(_("Trying to add datafile '%s' to the file cache ..."),
902 filename);
904 if (valid_filename(filename) == FALSE) {
905 log_write(_("%s: Invalid characters in filename"), filename);
906 return FALSE;
909 rc = read_data_file(filename, crypto);
910 if (rc) {
911 log_write("%s", pwmd_strerror(rc));
912 return FALSE;
915 if ((key = get_key_file_string(filename, "passphrase"))) {
916 log_write(_("Trying the passphrase specified in config ..."));
917 keylen = strlen(key);
919 else if ((key = get_key_file_string(filename, "passphrase_file"))) {
920 gint fd = open((gchar *)key, O_RDONLY);
921 struct stat st;
923 log_write(_("Trying the passphrase using file '%s' ..."), key);
924 if (fd == -1) {
925 log_write("%s: %s", key, pwmd_strerror(gpg_error_from_syserror()));
926 g_free(key);
927 return FALSE;
930 stat((gchar *)key, &st);
931 g_free(key);
932 key = g_malloc(st.st_size);
933 if (read(fd, key, st.st_size) != st.st_size) {
934 log_write("short read() count");
935 g_free(key);
936 close(fd);
937 return FALSE;
940 keylen = st.st_size;
943 if (key) {
944 rc = set_agent_passphrase(crypto, key, keylen);
945 g_free(key);
946 if (rc) {
947 log_write("%s", pwmd_strerror(rc));
948 return FALSE;
952 crypto->filename = g_strdup(filename);
953 rc = decrypt_data(NULL, crypto);
954 if (rc) {
955 log_write("%s", pwmd_strerror(rc));
956 return FALSE;
959 doc = parse_doc((gchar *)crypto->plaintext, crypto->plaintext_len);
960 if (!doc) {
961 log_write("%s", pwmd_strerror(GPG_ERR_ENOMEM));
962 return FALSE;
965 gcry_md_hash_buffer(GCRY_MD_MD5, md5file, filename, strlen(filename));
966 cdata = g_malloc0(sizeof(struct cache_data_s));
967 if (!cdata) {
968 xmlFreeDoc(doc);
969 log_write("%s", pwmd_strerror(GPG_ERR_ENOMEM));
970 return FALSE;
973 rc = get_checksum(filename, &crc, &len);
974 if (rc) {
975 log_write("%s", pwmd_strerror(rc));
976 xmlFreeDoc(doc);
977 free_cache_data_once(cdata);
978 return FALSE;
981 cdata->crc = crc;
982 rc = encrypt_xml(NULL, cache_key, cache_keysize, GCRY_CIPHER_AES,
983 crypto->plaintext, crypto->plaintext_len, &cdata->doc,
984 &cdata->doclen, &cache_iv, &cache_blocksize, 0);
985 if (rc) {
986 log_write("%s", pwmd_strerror(rc));
987 xmlFreeDoc(doc);
988 free_cache_data_once(cdata);
989 return FALSE;
992 gcry_sexp_build((gcry_sexp_t *)&cdata->pubkey, NULL, "%S", crypto->pkey_sexp);
993 gcry_sexp_build((gcry_sexp_t *)&cdata->sigkey, NULL, "%S", crypto->sigpkey_sexp);
994 gint timeout = get_key_file_integer(filename, "cache_timeout");
995 cache_add_file(md5file, crypto->grip, cdata, timeout);
996 log_write(_("Successfully added '%s' to the cache."), filename);
997 return TRUE;
1000 static gpg_error_t init_client_thread(gint fd, const gchar *addr)
1002 gpg_error_t rc = 0;
1003 struct client_thread_s *new = g_malloc0(sizeof(struct client_thread_s));
1005 if (!new) {
1006 close(fd);
1007 return GPG_ERR_ENOMEM;
1010 MUTEX_LOCK(&cn_mutex);
1011 pthread_cleanup_push(cleanup_mutex_cb, &cn_mutex);
1013 if (pipe(new->status_msg_pipe) == -1)
1014 rc = gpg_error_from_syserror();
1016 if (!rc) {
1017 fcntl(new->status_msg_pipe[0], F_SETFL, O_NONBLOCK);
1018 fcntl(new->status_msg_pipe[1], F_SETFL, O_NONBLOCK);
1019 pthread_mutex_init(&new->status_mutex, NULL);
1022 if (!rc) {
1023 #ifdef WITH_GNUTLS
1024 new->remote = addr ? TRUE : FALSE;
1025 #endif
1026 new->fd = fd;
1027 rc = create_thread(client_thread, new, &new->tid, TRUE);
1028 if (rc) {
1029 close(new->status_msg_pipe[0]);
1030 close(new->status_msg_pipe[1]);
1031 pthread_mutex_destroy(&new->status_mutex);
1035 if (!rc) {
1036 cn_thread_list = g_slist_append(cn_thread_list, new);
1037 if (addr)
1038 log_write(_("new connection: tid=%p, fd=%i, addr=%s"),
1039 (pthread_t *)new->tid, fd, addr);
1040 else
1041 log_write(_("new connection: tid=%p, fd=%i"),
1042 (pthread_t *)new->tid, fd);
1045 pthread_cleanup_pop(1);
1047 if (rc) {
1048 g_free(new);
1049 close(fd);
1050 log_write("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1051 pwmd_strerror(rc));
1053 return rc;
1056 #ifdef WITH_GNUTLS
1057 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1058 static void *get_in_addr(struct sockaddr *sa)
1060 if (sa->sa_family == AF_INET)
1061 return &(((struct sockaddr_in*)sa)->sin_addr);
1063 return &(((struct sockaddr_in6*)sa)->sin6_addr);
1066 static void *tcp_accept_thread(void *arg)
1068 gint sockfd = *(gint*)arg;
1070 #ifdef HAVE_PR_SET_NAME
1071 prctl(PR_SET_NAME, "tcp_accept");
1072 #endif
1073 pthread_setspecific(thread_name_key, g_strdup(__FUNCTION__));
1075 for (;;) {
1076 struct sockaddr_storage raddr;
1077 socklen_t slen = sizeof(raddr);
1078 gint fd = -1;
1079 gulong n;
1080 gchar *t;
1081 gchar s[INET6_ADDRSTRLEN];
1083 fd = accept(sockfd, (struct sockaddr *)&raddr, &slen);
1084 if (fd == -1) {
1085 if (errno != EAGAIN) {
1086 if (!quit) // probably EBADF
1087 log_write("accept(): %s", strerror(errno));
1089 break;
1092 continue;
1095 if (quit)
1096 break;
1098 inet_ntop(raddr.ss_family, get_in_addr((struct sockaddr *)&raddr),
1099 s, sizeof s);
1100 (void)init_client_thread(fd, s);
1101 t = get_key_file_string("global", "tcp_wait");
1102 n = strtol(t, NULL, 10);
1103 g_free(t);
1104 if (n > 0)
1105 usleep(n*100000);
1108 /* Just in case accept() failed for some reason other than EBADF */
1109 quit = 1;
1110 return NULL;
1113 static gboolean start_stop_tls_with_protocol(gboolean ipv6, gboolean term)
1115 struct addrinfo hints, *servinfo, *p;
1116 gint port = get_key_file_integer("global", "tcp_port");
1117 gchar buf[7];
1118 gint n;
1119 gpg_error_t rc;
1120 gint *fd = ipv6 ? &tls6_fd : &tls_fd;
1122 if (term || get_key_file_boolean("global", "enable_tcp") == FALSE) {
1123 if (tls6_fd != -1) {
1124 pthread_cancel(tls6_tid);
1125 pthread_join(tls6_tid, NULL);
1126 shutdown(tls6_fd, SHUT_RDWR);
1127 close(tls6_fd);
1128 tls6_fd = -1;
1131 if (tls_fd != -1) {
1132 pthread_cancel(tls_tid);
1133 pthread_join(tls_tid, NULL);
1134 shutdown(tls_fd, SHUT_RDWR);
1135 close(tls_fd);
1136 tls_fd = -1;
1139 /* A client may still be connected. */
1140 if (!quit && x509_cred != NULL)
1141 tls_deinit_params();
1143 return TRUE;
1146 if ((ipv6 && tls6_fd != -1) || (!ipv6 && tls_fd != -1))
1147 return TRUE;
1149 memset(&hints, 0, sizeof(hints));
1150 hints.ai_family = ipv6 ? AF_INET6 : AF_INET;
1151 hints.ai_socktype = SOCK_STREAM;
1152 hints.ai_flags = AI_PASSIVE;
1154 if ((n = getaddrinfo(NULL, print_fmt(buf, sizeof(buf), "%i", port),
1155 &hints, &servinfo)) == -1) {
1156 log_write("getaddrinfo(): %s", gai_strerror(n));
1157 return FALSE;
1160 for (n = 0, p = servinfo; p != NULL; p = p->ai_next) {
1161 if ((ipv6 && p->ai_family != AF_INET6)
1162 || (!ipv6 && p->ai_family != AF_INET))
1163 continue;
1165 if ((*fd = socket(p->ai_family, p->ai_socktype,
1166 p->ai_protocol)) == -1) {
1167 log_write("socket(): %s", strerror(errno));
1168 continue;
1171 if (setsockopt(*fd, SOL_SOCKET, SO_REUSEADDR, &n,
1172 sizeof(int)) == -1) {
1173 log_write("setsockopt(): %s", strerror(errno));
1174 freeaddrinfo(servinfo);
1175 goto fail;
1178 if (bind(*fd, p->ai_addr, p->ai_addrlen) == -1) {
1179 close(*fd);
1180 log_write("bind(): %s", strerror(errno));
1181 continue;
1184 n++;
1185 break;
1188 freeaddrinfo(servinfo);
1190 if (!n) {
1191 log_write("%s", _("could not bind"));
1192 goto fail;
1195 #ifdef HAVE_DECL_SO_BINDTODEVICE
1196 if (g_key_file_has_key(keyfileh, "global", "tcp_interface", NULL)) {
1197 gchar *tmp = get_key_file_string("global", "tcp_interface");
1199 if (setsockopt(*fd, SOL_SOCKET, SO_BINDTODEVICE, tmp, 1)
1200 == -1) {
1201 log_write("setsockopt(): %s", strerror(errno));
1202 g_free(tmp);
1203 goto fail;
1206 g_free(tmp);
1208 #endif
1210 if (x509_cred == NULL) {
1211 rc = tls_init_params();
1212 if (rc)
1213 goto fail;
1216 if (listen(*fd, 0) == -1) {
1217 log_write("listen(): %s", strerror(errno));
1218 goto fail;
1221 if (ipv6)
1222 rc = create_thread(tcp_accept_thread, fd, &tls6_tid, FALSE);
1223 else
1224 rc = create_thread(tcp_accept_thread, fd, &tls_tid, FALSE);
1226 if (rc) {
1227 log_write("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1228 pwmd_strerror(rc));
1229 goto fail;
1232 return TRUE;
1234 fail:
1235 start_stop_tls_with_protocol(FALSE, TRUE);
1236 if (tls_fd != -1)
1237 close(tls_fd);
1239 if (tls6_fd != -1)
1240 close(tls6_fd);
1242 tls_fd = -1;
1243 tls6_fd = -1;
1244 return FALSE;
1247 static gboolean start_stop_tls(gboolean term)
1249 gchar *s = get_key_file_string("global", "tcp_bind");
1250 gboolean b;
1252 if (!s)
1253 return FALSE;
1255 if (!g_strcmp0(s, "any")) {
1256 b = start_stop_tls_with_protocol(FALSE, term);
1257 if (b)
1258 b = start_stop_tls_with_protocol(TRUE, term);
1260 else if (!g_strcmp0(s, "ipv4"))
1261 b = start_stop_tls_with_protocol(FALSE, term);
1262 else if (!g_strcmp0(s, "ipv6"))
1263 b = start_stop_tls_with_protocol(TRUE, term);
1264 else
1265 b = FALSE;
1267 g_free(s);
1268 return b;
1270 #endif
1272 static void *accept_thread(void *arg)
1274 gint sockfd = *(gint *)arg;
1276 #ifdef HAVE_PR_SET_NAME
1277 prctl(PR_SET_NAME, "accept");
1278 #endif
1279 pthread_setspecific(thread_name_key, g_strdup(__FUNCTION__));
1281 for (;;) {
1282 socklen_t slen = sizeof(struct sockaddr_un);
1283 struct sockaddr_un raddr;
1284 gint fd;
1286 fd = accept(sockfd, (struct sockaddr *)&raddr, &slen);
1287 if (fd == -1) {
1288 if (errno != EAGAIN) {
1289 if (!quit) // probably EBADF
1290 log_write("accept(): %s", pwmd_strerror(gpg_error_from_syserror()));
1292 break;
1294 continue;
1297 (void)init_client_thread(fd, NULL);
1300 /* Just in case accept() failed for some reason other than EBADF */
1301 quit = TRUE;
1302 return NULL;
1305 static void *cache_timer_thread(void *arg)
1307 #ifdef HAVE_PR_SET_NAME
1308 prctl(PR_SET_NAME, "cache timer");
1309 #endif
1310 pthread_setspecific(thread_name_key, g_strdup(__FUNCTION__));
1312 for (;;) {
1313 sleep(1);
1314 cache_adjust_timeout();
1317 return NULL;
1320 static void catch_sigabrt(int sig)
1322 cache_clear(NULL);
1323 #ifndef MEM_DEBUG
1324 xpanic();
1325 #endif
1328 static gboolean signal_loop(sigset_t sigset)
1330 gboolean done = FALSE;
1331 gboolean sigint = FALSE;
1333 do {
1334 gint sig = sigwaitinfo(&sigset, NULL);
1336 if (sig == -1) {
1337 if (errno != EAGAIN)
1338 log_write("sigwaitinfo(): %s", strerror(errno));
1339 continue;
1342 if (sig != SIGUSR2)
1343 log_write(_("caught signal %i (%s)"), sig, strsignal(sig));
1345 switch (sig) {
1346 case SIGHUP:
1347 pthread_cond_signal(&rcfile_cond);
1348 break;
1349 case SIGABRT:
1350 // not really handled here.
1351 catch_sigabrt(SIGABRT);
1352 break;
1353 case SIGUSR1:
1354 log_write(_("clearing file cache"));
1355 cache_clear(NULL);
1356 send_status_all(STATUS_CACHE, NULL);
1357 break;
1358 case SIGUSR2:
1359 done = TRUE;
1360 break;
1361 default:
1362 sigint = TRUE;
1363 done = TRUE;
1364 break;
1366 } while (!done);
1368 return sigint;
1371 static void catchsig(int sig)
1373 log_write("Caught SIGSEGV. Exiting.");
1374 #ifdef HAVE_BACKTRACE
1375 BACKTRACE(__FUNCTION__);
1376 #endif
1377 longjmp(jmp, 1);
1380 static void *waiting_for_exit(void *arg)
1382 #ifdef HAVE_PR_SET_NAME
1383 prctl(PR_SET_NAME, "exiting");
1384 #endif
1385 pthread_setspecific(thread_name_key, g_strdup(__FUNCTION__));
1386 log_write(_("waiting for all clients to disconnect"));
1387 MUTEX_LOCK(&quit_mutex);
1388 pthread_cleanup_push(cleanup_mutex_cb, &quit_mutex);
1390 for (;;) {
1391 MUTEX_LOCK(&cn_mutex);
1392 gint n = g_slist_length(cn_thread_list);
1393 MUTEX_UNLOCK(&cn_mutex);
1394 if (!n)
1395 break;
1397 log_write(_("%i clients remain"), n);
1398 pthread_cond_wait(&quit_cond, &quit_mutex);
1401 pthread_cleanup_pop(1);
1402 kill(getpid(), SIGUSR2);
1403 return NULL;
1406 static gboolean server_loop(gint sockfd, gchar **socketpath)
1408 pthread_t accept_tid;
1409 pthread_t cache_timeout_tid;
1410 gboolean cancel_timeout_thread = FALSE, cancel_accept_thread = FALSE;
1411 gint n, i;
1412 sigset_t sigset;
1413 gboolean segv = FALSE;
1414 gpg_error_t rc;
1416 init_commands();
1417 sigemptyset(&sigset);
1419 /* Termination */
1420 sigaddset(&sigset, SIGTERM);
1421 sigaddset(&sigset, SIGINT);
1423 /* Clears the file cache. */
1424 sigaddset(&sigset, SIGUSR1);
1426 /* Configuration file reloading. */
1427 sigaddset(&sigset, SIGHUP);
1429 /* For exiting cleanly. */
1430 sigaddset(&sigset, SIGUSR2);
1432 /* Clears the cache and exits when something bad happens. */
1433 signal(SIGABRT, catch_sigabrt);
1434 sigaddset(&sigset, SIGABRT);
1435 sigprocmask(SIG_BLOCK, &sigset, NULL);
1437 /* Ignored everywhere. When a client disconnects abnormally this signal
1438 * gets raised. It isn't needed though because client_thread() will check
1439 * for rcs even after the client disconnects. */
1440 signal(SIGPIPE, SIG_IGN);
1442 /* Can show a backtrace of the stack in the log. */
1443 signal(SIGSEGV, catchsig);
1445 #ifdef WITH_GNUTLS
1446 /* Needs to be done after the fork(). */
1447 if (!start_stop_tls(FALSE)) {
1448 segv = TRUE;
1449 goto done;
1451 #endif
1453 pthread_mutex_init(&quit_mutex, NULL);
1454 pthread_cond_init(&quit_cond, NULL);
1455 log_write(_("%s started for user %s"), PACKAGE_STRING, g_get_user_name());
1456 #ifndef HAVE_DECL_SO_PEERCRED
1457 log_write(_("Peer credential checking is NOT supported on this OS."));
1458 #endif
1459 #ifdef WITH_GNUTLS
1460 if (get_key_file_boolean("global", "enable_tcp"))
1461 log_write(_("Listening on %s and TCP port %i"), *socketpath,
1462 get_key_file_integer("global", "tcp_port"));
1463 else
1464 log_write(_("Listening on %s"), *socketpath);
1465 #else
1466 log_write(_("Listening on %s"), *socketpath);
1467 #endif
1469 rc = create_thread(reload_rcfile_thread, NULL, &rcfile_tid, FALSE);
1470 if (rc) {
1471 log_write("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1472 pwmd_strerror(rc));
1473 goto done;
1476 rc = create_thread(cache_timer_thread, NULL, &cache_timeout_tid, TRUE);
1477 if (rc) {
1478 log_write("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1479 pwmd_strerror(rc));
1480 goto done;
1483 cancel_timeout_thread = TRUE;
1484 rc = create_thread(accept_thread, &sockfd, &accept_tid, TRUE);
1485 if (rc) {
1486 log_write("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1487 pwmd_strerror(rc));
1488 goto done;
1491 cancel_accept_thread = TRUE;
1492 sigdelset(&sigset, SIGUSR2);
1493 if (!setjmp(jmp))
1494 signal_loop(sigset);
1495 else
1496 segv = TRUE;
1498 done:
1500 * We're out of the main server loop. This happens when a signal was sent
1501 * to terminate the daemon. We'll wait for all clients to disconnect
1502 * before exiting but exit immediately if another termination signal is
1503 * sent.
1505 if (cancel_accept_thread)
1506 pthread_cancel(accept_tid);
1508 shutdown(sockfd, SHUT_RDWR);
1509 close(sockfd);
1510 unlink(*socketpath);
1511 g_free(*socketpath);
1512 *socketpath = NULL;
1513 MUTEX_LOCK(&cn_mutex);
1514 n = g_slist_length(cn_thread_list);
1515 MUTEX_UNLOCK(&cn_mutex);
1517 if (n && !segv) {
1518 pthread_t tid;
1520 rc = create_thread(waiting_for_exit, NULL, &tid, TRUE);
1521 if (!rc) {
1522 sigaddset(&sigset, SIGUSR2);
1523 if (signal_loop(sigset)) {
1524 log_write(_("Received second termination request. Exiting."));
1525 pthread_cancel(tid);
1528 else
1529 log_write("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1530 pwmd_strerror(rc));
1533 if (cancel_timeout_thread)
1534 pthread_cancel(cache_timeout_tid);
1536 MUTEX_LOCK(&cn_mutex);
1537 i = 0;
1538 n = g_slist_length(cn_thread_list);
1540 for (i = 0; i < n; i++) {
1541 struct client_thread_s *thd = g_slist_nth_data(cn_thread_list, i);
1543 if (thd->fd != -1) {
1544 close(thd->fd);
1545 thd->fd = -1;
1549 exiting = TRUE;
1550 MUTEX_UNLOCK(&cn_mutex);
1551 #ifdef WITH_GNUTLS
1552 start_stop_tls(TRUE);
1553 #endif
1554 cache_deinit();
1555 deinit_commands();
1556 pthread_cond_destroy(&quit_cond);
1557 pthread_mutex_destroy(&quit_mutex);
1558 return segv ? EXIT_FAILURE : EXIT_SUCCESS;;
1561 static void startup_failure()
1563 log_write(_("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
1564 cache_clear(NULL);
1567 /* This is called from cache.c:clear_once(). See
1568 * command.c:clearcache_command() for details about lock checking.
1570 static gpg_error_t free_cache_data(file_cache_t *cache)
1572 gpg_error_t rc = GPG_ERR_NO_DATA;
1573 gint i, t;
1574 struct client_thread_s *found = NULL;
1575 gboolean self = FALSE;
1577 if (!cache->data)
1578 return 0;
1580 cache_lock();
1581 MUTEX_LOCK(&cn_mutex);
1582 pthread_cleanup_push(cleanup_mutex_cb, &cn_mutex);
1583 t = g_slist_length(cn_thread_list);
1585 for (i = 0; i < t; i++) {
1586 struct client_thread_s *thd = g_slist_nth_data(cn_thread_list, i);
1588 if (!thd->cl)
1589 continue;
1591 if (!memcmp(thd->cl->md5file, cache->filename,
1592 sizeof(cache->filename))) {
1593 if (pthread_equal(pthread_self(), thd->tid)) {
1594 found = thd;
1595 self = TRUE;
1596 continue;
1599 /* Continue trying to find a client who has the same file open and
1600 * also has a lock. */
1601 rc = cache_lock_mutex(thd->cl->ctx, thd->cl->md5file, -1, FALSE, -1);
1602 if (!rc) {
1603 self = FALSE;
1604 found = thd;
1605 break;
1610 if (self && (!rc || rc == GPG_ERR_NO_DATA))
1611 rc = cache_lock_mutex(found->cl->ctx, found->cl->md5file, -1, FALSE, -1);
1613 if (exiting || !rc || rc == GPG_ERR_NO_DATA) {
1614 free_cache_data_once(cache->data);
1615 cache->data = NULL;
1616 cache->defer_clear = FALSE;
1617 cache->timeout = -1;
1619 if (found)
1620 cache_unlock_mutex(found->cl->md5file, FALSE);
1622 rc = 0;
1625 if (rc)
1626 cache->defer_clear = TRUE;
1628 pthread_cleanup_pop(1);
1629 cache_unlock();
1630 return rc;
1633 static gboolean convert_v2_datafile(const gchar *filename, const gchar *cipher,
1634 const gchar *keyfile, const gchar *keygrip, const gchar *sign_keygrip,
1635 gboolean nopass, const gchar *outfile, const gchar *keyparam,
1636 gulong s2k_count, guint64 iterations)
1638 gpg_error_t rc;
1639 gpointer data = NULL;
1640 gsize datalen;
1641 struct crypto_s *crypto = NULL;
1642 guint16 ver;
1643 gint algo;
1645 if (outfile[0] == '-' && outfile[1] == 0)
1646 outfile = NULL;
1648 log_write(_("Converting version 2 data file \"%s\" ..."), filename);
1649 if (access(filename, R_OK) == -1) {
1650 log_write("%s: %s", filename, pwmd_strerror(gpg_error_from_syserror()));
1651 return FALSE;
1654 if (keyfile) {
1655 log_write(_("Using passphrase file \"%s\" for decryption ..."),
1656 keyfile);
1657 if (access(keyfile, R_OK) == -1) {
1658 log_write("%s: %s", keyfile,
1659 pwmd_strerror(gpg_error_from_syserror()));
1660 return FALSE;
1664 rc = read_v2_datafile(filename, keyfile, &data, &datalen, &ver, &algo);
1665 if (rc) {
1666 log_write("%s", pwmd_strerror(rc));
1667 return FALSE;
1670 if (cipher) {
1671 algo = cipher_string_to_gcrypt(cipher);
1672 if (algo == -1) {
1673 rc = GPG_ERR_CIPHER_ALGO;
1674 goto fail;
1678 if (ver < 0x212) {
1679 xmlDocPtr doc = parse_doc(data, datalen);
1681 if (!doc) {
1682 rc = GPG_ERR_BAD_DATA;
1683 goto fail;
1686 rc = convert_pre_212_elements(doc);
1687 gcry_free(data);
1688 data = NULL;
1689 if (!rc) {
1690 xmlDocDumpFormatMemory(doc, (xmlChar **)&data, (gint *)&datalen, 0);
1691 if (!data)
1692 rc = GPG_ERR_ENOMEM;
1695 xmlFreeDoc(doc);
1696 if (rc)
1697 goto fail;
1700 rc = init_client_crypto(&crypto);
1701 if (!rc) {
1702 rc = set_pinentry_options(crypto->agent);
1703 if (!rc) {
1704 memcpy(&crypto->save.hdr, &crypto->hdr,
1705 sizeof(file_header_t));
1706 crypto->save.hdr.flags = set_cipher_flag(crypto->save.hdr.flags, algo);
1707 crypto->save.s2k_count = (gulong)s2k_count;
1708 crypto->save.hdr.iterations = iterations;
1709 rc = export_common(crypto, keygrip, sign_keygrip, nopass, data,
1710 datalen, outfile, keyparam,
1711 no_passphrase_file ? NULL : keyfile);
1712 if (!rc)
1713 log_write(_("Output written to \"%s\"."), outfile);
1717 fail:
1718 if (ver < 0x212)
1719 xmlFree(data);
1720 else
1721 gcry_free(data);
1722 cleanup_crypto(&crypto);
1724 if (rc)
1725 log_write("%s", pwmd_strerror(rc));
1726 return rc ? FALSE : TRUE;
1729 int main(int argc, char *argv[])
1731 gint opt;
1732 struct sockaddr_un addr;
1733 gchar buf[PATH_MAX];
1734 gchar *socketpath = NULL, *socketdir, *socketname = NULL;
1735 gchar *socketarg = NULL;
1736 gchar *datadir = NULL;
1737 gboolean n;
1738 gint x;
1739 gchar *p;
1740 gchar **cache_push = NULL;
1741 gchar *import = NULL, *keygrip = NULL, *sign_keygrip = NULL;
1742 gchar *keyparam = NULL;
1743 gboolean rcfile_spec = FALSE;
1744 gint estatus = EXIT_FAILURE;
1745 gint sockfd;
1746 gchar *outfile = NULL;
1747 GMemVTable mtable = { xmalloc, xrealloc, xfree, xcalloc, NULL, NULL };
1748 gint do_unlink = 0;
1749 gboolean secure = FALSE;
1750 gint show_version = 0;
1751 gboolean force = FALSE;
1752 gboolean no_passphrase = FALSE;
1753 gpg_error_t rc;
1754 gchar *convertfile = NULL;
1755 gchar *cipher = NULL;
1756 gchar *keyfile = NULL;
1757 glong s2k_count = -1;
1758 guint64 iterations = 0;
1759 GError *error = NULL;
1760 gchar *debug_level_opt = NULL;
1761 GOptionContext *context;
1762 GOptionEntry options[] =
1764 { "version", 0, 0, G_OPTION_ARG_NONE, &show_version,
1765 "version information", NULL },
1766 { "no-fork", 'n', 0, G_OPTION_ARG_NONE, &nofork,
1767 "run as a foreground process", NULL },
1768 { "disable-dump", 'D', 0, G_OPTION_ARG_NONE, &secure,
1769 "disable the LIST, XPATH and DUMP commands", NULL },
1770 { "rcfile", 'f', 0, G_OPTION_ARG_FILENAME, &rcfile,
1771 "load the specified rcfile (~/.pwmd/config)", "filename" },
1772 { "ignore", 0, 0, G_OPTION_ARG_NONE, &force,
1773 "ignore cache failures on startup", NULL },
1774 { "outfile", 'o', 0, G_OPTION_ARG_FILENAME, &outfile,
1775 "output file when importing (- for stdout)", "filename" },
1776 { "convert", 'C', 0, G_OPTION_ARG_FILENAME, &convertfile,
1777 "convert a version 2 data file to version 3", "filename" },
1778 { "passphrase-file", 'k', 0, G_OPTION_ARG_FILENAME, &keyfile,
1779 "for decryption when converting", "filename" },
1780 { "no-passphrase-file", 0, 0, G_OPTION_ARG_NONE, &no_passphrase_file,
1781 "no --passphrase-file after conversion", NULL },
1782 { "import", 'I', 0, G_OPTION_ARG_FILENAME, &import,
1783 "import an XML file", "filename" },
1784 { "keygrip", 0, 0, G_OPTION_ARG_STRING, &keygrip,
1785 "the public keygrip to use for encryption", "hexstring"},
1786 { "sign-keygrip", 0, 0, G_OPTION_ARG_STRING, &sign_keygrip,
1787 "the keygrip to use for signing of the data", "hexstring"},
1788 { "keyparam", 0, 0, G_OPTION_ARG_STRING, &keyparam,
1789 "alternate key parameters to use (RSA-2048)", "s-exp"},
1790 { "no-passphrase", 0, 0, G_OPTION_ARG_NONE, &no_passphrase,
1791 "for the imported/converted keypair", NULL },
1792 { "cipher", 0, 0, G_OPTION_ARG_STRING, &cipher,
1793 "encryption cipher, see man page (aes256)", "string" },
1794 { "s2k-count", 0, 0, G_OPTION_ARG_INT64, &s2k_count,
1795 "hash iteration count >65536 (calibrated)", "iterations" },
1796 { "cipher-iterations", 0, 0, G_OPTION_ARG_INT64, &iterations,
1797 "cipher iteration count (N+1)", "iterations" },
1798 { "debug-level", 0, 0, G_OPTION_ARG_STRING, &debug_level_opt,
1799 "protocol output, see man page", "keywords"},
1800 { "homedir", 'I', 0, G_OPTION_ARG_STRING, &homedir,
1801 "home directory for pwmd", "directory" },
1802 { NULL }
1805 #ifndef DEBUG
1806 #ifdef HAVE_SETRLIMIT
1807 struct rlimit rl;
1809 rl.rlim_cur = rl.rlim_max = 0;
1811 if (setrlimit(RLIMIT_CORE, &rl) != 0)
1812 err(EXIT_FAILURE, "setrlimit()");
1813 #endif
1814 #endif
1816 #ifdef ENABLE_NLS
1817 setlocale(LC_ALL, "");
1818 bindtextdomain("pwmd", LOCALEDIR);
1819 textdomain("pwmd");
1820 #endif
1822 #ifndef MEM_DEBUG
1823 xmem_init();
1824 #endif
1825 g_mem_set_vtable(&mtable);
1826 g_thread_init(NULL);
1827 gpg_err_init();
1829 if (setup_crypto())
1830 exit(EXIT_FAILURE);
1832 #ifdef WITH_GNUTLS
1833 gnutls_global_set_mem_functions(g_malloc, g_malloc, secure_mem_check,
1834 g_realloc, g_free);
1835 gnutls_global_init();
1836 gnutls_global_set_log_function(tls_log);
1837 gnutls_global_set_log_level(1);
1838 tls_fd = -1;
1839 tls6_fd = -1;
1840 #endif
1841 xmlMemSetup(g_free, g_malloc, g_realloc, g_strdup);
1842 xmlInitMemory();
1843 xmlInitGlobals();
1844 xmlInitParser();
1845 xmlXPathInit();
1847 cmdline = TRUE;
1848 context = g_option_context_new("- Password Manager Daemon");
1849 g_option_context_add_main_entries(context, options, NULL);
1850 if (!g_option_context_parse(context, &argc, &argv, &error))
1852 g_print("Option parsing failed: %s\n", error->message);
1853 exit(EXIT_FAILURE);
1856 if (show_version) {
1857 printf(_("%s\n\n"
1858 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012\n"
1859 "%s\n"
1860 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
1861 "Compile time features:\n%s"), PACKAGE_STRING, PACKAGE_BUGREPORT,
1862 #ifdef WITH_GNUTLS
1863 "+WITH_GNUTLS\n"
1864 #else
1865 "-WITH_GNUTLS\n"
1866 #endif
1867 #ifdef WITH_LIBACL
1868 "+WITH_LIBACL\n"
1869 #else
1870 "-WITH_LIBACL\n"
1871 #endif
1872 #ifdef DEBUG
1873 "+DEBUG\n"
1874 #else
1875 "-DEBUG\n"
1876 #endif
1877 #ifdef MEM_DEBUG
1878 "+MEM_DEBUG\n"
1879 #else
1880 "-MEM_DEBUG\n"
1881 #endif
1882 #ifdef MUTEX_DEBUG
1883 "+MUTEX_DEBUG\n"
1884 #else
1885 "-MUTEX_DEBUG\n"
1886 #endif
1888 exit(EXIT_SUCCESS);
1891 if (!homedir)
1892 homedir = g_strdup_printf("%s/.pwmd", g_get_home_dir());
1894 if (mkdir(homedir, 0700) == -1 && errno != EEXIST)
1895 err(EXIT_FAILURE, "%s", homedir);
1897 g_snprintf(buf, sizeof(buf), "%s/data", homedir);
1898 if (mkdir(buf, 0700) == -1 && errno != EEXIST)
1899 err(EXIT_FAILURE, "%s", buf);
1901 datadir = g_strdup(buf);
1902 pthread_mutexattr_t attr;
1903 pthread_mutexattr_init(&attr);
1904 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1905 pthread_mutex_init(&rcfile_mutex, &attr);
1906 pthread_cond_init(&rcfile_cond, NULL);
1907 pthread_mutex_init(&cn_mutex, &attr);
1908 pthread_mutexattr_destroy(&attr);
1909 pthread_key_create(&last_error_key, free_key);
1911 if (!rcfile)
1912 rcfile = g_strdup_printf("%s/config", homedir);
1913 else
1914 rcfile_spec = TRUE;
1916 if ((keyfileh = parse_rcfile(rcfile_spec, cmdline)) == NULL)
1917 exit(EXIT_FAILURE);
1919 if (debug_level_opt)
1920 debug_level = g_strsplit(debug_level_opt, ",", 0);
1922 if (g_key_file_has_key(keyfileh, "global", "syslog", NULL) == TRUE)
1923 log_syslog = g_key_file_get_boolean(keyfileh, "global", "syslog", NULL);
1925 if (log_syslog == TRUE)
1926 openlog("pwmd", LOG_NDELAY|LOG_PID, LOG_DAEMON);
1928 if (g_key_file_has_key(keyfileh, "global", "priority", NULL)) {
1929 x = g_key_file_get_integer(keyfileh, "global", "priority", NULL);
1930 errno = 0;
1932 if (setpriority(PRIO_PROCESS, 0, x) == -1) {
1933 log_write("setpriority(): %s", pwmd_strerror(gpg_error_from_syserror()));
1934 goto do_exit;
1938 #ifdef HAVE_MLOCKALL
1939 if (disable_mlock == FALSE && mlockall(MCL_CURRENT|MCL_FUTURE) == -1) {
1940 log_write("mlockall(): %s", pwmd_strerror(gpg_error_from_syserror()));
1941 goto do_exit;
1943 #endif
1945 rc = cache_init(free_cache_data);
1946 if (rc) {
1947 log_write("pwmd: gpg-agent: %s",
1948 gpg_err_code(rc) == GPG_ERR_UNKNOWN_VERSION
1949 ? _("incompatible version: 2.1.0 or later required")
1950 : pwmd_strerror(rc));
1951 goto do_exit;
1954 if (s2k_count == -1)
1955 s2k_count = get_key_file_ulong(NULL, "s2k_count");
1957 if (convertfile) {
1958 if (!outfile) {
1959 gchar *tmp = g_option_context_get_help(context, TRUE, NULL);
1960 fprintf(stderr, "%s", tmp);
1961 g_free(tmp);
1962 exit(EXIT_FAILURE);
1965 estatus = convert_v2_datafile(convertfile, cipher, keyfile, keygrip,
1966 sign_keygrip, no_passphrase, outfile, keyparam,
1967 (gulong)s2k_count, iterations);
1968 g_key_file_free(keyfileh);
1969 g_free(rcfile);
1970 exit(!estatus);
1973 if (import) {
1974 if (!outfile) {
1975 gchar *tmp = g_option_context_get_help(context, TRUE, NULL);
1976 fprintf(stderr, "%s", tmp);
1977 g_free(tmp);
1978 exit(EXIT_FAILURE);
1981 if (outfile[0] == '-' && outfile[1] == 0)
1982 outfile = NULL;
1984 estatus = xml_import(import, outfile, keygrip, sign_keygrip, keyfile,
1985 no_passphrase, cipher, keyparam, (gulong)s2k_count, iterations);
1986 g_key_file_free(keyfileh);
1987 g_free(rcfile);
1988 exit(!estatus);
1991 g_option_context_free(context);
1992 p = g_key_file_get_string(keyfileh, "global", "socket_path", NULL);
1993 if (!p)
1994 p = g_strdup_printf("%s/socket", homedir);
1996 socketarg = expand_homedir(p);
1997 g_free(p);
1999 if (secure == FALSE && g_key_file_has_key(keyfileh, "global", "disable_list_and_dump", NULL) == TRUE) {
2000 n = g_key_file_get_boolean(keyfileh, "global", "disable_list_and_dump", NULL);
2001 disable_list_and_dump = n;
2003 else
2004 disable_list_and_dump = secure;
2006 setup_logging(keyfileh);
2008 if (g_key_file_has_key(keyfileh, "global", "cache_push", NULL) == TRUE)
2009 cache_push = g_key_file_get_string_list(keyfileh, "global", "cache_push", NULL, NULL);
2011 for (gint n = 1; n < argc; n++) {
2012 if (strv_printf(&cache_push, "%s", argv[n]) == FALSE)
2013 errx(EXIT_FAILURE, "%s", pwmd_strerror(GPG_ERR_ENOMEM));
2016 if (strchr(socketarg, '/') == NULL) {
2017 socketdir = g_get_current_dir();
2018 socketname = g_strdup(socketarg);
2019 socketpath = g_strdup_printf("%s/%s", socketdir, socketname);
2021 else {
2022 socketname = g_strdup(strrchr(socketarg, '/'));
2023 socketname++;
2024 socketarg[strlen(socketarg) - strlen(socketname) -1] = 0;
2025 socketdir = g_strdup(socketarg);
2026 socketpath = g_strdup_printf("%s/%s", socketdir, socketname);
2029 if (chdir(datadir)) {
2030 log_write("%s: %s", datadir, pwmd_strerror(gpg_error_from_syserror()));
2031 unlink(socketpath);
2032 goto do_exit;
2036 * Set the cache entry for a file. Prompts for the password.
2038 if (cache_push) {
2039 struct crypto_s *crypto;
2040 gpg_error_t rc = init_client_crypto(&crypto);
2042 if (rc) {
2043 estatus = EXIT_FAILURE;
2044 goto do_exit;
2047 rc = set_pinentry_options(crypto->agent);
2048 if (rc) {
2049 estatus = EXIT_FAILURE;
2050 goto do_exit;
2053 for (opt = 0; cache_push[opt]; opt++) {
2054 if (!do_cache_push(cache_push[opt], crypto) && !force) {
2055 g_strfreev(cache_push);
2056 startup_failure();
2057 estatus = EXIT_FAILURE;
2058 cleanup_crypto(&crypto);
2059 goto do_exit;
2062 cleanup_crypto_stage1(crypto);
2065 (void)kill_scd(crypto->agent);
2066 cleanup_crypto(&crypto);
2067 g_strfreev(cache_push);
2068 log_write(!nofork ? _("Done. Daemonizing...") : _("Done. Waiting for connections..."));
2071 clear_rcfile_keys();
2074 * bind() doesn't like the full pathname of the socket or any non alphanum
2075 * characters so change to the directory where the socket is wanted then
2076 * create it then change to datadir.
2078 if (chdir(socketdir)) {
2079 log_write("%s: %s", socketdir, pwmd_strerror(gpg_error_from_syserror()));
2080 goto do_exit;
2083 g_free(socketdir);
2085 if ((sockfd = socket(PF_UNIX, SOCK_STREAM, 0)) == -1) {
2086 log_write("socket(): %s", pwmd_strerror(gpg_error_from_syserror()));
2087 goto do_exit;
2090 addr.sun_family = AF_UNIX;
2091 g_snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", socketname);
2093 if (bind(sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr)) == -1) {
2094 log_write("bind(): %s", pwmd_strerror(gpg_error_from_syserror()));
2096 if (errno == EADDRINUSE)
2097 log_write(_("Either there is another pwmd running or '%s' is a \n"
2098 "stale socket. Please remove it manually."), socketpath);
2100 goto do_exit;
2103 do_unlink = 1;
2104 if (g_key_file_has_key(keyfileh, "global", "socket_perms", NULL) == TRUE) {
2105 gchar *t = g_key_file_get_string(keyfileh, "global", "socket_perms", NULL);
2106 mode_t mode = strtol(t, NULL, 8);
2107 mode_t mask = umask(0);
2109 g_free(t);
2111 if (chmod(socketname, mode) == -1) {
2112 log_write("%s: %s", socketname, pwmd_strerror(gpg_error_from_syserror()));
2113 close(sockfd);
2114 unlink(socketpath);
2115 umask(mask);
2116 goto do_exit;
2119 umask(mask);
2122 g_free(--socketname);
2124 if (chdir(datadir)) {
2125 log_write("%s: %s", datadir, pwmd_strerror(gpg_error_from_syserror()));
2126 close(sockfd);
2127 unlink(socketpath);
2128 goto do_exit;
2131 g_free(datadir);
2133 if (listen(sockfd, 0) == -1) {
2134 log_write("listen(): %s", pwmd_strerror(gpg_error_from_syserror()));
2135 goto do_exit;
2138 cmdline = FALSE;
2140 if (!nofork) {
2141 switch (fork()) {
2142 case -1:
2143 log_write("fork(): %s", pwmd_strerror(gpg_error_from_syserror()));
2144 goto do_exit;
2145 case 0:
2146 close(0);
2147 close(1);
2148 close(2);
2149 setsid();
2150 break;
2151 default:
2152 _exit(EXIT_SUCCESS);
2156 pthread_key_create(&thread_name_key, free_key);
2157 pthread_setspecific(thread_name_key, g_strdup("main"));
2158 estatus = server_loop(sockfd, &socketpath);
2160 do_exit:
2161 if (socketpath && do_unlink) {
2162 unlink(socketpath);
2163 g_free(socketpath);
2166 g_free(socketarg);
2167 #ifdef WITH_GNUTLS
2168 gnutls_global_deinit();
2169 #endif
2170 pthread_cancel(rcfile_tid);
2171 pthread_join(rcfile_tid, NULL);
2172 pthread_cond_destroy(&rcfile_cond);
2173 pthread_mutex_destroy(&rcfile_mutex);
2175 if (keyfileh)
2176 g_key_file_free(keyfileh);
2178 g_free(rcfile);
2179 xmlCleanupParser();
2180 xmlCleanupGlobals();
2182 if (estatus == EXIT_SUCCESS)
2183 log_write(_("pwmd exiting normally"));
2185 #if defined(DEBUG) && !defined(MEM_DEBUG)
2186 xdump();
2187 #endif
2188 exit(estatus);