chiark / gitweb /
gpg: Fix searching for mail addresses in keyrings.
[gnupg2.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 <https://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[5];
199   assuan_fd_t no_close_list[3];
200   int i;
201   int rc;
202   char *abs_homedir = NULL;
203
204   if (opt.disable_scdaemon)
205     return gpg_error (GPG_ERR_NOT_SUPPORTED);
206
207   /* If this is the first call for this session, setup the local data
208      structure. */
209   if (!ctrl->scd_local)
210     {
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;
217     }
218
219
220   /* Assert that the lock count is as expected. */
221   if (ctrl->scd_local->locked)
222     {
223       log_error ("start_scd: invalid lock count (%d)\n",
224                  ctrl->scd_local->locked);
225       return gpg_error (GPG_ERR_INTERNAL);
226     }
227   ctrl->scd_local->locked++;
228
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
234                  error instead. */
235
236
237   /* We need to protect the following code. */
238   rc = npth_mutex_lock (&start_scd_lock);
239   if (rc)
240     {
241       log_error ("failed to acquire the start_scd lock: %s\n",
242                  strerror (rc));
243       return gpg_error (GPG_ERR_INTERNAL);
244     }
245
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)
250     {
251       ctx = primary_scd_ctx;
252       primary_scd_ctx_reusable = 0;
253       if (opt.verbose)
254         log_info ("new connection to SCdaemon established (reusing)\n");
255       goto leave;
256     }
257
258   rc = assuan_new (&ctx);
259   if (rc)
260     {
261       log_error ("can't allocate assuan context: %s\n", gpg_strerror (rc));
262       err = rc;
263       goto leave;
264     }
265
266   if (socket_name)
267     {
268       rc = assuan_socket_connect (ctx, socket_name, 0, 0);
269       if (rc)
270         {
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);
274           goto leave;
275         }
276
277       if (opt.verbose)
278         log_info ("new connection to SCdaemon established\n");
279       goto leave;
280     }
281
282   if (primary_scd_ctx)
283     {
284       log_info ("SCdaemon is running but won't accept further connections\n");
285       err = gpg_error (GPG_ERR_NO_SCDAEMON);
286       goto leave;
287     }
288
289   /* Nope, it has not been started.  Fire it up now. */
290   if (opt.verbose)
291     log_info ("no running SCdaemon - starting it\n");
292
293   if (fflush (NULL))
294     {
295 #ifndef HAVE_W32_SYSTEM
296       err = gpg_error_from_syserror ();
297 #endif
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
304       goto leave;
305 #endif
306     }
307
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;
312   else
313     pgmname++;
314
315   argv[0] = pgmname;
316   argv[1] = "--multi-server";
317   if (gnupg_default_homedir_p ())
318     argv[2] = NULL;
319   else
320     {
321       abs_homedir = make_absfilename_try (gnupg_homedir (), NULL);
322       if (!abs_homedir)
323         {
324           log_error ("error building filename: %s\n",
325                      gpg_strerror (gpg_error_from_syserror ()));
326           goto leave;
327         }
328
329       argv[2] = "--homedir";
330       argv[3] = abs_homedir;
331       argv[4] = NULL;
332     }
333
334   i=0;
335   if (!opt.running_detached)
336     {
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));
340     }
341   no_close_list[i] = ASSUAN_INVALID_FD;
342
343   /* Connect to the scdaemon and perform initial handshaking.  Use
344      detached flag so that under Windows SCDAEMON does not show up a
345      new window.  */
346   rc = assuan_pipe_connect (ctx, opt.scdaemon_program, argv,
347                             no_close_list, atfork_cb, NULL,
348                             ASSUAN_PIPE_CONNECT_DETACHED);
349   if (rc)
350     {
351       log_error ("can't connect to the SCdaemon: %s\n",
352                  gpg_strerror (rc));
353       err = gpg_error (GPG_ERR_NO_SCDAEMON);
354       goto leave;
355     }
356
357   if (opt.verbose)
358     log_debug ("first connection to SCdaemon established\n");
359
360
361   /* Get the name of the additional socket opened by scdaemon. */
362   {
363     membuf_t data;
364     unsigned char *databuf;
365     size_t datalen;
366
367     xfree (socket_name);
368     socket_name = NULL;
369     init_membuf (&data, 256);
370     assuan_transact (ctx, "GETINFO socket_name",
371                      put_membuf_cb, &data, NULL, NULL, NULL, NULL);
372
373     databuf = get_membuf (&data, &datalen);
374     if (databuf && datalen)
375       {
376         socket_name = xtrymalloc (datalen + 1);
377         if (!socket_name)
378           log_error ("warning: can't store socket name: %s\n",
379                      strerror (errno));
380         else
381           {
382             memcpy (socket_name, databuf, datalen);
383             socket_name[datalen] = 0;
384             if (DBG_IPC)
385               log_debug ("additional connections at '%s'\n", socket_name);
386           }
387       }
388     xfree (databuf);
389   }
390
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)
395     {
396       char buf[100];
397
398 #ifdef HAVE_W32_SYSTEM
399       snprintf (buf, sizeof buf, "OPTION event-signal=%lx",
400                 (unsigned long)get_agent_scd_notify_event ());
401 #else
402       snprintf (buf, sizeof buf, "OPTION event-signal=%d", SIGUSR2);
403 #endif
404       assuan_transact (ctx, buf, NULL, NULL, NULL, NULL, NULL, NULL);
405     }
406 #endif /*HAVE_W32CE_SYSTEM*/
407
408   primary_scd_ctx = ctx;
409   primary_scd_ctx_reusable = 0;
410   /* notify the main loop that something has changed */
411   interrupt_main_thread_loop ();
412   
413  leave:
414   xfree (abs_homedir);
415   if (err)
416     {
417       unlock_scd (ctrl, err);
418       if (ctx)
419         assuan_release (ctx);
420     }
421   else
422     {
423       ctrl->scd_local->ctx = ctx;
424     }
425   rc = npth_mutex_unlock (&start_scd_lock);
426   if (rc)
427     log_error ("failed to release the start_scd lock: %s\n", strerror (rc));
428   return err;
429 }
430
431
432 /* Check whether the SCdaemon is active.  This is a fast check without
433    any locking and might give a wrong result if another thread is about
434    to start the daemon or the daemon is about to be stopped.. */
435 int
436 agent_scd_check_running (void)
437 {
438   return !!primary_scd_ctx;
439 }
440
441
442 /* Check whether the Scdaemon is still alive and clean it up if not. */
443 void
444 agent_scd_check_aliveness (void)
445 {
446   pid_t pid;
447 #ifdef HAVE_W32_SYSTEM
448   DWORD rc;
449 #else
450   int rc;
451 #endif
452   struct timespec abstime;
453   int err;
454
455   if (!primary_scd_ctx)
456     return; /* No scdaemon running. */
457
458   /* This is not a critical function so we use a short timeout while
459      acquiring the lock.  */
460   npth_clock_gettime (&abstime);
461   abstime.tv_sec += 1;
462   err = npth_mutex_timedlock (&start_scd_lock, &abstime);
463   if (err)
464     {
465       if (err == ETIMEDOUT)
466         {
467           if (opt.verbose > 1)
468             log_info ("failed to acquire the start_scd lock while"
469                       " doing an aliveness check: %s\n", strerror (err));
470         }
471       else
472         log_error ("failed to acquire the start_scd lock while"
473                    " doing an aliveness check: %s\n", strerror (err));
474       return;
475     }
476
477   if (primary_scd_ctx)
478     {
479       pid = assuan_get_pid (primary_scd_ctx);
480 #ifdef HAVE_W32_SYSTEM
481       /* If we have a PID we disconnect if either GetExitProcessCode
482          fails or if ir returns the exit code of the scdaemon.  259 is
483          the error code for STILL_ALIVE.  */
484       if (pid != (pid_t)(void*)(-1) && pid
485           && (!GetExitCodeProcess ((HANDLE)pid, &rc) || rc != 259))
486 #else
487       if (pid != (pid_t)(-1) && pid
488           && ((rc=waitpid (pid, NULL, WNOHANG))==-1 || (rc == pid)) )
489 #endif
490         {
491           /* Okay, scdaemon died.  Disconnect the primary connection
492              now but take care that it won't do another wait. Also
493              cleanup all other connections and release their
494              resources.  The next use will start a new daemon then.
495              Due to the use of the START_SCD_LOCAL we are sure that
496              none of these context are actually in use. */
497           struct scd_local_s *sl;
498
499           assuan_set_flag (primary_scd_ctx, ASSUAN_NO_WAITPID, 1);
500           assuan_release (primary_scd_ctx);
501
502           for (sl=scd_local_list; sl; sl = sl->next_local)
503             {
504               if (sl->ctx)
505                 {
506                   if (sl->ctx != primary_scd_ctx)
507                     assuan_release (sl->ctx);
508                   sl->ctx = NULL;
509                 }
510             }
511
512           primary_scd_ctx = NULL;
513           primary_scd_ctx_reusable = 0;
514
515           xfree (socket_name);
516           socket_name = NULL;
517         }
518     }
519
520   err = npth_mutex_unlock (&start_scd_lock);
521   if (err)
522     log_error ("failed to release the start_scd lock while"
523                " doing the aliveness check: %s\n", strerror (err));
524 }
525
526
527
528 /* Reset the SCD if it has been used.  Actually it is not a reset but
529    a cleanup of resources used by the current connection. */
530 int
531 agent_reset_scd (ctrl_t ctrl)
532 {
533   if (ctrl->scd_local)
534     {
535       if (ctrl->scd_local->ctx)
536         {
537           /* We can't disconnect the primary context because libassuan
538              does a waitpid on it and thus the system would hang.
539              Instead we send a reset and keep that connection for
540              reuse. */
541           if (ctrl->scd_local->ctx == primary_scd_ctx)
542             {
543               /* Send a RESTART to the SCD.  This is required for the
544                  primary connection as a kind of virtual EOF; we don't
545                  have another way to tell it that the next command
546                  should be viewed as if a new connection has been
547                  made.  For the non-primary connections this is not
548                  needed as we simply close the socket.  We don't check
549                  for an error here because the RESTART may fail for
550                  example if the scdaemon has already been terminated.
551                  Anyway, we need to set the reusable flag to make sure
552                  that the aliveness check can clean it up. */
553               assuan_transact (primary_scd_ctx, "RESTART",
554                                NULL, NULL, NULL, NULL, NULL, NULL);
555               primary_scd_ctx_reusable = 1;
556             }
557           else
558             assuan_release (ctrl->scd_local->ctx);
559           ctrl->scd_local->ctx = NULL;
560         }
561
562       /* Remove the local context from our list and release it. */
563       if (!scd_local_list)
564         BUG ();
565       else if (scd_local_list == ctrl->scd_local)
566         scd_local_list = ctrl->scd_local->next_local;
567       else
568         {
569           struct scd_local_s *sl;
570
571           for (sl=scd_local_list; sl->next_local; sl = sl->next_local)
572             if (sl->next_local == ctrl->scd_local)
573               break;
574           if (!sl->next_local)
575             BUG ();
576           sl->next_local = ctrl->scd_local->next_local;
577         }
578       xfree (ctrl->scd_local);
579       ctrl->scd_local = NULL;
580     }
581
582   return 0;
583 }
584
585
586 \f
587 static gpg_error_t
588 learn_status_cb (void *opaque, const char *line)
589 {
590   struct learn_parm_s *parm = opaque;
591   const char *keyword = line;
592   int keywordlen;
593
594   for (keywordlen=0; *line && !spacep (line); line++, keywordlen++)
595     ;
596   while (spacep (line))
597     line++;
598   if (keywordlen == 8 && !memcmp (keyword, "CERTINFO", keywordlen))
599     {
600       parm->certinfo_cb (parm->certinfo_cb_arg, line);
601     }
602   else if (keywordlen == 11 && !memcmp (keyword, "KEYPAIRINFO", keywordlen))
603     {
604       parm->kpinfo_cb (parm->kpinfo_cb_arg, line);
605     }
606   else if (keywordlen && *line)
607     {
608       parm->sinfo_cb (parm->sinfo_cb_arg, keyword, keywordlen, line);
609     }
610
611   return 0;
612 }
613
614 /* Perform the LEARN command and return a list of all private keys
615    stored on the card. */
616 int
617 agent_card_learn (ctrl_t ctrl,
618                   void (*kpinfo_cb)(void*, const char *),
619                   void *kpinfo_cb_arg,
620                   void (*certinfo_cb)(void*, const char *),
621                   void *certinfo_cb_arg,
622                   void (*sinfo_cb)(void*, const char *, size_t, const char *),
623                   void *sinfo_cb_arg)
624 {
625   int rc;
626   struct learn_parm_s parm;
627
628   rc = start_scd (ctrl);
629   if (rc)
630     return rc;
631
632   memset (&parm, 0, sizeof parm);
633   parm.kpinfo_cb = kpinfo_cb;
634   parm.kpinfo_cb_arg = kpinfo_cb_arg;
635   parm.certinfo_cb = certinfo_cb;
636   parm.certinfo_cb_arg = certinfo_cb_arg;
637   parm.sinfo_cb = sinfo_cb;
638   parm.sinfo_cb_arg = sinfo_cb_arg;
639   rc = assuan_transact (ctrl->scd_local->ctx, "LEARN --force",
640                         NULL, NULL, NULL, NULL,
641                         learn_status_cb, &parm);
642   if (rc)
643     return unlock_scd (ctrl, rc);
644
645   return unlock_scd (ctrl, 0);
646 }
647
648
649 \f
650 static gpg_error_t
651 get_serialno_cb (void *opaque, const char *line)
652 {
653   char **serialno = opaque;
654   const char *keyword = line;
655   const char *s;
656   int keywordlen, n;
657
658   for (keywordlen=0; *line && !spacep (line); line++, keywordlen++)
659     ;
660   while (spacep (line))
661     line++;
662
663   if (keywordlen == 8 && !memcmp (keyword, "SERIALNO", keywordlen))
664     {
665       if (*serialno)
666         return gpg_error (GPG_ERR_CONFLICT); /* Unexpected status line. */
667       for (n=0,s=line; hexdigitp (s); s++, n++)
668         ;
669       if (!n || (n&1)|| !(spacep (s) || !*s) )
670         return gpg_error (GPG_ERR_ASS_PARAMETER);
671       *serialno = xtrymalloc (n+1);
672       if (!*serialno)
673         return out_of_core ();
674       memcpy (*serialno, line, n);
675       (*serialno)[n] = 0;
676     }
677
678   return 0;
679 }
680
681 /* Return the serial number of the card or an appropriate error.  The
682    serial number is returned as a hexstring. */
683 int
684 agent_card_serialno (ctrl_t ctrl, char **r_serialno, const char *demand)
685 {
686   int rc;
687   char *serialno = NULL;
688   char line[ASSUAN_LINELENGTH];
689
690   rc = start_scd (ctrl);
691   if (rc)
692     return rc;
693
694   if (!demand)
695     strcpy (line, "SERIALNO");
696   else
697     snprintf (line, DIM(line), "SERIALNO --demand=%s", demand);
698
699   rc = assuan_transact (ctrl->scd_local->ctx, line,
700                         NULL, NULL, NULL, NULL,
701                         get_serialno_cb, &serialno);
702   if (rc)
703     {
704       xfree (serialno);
705       return unlock_scd (ctrl, rc);
706     }
707   *r_serialno = serialno;
708   return unlock_scd (ctrl, 0);
709 }
710
711
712
713 \f
714 /* Handle the NEEDPIN inquiry. */
715 static gpg_error_t
716 inq_needpin (void *opaque, const char *line)
717 {
718   struct inq_needpin_s *parm = opaque;
719   const char *s;
720   char *pin;
721   size_t pinlen;
722   int rc;
723
724   parm->any_inq_seen = 1;
725   if ((s = has_leading_keyword (line, "NEEDPIN")))
726     {
727       line = s;
728       pinlen = 90;
729       pin = gcry_malloc_secure (pinlen);
730       if (!pin)
731         return out_of_core ();
732
733       rc = parm->getpin_cb (parm->getpin_cb_arg, line, pin, pinlen);
734       if (!rc)
735         rc = assuan_send_data (parm->ctx, pin, pinlen);
736       xfree (pin);
737     }
738   else if ((s = has_leading_keyword (line, "POPUPPINPADPROMPT")))
739     {
740       rc = parm->getpin_cb (parm->getpin_cb_arg, s, NULL, 1);
741     }
742   else if ((s = has_leading_keyword (line, "DISMISSPINPADPROMPT")))
743     {
744       rc = parm->getpin_cb (parm->getpin_cb_arg, "", NULL, 0);
745     }
746   else if (parm->passthru)
747     {
748       unsigned char *value;
749       size_t valuelen;
750       int rest;
751       int needrest = !strncmp (line, "KEYDATA", 8);
752
753       /* Pass the inquiry up to our caller.  We limit the maximum
754          amount to an arbitrary value.  As we know that the KEYDATA
755          enquiry is pretty sensitive we disable logging then */
756       if ((rest = (needrest
757                    && !assuan_get_flag (parm->passthru, ASSUAN_CONFIDENTIAL))))
758         assuan_begin_confidential (parm->passthru);
759       rc = assuan_inquire (parm->passthru, line, &value, &valuelen, 8096);
760       if (rest)
761         assuan_end_confidential (parm->passthru);
762       if (!rc)
763         {
764           if ((rest = (needrest
765                        && !assuan_get_flag (parm->ctx, ASSUAN_CONFIDENTIAL))))
766             assuan_begin_confidential (parm->ctx);
767           rc = assuan_send_data (parm->ctx, value, valuelen);
768           if (rest)
769             assuan_end_confidential (parm->ctx);
770           xfree (value);
771         }
772       else
773         log_error ("error forwarding inquiry '%s': %s\n",
774                    line, gpg_strerror (rc));
775     }
776   else
777     {
778       log_error ("unsupported inquiry '%s'\n", line);
779       rc = gpg_error (GPG_ERR_ASS_UNKNOWN_INQUIRE);
780     }
781
782   return rc;
783 }
784
785
786 /* Helper returning a command option to describe the used hash
787    algorithm.  See scd/command.c:cmd_pksign.  */
788 static const char *
789 hash_algo_option (int algo)
790 {
791   switch (algo)
792     {
793     case GCRY_MD_MD5   : return "--hash=md5";
794     case GCRY_MD_RMD160: return "--hash=rmd160";
795     case GCRY_MD_SHA1  : return "--hash=sha1";
796     case GCRY_MD_SHA224: return "--hash=sha224";
797     case GCRY_MD_SHA256: return "--hash=sha256";
798     case GCRY_MD_SHA384: return "--hash=sha384";
799     case GCRY_MD_SHA512: return "--hash=sha512";
800     default:             return "";
801     }
802 }
803
804
805 static gpg_error_t
806 cancel_inquire (ctrl_t ctrl, gpg_error_t rc)
807 {
808   gpg_error_t oldrc = rc;
809
810   /* The inquire callback was called and transact returned a
811      cancel error.  We assume that the inquired process sent a
812      CANCEL.  The passthrough code is not able to pass on the
813      CANCEL and thus scdaemon would stuck on this.  As a
814      workaround we send a CANCEL now.  */
815   rc = assuan_write_line (ctrl->scd_local->ctx, "CAN");
816   if (!rc) {
817     char *line;
818     size_t len;
819
820     rc = assuan_read_line (ctrl->scd_local->ctx, &line, &len);
821     if (!rc)
822       rc = oldrc;
823   }
824
825   return rc;
826 }
827
828 /* Create a signature using the current card.  MDALGO is either 0 or
829    gives the digest algorithm.  */
830 int
831 agent_card_pksign (ctrl_t ctrl,
832                    const char *keyid,
833                    int (*getpin_cb)(void *, const char *, char*, size_t),
834                    void *getpin_cb_arg,
835                    int mdalgo,
836                    const unsigned char *indata, size_t indatalen,
837                    unsigned char **r_buf, size_t *r_buflen)
838 {
839   int rc;
840   char line[ASSUAN_LINELENGTH];
841   membuf_t data;
842   struct inq_needpin_s inqparm;
843
844   *r_buf = NULL;
845   rc = start_scd (ctrl);
846   if (rc)
847     return rc;
848
849   if (indatalen*2 + 50 > DIM(line))
850     return unlock_scd (ctrl, gpg_error (GPG_ERR_GENERAL));
851
852   bin2hex (indata, indatalen, stpcpy (line, "SETDATA "));
853
854   rc = assuan_transact (ctrl->scd_local->ctx, line,
855                         NULL, NULL, NULL, NULL, NULL, NULL);
856   if (rc)
857     return unlock_scd (ctrl, rc);
858
859   init_membuf (&data, 1024);
860   inqparm.ctx = ctrl->scd_local->ctx;
861   inqparm.getpin_cb = getpin_cb;
862   inqparm.getpin_cb_arg = getpin_cb_arg;
863   inqparm.passthru = 0;
864   inqparm.any_inq_seen = 0;
865   if (ctrl->use_auth_call)
866     snprintf (line, sizeof line, "PKAUTH %s", keyid);
867   else
868     snprintf (line, sizeof line, "PKSIGN %s %s",
869               hash_algo_option (mdalgo), keyid);
870   rc = assuan_transact (ctrl->scd_local->ctx, line,
871                         put_membuf_cb, &data,
872                         inq_needpin, &inqparm,
873                         NULL, NULL);
874   if (inqparm.any_inq_seen && (gpg_err_code(rc) == GPG_ERR_CANCELED ||
875         gpg_err_code(rc) == GPG_ERR_ASS_CANCELED))
876     rc = cancel_inquire (ctrl, rc);
877
878   if (rc)
879     {
880       size_t len;
881
882       xfree (get_membuf (&data, &len));
883       return unlock_scd (ctrl, rc);
884     }
885
886   *r_buf = get_membuf (&data, r_buflen);
887   return unlock_scd (ctrl, 0);
888 }
889
890
891
892 \f
893 /* Check whether there is any padding info from scdaemon.  */
894 static gpg_error_t
895 padding_info_cb (void *opaque, const char *line)
896 {
897   int *r_padding = opaque;
898   const char *s;
899
900   if ((s=has_leading_keyword (line, "PADDING")))
901     {
902       *r_padding = atoi (s);
903     }
904
905   return 0;
906 }
907
908
909 /* Decipher INDATA using the current card.  Note that the returned
910    value is not an s-expression but the raw data as returned by
911    scdaemon.  The padding information is stored at R_PADDING with -1
912    for not known.  */
913 int
914 agent_card_pkdecrypt (ctrl_t ctrl,
915                       const char *keyid,
916                       int (*getpin_cb)(void *, const char *, char*, size_t),
917                       void *getpin_cb_arg,
918                       const unsigned char *indata, size_t indatalen,
919                       char **r_buf, size_t *r_buflen, int *r_padding)
920 {
921   int rc, i;
922   char *p, line[ASSUAN_LINELENGTH];
923   membuf_t data;
924   struct inq_needpin_s inqparm;
925   size_t len;
926
927   *r_buf = NULL;
928   *r_padding = -1; /* Unknown.  */
929   rc = start_scd (ctrl);
930   if (rc)
931     return rc;
932
933   /* FIXME: use secure memory where appropriate */
934
935   for (len = 0; len < indatalen;)
936     {
937       p = stpcpy (line, "SETDATA ");
938       if (len)
939         p = stpcpy (p, "--append ");
940       for (i=0; len < indatalen && (i*2 < DIM(line)-50); i++, len++)
941         {
942           sprintf (p, "%02X", indata[len]);
943           p += 2;
944         }
945       rc = assuan_transact (ctrl->scd_local->ctx, line,
946                             NULL, NULL, NULL, NULL, NULL, NULL);
947       if (rc)
948         return unlock_scd (ctrl, rc);
949     }
950
951   init_membuf (&data, 1024);
952   inqparm.ctx = ctrl->scd_local->ctx;
953   inqparm.getpin_cb = getpin_cb;
954   inqparm.getpin_cb_arg = getpin_cb_arg;
955   inqparm.passthru = 0;
956   inqparm.any_inq_seen = 0;
957   snprintf (line, DIM(line), "PKDECRYPT %s", keyid);
958   rc = assuan_transact (ctrl->scd_local->ctx, line,
959                         put_membuf_cb, &data,
960                         inq_needpin, &inqparm,
961                         padding_info_cb, r_padding);
962   if (inqparm.any_inq_seen && (gpg_err_code(rc) == GPG_ERR_CANCELED ||
963         gpg_err_code(rc) == GPG_ERR_ASS_CANCELED))
964     rc = cancel_inquire (ctrl, rc);
965
966   if (rc)
967     {
968       xfree (get_membuf (&data, &len));
969       return unlock_scd (ctrl, rc);
970     }
971   *r_buf = get_membuf (&data, r_buflen);
972   if (!*r_buf)
973     return unlock_scd (ctrl, gpg_error (GPG_ERR_ENOMEM));
974
975   return unlock_scd (ctrl, 0);
976 }
977
978
979 \f
980 /* Read a certificate with ID into R_BUF and R_BUFLEN. */
981 int
982 agent_card_readcert (ctrl_t ctrl,
983                      const char *id, char **r_buf, size_t *r_buflen)
984 {
985   int rc;
986   char line[ASSUAN_LINELENGTH];
987   membuf_t data;
988   size_t len;
989
990   *r_buf = NULL;
991   rc = start_scd (ctrl);
992   if (rc)
993     return rc;
994
995   init_membuf (&data, 1024);
996   snprintf (line, DIM(line), "READCERT %s", id);
997   rc = assuan_transact (ctrl->scd_local->ctx, line,
998                         put_membuf_cb, &data,
999                         NULL, NULL,
1000                         NULL, NULL);
1001   if (rc)
1002     {
1003       xfree (get_membuf (&data, &len));
1004       return unlock_scd (ctrl, rc);
1005     }
1006   *r_buf = get_membuf (&data, r_buflen);
1007   if (!*r_buf)
1008     return unlock_scd (ctrl, gpg_error (GPG_ERR_ENOMEM));
1009
1010   return unlock_scd (ctrl, 0);
1011 }
1012
1013
1014 \f
1015 /* Read a key with ID and return it in an allocate buffer pointed to
1016    by r_BUF as a valid S-expression. */
1017 int
1018 agent_card_readkey (ctrl_t ctrl, const char *id, unsigned char **r_buf)
1019 {
1020   int rc;
1021   char line[ASSUAN_LINELENGTH];
1022   membuf_t data;
1023   size_t len, buflen;
1024
1025   *r_buf = NULL;
1026   rc = start_scd (ctrl);
1027   if (rc)
1028     return rc;
1029
1030   init_membuf (&data, 1024);
1031   snprintf (line, DIM(line), "READKEY %s", id);
1032   rc = assuan_transact (ctrl->scd_local->ctx, line,
1033                         put_membuf_cb, &data,
1034                         NULL, NULL,
1035                         NULL, NULL);
1036   if (rc)
1037     {
1038       xfree (get_membuf (&data, &len));
1039       return unlock_scd (ctrl, rc);
1040     }
1041   *r_buf = get_membuf (&data, &buflen);
1042   if (!*r_buf)
1043     return unlock_scd (ctrl, gpg_error (GPG_ERR_ENOMEM));
1044
1045   if (!gcry_sexp_canon_len (*r_buf, buflen, NULL, NULL))
1046     {
1047       xfree (*r_buf); *r_buf = NULL;
1048       return unlock_scd (ctrl, gpg_error (GPG_ERR_INV_VALUE));
1049     }
1050
1051   return unlock_scd (ctrl, 0);
1052 }
1053
1054
1055 struct writekey_parm_s
1056 {
1057   assuan_context_t ctx;
1058   int (*getpin_cb)(void *, const char *, char*, size_t);
1059   void *getpin_cb_arg;
1060   assuan_context_t passthru;
1061   int any_inq_seen;
1062   /**/
1063   const unsigned char *keydata;
1064   size_t keydatalen;
1065 };
1066
1067 /* Handle a KEYDATA inquiry.  Note, we only send the data,
1068    assuan_transact takes care of flushing and writing the end */
1069 static gpg_error_t
1070 inq_writekey_parms (void *opaque, const char *line)
1071 {
1072   struct writekey_parm_s *parm = opaque;
1073
1074   if (has_leading_keyword (line, "KEYDATA"))
1075     return assuan_send_data (parm->ctx, parm->keydata, parm->keydatalen);
1076   else
1077     return inq_needpin (opaque, line);
1078 }
1079
1080
1081 int
1082 agent_card_writekey (ctrl_t ctrl,  int force, const char *serialno,
1083                      const char *id, const char *keydata, size_t keydatalen,
1084                      int (*getpin_cb)(void *, const char *, char*, size_t),
1085                      void *getpin_cb_arg)
1086 {
1087   int rc;
1088   char line[ASSUAN_LINELENGTH];
1089   struct writekey_parm_s parms;
1090
1091   (void)serialno;
1092   rc = start_scd (ctrl);
1093   if (rc)
1094     return rc;
1095
1096   snprintf (line, DIM(line), "WRITEKEY %s%s", force ? "--force " : "", id);
1097   parms.ctx = ctrl->scd_local->ctx;
1098   parms.getpin_cb = getpin_cb;
1099   parms.getpin_cb_arg = getpin_cb_arg;
1100   parms.passthru = 0;
1101   parms.any_inq_seen = 0;
1102   parms.keydata = keydata;
1103   parms.keydatalen = keydatalen;
1104
1105   rc = assuan_transact (ctrl->scd_local->ctx, line, NULL, NULL,
1106                         inq_writekey_parms, &parms, NULL, NULL);
1107   if (parms.any_inq_seen && (gpg_err_code(rc) == GPG_ERR_CANCELED ||
1108                              gpg_err_code(rc) == GPG_ERR_ASS_CANCELED))
1109     rc = cancel_inquire (ctrl, rc);
1110   return unlock_scd (ctrl, rc);
1111 }
1112 \f
1113 /* Type used with the card_getattr_cb.  */
1114 struct card_getattr_parm_s {
1115   const char *keyword;  /* Keyword to look for.  */
1116   size_t keywordlen;    /* strlen of KEYWORD.  */
1117   char *data;           /* Malloced and unescaped data.  */
1118   int error;            /* ERRNO value or 0 on success. */
1119 };
1120
1121 /* Callback function for agent_card_getattr.  */
1122 static gpg_error_t
1123 card_getattr_cb (void *opaque, const char *line)
1124 {
1125   struct card_getattr_parm_s *parm = opaque;
1126   const char *keyword = line;
1127   int keywordlen;
1128
1129   if (parm->data)
1130     return 0; /* We want only the first occurrence.  */
1131
1132   for (keywordlen=0; *line && !spacep (line); line++, keywordlen++)
1133     ;
1134   while (spacep (line))
1135     line++;
1136
1137   if (keywordlen == parm->keywordlen
1138       && !memcmp (keyword, parm->keyword, keywordlen))
1139     {
1140       parm->data = percent_plus_unescape ((const unsigned char*)line, 0xff);
1141       if (!parm->data)
1142         parm->error = errno;
1143     }
1144
1145   return 0;
1146 }
1147
1148
1149 /* Call the agent to retrieve a single line data object. On success
1150    the object is malloced and stored at RESULT; it is guaranteed that
1151    NULL is never stored in this case.  On error an error code is
1152    returned and NULL stored at RESULT. */
1153 gpg_error_t
1154 agent_card_getattr (ctrl_t ctrl, const char *name, char **result)
1155 {
1156   int err;
1157   struct card_getattr_parm_s parm;
1158   char line[ASSUAN_LINELENGTH];
1159
1160   *result = NULL;
1161
1162   if (!*name)
1163     return gpg_error (GPG_ERR_INV_VALUE);
1164
1165   memset (&parm, 0, sizeof parm);
1166   parm.keyword = name;
1167   parm.keywordlen = strlen (name);
1168
1169   /* We assume that NAME does not need escaping. */
1170   if (8 + strlen (name) > DIM(line)-1)
1171     return gpg_error (GPG_ERR_TOO_LARGE);
1172   stpcpy (stpcpy (line, "GETATTR "), name);
1173
1174   err = start_scd (ctrl);
1175   if (err)
1176     return err;
1177
1178   err = assuan_transact (ctrl->scd_local->ctx, line,
1179                          NULL, NULL, NULL, NULL,
1180                          card_getattr_cb, &parm);
1181   if (!err && parm.error)
1182     err = gpg_error_from_errno (parm.error);
1183
1184   if (!err && !parm.data)
1185     err = gpg_error (GPG_ERR_NO_DATA);
1186
1187   if (!err)
1188     *result = parm.data;
1189   else
1190     xfree (parm.data);
1191
1192   return unlock_scd (ctrl, err);
1193 }
1194
1195
1196
1197 \f
1198 static gpg_error_t
1199 pass_status_thru (void *opaque, const char *line)
1200 {
1201   assuan_context_t ctx = opaque;
1202   char keyword[200];
1203   int i;
1204
1205   if (line[0] == '#' && (!line[1] || spacep (line+1)))
1206     {
1207       /* We are called in convey comments mode.  Now, if we see a
1208          comment marker as keyword we forward the line verbatim to the
1209          the caller.  This way the comment lines from scdaemon won't
1210          appear as status lines with keyword '#'.  */
1211       assuan_write_line (ctx, line);
1212     }
1213   else
1214     {
1215       for (i=0; *line && !spacep (line) && i < DIM(keyword)-1; line++, i++)
1216         keyword[i] = *line;
1217       keyword[i] = 0;
1218
1219       /* Truncate any remaining keyword stuff.  */
1220       for (; *line && !spacep (line); line++)
1221         ;
1222       while (spacep (line))
1223         line++;
1224
1225       assuan_write_status (ctx, keyword, line);
1226     }
1227   return 0;
1228 }
1229
1230 static gpg_error_t
1231 pass_data_thru (void *opaque, const void *buffer, size_t length)
1232 {
1233   assuan_context_t ctx = opaque;
1234
1235   assuan_send_data (ctx, buffer, length);
1236   return 0;
1237 }
1238
1239
1240 /* Send the line CMDLINE with command for the SCDdaemon to it and send
1241    all status messages back.  This command is used as a general quoting
1242    mechanism to pass everything verbatim to SCDAEMON.  The PIN
1243    inquiry is handled inside gpg-agent.  */
1244 int
1245 agent_card_scd (ctrl_t ctrl, const char *cmdline,
1246                 int (*getpin_cb)(void *, const char *, char*, size_t),
1247                 void *getpin_cb_arg, void *assuan_context)
1248 {
1249   int rc;
1250   struct inq_needpin_s inqparm;
1251   int saveflag;
1252
1253   rc = start_scd (ctrl);
1254   if (rc)
1255     return rc;
1256
1257   inqparm.ctx = ctrl->scd_local->ctx;
1258   inqparm.getpin_cb = getpin_cb;
1259   inqparm.getpin_cb_arg = getpin_cb_arg;
1260   inqparm.passthru = assuan_context;
1261   inqparm.any_inq_seen = 0;
1262   saveflag = assuan_get_flag (ctrl->scd_local->ctx, ASSUAN_CONVEY_COMMENTS);
1263   assuan_set_flag (ctrl->scd_local->ctx, ASSUAN_CONVEY_COMMENTS, 1);
1264   rc = assuan_transact (ctrl->scd_local->ctx, cmdline,
1265                         pass_data_thru, assuan_context,
1266                         inq_needpin, &inqparm,
1267                         pass_status_thru, assuan_context);
1268   if (inqparm.any_inq_seen && gpg_err_code(rc) == GPG_ERR_ASS_CANCELED)
1269     rc = cancel_inquire (ctrl, rc);
1270
1271   assuan_set_flag (ctrl->scd_local->ctx, ASSUAN_CONVEY_COMMENTS, saveflag);
1272   if (rc)
1273     {
1274       return unlock_scd (ctrl, rc);
1275     }
1276
1277   return unlock_scd (ctrl, 0);
1278 }