1 /* vim:tw=78:ts=8:sw=4:set ft=c: */
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
38 #include <glib/gprintf.h>
47 #include <sys/resource.h>
61 #include "pwmd_error.h"
65 static void clear_rcfile_key()
71 groups
= g_key_file_get_groups(keyfileh
, &n
);
73 for (p
= groups
; *p
; p
++) {
76 if (g_key_file_has_key(keyfileh
, *p
, "key", &error
) == TRUE
)
77 g_key_file_set_string(keyfileh
, *p
, "key", "");
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);
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
);
104 return assuan_process_done(ctx
, 0);
107 log_write("%s\n", pwmd_strerror(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
, ...)
128 if ((!logfile
&& !isatty(STDERR_FILENO
) && log_syslog
== FALSE
) || !fmt
)
132 if ((fd
= open(logfile
, O_WRONLY
|O_CREAT
|O_APPEND
, 0600)) == -1) {
140 if (g_vasprintf(&args
, fmt
, ap
) == -1) {
145 if (log_syslog
== TRUE
)
146 syslog(LOG_INFO
, "%s", args
);
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
);
164 write(fd
, line
, strlen(line
));
169 if (isatty(STDERR_FILENO
)) {
170 fprintf(stderr
, "%s", line
);
178 static void usage(gchar
*pn
)
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"
187 " -h this help text\n"
193 static int gcry_SecureCheck(const void *ptr
)
199 static void setup_gcrypt()
201 gcry_check_version(NULL
);
204 gcry_set_allocation_handler(xmalloc
, xmalloc
, gcry_SecureCheck
, xrealloc
,
208 if (gcry_cipher_algo_info(GCRY_CIPHER_AES256
, GCRYCTL_TEST_ALGO
, NULL
,
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
)
219 gchar ver
[ASSUAN_LINELENGTH
];
220 assuan_context_t ctx
;
222 rc
= assuan_init_socket_server_ext(&ctx
, fd
, 2);
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
);
235 rc
= assuan_accept(ctx
);
243 assuan_deinit_server(ctx
);
244 log_write("%s", gpg_strerror(rc
));
248 void send_cache_status_all()
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
);
260 pth_raise(cn
->tid
, SIGUSR2
);
264 static void *keepalive_thread(void *arg
)
266 struct client_thread_s
*thd
= arg
;
271 sigaddset(&set
, SIGALRM
);
276 gint k
= get_key_file_integer("default", "keepalive");
278 ev
= pth_event(PTH_EVENT_TIME
, pth_timeout(k
<= 0 ? 1 : k
, 0));
279 pth_sigwait_ev(&set
, &sig
, ev
);
280 pth_event_free(ev
, PTH_FREE_THIS
);
288 error
= assuan_write_status(thd
->cl
->ctx
, "KEEPALIVE", NULL
);
291 pth_raise(thd
->tid
, SIGQUIT
);
300 * Called every time a connection is made via pth_spawn(). This is the thread
303 static void *client_thread(void *data
)
305 struct client_thread_s
*thd
= data
;
308 struct client_s
*cl
= g_malloc0(sizeof(struct client_s
));
312 log_write("%s(%i): %s", __FILE__
, __LINE__
, strerror(ENOMEM
));
319 * This is a "child" thread. Don't catch any signals. Let the master
320 * thread take care of signals in server_loop().
323 pth_sigmask(SIG_BLOCK
, &set
, NULL
);
325 /* Sends a cache status message to the client. */
326 sigaddset(&set
, SIGUSR2
);
327 /* Terminates this thread. Raised from keepalive_thread(). */
328 sigaddset(&set
, SIGQUIT
);
330 cl
->ctx
= new_connection(fd
);
336 assuan_set_pointer(cl
->ctx
, cl
);
339 if (disable_mlock
== FALSE
&& mlockall(MCL_FUTURE
) == -1) {
340 log_write("mlockall(): %s", strerror(errno
));
345 send_cache_status(cl
->ctx
);
346 ev
= pth_event(PTH_EVENT_FD
|PTH_UNTIL_FD_READABLE
, cl
->fd
);
347 thd
->keepalive_tid
= pth_spawn(NULL
, keepalive_thread
, thd
);
353 pth_sigwait_ev(&set
, &sig
, ev
);
358 send_cache_status(cl
->ctx
);
367 if (pth_event_occurred(ev
)) {
368 rc
= assuan_process_next(cl
->ctx
);
371 if (gpg_err_code(rc
) == GPG_ERR_EOF
)
374 log_write("assuan_process_next(): %s", gpg_strerror(rc
));
375 rc
= assuan_process_done(cl
->ctx
, gpg_err_make(GPG_ERR_SOURCE_USER_1
, rc
));
378 log_write("assuan_process_done(): %s", gpg_strerror(rc
));
386 * Client cleanup (including XML data) is done in remove_connection() from
387 * the cleanup thread.
390 pth_event_free(ev
, PTH_FREE_ALL
);
398 * Make sure all settings are set to either the specified setting or a
401 static void set_rcfile_defaults(GKeyFile
*kf
)
405 if (g_key_file_has_key(kf
, "default", "socket_path", NULL
) == FALSE
) {
406 snprintf(buf
, sizeof(buf
), "~/.pwmd/socket");
407 g_key_file_set_string(kf
, "default", "socket_path", buf
);
410 if (g_key_file_has_key(kf
, "default", "data_directory", NULL
) == FALSE
) {
411 snprintf(buf
, sizeof(buf
), "~/.pwmd/data");
412 g_key_file_set_string(kf
, "default", "data_directory", buf
);
415 if (g_key_file_has_key(kf
, "default", "log_path", NULL
) == FALSE
) {
416 snprintf(buf
, sizeof(buf
), "~/.pwmd/log");
417 g_key_file_set_string(kf
, "default", "log_path", buf
);
420 if (g_key_file_has_key(kf
, "default", "enable_logging", NULL
) == FALSE
)
421 g_key_file_set_boolean(kf
, "default", "enable_logging", FALSE
);
423 if (g_key_file_has_key(kf
, "default", "cache_size", NULL
) == FALSE
)
424 g_key_file_set_integer(kf
, "default", "cache_size", cache_size
);
427 if (g_key_file_has_key(kf
, "default", "disable_mlockall", NULL
) == FALSE
)
428 g_key_file_set_boolean(kf
, "default", "disable_mlockall", TRUE
);
431 if (g_key_file_has_key(kf
, "default", "cache_timeout", NULL
) == FALSE
)
432 g_key_file_set_integer(kf
, "default", "cache_timeout", -1);
434 if (g_key_file_has_key(kf
, "default", "iterations", NULL
) == FALSE
)
435 g_key_file_set_integer(kf
, "default", "iterations", 0);
437 if (g_key_file_has_key(kf
, "default", "disable_list_and_dump", NULL
) == FALSE
)
438 g_key_file_set_boolean(kf
, "default", "disable_list_and_dump", FALSE
);
440 if (g_key_file_has_key(kf
, "default", "iteration_progress", NULL
) == FALSE
)
441 g_key_file_set_integer(kf
, "default", "iteration_progress", 0);
443 if (g_key_file_has_key(kf
, "default", "compression_level", NULL
) == FALSE
)
444 g_key_file_set_integer(kf
, "default", "compression_level", 6);
446 if (g_key_file_has_key(kf
, "default", "recursion_depth", NULL
) == FALSE
)
447 g_key_file_set_integer(kf
, "default", "recursion_depth", DEFAULT_RECURSION_DEPTH
);
449 if (g_key_file_has_key(kf
, "default", "zlib_bufsize", NULL
) == FALSE
)
450 g_key_file_set_integer(kf
, "default", "zlib_bufsize", DEFAULT_ZLIB_BUFSIZE
);
452 zlib_bufsize
= g_key_file_get_integer(kf
, "default", "zlib_bufsize", NULL
);
454 max_recursion_depth
= g_key_file_get_integer(kf
, "default", "recursion_depth", NULL
);
455 disable_list_and_dump
= g_key_file_get_boolean(kf
, "default", "disable_list_and_dump", NULL
);
458 disable_mlock
= g_key_file_get_boolean(kf
, "default", "disable_mlockall", NULL
);
461 if (g_key_file_has_key(kf
, "default", "syslog", NULL
) == FALSE
)
462 g_key_file_set_boolean(kf
, "default", "syslog", FALSE
);
464 if (g_key_file_has_key(kf
, "default", "keepalive", NULL
) == FALSE
)
465 g_key_file_set_integer(kf
, "default", "keepalive", 5);
468 static GKeyFile
*parse_rcfile(int cmdline
)
470 GKeyFile
*kf
= g_key_file_new();
471 GError
*error
= NULL
;
473 if (g_key_file_load_from_file(kf
, rcfile
, G_KEY_FILE_NONE
, &error
) == FALSE
) {
474 log_write("%s: %s", rcfile
, error
->message
);
479 if (error
->code
== G_FILE_ERROR_NOENT
) {
480 g_clear_error(&error
);
481 set_rcfile_defaults(kf
);
485 g_clear_error(&error
);
489 set_rcfile_defaults(kf
);
494 static gchar
*get_password(const gchar
*prompt
)
496 gchar buf
[LINE_MAX
], *p
;
497 struct termios told
, tnew
;
500 if (tcgetattr(STDIN_FILENO
, &told
) == -1)
501 err(EXIT_FAILURE
, "tcgetattr()");
503 memcpy(&tnew
, &told
, sizeof(struct termios
));
504 tnew
.c_lflag
&= ~(ECHO
);
505 tnew
.c_lflag
|= ICANON
|ECHONL
;
507 if (tcsetattr(STDIN_FILENO
, TCSANOW
, &tnew
) == -1) {
508 tcsetattr(STDIN_FILENO
, TCSANOW
, &told
);
509 err(EXIT_FAILURE
, "tcsetattr()");
512 fprintf(stderr
, "%s", prompt
);
514 if ((p
= fgets(buf
, sizeof(buf
), stdin
)) == NULL
) {
515 tcsetattr(STDIN_FILENO
, TCSANOW
, &told
);
519 tcsetattr(STDIN_FILENO
, TCSANOW
, &told
);
520 p
[strlen(p
) - 1] = 0;
525 key
= gcry_malloc(strlen(p
) + 1);
526 sprintf(key
, "%s", p
);
527 memset(&buf
, 0, sizeof(buf
));
531 static gboolean
do_try_xml_decrypt(const gchar
*filename
, guchar
*key
)
537 if ((fd
= open_file(filename
, &st
)) == -1) {
538 warn("%s", filename
);
542 if (st
.st_size
== 0) {
543 warnx(N_("%s: skipping empty file"), filename
);
548 error
= try_xml_decrypt(NULL
, fd
, st
, key
);
550 return error
? FALSE
: TRUE
;
553 static gboolean
get_input(const gchar
*filename
, guchar
*key
)
559 prompt
= g_strdup_printf(N_("Password for '%s': "), filename
);
562 if ((password
= get_password(prompt
)) == NULL
) {
563 warnx(N_("%s: skipping file"), filename
);
568 gcry_md_hash_buffer(GCRY_MD_SHA256
, key
, password
, strlen(password
));
571 if (do_try_xml_decrypt(filename
, key
) == FALSE
) {
573 warnx(N_("%s: invalid password, skipping"), filename
);
578 warnx(N_("%s: invalid password"), filename
);
587 static gboolean
xml_import(const gchar
*filename
, gint iter
)
597 guchar shakey
[gcrykeysize
];
605 if (stat(filename
, &st
) == -1) {
606 warn("%s", filename
);
610 if ((error
= gcry_cipher_open(&gh
, GCRY_CIPHER_AES256
, GCRY_CIPHER_MODE_CBC
, 0))) {
611 send_error(NULL
, error
);
612 gcry_cipher_close(gh
);
613 log_write("%s(%i): %s", __FUNCTION__
, __LINE__
, gcry_strerror(error
));
617 if ((key
= get_password(N_("New password: "))) == NULL
) {
618 fprintf(stderr
, "%s\n", N_("Invalid password."));
619 gcry_cipher_close(gh
);
623 if ((key2
= get_password(N_("Verify password: "))) == NULL
) {
624 fprintf(stderr
, "%s\n", N_("Passwords do not match."));
626 gcry_cipher_close(gh
);
630 if (g_utf8_collate(key
, key2
) != 0) {
631 fprintf(stderr
, "%s\n", N_("Passwords do not match."));
634 gcry_cipher_close(gh
);
640 if ((fd
= open(filename
, O_RDONLY
)) == -1) {
642 warn("%s", filename
);
643 gcry_cipher_close(gh
);
647 if ((xmlbuf
= gcry_malloc(st
.st_size
+1)) == NULL
) {
650 log_write("%s", strerror(ENOMEM
));
651 gcry_cipher_close(gh
);
655 if (read(fd
, xmlbuf
, st
.st_size
) == -1) {
659 gcry_cipher_close(gh
);
661 err(EXIT_FAILURE
, "read()");
665 xmlbuf
[st
.st_size
] = 0;
668 * Make sure the document validates.
670 if ((doc
= xmlReadDoc(xmlbuf
, NULL
, "UTF-8", XML_PARSE_NOBLANKS
)) == NULL
) {
671 log_write("xmlReadDoc()");
675 gcry_cipher_close(gh
);
680 xmlDocDumpMemory(doc
, &xml
, &len
);
683 level
= get_key_file_integer(filename
, "compression_level");
688 if (do_compress(NULL
, level
, xml
, len
, &outbuf
, &outsize
, &zerror
) == FALSE
) {
689 memset(shakey
, 0, sizeof(shakey
));
692 if (zerror
== Z_MEM_ERROR
)
693 warnx("%s", strerror(ENOMEM
));
695 warnx("do_compress() failed");
697 gcry_cipher_close(gh
);
706 gcry_md_hash_buffer(GCRY_MD_SHA256
, shakey
, key
, strlen(key
));
708 error
= do_xml_encrypt(NULL
, gh
, NULL
, xml
, len
, shakey
, iter
);
709 gcry_cipher_close(gh
);
712 memset(shakey
, 0, sizeof(shakey
));
713 warnx("%s", gpg_strerror(error
));
717 memset(shakey
, 0, sizeof(shakey
));
721 gchar
*get_key_file_string(const gchar
*section
, const gchar
*what
)
724 GError
*gerror
= NULL
;
726 if (g_key_file_has_key(keyfileh
, section
, what
, NULL
) == TRUE
) {
727 val
= g_key_file_get_string(keyfileh
, section
, what
, &gerror
);
730 log_write("%s(%i): %s", __FILE__
, __LINE__
, gerror
->message
);
731 g_clear_error(&gerror
);
735 if (g_key_file_has_key(keyfileh
, "default", what
, NULL
) == TRUE
) {
736 val
= g_key_file_get_string(keyfileh
, "default", what
, &gerror
);
739 log_write("%s(%i): %s", __FILE__
, __LINE__
, gerror
->message
);
740 g_clear_error(&gerror
);
748 gint
get_key_file_integer(const gchar
*section
, const gchar
*what
)
751 GError
*gerror
= NULL
;
753 if (g_key_file_has_key(keyfileh
, section
, what
, NULL
) == TRUE
) {
754 val
= g_key_file_get_integer(keyfileh
, section
, what
, &gerror
);
757 log_write("%s(%i): %s", __FILE__
, __LINE__
, gerror
->message
);
758 g_clear_error(&gerror
);
762 if (g_key_file_has_key(keyfileh
, "default", what
, NULL
) == TRUE
) {
763 val
= g_key_file_get_integer(keyfileh
, "default", what
, &gerror
);
766 log_write("%s(%i): %s", __FILE__
, __LINE__
, gerror
->message
);
767 g_clear_error(&gerror
);
775 gboolean
get_key_file_boolean(const gchar
*section
, const gchar
*what
)
777 gboolean val
= FALSE
;
778 GError
*gerror
= NULL
;
780 if (g_key_file_has_key(keyfileh
, section
, what
, NULL
) == TRUE
) {
781 val
= g_key_file_get_boolean(keyfileh
, section
, what
, &gerror
);
784 log_write("%s(%i): %s", __FILE__
, __LINE__
, gerror
->message
);
785 g_clear_error(&gerror
);
789 if (g_key_file_has_key(keyfileh
, "default", what
, NULL
) == TRUE
) {
790 val
= g_key_file_get_boolean(keyfileh
, "default", what
, &gerror
);
793 log_write("%s(%i): %s", __FILE__
, __LINE__
, gerror
->message
);
794 g_clear_error(&gerror
);
802 gchar
*expand_homedir(gchar
*str
)
807 return g_strdup_printf("%s%s", g_get_home_dir(), p
);
809 return g_strdup(str
);
812 static gchar
*_getline(const gchar
*file
)
815 gchar buf
[LINE_MAX
], *p
;
818 if ((fp
= fopen(file
, "r")) == NULL
) {
823 if ((p
= fgets(buf
, sizeof(buf
), fp
)) == NULL
) {
824 warnx(N_("%s: empty file?"), file
);
830 if (buf
[strlen(buf
) - 1] == '\n')
831 buf
[strlen(buf
) - 1] = 0;
833 str
= gcry_malloc(strlen(p
) + 1);
834 memcpy(str
, p
, strlen(p
));
836 memset(&buf
, 0, sizeof(buf
));
840 static gboolean
parse_keyfile_key()
847 groups
= g_key_file_get_groups(keyfileh
, &n
);
849 for (p
= groups
; *p
; p
++) {
850 GError
*error
= NULL
;
852 if (g_key_file_has_key(keyfileh
, *p
, "key", &error
) == TRUE
) {
853 str
= g_key_file_get_string(keyfileh
, *p
, "key", &error
);
857 warnx("%s", error
->message
);
858 g_clear_error(&error
);
864 do_cache_push(*p
, str
);
870 warnx("%s", error
->message
);
871 g_clear_error(&error
);
875 if (g_key_file_has_key(keyfileh
, *p
, "key_file", &error
) == TRUE
) {
877 gchar
*file
= g_key_file_get_string(keyfileh
, *p
, "key_file", &error
);
881 warnx("%s", error
->message
);
882 g_clear_error(&error
);
888 t
= expand_homedir(file
);
892 if ((str
= _getline(file
)) == NULL
) {
898 do_cache_push(*p
, str
);
904 warnx("%s", error
->message
);
905 g_clear_error(&error
);
913 static gboolean
do_cache_push(const gchar
*filename
, const gchar
*password
)
918 const gchar
*p
= filename
;
926 if (valid_filename(p
) == FALSE
) {
927 warnx(N_("%s: invalid characters in filename"), p
);
931 md5file
= gcry_malloc(16);
932 key
= gcry_malloc(gcrykeysize
);
933 gcry_md_hash_buffer(GCRY_MD_MD5
, md5file
, p
, strlen(p
));
935 if (cache_iscached(md5file
) == TRUE
) {
936 warnx(N_("%s: file already cached, skipping"), p
);
942 if (access(p
, R_OK
|W_OK
) != 0) {
946 if (errno
!= ENOENT
) {
956 if (get_input(p
, key
) == FALSE
) {
963 gcry_md_hash_buffer(GCRY_MD_SHA256
, key
, password
, strlen(password
));
965 if (do_try_xml_decrypt(filename
, key
) == FALSE
) {
966 warnx(N_("%s: invalid password, skipping"), filename
);
973 if (cache_add_file(md5file
, key
) == FALSE
) {
974 warnx("%s: %s", p
, pwmd_strerror(EPWMD_MAX_SLOTS
));
980 timeout
= get_key_file_integer(p
, "cache_timeout");
981 cache_set_timeout(md5file
, timeout
);
982 warnx(N_("%s: file added to the cache"), filename
);
988 static GSList
*remove_connection(GSList
*list
, struct client_thread_s
*cn
)
991 struct client_s
*cl
= cn
->cl
;
993 if (cn
->keepalive_tid
) {
994 pth_raise(cn
->keepalive_tid
, SIGALRM
);
995 pth_join(cn
->keepalive_tid
, &value
);
998 pth_join(cn
->tid
, &value
);
1001 if (cl
->freed
== FALSE
)
1002 cleanup_assuan(cl
->ctx
);
1005 assuan_deinit_server(cl
->ctx
);
1010 pth_event_isolate(cn
->ev
);
1011 pth_event_free(cn
->ev
, PTH_FREE_THIS
);
1012 log_write(N_("client exited: fd=%i"), cn
->fd
);
1013 list
= g_slist_remove(list
, cn
);
1019 * Can't pth_event_concat() to an empty event.
1021 static int event_ring_hack(void *data
)
1027 * See if any thread has entered the DEAD queue and remove it.
1029 static GSList
*cleanup_dead_queue(GSList
*threads
, pth_event_t tid_events
)
1033 for (n
= g_slist_length(threads
), i
= 0; i
< n
; i
++) {
1034 struct client_thread_s
*cn
= g_slist_nth_data(threads
, i
);
1036 if (pth_event_occurred(cn
->ev
)) {
1037 threads
= remove_connection(threads
, cn
);
1038 return cleanup_dead_queue(threads
, tid_events
);
1041 pth_event_concat(tid_events
, cn
->ev
, NULL
);
1047 static void *socket_thread(void *arg
)
1049 gint sockfd
= (gint
)arg
;
1053 * Thread priority is inherited from the calling thread. This thread is
1054 * PTH_PRIO_MAX. Keep the "child" threads at standard priority.
1056 attr
= pth_attr_new();
1057 pth_attr_set(attr
, PTH_ATTR_PRIO
, PTH_PRIO_STD
);
1060 socklen_t slen
= sizeof(struct sockaddr_un
);
1061 struct sockaddr_un raddr
;
1064 if ((fd
= pth_accept(sockfd
, (struct sockaddr
*)&raddr
, &slen
)) == -1) {
1065 if (errno
!= EAGAIN
) {
1066 if (!quit
) // probably EBADF
1067 log_write("accept(): %s", strerror(errno
));
1075 struct client_thread_s
*new;
1077 new = g_malloc0(sizeof(struct client_thread_s
));
1080 log_write("%s", strerror(ENOMEM
));
1084 log_write(N_("new connection: fd=%i"), fd
);
1086 tid
= pth_spawn(attr
, client_thread
, new);
1090 log_write(N_("pth_spawn() failed"));
1096 new->ev
= pth_event(PTH_EVENT_TID
|PTH_UNTIL_TID_DEAD
, tid
);
1097 pth_mutex_acquire(&cn_mutex
, FALSE
, NULL
);
1098 pth_event_concat(cn_events
, new->ev
, NULL
);
1099 cn_thread_list
= g_slist_append(cn_thread_list
, new);
1100 pth_mutex_release(&cn_mutex
);
1104 pth_attr_destroy(attr
);
1106 /* Just in case pth_accept() failed for some reason other than EBADF */
1108 pth_exit(PTH_CANCELED
);
1112 static void *cleanup_thread(void *arg
)
1114 cn_events
= pth_event(PTH_EVENT_TIME
, pth_timeout(0, 500000));
1117 if (pth_wait(cn_events
) && pth_event_occurred(cn_events
)) {
1118 pth_mutex_acquire(&cn_mutex
, FALSE
, NULL
);
1119 pth_event_isolate(cn_events
);
1120 pth_event_free(cn_events
, PTH_FREE_THIS
);
1121 cn_events
= pth_event(PTH_EVENT_TIME
, pth_timeout(0, 500000));
1122 cn_thread_list
= cleanup_dead_queue(cn_thread_list
, cn_events
);
1123 pth_mutex_release(&cn_mutex
);
1127 pth_event_isolate(cn_events
);
1128 pth_event_free(cn_events
, PTH_FREE_THIS
);
1132 static void *adjust_cache_time_thread(void *arg
)
1135 cache_adjust_timer();
1140 static void server_loop(int sockfd
)
1142 pth_t socket_tid
, cleanup_tid
;
1147 pth_event_t timeout_event
;
1150 pth_mutex_init(&cn_mutex
);
1151 log_write(N_("%s started for user %s"), PACKAGE_STRING
, g_get_user_name());
1154 sigaddset(&set
, SIGTERM
);
1155 sigaddset(&set
, SIGINT
);
1156 sigaddset(&set
, SIGUSR1
);
1157 sigaddset(&set
, SIGHUP
);
1158 sigaddset(&set
, SIGABRT
);
1160 attr
= pth_attr_new();
1161 pth_attr_init(attr
);
1162 pth_attr_set(attr
, PTH_ATTR_PRIO
, PTH_PRIO_MAX
);
1163 socket_tid
= pth_spawn(attr
, socket_thread
, (void *)sockfd
);
1164 pth_attr_set(attr
, PTH_ATTR_JOINABLE
, FALSE
);
1165 pth_attr_set(attr
, PTH_ATTR_CANCEL_STATE
, PTH_CANCEL_ASYNCHRONOUS
);
1166 cleanup_tid
= pth_spawn(attr
, cleanup_thread
, NULL
);
1169 * For the cache_timeout configuration parameter. This replaces the old
1170 * SIGALRM stuff and is safer.
1172 timeout_event
= pth_event(PTH_EVENT_TIME
, pth_timeout(1, 0));
1173 pth_attr_init(attr
);
1174 pth_attr_set(attr
, PTH_ATTR_JOINABLE
, FALSE
);
1175 pth_attr_set(attr
, PTH_ATTR_PRIO
, PTH_PRIO_MAX
);
1180 pth_sigwait_ev(&set
, &sig
, timeout_event
);
1182 if (pth_event_occurred(timeout_event
)) {
1184 * The timer event has expired. Update the file cache. When the
1185 * cache mutex is locked and the timer expires again, the threads
1188 pth_spawn(attr
, adjust_cache_time_thread
, NULL
);
1189 pth_event_free(timeout_event
, PTH_FREE_THIS
);
1190 timeout_event
= pth_event(PTH_EVENT_TIME
, pth_timeout(1, 0));
1194 log_write(N_("caught signal %i (%s)"), sig
, strsignal(sig
));
1196 /* Caught a signal. */
1203 cache_clear(NULL
, 2);
1211 log_write(N_("clearing file cache"));
1212 cache_clear(NULL
, 2);
1217 shutdown(sockfd
, SHUT_RDWR
);
1225 * We're out of the main server loop. This happens when a signal was sent
1226 * to terminate the daemon. We'll wait for all clients to disconnect
1227 * before exiting and ignore any following signals.
1229 pth_join(socket_tid
, &value
);
1230 pth_attr_destroy(attr
);
1231 pth_event_free(timeout_event
, PTH_FREE_THIS
);
1233 n
= pth_ctrl(PTH_CTRL_GETTHREADS
);
1235 /* 2 because the cleanup thread still exists, plus self. */
1237 log_write(N_("waiting for all threads to terminate"));
1243 if (n
!= n_clients
) {
1244 log_write(N_("%i threads remain"), n
-2);
1248 events
= pth_event(PTH_EVENT_FUNC
, event_ring_hack
, NULL
, pth_timeout(1, 0));
1249 pth_mutex_acquire(&cn_mutex
, FALSE
, NULL
);
1251 for (t
= g_slist_length(cn_thread_list
), i
= 0; i
< t
; i
++) {
1252 struct client_thread_s
*cn
= g_slist_nth_data(cn_thread_list
, i
);
1254 pth_event_concat(events
, cn
->ev
, NULL
);
1260 pth_mutex_release(&cn_mutex
);
1262 pth_yield(cleanup_tid
);
1264 pth_event_isolate(events
);
1265 pth_event_free(events
, PTH_FREE_THIS
);
1266 n
= pth_ctrl(PTH_CTRL_GETTHREADS
);
1269 pth_cancel(cleanup_tid
);
1272 int main(int argc
, char *argv
[])
1275 struct sockaddr_un addr
;
1276 struct passwd
*pw
= getpwuid(getuid());
1277 gchar buf
[PATH_MAX
];
1278 gchar
*socketpath
= NULL
, *socketdir
, *socketname
= NULL
;
1279 gchar
*socketarg
= NULL
;
1280 gchar
*datadir
= NULL
;
1283 gchar
**cache_push
= NULL
;
1285 gchar
*import
= NULL
;
1286 gint default_timeout
;
1287 gint rcfile_spec
= 0;
1288 gint estatus
= EXIT_FAILURE
;
1291 GMemVTable mtable
= { xmalloc
, xrealloc
, xfree
, xcalloc
, NULL
, NULL
};
1294 gboolean secure
= FALSE
;
1296 gint background
= 0;
1299 #ifdef HAVE_SETRLIMIT
1302 rl
.rlim_cur
= rl
.rlim_max
= 0;
1304 if (setrlimit(RLIMIT_CORE
, &rl
) != 0)
1305 err(EXIT_FAILURE
, "setrlimit()");
1310 setlocale(LC_ALL
, "");
1311 bindtextdomain("pwmd", LOCALEDIR
);
1316 assuan_set_assuan_err_source(GPG_ERR_SOURCE_DEFAULT
);
1318 g_mem_set_vtable(&mtable
);
1319 assuan_set_malloc_hooks(xmalloc
, xrealloc
, xfree
);
1320 xmlMemSetup(xfree
, xmalloc
, xrealloc
, xstrdup
);
1324 snprintf(buf
, sizeof(buf
), "%s/.pwmd", pw
->pw_dir
);
1326 if (mkdir(buf
, 0700) == -1 && errno
!= EEXIST
)
1327 err(EXIT_FAILURE
, "%s", buf
);
1329 snprintf(buf
, sizeof(buf
), "%s/.pwmd/data", pw
->pw_dir
);
1331 if (mkdir(buf
, 0700) == -1 && errno
!= EEXIST
)
1332 err(EXIT_FAILURE
, "%s", buf
);
1334 rcfile
= g_strdup_printf("%s/.pwmd/config", pw
->pw_dir
);
1336 if ((page_size
= sysconf(_SC_PAGESIZE
)) == -1)
1337 err(EXIT_FAILURE
, "sysconf()");
1339 cache_size
= page_size
;
1341 while ((opt
= getopt(argc
, argv
, "bI:hvf:D")) != EOF
) {
1354 rcfile
= g_strdup(optarg
);
1358 printf("%s\n%s\n", PACKAGE_STRING
, PACKAGE_BUGREPORT
);
1366 if ((keyfileh
= parse_rcfile(rcfile_spec
)) == NULL
)
1369 if (g_key_file_has_key(keyfileh
, "default", "syslog", NULL
) == TRUE
)
1370 log_syslog
= g_key_file_get_boolean(keyfileh
, "default", "syslog", NULL
);
1372 if (log_syslog
== TRUE
)
1373 openlog("pwmd", LOG_NDELAY
|LOG_PID
, LOG_DAEMON
);
1375 if (g_key_file_has_key(keyfileh
, "default", "iterations", NULL
) == TRUE
)
1376 iter
= g_key_file_get_integer(keyfileh
, "default", "iterations", NULL
);
1378 #ifdef HAVE_MLOCKALL
1379 if (disable_mlock
== FALSE
&& mlockall(MCL_FUTURE
) == -1) {
1388 opt
= xml_import(import
, iter
);
1389 g_key_file_free(keyfileh
);
1391 exit(opt
== FALSE
? EXIT_FAILURE
: EXIT_SUCCESS
);
1394 g_key_file_set_list_separator(keyfileh
, ',');
1396 if ((p
= g_key_file_get_string(keyfileh
, "default", "socket_path", NULL
)) == NULL
)
1397 errx(EXIT_FAILURE
, N_("%s: socket_path not defined"), rcfile
);
1401 snprintf(buf
, sizeof(buf
), "%s%s", g_get_home_dir(), p
--);
1403 socketarg
= g_strdup(buf
);
1408 if ((p
= g_key_file_get_string(keyfileh
, "default", "data_directory", NULL
)) == NULL
)
1409 errx(EXIT_FAILURE
, N_("%s: data_directory not defined"), rcfile
);
1411 datadir
= expand_homedir(p
);
1414 if (secure
== FALSE
&& g_key_file_has_key(keyfileh
, "default", "disable_list_and_dump", NULL
) == TRUE
) {
1415 n
= g_key_file_get_boolean(keyfileh
, "default", "disable_list_and_dump", NULL
);
1416 disable_list_and_dump
= n
;
1419 disable_list_and_dump
= secure
;
1421 if (g_key_file_has_key(keyfileh
, "default", "cache_timeout", NULL
) == TRUE
)
1422 default_timeout
= g_key_file_get_integer(keyfileh
, "default", "cache_timeout", NULL
);
1424 default_timeout
= -1;
1426 if (g_key_file_has_key(keyfileh
, "default", "cache_size", NULL
) == TRUE
) {
1427 cache_size
= g_key_file_get_integer(keyfileh
, "default", "cache_size", NULL
);
1429 if (cache_size
< page_size
|| cache_size
% page_size
)
1430 errx(EXIT_FAILURE
, N_("cache size must be in multiples of %li"), page_size
);
1433 if (g_key_file_has_key(keyfileh
, "default", "log_path", NULL
) == TRUE
) {
1434 if (g_key_file_has_key(keyfileh
, "default", "enable_logging", NULL
) == TRUE
) {
1435 n
= g_key_file_get_boolean(keyfileh
, "default", "enable_logging", NULL
);
1438 p
= g_key_file_get_string(keyfileh
, "default", "log_path", NULL
);
1442 snprintf(buf
, sizeof(buf
), "%s%s", g_get_home_dir(), p
--);
1444 logfile
= g_strdup(buf
);
1452 if (g_key_file_has_key(keyfileh
, "default", "cache_push", NULL
) == TRUE
)
1453 cache_push
= g_key_file_get_string_list(keyfileh
, "default", "cache_push", NULL
, NULL
);
1455 if (argc
!= optind
) {
1457 ptotal
= g_strv_length(cache_push
);
1459 for (; optind
< argc
; optind
++) {
1460 if (strv_printf(&cache_push
, "%s", argv
[optind
]) == FALSE
)
1461 errx(EXIT_FAILURE
, "%s", strerror(ENOMEM
));
1465 if (strchr(socketarg
, '/') == NULL
) {
1466 socketdir
= g_get_current_dir();
1467 socketname
= g_strdup(socketarg
);
1468 socketpath
= g_strdup_printf("%s/%s", socketdir
, socketname
);
1471 socketname
= g_strdup(strrchr(socketarg
, '/'));
1473 socketarg
[strlen(socketarg
) - strlen(socketname
) -1] = 0;
1474 socketdir
= g_strdup(socketarg
);
1475 socketpath
= g_strdup_printf("%s/%s", socketdir
, socketname
);
1478 if ((key_cache
= mmap(NULL
, cache_size
, PROT_READ
|PROT_WRITE
,
1479 #ifdef MMAP_ANONYMOUS
1480 MAP_PRIVATE
|MAP_ANONYMOUS
, -1, 0)) == MAP_FAILED
) {
1482 MAP_PRIVATE
|MAP_ANON
, -1, 0)) == MAP_FAILED
) {
1484 err(EXIT_FAILURE
, "mmap()");
1487 if (mlock(key_cache
, cache_size
) == -1)
1488 log_write("mlock(): %s", strerror(errno
));
1490 memset(key_cache
, 0, cache_size
);
1492 if (chdir(datadir
)) {
1493 warn("%s", datadir
);
1498 if (parse_keyfile_key() == FALSE
)
1504 * Set the cache entry for a file. Prompts for the password.
1507 for (opt
= 0; cache_push
[opt
]; opt
++)
1508 do_cache_push(cache_push
[opt
], NULL
);
1510 g_strfreev(cache_push
);
1511 warnx(background
? N_("Done. Daemonizing...") : N_("Done. Waiting for connections..."));
1515 * bind() doesn't like the full pathname of the socket or any non alphanum
1516 * characters so change to the directory where the socket is wanted then
1517 * create it then change to datadir.
1519 if (chdir(socketdir
)) {
1520 warn("%s", socketdir
);
1526 if ((sockfd
= socket(PF_UNIX
, SOCK_STREAM
, 0)) == -1) {
1531 addr
.sun_family
= AF_UNIX
;
1532 snprintf(addr
.sun_path
, sizeof(addr
.sun_path
), "%s", socketname
);
1534 if (bind(sockfd
, (struct sockaddr
*)&addr
, sizeof(struct sockaddr
)) == -1) {
1537 if (errno
== EADDRINUSE
)
1538 warnx(N_("Either there is another pwmd running or '%s' is a \n"
1539 "stale socket. Please remove it manually."), socketpath
);
1545 if (g_key_file_has_key(keyfileh
, "default", "socket_perms", NULL
) == TRUE
) {
1546 gchar
*t
= g_key_file_get_string(keyfileh
, "default", "socket_perms", NULL
);
1547 mode_t mode
= strtol(t
, NULL
, 8);
1548 mode_t mask
= umask(0);
1552 if (chmod(socketname
, mode
) == -1) {
1553 warn("%s", socketname
);
1563 g_free(--socketname
);
1565 if (chdir(datadir
)) {
1566 warn("%s", datadir
);
1573 pth_mutex_init(&cache_mutex
);
1575 if (listen(sockfd
, 0) == -1) {
1597 * These are the signals that we use in threads. libpth can catch signals
1598 * itself so ignore them everywhere else. Note that using
1599 * signal(N, SIG_IGN) doesn't work like you might think.
1604 sigaddset(&set
, SIGTERM
);
1605 sigaddset(&set
, SIGINT
);
1607 /* Configuration file reloading. */
1608 sigaddset(&set
, SIGUSR1
);
1610 /* Clears the file cache. */
1611 sigaddset(&set
, SIGHUP
);
1613 /* Caught in client_thread(). Sends a cache status message. */
1614 sigaddset(&set
, SIGUSR2
);
1616 /* Caught in client_thread(). When keepalive_thread() fails, this signal
1617 * is raised to terminate the client. More of a failsafe than anything. */
1618 sigaddset(&set
, SIGQUIT
);
1620 /* Ignored everywhere. When a client disconnects abnormally this signal
1621 * gets raised. It isn't needed though because client_thread() will check
1622 * for errors even after the client disconnects. */
1623 signal(SIGPIPE
, SIG_IGN
);
1624 pth_sigmask(SIG_BLOCK
, &set
, NULL
);
1625 server_loop(sockfd
);
1626 estatus
= EXIT_SUCCESS
;
1629 if (socketpath
&& do_unlink
) {
1634 g_key_file_free(keyfileh
);
1638 cache_clear(NULL
, 2);
1639 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"));
1649 #if defined(DEBUG) && !defined(MEM_DEBUG)