Revert "Fix segfault when server_loop() fails for some reason."
[pwmd.git] / src / pwmd.c
blob0758e9d1bb25fa9802406f1e12ff68a933beacf3
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;
1407 pthread_t cache_timeout_tid;
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 pthread_cancel(accept_tid);
1501 shutdown(sockfd, SHUT_RDWR);
1502 close(sockfd);
1503 unlink(*socketpath);
1504 g_free(*socketpath);
1505 *socketpath = NULL;
1506 MUTEX_LOCK(&cn_mutex);
1507 n = g_slist_length(cn_thread_list);
1508 MUTEX_UNLOCK(&cn_mutex);
1510 if (n && !segv) {
1511 pthread_t tid;
1513 rc = create_thread(waiting_for_exit, NULL, &tid, TRUE);
1514 if (!rc) {
1515 sigaddset(&sigset, SIGUSR2);
1516 if (signal_loop(sigset)) {
1517 log_write(_("Received second termination request. Exiting."));
1518 pthread_cancel(tid);
1521 else
1522 log_write("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1523 pwmd_strerror(rc));
1526 pthread_cancel(cache_timeout_tid);
1527 MUTEX_LOCK(&cn_mutex);
1528 i = 0;
1529 n = g_slist_length(cn_thread_list);
1531 for (i = 0; i < n; i++) {
1532 struct client_thread_s *thd = g_slist_nth_data(cn_thread_list, i);
1534 if (thd->fd != -1) {
1535 close(thd->fd);
1536 thd->fd = -1;
1540 exiting = TRUE;
1541 MUTEX_UNLOCK(&cn_mutex);
1542 #ifdef WITH_GNUTLS
1543 start_stop_tls(TRUE);
1544 #endif
1545 cache_deinit();
1546 deinit_commands();
1547 pthread_cond_destroy(&quit_cond);
1548 pthread_mutex_destroy(&quit_mutex);
1549 return segv ? EXIT_FAILURE : EXIT_SUCCESS;;
1552 static void startup_failure()
1554 log_write(_("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
1555 cache_clear(NULL);
1558 /* This is called from cache.c:clear_once(). See
1559 * command.c:clearcache_command() for details about lock checking.
1561 static gpg_error_t free_cache_data(file_cache_t *cache)
1563 gpg_error_t rc = GPG_ERR_NO_DATA;
1564 gint i, t;
1565 struct client_thread_s *found = NULL;
1566 gboolean self = FALSE;
1568 if (!cache->data)
1569 return 0;
1571 cache_lock();
1572 MUTEX_LOCK(&cn_mutex);
1573 pthread_cleanup_push(cleanup_mutex_cb, &cn_mutex);
1574 t = g_slist_length(cn_thread_list);
1576 for (i = 0; i < t; i++) {
1577 struct client_thread_s *thd = g_slist_nth_data(cn_thread_list, i);
1579 if (!thd->cl)
1580 continue;
1582 if (!memcmp(thd->cl->md5file, cache->filename,
1583 sizeof(cache->filename))) {
1584 if (pthread_equal(pthread_self(), thd->tid)) {
1585 found = thd;
1586 self = TRUE;
1587 continue;
1590 /* Continue trying to find a client who has the same file open and
1591 * also has a lock. */
1592 rc = cache_lock_mutex(thd->cl->ctx, thd->cl->md5file, -1, FALSE, -1);
1593 if (!rc) {
1594 self = FALSE;
1595 found = thd;
1596 break;
1601 if (self && (!rc || rc == GPG_ERR_NO_DATA))
1602 rc = cache_lock_mutex(found->cl->ctx, found->cl->md5file, -1, FALSE, -1);
1604 if (exiting || !rc || rc == GPG_ERR_NO_DATA) {
1605 free_cache_data_once(cache->data);
1606 cache->data = NULL;
1607 cache->defer_clear = FALSE;
1608 cache->timeout = -1;
1610 if (found)
1611 cache_unlock_mutex(found->cl->md5file, FALSE);
1613 rc = 0;
1616 if (rc)
1617 cache->defer_clear = TRUE;
1619 pthread_cleanup_pop(1);
1620 cache_unlock();
1621 return rc;
1624 static gboolean convert_v2_datafile(const gchar *filename, const gchar *cipher,
1625 const gchar *keyfile, const gchar *keygrip, const gchar *sign_keygrip,
1626 gboolean nopass, const gchar *outfile, const gchar *keyparam,
1627 gulong s2k_count, guint64 iterations)
1629 gpg_error_t rc;
1630 gpointer data = NULL;
1631 gsize datalen;
1632 struct crypto_s *crypto = NULL;
1633 guint16 ver;
1634 gint algo;
1636 if (outfile[0] == '-' && outfile[1] == 0)
1637 outfile = NULL;
1639 log_write(_("Converting version 2 data file \"%s\" ..."), filename);
1640 if (access(filename, R_OK) == -1) {
1641 log_write("%s: %s", filename, pwmd_strerror(gpg_error_from_syserror()));
1642 return FALSE;
1645 if (keyfile) {
1646 log_write(_("Using passphrase file \"%s\" for decryption ..."),
1647 keyfile);
1648 if (access(keyfile, R_OK) == -1) {
1649 log_write("%s: %s", keyfile,
1650 pwmd_strerror(gpg_error_from_syserror()));
1651 return FALSE;
1655 rc = read_v2_datafile(filename, keyfile, &data, &datalen, &ver, &algo);
1656 if (rc) {
1657 log_write("%s", pwmd_strerror(rc));
1658 return FALSE;
1661 if (cipher) {
1662 algo = cipher_string_to_gcrypt(cipher);
1663 if (algo == -1) {
1664 rc = GPG_ERR_CIPHER_ALGO;
1665 goto fail;
1669 if (ver < 0x212) {
1670 xmlDocPtr doc = parse_doc(data, datalen);
1672 if (!doc) {
1673 rc = GPG_ERR_BAD_DATA;
1674 goto fail;
1677 rc = convert_pre_212_elements(doc);
1678 gcry_free(data);
1679 data = NULL;
1680 if (!rc) {
1681 xmlDocDumpFormatMemory(doc, (xmlChar **)&data, (gint *)&datalen, 0);
1682 if (!data)
1683 rc = GPG_ERR_ENOMEM;
1686 xmlFreeDoc(doc);
1687 if (rc)
1688 goto fail;
1691 rc = init_client_crypto(&crypto);
1692 if (!rc) {
1693 rc = set_pinentry_options(crypto->agent);
1694 if (!rc) {
1695 memcpy(&crypto->save.hdr, &crypto->hdr,
1696 sizeof(file_header_t));
1697 crypto->save.hdr.flags = set_cipher_flag(crypto->save.hdr.flags, algo);
1698 crypto->save.s2k_count = (gulong)s2k_count;
1699 crypto->save.hdr.iterations = iterations;
1700 rc = export_common(crypto, keygrip, sign_keygrip, nopass, data,
1701 datalen, outfile, keyparam,
1702 no_passphrase_file ? NULL : keyfile);
1703 if (!rc)
1704 log_write(_("Output written to \"%s\"."), outfile);
1708 fail:
1709 if (ver < 0x212)
1710 xmlFree(data);
1711 else
1712 gcry_free(data);
1713 cleanup_crypto(&crypto);
1715 if (rc)
1716 log_write("%s", pwmd_strerror(rc));
1717 return rc ? FALSE : TRUE;
1720 int main(int argc, char *argv[])
1722 gint opt;
1723 struct sockaddr_un addr;
1724 gchar buf[PATH_MAX];
1725 gchar *socketpath = NULL, *socketdir, *socketname = NULL;
1726 gchar *socketarg = NULL;
1727 gchar *datadir = NULL;
1728 gboolean n;
1729 gint x;
1730 gchar *p;
1731 gchar **cache_push = NULL;
1732 gchar *import = NULL, *keygrip = NULL, *sign_keygrip = NULL;
1733 gchar *keyparam = NULL;
1734 gboolean rcfile_spec = FALSE;
1735 gint estatus = EXIT_FAILURE;
1736 gint sockfd;
1737 gchar *outfile = NULL;
1738 GMemVTable mtable = { xmalloc, xrealloc, xfree, xcalloc, NULL, NULL };
1739 gint do_unlink = 0;
1740 gboolean secure = FALSE;
1741 gint show_version = 0;
1742 gboolean force = FALSE;
1743 gboolean no_passphrase = FALSE;
1744 gpg_error_t rc;
1745 gchar *convertfile = NULL;
1746 gchar *cipher = NULL;
1747 gchar *keyfile = NULL;
1748 glong s2k_count = -1;
1749 guint64 iterations = 0;
1750 GError *error = NULL;
1751 gchar *debug_level_opt = NULL;
1752 GOptionContext *context;
1753 GOptionEntry options[] =
1755 { "version", 0, 0, G_OPTION_ARG_NONE, &show_version,
1756 "version information", NULL },
1757 { "no-fork", 'n', 0, G_OPTION_ARG_NONE, &nofork,
1758 "run as a foreground process", NULL },
1759 { "disable-dump", 'D', 0, G_OPTION_ARG_NONE, &secure,
1760 "disable the LIST, XPATH and DUMP commands", NULL },
1761 { "rcfile", 'f', 0, G_OPTION_ARG_FILENAME, &rcfile,
1762 "load the specified rcfile (~/.pwmd/config)", "filename" },
1763 { "ignore", 0, 0, G_OPTION_ARG_NONE, &force,
1764 "ignore cache failures on startup", NULL },
1765 { "outfile", 'o', 0, G_OPTION_ARG_FILENAME, &outfile,
1766 "output file when importing (- for stdout)", "filename" },
1767 { "convert", 'C', 0, G_OPTION_ARG_FILENAME, &convertfile,
1768 "convert a version 2 data file to version 3", "filename" },
1769 { "passphrase-file", 'k', 0, G_OPTION_ARG_FILENAME, &keyfile,
1770 "for decryption when converting", "filename" },
1771 { "no-passphrase-file", 0, 0, G_OPTION_ARG_NONE, &no_passphrase_file,
1772 "no --passphrase-file after conversion", NULL },
1773 { "import", 'I', 0, G_OPTION_ARG_FILENAME, &import,
1774 "import an XML file", "filename" },
1775 { "keygrip", 0, 0, G_OPTION_ARG_STRING, &keygrip,
1776 "the public keygrip to use for encryption", "hexstring"},
1777 { "sign-keygrip", 0, 0, G_OPTION_ARG_STRING, &sign_keygrip,
1778 "the keygrip to use for signing of the data", "hexstring"},
1779 { "keyparam", 0, 0, G_OPTION_ARG_STRING, &keyparam,
1780 "alternate key parameters to use (RSA-2048)", "s-exp"},
1781 { "no-passphrase", 0, 0, G_OPTION_ARG_NONE, &no_passphrase,
1782 "for the imported/converted keypair", NULL },
1783 { "cipher", 0, 0, G_OPTION_ARG_STRING, &cipher,
1784 "encryption cipher, see man page (aes256)", "string" },
1785 { "s2k-count", 0, 0, G_OPTION_ARG_INT64, &s2k_count,
1786 "hash iteration count >65536 (calibrated)", "iterations" },
1787 { "cipher-iterations", 0, 0, G_OPTION_ARG_INT64, &iterations,
1788 "cipher iteration count (N+1)", "iterations" },
1789 { "debug-level", 0, 0, G_OPTION_ARG_STRING, &debug_level_opt,
1790 "protocol output, see man page", "keywords"},
1791 { "homedir", 'I', 0, G_OPTION_ARG_STRING, &homedir,
1792 "home directory for pwmd", "directory" },
1793 { NULL }
1796 #ifndef DEBUG
1797 #ifdef HAVE_SETRLIMIT
1798 struct rlimit rl;
1800 rl.rlim_cur = rl.rlim_max = 0;
1802 if (setrlimit(RLIMIT_CORE, &rl) != 0)
1803 err(EXIT_FAILURE, "setrlimit()");
1804 #endif
1805 #endif
1807 #ifdef ENABLE_NLS
1808 setlocale(LC_ALL, "");
1809 bindtextdomain("pwmd", LOCALEDIR);
1810 textdomain("pwmd");
1811 #endif
1813 #ifndef MEM_DEBUG
1814 xmem_init();
1815 #endif
1816 g_mem_set_vtable(&mtable);
1817 g_thread_init(NULL);
1818 gpg_err_init();
1820 if (setup_crypto())
1821 exit(EXIT_FAILURE);
1823 #ifdef WITH_GNUTLS
1824 gnutls_global_set_mem_functions(g_malloc, g_malloc, secure_mem_check,
1825 g_realloc, g_free);
1826 gnutls_global_init();
1827 gnutls_global_set_log_function(tls_log);
1828 gnutls_global_set_log_level(1);
1829 tls_fd = -1;
1830 tls6_fd = -1;
1831 #endif
1832 xmlMemSetup(g_free, g_malloc, g_realloc, g_strdup);
1833 xmlInitMemory();
1834 xmlInitGlobals();
1835 xmlInitParser();
1836 xmlXPathInit();
1838 cmdline = TRUE;
1839 context = g_option_context_new("- Password Manager Daemon");
1840 g_option_context_add_main_entries(context, options, NULL);
1841 if (!g_option_context_parse(context, &argc, &argv, &error))
1843 g_print("Option parsing failed: %s\n", error->message);
1844 exit(EXIT_FAILURE);
1847 if (show_version) {
1848 printf(_("%s\n\n"
1849 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012\n"
1850 "%s\n"
1851 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
1852 "Compile time features:\n%s"), PACKAGE_STRING, PACKAGE_BUGREPORT,
1853 #ifdef WITH_GNUTLS
1854 "+WITH_GNUTLS\n"
1855 #else
1856 "-WITH_GNUTLS\n"
1857 #endif
1858 #ifdef WITH_LIBACL
1859 "+WITH_LIBACL\n"
1860 #else
1861 "-WITH_LIBACL\n"
1862 #endif
1863 #ifdef DEBUG
1864 "+DEBUG\n"
1865 #else
1866 "-DEBUG\n"
1867 #endif
1868 #ifdef MEM_DEBUG
1869 "+MEM_DEBUG\n"
1870 #else
1871 "-MEM_DEBUG\n"
1872 #endif
1873 #ifdef MUTEX_DEBUG
1874 "+MUTEX_DEBUG\n"
1875 #else
1876 "-MUTEX_DEBUG\n"
1877 #endif
1879 exit(EXIT_SUCCESS);
1882 if (!homedir)
1883 homedir = g_strdup_printf("%s/.pwmd", g_get_home_dir());
1885 if (mkdir(homedir, 0700) == -1 && errno != EEXIST)
1886 err(EXIT_FAILURE, "%s", homedir);
1888 g_snprintf(buf, sizeof(buf), "%s/data", homedir);
1889 if (mkdir(buf, 0700) == -1 && errno != EEXIST)
1890 err(EXIT_FAILURE, "%s", buf);
1892 datadir = g_strdup(buf);
1893 pthread_mutexattr_t attr;
1894 pthread_mutexattr_init(&attr);
1895 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1896 pthread_mutex_init(&rcfile_mutex, &attr);
1897 pthread_cond_init(&rcfile_cond, NULL);
1898 pthread_mutex_init(&cn_mutex, &attr);
1899 pthread_mutexattr_destroy(&attr);
1900 pthread_key_create(&last_error_key, free_key);
1902 if (!rcfile)
1903 rcfile = g_strdup_printf("%s/config", homedir);
1904 else
1905 rcfile_spec = TRUE;
1907 if ((keyfileh = parse_rcfile(rcfile_spec, cmdline)) == NULL)
1908 exit(EXIT_FAILURE);
1910 if (debug_level_opt)
1911 debug_level = g_strsplit(debug_level_opt, ",", 0);
1913 if (g_key_file_has_key(keyfileh, "global", "syslog", NULL) == TRUE)
1914 log_syslog = g_key_file_get_boolean(keyfileh, "global", "syslog", NULL);
1916 if (log_syslog == TRUE)
1917 openlog("pwmd", LOG_NDELAY|LOG_PID, LOG_DAEMON);
1919 if (g_key_file_has_key(keyfileh, "global", "priority", NULL)) {
1920 x = g_key_file_get_integer(keyfileh, "global", "priority", NULL);
1921 errno = 0;
1923 if (setpriority(PRIO_PROCESS, 0, x) == -1) {
1924 log_write("setpriority(): %s", pwmd_strerror(gpg_error_from_syserror()));
1925 goto do_exit;
1929 #ifdef HAVE_MLOCKALL
1930 if (disable_mlock == FALSE && mlockall(MCL_CURRENT|MCL_FUTURE) == -1) {
1931 log_write("mlockall(): %s", pwmd_strerror(gpg_error_from_syserror()));
1932 goto do_exit;
1934 #endif
1936 rc = cache_init(free_cache_data);
1937 if (rc) {
1938 log_write("pwmd: gpg-agent: %s",
1939 gpg_err_code(rc) == GPG_ERR_UNKNOWN_VERSION
1940 ? _("incompatible version: 2.1.0 or later required")
1941 : pwmd_strerror(rc));
1942 goto do_exit;
1945 if (s2k_count == -1)
1946 s2k_count = get_key_file_ulong(NULL, "s2k_count");
1948 if (convertfile) {
1949 if (!outfile) {
1950 gchar *tmp = g_option_context_get_help(context, TRUE, NULL);
1951 fprintf(stderr, "%s", tmp);
1952 g_free(tmp);
1953 exit(EXIT_FAILURE);
1956 estatus = convert_v2_datafile(convertfile, cipher, keyfile, keygrip,
1957 sign_keygrip, no_passphrase, outfile, keyparam,
1958 (gulong)s2k_count, iterations);
1959 g_key_file_free(keyfileh);
1960 g_free(rcfile);
1961 exit(!estatus);
1964 if (import) {
1965 if (!outfile) {
1966 gchar *tmp = g_option_context_get_help(context, TRUE, NULL);
1967 fprintf(stderr, "%s", tmp);
1968 g_free(tmp);
1969 exit(EXIT_FAILURE);
1972 if (outfile[0] == '-' && outfile[1] == 0)
1973 outfile = NULL;
1975 estatus = xml_import(import, outfile, keygrip, sign_keygrip, keyfile,
1976 no_passphrase, cipher, keyparam, (gulong)s2k_count, iterations);
1977 g_key_file_free(keyfileh);
1978 g_free(rcfile);
1979 exit(!estatus);
1982 g_option_context_free(context);
1983 p = g_key_file_get_string(keyfileh, "global", "socket_path", NULL);
1984 if (!p)
1985 p = g_strdup_printf("%s/socket", homedir);
1987 socketarg = expand_homedir(p);
1988 g_free(p);
1990 if (secure == FALSE && g_key_file_has_key(keyfileh, "global", "disable_list_and_dump", NULL) == TRUE) {
1991 n = g_key_file_get_boolean(keyfileh, "global", "disable_list_and_dump", NULL);
1992 disable_list_and_dump = n;
1994 else
1995 disable_list_and_dump = secure;
1997 setup_logging(keyfileh);
1999 if (g_key_file_has_key(keyfileh, "global", "cache_push", NULL) == TRUE)
2000 cache_push = g_key_file_get_string_list(keyfileh, "global", "cache_push", NULL, NULL);
2002 for (gint n = 1; n < argc; n++) {
2003 if (strv_printf(&cache_push, "%s", argv[n]) == FALSE)
2004 errx(EXIT_FAILURE, "%s", pwmd_strerror(GPG_ERR_ENOMEM));
2007 if (strchr(socketarg, '/') == NULL) {
2008 socketdir = g_get_current_dir();
2009 socketname = g_strdup(socketarg);
2010 socketpath = g_strdup_printf("%s/%s", socketdir, socketname);
2012 else {
2013 socketname = g_strdup(strrchr(socketarg, '/'));
2014 socketname++;
2015 socketarg[strlen(socketarg) - strlen(socketname) -1] = 0;
2016 socketdir = g_strdup(socketarg);
2017 socketpath = g_strdup_printf("%s/%s", socketdir, socketname);
2020 if (chdir(datadir)) {
2021 log_write("%s: %s", datadir, pwmd_strerror(gpg_error_from_syserror()));
2022 unlink(socketpath);
2023 goto do_exit;
2027 * Set the cache entry for a file. Prompts for the password.
2029 if (cache_push) {
2030 struct crypto_s *crypto;
2031 gpg_error_t rc = init_client_crypto(&crypto);
2033 if (rc) {
2034 estatus = EXIT_FAILURE;
2035 goto do_exit;
2038 rc = set_pinentry_options(crypto->agent);
2039 if (rc) {
2040 estatus = EXIT_FAILURE;
2041 goto do_exit;
2044 for (opt = 0; cache_push[opt]; opt++) {
2045 if (!do_cache_push(cache_push[opt], crypto) && !force) {
2046 g_strfreev(cache_push);
2047 startup_failure();
2048 estatus = EXIT_FAILURE;
2049 cleanup_crypto(&crypto);
2050 goto do_exit;
2053 cleanup_crypto_stage1(crypto);
2056 (void)kill_scd(crypto->agent);
2057 cleanup_crypto(&crypto);
2058 g_strfreev(cache_push);
2059 log_write(!nofork ? _("Done. Daemonizing...") : _("Done. Waiting for connections..."));
2062 clear_rcfile_keys();
2065 * bind() doesn't like the full pathname of the socket or any non alphanum
2066 * characters so change to the directory where the socket is wanted then
2067 * create it then change to datadir.
2069 if (chdir(socketdir)) {
2070 log_write("%s: %s", socketdir, pwmd_strerror(gpg_error_from_syserror()));
2071 goto do_exit;
2074 g_free(socketdir);
2076 if ((sockfd = socket(PF_UNIX, SOCK_STREAM, 0)) == -1) {
2077 log_write("socket(): %s", pwmd_strerror(gpg_error_from_syserror()));
2078 goto do_exit;
2081 addr.sun_family = AF_UNIX;
2082 g_snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", socketname);
2084 if (bind(sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr)) == -1) {
2085 log_write("bind(): %s", pwmd_strerror(gpg_error_from_syserror()));
2087 if (errno == EADDRINUSE)
2088 log_write(_("Either there is another pwmd running or '%s' is a \n"
2089 "stale socket. Please remove it manually."), socketpath);
2091 goto do_exit;
2094 do_unlink = 1;
2095 if (g_key_file_has_key(keyfileh, "global", "socket_perms", NULL) == TRUE) {
2096 gchar *t = g_key_file_get_string(keyfileh, "global", "socket_perms", NULL);
2097 mode_t mode = strtol(t, NULL, 8);
2098 mode_t mask = umask(0);
2100 g_free(t);
2102 if (chmod(socketname, mode) == -1) {
2103 log_write("%s: %s", socketname, pwmd_strerror(gpg_error_from_syserror()));
2104 close(sockfd);
2105 unlink(socketpath);
2106 umask(mask);
2107 goto do_exit;
2110 umask(mask);
2113 g_free(--socketname);
2115 if (chdir(datadir)) {
2116 log_write("%s: %s", datadir, pwmd_strerror(gpg_error_from_syserror()));
2117 close(sockfd);
2118 unlink(socketpath);
2119 goto do_exit;
2122 g_free(datadir);
2124 if (listen(sockfd, 0) == -1) {
2125 log_write("listen(): %s", pwmd_strerror(gpg_error_from_syserror()));
2126 goto do_exit;
2129 cmdline = FALSE;
2131 if (!nofork) {
2132 switch (fork()) {
2133 case -1:
2134 log_write("fork(): %s", pwmd_strerror(gpg_error_from_syserror()));
2135 goto do_exit;
2136 case 0:
2137 close(0);
2138 close(1);
2139 close(2);
2140 setsid();
2141 break;
2142 default:
2143 _exit(EXIT_SUCCESS);
2147 pthread_key_create(&thread_name_key, free_key);
2148 pthread_setspecific(thread_name_key, g_strdup("main"));
2149 estatus = server_loop(sockfd, &socketpath);
2151 do_exit:
2152 if (socketpath && do_unlink) {
2153 unlink(socketpath);
2154 g_free(socketpath);
2157 g_free(socketarg);
2158 #ifdef WITH_GNUTLS
2159 gnutls_global_deinit();
2160 #endif
2161 if (keyfileh)
2162 g_key_file_free(keyfileh);
2164 pthread_cancel(rcfile_tid);
2165 pthread_join(rcfile_tid, NULL);
2166 pthread_cond_destroy(&rcfile_cond);
2167 pthread_mutex_destroy(&rcfile_mutex);
2168 g_free(rcfile);
2169 xmlCleanupParser();
2170 xmlCleanupGlobals();
2172 if (estatus == EXIT_SUCCESS)
2173 log_write(_("pwmd exiting normally"));
2175 #if defined(DEBUG) && !defined(MEM_DEBUG)
2176 xdump();
2177 #endif
2178 exit(estatus);