Added the "debug_file" configuration parameter to log all protocol IO to the
[pwmd.git] / src / pwmd.c
blob96f2d6d7b59fb1fe5d541025c3c8eb4f2f263d58
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 HAVE_GETOPT_LONG
52 #ifdef HAVE_GETOPT_H
53 #include <getopt.h>
54 #endif
55 #else
56 #include "getopt_long.h"
57 #endif
59 #ifdef TM_IN_SYS_TIME
60 #include <sys/time.h>
61 #else
62 #include <time.h>
63 #endif
65 #include "mem.h"
66 #include "xml.h"
67 #include "common.h"
69 #ifdef WITH_PINENTRY
70 #include "pinentry.h"
71 #endif
73 #include "commands.h"
74 #include "pwmd_error.h"
75 #include "cache.h"
76 #include "misc.h"
77 #include "pwmd.h"
78 #include "lock.h"
80 GCRY_THREAD_OPTION_PTH_IMPL;
82 static void clear_rcfile_keys()
84 gsize n;
85 gchar **groups;
86 gchar **p;
88 groups = g_key_file_get_groups(keyfileh, &n);
90 for (p = groups; *p; p++) {
91 GError *rc = NULL;
93 if (g_key_file_has_key(keyfileh, *p, "key", &rc) == TRUE)
94 g_key_file_set_string(keyfileh, *p, "key", "");
97 g_strfreev(groups);
100 static void *reload_rcfile_thread(void *arg)
102 gboolean b = disable_list_and_dump;
103 GKeyFile *k;
104 pth_attr_t attr = pth_attr_of(pth_self());
106 pth_attr_set(attr, PTH_ATTR_NAME, __FUNCTION__);
107 pth_attr_destroy(attr);
108 MUTEX_LOCK(&rcfile_mutex);
109 log_write(N_("reloading configuration file '%s'"), rcfile);
110 k = parse_rcfile(FALSE);
112 if (!k)
113 goto done;
115 g_key_file_free(keyfileh);
116 keyfileh = k;
117 parse_rcfile_keys();
118 clear_rcfile_keys();
119 disable_list_and_dump = b;
120 startStopKeepAlive(FALSE);
121 send_status_all(STATUS_CONFIG);
122 done:
123 MUTEX_UNLOCK(&rcfile_mutex);
124 return NULL;
127 static void reload_rcfile()
129 pth_t tid;
130 pth_attr_t attr = pth_attr_new();
131 gint n;
133 pth_attr_init(attr);
134 pth_attr_set(attr, PTH_ATTR_JOINABLE, 0);
135 tid = pth_spawn(attr, reload_rcfile_thread, NULL);
136 n = errno;
137 pth_attr_destroy(attr);
139 if (!tid)
140 log_write("%s(%i): pth_spawn(): %s", __FILE__, __LINE__,
141 _gpg_strerror(gpg_error_from_errno(n)));
144 gpg_error_t send_syserror(assuan_context_t ctx, gint e)
146 gpg_error_t n = gpg_error_from_errno(e);
147 struct client_s *client = assuan_get_pointer(ctx);
149 client->last_rc = e;
150 return assuan_process_done(ctx, assuan_set_error(ctx, n, _gpg_strerror(n)));
153 gpg_error_t send_error(assuan_context_t ctx, gpg_error_t e)
155 gpg_err_code_t n = gpg_err_code(e);
156 gpg_error_t code = gpg_err_make(PWMD_ERR_SOURCE, n);
157 struct client_s *client = assuan_get_pointer(ctx);
159 if (client)
160 client->last_rc = e;
162 if (!e)
163 return assuan_process_done(ctx, 0);
165 if (!ctx) {
166 log_write("%s", pwmd_strerror(e));
167 return e;
170 if (n == EPWMD_LIBXML_ERROR) {
171 xmlErrorPtr xe = client->xml_error;
173 if (!xe)
174 xe = xmlGetLastError();
176 e = assuan_process_done(ctx, assuan_set_error(ctx, code, xe->message));
177 log_write("%s", xe->message);
179 if (xe == client->xml_error)
180 xmlResetError(xe);
181 else
182 xmlResetLastError();
184 client->xml_error = NULL;
185 return e;
188 return assuan_process_done(ctx, assuan_set_error(ctx, code, pwmd_strerror(e)));
191 void log_write(const gchar *fmt, ...)
193 gchar *args, *line;
194 va_list ap;
195 struct tm *tm;
196 time_t now;
197 gchar tbuf[21];
198 gint fd = -1;
199 gchar *name;
200 gchar buf[255];
201 pth_t tid = pth_self();
202 pth_attr_t attr;
204 if ((!logfile && !isatty(STDERR_FILENO) && log_syslog == FALSE) || !fmt)
205 return;
207 if (!cmdline && logfile) {
208 if ((fd = open(logfile, O_WRONLY|O_CREAT|O_APPEND, 0600)) == -1) {
209 warn("%s", logfile);
210 return;
214 va_start(ap, fmt);
216 if (g_vasprintf(&args, fmt, ap) == -1) {
217 if (logfile)
218 close(fd);
220 va_end(ap);
221 return;
224 va_end(ap);
226 if (cmdline) {
227 fprintf(stderr, "%s\n", args);
228 fflush(stderr);
229 g_free(args);
230 return;
233 attr = pth_attr_of(tid);
235 if (pth_attr_get(attr, PTH_ATTR_NAME, &name) == FALSE)
236 name = "unknown";
238 pth_attr_destroy(attr);
239 name = print_fmt(buf, sizeof(buf), "%s(%p): ", name, tid);
241 if (!cmdline && log_syslog == TRUE)
242 syslog(LOG_INFO, "%s%s", name, args);
244 time(&now);
245 tm = localtime(&now);
246 strftime(tbuf, sizeof(tbuf), "%b %d %Y %H:%M:%S ", tm);
247 tbuf[sizeof(tbuf) - 1] = 0;
249 if (args[strlen(args)-1] == '\n')
250 args[strlen(args)-1] = 0;
252 line = g_strdup_printf("%s %i %s%s\n", tbuf, getpid(), name, args);
253 g_free(args);
255 if (!line) {
256 if (logfile)
257 close(fd);
259 return;
262 if (logfile) {
263 pth_write(fd, line, strlen(line));
264 fsync(fd);
265 close(fd);
268 if (isatty(STDERR_FILENO)) {
269 fprintf(stderr, "%s", line);
270 fflush(stderr);
273 g_free(line);
276 static void usage(gchar *pn, gint rc)
278 g_fprintf(rc == EXIT_FAILURE ? stderr : stdout, N_(
279 "Usage: %s [options] [file1] [...]\n"
280 " --no-fork/-n\n"
281 " run as a foreground process\n"
282 " --rcfile/-f <filename>\n"
283 " load the specified rcfile (~/.pwmd/config)\n"
284 " --convert/-C <filename>\n"
285 " convert a version 1 data file to version 2\n"
286 " --import/-I <filename>\n"
287 " import an XML file\n"
288 " --iterations/-i\n"
289 " encrypt with the specified number of iterations when importing\n"
290 " (default is in the rcfile \"global\" section)\n"
291 " --key-file/-k <filename>\n"
292 " obtain the key from the specified file when importing or converting\n"
293 " --outfile/-o <filename>\n"
294 " output file to use when importing or converting (- for stdout)\n"
295 " --disable-dump/-D\n"
296 " disable use of the LIST, XPATH and DUMP commands\n"
297 " --no-pinentry/-P\n"
298 " disable use of pinentry\n"
299 " --version\n"
300 " --help\n"
301 ), pn);
302 exit(rc);
305 static void setup_gcrypt()
307 gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pth);
309 if (!gcry_check_version(GCRYPT_VERSION))
310 errx(EXIT_FAILURE, N_("gcry_check_version(): Incompatible libgcrypt. Wanted %s, got %s."), GCRYPT_VERSION, gcry_check_version(NULL));
312 gcry_set_allocation_handler(xmalloc, xmalloc, NULL, xrealloc, xfree);
315 static gint new_connection(struct client_s *cl)
317 gpg_error_t rc;
318 gchar *ver;
320 rc = assuan_init_socket_server_ext(&cl->ctx, cl->thd->fd, 2);
322 if (rc)
323 goto fail;
325 assuan_set_pointer(cl->ctx, cl);
326 ver = g_strdup_printf("%s", PACKAGE_STRING);
327 assuan_set_hello_line(cl->ctx, ver);
328 g_free(ver);
329 rc = register_commands(cl->ctx);
331 if (rc)
332 goto fail;
334 rc = assuan_accept(cl->ctx);
336 if (rc)
337 goto fail;
340 FILE *fp;
341 gchar *str = get_key_file_string("global", "debug_file");
343 if (str) {
344 gchar *f = expand_homedir(str);
346 g_free(str);
347 fp = fopen(f, "w");
349 if (!fp)
350 log_write("%s: %s", f, pwmd_strerror(gpg_error_from_errno(errno)));
351 else
352 assuan_set_log_stream(cl->ctx, fp);
354 g_free(f);
358 return 0;
360 fail:
361 log_write("%s", _gpg_strerror(rc));
362 close(cl->thd->fd);
363 cl->thd->fd = -1;
364 return 1;
367 static void xml_error_cb(void *data, xmlErrorPtr e)
369 struct client_s *client = data;
372 * Keep the first reported error as the one to show in the error
373 * description. Reset in send_error().
375 if (client->xml_error)
376 return;
378 xmlCopyError(e, client->xml_error);
381 void close_file_header(file_header_internal_t *fh)
383 if (!fh)
384 return;
386 if (fh->fd != -1 || (cmdline == TRUE && fh->fd != STDOUT_FILENO))
387 close(fh->fd);
389 if (fh->doc)
390 gcry_free(fh->doc);
392 g_free(fh);
395 void cleanup_crypto(struct client_crypto_s **c)
397 struct client_crypto_s *cr = *c;
399 if (!cr)
400 return;
402 if (cr->iv) {
403 gcry_free(cr->iv);
404 cr->iv = NULL;
407 if (cr->key) {
408 gcry_free(cr->key);
409 cr->key = NULL;
412 if (cr->tkey) {
413 gcry_free(cr->tkey);
414 cr->tkey = NULL;
417 if (cr->tkey2) {
418 gcry_free(cr->tkey2);
419 cr->tkey2 = NULL;
422 if (cr->inbuf) {
423 gcry_free(cr->inbuf);
424 cr->inbuf = NULL;
427 if (cr->outbuf) {
428 gcry_free(cr->outbuf);
429 cr->outbuf = NULL;
432 close_file_header(cr->fh);
433 cr->fh = NULL;
435 if (cr->gh)
436 gcry_cipher_close(cr->gh);
438 cr->gh = NULL;
439 g_free(cr);
440 *c = NULL;
444 * This is called after a child_thread terminates. Set with
445 * pth_cleanup_push().
447 static void cleanup_cb(void *arg)
449 struct client_thread_s *cn = arg;
450 struct client_s *cl = cn->cl;
452 MUTEX_LOCK(&cn_mutex);
453 cn_thread_list = g_slist_remove(cn_thread_list, cn);
454 MUTEX_UNLOCK(&cn_mutex);
456 if (cn->msg_tid) {
457 MUTEX_LOCK(&cn->mp_mutex);
458 pth_cancel(cn->msg_tid);
459 MUTEX_UNLOCK(&cn->mp_mutex);
462 if (cn->mp) {
463 while (pth_msgport_pending(cn->mp)) {
464 pth_message_t *msg = pth_msgport_get(cn->mp);
466 g_free(msg->m_data);
467 g_free(msg);
470 pth_msgport_destroy(cn->mp);
473 if (!cl) {
474 if (cn->fd != -1)
475 close(cn->fd);
477 goto done;
480 if (!cl->freed)
481 cleanup_client(cl);
483 if (cl->ctx)
484 assuan_deinit_server(cl->ctx);
485 else if (cl->thd && cl->thd->fd != -1)
486 close(cl->thd->fd);
488 #ifdef WITH_PINENTRY
489 if (cl->pinentry)
490 cleanup_pinentry(cl->pinentry);
491 #endif
493 if (cl->crypto)
494 cleanup_crypto(&cl->crypto);
496 g_free(cl);
497 done:
498 log_write(N_("exiting, fd=%i"), cn->fd);
499 g_free(cn);
500 send_status_all(STATUS_CLIENTS);
504 * Called every time a connection is made from init_new_connection(). This is
505 * the thread entry point.
507 static void *client_thread(void *data)
509 struct client_thread_s *thd = data;
510 struct client_s *cl = g_malloc0(sizeof(struct client_s));
511 gpg_error_t rc;
512 pth_attr_t attr;
513 gint n;
516 * Prevent a race condition with init_new_connection() if this thread
517 * fails (returns) for some reason before init_new_connection() releases
518 * the cn_mutex.
520 MUTEX_LOCK(&cn_mutex);
521 MUTEX_UNLOCK(&cn_mutex);
522 pth_cleanup_push(cleanup_cb, thd);
524 if (!cl) {
525 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
526 goto fail;
529 attr = pth_attr_of(pth_self());
530 pth_attr_set(attr, PTH_ATTR_NAME, __FUNCTION__);
531 pth_attr_destroy(attr);
532 thd->cl = cl;
533 cl->thd = thd;
535 if (new_connection(cl))
536 goto fail;
538 #ifdef WITH_PINENTRY
539 cl->pinentry = pinentry_init();
541 if (!cl->pinentry) {
542 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
543 goto fail;
545 #endif
547 #ifdef HAVE_MLOCKALL
548 if (disable_mlock == FALSE && mlockall(MCL_FUTURE) == -1) {
549 log_write("mlockall(): %s", strerror(errno));
550 goto fail;
552 #endif
554 thd->mp = pth_msgport_create(NULL);
555 pth_mutex_init(&thd->mp_mutex);
556 thd->msg_tid = pth_spawn(NULL, client_msg_thread, thd);
557 n = errno;
559 if (!thd->msg_tid) {
560 log_write("%s(%i): pth_spawn(): %s", __FILE__, __LINE__,
561 _gpg_strerror(gpg_error_from_errno(n)));
562 goto fail;
565 pth_yield(thd->msg_tid);
566 rc = send_status(cl->ctx, STATUS_CACHE, NULL);
568 if (rc) {
569 log_write("%s", _gpg_strerror(rc));
570 goto fail;
573 send_status_all(STATUS_CLIENTS);
574 xmlSetStructuredErrorFunc(cl, xml_error_cb);
576 for (;;) {
577 #ifdef WITH_PINENTRY
578 pth_event_t pev = NULL;
579 #endif
580 pth_status_t st, wst;
581 pth_event_t wev = NULL;
582 pth_event_t rev = pth_event(PTH_EVENT_FD|PTH_UNTIL_FD_READABLE,
583 cl->thd->fd);
584 pth_event_t ev = rev;
586 #ifdef WITH_PINENTRY
587 if (cl->pinentry->status == PINENTRY_RUNNING) {
588 pev = pth_event(PTH_EVENT_FD|PTH_UNTIL_FD_READABLE, cl->pinentry->fd);
589 ev = pth_event_concat(ev, pev, NULL);
591 #endif
593 if (cl->inquire_status == INQUIRE_BUSY) {
594 wev = pth_event(PTH_EVENT_FD|PTH_UNTIL_FD_WRITEABLE, cl->thd->fd);
595 ev = pth_event_concat(ev, wev, NULL);
598 pth_cleanup_push(cleanup_ev_cb, ev);
599 pth_wait(ev);
600 st = pth_event_status(rev);
601 wst = pth_event_status(wev);
603 if (st == PTH_STATUS_OCCURRED || wst == PTH_STATUS_OCCURRED) {
604 rc = assuan_process_next(cl->ctx);
606 if (rc) {
607 cl->inquire_status = INQUIRE_INIT;
608 pth_cleanup_pop(1);
610 if (gpg_err_code(rc) == GPG_ERR_EOF)
611 goto done;
613 log_write("assuan_process_next(): %s", _gpg_strerror(rc));
614 rc = send_error(cl->ctx, gpg_err_make(PWMD_ERR_SOURCE, rc));
616 if (rc) {
617 log_write("assuan_process_done(): %s", _gpg_strerror(rc));
618 goto done;
621 else {
622 #ifdef WITH_PINENTRY
623 if (cl->pinentry->pid && cl->pinentry->status == PINENTRY_INIT)
624 cl->pinentry->status = PINENTRY_RUNNING;
625 #endif
627 switch (cl->inquire_status) {
628 case INQUIRE_BUSY:
629 case INQUIRE_INIT:
630 break;
631 case INQUIRE_DONE:
632 cl->inquire_status = INQUIRE_INIT;
633 rc = assuan_process_done(cl->ctx, 0);
634 break;
639 #ifdef WITH_PINENTRY
640 if (pev)
641 st = pth_event_status(pev);
643 rc = pinentry_iterate(cl,
644 pev && cl->pinentry->fd != -1 && st == PTH_STATUS_OCCURRED);
645 #endif
646 pth_cleanup_pop(1);
650 * Client cleanup (including XML data) is done in cleanup_cb().
652 done:
653 fail:
654 pth_exit(PTH_CANCELED);
655 return NULL;
658 static void setup_logging(GKeyFile *kf)
660 gboolean n = g_key_file_get_boolean(kf, "global", "enable_logging", NULL);
662 if (n == TRUE) {
663 gchar *p = g_key_file_get_string(kf, "global", "log_path", NULL);
665 if (*p == '~') {
666 gchar buf[PATH_MAX];
668 p++;
669 g_snprintf(buf, sizeof(buf), "%s%s", g_get_home_dir(), p--);
670 g_free(p);
672 if (logfile)
673 g_free(logfile);
675 logfile = g_strdup(buf);
677 else {
678 if (logfile)
679 g_free(logfile);
681 logfile = p;
685 log_syslog = g_key_file_get_boolean(kf, "global", "syslog", NULL);
689 * Make sure all settings are set to either the specified setting or a
690 * default.
692 static void set_rcfile_defaults(GKeyFile *kf)
694 gchar buf[PATH_MAX];
696 if (g_key_file_has_key(kf, "global", "socket_path", NULL) == FALSE) {
697 g_snprintf(buf, sizeof(buf), "~/.pwmd/socket");
698 g_key_file_set_string(kf, "global", "socket_path", buf);
701 if (g_key_file_has_key(kf, "global", "data_directory", NULL) == FALSE) {
702 g_snprintf(buf, sizeof(buf), "~/.pwmd/data");
703 g_key_file_set_string(kf, "global", "data_directory", buf);
706 if (g_key_file_has_key(kf, "global", "backup", NULL) == FALSE)
707 g_key_file_set_boolean(kf, "global", "backup", TRUE);
709 if (g_key_file_has_key(kf, "global", "log_path", NULL) == FALSE) {
710 g_snprintf(buf, sizeof(buf), "~/.pwmd/log");
711 g_key_file_set_string(kf, "global", "log_path", buf);
714 if (g_key_file_has_key(kf, "global", "enable_logging", NULL) == FALSE)
715 g_key_file_set_boolean(kf, "global", "enable_logging", FALSE);
717 #ifdef HAVE_MLOCKALL
718 if (g_key_file_has_key(kf, "global", "disable_mlockall", NULL) == FALSE)
719 g_key_file_set_boolean(kf, "global", "disable_mlockall", TRUE);
720 #endif
722 if (g_key_file_has_key(kf, "global", "cache_timeout", NULL) == FALSE)
723 g_key_file_set_integer(kf, "global", "cache_timeout", -1);
725 if (g_key_file_has_key(kf, "global", "iterations", NULL) == FALSE ||
726 g_key_file_get_double(kf, "global", "iterations", 0) < 0ULL)
727 g_key_file_set_double(kf, "global", "iterations", 1ULL);
729 if (g_key_file_has_key(kf, "global", "disable_list_and_dump", NULL) == FALSE)
730 g_key_file_set_boolean(kf, "global", "disable_list_and_dump", FALSE);
732 if (g_key_file_has_key(kf, "global", "iteration_progress", NULL) == FALSE)
733 g_key_file_set_double(kf, "global", "iteration_progress", 0ULL);
735 if (g_key_file_has_key(kf, "global", "compression_level", NULL) == FALSE)
736 g_key_file_set_integer(kf, "global", "compression_level", 6);
738 if (g_key_file_has_key(kf, "global", "recursion_depth", NULL) == FALSE)
739 g_key_file_set_integer(kf, "global", "recursion_depth", DEFAULT_RECURSION_DEPTH);
741 if (g_key_file_has_key(kf, "global", "zlib_bufsize", NULL) == FALSE)
742 g_key_file_set_integer(kf, "global", "zlib_bufsize", DEFAULT_ZLIB_BUFSIZE);
744 zlib_bufsize = (uInt)g_key_file_get_integer(kf, "global", "zlib_bufsize", NULL);
746 max_recursion_depth = g_key_file_get_integer(kf, "global", "recursion_depth", NULL);
747 disable_list_and_dump = g_key_file_get_boolean(kf, "global", "disable_list_and_dump", NULL);
749 #ifdef HAVE_MLOCKALL
750 disable_mlock = g_key_file_get_boolean(kf, "global", "disable_mlockall", NULL);
751 #endif
753 if (g_key_file_has_key(kf, "global", "syslog", NULL) == FALSE)
754 g_key_file_set_boolean(kf, "global", "syslog", FALSE);
756 if (g_key_file_has_key(kf, "global", "keepalive", NULL) == FALSE)
757 g_key_file_set_integer(kf, "global", "keepalive", DEFAULT_KEEPALIVE_TO);
759 #ifdef WITH_PINENTRY
760 if (g_key_file_has_key(kf, "global", "enable_pinentry", NULL) == FALSE)
761 g_key_file_set_boolean(kf, "global", "enable_pinentry", TRUE);
763 if (g_key_file_has_key(kf, "global", "pinentry_timeout", NULL) == FALSE)
764 g_key_file_set_integer(kf, "global", "pinentry_timeout",
765 DEFAULT_PIN_TIMEOUT);
767 if (g_key_file_has_key(kf, "global", "pinentry_path", NULL) == FALSE)
768 g_key_file_set_string(kf, "global", "pinentry_path", PINENTRY_PATH);
769 #endif
771 if (g_key_file_has_key(kf, "global", "xfer_progress", NULL) == FALSE)
772 g_key_file_set_integer(kf, "global", "xfer_progress", 8196);
774 if (g_key_file_has_key(kf, "global", "cipher", NULL) == FALSE)
775 g_key_file_set_string(kf, "global", "cipher", "AES256");
777 if (g_key_file_has_key(kf, "global", "log_level", NULL) == FALSE)
778 g_key_file_set_integer(kf, "global", "log_level", 0);
780 setup_logging(kf);
783 static GKeyFile *parse_rcfile(gboolean specified)
785 GKeyFile *kf = g_key_file_new();
786 GError *rc = NULL;
788 if (g_key_file_load_from_file(kf, rcfile, G_KEY_FILE_NONE, &rc) == FALSE) {
789 log_write("%s: %s", rcfile, rc->message);
791 if (cmdline && specified) {
792 g_clear_error(&rc);
793 return NULL;
796 if (rc->code == G_FILE_ERROR_NOENT) {
797 g_clear_error(&rc);
798 set_rcfile_defaults(kf);
799 return kf;
802 g_clear_error(&rc);
803 return NULL;
806 set_rcfile_defaults(kf);
807 return kf;
810 static gchar *do_get_password(const gchar *prompt)
812 gchar buf[LINE_MAX] = {0}, *p;
813 struct termios told, tnew;
814 gchar *key;
816 if (tcgetattr(STDIN_FILENO, &told) == -1) {
817 log_write("tcgetattr(): %s", strerror(errno));
818 return NULL;
821 memcpy(&tnew, &told, sizeof(struct termios));
822 tnew.c_lflag &= ~(ECHO);
823 tnew.c_lflag |= ICANON|ECHONL;
825 if (tcsetattr(STDIN_FILENO, TCSANOW, &tnew) == -1) {
826 log_write("tcsetattr(): %s", strerror(errno));
827 tcsetattr(STDIN_FILENO, TCSANOW, &told);
828 return NULL;
831 fprintf(stderr, "%s", prompt);
833 if ((p = fgets(buf, sizeof(buf), stdin)) == NULL) {
834 tcsetattr(STDIN_FILENO, TCSANOW, &told);
835 return NULL;
838 tcsetattr(STDIN_FILENO, TCSANOW, &told);
839 p[strlen(p) - 1] = 0;
841 if (!buf[0]) {
842 key = gcry_malloc(1);
843 key[0] = 0;
845 else {
846 key = gcry_malloc(strlen(p) + 1);
847 sprintf(key, "%s", p);
850 memset(&buf, 0, sizeof(buf));
851 return key;
854 /* Only used when "enable_pinentry" is "false" or -P. */
855 static gpg_error_t get_input(const gchar *filename,
856 struct client_crypto_s *crypto, guchar *key, pinentry_cmd_t which)
858 gchar *prompt;
860 if (which == PINENTRY_SAVE) {
861 prompt = g_strdup_printf(N_("New passphrase for file %s: "), filename);
862 crypto->tkey = do_get_password(prompt);
863 g_free(prompt);
865 if (!crypto->tkey) {
866 log_write(N_("%s: Skipping file"), filename);
867 return GPG_ERR_BAD_PASSPHRASE;
870 prompt = g_strdup_printf(N_("Repeat passphrase: "));
871 crypto->tkey2 = do_get_password(prompt);
872 g_free(prompt);
874 if (!crypto->tkey2) {
875 log_write(N_("%s: Skipping file"), filename);
876 return GPG_ERR_BAD_PASSPHRASE;
879 if (strcmp(crypto->tkey, crypto->tkey2)) {
880 log_write(N_("%s: Passphrase mismatch"), filename);
881 return EPWMD_BADKEY;
884 gcry_md_hash_buffer(GCRY_MD_SHA256, key, crypto->tkey,
885 strlen(crypto->tkey) ? strlen(crypto->tkey) : 1);
886 return 0;
889 prompt = g_strdup_printf(N_("Passphrase required for %s: "), filename);
891 if ((crypto->tkey = do_get_password(prompt)) == NULL) {
892 log_write(N_("%s: Skipping file"), filename);
893 g_free(prompt);
894 return GPG_ERR_BAD_PASSPHRASE;
897 gcry_md_hash_buffer(GCRY_MD_SHA256, key, crypto->tkey,
898 strlen(crypto->tkey) ? strlen(crypto->tkey) : 1);
899 g_free(prompt);
900 return 0;
904 * inbuf must have been allocated with gcry_malloc().
906 gpg_error_t export_common(const gchar *filename, struct client_crypto_s *crypto,
907 gpointer inbuf, gulong insize)
909 gpg_error_t rc;
910 gint level, zrc;
911 gulong outsize;
912 gpointer outbuf;
914 rc = update_save_flags(NULL, crypto);
916 if (rc)
917 return rc;
919 level = get_key_file_integer(filename, "compression_level");
921 if (level < 0)
922 level = 0;
924 if (do_compress(NULL, level, inbuf, insize, &outbuf, &outsize, &zrc)
925 == FALSE) {
926 return zrc == Z_MEM_ERROR ? GPG_ERR_ENOMEM : GPG_ERR_COMPR_ALGO;
929 crypto->inbuf = outbuf;
930 crypto->insize = outsize;
931 rc = do_xml_encrypt(NULL, crypto, filename);
932 return rc;
935 static gpg_error_t get_password(const gchar *filename,
936 struct client_crypto_s *crypto, guchar *md5file, guchar *key,
937 pinentry_cmd_t which)
939 #ifdef WITH_PINENTRY
940 gpg_error_t rc = 0;
942 if (g_key_file_get_boolean(keyfileh, "global", "enable_pinentry", NULL)
943 == FALSE) {
944 #endif
945 return get_input(filename, crypto, key, which);
946 #ifdef WITH_PINENTRY
948 else {
949 gchar *result = NULL;
950 struct pinentry_s *pin = g_malloc0(sizeof(struct pinentry_s));
952 pth_mutex_init(&pin->status_mutex);
953 set_pinentry_defaults(pin);
954 pin->which = which;
955 pin->filename = g_strdup(filename);
956 rc = pinentry_getpin(pin, &result);
958 if (rc) {
959 xfree(result);
960 goto done;
963 gcry_md_hash_buffer(GCRY_MD_SHA256, key, result, result ? strlen(result) : 1);
964 xfree(result);
965 cleanup_pinentry(pin);
968 done:
969 return rc;
970 #endif
973 static gboolean _getline(const gchar *file, gchar **result, gpg_error_t *rc)
975 FILE *fp;
976 gchar buf[LINE_MAX] = {0}, *p;
977 gchar *str = NULL;
978 gint len;
980 *rc = 0;
982 if ((fp = fopen(file, "r")) == NULL) {
983 *rc = gpg_error_from_syserror();
984 return FALSE;
987 p = fgets(buf, sizeof(buf), fp);
988 fclose(fp);
989 len = strlen(buf);
991 if (len && buf[len - 1] == '\n')
992 buf[--len] = 0;
994 str = gcry_malloc(len + 1);
996 if (!str) {
997 *rc = gpg_error_from_errno(ENOMEM);
998 return FALSE;
1001 memcpy(str, buf, len ? len : 1);
1002 str[len] = 0;
1003 memset(&buf, 0, sizeof(buf));
1004 *result = str;
1005 return TRUE;
1008 static gchar *parse_rcfile_keyfile(const gchar *filename, gboolean import,
1009 gpg_error_t *rc)
1011 GError *rv = NULL;
1012 gchar *t, *file = NULL, *str;
1014 *rc = GPG_ERR_UNKNOWN_ERRNO;
1016 if (import == FALSE) {
1017 if (g_key_file_has_key(keyfileh, filename, "key_file", &rv) == TRUE) {
1018 file = g_key_file_get_string(keyfileh, filename, "key_file", &rv);
1020 if (!file) {
1021 if (rv) {
1022 log_write("%s: key_file: %s", rcfile, rv->message);
1023 g_clear_error(&rv);
1026 return NULL;
1029 t = expand_homedir(file);
1031 if (!t) {
1032 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1033 *rc = gpg_error_from_errno(ENOMEM);
1034 return NULL;
1037 g_free(file);
1038 file = t;
1041 else {
1042 /* -I or -C. The filename is a key file. */
1043 file = g_strdup(filename);
1045 if (!file) {
1046 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1047 *rc = gpg_error_from_errno(ENOMEM);
1048 return NULL;
1052 if (rv) {
1053 log_write("%s: key_file: %s", rcfile, rv->message);
1054 g_clear_error(&rv);
1055 return NULL;
1058 if (!file)
1059 return NULL;
1061 if (_getline(file, &str, rc) == FALSE) {
1062 log_write("%s: %s: %s", filename, file, pwmd_strerror(*rc));
1063 g_free(file);
1064 return NULL;
1067 g_free(file);
1068 *rc = 0;
1069 return str;
1072 static gboolean xml_import(const gchar *filename, const gchar *outfile,
1073 const gchar *keyfile, guint64 iter)
1075 xmlDocPtr doc;
1076 gint fd;
1077 struct stat st;
1078 gint len;
1079 xmlChar *xmlbuf;
1080 xmlChar *xml;
1081 gpg_error_t rc;
1082 struct client_crypto_s *crypto;
1083 guint hashlen = gcry_md_get_algo_dlen(GCRY_MD_SHA256);
1085 if (stat(filename, &st) == -1) {
1086 log_write("%s: %s", filename, strerror(errno));
1087 return FALSE;
1090 crypto = init_client_crypto();
1092 if (!crypto)
1093 return FALSE;
1095 crypto->key = gcry_malloc(hashlen);
1096 memset(crypto->key, 0, hashlen);
1098 if (!crypto->key) {
1099 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1100 goto fail;
1103 log_write(N_("Importing XML from '%s'. Output will be written to '%s' ..."),
1104 filename, outfile);
1106 if (iter && keyfile) {
1107 crypto->tkey = parse_rcfile_keyfile(keyfile, TRUE, &rc);
1109 if (!crypto->tkey)
1110 goto fail;
1112 gcry_md_hash_buffer(GCRY_MD_SHA256, crypto->key, crypto->tkey,
1113 strlen(crypto->tkey) ? strlen(crypto->tkey) : 1);
1115 else if (iter) {
1116 rc = get_password(outfile, crypto, NULL, crypto->key, PINENTRY_SAVE);
1118 if (rc)
1119 goto fail;
1122 if ((fd = open(filename, O_RDONLY)) == -1) {
1123 log_write("%s: %s", filename, strerror(errno));
1124 goto fail;
1127 if ((xmlbuf = gcry_malloc(st.st_size+1)) == NULL) {
1128 close(fd);
1129 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1130 goto fail;
1133 if (pth_read(fd, xmlbuf, st.st_size) == -1) {
1134 rc = errno;
1135 close(fd);
1136 errno = rc;
1137 log_write("%s: %s", filename, strerror(errno));
1138 goto fail;
1141 close(fd);
1142 xmlbuf[st.st_size] = 0;
1145 * Make sure the document validates.
1147 if ((doc = xmlReadDoc(xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS)) == NULL) {
1148 log_write("xmlReadDoc() failed");
1149 gcry_free(xmlbuf);
1150 goto fail;
1153 gcry_free(xmlbuf);
1154 xmlDocDumpMemory(doc, &xml, &len);
1155 xmlFreeDoc(doc);
1157 if (!iter)
1158 memset(crypto->key, '!', hashlen);
1160 crypto->fh = g_malloc0(sizeof(file_header_internal_t));
1162 if (!crypto->fh) {
1163 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1164 goto fail;
1167 crypto->fh->ver.fh2.iter = iter;
1168 rc = export_common(outfile, crypto, xml, len);
1169 xmlFree(xml);
1171 if (rc) {
1172 send_error(NULL, rc);
1173 goto fail;
1176 cleanup_crypto(&crypto);
1177 return TRUE;
1179 fail:
1180 cleanup_crypto(&crypto);
1181 return FALSE;
1184 gchar *get_key_file_string(const gchar *section, const gchar *what)
1186 gchar *val = NULL;
1187 GError *grc = NULL;
1189 MUTEX_LOCK(&rcfile_mutex);
1191 if (g_key_file_has_key(keyfileh, section, what, NULL) == TRUE) {
1192 val = g_key_file_get_string(keyfileh, section, what, &grc);
1194 if (grc) {
1195 log_write("%s(%i): %s", __FILE__, __LINE__, grc->message);
1196 g_clear_error(&grc);
1199 else {
1200 if (g_key_file_has_key(keyfileh, "global", what, NULL) == TRUE) {
1201 val = g_key_file_get_string(keyfileh, "global", what, &grc);
1203 if (grc) {
1204 log_write("%s(%i): %s", __FILE__, __LINE__, grc->message);
1205 g_clear_error(&grc);
1210 MUTEX_UNLOCK(&rcfile_mutex);
1211 return val;
1214 gint get_key_file_integer(const gchar *section, const gchar *what)
1216 gint val = -1;
1217 GError *grc = NULL;
1219 MUTEX_LOCK(&rcfile_mutex);
1221 if (g_key_file_has_key(keyfileh, section ? section : "global", what, NULL) == TRUE) {
1222 val = g_key_file_get_integer(keyfileh, section ? section : "global", what, &grc);
1224 if (grc) {
1225 log_write("%s(%i): %s", __FILE__, __LINE__, grc->message);
1226 g_clear_error(&grc);
1229 else {
1230 if (g_key_file_has_key(keyfileh, "global", what, NULL) == TRUE) {
1231 val = g_key_file_get_integer(keyfileh, "global", what, &grc);
1233 if (grc) {
1234 log_write("%s(%i): %s", __FILE__, __LINE__, grc->message);
1235 g_clear_error(&grc);
1240 MUTEX_UNLOCK(&rcfile_mutex);
1241 return val;
1244 gdouble get_key_file_double(const gchar *section, const gchar *what)
1246 gdouble val = -1;
1247 GError *grc = NULL;
1249 MUTEX_LOCK(&rcfile_mutex);
1251 if (g_key_file_has_key(keyfileh, section ? section : "global", what, NULL) == TRUE) {
1252 val = g_key_file_get_double(keyfileh, section ? section : "global", what, &grc);
1254 if (grc) {
1255 log_write("%s(%i): %s", __FILE__, __LINE__, grc->message);
1256 g_clear_error(&grc);
1259 else {
1260 if (g_key_file_has_key(keyfileh, "global", what, NULL) == TRUE) {
1261 val = g_key_file_get_double(keyfileh, "global", what, &grc);
1263 if (grc) {
1264 log_write("%s(%i): %s", __FILE__, __LINE__, grc->message);
1265 g_clear_error(&grc);
1270 MUTEX_UNLOCK(&rcfile_mutex);
1271 return val;
1274 gboolean get_key_file_boolean(const gchar *section, const gchar *what)
1276 gboolean val = FALSE;
1277 GError *grc = NULL;
1279 MUTEX_LOCK(&rcfile_mutex);
1281 if (g_key_file_has_key(keyfileh, section ? section : "global", what, NULL)
1282 == TRUE) {
1283 val = g_key_file_get_boolean(keyfileh, section ? section : "global",
1284 what, &grc);
1286 if (grc) {
1287 log_write("%s(%i): %s", __FILE__, __LINE__, grc->message);
1288 g_clear_error(&grc);
1291 else {
1292 if (g_key_file_has_key(keyfileh, "global", what, NULL) == TRUE) {
1293 val = g_key_file_get_boolean(keyfileh, "global", what, &grc);
1295 if (grc) {
1296 log_write("%s(%i): %s", __FILE__, __LINE__, grc->message);
1297 g_clear_error(&grc);
1302 MUTEX_UNLOCK(&rcfile_mutex);
1303 return val;
1306 static gboolean parse_rcfile_keys()
1308 gsize n;
1309 gchar **groups;
1310 gchar **p;
1311 gchar *str;
1313 groups = g_key_file_get_groups(keyfileh, &n);
1315 for (p = groups; *p; p++) {
1316 GError *rc = NULL;
1318 if (g_key_file_has_key(keyfileh, *p, "key", &rc) == TRUE) {
1319 str = g_key_file_get_string(keyfileh, *p, "key", &rc);
1321 if (!str) {
1322 if (rc) {
1323 log_write("%s: key: %s", rcfile, rc->message);
1324 g_clear_error(&rc);
1326 continue;
1329 do_cache_push(*p, str);
1330 g_free(str);
1331 continue;
1334 if (rc) {
1335 log_write("%s: key: %s", rcfile, rc->message);
1336 g_clear_error(&rc);
1337 continue;
1340 gpg_error_t ret;
1341 str = parse_rcfile_keyfile(*p, FALSE, &ret);
1343 if (!str)
1344 continue;
1346 do_cache_push(*p, str);
1347 gcry_free(str);
1350 g_strfreev(groups);
1351 return TRUE;
1354 static gboolean do_cache_push(const gchar *filename, const gchar *password)
1356 guchar md5file[16];
1357 gint timeout;
1358 const gchar *p = filename;
1359 struct client_crypto_s *crypto;
1360 gpg_error_t rc;
1361 guint hashlen = gcry_md_get_algo_dlen(GCRY_MD_SHA256);
1363 while (isspace(*p))
1364 p++;
1366 if (!*p)
1367 return FALSE;
1369 if (valid_filename(p) == FALSE) {
1370 log_write(N_("%s: Invalid characters in filename"), p);
1371 return FALSE;
1374 gcry_md_hash_buffer(GCRY_MD_MD5, md5file, p, strlen(p));
1376 if (access(p, R_OK|W_OK) != 0) {
1377 log_write("%s: %s", p, strerror(errno));
1378 return FALSE;
1381 crypto = init_client_crypto();
1383 if (!crypto)
1384 return FALSE;
1386 crypto->fh = read_file_header(filename, FALSE, &rc);
1388 if (!crypto->fh) {
1389 log_write("%s: %s", p, pwmd_strerror(rc));
1390 cleanup_crypto(&crypto);
1391 return FALSE;
1394 crypto->key = gcry_malloc(hashlen);
1396 if (!crypto->key) {
1397 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1398 cleanup_crypto(&crypto);
1399 return FALSE;
1402 log_write(N_("Adding '%s' to the file cache ..."), filename);
1404 if (crypto->fh->ver.fh2.iter <= 0ULL) {
1405 memset(crypto->key, '!', hashlen);
1406 goto try_decrypt;
1409 if (!password) {
1410 rc = get_password(p, crypto, md5file, crypto->key, PINENTRY_OPEN);
1412 if (rc) {
1413 send_error(NULL, rc);
1414 cleanup_crypto(&crypto);
1415 return FALSE;
1418 gcry_free(crypto->fh->doc);
1419 crypto->fh->doc = NULL;
1421 else
1422 gcry_md_hash_buffer(GCRY_MD_SHA256, crypto->key, password,
1423 strlen(password) ? strlen(password) : 1);
1425 try_decrypt:
1426 rc = try_xml_decrypt(NULL, crypto->key, crypto, NULL, NULL);
1428 if (rc) {
1429 log_write("%s: %s", filename, pwmd_strerror(rc));
1430 cleanup_crypto(&crypto);
1431 return FALSE;
1434 if (cache_update_key(md5file, crypto->key) == FALSE) {
1435 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1436 cleanup_crypto(&crypto);
1437 return FALSE;
1440 timeout = get_key_file_integer(p, "cache_timeout");
1441 cache_set_timeout(md5file, timeout);
1442 log_write(N_("File '%s' now cached"), filename);
1443 cleanup_crypto(&crypto);
1444 return TRUE;
1447 static void init_new_connection(gint fd)
1449 pth_attr_t attr;
1450 struct client_thread_s *new;
1451 gint n;
1453 new = g_malloc0(sizeof(struct client_thread_s));
1455 if (!new) {
1456 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1457 close(fd);
1458 return;
1461 MUTEX_LOCK(&cn_mutex);
1462 new->fd = fd;
1463 attr = pth_attr_new();
1464 pth_attr_init(attr);
1465 pth_attr_set(attr, PTH_ATTR_JOINABLE, FALSE);
1466 new->tid = pth_spawn(attr, client_thread, new);
1467 n = errno;
1468 pth_attr_destroy(attr);
1470 if (!new->tid) {
1471 g_free(new);
1472 close(fd);
1473 log_write("%s(%i): pth_spawn(): %s", __FILE__, __LINE__,
1474 _gpg_strerror(gpg_error_from_errno(n)));
1475 MUTEX_UNLOCK(&cn_mutex);
1476 return;
1479 cn_thread_list = g_slist_append(cn_thread_list, new);
1480 MUTEX_UNLOCK(&cn_mutex);
1481 log_write(N_("new connection: tid=%p, fd=%i"), new->tid, fd);
1484 static void *accept_thread(void *arg)
1486 gint sockfd = (gint)arg;
1487 pth_attr_t attr = pth_attr_of(pth_self());
1489 pth_attr_set(attr, PTH_ATTR_NAME, __FUNCTION__);
1490 pth_attr_destroy(attr);
1492 for (;;) {
1493 socklen_t slen = sizeof(struct sockaddr_un);
1494 struct sockaddr_un raddr;
1495 gint fd = -1;
1497 fd = pth_accept(sockfd, (struct sockaddr *)&raddr, &slen);
1499 if (fd == -1) {
1500 if (errno != EAGAIN) {
1501 if (!quit) // probably EBADF
1502 log_write("accept(): %s", strerror(errno));
1504 break;
1507 continue;
1510 init_new_connection(fd);
1513 /* Just in case accept() failed for some reason other than EBADF */
1514 quit = 1;
1515 pth_exit(PTH_CANCELED);
1516 return NULL;
1519 static void *adjust_cache_timer_thread(void *arg)
1521 pth_attr_t attr = pth_attr_of(pth_self());
1523 pth_attr_set(attr, PTH_ATTR_NAME, __FUNCTION__);
1524 pth_attr_destroy(attr);
1526 for (;;) {
1527 pth_sleep(1);
1528 CACHE_LOCK(NULL);
1529 cache_adjust_timer();
1530 CACHE_UNLOCK;
1533 return NULL;
1536 void cleanup_mutex_cb(void *arg)
1538 pth_mutex_t *m = arg;
1540 MUTEX_UNLOCK(m);
1543 void cleanup_ev_cb(void *arg)
1545 pth_event_t ev = arg;
1547 pth_event_free(ev, PTH_FREE_ALL);
1550 void cleanup_fd_cb(void *arg)
1552 gint fd = (gint)arg;
1554 close(fd);
1557 void cleanup_unlink_cb(void *arg)
1559 gchar *file = arg;
1561 unlink(file);
1564 void cleanup_cancel_cb(void *arg)
1566 pth_t tid = arg;
1568 pth_cancel(tid);
1571 static void *keepalive_thread(void *arg)
1573 gint to = (gint)arg;
1574 pth_attr_t attr = pth_attr_of(pth_self());
1576 pth_attr_set(attr, PTH_ATTR_NAME, __FUNCTION__);
1577 pth_attr_destroy(attr);
1579 for (;;) {
1580 pth_event_t ev = pth_event(PTH_EVENT_TIME, pth_timeout(to, 0));
1582 pth_cleanup_push(cleanup_ev_cb, ev);
1583 pth_wait(ev);
1584 send_status_all(STATUS_KEEPALIVE);
1585 pth_cleanup_pop(1);
1588 return NULL;
1591 static void startStopKeepAlive(gboolean term)
1593 gint n = get_key_file_integer("global", "keepalive");
1595 if (keepalive_tid)
1596 pth_cancel(keepalive_tid);
1598 keepalive_tid = NULL;
1600 if (term)
1601 return;
1603 if (n > 0) {
1604 gint e;
1605 pth_attr_t attr = pth_attr_new();
1607 pth_attr_init(attr);
1608 pth_attr_set(attr, PTH_ATTR_JOINABLE, FALSE);
1609 keepalive_tid = pth_spawn(attr, keepalive_thread, (void *)n);
1610 e = errno;
1611 pth_attr_destroy(attr);
1613 if (!keepalive_tid) {
1614 log_write("%s(%i): pth_spawn(): %s", __FILE__, __LINE__,
1615 _gpg_strerror(gpg_error_from_errno(e)));
1616 return;
1619 pth_yield(keepalive_tid);
1623 static gboolean waiting_for_exit()
1625 guint i, t;
1626 pth_event_t evs = NULL;
1628 MUTEX_LOCK(&cn_mutex);
1630 for (t = g_slist_length(cn_thread_list), i = 0; i < t; i++) {
1631 struct client_thread_s *thd = g_slist_nth_data(cn_thread_list, i);
1632 pth_event_t ev = pth_event(PTH_EVENT_TID|PTH_UNTIL_TID_DEAD, thd->tid);
1634 if (evs)
1635 evs = pth_event_concat(evs, ev, NULL);
1636 else
1637 evs = ev;
1640 MUTEX_UNLOCK(&cn_mutex);
1642 if (!evs)
1643 return FALSE;
1645 pth_wait(evs);
1646 MUTEX_LOCK(&cn_mutex);
1647 i = g_slist_length(cn_thread_list);
1648 MUTEX_UNLOCK(&cn_mutex);
1649 pth_event_free(evs, PTH_FREE_ALL);
1650 return i ? TRUE : FALSE;
1653 static void server_loop(gint sockfd, gchar **socketpath)
1655 pth_t accept_tid;
1656 guint n;
1657 sigset_t sigset;
1658 pth_attr_t attr;
1659 pth_t cache_timeout_tid;
1661 sigemptyset(&sigset);
1663 /* Termination */
1664 sigaddset(&sigset, SIGTERM);
1665 sigaddset(&sigset, SIGINT);
1667 /* Clears the file cache. */
1668 sigaddset(&sigset, SIGUSR1);
1670 /* Configuration file reloading. */
1671 sigaddset(&sigset, SIGHUP);
1673 /* Clears the cache and exits when something bad happens. */
1674 sigaddset(&sigset, SIGABRT);
1676 /* Ignored everywhere. When a client disconnects abnormally this signal
1677 * gets raised. It isn't needed though because client_thread() will check
1678 * for rcs even after the client disconnects. */
1679 signal(SIGPIPE, SIG_IGN);
1680 sigprocmask(SIG_BLOCK, &sigset, NULL);
1682 log_write(N_("%s started for user %s"), PACKAGE_STRING, g_get_user_name());
1683 log_write(N_("Listening on %s"), *socketpath);
1684 attr = pth_attr_new();
1685 pth_attr_init(attr);
1686 accept_tid = pth_spawn(attr, accept_thread, (void *)sockfd);
1688 if (!accept_tid) {
1689 log_write("%s(%i): pth_spawn(): %s", __FILE__, __LINE__,
1690 _gpg_strerror(gpg_error_from_errno(errno)));
1691 pth_attr_destroy(attr);
1692 goto done;
1695 pth_yield(accept_tid);
1696 startStopKeepAlive(FALSE);
1697 pth_attr_set(attr, PTH_ATTR_JOINABLE, FALSE);
1698 cache_timeout_tid = pth_spawn(attr, adjust_cache_timer_thread, NULL);
1700 if (!cache_timeout_tid) {
1701 log_write("%s(%i): pth_spawn(): %s", __FILE__, __LINE__,
1702 _gpg_strerror(gpg_error_from_errno(errno)));
1703 pth_attr_destroy(attr);
1704 goto done;
1707 pth_yield(cache_timeout_tid);
1708 pth_attr_destroy(attr);
1710 do {
1711 gint sig;
1713 pth_sigwait(&sigset, &sig);
1714 log_write(N_("caught signal %i (%s)"), sig, strsignal(sig));
1716 /* Caught a signal. */
1717 switch (sig) {
1718 case SIGHUP:
1719 reload_rcfile();
1720 break;
1721 case SIGABRT:
1722 cache_clear(NULL, 2);
1723 #ifndef MEM_DEBUG
1724 xpanic();
1725 #endif
1726 exit(EXIT_FAILURE);
1727 case SIGUSR1:
1728 CACHE_LOCK(NULL);
1729 log_write(N_("clearing file cache"));
1730 cache_clear(NULL, 2);
1731 CACHE_UNLOCK;
1732 break;
1733 default:
1734 quit = 1;
1735 break;
1737 } while (!quit);
1739 done:
1741 * We're out of the main server loop. This happens when a signal was sent
1742 * to terminate the daemon. We'll wait for all clients to disconnect
1743 * before exiting and ignore any following signals.
1745 shutdown(sockfd, SHUT_RDWR);
1746 close(sockfd);
1747 pth_cancel(accept_tid);
1748 pth_join(accept_tid, NULL);
1749 unlink(*socketpath);
1750 g_free(*socketpath);
1751 *socketpath = NULL;
1752 MUTEX_LOCK(&cn_mutex);
1753 n = g_slist_length(cn_thread_list);
1754 MUTEX_UNLOCK(&cn_mutex);
1756 if (n) {
1757 log_write(N_("waiting for all clients to disconnect"));
1759 do {
1760 MUTEX_LOCK(&cn_mutex);
1761 n = g_slist_length(cn_thread_list);
1762 MUTEX_UNLOCK(&cn_mutex);
1763 log_write(N_("%i clients remain"), n);
1764 } while (waiting_for_exit());
1767 startStopKeepAlive(TRUE);
1768 pth_cancel(cache_timeout_tid);
1769 cache_free();
1773 * Only called from pinentry_fork() in the child process.
1775 void free_client_list()
1777 gint i, t = g_slist_length(cn_thread_list);
1779 for (i = 0; i < t; i++) {
1780 struct client_thread_s *cn = g_slist_nth_data(cn_thread_list, i);
1782 free_client(cn->cl);
1785 cache_free();
1788 static guint pwmd_cipher_to_gcrypt(guint64 flags)
1790 if (flags & PWMD_CIPHER_AES128)
1791 return GCRY_CIPHER_AES128;
1792 else if (flags & PWMD_CIPHER_AES192)
1793 return GCRY_CIPHER_AES192;
1794 else if (flags & PWMD_CIPHER_AES256)
1795 return GCRY_CIPHER_AES256;
1796 else if (flags & PWMD_CIPHER_SERPENT128)
1797 return GCRY_CIPHER_SERPENT128;
1798 else if (flags & PWMD_CIPHER_SERPENT192)
1799 return GCRY_CIPHER_SERPENT192;
1800 else if (flags & PWMD_CIPHER_SERPENT256)
1801 return GCRY_CIPHER_SERPENT256;
1802 else if (flags & PWMD_CIPHER_CAMELLIA128)
1803 return GCRY_CIPHER_CAMELLIA128;
1804 else if (flags & PWMD_CIPHER_CAMELLIA192)
1805 return GCRY_CIPHER_CAMELLIA192;
1806 else if (flags & PWMD_CIPHER_CAMELLIA256)
1807 return GCRY_CIPHER_CAMELLIA256;
1808 else if (flags & PWMD_CIPHER_BLOWFISH)
1809 return GCRY_CIPHER_BLOWFISH;
1810 else if (flags & PWMD_CIPHER_3DES)
1811 return GCRY_CIPHER_3DES;
1812 else if (flags & PWMD_CIPHER_CAST5)
1813 return GCRY_CIPHER_CAST5;
1814 else if (flags & PWMD_CIPHER_TWOFISH)
1815 return GCRY_CIPHER_TWOFISH;
1816 else if (flags & PWMD_CIPHER_TWOFISH128)
1817 return GCRY_CIPHER_TWOFISH128;
1819 /* For backwards compatibility (no flags). */
1820 return GCRY_CIPHER_AES256;
1823 guint pwmd_cipher_str_to_cipher(const gchar *str)
1825 guint64 flags = 0;
1827 if (!g_strcasecmp(str, "aes128"))
1828 flags = PWMD_CIPHER_AES128;
1829 else if (!g_strcasecmp(str, "aes192"))
1830 flags = PWMD_CIPHER_AES192;
1831 else if (!g_strcasecmp(str, "aes256"))
1832 flags = PWMD_CIPHER_AES256;
1833 if (!g_strcasecmp(str, "serpent128"))
1834 flags = PWMD_CIPHER_SERPENT128;
1835 else if (!g_strcasecmp(str, "serpent192"))
1836 flags = PWMD_CIPHER_SERPENT192;
1837 else if (!g_strcasecmp(str, "serpent256"))
1838 flags = PWMD_CIPHER_SERPENT256;
1839 if (!g_strcasecmp(str, "camellia128"))
1840 flags = PWMD_CIPHER_CAMELLIA128;
1841 else if (!g_strcasecmp(str, "camellia192"))
1842 flags = PWMD_CIPHER_CAMELLIA192;
1843 else if (!g_strcasecmp(str, "camellia256"))
1844 flags = PWMD_CIPHER_CAMELLIA256;
1845 else if (!g_strcasecmp(str, "blowfish"))
1846 flags = PWMD_CIPHER_BLOWFISH;
1847 else if (!g_strcasecmp(str, "cast5"))
1848 flags = PWMD_CIPHER_CAST5;
1849 else if (!g_strcasecmp(str, "3des"))
1850 flags = PWMD_CIPHER_3DES;
1851 else if (!g_strcasecmp(str, "twofish256"))
1852 flags = PWMD_CIPHER_TWOFISH;
1853 else if (!g_strcasecmp(str, "twofish128"))
1854 flags = PWMD_CIPHER_TWOFISH128;
1856 return flags;
1859 /* To be called after read_file_header(). This sets the wanted algorithm from
1860 * .flags */
1861 gpg_error_t init_client_crypto2(const char *filename,
1862 struct client_crypto_s *crypto)
1864 gpg_error_t rc;
1865 guint algo;
1867 /* New file or conversion. */
1868 if (crypto->fh->v1)
1869 algo = pwmd_cipher_to_gcrypt(PWMD_CIPHER_AES256);
1870 else if (!crypto->fh->ver.fh2.flags) {
1871 gchar *tmp = get_key_file_string(filename ? filename : "global", "cipher");
1872 guint64 flags;
1874 flags = pwmd_cipher_str_to_cipher(tmp);
1875 g_free(tmp);
1876 algo = pwmd_cipher_to_gcrypt(flags);
1877 crypto->fh->ver.fh2.flags = flags;
1879 else
1880 algo = pwmd_cipher_to_gcrypt(crypto->fh->ver.fh2.flags);
1882 rc = gcry_cipher_algo_info(algo, GCRYCTL_TEST_ALGO, NULL, NULL);
1884 if (rc)
1885 return rc;
1887 rc = gcry_cipher_algo_info(algo, GCRYCTL_GET_KEYLEN, NULL,
1888 &crypto->keysize);
1890 if (rc)
1891 return rc;
1893 rc = gcry_cipher_algo_info(algo, GCRYCTL_GET_BLKLEN, NULL,
1894 &crypto->blocksize);
1896 if (rc)
1897 return rc;
1899 if (crypto->gh)
1900 gcry_cipher_close(crypto->gh);
1902 return gcry_cipher_open(&crypto->gh, algo, GCRY_CIPHER_MODE_CBC, 0);
1905 struct client_crypto_s *init_client_crypto()
1907 struct client_crypto_s *new = g_malloc0(sizeof(struct client_crypto_s));
1909 if (!new) {
1910 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1911 return NULL;
1914 return new;
1917 static gpg_error_t convert_file(const gchar *filename, const gchar *keyfile,
1918 const gchar *outfile)
1920 gpg_error_t rc;
1921 guchar md5file[gcry_md_get_algo_dlen(GCRY_MD_MD5)];
1922 guint64 iter;
1923 struct client_crypto_s *crypto = init_client_crypto();
1924 guint hashlen = gcry_md_get_algo_dlen(GCRY_MD_SHA256);
1926 if (!crypto)
1927 return GPG_ERR_ENOMEM;
1929 crypto->key = gcry_malloc(hashlen);
1931 if (!crypto->key) {
1932 cleanup_crypto(&crypto);
1933 return GPG_ERR_ENOMEM;
1936 log_write(N_("Converting version 1 data file '%s' to version 2 ..."),
1937 filename);
1938 crypto->fh = read_file_header(filename, TRUE, &rc);
1940 if (!crypto->fh)
1941 goto done;
1943 gcry_md_hash_buffer(GCRY_MD_MD5, md5file, filename, strlen(filename));
1945 /* The header in version 1 had a bug where the iterations were off-by-one.
1946 * So 0 iterations was really -1 in the header. This is fixed in v2 of the
1947 * header.
1949 if (crypto->fh->ver.fh1.iter != -1) {
1950 if (keyfile) {
1951 crypto->tkey = parse_rcfile_keyfile(keyfile, TRUE, &rc);
1953 if (!crypto->tkey)
1954 goto done;
1956 gcry_md_hash_buffer(GCRY_MD_SHA256, crypto->key, crypto->tkey,
1957 strlen(crypto->tkey) ? strlen(crypto->tkey) : 1);
1959 else {
1960 rc = get_password(filename, crypto, md5file, crypto->key,
1961 PINENTRY_OPEN);
1963 if (rc)
1964 goto done;
1968 rc = init_client_crypto2(NULL, crypto);
1970 if (rc)
1971 goto done;
1973 rc = try_xml_decrypt(NULL, crypto->key, crypto, &crypto->fh->doc,
1974 &crypto->fh->len);
1976 if (rc)
1977 goto done;
1979 rc = convert_xml((gchar **)&crypto->fh->doc, &crypto->fh->len);
1981 if (rc) {
1982 log_write("%s: %s", filename, pwmd_strerror(rc));
1983 goto done;
1986 crypto->fh->v1 = FALSE;
1988 iter = crypto->fh->ver.fh1.iter+1;
1989 memset(&crypto->fh->ver.fh2, 0, sizeof(crypto->fh->ver.fh2));
1990 /* Keep the iterations and key from the original file. */
1991 crypto->fh->ver.fh2.iter = iter;
1992 rc = export_common(outfile, crypto, crypto->fh->doc, crypto->fh->len);
1994 done:
1995 if (rc)
1996 send_error(NULL, rc);
1998 /* fh->doc is freed from do_xml_decrypt() via the inbuf pointer. */
1999 cleanup_crypto(&crypto);
2000 return rc;
2003 int main(int argc, char *argv[])
2005 gint opt;
2006 struct sockaddr_un addr;
2007 gchar buf[PATH_MAX];
2008 gchar *socketpath = NULL, *socketdir, *socketname = NULL;
2009 gchar *socketarg = NULL;
2010 gchar *datadir = NULL;
2011 gboolean n;
2012 gint x;
2013 gchar *p;
2014 gchar **cache_push = NULL;
2015 gchar *import = NULL, *keyfile = NULL;
2016 guint64 cmd_iterations = -1ULL;
2017 gint default_timeout;
2018 gboolean rcfile_spec = FALSE;
2019 gint estatus = EXIT_FAILURE;
2020 gint sockfd;
2021 gchar *outfile = NULL;
2022 GMemVTable mtable = { xmalloc, xrealloc, xfree, xcalloc, NULL, NULL };
2023 gint do_unlink = 1;
2024 gboolean secure = FALSE;
2025 gint background = 1;
2026 gchar *convert = NULL;
2027 gint show_version = 0;
2028 gint show_help = 0;
2029 #ifdef WITH_PINENTRY
2030 gboolean disable_pinentry = FALSE;
2031 #endif
2032 gint opt_index;
2033 const struct option long_opts[] = {
2034 #ifdef WITH_PINENTRY
2035 { "no-pinentry", 0, 0, 'P' },
2036 #endif
2037 { "outfile", 1, 0, 'o' },
2038 { "convert", 1, 0, 'C' },
2039 { "no-fork", 0, 0, 'n' },
2040 { "disable-dump", 0, 0, 'D' },
2041 { "import", 1, 0, 'I' },
2042 { "iterations", 1, 0, 'i' },
2043 { "key-file", 1, 0, 'k' },
2044 { "rcfile", 1, 0, 'f' },
2045 { "version", 0, &show_version, 1 },
2046 { "help", 0, &show_help, 1 },
2047 { 0, 0, 0, 0}
2049 #ifdef WITH_PINENTRY
2050 const gchar *optstring = "Po:C:nDI:i:k:f:";
2051 #else
2052 const gchar *optstring = "o:C:nDI:i:k:f:";
2053 #endif
2054 #ifndef DEBUG
2055 #ifdef HAVE_SETRLIMIT
2056 struct rlimit rl;
2058 rl.rlim_cur = rl.rlim_max = 0;
2060 if (setrlimit(RLIMIT_CORE, &rl) != 0)
2061 err(EXIT_FAILURE, "setrlimit()");
2062 #endif
2063 #endif
2065 #ifdef ENABLE_NLS
2066 setlocale(LC_ALL, "");
2067 bindtextdomain("pwmd", LOCALEDIR);
2068 textdomain("pwmd");
2069 #endif
2071 #ifndef MEM_DEBUG
2072 xmem_init();
2073 #endif
2074 setup_gcrypt();
2075 gpg_err_init();
2076 assuan_set_assuan_err_source(GPG_ERR_SOURCE_DEFAULT);
2077 g_mem_set_vtable(&mtable);
2078 assuan_set_malloc_hooks(xmalloc, xrealloc, xfree);
2079 xmlMemSetup(xfree, xmalloc, xrealloc, xstrdup);
2080 xmlInitMemory();
2081 xmlInitGlobals();
2082 xmlInitParser();
2083 xmlXPathInit();
2084 g_snprintf(buf, sizeof(buf), "%s/.pwmd", g_get_home_dir());
2086 if (mkdir(buf, 0700) == -1 && errno != EEXIST)
2087 err(EXIT_FAILURE, "%s", buf);
2089 g_snprintf(buf, sizeof(buf), "%s/.pwmd/data", g_get_home_dir());
2091 if (mkdir(buf, 0700) == -1 && errno != EEXIST)
2092 err(EXIT_FAILURE, "%s", buf);
2094 cmdline = TRUE;
2096 while ((opt = getopt_long(argc, argv, optstring, long_opts, &opt_index)) != -1) {
2097 switch (opt) {
2098 case 0:
2099 if (show_help)
2100 usage(argv[0], EXIT_SUCCESS);
2102 if (show_version) {
2103 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,
2104 PACKAGE_BUGREPORT,
2105 #ifdef WITH_PINENTRY
2106 "+WITH_PINENTRY\n"
2107 #else
2108 "-WITH_PINENTRY\n"
2109 #endif
2110 #ifdef WITH_QUALITY
2111 "+WITH_QUALITY\n"
2112 #else
2113 "-WITH_QUALITY\n"
2114 #endif
2115 #ifdef WITH_LIBACL
2116 "+WITH_LIBACL\n"
2117 #else
2118 "-WITH_LIBACL\n"
2119 #endif
2120 #ifdef DEBUG
2121 "+DEBUG\n"
2122 #else
2123 "-DEBUG\n"
2124 #endif
2125 #ifdef MEM_DEBUG
2126 "+MEM_DEBUG\n"
2127 #else
2128 "-MEM_DEBUG\n"
2129 #endif
2131 exit(EXIT_SUCCESS);
2133 break;
2134 #ifdef WITH_PINENTRY
2135 case 'P':
2136 disable_pinentry = TRUE;
2137 break;
2138 #endif
2139 case 'o':
2140 outfile = optarg;
2141 break;
2142 case 'C':
2143 convert = optarg;
2144 break;
2145 case 'n':
2146 background = 0;
2147 break;
2148 case 'D':
2149 secure = TRUE;
2150 break;
2151 case 'I':
2152 import = optarg;
2153 break;
2154 case 'i':
2155 cmd_iterations = strtoll(optarg, NULL, 10);
2156 break;
2157 case 'k':
2158 keyfile = optarg;
2159 break;
2160 case 'f':
2161 rcfile = g_strdup(optarg);
2162 rcfile_spec = TRUE;
2163 break;
2164 default:
2165 usage(argv[0], EXIT_FAILURE);
2169 pth_mutex_init(&cn_mutex);
2170 pth_mutex_init(&cache_mutex);
2171 pth_mutex_init(&rcfile_mutex);
2172 #ifdef WITH_PINENTRY
2173 pth_mutex_init(&pin_mutex);
2174 #endif
2176 if (!rcfile)
2177 rcfile = g_strdup_printf("%s/.pwmd/config", g_get_home_dir());
2179 if ((keyfileh = parse_rcfile(rcfile_spec)) == NULL)
2180 exit(EXIT_FAILURE);
2182 #ifdef WITH_PINENTRY
2183 if (disable_pinentry == TRUE)
2184 g_key_file_set_boolean(keyfileh, "global", "enable_pinentry", FALSE);
2185 #endif
2187 if (g_key_file_has_key(keyfileh, "global", "syslog", NULL) == TRUE)
2188 log_syslog = g_key_file_get_boolean(keyfileh, "global", "syslog", NULL);
2190 if (log_syslog == TRUE)
2191 openlog("pwmd", LOG_NDELAY|LOG_PID, LOG_DAEMON);
2193 if (g_key_file_has_key(keyfileh, "global", "priority", NULL)) {
2194 x = g_key_file_get_integer(keyfileh, "global", "priority", NULL);
2195 errno = 0;
2197 if (setpriority(PRIO_PROCESS, 0, x) == -1) {
2198 log_write("setpriority(): %s", strerror(errno));
2199 goto do_exit;
2203 #ifdef HAVE_MLOCKALL
2204 if (disable_mlock == FALSE && mlockall(MCL_FUTURE) == -1) {
2205 log_write("mlockall(): %s", strerror(errno));
2206 goto do_exit;
2208 #endif
2210 if (convert) {
2211 if (!outfile)
2212 usage(argv[0], EXIT_FAILURE);
2214 opt = convert_file(convert, keyfile, outfile);
2215 g_key_file_free(keyfileh);
2216 g_free(rcfile);
2217 exit(opt ? EXIT_FAILURE : EXIT_SUCCESS);
2220 if (import) {
2221 if (!outfile)
2222 usage(argv[0], EXIT_FAILURE);
2224 if (cmd_iterations == -1ULL)
2225 cmd_iterations = (guint64)get_key_file_double("global", "iterations");
2227 opt = xml_import(import, outfile, keyfile, cmd_iterations);
2228 g_key_file_free(keyfileh);
2229 g_free(rcfile);
2230 exit(opt == FALSE ? EXIT_FAILURE : EXIT_SUCCESS);
2233 g_key_file_set_list_separator(keyfileh, ',');
2235 if ((p = g_key_file_get_string(keyfileh, "global", "socket_path", NULL)) == NULL)
2236 errx(EXIT_FAILURE, N_("%s: socket_path not defined"), rcfile);
2238 socketarg = expand_homedir(p);
2239 g_free(p);
2241 if ((p = g_key_file_get_string(keyfileh, "global", "data_directory", NULL)) == NULL)
2242 errx(EXIT_FAILURE, N_("%s: data_directory not defined"), rcfile);
2244 datadir = expand_homedir(p);
2245 g_free(p);
2247 if (secure == FALSE && g_key_file_has_key(keyfileh, "global", "disable_list_and_dump", NULL) == TRUE) {
2248 n = g_key_file_get_boolean(keyfileh, "global", "disable_list_and_dump", NULL);
2249 disable_list_and_dump = n;
2251 else
2252 disable_list_and_dump = secure;
2254 if (g_key_file_has_key(keyfileh, "global", "cache_timeout", NULL) == TRUE)
2255 default_timeout = g_key_file_get_integer(keyfileh, "global", "cache_timeout", NULL);
2256 else
2257 default_timeout = -1;
2259 setup_logging(keyfileh);
2261 if (g_key_file_has_key(keyfileh, "global", "cache_push", NULL) == TRUE)
2262 cache_push = g_key_file_get_string_list(keyfileh, "global", "cache_push", NULL, NULL);
2264 if (argc != optind) {
2265 for (; optind < argc; optind++) {
2266 if (strv_printf(&cache_push, "%s", argv[optind]) == FALSE)
2267 errx(EXIT_FAILURE, "%s", strerror(ENOMEM));
2271 if (strchr(socketarg, '/') == NULL) {
2272 socketdir = g_get_current_dir();
2273 socketname = g_strdup(socketarg);
2274 socketpath = g_strdup_printf("%s/%s", socketdir, socketname);
2276 else {
2277 socketname = g_strdup(strrchr(socketarg, '/'));
2278 socketname++;
2279 socketarg[strlen(socketarg) - strlen(socketname) -1] = 0;
2280 socketdir = g_strdup(socketarg);
2281 socketpath = g_strdup_printf("%s/%s", socketdir, socketname);
2284 if (chdir(datadir)) {
2285 log_write("%s: %s", datadir, strerror(errno));
2286 unlink(socketpath);
2287 goto do_exit;
2290 if (parse_rcfile_keys() == FALSE)
2291 goto do_exit;
2293 clear_rcfile_keys();
2296 * Set the cache entry for a file. Prompts for the password.
2298 if (cache_push) {
2299 for (opt = 0; cache_push[opt]; opt++)
2300 do_cache_push(cache_push[opt], NULL);
2302 g_strfreev(cache_push);
2303 log_write(background ? N_("Done. Daemonizing...") : N_("Done. Waiting for connections..."));
2307 * bind() doesn't like the full pathname of the socket or any non alphanum
2308 * characters so change to the directory where the socket is wanted then
2309 * create it then change to datadir.
2311 if (chdir(socketdir)) {
2312 log_write("%s: %s", socketdir, strerror(errno));
2313 goto do_exit;
2316 g_free(socketdir);
2318 if ((sockfd = socket(PF_UNIX, SOCK_STREAM, 0)) == -1) {
2319 log_write("socket(): %s", strerror(errno));
2320 goto do_exit;
2323 addr.sun_family = AF_UNIX;
2324 g_snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", socketname);
2326 if (bind(sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr)) == -1) {
2327 log_write("bind(): %s", strerror(errno));
2329 if (errno == EADDRINUSE)
2330 log_write(N_("Either there is another pwmd running or '%s' is a \n"
2331 "stale socket. Please remove it manually."), socketpath);
2333 do_unlink = 0;
2334 goto do_exit;
2337 if (g_key_file_has_key(keyfileh, "global", "socket_perms", NULL) == TRUE) {
2338 gchar *t = g_key_file_get_string(keyfileh, "global", "socket_perms", NULL);
2339 mode_t mode = strtol(t, NULL, 8);
2340 mode_t mask = umask(0);
2342 g_free(t);
2344 if (chmod(socketname, mode) == -1) {
2345 log_write("%s: %s", socketname, strerror(errno));
2346 close(sockfd);
2347 unlink(socketpath);
2348 umask(mask);
2349 goto do_exit;
2352 umask(mask);
2355 g_free(--socketname);
2357 if (chdir(datadir)) {
2358 log_write("%s: %s", datadir, strerror(errno));
2359 close(sockfd);
2360 unlink(socketpath);
2361 goto do_exit;
2364 g_free(datadir);
2366 if (listen(sockfd, 0) == -1) {
2367 log_write("listen(): %s", strerror(errno));
2368 goto do_exit;
2371 cmdline = FALSE;
2373 if (background) {
2374 switch (fork()) {
2375 case -1:
2376 log_write("fork(): %s", strerror(errno));
2377 goto do_exit;
2378 case 0:
2379 close(0);
2380 close(1);
2381 close(2);
2382 setsid();
2383 break;
2384 default:
2385 exit(EXIT_SUCCESS);
2389 server_loop(sockfd, &socketpath);
2390 estatus = EXIT_SUCCESS;
2392 do_exit:
2393 if (socketpath && do_unlink) {
2394 unlink(socketpath);
2395 g_free(socketpath);
2398 g_key_file_free(keyfileh);
2399 g_free(rcfile);
2400 xmlCleanupParser();
2401 xmlCleanupGlobals();
2403 if (estatus == EXIT_SUCCESS)
2404 log_write(N_("pwmd exiting normally"));
2406 #if defined(DEBUG) && !defined(MEM_DEBUG)
2407 xdump();
2408 #endif
2409 exit(estatus);