If there's an error while sending the KEEPALIVE status message, raise
[pwmd.git] / src / pwmd.c
bloba0db5e588a59d6efcce9174bb4abd2a5187c7d68
1 /* vim:tw=78:ts=8:sw=4:set ft=c: */
2 /*
3 Copyright (C) 2006-2007 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 02111-1307 USA
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <unistd.h>
22 #include <err.h>
23 #include <errno.h>
24 #include <ctype.h>
25 #include <string.h>
26 #include <sys/un.h>
27 #include <signal.h>
28 #include <stdarg.h>
29 #include <string.h>
30 #include <sys/wait.h>
31 #include <fcntl.h>
32 #include <pwd.h>
33 #include <glib.h>
34 #include <glib/gprintf.h>
35 #include <gcrypt.h>
36 #include <sys/mman.h>
37 #include <termios.h>
38 #include <assert.h>
39 #include <syslog.h>
41 #ifdef HAVE_CONFIG_H
42 #include <config.h>
43 #endif
45 #ifdef HAVE_SETRLIMIT
46 #include <sys/time.h>
47 #include <sys/resource.h>
48 #endif
50 #ifdef HAVE_ZLIB_H
51 #include <zlib.h>
52 #endif
54 #ifndef MEM_DEBUG
55 #include "mem.h"
56 #endif
58 #include "xml.h"
59 #include "common.h"
60 #include "commands.h"
61 #include "pwmd_error.h"
62 #include "cache.h"
63 #include "pwmd.h"
65 static void clear_rcfile_key()
67 gsize n;
68 gchar **groups;
69 gchar **p;
71 groups = g_key_file_get_groups(keyfileh, &n);
73 for (p = groups; *p; p++) {
74 GError *error = NULL;
76 if (g_key_file_has_key(keyfileh, *p, "key", &error) == TRUE)
77 g_key_file_set_string(keyfileh, *p, "key", "");
80 g_strfreev(groups);
83 static void reload_rcfile()
85 log_write(N_("reloading configuration file '%s'"), rcfile);
86 g_key_file_free(keyfileh);
87 keyfileh = parse_rcfile(0);
88 clear_rcfile_key();
91 gpg_error_t send_syserror(assuan_context_t ctx, gint e)
93 gpg_error_t n = gpg_error_from_errno(e);
95 return assuan_process_done(ctx, assuan_set_error(ctx, n, gpg_strerror(n)));
98 gpg_error_t send_error(assuan_context_t ctx, gpg_error_t e)
100 gpg_err_code_t n = gpg_err_code(e);
101 gpg_error_t code = gpg_err_make(GPG_ERR_SOURCE_USER_1, n);
103 if (!e)
104 return assuan_process_done(ctx, 0);
106 if (!ctx) {
107 log_write("%s\n", pwmd_strerror(e));
108 return e;
111 if (n == EPWMD_LIBXML_ERROR) {
112 xmlErrorPtr xml_error = xmlGetLastError();
113 return assuan_process_done(ctx, assuan_set_error(ctx, code, xml_error->message));
116 return assuan_process_done(ctx, assuan_set_error(ctx, code, pwmd_strerror(e)));
119 void log_write(const gchar *fmt, ...)
121 gchar *args, *line;
122 va_list ap;
123 struct tm *tm;
124 time_t now;
125 gchar tbuf[21];
126 gint fd = -1;
128 if ((!logfile && !isatty(STDERR_FILENO) && log_syslog == FALSE) || !fmt)
129 return;
131 if (logfile) {
132 if ((fd = open(logfile, O_WRONLY|O_CREAT|O_APPEND, 0600)) == -1) {
133 warn(N_("logfile"));
134 return;
138 va_start(ap, fmt);
140 if (g_vasprintf(&args, fmt, ap) == -1) {
141 va_end(ap);
142 return;
145 if (log_syslog == TRUE)
146 syslog(LOG_INFO, "%s", args);
148 va_end(ap);
149 time(&now);
150 tm = localtime(&now);
151 strftime(tbuf, sizeof(tbuf), "%b %d %Y %H:%M:%S ", tm);
152 tbuf[sizeof(tbuf) - 1] = 0;
153 line = g_strdup_printf("%s %i %s\n", tbuf, getpid(), args);
155 if (!line) {
156 if (logfile)
157 close(fd);
159 g_free(args);
160 return;
163 if (logfile) {
164 write(fd, line, strlen(line));
165 fsync(fd);
166 close(fd);
169 if (isatty(STDERR_FILENO)) {
170 fprintf(stderr, "%s", line);
171 fflush(stderr);
174 g_free(line);
175 g_free(args);
178 static void usage(gchar *pn)
180 g_printf(N_(
181 "Usage: %s [-hvDb] [-f <rcfile>] [-I <filename>] [file1] [...]\n"
182 " -b run as a background process\n"
183 " -f load the specified rcfile (~/.pwmd/config)\n"
184 " -I import an XML file and write the encrypted data to stdout\n"
185 " -D disable use of the LIST and DUMP commands\n"
186 " -v version\n"
187 " -h this help text\n"
188 ), pn);
189 exit(EXIT_SUCCESS);
192 #ifndef MEM_DEBUG
193 static int gcry_SecureCheck(const void *ptr)
195 return 1;
197 #endif
199 static void setup_gcrypt()
201 gcry_check_version(NULL);
203 #ifndef MEM_DEBUG
204 gcry_set_allocation_handler(xmalloc, xmalloc, gcry_SecureCheck, xrealloc,
205 xfree);
206 #endif
208 if (gcry_cipher_algo_info(GCRY_CIPHER_AES256, GCRYCTL_TEST_ALGO, NULL,
209 NULL) != 0)
210 errx(EXIT_FAILURE, N_("Required AES cipher not supported by libgcrypt."));
212 gcry_cipher_algo_info(GCRY_CIPHER_AES256, GCRYCTL_GET_KEYLEN, NULL, &gcrykeysize);
213 gcry_cipher_algo_info(GCRY_CIPHER_AES256, GCRYCTL_GET_BLKLEN, NULL, &gcryblocksize);
216 static assuan_context_t new_connection(gint fd)
218 gpg_error_t rc;
219 gchar ver[ASSUAN_LINELENGTH];
220 assuan_context_t ctx;
222 rc = assuan_init_socket_server_ext(&ctx, fd, 2);
224 if (rc)
225 goto fail;
227 g_snprintf(ver, sizeof(ver), "%s", PACKAGE_STRING);
228 assuan_set_hello_line(ctx, ver);
229 assuan_register_post_cmd_notify(ctx, command_finalize);
230 rc = register_commands(ctx);
232 if (rc)
233 goto fail;
235 rc = assuan_accept(ctx);
237 if (rc)
238 goto fail;
240 return ctx;
242 fail:
243 assuan_deinit_server(ctx);
244 log_write("%s", gpg_strerror(rc));
245 return NULL;
248 void send_cache_status_all()
250 guint i, t;
252 for (t = g_slist_length(cn_thread_list), i = 0; i < t; i++) {
253 struct client_thread_s *cn = g_slist_nth_data(cn_thread_list, i);
255 if (cn->tid == pth_self()) {
256 send_cache_status(cn->cl->ctx);
257 continue;
260 pth_raise(cn->tid, SIGUSR2);
264 static void *keepalive_thread(void *arg)
266 struct client_thread_s *thd = arg;
267 gint k = get_key_file_integer("default", "keepalive");
268 pth_event_t ev;
269 sigset_t set;
271 if (k <= 0)
272 pth_exit(NULL);
274 ev = pth_event(PTH_EVENT_TIME, pth_timeout(k, 0));
275 sigemptyset(&set);
276 sigaddset(&set, SIGALRM);
278 for (;;) {
279 gint sig = 0;
280 gpg_error_t error;
282 pth_sigwait_ev(&set, &sig, ev);
283 pth_event_free(ev, PTH_FREE_THIS);
284 ev = pth_event(PTH_EVENT_TIME, pth_timeout(k, 0));
286 if (sig)
287 break;
289 error = assuan_write_status(thd->cl->ctx, "KEEPALIVE", NULL);
291 if (error) {
292 pth_raise(thd->tid, SIGQUIT);
293 break;
297 pth_event_free(ev, PTH_FREE_THIS);
298 return NULL;
302 * Called every time a connection is made via pth_spawn(). This is the thread
303 * entry point.
305 static void *client_thread(void *data)
307 struct client_thread_s *thd = data;
308 gint fd = thd->fd;
309 pth_event_t ev;
310 struct client_s *cl = g_malloc0(sizeof(struct client_s));
311 sigset_t set;
313 if (!cl) {
314 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
315 goto fail;
318 thd->cl = cl;
321 * This is a "child" thread. Don't catch any signals. Let the master
322 * thread take care of signals in server_loop().
324 sigemptyset(&set);
325 sigaddset(&set, SIGINT);
326 sigaddset(&set, SIGUSR1);
327 sigaddset(&set, SIGHUP);
328 pth_sigmask(SIG_BLOCK, &set, NULL);
329 sigemptyset(&set);
330 sigaddset(&set, SIGUSR2);
331 sigaddset(&set, SIGQUIT);
333 cl->ctx = new_connection(fd);
334 cl->fd = fd;
336 if (!cl->ctx)
337 goto fail;
339 assuan_set_pointer(cl->ctx, cl);
341 #ifdef HAVE_MLOCKALL
342 if (disable_mlock == FALSE && mlockall(MCL_FUTURE) == -1) {
343 log_write("mlockall(): %s", strerror(errno));
344 goto fail;
346 #endif
348 send_cache_status(cl->ctx);
349 ev = pth_event(PTH_EVENT_FD|PTH_UNTIL_FD_READABLE, cl->fd);
350 thd->keepalive_tid = pth_spawn(NULL, keepalive_thread, thd);
352 for (;;) {
353 gpg_error_t rc;
354 gint sig = 0;
356 pth_sigwait_ev(&set, &sig, ev);
358 if (sig > 0) {
359 switch (sig) {
360 case SIGUSR2:
361 send_cache_status(cl->ctx);
362 continue;
363 case SIGQUIT:
364 goto done;
365 default:
366 break;
370 if (pth_event_occurred(ev)) {
371 rc = assuan_process_next(cl->ctx);
373 if (rc) {
374 cl->inquire = INQUIRE_NONE;
376 if (gpg_err_code(rc) == GPG_ERR_EOF)
377 goto done;
379 log_write("assuan_process_next(): %s", gpg_strerror(rc));
380 rc = assuan_process_done(cl->ctx, rc);
382 if (rc) {
383 log_write("assuan_process_done(): %s", gpg_strerror(rc));
384 goto done;
387 else {
388 if (cl->inquire == INQUIRE_OK || cl->inquire_error) {
389 /* Set from store_command_finalize(). */
390 cl->inquire = INQUIRE_NONE;
391 rc = assuan_process_done(cl->ctx, gpg_err_make(GPG_ERR_SOURCE_ANY, cl->inquire_error));
392 cl->inquire_error = 0;
394 if (rc) {
395 log_write("assuan_process_done(): %s", gpg_strerror(rc));
396 goto done;
404 * Client cleanup (including XML data) is done in remove_connection() from
405 * the cleanup thread.
407 done:
408 pth_event_free(ev, PTH_FREE_ALL);
410 fail:
411 pth_exit(NULL);
412 return NULL;
416 * Make sure all settings are set to either the specified setting or a
417 * default.
419 static void set_rcfile_defaults(GKeyFile *kf)
421 gchar buf[PATH_MAX];
423 if (g_key_file_has_key(kf, "default", "socket_path", NULL) == FALSE) {
424 snprintf(buf, sizeof(buf), "~/.pwmd/socket");
425 g_key_file_set_string(kf, "default", "socket_path", buf);
428 if (g_key_file_has_key(kf, "default", "data_directory", NULL) == FALSE) {
429 snprintf(buf, sizeof(buf), "~/.pwmd/data");
430 g_key_file_set_string(kf, "default", "data_directory", buf);
433 if (g_key_file_has_key(kf, "default", "log_path", NULL) == FALSE) {
434 snprintf(buf, sizeof(buf), "~/.pwmd/log");
435 g_key_file_set_string(kf, "default", "log_path", buf);
438 if (g_key_file_has_key(kf, "default", "enable_logging", NULL) == FALSE)
439 g_key_file_set_boolean(kf, "default", "enable_logging", FALSE);
441 if (g_key_file_has_key(kf, "default", "cache_size", NULL) == FALSE)
442 g_key_file_set_integer(kf, "default", "cache_size", cache_size);
444 #ifdef HAVE_MLOCKALL
445 if (g_key_file_has_key(kf, "default", "disable_mlockall", NULL) == FALSE)
446 g_key_file_set_boolean(kf, "default", "disable_mlockall", TRUE);
447 #endif
449 if (g_key_file_has_key(kf, "default", "cache_timeout", NULL) == FALSE)
450 g_key_file_set_integer(kf, "default", "cache_timeout", -1);
452 if (g_key_file_has_key(kf, "default", "iterations", NULL) == FALSE)
453 g_key_file_set_integer(kf, "default", "iterations", 0);
455 if (g_key_file_has_key(kf, "default", "disable_list_and_dump", NULL) == FALSE)
456 g_key_file_set_boolean(kf, "default", "disable_list_and_dump", FALSE);
458 if (g_key_file_has_key(kf, "default", "iteration_progress", NULL) == FALSE)
459 g_key_file_set_integer(kf, "default", "iteration_progress", 0);
461 if (g_key_file_has_key(kf, "default", "compression_level", NULL) == FALSE)
462 g_key_file_set_integer(kf, "default", "compression_level", 6);
464 if (g_key_file_has_key(kf, "default", "recursion_depth", NULL) == FALSE)
465 g_key_file_set_integer(kf, "default", "recursion_depth", DEFAULT_RECURSION_DEPTH);
467 if (g_key_file_has_key(kf, "default", "zlib_bufsize", NULL) == FALSE)
468 g_key_file_set_integer(kf, "default", "zlib_bufsize", DEFAULT_ZLIB_BUFSIZE);
470 zlib_bufsize = g_key_file_get_integer(kf, "default", "zlib_bufsize", NULL);
472 max_recursion_depth = g_key_file_get_integer(kf, "default", "recursion_depth", NULL);
473 disable_list_and_dump = g_key_file_get_boolean(kf, "default", "disable_list_and_dump", NULL);
475 #ifdef HAVE_MLOCKALL
476 disable_mlock = g_key_file_get_boolean(kf, "default", "disable_mlockall", NULL);
477 #endif
479 if (g_key_file_has_key(kf, "default", "syslog", NULL) == FALSE)
480 g_key_file_set_boolean(kf, "default", "syslog", FALSE);
482 if (g_key_file_has_key(kf, "default", "keepalive", NULL) == FALSE)
483 g_key_file_set_integer(kf, "default", "keepalive", 5);
486 static GKeyFile *parse_rcfile(int cmdline)
488 GKeyFile *kf = g_key_file_new();
489 GError *error = NULL;
491 if (g_key_file_load_from_file(kf, rcfile, G_KEY_FILE_NONE, &error) == FALSE) {
492 log_write("%s: %s", rcfile, error->message);
494 if (cmdline)
495 exit(EXIT_FAILURE);
497 if (error->code == G_FILE_ERROR_NOENT) {
498 g_clear_error(&error);
499 set_rcfile_defaults(kf);
500 return kf;
503 g_clear_error(&error);
504 return NULL;
506 else
507 set_rcfile_defaults(kf);
509 return kf;
512 static gchar *get_password(const gchar *prompt)
514 gchar buf[LINE_MAX], *p;
515 struct termios told, tnew;
516 gchar *key;
518 if (tcgetattr(STDIN_FILENO, &told) == -1)
519 err(EXIT_FAILURE, "tcgetattr()");
521 memcpy(&tnew, &told, sizeof(struct termios));
522 tnew.c_lflag &= ~(ECHO);
523 tnew.c_lflag |= ICANON|ECHONL;
525 if (tcsetattr(STDIN_FILENO, TCSANOW, &tnew) == -1) {
526 tcsetattr(STDIN_FILENO, TCSANOW, &told);
527 err(EXIT_FAILURE, "tcsetattr()");
530 fprintf(stderr, "%s", prompt);
532 if ((p = fgets(buf, sizeof(buf), stdin)) == NULL) {
533 tcsetattr(STDIN_FILENO, TCSANOW, &told);
534 return NULL;
537 tcsetattr(STDIN_FILENO, TCSANOW, &told);
538 p[strlen(p) - 1] = 0;
540 if (!p || !*p)
541 return NULL;
543 key = gcry_malloc(strlen(p) + 1);
544 sprintf(key, "%s", p);
545 memset(&buf, 0, sizeof(buf));
546 return key;
549 static gboolean do_try_xml_decrypt(const gchar *filename, guchar *key)
551 int fd;
552 struct stat st;
553 gpg_error_t error;
555 if ((fd = open_file(filename, &st)) == -1) {
556 warn("%s", filename);
557 return FALSE;
560 if (st.st_size == 0) {
561 warnx(N_("%s: skipping empty file"), filename);
562 close(fd);
563 return FALSE;
566 error = try_xml_decrypt(NULL, fd, st, key);
567 close(fd);
568 return error ? FALSE : TRUE;
571 static gboolean get_input(const gchar *filename, guchar *key)
573 gint try = 0;
574 gchar *password;
575 gchar *prompt;
577 prompt = g_strdup_printf(N_("Password for '%s': "), filename);
579 again:
580 if ((password = get_password(prompt)) == NULL) {
581 warnx(N_("%s: skipping file"), filename);
582 g_free(prompt);
583 return FALSE;
586 gcry_md_hash_buffer(GCRY_MD_SHA256, key, password, strlen(password));
587 gcry_free(password);
589 if (do_try_xml_decrypt(filename, key) == FALSE) {
590 if (try++ == 2) {
591 warnx(N_("%s: invalid password, skipping"), filename);
592 g_free(prompt);
593 return FALSE;
595 else {
596 warnx(N_("%s: invalid password"), filename);
597 goto again;
601 g_free(prompt);
602 return TRUE;
605 static gboolean xml_import(const gchar *filename, gint iter)
607 xmlDocPtr doc;
608 gint fd;
609 struct stat st;
610 gint len;
611 xmlChar *xmlbuf;
612 xmlChar *xml;
613 gchar *key = NULL;
614 gchar *key2 = NULL;
615 guchar shakey[gcrykeysize];
616 gcry_cipher_hd_t gh;
617 gpg_error_t error;
618 gint level;
619 glong outsize;
620 gpointer outbuf;
621 gint zerror;
623 if (stat(filename, &st) == -1) {
624 warn("%s", filename);
625 return FALSE;
628 if ((gcryerrno = gcry_cipher_open(&gh, GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CBC, 0))) {
629 send_error(NULL, gcryerrno);
630 gcry_cipher_close(gh);
631 log_write("%s(%i): %s", __FUNCTION__, __LINE__, gcry_strerror(gcryerrno));
632 return FALSE;
635 if ((key = get_password(N_("New password: "))) == NULL) {
636 fprintf(stderr, "%s\n", N_("Invalid password."));
637 gcry_cipher_close(gh);
638 return FALSE;
641 if ((key2 = get_password(N_("Verify password: "))) == NULL) {
642 fprintf(stderr, "%s\n", N_("Passwords do not match."));
643 gcry_free(key);
644 gcry_cipher_close(gh);
645 return FALSE;
648 if (g_utf8_collate(key, key2) != 0) {
649 fprintf(stderr, "%s\n", N_("Passwords do not match."));
650 gcry_free(key);
651 gcry_free(key2);
652 gcry_cipher_close(gh);
653 return FALSE;
656 gcry_free(key2);
658 if ((fd = open(filename, O_RDONLY)) == -1) {
659 gcry_free(key);
660 warn("%s", filename);
661 gcry_cipher_close(gh);
662 return FALSE;
665 if ((xmlbuf = gcry_malloc(st.st_size+1)) == NULL) {
666 gcry_free(key);
667 close(fd);
668 log_write("%s", strerror(ENOMEM));
669 gcry_cipher_close(gh);
670 return FALSE;
673 if (read(fd, xmlbuf, st.st_size) == -1) {
674 error = errno;
675 close(fd);
676 gcry_free(key);
677 gcry_cipher_close(gh);
678 errno = error;
679 err(EXIT_FAILURE, "read()");
682 close(fd);
683 xmlbuf[st.st_size] = 0;
686 * Make sure the document validates.
688 if ((doc = xmlReadDoc(xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS)) == NULL) {
689 log_write("xmlReadDoc()");
690 close(fd);
691 gcry_free(key);
692 gcry_free(xmlbuf);
693 gcry_cipher_close(gh);
694 return FALSE;
697 gcry_free(xmlbuf);
698 xmlDocDumpMemory(doc, &xml, &len);
699 xmlFreeDoc(doc);
701 level = get_key_file_integer(filename, "compression_level");
703 if (level < 0)
704 level = 0;
706 if (do_compress(NULL, level, xml, len, &outbuf, &outsize, &zerror) == FALSE) {
707 memset(shakey, 0, sizeof(shakey));
708 gcry_free(xml);
710 if (zerror == Z_MEM_ERROR)
711 warnx("%s", strerror(ENOMEM));
712 else
713 warnx("do_compress() failed");
715 gcry_cipher_close(gh);
716 return FALSE;
718 else {
719 gcry_free(xml);
720 xml = outbuf;
721 len = outsize;
724 gcry_md_hash_buffer(GCRY_MD_SHA256, shakey, key, strlen(key));
725 gcry_free(key);
726 error = do_xml_encrypt(NULL, gh, NULL, xml, len, shakey, iter);
727 gcry_cipher_close(gh);
729 if (error) {
730 memset(shakey, 0, sizeof(shakey));
731 warnx("%s", gpg_strerror(error));
732 return FALSE;
735 memset(shakey, 0, sizeof(shakey));
736 return TRUE;
739 gchar *get_key_file_string(const gchar *section, const gchar *what)
741 gchar *val = NULL;
742 GError *gerror = NULL;
744 if (g_key_file_has_key(keyfileh, section, what, NULL) == TRUE) {
745 val = g_key_file_get_string(keyfileh, section, what, &gerror);
747 if (gerror) {
748 log_write("%s(%i): %s", __FILE__, __LINE__, gerror->message);
749 g_clear_error(&gerror);
752 else {
753 if (g_key_file_has_key(keyfileh, "default", what, NULL) == TRUE) {
754 val = g_key_file_get_string(keyfileh, "default", what, &gerror);
756 if (gerror) {
757 log_write("%s(%i): %s", __FILE__, __LINE__, gerror->message);
758 g_clear_error(&gerror);
763 return val;
766 gint get_key_file_integer(const gchar *section, const gchar *what)
768 gint val = -1;
769 GError *gerror = NULL;
771 if (g_key_file_has_key(keyfileh, section, what, NULL) == TRUE) {
772 val = g_key_file_get_integer(keyfileh, section, what, &gerror);
774 if (gerror) {
775 log_write("%s(%i): %s", __FILE__, __LINE__, gerror->message);
776 g_clear_error(&gerror);
779 else {
780 if (g_key_file_has_key(keyfileh, "default", what, NULL) == TRUE) {
781 val = g_key_file_get_integer(keyfileh, "default", what, &gerror);
783 if (gerror) {
784 log_write("%s(%i): %s", __FILE__, __LINE__, gerror->message);
785 g_clear_error(&gerror);
790 return val;
793 gboolean get_key_file_boolean(const gchar *section, const gchar *what)
795 gboolean val = FALSE;
796 GError *gerror = NULL;
798 if (g_key_file_has_key(keyfileh, section, what, NULL) == TRUE) {
799 val = g_key_file_get_boolean(keyfileh, section, what, &gerror);
801 if (gerror) {
802 log_write("%s(%i): %s", __FILE__, __LINE__, gerror->message);
803 g_clear_error(&gerror);
806 else {
807 if (g_key_file_has_key(keyfileh, "default", what, NULL) == TRUE) {
808 val = g_key_file_get_boolean(keyfileh, "default", what, &gerror);
810 if (gerror) {
811 log_write("%s(%i): %s", __FILE__, __LINE__, gerror->message);
812 g_clear_error(&gerror);
817 return val;
820 gchar *expand_homedir(gchar *str)
822 gchar *p = str;
824 if (*p++ == '~')
825 return g_strdup_printf("%s%s", g_get_home_dir(), p);
827 return g_strdup(str);
830 static gchar *_getline(const gchar *file)
832 FILE *fp;
833 gchar buf[LINE_MAX], *p;
834 gchar *str = NULL;
836 if ((fp = fopen(file, "r")) == NULL) {
837 warn("%s", file);
838 return NULL;
841 if ((p = fgets(buf, sizeof(buf), fp)) == NULL) {
842 warnx(N_("%s: empty file?"), file);
843 return NULL;
846 fclose(fp);
848 if (buf[strlen(buf) - 1] == '\n')
849 buf[strlen(buf) - 1] = 0;
851 str = gcry_malloc(strlen(p) + 1);
852 memcpy(str, p, strlen(p));
853 str[strlen(p)] = 0;
854 memset(&buf, 0, sizeof(buf));
855 return str;
858 static gboolean parse_keyfile_key()
860 gsize n;
861 gchar **groups;
862 gchar **p;
863 gchar *str;
865 groups = g_key_file_get_groups(keyfileh, &n);
867 for (p = groups; *p; p++) {
868 GError *error = NULL;
870 if (g_key_file_has_key(keyfileh, *p, "key", &error) == TRUE) {
871 str = g_key_file_get_string(keyfileh, *p, "key", &error);
873 if (!str) {
874 if (error) {
875 warnx("%s", error->message);
876 g_clear_error(&error);
879 continue;
882 do_cache_push(*p, str);
883 g_free(str);
884 continue;
887 if (error) {
888 warnx("%s", error->message);
889 g_clear_error(&error);
890 continue;
893 if (g_key_file_has_key(keyfileh, *p, "key_file", &error) == TRUE) {
894 gchar *t;
895 gchar *file = g_key_file_get_string(keyfileh, *p, "key_file", &error);
897 if (!file) {
898 if (error) {
899 warnx("%s", error->message);
900 g_clear_error(&error);
903 continue;
906 t = expand_homedir(file);
907 g_free(file);
908 file = t;
910 if ((str = _getline(file)) == NULL) {
911 g_free(file);
912 continue;
915 g_free(file);
916 do_cache_push(*p, str);
917 gcry_free(str);
918 continue;
921 if (error) {
922 warnx("%s", error->message);
923 g_clear_error(&error);
927 g_strfreev(groups);
928 return TRUE;
931 static gboolean do_cache_push(const gchar *filename, const gchar *password)
933 guchar *md5file;
934 guchar *key;
935 gint timeout;
936 const gchar *p = filename;
938 while (isspace(*p))
939 p++;
941 if (!*p)
942 return FALSE;
944 if (valid_filename(p) == FALSE) {
945 warnx(N_("%s: invalid characters in filename"), p);
946 return FALSE;
949 md5file = gcry_malloc(16);
950 key = gcry_malloc(gcrykeysize);
951 gcry_md_hash_buffer(GCRY_MD_MD5, md5file, p, strlen(p));
953 if (cache_iscached(md5file) == TRUE) {
954 warnx(N_("%s: file already cached, skipping"), p);
955 gcry_free(md5file);
956 gcry_free(key);
957 return FALSE;
960 if (access(p, R_OK|W_OK) != 0) {
961 gcry_free(md5file);
962 gcry_free(key);
964 if (errno != ENOENT) {
965 warn("%s", p);
966 return FALSE;
969 warn("%s", p);
970 return TRUE;
973 if (!password) {
974 if (get_input(p, key) == FALSE) {
975 gcry_free(key);
976 gcry_free(md5file);
977 return FALSE;
980 else {
981 gcry_md_hash_buffer(GCRY_MD_SHA256, key, password, strlen(password));
983 if (do_try_xml_decrypt(filename, key) == FALSE) {
984 warnx(N_("%s: invalid password, skipping"), filename);
985 gcry_free(key);
986 gcry_free(md5file);
987 return FALSE;
991 if (cache_add_file(md5file, key) == FALSE) {
992 warnx("%s: %s", p, pwmd_strerror(EPWMD_MAX_SLOTS));
993 gcry_free(key);
994 gcry_free(md5file);
995 return FALSE;
998 timeout = get_key_file_integer(p, "cache_timeout");
999 cache_set_timeout(md5file, timeout);
1000 warnx(N_("%s: file added to the cache"), filename);
1001 gcry_free(key);
1002 gcry_free(md5file);
1003 return TRUE;
1006 static GSList *remove_connection(GSList *list, struct client_thread_s *cn)
1008 gpointer value;
1009 struct client_s *cl = cn->cl;
1011 if (cn->keepalive_tid) {
1012 pth_raise(cn->keepalive_tid, SIGALRM);
1013 pth_join(cn->keepalive_tid, &value);
1016 pth_join(cn->tid, &value);
1017 close(cn->fd);
1019 if (cl->freed == FALSE)
1020 cleanup_assuan(cl->ctx);
1022 if (cl->ctx)
1023 assuan_deinit_server(cl->ctx);
1025 if (cl)
1026 g_free(cl);
1028 pth_event_isolate(cn->ev);
1029 pth_event_free(cn->ev, PTH_FREE_THIS);
1030 log_write(N_("client exited: fd=%i"), cn->fd);
1031 list = g_slist_remove(list, cn);
1032 g_free(cn);
1033 return list;
1037 * Can't pth_event_concat() to an empty event.
1039 static int event_ring_hack(void *data)
1041 return FALSE;
1045 * See if any thread has entered the DEAD queue and remove it.
1047 static GSList *cleanup_dead_queue(GSList *threads, pth_event_t tid_events)
1049 guint n, i;
1051 for (n = g_slist_length(threads), i = 0; i < n; i++) {
1052 struct client_thread_s *cn = g_slist_nth_data(threads, i);
1054 if (pth_event_occurred(cn->ev)) {
1055 threads = remove_connection(threads, cn);
1056 return cleanup_dead_queue(threads, tid_events);
1059 pth_event_concat(tid_events, cn->ev, NULL);
1062 return threads;
1065 static void *socket_thread(void *arg)
1067 gint sockfd = (gint)arg;
1068 pth_attr_t attr;
1071 * Thread priority is inherited from the calling thread. This thread is
1072 * PTH_PRIO_MAX. Keep the "child" threads at standard priority.
1074 attr = pth_attr_new();
1075 pth_attr_set(attr, PTH_ATTR_PRIO, PTH_PRIO_STD);
1077 for (;;) {
1078 socklen_t slen = sizeof(struct sockaddr_un);
1079 struct sockaddr_un raddr;
1080 gint fd = -1;
1082 if ((fd = pth_accept(sockfd, (struct sockaddr *)&raddr, &slen)) == -1) {
1083 if (errno != EAGAIN) {
1084 if (!quit) // probably EBADF
1085 log_write("accept(): %s", strerror(errno));
1087 break;
1091 if (fd >= 0) {
1092 pth_t tid;
1093 struct client_thread_s *new;
1095 new = g_malloc0(sizeof(struct client_thread_s));
1097 if (!new) {
1098 log_write("%s", strerror(ENOMEM));
1099 continue;
1102 log_write(N_("new connection: fd=%i"), fd);
1103 new->fd = fd;
1104 tid = pth_spawn(attr, client_thread, new);
1106 if (!tid) {
1107 g_free(new);
1108 log_write(N_("pth_spawn() failed"));
1109 continue;
1112 new->tid = tid;
1113 new->fd = fd;
1114 new->ev = pth_event(PTH_EVENT_TID|PTH_UNTIL_TID_DEAD, tid);
1115 pth_mutex_acquire(&cn_mutex, FALSE, NULL);
1116 pth_event_concat(cn_events, new->ev, NULL);
1117 cn_thread_list = g_slist_append(cn_thread_list, new);
1118 pth_mutex_release(&cn_mutex);
1122 pth_attr_destroy(attr);
1124 /* Just in case pth_accept() failed for some reason other than EBADF */
1125 quit = 1;
1126 pth_exit(PTH_CANCELED);
1127 return NULL;
1130 static void *cleanup_thread(void *arg)
1132 cn_events = pth_event(PTH_EVENT_TIME, pth_timeout(0, 500000));
1134 for (;;) {
1135 if (pth_wait(cn_events) && pth_event_occurred(cn_events)) {
1136 pth_mutex_acquire(&cn_mutex, FALSE, NULL);
1137 pth_event_isolate(cn_events);
1138 pth_event_free(cn_events, PTH_FREE_THIS);
1139 cn_events = pth_event(PTH_EVENT_TIME, pth_timeout(0, 500000));
1140 cn_thread_list = cleanup_dead_queue(cn_thread_list, cn_events);
1141 pth_mutex_release(&cn_mutex);
1145 pth_event_isolate(cn_events);
1146 pth_event_free(cn_events, PTH_FREE_THIS);
1147 return NULL;
1150 static void *adjust_cache_time_thread(void *arg)
1152 CACHE_LOCK(NULL, NULL);
1153 cache_adjust_timer();
1154 CACHE_UNLOCK;
1155 return NULL;
1158 static void server_loop(int sockfd)
1160 pth_t socket_tid, cleanup_tid;
1161 guint n, i;
1162 sigset_t set;
1163 gint n_clients = 0;
1164 pth_attr_t attr;
1165 pth_event_t timeout_event;
1166 gpointer value;
1168 pth_mutex_init(&cn_mutex);
1169 log_write(N_("%s started"), PACKAGE_STRING);
1171 sigemptyset(&set);
1172 sigaddset(&set, SIGTERM);
1173 sigaddset(&set, SIGINT);
1174 sigaddset(&set, SIGUSR1);
1175 sigaddset(&set, SIGUSR2);
1176 sigaddset(&set, SIGHUP);
1178 attr = pth_attr_new();
1179 pth_attr_set(attr, PTH_ATTR_PRIO, PTH_PRIO_MAX);
1180 socket_tid = pth_spawn(attr, socket_thread, (void *)sockfd);
1181 pth_attr_init(attr);
1182 pth_attr_set(attr, PTH_ATTR_PRIO, PTH_PRIO_MAX);
1183 pth_attr_set(attr, PTH_ATTR_JOINABLE, FALSE);
1184 pth_attr_set(attr, PTH_ATTR_CANCEL_STATE, PTH_CANCEL_ASYNCHRONOUS);
1185 cleanup_tid = pth_spawn(attr, cleanup_thread, NULL);
1188 * For the cache_timeout configuration parameter. This replaces the old
1189 * SIGALRM stuff and is safer.
1191 timeout_event = pth_event(PTH_EVENT_TIME, pth_timeout(1, 0));
1192 pth_attr_init(attr);
1193 pth_attr_set(attr, PTH_ATTR_JOINABLE, FALSE);
1194 pth_attr_set(attr, PTH_ATTR_PRIO, PTH_PRIO_MAX);
1196 do {
1197 gint sig = 0;
1199 pth_sigwait_ev(&set, &sig, timeout_event);
1201 if (pth_event_occurred(timeout_event)) {
1203 * The timer event has expired. Update the file cache. When the
1204 * cache mutex is locked and the timer expires again, the threads
1205 * will stack.
1207 pth_spawn(attr, adjust_cache_time_thread, NULL);
1208 pth_event_free(timeout_event, PTH_FREE_THIS);
1209 timeout_event = pth_event(PTH_EVENT_TIME, pth_timeout(1, 0));
1212 if (sig > 0) {
1213 log_write(N_("caught signal %i (%s)"), sig, strsignal(sig));
1215 /* Caught a signal. */
1216 switch (sig) {
1217 case SIGUSR1:
1218 reload_rcfile();
1219 break;
1220 case SIGABRT:
1221 CACHE_LOCK(NULL, NULL);
1222 cache_clear(NULL, 2);
1223 CACHE_UNLOCK;
1224 #ifndef MEM_DEBUG
1225 xpanic();
1226 #endif
1227 exit(EXIT_FAILURE);
1228 case SIGHUP:
1229 CACHE_LOCK(NULL, NULL);
1230 log_write(N_("clearing file cache"));
1231 cache_clear(NULL, 2);
1232 CACHE_UNLOCK;
1233 break;
1234 case SIGUSR2:
1235 break;
1236 default:
1237 quit = 1;
1238 shutdown(sockfd, SHUT_RDWR);
1239 close(sockfd);
1240 break;
1243 } while (!quit);
1246 * We're out of the main server loop. This happens when a signal was sent
1247 * to terminate the daemon. We'll wait for all clients to disconnect
1248 * before exiting and ignore any following signals.
1250 pth_join(socket_tid, &value);
1251 pth_attr_destroy(attr);
1252 pth_event_free(timeout_event, PTH_FREE_THIS);
1254 n = pth_ctrl(PTH_CTRL_GETTHREADS);
1256 /* 2 because the cleanup thread still exists, plus self. */
1257 if (n > 2)
1258 log_write(N_("waiting for all threads to terminate"));
1260 while (n > 2) {
1261 gint t;
1262 pth_event_t events;
1264 if (n != n_clients) {
1265 log_write(N_("%i threads remain"), n-2);
1266 n_clients = n;
1269 events = pth_event(PTH_EVENT_FUNC, event_ring_hack, NULL, pth_timeout(1, 0));
1270 pth_mutex_acquire(&cn_mutex, FALSE, NULL);
1272 for (t = g_slist_length(cn_thread_list), i = 0; i < t; i++) {
1273 struct client_thread_s *cn = g_slist_nth_data(cn_thread_list, i);
1275 pth_event_concat(events, cn->ev, NULL);
1278 if (!t)
1279 goto done;
1281 pth_mutex_release(&cn_mutex);
1282 pth_wait(events);
1283 pth_yield(cleanup_tid);
1284 done:
1285 pth_event_isolate(events);
1286 pth_event_free(events, PTH_FREE_THIS);
1287 n = pth_ctrl(PTH_CTRL_GETTHREADS);
1290 pth_cancel(cleanup_tid);
1293 int main(int argc, char *argv[])
1295 gint opt;
1296 struct sockaddr_un addr;
1297 struct passwd *pw = getpwuid(getuid());
1298 gchar buf[PATH_MAX];
1299 gchar *socketpath = NULL, *socketdir, *socketname = NULL;
1300 gchar *socketarg = NULL;
1301 gchar *datadir = NULL;
1302 gboolean n;
1303 gchar *p;
1304 gchar **cache_push = NULL;
1305 gint iter = 0;
1306 gchar *import = NULL;
1307 gint default_timeout;
1308 gint rcfile_spec = 0;
1309 gint estatus = EXIT_FAILURE;
1310 gint sockfd;
1311 #ifndef MEM_DEBUG
1312 GMemVTable mtable = { xmalloc, xrealloc, xfree, xcalloc, NULL, NULL };
1313 #endif
1314 gint do_unlink = 1;
1315 gboolean secure = FALSE;
1316 guint ptotal = 0;
1317 gint background = 0;
1318 sigset_t set;
1319 #ifndef DEBUG
1320 #ifdef HAVE_SETRLIMIT
1321 struct rlimit rl;
1323 rl.rlim_cur = rl.rlim_max = 0;
1325 if (setrlimit(RLIMIT_CORE, &rl) != 0)
1326 err(EXIT_FAILURE, "setrlimit()");
1327 #endif
1328 #endif
1330 #ifdef ENABLE_NLS
1331 setlocale(LC_ALL, "");
1332 bindtextdomain("pwmd", LOCALEDIR);
1333 textdomain("pwmd");
1334 #endif
1336 gpg_err_init();
1337 assuan_set_assuan_err_source(GPG_ERR_SOURCE_DEFAULT);
1338 #ifndef MEM_DEBUG
1339 g_mem_set_vtable(&mtable);
1340 assuan_set_malloc_hooks(xmalloc, xrealloc, xfree);
1341 xmlMemSetup(xfree, xmalloc, xrealloc, xstrdup);
1342 xmlInitMemory();
1343 #endif
1344 pth_init();
1345 snprintf(buf, sizeof(buf), "%s/.pwmd", pw->pw_dir);
1347 if (mkdir(buf, 0700) == -1 && errno != EEXIST)
1348 err(EXIT_FAILURE, "%s", buf);
1350 snprintf(buf, sizeof(buf), "%s/.pwmd/data", pw->pw_dir);
1352 if (mkdir(buf, 0700) == -1 && errno != EEXIST)
1353 err(EXIT_FAILURE, "%s", buf);
1355 rcfile = g_strdup_printf("%s/.pwmd/config", pw->pw_dir);
1357 if ((page_size = sysconf(_SC_PAGESIZE)) == -1)
1358 err(EXIT_FAILURE, "sysconf()");
1360 cache_size = page_size;
1362 while ((opt = getopt(argc, argv, "bI:hvf:D")) != EOF) {
1363 switch (opt) {
1364 case 'b':
1365 background = 1;
1366 break;
1367 case 'D':
1368 secure = TRUE;
1369 break;
1370 case 'I':
1371 import = optarg;
1372 break;
1373 case 'f':
1374 g_free(rcfile);
1375 rcfile = g_strdup(optarg);
1376 rcfile_spec = 1;
1377 break;
1378 case 'v':
1379 printf("%s\n%s\n", PACKAGE_STRING, PACKAGE_BUGREPORT);
1380 exit(EXIT_SUCCESS);
1381 case 'h':
1382 default:
1383 usage(argv[0]);
1387 if ((keyfileh = parse_rcfile(rcfile_spec)) == NULL)
1388 exit(EXIT_FAILURE);
1390 if (g_key_file_has_key(keyfileh, "default", "syslog", NULL) == TRUE)
1391 log_syslog = g_key_file_get_boolean(keyfileh, "default", "syslog", NULL);
1393 if (log_syslog == TRUE)
1394 openlog("pwmd", LOG_NDELAY|LOG_PID, LOG_DAEMON);
1396 if (g_key_file_has_key(keyfileh, "default", "iterations", NULL) == TRUE)
1397 iter = g_key_file_get_integer(keyfileh, "default", "iterations", NULL);
1399 #ifdef HAVE_MLOCKALL
1400 if (disable_mlock == FALSE && mlockall(MCL_FUTURE) == -1) {
1401 warn("mlockall()");
1402 goto do_exit;
1404 #endif
1406 setup_gcrypt();
1408 if (import) {
1409 opt = xml_import(import, iter);
1410 g_key_file_free(keyfileh);
1411 g_free(rcfile);
1412 exit(opt == FALSE ? EXIT_FAILURE : EXIT_SUCCESS);
1415 g_key_file_set_list_separator(keyfileh, ',');
1417 if ((p = g_key_file_get_string(keyfileh, "default", "socket_path", NULL)) == NULL)
1418 errx(EXIT_FAILURE, N_("%s: socket_path not defined"), rcfile);
1420 if (*p == '~') {
1421 p++;
1422 snprintf(buf, sizeof(buf), "%s%s", g_get_home_dir(), p--);
1423 g_free(p);
1424 socketarg = g_strdup(buf);
1426 else
1427 socketarg = p;
1429 if ((p = g_key_file_get_string(keyfileh, "default", "data_directory", NULL)) == NULL)
1430 errx(EXIT_FAILURE, N_("%s: data_directory not defined"), rcfile);
1432 datadir = expand_homedir(p);
1433 g_free(p);
1435 if (secure == FALSE && g_key_file_has_key(keyfileh, "default", "disable_list_and_dump", NULL) == TRUE) {
1436 n = g_key_file_get_boolean(keyfileh, "default", "disable_list_and_dump", NULL);
1437 disable_list_and_dump = n;
1439 else
1440 disable_list_and_dump = secure;
1442 if (g_key_file_has_key(keyfileh, "default", "cache_timeout", NULL) == TRUE)
1443 default_timeout = g_key_file_get_integer(keyfileh, "default", "cache_timeout", NULL);
1444 else
1445 default_timeout = -1;
1447 if (g_key_file_has_key(keyfileh, "default", "cache_size", NULL) == TRUE) {
1448 cache_size = g_key_file_get_integer(keyfileh, "default", "cache_size", NULL);
1450 if (cache_size < page_size || cache_size % page_size)
1451 errx(EXIT_FAILURE, N_("cache size must be in multiples of %li"), page_size);
1454 if (g_key_file_has_key(keyfileh, "default", "log_path", NULL) == TRUE) {
1455 if (g_key_file_has_key(keyfileh, "default", "enable_logging", NULL) == TRUE) {
1456 n = g_key_file_get_boolean(keyfileh, "default", "enable_logging", NULL);
1458 if (n == TRUE) {
1459 p = g_key_file_get_string(keyfileh, "default", "log_path", NULL);
1461 if (*p == '~') {
1462 p++;
1463 snprintf(buf, sizeof(buf), "%s%s", g_get_home_dir(), p--);
1464 g_free(p);
1465 logfile = g_strdup(buf);
1467 else
1468 logfile = p;
1473 if (g_key_file_has_key(keyfileh, "default", "cache_push", NULL) == TRUE)
1474 cache_push = g_key_file_get_string_list(keyfileh, "default", "cache_push", NULL, NULL);
1476 if (argc != optind) {
1477 if (cache_push)
1478 ptotal = g_strv_length(cache_push);
1480 for (; optind < argc; optind++) {
1481 if (strv_printf(&cache_push, "%s", argv[optind]) == FALSE)
1482 errx(EXIT_FAILURE, "%s", strerror(ENOMEM));
1486 if (strchr(socketarg, '/') == NULL) {
1487 socketdir = g_get_current_dir();
1488 socketname = g_strdup(socketarg);
1489 socketpath = g_strdup_printf("%s/%s", socketdir, socketname);
1491 else {
1492 socketname = g_strdup(strrchr(socketarg, '/'));
1493 socketname++;
1494 socketarg[strlen(socketarg) - strlen(socketname) -1] = 0;
1495 socketdir = g_strdup(socketarg);
1496 socketpath = g_strdup_printf("%s/%s", socketdir, socketname);
1499 if ((key_cache = mmap(NULL, cache_size, PROT_READ|PROT_WRITE,
1500 #ifdef MMAP_ANONYMOUS
1501 MAP_PRIVATE|MAP_ANONYMOUS, -1, 0)) == MAP_FAILED) {
1502 #else
1503 MAP_PRIVATE|MAP_ANON, -1, 0)) == MAP_FAILED) {
1504 #endif
1505 err(EXIT_FAILURE, "mmap()");
1508 if (mlock(key_cache, cache_size) == -1)
1509 warn("mlock()");
1511 memset(key_cache, 0, cache_size);
1513 if (chdir(datadir)) {
1514 warn("%s", datadir);
1515 unlink(socketpath);
1516 goto do_exit;
1519 if (parse_keyfile_key() == FALSE)
1520 goto do_exit;
1522 clear_rcfile_key();
1525 * Set the cache entry for a file. Prompts for the password.
1527 if (cache_push) {
1528 for (opt = 0; cache_push[opt]; opt++)
1529 do_cache_push(cache_push[opt], NULL);
1531 g_strfreev(cache_push);
1532 warnx(background ? N_("Done. Daemonizing...") : N_("Done. Waiting for connections..."));
1536 * bind() doesn't like the full pathname of the socket or any non alphanum
1537 * characters so change to the directory where the socket is wanted then
1538 * create it then change to datadir.
1540 if (chdir(socketdir)) {
1541 warn("%s", socketdir);
1542 goto do_exit;
1545 g_free(socketdir);
1547 if ((sockfd = socket(PF_UNIX, SOCK_STREAM, 0)) == -1) {
1548 warn("socket()");
1549 goto do_exit;
1552 addr.sun_family = AF_UNIX;
1553 snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", socketname);
1555 if (bind(sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr)) == -1) {
1556 warn("bind()");
1558 if (errno == EADDRINUSE)
1559 warnx(N_("Either there is another pwmd running or '%s' is a \n"
1560 "stale socket. Please remove it manually."), socketpath);
1562 do_unlink = 0;
1563 goto do_exit;
1566 if (g_key_file_has_key(keyfileh, "default", "socket_perms", NULL) == TRUE) {
1567 gchar *t = g_key_file_get_string(keyfileh, "default", "socket_perms", NULL);
1568 mode_t mode = strtol(t, NULL, 8);
1569 mode_t mask = umask(0);
1571 g_free(t);
1573 if (chmod(socketname, mode) == -1) {
1574 warn("%s", socketname);
1575 close(sockfd);
1576 unlink(socketpath);
1577 umask(mask);
1578 goto do_exit;
1581 umask(mask);
1584 g_free(--socketname);
1586 if (chdir(datadir)) {
1587 warn("%s", datadir);
1588 close(sockfd);
1589 unlink(socketpath);
1590 goto do_exit;
1593 g_free(datadir);
1594 pth_mutex_init(&cache_mutex);
1596 if (listen(sockfd, 0) == -1) {
1597 warn("listen()");
1598 goto do_exit;
1601 if (background) {
1602 switch (fork()) {
1603 case -1:
1604 warn("fork()");
1605 goto do_exit;
1606 case 0:
1607 close(0);
1608 close(1);
1609 close(2);
1610 setsid();
1611 break;
1612 default:
1613 exit(EXIT_SUCCESS);
1617 sigemptyset(&set);
1618 sigaddset(&set, SIGTERM);
1619 sigaddset(&set, SIGINT);
1620 sigaddset(&set, SIGUSR1);
1621 sigaddset(&set, SIGUSR2);
1622 sigaddset(&set, SIGHUP);
1623 sigaddset(&set, SIGQUIT);
1624 pth_sigmask(SIG_BLOCK, &set, NULL);
1625 signal(SIGPIPE, SIG_IGN);
1626 signal(SIGQUIT, SIG_IGN);
1627 server_loop(sockfd);
1628 estatus = EXIT_SUCCESS;
1630 do_exit:
1631 if (socketpath && do_unlink) {
1632 unlink(socketpath);
1633 g_free(socketpath);
1636 g_key_file_free(keyfileh);
1637 g_free(rcfile);
1639 if (key_cache)
1640 memset(key_cache, 0, cache_size);
1642 if (key_cache && munmap(key_cache, cache_size) == -1)
1643 log_write("munmap(): %s", strerror(errno));
1645 if (estatus == EXIT_SUCCESS)
1646 log_write(N_("pwmd exiting normally"));
1648 pth_kill();
1649 #if defined(DEBUG) && !defined(MEM_DEBUG)
1650 xdump();
1651 #endif
1652 exit(estatus);