Removed pwmd_terminate_pinentry(). There is no need for it that I can
[libpwmd.git] / src / libpwmd.c
blob247434d28c79ce5007d88725da451dd463b378a3
1 /* vim:tw=78:ts=8:sw=4:set ft=c: */
2 /*
3 Copyright (C) 2006-2009 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 #endif
57 #ifdef HAVE_ASSUAN_H
58 #include <assuan.h>
59 #endif
61 #ifdef HAVE_SETLOCALE
62 #include <locale.h>
63 #endif
65 #include "gettext.h"
66 #define N_(msgid) dgettext("libpwmd", msgid)
68 #include "mem.h"
69 #include "types.h"
71 #ifdef WITH_PINENTRY
72 static pwm_t *gpwm;
73 static int gelapsed, gtimeout;
74 static gpg_error_t pinentry_command(pwm_t *pwm, char **result, const char *cmd);
75 #endif
77 static char *_getpwuid(struct passwd *pwd)
79 size_t size = sysconf(_SC_GETPW_R_SIZE_MAX);
80 struct passwd *result;
81 char *buf;
82 int n;
84 if (size == -1)
85 size = 16384;
87 buf = pwmd_malloc(size);
89 if (!buf)
90 return NULL;
92 n = getpwuid_r(getuid(), pwd, buf, size, &result);
94 if (n) {
95 pwmd_free(buf);
96 errno = n;
97 return NULL;
100 if (!result) {
101 pwmd_free(buf);
102 return NULL;
105 errno = n;
106 return buf;
109 const char *_pwmd_strerror(gpg_error_t e)
111 gpg_err_code_t code = gpg_err_code(e);
113 if (code >= GPG_ERR_USER_1 && code < gpg_err_code(EPWMD_MAX)) {
114 switch (code) {
115 default:
116 return NULL;
117 case GPG_ERR_USER_1:
118 return N_("Unknown error");
119 case GPG_ERR_USER_2:
120 return N_("No cache slots available");
121 case GPG_ERR_USER_3:
122 return N_("Recursion loop");
123 case GPG_ERR_USER_4:
124 return N_("No file is open");
125 case GPG_ERR_USER_5:
126 return N_("General LibXML error");
127 case GPG_ERR_USER_6:
128 return N_("File modified");
129 case GPG_ERR_USER_7:
130 return N_("Access denied");
134 return NULL;
137 const char *pwmd_strerror(gpg_error_t e)
139 const char *p = _pwmd_strerror(e);
141 return p ? p : gpg_strerror(e);
144 int pwmd_strerror_r(gpg_error_t e, char *buf, size_t size)
146 const char *p = _pwmd_strerror(e);
148 if (p) {
149 snprintf(buf, size, "%s", p);
151 if (strlen(p) > size)
152 return ERANGE;
154 return 0;
157 return gpg_strerror_r(e, buf, size);
160 gpg_error_t pwmd_init()
162 static int initialized;
164 if (initialized)
165 return 0;
167 #ifndef MEM_DEBUG
168 xmem_init();
169 #endif
170 #ifdef ENABLE_NLS
171 bindtextdomain("libpwmd", LOCALEDIR);
172 #endif
173 gpg_err_init();
174 assuan_set_malloc_hooks(pwmd_malloc, pwmd_realloc, pwmd_free);
175 assuan_set_assuan_err_source(GPG_ERR_SOURCE_DEFAULT);
176 initialized = 1;
177 return 0;
180 static gpg_error_t _socket_connect_finalize(pwm_t *pwm)
182 int active[2];
183 int n = assuan_get_active_fds(pwm->ctx, 0, active, N_ARRAY(active));
185 pwm->fd = n <= 0 ? -1 : dup(active[0]);
186 #ifdef WITH_PINENTRY
187 pwm->pid = -1;
188 pwm->pinentry_tries = 3;
189 #endif
190 assuan_set_pointer(pwm->ctx, pwm);
192 if (pwm->name)
193 return pwmd_command(pwm, NULL, "OPTION CLIENT NAME=%s", pwm->name);
195 return 0;
198 #ifdef WITH_TCP
199 static int read_hook(assuan_context_t ctx, assuan_fd_t fd, void *data,
200 size_t len, ssize_t *ret)
202 pwm_t *pwm = assuan_get_pointer(ctx);
204 if (!pwm || !pwm->tcp_conn)
205 #ifdef WITH_LIBPTH
206 *ret = pth_read((int)fd, data, len);
207 #else
208 *ret = read((int)fd, data, len);
209 #endif
210 else {
211 do {
212 *ret = libssh2_channel_read(pwm->tcp_conn->channel, data, len);
213 } while (*ret == LIBSSH2_ERROR_EAGAIN);
216 return *ret <= 0 ? 0 : 1;
219 static int write_hook(assuan_context_t ctx, assuan_fd_t fd, const void *data,
220 size_t len, ssize_t *ret)
222 pwm_t *pwm = assuan_get_pointer(ctx);
224 if (!pwm || !pwm->tcp_conn)
225 #ifdef WITH_LIBPTH
226 *ret = pth_write((int)fd, data, len);
227 #else
228 *ret = write((int)fd, data, len);
229 #endif
230 else {
231 do {
232 *ret = libssh2_channel_write(pwm->tcp_conn->channel, data, len);
233 } while (*ret == LIBSSH2_ERROR_EAGAIN);
236 return *ret <= 0 ? 0 : 1;
239 static void _ssh_deinit(pwmd_tcp_conn_t *conn);
240 static void free_tcp_conn(pwmd_tcp_conn_t *conn)
242 if (!conn)
243 return;
245 if (conn->username) {
246 pwmd_free(conn->username);
247 conn->username = NULL;
250 if (conn->known_hosts) {
251 pwmd_free(conn->known_hosts);
252 conn->known_hosts = NULL;
255 if (conn->identity) {
256 pwmd_free(conn->identity);
257 conn->identity = NULL;
260 if (conn->identity_pub) {
261 pwmd_free(conn->identity_pub);
262 conn->identity_pub = NULL;
265 if (conn->host) {
266 pwmd_free(conn->host);
267 conn->host = NULL;
270 if (conn->hostkey) {
271 pwmd_free(conn->hostkey);
272 conn->hostkey = NULL;
275 if (conn->chan) {
276 ares_destroy(conn->chan);
277 conn->chan = NULL;
280 if (conn->he) {
281 ares_free_hostent(conn->he);
282 conn->he = NULL;
285 if (conn->fd >= 0) {
286 close(conn->fd);
287 conn->fd = -1;
290 if (conn->session)
291 _ssh_deinit(conn);
292 else
293 pwmd_free(conn);
296 static void _ssh_deinit(pwmd_tcp_conn_t *conn)
298 if (!conn)
299 return;
301 if (conn->channel)
302 libssh2_channel_free(conn->channel);
304 if (conn->session) {
305 libssh2_session_disconnect(conn->session, "Bye!");
306 libssh2_session_free(conn->session);
309 conn->session = NULL;
310 conn->channel = NULL;
311 free_tcp_conn(conn);
314 static void _ssh_assuan_deinit(assuan_context_t ctx)
316 pwm_t *pwm = assuan_get_pointer(ctx);
318 _ssh_deinit(pwm->tcp_conn);
319 pwm->tcp_conn = NULL;
323 * Sets common options from both pwmd_tcp_connect() and
324 * pwmd_tcp_connect_async().
326 static gpg_error_t init_tcp_conn(pwmd_tcp_conn_t **dst, const char *host,
327 int port, const char *identity, const char *user, const char *hosts,
328 int get)
330 pwmd_tcp_conn_t *conn;
331 gpg_error_t rc = 0;
333 if (get) {
334 if (!host)
335 return GPG_ERR_INV_ARG;
337 else {
338 if (!host || !identity || !hosts)
339 return GPG_ERR_INV_ARG;
342 conn = pwmd_calloc(1, sizeof(pwmd_tcp_conn_t));
344 if (!conn)
345 return gpg_error_from_errno(ENOMEM);
347 conn->port = port == -1 ? 22 : port;
348 conn->host = pwmd_strdup(host);
350 if (!conn->host) {
351 rc = gpg_error_from_errno(ENOMEM);
352 goto fail;
355 if (!get) {
356 struct passwd pw;
357 char *pwbuf = _getpwuid(&pw);
359 if (!pwbuf) {
360 rc = gpg_error_from_errno(errno);
361 goto fail;
364 conn->username = pwmd_strdup(user ? user : pw.pw_name);
365 pwmd_free(pwbuf);
367 if (!conn->username) {
368 rc = gpg_error_from_errno(ENOMEM);
369 goto fail;
372 conn->identity = pwmd_strdup(identity);
374 if (!conn->identity) {
375 rc = gpg_error_from_errno(ENOMEM);
376 goto fail;
379 conn->identity_pub = pwmd_malloc(strlen(conn->identity)+5);
381 if (!conn->identity_pub) {
382 rc = gpg_error_from_errno(ENOMEM);
383 goto fail;
386 sprintf(conn->identity_pub, "%s.pub", conn->identity);
387 conn->known_hosts = pwmd_strdup(hosts);
389 if (!conn->known_hosts) {
390 rc = gpg_error_from_errno(ENOMEM);
391 goto fail;
395 *dst = conn;
396 return 0;
398 fail:
399 free_tcp_conn(conn);
400 return rc;
403 static gpg_error_t do_connect(pwm_t *pwm, int prot, void *addr)
405 struct sockaddr_in their_addr;
407 pwm->tcp_conn->fd = socket(prot, SOCK_STREAM, 0);
409 if (pwm->tcp_conn->fd == -1)
410 return gpg_error_from_syserror();
412 if (pwm->tcp_conn->async)
413 fcntl(pwm->tcp_conn->fd, F_SETFL, O_NONBLOCK);
415 pwm->cmd = ASYNC_CMD_CONNECT;
416 their_addr.sin_family = prot;
417 their_addr.sin_port = htons(pwm->tcp_conn->port);
418 their_addr.sin_addr = *((struct in_addr *)addr);
419 memset(their_addr.sin_zero, '\0', sizeof their_addr.sin_zero);
421 #ifdef WITH_LIBPTH
422 if (pth_connect(pwm->tcp_conn->fd, (struct sockaddr *)&their_addr,
423 sizeof(their_addr)) == -1)
424 #else
425 if (connect(pwm->tcp_conn->fd, (struct sockaddr *)&their_addr,
426 sizeof(their_addr)) == -1)
427 #endif
428 return gpg_error_from_syserror();
430 return 0;
433 static gpg_error_t ares_error_to_pwmd(int status)
435 if (status != ARES_SUCCESS)
436 warnx("%s", ares_strerror(status));
438 switch (status) {
439 case ARES_ENODATA:
440 case ARES_EFORMERR:
441 case ARES_ENOTFOUND:
442 return GPG_ERR_UNKNOWN_HOST;
443 case ARES_ESERVFAIL:
444 return GPG_ERR_EHOSTDOWN;
445 case ARES_ETIMEOUT:
446 return GPG_ERR_TIMEOUT;
447 case ARES_ENOMEM:
448 return gpg_error_from_errno(ENOMEM);
449 case ARES_ECONNREFUSED:
450 return GPG_ERR_ECONNREFUSED;
451 default:
452 /* FIXME ??? */
453 return GPG_ERR_EHOSTUNREACH;
456 return ARES_SUCCESS;
459 static void dns_resolve_cb(void *arg, int status, int timeouts,
460 unsigned char *abuf, int alen)
462 pwm_t *pwm = arg;
463 int rc;
464 struct hostent *he;
466 if (status == ARES_EDESTRUCTION)
467 return;
469 if (status != ARES_SUCCESS) {
470 pwm->tcp_conn->rc = ares_error_to_pwmd(status);
471 return;
474 //FIXME localhost. works with ipv4. maybe local system config error
475 /* Check for an IPv6 address first. */
476 rc = ares_parse_a_reply(abuf, alen, &he, NULL, NULL);
478 if (rc != ARES_SUCCESS) {
479 if (rc != ARES_ENODATA) {
480 pwm->tcp_conn->rc = ares_error_to_pwmd(status);
481 return;
484 rc = ares_parse_aaaa_reply(abuf, alen, &he, NULL, NULL);
486 if (rc != ARES_SUCCESS) {
487 pwm->tcp_conn->rc = ares_error_to_pwmd(status);
488 return;
492 pwm->tcp_conn->he = he;
493 pwm->tcp_conn->rc = do_connect(pwm, he->h_addrtype, he->h_addr);
496 static gpg_error_t _do_pwmd_tcp_connect_async(pwm_t *pwm, const char *host,
497 int port, const char *identity, const char *user,
498 const char *known_hosts, pwmd_async_cmd_t which)
500 pwmd_tcp_conn_t *conn;
501 gpg_error_t rc;
503 rc = init_tcp_conn(&conn, host, port, identity, user, known_hosts,
504 which == ASYNC_CMD_HOSTKEY ? 1 : 0);
506 if (rc)
507 return rc;
509 conn->async = 1;
510 pwm->tcp_conn = conn;
511 pwm->tcp_conn->cmd = which;
513 if (pwm->tcp_conn->cmd == ASYNC_CMD_HOSTKEY)
514 pwm->tcp_conn->get_only = 1;
516 pwm->cmd = ASYNC_CMD_DNS;
517 pwm->state = ASYNC_PROCESS;
518 ares_init(&pwm->tcp_conn->chan);
519 ares_query(pwm->tcp_conn->chan, pwm->tcp_conn->host, ns_c_any, ns_t_any,
520 dns_resolve_cb, pwm);
521 return 0;
524 gpg_error_t pwmd_tcp_connect_async(pwm_t *pwm, const char *host, int port,
525 const char *identity, const char *user, const char *known_hosts)
527 return _do_pwmd_tcp_connect_async(pwm, host, port, identity, user,
528 known_hosts, ASYNC_CMD_CONNECT);
531 static void *_ssh_malloc(size_t size, void **data)
533 return pwmd_malloc(size);
536 static void _ssh_free(void *ptr, void **data)
538 pwmd_free(ptr);
541 static void *_ssh_realloc(void *ptr, size_t size, void **data)
543 return pwmd_realloc(ptr, size);
546 static char *to_hex(const char *str, size_t slen)
548 int i;
549 char *buf = pwmd_malloc(slen*2+1);
551 if (!buf)
552 return NULL;
554 for (i = 0, buf[0] = 0; i < slen; i++) {
555 char tmp[3];
557 sprintf(tmp, "%02x", (unsigned char)str[i]);
558 strcat(buf, tmp);
561 return buf;
564 static int verify_host_key(pwm_t *pwm)
566 FILE *fp = fopen(pwm->tcp_conn->known_hosts, "r");
567 char *buf, *p;
569 if (!fp)
570 return 1;
572 buf = pwmd_malloc(LINE_MAX);
574 if (!buf)
575 goto fail;
577 while ((p = fgets(buf, LINE_MAX, fp))) {
578 if (*p == '#' || isspace(*p))
579 continue;
581 if (p[strlen(p)-1] == '\n')
582 p[strlen(p)-1] = 0;
584 if (!strcmp(buf, pwm->tcp_conn->hostkey))
585 goto done;
588 fail:
589 if (buf)
590 pwmd_free(buf);
592 fclose(fp);
593 return 1;
595 done:
596 pwmd_free(buf);
597 fclose(fp);
598 return 0;
601 static gpg_error_t authenticate_ssh(pwm_t *pwm)
603 const char *fp = libssh2_hostkey_hash(pwm->tcp_conn->session,
604 LIBSSH2_HOSTKEY_HASH_SHA1);
605 char *userauth;
607 pwm->tcp_conn->hostkey = to_hex(fp, 20);
609 if (!pwm->tcp_conn->hostkey)
610 return gpg_error_from_errno(ENOMEM);
612 if (pwm->tcp_conn->get_only)
613 return 0;
615 if (!fp || verify_host_key(pwm))
616 return GPG_ERR_CHECKSUM;
618 userauth = libssh2_userauth_list(pwm->tcp_conn->session,
619 pwm->tcp_conn->username, strlen(pwm->tcp_conn->username));
621 if (!userauth || !strstr(userauth, "publickey"))
622 return GPG_ERR_BAD_PIN_METHOD;
624 if (libssh2_userauth_publickey_fromfile(pwm->tcp_conn->session,
625 pwm->tcp_conn->username, pwm->tcp_conn->identity_pub,
626 pwm->tcp_conn->identity, NULL))
627 return GPG_ERR_BAD_SECKEY;
629 return 0;
632 static gpg_error_t setup_tcp_session(pwm_t *pwm)
634 assuan_context_t ctx;
635 struct assuan_io_hooks io_hooks = {read_hook, write_hook};
636 gpg_error_t rc;
638 pwm->tcp_conn->session = libssh2_session_init_ex(_ssh_malloc, _ssh_free,
639 _ssh_realloc, NULL);
641 if (!pwm->tcp_conn->session) {
642 rc = gpg_error_from_errno(ENOMEM);
643 goto fail;
646 if (libssh2_session_startup(pwm->tcp_conn->session, pwm->tcp_conn->fd)) {
647 rc = GPG_ERR_ASSUAN_SERVER_FAULT;
648 goto fail;
651 rc = authenticate_ssh(pwm);
653 if (rc)
654 goto fail;
656 /* pwmd_get_hostkey(). */
657 if (pwm->tcp_conn->get_only) {
658 pwm->result = pwmd_strdup(pwm->tcp_conn->hostkey);
660 if (!pwm->result) {
661 rc = gpg_error_from_errno(ENOMEM);
662 goto fail;
665 return 0;
668 pwm->tcp_conn->channel = libssh2_channel_open_session(pwm->tcp_conn->session);
670 if (!pwm->tcp_conn->channel) {
671 rc = GPG_ERR_ASSUAN_SERVER_FAULT;
672 goto fail;
675 if (libssh2_channel_shell(pwm->tcp_conn->channel)) {
676 rc = GPG_ERR_ASSUAN_SERVER_FAULT;
677 goto fail;
680 assuan_set_io_hooks(&io_hooks);
681 rc = assuan_socket_connect_fd(&ctx, pwm->tcp_conn->fd, 0, pwm);
683 if (rc)
684 goto fail;
686 assuan_set_finish_handler(ctx, _ssh_assuan_deinit);
687 pwm->ctx = ctx;
688 return _socket_connect_finalize(pwm);
690 fail:
691 free_tcp_conn(pwm->tcp_conn);
692 pwm->tcp_conn = NULL;
693 return rc;
696 static gpg_error_t _do_pwmd_tcp_connect(pwm_t *pwm, const char *host, int port,
697 const char *identity, const char *user, const char *known_hosts, int get)
699 pwmd_tcp_conn_t *conn;
700 gpg_error_t rc;
702 rc = init_tcp_conn(&conn, host, port, identity, user, known_hosts, get);
704 if (rc)
705 return rc;
707 pwm->tcp_conn = conn;
708 pwm->tcp_conn->get_only = get;
709 pwm->cmd = ASYNC_CMD_DNS;
710 ares_init(&pwm->tcp_conn->chan);
711 ares_query(pwm->tcp_conn->chan, pwm->tcp_conn->host, ns_c_any, ns_t_any,
712 dns_resolve_cb, pwm);
714 /* dns_resolve_cb() may have already been called. */
715 if (pwm->tcp_conn->rc) {
716 rc = pwm->tcp_conn->rc;
717 goto fail;
721 * Fake a blocking DNS lookup. libcares does a better job than
722 * getaddrinfo().
724 do {
725 fd_set rfds, wfds;
726 int n;
727 struct timeval tv;
729 FD_ZERO(&rfds);
730 FD_ZERO(&wfds);
731 n = ares_fds(pwm->tcp_conn->chan, &rfds, &wfds);
732 ares_timeout(pwm->tcp_conn->chan, NULL, &tv);
733 #ifdef WITH_LIBPTH
734 n = pth_select(n, &rfds, &wfds, NULL, &tv);
735 #else
736 n = select(n, &rfds, &wfds, NULL, &tv);
737 #endif
739 if (n == -1) {
740 rc = gpg_error_from_syserror();
741 goto fail;
743 else if (n == 0) {
744 rc = GPG_ERR_TIMEOUT;
745 goto fail;
748 ares_process(pwm->tcp_conn->chan, &rfds, &wfds);
750 if (pwm->tcp_conn->rc)
751 break;
752 } while (pwm->cmd == ASYNC_CMD_DNS);
754 if (pwm->tcp_conn->rc) {
755 rc = pwm->tcp_conn->rc;
756 goto fail;
759 return setup_tcp_session(pwm);
761 fail:
762 return rc;
765 gpg_error_t pwmd_tcp_connect(pwm_t *pwm, const char *host, int port,
766 const char *identity, const char *user, const char *known_hosts)
768 return _do_pwmd_tcp_connect(pwm, host, port, identity, user, known_hosts, 0);
771 /* Must free the result with pwmd_free(). */
772 gpg_error_t pwmd_get_hostkey(const char *host, int port, char **result)
774 char *hostkey;
775 pwm_t *pwm = pwmd_new(NULL);
776 gpg_error_t rc;
778 if (!pwm)
779 return gpg_error_from_errno(ENOMEM);
781 rc = _do_pwmd_tcp_connect(pwm, host, port, NULL, NULL, NULL, 1);
783 if (rc) {
784 pwmd_close(pwm);
785 return rc;
788 hostkey = pwmd_strdup(pwm->tcp_conn->hostkey);
790 if (!hostkey)
791 rc = gpg_error_from_errno(ENOMEM);
793 pwmd_close(pwm);
794 *result = hostkey;
795 return rc;
798 gpg_error_t pwmd_get_hostkey_async(pwm_t *pwm, const char *host, int port)
800 return _do_pwmd_tcp_connect_async(pwm, host, port, NULL, NULL, NULL,
801 ASYNC_CMD_HOSTKEY);
803 #endif
805 gpg_error_t pwmd_connect(pwm_t *pwm, const char *path)
807 char *socketpath = NULL;
808 assuan_context_t ctx;
809 struct passwd pw;
810 char *pwbuf = _getpwuid(&pw);
811 gpg_error_t rc;
813 if (!pwbuf)
814 return gpg_error_from_errno(errno);
816 if (!path) {
817 socketpath = (char *)pwmd_malloc(strlen(pw.pw_dir) + strlen("/.pwmd/socket") + 1);
818 sprintf(socketpath, "%s/.pwmd/socket", pw.pw_dir);
820 else
821 socketpath = pwmd_strdup(path);
823 pwmd_free(pwbuf);
824 rc = assuan_socket_connect_ext(&ctx, socketpath, -1, 0);
825 pwmd_free(socketpath);
827 if (rc)
828 return rc;
830 pwm->ctx = ctx;
831 return _socket_connect_finalize(pwm);
834 void pwmd_close(pwm_t *pwm)
836 if (!pwm)
837 return;
839 if (pwm->ctx)
840 assuan_disconnect(pwm->ctx);
842 if (pwm->password)
843 pwmd_free(pwm->password);
845 if (pwm->title)
846 pwmd_free(pwm->title);
848 if (pwm->desc)
849 pwmd_free(pwm->desc);
851 if (pwm->prompt)
852 pwmd_free(pwm->prompt);
854 if (pwm->pinentry_tty)
855 pwmd_free(pwm->pinentry_tty);
857 if (pwm->pinentry_display)
858 pwmd_free(pwm->pinentry_display);
860 if (pwm->pinentry_term)
861 pwmd_free(pwm->pinentry_term);
863 if (pwm->lcctype)
864 pwmd_free(pwm->lcctype);
866 if (pwm->lcmessages)
867 pwmd_free(pwm->lcmessages);
869 if (pwm->filename)
870 pwmd_free(pwm->filename);
872 if (pwm->name)
873 pwmd_free(pwm->name);
875 #ifdef WITH_TCP
876 if (pwm->tcp_conn)
877 free_tcp_conn(pwm->tcp_conn);
878 #endif
880 pwmd_free(pwm);
883 static int mem_realloc_cb(void *data, const void *buffer, size_t len)
885 membuf_t *mem = (membuf_t *)data;
886 void *p;
888 if (!buffer)
889 return 0;
891 if ((p = pwmd_realloc(mem->buf, mem->len + len)) == NULL)
892 return 1;
894 mem->buf = p;
895 memcpy((char *)mem->buf + mem->len, buffer, len);
896 mem->len += len;
897 return 0;
900 static int _inquire_cb(void *data, const char *keyword)
902 pwm_t *pwm = (pwm_t *)data;
903 gpg_error_t rc = 0;
904 int flags = fcntl(pwm->fd, F_GETFL);
906 /* Shouldn't get this far without a callback. */
907 if (!pwm->inquire_func)
908 return GPG_ERR_INV_ARG;
911 * Since the socket file descriptor is probably set to non-blocking, set to
912 * blocking to prevent GPG_ERR_EAGAIN errors. This should be fixes when
913 * asynchronous INQUIRE is supported by either libassuan or a later
914 * libpwmd.
916 fcntl(pwm->fd, F_SETFL, 0);
918 for (;;) {
919 char *result = NULL;
920 size_t len;
921 gpg_error_t arc;
923 rc = pwm->inquire_func(pwm->inquire_data, keyword, rc, &result, &len);
924 rc = gpg_err_code(rc);
926 if (rc == GPG_ERR_EOF || !rc) {
927 if (len <= 0 || !result || !*result) {
928 rc = 0;
929 break;
932 arc = assuan_send_data(pwm->ctx, result, len);
934 if (rc == GPG_ERR_EOF) {
935 rc = arc;
936 break;
939 rc = arc;
941 else if (rc)
942 break;
945 fcntl(pwm->fd, F_SETFL, flags);
946 return rc;
949 static gpg_error_t do_nb_command(pwm_t *pwm, const char *cmd, const char *arg)
951 char *buf;
952 gpg_error_t rc;
953 size_t len = strlen(cmd) + 2;
955 len += arg ? strlen(arg) : 0;
957 if (pwm->state == ASYNC_DONE)
958 pwm->state = ASYNC_INIT;
960 if (pwm->state != ASYNC_INIT)
961 return GPG_ERR_INV_STATE;
963 buf = (char *)pwmd_malloc(len);
965 if (!buf) {
966 rc = gpg_error_from_errno(ENOMEM);
967 goto fail;
970 snprintf(buf, len, "%s %s", cmd, arg ? arg : "");
971 rc = assuan_write_line(pwm->ctx, buf);
972 pwmd_free(buf);
974 if (!rc)
975 pwm->state = ASYNC_PROCESS;
977 fail:
978 return rc;
981 gpg_error_t pwmd_open_async(pwm_t *pwm, const char *filename)
983 if (!pwm || !filename)
984 return GPG_ERR_INV_ARG;
986 /* For pinentry retries. */
987 if (!pwm->is_open_cmd) {
988 if (pwm->filename)
989 pwmd_free(pwm->filename);
991 pwm->filename = pwmd_strdup(filename);
994 pwm->is_open_cmd = 1;
995 pwm->cmd = ASYNC_CMD_OPEN;
996 return do_nb_command(pwm, "OPEN", filename);
999 gpg_error_t pwmd_save_async(pwm_t *pwm)
1001 if (!pwm)
1002 return GPG_ERR_INV_ARG;
1004 pwm->cmd = ASYNC_CMD_SAVE;
1005 return do_nb_command(pwm, "SAVE", NULL);
1008 static gpg_error_t parse_assuan_line(pwm_t *pwm)
1010 gpg_error_t rc;
1011 char *line;
1012 size_t len;
1014 rc = assuan_read_line(pwm->ctx, &line, &len);
1016 if (!rc) {
1017 if (line[0] == 'O' && line[1] == 'K' &&
1018 (line[2] == 0 || line[2] == ' ')) {
1019 pwm->state = ASYNC_DONE;
1021 else if (line[0] == '#') {
1023 else if (line[0] == 'S' && (line[1] == 0 || line[1] == ' ')) {
1024 if (pwm->status_func) {
1025 pwm->status_func(pwm->status_data,
1026 line[1] == 0 ? line+1 : line+2);
1029 else if (line[0] == 'E' && line[1] == 'R' && line[2] == 'R' &&
1030 (line[3] == 0 || line[3] == ' ')) {
1031 line += 4;
1032 rc = atoi(line);
1033 pwm->state = ASYNC_DONE;
1037 return rc;
1040 gpg_error_t pwmd_pending_line(pwm_t *pwm)
1042 if (!pwm)
1043 return GPG_ERR_INV_ARG;
1045 if (!pwm->ctx)
1046 return GPG_ERR_INV_STATE;
1048 return assuan_pending_line(pwm->ctx) ? 0 : GPG_ERR_NO_DATA;
1051 static pwmd_async_t reset_async(pwm_t *pwm)
1053 pwm->state = ASYNC_INIT;
1054 pwm->cmd = ASYNC_CMD_NONE;
1055 pwm->ntries = 0;
1056 #ifdef WITH_PINENTRY
1057 pwm->is_open_cmd = 0;
1059 if (pwm->nb_fd != -1) {
1060 close(pwm->nb_fd);
1061 pwm->nb_fd = -1;
1063 #endif
1064 #ifdef WITH_TCP
1065 if (pwm->tcp_conn && pwm->tcp_conn->fd != -1) {
1066 close(pwm->tcp_conn->fd);
1067 pwm->tcp_conn->fd = -1;
1069 #endif
1071 return ASYNC_DONE;
1074 pwmd_async_t pwmd_process(pwm_t *pwm, gpg_error_t *rc, char **result)
1076 fd_set fds;
1077 int n;
1078 struct timeval tv = {0, 0};
1080 *rc = 0;
1082 if (!pwm) {
1083 *rc = GPG_ERR_INV_ARG;
1084 return ASYNC_DONE;
1087 /* When not in a command, this will let libassuan process status messages
1088 * by calling PWMD_OPTION_STATUS_FUNC. The client can poll the file
1089 * descriptor returned by pwmd_get_fd() to determine when this should be
1090 * called or call pwmd_pending_line() to determine whether a buffered line
1091 * needs to be processed. */
1092 if (pwm->cmd == ASYNC_CMD_NONE) {
1093 *rc = assuan_command(pwm, pwm->ctx, NULL, "NOP");
1094 return pwm->state;
1097 /* Fixes pwmd_open/save_async2() when there is a cached or new file. */
1098 if (pwm->state == ASYNC_DONE) {
1099 reset_async(pwm);
1100 return ASYNC_DONE;
1103 if (pwm->state != ASYNC_PROCESS) {
1104 *rc = GPG_ERR_INV_STATE;
1105 return ASYNC_DONE;
1108 #ifdef WITH_TCP
1109 if (pwm->cmd == ASYNC_CMD_DNS) {
1110 fd_set rfds, wfds;
1112 if (pwm->tcp_conn->rc) {
1113 *rc = pwm->tcp_conn->rc;
1114 reset_async(pwm);
1115 return ASYNC_DONE;
1118 FD_ZERO(&rfds);
1119 FD_ZERO(&wfds);
1120 n = ares_fds(pwm->tcp_conn->chan, &rfds, &wfds);
1122 /* Shouldn't happen. */
1123 if (!n)
1124 return pwm->state;
1126 #ifdef WITH_LIBPTH
1127 n = pth_select(n, &rfds, &wfds, NULL, &tv);
1128 #else
1129 n = select(n, &rfds, &wfds, NULL, &tv);
1130 #endif
1132 if (n > 0)
1133 ares_process(pwm->tcp_conn->chan, &rfds, &wfds);
1135 return pwm->state;
1137 else if (pwm->cmd == ASYNC_CMD_CONNECT) {
1138 if (pwm->tcp_conn->rc == GPG_ERR_EINPROGRESS) {
1139 int ret;
1140 socklen_t len = sizeof(int);
1142 FD_ZERO(&fds);
1143 FD_SET(pwm->tcp_conn->fd, &fds);
1144 #ifdef WITH_LIBPTH
1145 n = pth_select(pwm->tcp_conn->fd+1, NULL, &fds, NULL, &tv);
1146 #else
1147 n = select(pwm->tcp_conn->fd+1, NULL, &fds, NULL, &tv);
1148 #endif
1150 if (!n || !FD_ISSET(pwm->tcp_conn->fd, &fds))
1151 return pwm->state;
1152 else if (n == -1) {
1153 *rc = gpg_error_from_syserror();
1154 reset_async(pwm);
1155 return ASYNC_DONE;
1158 ret = getsockopt(pwm->tcp_conn->fd, SOL_SOCKET, SO_ERROR, &n, &len);
1160 if (ret || n) {
1161 *rc = ret ? gpg_error_from_syserror() : gpg_error_from_errno(n);
1162 reset_async(pwm);
1163 return ASYNC_DONE;
1166 else if (pwm->tcp_conn->rc) {
1167 *rc = pwm->tcp_conn->rc;
1168 reset_async(pwm);
1169 return ASYNC_DONE;
1172 fcntl(pwm->tcp_conn->fd, F_SETFL, 0);
1173 *rc = setup_tcp_session(pwm);
1175 switch (pwm->tcp_conn->cmd) {
1176 case ASYNC_CMD_HOSTKEY:
1177 if (!*rc)
1178 *result = pwm->result;
1179 break;
1180 default:
1181 break;
1184 return reset_async(pwm);
1186 #endif
1188 #ifdef WITH_PINENTRY
1189 if (pwm->cmd == ASYNC_CMD_OPEN2 || pwm->cmd == ASYNC_CMD_SAVE2) {
1190 if (pwm->nb_fd == -1) {
1191 *rc = GPG_ERR_INV_STATE;
1192 return reset_async(pwm);
1195 FD_ZERO(&fds);
1196 FD_SET(pwm->nb_fd, &fds);
1197 #ifdef WITH_LIBPTH
1198 n = pth_select(pwm->nb_fd+1, &fds, NULL, NULL, &tv);
1199 #else
1200 n = select(pwm->nb_fd+1, &fds, NULL, NULL, &tv);
1201 #endif
1202 if (n == -1) {
1203 *rc = gpg_error_from_syserror();
1204 return reset_async(pwm);
1207 if (n > 0) {
1208 pwmd_nb_status_t nb;
1209 size_t len = read(pwm->nb_fd, &nb, sizeof(nb));
1211 *rc = nb.error;
1212 return reset_async(pwm);
1215 return pwm->state;
1217 #endif
1219 if (pwm->fd < 0) {
1220 *rc = GPG_ERR_INV_STATE;
1221 return reset_async(pwm);
1224 /* This is for the non-blocking OPEN and SAVE commands. */
1225 FD_ZERO(&fds);
1226 FD_SET(pwm->fd, &fds);
1227 #ifdef WITH_LIBPTH
1228 n = pth_select(pwm->fd+1, &fds, NULL, NULL, &tv);
1229 #else
1230 n = select(pwm->fd+1, &fds, NULL, NULL, &tv);
1231 #endif
1233 if (n == -1) {
1234 *rc = gpg_error_from_syserror();
1235 return reset_async(pwm);
1238 if (n > 0) {
1239 if (FD_ISSET(pwm->fd, &fds)) {
1240 *rc = parse_assuan_line(pwm);
1242 if (*rc)
1243 return reset_async(pwm);
1247 while (!*rc && assuan_pending_line(pwm->ctx))
1248 *rc = parse_assuan_line(pwm);
1250 if (*rc)
1251 return reset_async(pwm);
1253 /* For pinentry retries. */
1254 if (pwm->is_open_cmd && gpg_err_code(*rc) == EPWMD_BADKEY &&
1255 ++pwm->ntries < pwm->pinentry_tries) {
1256 pwm->state = ASYNC_INIT;
1257 *rc = pwmd_open_async(pwm, pwm->filename);
1260 if (*rc)
1261 return reset_async(pwm);
1263 if (pwm->state == ASYNC_DONE) {
1264 reset_async(pwm);
1265 return ASYNC_DONE;
1268 return pwm->state;
1271 static gpg_error_t assuan_command(pwm_t *pwm, assuan_context_t ctx,
1272 char **result, const char *cmd)
1274 membuf_t data;
1275 gpg_error_t rc;
1277 data.len = 0;
1278 data.buf = NULL;
1280 rc = assuan_transact(ctx, cmd, mem_realloc_cb, &data, _inquire_cb, pwm,
1281 pwm->status_func, pwm->status_data);
1283 if (rc) {
1284 if (data.buf) {
1285 pwmd_free(data.buf);
1286 data.buf = NULL;
1289 else {
1290 if (data.buf) {
1291 mem_realloc_cb(&data, "", 1);
1293 if (!result) {
1294 pwmd_free(data.buf);
1295 rc = GPG_ERR_INV_ARG;
1297 else
1298 *result = (char *)data.buf;
1302 return gpg_err_code(rc);
1305 gpg_error_t pwmd_inquire(pwm_t *pwm, const char *cmd, pwmd_inquire_fn fn,
1306 void *data)
1308 if (!pwm || !cmd || !fn)
1309 return GPG_ERR_INV_ARG;
1311 pwm->inquire_func = fn;
1312 pwm->inquire_data = data;
1313 return assuan_command(pwm, pwm->ctx, NULL, cmd);
1316 static gpg_error_t terminate_pinentry(pwm_t *pwm)
1318 #ifndef WITH_PINENTRY
1319 return GPG_ERR_NOT_IMPLEMENTED;
1320 #else
1321 pid_t pid = pwm->pid;
1323 pwm->pid = -1;
1325 if (!pwm || pid == -1)
1326 return GPG_ERR_INV_ARG;
1328 if (kill(pid, 0) == 0) {
1329 if (kill(pid, SIGTERM) == -1) {
1330 if (kill(pid, SIGKILL) == -1)
1331 return gpg_error_from_errno(errno);
1334 else
1335 return gpg_error_from_errno(errno);
1337 return 0;
1338 #endif
1341 #ifdef WITH_PINENTRY
1342 static gpg_error_t set_pinentry_strings(pwm_t *pwm, int which)
1344 char *buf;
1345 char tmp[ASSUAN_LINELENGTH];
1346 gpg_error_t error;
1348 if (!pwm->title)
1349 pwm->title = pwmd_strdup(N_("LibPWMD"));
1351 if (!pwm->prompt)
1352 pwm->prompt = pwmd_strdup(N_("Passphrase:"));
1354 if (!pwm->desc && !which)
1355 pwm->desc = pwmd_strdup(N_("Enter a passphrase."));
1357 if (which == 1) {
1358 snprintf(tmp, sizeof(tmp), "SETERROR %s", N_("Invalid passphrase, please try again."));
1359 buf = pwmd_strdup(tmp);
1361 else if (which == 2) {
1362 snprintf(tmp, sizeof(tmp), "SETERROR %s", N_("Please type the passphrase again for confirmation."));
1363 buf = pwmd_strdup(tmp);
1365 else {
1366 buf = (char *)pwmd_malloc(strlen("SETERROR ") + strlen(pwm->desc) + 1);
1367 sprintf(buf, "SETERROR %s", pwm->desc);
1370 error = pinentry_command(pwm, NULL, buf);
1371 pwmd_free(buf);
1373 if (error)
1374 return error;
1376 buf = (char *)pwmd_malloc(strlen("SETPROMPT ") + strlen(pwm->prompt) + 1);
1377 sprintf(buf, "SETPROMPT %s", pwm->prompt);
1378 error = pinentry_command(pwm, NULL, buf);
1379 pwmd_free(buf);
1381 if (error)
1382 return error;
1384 buf = (char *)pwmd_malloc(strlen("SETDESC ") + strlen(pwm->title) + 1);
1385 sprintf(buf, "SETDESC %s", pwm->title);
1386 error = pinentry_command(pwm, NULL, buf);
1387 pwmd_free(buf);
1388 return error;
1391 static void update_pinentry_settings(pwm_t *pwm)
1393 FILE *fp;
1394 char buf[LINE_MAX];
1395 char *p;
1396 struct passwd pw;
1397 char *pwbuf = _getpwuid(&pw);
1399 if (!pwbuf)
1400 return;
1402 snprintf(buf, sizeof(buf), "%s/.pwmd/pinentry.conf", pw.pw_dir);
1403 pwmd_free(pwbuf);
1405 if ((fp = fopen(buf, "r")) == NULL)
1406 return;
1408 while ((p = fgets(buf, sizeof(buf), fp)) != NULL) {
1409 char name[32], val[256];
1411 if (sscanf(p, " %31[a-zA-Z] = %255s", name, val) != 2)
1412 continue;
1414 if (strcasecmp(name, "TTYNAME") == 0) {
1415 pwmd_free(pwm->pinentry_tty);
1416 pwm->pinentry_tty = pwmd_strdup(val);
1418 else if (strcasecmp(name, "TTYTYPE") == 0) {
1419 pwmd_free(pwm->pinentry_term);
1420 pwm->pinentry_term = pwmd_strdup(val);
1422 else if (strcasecmp(name, "DISPLAY") == 0) {
1423 pwmd_free(pwm->pinentry_display);
1424 pwm->pinentry_display = pwmd_strdup(val);
1426 else if (strcasecmp(name, "PATH") == 0) {
1427 pwmd_free(pwm->pinentry_path);
1428 pwm->pinentry_path = pwmd_strdup(val);
1432 fclose(fp);
1435 static gpg_error_t launch_pinentry(pwm_t *pwm)
1437 int rc;
1438 assuan_context_t ctx;
1439 int child_list[] = {-1};
1440 char *display = getenv("DISPLAY");
1441 const char *argv[10];
1442 const char **p = argv;
1443 int have_display = 0;
1444 char *tty = NULL;
1445 char *ttybuf = NULL;
1447 update_pinentry_settings(pwm);
1449 if (pwm->pinentry_display || display)
1450 have_display = 1;
1451 else {
1452 if (!pwm->pinentry_tty) {
1453 ttybuf = pwmd_malloc(255);
1455 if (!ttybuf)
1456 return gpg_error_from_errno(ENOMEM);
1458 rc = ttyname_r(STDOUT_FILENO, ttybuf, 255);
1460 if (rc) {
1461 pwmd_free(ttybuf);
1462 return gpg_error_from_errno(rc);
1465 tty = ttybuf;
1467 else
1468 tty = pwm->pinentry_tty;
1471 if (!have_display && !tty)
1472 return GPG_ERR_ENOTTY;
1474 *p++ = "pinentry";
1475 *p++ = have_display ? "--display" : "--ttyname";
1476 *p++ = have_display ? pwm->pinentry_display ? pwm->pinentry_display : display : tty;
1478 if (pwm->lcctype) {
1479 *p++ = "--lc-ctype";
1480 *p++ = pwm->lcctype;
1483 if (pwm->lcmessages) {
1484 *p++ = "--lc-messages";
1485 *p++ = pwm->lcmessages;
1488 *p = NULL;
1490 if (!have_display) {
1491 *p++ = "--ttytype";
1492 *p++ = pwm->pinentry_term ? pwm->pinentry_term : getenv("TERM");
1493 *p = NULL;
1496 rc = assuan_pipe_connect(&ctx, pwm->pinentry_path ? pwm->pinentry_path : PINENTRY_PATH, argv, child_list);
1498 if (ttybuf)
1499 pwmd_free(ttybuf);
1501 if (rc)
1502 return rc;
1504 pwm->pid = assuan_get_pid(ctx);
1505 pwm->pctx = ctx;
1506 return set_pinentry_strings(pwm, 0);
1509 static gpg_error_t pinentry_command(pwm_t *pwm, char **result, const char *cmd)
1511 gpg_error_t n;
1513 if (!pwm->pctx) {
1514 n = launch_pinentry(pwm);
1516 if (n)
1517 return n;
1520 return assuan_command(pwm, pwm->pctx, result, cmd);
1523 static void pinentry_disconnect(pwm_t *pwm)
1525 if (pwm->pctx)
1526 assuan_disconnect(pwm->pctx);
1528 pwm->pctx = NULL;
1529 pwm->pid = -1;
1533 * Only called from a child process.
1535 static void catchsig(int sig)
1537 switch (sig) {
1538 case SIGALRM:
1539 if (gelapsed++ >= gtimeout)
1540 terminate_pinentry(gpwm);
1541 else
1542 alarm(1);
1543 break;
1544 default:
1545 break;
1548 #endif
1551 * Borrowed from libassuan.
1553 static char *percent_escape(const char *atext)
1555 const unsigned char *s;
1556 int len = strlen(atext) * 3 + 1;
1557 char *buf = (char *)pwmd_malloc(len), *p = buf;
1559 if (!buf)
1560 return NULL;
1562 for (s=(const unsigned char *)atext; *s; s++) {
1563 if (*s < ' ') {
1564 sprintf (p, "%%%02X", *s);
1565 p += 3;
1567 else
1568 *p++ = *s;
1571 *p = 0;
1572 return buf;
1575 static gpg_error_t send_command(pwm_t *pwm, char **result, const char *cmd)
1577 if (!cmd)
1578 return GPG_ERR_INV_ARG;
1580 return assuan_command(pwm, pwm->ctx, result, cmd);
1583 gpg_error_t pwmd_command_ap(pwm_t *pwm, char **result, const char *cmd,
1584 va_list ap)
1586 char *buf;
1587 size_t len;
1588 gpg_error_t error;
1590 if (!pwm || !cmd)
1591 return GPG_ERR_INV_ARG;
1594 * C99 allows the dst pointer to be null which will calculate the length
1595 * of the would-be result and return it.
1597 len = vsnprintf(NULL, 0, cmd, ap)+1;
1598 buf = (char *)pwmd_malloc(len);
1599 len = vsnprintf(buf, len, cmd, ap);
1600 error = send_command(pwm, result, buf);
1601 pwmd_free(buf);
1602 return error;
1606 * Avoid sending the BYE command here. libassuan will close the file
1607 * descriptor and release the assuan context. Use pwmd_close() instead.
1609 gpg_error_t pwmd_command(pwm_t *pwm, char **result, const char *cmd, ...)
1611 va_list ap;
1612 gpg_error_t error;
1614 if (!pwm || !cmd)
1615 return GPG_ERR_INV_ARG;
1617 if (result)
1618 *result = NULL;
1620 va_start(ap, cmd);
1621 error = pwmd_command_ap(pwm, result, cmd, ap);
1622 va_end(ap);
1623 return error;
1626 #ifdef WITH_PINENTRY
1627 static gpg_error_t do_getpin(pwm_t *pwm, char **result)
1629 if (gtimeout) {
1630 signal(SIGALRM, catchsig);
1631 alarm(1);
1634 *result = NULL;
1635 return pinentry_command(pwm, result, "GETPIN");
1638 static gpg_error_t getpin(pwm_t *pwm, char **result, int *try_n, int which)
1640 int pin_try = *try_n;
1641 gpg_error_t error;
1643 getpin_again:
1644 *try_n = pin_try;
1646 if (pin_try == -1) {
1647 error = set_pinentry_strings(pwm, which);
1649 if (error) {
1650 pinentry_disconnect(pwm);
1651 return error;
1654 else {
1655 if (pwm->pinentry_tries-1 != pin_try) {
1656 error = set_pinentry_strings(pwm, 1);
1658 if (error) {
1659 pinentry_disconnect(pwm);
1660 return error;
1665 error = do_getpin(pwm, result);
1668 * Since there was input cancel any timeout setting.
1670 alarm(0);
1672 if (error) {
1673 if (error == GPG_ERR_CANCELED)
1674 return GPG_ERR_CANCELED;
1676 if (pin_try != -1 && pin_try--)
1677 goto getpin_again;
1679 if (pwm->pctx)
1680 pinentry_disconnect(pwm);
1682 *try_n = pin_try;
1683 return error;
1686 return 0;
1688 #endif
1690 static gpg_error_t do_open_command(pwm_t *pwm, const char *filename, char *password)
1692 char buf[ASSUAN_LINELENGTH];
1693 gpg_error_t error;
1694 char *result = NULL;
1696 snprintf(buf, sizeof(buf), "OPEN %s %s", filename, password ? password : "");
1697 error = send_command(pwm, &result, buf);
1698 memset(buf, 0, sizeof(buf));
1700 if (error && result)
1701 pwmd_free(result);
1703 return error;
1706 static gpg_error_t do_pwmd_open(pwm_t *pwm, const char *filename, int nb)
1708 char *result = NULL;
1709 char *password = NULL;
1710 char path[PATH_MAX];
1711 #ifdef WITH_PINENTRY
1712 int pin_try;
1713 #endif
1714 gpg_error_t rc;
1716 if (!pwm || !filename || !*filename)
1717 return GPG_ERR_INV_ARG;
1719 #ifdef WITH_PINENTRY
1720 pin_try = pwm->pinentry_tries - 1;
1721 #endif
1724 * Avoid calling pinentry if the password is cached on the server or if
1725 * this is a new file.
1727 rc = pwmd_command(pwm, &result, "GETCONFIG data_directory");
1729 if (rc)
1730 return rc;
1732 snprintf(path, sizeof(path), "%s/%s", result, filename);
1733 pwmd_free(result);
1735 if (access(path, R_OK) == -1) {
1736 if (errno == ENOENT)
1737 goto gotpassword;
1740 rc = pwmd_command(pwm, &result, "ISCACHED %s", filename);
1742 if (rc == EPWMD_CACHE_NOT_FOUND) {
1743 if (pwm->passfunc) {
1744 password = (char *)pwm->passfunc(pwm->passdata);
1745 goto gotpassword;
1748 #ifdef WITH_PINENTRY
1750 * Get the password from pinentry.
1752 if (pwm->use_pinentry) {
1754 * Nonblocking is wanted. fork() then return a file descriptor
1755 * that the client can use to read() from.
1757 if (nb) {
1758 int p[2];
1759 pid_t pid;
1760 pwmd_nb_status_t pw;
1762 if (pipe(p) == -1)
1763 return gpg_error_from_syserror();
1765 #ifdef WITH_LIBPTH
1766 pid = pth_fork();
1767 #else
1768 pid = fork();
1769 #endif
1771 switch (pid) {
1772 case 0:
1773 close(p[0]);
1774 pw.fd = p[0];
1776 if (pwm->pinentry_timeout > 0) {
1777 gpwm = pwm;
1778 gtimeout = pwm->pinentry_timeout;
1779 gelapsed = 0;
1782 getpin_nb_again:
1783 rc = getpin(pwm, &password, &pin_try, 0);
1785 if (rc) {
1786 getpin_nb_fail:
1787 if (pwm->pctx)
1788 pinentry_disconnect(pwm);
1790 if (gtimeout && gelapsed >= gtimeout)
1791 rc = GPG_ERR_TIMEOUT;
1793 pw.error = rc;
1794 #ifdef WITH_LIBPTH
1795 pth_write(p[1], &pw, sizeof(pw));
1796 #else
1797 write(p[1], &pw, sizeof(pw));
1798 #endif
1799 close(p[1]);
1800 _exit(1);
1804 * Don't count the time it takes to open the file
1805 * which may have many iterations.
1807 signal(SIGALRM, SIG_DFL);
1808 rc = do_open_command(pwm, filename, password);
1810 if (pwm->pinentry_timeout)
1811 signal(SIGALRM, catchsig);
1813 if (pwm->pctx && rc == EPWMD_BADKEY) {
1814 if (pin_try-- > 0)
1815 goto getpin_nb_again;
1817 goto getpin_nb_fail;
1820 pinentry_disconnect(pwm);
1821 pw.error = 0;
1822 #ifdef WITH_LIBPTH
1823 pth_write(p[1], &pw, sizeof(pw));
1824 #else
1825 write(p[1], &pw, sizeof(pw));
1826 #endif
1827 close(p[1]);
1828 _exit(0);
1829 break;
1830 case -1:
1831 rc = gpg_error_from_syserror();
1832 close(p[0]);
1833 close(p[1]);
1834 return rc;
1835 default:
1836 break;
1839 close(p[1]);
1840 pwm->nb_fd = p[0];
1841 return 0;
1844 else {
1845 #endif
1847 * Not using pinentry and the file was not found
1848 * in the cache.
1850 password = pwm->password;
1851 #ifdef WITH_PINENTRY
1853 #endif
1855 else if (rc)
1856 return rc;
1858 gotpassword:
1859 rc = do_open_command(pwm, filename, password);
1862 * Keep the user defined password set with pwmd_setopt(). The password may
1863 * be needed later (pwmd_save()) depending on the pwmd file cache settings.
1865 if (!pwm->passfunc && password && password != pwm->password)
1866 pwmd_free(password);
1868 #ifdef WITH_PINENTRY
1869 if (rc == EPWMD_BADKEY) {
1870 if (pin_try-- > 0 && !nb) {
1871 rc = pwmd_command(pwm, &result, "OPTION TITLE=%s",
1872 N_("Invalid passphrase, please try again."));
1874 if (rc)
1875 return rc;
1877 goto gotpassword;
1880 if (nb)
1881 pinentry_disconnect(pwm);
1883 return rc;
1885 #endif
1887 if (!rc) {
1888 if (pwm->filename)
1889 pwmd_free(pwm->filename);
1891 pwm->filename = pwmd_strdup(filename);
1894 return rc;
1897 gpg_error_t pwmd_open(pwm_t *pwm, const char *filename)
1899 return do_pwmd_open(pwm, filename, 0);
1902 gpg_error_t pwmd_open_async2(pwm_t *pwm, const char *filename)
1904 #ifndef WITH_PINENTRY
1905 return GPG_ERR_NOT_IMPLEMENTED;
1906 #else
1907 gpg_error_t rc;
1909 pwm->cmd = ASYNC_CMD_OPEN2;
1910 pwm->state = ASYNC_PROCESS;
1911 rc = do_pwmd_open(pwm, filename, 1);
1913 if (rc)
1914 reset_async(pwm);
1916 return rc;
1917 #endif
1920 #ifdef WITH_PINENTRY
1921 static gpg_error_t do_save_getpin(pwm_t *pwm, char **password)
1923 int confirm = 0;
1924 gpg_error_t error;
1925 char *result = NULL;
1926 int pin_try = -1;
1928 again:
1929 error = getpin(pwm, &result, &pin_try, confirm ? 2 : 0);
1931 if (error) {
1932 if (pwm->pctx)
1933 pinentry_disconnect(pwm);
1935 if (*password)
1936 pwmd_free(*password);
1938 return error;
1941 if (!confirm++) {
1942 *password = result;
1943 goto again;
1946 if (strcmp(*password, result)) {
1947 pwmd_free(*password);
1948 pwmd_free(result);
1949 pinentry_disconnect(pwm);
1950 error = EPWMD_BADKEY;
1951 return error;
1954 pwmd_free(result);
1955 pinentry_disconnect(pwm);
1956 return 0;
1958 #endif
1960 static gpg_error_t do_save_command(pwm_t *pwm, char *password)
1962 char buf[ASSUAN_LINELENGTH];
1963 gpg_error_t error;
1964 char *result = NULL;
1966 snprintf(buf, sizeof(buf), "SAVE %s", password ? password : "");
1967 error = send_command(pwm, &result, buf);
1968 memset(&buf, 0, sizeof(buf));
1970 if (error && result)
1971 pwmd_free(result);
1973 return error;
1976 static gpg_error_t do_pwmd_save(pwm_t *pwm, int nb)
1978 char *result = NULL;
1979 char *password = NULL;
1980 gpg_error_t rc;
1982 if (!pwm)
1983 return GPG_ERR_INV_ARG;
1985 if (pwm->use_pinentry || pwm->passfunc) {
1986 rc = pwmd_command(pwm, &result, "ISCACHED %s", pwm->filename);
1988 if (rc == EPWMD_CACHE_NOT_FOUND) {
1989 if (pwm->passfunc)
1990 password = (char *)(*pwm->passfunc)(pwm->passdata);
1991 #ifdef WITH_PINENTRY
1992 else if (pwm->use_pinentry) {
1993 if (nb) {
1994 int p[2];
1995 pid_t pid;
1996 pwmd_nb_status_t pw;
1998 if (pipe(p) == -1)
1999 return gpg_error_from_syserror();
2001 #ifdef WITH_LIBPTH
2002 pid = pth_fork();
2003 #else
2004 pid = fork();
2005 #endif
2007 switch (pid) {
2008 case 0:
2009 close(p[0]);
2010 pw.fd = p[0];
2012 do {
2013 password = NULL;
2014 rc = do_save_getpin(pwm, &password);
2015 } while (rc == EPWMD_BADKEY);
2017 if (rc) {
2018 if (pwm->pctx)
2019 pinentry_disconnect(pwm);
2021 pw.error = rc;
2022 #ifdef WITH_LIBPTH
2023 pth_write(p[1], &pw, sizeof(pw));
2024 #else
2025 write(p[1], &pw, sizeof(pw));
2026 #endif
2027 close(p[1]);
2028 _exit(1);
2031 rc = do_save_command(pwm, password);
2032 pinentry_disconnect(pwm);
2033 pw.error = rc;
2034 #ifdef WITH_LIBPTH
2035 pth_write(p[1], &pw, sizeof(pw));
2036 #else
2037 write(p[1], &pw, sizeof(pw));
2038 #endif
2039 close(p[1]);
2040 _exit(0);
2041 break;
2042 case -1:
2043 rc = gpg_error_from_syserror();
2044 close(p[0]);
2045 close(p[1]);
2046 return rc;
2047 default:
2048 break;
2051 close(p[1]);
2052 pwm->nb_fd = p[0];
2053 return 0;
2056 rc = do_save_getpin(pwm, &password);
2058 if (rc)
2059 return rc;
2061 #endif
2063 else {
2064 if (rc)
2065 return rc;
2068 else
2069 password = pwm->password;
2071 rc = do_save_command(pwm, password);
2073 if (!pwm->passfunc && password && password != pwm->password)
2074 pwmd_free(password);
2076 return rc;
2079 gpg_error_t pwmd_save_async2(pwm_t *pwm)
2081 #ifndef WITH_PINENTRY
2082 return GPG_ERR_NOT_IMPLEMENTED;
2083 #else
2084 gpg_error_t rc;
2086 pwm->cmd = ASYNC_CMD_SAVE2;
2087 pwm->state = ASYNC_PROCESS;
2088 rc = do_pwmd_save(pwm, 1);
2090 if (rc)
2091 reset_async(pwm);
2093 return rc;
2094 #endif
2097 gpg_error_t pwmd_save(pwm_t *pwm)
2099 return do_pwmd_save(pwm, 0);
2102 gpg_error_t pwmd_setopt(pwm_t *pwm, pwmd_option_t opt, ...)
2104 va_list ap;
2105 int n = va_arg(ap, int);
2106 char *result;
2107 char *arg1;
2108 gpg_error_t error = 0;
2110 if (!pwm)
2111 return GPG_ERR_INV_ARG;
2113 va_start(ap, opt);
2115 switch (opt) {
2116 case PWMD_OPTION_STATUS_FUNC:
2117 pwm->status_func = va_arg(ap, pwmd_status_fn);
2118 break;
2119 case PWMD_OPTION_STATUS_DATA:
2120 pwm->status_data = va_arg(ap, void *);
2121 break;
2122 case PWMD_OPTION_PASSWORD_FUNC:
2123 pwm->passfunc = va_arg(ap, pwmd_password_fn);
2124 break;
2125 case PWMD_OPTION_PASSWORD_DATA:
2126 pwm->passdata = va_arg(ap, void *);
2127 break;
2128 case PWMD_OPTION_PASSWORD:
2129 arg1 = va_arg(ap, char *);
2131 if (pwm->password)
2132 pwmd_free(pwm->password);
2134 pwm->password = pwmd_strdup(arg1);
2135 break;
2136 case PWMD_OPTION_PINENTRY:
2137 n = va_arg(ap, int);
2139 if (n != 0 && n != 1) {
2140 va_end(ap);
2141 error = GPG_ERR_INV_VALUE;
2143 else {
2144 pwm->use_pinentry = n;
2145 error = pwmd_command(pwm, &result, "OPTION PINENTRY=%i",
2146 !pwm->use_pinentry);
2148 break;
2149 #ifdef WITH_PINENTRY
2150 case PWMD_OPTION_PINENTRY_TRIES:
2151 n = va_arg(ap, int);
2153 if (n <= 0) {
2154 va_end(ap);
2155 error = GPG_ERR_INV_VALUE;
2157 else
2158 pwm->pinentry_tries = n;
2159 break;
2160 #endif
2161 case PWMD_OPTION_PINENTRY_TIMEOUT:
2162 n = va_arg(ap, int);
2164 if (n < 0) {
2165 va_end(ap);
2166 error = GPG_ERR_INV_VALUE;
2168 else
2169 pwm->pinentry_timeout = n;
2171 if (!pwm->use_pinentry)
2172 error = pwmd_command(pwm, &result, "OPTION TIMEOUT=%i",
2173 pwm->pinentry_timeout);
2174 break;
2175 case PWMD_OPTION_PINENTRY_PATH:
2176 if (pwm->pinentry_path)
2177 pwmd_free(pwm->pinentry_path);
2179 pwm->pinentry_path = pwmd_strdup(va_arg(ap, char *));
2181 if (!pwm->use_pinentry)
2182 error = pwmd_command(pwm, &result, "OPTION PATH=%s",
2183 pwm->pinentry_path);
2184 break;
2185 case PWMD_OPTION_PINENTRY_TTY:
2186 if (pwm->pinentry_tty)
2187 pwmd_free(pwm->pinentry_tty);
2189 pwm->pinentry_tty = pwmd_strdup(va_arg(ap, char *));
2191 if (!pwm->use_pinentry)
2192 error = pwmd_command(pwm, &result, "OPTION TTY=%s",
2193 pwm->pinentry_tty);
2194 break;
2195 case PWMD_OPTION_PINENTRY_DISPLAY:
2196 if (pwm->pinentry_display)
2197 pwmd_free(pwm->pinentry_display);
2199 pwm->pinentry_display = pwmd_strdup(va_arg(ap, char *));
2201 if (!pwm->use_pinentry)
2202 error = pwmd_command(pwm, &result, "OPTION DISPLAY=%s",
2203 pwm->pinentry_display);
2204 break;
2205 case PWMD_OPTION_PINENTRY_TERM:
2206 if (pwm->pinentry_term)
2207 pwmd_free(pwm->pinentry_term);
2209 pwm->pinentry_term = pwmd_strdup(va_arg(ap, char *));
2211 if (!pwm->use_pinentry)
2212 error = pwmd_command(pwm, &result, "OPTION TTYTYPE=%s",
2213 pwm->pinentry_term);
2214 break;
2215 case PWMD_OPTION_PINENTRY_TITLE:
2216 if (pwm->title)
2217 pwmd_free(pwm->title);
2219 pwm->title = percent_escape(va_arg(ap, char *));
2221 if (!pwm->use_pinentry)
2222 error = pwmd_command(pwm, &result, "OPTION TITLE=%s",
2223 pwm->title);
2224 break;
2225 case PWMD_OPTION_PINENTRY_PROMPT:
2226 if (pwm->prompt)
2227 pwmd_free(pwm->prompt);
2229 pwm->prompt = percent_escape(va_arg(ap, char *));
2231 if (!pwm->use_pinentry)
2232 error = pwmd_command(pwm, &result, "OPTION PROMPT=%s",
2233 pwm->prompt);
2234 break;
2235 case PWMD_OPTION_PINENTRY_DESC:
2236 if (pwm->desc)
2237 pwmd_free(pwm->desc);
2239 pwm->desc = percent_escape(va_arg(ap, char *));
2241 if (!pwm->use_pinentry)
2242 error = pwmd_command(pwm, &result, "OPTION DESC=%s",
2243 pwm->desc);
2244 break;
2245 case PWMD_OPTION_PINENTRY_LC_CTYPE:
2246 if (pwm->lcctype)
2247 pwmd_free(pwm->lcctype);
2249 pwm->lcctype = pwmd_strdup(va_arg(ap, char *));
2251 if (!pwm->use_pinentry)
2252 error = pwmd_command(pwm, &result, "OPTION LC_CTYPE=%s",
2253 pwm->lcctype);
2254 break;
2255 case PWMD_OPTION_PINENTRY_LC_MESSAGES:
2256 if (pwm->lcmessages)
2257 pwmd_free(pwm->lcmessages);
2259 pwm->lcmessages = pwmd_strdup(va_arg(ap, char *));
2261 if (!pwm->use_pinentry)
2262 error = pwmd_command(pwm, &result, "OPTION LC_MESSAGES=%s",
2263 pwm->lcmessages);
2264 break;
2265 default:
2266 error = GPG_ERR_NOT_IMPLEMENTED;
2267 break;
2270 va_end(ap);
2271 return error;
2274 gpg_error_t pwmd_get_fd(pwm_t *pwm, int *fd)
2276 if (!pwm)
2277 return GPG_ERR_INV_ARG;
2279 if (pwm->fd == -1)
2280 return GPG_ERR_INV_STATE;
2282 *fd = pwm->fd;
2283 return 0;
2286 pwm_t *pwmd_new(const char *name)
2288 pwm_t *h = pwmd_calloc(1, sizeof(pwm_t));
2290 if (!h)
2291 return NULL;
2293 if (name) {
2294 h->name = pwmd_strdup(name);
2296 if (!h->name) {
2297 pwmd_free(h);
2298 return NULL;
2302 h->fd = -1;
2303 #ifdef WITH_PINENTRY
2304 h->nb_fd = -1;
2305 #endif
2306 return h;
2309 void pwmd_free(void *ptr)
2311 xfree(ptr);
2314 void *pwmd_malloc(size_t size)
2316 return xmalloc(size);
2319 void *pwmd_calloc(size_t nmemb, size_t size)
2321 return xcalloc(nmemb, size);
2324 void *pwmd_realloc(void *ptr, size_t size)
2326 return xrealloc(ptr, size);
2329 char *pwmd_strdup(const char *str)
2331 return xstrdup(str);