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 <https://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];
202 char *abs_homedir = NULL;
204 if (opt.disable_scdaemon)
205 return gpg_error (GPG_ERR_NOT_SUPPORTED);
207 /* If this is the first call for this session, setup the local data
209 if (!ctrl->scd_local)
211 ctrl->scd_local = xtrycalloc (1, sizeof *ctrl->scd_local);
212 if (!ctrl->scd_local)
213 return gpg_error_from_syserror ();
214 ctrl->scd_local->ctrl_backlink = ctrl;
215 ctrl->scd_local->next_local = scd_local_list;
216 scd_local_list = ctrl->scd_local;
220 /* Assert that the lock count is as expected. */
221 if (ctrl->scd_local->locked)
223 log_error ("start_scd: invalid lock count (%d)\n",
224 ctrl->scd_local->locked);
225 return gpg_error (GPG_ERR_INTERNAL);
227 ctrl->scd_local->locked++;
229 if (ctrl->scd_local->ctx)
230 return 0; /* Okay, the context is fine. We used to test for an
231 alive context here and do an disconnect. Now that we
232 have a ticker function to check for it, it is easier
233 not to check here but to let the connection run on an
237 /* We need to protect the following code. */
238 rc = npth_mutex_lock (&start_scd_lock);
241 log_error ("failed to acquire the start_scd lock: %s\n",
243 return gpg_error (GPG_ERR_INTERNAL);
246 /* Check whether the pipe server has already been started and in
247 this case either reuse a lingering pipe connection or establish a
248 new socket based one. */
249 if (primary_scd_ctx && primary_scd_ctx_reusable)
251 ctx = primary_scd_ctx;
252 primary_scd_ctx_reusable = 0;
254 log_info ("new connection to SCdaemon established (reusing)\n");
258 rc = assuan_new (&ctx);
261 log_error ("can't allocate assuan context: %s\n", gpg_strerror (rc));
268 rc = assuan_socket_connect (ctx, socket_name, 0, 0);
271 log_error ("can't connect to socket '%s': %s\n",
272 socket_name, gpg_strerror (rc));
273 err = gpg_error (GPG_ERR_NO_SCDAEMON);
278 log_info ("new connection to SCdaemon established\n");
284 log_info ("SCdaemon is running but won't accept further connections\n");
285 err = gpg_error (GPG_ERR_NO_SCDAEMON);
289 /* Nope, it has not been started. Fire it up now. */
291 log_info ("no running SCdaemon - starting it\n");
295 #ifndef HAVE_W32_SYSTEM
296 err = gpg_error_from_syserror ();
298 log_error ("error flushing pending output: %s\n", strerror (errno));
299 /* At least Windows XP fails here with EBADF. According to docs
300 and Wine an fflush(NULL) is the same as _flushall. However
301 the Wime implementaion does not flush stdin,stdout and stderr
302 - see above. Lets try to ignore the error. */
303 #ifndef HAVE_W32_SYSTEM
308 if (!opt.scdaemon_program || !*opt.scdaemon_program)
309 opt.scdaemon_program = gnupg_module_name (GNUPG_MODULE_NAME_SCDAEMON);
310 if ( !(pgmname = strrchr (opt.scdaemon_program, '/')))
311 pgmname = opt.scdaemon_program;
316 argv[1] = "--multi-server";
317 if (gnupg_default_homedir_p ())
321 abs_homedir = make_absfilename_try (gnupg_homedir (), NULL);
324 log_error ("error building filename: %s\n",
325 gpg_strerror (gpg_error_from_syserror ()));
329 argv[2] = "--homedir";
330 argv[3] = abs_homedir;
335 if (!opt.running_detached)
337 if (log_get_fd () != -1)
338 no_close_list[i++] = assuan_fd_from_posix_fd (log_get_fd ());
339 no_close_list[i++] = assuan_fd_from_posix_fd (fileno (stderr));
341 no_close_list[i] = ASSUAN_INVALID_FD;
343 /* Connect to the scdaemon and perform initial handshaking. Use
344 detached flag so that under Windows SCDAEMON does not show up a
346 rc = assuan_pipe_connect (ctx, opt.scdaemon_program, argv,
347 no_close_list, atfork_cb, NULL,
348 ASSUAN_PIPE_CONNECT_DETACHED);
351 log_error ("can't connect to the SCdaemon: %s\n",
353 err = gpg_error (GPG_ERR_NO_SCDAEMON);
358 log_debug ("first connection to SCdaemon established\n");
361 /* Get the name of the additional socket opened by scdaemon. */
364 unsigned char *databuf;
369 init_membuf (&data, 256);
370 assuan_transact (ctx, "GETINFO socket_name",
371 put_membuf_cb, &data, NULL, NULL, NULL, NULL);
373 databuf = get_membuf (&data, &datalen);
374 if (databuf && datalen)
376 socket_name = xtrymalloc (datalen + 1);
378 log_error ("warning: can't store socket name: %s\n",
382 memcpy (socket_name, databuf, datalen);
383 socket_name[datalen] = 0;
385 log_debug ("additional connections at '%s'\n", socket_name);
391 /* Tell the scdaemon we want him to send us an event signal. We
392 don't support this for W32CE. */
393 #ifndef HAVE_W32CE_SYSTEM
394 if (opt.sigusr2_enabled)
398 #ifdef HAVE_W32_SYSTEM
399 snprintf (buf, sizeof buf, "OPTION event-signal=%lx",
400 (unsigned long)get_agent_scd_notify_event ());
402 snprintf (buf, sizeof buf, "OPTION event-signal=%d", SIGUSR2);
404 assuan_transact (ctx, buf, NULL, NULL, NULL, NULL, NULL, NULL);
406 #endif /*HAVE_W32CE_SYSTEM*/
408 primary_scd_ctx = ctx;
409 primary_scd_ctx_reusable = 0;
415 unlock_scd (ctrl, err);
417 assuan_release (ctx);
421 ctrl->scd_local->ctx = ctx;
423 rc = npth_mutex_unlock (&start_scd_lock);
425 log_error ("failed to release the start_scd lock: %s\n", strerror (rc));
430 /* Check whether the SCdaemon is active. This is a fast check without
431 any locking and might give a wrong result if another thread is about
432 to start the daemon or the daemon is about to be stopped.. */
434 agent_scd_check_running (void)
436 return !!primary_scd_ctx;
440 /* Check whether the Scdaemon is still alive and clean it up if not. */
442 agent_scd_check_aliveness (void)
445 #ifdef HAVE_W32_SYSTEM
450 struct timespec abstime;
453 if (!primary_scd_ctx)
454 return; /* No scdaemon running. */
456 /* This is not a critical function so we use a short timeout while
457 acquiring the lock. */
458 npth_clock_gettime (&abstime);
460 err = npth_mutex_timedlock (&start_scd_lock, &abstime);
463 if (err == ETIMEDOUT)
466 log_info ("failed to acquire the start_scd lock while"
467 " doing an aliveness check: %s\n", strerror (err));
470 log_error ("failed to acquire the start_scd lock while"
471 " doing an aliveness check: %s\n", strerror (err));
477 pid = assuan_get_pid (primary_scd_ctx);
478 #ifdef HAVE_W32_SYSTEM
479 /* If we have a PID we disconnect if either GetExitProcessCode
480 fails or if ir returns the exit code of the scdaemon. 259 is
481 the error code for STILL_ALIVE. */
482 if (pid != (pid_t)(void*)(-1) && pid
483 && (!GetExitCodeProcess ((HANDLE)pid, &rc) || rc != 259))
485 if (pid != (pid_t)(-1) && pid
486 && ((rc=waitpid (pid, NULL, WNOHANG))==-1 || (rc == pid)) )
489 /* Okay, scdaemon died. Disconnect the primary connection
490 now but take care that it won't do another wait. Also
491 cleanup all other connections and release their
492 resources. The next use will start a new daemon then.
493 Due to the use of the START_SCD_LOCAL we are sure that
494 none of these context are actually in use. */
495 struct scd_local_s *sl;
497 assuan_set_flag (primary_scd_ctx, ASSUAN_NO_WAITPID, 1);
498 assuan_release (primary_scd_ctx);
500 for (sl=scd_local_list; sl; sl = sl->next_local)
504 if (sl->ctx != primary_scd_ctx)
505 assuan_release (sl->ctx);
510 primary_scd_ctx = NULL;
511 primary_scd_ctx_reusable = 0;
518 err = npth_mutex_unlock (&start_scd_lock);
520 log_error ("failed to release the start_scd lock while"
521 " doing the aliveness check: %s\n", strerror (err));
526 /* Reset the SCD if it has been used. Actually it is not a reset but
527 a cleanup of resources used by the current connection. */
529 agent_reset_scd (ctrl_t ctrl)
533 if (ctrl->scd_local->ctx)
535 /* We can't disconnect the primary context because libassuan
536 does a waitpid on it and thus the system would hang.
537 Instead we send a reset and keep that connection for
539 if (ctrl->scd_local->ctx == primary_scd_ctx)
541 /* Send a RESTART to the SCD. This is required for the
542 primary connection as a kind of virtual EOF; we don't
543 have another way to tell it that the next command
544 should be viewed as if a new connection has been
545 made. For the non-primary connections this is not
546 needed as we simply close the socket. We don't check
547 for an error here because the RESTART may fail for
548 example if the scdaemon has already been terminated.
549 Anyway, we need to set the reusable flag to make sure
550 that the aliveness check can clean it up. */
551 assuan_transact (primary_scd_ctx, "RESTART",
552 NULL, NULL, NULL, NULL, NULL, NULL);
553 primary_scd_ctx_reusable = 1;
556 assuan_release (ctrl->scd_local->ctx);
557 ctrl->scd_local->ctx = NULL;
560 /* Remove the local context from our list and release it. */
563 else if (scd_local_list == ctrl->scd_local)
564 scd_local_list = ctrl->scd_local->next_local;
567 struct scd_local_s *sl;
569 for (sl=scd_local_list; sl->next_local; sl = sl->next_local)
570 if (sl->next_local == ctrl->scd_local)
574 sl->next_local = ctrl->scd_local->next_local;
576 xfree (ctrl->scd_local);
577 ctrl->scd_local = NULL;
586 learn_status_cb (void *opaque, const char *line)
588 struct learn_parm_s *parm = opaque;
589 const char *keyword = line;
592 for (keywordlen=0; *line && !spacep (line); line++, keywordlen++)
594 while (spacep (line))
596 if (keywordlen == 8 && !memcmp (keyword, "CERTINFO", keywordlen))
598 parm->certinfo_cb (parm->certinfo_cb_arg, line);
600 else if (keywordlen == 11 && !memcmp (keyword, "KEYPAIRINFO", keywordlen))
602 parm->kpinfo_cb (parm->kpinfo_cb_arg, line);
604 else if (keywordlen && *line)
606 parm->sinfo_cb (parm->sinfo_cb_arg, keyword, keywordlen, line);
612 /* Perform the LEARN command and return a list of all private keys
613 stored on the card. */
615 agent_card_learn (ctrl_t ctrl,
616 void (*kpinfo_cb)(void*, const char *),
618 void (*certinfo_cb)(void*, const char *),
619 void *certinfo_cb_arg,
620 void (*sinfo_cb)(void*, const char *, size_t, const char *),
624 struct learn_parm_s parm;
626 rc = start_scd (ctrl);
630 memset (&parm, 0, sizeof parm);
631 parm.kpinfo_cb = kpinfo_cb;
632 parm.kpinfo_cb_arg = kpinfo_cb_arg;
633 parm.certinfo_cb = certinfo_cb;
634 parm.certinfo_cb_arg = certinfo_cb_arg;
635 parm.sinfo_cb = sinfo_cb;
636 parm.sinfo_cb_arg = sinfo_cb_arg;
637 rc = assuan_transact (ctrl->scd_local->ctx, "LEARN --force",
638 NULL, NULL, NULL, NULL,
639 learn_status_cb, &parm);
641 return unlock_scd (ctrl, rc);
643 return unlock_scd (ctrl, 0);
649 get_serialno_cb (void *opaque, const char *line)
651 char **serialno = opaque;
652 const char *keyword = line;
656 for (keywordlen=0; *line && !spacep (line); line++, keywordlen++)
658 while (spacep (line))
661 if (keywordlen == 8 && !memcmp (keyword, "SERIALNO", keywordlen))
664 return gpg_error (GPG_ERR_CONFLICT); /* Unexpected status line. */
665 for (n=0,s=line; hexdigitp (s); s++, n++)
667 if (!n || (n&1)|| !(spacep (s) || !*s) )
668 return gpg_error (GPG_ERR_ASS_PARAMETER);
669 *serialno = xtrymalloc (n+1);
671 return out_of_core ();
672 memcpy (*serialno, line, n);
679 /* Return the serial number of the card or an appropriate error. The
680 serial number is returned as a hexstring. */
682 agent_card_serialno (ctrl_t ctrl, char **r_serialno, const char *demand)
685 char *serialno = NULL;
686 char line[ASSUAN_LINELENGTH];
688 rc = start_scd (ctrl);
693 strcpy (line, "SERIALNO");
695 snprintf (line, DIM(line), "SERIALNO --demand=%s", demand);
697 rc = assuan_transact (ctrl->scd_local->ctx, line,
698 NULL, NULL, NULL, NULL,
699 get_serialno_cb, &serialno);
703 return unlock_scd (ctrl, rc);
705 *r_serialno = serialno;
706 return unlock_scd (ctrl, 0);
712 /* Handle the NEEDPIN inquiry. */
714 inq_needpin (void *opaque, const char *line)
716 struct inq_needpin_s *parm = opaque;
722 parm->any_inq_seen = 1;
723 if ((s = has_leading_keyword (line, "NEEDPIN")))
727 pin = gcry_malloc_secure (pinlen);
729 return out_of_core ();
731 rc = parm->getpin_cb (parm->getpin_cb_arg, line, pin, pinlen);
733 rc = assuan_send_data (parm->ctx, pin, pinlen);
736 else if ((s = has_leading_keyword (line, "POPUPPINPADPROMPT")))
738 rc = parm->getpin_cb (parm->getpin_cb_arg, s, NULL, 1);
740 else if ((s = has_leading_keyword (line, "DISMISSPINPADPROMPT")))
742 rc = parm->getpin_cb (parm->getpin_cb_arg, "", NULL, 0);
744 else if (parm->passthru)
746 unsigned char *value;
749 int needrest = !strncmp (line, "KEYDATA", 8);
751 /* Pass the inquiry up to our caller. We limit the maximum
752 amount to an arbitrary value. As we know that the KEYDATA
753 enquiry is pretty sensitive we disable logging then */
754 if ((rest = (needrest
755 && !assuan_get_flag (parm->passthru, ASSUAN_CONFIDENTIAL))))
756 assuan_begin_confidential (parm->passthru);
757 rc = assuan_inquire (parm->passthru, line, &value, &valuelen, 8096);
759 assuan_end_confidential (parm->passthru);
762 if ((rest = (needrest
763 && !assuan_get_flag (parm->ctx, ASSUAN_CONFIDENTIAL))))
764 assuan_begin_confidential (parm->ctx);
765 rc = assuan_send_data (parm->ctx, value, valuelen);
767 assuan_end_confidential (parm->ctx);
771 log_error ("error forwarding inquiry '%s': %s\n",
772 line, gpg_strerror (rc));
776 log_error ("unsupported inquiry '%s'\n", line);
777 rc = gpg_error (GPG_ERR_ASS_UNKNOWN_INQUIRE);
784 /* Helper returning a command option to describe the used hash
785 algorithm. See scd/command.c:cmd_pksign. */
787 hash_algo_option (int algo)
791 case GCRY_MD_MD5 : return "--hash=md5";
792 case GCRY_MD_RMD160: return "--hash=rmd160";
793 case GCRY_MD_SHA1 : return "--hash=sha1";
794 case GCRY_MD_SHA224: return "--hash=sha224";
795 case GCRY_MD_SHA256: return "--hash=sha256";
796 case GCRY_MD_SHA384: return "--hash=sha384";
797 case GCRY_MD_SHA512: return "--hash=sha512";
804 cancel_inquire (ctrl_t ctrl, gpg_error_t rc)
806 gpg_error_t oldrc = rc;
808 /* The inquire callback was called and transact returned a
809 cancel error. We assume that the inquired process sent a
810 CANCEL. The passthrough code is not able to pass on the
811 CANCEL and thus scdaemon would stuck on this. As a
812 workaround we send a CANCEL now. */
813 rc = assuan_write_line (ctrl->scd_local->ctx, "CAN");
818 rc = assuan_read_line (ctrl->scd_local->ctx, &line, &len);
826 /* Create a signature using the current card. MDALGO is either 0 or
827 gives the digest algorithm. */
829 agent_card_pksign (ctrl_t ctrl,
831 int (*getpin_cb)(void *, const char *, char*, size_t),
834 const unsigned char *indata, size_t indatalen,
835 unsigned char **r_buf, size_t *r_buflen)
838 char line[ASSUAN_LINELENGTH];
840 struct inq_needpin_s inqparm;
843 rc = start_scd (ctrl);
847 if (indatalen*2 + 50 > DIM(line))
848 return unlock_scd (ctrl, gpg_error (GPG_ERR_GENERAL));
850 bin2hex (indata, indatalen, stpcpy (line, "SETDATA "));
852 rc = assuan_transact (ctrl->scd_local->ctx, line,
853 NULL, NULL, NULL, NULL, NULL, NULL);
855 return unlock_scd (ctrl, rc);
857 init_membuf (&data, 1024);
858 inqparm.ctx = ctrl->scd_local->ctx;
859 inqparm.getpin_cb = getpin_cb;
860 inqparm.getpin_cb_arg = getpin_cb_arg;
861 inqparm.passthru = 0;
862 inqparm.any_inq_seen = 0;
863 if (ctrl->use_auth_call)
864 snprintf (line, sizeof line, "PKAUTH %s", keyid);
866 snprintf (line, sizeof line, "PKSIGN %s %s",
867 hash_algo_option (mdalgo), keyid);
868 rc = assuan_transact (ctrl->scd_local->ctx, line,
869 put_membuf_cb, &data,
870 inq_needpin, &inqparm,
872 if (inqparm.any_inq_seen && (gpg_err_code(rc) == GPG_ERR_CANCELED ||
873 gpg_err_code(rc) == GPG_ERR_ASS_CANCELED))
874 rc = cancel_inquire (ctrl, rc);
880 xfree (get_membuf (&data, &len));
881 return unlock_scd (ctrl, rc);
884 *r_buf = get_membuf (&data, r_buflen);
885 return unlock_scd (ctrl, 0);
891 /* Check whether there is any padding info from scdaemon. */
893 padding_info_cb (void *opaque, const char *line)
895 int *r_padding = opaque;
898 if ((s=has_leading_keyword (line, "PADDING")))
900 *r_padding = atoi (s);
907 /* Decipher INDATA using the current card. Note that the returned
908 value is not an s-expression but the raw data as returned by
909 scdaemon. The padding information is stored at R_PADDING with -1
912 agent_card_pkdecrypt (ctrl_t ctrl,
914 int (*getpin_cb)(void *, const char *, char*, size_t),
916 const unsigned char *indata, size_t indatalen,
917 char **r_buf, size_t *r_buflen, int *r_padding)
920 char *p, line[ASSUAN_LINELENGTH];
922 struct inq_needpin_s inqparm;
926 *r_padding = -1; /* Unknown. */
927 rc = start_scd (ctrl);
931 /* FIXME: use secure memory where appropriate */
933 for (len = 0; len < indatalen;)
935 p = stpcpy (line, "SETDATA ");
937 p = stpcpy (p, "--append ");
938 for (i=0; len < indatalen && (i*2 < DIM(line)-50); i++, len++)
940 sprintf (p, "%02X", indata[len]);
943 rc = assuan_transact (ctrl->scd_local->ctx, line,
944 NULL, NULL, NULL, NULL, NULL, NULL);
946 return unlock_scd (ctrl, rc);
949 init_membuf (&data, 1024);
950 inqparm.ctx = ctrl->scd_local->ctx;
951 inqparm.getpin_cb = getpin_cb;
952 inqparm.getpin_cb_arg = getpin_cb_arg;
953 inqparm.passthru = 0;
954 inqparm.any_inq_seen = 0;
955 snprintf (line, DIM(line), "PKDECRYPT %s", keyid);
956 rc = assuan_transact (ctrl->scd_local->ctx, line,
957 put_membuf_cb, &data,
958 inq_needpin, &inqparm,
959 padding_info_cb, r_padding);
960 if (inqparm.any_inq_seen && (gpg_err_code(rc) == GPG_ERR_CANCELED ||
961 gpg_err_code(rc) == GPG_ERR_ASS_CANCELED))
962 rc = cancel_inquire (ctrl, rc);
966 xfree (get_membuf (&data, &len));
967 return unlock_scd (ctrl, rc);
969 *r_buf = get_membuf (&data, r_buflen);
971 return unlock_scd (ctrl, gpg_error (GPG_ERR_ENOMEM));
973 return unlock_scd (ctrl, 0);
978 /* Read a certificate with ID into R_BUF and R_BUFLEN. */
980 agent_card_readcert (ctrl_t ctrl,
981 const char *id, char **r_buf, size_t *r_buflen)
984 char line[ASSUAN_LINELENGTH];
989 rc = start_scd (ctrl);
993 init_membuf (&data, 1024);
994 snprintf (line, DIM(line), "READCERT %s", id);
995 rc = assuan_transact (ctrl->scd_local->ctx, line,
996 put_membuf_cb, &data,
1001 xfree (get_membuf (&data, &len));
1002 return unlock_scd (ctrl, rc);
1004 *r_buf = get_membuf (&data, r_buflen);
1006 return unlock_scd (ctrl, gpg_error (GPG_ERR_ENOMEM));
1008 return unlock_scd (ctrl, 0);
1013 /* Read a key with ID and return it in an allocate buffer pointed to
1014 by r_BUF as a valid S-expression. */
1016 agent_card_readkey (ctrl_t ctrl, const char *id, unsigned char **r_buf)
1019 char line[ASSUAN_LINELENGTH];
1024 rc = start_scd (ctrl);
1028 init_membuf (&data, 1024);
1029 snprintf (line, DIM(line), "READKEY %s", id);
1030 rc = assuan_transact (ctrl->scd_local->ctx, line,
1031 put_membuf_cb, &data,
1036 xfree (get_membuf (&data, &len));
1037 return unlock_scd (ctrl, rc);
1039 *r_buf = get_membuf (&data, &buflen);
1041 return unlock_scd (ctrl, gpg_error (GPG_ERR_ENOMEM));
1043 if (!gcry_sexp_canon_len (*r_buf, buflen, NULL, NULL))
1045 xfree (*r_buf); *r_buf = NULL;
1046 return unlock_scd (ctrl, gpg_error (GPG_ERR_INV_VALUE));
1049 return unlock_scd (ctrl, 0);
1053 struct writekey_parm_s
1055 assuan_context_t ctx;
1056 int (*getpin_cb)(void *, const char *, char*, size_t);
1057 void *getpin_cb_arg;
1058 assuan_context_t passthru;
1061 const unsigned char *keydata;
1065 /* Handle a KEYDATA inquiry. Note, we only send the data,
1066 assuan_transact takes care of flushing and writing the end */
1068 inq_writekey_parms (void *opaque, const char *line)
1070 struct writekey_parm_s *parm = opaque;
1072 if (has_leading_keyword (line, "KEYDATA"))
1073 return assuan_send_data (parm->ctx, parm->keydata, parm->keydatalen);
1075 return inq_needpin (opaque, line);
1080 agent_card_writekey (ctrl_t ctrl, int force, const char *serialno,
1081 const char *id, const char *keydata, size_t keydatalen,
1082 int (*getpin_cb)(void *, const char *, char*, size_t),
1083 void *getpin_cb_arg)
1086 char line[ASSUAN_LINELENGTH];
1087 struct writekey_parm_s parms;
1090 rc = start_scd (ctrl);
1094 snprintf (line, DIM(line), "WRITEKEY %s%s", force ? "--force " : "", id);
1095 parms.ctx = ctrl->scd_local->ctx;
1096 parms.getpin_cb = getpin_cb;
1097 parms.getpin_cb_arg = getpin_cb_arg;
1099 parms.any_inq_seen = 0;
1100 parms.keydata = keydata;
1101 parms.keydatalen = keydatalen;
1103 rc = assuan_transact (ctrl->scd_local->ctx, line, NULL, NULL,
1104 inq_writekey_parms, &parms, NULL, NULL);
1105 if (parms.any_inq_seen && (gpg_err_code(rc) == GPG_ERR_CANCELED ||
1106 gpg_err_code(rc) == GPG_ERR_ASS_CANCELED))
1107 rc = cancel_inquire (ctrl, rc);
1108 return unlock_scd (ctrl, rc);
1111 /* Type used with the card_getattr_cb. */
1112 struct card_getattr_parm_s {
1113 const char *keyword; /* Keyword to look for. */
1114 size_t keywordlen; /* strlen of KEYWORD. */
1115 char *data; /* Malloced and unescaped data. */
1116 int error; /* ERRNO value or 0 on success. */
1119 /* Callback function for agent_card_getattr. */
1121 card_getattr_cb (void *opaque, const char *line)
1123 struct card_getattr_parm_s *parm = opaque;
1124 const char *keyword = line;
1128 return 0; /* We want only the first occurrence. */
1130 for (keywordlen=0; *line && !spacep (line); line++, keywordlen++)
1132 while (spacep (line))
1135 if (keywordlen == parm->keywordlen
1136 && !memcmp (keyword, parm->keyword, keywordlen))
1138 parm->data = percent_plus_unescape ((const unsigned char*)line, 0xff);
1140 parm->error = errno;
1147 /* Call the agent to retrieve a single line data object. On success
1148 the object is malloced and stored at RESULT; it is guaranteed that
1149 NULL is never stored in this case. On error an error code is
1150 returned and NULL stored at RESULT. */
1152 agent_card_getattr (ctrl_t ctrl, const char *name, char **result)
1155 struct card_getattr_parm_s parm;
1156 char line[ASSUAN_LINELENGTH];
1161 return gpg_error (GPG_ERR_INV_VALUE);
1163 memset (&parm, 0, sizeof parm);
1164 parm.keyword = name;
1165 parm.keywordlen = strlen (name);
1167 /* We assume that NAME does not need escaping. */
1168 if (8 + strlen (name) > DIM(line)-1)
1169 return gpg_error (GPG_ERR_TOO_LARGE);
1170 stpcpy (stpcpy (line, "GETATTR "), name);
1172 err = start_scd (ctrl);
1176 err = assuan_transact (ctrl->scd_local->ctx, line,
1177 NULL, NULL, NULL, NULL,
1178 card_getattr_cb, &parm);
1179 if (!err && parm.error)
1180 err = gpg_error_from_errno (parm.error);
1182 if (!err && !parm.data)
1183 err = gpg_error (GPG_ERR_NO_DATA);
1186 *result = parm.data;
1190 return unlock_scd (ctrl, err);
1197 pass_status_thru (void *opaque, const char *line)
1199 assuan_context_t ctx = opaque;
1203 if (line[0] == '#' && (!line[1] || spacep (line+1)))
1205 /* We are called in convey comments mode. Now, if we see a
1206 comment marker as keyword we forward the line verbatim to the
1207 the caller. This way the comment lines from scdaemon won't
1208 appear as status lines with keyword '#'. */
1209 assuan_write_line (ctx, line);
1213 for (i=0; *line && !spacep (line) && i < DIM(keyword)-1; line++, i++)
1217 /* Truncate any remaining keyword stuff. */
1218 for (; *line && !spacep (line); line++)
1220 while (spacep (line))
1223 assuan_write_status (ctx, keyword, line);
1229 pass_data_thru (void *opaque, const void *buffer, size_t length)
1231 assuan_context_t ctx = opaque;
1233 assuan_send_data (ctx, buffer, length);
1238 /* Send the line CMDLINE with command for the SCDdaemon to it and send
1239 all status messages back. This command is used as a general quoting
1240 mechanism to pass everything verbatim to SCDAEMON. The PIN
1241 inquiry is handled inside gpg-agent. */
1243 agent_card_scd (ctrl_t ctrl, const char *cmdline,
1244 int (*getpin_cb)(void *, const char *, char*, size_t),
1245 void *getpin_cb_arg, void *assuan_context)
1248 struct inq_needpin_s inqparm;
1251 rc = start_scd (ctrl);
1255 inqparm.ctx = ctrl->scd_local->ctx;
1256 inqparm.getpin_cb = getpin_cb;
1257 inqparm.getpin_cb_arg = getpin_cb_arg;
1258 inqparm.passthru = assuan_context;
1259 inqparm.any_inq_seen = 0;
1260 saveflag = assuan_get_flag (ctrl->scd_local->ctx, ASSUAN_CONVEY_COMMENTS);
1261 assuan_set_flag (ctrl->scd_local->ctx, ASSUAN_CONVEY_COMMENTS, 1);
1262 rc = assuan_transact (ctrl->scd_local->ctx, cmdline,
1263 pass_data_thru, assuan_context,
1264 inq_needpin, &inqparm,
1265 pass_status_thru, assuan_context);
1266 if (inqparm.any_inq_seen && gpg_err_code(rc) == GPG_ERR_ASS_CANCELED)
1267 rc = cancel_inquire (ctrl, rc);
1269 assuan_set_flag (ctrl->scd_local->ctx, ASSUAN_CONVEY_COMMENTS, saveflag);
1272 return unlock_scd (ctrl, rc);
1275 return unlock_scd (ctrl, 0);