Set the pwmd_process() result when finished. Fixes
[libpwmd.git] / src / libpwmd.c
blob43b98633b902266a3dfec53fadc7c278a6a5da57
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 static gpg_error_t global_error;
76 #endif
78 static char *_getpwuid(struct passwd *pwd)
80 size_t size = sysconf(_SC_GETPW_R_SIZE_MAX);
81 struct passwd *result;
82 char *buf;
83 int n;
85 if (size == -1)
86 size = 16384;
88 buf = pwmd_malloc(size);
90 if (!buf)
91 return NULL;
93 n = getpwuid_r(getuid(), pwd, buf, size, &result);
95 if (n) {
96 pwmd_free(buf);
97 errno = n;
98 return NULL;
101 if (!result) {
102 pwmd_free(buf);
103 return NULL;
106 errno = n;
107 return buf;
110 const char *_pwmd_strerror(gpg_error_t e)
112 gpg_err_code_t code = gpg_err_code(e);
114 if (code >= GPG_ERR_USER_1 && code < gpg_err_code(EPWMD_MAX)) {
115 switch (code) {
116 default:
117 return NULL;
118 case GPG_ERR_USER_1:
119 return N_("Unknown error");
120 case GPG_ERR_USER_2:
121 return N_("No cache slots available");
122 case GPG_ERR_USER_3:
123 return N_("Recursion loop");
124 case GPG_ERR_USER_4:
125 return N_("No file is open");
126 case GPG_ERR_USER_5:
127 return N_("General LibXML error");
128 case GPG_ERR_USER_6:
129 return N_("File modified");
130 case GPG_ERR_USER_7:
131 return N_("Access denied");
135 return NULL;
138 const char *pwmd_strerror(gpg_error_t e)
140 const char *p = _pwmd_strerror(e);
142 return p ? p : gpg_strerror(e);
145 int pwmd_strerror_r(gpg_error_t e, char *buf, size_t size)
147 const char *p = _pwmd_strerror(e);
149 if (p) {
150 snprintf(buf, size, "%s", p);
152 if (strlen(p) > size)
153 return ERANGE;
155 return 0;
158 return gpg_strerror_r(e, buf, size);
161 gpg_error_t pwmd_init()
163 static int initialized;
165 if (initialized)
166 return 0;
168 #ifndef MEM_DEBUG
169 xmem_init();
170 #endif
171 #ifdef ENABLE_NLS
172 bindtextdomain("libpwmd", LOCALEDIR);
173 #endif
174 gpg_err_init();
175 assuan_set_malloc_hooks(pwmd_malloc, pwmd_realloc, pwmd_free);
176 assuan_set_assuan_err_source(GPG_ERR_SOURCE_DEFAULT);
177 initialized = 1;
178 return 0;
181 static gpg_error_t _socket_connect_finalize(pwm_t *pwm)
183 int active[2];
184 int n = assuan_get_active_fds(pwm->ctx, 0, active, N_ARRAY(active));
186 pwm->fd = n <= 0 ? -1 : dup(active[0]);
187 #ifdef WITH_PINENTRY
188 pwm->pid = -1;
189 pwm->pinentry_tries = 3;
190 #endif
191 assuan_set_pointer(pwm->ctx, pwm);
193 if (pwm->name)
194 return pwmd_command(pwm, NULL, "OPTION CLIENT NAME=%s", pwm->name);
196 return 0;
199 #ifdef WITH_TCP
200 static int read_hook(assuan_context_t ctx, assuan_fd_t fd, void *data,
201 size_t len, ssize_t *ret)
203 pwm_t *pwm = assuan_get_pointer(ctx);
205 if (!pwm || !pwm->tcp_conn)
206 #ifdef WITH_LIBPTH
207 *ret = pth_read((int)fd, data, len);
208 #else
209 *ret = read((int)fd, data, len);
210 #endif
211 else {
212 do {
213 *ret = libssh2_channel_read(pwm->tcp_conn->channel, data, len);
214 } while (*ret == LIBSSH2_ERROR_EAGAIN);
217 return *ret <= 0 ? 0 : 1;
220 static int write_hook(assuan_context_t ctx, assuan_fd_t fd, const void *data,
221 size_t len, ssize_t *ret)
223 pwm_t *pwm = assuan_get_pointer(ctx);
225 if (!pwm || !pwm->tcp_conn)
226 #ifdef WITH_LIBPTH
227 *ret = pth_write((int)fd, data, len);
228 #else
229 *ret = write((int)fd, data, len);
230 #endif
231 else {
232 do {
233 *ret = libssh2_channel_write(pwm->tcp_conn->channel, data, len);
234 } while (*ret == LIBSSH2_ERROR_EAGAIN);
237 return *ret <= 0 ? 0 : 1;
240 static void _ssh_deinit(pwmd_tcp_conn_t *conn);
241 static void free_tcp_conn(pwmd_tcp_conn_t *conn)
243 if (!conn)
244 return;
246 if (conn->username) {
247 pwmd_free(conn->username);
248 conn->username = NULL;
251 if (conn->known_hosts) {
252 pwmd_free(conn->known_hosts);
253 conn->known_hosts = NULL;
256 if (conn->identity) {
257 pwmd_free(conn->identity);
258 conn->identity = NULL;
261 if (conn->identity_pub) {
262 pwmd_free(conn->identity_pub);
263 conn->identity_pub = NULL;
266 if (conn->host) {
267 pwmd_free(conn->host);
268 conn->host = NULL;
271 if (conn->hostkey) {
272 pwmd_free(conn->hostkey);
273 conn->hostkey = NULL;
276 if (conn->chan) {
277 ares_destroy(conn->chan);
278 conn->chan = NULL;
281 if (conn->he) {
282 ares_free_hostent(conn->he);
283 conn->he = NULL;
286 if (conn->fd >= 0) {
287 close(conn->fd);
288 conn->fd = -1;
291 if (conn->session)
292 _ssh_deinit(conn);
293 else
294 pwmd_free(conn);
297 static void _ssh_deinit(pwmd_tcp_conn_t *conn)
299 if (!conn)
300 return;
302 if (conn->channel)
303 libssh2_channel_free(conn->channel);
305 if (conn->session) {
306 libssh2_session_disconnect(conn->session, "Bye!");
307 libssh2_session_free(conn->session);
310 conn->session = NULL;
311 conn->channel = NULL;
312 free_tcp_conn(conn);
315 static void _ssh_assuan_deinit(assuan_context_t ctx)
317 pwm_t *pwm = assuan_get_pointer(ctx);
319 _ssh_deinit(pwm->tcp_conn);
320 pwm->tcp_conn = NULL;
324 * Sets common options from both pwmd_tcp_connect() and
325 * pwmd_tcp_connect_async().
327 static gpg_error_t init_tcp_conn(pwmd_tcp_conn_t **dst, const char *host,
328 int port, const char *identity, const char *user, const char *hosts,
329 int get)
331 pwmd_tcp_conn_t *conn;
332 gpg_error_t rc = 0;
334 if (get) {
335 if (!host)
336 return GPG_ERR_INV_ARG;
338 else {
339 if (!host || !identity || !hosts)
340 return GPG_ERR_INV_ARG;
343 conn = pwmd_calloc(1, sizeof(pwmd_tcp_conn_t));
345 if (!conn)
346 return gpg_error_from_errno(ENOMEM);
348 conn->port = port == -1 ? 22 : port;
349 conn->host = pwmd_strdup(host);
351 if (!conn->host) {
352 rc = gpg_error_from_errno(ENOMEM);
353 goto fail;
356 if (!get) {
357 struct passwd pw;
358 char *pwbuf = _getpwuid(&pw);
360 if (!pwbuf) {
361 rc = gpg_error_from_errno(errno);
362 goto fail;
365 conn->username = pwmd_strdup(user ? user : pw.pw_name);
366 pwmd_free(pwbuf);
368 if (!conn->username) {
369 rc = gpg_error_from_errno(ENOMEM);
370 goto fail;
373 conn->identity = pwmd_strdup(identity);
375 if (!conn->identity) {
376 rc = gpg_error_from_errno(ENOMEM);
377 goto fail;
380 conn->identity_pub = pwmd_malloc(strlen(conn->identity)+5);
382 if (!conn->identity_pub) {
383 rc = gpg_error_from_errno(ENOMEM);
384 goto fail;
387 sprintf(conn->identity_pub, "%s.pub", conn->identity);
388 conn->known_hosts = pwmd_strdup(hosts);
390 if (!conn->known_hosts) {
391 rc = gpg_error_from_errno(ENOMEM);
392 goto fail;
396 *dst = conn;
397 return 0;
399 fail:
400 free_tcp_conn(conn);
401 return rc;
404 static gpg_error_t do_connect(pwm_t *pwm, int prot, void *addr)
406 struct sockaddr_in their_addr;
408 pwm->tcp_conn->fd = socket(prot, SOCK_STREAM, 0);
410 if (pwm->tcp_conn->fd == -1)
411 return gpg_error_from_syserror();
413 if (pwm->tcp_conn->async)
414 fcntl(pwm->tcp_conn->fd, F_SETFL, O_NONBLOCK);
416 pwm->cmd = ASYNC_CMD_CONNECT;
417 their_addr.sin_family = prot;
418 their_addr.sin_port = htons(pwm->tcp_conn->port);
419 their_addr.sin_addr = *((struct in_addr *)addr);
420 memset(their_addr.sin_zero, '\0', sizeof their_addr.sin_zero);
422 #ifdef WITH_LIBPTH
423 if (pth_connect(pwm->tcp_conn->fd, (struct sockaddr *)&their_addr,
424 sizeof(their_addr)) == -1)
425 #else
426 if (connect(pwm->tcp_conn->fd, (struct sockaddr *)&their_addr,
427 sizeof(their_addr)) == -1)
428 #endif
429 return gpg_error_from_syserror();
431 return 0;
434 static gpg_error_t ares_error_to_pwmd(int status)
436 if (status != ARES_SUCCESS)
437 warnx("%s", ares_strerror(status));
439 switch (status) {
440 case ARES_ENODATA:
441 case ARES_EFORMERR:
442 case ARES_ENOTFOUND:
443 return GPG_ERR_UNKNOWN_HOST;
444 case ARES_ESERVFAIL:
445 return GPG_ERR_EHOSTDOWN;
446 case ARES_ETIMEOUT:
447 return GPG_ERR_TIMEOUT;
448 case ARES_ENOMEM:
449 return gpg_error_from_errno(ENOMEM);
450 case ARES_ECONNREFUSED:
451 return GPG_ERR_ECONNREFUSED;
452 default:
453 /* FIXME ??? */
454 return GPG_ERR_EHOSTUNREACH;
457 return ARES_SUCCESS;
460 static void dns_resolve_cb(void *arg, int status, int timeouts,
461 unsigned char *abuf, int alen)
463 pwm_t *pwm = arg;
464 int rc;
465 struct hostent *he;
467 if (status == ARES_EDESTRUCTION)
468 return;
470 if (status != ARES_SUCCESS) {
471 pwm->tcp_conn->rc = ares_error_to_pwmd(status);
472 return;
475 //FIXME localhost. works with ipv4. maybe local system config error
476 /* Check for an IPv6 address first. */
477 rc = ares_parse_a_reply(abuf, alen, &he, NULL, NULL);
479 if (rc != ARES_SUCCESS) {
480 if (rc != ARES_ENODATA) {
481 pwm->tcp_conn->rc = ares_error_to_pwmd(status);
482 return;
485 rc = ares_parse_aaaa_reply(abuf, alen, &he, NULL, NULL);
487 if (rc != ARES_SUCCESS) {
488 pwm->tcp_conn->rc = ares_error_to_pwmd(status);
489 return;
493 pwm->tcp_conn->he = he;
494 pwm->tcp_conn->rc = do_connect(pwm, he->h_addrtype, he->h_addr);
497 static gpg_error_t _do_pwmd_tcp_connect_async(pwm_t *pwm, const char *host,
498 int port, const char *identity, const char *user,
499 const char *known_hosts, pwmd_async_cmd_t which)
501 pwmd_tcp_conn_t *conn;
502 gpg_error_t rc;
504 rc = init_tcp_conn(&conn, host, port, identity, user, known_hosts,
505 which == ASYNC_CMD_HOSTKEY ? 1 : 0);
507 if (rc)
508 return rc;
510 conn->async = 1;
511 pwm->tcp_conn = conn;
512 pwm->tcp_conn->cmd = which;
514 if (pwm->tcp_conn->cmd == ASYNC_CMD_HOSTKEY)
515 pwm->tcp_conn->get_only = 1;
517 pwm->cmd = ASYNC_CMD_DNS;
518 pwm->state = ASYNC_PROCESS;
519 ares_init(&pwm->tcp_conn->chan);
520 ares_query(pwm->tcp_conn->chan, pwm->tcp_conn->host, ns_c_any, ns_t_any,
521 dns_resolve_cb, pwm);
522 return 0;
525 gpg_error_t pwmd_tcp_connect_async(pwm_t *pwm, const char *host, int port,
526 const char *identity, const char *user, const char *known_hosts)
528 return _do_pwmd_tcp_connect_async(pwm, host, port, identity, user,
529 known_hosts, ASYNC_CMD_CONNECT);
532 static void *_ssh_malloc(size_t size, void **data)
534 return pwmd_malloc(size);
537 static void _ssh_free(void *ptr, void **data)
539 pwmd_free(ptr);
542 static void *_ssh_realloc(void *ptr, size_t size, void **data)
544 return pwmd_realloc(ptr, size);
547 static char *to_hex(const char *str, size_t slen)
549 int i;
550 char *buf = pwmd_malloc(slen*2+1);
552 if (!buf)
553 return NULL;
555 for (i = 0, buf[0] = 0; i < slen; i++) {
556 char tmp[3];
558 sprintf(tmp, "%02x", (unsigned char)str[i]);
559 strcat(buf, tmp);
562 return buf;
565 static int verify_host_key(pwm_t *pwm)
567 FILE *fp = fopen(pwm->tcp_conn->known_hosts, "r");
568 char *buf, *p;
570 if (!fp)
571 return 1;
573 buf = pwmd_malloc(LINE_MAX);
575 if (!buf)
576 goto fail;
578 while ((p = fgets(buf, LINE_MAX, fp))) {
579 if (*p == '#' || isspace(*p))
580 continue;
582 if (p[strlen(p)-1] == '\n')
583 p[strlen(p)-1] = 0;
585 if (!strcmp(buf, pwm->tcp_conn->hostkey))
586 goto done;
589 fail:
590 if (buf)
591 pwmd_free(buf);
593 fclose(fp);
594 return 1;
596 done:
597 pwmd_free(buf);
598 fclose(fp);
599 return 0;
602 static gpg_error_t authenticate_ssh(pwm_t *pwm)
604 const char *fp = libssh2_hostkey_hash(pwm->tcp_conn->session,
605 LIBSSH2_HOSTKEY_HASH_SHA1);
606 char *userauth;
608 pwm->tcp_conn->hostkey = to_hex(fp, 20);
610 if (!pwm->tcp_conn->hostkey)
611 return gpg_error_from_errno(ENOMEM);
613 if (pwm->tcp_conn->get_only)
614 return 0;
616 if (!fp || verify_host_key(pwm))
617 return GPG_ERR_CHECKSUM;
619 userauth = libssh2_userauth_list(pwm->tcp_conn->session,
620 pwm->tcp_conn->username, strlen(pwm->tcp_conn->username));
622 if (!userauth || !strstr(userauth, "publickey"))
623 return GPG_ERR_BAD_PIN_METHOD;
625 if (libssh2_userauth_publickey_fromfile(pwm->tcp_conn->session,
626 pwm->tcp_conn->username, pwm->tcp_conn->identity_pub,
627 pwm->tcp_conn->identity, NULL))
628 return GPG_ERR_BAD_SECKEY;
630 return 0;
633 static gpg_error_t setup_tcp_session(pwm_t *pwm)
635 assuan_context_t ctx;
636 struct assuan_io_hooks io_hooks = {read_hook, write_hook};
637 gpg_error_t rc;
639 pwm->tcp_conn->session = libssh2_session_init_ex(_ssh_malloc, _ssh_free,
640 _ssh_realloc, NULL);
642 if (!pwm->tcp_conn->session) {
643 rc = gpg_error_from_errno(ENOMEM);
644 goto fail;
647 if (libssh2_session_startup(pwm->tcp_conn->session, pwm->tcp_conn->fd)) {
648 rc = GPG_ERR_ASSUAN_SERVER_FAULT;
649 goto fail;
652 rc = authenticate_ssh(pwm);
654 if (rc)
655 goto fail;
657 /* pwmd_get_hostkey(). */
658 if (pwm->tcp_conn->get_only) {
659 pwm->result = pwmd_strdup(pwm->tcp_conn->hostkey);
661 if (!pwm->result) {
662 rc = gpg_error_from_errno(ENOMEM);
663 goto fail;
666 return 0;
669 pwm->tcp_conn->channel = libssh2_channel_open_session(pwm->tcp_conn->session);
671 if (!pwm->tcp_conn->channel) {
672 rc = GPG_ERR_ASSUAN_SERVER_FAULT;
673 goto fail;
676 if (libssh2_channel_shell(pwm->tcp_conn->channel)) {
677 rc = GPG_ERR_ASSUAN_SERVER_FAULT;
678 goto fail;
681 assuan_set_io_hooks(&io_hooks);
682 rc = assuan_socket_connect_fd(&ctx, pwm->tcp_conn->fd, 0, pwm);
684 if (rc)
685 goto fail;
687 assuan_set_finish_handler(ctx, _ssh_assuan_deinit);
688 pwm->ctx = ctx;
689 return _socket_connect_finalize(pwm);
691 fail:
692 free_tcp_conn(pwm->tcp_conn);
693 pwm->tcp_conn = NULL;
694 return rc;
697 static gpg_error_t _do_pwmd_tcp_connect(pwm_t *pwm, const char *host, int port,
698 const char *identity, const char *user, const char *known_hosts, int get)
700 pwmd_tcp_conn_t *conn;
701 gpg_error_t rc;
703 rc = init_tcp_conn(&conn, host, port, identity, user, known_hosts, get);
705 if (rc)
706 return rc;
708 pwm->tcp_conn = conn;
709 pwm->tcp_conn->get_only = get;
710 pwm->cmd = ASYNC_CMD_DNS;
711 ares_init(&pwm->tcp_conn->chan);
712 ares_query(pwm->tcp_conn->chan, pwm->tcp_conn->host, ns_c_any, ns_t_any,
713 dns_resolve_cb, pwm);
715 /* dns_resolve_cb() may have already been called. */
716 if (pwm->tcp_conn->rc) {
717 rc = pwm->tcp_conn->rc;
718 goto fail;
722 * Fake a blocking DNS lookup. libcares does a better job than
723 * getaddrinfo().
725 do {
726 fd_set rfds, wfds;
727 int n;
728 struct timeval tv;
730 FD_ZERO(&rfds);
731 FD_ZERO(&wfds);
732 n = ares_fds(pwm->tcp_conn->chan, &rfds, &wfds);
733 ares_timeout(pwm->tcp_conn->chan, NULL, &tv);
734 #ifdef WITH_LIBPTH
735 n = pth_select(n, &rfds, &wfds, NULL, &tv);
736 #else
737 n = select(n, &rfds, &wfds, NULL, &tv);
738 #endif
740 if (n == -1) {
741 rc = gpg_error_from_syserror();
742 goto fail;
744 else if (n == 0) {
745 rc = GPG_ERR_TIMEOUT;
746 goto fail;
749 ares_process(pwm->tcp_conn->chan, &rfds, &wfds);
751 if (pwm->tcp_conn->rc)
752 break;
753 } while (pwm->cmd == ASYNC_CMD_DNS);
755 if (pwm->tcp_conn->rc) {
756 rc = pwm->tcp_conn->rc;
757 goto fail;
760 return setup_tcp_session(pwm);
762 fail:
763 return rc;
766 gpg_error_t pwmd_tcp_connect(pwm_t *pwm, const char *host, int port,
767 const char *identity, const char *user, const char *known_hosts)
769 return _do_pwmd_tcp_connect(pwm, host, port, identity, user, known_hosts, 0);
772 /* Must free the result with pwmd_free(). */
773 gpg_error_t pwmd_get_hostkey(const char *host, int port, char **result)
775 char *hostkey;
776 pwm_t *pwm = pwmd_new(NULL);
777 gpg_error_t rc;
779 if (!pwm)
780 return gpg_error_from_errno(ENOMEM);
782 rc = _do_pwmd_tcp_connect(pwm, host, port, NULL, NULL, NULL, 1);
784 if (rc) {
785 pwmd_close(pwm);
786 return rc;
789 hostkey = pwmd_strdup(pwm->tcp_conn->hostkey);
791 if (!hostkey)
792 rc = gpg_error_from_errno(ENOMEM);
794 pwmd_close(pwm);
795 *result = hostkey;
796 return rc;
799 gpg_error_t pwmd_get_hostkey_async(pwm_t *pwm, const char *host, int port)
801 return _do_pwmd_tcp_connect_async(pwm, host, port, NULL, NULL, NULL,
802 ASYNC_CMD_HOSTKEY);
804 #endif
806 gpg_error_t pwmd_connect(pwm_t *pwm, const char *path)
808 char *socketpath = NULL;
809 assuan_context_t ctx;
810 struct passwd pw;
811 char *pwbuf = _getpwuid(&pw);
812 gpg_error_t rc;
814 if (!pwbuf)
815 return gpg_error_from_errno(errno);
817 if (!path) {
818 socketpath = (char *)pwmd_malloc(strlen(pw.pw_dir) + strlen("/.pwmd/socket") + 1);
819 sprintf(socketpath, "%s/.pwmd/socket", pw.pw_dir);
821 else
822 socketpath = pwmd_strdup(path);
824 pwmd_free(pwbuf);
825 rc = assuan_socket_connect_ext(&ctx, socketpath, -1, 0);
826 pwmd_free(socketpath);
828 if (rc)
829 return rc;
831 pwm->ctx = ctx;
832 return _socket_connect_finalize(pwm);
835 void pwmd_close(pwm_t *pwm)
837 if (!pwm)
838 return;
840 if (pwm->ctx)
841 assuan_disconnect(pwm->ctx);
843 if (pwm->password)
844 pwmd_free(pwm->password);
846 if (pwm->title)
847 pwmd_free(pwm->title);
849 if (pwm->desc)
850 pwmd_free(pwm->desc);
852 if (pwm->prompt)
853 pwmd_free(pwm->prompt);
855 if (pwm->pinentry_tty)
856 pwmd_free(pwm->pinentry_tty);
858 if (pwm->pinentry_display)
859 pwmd_free(pwm->pinentry_display);
861 if (pwm->pinentry_term)
862 pwmd_free(pwm->pinentry_term);
864 if (pwm->lcctype)
865 pwmd_free(pwm->lcctype);
867 if (pwm->lcmessages)
868 pwmd_free(pwm->lcmessages);
870 if (pwm->filename)
871 pwmd_free(pwm->filename);
873 if (pwm->name)
874 pwmd_free(pwm->name);
876 #ifdef WITH_TCP
877 if (pwm->tcp_conn)
878 free_tcp_conn(pwm->tcp_conn);
879 #endif
881 pwmd_free(pwm);
884 static int mem_realloc_cb(void *data, const void *buffer, size_t len)
886 membuf_t *mem = (membuf_t *)data;
887 void *p;
889 if (!buffer)
890 return 0;
892 if ((p = pwmd_realloc(mem->buf, mem->len + len)) == NULL)
893 return 1;
895 mem->buf = p;
896 memcpy((char *)mem->buf + mem->len, buffer, len);
897 mem->len += len;
898 return 0;
901 static int _inquire_cb(void *data, const char *keyword)
903 pwm_t *pwm = (pwm_t *)data;
904 gpg_error_t rc = 0;
905 int flags = fcntl(pwm->fd, F_GETFL);
907 /* Shouldn't get this far without a callback. */
908 if (!pwm->inquire_func)
909 return GPG_ERR_INV_ARG;
912 * Since the socket file descriptor is probably set to non-blocking, set to
913 * blocking to prevent GPG_ERR_EAGAIN errors. This should be fixes when
914 * asynchronous INQUIRE is supported by either libassuan or a later
915 * libpwmd.
917 fcntl(pwm->fd, F_SETFL, 0);
919 for (;;) {
920 char *result = NULL;
921 size_t len;
922 gpg_error_t arc;
924 rc = pwm->inquire_func(pwm->inquire_data, keyword, rc, &result, &len);
925 rc = gpg_err_code(rc);
927 if (rc == GPG_ERR_EOF || !rc) {
928 if (len <= 0 || !result || !*result) {
929 rc = 0;
930 break;
933 arc = assuan_send_data(pwm->ctx, result, len);
935 if (rc == GPG_ERR_EOF) {
936 rc = arc;
937 break;
940 rc = arc;
942 else if (rc)
943 break;
946 fcntl(pwm->fd, F_SETFL, flags);
947 return rc;
950 gpg_error_t pwmd_finalize(pwm_t *pwm)
952 if (!pwm)
953 return GPG_ERR_INV_ARG;
955 if (pwm->cmd == ASYNC_CMD_NONE || pwm->state != ASYNC_DONE)
956 return GPG_ERR_INV_STATE;
958 pwm->state = ASYNC_INIT;
959 pwm->cmd = ASYNC_CMD_NONE;
961 #ifdef WITH_TCP
962 if (pwm->cmd == ASYNC_CMD_CONNECT || pwm->cmd == ASYNC_CMD_DNS) {
963 gpg_error_t rc = pwm->tcp_conn->rc;
965 /* pwm is no longer a valid handle. */
966 if (rc)
967 pwmd_close(pwm);
969 return 0;
971 #endif
973 if (pwm->fd < 0)
974 return GPG_ERR_INV_ARG;
976 pwm->ntries = 0;
977 #ifdef WITH_PINENTRY
978 pwm->is_open_cmd = 0;
979 #endif
980 return 0;
983 static gpg_error_t do_nb_command(pwm_t *pwm, const char *cmd, const char *arg)
985 char *buf;
986 gpg_error_t rc;
987 size_t len = strlen(cmd) + 2;
989 len += arg ? strlen(arg) : 0;
991 if (pwm->state != ASYNC_INIT)
992 return GPG_ERR_INV_STATE;
994 buf = (char *)pwmd_malloc(len);
996 if (!buf) {
997 rc = gpg_error_from_errno(ENOMEM);
998 goto fail;
1001 snprintf(buf, len, "%s %s", cmd, arg ? arg : "");
1002 rc = assuan_write_line(pwm->ctx, buf);
1003 pwmd_free(buf);
1005 if (!rc)
1006 pwm->state = ASYNC_PROCESS;
1008 fail:
1009 return rc;
1012 gpg_error_t pwmd_open_async(pwm_t *pwm, const char *filename)
1014 if (!pwm || !filename)
1015 return GPG_ERR_INV_ARG;
1017 /* For pinentry retries. */
1018 if (!pwm->is_open_cmd) {
1019 if (pwm->filename)
1020 pwmd_free(pwm->filename);
1022 pwm->filename = pwmd_strdup(filename);
1025 pwm->is_open_cmd = 1;
1026 pwm->cmd = ASYNC_CMD_OPEN;
1027 return do_nb_command(pwm, "OPEN", filename);
1030 gpg_error_t pwmd_save_async(pwm_t *pwm)
1032 if (!pwm)
1033 return GPG_ERR_INV_ARG;
1035 pwm->cmd = ASYNC_CMD_SAVE;
1036 return do_nb_command(pwm, "SAVE", NULL);
1039 static gpg_error_t parse_assuan_line(pwm_t *pwm)
1041 gpg_error_t rc;
1042 char *line;
1043 size_t len;
1045 rc = assuan_read_line(pwm->ctx, &line, &len);
1047 if (!rc) {
1048 if (line[0] == 'O' && line[1] == 'K' &&
1049 (line[2] == 0 || line[2] == ' ')) {
1050 pwm->state = ASYNC_DONE;
1052 else if (line[0] == '#') {
1054 else if (line[0] == 'S' && (line[1] == 0 || line[1] == ' ')) {
1055 if (pwm->status_func) {
1056 pwm->status_func(pwm->status_data,
1057 line[1] == 0 ? line+1 : line+2);
1060 else if (line[0] == 'E' && line[1] == 'R' && line[2] == 'R' &&
1061 (line[3] == 0 || line[3] == ' ')) {
1062 line += 4;
1063 rc = atoi(line);
1064 pwm->state = ASYNC_DONE;
1068 return rc;
1071 gpg_error_t pwmd_pending_line(pwm_t *pwm)
1073 if (!pwm)
1074 return GPG_ERR_INV_ARG;
1076 if (!pwm->ctx)
1077 return GPG_ERR_INV_STATE;
1079 return assuan_pending_line(pwm->ctx) ? 0 : GPG_ERR_NO_DATA;
1082 pwmd_async_t pwmd_process(pwm_t *pwm, gpg_error_t *rc, char **result)
1084 fd_set fds;
1085 int n;
1086 struct timeval tv = {0, 0};
1088 *rc = 0;
1090 if (!pwm) {
1091 *rc = GPG_ERR_INV_ARG;
1092 return ASYNC_DONE;
1095 if (pwm->state == ASYNC_DONE)
1096 return pwm->state;
1098 /* When not in a command, this will let libassuan process status messages
1099 * by calling PWMD_OPTION_STATUS_FUNC. The client can poll the file
1100 * descriptor returned by pwmd_get_fd() to determine when this should be
1101 * called or call pwmd_pending_line() to determine whether a buffered line
1102 * needs to be processed. */
1103 if (pwm->cmd == ASYNC_CMD_NONE) {
1104 *rc = assuan_command(pwm, pwm->ctx, NULL, "NOP");
1105 return pwm->state;
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 close(pwm->tcp_conn->fd);
1115 pwm->tcp_conn->fd = -1;
1116 pwm->state = ASYNC_DONE;
1117 return pwm->state;
1120 FD_ZERO(&rfds);
1121 FD_ZERO(&wfds);
1122 n = ares_fds(pwm->tcp_conn->chan, &rfds, &wfds);
1124 /* Shouldn't happen. */
1125 if (!n)
1126 return pwm->state;
1128 #ifdef WITH_LIBPTH
1129 n = pth_select(n, &rfds, &wfds, NULL, &tv);
1130 #else
1131 n = select(n, &rfds, &wfds, NULL, &tv);
1132 #endif
1134 if (n > 0)
1135 ares_process(pwm->tcp_conn->chan, &rfds, &wfds);
1137 return pwm->state;
1139 else if (pwm->cmd == ASYNC_CMD_CONNECT) {
1140 if (pwm->tcp_conn->rc == GPG_ERR_EINPROGRESS) {
1141 int ret;
1142 socklen_t len = sizeof(int);
1144 FD_ZERO(&fds);
1145 FD_SET(pwm->tcp_conn->fd, &fds);
1146 #ifdef WITH_LIBPTH
1147 n = pth_select(pwm->tcp_conn->fd+1, NULL, &fds, NULL, &tv);
1148 #else
1149 n = select(pwm->tcp_conn->fd+1, NULL, &fds, NULL, &tv);
1150 #endif
1152 if (!n || !FD_ISSET(pwm->tcp_conn->fd, &fds))
1153 return pwm->state;
1154 else if (n == -1) {
1155 *rc = gpg_error_from_syserror();
1156 close(pwm->tcp_conn->fd);
1157 pwm->tcp_conn->fd = -1;
1158 pwm->state = ASYNC_DONE;
1159 return pwm->state;
1162 ret = getsockopt(pwm->tcp_conn->fd, SOL_SOCKET, SO_ERROR, &n, &len);
1164 if (ret || n) {
1165 *rc = ret ? gpg_error_from_syserror() : gpg_error_from_errno(n);
1166 close(pwm->tcp_conn->fd);
1167 pwm->tcp_conn->fd = -1;
1168 pwm->state = ASYNC_DONE;
1169 return pwm->state;
1172 else if (pwm->tcp_conn->rc) {
1173 *rc = pwm->tcp_conn->rc;
1174 close(pwm->tcp_conn->fd);
1175 pwm->tcp_conn->fd = -1;
1176 pwm->state = ASYNC_DONE;
1177 return pwm->state;
1180 fcntl(pwm->tcp_conn->fd, F_SETFL, 0);
1181 *rc = setup_tcp_session(pwm);
1183 if (!*rc)
1184 *result = pwm->result;
1186 pwm->state = ASYNC_DONE;
1187 return pwm->state;
1189 #endif
1191 if (pwm->fd < 0) {
1192 *rc = GPG_ERR_INV_ARG;
1193 return ASYNC_DONE;
1196 /* This is for the non-blocking OPEN and SAVE commands. */
1197 FD_ZERO(&fds);
1198 FD_SET(pwm->fd, &fds);
1199 #ifdef WITH_LIBPTH
1200 n = pth_select(pwm->fd+1, &fds, NULL, NULL, &tv);
1201 #else
1202 n = select(pwm->fd+1, &fds, NULL, NULL, &tv);
1203 #endif
1205 if (n > 0) {
1206 if (FD_ISSET(pwm->fd, &fds))
1207 *rc = parse_assuan_line(pwm);
1210 while (!*rc && assuan_pending_line(pwm->ctx))
1211 *rc = parse_assuan_line(pwm);
1213 /* For pinentry retries. */
1214 if (pwm->is_open_cmd && gpg_err_code(*rc) == EPWMD_BADKEY &&
1215 ++pwm->ntries < pwm->pinentry_tries) {
1216 pwm->state = ASYNC_INIT;
1217 *rc = pwmd_open_async(pwm, pwm->filename);
1220 return pwm->state;
1223 static gpg_error_t assuan_command(pwm_t *pwm, assuan_context_t ctx,
1224 char **result, const char *cmd)
1226 membuf_t data;
1227 gpg_error_t rc;
1229 data.len = 0;
1230 data.buf = NULL;
1232 rc = assuan_transact(ctx, cmd, mem_realloc_cb, &data, _inquire_cb, pwm,
1233 pwm->status_func, pwm->status_data);
1235 if (rc) {
1236 if (data.buf) {
1237 pwmd_free(data.buf);
1238 data.buf = NULL;
1241 else {
1242 if (data.buf) {
1243 mem_realloc_cb(&data, "", 1);
1245 if (!result) {
1246 pwmd_free(data.buf);
1247 rc = GPG_ERR_INV_ARG;
1249 else
1250 *result = (char *)data.buf;
1254 return gpg_err_code(rc);
1257 gpg_error_t pwmd_inquire(pwm_t *pwm, const char *cmd, pwmd_inquire_fn fn,
1258 void *data)
1260 if (!pwm || !cmd || !fn)
1261 return GPG_ERR_INV_ARG;
1263 pwm->inquire_func = fn;
1264 pwm->inquire_data = data;
1265 return assuan_command(pwm, pwm->ctx, NULL, cmd);
1268 gpg_error_t pwmd_terminate_pinentry(pwm_t *pwm)
1270 #ifndef WITH_PINENTRY
1271 return GPG_ERR_NOT_IMPLEMENTED;
1272 #else
1273 pid_t pid = pwm->pid;
1275 pwm->pid = -1;
1277 if (!pwm || pid == -1)
1278 return GPG_ERR_INV_ARG;
1280 if (kill(pid, 0) == 0) {
1281 if (kill(pid, SIGTERM) == -1) {
1282 if (kill(pid, SIGKILL) == -1)
1283 return gpg_error_from_errno(errno);
1286 pwm->pin_error = GPG_ERR_TIMEOUT;
1288 else
1289 return gpg_error_from_errno(errno);
1291 return 0;
1292 #endif
1295 #ifdef WITH_PINENTRY
1296 static gpg_error_t set_pinentry_strings(pwm_t *pwm, int which)
1298 char *buf;
1299 char tmp[ASSUAN_LINELENGTH];
1300 gpg_error_t error;
1302 if (!pwm->title)
1303 pwm->title = pwmd_strdup(N_("LibPWMD"));
1305 if (!pwm->prompt)
1306 pwm->prompt = pwmd_strdup(N_("Passphrase:"));
1308 if (!pwm->desc && !which)
1309 pwm->desc = pwmd_strdup(N_("Enter a passphrase."));
1311 if (which == 1) {
1312 snprintf(tmp, sizeof(tmp), "SETERROR %s", N_("Invalid passphrase, please try again."));
1313 buf = pwmd_strdup(tmp);
1315 else if (which == 2) {
1316 snprintf(tmp, sizeof(tmp), "SETERROR %s", N_("Please type the passphrase again for confirmation."));
1317 buf = pwmd_strdup(tmp);
1319 else {
1320 buf = (char *)pwmd_malloc(strlen("SETERROR ") + strlen(pwm->desc) + 1);
1321 sprintf(buf, "SETERROR %s", pwm->desc);
1324 error = pinentry_command(pwm, NULL, buf);
1325 pwmd_free(buf);
1327 if (error)
1328 return error;
1330 buf = (char *)pwmd_malloc(strlen("SETPROMPT ") + strlen(pwm->prompt) + 1);
1331 sprintf(buf, "SETPROMPT %s", pwm->prompt);
1332 error = pinentry_command(pwm, NULL, buf);
1333 pwmd_free(buf);
1335 if (error)
1336 return error;
1338 buf = (char *)pwmd_malloc(strlen("SETDESC ") + strlen(pwm->title) + 1);
1339 sprintf(buf, "SETDESC %s", pwm->title);
1340 error = pinentry_command(pwm, NULL, buf);
1341 pwmd_free(buf);
1342 return error;
1345 static void update_pinentry_settings(pwm_t *pwm)
1347 FILE *fp;
1348 char buf[LINE_MAX];
1349 char *p;
1350 struct passwd pw;
1351 char *pwbuf = _getpwuid(&pw);
1353 if (!pwbuf)
1354 return;
1356 snprintf(buf, sizeof(buf), "%s/.pwmd/pinentry.conf", pw.pw_dir);
1357 pwmd_free(pwbuf);
1359 if ((fp = fopen(buf, "r")) == NULL)
1360 return;
1362 while ((p = fgets(buf, sizeof(buf), fp)) != NULL) {
1363 char name[32], val[256];
1365 if (sscanf(p, " %31[a-zA-Z] = %255s", name, val) != 2)
1366 continue;
1368 if (strcasecmp(name, "TTYNAME") == 0) {
1369 pwmd_free(pwm->pinentry_tty);
1370 pwm->pinentry_tty = pwmd_strdup(val);
1372 else if (strcasecmp(name, "TTYTYPE") == 0) {
1373 pwmd_free(pwm->pinentry_term);
1374 pwm->pinentry_term = pwmd_strdup(val);
1376 else if (strcasecmp(name, "DISPLAY") == 0) {
1377 pwmd_free(pwm->pinentry_display);
1378 pwm->pinentry_display = pwmd_strdup(val);
1380 else if (strcasecmp(name, "PATH") == 0) {
1381 pwmd_free(pwm->pinentry_path);
1382 pwm->pinentry_path = pwmd_strdup(val);
1386 fclose(fp);
1389 static gpg_error_t launch_pinentry(pwm_t *pwm)
1391 int rc;
1392 assuan_context_t ctx;
1393 int child_list[] = {-1};
1394 char *display = getenv("DISPLAY");
1395 const char *argv[10];
1396 const char **p = argv;
1397 int have_display = 0;
1398 char *tty = NULL;
1399 char *ttybuf = NULL;
1401 update_pinentry_settings(pwm);
1403 if (pwm->pinentry_display || display)
1404 have_display = 1;
1405 else {
1406 if (!pwm->pinentry_tty) {
1407 ttybuf = pwmd_malloc(255);
1409 if (!ttybuf)
1410 return gpg_error_from_errno(ENOMEM);
1412 rc = ttyname_r(STDOUT_FILENO, ttybuf, 255);
1414 if (rc) {
1415 pwmd_free(ttybuf);
1416 return gpg_error_from_errno(rc);
1419 tty = ttybuf;
1421 else
1422 tty = pwm->pinentry_tty;
1425 if (!have_display && !tty)
1426 return GPG_ERR_ENOTTY;
1428 *p++ = "pinentry";
1429 *p++ = have_display ? "--display" : "--ttyname";
1430 *p++ = have_display ? pwm->pinentry_display ? pwm->pinentry_display : display : tty;
1432 if (pwm->lcctype) {
1433 *p++ = "--lc-ctype";
1434 *p++ = pwm->lcctype;
1437 if (pwm->lcmessages) {
1438 *p++ = "--lc-messages";
1439 *p++ = pwm->lcmessages;
1442 *p = NULL;
1444 if (!have_display) {
1445 *p++ = "--ttytype";
1446 *p++ = pwm->pinentry_term ? pwm->pinentry_term : getenv("TERM");
1447 *p = NULL;
1450 rc = assuan_pipe_connect(&ctx, pwm->pinentry_path ? pwm->pinentry_path : PINENTRY_PATH, argv, child_list);
1452 if (ttybuf)
1453 pwmd_free(ttybuf);
1455 if (rc)
1456 return rc;
1458 pwm->pid = assuan_get_pid(ctx);
1459 pwm->pctx = ctx;
1460 return set_pinentry_strings(pwm, 0);
1463 static gpg_error_t pinentry_command(pwm_t *pwm, char **result, const char *cmd)
1465 gpg_error_t n;
1467 if (!pwm->pctx) {
1468 n = launch_pinentry(pwm);
1470 if (n)
1471 return n;
1474 return assuan_command(pwm, pwm->pctx, result, cmd);
1477 static void pinentry_disconnect(pwm_t *pwm)
1479 if (pwm->pctx)
1480 assuan_disconnect(pwm->pctx);
1482 pwm->pctx = NULL;
1483 pwm->pid = -1;
1487 * Only called from a child process.
1489 static void catchsig(int sig)
1491 switch (sig) {
1492 case SIGALRM:
1493 if (gelapsed++ >= gtimeout) {
1494 global_error = pwmd_terminate_pinentry(gpwm);
1496 if (!global_error)
1497 global_error = GPG_ERR_TIMEOUT;
1499 break;
1502 alarm(1);
1503 break;
1504 default:
1505 break;
1508 #endif
1511 * Borrowed from libassuan.
1513 static char *percent_escape(const char *atext)
1515 const unsigned char *s;
1516 int len = strlen(atext) * 3 + 1;
1517 char *buf = (char *)pwmd_malloc(len), *p = buf;
1519 if (!buf)
1520 return NULL;
1522 for (s=(const unsigned char *)atext; *s; s++) {
1523 if (*s < ' ') {
1524 sprintf (p, "%%%02X", *s);
1525 p += 3;
1527 else
1528 *p++ = *s;
1531 *p = 0;
1532 return buf;
1535 static gpg_error_t send_command(pwm_t *pwm, char **result, const char *cmd)
1537 if (!cmd)
1538 return GPG_ERR_INV_ARG;
1540 return assuan_command(pwm, pwm->ctx, result, cmd);
1543 gpg_error_t pwmd_command_ap(pwm_t *pwm, char **result, const char *cmd,
1544 va_list ap)
1546 char *buf;
1547 size_t len;
1548 gpg_error_t error;
1550 if (!pwm || !cmd)
1551 return GPG_ERR_INV_ARG;
1554 * C99 allows the dst pointer to be null which will calculate the length
1555 * of the would-be result and return it.
1557 len = vsnprintf(NULL, 0, cmd, ap)+1;
1558 buf = (char *)pwmd_malloc(len);
1559 len = vsnprintf(buf, len, cmd, ap);
1560 error = send_command(pwm, result, buf);
1561 pwmd_free(buf);
1562 return error;
1566 * Avoid sending the BYE command here. libassuan will close the file
1567 * descriptor and release the assuan context. Use pwmd_close() instead.
1569 gpg_error_t pwmd_command(pwm_t *pwm, char **result, const char *cmd, ...)
1571 va_list ap;
1572 gpg_error_t error;
1574 if (!pwm || !cmd)
1575 return GPG_ERR_INV_ARG;
1577 if (result)
1578 *result = NULL;
1580 va_start(ap, cmd);
1581 error = pwmd_command_ap(pwm, result, cmd, ap);
1582 va_end(ap);
1583 return error;
1586 #ifdef WITH_PINENTRY
1587 static gpg_error_t do_getpin(pwm_t *pwm, char **result)
1589 if (gtimeout) {
1590 signal(SIGALRM, catchsig);
1591 alarm(1);
1594 *result = NULL;
1595 return pinentry_command(pwm, result, "GETPIN");
1598 static gpg_error_t getpin(pwm_t *pwm, char **result, int *try_n, int which)
1600 int pin_try = *try_n;
1601 gpg_error_t error;
1603 getpin_again:
1604 *try_n = pin_try;
1606 if (pin_try == -1) {
1607 error = set_pinentry_strings(pwm, which);
1609 if (error) {
1610 pinentry_disconnect(pwm);
1611 return error;
1614 else {
1615 if (pwm->pinentry_tries-1 != pin_try) {
1616 error = set_pinentry_strings(pwm, 1);
1618 if (error) {
1619 pinentry_disconnect(pwm);
1620 return error;
1625 error = do_getpin(pwm, result);
1628 * Since there was input cancel any timeout setting.
1630 alarm(0);
1632 if (error) {
1633 if (error == GPG_ERR_CANCELED)
1634 return GPG_ERR_CANCELED;
1636 if (pin_try != -1 && pin_try--)
1637 goto getpin_again;
1639 if (pwm->pctx)
1640 pinentry_disconnect(pwm);
1642 *try_n = pin_try;
1643 return error;
1646 return 0;
1648 #endif
1650 gpg_error_t pwmd_open_nb_finalize(pwm_t *pwm, pwmd_nb_status_t *pw)
1652 gpg_error_t error;
1654 #ifndef WITH_PINENTRY
1655 return GPG_ERR_NOT_IMPLEMENTED;
1656 #endif
1658 if (!pwm || !pw || !pw->filename[0])
1659 return GPG_ERR_INV_ARG;
1661 close(pw->fd);
1663 if (pw->error) {
1664 error = pw->error;
1665 goto fail;
1668 if (pwm->filename)
1669 pwmd_free(pwm->filename);
1671 pwm->filename = pwmd_strdup(pw->filename);
1672 memset(pw, 0, sizeof(pwmd_nb_status_t));
1673 return 0;
1675 fail:
1676 memset(pw, 0, sizeof(pwmd_nb_status_t));
1677 return error;
1680 static gpg_error_t do_open_command(pwm_t *pwm, const char *filename, char *password)
1682 char buf[ASSUAN_LINELENGTH];
1683 gpg_error_t error;
1684 char *result = NULL;
1686 snprintf(buf, sizeof(buf), "OPEN %s %s", filename, password ? password : "");
1687 error = send_command(pwm, &result, buf);
1688 memset(buf, 0, sizeof(buf));
1690 if (error && result)
1691 pwmd_free(result);
1693 return error;
1696 static int do_pwmd_open(pwm_t *pwm, gpg_error_t *error, const char *filename,
1697 int nb)
1699 char *result = NULL;
1700 char *password = NULL;
1701 char path[PATH_MAX];
1702 #ifdef WITH_PINENTRY
1703 int pin_try;
1704 #endif
1706 if (!pwm || !filename || !*filename) {
1707 *error = GPG_ERR_INV_ARG;
1708 return nb ? -1 : 1;
1711 #ifdef WITH_PINENTRY
1712 pin_try = pwm->pinentry_tries - 1;
1713 #endif
1716 * Avoid calling pinentry if the password is cached on the server or if
1717 * this is a new file.
1719 *error = pwmd_command(pwm, &result, "GETCONFIG data_directory");
1721 if (*error)
1722 return nb ? -1 : 1;
1724 snprintf(path, sizeof(path), "%s/%s", result, filename);
1725 pwmd_free(result);
1727 if (access(path, R_OK) == -1) {
1728 if (errno == ENOENT)
1729 goto gotpassword;
1732 *error = pwmd_command(pwm, &result, "ISCACHED %s", filename);
1734 if (*error == EPWMD_CACHE_NOT_FOUND) {
1735 if (pwm->passfunc) {
1736 password = (char *)pwm->passfunc(pwm->passdata);
1737 goto gotpassword;
1740 #ifdef WITH_PINENTRY
1742 * Get the password from pinentry.
1744 if (pwm->use_pinentry) {
1746 * Nonblocking is wanted. fork() then return a file descriptor
1747 * that the client can use to read() from.
1749 if (nb) {
1750 int p[2];
1751 pid_t pid;
1752 pwmd_nb_status_t pw;
1754 if (pipe(p) == -1) {
1755 *error = gpg_error_from_syserror();
1756 return -1;
1759 #ifdef WITH_LIBPTH
1760 pid = pth_fork();
1761 #else
1762 pid = fork();
1763 #endif
1765 switch (pid) {
1766 case 0:
1767 close(p[0]);
1768 strncpy(pw.filename, filename, sizeof(pw.filename));
1769 pw.filename[sizeof(pw.filename)-1] = 0;
1770 pw.fd = p[0];
1772 if (pwm->pinentry_timeout > 0) {
1773 gpwm = pwm;
1774 gtimeout = pwm->pinentry_timeout;
1775 gelapsed = 0;
1778 getpin_nb_again:
1779 *error = getpin(pwm, &password, &pin_try, 0);
1781 if (*error) {
1782 getpin_nb_fail:
1783 if (pwm->pctx)
1784 pinentry_disconnect(pwm);
1786 if (gtimeout && gelapsed >= gtimeout)
1787 *error = GPG_ERR_TIMEOUT;
1789 pw.error = *error;
1790 #ifdef WITH_LIBPTH
1791 pth_write(p[1], &pw, sizeof(pw));
1792 #else
1793 write(p[1], &pw, sizeof(pw));
1794 #endif
1795 close(p[1]);
1796 _exit(1);
1800 * Don't count the time it takes to open the file
1801 * which may have many iterations.
1803 signal(SIGALRM, SIG_DFL);
1804 *error = do_open_command(pwm, filename, password);
1806 if (pwm->pinentry_timeout)
1807 signal(SIGALRM, catchsig);
1809 if (pwm->pctx && *error == EPWMD_BADKEY) {
1810 if (pin_try-- > 0)
1811 goto getpin_nb_again;
1813 goto getpin_nb_fail;
1816 pinentry_disconnect(pwm);
1817 pw.error = 0;
1818 #ifdef WITH_LIBPTH
1819 pth_write(p[1], &pw, sizeof(pw));
1820 #else
1821 write(p[1], &pw, sizeof(pw));
1822 #endif
1823 close(p[1]);
1824 _exit(0);
1825 break;
1826 case -1:
1827 *error = gpg_error_from_syserror();
1828 close(p[0]);
1829 close(p[1]);
1830 return -1;
1831 default:
1832 break;
1835 close(p[1]);
1836 *error = 0;
1837 return p[0];
1840 else {
1841 #endif
1843 * Not using pinentry and the file was not found
1844 * in the cache.
1846 password = pwm->password;
1847 #ifdef WITH_PINENTRY
1849 #endif
1851 else if (*error)
1852 return nb ? -1 : 1;
1854 gotpassword:
1855 *error = do_open_command(pwm, filename, password);
1858 * Keep the user defined password set with pwmd_setopt(). The password may
1859 * be needed later (pwmd_save()) depending on the pwmd file cache settings.
1861 if (!pwm->passfunc && password && password != pwm->password)
1862 pwmd_free(password);
1864 #ifdef WITH_PINENTRY
1865 if (*error == EPWMD_BADKEY) {
1866 if (pin_try-- > 0 && !nb) {
1867 *error = pwmd_command(pwm, &result, "OPTION TITLE=%s",
1868 N_("Invalid passphrase, please try again."));
1870 if (*error)
1871 return 1;
1873 goto gotpassword;
1876 if (nb)
1877 pinentry_disconnect(pwm);
1879 return nb ? -1 : 1;
1881 #endif
1883 if (!*error) {
1884 if (pwm->filename)
1885 pwmd_free(pwm->filename);
1887 pwm->filename = pwmd_strdup(filename);
1891 * The file is cached or the file is a new file.
1893 if (nb)
1894 return *error ? -1 : -2;
1896 return *error ? 1 : 0;
1899 gpg_error_t pwmd_open(pwm_t *pwm, const char *filename)
1901 gpg_error_t error;
1903 do_pwmd_open(pwm, &error, filename, 0);
1904 return error;
1907 int pwmd_open_nb(pwm_t *pwm, gpg_error_t *error, const char *filename)
1909 #ifndef WITH_PINENTRY
1910 *error = GPG_ERR_NOT_IMPLEMENTED;
1911 return -1;
1912 #else
1913 return do_pwmd_open(pwm, error, filename, 1);
1914 #endif
1917 #ifdef WITH_PINENTRY
1918 static gpg_error_t do_save_getpin(pwm_t *pwm, char **password)
1920 int confirm = 0;
1921 gpg_error_t error;
1922 char *result = NULL;
1923 int pin_try = -1;
1925 again:
1926 error = getpin(pwm, &result, &pin_try, confirm ? 2 : 0);
1928 if (error) {
1929 if (pwm->pctx)
1930 pinentry_disconnect(pwm);
1932 if (*password)
1933 pwmd_free(*password);
1935 return error;
1938 if (!confirm++) {
1939 *password = result;
1940 goto again;
1943 if (strcmp(*password, result)) {
1944 pwmd_free(*password);
1945 pwmd_free(result);
1946 pinentry_disconnect(pwm);
1947 error = EPWMD_BADKEY;
1948 return error;
1951 pwmd_free(result);
1952 pinentry_disconnect(pwm);
1953 return 0;
1955 #endif
1957 static gpg_error_t do_save_command(pwm_t *pwm, char *password)
1959 char buf[ASSUAN_LINELENGTH];
1960 gpg_error_t error;
1961 char *result = NULL;
1963 snprintf(buf, sizeof(buf), "SAVE %s", password ? password : "");
1964 error = send_command(pwm, &result, buf);
1965 memset(&buf, 0, sizeof(buf));
1967 if (error && result)
1968 pwmd_free(result);
1970 return error;
1973 gpg_error_t pwmd_save_nb_finalize(pwm_t *pwm, pwmd_nb_status_t *pw)
1975 gpg_error_t rc;
1977 #ifndef WITH_PINENTRY
1978 return GPG_ERR_NOT_IMPLEMENTED;
1979 #endif
1981 if (!pwm || !pw || !pw->filename[0])
1982 return GPG_ERR_INV_ARG;
1984 close(pw->fd);
1985 rc = pw->error;
1986 memset(pw, 0, sizeof(pwmd_nb_status_t));
1987 return rc;
1990 static int do_pwmd_save(pwm_t *pwm, gpg_error_t *error, int nb)
1992 char *result = NULL;
1993 char *password = NULL;
1995 if (!pwm) {
1996 *error = GPG_ERR_INV_ARG;
1997 return nb ? -1 : 1;
2000 if (pwm->use_pinentry || pwm->passfunc) {
2001 *error = pwmd_command(pwm, &result, "ISCACHED %s", pwm->filename);
2003 if (*error == EPWMD_CACHE_NOT_FOUND) {
2004 if (pwm->passfunc)
2005 password = (char *)(*pwm->passfunc)(pwm->passdata);
2006 #ifdef WITH_PINENTRY
2007 else if (pwm->use_pinentry) {
2008 if (nb) {
2009 int p[2];
2010 pid_t pid;
2011 pwmd_nb_status_t pw;
2013 if (pipe(p) == -1) {
2014 *error = gpg_error_from_syserror();
2015 return -1;
2018 #ifdef WITH_LIBPTH
2019 pid = pth_fork();
2020 #else
2021 pid = fork();
2022 #endif
2024 switch (pid) {
2025 case 0:
2026 close(p[0]);
2027 strncpy(pw.filename, pwm->filename, sizeof(pw.filename));
2028 pw.filename[sizeof(pw.filename)-1] = 0;
2029 pw.fd = p[0];
2031 do {
2032 password = NULL;
2033 *error = do_save_getpin(pwm, &password);
2034 } while (*error == EPWMD_BADKEY);
2036 if (*error) {
2037 if (pwm->pctx)
2038 pinentry_disconnect(pwm);
2040 pw.error = *error;
2041 #ifdef WITH_LIBPTH
2042 pth_write(p[1], &pw, sizeof(pw));
2043 #else
2044 write(p[1], &pw, sizeof(pw));
2045 #endif
2046 close(p[1]);
2047 _exit(1);
2050 *error = do_save_command(pwm, password);
2051 pinentry_disconnect(pwm);
2052 pw.error = *error;
2053 #ifdef WITH_LIBPTH
2054 pth_write(p[1], &pw, sizeof(pw));
2055 #else
2056 write(p[1], &pw, sizeof(pw));
2057 #endif
2058 close(p[1]);
2059 _exit(0);
2060 break;
2061 case -1:
2062 *error = gpg_error_from_syserror();
2063 close(p[0]);
2064 close(p[1]);
2065 return -1;
2066 default:
2067 break;
2070 close(p[1]);
2071 *error = 0;
2072 return p[0];
2075 *error = do_save_getpin(pwm, &password);
2077 if (*error)
2078 return 1;
2080 #endif
2082 else {
2083 if (*error)
2084 return nb ? -1 : 1;
2087 else
2088 password = pwm->password;
2090 *error = do_save_command(pwm, password);
2092 if (!pwm->passfunc && password && password != pwm->password)
2093 pwmd_free(password);
2095 if (nb)
2096 return *error ? -1 : -2;
2098 return *error ? 1 : 0;
2101 int pwmd_save_nb(pwm_t *pwm, gpg_error_t *error)
2103 #ifndef WITH_PINENTRY
2104 *error = GPG_ERR_NOT_IMPLEMENTED;
2105 return -1;
2106 #else
2107 return do_pwmd_save(pwm, error, 1);
2108 #endif
2111 gpg_error_t pwmd_save(pwm_t *pwm)
2113 gpg_error_t error;
2115 do_pwmd_save(pwm, &error, 0);
2116 return error;
2119 gpg_error_t pwmd_setopt(pwm_t *pwm, pwmd_option_t opt, ...)
2121 va_list ap;
2122 int n = va_arg(ap, int);
2123 char *result;
2124 char *arg1;
2125 gpg_error_t error = 0;
2127 if (!pwm)
2128 return GPG_ERR_INV_ARG;
2130 va_start(ap, opt);
2132 switch (opt) {
2133 case PWMD_OPTION_STATUS_FUNC:
2134 pwm->status_func = va_arg(ap, pwmd_status_fn);
2135 break;
2136 case PWMD_OPTION_STATUS_DATA:
2137 pwm->status_data = va_arg(ap, void *);
2138 break;
2139 case PWMD_OPTION_PASSWORD_FUNC:
2140 pwm->passfunc = va_arg(ap, pwmd_password_fn);
2141 break;
2142 case PWMD_OPTION_PASSWORD_DATA:
2143 pwm->passdata = va_arg(ap, void *);
2144 break;
2145 case PWMD_OPTION_PASSWORD:
2146 arg1 = va_arg(ap, char *);
2148 if (pwm->password)
2149 pwmd_free(pwm->password);
2151 pwm->password = pwmd_strdup(arg1);
2152 break;
2153 case PWMD_OPTION_PINENTRY:
2154 n = va_arg(ap, int);
2156 if (n != 0 && n != 1) {
2157 va_end(ap);
2158 error = GPG_ERR_INV_VALUE;
2160 else {
2161 pwm->use_pinentry = n;
2162 error = pwmd_command(pwm, &result, "OPTION PINENTRY=%i",
2163 !pwm->use_pinentry);
2165 break;
2166 #ifdef WITH_PINENTRY
2167 case PWMD_OPTION_PINENTRY_TRIES:
2168 n = va_arg(ap, int);
2170 if (n <= 0) {
2171 va_end(ap);
2172 error = GPG_ERR_INV_VALUE;
2174 else
2175 pwm->pinentry_tries = n;
2176 break;
2177 #endif
2178 case PWMD_OPTION_PINENTRY_TIMEOUT:
2179 n = va_arg(ap, int);
2181 if (n < 0) {
2182 va_end(ap);
2183 error = GPG_ERR_INV_VALUE;
2185 else
2186 pwm->pinentry_timeout = n;
2188 if (!pwm->use_pinentry)
2189 error = pwmd_command(pwm, &result, "OPTION TIMEOUT=%i",
2190 pwm->pinentry_timeout);
2191 break;
2192 case PWMD_OPTION_PINENTRY_PATH:
2193 if (pwm->pinentry_path)
2194 pwmd_free(pwm->pinentry_path);
2196 pwm->pinentry_path = pwmd_strdup(va_arg(ap, char *));
2198 if (!pwm->use_pinentry)
2199 error = pwmd_command(pwm, &result, "OPTION PATH=%s",
2200 pwm->pinentry_path);
2201 break;
2202 case PWMD_OPTION_PINENTRY_TTY:
2203 if (pwm->pinentry_tty)
2204 pwmd_free(pwm->pinentry_tty);
2206 pwm->pinentry_tty = pwmd_strdup(va_arg(ap, char *));
2208 if (!pwm->use_pinentry)
2209 error = pwmd_command(pwm, &result, "OPTION TTY=%s",
2210 pwm->pinentry_tty);
2211 break;
2212 case PWMD_OPTION_PINENTRY_DISPLAY:
2213 if (pwm->pinentry_display)
2214 pwmd_free(pwm->pinentry_display);
2216 pwm->pinentry_display = pwmd_strdup(va_arg(ap, char *));
2218 if (!pwm->use_pinentry)
2219 error = pwmd_command(pwm, &result, "OPTION DISPLAY=%s",
2220 pwm->pinentry_display);
2221 break;
2222 case PWMD_OPTION_PINENTRY_TERM:
2223 if (pwm->pinentry_term)
2224 pwmd_free(pwm->pinentry_term);
2226 pwm->pinentry_term = pwmd_strdup(va_arg(ap, char *));
2228 if (!pwm->use_pinentry)
2229 error = pwmd_command(pwm, &result, "OPTION TTYTYPE=%s",
2230 pwm->pinentry_term);
2231 break;
2232 case PWMD_OPTION_PINENTRY_TITLE:
2233 if (pwm->title)
2234 pwmd_free(pwm->title);
2236 pwm->title = percent_escape(va_arg(ap, char *));
2238 if (!pwm->use_pinentry)
2239 error = pwmd_command(pwm, &result, "OPTION TITLE=%s",
2240 pwm->title);
2241 break;
2242 case PWMD_OPTION_PINENTRY_PROMPT:
2243 if (pwm->prompt)
2244 pwmd_free(pwm->prompt);
2246 pwm->prompt = percent_escape(va_arg(ap, char *));
2248 if (!pwm->use_pinentry)
2249 error = pwmd_command(pwm, &result, "OPTION PROMPT=%s",
2250 pwm->prompt);
2251 break;
2252 case PWMD_OPTION_PINENTRY_DESC:
2253 if (pwm->desc)
2254 pwmd_free(pwm->desc);
2256 pwm->desc = percent_escape(va_arg(ap, char *));
2258 if (!pwm->use_pinentry)
2259 error = pwmd_command(pwm, &result, "OPTION DESC=%s",
2260 pwm->desc);
2261 break;
2262 case PWMD_OPTION_PINENTRY_LC_CTYPE:
2263 if (pwm->lcctype)
2264 pwmd_free(pwm->lcctype);
2266 pwm->lcctype = pwmd_strdup(va_arg(ap, char *));
2268 if (!pwm->use_pinentry)
2269 error = pwmd_command(pwm, &result, "OPTION LC_CTYPE=%s",
2270 pwm->lcctype);
2271 break;
2272 case PWMD_OPTION_PINENTRY_LC_MESSAGES:
2273 if (pwm->lcmessages)
2274 pwmd_free(pwm->lcmessages);
2276 pwm->lcmessages = pwmd_strdup(va_arg(ap, char *));
2278 if (!pwm->use_pinentry)
2279 error = pwmd_command(pwm, &result, "OPTION LC_MESSAGES=%s",
2280 pwm->lcmessages);
2281 break;
2282 default:
2283 error = GPG_ERR_NOT_IMPLEMENTED;
2284 break;
2287 va_end(ap);
2288 return error;
2291 gpg_error_t pwmd_get_fd(pwm_t *pwm, int *fd)
2293 if (!pwm)
2294 return GPG_ERR_INV_ARG;
2296 if (pwm->fd == -1)
2297 return GPG_ERR_INV_STATE;
2299 *fd = pwm->fd;
2300 return 0;
2303 pwm_t *pwmd_new(const char *name)
2305 pwm_t *h = pwmd_calloc(1, sizeof(pwm_t));
2307 if (!h)
2308 return NULL;
2310 if (name) {
2311 h->name = pwmd_strdup(name);
2313 if (!h->name) {
2314 pwmd_free(h);
2315 return NULL;
2319 return h;
2322 void pwmd_free(void *ptr)
2324 xfree(ptr);
2327 void *pwmd_malloc(size_t size)
2329 return xmalloc(size);
2332 void *pwmd_calloc(size_t nmemb, size_t size)
2334 return xcalloc(nmemb, size);
2337 void *pwmd_realloc(void *ptr, size_t size)
2339 return xrealloc(ptr, size);
2342 char *pwmd_strdup(const char *str)
2344 return xstrdup(str);