1 /* vim:tw=78:ts=8:sw=4:set ft=c: */
3 Copyright (C) 2006-2008 Ben Kibbey <bjk@luxsci.net>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02110-1301 USA
38 #include <glib/gprintf.h>
48 #include <sys/resource.h>
69 #include "pwmd_error.h"
74 static void clear_errorfile_key()
80 groups
= g_key_file_get_groups(keyfileh
, &n
);
82 for (p
= groups
; *p
; p
++) {
85 if (g_key_file_has_key(keyfileh
, *p
, "key", &rc
) == TRUE
)
86 g_key_file_set_string(keyfileh
, *p
, "key", "");
92 static void reload_rcfile()
94 log_write(N_("reloading configuration file '%s'"), rcfile
);
95 g_key_file_free(keyfileh
);
96 keyfileh
= parse_rcfile(0);
97 clear_errorfile_key();
98 send_status_all(STATUS_CONFIG
);
101 gpg_error_t
send_syserror(assuan_context_t ctx
, gint e
)
103 gpg_error_t n
= gpg_error_from_errno(e
);
105 return assuan_process_done(ctx
, assuan_set_error(ctx
, n
, gpg_strerror(n
)));
108 gpg_error_t
send_error(assuan_context_t ctx
, gpg_error_t e
)
110 gpg_err_code_t n
= gpg_err_code(e
);
111 gpg_error_t code
= gpg_err_make(PWMD_ERR_SOURCE
, n
);
112 struct client_s
*client
= assuan_get_pointer(ctx
);
115 return assuan_process_done(ctx
, 0);
118 log_write("%s\n", pwmd_strerror(e
));
122 if (n
== EPWMD_LIBXML_ERROR
) {
123 xmlErrorPtr xe
= client
->xml_error
;
126 xe
= xmlGetLastError();
128 e
= assuan_process_done(ctx
, assuan_set_error(ctx
, code
, xe
->message
));
129 log_write("%s", xe
->message
);
131 if (xe
== client
->xml_error
)
136 client
->xml_error
= NULL
;
140 return assuan_process_done(ctx
, assuan_set_error(ctx
, code
, pwmd_strerror(e
)));
143 void log_write(const gchar
*fmt
, ...)
153 pth_t tid
= pth_self();
154 gchar tid_str
[12], *p
;
156 if ((!logfile
&& !isatty(STDERR_FILENO
) && log_syslog
== FALSE
) || !fmt
)
160 if ((fd
= open(logfile
, O_WRONLY
|O_CREAT
|O_APPEND
, 0600)) == -1) {
168 if (g_vasprintf(&args
, fmt
, ap
) == -1) {
176 attr
= pth_attr_of(tid
);
178 if (pth_attr_get(attr
, PTH_ATTR_NAME
, &name
) == FALSE
)
181 pth_attr_destroy(attr
);
182 g_snprintf(tid_str
, sizeof(tid_str
), "(%p)", tid
);
185 if (strncmp(p
+1, name
, 9) == 0)
188 if (log_syslog
== TRUE
)
189 syslog(LOG_INFO
, "%s%s: %s", name
, p
? p
: "", args
);
193 tm
= localtime(&now
);
194 strftime(tbuf
, sizeof(tbuf
), "%b %d %Y %H:%M:%S ", tm
);
195 tbuf
[sizeof(tbuf
) - 1] = 0;
197 if (args
[strlen(args
)-1] == '\n')
198 args
[strlen(args
)-1] = 0;
200 line
= g_strdup_printf("%s %i %s%s: %s\n", tbuf
, getpid(), name
,
212 write(fd
, line
, strlen(line
));
217 if (isatty(STDERR_FILENO
)) {
218 fprintf(stderr
, "%s", line
);
225 static void usage(gchar
*pn
)
228 "Usage: %s [-hvDn] [-f <rcfile>] [-I <filename> [-i <iter>]] [file1] [...]\n"
229 " -n run as a foreground process\n"
230 " -f load the specified rcfile (~/.pwmd/config)\n"
231 " -I import an XML file and write the encrypted data to stdout\n"
232 " -i encrypt with the specified number of iterations when importing\n"
233 " (config default in the \"global\" section)\n"
234 " -D disable use of the LIST and DUMP commands\n"
236 " -h this help text\n"
242 static int gcry_SecureCheck(const void *ptr
)
248 static void setup_gcrypt()
250 gcry_check_version(NULL
);
253 gcry_set_allocation_handler(xmalloc
, xmalloc
, gcry_SecureCheck
, xrealloc
,
257 if (gcry_cipher_algo_info(GCRY_CIPHER_AES256
, GCRYCTL_TEST_ALGO
, NULL
,
259 errx(EXIT_FAILURE
, N_("Required AES cipher not supported by libgcrypt."));
261 gcry_cipher_algo_info(GCRY_CIPHER_AES256
, GCRYCTL_GET_KEYLEN
, NULL
, &gcrykeysize
);
262 gcry_cipher_algo_info(GCRY_CIPHER_AES256
, GCRYCTL_GET_BLKLEN
, NULL
, &gcryblocksize
);
265 static assuan_context_t
new_connection(gint fd
)
268 gchar ver
[ASSUAN_LINELENGTH
];
269 assuan_context_t ctx
;
271 rc
= assuan_init_socket_server_ext(&ctx
, fd
, 2);
276 g_snprintf(ver
, sizeof(ver
), "%s", PACKAGE_STRING
);
277 assuan_set_hello_line(ctx
, ver
);
278 rc
= register_commands(ctx
);
283 rc
= assuan_accept(ctx
);
291 assuan_deinit_server(ctx
);
292 log_write("%s", gpg_strerror(rc
));
296 gpg_error_t
send_status(assuan_context_t ctx
, status_msg_t which
)
299 struct client_s
*client
= assuan_get_pointer(ctx
);
300 gchar buf
[ASSUAN_LINELENGTH
];
301 gchar
*status
= NULL
;
305 CACHE_LOCK(client
->ctx
);
306 line
= print_fmt(buf
, sizeof(buf
), "%i %i",
308 (cache_size
% sizeof(file_cache_t
)) ?
309 (cache_size
/ sizeof(file_cache_t
)) - cache_file_count()-1 :
310 (cache_size
/ sizeof(file_cache_t
)) - cache_file_count());
315 pth_mutex_acquire(&cn_mutex
, FALSE
, NULL
);
316 line
= print_fmt(buf
, sizeof(buf
), "%i", g_slist_length(cn_thread_list
));
317 pth_mutex_release(&cn_mutex
);
323 case STATUS_KEEPALIVE
:
324 status
= "KEEPALIVE";
328 line
= N_("Waiting for lock");
332 return assuan_write_status(ctx
, status
, line
);
335 void send_status_all(status_msg_t which
)
339 pth_mutex_acquire(&cn_mutex
, FALSE
, NULL
);
341 for (t
= g_slist_length(cn_thread_list
), i
= 0; i
< t
; i
++) {
342 struct client_thread_s
*cn
= g_slist_nth_data(cn_thread_list
, i
);
343 pth_msgport_t m
= pth_msgport_find(cn
->msg_name
);
346 pth_message_t
*msg
= g_malloc0(sizeof(pth_message_t
));
348 msg
->m_data
= (status_msg_t
*)which
;
349 pth_msgport_put(m
, msg
);
353 pth_mutex_release(&cn_mutex
);
356 static void xml_error_cb(void *data
, xmlErrorPtr e
)
358 struct client_s
*client
= data
;
361 * Keep the first reported error as the one to show in the error
362 * description. Reset in send_error().
364 if (client
->xml_error
)
367 xmlCopyError(e
, client
->xml_error
);
371 * This is called after a child_thread terminates. Set with
372 * pth_cleanup_push().
374 static void cleanup_cb(void *arg
)
376 struct client_thread_s
*cn
= arg
;
378 struct client_s
*cl
= cn
->cl
;
380 pth_mutex_acquire(&cn_mutex
, FALSE
, NULL
);
381 log_write(N_("exiting, fd=%i"), cn
->fd
);
384 pth_cancel(cn
->msg_tid
);
385 pth_join(cn
->msg_tid
, &value
);
386 pth_event_free(cn
->msg_ev
, PTH_FREE_THIS
);
390 g_free(cn
->msg_name
);
393 while (pth_msgport_pending(cn
->msg
) > 0) {
394 pth_message_t
*m
= pth_msgport_get(cn
->msg
);
399 pth_msgport_destroy(cn
->msg
);
402 pth_join(cn
->tid
, &value
);
404 if (cl
&& cl
->freed
== FALSE
)
405 cleanup_assuan(cl
->ctx
);
408 assuan_deinit_server(cl
->ctx
);
411 if (cl
&& cl
->pinentry
)
412 cleanup_pinentry(cl
->pinentry
);
416 cn_thread_list
= g_slist_remove(cn_thread_list
, cn
);
418 pth_mutex_release(&cn_mutex
);
419 send_status_all(STATUS_CLIENTS
);
422 static void *client_msg_thread(void *data
)
424 struct client_s
*cl
= data
;
425 pth_status_t ev_status
;
428 pth_wait(cl
->thd
->msg_ev
);
429 ev_status
= pth_event_status(cl
->thd
->msg_ev
);
431 if (ev_status
== PTH_STATUS_FAILED
) {
432 log_write("%s(%i): %s: PTH_STATUS_FAILED", __FILE__
, __LINE__
,
437 if (ev_status
== PTH_STATUS_OCCURRED
) {
438 pth_mutex_acquire(&cn_mutex
, FALSE
, NULL
);
440 while (pth_msgport_pending(cl
->thd
->msg
) > 0) {
441 pth_message_t
*m
= pth_msgport_get(cl
->thd
->msg
);
442 status_msg_t n
= (status_msg_t
)m
->m_data
;
443 gpg_error_t rc
= send_status(cl
->ctx
, n
);
448 pth_mutex_release(&cn_mutex
);
449 log_write("%s", gpg_strerror(rc
));
454 pth_mutex_release(&cn_mutex
);
460 * Called every time a connection is made via pth_spawn(). This is the thread
463 static void *client_thread(void *data
)
465 struct client_thread_s
*thd
= data
;
468 struct client_s
*cl
= g_malloc0(sizeof(struct client_s
));
473 log_write("%s(%i): %s", __FILE__
, __LINE__
, strerror(ENOMEM
));
478 cl
->pinentry
= pinentry_init();
482 log_write("%s(%i): %s", __FILE__
, __LINE__
, strerror(ENOMEM
));
489 pth_cleanup_push(cleanup_cb
, thd
);
490 thd
->msg_name
= g_strdup_printf("%p", thd
->tid
);
492 if (!thd
->msg_name
) {
493 log_write("%s(%i): %s", __FILE__
, __LINE__
, strerror(ENOMEM
));
497 thd
->msg
= pth_msgport_create(thd
->msg_name
);
500 log_write("%s(%i): %s", __FILE__
, __LINE__
, strerror(ENOMEM
));
504 thd
->msg_ev
= pth_event(PTH_EVENT_MSG
, thd
->msg
);
505 attr
= pth_attr_new();
506 pth_attr_set(attr
, PTH_ATTR_PRIO
, PTH_PRIO_STD
);
507 thd
->msg_tid
= pth_spawn(attr
, client_msg_thread
, cl
);
508 pth_attr_destroy(attr
);
511 log_write(N_("pth_spawn() failed"));
516 * This is a "child" thread. Don't catch any signals. Let the master
517 * thread take care of signals in accept_thread().
519 cl
->ctx
= new_connection(fd
);
525 assuan_set_pointer(cl
->ctx
, cl
);
528 if (disable_mlock
== FALSE
&& mlockall(MCL_FUTURE
) == -1) {
529 log_write("mlockall(): %s", strerror(errno
));
534 rc
= send_status(cl
->ctx
, STATUS_CACHE
);
537 log_write("%s", gpg_strerror(rc
));
541 send_status_all(STATUS_CLIENTS
);
542 ev
= pth_event(PTH_EVENT_FD
|PTH_UNTIL_FD_READABLE
, cl
->fd
);
545 xmlSetStructuredErrorFunc(cl
, xml_error_cb
);
548 pth_status_t ev_status
;
551 ev_status
= pth_event_status(ev
);
553 if (ev_status
== PTH_STATUS_FAILED
) {
554 log_write("%s(%i): %s: PTH_STATUS_FAILED", __FILE__
, __LINE__
,
558 else if (ev_status
== PTH_STATUS_OCCURRED
) {
559 rc
= assuan_process_next(cl
->ctx
);
562 cl
->inquire_status
= INQUIRE_INIT
;
564 if (gpg_err_code(rc
) == GPG_ERR_EOF
)
567 log_write("assuan_process_next(): %s", gpg_strerror(rc
));
568 rc
= send_error(cl
->ctx
, gpg_err_make(PWMD_ERR_SOURCE
, rc
));
571 log_write("assuan_process_done(): %s", gpg_strerror(rc
));
577 if (cl
->pinentry
->pid
&& cl
->pinentry
->status
== PINENTRY_INIT
) {
578 cl
->pinentry
->ev
= pth_event(PTH_EVENT_FD
|PTH_UNTIL_FD_READABLE
, cl
->pinentry
->fd
);
579 pth_event_concat(ev
, cl
->pinentry
->ev
, NULL
);
580 cl
->pinentry
->status
= PINENTRY_RUNNING
;
584 switch (cl
->inquire_status
) {
589 cl
->inquire_status
= INQUIRE_INIT
;
590 rc
= assuan_process_done(cl
->ctx
, 0);
597 ev
= pinentry_iterate(cl
, ev
);
602 * Client cleanup (including XML data) is done in cleanup_cb() from
603 * the cleanup thread.
606 pth_event_free(ev
, PTH_FREE_ALL
);
613 static void setup_logging(GKeyFile
*kf
)
615 gboolean n
= g_key_file_get_boolean(kf
, "global", "enable_logging", NULL
);
618 gchar
*p
= g_key_file_get_string(kf
, "global", "log_path", NULL
);
624 g_snprintf(buf
, sizeof(buf
), "%s%s", g_get_home_dir(), p
--);
630 logfile
= g_strdup(buf
);
640 log_syslog
= g_key_file_get_boolean(kf
, "global", "syslog", NULL
);
644 * Make sure all settings are set to either the specified setting or a
647 static void set_rcfile_defaults(GKeyFile
*kf
)
651 if (g_key_file_has_key(kf
, "global", "socket_path", NULL
) == FALSE
) {
652 g_snprintf(buf
, sizeof(buf
), "~/.pwmd/socket");
653 g_key_file_set_string(kf
, "global", "socket_path", buf
);
656 if (g_key_file_has_key(kf
, "global", "data_directory", NULL
) == FALSE
) {
657 g_snprintf(buf
, sizeof(buf
), "~/.pwmd/data");
658 g_key_file_set_string(kf
, "global", "data_directory", buf
);
661 if (g_key_file_has_key(kf
, "global", "backup", NULL
) == FALSE
)
662 g_key_file_set_boolean(kf
, "global", "backup", TRUE
);
664 if (g_key_file_has_key(kf
, "global", "log_path", NULL
) == FALSE
) {
665 g_snprintf(buf
, sizeof(buf
), "~/.pwmd/log");
666 g_key_file_set_string(kf
, "global", "log_path", buf
);
669 if (g_key_file_has_key(kf
, "global", "enable_logging", NULL
) == FALSE
)
670 g_key_file_set_boolean(kf
, "global", "enable_logging", FALSE
);
672 if (g_key_file_has_key(kf
, "global", "cache_size", NULL
) == FALSE
)
673 g_key_file_set_integer(kf
, "global", "cache_size", cache_size
);
676 if (g_key_file_has_key(kf
, "global", "disable_mlockall", NULL
) == FALSE
)
677 g_key_file_set_boolean(kf
, "global", "disable_mlockall", TRUE
);
680 if (g_key_file_has_key(kf
, "global", "cache_timeout", NULL
) == FALSE
)
681 g_key_file_set_integer(kf
, "global", "cache_timeout", -1);
683 if (g_key_file_has_key(kf
, "global", "iterations", NULL
) == FALSE
)
684 g_key_file_set_integer(kf
, "global", "iterations", 0);
686 if (g_key_file_has_key(kf
, "global", "disable_list_and_dump", NULL
) == FALSE
)
687 g_key_file_set_boolean(kf
, "global", "disable_list_and_dump", FALSE
);
689 if (g_key_file_has_key(kf
, "global", "iteration_progress", NULL
) == FALSE
)
690 g_key_file_set_integer(kf
, "global", "iteration_progress", 0);
692 if (g_key_file_has_key(kf
, "global", "compression_level", NULL
) == FALSE
)
693 g_key_file_set_integer(kf
, "global", "compression_level", 6);
695 if (g_key_file_has_key(kf
, "global", "recursion_depth", NULL
) == FALSE
)
696 g_key_file_set_integer(kf
, "global", "recursion_depth", DEFAULT_RECURSION_DEPTH
);
698 if (g_key_file_has_key(kf
, "global", "zlib_bufsize", NULL
) == FALSE
)
699 g_key_file_set_integer(kf
, "global", "zlib_bufsize", DEFAULT_ZLIB_BUFSIZE
);
701 zlib_bufsize
= g_key_file_get_integer(kf
, "global", "zlib_bufsize", NULL
);
703 max_recursion_depth
= g_key_file_get_integer(kf
, "global", "recursion_depth", NULL
);
704 disable_list_and_dump
= g_key_file_get_boolean(kf
, "global", "disable_list_and_dump", NULL
);
707 disable_mlock
= g_key_file_get_boolean(kf
, "global", "disable_mlockall", NULL
);
710 if (g_key_file_has_key(kf
, "global", "syslog", NULL
) == FALSE
)
711 g_key_file_set_boolean(kf
, "global", "syslog", FALSE
);
713 if (g_key_file_has_key(kf
, "global", "keepalive", NULL
) == FALSE
)
714 g_key_file_set_integer(kf
, "global", "keepalive", 30);
717 if (g_key_file_has_key(kf
, "global", "enable_pinentry", NULL
) == FALSE
)
718 g_key_file_set_boolean(kf
, "global", "enable_pinentry", TRUE
);
720 if (g_key_file_has_key(kf
, "global", "pinentry_timeout", NULL
) == FALSE
)
721 g_key_file_set_integer(kf
, "global", "pinentry_timeout", 20);
727 static GKeyFile
*parse_rcfile(int cmdline
)
729 GKeyFile
*kf
= g_key_file_new();
732 if (g_key_file_load_from_file(kf
, rcfile
, G_KEY_FILE_NONE
, &rc
) == FALSE
) {
733 log_write("%s: %s", rcfile
, rc
->message
);
738 if (rc
->code
== G_FILE_ERROR_NOENT
) {
740 set_rcfile_defaults(kf
);
748 set_rcfile_defaults(kf
);
753 static gchar
*get_password(const gchar
*prompt
)
755 gchar buf
[LINE_MAX
] = {0}, *p
;
756 struct termios told
, tnew
;
759 if (tcgetattr(STDIN_FILENO
, &told
) == -1)
760 err(EXIT_FAILURE
, "tcgetattr()");
762 memcpy(&tnew
, &told
, sizeof(struct termios
));
763 tnew
.c_lflag
&= ~(ECHO
);
764 tnew
.c_lflag
|= ICANON
|ECHONL
;
766 if (tcsetattr(STDIN_FILENO
, TCSANOW
, &tnew
) == -1) {
767 tcsetattr(STDIN_FILENO
, TCSANOW
, &told
);
768 err(EXIT_FAILURE
, "tcsetattr()");
771 fprintf(stderr
, "%s", prompt
);
773 if ((p
= fgets(buf
, sizeof(buf
), stdin
)) == NULL
) {
774 tcsetattr(STDIN_FILENO
, TCSANOW
, &told
);
778 tcsetattr(STDIN_FILENO
, TCSANOW
, &told
);
779 p
[strlen(p
) - 1] = 0;
782 key
= gcry_malloc(1);
786 key
= gcry_malloc(strlen(p
) + 1);
787 sprintf(key
, "%s", p
);
790 memset(&buf
, 0, sizeof(buf
));
794 static gboolean
do_try_xml_decrypt(const gchar
*filename
, guchar
*key
)
801 if ((fd
= open_file(filename
, &st
)) == -1) {
802 warn("%s", filename
);
806 if (st
.st_size
== 0) {
807 warnx(N_("%s: skipping empty file"), filename
);
812 rc
= try_xml_decrypt(NULL
, fd
, st
, key
, &iter
);
814 return rc
? FALSE
: TRUE
;
817 static gboolean
get_input(const gchar
*filename
, guchar
*key
)
823 prompt
= g_strdup_printf(N_("Password for '%s': "), filename
);
826 if ((password
= get_password(prompt
)) == NULL
) {
827 warnx(N_("%s: skipping file"), filename
);
832 gcry_md_hash_buffer(GCRY_MD_SHA256
, key
, password
, strlen(password
) ? strlen(password
) : 1);
835 if (do_try_xml_decrypt(filename
, key
) == FALSE
) {
837 warnx(N_("%s: invalid password, skipping"), filename
);
842 warnx(N_("%s: invalid password"), filename
);
851 static gboolean
xml_import(const gchar
*filename
, gint iter
)
861 guchar shakey
[gcrykeysize
];
869 if (stat(filename
, &st
) == -1) {
870 warn("%s", filename
);
874 if ((rc
= gcry_cipher_open(&gh
, GCRY_CIPHER_AES256
, GCRY_CIPHER_MODE_CBC
, 0))) {
875 send_error(NULL
, rc
);
876 gcry_cipher_close(gh
);
877 log_write("%s(%i): %s", __FUNCTION__
, __LINE__
, gcry_strerror(rc
));
884 if ((key
= get_password(N_("New password: "))) == NULL
) {
885 fprintf(stderr
, "%s\n", N_("Invalid password."));
886 gcry_cipher_close(gh
);
890 if ((key2
= get_password(N_("Verify password: "))) == NULL
) {
891 fprintf(stderr
, "%s\n", N_("Passwords do not match."));
893 gcry_cipher_close(gh
);
897 if (g_utf8_collate(key
, key2
) != 0) {
898 fprintf(stderr
, "%s\n", N_("Passwords do not match."));
901 gcry_cipher_close(gh
);
908 if ((fd
= open(filename
, O_RDONLY
)) == -1) {
910 warn("%s", filename
);
911 gcry_cipher_close(gh
);
915 if ((xmlbuf
= gcry_malloc(st
.st_size
+1)) == NULL
) {
918 log_write("%s", strerror(ENOMEM
));
919 gcry_cipher_close(gh
);
923 if (read(fd
, xmlbuf
, st
.st_size
) == -1) {
927 gcry_cipher_close(gh
);
929 err(EXIT_FAILURE
, "read()");
933 xmlbuf
[st
.st_size
] = 0;
936 * Make sure the document validates.
938 if ((doc
= xmlReadDoc(xmlbuf
, NULL
, "UTF-8", XML_PARSE_NOBLANKS
)) == NULL
) {
939 log_write("xmlReadDoc()");
943 gcry_cipher_close(gh
);
948 xmlDocDumpMemory(doc
, &xml
, &len
);
951 level
= get_key_file_integer(filename
, "compression_level");
956 if (do_compress(NULL
, level
, xml
, len
, &outbuf
, &outsize
, &zrc
) == FALSE
) {
957 memset(shakey
, 0, sizeof(shakey
));
960 if (zrc
== Z_MEM_ERROR
)
961 warnx("%s", strerror(ENOMEM
));
963 warnx("do_compress() failed");
965 gcry_cipher_close(gh
);
975 memset(shakey
, '!', sizeof(shakey
));
977 gcry_md_hash_buffer(GCRY_MD_SHA256
, shakey
, key
, strlen(key
) ? strlen(key
) : 1);
981 rc
= do_xml_encrypt(NULL
, gh
, NULL
, xml
, len
, shakey
, iter
);
982 gcry_cipher_close(gh
);
985 memset(shakey
, 0, sizeof(shakey
));
986 warnx("%s", gpg_strerror(rc
));
990 memset(shakey
, 0, sizeof(shakey
));
994 gchar
*get_key_file_string(const gchar
*section
, const gchar
*what
)
999 if (g_key_file_has_key(keyfileh
, section
, what
, NULL
) == TRUE
) {
1000 val
= g_key_file_get_string(keyfileh
, section
, what
, &grc
);
1003 log_write("%s(%i): %s", __FILE__
, __LINE__
, grc
->message
);
1004 g_clear_error(&grc
);
1008 if (g_key_file_has_key(keyfileh
, "global", what
, NULL
) == TRUE
) {
1009 val
= g_key_file_get_string(keyfileh
, "global", what
, &grc
);
1012 log_write("%s(%i): %s", __FILE__
, __LINE__
, grc
->message
);
1013 g_clear_error(&grc
);
1021 gint
get_key_file_integer(const gchar
*section
, const gchar
*what
)
1026 if (g_key_file_has_key(keyfileh
, section
, what
, NULL
) == TRUE
) {
1027 val
= g_key_file_get_integer(keyfileh
, section
, what
, &grc
);
1030 log_write("%s(%i): %s", __FILE__
, __LINE__
, grc
->message
);
1031 g_clear_error(&grc
);
1035 if (g_key_file_has_key(keyfileh
, "global", what
, NULL
) == TRUE
) {
1036 val
= g_key_file_get_integer(keyfileh
, "global", what
, &grc
);
1039 log_write("%s(%i): %s", __FILE__
, __LINE__
, grc
->message
);
1040 g_clear_error(&grc
);
1048 gboolean
get_key_file_boolean(const gchar
*section
, const gchar
*what
)
1050 gboolean val
= FALSE
;
1053 if (g_key_file_has_key(keyfileh
, section
, what
, NULL
) == TRUE
) {
1054 val
= g_key_file_get_boolean(keyfileh
, section
, what
, &grc
);
1057 log_write("%s(%i): %s", __FILE__
, __LINE__
, grc
->message
);
1058 g_clear_error(&grc
);
1062 if (g_key_file_has_key(keyfileh
, "global", what
, NULL
) == TRUE
) {
1063 val
= g_key_file_get_boolean(keyfileh
, "global", what
, &grc
);
1066 log_write("%s(%i): %s", __FILE__
, __LINE__
, grc
->message
);
1067 g_clear_error(&grc
);
1075 static gboolean
_getline(const gchar
*file
, gchar
**result
)
1078 gchar buf
[LINE_MAX
] = {0}, *p
;
1082 if ((fp
= fopen(file
, "r")) == NULL
) {
1087 p
= fgets(buf
, sizeof(buf
), fp
);
1091 if (len
&& buf
[len
- 1] == '\n')
1094 str
= gcry_malloc(len
+ 1);
1095 memcpy(str
, buf
, len
? len
: 1);
1097 memset(&buf
, 0, sizeof(buf
));
1102 static gboolean
parse_keyfile_key()
1109 groups
= g_key_file_get_groups(keyfileh
, &n
);
1111 for (p
= groups
; *p
; p
++) {
1114 if (g_key_file_has_key(keyfileh
, *p
, "key", &rc
) == TRUE
) {
1115 str
= g_key_file_get_string(keyfileh
, *p
, "key", &rc
);
1119 warnx("%s", rc
->message
);
1126 do_cache_push(*p
, str
);
1132 warnx("%s", rc
->message
);
1137 if (g_key_file_has_key(keyfileh
, *p
, "key_file", &rc
) == TRUE
) {
1139 gchar
*file
= g_key_file_get_string(keyfileh
, *p
, "key_file", &rc
);
1143 warnx("%s", rc
->message
);
1150 t
= expand_homedir(file
);
1154 if (_getline(file
, &str
) == FALSE
) {
1160 do_cache_push(*p
, str
);
1166 warnx("%s", rc
->message
);
1175 static gboolean
do_cache_push(const gchar
*filename
, const gchar
*password
)
1180 const gchar
*p
= filename
;
1181 file_header_t file_header
;
1190 if (valid_filename(p
) == FALSE
) {
1191 warnx(N_("%s: invalid characters in filename"), p
);
1195 md5file
= gcry_malloc(16);
1196 key
= gcry_malloc(gcrykeysize
);
1197 gcry_md_hash_buffer(GCRY_MD_MD5
, md5file
, p
, strlen(p
));
1199 if (cache_iscached(md5file
) == TRUE
) {
1200 warnx(N_("%s: file already cached, skipping"), p
);
1206 if (access(p
, R_OK
|W_OK
) != 0) {
1210 if (errno
!= ENOENT
) {
1219 rc
= read_file_header(filename
, &file_header
);
1224 warnx("%s", pwmd_strerror(rc
));
1228 if (file_header
.iter
== -1) {
1229 memset(key
, '!', gcrykeysize
);
1234 #ifdef WITH_PINENTRY
1235 if (g_key_file_get_boolean(keyfileh
, "global", "enable_pinentry", NULL
) == FALSE
) {
1237 if (get_input(p
, key
) == FALSE
) {
1242 #ifdef WITH_PINENTRY
1245 gchar
*result
= NULL
;
1246 struct pinentry_s
*pin
= g_malloc0(sizeof(struct pinentry_s
));
1249 set_pinentry_defaults(pin
);
1250 pin
->which
= PINENTRY_OPEN
;
1251 pin
->filename
= g_strdup(filename
);
1253 rc
= pinentry_getpin(pin
, &result
);
1256 warnx("%s: %s", filename
, gpg_strerror(rc
));
1257 cleanup_pinentry(pin
);
1264 gcry_md_hash_buffer(GCRY_MD_SHA256
, key
, result
, strlen(result
) ? strlen(result
) : 1);
1267 if (do_try_xml_decrypt(filename
, key
) == FALSE
) {
1269 cleanup_pinentry(pin
);
1272 warnx(N_("%s: invalid password, skipping"), filename
);
1277 pin
->title
= g_strdup(N_("Incorrect password. Please try again."));
1282 cleanup_pinentry(pin
);
1287 gcry_md_hash_buffer(GCRY_MD_SHA256
, key
, password
, strlen(password
) ? strlen(password
) : 1);
1290 if (do_try_xml_decrypt(filename
, key
) == FALSE
) {
1291 warnx(N_("%s: invalid password, skipping"), filename
);
1298 if (cache_add_file(md5file
, key
) == FALSE
) {
1299 warnx("%s: %s", p
, pwmd_strerror(EPWMD_MAX_SLOTS
));
1305 timeout
= get_key_file_integer(p
, "cache_timeout");
1306 cache_set_timeout(md5file
, timeout
);
1307 warnx(N_("%s: file added to the cache"), filename
);
1313 static void *accept_thread(void *arg
)
1315 gint sockfd
= (gint
)arg
;
1318 socklen_t slen
= sizeof(struct sockaddr_un
);
1319 struct sockaddr_un raddr
;
1323 if ((fd
= pth_accept(sockfd
, (struct sockaddr
*)&raddr
, &slen
)) == -1) {
1324 if (errno
!= EAGAIN
) {
1325 if (!quit
) // probably EBADF
1326 log_write("accept(): %s", strerror(errno
));
1334 struct client_thread_s
*new;
1337 new = g_malloc0(sizeof(struct client_thread_s
));
1340 log_write("%s", strerror(ENOMEM
));
1345 * Thread priority is inherited from the calling thread. This
1346 * thread is PTH_PRIO_MAX. Keep the "child" threads at standard
1350 attr
= pth_attr_new();
1351 pth_attr_set(attr
, PTH_ATTR_PRIO
, PTH_PRIO_STD
);
1352 pth_attr_set(attr
, PTH_ATTR_JOINABLE
, FALSE
);
1353 tid
= pth_spawn(attr
, client_thread
, new);
1354 pth_attr_destroy(attr
);
1358 log_write(N_("pth_spawn() failed"));
1362 g_snprintf(buf
, sizeof(buf
), "%p", tid
);
1363 log_write(N_("new tid=%s, fd=%i"), buf
, fd
);
1364 attr
= pth_attr_of(tid
);
1365 pth_attr_set(attr
, PTH_ATTR_NAME
, buf
);
1366 pth_attr_destroy(attr
);
1368 pth_mutex_acquire(&cn_mutex
, FALSE
, NULL
);
1369 cn_thread_list
= g_slist_append(cn_thread_list
, new);
1370 pth_mutex_release(&cn_mutex
);
1374 /* Just in case pth_accept() failed for some reason other than EBADF */
1376 pth_exit(PTH_CANCELED
);
1381 * This thread isn't joinable. For operations that block, these threads will
1384 static void *adjust_timer_thread(void *arg
)
1387 cache_adjust_timer();
1392 static pth_event_t
timeout_event_iterate(pth_event_t timeout_ev
,
1395 pth_status_t ev_status
;
1398 pth_event_isolate(timeout_ev
);
1399 ev_status
= pth_event_status(timeout_ev
);
1400 pth_event_free(timeout_ev
, PTH_FREE_THIS
);
1402 if (ev_status
== PTH_STATUS_OCCURRED
) {
1404 * The timer event has expired. Update the file cache. When the
1405 * cache mutex is locked and the timer expires again, the threads
1408 pth_spawn(attr
, adjust_timer_thread
, NULL
);
1412 return pth_event(PTH_EVENT_TIME
, pth_timeout(1, 0));
1415 static pth_event_t
keepalive_event_iterate(pth_event_t keepalive_ev
,
1418 pth_event_t ev
= NULL
;
1419 pth_status_t ev_status
;
1422 pth_event_isolate(keepalive_ev
);
1423 ev_status
= pth_event_status(keepalive_ev
);
1425 if (ev_status
== PTH_STATUS_OCCURRED
|| ev_status
== PTH_STATUS_FAILED
) {
1426 if (ev_status
== PTH_STATUS_OCCURRED
)
1427 send_status_all(STATUS_KEEPALIVE
);
1429 pth_event_free(keepalive_ev
, PTH_FREE_THIS
);
1435 if (keepalive
> 0 && !ev
)
1436 ev
= pth_event(PTH_EVENT_TIME
, pth_timeout(keepalive
, 0));
1441 static void server_loop(gint sockfd
, gchar
**socketpath
)
1448 pth_event_t timeout_ev
, keepalive_ev
= NULL
, ev_quit
;
1449 gint keepalive
= get_key_file_integer("global", "keepalive");
1452 pth_mutex_init(&cn_mutex
);
1453 log_write(N_("%s started for user %s"), PACKAGE_STRING
, g_get_user_name());
1456 sigaddset(&set
, SIGTERM
);
1457 sigaddset(&set
, SIGINT
);
1458 sigaddset(&set
, SIGUSR1
);
1459 sigaddset(&set
, SIGHUP
);
1460 sigaddset(&set
, SIGABRT
);
1462 attr
= pth_attr_new();
1463 pth_attr_init(attr
);
1464 pth_attr_set(attr
, PTH_ATTR_PRIO
, PTH_PRIO_MIN
);
1465 pth_attr_set(attr
, PTH_ATTR_NAME
, "accept");
1466 accept_tid
= pth_spawn(attr
, accept_thread
, (void *)sockfd
);
1467 pth_attr_init(attr
);
1468 pth_attr_set(attr
, PTH_ATTR_JOINABLE
, FALSE
);
1469 pth_attr_set(attr
, PTH_ATTR_PRIO
, PTH_PRIO_MAX
);
1472 * For the cache_timeout configuration parameter.
1474 timeout_ev
= timeout_event_iterate(NULL
, attr
);
1475 keepalive_ev
= keepalive_event_iterate(NULL
, keepalive
);
1476 timeout_ev
= pth_event_concat(timeout_ev
, keepalive_ev
, NULL
);
1481 pth_sigwait_ev(&set
, &sig
, timeout_ev
);
1482 timeout_ev
= timeout_event_iterate(timeout_ev
, attr
);
1483 keepalive_ev
= keepalive_event_iterate(keepalive_ev
, keepalive
);
1484 timeout_ev
= pth_event_concat(timeout_ev
, keepalive_ev
, NULL
);
1487 log_write(N_("caught signal %i (%s)"), sig
, strsignal(sig
));
1489 /* Caught a signal. */
1493 keepalive
= get_key_file_integer("global", "keepalive");
1497 cache_clear(NULL
, 2);
1505 log_write(N_("clearing file cache"));
1506 cache_clear(NULL
, 2);
1511 shutdown(sockfd
, SHUT_RDWR
);
1519 * We're out of the main server loop. This happens when a signal was sent
1520 * to terminate the daemon. We'll wait for all clients to disconnect
1521 * before exiting and ignore any following signals.
1523 pth_join(accept_tid
, &value
);
1524 n
= pth_ctrl(PTH_CTRL_GETTHREADS
);
1525 unlink(*socketpath
);
1526 g_free(*socketpath
);
1530 log_write(N_("waiting for all threads to terminate"));
1532 ev_quit
= pth_event(PTH_EVENT_TIME
, pth_timeout(0, 500000));
1535 if (n
!= n_clients
) {
1536 log_write(N_("%i threads remain"), n
-1);
1541 pth_event_isolate(ev_quit
);
1542 timeout_ev
= timeout_event_iterate(timeout_ev
, attr
);
1543 keepalive_ev
= keepalive_event_iterate(keepalive_ev
, keepalive
);
1544 ev_quit
= pth_event_concat(ev_quit
, timeout_ev
, keepalive_ev
, NULL
);
1545 n
= pth_ctrl(PTH_CTRL_GETTHREADS
);
1548 pth_event_free(timeout_ev
, PTH_FREE_THIS
);
1549 pth_event_free(keepalive_ev
, PTH_FREE_THIS
);
1550 pth_event_free(ev_quit
, PTH_FREE_THIS
);
1551 pth_attr_destroy(attr
);
1555 * Called from pinentry_fork() in the child process.
1557 void free_client_list()
1559 gint i
, t
= g_slist_length(cn_thread_list
);
1561 for (i
= 0; i
< t
; i
++) {
1562 struct client_thread_s
*cn
= g_slist_nth_data(cn_thread_list
, i
);
1564 free_client(cn
->cl
);
1567 memset(key_cache
, 0, cache_size
);
1570 int main(int argc
, char *argv
[])
1573 struct sockaddr_un addr
;
1574 struct passwd
*pw
= getpwuid(getuid());
1575 gchar buf
[PATH_MAX
];
1576 gchar
*socketpath
= NULL
, *socketdir
, *socketname
= NULL
;
1577 gchar
*socketarg
= NULL
;
1578 gchar
*datadir
= NULL
;
1581 gchar
**cache_push
= NULL
;
1583 gchar
*import
= NULL
;
1584 gint cmd_iterations
= -1;
1585 gint default_timeout
;
1586 gint rcfile_spec
= 0;
1587 gint estatus
= EXIT_FAILURE
;
1590 GMemVTable mtable
= { xmalloc
, xrealloc
, xfree
, xcalloc
, NULL
, NULL
};
1593 gboolean secure
= FALSE
;
1595 gint background
= 1;
1598 #ifdef HAVE_SETRLIMIT
1601 rl
.rlim_cur
= rl
.rlim_max
= 0;
1603 if (setrlimit(RLIMIT_CORE
, &rl
) != 0)
1604 err(EXIT_FAILURE
, "setrlimit()");
1609 setlocale(LC_ALL
, "");
1610 bindtextdomain("pwmd", LOCALEDIR
);
1615 assuan_set_assuan_err_source(GPG_ERR_SOURCE_DEFAULT
);
1617 g_mem_set_vtable(&mtable
);
1618 assuan_set_malloc_hooks(xmalloc
, xrealloc
, xfree
);
1619 xmlMemSetup(xfree
, xmalloc
, xrealloc
, xstrdup
);
1623 g_snprintf(buf
, sizeof(buf
), "%s/.pwmd", pw
->pw_dir
);
1625 if (mkdir(buf
, 0700) == -1 && errno
!= EEXIST
)
1626 err(EXIT_FAILURE
, "%s", buf
);
1628 g_snprintf(buf
, sizeof(buf
), "%s/.pwmd/data", pw
->pw_dir
);
1630 if (mkdir(buf
, 0700) == -1 && errno
!= EEXIST
)
1631 err(EXIT_FAILURE
, "%s", buf
);
1633 rcfile
= g_strdup_printf("%s/.pwmd/config", pw
->pw_dir
);
1635 if ((page_size
= sysconf(_SC_PAGESIZE
)) == -1)
1636 err(EXIT_FAILURE
, "sysconf()");
1638 cache_size
= page_size
;
1640 while ((opt
= getopt(argc
, argv
, "bnI:i:hvf:D")) != EOF
) {
1643 /* Compatibility for version < 1.11 */
1655 cmd_iterations
= atoi(optarg
);
1659 rcfile
= g_strdup(optarg
);
1663 printf("%s\n%s\n", PACKAGE_STRING
, PACKAGE_BUGREPORT
);
1671 if ((keyfileh
= parse_rcfile(rcfile_spec
)) == NULL
)
1674 if (g_key_file_has_key(keyfileh
, "global", "syslog", NULL
) == TRUE
)
1675 log_syslog
= g_key_file_get_boolean(keyfileh
, "global", "syslog", NULL
);
1677 if (log_syslog
== TRUE
)
1678 openlog("pwmd", LOG_NDELAY
|LOG_PID
, LOG_DAEMON
);
1680 if (g_key_file_has_key(keyfileh
, "global", "priority", NULL
)) {
1681 iter
= g_key_file_get_integer(keyfileh
, "global", "priority", NULL
);
1684 if (setpriority(PRIO_PROCESS
, 0, iter
) == -1) {
1685 warn("setpriority()");
1690 if (g_key_file_has_key(keyfileh
, "global", "iterations", NULL
) == TRUE
)
1691 iter
= g_key_file_get_integer(keyfileh
, "global", "iterations", NULL
);
1693 #ifdef HAVE_MLOCKALL
1694 if (disable_mlock
== FALSE
&& mlockall(MCL_FUTURE
) == -1) {
1703 opt
= xml_import(import
, cmd_iterations
< -1 ? iter
: cmd_iterations
);
1704 g_key_file_free(keyfileh
);
1706 exit(opt
== FALSE
? EXIT_FAILURE
: EXIT_SUCCESS
);
1709 g_key_file_set_list_separator(keyfileh
, ',');
1711 if ((p
= g_key_file_get_string(keyfileh
, "global", "socket_path", NULL
)) == NULL
)
1712 errx(EXIT_FAILURE
, N_("%s: socket_path not defined"), rcfile
);
1716 g_snprintf(buf
, sizeof(buf
), "%s%s", g_get_home_dir(), p
--);
1718 socketarg
= g_strdup(buf
);
1723 if ((p
= g_key_file_get_string(keyfileh
, "global", "data_directory", NULL
)) == NULL
)
1724 errx(EXIT_FAILURE
, N_("%s: data_directory not defined"), rcfile
);
1726 datadir
= expand_homedir(p
);
1729 if (secure
== FALSE
&& g_key_file_has_key(keyfileh
, "global", "disable_list_and_dump", NULL
) == TRUE
) {
1730 n
= g_key_file_get_boolean(keyfileh
, "global", "disable_list_and_dump", NULL
);
1731 disable_list_and_dump
= n
;
1734 disable_list_and_dump
= secure
;
1736 if (g_key_file_has_key(keyfileh
, "global", "cache_timeout", NULL
) == TRUE
)
1737 default_timeout
= g_key_file_get_integer(keyfileh
, "global", "cache_timeout", NULL
);
1739 default_timeout
= -1;
1741 if (g_key_file_has_key(keyfileh
, "global", "cache_size", NULL
) == TRUE
) {
1742 cache_size
= g_key_file_get_integer(keyfileh
, "global", "cache_size", NULL
);
1744 if (cache_size
< page_size
|| cache_size
% page_size
)
1745 errx(EXIT_FAILURE
, N_("cache size must be in multiples of %li"), page_size
);
1748 setup_logging(keyfileh
);
1750 if (g_key_file_has_key(keyfileh
, "global", "cache_push", NULL
) == TRUE
)
1751 cache_push
= g_key_file_get_string_list(keyfileh
, "global", "cache_push", NULL
, NULL
);
1753 if (argc
!= optind
) {
1755 ptotal
= g_strv_length(cache_push
);
1757 for (; optind
< argc
; optind
++) {
1758 if (strv_printf(&cache_push
, "%s", argv
[optind
]) == FALSE
)
1759 errx(EXIT_FAILURE
, "%s", strerror(ENOMEM
));
1763 if (strchr(socketarg
, '/') == NULL
) {
1764 socketdir
= g_get_current_dir();
1765 socketname
= g_strdup(socketarg
);
1766 socketpath
= g_strdup_printf("%s/%s", socketdir
, socketname
);
1769 socketname
= g_strdup(strrchr(socketarg
, '/'));
1771 socketarg
[strlen(socketarg
) - strlen(socketname
) -1] = 0;
1772 socketdir
= g_strdup(socketarg
);
1773 socketpath
= g_strdup_printf("%s/%s", socketdir
, socketname
);
1776 if ((key_cache
= mmap(NULL
, cache_size
, PROT_READ
|PROT_WRITE
,
1777 #ifdef MMAP_ANONYMOUS
1778 MAP_PRIVATE
|MAP_ANONYMOUS
, -1, 0)) == MAP_FAILED
) {
1780 MAP_PRIVATE
|MAP_ANON
, -1, 0)) == MAP_FAILED
) {
1782 err(EXIT_FAILURE
, "mmap()");
1785 if (mlock(key_cache
, cache_size
) == -1)
1786 log_write("mlock(): %s", strerror(errno
));
1788 memset(key_cache
, 0, cache_size
);
1790 if (chdir(datadir
)) {
1791 warn("%s", datadir
);
1796 if (parse_keyfile_key() == FALSE
)
1799 clear_errorfile_key();
1802 * Set the cache entry for a file. Prompts for the password.
1805 for (opt
= 0; cache_push
[opt
]; opt
++)
1806 do_cache_push(cache_push
[opt
], NULL
);
1808 g_strfreev(cache_push
);
1809 warnx(background
? N_("Done. Daemonizing...") : N_("Done. Waiting for connections..."));
1813 * bind() doesn't like the full pathname of the socket or any non alphanum
1814 * characters so change to the directory where the socket is wanted then
1815 * create it then change to datadir.
1817 if (chdir(socketdir
)) {
1818 warn("%s", socketdir
);
1824 if ((sockfd
= socket(PF_UNIX
, SOCK_STREAM
, 0)) == -1) {
1829 addr
.sun_family
= AF_UNIX
;
1830 g_snprintf(addr
.sun_path
, sizeof(addr
.sun_path
), "%s", socketname
);
1832 if (bind(sockfd
, (struct sockaddr
*)&addr
, sizeof(struct sockaddr
)) == -1) {
1835 if (errno
== EADDRINUSE
)
1836 warnx(N_("Either there is another pwmd running or '%s' is a \n"
1837 "stale socket. Please remove it manually."), socketpath
);
1843 if (g_key_file_has_key(keyfileh
, "global", "socket_perms", NULL
) == TRUE
) {
1844 gchar
*t
= g_key_file_get_string(keyfileh
, "global", "socket_perms", NULL
);
1845 mode_t mode
= strtol(t
, NULL
, 8);
1846 mode_t mask
= umask(0);
1850 if (chmod(socketname
, mode
) == -1) {
1851 warn("%s", socketname
);
1861 g_free(--socketname
);
1863 if (chdir(datadir
)) {
1864 warn("%s", datadir
);
1871 pth_mutex_init(&cache_mutex
);
1872 #ifdef WITH_PINENTRY
1873 pth_mutex_init(&pin_mutex
);
1876 if (listen(sockfd
, 0) == -1) {
1898 * These are the signals that we use in threads. libpth can catch signals
1899 * itself so ignore them everywhere else. Note that using
1900 * signal(N, SIG_IGN) doesn't work like you might think.
1905 sigaddset(&set
, SIGTERM
);
1906 sigaddset(&set
, SIGINT
);
1908 /* Configuration file reloading. */
1909 sigaddset(&set
, SIGUSR1
);
1911 /* Clears the file cache. */
1912 sigaddset(&set
, SIGHUP
);
1914 /* Caught in client_thread(). Sends a cache status message. */
1915 sigaddset(&set
, SIGUSR2
);
1917 /* Ignored everywhere. When a client disconnects abnormally this signal
1918 * gets raised. It isn't needed though because client_thread() will check
1919 * for rcs even after the client disconnects. */
1920 signal(SIGPIPE
, SIG_IGN
);
1921 pth_sigmask(SIG_BLOCK
, &set
, NULL
);
1922 server_loop(sockfd
, &socketpath
);
1923 estatus
= EXIT_SUCCESS
;
1926 if (socketpath
&& do_unlink
) {
1931 g_key_file_free(keyfileh
);
1936 cache_clear(NULL
, 2);
1937 memset(key_cache
, 0, cache_size
);
1940 if (key_cache
&& munmap(key_cache
, cache_size
) == -1)
1941 log_write("munmap(): %s", strerror(errno
));
1943 if (estatus
== EXIT_SUCCESS
)
1944 log_write(N_("pwmd exiting normally"));
1947 #if defined(DEBUG) && !defined(MEM_DEBUG)