Added configuration parameter "recursion_depth". This specifies the
[pwmd.git] / src / pwmd.c
blobed7dc4d751e00aefee05dca345ad8b145ed271ef
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/socket.h>
27 #include <sys/un.h>
28 #include <signal.h>
29 #include <stdarg.h>
30 #include <string.h>
31 #include <sys/wait.h>
32 #include <fcntl.h>
33 #include <pwd.h>
34 #include <glib.h>
35 #include <glib/gprintf.h>
36 #include <gcrypt.h>
37 #include <sys/mman.h>
38 #include <termios.h>
39 #include <assert.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 reload_rcfile()
67 log_write(N_("reloading configuration file '%s'"), rcfile);
68 g_key_file_free(keyfileh);
69 keyfileh = parse_rcfile(0);
72 gpg_error_t send_syserror(assuan_context_t ctx, int e)
74 gpg_error_t n = gpg_error_from_errno(e);
76 return assuan_set_error(ctx, n, gpg_strerror(n));
79 gpg_error_t send_error(assuan_context_t ctx, gpg_error_t e)
81 gpg_err_code_t n = gpg_err_code(e);
82 gpg_error_t code = gpg_err_make(GPG_ERR_SOURCE_USER_1, n);
84 if (!e)
85 return 0;
87 if (!ctx) {
88 log_write("%s\n", pwmd_strerror(e));
89 return e;
92 if (n == EPWMD_LIBXML_ERROR) {
93 xmlErrorPtr xml_error = xmlGetLastError();
94 return assuan_set_error(ctx, code, xml_error->message);
97 return assuan_set_error(ctx, code, pwmd_strerror(e));
100 void log_write(const gchar *fmt, ...)
102 gchar *args, *line;
103 va_list ap;
104 struct tm *tm;
105 time_t now;
106 gchar tbuf[21];
107 gint fd = -1;
109 if ((!logfile && !isatty(STDERR_FILENO)) || !fmt)
110 return;
112 if (logfile) {
113 if ((fd = open(logfile, O_WRONLY|O_CREAT|O_APPEND, 0600)) == -1) {
114 warn(N_("logfile"));
115 return;
119 va_start(ap, fmt);
120 g_vasprintf(&args, fmt, ap);
121 va_end(ap);
122 time(&now);
123 tm = localtime(&now);
124 strftime(tbuf, sizeof(tbuf), "%b %d %Y %H:%M:%S ", tm);
125 tbuf[sizeof(tbuf) - 1] = 0;
126 line = g_strdup_printf("%s %i %s\n", tbuf, getpid(), args);
128 if (logfile) {
129 write(fd, line, strlen(line));
130 fsync(fd);
131 close(fd);
134 if (isatty(STDERR_FILENO)) {
135 fprintf(stderr, "%s", line);
136 fflush(stderr);
139 g_free(line);
140 g_free(args);
143 static void catchsig(gint sig)
145 gint status;
147 if (sig != SIGALRM && sig != SIGCHLD)
148 log_write(N_("caught signal %i (%s)"), sig, strsignal(sig));
150 switch (sig) {
151 case SIGUSR1:
152 reload_rcfile();
153 break;
154 case SIGABRT:
155 cache_clear(NULL, 2);
156 #ifndef MEM_DEBUG
157 xpanic();
158 #endif
159 exit(EXIT_FAILURE);
160 case SIGALRM:
161 cache_adjust_timer();
162 alarm(1);
163 break;
164 case SIGCHLD:
165 waitpid(-1, &status, 0);
167 if (WIFEXITED(status) || WIFSIGNALED(status))
168 clients--;
170 break;
171 case SIGHUP:
172 log_write(N_("clearing file cache"));
173 cache_clear(NULL, 2);
174 break;
175 default:
176 signal(SIGALRM, SIG_IGN);
177 quit = 1;
178 shutdown(sfd, SHUT_RDWR);
179 close(sfd);
180 break;
184 static void usage(gchar *pn)
186 g_printf(N_(
187 "Usage: %s [-hvDb] [-f <rcfile>] [-I <filename>] [file1] [...]\n"
188 " -b run as a background process\n"
189 " -f load the specified rcfile (~/.pwmd/config)\n"
190 " -I import an XML file and write the encrypted data to stdout\n"
191 " -D disable use of the LIST and DUMP commands\n"
192 " -v version\n"
193 " -h this help text\n"
194 ), pn);
195 exit(EXIT_SUCCESS);
198 #ifndef MEM_DEBUG
199 static int gcry_SecureCheck(const void *ptr)
201 return 1;
203 #endif
205 static void setup_gcrypt()
207 gcry_check_version(NULL);
209 #ifndef MEM_DEBUG
210 gcry_set_allocation_handler(xmalloc, xmalloc, gcry_SecureCheck, xrealloc,
211 xfree);
212 #endif
214 if (gcry_cipher_algo_info(GCRY_CIPHER_AES256, GCRYCTL_TEST_ALGO, NULL,
215 NULL) != 0)
216 errx(EXIT_FAILURE, N_("Required AES cipher not supported by libgcrypt."));
218 gcry_cipher_algo_info(GCRY_CIPHER_AES256, GCRYCTL_GET_KEYLEN, NULL, &gcrykeysize);
219 gcry_cipher_algo_info(GCRY_CIPHER_AES256, GCRYCTL_GET_BLKLEN, NULL, &gcryblocksize);
222 static void child_catchsig(int sig)
224 assuan_context_t ctx = global_client->ctx;
226 switch (sig) {
227 case SIGTERM:
228 cleanup_assuan(ctx);
229 g_free(global_client);
230 assuan_deinit_server(ctx);
231 log_write(N_("exiting"));
232 _exit(EXIT_SUCCESS);
233 break;
234 case SIGABRT:
235 #ifndef MEM_DEBUG
236 xpanic();
237 #endif
238 exit(EXIT_FAILURE);
239 default:
240 break;
245 * Called every time a connection is made.
247 static void doit(int fd)
249 assuan_context_t ctx;
250 int rc;
251 struct client_s *cl = g_malloc0(sizeof(struct client_s));
253 signal(SIGCHLD, SIG_DFL);
254 signal(SIGHUP, SIG_IGN);
255 signal(SIGINT, SIG_IGN);
256 signal(SIGALRM, SIG_IGN);
257 signal(SIGTERM, child_catchsig);
258 signal(SIGABRT, child_catchsig);
259 gpg_err_init();
260 assuan_set_assuan_err_source(GPG_ERR_SOURCE_DEFAULT);
261 #ifndef MEM_DEBUG
262 assuan_set_malloc_hooks(xmalloc, xrealloc, xfree);
263 xmlMemSetup(xfree, xmalloc, xrealloc, xstrdup);
264 xmlInitMemory();
265 #endif
267 #ifdef HAVE_MLOCKALL
268 if (use_mlock && mlockall(MCL_FUTURE) == -1) {
269 log_write("mlockall(): %s", strerror(errno));
270 exit(EXIT_FAILURE);
272 #endif
274 rc = assuan_init_socket_server_ext(&ctx, fd, 2);
276 if (rc) {
277 log_write("%s", gpg_strerror(rc));
278 exit(EXIT_FAILURE);
281 assuan_set_pointer(ctx, cl);
282 rc = register_commands(ctx);
284 if (rc) {
285 log_write("%s", gpg_strerror(rc));
286 exit(EXIT_FAILURE);
289 cl->ctx = ctx;
290 global_client = cl;
293 * It would be nice if there were an assuan_register_pre_cmd_notify().
294 * That way we can see if the file has been modified before calling the
295 * command.
297 rc = assuan_accept(ctx);
299 if (rc) {
300 log_write("%s", gpg_strerror(rc));
301 goto done;
304 rc = assuan_process(ctx);
306 if (rc)
307 log_write("%s", gpg_strerror(rc));
309 done:
310 if (cl->freed == FALSE)
311 cleanup_assuan(ctx);
313 g_free(cl);
314 assuan_deinit_server(ctx);
315 log_write(N_("exiting"));
316 _exit(EXIT_SUCCESS);
320 * Make sure all settings are set to either the specified setting or a
321 * default.
323 static void set_rcfile_defaults(GKeyFile *kf)
325 gchar buf[PATH_MAX];
327 if (g_key_file_has_key(kf, "default", "socket_path", NULL) == FALSE) {
328 snprintf(buf, sizeof(buf), "~/.pwmd/socket");
329 g_key_file_set_string(kf, "default", "socket_path", buf);
332 if (g_key_file_has_key(kf, "default", "data_directory", NULL) == FALSE) {
333 snprintf(buf, sizeof(buf), "~/.pwmd/data");
334 g_key_file_set_string(kf, "default", "data_directory", buf);
337 if (g_key_file_has_key(kf, "default", "log_path", NULL) == FALSE) {
338 snprintf(buf, sizeof(buf), "~/.pwmd/log");
339 g_key_file_set_string(kf, "default", "log_path", buf);
342 if (g_key_file_has_key(kf, "default", "enable_logging", NULL) == FALSE)
343 g_key_file_set_boolean(kf, "default", "enable_logging", FALSE);
345 if (g_key_file_has_key(kf, "default", "cache_size", NULL) == FALSE)
346 g_key_file_set_integer(kf, "default", "cache_size", cache_size);
348 if (g_key_file_has_key(kf, "default", "disable_mlockall", NULL) == FALSE)
349 g_key_file_set_boolean(kf, "default", "disable_mlockall", FALSE);
351 if (g_key_file_has_key(kf, "default", "cache_timeout", NULL) == FALSE)
352 g_key_file_set_integer(kf, "default", "cache_timeout", -1);
354 if (g_key_file_has_key(kf, "default", "iterations", NULL) == FALSE)
355 g_key_file_set_integer(kf, "default", "iterations", 0);
357 if (g_key_file_has_key(kf, "default", "disable_list_and_dump", NULL) == FALSE)
358 g_key_file_set_boolean(kf, "default", "disable_list_and_dump", FALSE);
360 if (g_key_file_has_key(kf, "default", "iteration_progress", NULL) == FALSE)
361 g_key_file_set_integer(kf, "default", "iteration_progress", 0);
363 if (g_key_file_has_key(kf, "default", "compression_level", NULL) == FALSE)
364 g_key_file_set_integer(kf, "default", "compression_level", 6);
366 if (g_key_file_has_key(kf, "default", "recursion_depth", NULL) == FALSE)
367 g_key_file_set_integer(kf, "default", "recursion_depth", DEFAULT_RECURSION_DEPTH);
369 max_recursion_depth = g_key_file_get_integer(kf, "default", "recursion_depth", NULL);
372 static GKeyFile *parse_rcfile(int cmdline)
374 GKeyFile *kf = g_key_file_new();
375 GError *error = NULL;
377 if (g_key_file_load_from_file(kf, rcfile, G_KEY_FILE_NONE, &error) == FALSE) {
378 log_write("%s: %s", rcfile, error->message);
380 if (cmdline)
381 exit(EXIT_FAILURE);
383 if (error->code == G_FILE_ERROR_NOENT) {
384 g_clear_error(&error);
385 set_rcfile_defaults(kf);
386 return kf;
389 g_clear_error(&error);
390 return NULL;
392 else
393 set_rcfile_defaults(kf);
395 return kf;
398 static gchar *get_password(const gchar *prompt)
400 gchar buf[LINE_MAX], *p;
401 struct termios told, tnew;
402 gchar *key;
404 if (tcgetattr(STDIN_FILENO, &told) == -1)
405 err(EXIT_FAILURE, "tcgetattr()");
407 memcpy(&tnew, &told, sizeof(struct termios));
408 tnew.c_lflag &= ~(ECHO);
409 tnew.c_lflag |= ICANON|ECHONL;
411 if (tcsetattr(STDIN_FILENO, TCSANOW, &tnew) == -1) {
412 tcsetattr(STDIN_FILENO, TCSANOW, &told);
413 err(EXIT_FAILURE, "tcsetattr()");
416 fprintf(stderr, "%s", prompt);
418 if ((p = fgets(buf, sizeof(buf), stdin)) == NULL) {
419 tcsetattr(STDIN_FILENO, TCSANOW, &told);
420 return NULL;
423 tcsetattr(STDIN_FILENO, TCSANOW, &told);
424 p[strlen(p) - 1] = 0;
426 if (!p || !*p)
427 return NULL;
429 key = gcry_malloc(strlen(p) + 1);
430 sprintf(key, "%s", p);
431 memset(&buf, 0, sizeof(buf));
432 return key;
435 static gboolean do_try_xml_decrypt(const gchar *filename, guchar *key)
437 int fd;
438 struct stat st;
439 gpg_error_t error;
441 if ((fd = open_file(filename, &st)) == -1) {
442 warn("%s", filename);
443 return FALSE;
446 if (st.st_size == 0) {
447 warnx(N_("%s: skipping empty file"), filename);
448 close(fd);
449 return FALSE;
452 error = try_xml_decrypt(NULL, fd, st, key);
453 close(fd);
454 return error ? FALSE : TRUE;
457 static gboolean get_input(const gchar *filename, guchar *key)
459 gint try = 0;
460 gchar *password;
461 gchar *prompt;
463 prompt = g_strdup_printf(N_("Password for '%s': "), filename);
465 again:
466 if ((password = get_password(prompt)) == NULL) {
467 warnx(N_("%s: skipping file"), filename);
468 g_free(prompt);
469 return FALSE;
472 gcry_md_hash_buffer(GCRY_MD_SHA256, key, password, strlen(password));
473 gcry_free(password);
475 if (do_try_xml_decrypt(filename, key) == FALSE) {
476 if (try++ == 2) {
477 warnx(N_("%s: invalid password, skipping"), filename);
478 g_free(prompt);
479 return FALSE;
481 else {
482 warnx(N_("%s: invalid password"), filename);
483 goto again;
487 g_free(prompt);
488 return TRUE;
491 static gboolean xml_import(const gchar *filename, gint iter)
493 xmlDocPtr doc;
494 gint fd;
495 struct stat st;
496 gint len;
497 xmlChar *xmlbuf;
498 xmlChar *xml;
499 gchar *key = NULL;
500 gchar *key2 = NULL;
501 guchar shakey[gcrykeysize];
502 gcry_cipher_hd_t gh;
503 gpg_error_t error;
504 #ifdef HAVE_ZLIB_H
505 gint level;
506 glong outsize;
507 gpointer outbuf;
508 #endif
510 #ifdef HAVE_MLOCKALL
511 if (use_mlock && mlockall(MCL_FUTURE) == -1)
512 err(EXIT_FAILURE, "mlockall()");
513 #endif
515 if (stat(filename, &st) == -1) {
516 warn("%s", filename);
517 return FALSE;
520 #ifndef MEM_DEBUG
521 xmlMemSetup(xfree, xmalloc, xrealloc, xstrdup);
522 xmlInitMemory();
523 #endif
525 if ((gcryerrno = gcry_cipher_open(&gh, GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CBC, 0))) {
526 send_error(NULL, gcryerrno);
527 gcry_cipher_close(gh);
528 log_write("%s(%i): %s", __FUNCTION__, __LINE__, gcry_strerror(gcryerrno));
529 return FALSE;
532 if ((key = get_password(N_("New password: "))) == NULL) {
533 fprintf(stderr, "%s\n", N_("Invalid password."));
534 gcry_cipher_close(gh);
535 return FALSE;
538 if ((key2 = get_password(N_("Verify password: "))) == NULL) {
539 fprintf(stderr, "%s\n", N_("Passwords do not match."));
540 gcry_free(key);
541 gcry_cipher_close(gh);
542 return FALSE;
545 if (g_utf8_collate(key, key2) != 0) {
546 fprintf(stderr, "%s\n", N_("Passwords do not match."));
547 gcry_free(key);
548 gcry_free(key2);
549 gcry_cipher_close(gh);
550 return FALSE;
553 gcry_free(key2);
555 if ((fd = open(filename, O_RDONLY)) == -1) {
556 gcry_free(key);
557 warn("%s", filename);
558 gcry_cipher_close(gh);
559 return FALSE;
562 if ((xmlbuf = gcry_malloc(st.st_size+1)) == NULL) {
563 gcry_free(key);
564 close(fd);
565 log_write("%s", strerror(ENOMEM));
566 gcry_cipher_close(gh);
567 return FALSE;
570 read(fd, xmlbuf, st.st_size);
571 close(fd);
572 xmlbuf[st.st_size] = 0;
575 * Make sure the document validates.
577 if ((doc = xmlReadDoc(xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS)) == NULL) {
578 log_write("xmlReadDoc()");
579 close(fd);
580 gcry_free(key);
581 gcry_free(xmlbuf);
582 gcry_cipher_close(gh);
583 return FALSE;
586 gcry_free(xmlbuf);
587 xmlDocDumpMemory(doc, &xml, &len);
588 xmlFreeDoc(doc);
590 #ifdef HAVE_ZLIB_H
591 level = get_key_file_integer(filename, "compression_level");
593 if (level > 0) {
594 if (do_compress(NULL, level, xml, len, &outbuf, &outsize) == FALSE) {
595 memset(shakey, 0, sizeof(shakey));
596 gcry_free(xml);
597 warnx("do_compress() failed");
598 gcry_cipher_close(gh);
599 return FALSE;
601 else {
602 gcry_free(xml);
603 xml = outbuf;
604 len = outsize;
607 #endif
609 gcry_md_hash_buffer(GCRY_MD_SHA256, shakey, key, strlen(key));
610 gcry_free(key);
611 error = do_xml_encrypt(NULL, gh, NULL, xml, len, shakey, iter);
612 gcry_cipher_close(gh);
614 if (error) {
615 memset(shakey, 0, sizeof(shakey));
616 warnx("%s", gpg_strerror(error));
617 return FALSE;
620 memset(shakey, 0, sizeof(shakey));
621 return TRUE;
624 gchar *get_key_file_string(const gchar *section, const gchar *what)
626 gchar *val = NULL;
627 GError *gerror = NULL;
629 if (g_key_file_has_key(keyfileh, section, what, NULL) == TRUE) {
630 val = g_key_file_get_string(keyfileh, section, what, &gerror);
632 if (gerror) {
633 log_write("%s(%i): %s", __FILE__, __LINE__, gerror->message);
634 g_clear_error(&gerror);
637 else {
638 if (g_key_file_has_key(keyfileh, "default", what, NULL) == TRUE) {
639 val = g_key_file_get_string(keyfileh, "default", what, &gerror);
641 if (gerror) {
642 log_write("%s(%i): %s", __FILE__, __LINE__, gerror->message);
643 g_clear_error(&gerror);
648 return val;
651 gint get_key_file_integer(const gchar *section, const gchar *what)
653 gint val = -1;
654 GError *gerror = NULL;
656 if (g_key_file_has_key(keyfileh, section, what, NULL) == TRUE) {
657 val = g_key_file_get_integer(keyfileh, section, what, &gerror);
659 if (gerror) {
660 log_write("%s(%i): %s", __FILE__, __LINE__, gerror->message);
661 g_clear_error(&gerror);
664 else {
665 if (g_key_file_has_key(keyfileh, "default", what, NULL) == TRUE) {
666 val = g_key_file_get_integer(keyfileh, "default", what, &gerror);
668 if (gerror) {
669 log_write("%s(%i): %s", __FILE__, __LINE__, gerror->message);
670 g_clear_error(&gerror);
675 return val;
678 gboolean get_key_file_boolean(const gchar *section, const gchar *what)
680 gboolean val = FALSE;
681 GError *gerror = NULL;
683 if (g_key_file_has_key(keyfileh, section, what, NULL) == TRUE) {
684 val = g_key_file_get_boolean(keyfileh, section, what, &gerror);
686 if (gerror) {
687 log_write("%s(%i): %s", __FILE__, __LINE__, gerror->message);
688 g_clear_error(&gerror);
691 else {
692 if (g_key_file_has_key(keyfileh, "default", what, NULL) == TRUE) {
693 val = g_key_file_get_boolean(keyfileh, "default", what, &gerror);
695 if (gerror) {
696 log_write("%s(%i): %s", __FILE__, __LINE__, gerror->message);
697 g_clear_error(&gerror);
702 return val;
705 gchar *expand_homedir(gchar *str)
707 gchar *p = str;
709 if (*p++ == '~')
710 return g_strdup_printf("%s%s", g_get_home_dir(), p);
712 return g_strdup(str);
715 static gchar *_getline(const gchar *file)
717 FILE *fp;
718 gchar buf[LINE_MAX], *p;
719 gchar *str = NULL;
721 if ((fp = fopen(file, "r")) == NULL) {
722 warn("%s", file);
723 return NULL;
726 if ((p = fgets(buf, sizeof(buf), fp)) == NULL) {
727 warnx(N_("%s: empty file?"), file);
728 return NULL;
731 fclose(fp);
733 if (buf[strlen(buf) - 1] == '\n')
734 buf[strlen(buf) - 1] = 0;
736 str = gcry_malloc(strlen(p) + 1);
737 memcpy(str, p, strlen(p));
738 str[strlen(p)] = 0;
739 memset(&buf, 0, sizeof(buf));
740 return str;
743 static gboolean parse_keyfile_key()
745 gsize n;
746 gchar **groups;
747 gchar **p;
748 gchar *str;
750 groups = g_key_file_get_groups(keyfileh, &n);
752 for (p = groups; *p; p++) {
753 GError *error = NULL;
755 if (g_key_file_has_key(keyfileh, *p, "key", &error) == TRUE) {
756 str = g_key_file_get_string(keyfileh, *p, "key", &error);
758 if (!str) {
759 if (error) {
760 warnx("%s", error->message);
761 g_clear_error(&error);
764 continue;
767 do_cache_push(*p, str);
768 g_free(str);
769 continue;
772 if (error) {
773 warnx("%s", error->message);
774 g_clear_error(&error);
775 continue;
778 if (g_key_file_has_key(keyfileh, *p, "key_file", &error) == TRUE) {
779 gchar *t;
780 gchar *file = g_key_file_get_string(keyfileh, *p, "key_file", &error);
782 if (!file) {
783 if (error) {
784 warnx("%s", error->message);
785 g_clear_error(&error);
788 continue;
791 t = expand_homedir(file);
792 g_free(file);
793 file = t;
795 if ((str = _getline(file)) == NULL) {
796 g_free(file);
797 continue;
800 g_free(file);
801 do_cache_push(*p, str);
802 gcry_free(str);
803 continue;
806 if (error) {
807 warnx("%s", error->message);
808 g_clear_error(&error);
812 g_strfreev(groups);
813 return TRUE;
816 static gboolean do_cache_push(const gchar *filename, const gchar *password)
818 guchar *md5file;
819 guchar *key;
820 gint timeout;
821 const gchar *p = filename;
823 while (isspace(*p))
824 p++;
826 if (!*p)
827 return FALSE;
829 if (valid_filename(p) == FALSE) {
830 warnx(N_("%s: invalid characters in filename"), p);
831 return FALSE;
834 md5file = gcry_malloc(16);
835 key = gcry_malloc(gcrykeysize);
836 gcry_md_hash_buffer(GCRY_MD_MD5, md5file, p, strlen(p));
838 if (cache_iscached(md5file) == TRUE) {
839 warnx(N_("%s: file already cached, skipping"), p);
840 gcry_free(md5file);
841 gcry_free(key);
842 return FALSE;
845 if (access(p, R_OK|W_OK) != 0) {
846 gcry_free(md5file);
847 gcry_free(key);
849 if (errno != ENOENT) {
850 warn("%s", p);
851 return FALSE;
854 warn("%s", p);
855 return TRUE;
858 if (!password) {
859 if (get_input(p, key) == FALSE) {
860 gcry_free(key);
861 gcry_free(md5file);
862 return FALSE;
865 else {
866 gcry_md_hash_buffer(GCRY_MD_SHA256, key, password, strlen(password));
868 if (do_try_xml_decrypt(filename, key) == FALSE) {
869 warnx(N_("%s: invalid password, skipping"), filename);
870 gcry_free(key);
871 gcry_free(md5file);
872 return FALSE;
876 if (cache_add_file(md5file, key) == FALSE) {
877 warnx("%s: %s", p, pwmd_strerror(EPWMD_MAX_SLOTS));
878 gcry_free(key);
879 gcry_free(md5file);
880 return FALSE;
883 timeout = get_key_file_integer(p, "cache_timeout");
884 cache_set_timeout(md5file, timeout);
885 warnx(N_("%s: file added to the cache"), filename);
886 gcry_free(key);
887 gcry_free(md5file);
888 return TRUE;
891 int main(int argc, char *argv[])
893 gint opt;
894 struct sockaddr_un addr;
895 struct passwd *pw = getpwuid(getuid());
896 gchar buf[PATH_MAX];
897 #ifndef MMAP_ANONYMOUS_SHARED
898 gchar shm_path[PATH_MAX];
899 #endif
900 gchar *socketpath = NULL, *socketdir, *socketname = NULL;
901 gchar *socketarg = NULL;
902 gchar *datadir = NULL;
903 gint fd;
904 gboolean n;
905 gchar *p;
906 gchar **cache_push = NULL;
907 gint iter = 0;
908 gchar *import = NULL;
909 gint default_timeout;
910 gint rcfile_spec = 0;
911 gint estatus = EXIT_FAILURE;
912 #ifndef MEM_DEBUG
913 GMemVTable mtable = { xmalloc, xrealloc, xfree, xcalloc, NULL, NULL };
914 #endif
915 gint do_unlink = 1;
916 gboolean secure = FALSE;
917 guint ptotal = 0;
918 gint background = 0;
919 gint n_clients = 0;
920 #ifndef DEBUG
921 #ifdef HAVE_SETRLIMIT
922 struct rlimit rl;
924 rl.rlim_cur = rl.rlim_max = 0;
926 if (setrlimit(RLIMIT_CORE, &rl) != 0)
927 err(EXIT_FAILURE, "setrlimit()");
928 #endif
929 #endif
931 #ifdef ENABLE_NLS
932 setlocale(LC_ALL, "");
933 bindtextdomain("pwmd", LOCALEDIR);
934 textdomain("pwmd");
935 #endif
937 #ifndef MEM_DEBUG
938 g_mem_set_vtable(&mtable);
939 #endif
940 snprintf(buf, sizeof(buf), "%s/.pwmd", pw->pw_dir);
942 if (mkdir(buf, 0700) == -1 && errno != EEXIST)
943 err(EXIT_FAILURE, "%s", buf);
945 snprintf(buf, sizeof(buf), "%s/.pwmd/data", pw->pw_dir);
947 if (mkdir(buf, 0700) == -1 && errno != EEXIST)
948 err(EXIT_FAILURE, "%s", buf);
950 rcfile = g_strdup_printf("%s/.pwmd/config", pw->pw_dir);
952 if ((page_size = sysconf(_SC_PAGESIZE)) == -1)
953 err(EXIT_FAILURE, "sysconf()");
955 cache_size = page_size;
957 #ifdef HAVE_MLOCKALL
959 * Default to using mlockall().
961 use_mlock = 1;
962 #endif
964 while ((opt = getopt(argc, argv, "bI:hvf:D")) != EOF) {
965 switch (opt) {
966 case 'b':
967 background = 1;
968 break;
969 case 'D':
970 secure = TRUE;
971 break;
972 case 'I':
973 import = optarg;
974 break;
975 case 'f':
976 g_free(rcfile);
977 rcfile = g_strdup(optarg);
978 rcfile_spec = 1;
979 break;
980 case 'v':
981 printf("%s\n%s\n", PACKAGE_STRING, PACKAGE_BUGREPORT);
982 exit(EXIT_SUCCESS);
983 case 'h':
984 default:
985 usage(argv[0]);
989 if ((keyfileh = parse_rcfile(rcfile_spec)) == NULL)
990 exit(EXIT_FAILURE);
992 if (g_key_file_has_key(keyfileh, "default", "iterations", NULL) == TRUE)
993 iter = g_key_file_get_integer(keyfileh, "default", "iterations", NULL);
995 setup_gcrypt();
997 if (import) {
998 opt = xml_import(import, iter);
999 g_key_file_free(keyfileh);
1000 g_free(rcfile);
1001 exit(opt == FALSE ? EXIT_FAILURE : EXIT_SUCCESS);
1004 g_key_file_set_list_separator(keyfileh, ',');
1006 if ((p = g_key_file_get_string(keyfileh, "default", "socket_path", NULL)) == NULL)
1007 errx(EXIT_FAILURE, N_("%s: socket_path not defined"), rcfile);
1009 if (*p == '~') {
1010 p++;
1011 snprintf(buf, sizeof(buf), "%s%s", g_get_home_dir(), p--);
1012 g_free(p);
1013 socketarg = g_strdup(buf);
1015 else
1016 socketarg = p;
1018 if ((p = g_key_file_get_string(keyfileh, "default", "data_directory", NULL)) == NULL)
1019 errx(EXIT_FAILURE, N_("%s: data_directory not defined"), rcfile);
1021 datadir = expand_homedir(p);
1022 g_free(p);
1024 if (secure == FALSE && g_key_file_has_key(keyfileh, "default", "disable_list_and_dump", NULL) == TRUE) {
1025 n = g_key_file_get_boolean(keyfileh, "default", "disable_list_and_dump", NULL);
1026 disable_list_and_dump = n;
1028 else
1029 disable_list_and_dump = secure;
1031 if (g_key_file_has_key(keyfileh, "default", "cache_timeout", NULL) == TRUE)
1032 default_timeout = g_key_file_get_integer(keyfileh, "default", "cache_timeout", NULL);
1033 else
1034 default_timeout = -1;
1036 if (g_key_file_has_key(keyfileh, "default", "cache_size", NULL) == TRUE) {
1037 cache_size = g_key_file_get_integer(keyfileh, "default", "cache_size", NULL);
1039 if (cache_size < page_size || cache_size % page_size)
1040 errx(EXIT_FAILURE, N_("cache size must be in multiples of %li"), page_size);
1043 #ifdef HAVE_MLOCKALL
1044 if (g_key_file_has_key(keyfileh, "default", "disable_mlockall", NULL) == TRUE)
1045 use_mlock = g_key_file_get_integer(keyfileh, "default", "disable_mlockall", NULL);
1046 #endif
1048 if (g_key_file_has_key(keyfileh, "default", "log_path", NULL) == TRUE) {
1049 if (g_key_file_has_key(keyfileh, "default", "enable_logging", NULL) == TRUE) {
1050 n = g_key_file_get_boolean(keyfileh, "default", "enable_logging", NULL);
1052 if (n == TRUE) {
1053 p = g_key_file_get_string(keyfileh, "default", "log_path", NULL);
1055 if (*p == '~') {
1056 p++;
1057 snprintf(buf, sizeof(buf), "%s%s", g_get_home_dir(), p--);
1058 g_free(p);
1059 logfile = g_strdup(buf);
1061 else
1062 logfile = p;
1067 if (g_key_file_has_key(keyfileh, "default", "cache_push", NULL) == TRUE)
1068 cache_push = g_key_file_get_string_list(keyfileh, "default", "cache_push", NULL, NULL);
1070 if (argc != optind) {
1071 if (cache_push)
1072 ptotal = g_strv_length(cache_push);
1074 for (; optind < argc; optind++)
1075 strv_printf(&cache_push, "%s", argv[optind]);
1078 if (strchr(socketarg, '/') == NULL) {
1079 socketdir = g_get_current_dir();
1080 socketname = g_strdup(socketarg);
1081 socketpath = g_strdup_printf("%s/%s", socketdir, socketname);
1083 else {
1084 socketname = g_strdup(strrchr(socketarg, '/'));
1085 socketname++;
1086 socketarg[strlen(socketarg) - strlen(socketname) -1] = 0;
1087 socketdir = g_strdup(socketarg);
1088 socketpath = g_strdup_printf("%s/%s", socketdir, socketname);
1091 #ifdef MMAP_ANONYMOUS_SHARED
1092 if ((shm_data = mmap(NULL, cache_size, PROT_READ|PROT_WRITE,
1093 #ifdef MMAP_ANONYMOUS
1094 MAP_SHARED|MAP_ANONYMOUS, -1, 0)) == NULL) {
1095 #else
1096 MAP_SHARED|MAP_ANON, -1, 0)) == NULL) {
1097 #endif
1098 err(EXIT_FAILURE, "mmap()");
1100 #else
1101 snprintf(shm_path, sizeof(shm_path), "/pwmd.%i", pw->pw_uid);
1103 if ((fd = shm_open(shm_path, O_CREAT|O_RDWR|O_EXCL, 0600)) == -1)
1104 err(EXIT_FAILURE, "shm_open(): %s", shm_path);
1107 * Should be enough for the file cache.
1109 if (ftruncate(fd, cache_size) == -1) {
1110 warn("ftruncate()");
1111 shm_unlink(shm_path);
1112 exit(EXIT_FAILURE);
1115 if ((shm_data = mmap(NULL, cache_size, PROT_READ|PROT_WRITE, MAP_SHARED,
1116 fd, 0)) == NULL) {
1117 warn("mmap()");
1118 shm_unlink(shm_path);
1119 exit(EXIT_FAILURE);
1122 close(fd);
1123 #endif
1125 if (mlock(shm_data, cache_size) == -1)
1126 warn("mlock()");
1128 memset(shm_data, 0, cache_size);
1130 if (chdir(datadir)) {
1131 warn("%s", datadir);
1132 close(sfd);
1133 unlink(socketpath);
1134 goto do_exit;
1137 if (parse_keyfile_key() == FALSE)
1138 goto do_exit;
1141 * Set the cache entry for a file. Prompts for the password.
1143 if (cache_push) {
1144 for (opt = 0; cache_push[opt]; opt++)
1145 do_cache_push(cache_push[opt], NULL);
1147 g_strfreev(cache_push);
1148 warnx(background ? N_("Done. Daemonizing...") : N_("Done. Waiting for connections..."));
1152 * bind() doesn't like the full pathname of the socket or any non alphanum
1153 * characters so change to the directory where the socket is wanted then
1154 * create it then change to datadir.
1156 if (chdir(socketdir)) {
1157 warn("%s", socketdir);
1158 goto do_exit;
1161 g_free(socketdir);
1163 if ((sfd = socket(PF_UNIX, SOCK_STREAM, 0)) == -1) {
1164 warn("socket()");
1165 goto do_exit;
1168 addr.sun_family = AF_UNIX;
1169 snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", socketname);
1170 g_free(--socketname);
1172 if (bind(sfd, (struct sockaddr *)&addr, sizeof(struct sockaddr)) == -1) {
1173 warn("bind()");
1175 if (errno == EADDRINUSE)
1176 warnx(N_("Either there is another pwmd running or '%s' is a \n"
1177 "stale socket. Please remove it manually."), socketpath);
1179 do_unlink = 0;
1180 goto do_exit;
1183 if (chdir(datadir)) {
1184 warn("%s", datadir);
1185 close(sfd);
1186 unlink(socketpath);
1187 goto do_exit;
1190 g_free(datadir);
1192 if (listen(sfd, 0) == -1) {
1193 warn("listen()");
1194 goto do_exit;
1197 signal(SIGCHLD, catchsig);
1198 signal(SIGTERM, catchsig);
1199 signal(SIGINT, catchsig);
1200 signal(SIGHUP, catchsig);
1201 signal(SIGALRM, catchsig);
1202 signal(SIGABRT, catchsig);
1203 signal(SIGUSR1, catchsig);
1204 alarm(1);
1206 if (background) {
1207 switch (fork()) {
1208 case -1:
1209 warn("fork()");
1210 goto do_exit;
1211 case 0:
1212 close(0);
1213 close(1);
1214 close(2);
1215 break;
1216 default:
1217 exit(EXIT_SUCCESS);
1221 log_write("%s %s", PACKAGE_STRING, N_("started"));
1222 send_cache_status(NULL);
1224 while (!quit) {
1225 socklen_t slen = sizeof(struct sockaddr_un);
1226 struct sockaddr_un raddr;
1227 pid_t pid;
1229 if ((fd = accept(sfd, (struct sockaddr *)&raddr, &slen)) == -1) {
1230 if (quit)
1231 break;
1233 if (errno == EAGAIN)
1234 continue;
1236 log_write("accept(): %s", strerror(errno));
1237 continue;
1240 switch ((pid = fork())) {
1241 case -1:
1242 log_write("fork(): %s", strerror(errno));
1243 break;
1244 case 0:
1245 doit(fd);
1246 break;
1247 default:
1248 break;
1251 clients++;
1252 log_write(N_("new connection: pid=%i"), pid);
1253 close(fd);
1256 estatus = EXIT_SUCCESS;
1258 do_exit:
1259 if (socketpath && do_unlink) {
1260 unlink(socketpath);
1261 g_free(socketpath);
1264 signal(SIGUSR1, SIG_IGN);
1265 g_key_file_free(keyfileh);
1266 g_free(rcfile);
1268 if (clients) {
1269 log_write(N_("waiting for all clients to disconnect"));
1271 do {
1272 if (clients != n_clients) {
1273 log_write(N_("%i clients remain"), clients);
1274 n_clients = clients;
1277 select(0, NULL, NULL, NULL, NULL);
1278 } while (clients);
1281 memset(shm_data, 0, cache_size);
1283 if (munmap(shm_data, cache_size) == -1)
1284 log_write("munmap(): %s", strerror(errno));
1286 #ifndef MMAP_ANONYMOUS_SHARED
1287 if (shm_unlink(shm_path) == -1)
1288 log_write("shm_unlink(): %s: %s", shm_path, strerror(errno));
1289 #endif
1291 if (estatus == EXIT_SUCCESS)
1292 log_write(N_("pwmd exiting normally"));
1294 exit(estatus);