Added warn_unused_result attribute to pwmd_command_ap().
[libpwmd.git] / libpwmd.c
blob48df5441407d96e02469be447c08a8b83e64fe1c
1 /* vim:tw=78:ts=8:sw=4:set ft=c: */
2 /*
3 Copyright (C) 2006-2008 Ben Kibbey <bjk@luxsci.net>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02110-1301 USA
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <unistd.h>
22 #include <err.h>
23 #include <errno.h>
24 #include <ctype.h>
25 #include <string.h>
26 #include <sys/socket.h>
27 #include <sys/un.h>
28 #include <signal.h>
29 #include <stdarg.h>
30 #include <string.h>
31 #include <sys/wait.h>
32 #include <fcntl.h>
33 #include <pwd.h>
34 #include <time.h>
35 #include <sys/types.h>
36 #include <limits.h>
37 #include <sys/select.h>
38 #include <netdb.h>
39 #include <netinet/in.h>
40 #include <sys/socket.h>
41 #include <libpwmd.h>
43 #ifdef HAVE_CONFIG_H
44 #include <config.h>
45 #endif
47 #ifdef WITH_LIBPTH
48 #include <pth.h>
49 #endif
51 #ifdef WITH_TCP
52 #define DNS_USE_GETTIMEOFDAY_FOR_ID 1
53 #include <ares.h>
54 #include <arpa/nameser.h>
55 #ifdef WITH_LIBPTH
56 #include <gcrypt.h>
57 GCRY_THREAD_OPTION_PTH_IMPL;
58 #endif
59 #endif
61 #ifdef HAVE_ASSUAN_H
62 #include <assuan.h>
63 #endif
65 #ifdef HAVE_SETLOCALE
66 #include <locale.h>
67 #endif
69 #include "gettext.h"
70 #define N_(msgid) dgettext("libpwmd", msgid)
72 #ifndef MEM_DEBUG
73 #include "mem.h"
74 #else
75 #define xfree free
76 #define xrealloc realloc
77 #define xmalloc malloc
78 #define xstrdup strdup
79 #define xcalloc calloc
80 #endif
82 #include "types.h"
84 #ifdef WITH_PINENTRY
85 static pwm_t *gpwm;
86 static int gelapsed, gtimeout;
87 static gpg_error_t pinentry_command(pwm_t *pwm, char **result, const char *cmd);
88 static gpg_error_t global_error;
89 #endif
91 const char *pwmd_strerror(gpg_error_t e)
93 gpg_err_code_t code = gpg_err_code(e);
95 if (code >= GPG_ERR_USER_1 && code < gpg_err_code(EPWMD_MAX)) {
96 switch (code) {
97 case GPG_ERR_USER_1:
98 default:
99 return N_("Unknown error");
100 case GPG_ERR_USER_2:
101 return N_("No cache slots available");
102 case GPG_ERR_USER_3:
103 return N_("Recursion loop");
104 case GPG_ERR_USER_4:
105 return N_("No file is open");
106 case GPG_ERR_USER_5:
107 return N_("General LibXML error");
108 case GPG_ERR_USER_6:
109 return N_("File modified");
110 case GPG_ERR_USER_7:
111 return N_("Access denied");
115 return gpg_strerror(e);
118 gpg_error_t pwmd_init()
120 static int initialized;
122 if (initialized)
123 return 0;
125 #ifdef WITH_LIBPTH
126 gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pth);
127 #endif
128 xmem_init();
129 #ifdef ENABLE_NLS
130 bindtextdomain("libpwmd", LOCALEDIR);
131 #endif
132 gpg_err_init();
133 assuan_set_malloc_hooks(xmalloc, xrealloc, xfree);
134 assuan_set_assuan_err_source(GPG_ERR_SOURCE_DEFAULT);
135 initialized = 1;
136 return 0;
139 static pwm_t *_socket_connect_finalize(pwm_t *pwm, assuan_context_t ctx)
141 int active[2];
142 int n = assuan_get_active_fds(ctx, 0, active, sizeof(active));
144 pwm->fd = n <= 0 ? -1 : dup(active[0]);
145 pwm->ctx = ctx;
146 #ifdef WITH_PINENTRY
147 pwm->pid = -1;
148 pwm->pinentry_tries = 3;
149 #endif
150 assuan_set_pointer(ctx, pwm);
151 return pwm;
154 #ifdef WITH_TCP
155 static int read_hook(assuan_context_t ctx, assuan_fd_t fd, void *data,
156 size_t len, ssize_t *ret)
158 pwm_t *pwm = assuan_get_pointer(ctx);
160 if (!pwm || !pwm->tcp_conn)
161 *ret = read((int)fd, data, len);
162 else {
163 do {
164 *ret = libssh2_channel_read(pwm->tcp_conn->channel, data, len);
165 } while (*ret == LIBSSH2_ERROR_EAGAIN);
168 return *ret <= 0 ? 0 : 1;
171 static int write_hook(assuan_context_t ctx, assuan_fd_t fd, const void *data,
172 size_t len, ssize_t *ret)
174 pwm_t *pwm = assuan_get_pointer(ctx);
176 if (!pwm || !pwm->tcp_conn)
177 *ret = write((int)fd, data, len);
178 else {
179 do {
180 *ret = libssh2_channel_write(pwm->tcp_conn->channel, data, len);
181 } while (*ret == LIBSSH2_ERROR_EAGAIN);
184 return *ret <= 0 ? 0 : 1;
187 static void _ssh_deinit(pwmd_tcp_conn_t *conn);
188 static void free_tcp_conn(pwmd_tcp_conn_t *conn)
190 if (!conn)
191 return;
193 if (conn->username) {
194 xfree(conn->username);
195 conn->username = NULL;
198 if (conn->known_hosts) {
199 xfree(conn->known_hosts);
200 conn->known_hosts = NULL;
203 if (conn->identity) {
204 xfree(conn->identity);
205 conn->identity = NULL;
208 if (conn->identity_pub) {
209 xfree(conn->identity_pub);
210 conn->identity_pub = NULL;
213 if (conn->host) {
214 xfree(conn->host);
215 conn->host = NULL;
218 if (conn->hostkey) {
219 xfree(conn->hostkey);
220 conn->hostkey = NULL;
223 if (conn->chan) {
224 ares_destroy(conn->chan);
225 conn->chan = NULL;
228 if (conn->he) {
229 ares_free_hostent(conn->he);
230 conn->he = NULL;
233 if (conn->fd >= 0) {
234 close(conn->fd);
235 conn->fd = -1;
238 if (conn->session)
239 _ssh_deinit(conn);
240 else
241 xfree(conn);
244 static void _ssh_deinit(pwmd_tcp_conn_t *conn)
246 if (!conn)
247 return;
249 if (conn->channel)
250 libssh2_channel_free(conn->channel);
252 if (conn->session) {
253 libssh2_session_disconnect(conn->session, "Bye!");
254 libssh2_session_free(conn->session);
257 conn->session = NULL;
258 conn->channel = NULL;
259 free_tcp_conn(conn);
262 static void _ssh_assuan_deinit(assuan_context_t ctx)
264 pwm_t *pwm = assuan_get_pointer(ctx);
266 _ssh_deinit(pwm->tcp_conn);
270 * Sets common options from both pwmd_tcp_connect() and
271 * pwmd_tcp_connect_async().
273 static gpg_error_t init_tcp_conn(pwmd_tcp_conn_t **dst, const char *host,
274 int port, const char *identity, const char *user, const char *hosts,
275 int get)
277 pwmd_tcp_conn_t *conn;
278 gpg_error_t rc = 0;
280 if (get) {
281 if (!host)
282 return GPG_ERR_INV_ARG;
284 else {
285 if (!host || !identity || !user || !hosts)
286 return GPG_ERR_INV_ARG;
289 conn = xcalloc(1, sizeof(pwmd_tcp_conn_t));
291 if (!conn)
292 return gpg_error_from_errno(ENOMEM);
294 conn->port = port == -1 ? 22 : port;
295 conn->host = xstrdup(host);
297 if (!conn->host) {
298 rc = gpg_error_from_errno(ENOMEM);
299 goto fail;
302 if (!get) {
303 conn->identity = xstrdup(identity);
305 if (!conn->identity) {
306 rc = gpg_error_from_errno(ENOMEM);
307 goto fail;
310 conn->identity_pub = xmalloc(strlen(conn->identity)+5);
312 if (!conn->identity_pub) {
313 rc = gpg_error_from_errno(ENOMEM);
314 goto fail;
317 sprintf(conn->identity_pub, "%s.pub", conn->identity);
318 conn->username = xstrdup(user);
320 if (!conn->username) {
321 rc = gpg_error_from_errno(ENOMEM);
322 goto fail;
325 conn->known_hosts = xstrdup(hosts);
327 if (!conn->known_hosts) {
328 rc = gpg_error_from_errno(ENOMEM);
329 goto fail;
333 *dst = conn;
334 return 0;
336 fail:
337 free_tcp_conn(conn);
338 return rc;
341 static gpg_error_t do_connect(pwm_t *pwm, int prot, void *addr)
343 struct sockaddr_in their_addr;
345 pwm->tcp_conn->fd = socket(prot, SOCK_STREAM, 0);
347 if (pwm->tcp_conn->fd == -1)
348 return gpg_error_from_syserror();
350 if (pwm->tcp_conn->async)
351 fcntl(pwm->tcp_conn->fd, F_SETFL, O_NONBLOCK);
353 pwm->cmd = ASYNC_CMD_CONNECT;
354 their_addr.sin_family = prot;
355 their_addr.sin_port = htons(pwm->tcp_conn->port);
356 their_addr.sin_addr = *((struct in_addr *)addr);
357 memset(their_addr.sin_zero, '\0', sizeof their_addr.sin_zero);
359 #ifdef WITH_LIBPTH
360 if (pth_connect(pwm->tcp_conn->fd, (struct sockaddr *)&their_addr,
361 sizeof(their_addr)) == -1)
362 #else
363 if (connect(pwm->tcp_conn->fd, (struct sockaddr *)&their_addr,
364 sizeof(their_addr)) == -1)
365 #endif
366 return gpg_error_from_syserror();
368 return 0;
371 static gpg_error_t ares_error_to_pwmd(int status)
373 if (status != ARES_SUCCESS)
374 warnx("%s", ares_strerror(status));
376 switch (status) {
377 case ARES_ENODATA:
378 case ARES_EFORMERR:
379 case ARES_ENOTFOUND:
380 return GPG_ERR_UNKNOWN_HOST;
381 case ARES_ESERVFAIL:
382 return GPG_ERR_EHOSTDOWN;
383 case ARES_ETIMEOUT:
384 return GPG_ERR_TIMEOUT;
385 case ARES_ENOMEM:
386 return gpg_error_from_errno(ENOMEM);
387 case ARES_ECONNREFUSED:
388 return GPG_ERR_ECONNREFUSED;
389 default:
390 /* FIXME ??? */
391 return GPG_ERR_EHOSTUNREACH;
394 return ARES_SUCCESS;
397 static void dns_resolve_cb(void *arg, int status, int timeouts,
398 unsigned char *abuf, int alen)
400 pwm_t *pwm = arg;
401 int rc;
402 struct hostent *he;
404 if (status == ARES_EDESTRUCTION)
405 return;
407 if (status != ARES_SUCCESS) {
408 pwm->tcp_conn->rc = ares_error_to_pwmd(status);
409 return;
412 //FIXME localhost. works with ipv4. maybe local system config error
413 /* Check for an IPv6 address first. */
414 rc = ares_parse_a_reply(abuf, alen, &he, NULL, NULL);
416 if (rc != ARES_SUCCESS) {
417 if (rc != ARES_ENODATA) {
418 pwm->tcp_conn->rc = ares_error_to_pwmd(status);
419 return;
422 rc = ares_parse_aaaa_reply(abuf, alen, &he, NULL, NULL);
424 if (rc != ARES_SUCCESS) {
425 pwm->tcp_conn->rc = ares_error_to_pwmd(status);
426 return;
430 pwm->tcp_conn->he = he;
431 pwm->tcp_conn->rc = do_connect(pwm, he->h_addrtype, he->h_addr);
434 pwm_t *_do_pwmd_tcp_connect_async(const char *host, int port,
435 const char *identity, const char *user, const char *known_hosts,
436 gpg_error_t *rc, pwmd_async_cmd_t which)
438 pwmd_tcp_conn_t *conn;
439 pwm_t *pwm;
441 *rc = init_tcp_conn(&conn, host, port, identity, user, known_hosts,
442 which == ASYNC_CMD_HOSTKEY ? 1 : 0);
444 if (*rc)
445 return NULL;
447 if ((pwm = (pwm_t *)xcalloc(1, sizeof(pwm_t))) == NULL) {
448 *rc = gpg_error_from_syserror();
449 free_tcp_conn(conn);
450 return NULL;
453 conn->async = 1;
454 pwm->tcp_conn = conn;
455 pwm->tcp_conn->cmd = which;
457 if (pwm->tcp_conn->cmd == ASYNC_CMD_HOSTKEY)
458 pwm->tcp_conn->get_only = 1;
460 pwm->cmd = ASYNC_CMD_DNS;
461 pwm->state = ASYNC_PROCESS;
462 ares_init(&pwm->tcp_conn->chan);
463 ares_query(pwm->tcp_conn->chan, pwm->tcp_conn->host, ns_c_any, ns_t_any,
464 dns_resolve_cb, pwm);
465 return pwm;
468 pwm_t *pwmd_tcp_connect_async(const char *host, int port, const char *identity,
469 const char *user, const char *known_hosts, gpg_error_t *rc)
471 return _do_pwmd_tcp_connect_async(host, port, identity, user, known_hosts,
472 rc, ASYNC_CMD_CONNECT);
475 void *_ssh_malloc(size_t size, void **data)
477 return xmalloc(size);
480 void _ssh_free(void *ptr, void **data)
482 xfree(ptr);
485 void *_ssh_realloc(void *ptr, size_t size, void **data)
487 return xrealloc(ptr, size);
490 static char *to_hex(const char *str, size_t slen)
492 int i;
493 char *buf = xmalloc(slen*2+1);
495 if (!buf)
496 return NULL;
498 for (i = 0, buf[0] = 0; i < slen; i++) {
499 char tmp[3];
501 sprintf(tmp, "%02x", (unsigned char)str[i]);
502 strcat(buf, tmp);
505 return buf;
508 static int verify_host_key(pwm_t *pwm)
510 FILE *fp = fopen(pwm->tcp_conn->known_hosts, "r");
511 char *buf, *p;
513 if (!fp)
514 return 1;
516 buf = xmalloc(LINE_MAX);
518 if (!buf)
519 goto fail;
521 while ((p = fgets(buf, LINE_MAX, fp))) {
522 if (*p == '#' || isspace(*p))
523 continue;
525 if (p[strlen(p)-1] == '\n')
526 p[strlen(p)-1] = 0;
528 if (!strcmp(buf, pwm->tcp_conn->hostkey))
529 goto done;
532 fail:
533 if (buf)
534 xfree(buf);
536 fclose(fp);
537 return 1;
539 done:
540 xfree(buf);
541 fclose(fp);
542 return 0;
545 static gpg_error_t authenticate_ssh(pwm_t *pwm)
547 const char *fp = libssh2_hostkey_hash(pwm->tcp_conn->session,
548 LIBSSH2_HOSTKEY_HASH_SHA1);
549 char *userauth;
551 pwm->tcp_conn->hostkey = to_hex(fp, 20);
553 if (!pwm->tcp_conn->hostkey)
554 return gpg_error_from_errno(ENOMEM);
556 if (pwm->tcp_conn->get_only)
557 return 0;
559 if (!fp || verify_host_key(pwm))
560 return GPG_ERR_CHECKSUM;
562 userauth = libssh2_userauth_list(pwm->tcp_conn->session,
563 pwm->tcp_conn->username, strlen(pwm->tcp_conn->username));
565 if (!userauth || !strstr(userauth, "publickey"))
566 return GPG_ERR_BAD_PIN_METHOD;
568 if (libssh2_userauth_publickey_fromfile(pwm->tcp_conn->session,
569 pwm->tcp_conn->username, pwm->tcp_conn->identity_pub,
570 pwm->tcp_conn->identity, NULL))
571 return GPG_ERR_BAD_SECKEY;
573 return 0;
576 static pwm_t *setup_context(pwm_t *pwm, gpg_error_t *rc)
578 assuan_context_t ctx;
579 struct assuan_io_hooks io_hooks = {read_hook, write_hook};
581 pwm->tcp_conn->session = libssh2_session_init_ex(_ssh_malloc, _ssh_free,
582 _ssh_realloc, NULL);
584 if (!pwm->tcp_conn->session) {
585 *rc = gpg_error_from_errno(ENOMEM);
586 goto fail;
589 if (libssh2_session_startup(pwm->tcp_conn->session, pwm->tcp_conn->fd)) {
590 *rc = GPG_ERR_ASSUAN_SERVER_FAULT;
591 goto fail;
594 *rc = authenticate_ssh(pwm);
596 if (*rc)
597 goto fail;
599 /* pwmd_get_hostkey(). */
600 if (pwm->tcp_conn->get_only) {
601 pwm->result = xstrdup(pwm->tcp_conn->hostkey);
603 if (!pwm->result) {
604 *rc = gpg_error_from_errno(ENOMEM);
605 goto fail;
608 return pwm;
611 pwm->tcp_conn->channel = libssh2_channel_open_session(pwm->tcp_conn->session);
613 if (!pwm->tcp_conn->channel) {
614 *rc = GPG_ERR_ASSUAN_SERVER_FAULT;
615 goto fail;
618 if (libssh2_channel_shell(pwm->tcp_conn->channel)) {
619 *rc = GPG_ERR_ASSUAN_SERVER_FAULT;
620 goto fail;
623 assuan_set_io_hooks(&io_hooks);
624 *rc = assuan_socket_connect_fd(&ctx, pwm->tcp_conn->fd, 0, pwm);
626 if (*rc)
627 goto fail;
629 assuan_set_finish_handler(ctx, _ssh_assuan_deinit);
630 return _socket_connect_finalize(pwm, ctx);
632 fail:
633 if (!pwm->tcp_conn->async)
634 pwmd_close(pwm);
636 return NULL;
639 static pwm_t *_do_pwmd_tcp_connect(const char *host, int port,
640 const char *identity, const char *user, const char *known_hosts,
641 gpg_error_t *rc, int get)
643 pwm_t *pwm = NULL;
644 pwmd_tcp_conn_t *conn;
646 *rc = init_tcp_conn(&conn, host, port, identity, user, known_hosts, get);
648 if (*rc)
649 return NULL;
651 if ((pwm = (pwm_t *)xcalloc(1, sizeof(pwm_t))) == NULL) {
652 *rc = gpg_error_from_errno(ENOMEM);
653 goto fail;
656 pwm->tcp_conn = conn;
657 pwm->tcp_conn->get_only = get;
658 pwm->cmd = ASYNC_CMD_DNS;
659 ares_init(&pwm->tcp_conn->chan);
660 ares_query(pwm->tcp_conn->chan, pwm->tcp_conn->host, ns_c_any, ns_t_any,
661 dns_resolve_cb, pwm);
663 /* dns_resolve_cb() may have already been called. */
664 if (pwm->tcp_conn->rc) {
665 *rc = pwm->tcp_conn->rc;
666 goto fail;
670 * Fake a blocking DNS lookup. libcares does a better job than
671 * getaddrinfo().
673 do {
674 fd_set rfds, wfds;
675 int n;
676 struct timeval tv;
678 FD_ZERO(&rfds);
679 FD_ZERO(&wfds);
680 n = ares_fds(pwm->tcp_conn->chan, &rfds, &wfds);
681 ares_timeout(pwm->tcp_conn->chan, NULL, &tv);
682 #ifdef WITH_LIBPTH
683 n = pth_select(n, &rfds, &wfds, NULL, &tv);
684 #else
685 n = select(n, &rfds, &wfds, NULL, &tv);
686 #endif
688 if (n == -1) {
689 *rc = gpg_error_from_syserror();
690 goto fail;
692 else if (n == 0) {
693 *rc = GPG_ERR_TIMEOUT;
694 goto fail;
697 ares_process(pwm->tcp_conn->chan, &rfds, &wfds);
699 if (pwm->tcp_conn->rc)
700 break;
701 } while (pwm->cmd == ASYNC_CMD_DNS);
703 if (pwm->tcp_conn->rc) {
704 *rc = pwm->tcp_conn->rc;
705 goto fail;
708 return setup_context(pwm, rc);
710 fail:
711 pwmd_close(pwm);
712 return NULL;
715 pwm_t *pwmd_tcp_connect(const char *host, int port, const char *identity,
716 const char *user, const char *known_hosts, gpg_error_t *rc)
718 return _do_pwmd_tcp_connect(host, port, identity, user, known_hosts, rc, 0);
721 /* Must free the result with pwmd_free_result(). */
722 char *pwmd_get_hostkey(const char *host, int port, gpg_error_t *rc)
724 char *hostkey;
725 pwm_t *pwm;
727 pwm = _do_pwmd_tcp_connect(host, port, NULL, NULL, NULL, rc, 1);
729 if (!pwm)
730 return NULL;
732 hostkey = xstrdup(pwm->tcp_conn->hostkey);
734 if (!hostkey)
735 *rc = gpg_error_from_errno(ENOMEM);
737 pwmd_close(pwm);
738 return hostkey;
741 pwm_t *pwmd_get_hostkey_async(const char *host, int port, gpg_error_t *rc)
743 return _do_pwmd_tcp_connect_async(host, port, NULL, NULL, NULL, rc,
744 ASYNC_CMD_HOSTKEY);
746 #endif
748 pwm_t *pwmd_connect(const char *path, gpg_error_t *rc)
750 pwm_t *pwm = NULL;
751 char *socketpath = NULL;
752 struct passwd *pw;
753 assuan_context_t ctx;
755 if (!path) {
756 pw = getpwuid(getuid());
757 socketpath = (char *)xmalloc(strlen(pw->pw_dir) + strlen("/.pwmd/socket") + 1);
758 sprintf(socketpath, "%s/.pwmd/socket", pw->pw_dir);
760 else
761 socketpath = xstrdup(path);
763 *rc = assuan_socket_connect_ext(&ctx, socketpath, -1, 0);
764 xfree(socketpath);
766 if (*rc)
767 return NULL;
769 if ((pwm = (pwm_t *)xcalloc(1, sizeof(pwm_t))) == NULL) {
770 *rc = gpg_error_from_syserror();
771 return NULL;
774 return _socket_connect_finalize(pwm, ctx);
777 gpg_error_t pwmd_pending_line(pwm_t *pwm, char **line, size_t *len)
779 if (!pwm)
780 return GPG_ERR_INV_ARG;
782 if (assuan_pending_line(pwm->ctx))
783 return assuan_read_line(pwm->ctx, line, len);
785 return GPG_ERR_NO_DATA;
788 void pwmd_close(pwm_t *pwm)
790 if (!pwm)
791 return;
793 if (pwm->ctx)
794 assuan_disconnect(pwm->ctx);
796 if (pwm->password)
797 xfree(pwm->password);
799 if (pwm->title)
800 xfree(pwm->title);
802 if (pwm->desc)
803 xfree(pwm->desc);
805 if (pwm->prompt)
806 xfree(pwm->prompt);
808 if (pwm->pinentry_tty)
809 xfree(pwm->pinentry_tty);
811 if (pwm->pinentry_display)
812 xfree(pwm->pinentry_display);
814 if (pwm->pinentry_term)
815 xfree(pwm->pinentry_term);
817 if (pwm->filename)
818 xfree(pwm->filename);
820 #ifdef WITH_TCP
821 if (pwm->result)
822 xfree(pwm->result);
824 if (pwm->tcp_conn)
825 free_tcp_conn(pwm->tcp_conn);
827 #endif
828 xfree(pwm);
831 static int mem_realloc_cb(void *data, const void *buffer, size_t len)
833 membuf_t *mem = (membuf_t *)data;
834 void *p;
836 if (!buffer)
837 return 0;
839 if ((p = xrealloc(mem->buf, mem->len + len)) == NULL)
840 return 1;
842 mem->buf = p;
843 memcpy((char *)mem->buf + mem->len, buffer, len);
844 mem->len += len;
845 return 0;
848 void pwmd_free_result(void *data)
850 xfree(data);
853 static int _inquire_cb(void *data, const char *keyword)
855 pwm_t *pwm = (pwm_t *)data;
856 gpg_error_t rc = 0;
857 int flags = fcntl(pwm->fd, F_GETFL);
859 /* Shouldn't get this far without a callback. */
860 if (!pwm->inquire_func)
861 return GPG_ERR_INV_ARG;
864 * Since the socket file descriptor is probably set to non-blocking, set to
865 * blocking to prevent GPG_ERR_EAGAIN errors. This should be fixes when
866 * asynchronous INQUIRE is supported by either libassuan or a later
867 * libpwmd.
869 fcntl(pwm->fd, F_SETFL, 0);
871 for (;;) {
872 char *result = NULL;
873 size_t len;
874 gpg_error_t arc;
876 rc = pwm->inquire_func(pwm->inquire_data, keyword, rc, &result, &len);
877 rc = gpg_err_code(rc);
879 if (rc == GPG_ERR_EOF || !rc) {
880 if (len <= 0 || !result || !*result) {
881 rc = 0;
882 break;
885 arc = assuan_send_data(pwm->ctx, result, len);
887 if (rc == GPG_ERR_EOF) {
888 rc = arc;
889 break;
892 rc = arc;
894 else if (rc)
895 break;
898 fcntl(pwm->fd, F_SETFL, flags);
899 return rc;
902 gpg_error_t pwmd_finalize(pwm_t *pwm)
904 if (!pwm || pwm->cmd == ASYNC_CMD_NONE || pwm->state != ASYNC_DONE)
905 return GPG_ERR_INV_ARG;
907 pwm->state = ASYNC_INIT;
908 pwm->cmd = ASYNC_CMD_NONE;
910 #ifdef WITH_TCP
911 if (pwm->cmd == ASYNC_CMD_CONNECT || pwm->cmd == ASYNC_CMD_DNS) {
912 gpg_error_t rc = pwm->tcp_conn->rc;
914 if (pwm->result)
915 xfree(pwm->result);
917 pwm->result = NULL;
919 /* pwm is no longer a valid handle. */
920 if (rc)
921 pwmd_close(pwm);
923 return 0;
925 #endif
927 if (pwm->fd < 0)
928 return GPG_ERR_INV_ARG;
930 pwm->ntries = 0;
931 #ifdef WITH_PINENTRY
932 pwm->is_open_cmd = 0;
933 #endif
934 return 0;
937 static gpg_error_t do_nb_command(pwm_t *pwm, const char *cmd, const char *arg)
939 char *buf;
940 gpg_error_t rc;
941 size_t len = strlen(cmd) + 2;
943 len += arg ? strlen(arg) : 0;
945 if (pwm->state != ASYNC_INIT)
946 return GPG_ERR_INV_STATE;
948 buf = (char *)xmalloc(len);
950 if (!buf) {
951 rc = gpg_error_from_errno(ENOMEM);
952 goto fail;
955 snprintf(buf, len, "%s %s", cmd, arg ? arg : "");
956 rc = assuan_write_line(pwm->ctx, buf);
957 xfree(buf);
959 if (!rc)
960 pwm->state = ASYNC_PROCESS;
962 fail:
963 return rc;
966 gpg_error_t pwmd_open_async(pwm_t *pwm, const char *filename)
968 if (!pwm || !filename)
969 return GPG_ERR_INV_ARG;
971 /* For pinentry retries. */
972 if (!pwm->is_open_cmd) {
973 if (pwm->filename)
974 xfree(pwm->filename);
976 pwm->filename = xstrdup(filename);
979 pwm->is_open_cmd = 1;
980 return do_nb_command(pwm, "OPEN", filename);
983 gpg_error_t pwmd_save_async(pwm_t *pwm)
985 if (!pwm)
986 return GPG_ERR_INV_ARG;
988 return do_nb_command(pwm, "SAVE", NULL);
991 static gpg_error_t parse_assuan_line(pwm_t *pwm)
993 gpg_error_t rc;
994 char *line;
995 size_t len;
997 rc = assuan_read_line(pwm->ctx, &line, &len);
999 if (!rc) {
1000 if (line[0] == 'O' && line[1] == 'K' &&
1001 (line[2] == 0 || line[2] == ' ')) {
1002 pwm->state = ASYNC_DONE;
1004 else if (line[0] == '#') {
1006 else if (line[0] == 'S' && (line[1] == 0 || line[1] == ' ')) {
1007 if (pwm->status_func) {
1008 pwm->status_func(pwm->status_data,
1009 line[1] == 0 ? line+1 : line+2);
1012 else if (line[0] == 'E' && line[1] == 'R' && line[2] == 'R' &&
1013 (line[3] == 0 || line[3] == ' ')) {
1014 line += 4;
1015 rc = atoi(line);
1016 pwm->state = ASYNC_DONE;
1020 return rc;
1023 gpg_error_t pwmd_get_result(pwm_t *pwm, const char **result)
1025 if (!pwm || !result)
1026 return GPG_ERR_INV_ARG;
1028 if (pwm->state != ASYNC_DONE)
1029 return GPG_ERR_INV_STATE;
1031 if (!pwm->result)
1032 return GPG_ERR_NO_DATA;
1034 *result = pwm->result;
1035 return 0;
1038 pwmd_async_t pwmd_process(pwm_t *pwm, gpg_error_t *rc)
1040 fd_set fds;
1041 int n;
1042 struct timeval tv = {0, 0};
1044 *rc = 0;
1046 if (!pwm) {
1047 *rc = GPG_ERR_INV_ARG;
1048 return ASYNC_DONE;
1051 #ifdef WITH_TCP
1052 if (pwm->cmd == ASYNC_CMD_DNS) {
1053 fd_set rfds, wfds;
1055 if (pwm->tcp_conn->rc) {
1056 *rc = pwm->tcp_conn->rc;
1057 close(pwm->tcp_conn->fd);
1058 pwm->state = ASYNC_DONE;
1059 return pwm->state;
1062 FD_ZERO(&rfds);
1063 FD_ZERO(&wfds);
1064 n = ares_fds(pwm->tcp_conn->chan, &rfds, &wfds);
1066 /* Shouldn't happen. */
1067 if (!n)
1068 return pwm->state;
1070 n = select(n, &rfds, &wfds, NULL, &tv);
1072 if (n > 0)
1073 ares_process(pwm->tcp_conn->chan, &rfds, &wfds);
1075 return pwm->state;
1077 else if (pwm->cmd == ASYNC_CMD_CONNECT) {
1078 if (pwm->tcp_conn->rc == GPG_ERR_EINPROGRESS) {
1079 int ret;
1080 socklen_t len = sizeof(int);
1082 FD_ZERO(&fds);
1083 FD_SET(pwm->tcp_conn->fd, &fds);
1084 n = select(pwm->tcp_conn->fd+1, NULL, &fds, NULL, &tv);
1086 if (!n || !FD_ISSET(pwm->tcp_conn->fd, &fds))
1087 return pwm->state;
1088 else if (n == -1) {
1089 *rc = gpg_error_from_syserror();
1090 close(pwm->tcp_conn->fd);
1091 pwm->state = ASYNC_DONE;
1092 return pwm->state;
1095 ret = getsockopt(pwm->tcp_conn->fd, SOL_SOCKET, SO_ERROR, &n, &len);
1096 if (ret || n) {
1097 *rc = ret ? gpg_error_from_syserror() : gpg_error_from_errno(n);
1098 close(pwm->tcp_conn->fd);
1099 pwm->state = ASYNC_DONE;
1100 return pwm->state;
1103 else if (pwm->tcp_conn->rc) {
1104 *rc = pwm->tcp_conn->rc;
1105 close(pwm->tcp_conn->fd);
1106 pwm->state = ASYNC_DONE;
1107 return pwm->state;
1110 fcntl(pwm->tcp_conn->fd, F_SETFL, 0);
1111 setup_context(pwm, rc);
1112 pwm->state = ASYNC_DONE;
1113 return pwm->state;
1115 #endif
1117 if (pwm->fd < 0) {
1118 *rc = GPG_ERR_INV_ARG;
1119 return ASYNC_DONE;
1121 else if (pwm->state == ASYNC_DONE)
1122 return pwm->state;
1123 else if (pwm->state == ASYNC_INIT) {
1124 *rc = GPG_ERR_INV_STATE;
1125 return ASYNC_DONE;
1128 FD_ZERO(&fds);
1129 FD_SET(pwm->fd, &fds);
1130 #ifdef WITH_LIBPTH
1131 n = pth_select(pwm->fd+1, &fds, NULL, NULL, &tv);
1132 #else
1133 n = select(pwm->fd+1, &fds, NULL, NULL, &tv);
1134 #endif
1136 if (n > 0) {
1137 if (FD_ISSET(pwm->fd, &fds))
1138 *rc = parse_assuan_line(pwm);
1141 while (!*rc && assuan_pending_line(pwm->ctx))
1142 *rc = parse_assuan_line(pwm);
1144 if (pwm->is_open_cmd && gpg_err_code(*rc) == EPWMD_BADKEY &&
1145 ++pwm->ntries < pwm->pinentry_tries) {
1146 pwm->state = ASYNC_INIT;
1147 *rc = pwmd_open_async(pwm, pwm->filename);
1150 return pwm->state;
1153 static gpg_error_t assuan_command(pwm_t *pwm, assuan_context_t ctx,
1154 char **result, const char *cmd)
1156 membuf_t data;
1157 gpg_error_t rc;
1159 data.len = 0;
1160 data.buf = NULL;
1162 rc = assuan_transact(ctx, cmd, mem_realloc_cb, &data, _inquire_cb, pwm,
1163 pwm->status_func, pwm->status_data);
1165 if (rc) {
1166 if (data.buf) {
1167 xfree(data.buf);
1168 data.buf = NULL;
1171 else {
1172 if (data.buf) {
1173 mem_realloc_cb(&data, "", 1);
1174 *result = (char *)data.buf;
1178 return gpg_err_code(rc);
1181 gpg_error_t pwmd_inquire(pwm_t *pwm, const char *cmd, pwmd_inquire_fn fn,
1182 void *data)
1184 if (!pwm || !cmd || !fn)
1185 return GPG_ERR_INV_ARG;
1187 pwm->inquire_func = fn;
1188 pwm->inquire_data = data;
1189 return assuan_command(pwm, pwm->ctx, NULL, cmd);
1192 gpg_error_t pwmd_terminate_pinentry(pwm_t *pwm)
1194 #ifndef WITH_PINENTRY
1195 return GPG_ERR_NOT_IMPLEMENTED;
1196 #else
1197 if (!pwm || pwm->pid == -1)
1198 return GPG_ERR_INV_ARG;
1200 if (kill(pwm->pid, 0) == 0) {
1201 if (kill(pwm->pid, SIGTERM) == -1) {
1202 if (kill(pwm->pid, SIGKILL) == -1)
1203 return gpg_error_from_errno(errno);
1206 pwm->pin_error = GPG_ERR_TIMEOUT;
1208 else
1209 return gpg_error_from_errno(errno);
1211 return 0;
1212 #endif
1215 #ifdef WITH_PINENTRY
1216 static gpg_error_t set_pinentry_strings(pwm_t *pwm, int which)
1218 char *buf;
1219 char tmp[ASSUAN_LINELENGTH];
1220 gpg_error_t error;
1222 if (!pwm->title)
1223 pwm->title = xstrdup(N_("LibPWMD"));
1225 if (!pwm->prompt)
1226 pwm->prompt = xstrdup(N_("Passphrase:"));
1228 if (!pwm->desc && !which)
1229 pwm->desc = xstrdup(N_("Enter a passphrase."));
1231 if (which == 1) {
1232 snprintf(tmp, sizeof(tmp), "SETERROR %s", N_("Invalid passphrase, please try again."));
1233 buf = xstrdup(tmp);
1235 else if (which == 2) {
1236 snprintf(tmp, sizeof(tmp), "SETERROR %s", N_("Please type the passphrase again for confirmation."));
1237 buf = xstrdup(tmp);
1239 else {
1240 buf = (char *)xmalloc(strlen("SETERROR ") + strlen(pwm->desc) + 1);
1241 sprintf(buf, "SETERROR %s", pwm->desc);
1244 error = pinentry_command(pwm, NULL, buf);
1245 xfree(buf);
1247 if (error)
1248 return error;
1250 buf = (char *)xmalloc(strlen("SETPROMPT ") + strlen(pwm->prompt) + 1);
1251 sprintf(buf, "SETPROMPT %s", pwm->prompt);
1252 error = pinentry_command(pwm, NULL, buf);
1253 xfree(buf);
1255 if (error)
1256 return error;
1258 buf = (char *)xmalloc(strlen("SETDESC ") + strlen(pwm->title) + 1);
1259 sprintf(buf, "SETDESC %s", pwm->title);
1260 error = pinentry_command(pwm, NULL, buf);
1261 xfree(buf);
1262 return error;
1265 static void update_pinentry_settings(pwm_t *pwm)
1267 FILE *fp;
1268 char buf[LINE_MAX];
1269 struct passwd *pw = getpwuid(getuid());
1270 char *p;
1272 snprintf(buf, sizeof(buf), "%s/.pwmd/pinentry.conf", pw->pw_dir);
1274 if ((fp = fopen(buf, "r")) == NULL)
1275 return;
1277 while ((p = fgets(buf, sizeof(buf), fp)) != NULL) {
1278 char name[32], val[256];
1280 if (sscanf(p, " %31[a-zA-Z] = %255s", name, val) != 2)
1281 continue;
1283 if (strcasecmp(name, "TTYNAME") == 0) {
1284 xfree(pwm->pinentry_tty);
1285 pwm->pinentry_tty = xstrdup(val);
1287 else if (strcasecmp(name, "TTYTYPE") == 0) {
1288 xfree(pwm->pinentry_term);
1289 pwm->pinentry_term = xstrdup(val);
1291 else if (strcasecmp(name, "DISPLAY") == 0) {
1292 xfree(pwm->pinentry_display);
1293 pwm->pinentry_display = xstrdup(val);
1295 else if (strcasecmp(name, "PATH") == 0) {
1296 xfree(pwm->pinentry_path);
1297 pwm->pinentry_path = xstrdup(val);
1301 fclose(fp);
1304 static gpg_error_t launch_pinentry(pwm_t *pwm)
1306 int rc;
1307 assuan_context_t ctx;
1308 int child_list[] = {-1};
1309 char *display = getenv("DISPLAY");
1310 const char *argv[6];
1311 int have_display = 0;
1312 char *tty = NULL;
1314 update_pinentry_settings(pwm);
1316 if (pwm->pinentry_display || display)
1317 have_display = 1;
1318 else {
1319 tty = pwm->pinentry_tty ? pwm->pinentry_tty : ttyname(STDOUT_FILENO);
1321 if (!tty)
1322 return gpg_error_from_errno(errno);
1325 if (!have_display && !tty)
1326 return GPG_ERR_ENOTTY;
1328 argv[0] = "pinentry";
1329 argv[1] = have_display ? "--display" : "--ttyname";
1330 argv[2] = have_display ? pwm->pinentry_display ? pwm->pinentry_display : display : tty;
1331 argv[3] = NULL;
1333 if (!have_display) {
1334 argv[3] = "--ttytype";
1335 argv[4] = pwm->pinentry_term ? pwm->pinentry_term : getenv("TERM");
1336 argv[5] = NULL;
1339 rc = assuan_pipe_connect(&ctx, pwm->pinentry_path ? pwm->pinentry_path : PINENTRY_PATH, argv, child_list);
1341 if (rc)
1342 return rc;
1344 pwm->pid = assuan_get_pid(ctx);
1345 pwm->pctx = ctx;
1346 return set_pinentry_strings(pwm, 0);
1349 static gpg_error_t pinentry_command(pwm_t *pwm, char **result, const char *cmd)
1351 gpg_error_t n;
1353 if (!pwm->pctx) {
1354 n = launch_pinentry(pwm);
1356 if (n)
1357 return n;
1360 return assuan_command(pwm, pwm->pctx, result, cmd);
1363 static void pinentry_disconnect(pwm_t *pwm)
1365 if (pwm->pctx)
1366 assuan_disconnect(pwm->pctx);
1368 pwm->pctx = NULL;
1369 pwm->pid = -1;
1373 * Only called from a child process.
1375 static void catchsig(int sig)
1377 switch (sig) {
1378 case SIGALRM:
1379 if (gelapsed++ >= gtimeout) {
1380 global_error = pwmd_terminate_pinentry(gpwm);
1382 if (!global_error)
1383 global_error = GPG_ERR_TIMEOUT;
1385 break;
1388 alarm(1);
1389 break;
1390 default:
1391 break;
1396 * Borrowed from libassuan.
1398 static char *percent_escape(const char *atext)
1400 const unsigned char *s;
1401 int len = strlen(atext) * 3 + 1;
1402 char *buf = (char *)xmalloc(len), *p = buf;
1404 if (!buf)
1405 return NULL;
1407 for (s=(const unsigned char *)atext; *s; s++) {
1408 if (*s < ' ') {
1409 sprintf (p, "%%%02X", *s);
1410 p += 3;
1412 else
1413 *p++ = *s;
1416 *p = 0;
1417 return buf;
1419 #endif
1421 static gpg_error_t send_command(pwm_t *pwm, char **result, const char *cmd)
1423 if (!cmd)
1424 return GPG_ERR_INV_ARG;
1426 return assuan_command(pwm, pwm->ctx, result, cmd);
1429 gpg_error_t pwmd_command_ap(pwm_t *pwm, char **result, const char *cmd,
1430 va_list ap)
1432 char *buf;
1433 size_t len;
1434 gpg_error_t error;
1437 * C99 allows the dst pointer to be null which will calculate the length
1438 * of the would-be result and return it.
1440 len = vsnprintf(NULL, 0, cmd, ap)+1;
1441 buf = (char *)xmalloc(len);
1442 len = vsnprintf(buf, len, cmd, ap);
1443 error = send_command(pwm, result, buf);
1444 xfree(buf);
1445 return error;
1449 * Avoid sending the BYE command here. libassuan will close the file
1450 * descriptor and release the assuan context. Use pwmd_close() instead.
1452 gpg_error_t pwmd_command(pwm_t *pwm, char **result, const char *cmd, ...)
1454 va_list ap;
1455 gpg_error_t error;
1457 if (!pwm || !cmd)
1458 return GPG_ERR_INV_ARG;
1460 *result = NULL;
1461 va_start(ap, cmd);
1462 error = pwmd_command_ap(pwm, result, cmd, ap);
1463 va_end(ap);
1464 return error;
1467 #ifdef WITH_PINENTRY
1468 static gpg_error_t do_getpin(pwm_t *pwm, char **result)
1470 if (gtimeout) {
1471 signal(SIGALRM, catchsig);
1472 alarm(1);
1475 *result = NULL;
1476 return pinentry_command(pwm, result, "GETPIN");
1479 static gpg_error_t getpin(pwm_t *pwm, char **result, int *try_n, int which)
1481 int pin_try = *try_n;
1482 gpg_error_t error;
1484 getpin_again:
1485 *try_n = pin_try;
1487 if (pin_try == -1) {
1488 error = set_pinentry_strings(pwm, which);
1490 if (error) {
1491 pinentry_disconnect(pwm);
1492 return error;
1495 else {
1496 if (pwm->pinentry_tries-1 != pin_try) {
1497 error = set_pinentry_strings(pwm, 1);
1499 if (error) {
1500 pinentry_disconnect(pwm);
1501 return error;
1506 error = do_getpin(pwm, result);
1509 * Since there was input cancel any timeout setting.
1511 alarm(0);
1513 if (error) {
1514 if (error == GPG_ERR_CANCELED)
1515 return GPG_ERR_CANCELED;
1517 if (pin_try != -1 && pin_try--)
1518 goto getpin_again;
1520 if (pwm->pctx)
1521 pinentry_disconnect(pwm);
1523 *try_n = pin_try;
1524 return error;
1527 return 0;
1529 #endif
1531 gpg_error_t pwmd_open_nb_finalize(pwm_t *pwm, pwmd_nb_status_t *pw)
1533 gpg_error_t error;
1535 #ifndef WITH_PINENTRY
1536 return GPG_ERR_NOT_IMPLEMENTED;
1537 #endif
1539 if (!pwm || !pw || !pw->filename[0])
1540 return GPG_ERR_INV_ARG;
1542 close(pw->fd);
1544 if (pw->error) {
1545 error = pw->error;
1546 goto fail;
1549 if (pwm->filename)
1550 xfree(pwm->filename);
1552 pwm->filename = xstrdup(pw->filename);
1553 memset(pw, 0, sizeof(pwmd_nb_status_t));
1554 return 0;
1556 fail:
1557 memset(pw, 0, sizeof(pwmd_nb_status_t));
1558 return error;
1561 static gpg_error_t do_open_command(pwm_t *pwm, const char *filename, char *password)
1563 char buf[ASSUAN_LINELENGTH];
1564 gpg_error_t error;
1565 char *result = NULL;
1567 snprintf(buf, sizeof(buf), "OPEN %s %s", filename, password ? password : "");
1568 error = send_command(pwm, &result, buf);
1569 memset(buf, 0, sizeof(buf));
1571 if (error && result)
1572 xfree(result);
1574 return error;
1577 static int do_pwmd_open(pwm_t *pwm, gpg_error_t *error, const char *filename,
1578 int nb, int timeout)
1580 char *result = NULL;
1581 char *password = NULL;
1582 char path[PATH_MAX];
1583 #ifdef WITH_PINENTRY
1584 int pin_try;
1585 #endif
1587 if (!pwm || !filename || !*filename) {
1588 *error = GPG_ERR_INV_ARG;
1589 return nb ? -1 : 1;
1592 #ifdef WITH_PINENTRY
1593 pin_try = pwm->pinentry_tries - 1;
1594 #endif
1597 * Avoid calling pinentry if the password is cached on the server or if
1598 * this is a new file.
1600 *error = pwmd_command(pwm, &result, "GETCONFIG data_directory");
1602 if (*error)
1603 return nb ? -1 : 1;
1605 snprintf(path, sizeof(path), "%s/%s", result, filename);
1606 pwmd_free_result(result);
1608 if (access(path, R_OK) == -1) {
1609 if (errno == ENOENT)
1610 goto gotpassword;
1613 *error = pwmd_command(pwm, &result, "ISCACHED %s", filename);
1615 if (*error == EPWMD_CACHE_NOT_FOUND) {
1616 if (pwm->passfunc) {
1617 password = pwm->passfunc(pwm, pwm->passdata);
1618 goto gotpassword;
1621 #ifdef WITH_PINENTRY
1623 * Get the password from pinentry.
1625 if (pwm->use_pinentry) {
1627 * Nonblocking is wanted. fork() then return a file descriptor
1628 * that the client can use to read() from.
1630 if (nb) {
1631 int p[2];
1632 pid_t pid;
1633 pwmd_nb_status_t pw;
1635 if (pipe(p) == -1) {
1636 *error = gpg_error_from_syserror();
1637 return -1;
1640 #ifdef WITH_LIBPTH
1641 pid = pth_fork();
1642 #else
1643 pid = fork();
1644 #endif
1646 switch (pid) {
1647 case 0:
1648 close(p[0]);
1649 strncpy(pw.filename, filename, sizeof(pw.filename));
1650 pw.filename[sizeof(pw.filename)-1] = 0;
1651 pw.fd = p[0];
1653 if (timeout > 0) {
1654 gpwm = pwm;
1655 gtimeout = timeout;
1656 gelapsed = 0;
1659 getpin_nb_again:
1660 *error = getpin(pwm, &password, &pin_try, 0);
1662 if (*error) {
1663 getpin_nb_fail:
1664 if (pwm->pctx)
1665 pinentry_disconnect(pwm);
1667 if (gtimeout && gelapsed >= gtimeout)
1668 *error = GPG_ERR_TIMEOUT;
1670 pw.error = *error;
1671 #ifdef WITH_LIBPTH
1672 pth_write(p[1], &pw, sizeof(pw));
1673 #else
1674 write(p[1], &pw, sizeof(pw));
1675 #endif
1676 close(p[1]);
1677 _exit(1);
1681 * Don't count the time it takes to open the file
1682 * which may have many iterations.
1684 signal(SIGALRM, SIG_DFL);
1685 *error = do_open_command(pwm, filename, password);
1687 if (timeout)
1688 signal(SIGALRM, catchsig);
1690 if (pwm->pctx && *error == EPWMD_BADKEY) {
1691 if (pin_try-- > 0)
1692 goto getpin_nb_again;
1694 goto getpin_nb_fail;
1697 pinentry_disconnect(pwm);
1698 pw.error = 0;
1699 #ifdef WITH_LIBPTH
1700 pth_write(p[1], &pw, sizeof(pw));
1701 #else
1702 write(p[1], &pw, sizeof(pw));
1703 #endif
1704 close(p[1]);
1705 _exit(0);
1706 break;
1707 case -1:
1708 *error = gpg_error_from_syserror();
1709 close(p[0]);
1710 close(p[1]);
1711 return -1;
1712 default:
1713 break;
1716 close(p[1]);
1717 *error = 0;
1718 return p[0];
1721 else {
1722 #endif
1724 * Not using pinentry and the file was not found
1725 * in the cache.
1727 password = pwm->password;
1728 #ifdef WITH_PINENTRY
1730 #endif
1732 else if (*error)
1733 return nb ? -1 : 1;
1735 gotpassword:
1736 *error = do_open_command(pwm, filename, password);
1739 * Keep the user defined password set with pwmd_setopt(). The password may
1740 * be needed later (pwmd_save()) depending on the pwmd file cache settings.
1742 if (password && password != pwm->password)
1743 xfree(password);
1745 #ifdef WITH_PINENTRY
1746 if (*error == EPWMD_BADKEY) {
1747 if (pin_try-- > 0 && !nb) {
1748 *error = pwmd_command(pwm, &result, "OPTION TITLE=%s",
1749 N_("Invalid passphrase, please try again."));
1751 if (*error)
1752 return 1;
1754 goto gotpassword;
1757 if (nb)
1758 pinentry_disconnect(pwm);
1760 return nb ? -1 : 1;
1762 #endif
1764 if (!*error) {
1765 if (pwm->filename)
1766 xfree(pwm->filename);
1768 pwm->filename = xstrdup(filename);
1772 * The file is cached or the file is a new file.
1774 if (nb)
1775 return *error ? -1 : -2;
1777 return *error ? 1 : 0;
1780 gpg_error_t pwmd_open(pwm_t *pwm, const char *filename)
1782 gpg_error_t error;
1784 do_pwmd_open(pwm, &error, filename, 0, 0);
1785 return error;
1788 int pwmd_open_nb(pwm_t *pwm, gpg_error_t *error, const char *filename,
1789 int timeout)
1791 #ifndef WITH_PINENTRY
1792 *error = GPG_ERR_NOT_IMPLEMENTED;
1793 return -1;
1794 #else
1795 return do_pwmd_open(pwm, error, filename, 1, timeout);
1796 #endif
1799 #ifdef WITH_PINENTRY
1800 static gpg_error_t do_save_getpin(pwm_t *pwm, char **password)
1802 int confirm = 0;
1803 gpg_error_t error;
1804 char *result = NULL;
1805 int pin_try = -1;
1807 again:
1808 error = getpin(pwm, &result, &pin_try, confirm ? 2 : 0);
1810 if (error) {
1811 if (pwm->pctx)
1812 pinentry_disconnect(pwm);
1814 if (*password)
1815 xfree(*password);
1817 return error;
1820 if (!confirm++) {
1821 *password = result;
1822 goto again;
1825 if (strcmp(*password, result)) {
1826 xfree(*password);
1827 xfree(result);
1828 pinentry_disconnect(pwm);
1829 error = EPWMD_BADKEY;
1830 return error;
1833 xfree(result);
1834 pinentry_disconnect(pwm);
1835 return 0;
1837 #endif
1839 static gpg_error_t do_save_command(pwm_t *pwm, char *password)
1841 char buf[ASSUAN_LINELENGTH];
1842 gpg_error_t error;
1843 char *result = NULL;
1845 snprintf(buf, sizeof(buf), "SAVE %s", password ? password : "");
1846 error = send_command(pwm, &result, buf);
1847 memset(&buf, 0, sizeof(buf));
1849 if (error && result)
1850 xfree(result);
1852 return error;
1855 gpg_error_t pwmd_save_nb_finalize(pwm_t *pwm, pwmd_nb_status_t *pw)
1857 gpg_error_t rc;
1859 #ifndef WITH_PINENTRY
1860 return GPG_ERR_NOT_IMPLEMENTED;
1861 #endif
1863 if (!pwm || !pw || !pw->filename[0])
1864 return GPG_ERR_INV_ARG;
1866 close(pw->fd);
1867 rc = pw->error;
1868 memset(pw, 0, sizeof(pwmd_nb_status_t));
1869 return rc;
1872 static int do_pwmd_save(pwm_t *pwm, gpg_error_t *error, int nb)
1874 char *result = NULL;
1875 char *password = NULL;
1877 if (!pwm) {
1878 *error = GPG_ERR_INV_ARG;
1879 return nb ? -1 : 1;
1882 if (pwm->use_pinentry || pwm->passfunc) {
1883 *error = pwmd_command(pwm, &result, "ISCACHED %s", pwm->filename);
1885 if (*error == EPWMD_CACHE_NOT_FOUND) {
1886 #ifdef WITH_PINENTRY
1887 if (pwm->use_pinentry) {
1888 if (nb) {
1889 int p[2];
1890 pid_t pid;
1891 pwmd_nb_status_t pw;
1893 if (pipe(p) == -1) {
1894 *error = gpg_error_from_syserror();
1895 return -1;
1898 #ifdef WITH_LIBPTH
1899 pid = pth_fork();
1900 #else
1901 pid = fork();
1902 #endif
1904 switch (pid) {
1905 case 0:
1906 close(p[0]);
1907 strncpy(pw.filename, pwm->filename, sizeof(pw.filename));
1908 pw.filename[sizeof(pw.filename)-1] = 0;
1909 pw.fd = p[0];
1911 do {
1912 password = NULL;
1913 *error = do_save_getpin(pwm, &password);
1914 } while (*error == EPWMD_BADKEY);
1916 if (*error) {
1917 if (pwm->pctx)
1918 pinentry_disconnect(pwm);
1920 pw.error = *error;
1921 #ifdef WITH_LIBPTH
1922 pth_write(p[1], &pw, sizeof(pw));
1923 #else
1924 write(p[1], &pw, sizeof(pw));
1925 #endif
1926 close(p[1]);
1927 _exit(1);
1930 *error = do_save_command(pwm, password);
1931 pinentry_disconnect(pwm);
1932 pw.error = *error;
1933 #ifdef WITH_LIBPTH
1934 pth_write(p[1], &pw, sizeof(pw));
1935 #else
1936 write(p[1], &pw, sizeof(pw));
1937 #endif
1938 close(p[1]);
1939 _exit(0);
1940 break;
1941 case -1:
1942 *error = gpg_error_from_syserror();
1943 close(p[0]);
1944 close(p[1]);
1945 return -1;
1946 default:
1947 break;
1950 close(p[1]);
1951 *error = 0;
1952 return p[0];
1955 *error = do_save_getpin(pwm, &password);
1957 if (*error)
1958 return 1;
1960 else {
1961 #endif
1962 if (pwm->passfunc)
1963 password = (*pwm->passfunc)(pwm, pwm->passdata);
1964 #ifdef WITH_PINENTRY
1966 #endif
1968 else {
1969 if (*error)
1970 return nb ? -1 : 1;
1973 else
1974 password = pwm->password;
1976 *error = do_save_command(pwm, password);
1978 if (password && password != pwm->password)
1979 xfree(password);
1981 if (nb)
1982 return *error ? -1 : -2;
1984 return *error ? 1 : 0;
1987 int pwmd_save_nb(pwm_t *pwm, gpg_error_t *error)
1989 #ifndef WITH_PINENTRY
1990 *error = GPG_ERR_NOT_IMPLEMENTED;
1991 return -1;
1992 #else
1993 return do_pwmd_save(pwm, error, 1);
1994 #endif
1997 gpg_error_t pwmd_save(pwm_t *pwm)
1999 gpg_error_t error;
2001 do_pwmd_save(pwm, &error, 0);
2002 return error;
2005 gpg_error_t pwmd_setopt(pwm_t *pwm, pwmd_option_t opt, ...)
2007 va_list ap;
2008 #ifdef WITH_PINENTRY
2009 int n = va_arg(ap, int);
2010 char *result;
2011 #endif
2012 char *arg1;
2013 gpg_error_t error = 0;
2015 if (!pwm)
2016 return GPG_ERR_INV_ARG;
2018 va_start(ap, opt);
2020 switch (opt) {
2021 case PWMD_OPTION_STATUS_FUNC:
2022 pwm->status_func = va_arg(ap, pwmd_status_fn);
2023 break;
2024 case PWMD_OPTION_STATUS_DATA:
2025 pwm->status_data = va_arg(ap, void *);
2026 break;
2027 case PWMD_OPTION_PASSWORD_FUNC:
2028 pwm->passfunc = va_arg(ap, pwmd_password_fn);
2029 break;
2030 case PWMD_OPTION_PASSWORD_DATA:
2031 pwm->passdata = va_arg(ap, void *);
2032 break;
2033 case PWMD_OPTION_PASSWORD:
2034 arg1 = va_arg(ap, char *);
2036 if (pwm->password)
2037 xfree(pwm->password);
2039 pwm->password = xstrdup(arg1);
2040 break;
2041 #ifdef WITH_PINENTRY
2042 case PWMD_OPTION_PINENTRY:
2043 n = va_arg(ap, int);
2045 if (n != 0 && n != 1) {
2046 va_end(ap);
2047 error = GPG_ERR_INV_VALUE;
2049 else {
2050 pwm->use_pinentry = n;
2051 error = pwmd_command(pwm, &result, "OPTION PINENTRY=%i",
2052 !pwm->use_pinentry);
2054 break;
2055 case PWMD_OPTION_PINENTRY_TRIES:
2056 n = va_arg(ap, int);
2058 if (n <= 0) {
2059 va_end(ap);
2060 error = GPG_ERR_INV_VALUE;
2062 else
2063 pwm->pinentry_tries = n;
2064 break;
2065 case PWMD_OPTION_PINENTRY_PATH:
2066 if (pwm->pinentry_path)
2067 xfree(pwm->pinentry_path);
2069 pwm->pinentry_path = xstrdup(va_arg(ap, char *));
2070 break;
2071 case PWMD_OPTION_PINENTRY_TTY:
2072 if (pwm->pinentry_tty)
2073 xfree(pwm->pinentry_tty);
2075 pwm->pinentry_tty = xstrdup(va_arg(ap, char *));
2076 break;
2077 case PWMD_OPTION_PINENTRY_DISPLAY:
2078 if (pwm->pinentry_display)
2079 xfree(pwm->pinentry_display);
2081 pwm->pinentry_display = xstrdup(va_arg(ap, char *));
2082 break;
2083 case PWMD_OPTION_PINENTRY_TERM:
2084 if (pwm->pinentry_term)
2085 xfree(pwm->pinentry_term);
2087 pwm->pinentry_term = xstrdup(va_arg(ap, char *));
2088 break;
2089 case PWMD_OPTION_PINENTRY_TITLE:
2090 if (pwm->title)
2091 xfree(pwm->title);
2092 pwm->title = percent_escape(va_arg(ap, char *));
2093 break;
2094 case PWMD_OPTION_PINENTRY_PROMPT:
2095 if (pwm->prompt)
2096 xfree(pwm->prompt);
2097 pwm->prompt = percent_escape(va_arg(ap, char *));
2098 break;
2099 case PWMD_OPTION_PINENTRY_DESC:
2100 if (pwm->desc)
2101 xfree(pwm->desc);
2102 pwm->desc = percent_escape(va_arg(ap, char *));
2103 break;
2104 #else
2105 case PWMD_OPTION_PINENTRY:
2106 case PWMD_OPTION_PINENTRY_TRIES:
2107 case PWMD_OPTION_PINENTRY_PATH:
2108 case PWMD_OPTION_PINENTRY_TTY:
2109 case PWMD_OPTION_PINENTRY_DISPLAY:
2110 case PWMD_OPTION_PINENTRY_TERM:
2111 case PWMD_OPTION_PINENTRY_TITLE:
2112 case PWMD_OPTION_PINENTRY_PROMPT:
2113 case PWMD_OPTION_PINENTRY_DESC:
2114 error = GPG_ERR_NOT_IMPLEMENTED;
2115 break;
2116 #endif
2117 default:
2118 error = GPG_ERR_NOT_IMPLEMENTED;
2119 break;
2122 va_end(ap);
2123 return error;
2127 * Prevent requiring assuan.h when setting ctx. The ctx is really an
2128 * assuan_context_t *.
2130 gpg_error_t pwmd_assuan_ctx(pwm_t *pwm, void *ctx, int *fd)
2132 if (!pwm)
2133 return GPG_ERR_INV_ARG;
2135 ctx = pwm->ctx;
2136 *fd = pwm->fd;
2137 return 0;