Include <sys/socket.h>.
[pwmd.git] / src / pwmd.c
blob591090d6a239176436aa849b4adc77ae2d499643
1 /*
2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012
3 Ben Kibbey <bjk@luxsci.net>
5 This file is part of pwmd.
7 Pwmd is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 2 of the License, or
10 (at your option) any later version.
12 Pwmd is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
20 #ifdef HAVE_CONFIG_H
21 #include <config.h>
22 #endif
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <unistd.h>
27 #include <err.h>
28 #include <ctype.h>
29 #include <string.h>
30 #include <sys/socket.h>
31 #include <sys/un.h>
32 #include <signal.h>
33 #include <stdarg.h>
34 #include <string.h>
35 #include <sys/wait.h>
36 #include <fcntl.h>
37 #include <pwd.h>
38 #include <grp.h>
39 #include <pthread.h>
40 #include <glib.h>
41 #include <glib/gprintf.h>
42 #include <sys/mman.h>
43 #include <termios.h>
44 #include <assert.h>
45 #include <syslog.h>
46 #include <netinet/in.h>
47 #include <arpa/inet.h>
48 #include <netdb.h>
49 #include <sys/time.h>
50 #include <sys/resource.h>
51 #include <setjmp.h>
53 #ifdef TM_IN_SYS_TIME
54 #include <sys/time.h>
55 #else
56 #include <time.h>
57 #endif
59 #ifdef HAVE_PR_SET_NAME
60 #include <sys/prctl.h>
61 #endif
63 #include "pwmd-error.h"
64 #include <gcrypt.h>
66 #include "mem.h"
67 #include "xml.h"
68 #include "common.h"
69 #include "commands.h"
70 #include "cache.h"
71 #include "misc.h"
72 #include "mutex.h"
73 #include "rcfile.h"
74 #include "agent.h"
75 #include "convert.h"
77 static gboolean quit;
78 static gboolean exiting;
79 static gboolean cmdline;
80 static jmp_buf jmp;
81 static gboolean nofork;
82 static pthread_cond_t quit_cond;
83 static pthread_mutex_t quit_mutex;
84 static gboolean no_passphrase_file = FALSE;
85 #ifdef WITH_GNUTLS
86 static gint tls_fd;
87 static gint tls6_fd;
88 static pthread_t tls_tid;
89 static pthread_t tls6_tid;
91 static gboolean start_stop_tls(gboolean term);
92 #endif
94 static gboolean do_cache_push(const gchar *filename, struct crypto_s *crypto);
95 static gboolean signal_loop(sigset_t sigset);
97 GCRY_THREAD_OPTION_PTHREAD_IMPL;
99 static void cache_push_from_rcfile()
101 struct crypto_s *crypto;
102 gpg_error_t rc = init_client_crypto(&crypto);
104 if (rc) {
105 log_write("%s: %s", __FUNCTION__, pwmd_strerror(rc));
106 return;
109 rc = set_agent_option(crypto->agent, "pinentry-mode", "error");
110 if (rc) {
111 log_write("%s: %s", __FUNCTION__, pwmd_strerror(rc));
112 return;
115 if (g_key_file_has_key(keyfileh, "global", "cache_push", NULL)) {
116 gchar **cache_push = g_key_file_get_string_list(keyfileh, "global",
117 "cache_push", NULL, NULL);
118 gchar **p;
120 for (p = cache_push; *p; p++) {
121 (void)do_cache_push(*p, crypto);
122 cleanup_crypto_stage1(crypto);
125 g_strfreev(cache_push);
128 (void)kill_scd(crypto->agent);
129 cleanup_crypto(&crypto);
132 static void *reload_rcfile_thread(void *arg)
134 #ifdef HAVE_PR_SET_NAME
135 prctl(PR_SET_NAME, "reload rcfile");
136 #endif
137 pthread_setspecific(thread_name_key, g_strdup(__FUNCTION__));
138 MUTEX_LOCK(&rcfile_mutex);
139 pthread_cleanup_push(cleanup_mutex_cb, &rcfile_mutex);
141 for (;;) {
142 gboolean b = disable_list_and_dump;
143 #ifdef WITH_GNUTLS
144 gboolean tcp_require_key = get_key_file_boolean("global",
145 "tcp_require_key");
146 #endif
147 gchar **users;
148 GKeyFile *k;
150 pthread_cond_wait(&rcfile_cond, &rcfile_mutex);
151 users = g_key_file_get_string_list(keyfileh, "global", "allowed", NULL, NULL);
152 log_write(_("reloading configuration file '%s'"), rcfile);
153 k = parse_rcfile(FALSE, cmdline);
154 if (k) {
155 g_key_file_free(keyfileh);
156 keyfileh = k;
157 cache_push_from_rcfile();
158 clear_rcfile_keys();
161 disable_list_and_dump = !disable_list_and_dump ? b : TRUE;
162 #ifdef WITH_GNUTLS
163 tcp_require_key = get_key_file_boolean("global", "tcp_require_key")
164 ? TRUE : tcp_require_key;
165 g_key_file_set_boolean(keyfileh, "global", "tcp_require_key",
166 tcp_require_key);
167 #endif
168 g_key_file_set_string_list(keyfileh, "global", "allowed",
169 (const gchar **)users, g_strv_length(users));
170 g_strfreev(users);
171 #ifdef WITH_GNUTLS
172 /* Kill existing listening threads since the configured listening
173 * protocols may have changed. */
174 start_stop_tls(TRUE);
175 start_stop_tls(FALSE);
176 #endif
179 pthread_cleanup_pop(1);
180 return NULL;
183 gpg_error_t send_error(assuan_context_t ctx, gpg_error_t e)
185 struct client_s *client = assuan_get_pointer(ctx);
187 if (gpg_err_source(e) == GPG_ERR_SOURCE_UNKNOWN)
188 e = gpg_error(e);
190 if (client)
191 client->last_rc = e;
193 if (!e)
194 return assuan_process_done(ctx, 0);
196 if (!ctx) {
197 log_write("%s", pwmd_strerror(e));
198 return e;
201 if (gpg_err_code(e) == GPG_ERR_BAD_DATA) {
202 xmlErrorPtr xe = client->xml_error;
204 if (!xe)
205 xe = xmlGetLastError();
206 if (xe) {
207 log_write("%s", xe->message);
208 if (client->last_error)
209 g_free(client->last_error);
211 client->last_error = g_strdup(xe->message);
214 e = assuan_process_done(ctx, assuan_set_error(ctx, e,
215 xe ? xe->message : NULL));
217 if (xe == client->xml_error)
218 xmlResetError(xe);
219 else
220 xmlResetLastError();
222 client->xml_error = NULL;
223 return e;
226 return assuan_process_done(ctx, assuan_set_error(ctx, e, pwmd_strerror(e)));
229 int assuan_log_cb(assuan_context_t ctx, void *data, unsigned cat,
230 const char *msg)
232 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
233 int i, t;
234 gboolean match = FALSE;
236 pthread_mutex_lock(&m);
237 pthread_cleanup_push((void (*)(void *))pthread_mutex_unlock, &m);
238 t = g_strv_length(debug_level);
240 for (i = 0; i < t; i++) {
241 if (!g_ascii_strcasecmp(debug_level[i], (gchar *)"init")
242 && cat == ASSUAN_LOG_INIT) {
243 match = TRUE;
244 break;
247 if (!g_ascii_strcasecmp(debug_level[i], (gchar *)"ctx")
248 && cat == ASSUAN_LOG_CTX) {
249 match = TRUE;
250 break;
253 if (!g_ascii_strcasecmp(debug_level[i], (gchar *)"engine")
254 && cat == ASSUAN_LOG_ENGINE) {
255 match = TRUE;
256 break;
259 if (!g_ascii_strcasecmp(debug_level[i], (gchar *)"data")
260 && cat == ASSUAN_LOG_DATA) {
261 match = TRUE;
262 break;
265 if (!g_ascii_strcasecmp(debug_level[i], (gchar *)"sysio")
266 && cat == ASSUAN_LOG_SYSIO) {
267 match = TRUE;
268 break;
271 if (!g_ascii_strcasecmp(debug_level[i], (gchar *)"control")
272 && cat == ASSUAN_LOG_CONTROL) {
273 match = TRUE;
274 break;
278 if (match && msg) {
279 if (logfile) {
280 int fd;
282 if ((fd = open(logfile, O_WRONLY|O_CREAT|O_APPEND, 0600)) == -1)
283 warn("%s", logfile);
284 else {
285 pthread_cleanup_push(cleanup_fd_cb, &fd);
286 write(fd, msg, strlen(msg));
287 pthread_cleanup_pop(1);
291 if (nofork) {
292 fprintf(stderr, "%s%s", data ? (gchar *)data : "", msg);
293 fflush(stderr);
297 pthread_cleanup_pop(1);
298 return match;
301 void log_write(const gchar *fmt, ...)
303 gchar *args, *line;
304 va_list ap;
305 struct tm *tm;
306 time_t now;
307 gchar tbuf[21];
308 gint fd = -1;
309 gchar *name = NULL;
310 gchar buf[255];
311 pthread_t tid = pthread_self();
312 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
314 if ((!logfile && !isatty(STDERR_FILENO) && !log_syslog) || !fmt)
315 return;
317 pthread_mutex_lock(&m);
318 pthread_cleanup_push((void (*)(void *))pthread_mutex_unlock, &m);
319 pthread_cleanup_push(cleanup_fd_cb, &fd);
321 if (!cmdline && logfile) {
322 if ((fd = open(logfile, O_WRONLY|O_CREAT|O_APPEND, 0600)) == -1)
323 warn("%s", logfile);
326 va_start(ap, fmt);
328 if (g_vasprintf(&args, fmt, ap) != -1) {
329 if (cmdline) {
330 pthread_cleanup_push(g_free, args);
331 fprintf(stderr, "%s\n", args);
332 fflush(stderr);
333 pthread_cleanup_pop(1);
335 else {
336 pthread_cleanup_push(g_free, args);
337 name = pthread_getspecific(thread_name_key);
338 name = print_fmt(buf, sizeof(buf), "%s(%p): ",
339 name ? name : _("unknown"), (pthread_t *)tid);
341 if (!cmdline && log_syslog && !nofork)
342 syslog(LOG_INFO, "%s%s", name, args);
344 time(&now);
345 tm = localtime(&now);
346 strftime(tbuf, sizeof(tbuf), "%b %d %Y %H:%M:%S ", tm);
347 tbuf[sizeof(tbuf) - 1] = 0;
349 if (args[strlen(args)-1] == '\n')
350 args[strlen(args)-1] = 0;
352 line = g_strdup_printf("%s %i %s%s\n", tbuf, getpid(), name,
353 args);
354 pthread_cleanup_pop(1);
355 if (line) {
356 pthread_cleanup_push(g_free, line);
357 if (logfile && fd != -1) {
358 write(fd, line, strlen(line));
359 fsync(fd);
362 if (nofork) {
363 fprintf(stdout, "%s", line);
364 fflush(stdout);
367 pthread_cleanup_pop(1);
372 va_end(ap);
373 pthread_cleanup_pop(1);
374 pthread_cleanup_pop(0);
375 pthread_mutex_unlock(&m);
378 #ifdef WITH_GNUTLS
379 static gint secure_mem_check(const void *arg)
381 return 1;
383 #endif
385 static gpg_error_t setup_crypto()
387 gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
389 if (!gcry_check_version(GCRYPT_VERSION)) {
390 fprintf(stderr, _("gcry_check_version(): Incompatible libgcrypt. "
391 "Wanted %s, got %s.\n"), GCRYPT_VERSION,
392 gcry_check_version(NULL));
393 return GPG_ERR_UNKNOWN_VERSION;
396 gcry_set_allocation_handler(g_malloc, g_malloc, NULL, g_realloc, g_free);
397 return 0;
400 static gpg_error_t validate_peer(struct client_s *cl)
402 gchar **users;
403 gboolean allowed = FALSE;
404 assuan_peercred_t peercred;
405 gpg_error_t rc;
407 #ifdef WITH_GNUTLS
408 if (cl->thd->remote)
409 return 0;
410 #endif
412 rc = assuan_get_peercred(cl->ctx, &peercred);
413 if (rc)
414 return rc;
416 users = g_key_file_get_string_list(keyfileh, "global", "allowed", NULL, NULL);
418 if (users) {
419 for (gchar **p = users; *p; p++) {
420 struct passwd pw, *result;
421 struct group gr, *gresult;
422 char *buf;
424 if (*(*p) == '@') {
425 size_t len = sysconf(_SC_GETGR_R_SIZE_MAX);
427 if (len == -1)
428 len = 16384;
430 buf = g_malloc(len);
432 if (!buf) {
433 g_strfreev(users);
434 return GPG_ERR_ENOMEM;
437 if (!getgrnam_r(*(p)+1, &gr, buf, len, &gresult) && gresult) {
438 if (gresult->gr_gid == peercred->gid) {
439 g_free(buf);
440 allowed = TRUE;
441 break;
444 len = sysconf(_SC_GETPW_R_SIZE_MAX);
446 if (len == -1)
447 len = 16384;
449 gchar *tbuf = g_malloc(len);
451 for (gchar **t = gresult->gr_mem; *t; t++) {
452 if (!getpwnam_r(*t, &pw, tbuf, len, &result) && result) {
453 if (result->pw_uid == peercred->uid) {
454 g_free(buf);
455 allowed = TRUE;
456 break;
461 g_free(tbuf);
463 if (allowed)
464 break;
467 else {
468 size_t len = sysconf(_SC_GETPW_R_SIZE_MAX);
470 if (len == -1)
471 len = 16384;
473 buf = g_malloc(len);
475 if (!buf) {
476 g_strfreev(users);
477 return GPG_ERR_ENOMEM;
480 if (!getpwnam_r(*p, &pw, buf, len, &result) && result) {
481 if (result->pw_uid == peercred->uid) {
482 g_free(buf);
483 allowed = TRUE;
484 break;
489 g_free(buf);
492 g_strfreev(users);
495 log_write("peer %s: uid=%i, gid=%i, pid=%i",
496 allowed ? _("accepted") : _("rejected"), peercred->uid,
497 peercred->gid, peercred->pid);
498 return allowed ? 0 : GPG_ERR_INV_USER_ID;
501 static void xml_error_cb(void *data, xmlErrorPtr e)
503 struct client_s *client = data;
506 * Keep the first reported error as the one to show in the error
507 * description. Reset in send_error().
509 if (client->xml_error)
510 return;
512 xmlCopyError(e, client->xml_error);
515 static pid_t hook_waitpid(assuan_context_t ctx, pid_t pid, int action,
516 int *status, int options)
518 return waitpid(pid, status, options);
521 static ssize_t hook_read(assuan_context_t ctx, assuan_fd_t fd, void *data,
522 size_t len)
524 #ifdef WITH_GNUTLS
525 struct client_s *client = assuan_get_pointer(ctx);
527 if (client->thd->remote)
528 return tls_read_hook(ctx, (gint)fd, data, len);
529 #endif
531 return read((gint)fd, data, len);
534 static ssize_t hook_write(assuan_context_t ctx, assuan_fd_t fd,
535 const void *data, size_t len)
537 #ifdef WITH_GNUTLS
538 struct client_s *client = assuan_get_pointer(ctx);
540 if (client->thd->remote)
541 return tls_write_hook(ctx, (gint)fd, data, len);
542 #endif
544 return write((gint)fd, data, len);
547 static gboolean new_connection(struct client_s *cl)
549 gpg_error_t rc;
550 static struct assuan_malloc_hooks mhooks = { g_malloc, g_realloc, g_free };
551 static struct assuan_system_hooks shooks = {
552 ASSUAN_SYSTEM_HOOKS_VERSION,
553 __assuan_usleep,
554 __assuan_pipe,
555 __assuan_close,
556 hook_read,
557 hook_write,
558 //FIXME
559 NULL, //recvmsg
560 NULL, //sendmsg both are used for FD passing
561 __assuan_spawn,
562 hook_waitpid,
563 __assuan_socketpair,
564 __assuan_socket,
565 __assuan_connect
568 #ifdef WITH_GNUTLS
569 if (cl->thd->remote) {
570 gchar *prio = get_key_file_string("global", "tls_cipher_suite");
572 cl->thd->tls = tls_init(cl->thd->fd, prio);
573 g_free(prio);
574 if (!cl->thd->tls)
575 return FALSE;
577 #endif
579 rc = assuan_new_ext(&cl->ctx, GPG_ERR_SOURCE_DEFAULT, &mhooks,
580 debug_level ? assuan_log_cb : NULL, NULL);
581 if (rc)
582 goto fail;
584 assuan_ctx_set_system_hooks(cl->ctx, &shooks);
585 rc = assuan_init_socket_server(cl->ctx, cl->thd->fd, 2);
586 if (rc)
587 goto fail;
589 assuan_set_pointer(cl->ctx, cl);
590 assuan_set_hello_line(cl->ctx, PACKAGE_STRING);
591 rc = register_commands(cl->ctx);
592 if (rc)
593 goto fail;
595 rc = assuan_accept(cl->ctx);
596 if (rc)
597 goto fail;
599 rc = validate_peer(cl);
600 /* May not be implemented on all platforms. */
601 if (rc && gpg_err_code(rc) != GPG_ERR_ASS_GENERAL)
602 goto fail;
604 rc = init_client_crypto(&cl->crypto);
605 if (rc)
606 goto fail;
608 cl->crypto->agent->client_ctx = cl->ctx;
609 cl->crypto->client_ctx = cl->ctx;
610 xmlSetStructuredErrorFunc(cl, xml_error_cb);
611 return TRUE;
613 fail:
614 log_write("%s", pwmd_strerror(rc));
615 return FALSE;
619 * This is called after a client_thread() terminates. Set with
620 * pthread_cleanup_push().
622 static void cleanup_cb(void *arg)
624 struct client_thread_s *cn = arg;
625 struct client_s *cl = cn->cl;
627 MUTEX_LOCK(&cn_mutex);
628 cn_thread_list = g_slist_remove(cn_thread_list, cn);
629 MUTEX_UNLOCK(&cn_mutex);
631 if (cl) {
632 cleanup_client(cl);
634 #ifdef WITH_GNUTLS
635 if (cn->tls) {
636 gnutls_deinit(cn->tls->ses);
637 g_free(cn->tls->fp);
638 g_free(cn->tls);
640 #endif
642 if (cl->ctx)
643 assuan_release(cl->ctx);
644 else if (cl->thd && cl->thd->fd != -1)
645 close(cl->thd->fd);
647 if (cl->crypto)
648 cleanup_crypto(&cl->crypto);
650 g_free(cl);
652 else {
653 if (cn->fd != -1)
654 close(cn->fd);
657 while (cn->msg_queue) {
658 struct status_msg_s *msg = cn->msg_queue;
660 cn->msg_queue = msg->next;
661 g_free(msg->line);
662 g_free(msg);
665 if (cn->status_msg_pipe[0] != -1)
666 close(cn->status_msg_pipe[0]);
668 if (cn->status_msg_pipe[1] != -1)
669 close(cn->status_msg_pipe[1]);
671 pthread_mutex_destroy(&cn->status_mutex);
672 log_write(_("exiting, fd=%i"), cn->fd);
673 g_free(cn);
674 send_status_all(STATUS_CLIENTS, NULL);
675 pthread_cond_signal(&quit_cond);
678 static gpg_error_t send_msg_queue(struct client_thread_s *thd)
680 MUTEX_LOCK(&thd->status_mutex);
681 gpg_error_t rc = 0;
682 gchar c;
684 read(thd->status_msg_pipe[0], &c, 1);
686 while (thd->msg_queue) {
687 struct status_msg_s *msg = thd->msg_queue;
689 thd->msg_queue = thd->msg_queue->next;
690 MUTEX_UNLOCK(&thd->status_mutex);
691 rc = send_status(thd->cl->ctx, msg->s, msg->line);
692 MUTEX_LOCK(&thd->status_mutex);
693 g_free(msg->line);
694 g_free(msg);
696 if (rc)
697 break;
700 MUTEX_UNLOCK(&thd->status_mutex);
701 return rc;
704 static void *client_thread(void *data)
706 struct client_thread_s *thd = data;
707 struct client_s *cl = g_malloc0(sizeof(struct client_s));
709 #ifdef HAVE_PR_SET_NAME
710 prctl(PR_SET_NAME, "client");
711 #endif
712 pthread_setspecific(thread_name_key, g_strdup(__FUNCTION__));
714 if (!cl) {
715 log_write("%s(%i): %s", __FILE__, __LINE__,
716 pwmd_strerror(GPG_ERR_ENOMEM));
717 return NULL;
720 MUTEX_LOCK(&cn_mutex);
721 pthread_cleanup_push(cleanup_cb, thd);
722 thd->cl = cl;
723 cl->thd = thd;
724 MUTEX_UNLOCK(&cn_mutex);
726 if (new_connection(cl)) {
727 gboolean finished = FALSE;
728 gpg_error_t rc;
730 send_status_all(STATUS_CLIENTS, NULL);
731 rc = send_status(cl->ctx, STATUS_CACHE, NULL);
732 if (rc) {
733 log_write("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror(rc));
734 finished = TRUE;
737 while (!finished) {
738 fd_set rfds;
739 gint n;
740 gint eof;
742 FD_ZERO(&rfds);
743 FD_SET(thd->fd, &rfds);
744 FD_SET(thd->status_msg_pipe[0], &rfds);
745 n = thd->fd > thd->status_msg_pipe[0] ? thd->fd : thd->status_msg_pipe[0];
747 n = select(n+1, &rfds, NULL, NULL, NULL);
748 if (n == -1) {
749 log_write("%s", strerror(errno));
750 break;
753 if (FD_ISSET(thd->status_msg_pipe[0], &rfds)) {
754 rc = send_msg_queue(thd);
755 if (rc && gpg_err_code(rc) != GPG_ERR_EPIPE) {
756 log_write("%s(%i): %s", __FUNCTION__, __LINE__,
757 pwmd_strerror(rc));
758 break;
762 if (!FD_ISSET(thd->fd, &rfds))
763 continue;
765 rc = assuan_process_next(cl->ctx, &eof);
766 if (rc || eof) {
767 if (gpg_err_code(rc) == GPG_ERR_EOF || eof)
768 break;
770 log_write("assuan_process_next(): %s", pwmd_strerror(rc));
771 rc = send_error(cl->ctx, rc);
773 if (rc) {
774 log_write("assuan_process_done(): %s", pwmd_strerror(rc));
775 break;
779 /* Since the msg queue pipe fd's are non-blocking, check for
780 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
781 * client has already disconnected and will be converted to
782 * GPG_ERR_EOF during assuan_process_next().
784 rc = send_msg_queue(thd);
785 if (rc && gpg_err_code(rc) != GPG_ERR_EPIPE) {
786 log_write("%s(%i): %s", __FUNCTION__, __LINE__,
787 pwmd_strerror(rc));
788 break;
793 pthread_cleanup_pop(1);
794 return NULL;
797 static gboolean xml_import(const gchar *filename, const gchar *outfile,
798 const gchar *keygrip, const char *sign_keygrip, const gchar *keyfile,
799 gboolean no_passphrase, const gchar *cipher, const gchar *params,
800 gulong s2k_count, guint64 iterations)
802 xmlDocPtr doc;
803 gint fd;
804 struct stat st;
805 gint len;
806 xmlChar *xmlbuf;
807 xmlChar *xml;
808 gpg_error_t rc;
809 struct crypto_s *crypto;
810 gint algo = cipher ? cipher_string_to_gcrypt((gchar *)cipher) :
811 GCRY_CIPHER_AES256;
813 if (algo == -1) {
814 log_write("ERR %i: %s", gpg_error(GPG_ERR_CIPHER_ALGO),
815 pwmd_strerror(GPG_ERR_CIPHER_ALGO));
816 return FALSE;
819 if (stat(filename, &st) == -1) {
820 log_write("%s: %s", filename, pwmd_strerror(gpg_error_from_syserror()));
821 return FALSE;
824 rc = init_client_crypto(&crypto);
825 if (rc)
826 return FALSE;
828 memcpy(&crypto->save.hdr, &crypto->hdr, sizeof(file_header_t));
829 crypto->save.hdr.flags = set_cipher_flag(crypto->save.hdr.flags, algo);
830 log_write(_("Importing XML from '%s'. Output will be written to '%s' ..."),
831 filename, outfile);
833 if ((fd = open(filename, O_RDONLY)) == -1) {
834 log_write("%s: %s", filename, pwmd_strerror(gpg_error_from_syserror()));
835 goto fail;
838 if ((xmlbuf = xmalloc(st.st_size+1)) == NULL) {
839 close(fd);
840 log_write("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror(GPG_ERR_ENOMEM));
841 goto fail;
844 if (read(fd, xmlbuf, st.st_size) == -1) {
845 rc = gpg_error_from_syserror();
846 close(fd);
847 log_write("%s: %s", filename, pwmd_strerror(rc));
848 goto fail;
851 close(fd);
852 xmlbuf[st.st_size] = 0;
854 * Make sure the document validates.
856 if ((doc = xmlReadDoc(xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS)) == NULL) {
857 log_write("xmlReadDoc() failed");
858 xfree(xmlbuf);
859 goto fail;
862 xfree(xmlbuf);
863 xmlNodePtr n = xmlDocGetRootElement(doc);
864 if (!xmlStrEqual(n->name, (xmlChar *)"pwmd")) {
865 log_write(_("Could not find root \"pwmd\" element."));
866 rc = GPG_ERR_BAD_DATA;
869 if (!rc)
870 rc = validate_import(n ? n->children : n);
872 if (rc) {
873 log_write("ERR %i: %s", rc, pwmd_strerror(rc));
874 xmlFreeDoc(doc);
875 goto fail;
878 xmlDocDumpMemory(doc, &xml, &len);
879 xmlFreeDoc(doc);
880 crypto->save.s2k_count = (gulong)s2k_count;
881 crypto->save.hdr.iterations = iterations;
882 rc = set_pinentry_options(crypto->agent);
883 if (!rc)
884 rc = export_common(crypto, keygrip, sign_keygrip, no_passphrase, xml,
885 len, outfile, params, keyfile);
887 xmlFree(xml);
888 if (rc) {
889 send_error(NULL, rc);
890 goto fail;
893 cleanup_crypto(&crypto);
894 return TRUE;
896 fail:
897 cleanup_crypto(&crypto);
898 return FALSE;
901 static gboolean do_cache_push(const gchar *filename, struct crypto_s *crypto)
903 guchar md5file[16];
904 gpg_error_t rc;
905 gchar *key = NULL;
906 gsize keylen;
907 xmlDocPtr doc;
908 struct cache_data_s *cdata;
909 guchar *crc;
910 gsize len;
912 log_write(_("Trying to add datafile '%s' to the file cache ..."),
913 filename);
915 if (valid_filename(filename) == FALSE) {
916 log_write(_("%s: Invalid characters in filename"), filename);
917 return FALSE;
920 rc = read_data_file(filename, crypto);
921 if (rc) {
922 log_write("ERR %i: %s", rc, pwmd_strerror(rc));
923 return FALSE;
926 if ((key = get_key_file_string(filename, "passphrase"))) {
927 log_write(_("Trying the passphrase specified in config ..."));
928 keylen = strlen(key);
930 else if ((key = get_key_file_string(filename, "passphrase_file"))) {
931 gint fd = open((gchar *)key, O_RDONLY);
932 struct stat st;
934 log_write(_("Trying the passphrase using file '%s' ..."), key);
935 if (fd == -1) {
936 log_write("%s: %s", key, pwmd_strerror(gpg_error_from_syserror()));
937 g_free(key);
938 return FALSE;
941 stat((gchar *)key, &st);
942 g_free(key);
943 key = g_malloc(st.st_size);
944 if (read(fd, key, st.st_size) != st.st_size) {
945 log_write("short read() count");
946 g_free(key);
947 close(fd);
948 return FALSE;
951 keylen = st.st_size;
954 if (key) {
955 rc = set_agent_passphrase(crypto, key, keylen);
956 g_free(key);
957 if (rc) {
958 log_write("ERR %i: %s", rc, pwmd_strerror(rc));
959 return FALSE;
963 crypto->filename = g_strdup(filename);
964 rc = decrypt_data(NULL, crypto);
965 if (rc) {
966 log_write("ERR %i: %s", rc, pwmd_strerror(rc));
967 return FALSE;
970 doc = parse_doc((gchar *)crypto->plaintext, crypto->plaintext_len);
971 if (!doc) {
972 log_write("%s", pwmd_strerror(GPG_ERR_ENOMEM));
973 return FALSE;
976 gcry_md_hash_buffer(GCRY_MD_MD5, md5file, filename, strlen(filename));
977 cdata = g_malloc0(sizeof(struct cache_data_s));
978 if (!cdata) {
979 xmlFreeDoc(doc);
980 log_write("%s", pwmd_strerror(GPG_ERR_ENOMEM));
981 return FALSE;
984 rc = get_checksum(filename, &crc, &len);
985 if (rc) {
986 log_write("ERR %i: %s", rc, pwmd_strerror(rc));
987 xmlFreeDoc(doc);
988 free_cache_data_once(cdata);
989 return FALSE;
992 cdata->crc = crc;
993 rc = encrypt_xml(NULL, cache_key, cache_keysize, GCRY_CIPHER_AES,
994 crypto->plaintext, crypto->plaintext_len, &cdata->doc,
995 &cdata->doclen, &cache_iv, &cache_blocksize, 0);
996 if (rc) {
997 log_write("ERR %i: %s", rc, pwmd_strerror(rc));
998 xmlFreeDoc(doc);
999 free_cache_data_once(cdata);
1000 return FALSE;
1003 gcry_sexp_build((gcry_sexp_t *)&cdata->pubkey, NULL, "%S", crypto->pkey_sexp);
1004 gcry_sexp_build((gcry_sexp_t *)&cdata->sigkey, NULL, "%S", crypto->sigpkey_sexp);
1005 gint timeout = get_key_file_integer(filename, "cache_timeout");
1006 cache_add_file(md5file, crypto->grip, cdata, timeout);
1007 log_write(_("Successfully added '%s' to the cache."), filename);
1008 return TRUE;
1011 static gpg_error_t init_client_thread(gint fd, const gchar *addr)
1013 gpg_error_t rc = 0;
1014 struct client_thread_s *new = g_malloc0(sizeof(struct client_thread_s));
1016 if (!new) {
1017 close(fd);
1018 return GPG_ERR_ENOMEM;
1021 MUTEX_LOCK(&cn_mutex);
1022 pthread_cleanup_push(cleanup_mutex_cb, &cn_mutex);
1024 if (pipe(new->status_msg_pipe) == -1)
1025 rc = gpg_error_from_syserror();
1027 if (!rc) {
1028 fcntl(new->status_msg_pipe[0], F_SETFL, O_NONBLOCK);
1029 fcntl(new->status_msg_pipe[1], F_SETFL, O_NONBLOCK);
1030 pthread_mutex_init(&new->status_mutex, NULL);
1033 if (!rc) {
1034 #ifdef WITH_GNUTLS
1035 new->remote = addr ? TRUE : FALSE;
1036 #endif
1037 new->fd = fd;
1038 rc = create_thread(client_thread, new, &new->tid, TRUE);
1039 if (rc) {
1040 close(new->status_msg_pipe[0]);
1041 close(new->status_msg_pipe[1]);
1042 pthread_mutex_destroy(&new->status_mutex);
1046 if (!rc) {
1047 GSList *list = g_slist_append(cn_thread_list, new);
1049 if (list) {
1050 cn_thread_list = list;
1051 if (addr)
1052 log_write(_("new connection: tid=%p, fd=%i, addr=%s"),
1053 (pthread_t *)new->tid, fd, addr);
1054 else
1055 log_write(_("new connection: tid=%p, fd=%i"),
1056 (pthread_t *)new->tid, fd);
1058 else
1059 rc = GPG_ERR_ENOMEM;
1062 pthread_cleanup_pop(1);
1064 if (rc) {
1065 g_free(new);
1066 close(fd);
1067 log_write("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1068 pwmd_strerror(rc));
1070 return rc;
1073 #ifdef WITH_GNUTLS
1074 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1075 static void *get_in_addr(struct sockaddr *sa)
1077 if (sa->sa_family == AF_INET)
1078 return &(((struct sockaddr_in*)sa)->sin_addr);
1080 return &(((struct sockaddr_in6*)sa)->sin6_addr);
1083 static void *tcp_accept_thread(void *arg)
1085 gint sockfd = *(gint*)arg;
1087 #ifdef HAVE_PR_SET_NAME
1088 prctl(PR_SET_NAME, "tcp_accept");
1089 #endif
1090 pthread_setspecific(thread_name_key, g_strdup(__FUNCTION__));
1092 for (;;) {
1093 struct sockaddr_storage raddr;
1094 socklen_t slen = sizeof(raddr);
1095 gint fd = -1;
1096 gulong n;
1097 gchar *t;
1098 gchar s[INET6_ADDRSTRLEN];
1100 fd = accept(sockfd, (struct sockaddr *)&raddr, &slen);
1101 if (fd == -1) {
1102 if (errno == EMFILE || errno == ENFILE)
1103 log_write("accept(): %s", pwmd_strerror(gpg_error_from_syserror()));
1104 else if (errno != EAGAIN) {
1105 if (!quit) // probably EBADF
1106 log_write("accept(): %s", strerror(errno));
1108 break;
1111 continue;
1114 if (quit)
1115 break;
1117 inet_ntop(raddr.ss_family, get_in_addr((struct sockaddr *)&raddr),
1118 s, sizeof s);
1119 (void)init_client_thread(fd, s);
1120 t = get_key_file_string("global", "tcp_wait");
1121 n = strtol(t, NULL, 10);
1122 g_free(t);
1123 if (n > 0)
1124 usleep(n*100000);
1127 /* Just in case accept() failed for some reason other than EBADF */
1128 quit = 1;
1129 return NULL;
1132 static gboolean start_stop_tls_with_protocol(gboolean ipv6, gboolean term)
1134 struct addrinfo hints, *servinfo, *p;
1135 gint port = get_key_file_integer("global", "tcp_port");
1136 gchar buf[7];
1137 gint n;
1138 gpg_error_t rc;
1139 gint *fd = ipv6 ? &tls6_fd : &tls_fd;
1141 if (term || get_key_file_boolean("global", "enable_tcp") == FALSE) {
1142 if (tls6_fd != -1) {
1143 pthread_cancel(tls6_tid);
1144 pthread_join(tls6_tid, NULL);
1145 shutdown(tls6_fd, SHUT_RDWR);
1146 close(tls6_fd);
1147 tls6_fd = -1;
1150 if (tls_fd != -1) {
1151 pthread_cancel(tls_tid);
1152 pthread_join(tls_tid, NULL);
1153 shutdown(tls_fd, SHUT_RDWR);
1154 close(tls_fd);
1155 tls_fd = -1;
1158 /* A client may still be connected. */
1159 if (!quit && x509_cred != NULL)
1160 tls_deinit_params();
1162 return TRUE;
1165 if ((ipv6 && tls6_fd != -1) || (!ipv6 && tls_fd != -1))
1166 return TRUE;
1168 memset(&hints, 0, sizeof(hints));
1169 hints.ai_family = ipv6 ? AF_INET6 : AF_INET;
1170 hints.ai_socktype = SOCK_STREAM;
1171 hints.ai_flags = AI_PASSIVE;
1173 if ((n = getaddrinfo(NULL, print_fmt(buf, sizeof(buf), "%i", port),
1174 &hints, &servinfo)) == -1) {
1175 log_write("getaddrinfo(): %s", gai_strerror(n));
1176 return FALSE;
1179 for (n = 0, p = servinfo; p != NULL; p = p->ai_next) {
1180 if ((ipv6 && p->ai_family != AF_INET6)
1181 || (!ipv6 && p->ai_family != AF_INET))
1182 continue;
1184 if ((*fd = socket(p->ai_family, p->ai_socktype,
1185 p->ai_protocol)) == -1) {
1186 log_write("socket(): %s", strerror(errno));
1187 continue;
1190 if (setsockopt(*fd, SOL_SOCKET, SO_REUSEADDR, &n,
1191 sizeof(int)) == -1) {
1192 log_write("setsockopt(): %s", strerror(errno));
1193 freeaddrinfo(servinfo);
1194 goto fail;
1197 if (bind(*fd, p->ai_addr, p->ai_addrlen) == -1) {
1198 close(*fd);
1199 log_write("bind(): %s", strerror(errno));
1200 continue;
1203 n++;
1204 break;
1207 freeaddrinfo(servinfo);
1209 if (!n) {
1210 log_write("%s", _("could not bind"));
1211 goto fail;
1214 #ifdef HAVE_DECL_SO_BINDTODEVICE
1215 if (g_key_file_has_key(keyfileh, "global", "tcp_interface", NULL)) {
1216 gchar *tmp = get_key_file_string("global", "tcp_interface");
1218 if (setsockopt(*fd, SOL_SOCKET, SO_BINDTODEVICE, tmp, 1)
1219 == -1) {
1220 log_write("setsockopt(): %s", strerror(errno));
1221 g_free(tmp);
1222 goto fail;
1225 g_free(tmp);
1227 #endif
1229 if (x509_cred == NULL) {
1230 rc = tls_init_params();
1231 if (rc)
1232 goto fail;
1235 if (listen(*fd, 0) == -1) {
1236 log_write("listen(): %s", strerror(errno));
1237 goto fail;
1240 if (ipv6)
1241 rc = create_thread(tcp_accept_thread, fd, &tls6_tid, FALSE);
1242 else
1243 rc = create_thread(tcp_accept_thread, fd, &tls_tid, FALSE);
1245 if (rc) {
1246 log_write("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1247 pwmd_strerror(rc));
1248 goto fail;
1251 return TRUE;
1253 fail:
1254 start_stop_tls_with_protocol(FALSE, TRUE);
1255 if (tls_fd != -1)
1256 close(tls_fd);
1258 if (tls6_fd != -1)
1259 close(tls6_fd);
1261 tls_fd = -1;
1262 tls6_fd = -1;
1263 return FALSE;
1266 static gboolean start_stop_tls(gboolean term)
1268 gchar *s = get_key_file_string("global", "tcp_bind");
1269 gboolean b;
1271 if (!s)
1272 return FALSE;
1274 if (!g_strcmp0(s, "any")) {
1275 b = start_stop_tls_with_protocol(FALSE, term);
1276 if (b)
1277 b = start_stop_tls_with_protocol(TRUE, term);
1279 else if (!g_strcmp0(s, "ipv4"))
1280 b = start_stop_tls_with_protocol(FALSE, term);
1281 else if (!g_strcmp0(s, "ipv6"))
1282 b = start_stop_tls_with_protocol(TRUE, term);
1283 else
1284 b = FALSE;
1286 g_free(s);
1287 return b;
1289 #endif
1291 static void *accept_thread(void *arg)
1293 gint sockfd = *(gint *)arg;
1295 #ifdef HAVE_PR_SET_NAME
1296 prctl(PR_SET_NAME, "accept");
1297 #endif
1298 pthread_setspecific(thread_name_key, g_strdup(__FUNCTION__));
1300 for (;;) {
1301 socklen_t slen = sizeof(struct sockaddr_un);
1302 struct sockaddr_un raddr;
1303 gint fd;
1305 fd = accept(sockfd, (struct sockaddr *)&raddr, &slen);
1306 if (fd == -1) {
1307 if (errno == EMFILE || errno == ENFILE)
1308 log_write("accept(): %s", pwmd_strerror(gpg_error_from_syserror()));
1309 else if (errno != EAGAIN) {
1310 if (!quit) // probably EBADF
1311 log_write("accept(): %s", pwmd_strerror(gpg_error_from_syserror()));
1313 break;
1315 continue;
1318 (void)init_client_thread(fd, NULL);
1321 /* Just in case accept() failed for some reason other than EBADF */
1322 quit = TRUE;
1323 return NULL;
1326 static void *cache_timer_thread(void *arg)
1328 #ifdef HAVE_PR_SET_NAME
1329 prctl(PR_SET_NAME, "cache timer");
1330 #endif
1331 pthread_setspecific(thread_name_key, g_strdup(__FUNCTION__));
1333 for (;;) {
1334 sleep(1);
1335 cache_adjust_timeout();
1338 return NULL;
1341 static void catch_sigabrt(int sig)
1343 cache_clear(NULL);
1344 #ifndef MEM_DEBUG
1345 xpanic();
1346 #endif
1349 static gboolean signal_loop(sigset_t sigset)
1351 gboolean done = FALSE;
1352 gboolean sigint = FALSE;
1354 do {
1355 gint sig = sigwaitinfo(&sigset, NULL);
1357 if (sig == -1) {
1358 if (errno != EAGAIN)
1359 log_write("sigwaitinfo(): %s", strerror(errno));
1360 continue;
1363 if (sig != SIGUSR2)
1364 log_write(_("caught signal %i (%s)"), sig, strsignal(sig));
1366 switch (sig) {
1367 case SIGHUP:
1368 pthread_cond_signal(&rcfile_cond);
1369 break;
1370 case SIGABRT:
1371 // not really handled here.
1372 catch_sigabrt(SIGABRT);
1373 break;
1374 case SIGUSR1:
1375 log_write(_("clearing file cache"));
1376 cache_clear(NULL);
1377 send_status_all(STATUS_CACHE, NULL);
1378 break;
1379 case SIGUSR2:
1380 done = TRUE;
1381 break;
1382 default:
1383 sigint = TRUE;
1384 done = TRUE;
1385 break;
1387 } while (!done);
1389 return sigint;
1392 static void catchsig(int sig)
1394 log_write("Caught SIGSEGV. Exiting.");
1395 #ifdef HAVE_BACKTRACE
1396 BACKTRACE(__FUNCTION__);
1397 #endif
1398 longjmp(jmp, 1);
1401 static void *waiting_for_exit(void *arg)
1403 #ifdef HAVE_PR_SET_NAME
1404 prctl(PR_SET_NAME, "exiting");
1405 #endif
1406 pthread_setspecific(thread_name_key, g_strdup(__FUNCTION__));
1407 log_write(_("waiting for all clients to disconnect"));
1408 MUTEX_LOCK(&quit_mutex);
1409 pthread_cleanup_push(cleanup_mutex_cb, &quit_mutex);
1411 for (;;) {
1412 MUTEX_LOCK(&cn_mutex);
1413 gint n = g_slist_length(cn_thread_list);
1414 MUTEX_UNLOCK(&cn_mutex);
1415 if (!n)
1416 break;
1418 log_write(_("%i clients remain"), n);
1419 pthread_cond_wait(&quit_cond, &quit_mutex);
1422 pthread_cleanup_pop(1);
1423 kill(getpid(), SIGUSR2);
1424 return NULL;
1427 static gboolean server_loop(gint sockfd, gchar **socketpath)
1429 pthread_t accept_tid;
1430 pthread_t cache_timeout_tid;
1431 gboolean cancel_timeout_thread = FALSE, cancel_accept_thread = FALSE;
1432 gint n, i;
1433 sigset_t sigset;
1434 gboolean segv = FALSE;
1435 gpg_error_t rc;
1437 init_commands();
1438 sigemptyset(&sigset);
1440 /* Termination */
1441 sigaddset(&sigset, SIGTERM);
1442 sigaddset(&sigset, SIGINT);
1444 /* Clears the file cache. */
1445 sigaddset(&sigset, SIGUSR1);
1447 /* Configuration file reloading. */
1448 sigaddset(&sigset, SIGHUP);
1450 /* For exiting cleanly. */
1451 sigaddset(&sigset, SIGUSR2);
1453 /* Clears the cache and exits when something bad happens. */
1454 signal(SIGABRT, catch_sigabrt);
1455 sigaddset(&sigset, SIGABRT);
1456 sigprocmask(SIG_BLOCK, &sigset, NULL);
1458 /* Ignored everywhere. When a client disconnects abnormally this signal
1459 * gets raised. It isn't needed though because client_thread() will check
1460 * for rcs even after the client disconnects. */
1461 signal(SIGPIPE, SIG_IGN);
1463 /* Can show a backtrace of the stack in the log. */
1464 signal(SIGSEGV, catchsig);
1466 #ifdef WITH_GNUTLS
1467 /* Needs to be done after the fork(). */
1468 if (!start_stop_tls(FALSE)) {
1469 segv = TRUE;
1470 goto done;
1472 #endif
1474 pthread_mutex_init(&quit_mutex, NULL);
1475 pthread_cond_init(&quit_cond, NULL);
1476 log_write(_("%s started for user %s"), PACKAGE_STRING, g_get_user_name());
1477 #ifndef HAVE_DECL_SO_PEERCRED
1478 log_write(_("Peer credential checking is NOT supported on this OS."));
1479 #endif
1480 #ifdef WITH_GNUTLS
1481 if (get_key_file_boolean("global", "enable_tcp"))
1482 log_write(_("Listening on %s and TCP port %i"), *socketpath,
1483 get_key_file_integer("global", "tcp_port"));
1484 else
1485 log_write(_("Listening on %s"), *socketpath);
1486 #else
1487 log_write(_("Listening on %s"), *socketpath);
1488 #endif
1490 rc = create_thread(reload_rcfile_thread, NULL, &rcfile_tid, FALSE);
1491 if (rc) {
1492 log_write("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1493 pwmd_strerror(rc));
1494 goto done;
1497 rc = create_thread(cache_timer_thread, NULL, &cache_timeout_tid, TRUE);
1498 if (rc) {
1499 log_write("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1500 pwmd_strerror(rc));
1501 goto done;
1504 cancel_timeout_thread = TRUE;
1505 rc = create_thread(accept_thread, &sockfd, &accept_tid, TRUE);
1506 if (rc) {
1507 log_write("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1508 pwmd_strerror(rc));
1509 goto done;
1512 cancel_accept_thread = TRUE;
1513 sigdelset(&sigset, SIGUSR2);
1514 if (!setjmp(jmp))
1515 signal_loop(sigset);
1516 else
1517 segv = TRUE;
1519 done:
1521 * We're out of the main server loop. This happens when a signal was sent
1522 * to terminate the daemon. We'll wait for all clients to disconnect
1523 * before exiting but exit immediately if another termination signal is
1524 * sent.
1526 if (cancel_accept_thread)
1527 pthread_cancel(accept_tid);
1529 shutdown(sockfd, SHUT_RDWR);
1530 close(sockfd);
1531 unlink(*socketpath);
1532 g_free(*socketpath);
1533 *socketpath = NULL;
1534 MUTEX_LOCK(&cn_mutex);
1535 n = g_slist_length(cn_thread_list);
1536 MUTEX_UNLOCK(&cn_mutex);
1538 if (n && !segv) {
1539 pthread_t tid;
1541 rc = create_thread(waiting_for_exit, NULL, &tid, TRUE);
1542 if (!rc) {
1543 sigaddset(&sigset, SIGUSR2);
1544 if (signal_loop(sigset)) {
1545 log_write(_("Received second termination request. Exiting."));
1546 pthread_cancel(tid);
1549 else
1550 log_write("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1551 pwmd_strerror(rc));
1554 if (cancel_timeout_thread)
1555 pthread_cancel(cache_timeout_tid);
1557 MUTEX_LOCK(&cn_mutex);
1558 i = 0;
1559 n = g_slist_length(cn_thread_list);
1561 for (i = 0; i < n; i++) {
1562 struct client_thread_s *thd = g_slist_nth_data(cn_thread_list, i);
1564 if (thd->fd != -1) {
1565 close(thd->fd);
1566 thd->fd = -1;
1570 exiting = TRUE;
1571 MUTEX_UNLOCK(&cn_mutex);
1572 #ifdef WITH_GNUTLS
1573 start_stop_tls(TRUE);
1574 #endif
1575 cache_deinit();
1576 deinit_commands();
1577 pthread_cond_destroy(&quit_cond);
1578 pthread_mutex_destroy(&quit_mutex);
1579 return segv ? EXIT_FAILURE : EXIT_SUCCESS;;
1582 static void startup_failure()
1584 log_write(_("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
1585 cache_clear(NULL);
1588 /* This is called from cache.c:clear_once(). See
1589 * command.c:clearcache_command() for details about lock checking.
1591 static gpg_error_t free_cache_data(file_cache_t *cache)
1593 gpg_error_t rc = GPG_ERR_NO_DATA;
1594 gint i, t;
1595 struct client_thread_s *found = NULL;
1596 gboolean self = FALSE;
1598 if (!cache->data)
1599 return 0;
1601 cache_lock();
1602 MUTEX_LOCK(&cn_mutex);
1603 pthread_cleanup_push(cleanup_mutex_cb, &cn_mutex);
1604 t = g_slist_length(cn_thread_list);
1606 for (i = 0; i < t; i++) {
1607 struct client_thread_s *thd = g_slist_nth_data(cn_thread_list, i);
1609 if (!thd->cl)
1610 continue;
1612 if (!memcmp(thd->cl->md5file, cache->filename,
1613 sizeof(cache->filename))) {
1614 if (pthread_equal(pthread_self(), thd->tid)) {
1615 found = thd;
1616 self = TRUE;
1617 continue;
1620 /* Continue trying to find a client who has the same file open and
1621 * also has a lock. */
1622 rc = cache_lock_mutex(thd->cl->ctx, thd->cl->md5file, -1, FALSE, -1);
1623 if (!rc) {
1624 self = FALSE;
1625 found = thd;
1626 break;
1631 if (self && (!rc || rc == GPG_ERR_NO_DATA))
1632 rc = cache_lock_mutex(found->cl->ctx, found->cl->md5file, -1, FALSE, -1);
1634 if (exiting || !rc || rc == GPG_ERR_NO_DATA) {
1635 free_cache_data_once(cache->data);
1636 cache->data = NULL;
1637 cache->defer_clear = FALSE;
1638 cache->timeout = -1;
1640 if (found)
1641 cache_unlock_mutex(found->cl->md5file, FALSE);
1643 rc = 0;
1646 if (rc)
1647 cache->defer_clear = TRUE;
1649 pthread_cleanup_pop(1);
1650 cache_unlock();
1651 return rc;
1654 static gboolean convert_v2_datafile(const gchar *filename, const gchar *cipher,
1655 const gchar *keyfile, const gchar *keygrip, const gchar *sign_keygrip,
1656 gboolean nopass, const gchar *outfile, const gchar *keyparam,
1657 gulong s2k_count, guint64 iterations)
1659 gpg_error_t rc;
1660 gpointer data = NULL;
1661 gsize datalen;
1662 struct crypto_s *crypto = NULL;
1663 guint16 ver;
1664 gint algo;
1666 if (outfile[0] == '-' && outfile[1] == 0)
1667 outfile = NULL;
1669 log_write(_("Converting version 2 data file \"%s\" ..."), filename);
1670 if (access(filename, R_OK) == -1) {
1671 log_write("%s: %s", filename, pwmd_strerror(gpg_error_from_syserror()));
1672 return FALSE;
1675 if (keyfile) {
1676 log_write(_("Using passphrase file \"%s\" for decryption ..."),
1677 keyfile);
1678 if (access(keyfile, R_OK) == -1) {
1679 log_write("%s: %s", keyfile,
1680 pwmd_strerror(gpg_error_from_syserror()));
1681 return FALSE;
1685 rc = read_v2_datafile(filename, keyfile, &data, &datalen, &ver, &algo);
1686 if (rc) {
1687 log_write("ERR %i: %s", rc, pwmd_strerror(rc));
1688 return FALSE;
1691 if (cipher) {
1692 algo = cipher_string_to_gcrypt(cipher);
1693 if (algo == -1) {
1694 rc = GPG_ERR_CIPHER_ALGO;
1695 goto fail;
1699 if (ver < 0x212) {
1700 xmlDocPtr doc = parse_doc(data, datalen);
1702 if (!doc) {
1703 rc = GPG_ERR_BAD_DATA;
1704 goto fail;
1707 rc = convert_pre_212_elements(doc);
1708 gcry_free(data);
1709 data = NULL;
1710 if (!rc) {
1711 xmlDocDumpFormatMemory(doc, (xmlChar **)&data, (gint *)&datalen, 0);
1712 if (!data)
1713 rc = GPG_ERR_ENOMEM;
1716 xmlFreeDoc(doc);
1717 if (rc)
1718 goto fail;
1721 rc = init_client_crypto(&crypto);
1722 if (!rc) {
1723 rc = set_pinentry_options(crypto->agent);
1724 if (!rc) {
1725 memcpy(&crypto->save.hdr, &crypto->hdr,
1726 sizeof(file_header_t));
1727 crypto->save.hdr.flags = set_cipher_flag(crypto->save.hdr.flags, algo);
1728 crypto->save.s2k_count = (gulong)s2k_count;
1729 crypto->save.hdr.iterations = iterations;
1730 rc = export_common(crypto, keygrip, sign_keygrip, nopass, data,
1731 datalen, outfile, keyparam,
1732 no_passphrase_file ? NULL : keyfile);
1733 if (!rc)
1734 log_write(_("Output written to \"%s\"."), outfile);
1738 fail:
1739 if (ver < 0x212)
1740 xmlFree(data);
1741 else
1742 gcry_free(data);
1743 cleanup_crypto(&crypto);
1745 if (rc)
1746 log_write("ERR %i: %s", rc, pwmd_strerror(rc));
1747 return rc ? FALSE : TRUE;
1750 int main(int argc, char *argv[])
1752 gint opt;
1753 struct sockaddr_un addr;
1754 gchar buf[PATH_MAX];
1755 gchar *socketpath = NULL, *socketdir, *socketname = NULL;
1756 gchar *socketarg = NULL;
1757 gchar *datadir = NULL;
1758 gboolean n;
1759 gint x;
1760 gchar *p;
1761 gchar **cache_push = NULL;
1762 gchar *import = NULL, *keygrip = NULL, *sign_keygrip = NULL;
1763 gchar *keyparam = NULL;
1764 gboolean rcfile_spec = FALSE;
1765 gint estatus = EXIT_FAILURE;
1766 gint sockfd;
1767 gchar *outfile = NULL;
1768 GMemVTable mtable = { xmalloc, xrealloc, xfree, xcalloc, NULL, NULL };
1769 gint do_unlink = 0;
1770 gboolean secure = FALSE;
1771 gint show_version = 0;
1772 gboolean force = FALSE;
1773 gboolean no_passphrase = FALSE;
1774 gpg_error_t rc;
1775 gchar *convertfile = NULL;
1776 gchar *cipher = NULL;
1777 gchar *keyfile = NULL;
1778 glong s2k_count = -1;
1779 guint64 iterations = 0;
1780 GError *error = NULL;
1781 gchar *debug_level_opt = NULL;
1782 GOptionContext *context;
1783 GOptionEntry options[] =
1785 { "version", 0, 0, G_OPTION_ARG_NONE, &show_version,
1786 "version information", NULL },
1787 { "no-fork", 'n', 0, G_OPTION_ARG_NONE, &nofork,
1788 "run as a foreground process", NULL },
1789 { "disable-dump", 'D', 0, G_OPTION_ARG_NONE, &secure,
1790 "disable the LIST, XPATH and DUMP commands", NULL },
1791 { "rcfile", 'f', 0, G_OPTION_ARG_FILENAME, &rcfile,
1792 "load the specified rcfile (~/.pwmd/config)", "filename" },
1793 { "ignore", 0, 0, G_OPTION_ARG_NONE, &force,
1794 "ignore cache failures on startup", NULL },
1795 { "outfile", 'o', 0, G_OPTION_ARG_FILENAME, &outfile,
1796 "output file when importing (- for stdout)", "filename" },
1797 { "convert", 'C', 0, G_OPTION_ARG_FILENAME, &convertfile,
1798 "convert a version 2 data file to version 3", "filename" },
1799 { "passphrase-file", 'k', 0, G_OPTION_ARG_FILENAME, &keyfile,
1800 "for decryption when converting", "filename" },
1801 { "no-passphrase-file", 0, 0, G_OPTION_ARG_NONE, &no_passphrase_file,
1802 "no --passphrase-file after conversion", NULL },
1803 { "import", 'I', 0, G_OPTION_ARG_FILENAME, &import,
1804 "import an XML file", "filename" },
1805 { "keygrip", 0, 0, G_OPTION_ARG_STRING, &keygrip,
1806 "the public keygrip to use for encryption", "hexstring"},
1807 { "sign-keygrip", 0, 0, G_OPTION_ARG_STRING, &sign_keygrip,
1808 "the keygrip to use for signing of the data", "hexstring"},
1809 { "keyparam", 0, 0, G_OPTION_ARG_STRING, &keyparam,
1810 "alternate key parameters to use (RSA-2048)", "s-exp"},
1811 { "no-passphrase", 0, 0, G_OPTION_ARG_NONE, &no_passphrase,
1812 "for the imported/converted keypair", NULL },
1813 { "cipher", 0, 0, G_OPTION_ARG_STRING, &cipher,
1814 "encryption cipher, see man page (aes256)", "string" },
1815 { "s2k-count", 0, 0, G_OPTION_ARG_INT64, &s2k_count,
1816 "hash iteration count >65536 (calibrated)", "iterations" },
1817 { "cipher-iterations", 0, 0, G_OPTION_ARG_INT64, &iterations,
1818 "cipher iteration count (N+1)", "iterations" },
1819 { "debug-level", 0, 0, G_OPTION_ARG_STRING, &debug_level_opt,
1820 "protocol output, see man page", "keywords"},
1821 { "homedir", 'I', 0, G_OPTION_ARG_STRING, &homedir,
1822 "home directory for pwmd", "directory" },
1823 { NULL }
1826 #ifndef DEBUG
1827 #ifdef HAVE_SETRLIMIT
1828 struct rlimit rl;
1830 rl.rlim_cur = rl.rlim_max = 0;
1832 if (setrlimit(RLIMIT_CORE, &rl) != 0)
1833 err(EXIT_FAILURE, "setrlimit()");
1834 #endif
1835 #endif
1837 #ifdef ENABLE_NLS
1838 setlocale(LC_ALL, "");
1839 bindtextdomain("pwmd", LOCALEDIR);
1840 textdomain("pwmd");
1841 #endif
1843 #ifndef MEM_DEBUG
1844 xmem_init();
1845 #endif
1846 g_mem_set_vtable(&mtable);
1847 g_thread_init(NULL);
1848 gpg_err_init();
1850 if (setup_crypto())
1851 exit(EXIT_FAILURE);
1853 #ifdef WITH_GNUTLS
1854 gnutls_global_set_mem_functions(g_malloc, g_malloc, secure_mem_check,
1855 g_realloc, g_free);
1856 gnutls_global_init();
1857 gnutls_global_set_log_function(tls_log);
1858 gnutls_global_set_log_level(1);
1859 tls_fd = -1;
1860 tls6_fd = -1;
1861 #endif
1862 xmlMemSetup(g_free, g_malloc, g_realloc, g_strdup);
1863 xmlInitMemory();
1864 xmlInitGlobals();
1865 xmlInitParser();
1866 xmlXPathInit();
1868 cmdline = TRUE;
1869 context = g_option_context_new("- Password Manager Daemon");
1870 g_option_context_add_main_entries(context, options, NULL);
1871 if (!g_option_context_parse(context, &argc, &argv, &error))
1873 g_print("Option parsing failed: %s\n", error->message);
1874 exit(EXIT_FAILURE);
1877 if (show_version) {
1878 printf(_("%s\n\n"
1879 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012\n"
1880 "%s\n"
1881 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
1882 "Compile time features:\n%s"), PACKAGE_STRING, PACKAGE_BUGREPORT,
1883 #ifdef WITH_GNUTLS
1884 "+WITH_GNUTLS\n"
1885 #else
1886 "-WITH_GNUTLS\n"
1887 #endif
1888 #ifdef WITH_LIBACL
1889 "+WITH_LIBACL\n"
1890 #else
1891 "-WITH_LIBACL\n"
1892 #endif
1893 #ifdef DEBUG
1894 "+DEBUG\n"
1895 #else
1896 "-DEBUG\n"
1897 #endif
1898 #ifdef MEM_DEBUG
1899 "+MEM_DEBUG\n"
1900 #else
1901 "-MEM_DEBUG\n"
1902 #endif
1903 #ifdef MUTEX_DEBUG
1904 "+MUTEX_DEBUG\n"
1905 #else
1906 "-MUTEX_DEBUG\n"
1907 #endif
1909 exit(EXIT_SUCCESS);
1912 if (!homedir)
1913 homedir = g_strdup_printf("%s/.pwmd", g_get_home_dir());
1915 if (mkdir(homedir, 0700) == -1 && errno != EEXIST)
1916 err(EXIT_FAILURE, "%s", homedir);
1918 g_snprintf(buf, sizeof(buf), "%s/data", homedir);
1919 if (mkdir(buf, 0700) == -1 && errno != EEXIST)
1920 err(EXIT_FAILURE, "%s", buf);
1922 datadir = g_strdup(buf);
1923 pthread_mutexattr_t attr;
1924 pthread_mutexattr_init(&attr);
1925 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1926 pthread_mutex_init(&rcfile_mutex, &attr);
1927 pthread_cond_init(&rcfile_cond, NULL);
1928 pthread_mutex_init(&cn_mutex, &attr);
1929 pthread_mutexattr_destroy(&attr);
1930 pthread_key_create(&last_error_key, free_key);
1932 if (!rcfile)
1933 rcfile = g_strdup_printf("%s/config", homedir);
1934 else
1935 rcfile_spec = TRUE;
1937 if ((keyfileh = parse_rcfile(rcfile_spec, cmdline)) == NULL)
1938 exit(EXIT_FAILURE);
1940 if (debug_level_opt)
1941 debug_level = g_strsplit(debug_level_opt, ",", 0);
1943 if (g_key_file_has_key(keyfileh, "global", "syslog", NULL) == TRUE)
1944 log_syslog = g_key_file_get_boolean(keyfileh, "global", "syslog", NULL);
1946 if (log_syslog == TRUE)
1947 openlog("pwmd", LOG_NDELAY|LOG_PID, LOG_DAEMON);
1949 if (g_key_file_has_key(keyfileh, "global", "priority", NULL)) {
1950 x = g_key_file_get_integer(keyfileh, "global", "priority", NULL);
1951 errno = 0;
1953 if (setpriority(PRIO_PROCESS, 0, x) == -1) {
1954 log_write("setpriority(): %s", pwmd_strerror(gpg_error_from_syserror()));
1955 goto do_exit;
1959 #ifdef HAVE_MLOCKALL
1960 if (disable_mlock == FALSE && mlockall(MCL_CURRENT|MCL_FUTURE) == -1) {
1961 log_write("mlockall(): %s", pwmd_strerror(gpg_error_from_syserror()));
1962 goto do_exit;
1964 #endif
1966 rc = cache_init(free_cache_data);
1967 if (rc) {
1968 log_write("pwmd: gpg-agent: ERR %i: %s", rc,
1969 gpg_err_code(rc) == GPG_ERR_UNKNOWN_VERSION
1970 ? _("incompatible version: 2.1.0 or later required")
1971 : pwmd_strerror(rc));
1972 goto do_exit;
1975 if (s2k_count == -1)
1976 s2k_count = get_key_file_ulong(NULL, "s2k_count");
1978 if (convertfile) {
1979 if (!outfile) {
1980 gchar *tmp = g_option_context_get_help(context, TRUE, NULL);
1981 fprintf(stderr, "%s", tmp);
1982 g_free(tmp);
1983 exit(EXIT_FAILURE);
1986 estatus = convert_v2_datafile(convertfile, cipher, keyfile, keygrip,
1987 sign_keygrip, no_passphrase, outfile, keyparam,
1988 (gulong)s2k_count, iterations);
1989 g_key_file_free(keyfileh);
1990 g_free(rcfile);
1991 exit(!estatus);
1994 if (import) {
1995 if (!outfile) {
1996 gchar *tmp = g_option_context_get_help(context, TRUE, NULL);
1997 fprintf(stderr, "%s", tmp);
1998 g_free(tmp);
1999 exit(EXIT_FAILURE);
2002 if (outfile[0] == '-' && outfile[1] == 0)
2003 outfile = NULL;
2005 estatus = xml_import(import, outfile, keygrip, sign_keygrip, keyfile,
2006 no_passphrase, cipher, keyparam, (gulong)s2k_count, iterations);
2007 g_key_file_free(keyfileh);
2008 g_free(rcfile);
2009 exit(!estatus);
2012 g_option_context_free(context);
2013 p = g_key_file_get_string(keyfileh, "global", "socket_path", NULL);
2014 if (!p)
2015 p = g_strdup_printf("%s/socket", homedir);
2017 socketarg = expand_homedir(p);
2018 g_free(p);
2020 if (secure == FALSE && g_key_file_has_key(keyfileh, "global", "disable_list_and_dump", NULL) == TRUE) {
2021 n = g_key_file_get_boolean(keyfileh, "global", "disable_list_and_dump", NULL);
2022 disable_list_and_dump = n;
2024 else
2025 disable_list_and_dump = secure;
2027 setup_logging(keyfileh);
2029 if (g_key_file_has_key(keyfileh, "global", "cache_push", NULL) == TRUE)
2030 cache_push = g_key_file_get_string_list(keyfileh, "global", "cache_push", NULL, NULL);
2032 for (gint n = 1; n < argc; n++) {
2033 if (strv_printf(&cache_push, "%s", argv[n]) == FALSE)
2034 errx(EXIT_FAILURE, "%s", pwmd_strerror(GPG_ERR_ENOMEM));
2037 if (strchr(socketarg, '/') == NULL) {
2038 socketdir = g_get_current_dir();
2039 socketname = g_strdup(socketarg);
2040 socketpath = g_strdup_printf("%s/%s", socketdir, socketname);
2042 else {
2043 socketname = g_strdup(strrchr(socketarg, '/'));
2044 socketname++;
2045 socketarg[strlen(socketarg) - strlen(socketname) -1] = 0;
2046 socketdir = g_strdup(socketarg);
2047 socketpath = g_strdup_printf("%s/%s", socketdir, socketname);
2050 if (chdir(datadir)) {
2051 log_write("%s: %s", datadir, pwmd_strerror(gpg_error_from_syserror()));
2052 unlink(socketpath);
2053 goto do_exit;
2057 * Set the cache entry for a file. Prompts for the password.
2059 if (cache_push) {
2060 struct crypto_s *crypto;
2061 gpg_error_t rc = init_client_crypto(&crypto);
2063 if (rc) {
2064 estatus = EXIT_FAILURE;
2065 goto do_exit;
2068 rc = set_pinentry_options(crypto->agent);
2069 if (rc) {
2070 estatus = EXIT_FAILURE;
2071 goto do_exit;
2074 for (opt = 0; cache_push[opt]; opt++) {
2075 if (!do_cache_push(cache_push[opt], crypto) && !force) {
2076 g_strfreev(cache_push);
2077 startup_failure();
2078 estatus = EXIT_FAILURE;
2079 cleanup_crypto(&crypto);
2080 goto do_exit;
2083 cleanup_crypto_stage1(crypto);
2086 (void)kill_scd(crypto->agent);
2087 cleanup_crypto(&crypto);
2088 g_strfreev(cache_push);
2089 log_write(!nofork ? _("Done. Daemonizing...") : _("Done. Waiting for connections..."));
2092 clear_rcfile_keys();
2095 * bind() doesn't like the full pathname of the socket or any non alphanum
2096 * characters so change to the directory where the socket is wanted then
2097 * create it then change to datadir.
2099 if (chdir(socketdir)) {
2100 log_write("%s: %s", socketdir, pwmd_strerror(gpg_error_from_syserror()));
2101 goto do_exit;
2104 g_free(socketdir);
2106 if ((sockfd = socket(PF_UNIX, SOCK_STREAM, 0)) == -1) {
2107 log_write("socket(): %s", pwmd_strerror(gpg_error_from_syserror()));
2108 goto do_exit;
2111 addr.sun_family = AF_UNIX;
2112 g_snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", socketname);
2114 if (bind(sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr)) == -1) {
2115 log_write("bind(): %s", pwmd_strerror(gpg_error_from_syserror()));
2117 if (errno == EADDRINUSE)
2118 log_write(_("Either there is another pwmd running or '%s' is a \n"
2119 "stale socket. Please remove it manually."), socketpath);
2121 goto do_exit;
2124 do_unlink = 1;
2125 if (g_key_file_has_key(keyfileh, "global", "socket_perms", NULL) == TRUE) {
2126 gchar *t = g_key_file_get_string(keyfileh, "global", "socket_perms", NULL);
2127 mode_t mode = strtol(t, NULL, 8);
2128 mode_t mask = umask(0);
2130 g_free(t);
2132 if (chmod(socketname, mode) == -1) {
2133 log_write("%s: %s", socketname, pwmd_strerror(gpg_error_from_syserror()));
2134 close(sockfd);
2135 unlink(socketpath);
2136 umask(mask);
2137 goto do_exit;
2140 umask(mask);
2143 g_free(--socketname);
2145 if (chdir(datadir)) {
2146 log_write("%s: %s", datadir, pwmd_strerror(gpg_error_from_syserror()));
2147 close(sockfd);
2148 unlink(socketpath);
2149 goto do_exit;
2152 g_free(datadir);
2154 if (listen(sockfd, 0) == -1) {
2155 log_write("listen(): %s", pwmd_strerror(gpg_error_from_syserror()));
2156 goto do_exit;
2159 cmdline = FALSE;
2161 if (!nofork) {
2162 switch (fork()) {
2163 case -1:
2164 log_write("fork(): %s", pwmd_strerror(gpg_error_from_syserror()));
2165 goto do_exit;
2166 case 0:
2167 close(0);
2168 close(1);
2169 close(2);
2170 setsid();
2171 break;
2172 default:
2173 _exit(EXIT_SUCCESS);
2177 pthread_key_create(&thread_name_key, free_key);
2178 pthread_setspecific(thread_name_key, g_strdup("main"));
2179 estatus = server_loop(sockfd, &socketpath);
2181 do_exit:
2182 if (socketpath && do_unlink) {
2183 unlink(socketpath);
2184 g_free(socketpath);
2187 g_free(socketarg);
2188 #ifdef WITH_GNUTLS
2189 gnutls_global_deinit();
2190 #endif
2191 pthread_cancel(rcfile_tid);
2192 pthread_join(rcfile_tid, NULL);
2193 pthread_cond_destroy(&rcfile_cond);
2194 pthread_mutex_destroy(&rcfile_mutex);
2196 if (keyfileh)
2197 g_key_file_free(keyfileh);
2199 g_free(rcfile);
2200 xmlCleanupParser();
2201 xmlCleanupGlobals();
2203 if (estatus == EXIT_SUCCESS)
2204 log_write(_("pwmd exiting normally"));
2206 closelog();
2207 #if defined(DEBUG) && !defined(MEM_DEBUG)
2208 xdump();
2209 #endif
2210 exit(estatus);