Fix segfault when server_loop() fails for some reason.
[pwmd.git] / src / pwmd.c
blob7df41b0ff2c82744fe6e4fcd2dbfcc51ad19afe1
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);
140 for (;;) {
141 gboolean b = disable_list_and_dump;
142 gchar **users;
143 GKeyFile *k;
145 pthread_cond_wait(&rcfile_cond, &rcfile_mutex);
146 users = g_key_file_get_string_list(keyfileh, "global", "allowed", NULL, NULL);
147 log_write(_("reloading configuration file '%s'"), rcfile);
148 k = parse_rcfile(FALSE, cmdline);
149 if (k) {
150 g_key_file_free(keyfileh);
151 keyfileh = k;
152 cache_push_from_rcfile();
153 clear_rcfile_keys();
156 disable_list_and_dump = !disable_list_and_dump ? b : TRUE;
157 g_key_file_set_string_list(keyfileh, "global", "allowed",
158 (const gchar **)users, g_strv_length(users));
159 g_strfreev(users);
160 #ifdef WITH_GNUTLS
161 /* Kill existing listening threads since the configured listening
162 * protocols may have changed. */
163 start_stop_tls(TRUE);
164 start_stop_tls(FALSE);
165 #endif
168 return NULL;
171 gpg_error_t send_error(assuan_context_t ctx, gpg_error_t e)
173 struct client_s *client = assuan_get_pointer(ctx);
175 if (gpg_err_source(e) == GPG_ERR_SOURCE_UNKNOWN)
176 e = gpg_error(e);
178 if (client)
179 client->last_rc = e;
181 if (!e)
182 return assuan_process_done(ctx, 0);
184 if (!ctx) {
185 log_write("%s", pwmd_strerror(e));
186 return e;
189 if (gpg_err_code(e) == GPG_ERR_BAD_DATA) {
190 xmlErrorPtr xe = client->xml_error;
192 if (!xe)
193 xe = xmlGetLastError();
194 if (xe) {
195 log_write("%s", xe->message);
196 if (client->last_error)
197 g_free(client->last_error);
199 client->last_error = g_strdup(xe->message);
202 e = assuan_process_done(ctx, assuan_set_error(ctx, e,
203 xe ? xe->message : NULL));
205 if (xe == client->xml_error)
206 xmlResetError(xe);
207 else
208 xmlResetLastError();
210 client->xml_error = NULL;
211 return e;
214 return assuan_process_done(ctx, assuan_set_error(ctx, e, pwmd_strerror(e)));
217 int assuan_log_cb(assuan_context_t ctx, void *data, unsigned cat,
218 const char *msg)
220 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
221 int i, t;
222 gboolean match = FALSE;
224 pthread_mutex_lock(&m);
225 pthread_cleanup_push((void (*)(void *))pthread_mutex_unlock, &m);
226 t = g_strv_length(debug_level);
228 for (i = 0; i < t; i++) {
229 if (!g_ascii_strcasecmp(debug_level[i], (gchar *)"init")
230 && cat == ASSUAN_LOG_INIT) {
231 match = TRUE;
232 break;
235 if (!g_ascii_strcasecmp(debug_level[i], (gchar *)"ctx")
236 && cat == ASSUAN_LOG_CTX) {
237 match = TRUE;
238 break;
241 if (!g_ascii_strcasecmp(debug_level[i], (gchar *)"engine")
242 && cat == ASSUAN_LOG_ENGINE) {
243 match = TRUE;
244 break;
247 if (!g_ascii_strcasecmp(debug_level[i], (gchar *)"data")
248 && cat == ASSUAN_LOG_DATA) {
249 match = TRUE;
250 break;
253 if (!g_ascii_strcasecmp(debug_level[i], (gchar *)"sysio")
254 && cat == ASSUAN_LOG_SYSIO) {
255 match = TRUE;
256 break;
259 if (!g_ascii_strcasecmp(debug_level[i], (gchar *)"control")
260 && cat == ASSUAN_LOG_CONTROL) {
261 match = TRUE;
262 break;
266 if (match && msg) {
267 if (logfile) {
268 int fd;
270 if ((fd = open(logfile, O_WRONLY|O_CREAT|O_APPEND, 0600)) == -1)
271 warn("%s", logfile);
272 else {
273 pthread_cleanup_push(cleanup_fd_cb, &fd);
274 write(fd, msg, strlen(msg));
275 pthread_cleanup_pop(1);
279 if (nofork) {
280 fprintf(stderr, "%s%s", data ? (gchar *)data : "", msg);
281 fflush(stderr);
285 pthread_cleanup_pop(1);
286 return match;
289 void log_write(const gchar *fmt, ...)
291 gchar *args, *line;
292 va_list ap;
293 struct tm *tm;
294 time_t now;
295 gchar tbuf[21];
296 gint fd = -1;
297 gchar *name = NULL;
298 gchar buf[255];
299 pthread_t tid = pthread_self();
300 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
302 if ((!logfile && !isatty(STDERR_FILENO) && !log_syslog) || !fmt)
303 return;
305 pthread_mutex_lock(&m);
306 pthread_cleanup_push((void (*)(void *))pthread_mutex_unlock, &m);
307 pthread_cleanup_push(cleanup_fd_cb, &fd);
309 if (!cmdline && logfile) {
310 if ((fd = open(logfile, O_WRONLY|O_CREAT|O_APPEND, 0600)) == -1)
311 warn("%s", logfile);
314 va_start(ap, fmt);
316 if (g_vasprintf(&args, fmt, ap) != -1) {
317 if (cmdline) {
318 pthread_cleanup_push(g_free, args);
319 fprintf(stderr, "%s\n", args);
320 fflush(stderr);
321 pthread_cleanup_pop(1);
323 else {
324 pthread_cleanup_push(g_free, args);
325 name = pthread_getspecific(thread_name_key);
326 name = print_fmt(buf, sizeof(buf), "%s(%p): ",
327 name ? name : _("unknown"), (pthread_t *)tid);
329 if (!cmdline && log_syslog && !nofork)
330 syslog(LOG_INFO, "%s%s", name, args);
332 time(&now);
333 tm = localtime(&now);
334 strftime(tbuf, sizeof(tbuf), "%b %d %Y %H:%M:%S ", tm);
335 tbuf[sizeof(tbuf) - 1] = 0;
337 if (args[strlen(args)-1] == '\n')
338 args[strlen(args)-1] = 0;
340 line = g_strdup_printf("%s %i %s%s\n", tbuf, getpid(), name,
341 args);
342 pthread_cleanup_pop(1);
343 if (line) {
344 pthread_cleanup_push(g_free, line);
345 if (logfile && fd != -1) {
346 write(fd, line, strlen(line));
347 fsync(fd);
350 if (nofork) {
351 fprintf(stdout, "%s", line);
352 fflush(stdout);
355 pthread_cleanup_pop(1);
360 va_end(ap);
361 pthread_cleanup_pop(1);
362 pthread_cleanup_pop(0);
363 pthread_mutex_unlock(&m);
366 #ifdef WITH_GNUTLS
367 static gint secure_mem_check(const void *arg)
369 return 1;
371 #endif
373 static gpg_error_t setup_crypto()
375 gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
377 if (!gcry_check_version(GCRYPT_VERSION)) {
378 fprintf(stderr, _("gcry_check_version(): Incompatible libgcrypt. "
379 "Wanted %s, got %s.\n"), GCRYPT_VERSION,
380 gcry_check_version(NULL));
381 return GPG_ERR_UNKNOWN_VERSION;
384 gcry_set_allocation_handler(g_malloc, g_malloc, NULL, g_realloc, g_free);
385 return 0;
388 static gpg_error_t validate_peer(struct client_s *cl)
390 gchar **users;
391 gboolean allowed = FALSE;
392 assuan_peercred_t peercred;
393 gpg_error_t rc;
395 #ifdef WITH_GNUTLS
396 if (cl->thd->remote)
397 return 0;
398 #endif
400 rc = assuan_get_peercred(cl->ctx, &peercred);
401 if (rc)
402 return rc;
404 users = g_key_file_get_string_list(keyfileh, "global", "allowed", NULL, NULL);
406 if (users) {
407 for (gchar **p = users; *p; p++) {
408 struct passwd pw, *result;
409 struct group gr, *gresult;
410 char *buf;
412 if (*(*p) == '@') {
413 size_t len = sysconf(_SC_GETGR_R_SIZE_MAX);
415 if (len == -1)
416 len = 16384;
418 buf = g_malloc(len);
420 if (!buf) {
421 g_strfreev(users);
422 return GPG_ERR_ENOMEM;
425 if (!getgrnam_r(*(p)+1, &gr, buf, len, &gresult) && gresult) {
426 if (gresult->gr_gid == peercred->gid) {
427 g_free(buf);
428 allowed = TRUE;
429 break;
432 len = sysconf(_SC_GETPW_R_SIZE_MAX);
434 if (len == -1)
435 len = 16384;
437 gchar *tbuf = g_malloc(len);
439 for (gchar **t = gresult->gr_mem; *t; t++) {
440 if (!getpwnam_r(*t, &pw, tbuf, len, &result) && result) {
441 if (result->pw_uid == peercred->uid) {
442 g_free(buf);
443 allowed = TRUE;
444 break;
449 g_free(tbuf);
451 if (allowed)
452 break;
455 else {
456 size_t len = sysconf(_SC_GETPW_R_SIZE_MAX);
458 if (len == -1)
459 len = 16384;
461 buf = g_malloc(len);
463 if (!buf) {
464 g_strfreev(users);
465 return GPG_ERR_ENOMEM;
468 if (!getpwnam_r(*p, &pw, buf, len, &result) && result) {
469 if (result->pw_uid == peercred->uid) {
470 g_free(buf);
471 allowed = TRUE;
472 break;
477 g_free(buf);
480 g_strfreev(users);
483 log_write("peer %s: uid=%i, gid=%i, pid=%i",
484 allowed ? _("accepted") : _("rejected"), peercred->uid,
485 peercred->gid, peercred->pid);
486 return allowed ? 0 : GPG_ERR_INV_USER_ID;
489 static void xml_error_cb(void *data, xmlErrorPtr e)
491 struct client_s *client = data;
494 * Keep the first reported error as the one to show in the error
495 * description. Reset in send_error().
497 if (client->xml_error)
498 return;
500 xmlCopyError(e, client->xml_error);
503 static pid_t hook_waitpid(assuan_context_t ctx, pid_t pid, int action,
504 int *status, int options)
506 return waitpid(pid, status, options);
509 static ssize_t hook_read(assuan_context_t ctx, assuan_fd_t fd, void *data,
510 size_t len)
512 #ifdef WITH_GNUTLS
513 struct client_s *client = assuan_get_pointer(ctx);
515 if (client->thd->remote)
516 return tls_read_hook(ctx, (gint)fd, data, len);
517 #endif
519 return read((gint)fd, data, len);
522 static ssize_t hook_write(assuan_context_t ctx, assuan_fd_t fd,
523 const void *data, size_t len)
525 #ifdef WITH_GNUTLS
526 struct client_s *client = assuan_get_pointer(ctx);
528 if (client->thd->remote)
529 return tls_write_hook(ctx, (gint)fd, data, len);
530 #endif
532 return write((gint)fd, data, len);
535 static gboolean new_connection(struct client_s *cl)
537 gpg_error_t rc;
538 static struct assuan_malloc_hooks mhooks = { g_malloc, g_realloc, g_free };
539 static struct assuan_system_hooks shooks = {
540 ASSUAN_SYSTEM_HOOKS_VERSION,
541 __assuan_usleep,
542 __assuan_pipe,
543 __assuan_close,
544 hook_read,
545 hook_write,
546 //FIXME
547 NULL, //recvmsg
548 NULL, //sendmsg both are used for FD passing
549 __assuan_spawn,
550 hook_waitpid,
551 __assuan_socketpair,
552 __assuan_socket,
553 __assuan_connect
556 #ifdef WITH_GNUTLS
557 if (cl->thd->remote) {
558 gchar *prio = get_key_file_string("global", "tls_cipher_suite");
560 cl->thd->tls = tls_init(cl->thd->fd, prio);
561 g_free(prio);
562 if (!cl->thd->tls)
563 return FALSE;
565 #endif
567 rc = assuan_new_ext(&cl->ctx, GPG_ERR_SOURCE_DEFAULT, &mhooks,
568 debug_level ? assuan_log_cb : NULL, NULL);
569 if (rc)
570 goto fail;
572 assuan_ctx_set_system_hooks(cl->ctx, &shooks);
573 rc = assuan_init_socket_server(cl->ctx, cl->thd->fd, 2);
574 if (rc)
575 goto fail;
577 assuan_set_pointer(cl->ctx, cl);
578 assuan_set_hello_line(cl->ctx, PACKAGE_STRING);
579 rc = register_commands(cl->ctx);
580 if (rc)
581 goto fail;
583 rc = assuan_accept(cl->ctx);
584 if (rc)
585 goto fail;
587 rc = validate_peer(cl);
588 /* May not be implemented on all platforms. */
589 if (rc && gpg_err_code(rc) != GPG_ERR_ASS_GENERAL)
590 goto fail;
592 rc = init_client_crypto(&cl->crypto);
593 if (rc)
594 goto fail;
596 cl->crypto->agent->client_ctx = cl->ctx;
597 cl->crypto->client_ctx = cl->ctx;
598 xmlSetStructuredErrorFunc(cl, xml_error_cb);
599 return TRUE;
601 fail:
602 log_write("%s", pwmd_strerror(rc));
603 return FALSE;
607 * This is called after a client_thread() terminates. Set with
608 * pthread_cleanup_push().
610 static void cleanup_cb(void *arg)
612 struct client_thread_s *cn = arg;
613 struct client_s *cl = cn->cl;
615 MUTEX_LOCK(&cn_mutex);
616 cn_thread_list = g_slist_remove(cn_thread_list, cn);
617 MUTEX_UNLOCK(&cn_mutex);
619 if (cl) {
620 cleanup_client(cl);
622 #ifdef WITH_GNUTLS
623 if (cn->tls) {
624 gnutls_deinit(cn->tls->ses);
625 g_free(cn->tls->fp);
626 g_free(cn->tls);
628 #endif
630 if (cl->ctx)
631 assuan_release(cl->ctx);
632 else if (cl->thd && cl->thd->fd != -1)
633 close(cl->thd->fd);
635 if (cl->crypto)
636 cleanup_crypto(&cl->crypto);
638 g_free(cl);
640 else {
641 if (cn->fd != -1)
642 close(cn->fd);
645 while (cn->msg_queue) {
646 struct status_msg_s *msg = cn->msg_queue;
648 cn->msg_queue = msg->next;
649 g_free(msg->line);
650 g_free(msg);
653 if (cn->status_msg_pipe[0] != -1)
654 close(cn->status_msg_pipe[0]);
656 if (cn->status_msg_pipe[1] != -1)
657 close(cn->status_msg_pipe[1]);
659 pthread_mutex_destroy(&cn->status_mutex);
660 log_write(_("exiting, fd=%i"), cn->fd);
661 g_free(cn);
662 send_status_all(STATUS_CLIENTS, NULL);
663 pthread_cond_signal(&quit_cond);
666 static gpg_error_t send_msg_queue(struct client_thread_s *thd)
668 MUTEX_LOCK(&thd->status_mutex);
669 gpg_error_t rc = 0;
670 gchar c;
672 read(thd->status_msg_pipe[0], &c, 1);
674 while (thd->msg_queue) {
675 struct status_msg_s *msg = thd->msg_queue;
677 thd->msg_queue = thd->msg_queue->next;
678 MUTEX_UNLOCK(&thd->status_mutex);
679 rc = send_status(thd->cl->ctx, msg->s, msg->line);
680 MUTEX_LOCK(&thd->status_mutex);
681 g_free(msg->line);
682 g_free(msg);
684 if (rc)
685 break;
688 MUTEX_UNLOCK(&thd->status_mutex);
689 return rc;
692 static void *client_thread(void *data)
694 struct client_thread_s *thd = data;
695 struct client_s *cl = g_malloc0(sizeof(struct client_s));
697 #ifdef HAVE_PR_SET_NAME
698 prctl(PR_SET_NAME, "client");
699 #endif
700 pthread_setspecific(thread_name_key, g_strdup(__FUNCTION__));
702 if (!cl) {
703 log_write("%s(%i): %s", __FILE__, __LINE__,
704 pwmd_strerror(GPG_ERR_ENOMEM));
705 return NULL;
708 MUTEX_LOCK(&cn_mutex);
709 pthread_cleanup_push(cleanup_cb, thd);
710 thd->cl = cl;
711 cl->thd = thd;
712 MUTEX_UNLOCK(&cn_mutex);
714 if (new_connection(cl)) {
715 gboolean finished = FALSE;
716 gpg_error_t rc;
718 send_status_all(STATUS_CLIENTS, NULL);
719 rc = send_status(cl->ctx, STATUS_CACHE, NULL);
720 if (rc) {
721 log_write("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror(rc));
722 finished = TRUE;
725 while (!finished) {
726 fd_set rfds;
727 gint n;
728 gint eof;
730 FD_ZERO(&rfds);
731 FD_SET(thd->fd, &rfds);
732 FD_SET(thd->status_msg_pipe[0], &rfds);
733 n = thd->fd > thd->status_msg_pipe[0] ? thd->fd : thd->status_msg_pipe[0];
735 n = select(n+1, &rfds, NULL, NULL, NULL);
736 if (n == -1) {
737 log_write("%s", strerror(errno));
738 break;
741 if (FD_ISSET(thd->status_msg_pipe[0], &rfds)) {
742 rc = send_msg_queue(thd);
743 if (rc && gpg_err_code(rc) != GPG_ERR_EPIPE) {
744 log_write("%s(%i): %s", __FUNCTION__, __LINE__,
745 pwmd_strerror(rc));
746 break;
750 if (!FD_ISSET(thd->fd, &rfds))
751 continue;
753 rc = assuan_process_next(cl->ctx, &eof);
754 if (rc || eof) {
755 if (gpg_err_code(rc) == GPG_ERR_EOF || eof)
756 break;
758 log_write("assuan_process_next(): %s", pwmd_strerror(rc));
759 rc = send_error(cl->ctx, rc);
761 if (rc) {
762 log_write("assuan_process_done(): %s", pwmd_strerror(rc));
763 break;
767 /* Since the msg queue pipe fd's are non-blocking, check for
768 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
769 * client has already disconnected and will be converted to
770 * GPG_ERR_EOF during assuan_process_next().
772 rc = send_msg_queue(thd);
773 if (rc && gpg_err_code(rc) != GPG_ERR_EPIPE) {
774 log_write("%s(%i): %s", __FUNCTION__, __LINE__,
775 pwmd_strerror(rc));
776 break;
781 pthread_cleanup_pop(1);
782 return NULL;
785 static gboolean xml_import(const gchar *filename, const gchar *outfile,
786 const gchar *keygrip, const char *sign_keygrip, const gchar *keyfile,
787 gboolean no_passphrase, const gchar *cipher, const gchar *params,
788 gulong s2k_count, guint64 iterations)
790 xmlDocPtr doc;
791 gint fd;
792 struct stat st;
793 gint len;
794 xmlChar *xmlbuf;
795 xmlChar *xml;
796 gpg_error_t rc;
797 struct crypto_s *crypto;
798 gint algo = cipher ? cipher_string_to_gcrypt((gchar *)cipher) :
799 GCRY_CIPHER_AES256;
801 if (algo == -1) {
802 log_write("%s", pwmd_strerror(GPG_ERR_CIPHER_ALGO));
803 return FALSE;
806 if (stat(filename, &st) == -1) {
807 log_write("%s: %s", filename, pwmd_strerror(gpg_error_from_syserror()));
808 return FALSE;
811 rc = init_client_crypto(&crypto);
812 if (rc)
813 return FALSE;
815 memcpy(&crypto->save.hdr, &crypto->hdr, sizeof(file_header_t));
816 crypto->save.hdr.flags = set_cipher_flag(crypto->save.hdr.flags, algo);
817 log_write(_("Importing XML from '%s'. Output will be written to '%s' ..."),
818 filename, outfile);
820 if ((fd = open(filename, O_RDONLY)) == -1) {
821 log_write("%s: %s", filename, pwmd_strerror(gpg_error_from_syserror()));
822 goto fail;
825 if ((xmlbuf = xmalloc(st.st_size+1)) == NULL) {
826 close(fd);
827 log_write("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror(GPG_ERR_ENOMEM));
828 goto fail;
831 if (read(fd, xmlbuf, st.st_size) == -1) {
832 rc = gpg_error_from_syserror();
833 close(fd);
834 log_write("%s: %s", filename, pwmd_strerror(rc));
835 goto fail;
838 close(fd);
839 xmlbuf[st.st_size] = 0;
841 * Make sure the document validates.
843 if ((doc = xmlReadDoc(xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS)) == NULL) {
844 log_write("xmlReadDoc() failed");
845 xfree(xmlbuf);
846 goto fail;
849 xfree(xmlbuf);
850 xmlNodePtr n = xmlDocGetRootElement(doc);
851 if (!xmlStrEqual(n->name, (xmlChar *)"pwmd")) {
852 log_write(_("Could not find root \"pwmd\" element."));
853 rc = GPG_ERR_BAD_DATA;
856 if (!rc)
857 rc = validate_import(n ? n->children : n);
859 if (rc) {
860 log_write("%s", pwmd_strerror(rc));
861 xmlFreeDoc(doc);
862 goto fail;
865 xmlDocDumpMemory(doc, &xml, &len);
866 xmlFreeDoc(doc);
867 crypto->save.s2k_count = (gulong)s2k_count;
868 crypto->save.hdr.iterations = iterations;
869 rc = set_pinentry_options(crypto->agent);
870 if (!rc)
871 rc = export_common(crypto, keygrip, sign_keygrip, no_passphrase, xml,
872 len, outfile, params, keyfile);
874 xmlFree(xml);
875 if (rc) {
876 send_error(NULL, rc);
877 goto fail;
880 cleanup_crypto(&crypto);
881 return TRUE;
883 fail:
884 cleanup_crypto(&crypto);
885 return FALSE;
888 static gboolean do_cache_push(const gchar *filename, struct crypto_s *crypto)
890 guchar md5file[16];
891 gpg_error_t rc;
892 gchar *key = NULL;
893 gsize keylen;
894 xmlDocPtr doc;
895 struct cache_data_s *cdata;
896 guchar *crc;
897 gsize len;
899 log_write(_("Trying to add datafile '%s' to the file cache ..."),
900 filename);
902 if (valid_filename(filename) == FALSE) {
903 log_write(_("%s: Invalid characters in filename"), filename);
904 return FALSE;
907 rc = read_data_file(filename, crypto);
908 if (rc) {
909 log_write("%s", pwmd_strerror(rc));
910 return FALSE;
913 if ((key = get_key_file_string(filename, "passphrase"))) {
914 log_write(_("Trying the passphrase specified in config ..."));
915 keylen = strlen(key);
917 else if ((key = get_key_file_string(filename, "passphrase_file"))) {
918 gint fd = open((gchar *)key, O_RDONLY);
919 struct stat st;
921 log_write(_("Trying the passphrase using file '%s' ..."), key);
922 if (fd == -1) {
923 log_write("%s: %s", key, pwmd_strerror(gpg_error_from_syserror()));
924 g_free(key);
925 return FALSE;
928 stat((gchar *)key, &st);
929 g_free(key);
930 key = g_malloc(st.st_size);
931 if (read(fd, key, st.st_size) != st.st_size) {
932 log_write("short read() count");
933 g_free(key);
934 close(fd);
935 return FALSE;
938 keylen = st.st_size;
941 if (key) {
942 rc = set_agent_passphrase(crypto, key, keylen);
943 g_free(key);
944 if (rc) {
945 log_write("%s", pwmd_strerror(rc));
946 return FALSE;
950 crypto->filename = g_strdup(filename);
951 rc = decrypt_data(NULL, crypto);
952 if (rc) {
953 log_write("%s", pwmd_strerror(rc));
954 return FALSE;
957 doc = parse_doc((gchar *)crypto->plaintext, crypto->plaintext_len);
958 if (!doc) {
959 log_write("%s", pwmd_strerror(GPG_ERR_ENOMEM));
960 return FALSE;
963 gcry_md_hash_buffer(GCRY_MD_MD5, md5file, filename, strlen(filename));
964 cdata = g_malloc0(sizeof(struct cache_data_s));
965 if (!cdata) {
966 xmlFreeDoc(doc);
967 log_write("%s", pwmd_strerror(GPG_ERR_ENOMEM));
968 return FALSE;
971 rc = get_checksum(filename, &crc, &len);
972 if (rc) {
973 log_write("%s", pwmd_strerror(rc));
974 xmlFreeDoc(doc);
975 free_cache_data_once(cdata);
976 return FALSE;
979 cdata->crc = crc;
980 rc = encrypt_xml(NULL, cache_key, cache_keysize, GCRY_CIPHER_AES,
981 crypto->plaintext, crypto->plaintext_len, &cdata->doc,
982 &cdata->doclen, &cache_iv, &cache_blocksize, 0);
983 if (rc) {
984 log_write("%s", pwmd_strerror(rc));
985 xmlFreeDoc(doc);
986 free_cache_data_once(cdata);
987 return FALSE;
990 gcry_sexp_build((gcry_sexp_t *)&cdata->pubkey, NULL, "%S", crypto->pkey_sexp);
991 gcry_sexp_build((gcry_sexp_t *)&cdata->sigkey, NULL, "%S", crypto->sigpkey_sexp);
992 gint timeout = get_key_file_integer(filename, "cache_timeout");
993 cache_add_file(md5file, crypto->grip, cdata, timeout);
994 log_write(_("Successfully added '%s' to the cache."), filename);
995 return TRUE;
998 static gpg_error_t init_client_thread(gint fd, const gchar *addr)
1000 gpg_error_t rc = 0;
1001 struct client_thread_s *new = g_malloc0(sizeof(struct client_thread_s));
1003 if (!new) {
1004 close(fd);
1005 return GPG_ERR_ENOMEM;
1008 MUTEX_LOCK(&cn_mutex);
1009 pthread_cleanup_push(cleanup_mutex_cb, &cn_mutex);
1011 if (pipe(new->status_msg_pipe) == -1)
1012 rc = gpg_error_from_syserror();
1014 if (!rc) {
1015 fcntl(new->status_msg_pipe[0], F_SETFL, O_NONBLOCK);
1016 fcntl(new->status_msg_pipe[1], F_SETFL, O_NONBLOCK);
1017 pthread_mutex_init(&new->status_mutex, NULL);
1020 if (!rc) {
1021 #ifdef WITH_GNUTLS
1022 new->remote = addr ? TRUE : FALSE;
1023 #endif
1024 new->fd = fd;
1025 rc = create_thread(client_thread, new, &new->tid, TRUE);
1026 if (rc) {
1027 close(new->status_msg_pipe[0]);
1028 close(new->status_msg_pipe[1]);
1029 pthread_mutex_destroy(&new->status_mutex);
1033 if (!rc) {
1034 cn_thread_list = g_slist_append(cn_thread_list, new);
1035 if (addr)
1036 log_write(_("new connection: tid=%p, fd=%i, addr=%s"),
1037 (pthread_t *)new->tid, fd, addr);
1038 else
1039 log_write(_("new connection: tid=%p, fd=%i"),
1040 (pthread_t *)new->tid, fd);
1043 pthread_cleanup_pop(1);
1045 if (rc) {
1046 g_free(new);
1047 close(fd);
1048 log_write("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1049 pwmd_strerror(rc));
1051 return rc;
1054 #ifdef WITH_GNUTLS
1055 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1056 static void *get_in_addr(struct sockaddr *sa)
1058 if (sa->sa_family == AF_INET)
1059 return &(((struct sockaddr_in*)sa)->sin_addr);
1061 return &(((struct sockaddr_in6*)sa)->sin6_addr);
1064 static void *tcp_accept_thread(void *arg)
1066 gint sockfd = *(gint*)arg;
1068 #ifdef HAVE_PR_SET_NAME
1069 prctl(PR_SET_NAME, "tcp_accept");
1070 #endif
1071 pthread_setspecific(thread_name_key, g_strdup(__FUNCTION__));
1073 for (;;) {
1074 struct sockaddr_storage raddr;
1075 socklen_t slen = sizeof(raddr);
1076 gint fd = -1;
1077 gulong n;
1078 gchar *t;
1079 gchar s[INET6_ADDRSTRLEN];
1081 fd = accept(sockfd, (struct sockaddr *)&raddr, &slen);
1082 if (fd == -1) {
1083 if (errno != EAGAIN) {
1084 if (!quit) // probably EBADF
1085 log_write("accept(): %s", strerror(errno));
1087 break;
1090 continue;
1093 if (quit)
1094 break;
1096 inet_ntop(raddr.ss_family, get_in_addr((struct sockaddr *)&raddr),
1097 s, sizeof s);
1098 (void)init_client_thread(fd, s);
1099 t = get_key_file_string("global", "tcp_wait");
1100 n = strtol(t, NULL, 10);
1101 g_free(t);
1102 if (n > 0)
1103 usleep(n*100000);
1106 /* Just in case accept() failed for some reason other than EBADF */
1107 quit = 1;
1108 return NULL;
1111 static gboolean start_stop_tls_with_protocol(gboolean ipv6, gboolean term)
1113 struct addrinfo hints, *servinfo, *p;
1114 gint port = get_key_file_integer("global", "tcp_port");
1115 gchar buf[7];
1116 gint n;
1117 gpg_error_t rc;
1118 gint *fd = ipv6 ? &tls6_fd : &tls_fd;
1120 if (term || get_key_file_boolean("global", "enable_tcp") == FALSE) {
1121 if (tls6_fd != -1) {
1122 pthread_cancel(tls6_tid);
1123 pthread_join(tls6_tid, NULL);
1124 shutdown(tls6_fd, SHUT_RDWR);
1125 close(tls6_fd);
1126 tls6_fd = -1;
1129 if (tls_fd != -1) {
1130 pthread_cancel(tls_tid);
1131 pthread_join(tls_tid, NULL);
1132 shutdown(tls_fd, SHUT_RDWR);
1133 close(tls_fd);
1134 tls_fd = -1;
1137 /* A client may still be connected. */
1138 if (!quit && x509_cred != NULL)
1139 tls_deinit_params();
1141 return TRUE;
1144 if ((ipv6 && tls6_fd != -1) || (!ipv6 && tls_fd != -1))
1145 return TRUE;
1147 memset(&hints, 0, sizeof(hints));
1148 hints.ai_family = ipv6 ? AF_INET6 : AF_INET;
1149 hints.ai_socktype = SOCK_STREAM;
1150 hints.ai_flags = AI_PASSIVE;
1152 if ((n = getaddrinfo(NULL, print_fmt(buf, sizeof(buf), "%i", port),
1153 &hints, &servinfo)) == -1) {
1154 log_write("getaddrinfo(): %s", gai_strerror(n));
1155 return FALSE;
1158 for (n = 0, p = servinfo; p != NULL; p = p->ai_next) {
1159 if ((ipv6 && p->ai_family != AF_INET6)
1160 || (!ipv6 && p->ai_family != AF_INET))
1161 continue;
1163 if ((*fd = socket(p->ai_family, p->ai_socktype,
1164 p->ai_protocol)) == -1) {
1165 log_write("socket(): %s", strerror(errno));
1166 continue;
1169 if (setsockopt(*fd, SOL_SOCKET, SO_REUSEADDR, &n,
1170 sizeof(int)) == -1) {
1171 log_write("setsockopt(): %s", strerror(errno));
1172 freeaddrinfo(servinfo);
1173 goto fail;
1176 if (bind(*fd, p->ai_addr, p->ai_addrlen) == -1) {
1177 close(*fd);
1178 log_write("bind(): %s", strerror(errno));
1179 continue;
1182 n++;
1183 break;
1186 freeaddrinfo(servinfo);
1188 if (!n) {
1189 log_write("%s", _("could not bind"));
1190 goto fail;
1193 #ifdef HAVE_DECL_SO_BINDTODEVICE
1194 if (g_key_file_has_key(keyfileh, "global", "tcp_interface", NULL)) {
1195 gchar *tmp = get_key_file_string("global", "tcp_interface");
1197 if (setsockopt(*fd, SOL_SOCKET, SO_BINDTODEVICE, tmp, 1)
1198 == -1) {
1199 log_write("setsockopt(): %s", strerror(errno));
1200 g_free(tmp);
1201 goto fail;
1204 g_free(tmp);
1206 #endif
1208 if (x509_cred == NULL) {
1209 rc = tls_init_params();
1210 if (rc)
1211 goto fail;
1214 if (listen(*fd, 0) == -1) {
1215 log_write("listen(): %s", strerror(errno));
1216 goto fail;
1219 if (ipv6)
1220 rc = create_thread(tcp_accept_thread, fd, &tls6_tid, FALSE);
1221 else
1222 rc = create_thread(tcp_accept_thread, fd, &tls_tid, FALSE);
1224 if (rc) {
1225 log_write("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1226 pwmd_strerror(rc));
1227 goto fail;
1230 return TRUE;
1232 fail:
1233 start_stop_tls_with_protocol(FALSE, TRUE);
1234 if (tls_fd != -1)
1235 close(tls_fd);
1237 if (tls6_fd != -1)
1238 close(tls6_fd);
1240 tls_fd = -1;
1241 tls6_fd = -1;
1242 return FALSE;
1245 static gboolean start_stop_tls(gboolean term)
1247 gchar *s = get_key_file_string("global", "tcp_bind");
1248 gboolean b;
1250 if (!s)
1251 return FALSE;
1253 if (!g_strcmp0(s, "any")) {
1254 b = start_stop_tls_with_protocol(FALSE, term);
1255 if (b)
1256 b = start_stop_tls_with_protocol(TRUE, term);
1258 else if (!g_strcmp0(s, "ipv4"))
1259 b = start_stop_tls_with_protocol(FALSE, term);
1260 else if (!g_strcmp0(s, "ipv6"))
1261 b = start_stop_tls_with_protocol(TRUE, term);
1262 else
1263 b = FALSE;
1265 g_free(s);
1266 return b;
1268 #endif
1270 static void *accept_thread(void *arg)
1272 gint sockfd = *(gint *)arg;
1274 #ifdef HAVE_PR_SET_NAME
1275 prctl(PR_SET_NAME, "accept");
1276 #endif
1277 pthread_setspecific(thread_name_key, g_strdup(__FUNCTION__));
1279 for (;;) {
1280 socklen_t slen = sizeof(struct sockaddr_un);
1281 struct sockaddr_un raddr;
1282 gint fd;
1284 fd = accept(sockfd, (struct sockaddr *)&raddr, &slen);
1285 if (fd == -1) {
1286 if (errno != EAGAIN) {
1287 if (!quit) // probably EBADF
1288 log_write("accept(): %s", pwmd_strerror(gpg_error_from_syserror()));
1290 break;
1292 continue;
1295 (void)init_client_thread(fd, NULL);
1298 /* Just in case accept() failed for some reason other than EBADF */
1299 quit = TRUE;
1300 return NULL;
1303 static void *cache_timer_thread(void *arg)
1305 #ifdef HAVE_PR_SET_NAME
1306 prctl(PR_SET_NAME, "cache timer");
1307 #endif
1308 pthread_setspecific(thread_name_key, g_strdup(__FUNCTION__));
1310 for (;;) {
1311 sleep(1);
1312 cache_adjust_timeout();
1315 return NULL;
1318 static void catch_sigabrt(int sig)
1320 cache_clear(NULL);
1321 #ifndef MEM_DEBUG
1322 xpanic();
1323 #endif
1326 static gboolean signal_loop(sigset_t sigset)
1328 gboolean done = FALSE;
1329 gboolean sigint = FALSE;
1331 do {
1332 gint sig = sigwaitinfo(&sigset, NULL);
1334 if (sig == -1) {
1335 if (errno != EAGAIN)
1336 log_write("sigwaitinfo(): %s", strerror(errno));
1337 continue;
1340 if (sig != SIGUSR2)
1341 log_write(_("caught signal %i (%s)"), sig, strsignal(sig));
1343 switch (sig) {
1344 case SIGHUP:
1345 pthread_cond_signal(&rcfile_cond);
1346 break;
1347 case SIGABRT:
1348 // not really handled here.
1349 catch_sigabrt(SIGABRT);
1350 break;
1351 case SIGUSR1:
1352 log_write(_("clearing file cache"));
1353 cache_clear(NULL);
1354 send_status_all(STATUS_CACHE, NULL);
1355 break;
1356 case SIGUSR2:
1357 done = TRUE;
1358 break;
1359 default:
1360 sigint = TRUE;
1361 done = TRUE;
1362 break;
1364 } while (!done);
1366 return sigint;
1369 static void catchsig(int sig)
1371 log_write("Caught SIGSEGV. Exiting.");
1372 #ifdef HAVE_BACKTRACE
1373 BACKTRACE(__FUNCTION__);
1374 #endif
1375 longjmp(jmp, 1);
1378 static void *waiting_for_exit(void *arg)
1380 #ifdef HAVE_PR_SET_NAME
1381 prctl(PR_SET_NAME, "exiting");
1382 #endif
1383 pthread_setspecific(thread_name_key, g_strdup(__FUNCTION__));
1384 log_write(_("waiting for all clients to disconnect"));
1385 MUTEX_LOCK(&quit_mutex);
1386 pthread_cleanup_push(cleanup_mutex_cb, &quit_mutex);
1388 for (;;) {
1389 MUTEX_LOCK(&cn_mutex);
1390 gint n = g_slist_length(cn_thread_list);
1391 MUTEX_UNLOCK(&cn_mutex);
1392 if (!n)
1393 break;
1395 log_write(_("%i clients remain"), n);
1396 pthread_cond_wait(&quit_cond, &quit_mutex);
1399 pthread_cleanup_pop(1);
1400 kill(getpid(), SIGUSR2);
1401 return NULL;
1404 static gboolean server_loop(gint sockfd, gchar **socketpath)
1406 pthread_t accept_tid = 0;
1407 pthread_t cache_timeout_tid = 0;
1408 gint n, i;
1409 sigset_t sigset;
1410 gboolean segv = FALSE;
1411 gpg_error_t rc;
1413 init_commands();
1414 sigemptyset(&sigset);
1416 /* Termination */
1417 sigaddset(&sigset, SIGTERM);
1418 sigaddset(&sigset, SIGINT);
1420 /* Clears the file cache. */
1421 sigaddset(&sigset, SIGUSR1);
1423 /* Configuration file reloading. */
1424 sigaddset(&sigset, SIGHUP);
1426 /* For exiting cleanly. */
1427 sigaddset(&sigset, SIGUSR2);
1429 /* Clears the cache and exits when something bad happens. */
1430 signal(SIGABRT, catch_sigabrt);
1431 sigaddset(&sigset, SIGABRT);
1432 sigprocmask(SIG_BLOCK, &sigset, NULL);
1434 /* Ignored everywhere. When a client disconnects abnormally this signal
1435 * gets raised. It isn't needed though because client_thread() will check
1436 * for rcs even after the client disconnects. */
1437 signal(SIGPIPE, SIG_IGN);
1439 /* Can show a backtrace of the stack in the log. */
1440 signal(SIGSEGV, catchsig);
1442 #ifdef WITH_GNUTLS
1443 /* Needs to be done after the fork(). */
1444 if (!start_stop_tls(FALSE)) {
1445 segv = TRUE;
1446 goto done;
1448 #endif
1450 pthread_mutex_init(&quit_mutex, NULL);
1451 pthread_cond_init(&quit_cond, NULL);
1452 log_write(_("%s started for user %s"), PACKAGE_STRING, g_get_user_name());
1453 #ifndef HAVE_DECL_SO_PEERCRED
1454 log_write(_("Peer credential checking is NOT supported on this OS."));
1455 #endif
1456 #ifdef WITH_GNUTLS
1457 if (get_key_file_boolean("global", "enable_tcp"))
1458 log_write(_("Listening on %s and TCP port %i"), *socketpath,
1459 get_key_file_integer("global", "tcp_port"));
1460 else
1461 log_write(_("Listening on %s"), *socketpath);
1462 #else
1463 log_write(_("Listening on %s"), *socketpath);
1464 #endif
1466 rc = create_thread(reload_rcfile_thread, NULL, &rcfile_tid, FALSE);
1467 if (rc) {
1468 log_write("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1469 pwmd_strerror(rc));
1470 goto done;
1473 rc = create_thread(cache_timer_thread, NULL, &cache_timeout_tid, TRUE);
1474 if (rc) {
1475 log_write("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1476 pwmd_strerror(rc));
1477 goto done;
1480 rc = create_thread(accept_thread, &sockfd, &accept_tid, TRUE);
1481 if (rc) {
1482 log_write("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1483 pwmd_strerror(rc));
1484 goto done;
1487 sigdelset(&sigset, SIGUSR2);
1488 if (!setjmp(jmp))
1489 signal_loop(sigset);
1490 else
1491 segv = TRUE;
1493 done:
1495 * We're out of the main server loop. This happens when a signal was sent
1496 * to terminate the daemon. We'll wait for all clients to disconnect
1497 * before exiting but exit immediately if another termination signal is
1498 * sent.
1500 if (accept_tid)
1501 pthread_cancel(accept_tid);
1503 shutdown(sockfd, SHUT_RDWR);
1504 close(sockfd);
1505 unlink(*socketpath);
1506 g_free(*socketpath);
1507 *socketpath = NULL;
1508 MUTEX_LOCK(&cn_mutex);
1509 n = g_slist_length(cn_thread_list);
1510 MUTEX_UNLOCK(&cn_mutex);
1512 if (n && !segv) {
1513 pthread_t tid;
1515 rc = create_thread(waiting_for_exit, NULL, &tid, TRUE);
1516 if (!rc) {
1517 sigaddset(&sigset, SIGUSR2);
1518 if (signal_loop(sigset)) {
1519 log_write(_("Received second termination request. Exiting."));
1520 pthread_cancel(tid);
1523 else
1524 log_write("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1525 pwmd_strerror(rc));
1528 if (cache_timeout_tid)
1529 pthread_cancel(cache_timeout_tid);
1531 MUTEX_LOCK(&cn_mutex);
1532 i = 0;
1533 n = g_slist_length(cn_thread_list);
1535 for (i = 0; i < n; i++) {
1536 struct client_thread_s *thd = g_slist_nth_data(cn_thread_list, i);
1538 if (thd->fd != -1) {
1539 close(thd->fd);
1540 thd->fd = -1;
1544 exiting = TRUE;
1545 MUTEX_UNLOCK(&cn_mutex);
1546 #ifdef WITH_GNUTLS
1547 start_stop_tls(TRUE);
1548 #endif
1549 cache_deinit();
1550 deinit_commands();
1551 pthread_cond_destroy(&quit_cond);
1552 pthread_mutex_destroy(&quit_mutex);
1553 return segv ? EXIT_FAILURE : EXIT_SUCCESS;;
1556 static void startup_failure()
1558 log_write(_("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
1559 cache_clear(NULL);
1562 /* This is called from cache.c:clear_once(). See
1563 * command.c:clearcache_command() for details about lock checking.
1565 static gpg_error_t free_cache_data(file_cache_t *cache)
1567 gpg_error_t rc = GPG_ERR_NO_DATA;
1568 gint i, t;
1569 struct client_thread_s *found = NULL;
1570 gboolean self = FALSE;
1572 if (!cache->data)
1573 return 0;
1575 cache_lock();
1576 MUTEX_LOCK(&cn_mutex);
1577 pthread_cleanup_push(cleanup_mutex_cb, &cn_mutex);
1578 t = g_slist_length(cn_thread_list);
1580 for (i = 0; i < t; i++) {
1581 struct client_thread_s *thd = g_slist_nth_data(cn_thread_list, i);
1583 if (!thd->cl)
1584 continue;
1586 if (!memcmp(thd->cl->md5file, cache->filename,
1587 sizeof(cache->filename))) {
1588 if (pthread_equal(pthread_self(), thd->tid)) {
1589 found = thd;
1590 self = TRUE;
1591 continue;
1594 /* Continue trying to find a client who has the same file open and
1595 * also has a lock. */
1596 rc = cache_lock_mutex(thd->cl->ctx, thd->cl->md5file, -1, FALSE, -1);
1597 if (!rc) {
1598 self = FALSE;
1599 found = thd;
1600 break;
1605 if (self && (!rc || rc == GPG_ERR_NO_DATA))
1606 rc = cache_lock_mutex(found->cl->ctx, found->cl->md5file, -1, FALSE, -1);
1608 if (exiting || !rc || rc == GPG_ERR_NO_DATA) {
1609 free_cache_data_once(cache->data);
1610 cache->data = NULL;
1611 cache->defer_clear = FALSE;
1612 cache->timeout = -1;
1614 if (found)
1615 cache_unlock_mutex(found->cl->md5file, FALSE);
1617 rc = 0;
1620 if (rc)
1621 cache->defer_clear = TRUE;
1623 pthread_cleanup_pop(1);
1624 cache_unlock();
1625 return rc;
1628 static gboolean convert_v2_datafile(const gchar *filename, const gchar *cipher,
1629 const gchar *keyfile, const gchar *keygrip, const gchar *sign_keygrip,
1630 gboolean nopass, const gchar *outfile, const gchar *keyparam,
1631 gulong s2k_count, guint64 iterations)
1633 gpg_error_t rc;
1634 gpointer data = NULL;
1635 gsize datalen;
1636 struct crypto_s *crypto = NULL;
1637 guint16 ver;
1638 gint algo;
1640 if (outfile[0] == '-' && outfile[1] == 0)
1641 outfile = NULL;
1643 log_write(_("Converting version 2 data file \"%s\" ..."), filename);
1644 if (access(filename, R_OK) == -1) {
1645 log_write("%s: %s", filename, pwmd_strerror(gpg_error_from_syserror()));
1646 return FALSE;
1649 if (keyfile) {
1650 log_write(_("Using passphrase file \"%s\" for decryption ..."),
1651 keyfile);
1652 if (access(keyfile, R_OK) == -1) {
1653 log_write("%s: %s", keyfile,
1654 pwmd_strerror(gpg_error_from_syserror()));
1655 return FALSE;
1659 rc = read_v2_datafile(filename, keyfile, &data, &datalen, &ver, &algo);
1660 if (rc) {
1661 log_write("%s", pwmd_strerror(rc));
1662 return FALSE;
1665 if (cipher) {
1666 algo = cipher_string_to_gcrypt(cipher);
1667 if (algo == -1) {
1668 rc = GPG_ERR_CIPHER_ALGO;
1669 goto fail;
1673 if (ver < 0x212) {
1674 xmlDocPtr doc = parse_doc(data, datalen);
1676 if (!doc) {
1677 rc = GPG_ERR_BAD_DATA;
1678 goto fail;
1681 rc = convert_pre_212_elements(doc);
1682 gcry_free(data);
1683 data = NULL;
1684 if (!rc) {
1685 xmlDocDumpFormatMemory(doc, (xmlChar **)&data, (gint *)&datalen, 0);
1686 if (!data)
1687 rc = GPG_ERR_ENOMEM;
1690 xmlFreeDoc(doc);
1691 if (rc)
1692 goto fail;
1695 rc = init_client_crypto(&crypto);
1696 if (!rc) {
1697 rc = set_pinentry_options(crypto->agent);
1698 if (!rc) {
1699 memcpy(&crypto->save.hdr, &crypto->hdr,
1700 sizeof(file_header_t));
1701 crypto->save.hdr.flags = set_cipher_flag(crypto->save.hdr.flags, algo);
1702 crypto->save.s2k_count = (gulong)s2k_count;
1703 crypto->save.hdr.iterations = iterations;
1704 rc = export_common(crypto, keygrip, sign_keygrip, nopass, data,
1705 datalen, outfile, keyparam,
1706 no_passphrase_file ? NULL : keyfile);
1707 if (!rc)
1708 log_write(_("Output written to \"%s\"."), outfile);
1712 fail:
1713 if (ver < 0x212)
1714 xmlFree(data);
1715 else
1716 gcry_free(data);
1717 cleanup_crypto(&crypto);
1719 if (rc)
1720 log_write("%s", pwmd_strerror(rc));
1721 return rc ? FALSE : TRUE;
1724 int main(int argc, char *argv[])
1726 gint opt;
1727 struct sockaddr_un addr;
1728 gchar buf[PATH_MAX];
1729 gchar *socketpath = NULL, *socketdir, *socketname = NULL;
1730 gchar *socketarg = NULL;
1731 gchar *datadir = NULL;
1732 gboolean n;
1733 gint x;
1734 gchar *p;
1735 gchar **cache_push = NULL;
1736 gchar *import = NULL, *keygrip = NULL, *sign_keygrip = NULL;
1737 gchar *keyparam = NULL;
1738 gboolean rcfile_spec = FALSE;
1739 gint estatus = EXIT_FAILURE;
1740 gint sockfd;
1741 gchar *outfile = NULL;
1742 GMemVTable mtable = { xmalloc, xrealloc, xfree, xcalloc, NULL, NULL };
1743 gint do_unlink = 0;
1744 gboolean secure = FALSE;
1745 gint show_version = 0;
1746 gboolean force = FALSE;
1747 gboolean no_passphrase = FALSE;
1748 gpg_error_t rc;
1749 gchar *convertfile = NULL;
1750 gchar *cipher = NULL;
1751 gchar *keyfile = NULL;
1752 glong s2k_count = -1;
1753 guint64 iterations = 0;
1754 GError *error = NULL;
1755 gchar *debug_level_opt = NULL;
1756 GOptionContext *context;
1757 GOptionEntry options[] =
1759 { "version", 0, 0, G_OPTION_ARG_NONE, &show_version,
1760 "version information", NULL },
1761 { "no-fork", 'n', 0, G_OPTION_ARG_NONE, &nofork,
1762 "run as a foreground process", NULL },
1763 { "disable-dump", 'D', 0, G_OPTION_ARG_NONE, &secure,
1764 "disable the LIST, XPATH and DUMP commands", NULL },
1765 { "rcfile", 'f', 0, G_OPTION_ARG_FILENAME, &rcfile,
1766 "load the specified rcfile (~/.pwmd/config)", "filename" },
1767 { "ignore", 0, 0, G_OPTION_ARG_NONE, &force,
1768 "ignore cache failures on startup", NULL },
1769 { "outfile", 'o', 0, G_OPTION_ARG_FILENAME, &outfile,
1770 "output file when importing (- for stdout)", "filename" },
1771 { "convert", 'C', 0, G_OPTION_ARG_FILENAME, &convertfile,
1772 "convert a version 2 data file to version 3", "filename" },
1773 { "passphrase-file", 'k', 0, G_OPTION_ARG_FILENAME, &keyfile,
1774 "for decryption when converting", "filename" },
1775 { "no-passphrase-file", 0, 0, G_OPTION_ARG_NONE, &no_passphrase_file,
1776 "no --passphrase-file after conversion", NULL },
1777 { "import", 'I', 0, G_OPTION_ARG_FILENAME, &import,
1778 "import an XML file", "filename" },
1779 { "keygrip", 0, 0, G_OPTION_ARG_STRING, &keygrip,
1780 "the public keygrip to use for encryption", "hexstring"},
1781 { "sign-keygrip", 0, 0, G_OPTION_ARG_STRING, &sign_keygrip,
1782 "the keygrip to use for signing of the data", "hexstring"},
1783 { "keyparam", 0, 0, G_OPTION_ARG_STRING, &keyparam,
1784 "alternate key parameters to use (RSA-2048)", "s-exp"},
1785 { "no-passphrase", 0, 0, G_OPTION_ARG_NONE, &no_passphrase,
1786 "for the imported/converted keypair", NULL },
1787 { "cipher", 0, 0, G_OPTION_ARG_STRING, &cipher,
1788 "encryption cipher, see man page (aes256)", "string" },
1789 { "s2k-count", 0, 0, G_OPTION_ARG_INT64, &s2k_count,
1790 "hash iteration count >65536 (calibrated)", "iterations" },
1791 { "cipher-iterations", 0, 0, G_OPTION_ARG_INT64, &iterations,
1792 "cipher iteration count (N+1)", "iterations" },
1793 { "debug-level", 0, 0, G_OPTION_ARG_STRING, &debug_level_opt,
1794 "protocol output, see man page", "keywords"},
1795 { "homedir", 'I', 0, G_OPTION_ARG_STRING, &homedir,
1796 "home directory for pwmd", "directory" },
1797 { NULL }
1800 #ifndef DEBUG
1801 #ifdef HAVE_SETRLIMIT
1802 struct rlimit rl;
1804 rl.rlim_cur = rl.rlim_max = 0;
1806 if (setrlimit(RLIMIT_CORE, &rl) != 0)
1807 err(EXIT_FAILURE, "setrlimit()");
1808 #endif
1809 #endif
1811 #ifdef ENABLE_NLS
1812 setlocale(LC_ALL, "");
1813 bindtextdomain("pwmd", LOCALEDIR);
1814 textdomain("pwmd");
1815 #endif
1817 #ifndef MEM_DEBUG
1818 xmem_init();
1819 #endif
1820 g_mem_set_vtable(&mtable);
1821 g_thread_init(NULL);
1822 gpg_err_init();
1824 if (setup_crypto())
1825 exit(EXIT_FAILURE);
1827 #ifdef WITH_GNUTLS
1828 gnutls_global_set_mem_functions(g_malloc, g_malloc, secure_mem_check,
1829 g_realloc, g_free);
1830 gnutls_global_init();
1831 gnutls_global_set_log_function(tls_log);
1832 gnutls_global_set_log_level(1);
1833 tls_fd = -1;
1834 tls6_fd = -1;
1835 #endif
1836 xmlMemSetup(g_free, g_malloc, g_realloc, g_strdup);
1837 xmlInitMemory();
1838 xmlInitGlobals();
1839 xmlInitParser();
1840 xmlXPathInit();
1842 cmdline = TRUE;
1843 context = g_option_context_new("- Password Manager Daemon");
1844 g_option_context_add_main_entries(context, options, NULL);
1845 if (!g_option_context_parse(context, &argc, &argv, &error))
1847 g_print("Option parsing failed: %s\n", error->message);
1848 exit(EXIT_FAILURE);
1851 if (show_version) {
1852 printf(_("%s\n\n"
1853 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012\n"
1854 "%s\n"
1855 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
1856 "Compile time features:\n%s"), PACKAGE_STRING, PACKAGE_BUGREPORT,
1857 #ifdef WITH_GNUTLS
1858 "+WITH_GNUTLS\n"
1859 #else
1860 "-WITH_GNUTLS\n"
1861 #endif
1862 #ifdef WITH_LIBACL
1863 "+WITH_LIBACL\n"
1864 #else
1865 "-WITH_LIBACL\n"
1866 #endif
1867 #ifdef DEBUG
1868 "+DEBUG\n"
1869 #else
1870 "-DEBUG\n"
1871 #endif
1872 #ifdef MEM_DEBUG
1873 "+MEM_DEBUG\n"
1874 #else
1875 "-MEM_DEBUG\n"
1876 #endif
1877 #ifdef MUTEX_DEBUG
1878 "+MUTEX_DEBUG\n"
1879 #else
1880 "-MUTEX_DEBUG\n"
1881 #endif
1883 exit(EXIT_SUCCESS);
1886 if (!homedir)
1887 homedir = g_strdup_printf("%s/.pwmd", g_get_home_dir());
1889 if (mkdir(homedir, 0700) == -1 && errno != EEXIST)
1890 err(EXIT_FAILURE, "%s", homedir);
1892 g_snprintf(buf, sizeof(buf), "%s/data", homedir);
1893 if (mkdir(buf, 0700) == -1 && errno != EEXIST)
1894 err(EXIT_FAILURE, "%s", buf);
1896 datadir = g_strdup(buf);
1897 pthread_mutexattr_t attr;
1898 pthread_mutexattr_init(&attr);
1899 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1900 pthread_mutex_init(&rcfile_mutex, &attr);
1901 pthread_cond_init(&rcfile_cond, NULL);
1902 pthread_mutex_init(&cn_mutex, &attr);
1903 pthread_mutexattr_destroy(&attr);
1904 pthread_key_create(&last_error_key, free_key);
1906 if (!rcfile)
1907 rcfile = g_strdup_printf("%s/config", homedir);
1908 else
1909 rcfile_spec = TRUE;
1911 if ((keyfileh = parse_rcfile(rcfile_spec, cmdline)) == NULL)
1912 exit(EXIT_FAILURE);
1914 if (debug_level_opt)
1915 debug_level = g_strsplit(debug_level_opt, ",", 0);
1917 if (g_key_file_has_key(keyfileh, "global", "syslog", NULL) == TRUE)
1918 log_syslog = g_key_file_get_boolean(keyfileh, "global", "syslog", NULL);
1920 if (log_syslog == TRUE)
1921 openlog("pwmd", LOG_NDELAY|LOG_PID, LOG_DAEMON);
1923 if (g_key_file_has_key(keyfileh, "global", "priority", NULL)) {
1924 x = g_key_file_get_integer(keyfileh, "global", "priority", NULL);
1925 errno = 0;
1927 if (setpriority(PRIO_PROCESS, 0, x) == -1) {
1928 log_write("setpriority(): %s", pwmd_strerror(gpg_error_from_syserror()));
1929 goto do_exit;
1933 #ifdef HAVE_MLOCKALL
1934 if (disable_mlock == FALSE && mlockall(MCL_CURRENT|MCL_FUTURE) == -1) {
1935 log_write("mlockall(): %s", pwmd_strerror(gpg_error_from_syserror()));
1936 goto do_exit;
1938 #endif
1940 rc = cache_init(free_cache_data);
1941 if (rc) {
1942 log_write("pwmd: gpg-agent: %s",
1943 gpg_err_code(rc) == GPG_ERR_UNKNOWN_VERSION
1944 ? _("incompatible version: 2.1.0 or later required")
1945 : pwmd_strerror(rc));
1946 goto do_exit;
1949 if (s2k_count == -1)
1950 s2k_count = get_key_file_ulong(NULL, "s2k_count");
1952 if (convertfile) {
1953 if (!outfile) {
1954 gchar *tmp = g_option_context_get_help(context, TRUE, NULL);
1955 fprintf(stderr, "%s", tmp);
1956 g_free(tmp);
1957 exit(EXIT_FAILURE);
1960 estatus = convert_v2_datafile(convertfile, cipher, keyfile, keygrip,
1961 sign_keygrip, no_passphrase, outfile, keyparam,
1962 (gulong)s2k_count, iterations);
1963 g_key_file_free(keyfileh);
1964 g_free(rcfile);
1965 exit(!estatus);
1968 if (import) {
1969 if (!outfile) {
1970 gchar *tmp = g_option_context_get_help(context, TRUE, NULL);
1971 fprintf(stderr, "%s", tmp);
1972 g_free(tmp);
1973 exit(EXIT_FAILURE);
1976 if (outfile[0] == '-' && outfile[1] == 0)
1977 outfile = NULL;
1979 estatus = xml_import(import, outfile, keygrip, sign_keygrip, keyfile,
1980 no_passphrase, cipher, keyparam, (gulong)s2k_count, iterations);
1981 g_key_file_free(keyfileh);
1982 g_free(rcfile);
1983 exit(!estatus);
1986 g_option_context_free(context);
1987 p = g_key_file_get_string(keyfileh, "global", "socket_path", NULL);
1988 if (!p)
1989 p = g_strdup_printf("%s/socket", homedir);
1991 socketarg = expand_homedir(p);
1992 g_free(p);
1994 if (secure == FALSE && g_key_file_has_key(keyfileh, "global", "disable_list_and_dump", NULL) == TRUE) {
1995 n = g_key_file_get_boolean(keyfileh, "global", "disable_list_and_dump", NULL);
1996 disable_list_and_dump = n;
1998 else
1999 disable_list_and_dump = secure;
2001 setup_logging(keyfileh);
2003 if (g_key_file_has_key(keyfileh, "global", "cache_push", NULL) == TRUE)
2004 cache_push = g_key_file_get_string_list(keyfileh, "global", "cache_push", NULL, NULL);
2006 for (gint n = 1; n < argc; n++) {
2007 if (strv_printf(&cache_push, "%s", argv[n]) == FALSE)
2008 errx(EXIT_FAILURE, "%s", pwmd_strerror(GPG_ERR_ENOMEM));
2011 if (strchr(socketarg, '/') == NULL) {
2012 socketdir = g_get_current_dir();
2013 socketname = g_strdup(socketarg);
2014 socketpath = g_strdup_printf("%s/%s", socketdir, socketname);
2016 else {
2017 socketname = g_strdup(strrchr(socketarg, '/'));
2018 socketname++;
2019 socketarg[strlen(socketarg) - strlen(socketname) -1] = 0;
2020 socketdir = g_strdup(socketarg);
2021 socketpath = g_strdup_printf("%s/%s", socketdir, socketname);
2024 if (chdir(datadir)) {
2025 log_write("%s: %s", datadir, pwmd_strerror(gpg_error_from_syserror()));
2026 unlink(socketpath);
2027 goto do_exit;
2031 * Set the cache entry for a file. Prompts for the password.
2033 if (cache_push) {
2034 struct crypto_s *crypto;
2035 gpg_error_t rc = init_client_crypto(&crypto);
2037 if (rc) {
2038 estatus = EXIT_FAILURE;
2039 goto do_exit;
2042 rc = set_pinentry_options(crypto->agent);
2043 if (rc) {
2044 estatus = EXIT_FAILURE;
2045 goto do_exit;
2048 for (opt = 0; cache_push[opt]; opt++) {
2049 if (!do_cache_push(cache_push[opt], crypto) && !force) {
2050 g_strfreev(cache_push);
2051 startup_failure();
2052 estatus = EXIT_FAILURE;
2053 cleanup_crypto(&crypto);
2054 goto do_exit;
2057 cleanup_crypto_stage1(crypto);
2060 (void)kill_scd(crypto->agent);
2061 cleanup_crypto(&crypto);
2062 g_strfreev(cache_push);
2063 log_write(!nofork ? _("Done. Daemonizing...") : _("Done. Waiting for connections..."));
2066 clear_rcfile_keys();
2069 * bind() doesn't like the full pathname of the socket or any non alphanum
2070 * characters so change to the directory where the socket is wanted then
2071 * create it then change to datadir.
2073 if (chdir(socketdir)) {
2074 log_write("%s: %s", socketdir, pwmd_strerror(gpg_error_from_syserror()));
2075 goto do_exit;
2078 g_free(socketdir);
2080 if ((sockfd = socket(PF_UNIX, SOCK_STREAM, 0)) == -1) {
2081 log_write("socket(): %s", pwmd_strerror(gpg_error_from_syserror()));
2082 goto do_exit;
2085 addr.sun_family = AF_UNIX;
2086 g_snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", socketname);
2088 if (bind(sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr)) == -1) {
2089 log_write("bind(): %s", pwmd_strerror(gpg_error_from_syserror()));
2091 if (errno == EADDRINUSE)
2092 log_write(_("Either there is another pwmd running or '%s' is a \n"
2093 "stale socket. Please remove it manually."), socketpath);
2095 goto do_exit;
2098 do_unlink = 1;
2099 if (g_key_file_has_key(keyfileh, "global", "socket_perms", NULL) == TRUE) {
2100 gchar *t = g_key_file_get_string(keyfileh, "global", "socket_perms", NULL);
2101 mode_t mode = strtol(t, NULL, 8);
2102 mode_t mask = umask(0);
2104 g_free(t);
2106 if (chmod(socketname, mode) == -1) {
2107 log_write("%s: %s", socketname, pwmd_strerror(gpg_error_from_syserror()));
2108 close(sockfd);
2109 unlink(socketpath);
2110 umask(mask);
2111 goto do_exit;
2114 umask(mask);
2117 g_free(--socketname);
2119 if (chdir(datadir)) {
2120 log_write("%s: %s", datadir, pwmd_strerror(gpg_error_from_syserror()));
2121 close(sockfd);
2122 unlink(socketpath);
2123 goto do_exit;
2126 g_free(datadir);
2128 if (listen(sockfd, 0) == -1) {
2129 log_write("listen(): %s", pwmd_strerror(gpg_error_from_syserror()));
2130 goto do_exit;
2133 cmdline = FALSE;
2135 if (!nofork) {
2136 switch (fork()) {
2137 case -1:
2138 log_write("fork(): %s", pwmd_strerror(gpg_error_from_syserror()));
2139 goto do_exit;
2140 case 0:
2141 close(0);
2142 close(1);
2143 close(2);
2144 setsid();
2145 break;
2146 default:
2147 _exit(EXIT_SUCCESS);
2151 pthread_key_create(&thread_name_key, free_key);
2152 pthread_setspecific(thread_name_key, g_strdup("main"));
2153 estatus = server_loop(sockfd, &socketpath);
2155 do_exit:
2156 if (socketpath && do_unlink) {
2157 unlink(socketpath);
2158 g_free(socketpath);
2161 g_free(socketarg);
2162 #ifdef WITH_GNUTLS
2163 gnutls_global_deinit();
2164 #endif
2165 if (keyfileh)
2166 g_key_file_free(keyfileh);
2168 pthread_cancel(rcfile_tid);
2169 pthread_join(rcfile_tid, NULL);
2170 pthread_cond_destroy(&rcfile_cond);
2171 pthread_mutex_destroy(&rcfile_mutex);
2172 g_free(rcfile);
2173 xmlCleanupParser();
2174 xmlCleanupGlobals();
2176 if (estatus == EXIT_SUCCESS)
2177 log_write(_("pwmd exiting normally"));
2179 #if defined(DEBUG) && !defined(MEM_DEBUG)
2180 xdump();
2181 #endif
2182 exit(estatus);