Generate translation strings for src/tls.c.
[pwmd.git] / src / pwmd.c
blobfa3d8453afa08df6b2294a4587252c9369ae7c7d
1 /* vim:tw=78:ts=8:sw=4:set ft=c: */
2 /*
3 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012
4 Ben Kibbey <bjk@luxsci.net>
6 This file is part of pwmd.
8 Pwmd is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 2 of the License, or
11 (at your option) any later version.
13 Pwmd is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
21 #ifdef HAVE_CONFIG_H
22 #include <config.h>
23 #endif
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <err.h>
29 #include <ctype.h>
30 #include <string.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 gchar **users;
144 GKeyFile *k;
146 pthread_cond_wait(&rcfile_cond, &rcfile_mutex);
147 users = g_key_file_get_string_list(keyfileh, "global", "allowed", NULL, NULL);
148 log_write(_("reloading configuration file '%s'"), rcfile);
149 k = parse_rcfile(FALSE, cmdline);
150 if (k) {
151 g_key_file_free(keyfileh);
152 keyfileh = k;
153 cache_push_from_rcfile();
154 clear_rcfile_keys();
157 disable_list_and_dump = !disable_list_and_dump ? b : TRUE;
158 g_key_file_set_string_list(keyfileh, "global", "allowed",
159 (const gchar **)users, g_strv_length(users));
160 g_strfreev(users);
161 #ifdef WITH_GNUTLS
162 /* Kill existing listening threads since the configured listening
163 * protocols may have changed. */
164 start_stop_tls(TRUE);
165 start_stop_tls(FALSE);
166 #endif
169 pthread_cleanup_pop(1);
170 return NULL;
173 gpg_error_t send_error(assuan_context_t ctx, gpg_error_t e)
175 struct client_s *client = assuan_get_pointer(ctx);
177 if (gpg_err_source(e) == GPG_ERR_SOURCE_UNKNOWN)
178 e = gpg_error(e);
180 if (client)
181 client->last_rc = e;
183 if (!e)
184 return assuan_process_done(ctx, 0);
186 if (!ctx) {
187 log_write("%s", pwmd_strerror(e));
188 return e;
191 if (gpg_err_code(e) == GPG_ERR_BAD_DATA) {
192 xmlErrorPtr xe = client->xml_error;
194 if (!xe)
195 xe = xmlGetLastError();
196 if (xe) {
197 log_write("%s", xe->message);
198 if (client->last_error)
199 g_free(client->last_error);
201 client->last_error = g_strdup(xe->message);
204 e = assuan_process_done(ctx, assuan_set_error(ctx, e,
205 xe ? xe->message : NULL));
207 if (xe == client->xml_error)
208 xmlResetError(xe);
209 else
210 xmlResetLastError();
212 client->xml_error = NULL;
213 return e;
216 return assuan_process_done(ctx, assuan_set_error(ctx, e, pwmd_strerror(e)));
219 int assuan_log_cb(assuan_context_t ctx, void *data, unsigned cat,
220 const char *msg)
222 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
223 int i, t;
224 gboolean match = FALSE;
226 pthread_mutex_lock(&m);
227 pthread_cleanup_push((void (*)(void *))pthread_mutex_unlock, &m);
228 t = g_strv_length(debug_level);
230 for (i = 0; i < t; i++) {
231 if (!g_ascii_strcasecmp(debug_level[i], (gchar *)"init")
232 && cat == ASSUAN_LOG_INIT) {
233 match = TRUE;
234 break;
237 if (!g_ascii_strcasecmp(debug_level[i], (gchar *)"ctx")
238 && cat == ASSUAN_LOG_CTX) {
239 match = TRUE;
240 break;
243 if (!g_ascii_strcasecmp(debug_level[i], (gchar *)"engine")
244 && cat == ASSUAN_LOG_ENGINE) {
245 match = TRUE;
246 break;
249 if (!g_ascii_strcasecmp(debug_level[i], (gchar *)"data")
250 && cat == ASSUAN_LOG_DATA) {
251 match = TRUE;
252 break;
255 if (!g_ascii_strcasecmp(debug_level[i], (gchar *)"sysio")
256 && cat == ASSUAN_LOG_SYSIO) {
257 match = TRUE;
258 break;
261 if (!g_ascii_strcasecmp(debug_level[i], (gchar *)"control")
262 && cat == ASSUAN_LOG_CONTROL) {
263 match = TRUE;
264 break;
268 if (match && msg) {
269 if (logfile) {
270 int fd;
272 if ((fd = open(logfile, O_WRONLY|O_CREAT|O_APPEND, 0600)) == -1)
273 warn("%s", logfile);
274 else {
275 pthread_cleanup_push(cleanup_fd_cb, &fd);
276 write(fd, msg, strlen(msg));
277 pthread_cleanup_pop(1);
281 if (nofork) {
282 fprintf(stderr, "%s%s", data ? (gchar *)data : "", msg);
283 fflush(stderr);
287 pthread_cleanup_pop(1);
288 return match;
291 void log_write(const gchar *fmt, ...)
293 gchar *args, *line;
294 va_list ap;
295 struct tm *tm;
296 time_t now;
297 gchar tbuf[21];
298 gint fd = -1;
299 gchar *name = NULL;
300 gchar buf[255];
301 pthread_t tid = pthread_self();
302 static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
304 if ((!logfile && !isatty(STDERR_FILENO) && !log_syslog) || !fmt)
305 return;
307 pthread_mutex_lock(&m);
308 pthread_cleanup_push((void (*)(void *))pthread_mutex_unlock, &m);
309 pthread_cleanup_push(cleanup_fd_cb, &fd);
311 if (!cmdline && logfile) {
312 if ((fd = open(logfile, O_WRONLY|O_CREAT|O_APPEND, 0600)) == -1)
313 warn("%s", logfile);
316 va_start(ap, fmt);
318 if (g_vasprintf(&args, fmt, ap) != -1) {
319 if (cmdline) {
320 pthread_cleanup_push(g_free, args);
321 fprintf(stderr, "%s\n", args);
322 fflush(stderr);
323 pthread_cleanup_pop(1);
325 else {
326 pthread_cleanup_push(g_free, args);
327 name = pthread_getspecific(thread_name_key);
328 name = print_fmt(buf, sizeof(buf), "%s(%p): ",
329 name ? name : _("unknown"), (pthread_t *)tid);
331 if (!cmdline && log_syslog && !nofork)
332 syslog(LOG_INFO, "%s%s", name, args);
334 time(&now);
335 tm = localtime(&now);
336 strftime(tbuf, sizeof(tbuf), "%b %d %Y %H:%M:%S ", tm);
337 tbuf[sizeof(tbuf) - 1] = 0;
339 if (args[strlen(args)-1] == '\n')
340 args[strlen(args)-1] = 0;
342 line = g_strdup_printf("%s %i %s%s\n", tbuf, getpid(), name,
343 args);
344 pthread_cleanup_pop(1);
345 if (line) {
346 pthread_cleanup_push(g_free, line);
347 if (logfile && fd != -1) {
348 write(fd, line, strlen(line));
349 fsync(fd);
352 if (nofork) {
353 fprintf(stdout, "%s", line);
354 fflush(stdout);
357 pthread_cleanup_pop(1);
362 va_end(ap);
363 pthread_cleanup_pop(1);
364 pthread_cleanup_pop(0);
365 pthread_mutex_unlock(&m);
368 #ifdef WITH_GNUTLS
369 static gint secure_mem_check(const void *arg)
371 return 1;
373 #endif
375 static gpg_error_t setup_crypto()
377 gpg_error_t rc;
379 gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
381 if (!gcry_check_version(NULL))
382 errx(EXIT_FAILURE, _("gcry_check_version(): Incompatible libgcrypt. Wanted %s, got %s."), GCRYPT_VERSION, gcry_check_version(NULL));
384 gcry_set_allocation_handler(g_malloc, g_malloc, NULL, g_realloc, g_free);
385 return rc;
388 static gpg_error_t validate_peer(struct client_s *cl)
390 gchar **users;
391 gboolean allowed = FALSE;
392 assuan_peercred_t peercred;
393 gpg_error_t rc;
395 #ifdef WITH_GNUTLS
396 if (cl->thd->remote)
397 return 0;
398 #endif
400 rc = assuan_get_peercred(cl->ctx, &peercred);
401 if (rc)
402 return rc;
404 users = g_key_file_get_string_list(keyfileh, "global", "allowed", NULL, NULL);
406 if (users) {
407 for (gchar **p = users; *p; p++) {
408 struct passwd pw, *result;
409 struct group gr, *gresult;
410 char *buf;
412 if (*(*p) == '@') {
413 size_t len = sysconf(_SC_GETGR_R_SIZE_MAX);
415 if (len == -1)
416 len = 16384;
418 buf = g_malloc(len);
420 if (!buf) {
421 g_strfreev(users);
422 return GPG_ERR_ENOMEM;
425 if (!getgrnam_r(*(p)+1, &gr, buf, len, &gresult) && gresult) {
426 if (gresult->gr_gid == peercred->gid) {
427 g_free(buf);
428 allowed = TRUE;
429 break;
432 len = sysconf(_SC_GETPW_R_SIZE_MAX);
434 if (len == -1)
435 len = 16384;
437 gchar *tbuf = g_malloc(len);
439 for (gchar **t = gresult->gr_mem; *t; t++) {
440 if (!getpwnam_r(*t, &pw, tbuf, len, &result) && result) {
441 if (result->pw_uid == peercred->uid) {
442 g_free(buf);
443 allowed = TRUE;
444 break;
449 g_free(tbuf);
451 if (allowed)
452 break;
455 else {
456 size_t len = sysconf(_SC_GETPW_R_SIZE_MAX);
458 if (len == -1)
459 len = 16384;
461 buf = g_malloc(len);
463 if (!buf) {
464 g_strfreev(users);
465 return GPG_ERR_ENOMEM;
468 if (!getpwnam_r(*p, &pw, buf, len, &result) && result) {
469 if (result->pw_uid == peercred->uid) {
470 g_free(buf);
471 allowed = TRUE;
472 break;
477 g_free(buf);
480 g_strfreev(users);
483 log_write("peer %s: uid=%i, gid=%i, pid=%i",
484 allowed ? _("accepted") : _("rejected"), peercred->uid,
485 peercred->gid, peercred->pid);
486 return allowed ? 0 : GPG_ERR_INV_USER_ID;
489 static void xml_error_cb(void *data, xmlErrorPtr e)
491 struct client_s *client = data;
494 * Keep the first reported error as the one to show in the error
495 * description. Reset in send_error().
497 if (client->xml_error)
498 return;
500 xmlCopyError(e, client->xml_error);
503 static pid_t hook_waitpid(assuan_context_t ctx, pid_t pid, int action,
504 int *status, int options)
506 return waitpid(pid, status, options);
509 static ssize_t hook_read(assuan_context_t ctx, assuan_fd_t fd, void *data,
510 size_t len)
512 #ifdef WITH_GNUTLS
513 struct client_s *client = assuan_get_pointer(ctx);
515 if (client->thd->remote)
516 return tls_read_hook(ctx, (gint)fd, data, len);
517 #endif
519 return read((gint)fd, data, len);
522 static ssize_t hook_write(assuan_context_t ctx, assuan_fd_t fd,
523 const void *data, size_t len)
525 #ifdef WITH_GNUTLS
526 struct client_s *client = assuan_get_pointer(ctx);
528 if (client->thd->remote)
529 return tls_write_hook(ctx, (gint)fd, data, len);
530 #endif
532 return write((gint)fd, data, len);
535 static gboolean new_connection(struct client_s *cl)
537 gpg_error_t rc;
538 static struct assuan_malloc_hooks mhooks = { g_malloc, g_realloc, g_free };
539 static struct assuan_system_hooks shooks = {
540 ASSUAN_SYSTEM_HOOKS_VERSION,
541 __assuan_usleep,
542 __assuan_pipe,
543 __assuan_close,
544 hook_read,
545 hook_write,
546 //FIXME
547 NULL, //recvmsg
548 NULL, //sendmsg both are used for FD passing
549 __assuan_spawn,
550 hook_waitpid,
551 __assuan_socketpair,
552 __assuan_socket,
553 __assuan_connect
556 #ifdef WITH_GNUTLS
557 if (cl->thd->remote) {
558 gchar *prio = get_key_file_string("global", "tls_cipher_suite");
560 cl->thd->tls = tls_init(cl->thd->fd, prio);
561 g_free(prio);
562 if (!cl->thd->tls)
563 return FALSE;
565 #endif
567 rc = assuan_new_ext(&cl->ctx, GPG_ERR_SOURCE_DEFAULT, &mhooks,
568 debug_level ? assuan_log_cb : NULL, NULL);
569 if (rc)
570 goto fail;
572 assuan_ctx_set_system_hooks(cl->ctx, &shooks);
573 rc = assuan_init_socket_server(cl->ctx, cl->thd->fd, 2);
574 if (rc)
575 goto fail;
577 assuan_set_pointer(cl->ctx, cl);
578 assuan_set_hello_line(cl->ctx, PACKAGE_STRING);
579 rc = register_commands(cl->ctx);
580 if (rc)
581 goto fail;
583 rc = assuan_accept(cl->ctx);
584 if (rc)
585 goto fail;
587 rc = validate_peer(cl);
588 /* May not be implemented on all platforms. */
589 if (rc && gpg_err_code(rc) != GPG_ERR_ASS_GENERAL)
590 goto fail;
592 rc = init_client_crypto(&cl->crypto);
593 if (rc)
594 goto fail;
596 cl->crypto->agent->client_ctx = cl->ctx;
597 cl->crypto->client_ctx = cl->ctx;
598 xmlSetStructuredErrorFunc(cl, xml_error_cb);
599 return TRUE;
601 fail:
602 log_write("%s", pwmd_strerror(rc));
603 return FALSE;
607 * This is called after a client_thread() terminates. Set with
608 * pthread_cleanup_push().
610 static void cleanup_cb(void *arg)
612 struct client_thread_s *cn = arg;
613 struct client_s *cl = cn->cl;
615 MUTEX_LOCK(&cn_mutex);
616 cn_thread_list = g_slist_remove(cn_thread_list, cn);
617 MUTEX_UNLOCK(&cn_mutex);
619 if (cl) {
620 cleanup_client(cl);
622 #ifdef WITH_GNUTLS
623 if (cn->tls) {
624 gnutls_deinit(cn->tls->ses);
625 g_free(cn->tls->fp);
626 g_free(cn->tls);
628 #endif
630 if (cl->ctx)
631 assuan_release(cl->ctx);
632 else if (cl->thd && cl->thd->fd != -1)
633 close(cl->thd->fd);
635 if (cl->crypto)
636 cleanup_crypto(&cl->crypto);
638 g_free(cl);
640 else {
641 if (cn->fd != -1)
642 close(cn->fd);
645 while (cn->msg_queue) {
646 struct status_msg_s *msg = cn->msg_queue;
648 cn->msg_queue = msg->next;
649 g_free(msg->line);
650 g_free(msg);
653 if (cn->status_msg_pipe[0] != -1)
654 close(cn->status_msg_pipe[0]);
656 if (cn->status_msg_pipe[1] != -1)
657 close(cn->status_msg_pipe[1]);
659 pthread_mutex_destroy(&cn->status_mutex);
660 log_write(_("exiting, fd=%i"), cn->fd);
661 g_free(cn);
662 send_status_all(STATUS_CLIENTS, NULL);
663 pthread_cond_signal(&quit_cond);
666 static gpg_error_t send_msg_queue(struct client_thread_s *thd)
668 MUTEX_LOCK(&thd->status_mutex);
669 gpg_error_t rc = 0;
670 gchar c;
672 read(thd->status_msg_pipe[0], &c, 1);
674 while (thd->msg_queue) {
675 struct status_msg_s *msg = thd->msg_queue;
677 thd->msg_queue = thd->msg_queue->next;
678 MUTEX_UNLOCK(&thd->status_mutex);
679 rc = send_status(thd->cl->ctx, msg->s, msg->line);
680 MUTEX_LOCK(&thd->status_mutex);
681 g_free(msg->line);
682 g_free(msg);
684 if (rc)
685 break;
688 MUTEX_UNLOCK(&thd->status_mutex);
689 return rc;
692 static void *client_thread(void *data)
694 struct client_thread_s *thd = data;
695 struct client_s *cl = g_malloc0(sizeof(struct client_s));
697 #ifdef HAVE_PR_SET_NAME
698 prctl(PR_SET_NAME, "client");
699 #endif
700 pthread_setspecific(thread_name_key, g_strdup(__FUNCTION__));
702 if (!cl) {
703 log_write("%s(%i): %s", __FILE__, __LINE__,
704 pwmd_strerror(GPG_ERR_ENOMEM));
705 return NULL;
708 MUTEX_LOCK(&cn_mutex);
709 pthread_cleanup_push(cleanup_cb, thd);
710 thd->cl = cl;
711 cl->thd = thd;
712 MUTEX_UNLOCK(&cn_mutex);
714 if (new_connection(cl)) {
715 gboolean finished = FALSE;
716 gpg_error_t rc;
718 send_status_all(STATUS_CLIENTS, NULL);
719 rc = send_status(cl->ctx, STATUS_CACHE, NULL);
720 if (rc) {
721 log_write("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror(rc));
722 finished = TRUE;
725 while (!finished) {
726 fd_set rfds;
727 gint n;
728 gint eof;
730 FD_ZERO(&rfds);
731 FD_SET(thd->fd, &rfds);
732 FD_SET(thd->status_msg_pipe[0], &rfds);
733 n = thd->fd > thd->status_msg_pipe[0] ? thd->fd : thd->status_msg_pipe[0];
735 n = select(n+1, &rfds, NULL, NULL, NULL);
736 if (n == -1) {
737 log_write("%s", strerror(errno));
738 break;
741 if (FD_ISSET(thd->status_msg_pipe[0], &rfds)) {
742 rc = send_msg_queue(thd);
743 if (rc && gpg_err_code(rc) != GPG_ERR_EPIPE) {
744 log_write("%s(%i): %s", __FUNCTION__, __LINE__,
745 pwmd_strerror(rc));
746 break;
750 if (!FD_ISSET(thd->fd, &rfds))
751 continue;
753 rc = assuan_process_next(cl->ctx, &eof);
754 if (rc || eof) {
755 if (gpg_err_code(rc) == GPG_ERR_EOF || eof)
756 break;
758 log_write("assuan_process_next(): %s", pwmd_strerror(rc));
759 rc = send_error(cl->ctx, rc);
761 if (rc) {
762 log_write("assuan_process_done(): %s", pwmd_strerror(rc));
763 break;
767 /* Since the msg queue pipe fd's are non-blocking, check for
768 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
769 * client has already disconnected and will be converted to
770 * GPG_ERR_EOF during assuan_process_next().
772 rc = send_msg_queue(thd);
773 if (rc && gpg_err_code(rc) != GPG_ERR_EPIPE) {
774 log_write("%s(%i): %s", __FUNCTION__, __LINE__,
775 pwmd_strerror(rc));
776 break;
781 pthread_cleanup_pop(1);
782 return NULL;
785 static gboolean xml_import(const gchar *filename, const gchar *outfile,
786 const gchar *keygrip, const char *sign_keygrip, const gchar *keyfile,
787 gboolean no_passphrase, const gchar *cipher, const gchar *params,
788 gulong s2k_count)
790 xmlDocPtr doc;
791 gint fd;
792 struct stat st;
793 gint len;
794 xmlChar *xmlbuf;
795 xmlChar *xml;
796 gpg_error_t rc;
797 struct crypto_s *crypto;
798 gint algo = cipher ? cipher_string_to_gcrypt((gchar *)cipher) :
799 GCRY_CIPHER_AES256;
801 if (algo == -1) {
802 log_write("%s", pwmd_strerror(GPG_ERR_CIPHER_ALGO));
803 return FALSE;
806 if (stat(filename, &st) == -1) {
807 log_write("%s: %s", filename, pwmd_strerror(gpg_error_from_syserror()));
808 return FALSE;
811 rc = init_client_crypto(&crypto);
812 if (rc)
813 return FALSE;
815 memcpy(&crypto->save.hdr, &crypto->hdr, sizeof(file_header_t));
816 crypto->save.hdr.flags = set_cipher_flag(crypto->save.hdr.flags, algo);
817 log_write(_("Importing XML from '%s'. Output will be written to '%s' ..."),
818 filename, outfile);
820 if ((fd = open(filename, O_RDONLY)) == -1) {
821 log_write("%s: %s", filename, pwmd_strerror(gpg_error_from_syserror()));
822 goto fail;
825 if ((xmlbuf = xmalloc(st.st_size+1)) == NULL) {
826 close(fd);
827 log_write("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror(GPG_ERR_ENOMEM));
828 goto fail;
831 if (read(fd, xmlbuf, st.st_size) == -1) {
832 rc = gpg_error_from_syserror();
833 close(fd);
834 log_write("%s: %s", filename, pwmd_strerror(rc));
835 goto fail;
838 close(fd);
839 xmlbuf[st.st_size] = 0;
841 * Make sure the document validates.
843 if ((doc = xmlReadDoc(xmlbuf, NULL, "UTF-8", XML_PARSE_NOBLANKS)) == NULL) {
844 log_write("xmlReadDoc() failed");
845 xfree(xmlbuf);
846 goto fail;
849 xfree(xmlbuf);
850 xmlNodePtr n = xmlDocGetRootElement(doc);
851 if (strcmp((gchar *)n->name, (gchar *)"pwmd")) {
852 log_write(_("Could not find root \"pwmd\" element."));
853 rc = GPG_ERR_BAD_DATA;
856 if (!rc)
857 rc = validate_import(n ? n->children : n);
859 if (rc) {
860 log_write("%s", pwmd_strerror(rc));
861 xmlFreeDoc(doc);
862 goto fail;
865 xmlDocDumpMemory(doc, &xml, &len);
866 xmlFreeDoc(doc);
867 crypto->save.s2k_count = (gulong)s2k_count;
868 rc = set_pinentry_options(crypto->agent);
869 if (!rc)
870 rc = export_common(crypto, keygrip, sign_keygrip, no_passphrase, xml,
871 len, outfile, params, keyfile);
873 xmlFree(xml);
874 if (rc) {
875 send_error(NULL, rc);
876 goto fail;
879 cleanup_crypto(&crypto);
880 return TRUE;
882 fail:
883 cleanup_crypto(&crypto);
884 return FALSE;
887 static gboolean do_cache_push(const gchar *filename, struct crypto_s *crypto)
889 guchar md5file[16];
890 gpg_error_t rc;
891 gchar *key = NULL;
892 gsize keylen;
893 xmlDocPtr doc;
894 struct cache_data_s *cdata;
895 guchar *crc;
896 gsize len;
898 log_write(_("Trying to add datafile '%s' to the file cache ..."),
899 filename);
901 if (valid_filename(filename) == FALSE) {
902 log_write(_("%s: Invalid characters in filename"), filename);
903 return FALSE;
906 rc = read_data_file(filename, crypto);
907 if (rc) {
908 log_write("%s", pwmd_strerror(rc));
909 return FALSE;
912 if ((key = get_key_file_string(filename, "passphrase"))) {
913 log_write(_("Trying the passphrase specified in config ..."));
914 keylen = strlen(key);
916 else if ((key = get_key_file_string(filename, "passphrase_file"))) {
917 gint fd = open((gchar *)key, O_RDONLY);
918 struct stat st;
920 log_write(_("Trying the passphrase using file '%s' ..."), key);
921 if (fd == -1) {
922 log_write("%s: %s", key, pwmd_strerror(gpg_error_from_syserror()));
923 g_free(key);
924 return FALSE;
927 stat((gchar *)key, &st);
928 g_free(key);
929 key = g_malloc(st.st_size);
930 if (read(fd, key, st.st_size) != st.st_size) {
931 log_write("short read() count");
932 g_free(key);
933 close(fd);
934 return FALSE;
937 keylen = st.st_size;
940 if (key) {
941 rc = set_agent_passphrase(crypto, key, keylen);
942 g_free(key);
943 if (rc) {
944 log_write("%s", pwmd_strerror(rc));
945 return FALSE;
949 crypto->filename = g_strdup(filename);
950 rc = decrypt_data(crypto);
951 if (rc) {
952 log_write("%s", pwmd_strerror(rc));
953 return FALSE;
956 doc = parse_doc((gchar *)crypto->plaintext, crypto->plaintext_len);
957 if (!doc) {
958 log_write("%s", pwmd_strerror(GPG_ERR_ENOMEM));
959 return FALSE;
962 gcry_md_hash_buffer(GCRY_MD_MD5, md5file, filename, strlen(filename));
963 cdata = g_malloc0(sizeof(struct cache_data_s));
964 if (!cdata) {
965 xmlFreeDoc(doc);
966 log_write("%s", pwmd_strerror(GPG_ERR_ENOMEM));
967 return FALSE;
970 rc = get_checksum(filename, &crc, &len);
971 if (rc) {
972 log_write("%s", pwmd_strerror(rc));
973 xmlFreeDoc(doc);
974 free_cache_data_once(cdata);
975 return FALSE;
978 cdata->crc = crc;
979 rc = encrypt_xml(cache_key, cache_keysize, GCRY_CIPHER_AES,
980 crypto->plaintext, crypto->plaintext_len, &cdata->doc,
981 &cdata->doclen, &cache_iv, &cache_blocksize);
982 if (rc) {
983 log_write("%s", pwmd_strerror(rc));
984 xmlFreeDoc(doc);
985 free_cache_data_once(cdata);
986 return FALSE;
989 gcry_sexp_build((gcry_sexp_t *)&cdata->pubkey, NULL, "%S", crypto->pkey_sexp);
990 gcry_sexp_build((gcry_sexp_t *)&cdata->sigkey, NULL, "%S", crypto->sigpkey_sexp);
991 gint timeout = get_key_file_integer(filename, "cache_timeout");
992 cache_add_file(md5file, crypto->grip, cdata, timeout);
993 log_write(_("Successfully added '%s' to the cache."), filename);
994 return TRUE;
997 static gpg_error_t init_client_thread(gint fd, const gchar *addr)
999 gpg_error_t rc = 0;
1000 struct client_thread_s *new = g_malloc0(sizeof(struct client_thread_s));
1002 if (!new) {
1003 close(fd);
1004 return GPG_ERR_ENOMEM;
1007 MUTEX_LOCK(&cn_mutex);
1008 pthread_cleanup_push(cleanup_mutex_cb, &cn_mutex);
1010 if (pipe(new->status_msg_pipe) == -1)
1011 rc = gpg_error_from_syserror();
1013 if (!rc) {
1014 fcntl(new->status_msg_pipe[0], F_SETFL, O_NONBLOCK);
1015 fcntl(new->status_msg_pipe[1], F_SETFL, O_NONBLOCK);
1016 pthread_mutex_init(&new->status_mutex, NULL);
1019 if (!rc) {
1020 #ifdef WITH_GNUTLS
1021 new->remote = addr ? TRUE : FALSE;
1022 #endif
1023 new->fd = fd;
1024 rc = create_thread(client_thread, new, &new->tid, TRUE);
1025 if (rc) {
1026 close(new->status_msg_pipe[0]);
1027 close(new->status_msg_pipe[1]);
1028 pthread_mutex_destroy(&new->status_mutex);
1032 if (!rc) {
1033 cn_thread_list = g_slist_append(cn_thread_list, new);
1034 if (addr)
1035 log_write(_("new connection: tid=%p, fd=%i, addr=%s"),
1036 (pthread_t *)new->tid, fd, addr);
1037 else
1038 log_write(_("new connection: tid=%p, fd=%i"),
1039 (pthread_t *)new->tid, fd);
1042 pthread_cleanup_pop(1);
1044 if (rc) {
1045 g_free(new);
1046 close(fd);
1047 log_write("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1048 pwmd_strerror(rc));
1050 return rc;
1053 #ifdef WITH_GNUTLS
1054 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1055 static void *get_in_addr(struct sockaddr *sa)
1057 if (sa->sa_family == AF_INET)
1058 return &(((struct sockaddr_in*)sa)->sin_addr);
1060 return &(((struct sockaddr_in6*)sa)->sin6_addr);
1063 static void *tcp_accept_thread(void *arg)
1065 gint sockfd = *(gint*)arg;
1067 #ifdef HAVE_PR_SET_NAME
1068 prctl(PR_SET_NAME, "tcp_accept");
1069 #endif
1070 pthread_setspecific(thread_name_key, g_strdup(__FUNCTION__));
1072 for (;;) {
1073 struct sockaddr_storage raddr;
1074 socklen_t slen = sizeof(raddr);
1075 gint fd = -1;
1076 gulong n;
1077 gchar *t;
1078 gchar s[INET6_ADDRSTRLEN];
1080 fd = accept(sockfd, (struct sockaddr *)&raddr, &slen);
1081 if (fd == -1) {
1082 if (errno != EAGAIN) {
1083 if (!quit) // probably EBADF
1084 log_write("accept(): %s", strerror(errno));
1086 break;
1089 continue;
1092 if (quit)
1093 break;
1095 inet_ntop(raddr.ss_family, get_in_addr((struct sockaddr *)&raddr),
1096 s, sizeof s);
1097 (void)init_client_thread(fd, s);
1098 t = get_key_file_string("global", "tcp_wait");
1099 n = strtol(t, NULL, 10);
1100 g_free(t);
1101 if (n > 0)
1102 usleep(n*100000);
1105 /* Just in case accept() failed for some reason other than EBADF */
1106 quit = 1;
1107 return NULL;
1110 static gboolean start_stop_tls_with_protocol(gboolean ipv6, gboolean term)
1112 struct addrinfo hints, *servinfo, *p;
1113 gint port = get_key_file_integer("global", "tcp_port");
1114 gchar buf[7];
1115 gint n;
1116 gpg_error_t rc;
1117 gint *fd = ipv6 ? &tls6_fd : &tls_fd;
1119 if (term || get_key_file_boolean("global", "enable_tcp") == FALSE) {
1120 if (tls6_fd != -1) {
1121 pthread_cancel(tls6_tid);
1122 pthread_join(tls6_tid, NULL);
1123 shutdown(tls6_fd, SHUT_RDWR);
1124 close(tls6_fd);
1125 tls6_fd = -1;
1128 if (tls_fd != -1) {
1129 pthread_cancel(tls_tid);
1130 pthread_join(tls_tid, NULL);
1131 shutdown(tls_fd, SHUT_RDWR);
1132 close(tls_fd);
1133 tls_fd = -1;
1136 /* A client may still be connected. */
1137 if (!quit && x509_cred != NULL)
1138 tls_deinit_params();
1140 return TRUE;
1143 if ((ipv6 && tls6_fd != -1) || (!ipv6 && tls_fd != -1))
1144 return TRUE;
1146 memset(&hints, 0, sizeof(hints));
1147 hints.ai_family = ipv6 ? AF_INET6 : AF_INET;
1148 hints.ai_socktype = SOCK_STREAM;
1149 hints.ai_flags = AI_PASSIVE;
1151 if ((n = getaddrinfo(NULL, print_fmt(buf, sizeof(buf), "%i", port),
1152 &hints, &servinfo)) == -1) {
1153 log_write("getaddrinfo(): %s", gai_strerror(n));
1154 return FALSE;
1157 for (n = 0, p = servinfo; p != NULL; p = p->ai_next) {
1158 if ((ipv6 && p->ai_family != AF_INET6)
1159 || (!ipv6 && p->ai_family != AF_INET))
1160 continue;
1162 if ((*fd = socket(p->ai_family, p->ai_socktype,
1163 p->ai_protocol)) == -1) {
1164 log_write("socket(): %s", strerror(errno));
1165 continue;
1168 if (setsockopt(*fd, SOL_SOCKET, SO_REUSEADDR, &n,
1169 sizeof(int)) == -1) {
1170 log_write("setsockopt(): %s", strerror(errno));
1171 freeaddrinfo(servinfo);
1172 goto fail;
1175 if (bind(*fd, p->ai_addr, p->ai_addrlen) == -1) {
1176 close(*fd);
1177 log_write("bind(): %s", strerror(errno));
1178 continue;
1181 n++;
1182 break;
1185 freeaddrinfo(servinfo);
1187 if (!n) {
1188 log_write("%s", _("could not bind"));
1189 goto fail;
1192 #ifdef HAVE_DECL_SO_BINDTODEVICE
1193 if (g_key_file_has_key(keyfileh, "global", "tcp_interface", NULL)) {
1194 gchar *tmp = get_key_file_string("global", "tcp_interface");
1196 if (setsockopt(*fd, SOL_SOCKET, SO_BINDTODEVICE, tmp, 1)
1197 == -1) {
1198 log_write("setsockopt(): %s", strerror(errno));
1199 g_free(tmp);
1200 goto fail;
1203 g_free(tmp);
1205 #endif
1207 if (x509_cred == NULL) {
1208 rc = tls_init_params();
1209 if (rc)
1210 goto fail;
1213 if (listen(*fd, 0) == -1) {
1214 log_write("listen(): %s", strerror(errno));
1215 goto fail;
1218 if (ipv6)
1219 rc = create_thread(tcp_accept_thread, fd, &tls6_tid, FALSE);
1220 else
1221 rc = create_thread(tcp_accept_thread, fd, &tls_tid, FALSE);
1223 if (rc) {
1224 log_write("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1225 pwmd_strerror(rc));
1226 goto fail;
1229 return TRUE;
1231 fail:
1232 start_stop_tls_with_protocol(FALSE, TRUE);
1233 if (tls_fd != -1)
1234 close(tls_fd);
1236 if (tls6_fd != -1)
1237 close(tls6_fd);
1239 tls_fd = -1;
1240 tls6_fd = -1;
1241 return FALSE;
1244 static gboolean start_stop_tls(gboolean term)
1246 gchar *s = get_key_file_string("global", "tcp_bind");
1247 gboolean b;
1249 if (!s)
1250 return FALSE;
1252 if (!strcmp(s, "any")) {
1253 b = start_stop_tls_with_protocol(FALSE, term);
1254 if (b)
1255 b = start_stop_tls_with_protocol(TRUE, term);
1257 else if (!strcmp(s, "ipv4"))
1258 b = start_stop_tls_with_protocol(FALSE, term);
1259 else if (!strcmp(s, "ipv6"))
1260 b = start_stop_tls_with_protocol(TRUE, term);
1261 else
1262 b = FALSE;
1264 g_free(s);
1265 return b;
1267 #endif
1269 static void *accept_thread(void *arg)
1271 gint sockfd = *(gint *)arg;
1273 #ifdef HAVE_PR_SET_NAME
1274 prctl(PR_SET_NAME, "accept");
1275 #endif
1276 pthread_setspecific(thread_name_key, g_strdup(__FUNCTION__));
1278 for (;;) {
1279 socklen_t slen = sizeof(struct sockaddr_un);
1280 struct sockaddr_un raddr;
1281 gint fd;
1283 fd = accept(sockfd, (struct sockaddr *)&raddr, &slen);
1284 if (fd == -1) {
1285 if (errno != EAGAIN) {
1286 if (!quit) // probably EBADF
1287 log_write("accept(): %s", pwmd_strerror(gpg_error_from_syserror()));
1289 break;
1291 continue;
1294 (void)init_client_thread(fd, NULL);
1297 /* Just in case accept() failed for some reason other than EBADF */
1298 quit = TRUE;
1299 return NULL;
1302 static void *cache_timer_thread(void *arg)
1304 #ifdef HAVE_PR_SET_NAME
1305 prctl(PR_SET_NAME, "cache timer");
1306 #endif
1307 pthread_setspecific(thread_name_key, g_strdup(__FUNCTION__));
1309 for (;;) {
1310 sleep(1);
1311 cache_adjust_timeout();
1314 return NULL;
1317 static void catch_sigabrt(int sig)
1319 cache_clear(NULL);
1320 #ifndef MEM_DEBUG
1321 xpanic();
1322 #endif
1325 static gboolean signal_loop(sigset_t sigset)
1327 gboolean done = FALSE;
1328 gboolean sigint = FALSE;
1330 do {
1331 gint sig = sigwaitinfo(&sigset, NULL);
1333 if (sig == -1) {
1334 if (errno != EAGAIN)
1335 log_write("sigwaitinfo(): %s", strerror(errno));
1336 continue;
1339 if (sig != SIGUSR2)
1340 log_write(_("caught signal %i (%s)"), sig, strsignal(sig));
1342 switch (sig) {
1343 case SIGHUP:
1344 pthread_cond_signal(&rcfile_cond);
1345 break;
1346 case SIGABRT:
1347 // not really handled here.
1348 catch_sigabrt(SIGABRT);
1349 break;
1350 case SIGUSR1:
1351 log_write(_("clearing file cache"));
1352 cache_clear(NULL);
1353 send_status_all(STATUS_CACHE, NULL);
1354 break;
1355 case SIGUSR2:
1356 done = TRUE;
1357 break;
1358 default:
1359 sigint = TRUE;
1360 done = TRUE;
1361 break;
1363 } while (!done);
1365 return sigint;
1368 static void catchsig(int sig)
1370 log_write("Caught SIGSEGV. Exiting.");
1371 #ifdef HAVE_BACKTRACE
1372 BACKTRACE(__FUNCTION__);
1373 #endif
1374 longjmp(jmp, 1);
1377 static void *waiting_for_exit(void *arg)
1379 #ifdef HAVE_PR_SET_NAME
1380 prctl(PR_SET_NAME, "exiting");
1381 #endif
1382 pthread_setspecific(thread_name_key, g_strdup(__FUNCTION__));
1383 log_write(_("waiting for all clients to disconnect"));
1384 MUTEX_LOCK(&quit_mutex);
1385 pthread_cleanup_push(cleanup_mutex_cb, &quit_mutex);
1387 for (;;) {
1388 MUTEX_LOCK(&cn_mutex);
1389 gint n = g_slist_length(cn_thread_list);
1390 MUTEX_UNLOCK(&cn_mutex);
1391 if (!n)
1392 break;
1394 log_write(_("%i clients remain"), n);
1395 pthread_cond_wait(&quit_cond, &quit_mutex);
1398 pthread_cleanup_pop(1);
1399 kill(getpid(), SIGUSR2);
1400 return NULL;
1403 static gboolean server_loop(gint sockfd, gchar **socketpath)
1405 pthread_t accept_tid;
1406 pthread_t cache_timeout_tid;
1407 gint n, i;
1408 sigset_t sigset;
1409 gboolean segv = FALSE;
1410 gpg_error_t rc;
1412 init_commands();
1413 sigemptyset(&sigset);
1415 /* Termination */
1416 sigaddset(&sigset, SIGTERM);
1417 sigaddset(&sigset, SIGINT);
1419 /* Clears the file cache. */
1420 sigaddset(&sigset, SIGUSR1);
1422 /* Configuration file reloading. */
1423 sigaddset(&sigset, SIGHUP);
1425 /* For exiting cleanly. */
1426 sigaddset(&sigset, SIGUSR2);
1428 /* Clears the cache and exits when something bad happens. */
1429 signal(SIGABRT, catch_sigabrt);
1430 sigaddset(&sigset, SIGABRT);
1431 sigprocmask(SIG_BLOCK, &sigset, NULL);
1433 /* Ignored everywhere. When a client disconnects abnormally this signal
1434 * gets raised. It isn't needed though because client_thread() will check
1435 * for rcs even after the client disconnects. */
1436 signal(SIGPIPE, SIG_IGN);
1438 /* Can show a backtrace of the stack in the log. */
1439 signal(SIGSEGV, catchsig);
1441 #ifdef WITH_GNUTLS
1442 /* Needs to be done after the fork(). */
1443 if (!start_stop_tls(FALSE)) {
1444 segv = TRUE;
1445 goto done;
1447 #endif
1449 pthread_mutex_init(&quit_mutex, NULL);
1450 pthread_cond_init(&quit_cond, NULL);
1451 log_write(_("%s started for user %s"), PACKAGE_STRING, g_get_user_name());
1452 #ifndef HAVE_DECL_SO_PEERCRED
1453 log_write(_("Peer credential checking is NOT supported on this OS."));
1454 #endif
1455 #ifdef WITH_GNUTLS
1456 if (get_key_file_boolean("global", "enable_tcp"))
1457 log_write(_("Listening on %s and TCP port %i"), *socketpath,
1458 get_key_file_integer("global", "tcp_port"));
1459 else
1460 log_write(_("Listening on %s"), *socketpath);
1461 #else
1462 log_write(_("Listening on %s"), *socketpath);
1463 #endif
1465 rc = create_thread(reload_rcfile_thread, NULL, &rcfile_tid, TRUE);
1466 if (rc) {
1467 log_write("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1468 pwmd_strerror(rc));
1469 goto done;
1472 rc = create_thread(cache_timer_thread, NULL, &cache_timeout_tid, TRUE);
1473 if (rc) {
1474 log_write("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1475 pwmd_strerror(rc));
1476 goto done;
1479 rc = create_thread(accept_thread, &sockfd, &accept_tid, TRUE);
1480 if (rc) {
1481 log_write("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1482 pwmd_strerror(rc));
1483 goto done;
1486 sigdelset(&sigset, SIGUSR2);
1487 if (!setjmp(jmp))
1488 signal_loop(sigset);
1489 else
1490 segv = TRUE;
1492 done:
1494 * We're out of the main server loop. This happens when a signal was sent
1495 * to terminate the daemon. We'll wait for all clients to disconnect
1496 * before exiting but exit immediately if another termination signal is
1497 * sent.
1499 pthread_cancel(accept_tid);
1500 shutdown(sockfd, SHUT_RDWR);
1501 close(sockfd);
1502 unlink(*socketpath);
1503 g_free(*socketpath);
1504 *socketpath = NULL;
1505 MUTEX_LOCK(&cn_mutex);
1506 n = g_slist_length(cn_thread_list);
1507 MUTEX_UNLOCK(&cn_mutex);
1509 if (n && !segv) {
1510 pthread_t tid;
1512 rc = create_thread(waiting_for_exit, NULL, &tid, TRUE);
1513 if (!rc) {
1514 sigaddset(&sigset, SIGUSR2);
1515 if (signal_loop(sigset)) {
1516 log_write(_("Received second termination request. Exiting."));
1517 pthread_cancel(tid);
1520 else
1521 log_write("%s(%i): pthread_create(): %s", __FILE__, __LINE__,
1522 pwmd_strerror(rc));
1525 pthread_cancel(cache_timeout_tid);
1526 MUTEX_LOCK(&cn_mutex);
1527 i = 0;
1528 n = g_slist_length(cn_thread_list);
1530 for (i = 0; i < n; i++) {
1531 struct client_thread_s *thd = g_slist_nth_data(cn_thread_list, i);
1533 if (thd->fd != -1) {
1534 close(thd->fd);
1535 thd->fd = -1;
1539 exiting = TRUE;
1540 cache_deinit();
1541 MUTEX_UNLOCK(&cn_mutex);
1542 deinit_commands();
1543 pthread_cancel(rcfile_tid);
1544 pthread_cond_destroy(&rcfile_cond);
1545 pthread_mutex_destroy(&rcfile_mutex);
1546 pthread_cond_destroy(&quit_cond);
1547 pthread_mutex_destroy(&quit_mutex);
1548 return segv ? EXIT_FAILURE : EXIT_SUCCESS;;
1551 static void startup_failure()
1553 log_write(_("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
1554 cache_clear(NULL);
1557 /* This is called from cache.c:clear_once(). See
1558 * command.c:clearcache_command() for details about lock checking.
1560 static gpg_error_t free_cache_data(file_cache_t *cache)
1562 gpg_error_t rc = GPG_ERR_NO_DATA;
1563 gint i, t;
1564 struct client_thread_s *found = NULL;
1565 gboolean self = FALSE;
1567 if (!cache->data)
1568 return 0;
1570 cache_lock();
1571 MUTEX_LOCK(&cn_mutex);
1572 pthread_cleanup_push(cleanup_mutex_cb, &cn_mutex);
1573 t = g_slist_length(cn_thread_list);
1575 for (i = 0; i < t; i++) {
1576 struct client_thread_s *thd = g_slist_nth_data(cn_thread_list, i);
1578 if (!thd->cl)
1579 continue;
1581 if (!memcmp(thd->cl->md5file, cache->filename,
1582 sizeof(cache->filename))) {
1583 if (pthread_equal(pthread_self(), thd->tid)) {
1584 found = thd;
1585 self = TRUE;
1586 continue;
1589 /* Continue trying to find a client who has the same file open and
1590 * also has a lock. */
1591 rc = cache_lock_mutex(thd->cl->ctx, thd->cl->md5file, TRUE,
1592 FALSE, -1);
1593 if (!rc) {
1594 self = FALSE;
1595 found = thd;
1596 break;
1601 if (!rc && self)
1602 rc = cache_lock_mutex(found->cl->ctx, found->cl->md5file, TRUE,
1603 FALSE, -1);
1605 if (exiting || !rc || rc == GPG_ERR_NO_DATA) {
1606 free_cache_data_once(cache->data);
1607 cache->data = NULL;
1609 if (found)
1610 cache_unlock_mutex(found->cl->md5file, FALSE);
1612 rc = 0;
1615 pthread_cleanup_pop(1);
1616 cache_unlock();
1617 return rc;
1620 static gboolean convert_v2_datafile(const gchar *filename, const gchar *cipher,
1621 const gchar *keyfile, const gchar *keygrip, const gchar *sign_keygrip,
1622 gboolean nopass, const gchar *outfile, const gchar *keyparam,
1623 gulong s2k_count)
1625 gpg_error_t rc;
1626 gpointer data = NULL;
1627 gsize datalen;
1628 struct crypto_s *crypto = NULL;
1629 guint16 ver;
1630 gint algo;
1632 if (outfile[0] == '-' && outfile[1] == 0)
1633 outfile = NULL;
1635 log_write(_("Converting version 2 data file \"%s\" ..."), filename);
1636 if (access(filename, R_OK) == -1) {
1637 log_write("%s: %s", filename, pwmd_strerror(gpg_error_from_syserror()));
1638 return FALSE;
1641 if (keyfile) {
1642 log_write(_("Using passphrase file \"%s\" for decryption ..."),
1643 keyfile);
1644 if (access(keyfile, R_OK) == -1) {
1645 log_write("%s: %s", keyfile,
1646 pwmd_strerror(gpg_error_from_syserror()));
1647 return FALSE;
1651 rc = read_v2_datafile(filename, keyfile, &data, &datalen, &ver, &algo);
1652 if (rc) {
1653 log_write("%s", pwmd_strerror(rc));
1654 return FALSE;
1657 if (cipher) {
1658 algo = cipher_string_to_gcrypt(cipher);
1659 if (algo == -1) {
1660 rc = GPG_ERR_CIPHER_ALGO;
1661 goto fail;
1665 if (ver < 0x212) {
1666 xmlDocPtr doc = parse_doc(data, datalen);
1668 if (!doc) {
1669 rc = GPG_ERR_BAD_DATA;
1670 goto fail;
1673 rc = convert_pre_212_elements(doc);
1674 gcry_free(data);
1675 data = NULL;
1676 if (!rc) {
1677 xmlDocDumpFormatMemory(doc, (xmlChar **)&data, (gint *)&datalen, 0);
1678 if (!data)
1679 rc = GPG_ERR_ENOMEM;
1682 xmlFreeDoc(doc);
1683 if (rc)
1684 goto fail;
1687 rc = init_client_crypto(&crypto);
1688 if (!rc) {
1689 rc = set_pinentry_options(crypto->agent);
1690 if (!rc) {
1691 memcpy(&crypto->save.hdr, &crypto->hdr,
1692 sizeof(file_header_t));
1693 crypto->save.hdr.flags = set_cipher_flag(crypto->save.hdr.flags, algo);
1694 crypto->save.s2k_count = (gulong)s2k_count;
1695 rc = export_common(crypto, keygrip, sign_keygrip, nopass, data,
1696 datalen, outfile, keyparam,
1697 no_passphrase_file ? NULL : keyfile);
1698 if (!rc)
1699 log_write(_("Output written to \"%s\"."), outfile);
1703 fail:
1704 if (ver < 0x212)
1705 xmlFree(data);
1706 else
1707 gcry_free(data);
1708 cleanup_crypto(&crypto);
1710 if (rc)
1711 log_write("%s", pwmd_strerror(rc));
1712 return rc ? FALSE : TRUE;
1715 int main(int argc, char *argv[])
1717 gint opt;
1718 struct sockaddr_un addr;
1719 gchar buf[PATH_MAX];
1720 gchar *socketpath = NULL, *socketdir, *socketname = NULL;
1721 gchar *socketarg = NULL;
1722 gchar *datadir = NULL;
1723 gboolean n;
1724 gint x;
1725 gchar *p;
1726 gchar **cache_push = NULL;
1727 gchar *import = NULL, *keygrip = NULL, *sign_keygrip = NULL;
1728 gchar *keyparam = NULL;
1729 gboolean rcfile_spec = FALSE;
1730 gint estatus = EXIT_FAILURE;
1731 gint sockfd;
1732 gchar *outfile = NULL;
1733 GMemVTable mtable = { xmalloc, xrealloc, xfree, xcalloc, NULL, NULL };
1734 gint do_unlink = 0;
1735 gboolean secure = FALSE;
1736 gint show_version = 0;
1737 gboolean force = FALSE;
1738 gboolean no_passphrase = FALSE;
1739 gpg_error_t rc;
1740 gchar *convertfile = NULL;
1741 gchar *cipher = NULL;
1742 gchar *keyfile = NULL;
1743 glong s2k_count = -1;
1744 GError *error = NULL;
1745 gchar *debug_level_opt = NULL;
1746 GOptionContext *context;
1747 GOptionEntry options[] =
1749 { "version", 0, 0, G_OPTION_ARG_NONE, &show_version,
1750 "version information", NULL },
1751 { "no-fork", 'n', 0, G_OPTION_ARG_NONE, &nofork,
1752 "run as a foreground process", NULL },
1753 { "disable-dump", 'D', 0, G_OPTION_ARG_NONE, &secure,
1754 "disable the LIST, XPATH and DUMP commands", NULL },
1755 { "rcfile", 'f', 0, G_OPTION_ARG_FILENAME, &rcfile,
1756 "load the specified rcfile (~/.pwmd/config)", "filename" },
1757 { "ignore", 0, 0, G_OPTION_ARG_NONE, &force,
1758 "ignore cache failures on startup", NULL },
1759 { "outfile", 'o', 0, G_OPTION_ARG_FILENAME, &outfile,
1760 "output file when importing (- for stdout)", "filename" },
1761 { "convert", 'C', 0, G_OPTION_ARG_FILENAME, &convertfile,
1762 "convert a version 2 data file to version 3", "filename" },
1763 { "passphrase-file", 'k', 0, G_OPTION_ARG_FILENAME, &keyfile,
1764 "for decryption when converting", "filename" },
1765 { "no-passphrase-file", 0, 0, G_OPTION_ARG_NONE, &no_passphrase_file,
1766 "no --passphrase-file after conversion", NULL },
1767 { "import", 'I', 0, G_OPTION_ARG_FILENAME, &import,
1768 "import an XML file", "filename" },
1769 { "keygrip", 0, 0, G_OPTION_ARG_STRING, &keygrip,
1770 "the public keygrip to use for encryption", "hexstring"},
1771 { "sign-keygrip", 0, 0, G_OPTION_ARG_STRING, &sign_keygrip,
1772 "the keygrip to use for signing of the data", "hexstring"},
1773 { "keyparam", 0, 0, G_OPTION_ARG_STRING, &keyparam,
1774 "alternate key parameters to use (RSA-2048)", "s-exp"},
1775 { "no-passphrase", 0, 0, G_OPTION_ARG_NONE, &no_passphrase,
1776 "for the imported/converted keypair", NULL },
1777 { "cipher", 0, 0, G_OPTION_ARG_STRING, &cipher,
1778 "encryption cipher, see man page (AES-256)", "string" },
1779 { "s2k-count", 0, 0, G_OPTION_ARG_INT64, &s2k_count,
1780 "hash iteration count >65536 (calibrated)", "iterations" },
1781 { "debug-level", 0, 0, G_OPTION_ARG_STRING, &debug_level_opt,
1782 "protocol output, see man page", "keywords"},
1783 { NULL }
1786 #ifndef DEBUG
1787 #ifdef HAVE_SETRLIMIT
1788 struct rlimit rl;
1790 rl.rlim_cur = rl.rlim_max = 0;
1792 if (setrlimit(RLIMIT_CORE, &rl) != 0)
1793 err(EXIT_FAILURE, "setrlimit()");
1794 #endif
1795 #endif
1797 #ifdef ENABLE_NLS
1798 setlocale(LC_ALL, "");
1799 bindtextdomain("pwmd", LOCALEDIR);
1800 textdomain("pwmd");
1801 #endif
1803 #ifndef MEM_DEBUG
1804 xmem_init();
1805 #endif
1806 g_mem_set_vtable(&mtable);
1807 g_thread_init(NULL);
1808 gpg_err_init();
1809 setup_crypto();
1810 #ifdef WITH_GNUTLS
1811 gnutls_global_set_mem_functions(g_malloc, g_malloc, secure_mem_check,
1812 g_realloc, g_free);
1813 gnutls_global_init();
1814 gnutls_global_set_log_function(tls_log);
1815 gnutls_global_set_log_level(1);
1816 tls_fd = -1;
1817 tls6_fd = -1;
1818 #endif
1819 xmlMemSetup(g_free, g_malloc, g_realloc, g_strdup);
1820 xmlInitMemory();
1821 xmlInitGlobals();
1822 xmlInitParser();
1823 xmlXPathInit();
1824 g_snprintf(buf, sizeof(buf), "%s/.pwmd", g_get_home_dir());
1825 if (mkdir(buf, 0700) == -1 && errno != EEXIST)
1826 err(EXIT_FAILURE, "%s", buf);
1828 g_snprintf(buf, sizeof(buf), "%s/.pwmd/data", g_get_home_dir());
1829 if (mkdir(buf, 0700) == -1 && errno != EEXIST)
1830 err(EXIT_FAILURE, "%s", buf);
1832 cmdline = TRUE;
1833 context = g_option_context_new("- Password Manager Daemon");
1834 g_option_context_add_main_entries(context, options, NULL);
1835 if (!g_option_context_parse(context, &argc, &argv, &error))
1837 g_print("Option parsing failed: %s\n", error->message);
1838 exit(EXIT_FAILURE);
1841 if (show_version) {
1842 printf(_("%s\n\n"
1843 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012\n"
1844 "%s\n"
1845 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
1846 "Compile time features:\n%s"), PACKAGE_STRING, PACKAGE_BUGREPORT,
1847 #ifdef WITH_GNUTLS
1848 "+WITH_GNUTLS\n"
1849 #else
1850 "-WITH_GNUTLS\n"
1851 #endif
1852 #ifdef WITH_LIBACL
1853 "+WITH_LIBACL\n"
1854 #else
1855 "-WITH_LIBACL\n"
1856 #endif
1857 #ifdef DEBUG
1858 "+DEBUG\n"
1859 #else
1860 "-DEBUG\n"
1861 #endif
1862 #ifdef MEM_DEBUG
1863 "+MEM_DEBUG\n"
1864 #else
1865 "-MEM_DEBUG\n"
1866 #endif
1867 #ifdef MUTEX_DEBUG
1868 "+MUTEX_DEBUG\n"
1869 #else
1870 "-MUTEX_DEBUG\n"
1871 #endif
1873 exit(EXIT_SUCCESS);
1876 pthread_mutexattr_t attr;
1877 pthread_mutexattr_init(&attr);
1878 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1879 pthread_mutex_init(&rcfile_mutex, &attr);
1880 pthread_mutex_init(&cn_mutex, &attr);
1881 pthread_mutexattr_destroy(&attr);
1882 pthread_key_create(&last_error_key, free_key);
1884 if (!rcfile)
1885 rcfile = g_strdup_printf("%s/.pwmd/config", g_get_home_dir());
1886 else
1887 rcfile_spec = TRUE;
1889 if ((keyfileh = parse_rcfile(rcfile_spec, cmdline)) == NULL)
1890 exit(EXIT_FAILURE);
1892 if (debug_level_opt)
1893 debug_level = g_strsplit(debug_level_opt, ",", 0);
1895 if (g_key_file_has_key(keyfileh, "global", "syslog", NULL) == TRUE)
1896 log_syslog = g_key_file_get_boolean(keyfileh, "global", "syslog", NULL);
1898 if (log_syslog == TRUE)
1899 openlog("pwmd", LOG_NDELAY|LOG_PID, LOG_DAEMON);
1901 if (g_key_file_has_key(keyfileh, "global", "priority", NULL)) {
1902 x = g_key_file_get_integer(keyfileh, "global", "priority", NULL);
1903 errno = 0;
1905 if (setpriority(PRIO_PROCESS, 0, x) == -1) {
1906 log_write("setpriority(): %s", pwmd_strerror(gpg_error_from_syserror()));
1907 goto do_exit;
1911 #ifdef HAVE_MLOCKALL
1912 if (disable_mlock == FALSE && mlockall(MCL_CURRENT|MCL_FUTURE) == -1) {
1913 log_write("mlockall(): %s", pwmd_strerror(gpg_error_from_syserror()));
1914 goto do_exit;
1916 #endif
1918 rc = cache_init(free_cache_data);
1919 if (rc) {
1920 log_write("pwmd: gpg-agent: %s",
1921 gpg_err_code(rc) == GPG_ERR_UNKNOWN_VERSION
1922 ? _("incompatible version: 2.1.0 or later required")
1923 : pwmd_strerror(rc));
1924 goto do_exit;
1927 if (s2k_count == -1)
1928 s2k_count = get_key_file_ulong(NULL, "s2k_count");
1930 if (convertfile) {
1931 if (!outfile) {
1932 gchar *tmp = g_option_context_get_help(context, TRUE, NULL);
1933 fprintf(stderr, "%s", tmp);
1934 g_free(tmp);
1935 exit(EXIT_FAILURE);
1938 estatus = convert_v2_datafile(convertfile, cipher, keyfile, keygrip,
1939 sign_keygrip, no_passphrase, outfile, keyparam,
1940 (gulong)s2k_count);
1941 g_key_file_free(keyfileh);
1942 g_free(rcfile);
1943 exit(!estatus);
1946 if (import) {
1947 if (!outfile) {
1948 gchar *tmp = g_option_context_get_help(context, TRUE, NULL);
1949 fprintf(stderr, "%s", tmp);
1950 g_free(tmp);
1951 exit(EXIT_FAILURE);
1954 if (outfile[0] == '-' && outfile[1] == 0)
1955 outfile = NULL;
1957 estatus = xml_import(import, outfile, keygrip, sign_keygrip, keyfile,
1958 no_passphrase, cipher, keyparam, (gulong)s2k_count);
1959 g_key_file_free(keyfileh);
1960 g_free(rcfile);
1961 exit(!estatus);
1964 g_option_context_free(context);
1965 if ((p = g_key_file_get_string(keyfileh, "global", "socket_path", NULL)) == NULL)
1966 errx(EXIT_FAILURE, _("%s: socket_path not defined"), rcfile);
1968 socketarg = expand_homedir(p);
1969 g_free(p);
1971 if ((p = g_key_file_get_string(keyfileh, "global", "data_directory", NULL)) == NULL)
1972 errx(EXIT_FAILURE, _("%s: data_directory not defined"), rcfile);
1974 datadir = expand_homedir(p);
1975 g_free(p);
1977 if (secure == FALSE && g_key_file_has_key(keyfileh, "global", "disable_list_and_dump", NULL) == TRUE) {
1978 n = g_key_file_get_boolean(keyfileh, "global", "disable_list_and_dump", NULL);
1979 disable_list_and_dump = n;
1981 else
1982 disable_list_and_dump = secure;
1984 setup_logging(keyfileh);
1986 if (g_key_file_has_key(keyfileh, "global", "cache_push", NULL) == TRUE)
1987 cache_push = g_key_file_get_string_list(keyfileh, "global", "cache_push", NULL, NULL);
1989 for (gint n = 1; n < argc; n++) {
1990 if (strv_printf(&cache_push, "%s", argv[n]) == FALSE)
1991 errx(EXIT_FAILURE, "%s", pwmd_strerror(GPG_ERR_ENOMEM));
1994 if (strchr(socketarg, '/') == NULL) {
1995 socketdir = g_get_current_dir();
1996 socketname = g_strdup(socketarg);
1997 socketpath = g_strdup_printf("%s/%s", socketdir, socketname);
1999 else {
2000 socketname = g_strdup(strrchr(socketarg, '/'));
2001 socketname++;
2002 socketarg[strlen(socketarg) - strlen(socketname) -1] = 0;
2003 socketdir = g_strdup(socketarg);
2004 socketpath = g_strdup_printf("%s/%s", socketdir, socketname);
2007 if (chdir(datadir)) {
2008 log_write("%s: %s", datadir, pwmd_strerror(gpg_error_from_syserror()));
2009 unlink(socketpath);
2010 goto do_exit;
2014 * Set the cache entry for a file. Prompts for the password.
2016 if (cache_push) {
2017 struct crypto_s *crypto;
2018 gpg_error_t rc = init_client_crypto(&crypto);
2020 if (rc) {
2021 estatus = EXIT_FAILURE;
2022 goto do_exit;
2025 rc = set_pinentry_options(crypto->agent);
2026 if (rc) {
2027 estatus = EXIT_FAILURE;
2028 goto do_exit;
2031 for (opt = 0; cache_push[opt]; opt++) {
2032 if (!do_cache_push(cache_push[opt], crypto) && !force) {
2033 g_strfreev(cache_push);
2034 startup_failure();
2035 estatus = EXIT_FAILURE;
2036 cleanup_crypto(&crypto);
2037 goto do_exit;
2040 cleanup_crypto_stage1(crypto);
2043 (void)kill_scd(crypto->agent);
2044 cleanup_crypto(&crypto);
2045 g_strfreev(cache_push);
2046 log_write(!nofork ? _("Done. Daemonizing...") : _("Done. Waiting for connections..."));
2049 clear_rcfile_keys();
2052 * bind() doesn't like the full pathname of the socket or any non alphanum
2053 * characters so change to the directory where the socket is wanted then
2054 * create it then change to datadir.
2056 if (chdir(socketdir)) {
2057 log_write("%s: %s", socketdir, pwmd_strerror(gpg_error_from_syserror()));
2058 goto do_exit;
2061 g_free(socketdir);
2063 if ((sockfd = socket(PF_UNIX, SOCK_STREAM, 0)) == -1) {
2064 log_write("socket(): %s", pwmd_strerror(gpg_error_from_syserror()));
2065 goto do_exit;
2068 addr.sun_family = AF_UNIX;
2069 g_snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", socketname);
2071 if (bind(sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr)) == -1) {
2072 log_write("bind(): %s", pwmd_strerror(gpg_error_from_syserror()));
2074 if (errno == EADDRINUSE)
2075 log_write(_("Either there is another pwmd running or '%s' is a \n"
2076 "stale socket. Please remove it manually."), socketpath);
2078 goto do_exit;
2081 do_unlink = 1;
2082 if (g_key_file_has_key(keyfileh, "global", "socket_perms", NULL) == TRUE) {
2083 gchar *t = g_key_file_get_string(keyfileh, "global", "socket_perms", NULL);
2084 mode_t mode = strtol(t, NULL, 8);
2085 mode_t mask = umask(0);
2087 g_free(t);
2089 if (chmod(socketname, mode) == -1) {
2090 log_write("%s: %s", socketname, pwmd_strerror(gpg_error_from_syserror()));
2091 close(sockfd);
2092 unlink(socketpath);
2093 umask(mask);
2094 goto do_exit;
2097 umask(mask);
2100 g_free(--socketname);
2102 if (chdir(datadir)) {
2103 log_write("%s: %s", datadir, pwmd_strerror(gpg_error_from_syserror()));
2104 close(sockfd);
2105 unlink(socketpath);
2106 goto do_exit;
2109 g_free(datadir);
2111 if (listen(sockfd, 0) == -1) {
2112 log_write("listen(): %s", pwmd_strerror(gpg_error_from_syserror()));
2113 goto do_exit;
2116 cmdline = FALSE;
2118 if (!nofork) {
2119 switch (fork()) {
2120 case -1:
2121 log_write("fork(): %s", pwmd_strerror(gpg_error_from_syserror()));
2122 goto do_exit;
2123 case 0:
2124 close(0);
2125 close(1);
2126 close(2);
2127 setsid();
2128 break;
2129 default:
2130 _exit(EXIT_SUCCESS);
2134 pthread_key_create(&thread_name_key, free_key);
2135 pthread_setspecific(thread_name_key, g_strdup("main"));
2136 pthread_cond_init(&rcfile_cond, NULL);
2137 estatus = server_loop(sockfd, &socketpath);
2139 do_exit:
2140 if (socketpath && do_unlink) {
2141 unlink(socketpath);
2142 g_free(socketpath);
2145 g_free(socketarg);
2146 #ifdef WITH_GNUTLS
2147 start_stop_tls(TRUE);
2148 gnutls_global_deinit();
2149 #endif
2150 if (keyfileh)
2151 g_key_file_free(keyfileh);
2152 g_free(rcfile);
2153 xmlCleanupParser();
2154 xmlCleanupGlobals();
2156 if (estatus == EXIT_SUCCESS)
2157 log_write(_("pwmd exiting normally"));
2159 #if defined(DEBUG) && !defined(MEM_DEBUG)
2160 xdump();
2161 #endif
2162 exit(estatus);