Imported Upstream version 2.1.11
[platform/upstream/gpg2.git] / agent / call-scd.c
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
5  *
6  * This file is part of GnuPG.
7  *
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.
12  *
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.
17  *
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/>.
20  */
21
22 #include <config.h>
23 #include <errno.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <ctype.h>
28 #include <assert.h>
29 #include <unistd.h>
30 #ifdef HAVE_SIGNAL_H
31 # include <signal.h>
32 #endif
33 #include <sys/stat.h>
34 #include <sys/types.h>
35 #ifndef HAVE_W32_SYSTEM
36 #include <sys/wait.h>
37 #endif
38 #include <npth.h>
39
40 #include "agent.h"
41 #include <assuan.h>
42
43 #ifdef _POSIX_OPEN_MAX
44 #define MAX_OPEN_FDS _POSIX_OPEN_MAX
45 #else
46 #define MAX_OPEN_FDS 20
47 #endif
48
49 /* Definition of module local data of the CTRL structure.  */
50 struct scd_local_s
51 {
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;
55
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.  */
60   ctrl_t ctrl_backlink;
61
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. */
66
67 };
68
69
70 /* Callback parameter for learn card */
71 struct learn_parm_s
72 {
73   void (*kpinfo_cb)(void*, const char *);
74   void *kpinfo_cb_arg;
75   void (*certinfo_cb)(void*, const char *);
76   void *certinfo_cb_arg;
77   void (*sinfo_cb)(void*, const char *, size_t, const char *);
78   void *sinfo_cb_arg;
79 };
80
81 struct inq_needpin_s
82 {
83   assuan_context_t ctx;
84   int (*getpin_cb)(void *, const char *, char*, size_t);
85   void *getpin_cb_arg;
86   assuan_context_t passthru;  /* If not NULL, pass unknown inquiries
87                                  up to the caller.  */
88   int any_inq_seen;
89 };
90
91
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;
95
96 /* A Mutex used inside the start_scd function. */
97 static npth_mutex_t start_scd_lock;
98
99 /* A malloced string with the name of the socket to be used for
100    additional connections.  May be NULL if not provided by
101    SCdaemon. */
102 static char *socket_name;
103
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;
107
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
110    any connection. */
111 static int primary_scd_ctx_reusable;
112
113
114
115 /* Local prototypes.  */
116
117
118
119 \f
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. */
124 void
125 initialize_module_call_scd (void)
126 {
127   static int initialized;
128   int err;
129
130   if (!initialized)
131     {
132       err = npth_mutex_init (&start_scd_lock, NULL);
133       if (err)
134         log_fatal ("error initializing mutex: %s\n", strerror (err));
135       initialized = 1;
136     }
137 }
138
139
140 /* This function may be called to print infromation pertaining to the
141    current state of this module to the log. */
142 void
143 agent_scd_dump_state (void)
144 {
145   log_info ("agent_scd_dump_state: primary_scd_ctx=%p pid=%ld reusable=%d\n",
146             primary_scd_ctx,
147             (long)assuan_get_pid (primary_scd_ctx),
148             primary_scd_ctx_reusable);
149   if (socket_name)
150     log_info ("agent_scd_dump_state: socket='%s'\n", socket_name);
151 }
152
153
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
160    the function. */
161 static int
162 unlock_scd (ctrl_t ctrl, int rc)
163 {
164   if (ctrl->scd_local->locked != 1)
165     {
166       log_error ("unlock_scd: invalid lock count (%d)\n",
167                  ctrl->scd_local->locked);
168       if (!rc)
169         rc = gpg_error (GPG_ERR_INTERNAL);
170     }
171   ctrl->scd_local->locked = 0;
172   return rc;
173 }
174
175 /* To make sure we leave no secrets in our image after forking of the
176    scdaemon, we use this callback. */
177 static void
178 atfork_cb (void *opaque, int where)
179 {
180   (void)opaque;
181
182   if (!where)
183     gcry_control (GCRYCTL_TERM_SECMEM);
184 }
185
186
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. */
192 static int
193 start_scd (ctrl_t ctrl)
194 {
195   gpg_error_t err = 0;
196   const char *pgmname;
197   assuan_context_t ctx = NULL;
198   const char *argv[3];
199   assuan_fd_t no_close_list[3];
200   int i;
201   int rc;
202
203   if (opt.disable_scdaemon)
204     return gpg_error (GPG_ERR_NOT_SUPPORTED);
205
206   /* If this is the first call for this session, setup the local data
207      structure. */
208   if (!ctrl->scd_local)
209     {
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;
216     }
217
218
219   /* Assert that the lock count is as expected. */
220   if (ctrl->scd_local->locked)
221     {
222       log_error ("start_scd: invalid lock count (%d)\n",
223                  ctrl->scd_local->locked);
224       return gpg_error (GPG_ERR_INTERNAL);
225     }
226   ctrl->scd_local->locked++;
227
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
233                  error instead. */
234
235
236   /* We need to protect the following code. */
237   rc = npth_mutex_lock (&start_scd_lock);
238   if (rc)
239     {
240       log_error ("failed to acquire the start_scd lock: %s\n",
241                  strerror (rc));
242       return gpg_error (GPG_ERR_INTERNAL);
243     }
244
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)
249     {
250       ctx = primary_scd_ctx;
251       primary_scd_ctx_reusable = 0;
252       if (opt.verbose)
253         log_info ("new connection to SCdaemon established (reusing)\n");
254       goto leave;
255     }
256
257   rc = assuan_new (&ctx);
258   if (rc)
259     {
260       log_error ("can't allocate assuan context: %s\n", gpg_strerror (rc));
261       err = rc;
262       goto leave;
263     }
264
265   if (socket_name)
266     {
267       rc = assuan_socket_connect (ctx, socket_name, 0, 0);
268       if (rc)
269         {
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);
273           goto leave;
274         }
275
276       if (opt.verbose)
277         log_info ("new connection to SCdaemon established\n");
278       goto leave;
279     }
280
281   if (primary_scd_ctx)
282     {
283       log_info ("SCdaemon is running but won't accept further connections\n");
284       err = gpg_error (GPG_ERR_NO_SCDAEMON);
285       goto leave;
286     }
287
288   /* Nope, it has not been started.  Fire it up now. */
289   if (opt.verbose)
290     log_info ("no running SCdaemon - starting it\n");
291
292   if (fflush (NULL))
293     {
294 #ifndef HAVE_W32_SYSTEM
295       err = gpg_error_from_syserror ();
296 #endif
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
303       goto leave;
304 #endif
305     }
306
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;
311   else
312     pgmname++;
313
314   argv[0] = pgmname;
315   argv[1] = "--multi-server";
316   argv[2] = NULL;
317
318   i=0;
319   if (!opt.running_detached)
320     {
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));
324     }
325   no_close_list[i] = ASSUAN_INVALID_FD;
326
327   /* Connect to the scdaemon and perform initial handshaking.  Use
328      detached flag so that under Windows SCDAEMON does not show up a
329      new window.  */
330   rc = assuan_pipe_connect (ctx, opt.scdaemon_program, argv,
331                             no_close_list, atfork_cb, NULL,
332                             ASSUAN_PIPE_CONNECT_DETACHED);
333   if (rc)
334     {
335       log_error ("can't connect to the SCdaemon: %s\n",
336                  gpg_strerror (rc));
337       err = gpg_error (GPG_ERR_NO_SCDAEMON);
338       goto leave;
339     }
340
341   if (opt.verbose)
342     log_debug ("first connection to SCdaemon established\n");
343
344
345   /* Get the name of the additional socket opened by scdaemon. */
346   {
347     membuf_t data;
348     unsigned char *databuf;
349     size_t datalen;
350
351     xfree (socket_name);
352     socket_name = NULL;
353     init_membuf (&data, 256);
354     assuan_transact (ctx, "GETINFO socket_name",
355                      put_membuf_cb, &data, NULL, NULL, NULL, NULL);
356
357     databuf = get_membuf (&data, &datalen);
358     if (databuf && datalen)
359       {
360         socket_name = xtrymalloc (datalen + 1);
361         if (!socket_name)
362           log_error ("warning: can't store socket name: %s\n",
363                      strerror (errno));
364         else
365           {
366             memcpy (socket_name, databuf, datalen);
367             socket_name[datalen] = 0;
368             if (DBG_IPC)
369               log_debug ("additional connections at '%s'\n", socket_name);
370           }
371       }
372     xfree (databuf);
373   }
374
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)
379     {
380       char buf[100];
381
382 #ifdef HAVE_W32_SYSTEM
383       snprintf (buf, sizeof buf, "OPTION event-signal=%lx",
384                 (unsigned long)get_agent_scd_notify_event ());
385 #else
386       snprintf (buf, sizeof buf, "OPTION event-signal=%d", SIGUSR2);
387 #endif
388       assuan_transact (ctx, buf, NULL, NULL, NULL, NULL, NULL, NULL);
389     }
390 #endif /*HAVE_W32CE_SYSTEM*/
391
392   primary_scd_ctx = ctx;
393   primary_scd_ctx_reusable = 0;
394
395  leave:
396   if (err)
397     {
398       unlock_scd (ctrl, err);
399       if (ctx)
400         assuan_release (ctx);
401     }
402   else
403     {
404       ctrl->scd_local->ctx = ctx;
405     }
406   rc = npth_mutex_unlock (&start_scd_lock);
407   if (rc)
408     log_error ("failed to release the start_scd lock: %s\n", strerror (rc));
409   return err;
410 }
411
412
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.. */
416 int
417 agent_scd_check_running (void)
418 {
419   return !!primary_scd_ctx;
420 }
421
422
423 /* Check whether the Scdaemon is still alive and clean it up if not. */
424 void
425 agent_scd_check_aliveness (void)
426 {
427   pid_t pid;
428 #ifdef HAVE_W32_SYSTEM
429   DWORD rc;
430 #else
431   int rc;
432 #endif
433   struct timespec abstime;
434   int err;
435
436   if (!primary_scd_ctx)
437     return; /* No scdaemon running. */
438
439   /* This is not a critical function so we use a short timeout while
440      acquiring the lock.  */
441   npth_clock_gettime (&abstime);
442   abstime.tv_sec += 1;
443   err = npth_mutex_timedlock (&start_scd_lock, &abstime);
444   if (err)
445     {
446       if (err == ETIMEDOUT)
447         {
448           if (opt.verbose > 1)
449             log_info ("failed to acquire the start_scd lock while"
450                       " doing an aliveness check: %s\n", strerror (err));
451         }
452       else
453         log_error ("failed to acquire the start_scd lock while"
454                    " doing an aliveness check: %s\n", strerror (err));
455       return;
456     }
457
458   if (primary_scd_ctx)
459     {
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))
467 #else
468       if (pid != (pid_t)(-1) && pid
469           && ((rc=waitpid (pid, NULL, WNOHANG))==-1 || (rc == pid)) )
470 #endif
471         {
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;
479
480           assuan_set_flag (primary_scd_ctx, ASSUAN_NO_WAITPID, 1);
481           assuan_release (primary_scd_ctx);
482
483           for (sl=scd_local_list; sl; sl = sl->next_local)
484             {
485               if (sl->ctx)
486                 {
487                   if (sl->ctx != primary_scd_ctx)
488                     assuan_release (sl->ctx);
489                   sl->ctx = NULL;
490                 }
491             }
492
493           primary_scd_ctx = NULL;
494           primary_scd_ctx_reusable = 0;
495
496           xfree (socket_name);
497           socket_name = NULL;
498         }
499     }
500
501   err = npth_mutex_unlock (&start_scd_lock);
502   if (err)
503     log_error ("failed to release the start_scd lock while"
504                " doing the aliveness check: %s\n", strerror (err));
505 }
506
507
508
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. */
511 int
512 agent_reset_scd (ctrl_t ctrl)
513 {
514   if (ctrl->scd_local)
515     {
516       if (ctrl->scd_local->ctx)
517         {
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
521              reuse. */
522           if (ctrl->scd_local->ctx == primary_scd_ctx)
523             {
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;
537             }
538           else
539             assuan_release (ctrl->scd_local->ctx);
540           ctrl->scd_local->ctx = NULL;
541         }
542
543       /* Remove the local context from our list and release it. */
544       if (!scd_local_list)
545         BUG ();
546       else if (scd_local_list == ctrl->scd_local)
547         scd_local_list = ctrl->scd_local->next_local;
548       else
549         {
550           struct scd_local_s *sl;
551
552           for (sl=scd_local_list; sl->next_local; sl = sl->next_local)
553             if (sl->next_local == ctrl->scd_local)
554               break;
555           if (!sl->next_local)
556             BUG ();
557           sl->next_local = ctrl->scd_local->next_local;
558         }
559       xfree (ctrl->scd_local);
560       ctrl->scd_local = NULL;
561     }
562
563   return 0;
564 }
565
566
567 \f
568 static gpg_error_t
569 learn_status_cb (void *opaque, const char *line)
570 {
571   struct learn_parm_s *parm = opaque;
572   const char *keyword = line;
573   int keywordlen;
574
575   for (keywordlen=0; *line && !spacep (line); line++, keywordlen++)
576     ;
577   while (spacep (line))
578     line++;
579   if (keywordlen == 8 && !memcmp (keyword, "CERTINFO", keywordlen))
580     {
581       parm->certinfo_cb (parm->certinfo_cb_arg, line);
582     }
583   else if (keywordlen == 11 && !memcmp (keyword, "KEYPAIRINFO", keywordlen))
584     {
585       parm->kpinfo_cb (parm->kpinfo_cb_arg, line);
586     }
587   else if (keywordlen && *line)
588     {
589       parm->sinfo_cb (parm->sinfo_cb_arg, keyword, keywordlen, line);
590     }
591
592   return 0;
593 }
594
595 /* Perform the LEARN command and return a list of all private keys
596    stored on the card. */
597 int
598 agent_card_learn (ctrl_t ctrl,
599                   void (*kpinfo_cb)(void*, const char *),
600                   void *kpinfo_cb_arg,
601                   void (*certinfo_cb)(void*, const char *),
602                   void *certinfo_cb_arg,
603                   void (*sinfo_cb)(void*, const char *, size_t, const char *),
604                   void *sinfo_cb_arg)
605 {
606   int rc;
607   struct learn_parm_s parm;
608
609   rc = start_scd (ctrl);
610   if (rc)
611     return rc;
612
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);
623   if (rc)
624     return unlock_scd (ctrl, rc);
625
626   return unlock_scd (ctrl, 0);
627 }
628
629
630 \f
631 static gpg_error_t
632 get_serialno_cb (void *opaque, const char *line)
633 {
634   char **serialno = opaque;
635   const char *keyword = line;
636   const char *s;
637   int keywordlen, n;
638
639   for (keywordlen=0; *line && !spacep (line); line++, keywordlen++)
640     ;
641   while (spacep (line))
642     line++;
643
644   if (keywordlen == 8 && !memcmp (keyword, "SERIALNO", keywordlen))
645     {
646       if (*serialno)
647         return gpg_error (GPG_ERR_CONFLICT); /* Unexpected status line. */
648       for (n=0,s=line; hexdigitp (s); s++, n++)
649         ;
650       if (!n || (n&1)|| !(spacep (s) || !*s) )
651         return gpg_error (GPG_ERR_ASS_PARAMETER);
652       *serialno = xtrymalloc (n+1);
653       if (!*serialno)
654         return out_of_core ();
655       memcpy (*serialno, line, n);
656       (*serialno)[n] = 0;
657     }
658
659   return 0;
660 }
661
662 /* Return the serial number of the card or an appropriate error.  The
663    serial number is returned as a hexstring. */
664 int
665 agent_card_serialno (ctrl_t ctrl, char **r_serialno)
666 {
667   int rc;
668   char *serialno = NULL;
669
670   rc = start_scd (ctrl);
671   if (rc)
672     return rc;
673
674   rc = assuan_transact (ctrl->scd_local->ctx, "SERIALNO",
675                         NULL, NULL, NULL, NULL,
676                         get_serialno_cb, &serialno);
677   if (rc)
678     {
679       xfree (serialno);
680       return unlock_scd (ctrl, rc);
681     }
682   *r_serialno = serialno;
683   return unlock_scd (ctrl, 0);
684 }
685
686
687
688 \f
689 /* Handle the NEEDPIN inquiry. */
690 static gpg_error_t
691 inq_needpin (void *opaque, const char *line)
692 {
693   struct inq_needpin_s *parm = opaque;
694   const char *s;
695   char *pin;
696   size_t pinlen;
697   int rc;
698
699   parm->any_inq_seen = 1;
700   if ((s = has_leading_keyword (line, "NEEDPIN")))
701     {
702       line = s;
703       pinlen = 90;
704       pin = gcry_malloc_secure (pinlen);
705       if (!pin)
706         return out_of_core ();
707
708       rc = parm->getpin_cb (parm->getpin_cb_arg, line, pin, pinlen);
709       if (!rc)
710         rc = assuan_send_data (parm->ctx, pin, pinlen);
711       xfree (pin);
712     }
713   else if ((s = has_leading_keyword (line, "POPUPPINPADPROMPT")))
714     {
715       rc = parm->getpin_cb (parm->getpin_cb_arg, s, NULL, 1);
716     }
717   else if ((s = has_leading_keyword (line, "DISMISSPINPADPROMPT")))
718     {
719       rc = parm->getpin_cb (parm->getpin_cb_arg, "", NULL, 0);
720     }
721   else if (parm->passthru)
722     {
723       unsigned char *value;
724       size_t valuelen;
725       int rest;
726       int needrest = !strncmp (line, "KEYDATA", 8);
727
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);
735       if (rest)
736         assuan_end_confidential (parm->passthru);
737       if (!rc)
738         {
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);
743           if (rest)
744             assuan_end_confidential (parm->ctx);
745           xfree (value);
746         }
747       else
748         log_error ("error forwarding inquiry '%s': %s\n",
749                    line, gpg_strerror (rc));
750     }
751   else
752     {
753       log_error ("unsupported inquiry '%s'\n", line);
754       rc = gpg_error (GPG_ERR_ASS_UNKNOWN_INQUIRE);
755     }
756
757   return rc;
758 }
759
760
761 /* Helper returning a command option to describe the used hash
762    algorithm.  See scd/command.c:cmd_pksign.  */
763 static const char *
764 hash_algo_option (int algo)
765 {
766   switch (algo)
767     {
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";
775     default:             return "";
776     }
777 }
778
779
780 static gpg_error_t
781 cancel_inquire (ctrl_t ctrl, gpg_error_t rc)
782 {
783   gpg_error_t oldrc = rc;
784
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");
791   if (!rc) {
792     char *line;
793     size_t len;
794
795     rc = assuan_read_line (ctrl->scd_local->ctx, &line, &len);
796     if (!rc)
797       rc = oldrc;
798   }
799
800   return rc;
801 }
802
803 /* Create a signature using the current card.  MDALGO is either 0 or
804    gives the digest algorithm.  */
805 int
806 agent_card_pksign (ctrl_t ctrl,
807                    const char *keyid,
808                    int (*getpin_cb)(void *, const char *, char*, size_t),
809                    void *getpin_cb_arg,
810                    int mdalgo,
811                    const unsigned char *indata, size_t indatalen,
812                    unsigned char **r_buf, size_t *r_buflen)
813 {
814   int rc;
815   char line[ASSUAN_LINELENGTH];
816   membuf_t data;
817   struct inq_needpin_s inqparm;
818
819   *r_buf = NULL;
820   rc = start_scd (ctrl);
821   if (rc)
822     return rc;
823
824   if (indatalen*2 + 50 > DIM(line))
825     return unlock_scd (ctrl, gpg_error (GPG_ERR_GENERAL));
826
827   bin2hex (indata, indatalen, stpcpy (line, "SETDATA "));
828
829   rc = assuan_transact (ctrl->scd_local->ctx, line,
830                         NULL, NULL, NULL, NULL, NULL, NULL);
831   if (rc)
832     return unlock_scd (ctrl, rc);
833
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);
842   else
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,
848                         NULL, NULL);
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);
852
853   if (rc)
854     {
855       size_t len;
856
857       xfree (get_membuf (&data, &len));
858       return unlock_scd (ctrl, rc);
859     }
860
861   *r_buf = get_membuf (&data, r_buflen);
862   return unlock_scd (ctrl, 0);
863 }
864
865
866
867 \f
868 /* Check whether there is any padding info from scdaemon.  */
869 static gpg_error_t
870 padding_info_cb (void *opaque, const char *line)
871 {
872   int *r_padding = opaque;
873   const char *s;
874
875   if ((s=has_leading_keyword (line, "PADDING")))
876     {
877       *r_padding = atoi (s);
878     }
879
880   return 0;
881 }
882
883
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
887    for not known.  */
888 int
889 agent_card_pkdecrypt (ctrl_t ctrl,
890                       const char *keyid,
891                       int (*getpin_cb)(void *, const char *, char*, size_t),
892                       void *getpin_cb_arg,
893                       const unsigned char *indata, size_t indatalen,
894                       char **r_buf, size_t *r_buflen, int *r_padding)
895 {
896   int rc, i;
897   char *p, line[ASSUAN_LINELENGTH];
898   membuf_t data;
899   struct inq_needpin_s inqparm;
900   size_t len;
901
902   *r_buf = NULL;
903   *r_padding = -1; /* Unknown.  */
904   rc = start_scd (ctrl);
905   if (rc)
906     return rc;
907
908   /* FIXME: use secure memory where appropriate */
909
910   for (len = 0; len < indatalen;)
911     {
912       p = stpcpy (line, "SETDATA ");
913       if (len)
914         p = stpcpy (p, "--append ");
915       for (i=0; len < indatalen && (i*2 < DIM(line)-50); i++, len++)
916         {
917           sprintf (p, "%02X", indata[len]);
918           p += 2;
919         }
920       rc = assuan_transact (ctrl->scd_local->ctx, line,
921                             NULL, NULL, NULL, NULL, NULL, NULL);
922       if (rc)
923         return unlock_scd (ctrl, rc);
924     }
925
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);
941
942   if (rc)
943     {
944       xfree (get_membuf (&data, &len));
945       return unlock_scd (ctrl, rc);
946     }
947   *r_buf = get_membuf (&data, r_buflen);
948   if (!*r_buf)
949     return unlock_scd (ctrl, gpg_error (GPG_ERR_ENOMEM));
950
951   return unlock_scd (ctrl, 0);
952 }
953
954
955 \f
956 /* Read a certificate with ID into R_BUF and R_BUFLEN. */
957 int
958 agent_card_readcert (ctrl_t ctrl,
959                      const char *id, char **r_buf, size_t *r_buflen)
960 {
961   int rc;
962   char line[ASSUAN_LINELENGTH];
963   membuf_t data;
964   size_t len;
965
966   *r_buf = NULL;
967   rc = start_scd (ctrl);
968   if (rc)
969     return rc;
970
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,
976                         NULL, NULL,
977                         NULL, NULL);
978   if (rc)
979     {
980       xfree (get_membuf (&data, &len));
981       return unlock_scd (ctrl, rc);
982     }
983   *r_buf = get_membuf (&data, r_buflen);
984   if (!*r_buf)
985     return unlock_scd (ctrl, gpg_error (GPG_ERR_ENOMEM));
986
987   return unlock_scd (ctrl, 0);
988 }
989
990
991 \f
992 /* Read a key with ID and return it in an allocate buffer pointed to
993    by r_BUF as a valid S-expression. */
994 int
995 agent_card_readkey (ctrl_t ctrl, const char *id, unsigned char **r_buf)
996 {
997   int rc;
998   char line[ASSUAN_LINELENGTH];
999   membuf_t data;
1000   size_t len, buflen;
1001
1002   *r_buf = NULL;
1003   rc = start_scd (ctrl);
1004   if (rc)
1005     return rc;
1006
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,
1012                         NULL, NULL,
1013                         NULL, NULL);
1014   if (rc)
1015     {
1016       xfree (get_membuf (&data, &len));
1017       return unlock_scd (ctrl, rc);
1018     }
1019   *r_buf = get_membuf (&data, &buflen);
1020   if (!*r_buf)
1021     return unlock_scd (ctrl, gpg_error (GPG_ERR_ENOMEM));
1022
1023   if (!gcry_sexp_canon_len (*r_buf, buflen, NULL, NULL))
1024     {
1025       xfree (*r_buf); *r_buf = NULL;
1026       return unlock_scd (ctrl, gpg_error (GPG_ERR_INV_VALUE));
1027     }
1028
1029   return unlock_scd (ctrl, 0);
1030 }
1031
1032
1033 struct writekey_parm_s
1034 {
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;
1039   int any_inq_seen;
1040   /**/
1041   const unsigned char *keydata;
1042   size_t keydatalen;
1043 };
1044
1045 /* Handle a KEYDATA inquiry.  Note, we only send the data,
1046    assuan_transact takes care of flushing and writing the end */
1047 static gpg_error_t
1048 inq_writekey_parms (void *opaque, const char *line)
1049 {
1050   struct writekey_parm_s *parm = opaque;
1051
1052   if (has_leading_keyword (line, "KEYDATA"))
1053     return assuan_send_data (parm->ctx, parm->keydata, parm->keydatalen);
1054   else
1055     return inq_needpin (opaque, line);
1056 }
1057
1058
1059 int
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)
1064 {
1065   int rc;
1066   char line[ASSUAN_LINELENGTH];
1067   struct writekey_parm_s parms;
1068
1069   (void)serialno;
1070   rc = start_scd (ctrl);
1071   if (rc)
1072     return rc;
1073
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;
1079   parms.passthru = 0;
1080   parms.any_inq_seen = 0;
1081   parms.keydata = keydata;
1082   parms.keydatalen = keydatalen;
1083
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);
1090 }
1091 \f
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. */
1098 };
1099
1100 /* Callback function for agent_card_getattr.  */
1101 static gpg_error_t
1102 card_getattr_cb (void *opaque, const char *line)
1103 {
1104   struct card_getattr_parm_s *parm = opaque;
1105   const char *keyword = line;
1106   int keywordlen;
1107
1108   if (parm->data)
1109     return 0; /* We want only the first occurrence.  */
1110
1111   for (keywordlen=0; *line && !spacep (line); line++, keywordlen++)
1112     ;
1113   while (spacep (line))
1114     line++;
1115
1116   if (keywordlen == parm->keywordlen
1117       && !memcmp (keyword, parm->keyword, keywordlen))
1118     {
1119       parm->data = percent_plus_unescape ((const unsigned char*)line, 0xff);
1120       if (!parm->data)
1121         parm->error = errno;
1122     }
1123
1124   return 0;
1125 }
1126
1127
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. */
1132 gpg_error_t
1133 agent_card_getattr (ctrl_t ctrl, const char *name, char **result)
1134 {
1135   int err;
1136   struct card_getattr_parm_s parm;
1137   char line[ASSUAN_LINELENGTH];
1138
1139   *result = NULL;
1140
1141   if (!*name)
1142     return gpg_error (GPG_ERR_INV_VALUE);
1143
1144   memset (&parm, 0, sizeof parm);
1145   parm.keyword = name;
1146   parm.keywordlen = strlen (name);
1147
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);
1152
1153   err = start_scd (ctrl);
1154   if (err)
1155     return err;
1156
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);
1162
1163   if (!err && !parm.data)
1164     err = gpg_error (GPG_ERR_NO_DATA);
1165
1166   if (!err)
1167     *result = parm.data;
1168   else
1169     xfree (parm.data);
1170
1171   return unlock_scd (ctrl, err);
1172 }
1173
1174
1175
1176 \f
1177 static gpg_error_t
1178 pass_status_thru (void *opaque, const char *line)
1179 {
1180   assuan_context_t ctx = opaque;
1181   char keyword[200];
1182   int i;
1183
1184   if (line[0] == '#' && (!line[1] || spacep (line+1)))
1185     {
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);
1191     }
1192   else
1193     {
1194       for (i=0; *line && !spacep (line) && i < DIM(keyword)-1; line++, i++)
1195         keyword[i] = *line;
1196       keyword[i] = 0;
1197
1198       /* Truncate any remaining keyword stuff.  */
1199       for (; *line && !spacep (line); line++)
1200         ;
1201       while (spacep (line))
1202         line++;
1203
1204       assuan_write_status (ctx, keyword, line);
1205     }
1206   return 0;
1207 }
1208
1209 static gpg_error_t
1210 pass_data_thru (void *opaque, const void *buffer, size_t length)
1211 {
1212   assuan_context_t ctx = opaque;
1213
1214   assuan_send_data (ctx, buffer, length);
1215   return 0;
1216 }
1217
1218
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.  */
1223 int
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)
1227 {
1228   int rc;
1229   struct inq_needpin_s inqparm;
1230   int saveflag;
1231
1232   rc = start_scd (ctrl);
1233   if (rc)
1234     return rc;
1235
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);
1249
1250   assuan_set_flag (ctrl->scd_local->ctx, ASSUAN_CONVEY_COMMENTS, saveflag);
1251   if (rc)
1252     {
1253       return unlock_scd (ctrl, rc);
1254     }
1255
1256   return unlock_scd (ctrl, 0);
1257 }