Fixed a minor memory leak.
[pwmd.git] / src / pwmd.c
blob7de58ab70b7e4758100e0d2ebef4defde4121c34
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);
367 static GKeyFile *parse_rcfile(int cmdline)
369 GKeyFile *kf = g_key_file_new();
370 GError *error = NULL;
372 if (g_key_file_load_from_file(kf, rcfile, G_KEY_FILE_NONE, &error) == FALSE) {
373 log_write("%s: %s", rcfile, error->message);
375 if (cmdline)
376 exit(EXIT_FAILURE);
378 if (error->code == G_FILE_ERROR_NOENT) {
379 g_clear_error(&error);
380 set_rcfile_defaults(kf);
381 return kf;
384 g_clear_error(&error);
385 return NULL;
387 else
388 set_rcfile_defaults(kf);
390 return kf;
393 static gchar *get_password(const gchar *prompt)
395 gchar buf[LINE_MAX], *p;
396 struct termios told, tnew;
397 gchar *key;
399 if (tcgetattr(STDIN_FILENO, &told) == -1)
400 err(EXIT_FAILURE, "tcgetattr()");
402 memcpy(&tnew, &told, sizeof(struct termios));
403 tnew.c_lflag &= ~(ECHO);
404 tnew.c_lflag |= ICANON|ECHONL;
406 if (tcsetattr(STDIN_FILENO, TCSANOW, &tnew) == -1) {
407 tcsetattr(STDIN_FILENO, TCSANOW, &told);
408 err(EXIT_FAILURE, "tcsetattr()");
411 fprintf(stderr, "%s", prompt);
413 if ((p = fgets(buf, sizeof(buf), stdin)) == NULL) {
414 tcsetattr(STDIN_FILENO, TCSANOW, &told);
415 return NULL;
418 tcsetattr(STDIN_FILENO, TCSANOW, &told);
419 p[strlen(p) - 1] = 0;
421 if (!p || !*p)
422 return NULL;
424 key = gcry_malloc(strlen(p) + 1);
425 sprintf(key, "%s", p);
426 memset(&buf, 0, sizeof(buf));
427 return key;
430 static gboolean do_try_xml_decrypt(const gchar *filename, guchar *key)
432 int fd;
433 struct stat st;
434 gpg_error_t error;
436 if ((fd = open_file(filename, &st)) == -1) {
437 warn("%s", filename);
438 return FALSE;
441 if (st.st_size == 0) {
442 warnx(N_("%s: skipping empty file"), filename);
443 close(fd);
444 return FALSE;
447 error = try_xml_decrypt(NULL, fd, st, key);
448 close(fd);
449 return error ? FALSE : TRUE;
452 static gboolean get_input(const gchar *filename, guchar *key)
454 gint try = 0;
455 gchar *password;
456 gchar *prompt;
458 prompt = g_strdup_printf(N_("Password for '%s': "), filename);
460 again:
461 if ((password = get_password(prompt)) == NULL) {
462 warnx(N_("%s: skipping file"), filename);
463 g_free(prompt);
464 return FALSE;
467 gcry_md_hash_buffer(GCRY_MD_SHA256, key, password, strlen(password));
468 gcry_free(password);
470 if (do_try_xml_decrypt(filename, key) == FALSE) {
471 if (try++ == 2) {
472 warnx(N_("%s: invalid password, skipping"), filename);
473 g_free(prompt);
474 return FALSE;
476 else {
477 warnx(N_("%s: invalid password"), filename);
478 goto again;
482 g_free(prompt);
483 return TRUE;
486 static gboolean xml_import(const gchar *filename, gint iter)
488 xmlDocPtr doc;
489 gint fd;
490 struct stat st;
491 gint len;
492 xmlChar *xmlbuf;
493 xmlChar *xml;
494 gchar *key = NULL;
495 gchar *key2 = NULL;
496 guchar shakey[gcrykeysize];
497 gcry_cipher_hd_t gh;
498 gpg_error_t error;
499 #ifdef HAVE_ZLIB_H
500 gint level;
501 glong outsize;
502 gpointer outbuf;
503 #endif
505 #ifdef HAVE_MLOCKALL
506 if (use_mlock && mlockall(MCL_FUTURE) == -1)
507 err(EXIT_FAILURE, "mlockall()");
508 #endif
510 if (stat(filename, &st) == -1) {
511 warn("%s", filename);
512 return FALSE;
515 #ifndef MEM_DEBUG
516 xmlMemSetup(xfree, xmalloc, xrealloc, xstrdup);
517 xmlInitMemory();
518 #endif
520 if ((gcryerrno = gcry_cipher_open(&gh, GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CBC, 0))) {
521 send_error(NULL, gcryerrno);
522 gcry_cipher_close(gh);
523 log_write("%s(%i): %s", __FUNCTION__, __LINE__, gcry_strerror(gcryerrno));
524 return FALSE;
527 if ((key = get_password(N_("New password: "))) == NULL) {
528 fprintf(stderr, "%s\n", N_("Invalid password."));
529 gcry_cipher_close(gh);
530 return FALSE;
533 if ((key2 = get_password(N_("Verify password: "))) == NULL) {
534 fprintf(stderr, "%s\n", N_("Passwords do not match."));
535 gcry_free(key);
536 gcry_cipher_close(gh);
537 return FALSE;
540 if (g_utf8_collate(key, key2) != 0) {
541 fprintf(stderr, "%s\n", N_("Passwords do not match."));
542 gcry_free(key);
543 gcry_free(key2);
544 gcry_cipher_close(gh);
545 return FALSE;
548 gcry_free(key2);
550 if ((fd = open(filename, O_RDONLY)) == -1) {
551 gcry_free(key);
552 warn("%s", filename);
553 gcry_cipher_close(gh);
554 return FALSE;
557 if ((xmlbuf = gcry_malloc(st.st_size+1)) == NULL) {
558 gcry_free(key);
559 close(fd);
560 log_write("%s", strerror(ENOMEM));
561 gcry_cipher_close(gh);
562 return FALSE;
565 read(fd, xmlbuf, st.st_size);
566 close(fd);
567 xmlbuf[st.st_size] = 0;
570 * Make sure the document validates.
572 if ((doc = xmlReadDoc(xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS)) == NULL) {
573 log_write("xmlReadDoc()");
574 close(fd);
575 gcry_free(key);
576 gcry_free(xmlbuf);
577 gcry_cipher_close(gh);
578 return FALSE;
581 gcry_free(xmlbuf);
582 xmlDocDumpMemory(doc, &xml, &len);
583 xmlFreeDoc(doc);
585 #ifdef HAVE_ZLIB_H
586 level = get_key_file_integer(filename, "compression_level");
588 if (level > 0) {
589 if (do_compress(NULL, level, xml, len, &outbuf, &outsize) == FALSE) {
590 memset(shakey, 0, sizeof(shakey));
591 gcry_free(xml);
592 warnx("do_compress() failed");
593 gcry_cipher_close(gh);
594 return FALSE;
596 else {
597 gcry_free(xml);
598 xml = outbuf;
599 len = outsize;
602 #endif
604 gcry_md_hash_buffer(GCRY_MD_SHA256, shakey, key, strlen(key));
605 gcry_free(key);
606 error = do_xml_encrypt(NULL, gh, NULL, xml, len, shakey, iter);
607 gcry_cipher_close(gh);
609 if (error) {
610 memset(shakey, 0, sizeof(shakey));
611 warnx("%s", gpg_strerror(error));
612 return FALSE;
615 memset(shakey, 0, sizeof(shakey));
616 return TRUE;
619 gchar *get_key_file_string(const gchar *section, const gchar *what)
621 gchar *val = NULL;
622 GError *gerror = NULL;
624 if (g_key_file_has_key(keyfileh, section, what, NULL) == TRUE) {
625 val = g_key_file_get_string(keyfileh, section, what, &gerror);
627 if (gerror) {
628 log_write("%s(%i): %s", __FILE__, __LINE__, gerror->message);
629 g_clear_error(&gerror);
632 else {
633 if (g_key_file_has_key(keyfileh, "default", what, NULL) == TRUE) {
634 val = g_key_file_get_string(keyfileh, "default", what, &gerror);
636 if (gerror) {
637 log_write("%s(%i): %s", __FILE__, __LINE__, gerror->message);
638 g_clear_error(&gerror);
643 return val;
646 gint get_key_file_integer(const gchar *section, const gchar *what)
648 gint val = -1;
649 GError *gerror = NULL;
651 if (g_key_file_has_key(keyfileh, section, what, NULL) == TRUE) {
652 val = g_key_file_get_integer(keyfileh, section, what, &gerror);
654 if (gerror) {
655 log_write("%s(%i): %s", __FILE__, __LINE__, gerror->message);
656 g_clear_error(&gerror);
659 else {
660 if (g_key_file_has_key(keyfileh, "default", what, NULL) == TRUE) {
661 val = g_key_file_get_integer(keyfileh, "default", what, &gerror);
663 if (gerror) {
664 log_write("%s(%i): %s", __FILE__, __LINE__, gerror->message);
665 g_clear_error(&gerror);
670 return val;
673 gboolean get_key_file_boolean(const gchar *section, const gchar *what)
675 gboolean val = FALSE;
676 GError *gerror = NULL;
678 if (g_key_file_has_key(keyfileh, section, what, NULL) == TRUE) {
679 val = g_key_file_get_boolean(keyfileh, section, what, &gerror);
681 if (gerror) {
682 log_write("%s(%i): %s", __FILE__, __LINE__, gerror->message);
683 g_clear_error(&gerror);
686 else {
687 if (g_key_file_has_key(keyfileh, "default", what, NULL) == TRUE) {
688 val = g_key_file_get_boolean(keyfileh, "default", what, &gerror);
690 if (gerror) {
691 log_write("%s(%i): %s", __FILE__, __LINE__, gerror->message);
692 g_clear_error(&gerror);
697 return val;
700 gchar *expand_homedir(gchar *str)
702 gchar *p = str;
704 if (*p++ == '~')
705 return g_strdup_printf("%s%s", g_get_home_dir(), p);
707 return g_strdup(str);
710 static gchar *_getline(const gchar *file)
712 FILE *fp;
713 gchar buf[LINE_MAX], *p;
714 gchar *str = NULL;
716 if ((fp = fopen(file, "r")) == NULL) {
717 warn("%s", file);
718 return NULL;
721 if ((p = fgets(buf, sizeof(buf), fp)) == NULL) {
722 warnx(N_("%s: empty file?"), file);
723 return NULL;
726 fclose(fp);
728 if (buf[strlen(buf) - 1] == '\n')
729 buf[strlen(buf) - 1] = 0;
731 str = gcry_malloc(strlen(p) + 1);
732 memcpy(str, p, strlen(p));
733 str[strlen(p)] = 0;
734 memset(&buf, 0, sizeof(buf));
735 return str;
738 static gboolean parse_keyfile_key()
740 gsize n;
741 gchar **groups;
742 gchar **p;
743 gchar *str;
745 groups = g_key_file_get_groups(keyfileh, &n);
747 for (p = groups; *p; p++) {
748 GError *error = NULL;
750 if (g_key_file_has_key(keyfileh, *p, "key", &error) == TRUE) {
751 str = g_key_file_get_string(keyfileh, *p, "key", &error);
753 if (!str) {
754 if (error) {
755 warnx("%s", error->message);
756 g_clear_error(&error);
759 continue;
762 do_cache_push(*p, str);
763 g_free(str);
764 continue;
767 if (error) {
768 warnx("%s", error->message);
769 g_clear_error(&error);
770 continue;
773 if (g_key_file_has_key(keyfileh, *p, "key_file", &error) == TRUE) {
774 gchar *t;
775 gchar *file = g_key_file_get_string(keyfileh, *p, "key_file", &error);
777 if (!file) {
778 if (error) {
779 warnx("%s", error->message);
780 g_clear_error(&error);
783 continue;
786 t = expand_homedir(file);
787 g_free(file);
788 file = t;
790 if ((str = _getline(file)) == NULL) {
791 g_free(file);
792 continue;
795 g_free(file);
796 do_cache_push(*p, str);
797 gcry_free(str);
798 continue;
801 if (error) {
802 warnx("%s", error->message);
803 g_clear_error(&error);
807 g_strfreev(groups);
808 return TRUE;
811 static gboolean do_cache_push(const gchar *filename, const gchar *password)
813 guchar *md5file;
814 guchar *key;
815 gint timeout;
816 const gchar *p = filename;
818 while (isspace(*p))
819 p++;
821 if (!*p)
822 return FALSE;
824 if (valid_filename(p) == FALSE) {
825 warnx(N_("%s: invalid characters in filename"), p);
826 return FALSE;
829 md5file = gcry_malloc(16);
830 key = gcry_malloc(gcrykeysize);
831 gcry_md_hash_buffer(GCRY_MD_MD5, md5file, p, strlen(p));
833 if (cache_iscached(md5file) == TRUE) {
834 warnx(N_("%s: file already cached, skipping"), p);
835 gcry_free(md5file);
836 gcry_free(key);
837 return FALSE;
840 if (access(p, R_OK|W_OK) != 0) {
841 gcry_free(md5file);
842 gcry_free(key);
844 if (errno != ENOENT) {
845 warn("%s", p);
846 return FALSE;
849 warn("%s", p);
850 return TRUE;
853 if (!password) {
854 if (get_input(p, key) == FALSE) {
855 gcry_free(key);
856 gcry_free(md5file);
857 return FALSE;
860 else {
861 gcry_md_hash_buffer(GCRY_MD_SHA256, key, password, strlen(password));
863 if (do_try_xml_decrypt(filename, key) == FALSE) {
864 warnx(N_("%s: invalid password, skipping"), filename);
865 gcry_free(key);
866 gcry_free(md5file);
867 return FALSE;
871 if (cache_add_file(md5file, key) == FALSE) {
872 warnx("%s: %s", p, pwmd_strerror(EPWMD_MAX_SLOTS));
873 gcry_free(key);
874 gcry_free(md5file);
875 return FALSE;
878 timeout = get_key_file_integer(p, "cache_timeout");
879 cache_set_timeout(md5file, timeout);
880 warnx(N_("%s: file added to the cache"), filename);
881 gcry_free(key);
882 gcry_free(md5file);
883 return TRUE;
886 int main(int argc, char *argv[])
888 gint opt;
889 struct sockaddr_un addr;
890 struct passwd *pw = getpwuid(getuid());
891 gchar buf[PATH_MAX];
892 #ifndef MMAP_ANONYMOUS_SHARED
893 gchar shm_path[PATH_MAX];
894 #endif
895 gchar *socketpath = NULL, *socketdir, *socketname = NULL;
896 gchar *socketarg = NULL;
897 gchar *datadir = NULL;
898 gint fd;
899 gboolean n;
900 gchar *p;
901 gchar **cache_push = NULL;
902 gint iter = 0;
903 gchar *import = NULL;
904 gint default_timeout;
905 gint rcfile_spec = 0;
906 gint estatus = EXIT_FAILURE;
907 #ifndef MEM_DEBUG
908 GMemVTable mtable = { xmalloc, xrealloc, xfree, xcalloc, NULL, NULL };
909 #endif
910 gint do_unlink = 1;
911 gboolean secure = FALSE;
912 guint ptotal = 0;
913 gint background = 0;
914 gint n_clients = 0;
915 #ifndef DEBUG
916 #ifdef HAVE_SETRLIMIT
917 struct rlimit rl;
919 rl.rlim_cur = rl.rlim_max = 0;
921 if (setrlimit(RLIMIT_CORE, &rl) != 0)
922 err(EXIT_FAILURE, "setrlimit()");
923 #endif
924 #endif
926 #ifdef ENABLE_NLS
927 setlocale(LC_ALL, "");
928 bindtextdomain("pwmd", LOCALEDIR);
929 textdomain("pwmd");
930 #endif
932 #ifndef MEM_DEBUG
933 g_mem_set_vtable(&mtable);
934 #endif
935 snprintf(buf, sizeof(buf), "%s/.pwmd", pw->pw_dir);
937 if (mkdir(buf, 0700) == -1 && errno != EEXIST)
938 err(EXIT_FAILURE, "%s", buf);
940 snprintf(buf, sizeof(buf), "%s/.pwmd/data", pw->pw_dir);
942 if (mkdir(buf, 0700) == -1 && errno != EEXIST)
943 err(EXIT_FAILURE, "%s", buf);
945 rcfile = g_strdup_printf("%s/.pwmd/config", pw->pw_dir);
947 if ((page_size = sysconf(_SC_PAGESIZE)) == -1)
948 err(EXIT_FAILURE, "sysconf()");
950 cache_size = page_size;
952 #ifdef HAVE_MLOCKALL
954 * Default to using mlockall().
956 use_mlock = 1;
957 #endif
959 while ((opt = getopt(argc, argv, "bI:hvf:D")) != EOF) {
960 switch (opt) {
961 case 'b':
962 background = 1;
963 break;
964 case 'D':
965 secure = TRUE;
966 break;
967 case 'I':
968 import = optarg;
969 break;
970 case 'f':
971 g_free(rcfile);
972 rcfile = g_strdup(optarg);
973 rcfile_spec = 1;
974 break;
975 case 'v':
976 printf("%s\n%s\n", PACKAGE_STRING, PACKAGE_BUGREPORT);
977 exit(EXIT_SUCCESS);
978 case 'h':
979 default:
980 usage(argv[0]);
984 if ((keyfileh = parse_rcfile(rcfile_spec)) == NULL)
985 exit(EXIT_FAILURE);
987 if (g_key_file_has_key(keyfileh, "default", "iterations", NULL) == TRUE)
988 iter = g_key_file_get_integer(keyfileh, "default", "iterations", NULL);
990 setup_gcrypt();
992 if (import) {
993 opt = xml_import(import, iter);
994 g_key_file_free(keyfileh);
995 g_free(rcfile);
996 exit(opt == FALSE ? EXIT_FAILURE : EXIT_SUCCESS);
999 g_key_file_set_list_separator(keyfileh, ',');
1001 if ((p = g_key_file_get_string(keyfileh, "default", "socket_path", NULL)) == NULL)
1002 errx(EXIT_FAILURE, N_("%s: socket_path not defined"), rcfile);
1004 if (*p == '~') {
1005 p++;
1006 snprintf(buf, sizeof(buf), "%s%s", g_get_home_dir(), p--);
1007 g_free(p);
1008 socketarg = g_strdup(buf);
1010 else
1011 socketarg = p;
1013 if ((p = g_key_file_get_string(keyfileh, "default", "data_directory", NULL)) == NULL)
1014 errx(EXIT_FAILURE, N_("%s: data_directory not defined"), rcfile);
1016 datadir = expand_homedir(p);
1017 g_free(p);
1019 if (secure == FALSE && g_key_file_has_key(keyfileh, "default", "disable_list_and_dump", NULL) == TRUE) {
1020 n = g_key_file_get_boolean(keyfileh, "default", "disable_list_and_dump", NULL);
1021 disable_list_and_dump = n;
1023 else
1024 disable_list_and_dump = secure;
1026 if (g_key_file_has_key(keyfileh, "default", "cache_timeout", NULL) == TRUE)
1027 default_timeout = g_key_file_get_integer(keyfileh, "default", "cache_timeout", NULL);
1028 else
1029 default_timeout = -1;
1031 if (g_key_file_has_key(keyfileh, "default", "cache_size", NULL) == TRUE) {
1032 cache_size = g_key_file_get_integer(keyfileh, "default", "cache_size", NULL);
1034 if (cache_size < page_size || cache_size % page_size)
1035 errx(EXIT_FAILURE, N_("cache size must be in multiples of %li"), page_size);
1038 #ifdef HAVE_MLOCKALL
1039 if (g_key_file_has_key(keyfileh, "default", "disable_mlockall", NULL) == TRUE)
1040 use_mlock = g_key_file_get_integer(keyfileh, "default", "disable_mlockall", NULL);
1041 #endif
1043 if (g_key_file_has_key(keyfileh, "default", "log_path", NULL) == TRUE) {
1044 if (g_key_file_has_key(keyfileh, "default", "enable_logging", NULL) == TRUE) {
1045 n = g_key_file_get_boolean(keyfileh, "default", "enable_logging", NULL);
1047 if (n == TRUE) {
1048 p = g_key_file_get_string(keyfileh, "default", "log_path", NULL);
1050 if (*p == '~') {
1051 p++;
1052 snprintf(buf, sizeof(buf), "%s%s", g_get_home_dir(), p--);
1053 g_free(p);
1054 logfile = g_strdup(buf);
1056 else
1057 logfile = p;
1062 if (g_key_file_has_key(keyfileh, "default", "cache_push", NULL) == TRUE)
1063 cache_push = g_key_file_get_string_list(keyfileh, "default", "cache_push", NULL, NULL);
1065 if (argc != optind) {
1066 if (cache_push)
1067 ptotal = g_strv_length(cache_push);
1069 for (; optind < argc; optind++)
1070 strv_printf(&cache_push, "%s", argv[optind]);
1073 if (strchr(socketarg, '/') == NULL) {
1074 socketdir = g_get_current_dir();
1075 socketname = g_strdup(socketarg);
1076 socketpath = g_strdup_printf("%s/%s", socketdir, socketname);
1078 else {
1079 socketname = g_strdup(strrchr(socketarg, '/'));
1080 socketname++;
1081 socketarg[strlen(socketarg) - strlen(socketname) -1] = 0;
1082 socketdir = g_strdup(socketarg);
1083 socketpath = g_strdup_printf("%s/%s", socketdir, socketname);
1086 #ifdef MMAP_ANONYMOUS_SHARED
1087 if ((shm_data = mmap(NULL, cache_size, PROT_READ|PROT_WRITE,
1088 #ifdef MMAP_ANONYMOUS
1089 MAP_SHARED|MAP_ANONYMOUS, -1, 0)) == NULL) {
1090 #else
1091 MAP_SHARED|MAP_ANON, -1, 0)) == NULL) {
1092 #endif
1093 err(EXIT_FAILURE, "mmap()");
1095 #else
1096 snprintf(shm_path, sizeof(shm_path), "/pwmd.%i", pw->pw_uid);
1098 if ((fd = shm_open(shm_path, O_CREAT|O_RDWR|O_EXCL, 0600)) == -1)
1099 err(EXIT_FAILURE, "shm_open(): %s", shm_path);
1102 * Should be enough for the file cache.
1104 if (ftruncate(fd, cache_size) == -1) {
1105 warn("ftruncate()");
1106 shm_unlink(shm_path);
1107 exit(EXIT_FAILURE);
1110 if ((shm_data = mmap(NULL, cache_size, PROT_READ|PROT_WRITE, MAP_SHARED,
1111 fd, 0)) == NULL) {
1112 warn("mmap()");
1113 shm_unlink(shm_path);
1114 exit(EXIT_FAILURE);
1117 close(fd);
1118 #endif
1120 if (mlock(shm_data, cache_size) == -1)
1121 warn("mlock()");
1123 memset(shm_data, 0, cache_size);
1125 if (chdir(datadir)) {
1126 warn("%s", datadir);
1127 close(sfd);
1128 unlink(socketpath);
1129 goto do_exit;
1132 if (parse_keyfile_key() == FALSE)
1133 goto do_exit;
1136 * Set the cache entry for a file. Prompts for the password.
1138 if (cache_push) {
1139 for (opt = 0; cache_push[opt]; opt++)
1140 do_cache_push(cache_push[opt], NULL);
1142 g_strfreev(cache_push);
1143 warnx(background ? N_("Done. Daemonizing...") : N_("Done. Waiting for connections..."));
1147 * bind() doesn't like the full pathname of the socket or any non alphanum
1148 * characters so change to the directory where the socket is wanted then
1149 * create it then change to datadir.
1151 if (chdir(socketdir)) {
1152 warn("%s", socketdir);
1153 goto do_exit;
1156 g_free(socketdir);
1158 if ((sfd = socket(PF_UNIX, SOCK_STREAM, 0)) == -1) {
1159 warn("socket()");
1160 goto do_exit;
1163 addr.sun_family = AF_UNIX;
1164 snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", socketname);
1165 g_free(--socketname);
1167 if (bind(sfd, (struct sockaddr *)&addr, sizeof(struct sockaddr)) == -1) {
1168 warn("bind()");
1170 if (errno == EADDRINUSE)
1171 warnx(N_("Either there is another pwmd running or '%s' is a \n"
1172 "stale socket. Please remove it manually."), socketpath);
1174 do_unlink = 0;
1175 goto do_exit;
1178 if (chdir(datadir)) {
1179 warn("%s", datadir);
1180 close(sfd);
1181 unlink(socketpath);
1182 goto do_exit;
1185 g_free(datadir);
1187 if (listen(sfd, 0) == -1) {
1188 warn("listen()");
1189 goto do_exit;
1192 signal(SIGCHLD, catchsig);
1193 signal(SIGTERM, catchsig);
1194 signal(SIGINT, catchsig);
1195 signal(SIGHUP, catchsig);
1196 signal(SIGALRM, catchsig);
1197 signal(SIGABRT, catchsig);
1198 signal(SIGUSR1, catchsig);
1199 alarm(1);
1201 if (background) {
1202 switch (fork()) {
1203 case -1:
1204 warn("fork()");
1205 goto do_exit;
1206 case 0:
1207 close(0);
1208 close(1);
1209 close(2);
1210 break;
1211 default:
1212 exit(EXIT_SUCCESS);
1216 log_write("%s %s", PACKAGE_STRING, N_("started"));
1217 send_cache_status(NULL);
1219 while (!quit) {
1220 socklen_t slen = sizeof(struct sockaddr_un);
1221 struct sockaddr_un raddr;
1222 pid_t pid;
1224 if ((fd = accept(sfd, (struct sockaddr *)&raddr, &slen)) == -1) {
1225 if (quit)
1226 break;
1228 if (errno == EAGAIN)
1229 continue;
1231 log_write("accept(): %s", strerror(errno));
1232 continue;
1235 switch ((pid = fork())) {
1236 case -1:
1237 log_write("fork(): %s", strerror(errno));
1238 break;
1239 case 0:
1240 doit(fd);
1241 break;
1242 default:
1243 break;
1246 clients++;
1247 log_write(N_("new connection: pid=%i"), pid);
1248 close(fd);
1251 estatus = EXIT_SUCCESS;
1253 do_exit:
1254 if (socketpath && do_unlink) {
1255 unlink(socketpath);
1256 g_free(socketpath);
1259 signal(SIGUSR1, SIG_IGN);
1260 g_key_file_free(keyfileh);
1261 g_free(rcfile);
1263 if (clients) {
1264 log_write(N_("waiting for all clients to disconnect"));
1266 do {
1267 if (clients != n_clients) {
1268 log_write(N_("%i clients remain"), clients);
1269 n_clients = clients;
1272 select(0, NULL, NULL, NULL, NULL);
1273 } while (clients);
1276 memset(shm_data, 0, cache_size);
1278 if (munmap(shm_data, cache_size) == -1)
1279 log_write("munmap(): %s", strerror(errno));
1281 #ifndef MMAP_ANONYMOUS_SHARED
1282 if (shm_unlink(shm_path) == -1)
1283 log_write("shm_unlink(): %s: %s", shm_path, strerror(errno));
1284 #endif
1286 if (estatus == EXIT_SUCCESS)
1287 log_write(N_("pwmd exiting normally"));
1289 exit(estatus);