Fixed --port.
[libpwmd.git] / src / libpwmd.c
blob99ddc1dc2a903ae707ff4de7c001082713dee287
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 static 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 if (n <= 0)
186 return GPG_ERR_EBADFD;
188 pwm->fd = active[0];
189 #ifdef WITH_PINENTRY
190 pwm->pid = -1;
191 pwm->pinentry_tries = 3;
192 #endif
193 assuan_set_pointer(pwm->ctx, pwm);
195 if (pwm->name)
196 return pwmd_command(pwm, NULL, "OPTION CLIENT NAME=%s", pwm->name);
198 return 0;
201 #ifdef WITH_TCP
202 static int read_hook(assuan_context_t ctx, assuan_fd_t fd, void *data,
203 size_t len, ssize_t *ret)
205 pwm_t *pwm = assuan_get_pointer(ctx);
206 int n = 0;
208 if (!pwm || !pwm->tcp_conn)
209 #ifdef WITH_LIBPTH
210 *ret = pth_read((int)fd, data, len);
211 #else
212 *ret = read((int)fd, data, len);
213 #endif
214 else {
215 do {
216 *ret = libssh2_channel_read(pwm->tcp_conn->channel, data, len);
217 n = libssh2_session_last_errno(pwm->tcp_conn->session);
218 } while (n == LIBSSH2_ERROR_EAGAIN);
221 return !n && *ret != -1 ? 1 : 0;
224 static int write_hook(assuan_context_t ctx, assuan_fd_t fd, const void *data,
225 size_t len, ssize_t *ret)
227 pwm_t *pwm = assuan_get_pointer(ctx);
228 int n = 0;
230 if (!pwm || !pwm->tcp_conn)
231 #ifdef WITH_LIBPTH
232 *ret = pth_write((int)fd, data, len);
233 #else
234 *ret = write((int)fd, data, len);
235 #endif
236 else {
237 do {
238 *ret = libssh2_channel_write(pwm->tcp_conn->channel, data, len);
239 n = libssh2_session_last_errno(pwm->tcp_conn->session);
240 } while (n == LIBSSH2_ERROR_EAGAIN);
243 return !n && *ret != -1 ? 1 : 0;
246 static void _ssh_deinit(pwmd_tcp_conn_t *conn);
247 static void free_tcp_conn(pwmd_tcp_conn_t *conn)
249 if (!conn)
250 return;
252 if (conn->username) {
253 pwmd_free(conn->username);
254 conn->username = NULL;
257 if (conn->known_hosts) {
258 pwmd_free(conn->known_hosts);
259 conn->known_hosts = NULL;
262 if (conn->identity) {
263 pwmd_free(conn->identity);
264 conn->identity = NULL;
267 if (conn->identity_pub) {
268 pwmd_free(conn->identity_pub);
269 conn->identity_pub = NULL;
272 if (conn->host) {
273 pwmd_free(conn->host);
274 conn->host = NULL;
277 if (conn->hostkey) {
278 pwmd_free(conn->hostkey);
279 conn->hostkey = NULL;
282 if (conn->chan) {
283 ares_destroy(conn->chan);
284 conn->chan = NULL;
287 if (conn->he) {
288 ares_free_hostent(conn->he);
289 conn->he = NULL;
292 if (conn->fd >= 0) {
293 close(conn->fd);
294 conn->fd = -1;
297 if (conn->session)
298 _ssh_deinit(conn);
299 else
300 pwmd_free(conn);
303 static void _ssh_deinit(pwmd_tcp_conn_t *conn)
305 if (!conn)
306 return;
308 if (conn->channel)
309 libssh2_channel_free(conn->channel);
311 if (conn->session) {
312 libssh2_session_disconnect(conn->session, "Bye!");
313 libssh2_session_free(conn->session);
316 conn->session = NULL;
317 conn->channel = NULL;
318 free_tcp_conn(conn);
321 static void _ssh_assuan_deinit(assuan_context_t ctx)
323 pwm_t *pwm = assuan_get_pointer(ctx);
325 pwm->tcp_conn->fd = -1;
326 _ssh_deinit(pwm->tcp_conn);
327 pwm->tcp_conn = NULL;
331 * Sets common options from both pwmd_ssh_connect() and
332 * pwmd_ssh_connect_async().
334 static gpg_error_t init_tcp_conn(pwmd_tcp_conn_t **dst, const char *host,
335 int port, const char *identity, const char *user, const char *hosts,
336 int get)
338 pwmd_tcp_conn_t *conn;
339 gpg_error_t rc = 0;
341 if (get) {
342 if (!host)
343 return GPG_ERR_INV_ARG;
345 else {
346 if (!host || !identity || !hosts)
347 return GPG_ERR_INV_ARG;
350 conn = pwmd_calloc(1, sizeof(pwmd_tcp_conn_t));
352 if (!conn)
353 return gpg_error_from_errno(ENOMEM);
355 conn->port = port == -1 ? 22 : port;
356 conn->host = pwmd_strdup(host);
358 if (!conn->host) {
359 rc = gpg_error_from_errno(ENOMEM);
360 goto fail;
363 if (!get) {
364 struct passwd pw;
365 char *pwbuf = _getpwuid(&pw);
367 if (!pwbuf) {
368 rc = gpg_error_from_errno(errno);
369 goto fail;
372 conn->username = pwmd_strdup(user ? user : pw.pw_name);
373 pwmd_free(pwbuf);
375 if (!conn->username) {
376 rc = gpg_error_from_errno(ENOMEM);
377 goto fail;
380 conn->identity = pwmd_strdup(identity);
382 if (!conn->identity) {
383 rc = gpg_error_from_errno(ENOMEM);
384 goto fail;
387 conn->identity_pub = pwmd_malloc(strlen(conn->identity)+5);
389 if (!conn->identity_pub) {
390 rc = gpg_error_from_errno(ENOMEM);
391 goto fail;
394 sprintf(conn->identity_pub, "%s.pub", conn->identity);
395 conn->known_hosts = pwmd_strdup(hosts);
397 if (!conn->known_hosts) {
398 rc = gpg_error_from_errno(ENOMEM);
399 goto fail;
403 *dst = conn;
404 return 0;
406 fail:
407 free_tcp_conn(conn);
408 return rc;
411 static gpg_error_t do_connect(pwm_t *pwm, int prot, void *addr)
413 struct sockaddr_in their_addr;
415 pwm->tcp_conn->fd = socket(prot, SOCK_STREAM, 0);
417 if (pwm->tcp_conn->fd == -1)
418 return gpg_error_from_syserror();
420 if (pwm->tcp_conn->async)
421 fcntl(pwm->tcp_conn->fd, F_SETFL, O_NONBLOCK);
423 pwm->cmd = ASYNC_CMD_CONNECT;
424 their_addr.sin_family = prot;
425 their_addr.sin_port = htons(pwm->tcp_conn->port);
426 their_addr.sin_addr = *((struct in_addr *)addr);
427 memset(their_addr.sin_zero, '\0', sizeof their_addr.sin_zero);
429 #ifdef WITH_LIBPTH
430 if (pth_connect(pwm->tcp_conn->fd, (struct sockaddr *)&their_addr,
431 sizeof(their_addr)) == -1)
432 #else
433 if (connect(pwm->tcp_conn->fd, (struct sockaddr *)&their_addr,
434 sizeof(their_addr)) == -1)
435 #endif
436 return gpg_error_from_syserror();
438 return 0;
441 static gpg_error_t ares_error_to_pwmd(int status)
443 if (status != ARES_SUCCESS)
444 warnx("%s", ares_strerror(status));
446 switch (status) {
447 case ARES_ENODATA:
448 case ARES_EFORMERR:
449 case ARES_ENOTFOUND:
450 return GPG_ERR_UNKNOWN_HOST;
451 case ARES_ESERVFAIL:
452 return GPG_ERR_EHOSTDOWN;
453 case ARES_ETIMEOUT:
454 return GPG_ERR_TIMEOUT;
455 case ARES_ENOMEM:
456 return gpg_error_from_errno(ENOMEM);
457 case ARES_ECONNREFUSED:
458 return GPG_ERR_ECONNREFUSED;
459 default:
460 /* FIXME ??? */
461 return GPG_ERR_EHOSTUNREACH;
464 return ARES_SUCCESS;
467 static void dns_resolve_cb(void *arg, int status, int timeouts,
468 unsigned char *abuf, int alen)
470 pwm_t *pwm = arg;
471 int rc;
472 struct hostent *he;
474 if (status == ARES_EDESTRUCTION)
475 return;
477 if (status != ARES_SUCCESS) {
478 pwm->tcp_conn->rc = ares_error_to_pwmd(status);
479 return;
482 //FIXME localhost. works with ipv4. maybe local system config error
483 /* Check for an IPv6 address first. */
484 rc = ares_parse_a_reply(abuf, alen, &he, NULL, NULL);
486 if (rc != ARES_SUCCESS) {
487 if (rc != ARES_ENODATA) {
488 pwm->tcp_conn->rc = ares_error_to_pwmd(status);
489 return;
492 rc = ares_parse_aaaa_reply(abuf, alen, &he, NULL, NULL);
494 if (rc != ARES_SUCCESS) {
495 pwm->tcp_conn->rc = ares_error_to_pwmd(status);
496 return;
500 pwm->tcp_conn->he = he;
501 pwm->tcp_conn->rc = do_connect(pwm, he->h_addrtype, he->h_addr);
504 static gpg_error_t _do_pwmd_tcp_connect_async(pwm_t *pwm, const char *host,
505 int port, const char *identity, const char *user,
506 const char *known_hosts, pwmd_async_cmd_t which)
508 pwmd_tcp_conn_t *conn;
509 gpg_error_t rc;
511 rc = init_tcp_conn(&conn, host, port, identity, user, known_hosts,
512 which == ASYNC_CMD_HOSTKEY ? 1 : 0);
514 if (rc)
515 return rc;
517 conn->async = 1;
518 pwm->tcp_conn = conn;
519 pwm->tcp_conn->cmd = which;
521 if (pwm->tcp_conn->cmd == ASYNC_CMD_HOSTKEY)
522 pwm->tcp_conn->get_only = 1;
524 pwm->cmd = ASYNC_CMD_DNS;
525 pwm->state = ASYNC_PROCESS;
526 ares_init(&pwm->tcp_conn->chan);
527 ares_query(pwm->tcp_conn->chan, pwm->tcp_conn->host, ns_c_any, ns_t_any,
528 dns_resolve_cb, pwm);
529 return 0;
532 gpg_error_t pwmd_ssh_connect_async(pwm_t *pwm, const char *host, int port,
533 const char *identity, const char *user, const char *known_hosts)
535 return _do_pwmd_tcp_connect_async(pwm, host, port, identity, user,
536 known_hosts, ASYNC_CMD_CONNECT);
539 static void *_ssh_malloc(size_t size, void **data)
541 return pwmd_malloc(size);
544 static void _ssh_free(void *ptr, void **data)
546 pwmd_free(ptr);
549 static void *_ssh_realloc(void *ptr, size_t size, void **data)
551 return pwmd_realloc(ptr, size);
554 static char *to_hex(const char *str, size_t slen)
556 int i;
557 char *buf = pwmd_malloc(slen*2+1);
559 if (!buf)
560 return NULL;
562 for (i = 0, buf[0] = 0; i < slen; i++) {
563 char tmp[3];
565 sprintf(tmp, "%02x", (unsigned char)str[i]);
566 strcat(buf, tmp);
569 return buf;
572 static int verify_host_key(pwm_t *pwm)
574 FILE *fp = fopen(pwm->tcp_conn->known_hosts, "r");
575 char *buf, *p;
577 if (!fp)
578 return 1;
580 buf = pwmd_malloc(LINE_MAX);
582 if (!buf)
583 goto fail;
585 while ((p = fgets(buf, LINE_MAX, fp))) {
586 if (*p == '#' || isspace(*p))
587 continue;
589 if (p[strlen(p)-1] == '\n')
590 p[strlen(p)-1] = 0;
592 if (!strcmp(buf, pwm->tcp_conn->hostkey))
593 goto done;
596 fail:
597 if (buf)
598 pwmd_free(buf);
600 fclose(fp);
601 return 1;
603 done:
604 pwmd_free(buf);
605 fclose(fp);
606 return 0;
609 static gpg_error_t authenticate_ssh(pwm_t *pwm)
611 const char *fp = libssh2_hostkey_hash(pwm->tcp_conn->session,
612 LIBSSH2_HOSTKEY_HASH_SHA1);
613 char *userauth;
615 pwm->tcp_conn->hostkey = to_hex(fp, 20);
617 if (!pwm->tcp_conn->hostkey)
618 return gpg_error_from_errno(ENOMEM);
620 if (pwm->tcp_conn->get_only)
621 return 0;
623 if (!fp || verify_host_key(pwm))
624 return GPG_ERR_CHECKSUM;
626 userauth = libssh2_userauth_list(pwm->tcp_conn->session,
627 pwm->tcp_conn->username, strlen(pwm->tcp_conn->username));
629 if (!userauth || !strstr(userauth, "publickey"))
630 return GPG_ERR_BAD_PIN_METHOD;
632 if (libssh2_userauth_publickey_fromfile(pwm->tcp_conn->session,
633 pwm->tcp_conn->username, pwm->tcp_conn->identity_pub,
634 pwm->tcp_conn->identity, NULL))
635 return GPG_ERR_BAD_SECKEY;
637 return 0;
640 static gpg_error_t setup_tcp_session(pwm_t *pwm)
642 assuan_context_t ctx;
643 struct assuan_io_hooks io_hooks = {read_hook, write_hook};
644 gpg_error_t rc;
646 pwm->tcp_conn->session = libssh2_session_init_ex(_ssh_malloc, _ssh_free,
647 _ssh_realloc, NULL);
649 if (!pwm->tcp_conn->session) {
650 rc = gpg_error_from_errno(ENOMEM);
651 goto fail;
654 if (libssh2_session_startup(pwm->tcp_conn->session, pwm->tcp_conn->fd)) {
655 rc = GPG_ERR_ASSUAN_SERVER_FAULT;
656 goto fail;
659 rc = authenticate_ssh(pwm);
661 if (rc)
662 goto fail;
664 /* pwmd_get_hostkey(). */
665 if (pwm->tcp_conn->get_only) {
666 pwm->result = pwmd_strdup(pwm->tcp_conn->hostkey);
668 if (!pwm->result) {
669 rc = gpg_error_from_errno(ENOMEM);
670 goto fail;
673 return 0;
676 pwm->tcp_conn->channel = libssh2_channel_open_session(pwm->tcp_conn->session);
678 if (!pwm->tcp_conn->channel) {
679 rc = GPG_ERR_ASSUAN_SERVER_FAULT;
680 goto fail;
683 if (libssh2_channel_shell(pwm->tcp_conn->channel)) {
684 rc = GPG_ERR_ASSUAN_SERVER_FAULT;
685 goto fail;
688 assuan_set_io_hooks(&io_hooks);
689 rc = assuan_socket_connect_fd(&ctx, pwm->tcp_conn->fd, 0, pwm);
691 if (rc)
692 goto fail;
694 assuan_set_finish_handler(ctx, _ssh_assuan_deinit);
695 pwm->ctx = ctx;
696 return _socket_connect_finalize(pwm);
698 fail:
699 free_tcp_conn(pwm->tcp_conn);
700 pwm->tcp_conn = NULL;
701 return rc;
704 static gpg_error_t _do_pwmd_tcp_connect(pwm_t *pwm, const char *host, int port,
705 const char *identity, const char *user, const char *known_hosts, int get)
707 pwmd_tcp_conn_t *conn;
708 gpg_error_t rc;
710 rc = init_tcp_conn(&conn, host, port, identity, user, known_hosts, get);
712 if (rc)
713 return rc;
715 pwm->tcp_conn = conn;
716 pwm->tcp_conn->get_only = get;
717 pwm->cmd = ASYNC_CMD_DNS;
718 ares_init(&pwm->tcp_conn->chan);
719 ares_query(pwm->tcp_conn->chan, pwm->tcp_conn->host, ns_c_any, ns_t_any,
720 dns_resolve_cb, pwm);
722 /* dns_resolve_cb() may have already been called. */
723 if (pwm->tcp_conn->rc) {
724 rc = pwm->tcp_conn->rc;
725 goto fail;
729 * Fake a blocking DNS lookup. libcares does a better job than
730 * getaddrinfo().
732 do {
733 fd_set rfds, wfds;
734 int n;
735 struct timeval tv;
737 FD_ZERO(&rfds);
738 FD_ZERO(&wfds);
739 n = ares_fds(pwm->tcp_conn->chan, &rfds, &wfds);
740 ares_timeout(pwm->tcp_conn->chan, NULL, &tv);
741 #ifdef WITH_LIBPTH
742 n = pth_select(n, &rfds, &wfds, NULL, &tv);
743 #else
744 n = select(n, &rfds, &wfds, NULL, &tv);
745 #endif
747 if (n == -1) {
748 rc = gpg_error_from_syserror();
749 goto fail;
751 else if (n == 0) {
752 rc = GPG_ERR_TIMEOUT;
753 goto fail;
756 ares_process(pwm->tcp_conn->chan, &rfds, &wfds);
758 if (pwm->tcp_conn->rc)
759 break;
760 } while (pwm->cmd == ASYNC_CMD_DNS);
762 if (pwm->tcp_conn->rc) {
763 rc = pwm->tcp_conn->rc;
764 goto fail;
767 return setup_tcp_session(pwm);
769 fail:
770 return rc;
773 gpg_error_t pwmd_ssh_connect(pwm_t *pwm, const char *host, int port,
774 const char *identity, const char *user, const char *known_hosts)
776 return _do_pwmd_tcp_connect(pwm, host, port, identity, user, known_hosts, 0);
779 /* Must free the result with pwmd_free(). */
780 gpg_error_t pwmd_get_hostkey(const char *host, int port, char **result)
782 char *hostkey;
783 pwm_t *pwm = pwmd_new(NULL);
784 gpg_error_t rc;
786 if (!pwm)
787 return gpg_error_from_errno(ENOMEM);
789 rc = _do_pwmd_tcp_connect(pwm, host, port, NULL, NULL, NULL, 1);
791 if (rc) {
792 pwmd_close(pwm);
793 return rc;
796 hostkey = pwmd_strdup(pwm->tcp_conn->hostkey);
798 if (!hostkey)
799 rc = gpg_error_from_errno(ENOMEM);
801 pwmd_close(pwm);
802 *result = hostkey;
803 return rc;
806 gpg_error_t pwmd_get_hostkey_async(pwm_t *pwm, const char *host, int port)
808 return _do_pwmd_tcp_connect_async(pwm, host, port, NULL, NULL, NULL,
809 ASYNC_CMD_HOSTKEY);
811 #endif
813 gpg_error_t pwmd_connect(pwm_t *pwm, const char *path)
815 char *socketpath = NULL;
816 assuan_context_t ctx;
817 struct passwd pw;
818 char *pwbuf = _getpwuid(&pw);
819 gpg_error_t rc;
821 if (!pwbuf)
822 return gpg_error_from_errno(errno);
824 if (!path) {
825 socketpath = (char *)pwmd_malloc(strlen(pw.pw_dir) + strlen("/.pwmd/socket") + 1);
826 sprintf(socketpath, "%s/.pwmd/socket", pw.pw_dir);
828 else
829 socketpath = pwmd_strdup(path);
831 pwmd_free(pwbuf);
832 rc = assuan_socket_connect_ext(&ctx, socketpath, -1, 0);
833 pwmd_free(socketpath);
835 if (rc)
836 return rc;
838 pwm->ctx = ctx;
839 return _socket_connect_finalize(pwm);
842 void pwmd_close(pwm_t *pwm)
844 if (!pwm)
845 return;
847 if (pwm->ctx)
848 assuan_disconnect(pwm->ctx);
850 if (pwm->password)
851 pwmd_free(pwm->password);
853 if (pwm->title)
854 pwmd_free(pwm->title);
856 if (pwm->desc)
857 pwmd_free(pwm->desc);
859 if (pwm->prompt)
860 pwmd_free(pwm->prompt);
862 if (pwm->pinentry_tty)
863 pwmd_free(pwm->pinentry_tty);
865 if (pwm->pinentry_display)
866 pwmd_free(pwm->pinentry_display);
868 if (pwm->pinentry_term)
869 pwmd_free(pwm->pinentry_term);
871 if (pwm->lcctype)
872 pwmd_free(pwm->lcctype);
874 if (pwm->lcmessages)
875 pwmd_free(pwm->lcmessages);
877 if (pwm->filename)
878 pwmd_free(pwm->filename);
880 if (pwm->name)
881 pwmd_free(pwm->name);
883 #ifdef WITH_TCP
884 if (pwm->tcp_conn)
885 free_tcp_conn(pwm->tcp_conn);
886 #endif
888 pwmd_free(pwm);
891 static int mem_realloc_cb(void *data, const void *buffer, size_t len)
893 membuf_t *mem = (membuf_t *)data;
894 void *p;
896 if (!buffer)
897 return 0;
899 if ((p = pwmd_realloc(mem->buf, mem->len + len)) == NULL)
900 return 1;
902 mem->buf = p;
903 memcpy((char *)mem->buf + mem->len, buffer, len);
904 mem->len += len;
905 return 0;
908 static int _inquire_cb(void *data, const char *keyword)
910 pwm_t *pwm = (pwm_t *)data;
911 gpg_error_t rc = 0;
912 int flags = fcntl(pwm->fd, F_GETFL);
914 /* Shouldn't get this far without a callback. */
915 if (!pwm->inquire_func)
916 return GPG_ERR_INV_ARG;
919 * Since the socket file descriptor is probably set to non-blocking, set to
920 * blocking to prevent GPG_ERR_EAGAIN errors. This should be fixes when
921 * asynchronous INQUIRE is supported by either libassuan or a later
922 * libpwmd.
924 fcntl(pwm->fd, F_SETFL, 0);
926 for (;;) {
927 char *result = NULL;
928 size_t len;
929 gpg_error_t arc;
931 rc = pwm->inquire_func(pwm->inquire_data, keyword, rc, &result, &len);
932 rc = gpg_err_code(rc);
934 if (rc == GPG_ERR_EOF || !rc) {
935 if (len <= 0 || !result || !*result) {
936 rc = 0;
937 break;
940 arc = assuan_send_data(pwm->ctx, result, len);
942 if (rc == GPG_ERR_EOF) {
943 rc = arc;
944 break;
947 rc = arc;
949 else if (rc)
950 break;
953 fcntl(pwm->fd, F_SETFL, flags);
954 return rc;
957 static gpg_error_t do_nb_command(pwm_t *pwm, const char *cmd, ...)
959 char *buf;
960 gpg_error_t rc;
961 va_list ap;
963 if (pwm->state == ASYNC_DONE)
964 pwm->state = ASYNC_INIT;
966 if (pwm->state != ASYNC_INIT)
967 return GPG_ERR_INV_STATE;
969 buf = pwmd_malloc(ASSUAN_LINELENGTH+1);
971 if (!buf)
972 return gpg_error_from_errno(ENOMEM);
974 va_start(ap, cmd);
975 vsnprintf(buf, ASSUAN_LINELENGTH, cmd, ap);
976 va_end(ap);
977 rc = assuan_write_line(pwm->ctx, buf);
978 pwmd_free(buf);
980 if (!rc)
981 pwm->state = ASYNC_PROCESS;
983 return rc;
986 gpg_error_t pwmd_open_async(pwm_t *pwm, const char *filename)
988 if (!pwm || !filename)
989 return GPG_ERR_INV_ARG;
991 if (pwm->cmd != ASYNC_CMD_OPEN) {
992 pwm->pin_try = 0;
994 if (pwm->filename)
995 pwmd_free(pwm->filename);
997 pwm->filename = pwmd_strdup(filename);
1000 pwm->cmd = ASYNC_CMD_OPEN;
1001 return do_nb_command(pwm, "OPEN %s %s", filename,
1002 pwm->password ? pwm->password : "");
1005 gpg_error_t pwmd_save_async(pwm_t *pwm)
1007 if (!pwm)
1008 return GPG_ERR_INV_ARG;
1010 pwm->cmd = ASYNC_CMD_SAVE;
1011 return do_nb_command(pwm, "SAVE %s", pwm->password ? pwm->password : "");
1014 static gpg_error_t parse_assuan_line(pwm_t *pwm)
1016 gpg_error_t rc;
1017 char *line;
1018 size_t len;
1020 rc = assuan_read_line(pwm->ctx, &line, &len);
1022 if (!rc) {
1023 if (line[0] == 'O' && line[1] == 'K' &&
1024 (line[2] == 0 || line[2] == ' ')) {
1025 pwm->state = ASYNC_DONE;
1027 else if (line[0] == '#') {
1029 else if (line[0] == 'S' && (line[1] == 0 || line[1] == ' ')) {
1030 if (pwm->status_func) {
1031 pwm->status_func(pwm->status_data,
1032 line[1] == 0 ? line+1 : line+2);
1035 else if (line[0] == 'E' && line[1] == 'R' && line[2] == 'R' &&
1036 (line[3] == 0 || line[3] == ' ')) {
1037 line += 4;
1038 rc = atoi(line);
1039 pwm->state = ASYNC_DONE;
1043 return rc;
1046 gpg_error_t pwmd_pending_line(pwm_t *pwm)
1048 if (!pwm)
1049 return GPG_ERR_INV_ARG;
1051 if (!pwm->ctx)
1052 return GPG_ERR_INV_STATE;
1054 return assuan_pending_line(pwm->ctx) ? 0 : GPG_ERR_NO_DATA;
1057 static pwmd_async_t reset_async(pwm_t *pwm, int done)
1059 pwm->state = ASYNC_INIT;
1060 pwm->cmd = ASYNC_CMD_NONE;
1062 #ifdef WITH_PINENTRY
1063 if (pwm->nb_fd != -1) {
1064 close(pwm->nb_fd);
1065 pwm->nb_fd = -1;
1067 #endif
1068 #ifdef WITH_TCP
1069 if (done && pwm->tcp_conn && pwm->tcp_conn->fd != -1) {
1070 close(pwm->tcp_conn->fd);
1071 pwm->tcp_conn->fd = -1;
1073 #endif
1075 return ASYNC_DONE;
1078 pwmd_async_t pwmd_process(pwm_t *pwm, gpg_error_t *rc, char **result)
1080 fd_set fds;
1081 int n;
1082 struct timeval tv = {0, 0};
1084 *rc = 0;
1086 if (!pwm) {
1087 *rc = GPG_ERR_INV_ARG;
1088 return ASYNC_DONE;
1091 /* When not in a command, this will let libassuan process status messages
1092 * by calling PWMD_OPTION_STATUS_FUNC. The client can poll the file
1093 * descriptor returned by pwmd_get_fd() to determine when this should be
1094 * called or call pwmd_pending_line() to determine whether a buffered line
1095 * needs to be processed. */
1096 if (pwm->cmd == ASYNC_CMD_NONE) {
1097 *rc = assuan_command(pwm, pwm->ctx, NULL, "NOP");
1098 return pwm->state;
1101 /* Fixes pwmd_open/save_async2() when there is a cached or new file. */
1102 if (pwm->state == ASYNC_DONE) {
1103 reset_async(pwm, 0);
1104 return ASYNC_DONE;
1107 if (pwm->state != ASYNC_PROCESS) {
1108 *rc = GPG_ERR_INV_STATE;
1109 return ASYNC_DONE;
1112 #ifdef WITH_TCP
1113 if (pwm->cmd == ASYNC_CMD_DNS) {
1114 fd_set rfds, wfds;
1116 if (pwm->tcp_conn->rc) {
1117 *rc = pwm->tcp_conn->rc;
1118 reset_async(pwm, 1);
1119 return ASYNC_DONE;
1122 FD_ZERO(&rfds);
1123 FD_ZERO(&wfds);
1124 n = ares_fds(pwm->tcp_conn->chan, &rfds, &wfds);
1126 /* Shouldn't happen. */
1127 if (!n)
1128 return pwm->state;
1130 #ifdef WITH_LIBPTH
1131 n = pth_select(n, &rfds, &wfds, NULL, &tv);
1132 #else
1133 n = select(n, &rfds, &wfds, NULL, &tv);
1134 #endif
1136 if (n > 0)
1137 ares_process(pwm->tcp_conn->chan, &rfds, &wfds);
1139 return pwm->state;
1141 else if (pwm->cmd == ASYNC_CMD_CONNECT) {
1142 if (pwm->tcp_conn->rc == GPG_ERR_EINPROGRESS) {
1143 int ret;
1144 socklen_t len = sizeof(int);
1146 FD_ZERO(&fds);
1147 FD_SET(pwm->tcp_conn->fd, &fds);
1148 #ifdef WITH_LIBPTH
1149 n = pth_select(pwm->tcp_conn->fd+1, NULL, &fds, NULL, &tv);
1150 #else
1151 n = select(pwm->tcp_conn->fd+1, NULL, &fds, NULL, &tv);
1152 #endif
1154 if (!n || !FD_ISSET(pwm->tcp_conn->fd, &fds))
1155 return pwm->state;
1156 else if (n == -1) {
1157 *rc = gpg_error_from_syserror();
1158 reset_async(pwm, 1);
1159 return ASYNC_DONE;
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 reset_async(pwm, 1);
1167 return ASYNC_DONE;
1170 else if (pwm->tcp_conn->rc) {
1171 *rc = pwm->tcp_conn->rc;
1172 reset_async(pwm, 1);
1173 return ASYNC_DONE;
1176 fcntl(pwm->tcp_conn->fd, F_SETFL, 0);
1177 *rc = setup_tcp_session(pwm);
1179 if (!*rc) {
1180 switch (pwm->tcp_conn->cmd) {
1181 case ASYNC_CMD_HOSTKEY:
1182 if (!*rc)
1183 *result = pwm->result;
1184 break;
1185 default:
1186 break;
1190 return reset_async(pwm, *rc ? 1 : 0);
1192 #endif
1194 #ifdef WITH_PINENTRY
1195 if (pwm->cmd == ASYNC_CMD_OPEN2 || pwm->cmd == ASYNC_CMD_SAVE2) {
1196 int status;
1198 if (pwm->nb_fd == -1) {
1199 *rc = GPG_ERR_INV_STATE;
1200 return reset_async(pwm, 0);
1203 FD_ZERO(&fds);
1204 FD_SET(pwm->nb_fd, &fds);
1205 #ifdef WITH_LIBPTH
1206 n = pth_select(pwm->nb_fd+1, &fds, NULL, NULL, &tv);
1207 #else
1208 n = select(pwm->nb_fd+1, &fds, NULL, NULL, &tv);
1209 #endif
1210 if (n == -1) {
1211 *rc = gpg_error_from_syserror();
1212 return reset_async(pwm, 0);
1215 if (n > 0) {
1216 pwmd_nb_status_t nb;
1217 #ifdef WITH_LIBPTH
1218 size_t len = pth_read(pwm->nb_fd, &nb, sizeof(nb));
1219 #else
1220 size_t len = read(pwm->nb_fd, &nb, sizeof(nb));
1221 #endif
1222 waitpid(pwm->nb_pid, &status, WNOHANG);
1224 if (len != sizeof(nb)) {
1225 *rc = gpg_error_from_syserror();
1226 return reset_async(pwm, pwm->cmd == ASYNC_CMD_OPEN2 ? 1 : 0);
1229 *rc = nb.error;
1231 if (*rc == EPWMD_BADKEY && pwm->cmd == ASYNC_CMD_SAVE2) {
1232 reset_async(pwm, 0);
1233 *rc = pwmd_save_async2(pwm);
1234 return ASYNC_PROCESS;
1236 else if (*rc)
1237 return reset_async(pwm, pwm->cmd == ASYNC_CMD_OPEN2 ? 1 : 0);
1239 if (pwm->cmd == ASYNC_CMD_SAVE2) {
1240 *rc = do_save_command(pwm, nb.password);
1241 memset(&nb, 0, sizeof(pwmd_nb_status_t));
1242 return reset_async(pwm, 0);
1245 if (pwm->cmd == ASYNC_CMD_OPEN2) {
1246 *rc = do_open_command(pwm, pwm->filename, nb.password);
1247 memset(&nb, 0, sizeof(pwmd_nb_status_t));
1249 if (*rc == EPWMD_BADKEY) {
1250 if (++pwm->pin_try < pwm->pinentry_tries) {
1251 int n = pwm->pin_try;
1253 reset_async(pwm, 0);
1254 pwm->pin_try = n;
1255 pwm->cmd = ASYNC_CMD_OPEN2;
1256 *rc = pwmd_open_async2(pwm, pwm->filename);
1258 if (*rc)
1259 return reset_async(pwm, 1);
1261 return pwm->state;
1265 return reset_async(pwm, *rc ? 1 : 0);
1269 return pwm->state;
1271 #endif
1273 if (pwm->fd < 0) {
1274 *rc = GPG_ERR_INV_STATE;
1275 return reset_async(pwm, 0);
1278 /* This is for the non-blocking OPEN and SAVE commands. */
1279 FD_ZERO(&fds);
1280 FD_SET(pwm->fd, &fds);
1281 #ifdef WITH_LIBPTH
1282 n = pth_select(pwm->fd+1, &fds, NULL, NULL, &tv);
1283 #else
1284 n = select(pwm->fd+1, &fds, NULL, NULL, &tv);
1285 #endif
1287 if (n == -1) {
1288 *rc = gpg_error_from_syserror();
1289 return reset_async(pwm, 0);
1292 if (n > 0) {
1293 if (FD_ISSET(pwm->fd, &fds))
1294 *rc = parse_assuan_line(pwm);
1297 while (!*rc && assuan_pending_line(pwm->ctx))
1298 *rc = parse_assuan_line(pwm);
1300 /* For pinentry retries. */
1301 if (pwm->cmd == ASYNC_CMD_OPEN && gpg_err_code(*rc) == EPWMD_BADKEY &&
1302 ++pwm->pin_try < pwm->pinentry_tries) {
1303 pwm->state = ASYNC_INIT;
1304 *rc = pwmd_open_async(pwm, pwm->filename);
1307 if (*rc)
1308 return reset_async(pwm, pwm->cmd == ASYNC_CMD_OPEN ? 1 : 0);
1310 if (pwm->state == ASYNC_DONE) {
1311 reset_async(pwm, 0);
1312 return ASYNC_DONE;
1315 return pwm->state;
1318 static gpg_error_t assuan_command(pwm_t *pwm, assuan_context_t ctx,
1319 char **result, const char *cmd)
1321 membuf_t data;
1322 gpg_error_t rc;
1324 data.len = 0;
1325 data.buf = NULL;
1327 rc = assuan_transact(ctx, cmd, mem_realloc_cb, &data, _inquire_cb, pwm,
1328 pwm->status_func, pwm->status_data);
1330 if (rc) {
1331 if (data.buf) {
1332 pwmd_free(data.buf);
1333 data.buf = NULL;
1336 else {
1337 if (data.buf) {
1338 mem_realloc_cb(&data, "", 1);
1340 if (!result) {
1341 pwmd_free(data.buf);
1342 rc = GPG_ERR_INV_ARG;
1344 else
1345 *result = (char *)data.buf;
1349 return gpg_err_code(rc);
1352 gpg_error_t pwmd_inquire(pwm_t *pwm, const char *cmd, pwmd_inquire_fn fn,
1353 void *data)
1355 if (!pwm || !cmd || !fn)
1356 return GPG_ERR_INV_ARG;
1358 pwm->inquire_func = fn;
1359 pwm->inquire_data = data;
1360 return assuan_command(pwm, pwm->ctx, NULL, cmd);
1363 static gpg_error_t terminate_pinentry(pwm_t *pwm)
1365 #ifndef WITH_PINENTRY
1366 return GPG_ERR_NOT_IMPLEMENTED;
1367 #else
1368 pid_t pid = pwm->pid;
1370 pwm->pid = -1;
1372 if (!pwm || pid == -1)
1373 return GPG_ERR_INV_ARG;
1375 if (kill(pid, 0) == 0) {
1376 if (kill(pid, SIGTERM) == -1) {
1377 if (kill(pid, SIGKILL) == -1)
1378 return gpg_error_from_errno(errno);
1381 else
1382 return gpg_error_from_errno(errno);
1384 return 0;
1385 #endif
1388 #ifdef WITH_PINENTRY
1389 static gpg_error_t set_pinentry_strings(pwm_t *pwm, int which)
1391 char *tmp;
1392 gpg_error_t error;
1394 tmp = pwmd_malloc(ASSUAN_LINELENGTH+1);
1396 if (!tmp)
1397 return gpg_error_from_errno(ENOMEM);
1399 if (!pwm->title)
1400 pwm->title = pwmd_strdup(N_("LibPWMD"));
1402 if (!pwm->title)
1403 goto fail_no_mem;
1405 if (!pwm->prompt)
1406 pwm->prompt = pwmd_strdup(N_("Passphrase:"));
1408 if (!pwm->prompt)
1409 goto fail_no_mem;
1411 if (!pwm->desc && !which) {
1412 pwm->desc = pwmd_strdup(N_("Enter a passphrase."));
1414 if (!pwm->desc)
1415 goto fail_no_mem;
1418 if (which == 1)
1419 snprintf(tmp, ASSUAN_LINELENGTH, "SETERROR %s",
1420 N_("Invalid passphrase, please try again."));
1421 else if (which == 2)
1422 snprintf(tmp, ASSUAN_LINELENGTH, "SETERROR %s",
1423 N_("Please type the passphrase again for confirmation."));
1424 else
1425 snprintf(tmp, ASSUAN_LINELENGTH, "SETERROR %s", pwm->desc);
1427 error = pinentry_command(pwm, NULL, tmp);
1429 if (error) {
1430 pwmd_free(tmp);
1431 return error;
1434 snprintf(tmp, ASSUAN_LINELENGTH, "SETPROMPT %s", pwm->prompt);
1435 error = pinentry_command(pwm, NULL, tmp);
1437 if (error) {
1438 pwmd_free(tmp);
1439 return error;
1442 snprintf(tmp, ASSUAN_LINELENGTH, "SETDESC %s", pwm->title);
1443 error = pinentry_command(pwm, NULL, tmp);
1444 pwmd_free(tmp);
1445 return error;
1447 fail_no_mem:
1448 pwmd_free(tmp);
1449 return gpg_error_from_errno(ENOMEM);
1452 static void update_pinentry_settings(pwm_t *pwm)
1454 FILE *fp;
1455 char buf[LINE_MAX];
1456 char *p;
1457 struct passwd pw;
1458 char *pwbuf = _getpwuid(&pw);
1460 if (!pwbuf)
1461 return;
1463 snprintf(buf, sizeof(buf), "%s/.pwmd/pinentry.conf", pw.pw_dir);
1464 pwmd_free(pwbuf);
1466 if ((fp = fopen(buf, "r")) == NULL)
1467 return;
1469 while ((p = fgets(buf, sizeof(buf), fp)) != NULL) {
1470 char name[32], val[256];
1472 if (sscanf(p, " %31[a-zA-Z] = %255s", name, val) != 2)
1473 continue;
1475 if (strcasecmp(name, "TTYNAME") == 0) {
1476 pwmd_free(pwm->pinentry_tty);
1477 pwm->pinentry_tty = pwmd_strdup(val);
1479 else if (strcasecmp(name, "TTYTYPE") == 0) {
1480 pwmd_free(pwm->pinentry_term);
1481 pwm->pinentry_term = pwmd_strdup(val);
1483 else if (strcasecmp(name, "DISPLAY") == 0) {
1484 pwmd_free(pwm->pinentry_display);
1485 pwm->pinentry_display = pwmd_strdup(val);
1487 else if (strcasecmp(name, "PATH") == 0) {
1488 pwmd_free(pwm->pinentry_path);
1489 pwm->pinentry_path = pwmd_strdup(val);
1493 fclose(fp);
1496 static gpg_error_t launch_pinentry(pwm_t *pwm)
1498 int rc;
1499 assuan_context_t ctx;
1500 int child_list[] = {-1};
1501 char *display = getenv("DISPLAY");
1502 const char *argv[10];
1503 const char **p = argv;
1504 int have_display = 0;
1505 char *tty = NULL;
1506 char *ttybuf = NULL;
1508 update_pinentry_settings(pwm);
1510 if (pwm->pinentry_display || display)
1511 have_display = 1;
1512 else {
1513 if (!pwm->pinentry_tty) {
1514 ttybuf = pwmd_malloc(255);
1516 if (!ttybuf)
1517 return gpg_error_from_errno(ENOMEM);
1519 rc = ttyname_r(STDOUT_FILENO, ttybuf, 255);
1521 if (rc) {
1522 pwmd_free(ttybuf);
1523 return gpg_error_from_errno(rc);
1526 tty = ttybuf;
1528 else
1529 tty = pwm->pinentry_tty;
1532 if (!have_display && !tty)
1533 return GPG_ERR_ENOTTY;
1535 *p++ = "pinentry";
1536 *p++ = have_display ? "--display" : "--ttyname";
1537 *p++ = have_display ? pwm->pinentry_display ? pwm->pinentry_display : display : tty;
1539 if (pwm->lcctype) {
1540 *p++ = "--lc-ctype";
1541 *p++ = pwm->lcctype;
1544 if (pwm->lcmessages) {
1545 *p++ = "--lc-messages";
1546 *p++ = pwm->lcmessages;
1549 *p = NULL;
1551 if (!have_display) {
1552 *p++ = "--ttytype";
1553 *p++ = pwm->pinentry_term ? pwm->pinentry_term : getenv("TERM");
1554 *p = NULL;
1557 rc = assuan_pipe_connect(&ctx, pwm->pinentry_path ? pwm->pinentry_path : PINENTRY_PATH, argv, child_list);
1559 if (ttybuf)
1560 pwmd_free(ttybuf);
1562 if (rc)
1563 return rc;
1565 pwm->pid = assuan_get_pid(ctx);
1566 pwm->pctx = ctx;
1567 return set_pinentry_strings(pwm, 0);
1570 static gpg_error_t pinentry_command(pwm_t *pwm, char **result, const char *cmd)
1572 gpg_error_t n;
1574 if (!pwm->pctx) {
1575 n = launch_pinentry(pwm);
1577 if (n)
1578 return n;
1581 return assuan_command(pwm, pwm->pctx, result, cmd);
1584 static void pinentry_disconnect(pwm_t *pwm)
1586 if (pwm->pctx)
1587 assuan_disconnect(pwm->pctx);
1589 pwm->pctx = NULL;
1590 pwm->pid = -1;
1594 * Only called from a child process.
1596 static void catchsig(int sig)
1598 switch (sig) {
1599 case SIGALRM:
1600 if (gelapsed++ >= gtimeout)
1601 terminate_pinentry(gpwm);
1602 else
1603 alarm(1);
1604 break;
1605 default:
1606 break;
1609 #endif
1612 * Borrowed from libassuan.
1614 static char *percent_escape(const char *atext)
1616 const unsigned char *s;
1617 int len = strlen(atext) * 3 + 1;
1618 char *buf = (char *)pwmd_malloc(len), *p = buf;
1620 if (!buf)
1621 return NULL;
1623 for (s=(const unsigned char *)atext; *s; s++) {
1624 if (*s < ' ') {
1625 sprintf (p, "%%%02X", *s);
1626 p += 3;
1628 else
1629 *p++ = *s;
1632 *p = 0;
1633 return buf;
1636 static gpg_error_t send_command(pwm_t *pwm, char **result, const char *cmd)
1638 if (!cmd)
1639 return GPG_ERR_INV_ARG;
1641 return assuan_command(pwm, pwm->ctx, result, cmd);
1644 gpg_error_t pwmd_command_ap(pwm_t *pwm, char **result, const char *cmd,
1645 va_list ap)
1647 char *buf;
1648 size_t len;
1649 gpg_error_t error;
1651 if (!pwm || !cmd)
1652 return GPG_ERR_INV_ARG;
1655 * C99 allows the dst pointer to be null which will calculate the length
1656 * of the would-be result and return it.
1658 len = vsnprintf(NULL, 0, cmd, ap)+1;
1659 buf = (char *)pwmd_malloc(len);
1661 if (!buf)
1662 return gpg_error_from_errno(ENOMEM);
1664 len = vsnprintf(buf, len, cmd, ap);
1666 if (buf[strlen(buf)-1] == '\n')
1667 buf[strlen(buf)-1] = 0;
1669 if (buf[strlen(buf)-1] == '\r')
1670 buf[strlen(buf)-1] = 0;
1672 error = send_command(pwm, result, buf);
1673 pwmd_free(buf);
1674 return error;
1678 * Avoid sending the BYE command here. libassuan will close the file
1679 * descriptor and release the assuan context. Use pwmd_close() instead.
1681 gpg_error_t pwmd_command(pwm_t *pwm, char **result, const char *cmd, ...)
1683 va_list ap;
1684 gpg_error_t error;
1686 if (!pwm || !cmd)
1687 return GPG_ERR_INV_ARG;
1689 if (result)
1690 *result = NULL;
1692 va_start(ap, cmd);
1693 error = pwmd_command_ap(pwm, result, cmd, ap);
1694 va_end(ap);
1695 return error;
1698 #ifdef WITH_PINENTRY
1699 static gpg_error_t do_getpin(pwm_t *pwm, char **result)
1701 if (gtimeout) {
1702 signal(SIGALRM, catchsig);
1703 alarm(1);
1706 *result = NULL;
1707 return pinentry_command(pwm, result, "GETPIN");
1710 static gpg_error_t getpin(pwm_t *pwm, char **result, int which)
1712 gpg_error_t error;
1714 error = set_pinentry_strings(pwm, which);
1716 if (error) {
1717 pinentry_disconnect(pwm);
1718 return error;
1721 error = do_getpin(pwm, result);
1724 * Since there was input cancel any timeout setting.
1726 alarm(0);
1728 if (error) {
1729 if (error == GPG_ERR_CANCELED)
1730 return GPG_ERR_CANCELED;
1732 if (pwm->pctx)
1733 pinentry_disconnect(pwm);
1735 return error;
1738 return 0;
1740 #endif
1742 static gpg_error_t do_open_command(pwm_t *pwm, const char *filename, char *password)
1744 char *buf;
1745 gpg_error_t error;
1746 char *result = NULL;
1748 buf = pwmd_malloc(ASSUAN_LINELENGTH+1);
1750 if (!buf)
1751 return gpg_error_from_errno(ENOMEM);
1753 snprintf(buf, ASSUAN_LINELENGTH, "OPEN %s %s", filename,
1754 password ? password : "");
1755 error = send_command(pwm, &result, buf);
1756 pwmd_free(buf);
1758 if (error && result)
1759 pwmd_free(result);
1761 return error;
1764 static gpg_error_t do_pwmd_open(pwm_t *pwm, const char *filename, int nb)
1766 char *result = NULL;
1767 char *password = NULL;
1768 char path[PATH_MAX];
1769 #ifdef WITH_PINENTRY
1770 int pin_try;
1771 #endif
1772 gpg_error_t rc;
1774 if (!pwm || !filename || !*filename)
1775 return GPG_ERR_INV_ARG;
1777 #ifdef WITH_PINENTRY
1778 pin_try = pwm->pinentry_tries - 1;
1779 #endif
1782 * Avoid calling pinentry if the password is cached on the server or if
1783 * this is a new file.
1785 rc = pwmd_command(pwm, &result, "GETCONFIG data_directory");
1787 if (rc)
1788 return rc;
1790 snprintf(path, sizeof(path), "%s/%s", result, filename);
1791 pwmd_free(result);
1793 if (access(path, R_OK) == -1) {
1794 if (errno == ENOENT)
1795 goto gotpassword;
1798 rc = pwmd_command(pwm, &result, "ISCACHED %s", filename);
1800 if (rc == EPWMD_CACHE_NOT_FOUND) {
1801 if (pwm->passfunc) {
1802 password = (char *)pwm->passfunc(pwm->passdata);
1803 goto gotpassword;
1806 #ifdef WITH_PINENTRY
1808 * Get the password from pinentry.
1810 if (pwm->use_pinentry) {
1812 * Nonblocking is wanted. fork() then return a file descriptor
1813 * that the client can use to read() from.
1815 if (nb) {
1816 int p[2];
1817 pid_t pid;
1818 pwmd_nb_status_t pw;
1820 if (pipe(p) == -1)
1821 return gpg_error_from_syserror();
1823 if (!pwm->filename)
1824 pwm->filename = pwmd_strdup(filename);
1826 if (!pwm->filename)
1827 return gpg_error_from_errno(ENOMEM);
1829 #ifdef WITH_LIBPTH
1830 pid = pth_fork();
1831 #else
1832 pid = fork();
1833 #endif
1835 switch (pid) {
1836 case 0:
1837 close(p[0]);
1838 pw.fd = p[0];
1840 if (pwm->pinentry_timeout > 0) {
1841 gpwm = pwm;
1842 gtimeout = pwm->pinentry_timeout;
1843 gelapsed = 0;
1846 pw.error = getpin(pwm, &password, 0);
1848 if (gtimeout && gelapsed >= gtimeout)
1849 pw.error = GPG_ERR_TIMEOUT;
1851 signal(SIGALRM, SIG_DFL);
1853 if (!pw.error)
1854 snprintf(pw.password, sizeof(pw.password), "%s",
1855 password);
1857 pinentry_disconnect(pwm);
1858 #ifdef WITH_LIBPTH
1859 pth_write(p[1], &pw, sizeof(pw));
1860 #else
1861 write(p[1], &pw, sizeof(pw));
1862 #endif
1863 memset(&pw, 0, sizeof(pw));
1864 close(p[1]);
1865 _exit(0);
1866 break;
1867 case -1:
1868 rc = gpg_error_from_syserror();
1869 close(p[0]);
1870 close(p[1]);
1871 return rc;
1872 default:
1873 break;
1876 close(p[1]);
1877 pwm->nb_fd = p[0];
1878 pwm->nb_pid = pid;
1879 return 0;
1882 else {
1883 #endif
1885 * Not using pinentry and the file was not found
1886 * in the cache.
1888 password = pwm->password;
1889 #ifdef WITH_PINENTRY
1891 #endif
1893 else if (rc)
1894 return rc;
1896 gotpassword:
1897 pwm->state = ASYNC_DONE;
1898 rc = do_open_command(pwm, filename, password);
1901 * Keep the user defined password set with pwmd_setopt(). The password may
1902 * be needed later (pwmd_save()) depending on the pwmd file cache settings.
1904 if (!pwm->passfunc && password && password != pwm->password)
1905 pwmd_free(password);
1907 #ifdef WITH_PINENTRY
1908 if (rc == EPWMD_BADKEY) {
1909 if (pin_try-- > 0 && !nb) {
1910 rc = pwmd_command(pwm, &result, "OPTION TITLE=%s",
1911 N_("Invalid passphrase, please try again."));
1913 if (rc)
1914 return rc;
1916 goto gotpassword;
1919 if (nb)
1920 pinentry_disconnect(pwm);
1922 return rc;
1924 #endif
1926 if (!rc) {
1927 if (pwm->filename)
1928 pwmd_free(pwm->filename);
1930 pwm->filename = pwmd_strdup(filename);
1933 return rc;
1936 gpg_error_t pwmd_open(pwm_t *pwm, const char *filename)
1938 return do_pwmd_open(pwm, filename, 0);
1941 gpg_error_t pwmd_open_async2(pwm_t *pwm, const char *filename)
1943 #ifndef WITH_PINENTRY
1944 return GPG_ERR_NOT_IMPLEMENTED;
1945 #else
1946 gpg_error_t rc;
1948 if (pwm->cmd != ASYNC_CMD_OPEN2)
1949 pwm->pin_try = 0;
1951 pwm->cmd = ASYNC_CMD_OPEN2;
1952 pwm->state = ASYNC_PROCESS;
1953 rc = do_pwmd_open(pwm, filename, 1);
1955 if (rc)
1956 reset_async(pwm, 1);
1958 return rc;
1959 #endif
1962 #ifdef WITH_PINENTRY
1963 static gpg_error_t do_save_getpin(pwm_t *pwm, char **password)
1965 int confirm = 0;
1966 gpg_error_t error;
1967 char *result = NULL;
1969 again:
1970 error = getpin(pwm, &result, confirm ? 2 : 0);
1972 if (error) {
1973 if (pwm->pctx)
1974 pinentry_disconnect(pwm);
1976 if (*password)
1977 pwmd_free(*password);
1979 return error;
1982 if (!confirm++) {
1983 *password = result;
1984 goto again;
1987 if (strcmp(*password, result)) {
1988 pwmd_free(*password);
1989 pwmd_free(result);
1990 pinentry_disconnect(pwm);
1991 error = EPWMD_BADKEY;
1992 return error;
1995 pwmd_free(result);
1996 pinentry_disconnect(pwm);
1997 return 0;
1999 #endif
2001 static gpg_error_t do_save_command(pwm_t *pwm, char *password)
2003 char *buf;
2004 gpg_error_t error;
2005 char *result = NULL;
2007 buf = pwmd_malloc(ASSUAN_LINELENGTH+1);
2009 if (!buf)
2010 return gpg_error_from_errno(ENOMEM);
2012 snprintf(buf, ASSUAN_LINELENGTH, "SAVE %s", password ? password : "");
2013 error = send_command(pwm, &result, buf);
2014 pwmd_free(buf);
2016 if (error && result)
2017 pwmd_free(result);
2019 return error;
2022 static gpg_error_t do_pwmd_save(pwm_t *pwm, int nb)
2024 char *result = NULL;
2025 char *password = NULL;
2026 gpg_error_t rc;
2028 if (!pwm)
2029 return GPG_ERR_INV_ARG;
2031 if (pwm->use_pinentry || pwm->passfunc) {
2032 rc = pwmd_command(pwm, &result, "ISCACHED %s", pwm->filename);
2034 if (rc == EPWMD_CACHE_NOT_FOUND) {
2035 if (pwm->passfunc)
2036 password = (char *)(*pwm->passfunc)(pwm->passdata);
2037 #ifdef WITH_PINENTRY
2038 else if (pwm->use_pinentry) {
2039 if (nb) {
2040 int p[2];
2041 pid_t pid;
2042 pwmd_nb_status_t pw;
2044 if (pipe(p) == -1)
2045 return gpg_error_from_syserror();
2047 #ifdef WITH_LIBPTH
2048 pid = pth_fork();
2049 #else
2050 pid = fork();
2051 #endif
2053 switch (pid) {
2054 case 0:
2055 close(p[0]);
2056 pw.fd = p[0];
2057 password = NULL;
2058 pw.error = do_save_getpin(pwm, &password);
2059 pinentry_disconnect(pwm);
2060 snprintf(pw.password, sizeof(pw.password), "%s",
2061 password);
2062 #ifdef WITH_LIBPTH
2063 pth_write(p[1], &pw, sizeof(pw));
2064 #else
2065 write(p[1], &pw, sizeof(pw));
2066 #endif
2067 memset(&pw, 0, sizeof(pw));
2068 close(p[1]);
2069 _exit(0);
2070 break;
2071 case -1:
2072 rc = gpg_error_from_syserror();
2073 close(p[0]);
2074 close(p[1]);
2075 return rc;
2076 default:
2077 break;
2080 close(p[1]);
2081 pwm->nb_fd = p[0];
2082 pwm->nb_pid = pid;
2083 return 0;
2086 rc = do_save_getpin(pwm, &password);
2088 if (rc)
2089 return rc;
2091 #endif
2093 else {
2094 if (rc)
2095 return rc;
2097 pwm->state = ASYNC_DONE;
2100 else
2101 password = pwm->password;
2103 rc = do_save_command(pwm, password);
2105 if (!pwm->passfunc && password && password != pwm->password)
2106 pwmd_free(password);
2108 return rc;
2111 gpg_error_t pwmd_save_async2(pwm_t *pwm)
2113 #ifndef WITH_PINENTRY
2114 return GPG_ERR_NOT_IMPLEMENTED;
2115 #else
2116 gpg_error_t rc;
2118 pwm->cmd = ASYNC_CMD_SAVE2;
2119 pwm->state = ASYNC_PROCESS;
2120 rc = do_pwmd_save(pwm, 1);
2122 if (rc)
2123 reset_async(pwm, 0);
2125 return rc;
2126 #endif
2129 gpg_error_t pwmd_save(pwm_t *pwm)
2131 return do_pwmd_save(pwm, 0);
2134 gpg_error_t pwmd_setopt(pwm_t *pwm, pwmd_option_t opt, ...)
2136 va_list ap;
2137 int n = va_arg(ap, int);
2138 char *result;
2139 char *arg1;
2140 gpg_error_t error = 0;
2142 if (!pwm)
2143 return GPG_ERR_INV_ARG;
2145 va_start(ap, opt);
2147 switch (opt) {
2148 case PWMD_OPTION_STATUS_FUNC:
2149 pwm->status_func = va_arg(ap, pwmd_status_fn);
2150 break;
2151 case PWMD_OPTION_STATUS_DATA:
2152 pwm->status_data = va_arg(ap, void *);
2153 break;
2154 case PWMD_OPTION_PASSWORD_FUNC:
2155 pwm->passfunc = va_arg(ap, pwmd_password_fn);
2156 break;
2157 case PWMD_OPTION_PASSWORD_DATA:
2158 pwm->passdata = va_arg(ap, void *);
2159 break;
2160 case PWMD_OPTION_PASSWORD:
2161 arg1 = va_arg(ap, char *);
2163 if (pwm->password)
2164 pwmd_free(pwm->password);
2166 pwm->password = pwmd_strdup(arg1);
2167 break;
2168 case PWMD_OPTION_PINENTRY:
2169 n = va_arg(ap, int);
2171 if (n != 0 && n != 1) {
2172 va_end(ap);
2173 error = GPG_ERR_INV_VALUE;
2175 else {
2176 pwm->use_pinentry = n;
2177 error = pwmd_command(pwm, &result, "OPTION PINENTRY=%i",
2178 !pwm->use_pinentry);
2180 break;
2181 #ifdef WITH_PINENTRY
2182 case PWMD_OPTION_PINENTRY_TRIES:
2183 n = va_arg(ap, int);
2185 if (n <= 0) {
2186 va_end(ap);
2187 error = GPG_ERR_INV_VALUE;
2189 else
2190 pwm->pinentry_tries = n;
2191 break;
2192 #endif
2193 case PWMD_OPTION_PINENTRY_TIMEOUT:
2194 n = va_arg(ap, int);
2196 if (n < 0) {
2197 va_end(ap);
2198 error = GPG_ERR_INV_VALUE;
2200 else
2201 pwm->pinentry_timeout = n;
2203 if (!pwm->use_pinentry)
2204 error = pwmd_command(pwm, &result, "OPTION TIMEOUT=%i",
2205 pwm->pinentry_timeout);
2206 break;
2207 case PWMD_OPTION_PINENTRY_PATH:
2208 if (pwm->pinentry_path)
2209 pwmd_free(pwm->pinentry_path);
2211 pwm->pinentry_path = pwmd_strdup(va_arg(ap, char *));
2213 if (!pwm->use_pinentry)
2214 error = pwmd_command(pwm, &result, "OPTION PATH=%s",
2215 pwm->pinentry_path);
2216 break;
2217 case PWMD_OPTION_PINENTRY_TTY:
2218 if (pwm->pinentry_tty)
2219 pwmd_free(pwm->pinentry_tty);
2221 pwm->pinentry_tty = pwmd_strdup(va_arg(ap, char *));
2223 if (!pwm->use_pinentry)
2224 error = pwmd_command(pwm, &result, "OPTION TTY=%s",
2225 pwm->pinentry_tty);
2226 break;
2227 case PWMD_OPTION_PINENTRY_DISPLAY:
2228 if (pwm->pinentry_display)
2229 pwmd_free(pwm->pinentry_display);
2231 pwm->pinentry_display = pwmd_strdup(va_arg(ap, char *));
2233 if (!pwm->use_pinentry)
2234 error = pwmd_command(pwm, &result, "OPTION DISPLAY=%s",
2235 pwm->pinentry_display);
2236 break;
2237 case PWMD_OPTION_PINENTRY_TERM:
2238 if (pwm->pinentry_term)
2239 pwmd_free(pwm->pinentry_term);
2241 pwm->pinentry_term = pwmd_strdup(va_arg(ap, char *));
2243 if (!pwm->use_pinentry)
2244 error = pwmd_command(pwm, &result, "OPTION TTYTYPE=%s",
2245 pwm->pinentry_term);
2246 break;
2247 case PWMD_OPTION_PINENTRY_TITLE:
2248 if (pwm->title)
2249 pwmd_free(pwm->title);
2251 pwm->title = percent_escape(va_arg(ap, char *));
2253 if (!pwm->use_pinentry)
2254 error = pwmd_command(pwm, &result, "OPTION TITLE=%s",
2255 pwm->title);
2256 break;
2257 case PWMD_OPTION_PINENTRY_PROMPT:
2258 if (pwm->prompt)
2259 pwmd_free(pwm->prompt);
2261 pwm->prompt = percent_escape(va_arg(ap, char *));
2263 if (!pwm->use_pinentry)
2264 error = pwmd_command(pwm, &result, "OPTION PROMPT=%s",
2265 pwm->prompt);
2266 break;
2267 case PWMD_OPTION_PINENTRY_DESC:
2268 if (pwm->desc)
2269 pwmd_free(pwm->desc);
2271 pwm->desc = percent_escape(va_arg(ap, char *));
2273 if (!pwm->use_pinentry)
2274 error = pwmd_command(pwm, &result, "OPTION DESC=%s",
2275 pwm->desc);
2276 break;
2277 case PWMD_OPTION_PINENTRY_LC_CTYPE:
2278 if (pwm->lcctype)
2279 pwmd_free(pwm->lcctype);
2281 pwm->lcctype = pwmd_strdup(va_arg(ap, char *));
2283 if (!pwm->use_pinentry)
2284 error = pwmd_command(pwm, &result, "OPTION LC_CTYPE=%s",
2285 pwm->lcctype);
2286 break;
2287 case PWMD_OPTION_PINENTRY_LC_MESSAGES:
2288 if (pwm->lcmessages)
2289 pwmd_free(pwm->lcmessages);
2291 pwm->lcmessages = pwmd_strdup(va_arg(ap, char *));
2293 if (!pwm->use_pinentry)
2294 error = pwmd_command(pwm, &result, "OPTION LC_MESSAGES=%s",
2295 pwm->lcmessages);
2296 break;
2297 default:
2298 error = GPG_ERR_NOT_IMPLEMENTED;
2299 break;
2302 va_end(ap);
2303 return error;
2306 gpg_error_t pwmd_get_fd(pwm_t *pwm, int *fd)
2308 if (!pwm)
2309 return GPG_ERR_INV_ARG;
2311 if (pwm->fd == -1)
2312 return GPG_ERR_INV_STATE;
2314 *fd = pwm->fd;
2315 return 0;
2318 gpg_error_t pwmd_get_fd2(pwm_t *pwm, int *fd)
2320 #ifndef WITH_PINENTRY
2321 return GPG_ERR_NOT_IMPLEMENTED;
2322 #else
2323 if (!pwm)
2324 return GPG_ERR_INV_ARG;
2326 if (pwm->nb_fd == -1)
2327 return GPG_ERR_INV_STATE;
2329 *fd = pwm->nb_fd;
2330 return 0;
2331 #endif
2334 pwm_t *pwmd_new(const char *name)
2336 pwm_t *h = pwmd_calloc(1, sizeof(pwm_t));
2338 if (!h)
2339 return NULL;
2341 if (name) {
2342 h->name = pwmd_strdup(name);
2344 if (!h->name) {
2345 pwmd_free(h);
2346 return NULL;
2350 h->fd = -1;
2351 #ifdef WITH_PINENTRY
2352 h->nb_fd = -1;
2353 #endif
2354 return h;
2357 void pwmd_free(void *ptr)
2359 xfree(ptr);
2362 void *pwmd_malloc(size_t size)
2364 return xmalloc(size);
2367 void *pwmd_calloc(size_t nmemb, size_t size)
2369 return xcalloc(nmemb, size);
2372 void *pwmd_realloc(void *ptr, size_t size)
2374 return xrealloc(ptr, size);
2377 char *pwmd_strdup(const char *str)
2379 return xstrdup(str);