1 /* call-scd.c - fork of the scdaemon to do SC operations
2 * Copyright (C) 2001, 2002, 2005, 2007, 2010,
3 * 2011 Free Software Foundation, Inc.
4 * Copyright (C) 2013 Werner Koch
6 * This file is part of GnuPG.
8 * GnuPG is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
13 * GnuPG is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, see <http://www.gnu.org/licenses/>.
34 #include <sys/types.h>
35 #ifndef HAVE_W32_SYSTEM
43 #ifdef _POSIX_OPEN_MAX
44 #define MAX_OPEN_FDS _POSIX_OPEN_MAX
46 #define MAX_OPEN_FDS 20
49 /* Definition of module local data of the CTRL structure. */
52 /* We keep a list of all allocated context with a an achnor at
53 SCD_LOCAL_LIST (see below). */
54 struct scd_local_s *next_local;
56 /* We need to get back to the ctrl object actually referencing this
57 structure. This is really an awkward way of enumerint the lcoal
58 contects. A much cleaner way would be to keep a global list of
59 ctrl objects to enumerate them. */
62 assuan_context_t ctx; /* NULL or session context for the SCdaemon
63 used with this connection. */
64 int locked; /* This flag is used to assert proper use of
65 start_scd and unlock_scd. */
70 /* Callback parameter for learn card */
73 void (*kpinfo_cb)(void*, const char *);
75 void (*certinfo_cb)(void*, const char *);
76 void *certinfo_cb_arg;
77 void (*sinfo_cb)(void*, const char *, size_t, const char *);
84 int (*getpin_cb)(void *, const char *, char*, size_t);
86 assuan_context_t passthru; /* If not NULL, pass unknown inquiries
92 /* To keep track of all active SCD contexts, we keep a linked list
93 anchored at this variable. */
94 static struct scd_local_s *scd_local_list;
96 /* A Mutex used inside the start_scd function. */
97 static npth_mutex_t start_scd_lock;
99 /* A malloced string with the name of the socket to be used for
100 additional connections. May be NULL if not provided by
102 static char *socket_name;
104 /* The context of the primary connection. This is also used as a flag
105 to indicate whether the scdaemon has been started. */
106 static assuan_context_t primary_scd_ctx;
108 /* To allow reuse of the primary connection, the following flag is set
109 to true if the primary context has been reset and is not in use by
111 static int primary_scd_ctx_reusable;
115 /* Local prototypes. */
120 /* This function must be called once to initialize this module. This
121 has to be done before a second thread is spawned. We can't do the
122 static initialization because NPth emulation code might not be able
123 to do a static init; in particular, it is not possible for W32. */
125 initialize_module_call_scd (void)
127 static int initialized;
132 err = npth_mutex_init (&start_scd_lock, NULL);
134 log_fatal ("error initializing mutex: %s\n", strerror (err));
140 /* This function may be called to print infromation pertaining to the
141 current state of this module to the log. */
143 agent_scd_dump_state (void)
145 log_info ("agent_scd_dump_state: primary_scd_ctx=%p pid=%ld reusable=%d\n",
147 (long)assuan_get_pid (primary_scd_ctx),
148 primary_scd_ctx_reusable);
150 log_info ("agent_scd_dump_state: socket='%s'\n", socket_name);
154 /* The unlock_scd function shall be called after having accessed the
155 SCD. It is currently not very useful but gives an opportunity to
156 keep track of connections currently calling SCD. Note that the
157 "lock" operation is done by the start_scd() function which must be
158 called and error checked before any SCD operation. CTRL is the
159 usual connection context and RC the error code to be passed trhough
162 unlock_scd (ctrl_t ctrl, int rc)
164 if (ctrl->scd_local->locked != 1)
166 log_error ("unlock_scd: invalid lock count (%d)\n",
167 ctrl->scd_local->locked);
169 rc = gpg_error (GPG_ERR_INTERNAL);
171 ctrl->scd_local->locked = 0;
175 /* To make sure we leave no secrets in our image after forking of the
176 scdaemon, we use this callback. */
178 atfork_cb (void *opaque, int where)
183 gcry_control (GCRYCTL_TERM_SECMEM);
187 /* Fork off the SCdaemon if this has not already been done. Lock the
188 daemon and make sure that a proper context has been setup in CTRL.
189 This function might also lock the daemon, which means that the
190 caller must call unlock_scd after this function has returned
191 success and the actual Assuan transaction been done. */
193 start_scd (ctrl_t ctrl)
197 assuan_context_t ctx = NULL;
199 assuan_fd_t no_close_list[3];
203 if (opt.disable_scdaemon)
204 return gpg_error (GPG_ERR_NOT_SUPPORTED);
206 /* If this is the first call for this session, setup the local data
208 if (!ctrl->scd_local)
210 ctrl->scd_local = xtrycalloc (1, sizeof *ctrl->scd_local);
211 if (!ctrl->scd_local)
212 return gpg_error_from_syserror ();
213 ctrl->scd_local->ctrl_backlink = ctrl;
214 ctrl->scd_local->next_local = scd_local_list;
215 scd_local_list = ctrl->scd_local;
219 /* Assert that the lock count is as expected. */
220 if (ctrl->scd_local->locked)
222 log_error ("start_scd: invalid lock count (%d)\n",
223 ctrl->scd_local->locked);
224 return gpg_error (GPG_ERR_INTERNAL);
226 ctrl->scd_local->locked++;
228 if (ctrl->scd_local->ctx)
229 return 0; /* Okay, the context is fine. We used to test for an
230 alive context here and do an disconnect. Now that we
231 have a ticker function to check for it, it is easier
232 not to check here but to let the connection run on an
236 /* We need to protect the following code. */
237 rc = npth_mutex_lock (&start_scd_lock);
240 log_error ("failed to acquire the start_scd lock: %s\n",
242 return gpg_error (GPG_ERR_INTERNAL);
245 /* Check whether the pipe server has already been started and in
246 this case either reuse a lingering pipe connection or establish a
247 new socket based one. */
248 if (primary_scd_ctx && primary_scd_ctx_reusable)
250 ctx = primary_scd_ctx;
251 primary_scd_ctx_reusable = 0;
253 log_info ("new connection to SCdaemon established (reusing)\n");
257 rc = assuan_new (&ctx);
260 log_error ("can't allocate assuan context: %s\n", gpg_strerror (rc));
267 rc = assuan_socket_connect (ctx, socket_name, 0, 0);
270 log_error ("can't connect to socket '%s': %s\n",
271 socket_name, gpg_strerror (rc));
272 err = gpg_error (GPG_ERR_NO_SCDAEMON);
277 log_info ("new connection to SCdaemon established\n");
283 log_info ("SCdaemon is running but won't accept further connections\n");
284 err = gpg_error (GPG_ERR_NO_SCDAEMON);
288 /* Nope, it has not been started. Fire it up now. */
290 log_info ("no running SCdaemon - starting it\n");
294 #ifndef HAVE_W32_SYSTEM
295 err = gpg_error_from_syserror ();
297 log_error ("error flushing pending output: %s\n", strerror (errno));
298 /* At least Windows XP fails here with EBADF. According to docs
299 and Wine an fflush(NULL) is the same as _flushall. However
300 the Wime implementaion does not flush stdin,stdout and stderr
301 - see above. Lets try to ignore the error. */
302 #ifndef HAVE_W32_SYSTEM
307 if (!opt.scdaemon_program || !*opt.scdaemon_program)
308 opt.scdaemon_program = gnupg_module_name (GNUPG_MODULE_NAME_SCDAEMON);
309 if ( !(pgmname = strrchr (opt.scdaemon_program, '/')))
310 pgmname = opt.scdaemon_program;
315 argv[1] = "--multi-server";
319 if (!opt.running_detached)
321 if (log_get_fd () != -1)
322 no_close_list[i++] = assuan_fd_from_posix_fd (log_get_fd ());
323 no_close_list[i++] = assuan_fd_from_posix_fd (fileno (stderr));
325 no_close_list[i] = ASSUAN_INVALID_FD;
327 /* Connect to the scdaemon and perform initial handshaking. Use
328 detached flag so that under Windows SCDAEMON does not show up a
330 rc = assuan_pipe_connect (ctx, opt.scdaemon_program, argv,
331 no_close_list, atfork_cb, NULL,
332 ASSUAN_PIPE_CONNECT_DETACHED);
335 log_error ("can't connect to the SCdaemon: %s\n",
337 err = gpg_error (GPG_ERR_NO_SCDAEMON);
342 log_debug ("first connection to SCdaemon established\n");
345 /* Get the name of the additional socket opened by scdaemon. */
348 unsigned char *databuf;
353 init_membuf (&data, 256);
354 assuan_transact (ctx, "GETINFO socket_name",
355 put_membuf_cb, &data, NULL, NULL, NULL, NULL);
357 databuf = get_membuf (&data, &datalen);
358 if (databuf && datalen)
360 socket_name = xtrymalloc (datalen + 1);
362 log_error ("warning: can't store socket name: %s\n",
366 memcpy (socket_name, databuf, datalen);
367 socket_name[datalen] = 0;
369 log_debug ("additional connections at '%s'\n", socket_name);
375 /* Tell the scdaemon we want him to send us an event signal. We
376 don't support this for W32CE. */
377 #ifndef HAVE_W32CE_SYSTEM
378 if (opt.sigusr2_enabled)
382 #ifdef HAVE_W32_SYSTEM
383 snprintf (buf, sizeof buf, "OPTION event-signal=%lx",
384 (unsigned long)get_agent_scd_notify_event ());
386 snprintf (buf, sizeof buf, "OPTION event-signal=%d", SIGUSR2);
388 assuan_transact (ctx, buf, NULL, NULL, NULL, NULL, NULL, NULL);
390 #endif /*HAVE_W32CE_SYSTEM*/
392 primary_scd_ctx = ctx;
393 primary_scd_ctx_reusable = 0;
398 unlock_scd (ctrl, err);
400 assuan_release (ctx);
404 ctrl->scd_local->ctx = ctx;
406 rc = npth_mutex_unlock (&start_scd_lock);
408 log_error ("failed to release the start_scd lock: %s\n", strerror (rc));
413 /* Check whether the SCdaemon is active. This is a fast check without
414 any locking and might give a wrong result if another thread is about
415 to start the daemon or the daemon is about to be stopped.. */
417 agent_scd_check_running (void)
419 return !!primary_scd_ctx;
423 /* Check whether the Scdaemon is still alive and clean it up if not. */
425 agent_scd_check_aliveness (void)
428 #ifdef HAVE_W32_SYSTEM
433 struct timespec abstime;
436 if (!primary_scd_ctx)
437 return; /* No scdaemon running. */
439 /* This is not a critical function so we use a short timeout while
440 acquiring the lock. */
441 npth_clock_gettime (&abstime);
443 err = npth_mutex_timedlock (&start_scd_lock, &abstime);
446 if (err == ETIMEDOUT)
449 log_info ("failed to acquire the start_scd lock while"
450 " doing an aliveness check: %s\n", strerror (err));
453 log_error ("failed to acquire the start_scd lock while"
454 " doing an aliveness check: %s\n", strerror (err));
460 pid = assuan_get_pid (primary_scd_ctx);
461 #ifdef HAVE_W32_SYSTEM
462 /* If we have a PID we disconnect if either GetExitProcessCode
463 fails or if ir returns the exit code of the scdaemon. 259 is
464 the error code for STILL_ALIVE. */
465 if (pid != (pid_t)(void*)(-1) && pid
466 && (!GetExitCodeProcess ((HANDLE)pid, &rc) || rc != 259))
468 if (pid != (pid_t)(-1) && pid
469 && ((rc=waitpid (pid, NULL, WNOHANG))==-1 || (rc == pid)) )
472 /* Okay, scdaemon died. Disconnect the primary connection
473 now but take care that it won't do another wait. Also
474 cleanup all other connections and release their
475 resources. The next use will start a new daemon then.
476 Due to the use of the START_SCD_LOCAL we are sure that
477 none of these context are actually in use. */
478 struct scd_local_s *sl;
480 assuan_set_flag (primary_scd_ctx, ASSUAN_NO_WAITPID, 1);
481 assuan_release (primary_scd_ctx);
483 for (sl=scd_local_list; sl; sl = sl->next_local)
487 if (sl->ctx != primary_scd_ctx)
488 assuan_release (sl->ctx);
493 primary_scd_ctx = NULL;
494 primary_scd_ctx_reusable = 0;
501 err = npth_mutex_unlock (&start_scd_lock);
503 log_error ("failed to release the start_scd lock while"
504 " doing the aliveness check: %s\n", strerror (err));
509 /* Reset the SCD if it has been used. Actually it is not a reset but
510 a cleanup of resources used by the current connection. */
512 agent_reset_scd (ctrl_t ctrl)
516 if (ctrl->scd_local->ctx)
518 /* We can't disconnect the primary context because libassuan
519 does a waitpid on it and thus the system would hang.
520 Instead we send a reset and keep that connection for
522 if (ctrl->scd_local->ctx == primary_scd_ctx)
524 /* Send a RESTART to the SCD. This is required for the
525 primary connection as a kind of virtual EOF; we don't
526 have another way to tell it that the next command
527 should be viewed as if a new connection has been
528 made. For the non-primary connections this is not
529 needed as we simply close the socket. We don't check
530 for an error here because the RESTART may fail for
531 example if the scdaemon has already been terminated.
532 Anyway, we need to set the reusable flag to make sure
533 that the aliveness check can clean it up. */
534 assuan_transact (primary_scd_ctx, "RESTART",
535 NULL, NULL, NULL, NULL, NULL, NULL);
536 primary_scd_ctx_reusable = 1;
539 assuan_release (ctrl->scd_local->ctx);
540 ctrl->scd_local->ctx = NULL;
543 /* Remove the local context from our list and release it. */
546 else if (scd_local_list == ctrl->scd_local)
547 scd_local_list = ctrl->scd_local->next_local;
550 struct scd_local_s *sl;
552 for (sl=scd_local_list; sl->next_local; sl = sl->next_local)
553 if (sl->next_local == ctrl->scd_local)
557 sl->next_local = ctrl->scd_local->next_local;
559 xfree (ctrl->scd_local);
560 ctrl->scd_local = NULL;
569 learn_status_cb (void *opaque, const char *line)
571 struct learn_parm_s *parm = opaque;
572 const char *keyword = line;
575 for (keywordlen=0; *line && !spacep (line); line++, keywordlen++)
577 while (spacep (line))
579 if (keywordlen == 8 && !memcmp (keyword, "CERTINFO", keywordlen))
581 parm->certinfo_cb (parm->certinfo_cb_arg, line);
583 else if (keywordlen == 11 && !memcmp (keyword, "KEYPAIRINFO", keywordlen))
585 parm->kpinfo_cb (parm->kpinfo_cb_arg, line);
587 else if (keywordlen && *line)
589 parm->sinfo_cb (parm->sinfo_cb_arg, keyword, keywordlen, line);
595 /* Perform the LEARN command and return a list of all private keys
596 stored on the card. */
598 agent_card_learn (ctrl_t ctrl,
599 void (*kpinfo_cb)(void*, const char *),
601 void (*certinfo_cb)(void*, const char *),
602 void *certinfo_cb_arg,
603 void (*sinfo_cb)(void*, const char *, size_t, const char *),
607 struct learn_parm_s parm;
609 rc = start_scd (ctrl);
613 memset (&parm, 0, sizeof parm);
614 parm.kpinfo_cb = kpinfo_cb;
615 parm.kpinfo_cb_arg = kpinfo_cb_arg;
616 parm.certinfo_cb = certinfo_cb;
617 parm.certinfo_cb_arg = certinfo_cb_arg;
618 parm.sinfo_cb = sinfo_cb;
619 parm.sinfo_cb_arg = sinfo_cb_arg;
620 rc = assuan_transact (ctrl->scd_local->ctx, "LEARN --force",
621 NULL, NULL, NULL, NULL,
622 learn_status_cb, &parm);
624 return unlock_scd (ctrl, rc);
626 return unlock_scd (ctrl, 0);
632 get_serialno_cb (void *opaque, const char *line)
634 char **serialno = opaque;
635 const char *keyword = line;
639 for (keywordlen=0; *line && !spacep (line); line++, keywordlen++)
641 while (spacep (line))
644 if (keywordlen == 8 && !memcmp (keyword, "SERIALNO", keywordlen))
647 return gpg_error (GPG_ERR_CONFLICT); /* Unexpected status line. */
648 for (n=0,s=line; hexdigitp (s); s++, n++)
650 if (!n || (n&1)|| !(spacep (s) || !*s) )
651 return gpg_error (GPG_ERR_ASS_PARAMETER);
652 *serialno = xtrymalloc (n+1);
654 return out_of_core ();
655 memcpy (*serialno, line, n);
662 /* Return the serial number of the card or an appropriate error. The
663 serial number is returned as a hexstring. */
665 agent_card_serialno (ctrl_t ctrl, char **r_serialno)
668 char *serialno = NULL;
670 rc = start_scd (ctrl);
674 rc = assuan_transact (ctrl->scd_local->ctx, "SERIALNO",
675 NULL, NULL, NULL, NULL,
676 get_serialno_cb, &serialno);
680 return unlock_scd (ctrl, rc);
682 *r_serialno = serialno;
683 return unlock_scd (ctrl, 0);
689 /* Handle the NEEDPIN inquiry. */
691 inq_needpin (void *opaque, const char *line)
693 struct inq_needpin_s *parm = opaque;
699 parm->any_inq_seen = 1;
700 if ((s = has_leading_keyword (line, "NEEDPIN")))
704 pin = gcry_malloc_secure (pinlen);
706 return out_of_core ();
708 rc = parm->getpin_cb (parm->getpin_cb_arg, line, pin, pinlen);
710 rc = assuan_send_data (parm->ctx, pin, pinlen);
713 else if ((s = has_leading_keyword (line, "POPUPPINPADPROMPT")))
715 rc = parm->getpin_cb (parm->getpin_cb_arg, s, NULL, 1);
717 else if ((s = has_leading_keyword (line, "DISMISSPINPADPROMPT")))
719 rc = parm->getpin_cb (parm->getpin_cb_arg, "", NULL, 0);
721 else if (parm->passthru)
723 unsigned char *value;
726 int needrest = !strncmp (line, "KEYDATA", 8);
728 /* Pass the inquiry up to our caller. We limit the maximum
729 amount to an arbitrary value. As we know that the KEYDATA
730 enquiry is pretty sensitive we disable logging then */
731 if ((rest = (needrest
732 && !assuan_get_flag (parm->passthru, ASSUAN_CONFIDENTIAL))))
733 assuan_begin_confidential (parm->passthru);
734 rc = assuan_inquire (parm->passthru, line, &value, &valuelen, 8096);
736 assuan_end_confidential (parm->passthru);
739 if ((rest = (needrest
740 && !assuan_get_flag (parm->ctx, ASSUAN_CONFIDENTIAL))))
741 assuan_begin_confidential (parm->ctx);
742 rc = assuan_send_data (parm->ctx, value, valuelen);
744 assuan_end_confidential (parm->ctx);
748 log_error ("error forwarding inquiry '%s': %s\n",
749 line, gpg_strerror (rc));
753 log_error ("unsupported inquiry '%s'\n", line);
754 rc = gpg_error (GPG_ERR_ASS_UNKNOWN_INQUIRE);
761 /* Helper returning a command option to describe the used hash
762 algorithm. See scd/command.c:cmd_pksign. */
764 hash_algo_option (int algo)
768 case GCRY_MD_MD5 : return "--hash=md5";
769 case GCRY_MD_RMD160: return "--hash=rmd160";
770 case GCRY_MD_SHA1 : return "--hash=sha1";
771 case GCRY_MD_SHA224: return "--hash=sha224";
772 case GCRY_MD_SHA256: return "--hash=sha256";
773 case GCRY_MD_SHA384: return "--hash=sha384";
774 case GCRY_MD_SHA512: return "--hash=sha512";
781 cancel_inquire (ctrl_t ctrl, gpg_error_t rc)
783 gpg_error_t oldrc = rc;
785 /* The inquire callback was called and transact returned a
786 cancel error. We assume that the inquired process sent a
787 CANCEL. The passthrough code is not able to pass on the
788 CANCEL and thus scdaemon would stuck on this. As a
789 workaround we send a CANCEL now. */
790 rc = assuan_write_line (ctrl->scd_local->ctx, "CAN");
795 rc = assuan_read_line (ctrl->scd_local->ctx, &line, &len);
803 /* Create a signature using the current card. MDALGO is either 0 or
804 gives the digest algorithm. */
806 agent_card_pksign (ctrl_t ctrl,
808 int (*getpin_cb)(void *, const char *, char*, size_t),
811 const unsigned char *indata, size_t indatalen,
812 unsigned char **r_buf, size_t *r_buflen)
815 char line[ASSUAN_LINELENGTH];
817 struct inq_needpin_s inqparm;
820 rc = start_scd (ctrl);
824 if (indatalen*2 + 50 > DIM(line))
825 return unlock_scd (ctrl, gpg_error (GPG_ERR_GENERAL));
827 bin2hex (indata, indatalen, stpcpy (line, "SETDATA "));
829 rc = assuan_transact (ctrl->scd_local->ctx, line,
830 NULL, NULL, NULL, NULL, NULL, NULL);
832 return unlock_scd (ctrl, rc);
834 init_membuf (&data, 1024);
835 inqparm.ctx = ctrl->scd_local->ctx;
836 inqparm.getpin_cb = getpin_cb;
837 inqparm.getpin_cb_arg = getpin_cb_arg;
838 inqparm.passthru = 0;
839 inqparm.any_inq_seen = 0;
840 if (ctrl->use_auth_call)
841 snprintf (line, sizeof line, "PKAUTH %s", keyid);
843 snprintf (line, sizeof line, "PKSIGN %s %s",
844 hash_algo_option (mdalgo), keyid);
845 rc = assuan_transact (ctrl->scd_local->ctx, line,
846 put_membuf_cb, &data,
847 inq_needpin, &inqparm,
849 if (inqparm.any_inq_seen && (gpg_err_code(rc) == GPG_ERR_CANCELED ||
850 gpg_err_code(rc) == GPG_ERR_ASS_CANCELED))
851 rc = cancel_inquire (ctrl, rc);
857 xfree (get_membuf (&data, &len));
858 return unlock_scd (ctrl, rc);
861 *r_buf = get_membuf (&data, r_buflen);
862 return unlock_scd (ctrl, 0);
868 /* Check whether there is any padding info from scdaemon. */
870 padding_info_cb (void *opaque, const char *line)
872 int *r_padding = opaque;
875 if ((s=has_leading_keyword (line, "PADDING")))
877 *r_padding = atoi (s);
884 /* Decipher INDATA using the current card. Note that the returned
885 value is not an s-expression but the raw data as returned by
886 scdaemon. The padding information is stored at R_PADDING with -1
889 agent_card_pkdecrypt (ctrl_t ctrl,
891 int (*getpin_cb)(void *, const char *, char*, size_t),
893 const unsigned char *indata, size_t indatalen,
894 char **r_buf, size_t *r_buflen, int *r_padding)
897 char *p, line[ASSUAN_LINELENGTH];
899 struct inq_needpin_s inqparm;
903 *r_padding = -1; /* Unknown. */
904 rc = start_scd (ctrl);
908 /* FIXME: use secure memory where appropriate */
910 for (len = 0; len < indatalen;)
912 p = stpcpy (line, "SETDATA ");
914 p = stpcpy (p, "--append ");
915 for (i=0; len < indatalen && (i*2 < DIM(line)-50); i++, len++)
917 sprintf (p, "%02X", indata[len]);
920 rc = assuan_transact (ctrl->scd_local->ctx, line,
921 NULL, NULL, NULL, NULL, NULL, NULL);
923 return unlock_scd (ctrl, rc);
926 init_membuf (&data, 1024);
927 inqparm.ctx = ctrl->scd_local->ctx;
928 inqparm.getpin_cb = getpin_cb;
929 inqparm.getpin_cb_arg = getpin_cb_arg;
930 inqparm.passthru = 0;
931 inqparm.any_inq_seen = 0;
932 snprintf (line, DIM(line)-1, "PKDECRYPT %s", keyid);
933 line[DIM(line)-1] = 0;
934 rc = assuan_transact (ctrl->scd_local->ctx, line,
935 put_membuf_cb, &data,
936 inq_needpin, &inqparm,
937 padding_info_cb, r_padding);
938 if (inqparm.any_inq_seen && (gpg_err_code(rc) == GPG_ERR_CANCELED ||
939 gpg_err_code(rc) == GPG_ERR_ASS_CANCELED))
940 rc = cancel_inquire (ctrl, rc);
944 xfree (get_membuf (&data, &len));
945 return unlock_scd (ctrl, rc);
947 *r_buf = get_membuf (&data, r_buflen);
949 return unlock_scd (ctrl, gpg_error (GPG_ERR_ENOMEM));
951 return unlock_scd (ctrl, 0);
956 /* Read a certificate with ID into R_BUF and R_BUFLEN. */
958 agent_card_readcert (ctrl_t ctrl,
959 const char *id, char **r_buf, size_t *r_buflen)
962 char line[ASSUAN_LINELENGTH];
967 rc = start_scd (ctrl);
971 init_membuf (&data, 1024);
972 snprintf (line, DIM(line)-1, "READCERT %s", id);
973 line[DIM(line)-1] = 0;
974 rc = assuan_transact (ctrl->scd_local->ctx, line,
975 put_membuf_cb, &data,
980 xfree (get_membuf (&data, &len));
981 return unlock_scd (ctrl, rc);
983 *r_buf = get_membuf (&data, r_buflen);
985 return unlock_scd (ctrl, gpg_error (GPG_ERR_ENOMEM));
987 return unlock_scd (ctrl, 0);
992 /* Read a key with ID and return it in an allocate buffer pointed to
993 by r_BUF as a valid S-expression. */
995 agent_card_readkey (ctrl_t ctrl, const char *id, unsigned char **r_buf)
998 char line[ASSUAN_LINELENGTH];
1003 rc = start_scd (ctrl);
1007 init_membuf (&data, 1024);
1008 snprintf (line, DIM(line)-1, "READKEY %s", id);
1009 line[DIM(line)-1] = 0;
1010 rc = assuan_transact (ctrl->scd_local->ctx, line,
1011 put_membuf_cb, &data,
1016 xfree (get_membuf (&data, &len));
1017 return unlock_scd (ctrl, rc);
1019 *r_buf = get_membuf (&data, &buflen);
1021 return unlock_scd (ctrl, gpg_error (GPG_ERR_ENOMEM));
1023 if (!gcry_sexp_canon_len (*r_buf, buflen, NULL, NULL))
1025 xfree (*r_buf); *r_buf = NULL;
1026 return unlock_scd (ctrl, gpg_error (GPG_ERR_INV_VALUE));
1029 return unlock_scd (ctrl, 0);
1033 struct writekey_parm_s
1035 assuan_context_t ctx;
1036 int (*getpin_cb)(void *, const char *, char*, size_t);
1037 void *getpin_cb_arg;
1038 assuan_context_t passthru;
1041 const unsigned char *keydata;
1045 /* Handle a KEYDATA inquiry. Note, we only send the data,
1046 assuan_transact takes care of flushing and writing the end */
1048 inq_writekey_parms (void *opaque, const char *line)
1050 struct writekey_parm_s *parm = opaque;
1052 if (has_leading_keyword (line, "KEYDATA"))
1053 return assuan_send_data (parm->ctx, parm->keydata, parm->keydatalen);
1055 return inq_needpin (opaque, line);
1060 agent_card_writekey (ctrl_t ctrl, int force, const char *serialno,
1061 const char *id, const char *keydata, size_t keydatalen,
1062 int (*getpin_cb)(void *, const char *, char*, size_t),
1063 void *getpin_cb_arg)
1066 char line[ASSUAN_LINELENGTH];
1067 struct writekey_parm_s parms;
1070 rc = start_scd (ctrl);
1074 snprintf (line, DIM(line)-1, "WRITEKEY %s%s", force ? "--force " : "", id);
1075 line[DIM(line)-1] = 0;
1076 parms.ctx = ctrl->scd_local->ctx;
1077 parms.getpin_cb = getpin_cb;
1078 parms.getpin_cb_arg = getpin_cb_arg;
1080 parms.any_inq_seen = 0;
1081 parms.keydata = keydata;
1082 parms.keydatalen = keydatalen;
1084 rc = assuan_transact (ctrl->scd_local->ctx, line, NULL, NULL,
1085 inq_writekey_parms, &parms, NULL, NULL);
1086 if (parms.any_inq_seen && (gpg_err_code(rc) == GPG_ERR_CANCELED ||
1087 gpg_err_code(rc) == GPG_ERR_ASS_CANCELED))
1088 rc = cancel_inquire (ctrl, rc);
1089 return unlock_scd (ctrl, rc);
1092 /* Type used with the card_getattr_cb. */
1093 struct card_getattr_parm_s {
1094 const char *keyword; /* Keyword to look for. */
1095 size_t keywordlen; /* strlen of KEYWORD. */
1096 char *data; /* Malloced and unescaped data. */
1097 int error; /* ERRNO value or 0 on success. */
1100 /* Callback function for agent_card_getattr. */
1102 card_getattr_cb (void *opaque, const char *line)
1104 struct card_getattr_parm_s *parm = opaque;
1105 const char *keyword = line;
1109 return 0; /* We want only the first occurrence. */
1111 for (keywordlen=0; *line && !spacep (line); line++, keywordlen++)
1113 while (spacep (line))
1116 if (keywordlen == parm->keywordlen
1117 && !memcmp (keyword, parm->keyword, keywordlen))
1119 parm->data = percent_plus_unescape ((const unsigned char*)line, 0xff);
1121 parm->error = errno;
1128 /* Call the agent to retrieve a single line data object. On success
1129 the object is malloced and stored at RESULT; it is guaranteed that
1130 NULL is never stored in this case. On error an error code is
1131 returned and NULL stored at RESULT. */
1133 agent_card_getattr (ctrl_t ctrl, const char *name, char **result)
1136 struct card_getattr_parm_s parm;
1137 char line[ASSUAN_LINELENGTH];
1142 return gpg_error (GPG_ERR_INV_VALUE);
1144 memset (&parm, 0, sizeof parm);
1145 parm.keyword = name;
1146 parm.keywordlen = strlen (name);
1148 /* We assume that NAME does not need escaping. */
1149 if (8 + strlen (name) > DIM(line)-1)
1150 return gpg_error (GPG_ERR_TOO_LARGE);
1151 stpcpy (stpcpy (line, "GETATTR "), name);
1153 err = start_scd (ctrl);
1157 err = assuan_transact (ctrl->scd_local->ctx, line,
1158 NULL, NULL, NULL, NULL,
1159 card_getattr_cb, &parm);
1160 if (!err && parm.error)
1161 err = gpg_error_from_errno (parm.error);
1163 if (!err && !parm.data)
1164 err = gpg_error (GPG_ERR_NO_DATA);
1167 *result = parm.data;
1171 return unlock_scd (ctrl, err);
1178 pass_status_thru (void *opaque, const char *line)
1180 assuan_context_t ctx = opaque;
1184 if (line[0] == '#' && (!line[1] || spacep (line+1)))
1186 /* We are called in convey comments mode. Now, if we see a
1187 comment marker as keyword we forward the line verbatim to the
1188 the caller. This way the comment lines from scdaemon won't
1189 appear as status lines with keyword '#'. */
1190 assuan_write_line (ctx, line);
1194 for (i=0; *line && !spacep (line) && i < DIM(keyword)-1; line++, i++)
1198 /* Truncate any remaining keyword stuff. */
1199 for (; *line && !spacep (line); line++)
1201 while (spacep (line))
1204 assuan_write_status (ctx, keyword, line);
1210 pass_data_thru (void *opaque, const void *buffer, size_t length)
1212 assuan_context_t ctx = opaque;
1214 assuan_send_data (ctx, buffer, length);
1219 /* Send the line CMDLINE with command for the SCDdaemon to it and send
1220 all status messages back. This command is used as a general quoting
1221 mechanism to pass everything verbatim to SCDAEMON. The PIN
1222 inquiry is handled inside gpg-agent. */
1224 agent_card_scd (ctrl_t ctrl, const char *cmdline,
1225 int (*getpin_cb)(void *, const char *, char*, size_t),
1226 void *getpin_cb_arg, void *assuan_context)
1229 struct inq_needpin_s inqparm;
1232 rc = start_scd (ctrl);
1236 inqparm.ctx = ctrl->scd_local->ctx;
1237 inqparm.getpin_cb = getpin_cb;
1238 inqparm.getpin_cb_arg = getpin_cb_arg;
1239 inqparm.passthru = assuan_context;
1240 inqparm.any_inq_seen = 0;
1241 saveflag = assuan_get_flag (ctrl->scd_local->ctx, ASSUAN_CONVEY_COMMENTS);
1242 assuan_set_flag (ctrl->scd_local->ctx, ASSUAN_CONVEY_COMMENTS, 1);
1243 rc = assuan_transact (ctrl->scd_local->ctx, cmdline,
1244 pass_data_thru, assuan_context,
1245 inq_needpin, &inqparm,
1246 pass_status_thru, assuan_context);
1247 if (inqparm.any_inq_seen && gpg_err_code(rc) == GPG_ERR_ASS_CANCELED)
1248 rc = cancel_inquire (ctrl, rc);
1250 assuan_set_flag (ctrl->scd_local->ctx, ASSUAN_CONVEY_COMMENTS, saveflag);
1253 return unlock_scd (ctrl, rc);
1256 return unlock_scd (ctrl, 0);