Require automake 2.60.
[pwmd.git] / src / pwmd.c
blob9367910799ab47543332f579b1a6db460b3f4940
1 /* vim:tw=78:ts=8:sw=4:set ft=c: */
2 /*
3 Copyright (C) 2006-2009 Ben Kibbey <bjk@luxsci.net>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02110-1301 USA
19 #ifdef HAVE_CONFIG_H
20 #include <config.h>
21 #endif
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <unistd.h>
26 #include <err.h>
27 #include <errno.h>
28 #include <ctype.h>
29 #include <string.h>
30 #include <sys/un.h>
31 #include <signal.h>
32 #include <stdarg.h>
33 #include <string.h>
34 #include <sys/wait.h>
35 #include <fcntl.h>
36 #include <pwd.h>
37 #include <glib.h>
38 #include <glib/gprintf.h>
39 #include <sys/mman.h>
40 #include <termios.h>
41 #include <assert.h>
42 #include <syslog.h>
43 #include <zlib.h>
44 #include <gcrypt.h>
45 #include <netinet/in.h>
46 #include <arpa/inet.h>
47 #include <netdb.h>
48 #include <sys/time.h>
49 #include <sys/resource.h>
51 #ifdef TM_IN_SYS_TIME
52 #include <sys/time.h>
53 #else
54 #include <time.h>
55 #endif
57 #include "mem.h"
58 #include "xml.h"
59 #include "common.h"
61 #ifdef WITH_PINENTRY
62 #include "pinentry.h"
63 #endif
65 #include "commands.h"
66 #include "pwmd_error.h"
67 #include "cache.h"
68 #include "misc.h"
69 #include "pwmd.h"
70 #include "lock.h"
72 GCRY_THREAD_OPTION_PTH_IMPL;
74 static void clear_rcfile_keys()
76 gsize n;
77 gchar **groups;
78 gchar **p;
80 groups = g_key_file_get_groups(keyfileh, &n);
82 for (p = groups; *p; p++) {
83 GError *rc = NULL;
85 if (g_key_file_has_key(keyfileh, *p, "key", &rc) == TRUE)
86 g_key_file_set_string(keyfileh, *p, "key", "");
89 g_strfreev(groups);
92 static void *reload_rcfile_thread(void *arg)
94 gboolean b = disable_list_and_dump;
95 GKeyFile *k;
96 pth_attr_t attr = pth_attr_of(pth_self());
98 pth_attr_set(attr, PTH_ATTR_NAME, __FUNCTION__);
99 pth_attr_destroy(attr);
100 MUTEX_LOCK(&rcfile_mutex);
101 log_write(N_("reloading configuration file '%s'"), rcfile);
102 k = parse_rcfile(FALSE);
104 if (!k)
105 goto done;
107 g_key_file_free(keyfileh);
108 keyfileh = k;
109 parse_rcfile_keys();
110 clear_rcfile_keys();
111 disable_list_and_dump = b;
112 startStopKeepAlive(FALSE);
113 send_status_all(STATUS_CONFIG);
114 done:
115 MUTEX_UNLOCK(&rcfile_mutex);
116 return NULL;
119 static void reload_rcfile()
121 pth_t tid;
122 pth_attr_t attr = pth_attr_new();
123 gint n;
125 pth_attr_init(attr);
126 pth_attr_set(attr, PTH_ATTR_JOINABLE, 0);
127 tid = pth_spawn(attr, reload_rcfile_thread, NULL);
128 n = errno;
129 pth_attr_destroy(attr);
131 if (!tid)
132 log_write("%s(%i): pth_spawn(): %s", __FILE__, __LINE__,
133 _gpg_strerror(gpg_error_from_errno(n)));
136 gpg_error_t send_syserror(assuan_context_t ctx, gint e)
138 gpg_error_t n = gpg_error_from_errno(e);
140 pth_cancel_point();
141 return assuan_process_done(ctx, assuan_set_error(ctx, n, _gpg_strerror(n)));
144 gpg_error_t send_error(assuan_context_t ctx, gpg_error_t e)
146 gpg_err_code_t n = gpg_err_code(e);
147 gpg_error_t code = gpg_err_make(PWMD_ERR_SOURCE, n);
148 struct client_s *client = assuan_get_pointer(ctx);
150 pth_cancel_point();
152 if (!e)
153 return assuan_process_done(ctx, 0);
155 if (!ctx) {
156 log_write("%s", pwmd_strerror(e));
157 return e;
160 if (n == EPWMD_LIBXML_ERROR) {
161 xmlErrorPtr xe = client->xml_error;
163 if (!xe)
164 xe = xmlGetLastError();
166 e = assuan_process_done(ctx, assuan_set_error(ctx, code, xe->message));
167 log_write("%s", xe->message);
169 if (xe == client->xml_error)
170 xmlResetError(xe);
171 else
172 xmlResetLastError();
174 client->xml_error = NULL;
175 return e;
178 return assuan_process_done(ctx, assuan_set_error(ctx, code, pwmd_strerror(e)));
181 void log_write(const gchar *fmt, ...)
183 gchar *args, *line;
184 va_list ap;
185 struct tm *tm;
186 time_t now;
187 gchar tbuf[21];
188 gint fd = -1;
189 gchar *name;
190 gchar buf[255];
191 pth_t tid = pth_self();
192 pth_attr_t attr;
194 if ((!logfile && !isatty(STDERR_FILENO) && log_syslog == FALSE) || !fmt)
195 return;
197 if (!cmdline && logfile) {
198 if ((fd = open(logfile, O_WRONLY|O_CREAT|O_APPEND, 0600)) == -1) {
199 warn("%s", logfile);
200 return;
204 va_start(ap, fmt);
206 if (g_vasprintf(&args, fmt, ap) == -1) {
207 if (logfile)
208 close(fd);
210 va_end(ap);
211 return;
214 va_end(ap);
216 if (cmdline) {
217 fprintf(stderr, "%s\n", args);
218 fflush(stderr);
219 g_free(args);
220 return;
223 attr = pth_attr_of(tid);
225 if (pth_attr_get(attr, PTH_ATTR_NAME, &name) == FALSE)
226 name = "unknown";
228 pth_attr_destroy(attr);
229 name = print_fmt(buf, sizeof(buf), "%s(%p): ", name, tid);
231 if (!cmdline && log_syslog == TRUE)
232 syslog(LOG_INFO, "%s%s", name, args);
234 time(&now);
235 tm = localtime(&now);
236 strftime(tbuf, sizeof(tbuf), "%b %d %Y %H:%M:%S ", tm);
237 tbuf[sizeof(tbuf) - 1] = 0;
239 if (args[strlen(args)-1] == '\n')
240 args[strlen(args)-1] = 0;
242 line = g_strdup_printf("%s %i %s%s\n", tbuf, getpid(), name, args);
243 g_free(args);
245 if (!line) {
246 if (logfile)
247 close(fd);
249 return;
252 if (logfile) {
253 write(fd, line, strlen(line));
254 fsync(fd);
255 close(fd);
258 if (isatty(STDERR_FILENO)) {
259 fprintf(stderr, "%s", line);
260 fflush(stderr);
263 g_free(line);
266 static void usage(gchar *pn)
268 g_fprintf(stderr, N_(
269 "Usage: %s [-hvDnP] [-f <rcfile>] [-C <filename>] "
270 "[-I <filename> [-i <iter>]]\n "
271 "[-k <keyfile>] [-o <outfile>] [file1] [...]\n"
272 " -n run as a foreground process\n"
273 " -f load the specified rcfile (~/.pwmd/config)\n"
274 " -C convert a version 1 data file to version 2\n"
275 " -I import an XML file\n"
276 " -i encrypt with the specified number of iterations when importing\n"
277 " (config default in the \"global\" section)\n"
278 " -k obtain the key from the specified file\n"
279 " -o output file for use with the -C and -I options\n"
280 " -D disable use of the LIST and DUMP commands\n"
281 " -P disable pinentry\n"
282 " -v version\n"
283 " -h this help text\n"
284 ), pn);
285 exit(EXIT_FAILURE);
288 static int gcry_SecureCheck(const void *ptr)
290 return 1;
293 static void setup_gcrypt()
295 gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pth);
296 gcry_check_version(GCRYPT_VERSION);
298 gcry_set_allocation_handler(xmalloc, xmalloc, gcry_SecureCheck, xrealloc,
299 xfree);
301 if (gcry_cipher_algo_info(GCRY_CIPHER_AES256, GCRYCTL_TEST_ALGO, NULL,
302 NULL) != 0)
303 errx(EXIT_FAILURE, N_("Required AES cipher not supported by libgcrypt."));
305 gcry_cipher_algo_info(GCRY_CIPHER_AES256, GCRYCTL_GET_KEYLEN, NULL, &gcrykeysize);
306 gcry_cipher_algo_info(GCRY_CIPHER_AES256, GCRYCTL_GET_BLKLEN, NULL, &gcryblocksize);
309 static gint new_connection(struct client_s *cl)
311 gpg_error_t rc;
312 gchar *ver;
314 rc = assuan_init_socket_server_ext(&cl->ctx, cl->thd->fd, 2);
316 if (rc)
317 goto fail;
319 assuan_set_pointer(cl->ctx, cl);
320 ver = g_strdup_printf("%s", PACKAGE_STRING);
321 assuan_set_hello_line(cl->ctx, ver);
322 g_free(ver);
323 rc = register_commands(cl->ctx);
325 if (rc)
326 goto fail;
328 rc = assuan_accept(cl->ctx);
330 if (rc)
331 goto fail;
333 return 0;
335 fail:
336 log_write("%s", _gpg_strerror(rc));
337 close(cl->thd->fd);
338 cl->thd->fd = -1;
339 return 1;
342 static void xml_error_cb(void *data, xmlErrorPtr e)
344 struct client_s *client = data;
347 * Keep the first reported error as the one to show in the error
348 * description. Reset in send_error().
350 if (client->xml_error)
351 return;
353 xmlCopyError(e, client->xml_error);
356 void cleanup_crypto(struct client_crypto_s **c)
358 struct client_crypto_s *cr = *c;
360 if (!cr)
361 return;
363 if (cr->iv)
364 gcry_free(cr->iv);
366 if (cr->key)
367 gcry_free(cr->key);
369 if (cr->tkey)
370 gcry_free(cr->tkey);
372 if (cr->tkey2)
373 gcry_free(cr->tkey2);
375 if (cr->inbuf)
376 gcry_free(cr->inbuf);
378 if (cr->outbuf)
379 gcry_free(cr->outbuf);
381 if (cr->fh) {
382 if (cr->fh->fd != -1 ||
383 (cmdline == TRUE && cr->fh->fd != STDOUT_FILENO))
384 close(cr->fh->fd);
386 if (cr->fh->doc)
387 gcry_free(cr->fh->doc);
389 g_free(cr->fh);
392 if (cr->gh)
393 gcry_cipher_close(cr->gh);
395 g_free(cr);
396 *c = NULL;
400 * This is called after a child_thread terminates. Set with
401 * pth_cleanup_push().
403 static void cleanup_cb(void *arg)
405 struct client_thread_s *cn = arg;
406 struct client_s *cl = cn->cl;
408 MUTEX_LOCK(&cn_mutex);
409 cn_thread_list = g_slist_remove(cn_thread_list, cn);
410 MUTEX_UNLOCK(&cn_mutex);
412 if (cn->msg_tid) {
413 pth_cancel(cn->msg_tid);
414 pth_join(cn->msg_tid, NULL);
417 for (;;) {
418 struct status_msg_s *m = g_slist_nth_data(cn->msg_list, 0);
420 if (!m)
421 break;
423 cn->msg_list = g_slist_remove(cn->msg_list, m);
424 g_free(m);
427 if (cl && cl->freed == FALSE)
428 cleanup_client(cl);
430 if (cl && cl->ctx)
431 assuan_deinit_server(cl->ctx);
432 else if (cl && cl->thd && cl->thd->fd != -1)
433 close(cl->thd->fd);
435 #ifdef WITH_PINENTRY
436 if (cl && cl->pinentry)
437 cleanup_pinentry(cl->pinentry);
438 #endif
440 if (cl->crypto)
441 cleanup_crypto(&cl->crypto);
443 g_free(cl);
444 log_write(N_("exiting, fd=%i"), cn->fd);
445 g_free(cn);
446 send_status_all(STATUS_CLIENTS);
450 * Called every time a connection is made from init_new_connection(). This is
451 * the thread entry point.
453 static void *client_thread(void *data)
455 struct client_thread_s *thd = data;
456 struct client_s *cl = g_malloc0(sizeof(struct client_s));
457 gpg_error_t rc;
458 pth_attr_t attr;
459 gint n;
462 * Prevent a race condition with init_new_connection() if this thread
463 * fails (returns) for some reason before init_new_connection() releases
464 * the cn_mutex.
466 MUTEX_LOCK(&cn_mutex);
467 MUTEX_UNLOCK(&cn_mutex);
468 pth_cleanup_push(cleanup_cb, thd);
470 if (!cl) {
471 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
472 goto fail;
475 attr = pth_attr_of(pth_self());
476 pth_attr_set(attr, PTH_ATTR_NAME, __FUNCTION__);
477 pth_attr_destroy(attr);
478 thd->cl = cl;
479 cl->thd = thd;
481 if (new_connection(cl))
482 goto fail;
484 #ifdef WITH_PINENTRY
485 cl->pinentry = pinentry_init();
487 if (!cl->pinentry) {
488 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
489 goto fail;
491 #endif
493 #ifdef HAVE_MLOCKALL
494 if (disable_mlock == FALSE && mlockall(MCL_FUTURE) == -1) {
495 log_write("mlockall(): %s", strerror(errno));
496 goto fail;
498 #endif
500 pth_mutex_init(&thd->msg_list_mutex);
501 attr = pth_attr_new();
502 pth_attr_init(attr);
503 pth_attr_set(attr, PTH_ATTR_JOINABLE, TRUE);
504 thd->msg_tid = pth_spawn(attr, client_msg_thread, thd);
505 n = errno;
506 pth_attr_destroy(attr);
508 if (!thd->msg_tid) {
509 log_write("%s(%i): pth_spawn(): %s", __FILE__, __LINE__,
510 _gpg_strerror(gpg_error_from_errno(n)));
511 goto fail;
514 pth_yield(thd->msg_tid);
515 rc = send_status(cl->ctx, STATUS_CACHE, NULL);
517 if (rc) {
518 log_write("%s", _gpg_strerror(rc));
519 goto fail;
522 send_status_all(STATUS_CLIENTS);
523 xmlSetStructuredErrorFunc(cl, xml_error_cb);
525 for (;;) {
526 #ifdef WITH_PINENTRY
527 pth_event_t pev = NULL;
528 #endif
529 pth_status_t st;
530 pth_event_t ev = pth_event(PTH_EVENT_FD|PTH_UNTIL_FD_READABLE,
531 cl->thd->fd);
533 #ifdef WITH_PINENTRY
534 if (cl->pinentry->status == PINENTRY_RUNNING) {
535 pev = pth_event(PTH_EVENT_FD|PTH_UNTIL_FD_READABLE, cl->pinentry->fd);
536 ev = pth_event_concat(ev, pev, NULL);
538 #endif
540 pth_wait(ev);
541 pth_event_isolate(ev);
542 st = pth_event_status(ev);
544 if (st == PTH_STATUS_OCCURRED) {
545 rc = assuan_process_next(cl->ctx);
546 pth_cancel_point();
548 if (rc) {
549 cl->inquire_status = INQUIRE_INIT;
551 if (gpg_err_code(rc) == GPG_ERR_EOF)
552 goto done;
554 log_write("assuan_process_next(): %s", _gpg_strerror(rc));
555 rc = send_error(cl->ctx, gpg_err_make(PWMD_ERR_SOURCE, rc));
557 if (rc) {
558 log_write("assuan_process_done(): %s", _gpg_strerror(rc));
559 goto done;
562 else {
563 #ifdef WITH_PINENTRY
564 if (cl->pinentry->pid && cl->pinentry->status == PINENTRY_INIT)
565 cl->pinentry->status = PINENTRY_RUNNING;
566 #endif
568 switch (cl->inquire_status) {
569 case INQUIRE_BUSY:
570 case INQUIRE_INIT:
571 break;
572 case INQUIRE_DONE:
573 cl->inquire_status = INQUIRE_INIT;
574 rc = assuan_process_done(cl->ctx, 0);
575 pth_cancel_point();
576 break;
581 pth_event_free(ev, PTH_FREE_THIS);
583 #ifdef WITH_PINENTRY
584 if (pev) {
585 pth_event_isolate(pev);
586 st = pth_event_status(pev);
587 pth_event_free(pev, PTH_FREE_THIS);
590 rc = pinentry_iterate(cl,
591 pev && cl->pinentry->fd != -1 && st == PTH_STATUS_OCCURRED);
592 #endif
596 * Client cleanup (including XML data) is done in cleanup_cb() from
597 * the cleanup thread.
599 done:
600 fail:
601 pth_cleanup_pop(1);
602 pth_exit(PTH_CANCELED);
603 return NULL;
606 static void setup_logging(GKeyFile *kf)
608 gboolean n = g_key_file_get_boolean(kf, "global", "enable_logging", NULL);
610 if (n == TRUE) {
611 gchar *p = g_key_file_get_string(kf, "global", "log_path", NULL);
613 if (*p == '~') {
614 gchar buf[PATH_MAX];
616 p++;
617 g_snprintf(buf, sizeof(buf), "%s%s", g_get_home_dir(), p--);
618 g_free(p);
620 if (logfile)
621 g_free(logfile);
623 logfile = g_strdup(buf);
625 else {
626 if (logfile)
627 g_free(logfile);
629 logfile = p;
633 log_syslog = g_key_file_get_boolean(kf, "global", "syslog", NULL);
637 * Make sure all settings are set to either the specified setting or a
638 * default.
640 static void set_rcfile_defaults(GKeyFile *kf)
642 gchar buf[PATH_MAX];
644 if (g_key_file_has_key(kf, "global", "socket_path", NULL) == FALSE) {
645 g_snprintf(buf, sizeof(buf), "~/.pwmd/socket");
646 g_key_file_set_string(kf, "global", "socket_path", buf);
649 if (g_key_file_has_key(kf, "global", "data_directory", NULL) == FALSE) {
650 g_snprintf(buf, sizeof(buf), "~/.pwmd/data");
651 g_key_file_set_string(kf, "global", "data_directory", buf);
654 if (g_key_file_has_key(kf, "global", "backup", NULL) == FALSE)
655 g_key_file_set_boolean(kf, "global", "backup", TRUE);
657 if (g_key_file_has_key(kf, "global", "log_path", NULL) == FALSE) {
658 g_snprintf(buf, sizeof(buf), "~/.pwmd/log");
659 g_key_file_set_string(kf, "global", "log_path", buf);
662 if (g_key_file_has_key(kf, "global", "enable_logging", NULL) == FALSE)
663 g_key_file_set_boolean(kf, "global", "enable_logging", FALSE);
665 #ifdef HAVE_MLOCKALL
666 if (g_key_file_has_key(kf, "global", "disable_mlockall", NULL) == FALSE)
667 g_key_file_set_boolean(kf, "global", "disable_mlockall", TRUE);
668 #endif
670 if (g_key_file_has_key(kf, "global", "cache_timeout", NULL) == FALSE)
671 g_key_file_set_integer(kf, "global", "cache_timeout", -1);
673 if (g_key_file_has_key(kf, "global", "iterations", NULL) == FALSE ||
674 g_key_file_get_integer(kf, "global", "iterations", 0) < 0)
675 g_key_file_set_integer(kf, "global", "iterations", 1);
677 if (g_key_file_has_key(kf, "global", "disable_list_and_dump", NULL) == FALSE)
678 g_key_file_set_boolean(kf, "global", "disable_list_and_dump", FALSE);
680 if (g_key_file_has_key(kf, "global", "iteration_progress", NULL) == FALSE)
681 g_key_file_set_integer(kf, "global", "iteration_progress", 0);
683 if (g_key_file_has_key(kf, "global", "compression_level", NULL) == FALSE)
684 g_key_file_set_integer(kf, "global", "compression_level", 6);
686 if (g_key_file_has_key(kf, "global", "recursion_depth", NULL) == FALSE)
687 g_key_file_set_integer(kf, "global", "recursion_depth", DEFAULT_RECURSION_DEPTH);
689 if (g_key_file_has_key(kf, "global", "zlib_bufsize", NULL) == FALSE)
690 g_key_file_set_integer(kf, "global", "zlib_bufsize", DEFAULT_ZLIB_BUFSIZE);
692 zlib_bufsize = (uInt)g_key_file_get_integer(kf, "global", "zlib_bufsize", NULL);
694 max_recursion_depth = g_key_file_get_integer(kf, "global", "recursion_depth", NULL);
695 disable_list_and_dump = g_key_file_get_boolean(kf, "global", "disable_list_and_dump", NULL);
697 #ifdef HAVE_MLOCKALL
698 disable_mlock = g_key_file_get_boolean(kf, "global", "disable_mlockall", NULL);
699 #endif
701 if (g_key_file_has_key(kf, "global", "syslog", NULL) == FALSE)
702 g_key_file_set_boolean(kf, "global", "syslog", FALSE);
704 if (g_key_file_has_key(kf, "global", "keepalive", NULL) == FALSE)
705 g_key_file_set_integer(kf, "global", "keepalive", DEFAULT_KEEPALIVE_TO);
707 #ifdef WITH_PINENTRY
708 if (g_key_file_has_key(kf, "global", "enable_pinentry", NULL) == FALSE)
709 g_key_file_set_boolean(kf, "global", "enable_pinentry", TRUE);
711 if (g_key_file_has_key(kf, "global", "pinentry_timeout", NULL) == FALSE)
712 g_key_file_set_integer(kf, "global", "pinentry_timeout", 20);
713 #endif
715 setup_logging(kf);
718 static GKeyFile *parse_rcfile(gboolean specified)
720 GKeyFile *kf = g_key_file_new();
721 GError *rc = NULL;
723 if (g_key_file_load_from_file(kf, rcfile, G_KEY_FILE_NONE, &rc) == FALSE) {
724 log_write("%s: %s", rcfile, rc->message);
726 if (cmdline && specified) {
727 g_clear_error(&rc);
728 return NULL;
731 if (rc->code == G_FILE_ERROR_NOENT) {
732 g_clear_error(&rc);
733 set_rcfile_defaults(kf);
734 return kf;
737 g_clear_error(&rc);
738 return NULL;
741 set_rcfile_defaults(kf);
742 return kf;
745 static gchar *do_get_password(const gchar *prompt)
747 gchar buf[LINE_MAX] = {0}, *p;
748 struct termios told, tnew;
749 gchar *key;
751 if (tcgetattr(STDIN_FILENO, &told) == -1) {
752 log_write("tcgetattr(): %s", strerror(errno));
753 return NULL;
756 memcpy(&tnew, &told, sizeof(struct termios));
757 tnew.c_lflag &= ~(ECHO);
758 tnew.c_lflag |= ICANON|ECHONL;
760 if (tcsetattr(STDIN_FILENO, TCSANOW, &tnew) == -1) {
761 log_write("tcsetattr(): %s", strerror(errno));
762 tcsetattr(STDIN_FILENO, TCSANOW, &told);
763 return NULL;
766 fprintf(stderr, "%s", prompt);
768 if ((p = fgets(buf, sizeof(buf), stdin)) == NULL) {
769 tcsetattr(STDIN_FILENO, TCSANOW, &told);
770 return NULL;
773 tcsetattr(STDIN_FILENO, TCSANOW, &told);
774 p[strlen(p) - 1] = 0;
776 if (!buf[0]) {
777 key = gcry_malloc(1);
778 key[0] = 0;
780 else {
781 key = gcry_malloc(strlen(p) + 1);
782 sprintf(key, "%s", p);
785 memset(&buf, 0, sizeof(buf));
786 return key;
789 /* Only used when "enable_pinentry" is "false" or -P. */
790 static gpg_error_t get_input(const gchar *filename,
791 struct client_crypto_s *crypto, guchar *key, pinentry_cmd_t which)
793 gchar *prompt;
795 if (which == PINENTRY_SAVE) {
796 prompt = g_strdup_printf(N_("New passphrase for file %s: "), filename);
797 crypto->tkey = do_get_password(prompt);
798 g_free(prompt);
800 if (!crypto->tkey) {
801 log_write(N_("%s: Skipping file"), filename);
802 return GPG_ERR_BAD_PASSPHRASE;
805 prompt = g_strdup_printf(N_("Repeat passphrase: "));
806 crypto->tkey2 = do_get_password(prompt);
807 g_free(prompt);
809 if (!crypto->tkey2) {
810 log_write(N_("%s: Skipping file"), filename);
811 return GPG_ERR_BAD_PASSPHRASE;
814 if (strcmp(crypto->tkey, crypto->tkey2)) {
815 log_write(N_("%s: Passphrase mismatch"), filename);
816 return EPWMD_BADKEY;
819 gcry_md_hash_buffer(GCRY_MD_SHA256, key, crypto->tkey,
820 strlen(crypto->tkey) ? strlen(crypto->tkey) : 1);
821 return 0;
824 prompt = g_strdup_printf(N_("Passphrase required for %s: "), filename);
826 if ((crypto->tkey = do_get_password(prompt)) == NULL) {
827 log_write(N_("%s: Skipping file"), filename);
828 g_free(prompt);
829 return GPG_ERR_BAD_PASSPHRASE;
832 gcry_md_hash_buffer(GCRY_MD_SHA256, key, crypto->tkey,
833 strlen(crypto->tkey) ? strlen(crypto->tkey) : 1);
834 g_free(prompt);
835 return 0;
839 * inbuf must have been allocated with gcry_malloc().
841 gpg_error_t export_common(const gchar *filename, struct client_crypto_s *crypto,
842 gpointer inbuf, gulong insize)
844 gpg_error_t rc;
845 gint level, zrc;
846 gulong outsize;
847 gpointer outbuf;
849 level = get_key_file_integer(filename, "compression_level");
851 if (level < 0)
852 level = 0;
854 if (do_compress(NULL, level, inbuf, insize, &outbuf, &outsize, &zrc)
855 == FALSE) {
856 return zrc == Z_MEM_ERROR ? GPG_ERR_ENOMEM : GPG_ERR_COMPR_ALGO;
859 crypto->inbuf = outbuf;
860 crypto->insize = outsize;
861 rc = do_xml_encrypt(NULL, crypto, filename);
862 return rc;
865 static gpg_error_t get_password(const gchar *filename,
866 struct client_crypto_s *crypto, guchar *md5file, guchar *key,
867 pinentry_cmd_t which)
869 #ifdef WITH_PINENTRY
870 gpg_error_t rc = 0;
872 if (g_key_file_get_boolean(keyfileh, "global", "enable_pinentry", NULL)
873 == FALSE) {
874 #endif
875 return get_input(filename, crypto, key, which);
876 #ifdef WITH_PINENTRY
878 else {
879 gchar *result = NULL;
880 struct pinentry_s *pin = g_malloc0(sizeof(struct pinentry_s));
882 set_pinentry_defaults(pin);
883 pin->which = which;
884 pin->filename = g_strdup(filename);
885 rc = pinentry_getpin(pin, &result);
887 if (rc) {
888 xfree(result);
889 goto done;
892 gcry_md_hash_buffer(GCRY_MD_SHA256, key, result, strlen(result) ? strlen(result) : 1);
893 xfree(result);
894 cleanup_pinentry(pin);
897 done:
898 return rc;
899 #endif
902 static gboolean _getline(const gchar *file, gchar **result, gpg_error_t *rc)
904 FILE *fp;
905 gchar buf[LINE_MAX] = {0}, *p;
906 gchar *str = NULL;
907 gint len;
909 *rc = 0;
911 if ((fp = fopen(file, "r")) == NULL) {
912 *rc = gpg_error_from_syserror();
913 return FALSE;
916 p = fgets(buf, sizeof(buf), fp);
917 fclose(fp);
918 len = strlen(buf);
920 if (len && buf[len - 1] == '\n')
921 buf[--len] = 0;
923 str = gcry_malloc(len + 1);
925 if (!str) {
926 *rc = gpg_error_from_errno(ENOMEM);
927 return FALSE;
930 memcpy(str, buf, len ? len : 1);
931 str[len] = 0;
932 memset(&buf, 0, sizeof(buf));
933 *result = str;
934 return TRUE;
937 static gchar *parse_rcfile_keyfile(const gchar *filename, gboolean import,
938 gpg_error_t *rc)
940 GError *rv = NULL;
941 gchar *t, *file = NULL, *str;
943 *rc = GPG_ERR_UNKNOWN_ERRNO;
945 if (import == FALSE) {
946 if (g_key_file_has_key(keyfileh, filename, "key_file", &rv) == TRUE) {
947 file = g_key_file_get_string(keyfileh, filename, "key_file", &rv);
949 if (!file) {
950 if (rv) {
951 log_write("%s: key_file: %s", rcfile, rv->message);
952 g_clear_error(&rv);
955 return NULL;
958 t = expand_homedir(file);
960 if (!t) {
961 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
962 *rc = gpg_error_from_errno(ENOMEM);
963 return NULL;
966 g_free(file);
967 file = t;
970 else {
971 /* -I or -C. The filename is a key file. */
972 file = g_strdup(filename);
974 if (!file) {
975 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
976 *rc = gpg_error_from_errno(ENOMEM);
977 return NULL;
981 if (rv) {
982 log_write("%s: key_file: %s", rcfile, rv->message);
983 g_clear_error(&rv);
984 return NULL;
987 if (!file)
988 return NULL;
990 if (_getline(file, &str, rc) == FALSE) {
991 log_write("%s: %s: %s", filename, file, pwmd_strerror(*rc));
992 g_free(file);
993 return NULL;
996 g_free(file);
997 *rc = 0;
998 return str;
1001 static gboolean xml_import(const gchar *filename, const gchar *outfile,
1002 const gchar *keyfile, guint64 iter)
1004 xmlDocPtr doc;
1005 gint fd;
1006 struct stat st;
1007 gint len;
1008 xmlChar *xmlbuf;
1009 xmlChar *xml;
1010 gpg_error_t rc;
1011 struct client_crypto_s *crypto;
1013 if (stat(filename, &st) == -1) {
1014 log_write("%s: %s", filename, strerror(errno));
1015 return FALSE;
1018 crypto = init_client_crypto();
1020 if (!crypto)
1021 return FALSE;
1023 crypto->key = gcry_malloc(gcrykeysize);
1024 memset(crypto->key, 0, gcrykeysize);
1026 if (!crypto->key) {
1027 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1028 goto fail;
1031 log_write(N_("Importing XML from '%s'. Output will be written to '%s' ..."),
1032 filename, outfile);
1034 if (iter && keyfile) {
1035 crypto->tkey = parse_rcfile_keyfile(keyfile, TRUE, &rc);
1037 if (!crypto->tkey)
1038 goto fail;
1040 gcry_md_hash_buffer(GCRY_MD_SHA256, crypto->key, crypto->tkey,
1041 strlen(crypto->tkey) ? strlen(crypto->tkey) : 1);
1043 else if (iter) {
1044 rc = get_password(outfile, crypto, NULL, crypto->key, PINENTRY_SAVE);
1046 if (rc)
1047 goto fail;
1050 if ((fd = open(filename, O_RDONLY)) == -1) {
1051 log_write("%s: %s", filename, strerror(errno));
1052 goto fail;
1055 if ((xmlbuf = gcry_malloc(st.st_size+1)) == NULL) {
1056 close(fd);
1057 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1058 goto fail;
1061 if (pth_read(fd, xmlbuf, st.st_size) == -1) {
1062 rc = errno;
1063 close(fd);
1064 errno = rc;
1065 log_write("%s: %s", filename, strerror(errno));
1066 goto fail;
1069 close(fd);
1070 xmlbuf[st.st_size] = 0;
1073 * Make sure the document validates.
1075 if ((doc = xmlReadDoc(xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS)) == NULL) {
1076 log_write("xmlReadDoc() failed");
1077 gcry_free(xmlbuf);
1078 goto fail;
1081 gcry_free(xmlbuf);
1082 xmlDocDumpMemory(doc, &xml, &len);
1083 xmlFreeDoc(doc);
1085 if (!iter)
1086 memset(crypto->key, '!', gcrykeysize);
1088 crypto->fh = g_malloc0(sizeof(file_header_internal_t));
1090 if (!crypto->fh) {
1091 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1092 goto fail;
1095 crypto->fh->fh2.iter = iter;
1096 rc = export_common(outfile, crypto, xml, len);
1097 xmlFree(xml);
1099 if (rc) {
1100 send_error(NULL, rc);
1101 goto fail;
1104 cleanup_crypto(&crypto);
1105 return TRUE;
1107 fail:
1108 cleanup_crypto(&crypto);
1109 return FALSE;
1112 gchar *get_key_file_string(const gchar *section, const gchar *what)
1114 gchar *val = NULL;
1115 GError *grc = NULL;
1117 MUTEX_LOCK(&rcfile_mutex);
1119 if (g_key_file_has_key(keyfileh, section, what, NULL) == TRUE) {
1120 val = g_key_file_get_string(keyfileh, section, what, &grc);
1122 if (grc) {
1123 log_write("%s(%i): %s", __FILE__, __LINE__, grc->message);
1124 g_clear_error(&grc);
1127 else {
1128 if (g_key_file_has_key(keyfileh, "global", what, NULL) == TRUE) {
1129 val = g_key_file_get_string(keyfileh, "global", what, &grc);
1131 if (grc) {
1132 log_write("%s(%i): %s", __FILE__, __LINE__, grc->message);
1133 g_clear_error(&grc);
1138 MUTEX_UNLOCK(&rcfile_mutex);
1139 return val;
1142 gint get_key_file_integer(const gchar *section, const gchar *what)
1144 gint val = -1;
1145 GError *grc = NULL;
1147 MUTEX_LOCK(&rcfile_mutex);
1149 if (g_key_file_has_key(keyfileh, section ? section : "global", what, NULL) == TRUE) {
1150 val = g_key_file_get_integer(keyfileh, section ? section : "global", what, &grc);
1152 if (grc) {
1153 log_write("%s(%i): %s", __FILE__, __LINE__, grc->message);
1154 g_clear_error(&grc);
1157 else {
1158 if (g_key_file_has_key(keyfileh, "global", what, NULL) == TRUE) {
1159 val = g_key_file_get_integer(keyfileh, "global", what, &grc);
1161 if (grc) {
1162 log_write("%s(%i): %s", __FILE__, __LINE__, grc->message);
1163 g_clear_error(&grc);
1168 MUTEX_UNLOCK(&rcfile_mutex);
1169 return val;
1172 gboolean get_key_file_boolean(const gchar *section, const gchar *what)
1174 gboolean val = FALSE;
1175 GError *grc = NULL;
1177 MUTEX_LOCK(&rcfile_mutex);
1179 if (g_key_file_has_key(keyfileh, section, what, NULL) == TRUE) {
1180 val = g_key_file_get_boolean(keyfileh, section, what, &grc);
1182 if (grc) {
1183 log_write("%s(%i): %s", __FILE__, __LINE__, grc->message);
1184 g_clear_error(&grc);
1187 else {
1188 if (g_key_file_has_key(keyfileh, "global", what, NULL) == TRUE) {
1189 val = g_key_file_get_boolean(keyfileh, "global", what, &grc);
1191 if (grc) {
1192 log_write("%s(%i): %s", __FILE__, __LINE__, grc->message);
1193 g_clear_error(&grc);
1198 MUTEX_UNLOCK(&rcfile_mutex);
1199 return val;
1202 static gboolean parse_rcfile_keys()
1204 gsize n;
1205 gchar **groups;
1206 gchar **p;
1207 gchar *str;
1209 groups = g_key_file_get_groups(keyfileh, &n);
1211 for (p = groups; *p; p++) {
1212 GError *rc = NULL;
1214 if (g_key_file_has_key(keyfileh, *p, "key", &rc) == TRUE) {
1215 str = g_key_file_get_string(keyfileh, *p, "key", &rc);
1217 if (!str) {
1218 if (rc) {
1219 log_write("%s: key: %s", rcfile, rc->message);
1220 g_clear_error(&rc);
1222 continue;
1225 do_cache_push(*p, str);
1226 g_free(str);
1227 continue;
1230 if (rc) {
1231 log_write("%s: key: %s", rcfile, rc->message);
1232 g_clear_error(&rc);
1233 continue;
1236 gpg_error_t ret;
1237 str = parse_rcfile_keyfile(*p, FALSE, &ret);
1239 if (!str)
1240 continue;
1242 do_cache_push(*p, str);
1243 gcry_free(str);
1246 g_strfreev(groups);
1247 return TRUE;
1250 static gboolean do_cache_push(const gchar *filename, const gchar *password)
1252 guchar md5file[16];
1253 gint timeout;
1254 const gchar *p = filename;
1255 struct client_crypto_s *crypto;
1256 gpg_error_t rc;
1258 while (isspace(*p))
1259 p++;
1261 if (!*p)
1262 return FALSE;
1264 if (valid_filename(p) == FALSE) {
1265 log_write(N_("%s: Invalid characters in filename"), p);
1266 return FALSE;
1269 gcry_md_hash_buffer(GCRY_MD_MD5, md5file, p, strlen(p));
1271 if (access(p, R_OK|W_OK) != 0) {
1272 log_write("%s: %s", p, strerror(errno));
1273 return FALSE;
1276 crypto = init_client_crypto();
1278 if (!crypto)
1279 return FALSE;
1281 crypto->fh = read_file_header(filename, FALSE, &rc);
1283 if (!crypto->fh) {
1284 log_write("%s: %s", p, pwmd_strerror(rc));
1285 cleanup_crypto(&crypto);
1286 return FALSE;
1289 crypto->key = gcry_malloc(gcrykeysize);
1291 if (!crypto->key) {
1292 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1293 cleanup_crypto(&crypto);
1294 return FALSE;
1297 log_write(N_("Adding '%s' to the file cache ..."), filename);
1299 if (crypto->fh->fh2.iter <= 0) {
1300 memset(crypto->key, '!', gcrykeysize);
1301 goto try_decrypt;
1304 if (!password) {
1305 rc = get_password(p, crypto, md5file, crypto->key, PINENTRY_OPEN);
1307 if (rc) {
1308 send_error(NULL, rc);
1309 cleanup_crypto(&crypto);
1310 return FALSE;
1313 gcry_free(crypto->fh->doc);
1314 crypto->fh->doc = NULL;
1316 else
1317 gcry_md_hash_buffer(GCRY_MD_SHA256, crypto->key, password,
1318 strlen(password) ? strlen(password) : 1);
1320 try_decrypt:
1321 rc = try_xml_decrypt(NULL, crypto->key, crypto, NULL, NULL);
1323 if (rc) {
1324 log_write("%s: %s", filename, pwmd_strerror(rc));
1325 cleanup_crypto(&crypto);
1326 return FALSE;
1329 if (cache_update_key(md5file, crypto->key) == FALSE) {
1330 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1331 cleanup_crypto(&crypto);
1332 return FALSE;
1335 timeout = get_key_file_integer(p, "cache_timeout");
1336 cache_set_timeout(md5file, timeout);
1337 log_write(N_("File '%s' now cached"), filename);
1338 cleanup_crypto(&crypto);
1339 return TRUE;
1342 static void init_new_connection(gint fd)
1344 pth_attr_t attr;
1345 struct client_thread_s *new;
1346 gint n;
1348 new = g_malloc0(sizeof(struct client_thread_s));
1350 if (!new) {
1351 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1352 close(fd);
1353 return;
1356 MUTEX_LOCK(&cn_mutex);
1357 new->fd = fd;
1358 attr = pth_attr_new();
1359 pth_attr_init(attr);
1360 pth_attr_set(attr, PTH_ATTR_JOINABLE, FALSE);
1361 new->tid = pth_spawn(attr, client_thread, new);
1362 n = errno;
1363 pth_attr_destroy(attr);
1365 if (!new->tid) {
1366 g_free(new);
1367 close(fd);
1368 log_write("%s(%i): pth_spawn(): %s", __FILE__, __LINE__,
1369 _gpg_strerror(gpg_error_from_errno(n)));
1370 MUTEX_UNLOCK(&cn_mutex);
1371 return;
1374 cn_thread_list = g_slist_append(cn_thread_list, new);
1375 MUTEX_UNLOCK(&cn_mutex);
1376 log_write(N_("new connection: tid=%p, fd=%i"), new->tid, fd);
1379 static void *accept_thread(void *arg)
1381 gint sockfd = (gint)arg;
1382 pth_attr_t attr = pth_attr_of(pth_self());
1384 pth_attr_set(attr, PTH_ATTR_NAME, __FUNCTION__);
1385 pth_attr_destroy(attr);
1387 for (;;) {
1388 socklen_t slen = sizeof(struct sockaddr_un);
1389 struct sockaddr_un raddr;
1390 gint fd = -1;
1392 fd = pth_accept(sockfd, (struct sockaddr *)&raddr, &slen);
1393 pth_cancel_point();
1395 if (fd == -1) {
1396 if (errno != EAGAIN) {
1397 if (!quit) // probably EBADF
1398 log_write("accept(): %s", strerror(errno));
1400 break;
1403 continue;
1406 init_new_connection(fd);
1409 /* Just in case accept() failed for some reason other than EBADF */
1410 quit = 1;
1411 pth_exit(PTH_CANCELED);
1412 return NULL;
1415 static void *adjust_cache_timer_thread(void *arg)
1417 pth_attr_t attr = pth_attr_of(pth_self());
1419 pth_attr_set(attr, PTH_ATTR_NAME, __FUNCTION__);
1420 pth_attr_destroy(attr);
1422 for (;;) {
1423 pth_sleep(1);
1424 pth_cancel_point();
1425 CACHE_LOCK(NULL);
1426 cache_adjust_timer();
1427 CACHE_UNLOCK;
1430 return NULL;
1433 static void keepalive_cleanup(void *arg)
1435 pth_event_t ev = arg;
1437 pth_event_free(ev, PTH_FREE_ALL);
1440 static void *keepalive_thread(void *arg)
1442 gint to = (gint)arg;
1443 pth_mutex_t m;
1444 pth_cond_t cond;
1445 pth_attr_t attr = pth_attr_of(pth_self());
1447 pth_attr_set(attr, PTH_ATTR_NAME, __FUNCTION__);
1448 pth_attr_destroy(attr);
1449 pth_cond_init(&cond);
1450 pth_mutex_init(&m);
1451 pth_mutex_acquire(&m, FALSE, NULL);
1453 for (;;) {
1454 pth_event_t ev = pth_event(PTH_EVENT_TIME, pth_timeout(to, 0));
1455 pth_cleanup_push(keepalive_cleanup, ev);
1456 pth_cond_await(&cond, &m, ev);
1457 pth_cancel_point();
1458 send_status_all(STATUS_KEEPALIVE);
1459 pth_cleanup_pop(1);
1462 return NULL;
1465 static void startStopKeepAlive(gboolean term)
1467 gint n = get_key_file_integer("global", "keepalive");
1469 if (keepalive_tid)
1470 pth_cancel(keepalive_tid);
1472 keepalive_tid = NULL;
1474 if (term)
1475 return;
1477 if (n > 0) {
1478 gint e;
1479 pth_attr_t attr = pth_attr_new();
1480 pth_attr_init(attr);
1481 pth_attr_set(attr, PTH_ATTR_JOINABLE, FALSE);
1482 keepalive_tid = pth_spawn(attr, keepalive_thread, (void *)n);
1483 e = errno;
1484 pth_attr_destroy(attr);
1486 if (!keepalive_tid) {
1487 log_write("%s(%i): pth_spawn(): %s", __FILE__, __LINE__,
1488 _gpg_strerror(gpg_error_from_errno(e)));
1489 return;
1492 pth_yield(keepalive_tid);
1496 static gboolean waiting_for_exit()
1498 guint i, t;
1499 pth_event_t evs = NULL;
1501 MUTEX_LOCK(&cn_mutex);
1503 for (t = g_slist_length(cn_thread_list), i = 0; i < t; i++) {
1504 struct client_thread_s *thd = g_slist_nth_data(cn_thread_list, i);
1505 pth_event_t ev = pth_event(PTH_EVENT_TID|PTH_UNTIL_TID_DEAD, thd->tid);
1507 if (evs)
1508 evs = pth_event_concat(evs, ev, NULL);
1509 else
1510 evs = ev;
1513 MUTEX_UNLOCK(&cn_mutex);
1515 if (!evs)
1516 return FALSE;
1518 pth_wait(evs);
1519 MUTEX_LOCK(&cn_mutex);
1520 i = g_slist_length(cn_thread_list);
1521 MUTEX_UNLOCK(&cn_mutex);
1522 return i ? TRUE : FALSE;
1525 static void server_loop(gint sockfd, gchar **socketpath)
1527 pth_t accept_tid;
1528 guint n;
1529 sigset_t sigset;
1530 pth_attr_t attr;
1531 pth_t cache_timeout_tid;
1533 sigemptyset(&sigset);
1535 /* Termination */
1536 sigaddset(&sigset, SIGTERM);
1537 sigaddset(&sigset, SIGINT);
1539 /* Clears the file cache. */
1540 sigaddset(&sigset, SIGUSR1);
1542 /* Configuration file reloading. */
1543 sigaddset(&sigset, SIGHUP);
1545 /* Clears the cache and exits when something bad happens. */
1546 sigaddset(&sigset, SIGABRT);
1548 /* Ignored everywhere. When a client disconnects abnormally this signal
1549 * gets raised. It isn't needed though because client_thread() will check
1550 * for rcs even after the client disconnects. */
1551 signal(SIGPIPE, SIG_IGN);
1552 sigprocmask(SIG_BLOCK, &sigset, NULL);
1554 log_write(N_("%s started for user %s"), PACKAGE_STRING, g_get_user_name());
1555 attr = pth_attr_new();
1556 pth_attr_init(attr);
1557 accept_tid = pth_spawn(attr, accept_thread, (void *)sockfd);
1559 if (!accept_tid) {
1560 log_write("%s(%i): pth_spawn(): %s", __FILE__, __LINE__,
1561 _gpg_strerror(gpg_error_from_errno(errno)));
1562 goto done;
1565 pth_yield(accept_tid);
1566 startStopKeepAlive(FALSE);
1567 pth_attr_set(attr, PTH_ATTR_JOINABLE, FALSE);
1568 cache_timeout_tid = pth_spawn(attr, adjust_cache_timer_thread, NULL);
1570 if (!cache_timeout_tid) {
1571 log_write("%s(%i): pth_spawn(): %s", __FILE__, __LINE__,
1572 _gpg_strerror(gpg_error_from_errno(errno)));
1573 goto done;
1576 pth_yield(cache_timeout_tid);
1577 pth_attr_destroy(attr);
1579 do {
1580 gint sig;
1582 pth_sigwait(&sigset, &sig);
1583 log_write(N_("caught signal %i (%s)"), sig, strsignal(sig));
1585 /* Caught a signal. */
1586 switch (sig) {
1587 case SIGHUP:
1588 reload_rcfile();
1589 break;
1590 case SIGABRT:
1591 cache_clear(NULL, 2);
1592 #ifndef MEM_DEBUG
1593 xpanic();
1594 #endif
1595 exit(EXIT_FAILURE);
1596 case SIGUSR1:
1597 CACHE_LOCK(NULL);
1598 log_write(N_("clearing file cache"));
1599 cache_clear(NULL, 2);
1600 CACHE_UNLOCK;
1601 break;
1602 default:
1603 quit = 1;
1604 break;
1606 } while (!quit);
1608 done:
1610 * We're out of the main server loop. This happens when a signal was sent
1611 * to terminate the daemon. We'll wait for all clients to disconnect
1612 * before exiting and ignore any following signals.
1614 shutdown(sockfd, SHUT_RDWR);
1615 close(sockfd);
1616 pth_cancel(accept_tid);
1617 pth_join(accept_tid, NULL);
1618 unlink(*socketpath);
1619 g_free(*socketpath);
1620 *socketpath = NULL;
1621 MUTEX_LOCK(&cn_mutex);
1622 n = g_slist_length(cn_thread_list);
1623 MUTEX_UNLOCK(&cn_mutex);
1625 if (n) {
1626 log_write(N_("waiting for all clients to disconnect"));
1628 do {
1629 MUTEX_LOCK(&cn_mutex);
1630 n = g_slist_length(cn_thread_list);
1631 MUTEX_UNLOCK(&cn_mutex);
1632 log_write(N_("%i clients remain"), n);
1633 } while (waiting_for_exit());
1636 startStopKeepAlive(TRUE);
1637 pth_cancel(cache_timeout_tid);
1638 cache_free();
1642 * Only called from pinentry_fork() in the child process.
1644 void free_client_list()
1646 gint i, t = g_slist_length(cn_thread_list);
1648 for (i = 0; i < t; i++) {
1649 struct client_thread_s *cn = g_slist_nth_data(cn_thread_list, i);
1651 free_client(cn->cl);
1654 cache_free();
1657 struct client_crypto_s *init_client_crypto()
1659 struct client_crypto_s *new = g_malloc0(sizeof(struct client_crypto_s));
1660 gpg_error_t rc;
1662 if (!new) {
1663 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1664 return NULL;
1667 rc = gcry_cipher_open(&new->gh, GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CBC, 0);
1669 if (rc) {
1670 log_write("%s(%i): %s", __FUNCTION__, __LINE__, _gpg_strerror(rc));
1671 g_free(new);
1672 return NULL;
1675 return new;
1678 static gpg_error_t convert_file(const gchar *filename, const gchar *keyfile,
1679 const gchar *outfile)
1681 gpg_error_t rc;
1682 guchar md5file[16];
1683 guint64 iter;
1684 struct client_crypto_s *crypto = init_client_crypto();
1686 if (!crypto)
1687 return GPG_ERR_ENOMEM;
1689 crypto->key = gcry_malloc(gcrykeysize);
1691 if (!crypto->key) {
1692 cleanup_crypto(&crypto);
1693 return GPG_ERR_ENOMEM;
1696 log_write(N_("Converting version 1 data file '%s' to version 2 ..."),
1697 filename);
1698 crypto->fh = read_file_header(filename, TRUE, &rc);
1700 if (!crypto->fh)
1701 goto done;
1703 gcry_md_hash_buffer(GCRY_MD_MD5, md5file, filename, strlen(filename));
1705 /* The header in version 1 had a bug where the iterations were off-by-one.
1706 * So 0 iterations was really -1 in the header. This is fixed in v2 of the
1707 * header.
1709 if (crypto->fh->fh1.iter >= 0) {
1710 if (keyfile) {
1711 crypto->tkey = parse_rcfile_keyfile(keyfile, TRUE, &rc);
1713 if (!crypto->tkey)
1714 goto done;
1716 gcry_md_hash_buffer(GCRY_MD_SHA256, crypto->key, crypto->tkey,
1717 strlen(crypto->tkey) ? strlen(crypto->tkey) : 1);
1719 else {
1720 rc = get_password(filename, crypto, md5file, crypto->key,
1721 PINENTRY_OPEN);
1723 if (rc)
1724 goto done;
1728 rc = try_xml_decrypt(NULL, crypto->key, crypto, &crypto->fh->doc,
1729 &crypto->fh->len);
1731 if (rc)
1732 goto done;
1734 rc = convert_xml((gchar **)&crypto->fh->doc, &crypto->fh->len);
1736 if (rc) {
1737 log_write("%s: %s", filename, pwmd_strerror(rc));
1738 goto done;
1741 crypto->fh->v1 = FALSE;
1742 iter = crypto->fh->fh1.iter;
1743 memset(&crypto->fh->fh2, 0, sizeof(crypto->fh->fh2));
1744 /* Keep the iterations and key from the original file. */
1745 crypto->fh->fh2.iter = iter+1; // Bugfix for v1 data files.
1746 rc = export_common(outfile, crypto, crypto->fh->doc, crypto->fh->len);
1748 done:
1749 if (rc)
1750 send_error(NULL, rc);
1752 /* fh->doc is freed from do_xml_decrypt() via the inbuf pointer. */
1753 cleanup_crypto(&crypto);
1754 return rc;
1757 int main(int argc, char *argv[])
1759 gint opt;
1760 struct sockaddr_un addr;
1761 gchar buf[PATH_MAX];
1762 gchar *socketpath = NULL, *socketdir, *socketname = NULL;
1763 gchar *socketarg = NULL;
1764 gchar *datadir = NULL;
1765 gboolean n;
1766 gint x;
1767 gchar *p;
1768 gchar **cache_push = NULL;
1769 gchar *import = NULL, *keyfile = NULL;
1770 guint64 cmd_iterations = -1;
1771 gint default_timeout;
1772 gboolean rcfile_spec = FALSE;
1773 gint estatus = EXIT_FAILURE;
1774 gint sockfd;
1775 gchar *outfile = NULL;
1776 GMemVTable mtable = { xmalloc, xrealloc, xfree, xcalloc, NULL, NULL };
1777 gint do_unlink = 1;
1778 gboolean secure = FALSE;
1779 gint background = 1;
1780 gchar *convert = NULL;
1781 #ifdef WITH_PINENTRY
1782 gboolean disable_pinentry = FALSE;
1783 #endif
1784 #if 0
1785 #ifndef DEBUG
1786 #ifdef HAVE_SETRLIMIT
1787 struct rlimit rl;
1789 rl.rlim_cur = rl.rlim_max = 0;
1791 if (setrlimit(RLIMIT_CORE, &rl) != 0)
1792 err(EXIT_FAILURE, "setrlimit()");
1793 #endif
1794 #endif
1795 #endif
1797 #ifdef ENABLE_NLS
1798 setlocale(LC_ALL, "");
1799 bindtextdomain("pwmd", LOCALEDIR);
1800 textdomain("pwmd");
1801 #endif
1803 #ifndef MEM_DEBUG
1804 xmem_init();
1805 #endif
1806 setup_gcrypt();
1807 gpg_err_init();
1808 assuan_set_assuan_err_source(GPG_ERR_SOURCE_DEFAULT);
1809 g_mem_set_vtable(&mtable);
1810 assuan_set_malloc_hooks(xmalloc, xrealloc, xfree);
1811 xmlMemSetup(xfree, xmalloc, xrealloc, xstrdup);
1812 xmlInitMemory();
1813 xmlInitGlobals();
1814 xmlInitParser();
1815 xmlXPathInit();
1816 g_snprintf(buf, sizeof(buf), "%s/.pwmd", g_get_home_dir());
1818 if (mkdir(buf, 0700) == -1 && errno != EEXIST)
1819 err(EXIT_FAILURE, "%s", buf);
1821 g_snprintf(buf, sizeof(buf), "%s/.pwmd/data", g_get_home_dir());
1823 if (mkdir(buf, 0700) == -1 && errno != EEXIST)
1824 err(EXIT_FAILURE, "%s", buf);
1826 cmdline = TRUE;
1828 while ((opt = getopt(argc, argv, "Po:C:nI:i:k:hvf:D")) != EOF) {
1829 switch (opt) {
1830 #ifdef WITH_PINENTRY
1831 case 'P':
1832 disable_pinentry = TRUE;
1833 break;
1834 #endif
1835 case 'o':
1836 outfile = optarg;
1837 break;
1838 case 'C':
1839 convert = optarg;
1840 break;
1841 case 'n':
1842 background = 0;
1843 break;
1844 case 'D':
1845 secure = TRUE;
1846 break;
1847 case 'I':
1848 import = optarg;
1849 break;
1850 case 'i':
1851 cmd_iterations = strtol(optarg, NULL, 10);
1852 break;
1853 case 'k':
1854 keyfile = optarg;
1855 break;
1856 case 'f':
1857 rcfile = g_strdup(optarg);
1858 rcfile_spec = TRUE;
1859 break;
1860 case 'v':
1861 printf(N_("%s\nCopyright (c) %s\nReleased under the terms of the GPL v2. Use at your own risk.\n\nCompile time features:\n%s"), PACKAGE_STRING,
1862 PACKAGE_BUGREPORT,
1863 #ifdef WITH_PINENTRY
1864 "+WITH_PINENTRY\n"
1865 #else
1866 "-WITH_PINENTRY\n"
1867 #endif
1868 #ifdef WITH_QUALITY
1869 "+WITH_QUALITY\n"
1870 #else
1871 "-WITH_QUALITY\n"
1872 #endif
1873 #ifdef DEBUG
1874 "+DEBUG\n"
1875 #else
1876 "-DEBUG\n"
1877 #endif
1878 #ifdef MEM_DEBUG
1879 "+MEM_DEBUG\n"
1880 #else
1881 "-MEM_DEBUG\n"
1882 #endif
1884 exit(EXIT_SUCCESS);
1885 case 'h':
1886 default:
1887 usage(argv[0]);
1891 pth_mutex_init(&cn_mutex);
1892 pth_mutex_init(&cache_mutex);
1893 pth_mutex_init(&rcfile_mutex);
1894 #ifdef WITH_PINENTRY
1895 pth_mutex_init(&pin_mutex);
1896 #endif
1898 if (!rcfile)
1899 rcfile = g_strdup_printf("%s/.pwmd/config", g_get_home_dir());
1901 if ((keyfileh = parse_rcfile(rcfile_spec)) == NULL)
1902 exit(EXIT_FAILURE);
1904 #ifdef WITH_PINENTRY
1905 if (disable_pinentry == TRUE)
1906 g_key_file_set_boolean(keyfileh, "global", "enable_pinentry", FALSE);
1907 #endif
1909 if (g_key_file_has_key(keyfileh, "global", "syslog", NULL) == TRUE)
1910 log_syslog = g_key_file_get_boolean(keyfileh, "global", "syslog", NULL);
1912 if (log_syslog == TRUE)
1913 openlog("pwmd", LOG_NDELAY|LOG_PID, LOG_DAEMON);
1915 if (g_key_file_has_key(keyfileh, "global", "priority", NULL)) {
1916 x = g_key_file_get_integer(keyfileh, "global", "priority", NULL);
1917 errno = 0;
1919 if (setpriority(PRIO_PROCESS, 0, x) == -1) {
1920 log_write("setpriority(): %s", strerror(errno));
1921 goto do_exit;
1925 #ifdef HAVE_MLOCKALL
1926 if (disable_mlock == FALSE && mlockall(MCL_FUTURE) == -1) {
1927 log_write("mlockall(): %s", strerror(errno));
1928 goto do_exit;
1930 #endif
1932 if (convert) {
1933 if (!outfile)
1934 usage(argv[0]);
1936 opt = convert_file(convert, keyfile, outfile);
1937 g_key_file_free(keyfileh);
1938 g_free(rcfile);
1939 exit(opt ? EXIT_FAILURE : EXIT_SUCCESS);
1942 if (import) {
1943 if (!outfile)
1944 usage(argv[0]);
1946 if (cmd_iterations == -1)
1947 cmd_iterations = (guint64)get_key_file_integer("global", "iterations");
1949 opt = xml_import(import, outfile, keyfile, cmd_iterations);
1950 g_key_file_free(keyfileh);
1951 g_free(rcfile);
1952 exit(opt == FALSE ? EXIT_FAILURE : EXIT_SUCCESS);
1955 g_key_file_set_list_separator(keyfileh, ',');
1957 if ((p = g_key_file_get_string(keyfileh, "global", "socket_path", NULL)) == NULL)
1958 errx(EXIT_FAILURE, N_("%s: socket_path not defined"), rcfile);
1960 socketarg = expand_homedir(p);
1961 g_free(p);
1963 if ((p = g_key_file_get_string(keyfileh, "global", "data_directory", NULL)) == NULL)
1964 errx(EXIT_FAILURE, N_("%s: data_directory not defined"), rcfile);
1966 datadir = expand_homedir(p);
1967 g_free(p);
1969 if (secure == FALSE && g_key_file_has_key(keyfileh, "global", "disable_list_and_dump", NULL) == TRUE) {
1970 n = g_key_file_get_boolean(keyfileh, "global", "disable_list_and_dump", NULL);
1971 disable_list_and_dump = n;
1973 else
1974 disable_list_and_dump = secure;
1976 if (g_key_file_has_key(keyfileh, "global", "cache_timeout", NULL) == TRUE)
1977 default_timeout = g_key_file_get_integer(keyfileh, "global", "cache_timeout", NULL);
1978 else
1979 default_timeout = -1;
1981 setup_logging(keyfileh);
1983 if (g_key_file_has_key(keyfileh, "global", "cache_push", NULL) == TRUE)
1984 cache_push = g_key_file_get_string_list(keyfileh, "global", "cache_push", NULL, NULL);
1986 if (argc != optind) {
1987 for (; optind < argc; optind++) {
1988 if (strv_printf(&cache_push, "%s", argv[optind]) == FALSE)
1989 errx(EXIT_FAILURE, "%s", strerror(ENOMEM));
1993 if (strchr(socketarg, '/') == NULL) {
1994 socketdir = g_get_current_dir();
1995 socketname = g_strdup(socketarg);
1996 socketpath = g_strdup_printf("%s/%s", socketdir, socketname);
1998 else {
1999 socketname = g_strdup(strrchr(socketarg, '/'));
2000 socketname++;
2001 socketarg[strlen(socketarg) - strlen(socketname) -1] = 0;
2002 socketdir = g_strdup(socketarg);
2003 socketpath = g_strdup_printf("%s/%s", socketdir, socketname);
2006 if (chdir(datadir)) {
2007 log_write("%s: %s", datadir, strerror(errno));
2008 unlink(socketpath);
2009 goto do_exit;
2012 if (parse_rcfile_keys() == FALSE)
2013 goto do_exit;
2015 clear_rcfile_keys();
2018 * Set the cache entry for a file. Prompts for the password.
2020 if (cache_push) {
2021 for (opt = 0; cache_push[opt]; opt++)
2022 do_cache_push(cache_push[opt], NULL);
2024 g_strfreev(cache_push);
2025 log_write(background ? N_("Done. Daemonizing...") : N_("Done. Waiting for connections..."));
2029 * bind() doesn't like the full pathname of the socket or any non alphanum
2030 * characters so change to the directory where the socket is wanted then
2031 * create it then change to datadir.
2033 if (chdir(socketdir)) {
2034 log_write("%s: %s", socketdir, strerror(errno));
2035 goto do_exit;
2038 g_free(socketdir);
2040 if ((sockfd = socket(PF_UNIX, SOCK_STREAM, 0)) == -1) {
2041 log_write("socket(): %s", strerror(errno));
2042 goto do_exit;
2045 addr.sun_family = AF_UNIX;
2046 g_snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", socketname);
2048 if (bind(sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr)) == -1) {
2049 log_write("bind(): %s", strerror(errno));
2051 if (errno == EADDRINUSE)
2052 log_write(N_("Either there is another pwmd running or '%s' is a \n"
2053 "stale socket. Please remove it manually."), socketpath);
2055 do_unlink = 0;
2056 goto do_exit;
2059 if (g_key_file_has_key(keyfileh, "global", "socket_perms", NULL) == TRUE) {
2060 gchar *t = g_key_file_get_string(keyfileh, "global", "socket_perms", NULL);
2061 mode_t mode = strtol(t, NULL, 8);
2062 mode_t mask = umask(0);
2064 g_free(t);
2066 if (chmod(socketname, mode) == -1) {
2067 log_write("%s: %s", socketname, strerror(errno));
2068 close(sockfd);
2069 unlink(socketpath);
2070 umask(mask);
2071 goto do_exit;
2074 umask(mask);
2077 g_free(--socketname);
2079 if (chdir(datadir)) {
2080 log_write("%s: %s", datadir, strerror(errno));
2081 close(sockfd);
2082 unlink(socketpath);
2083 goto do_exit;
2086 g_free(datadir);
2088 if (listen(sockfd, 0) == -1) {
2089 log_write("listen(): %s", strerror(errno));
2090 goto do_exit;
2093 cmdline = FALSE;
2095 if (background) {
2096 switch (fork()) {
2097 case -1:
2098 log_write("fork(): %s", strerror(errno));
2099 goto do_exit;
2100 case 0:
2101 close(0);
2102 close(1);
2103 close(2);
2104 setsid();
2105 break;
2106 default:
2107 exit(EXIT_SUCCESS);
2111 server_loop(sockfd, &socketpath);
2112 estatus = EXIT_SUCCESS;
2114 do_exit:
2115 if (socketpath && do_unlink) {
2116 unlink(socketpath);
2117 g_free(socketpath);
2120 g_key_file_free(keyfileh);
2121 g_free(rcfile);
2122 xmlCleanupParser();
2123 xmlCleanupGlobals();
2125 if (estatus == EXIT_SUCCESS)
2126 log_write(N_("pwmd exiting normally"));
2128 #if defined(DEBUG) && !defined(MEM_DEBUG)
2129 xdump();
2130 #endif
2131 exit(estatus);