Imported Upstream version 2.3.4
[platform/upstream/gpg2.git] / scd / app.c
1 /* app.c - Application selection.
2  * Copyright (C) 2003, 2004, 2005 Free Software Foundation, Inc.
3  *
4  * This file is part of GnuPG.
5  *
6  * GnuPG is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * GnuPG is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, see <https://www.gnu.org/licenses/>.
18  */
19
20 #include <config.h>
21 #include <errno.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <npth.h>
26
27 #include "scdaemon.h"
28 #include "../common/exechelp.h"
29 #include "iso7816.h"
30 #include "apdu.h"
31 #include "../common/tlv.h"
32 #include "../common/membuf.h"
33
34
35 /* Forward declaration of internal function.  */
36 static gpg_error_t
37 select_additional_application_internal (card_t card, apptype_t req_apptype);
38 static gpg_error_t
39 send_serialno_and_app_status (card_t card, int with_apps, ctrl_t ctrl);
40 static gpg_error_t run_reselect (ctrl_t ctrl, card_t c, app_t a, app_t a_prev);
41
42 /*
43  * Multiple readers, single writer (MRSW) lock.
44  */
45 struct mrsw_lock
46 {
47   npth_mutex_t lock;
48   npth_cond_t cond;
49   int num_readers_active;
50   int num_writers_waiting;
51   int writer_active;
52   npth_cond_t notify_cond;
53 };
54
55 /* MRSW lock to protect the list of cards.
56  *
57  * This structure is used for serializing access to the list of cards
58  * (by CARD_TOP).  While allowing multiple accesses by different
59  * connections as "r" access (for a CARD in the list), "w" access to
60  * update the list is only possible with a single thread.
61  *
62  * Each use of a CARD (in the list) does "r" access.
63  *
64  * For "w" access, the app_send_devinfo function may wait on any
65  * change of the list.  For other cases of "w" access are opening new
66  * card or removal of card, updating the list of card.
67  *
68  * Note that for serializing access to each CARD (and its associated
69  * applications) itself, it is done separately by another mutex with
70  * lock_card/unlock_card.
71  */
72 static struct mrsw_lock card_list_lock;
73
74 /* A list of card contexts.  A card is a collection of applications
75  * (described by app_t) on the same physical token. */
76 static card_t card_top;
77
78
79 /* The list of application names and their select function.  If no
80  * specific application is selected the first available application on
81  * a card is selected.  */
82 struct app_priority_list_s
83 {
84   apptype_t apptype;
85   char const *name;
86   gpg_error_t (*select_func)(app_t);
87 };
88
89 static struct app_priority_list_s app_priority_list[] =
90   {{ APPTYPE_OPENPGP  , "openpgp",   app_select_openpgp   },
91    { APPTYPE_PIV      , "piv",       app_select_piv       },
92    { APPTYPE_NKS      , "nks",       app_select_nks       },
93    { APPTYPE_P15      , "p15",       app_select_p15       },
94    { APPTYPE_GELDKARTE, "geldkarte", app_select_geldkarte },
95    { APPTYPE_DINSIG   , "dinsig",    app_select_dinsig    },
96    { APPTYPE_SC_HSM   , "sc-hsm",    app_select_sc_hsm    },
97    { APPTYPE_NONE     , NULL,        NULL                 }
98    /* APPTYPE_UNDEFINED is special and not listed here.  */
99   };
100
101
102
103
104 \f
105 /* Map a cardtype to a string.  Never returns NULL.  */
106 const char *
107 strcardtype (cardtype_t t)
108 {
109   switch (t)
110     {
111     case CARDTYPE_GENERIC:     return "generic";
112     case CARDTYPE_GNUK:        return "gnuk";
113     case CARDTYPE_YUBIKEY:     return "yubikey";
114     case CARDTYPE_ZEITCONTROL: return "zeitcontrol";
115     }
116   return "?";
117 }
118
119
120 /* Map an application type to a string.  Never returns NULL.  */
121 const char *
122 strapptype (apptype_t t)
123 {
124   int i;
125
126   for (i=0; app_priority_list[i].apptype; i++)
127     if (app_priority_list[i].apptype == t)
128       return app_priority_list[i].name;
129   return t == APPTYPE_UNDEFINED? "undefined" : t? "?" : "none";
130 }
131
132
133 const char *
134 xstrapptype (app_t app)
135 {
136   return app? strapptype (app->apptype) : "[no_app]";
137 }
138
139
140 /* Return the apptype for NAME.  */
141 static apptype_t
142 apptype_from_name (const char *name)
143 {
144   int i;
145
146   if (!name)
147     return APPTYPE_NONE;
148
149   for (i=0; app_priority_list[i].apptype; i++)
150     if (!ascii_strcasecmp (app_priority_list[i].name, name))
151       return app_priority_list[i].apptype;
152   if (!ascii_strcasecmp ("undefined", name))
153     return APPTYPE_UNDEFINED;
154   return APPTYPE_NONE;
155 }
156
157
158 /* Return the apptype for KEYREF.  This is the first part of the
159  * KEYREF up to the dot.  */
160 static apptype_t
161 apptype_from_keyref (const char *keyref)
162 {
163   int i;
164   unsigned int n;
165   const char *s;
166
167   if (!keyref)
168     return APPTYPE_NONE;
169   s = strchr (keyref, '.');
170   if (!s || s == keyref || !s[1])
171     return APPTYPE_NONE; /* Not a valid keyref.  */
172   n = s - keyref;
173
174   for (i=0; app_priority_list[i].apptype; i++)
175     if (strlen (app_priority_list[i].name) == n
176         && !ascii_strncasecmp (app_priority_list[i].name, keyref, n))
177       return app_priority_list[i].apptype;
178
179   return APPTYPE_NONE;
180 }
181
182
183 /* Return true if both serilanumbers are the same.  This function
184  * takes care of some peculiarities.  */
185 static int
186 is_same_serialno (const unsigned char *sna, size_t snalen,
187                   const unsigned char *snb, size_t snblen)
188 {
189   if ((!sna && !snb) || (!snalen && !snblen))
190     return 1;
191   if (!sna || !snb)
192     return 0;  /* One of them is NULL.  (Both NULL tested above).  */
193
194   if (snalen != snblen)
195     return 0;  /* (No special cases for this below).  */
196
197   /* The special case for OpenPGP cards where we ignore the version
198    * bytes (vvvv).  Example: D276000124010304000500009D8A0000
199    *                         ^^^^^^^^^^^^vvvvmmmmssssssssrrrr  */
200   if (snalen == 16 && !memcmp (sna, "\xD2\x76\x00\x01\x24\x01", 6))
201     {
202       if (memcmp (snb, "\xD2\x76\x00\x01\x24\x01", 6))
203         return 0;  /* No */
204       return !memcmp (sna + 8, snb + 8, 8);
205     }
206
207   return !memcmp (sna, snb, snalen);
208 }
209
210
211
212 /* Initialization function to change the default app_priority_list.
213  * LIST is a list of comma or space separated strings with application
214  * names.  Unknown names will only result in warning message.
215  * Application not mentioned in LIST are used in their original order
216  * after the given once.  */
217 void
218 app_update_priority_list (const char *arg)
219 {
220   struct app_priority_list_s save;
221   char **names;
222   int i, j, idx;
223
224   names = strtokenize (arg, ", ");
225   if (!names)
226     log_fatal ("strtokenize failed: %s\n",
227                gpg_strerror (gpg_error_from_syserror ()));
228
229   idx = 0;
230   for (i=0; names[i]; i++)
231     {
232       ascii_strlwr (names[i]);
233       for (j=0; j < i; j++)
234         if (!strcmp (names[j], names[i]))
235           break;
236       if (j < i)
237         {
238           log_info ("warning: duplicate application '%s' in priority list\n",
239                     names[i]);
240           continue;
241         }
242
243       for (j=idx; app_priority_list[j].name; j++)
244         if (!strcmp (names[i], app_priority_list[j].name))
245           break;
246       if (!app_priority_list[j].name)
247         {
248           log_info ("warning: unknown application '%s' in priority list\n",
249                     names[i]);
250           continue;
251         }
252       save = app_priority_list[idx];
253       app_priority_list[idx] = app_priority_list[j];
254       app_priority_list[j] = save;
255       idx++;
256     }
257   log_assert (idx < DIM (app_priority_list));
258
259   xfree (names);
260   for (i=0; app_priority_list[i].name; i++)
261     log_info ("app priority %d: %s\n", i, app_priority_list[i].name);
262 }
263
264
265 static void
266 print_progress_line (void *opaque, const char *what, int pc, int cur, int tot)
267 {
268   ctrl_t ctrl = opaque;
269   char line[100];
270
271   if (ctrl)
272     {
273       snprintf (line, sizeof line, "%s %c %d %d", what, pc, cur, tot);
274       send_status_direct (ctrl, "PROGRESS", line);
275     }
276 }
277
278
279 /* Lock the CARD.  This function shall be used right before calling
280  * any of the actual application functions to serialize access to the
281  * reader.  We do this always even if the card is not actually used.
282  * This allows an actual connection to assume that it never shares a
283  * card (while performing one command).  Returns 0 on success; only
284  * then the unlock_reader function must be called after returning from
285  * the handler.  Right now we assume a that a reader has just one
286  * card; this may eventually need refinement. */
287 static gpg_error_t
288 lock_card (card_t card, ctrl_t ctrl)
289 {
290   if (npth_mutex_lock (&card->lock))
291     {
292       gpg_error_t err = gpg_error_from_syserror ();
293       log_error ("failed to acquire CARD lock for %p: %s\n",
294                  card, gpg_strerror (err));
295       return err;
296     }
297
298   apdu_set_progress_cb (card->slot, print_progress_line, ctrl);
299   apdu_set_prompt_cb (card->slot, popup_prompt, ctrl);
300
301   return 0;
302 }
303
304
305 /* Release a lock on a card.  See lock_reader(). */
306 static void
307 unlock_card (card_t card)
308 {
309   apdu_set_progress_cb (card->slot, NULL, NULL);
310   apdu_set_prompt_cb (card->slot, NULL, NULL);
311
312   if (npth_mutex_unlock (&card->lock))
313     {
314       gpg_error_t err = gpg_error_from_syserror ();
315       log_error ("failed to release CARD lock for %p: %s\n",
316                  card, gpg_strerror (err));
317     }
318 }
319
320
321 static void
322 card_list_r_lock (void)
323 {
324   npth_mutex_lock (&card_list_lock.lock);
325   while (card_list_lock.num_writers_waiting
326          || card_list_lock.writer_active)
327     npth_cond_wait (&card_list_lock.cond, &card_list_lock.lock);
328   card_list_lock.num_readers_active++;
329   npth_mutex_unlock (&card_list_lock.lock);
330 }
331
332 static void
333 card_list_r_unlock (void)
334 {
335   npth_mutex_lock (&card_list_lock.lock);
336   if (--card_list_lock.num_readers_active == 0)
337     npth_cond_broadcast (&card_list_lock.cond);
338   npth_mutex_unlock (&card_list_lock.lock);
339 }
340
341
342 static void
343 card_list_w_lock (void)
344 {
345   npth_mutex_lock (&card_list_lock.lock);
346   card_list_lock.num_writers_waiting++;
347   while (card_list_lock.num_readers_active
348          || card_list_lock.writer_active)
349     npth_cond_wait (&card_list_lock.cond, &card_list_lock.lock);
350   card_list_lock.num_writers_waiting--;
351   card_list_lock.writer_active++;
352   npth_mutex_unlock (&card_list_lock.lock);
353 }
354
355 static void
356 card_list_w_unlock (void)
357 {
358   npth_mutex_lock (&card_list_lock.lock);
359   card_list_lock.writer_active--;
360   npth_cond_broadcast (&card_list_lock.cond);
361   npth_mutex_unlock (&card_list_lock.lock);
362 }
363
364
365 static void
366 card_list_signal (void)
367 {
368   npth_cond_broadcast (&card_list_lock.notify_cond);
369 }
370
371 static void
372 card_list_wait (void)
373 {
374   npth_mutex_lock (&card_list_lock.lock);
375   card_list_lock.writer_active--;
376   npth_cond_broadcast (&card_list_lock.cond);
377
378   npth_cond_wait (&card_list_lock.notify_cond, &card_list_lock.lock);
379
380   card_list_lock.num_writers_waiting++;
381   while (card_list_lock.num_readers_active
382          || card_list_lock.writer_active)
383     npth_cond_wait (&card_list_lock.cond, &card_list_lock.lock);
384   card_list_lock.num_writers_waiting--;
385
386   card_list_lock.writer_active++;
387   npth_mutex_unlock (&card_list_lock.lock);
388 }
389
390
391 /* This function may be called to print information pertaining to the
392  * current state of this module to the log. */
393 void
394 app_dump_state (void)
395 {
396   card_t c;
397   app_t a;
398
399   card_list_r_lock ();
400   for (c = card_top; c; c = c->next)
401     {
402       log_info ("app_dump_state: card=%p slot=%d type=%s refcount=%u\n",
403                 c, c->slot, strcardtype (c->cardtype), c->ref_count);
404       /* FIXME The use of log_info risks a race!  */
405       for (a=c->app; a; a = a->next)
406         log_info ("app_dump_state:   app=%p type='%s'\n",
407                   a, strapptype (a->apptype));
408     }
409   card_list_r_unlock ();
410 }
411
412
413 /*
414  * Send information for all available cards.
415  *
416  * With KEEP_LOOPING=0, it only outputs once.
417  * With KEEP_LOOPING<0, it keeps looping, until it detects no device.
418  * With KEEP_LOOPING>0, it keeps looping forever.
419  */
420 gpg_error_t
421 app_send_devinfo (ctrl_t ctrl, int keep_looping)
422 {
423   card_t c;
424   app_t a;
425   int no_device;
426
427   card_list_w_lock ();
428   while (1)
429     {
430       no_device = (card_top == NULL);
431       if (no_device && keep_looping < 0)
432         break;
433
434       send_status_direct (ctrl, "DEVINFO_START", "");
435       for (c = card_top; c; c = c->next)
436         {
437           char *serialno;
438           char card_info[80];
439
440           serialno = card_get_serialno (c);
441           snprintf (card_info, sizeof card_info, "DEVICE %s %s",
442                     strcardtype (c->cardtype), serialno);
443           xfree (serialno);
444
445           for (a = c->app; a; a = a->next)
446             send_status_direct (ctrl, card_info, strapptype (a->apptype));
447         }
448       send_status_direct (ctrl, "DEVINFO_END", "");
449
450       if (no_device && !keep_looping)
451         break;
452
453       card_list_wait ();
454     }
455   card_list_w_unlock ();
456
457   return no_device ? gpg_error (GPG_ERR_NOT_FOUND): 0;
458 }
459
460 /* Check whether the application NAME is allowed.  This does not mean
461    we have support for it though.  */
462 static int
463 is_app_allowed (const char *name)
464 {
465   strlist_t l;
466
467   for (l=opt.disabled_applications; l; l = l->next)
468     if (!strcmp (l->d, name))
469       return 0; /* no */
470   return 1; /* yes */
471 }
472
473
474 /* This function is mainly used by the serialno command to check for
475  * an application conflict which may appear if the serialno command is
476  * used to request a specific application and the connection has
477  * already done a select_application.   Return values are:
478  *   0              - No conflict
479  *   GPG_ERR_FALSE  - Another application is in use but it is possible
480  *                    to switch to the requested application.
481  *   Other code     - Switching is not possible.
482  *
483  * If SERIALNO_BIN is not NULL a conflict is only asserted if the
484  * serialno of the card matches.
485  */
486 gpg_error_t
487 check_application_conflict (card_t card, const char *name,
488                             const unsigned char *serialno_bin,
489                             size_t serialno_bin_len)
490 {
491   apptype_t apptype;
492
493   if (!card || !name)
494     return 0;
495   if (!card->app)
496     return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED); /* Should not happen.  */
497
498   if (serialno_bin && card->serialno)
499     {
500       if (!is_same_serialno (card->serialno,  card->serialnolen,
501                              serialno_bin, serialno_bin_len))
502         return 0; /* The card does not match the requested S/N.  */
503     }
504
505   apptype = apptype_from_name (name);
506   if (card->app->apptype == apptype)
507     return 0;
508
509   if (card->app->apptype == APPTYPE_UNDEFINED)
510     return 0;
511
512   if (card->cardtype == CARDTYPE_YUBIKEY)
513     {
514       if (card->app->apptype == APPTYPE_OPENPGP)
515         {
516           /* Current app is OpenPGP.  */
517           if (!ascii_strcasecmp (name, "piv"))
518             return gpg_error (GPG_ERR_FALSE);  /* Switching allowed.  */
519         }
520       else if (card->app->apptype == APPTYPE_PIV)
521         {
522           /* Current app is PIV.  */
523           if (!ascii_strcasecmp (name, "openpgp"))
524             return gpg_error (GPG_ERR_FALSE);  /* Switching allowed.  */
525         }
526     }
527
528   log_info ("application '%s' in use - can't switch\n",
529             strapptype (card->app->apptype));
530
531   return gpg_error (GPG_ERR_CONFLICT);
532 }
533
534
535 gpg_error_t
536 card_reset (card_t card)
537 {
538   gpg_error_t err = 0;
539   int sw;
540
541   sw = apdu_reset (card->slot);
542   if (sw)
543     err = gpg_error (GPG_ERR_CARD_RESET);
544
545   card->reset_requested = 1;
546   scd_kick_the_loop ();
547   gnupg_sleep (1);
548
549   return err;
550 }
551
552 static gpg_error_t
553 app_new_register (int slot, ctrl_t ctrl, const char *name,
554                   int periodical_check_needed)
555 {
556   gpg_error_t err = 0;
557   card_t card = NULL;
558   app_t app = NULL;
559   unsigned char *result = NULL;
560   size_t resultlen;
561   int want_undefined;
562   int i;
563
564   /* Need to allocate a new card object  */
565   card = xtrycalloc (1, sizeof *card);
566   if (!card)
567     {
568       err = gpg_error_from_syserror ();
569       log_info ("error allocating context: %s\n", gpg_strerror (err));
570       return err;
571     }
572
573   card->slot = slot;
574   card->card_status = (unsigned int)-1;
575
576   if (npth_mutex_init (&card->lock, NULL))
577     {
578       err = gpg_error_from_syserror ();
579       log_error ("error initializing mutex: %s\n", gpg_strerror (err));
580       xfree (card);
581       return err;
582     }
583
584   err = lock_card (card, ctrl);
585   if (err)
586     {
587       xfree (card);
588       return err;
589     }
590
591   want_undefined = (name && !strcmp (name, "undefined"));
592
593   /* Try to read the GDO file first to get a default serial number.
594      We skip this if the undefined application has been requested. */
595   if (!want_undefined)
596     {
597       err = iso7816_select_file (slot, 0x3F00, 1);
598       if (gpg_err_code (err) == GPG_ERR_CARD)
599         {
600           /* Might be SW==0x7D00.  Let's test whether it is a Yubikey
601            * by selecting its manager application and then reading the
602            * config.  */
603           static char const yk_aid[] =
604             { 0xA0, 0x00, 0x00, 0x05, 0x27, 0x47, 0x11, 0x17 }; /*MGR*/
605           static char const otp_aid[] =
606             { 0xA0, 0x00, 0x00, 0x05, 0x27, 0x20, 0x01 }; /*OTP*/
607           unsigned char *buf;
608           size_t buflen;
609           const unsigned char *s0;
610           unsigned char formfactor;
611           size_t n;
612
613           if (!iso7816_select_application (slot, yk_aid, sizeof yk_aid,
614                                            0x0001)
615               && !iso7816_apdu_direct (slot, "\x00\x1d\x00\x00\x00", 5, 0,
616                                        NULL, &buf, &buflen))
617             {
618               card->cardtype = CARDTYPE_YUBIKEY;
619               if (opt.verbose)
620                 {
621                   log_info ("Yubico: config=");
622                   log_printhex (buf, buflen, "");
623                 }
624
625               /* We skip the first byte which seems to be the total
626                * length of the config data.  */
627               if (buflen > 1)
628                 {
629                   s0 = find_tlv (buf+1, buflen-1, 0x04, &n);  /* Form factor */
630                   formfactor = (s0 && n == 1)? *s0 : 0;
631
632                   s0 = find_tlv (buf+1, buflen-1, 0x02, &n);  /* Serial */
633                   if (s0 && n <= 4)
634                     {
635                       card->serialno = xtrymalloc (3 + 1 + 4);
636                       if (card->serialno)
637                         {
638                           card->serialnolen = 3 + 1 + 4;
639                           card->serialno[0] = 0xff;
640                           card->serialno[1] = 0x02;
641                           card->serialno[2] = 0x0;
642                           card->serialno[3] = formfactor;
643                           memset (card->serialno + 4, 0, 4 - n);
644                           memcpy (card->serialno + 4 + 4 - n, s0, n);
645                           err = app_munge_serialno (card);
646                         }
647                     }
648
649                   s0 = find_tlv (buf+1, buflen-1, 0x05, &n);  /* version */
650                   if (s0 && n == 3)
651                     card->cardversion = ((s0[0]<<16)|(s0[1]<<8)|s0[2]);
652                   else if (!s0)
653                     {
654                       /* No version - this is not a Yubikey 5.  We now
655                        * switch to the OTP app and take the first
656                        * three bytes of the response as version
657                        * number.  */
658                       xfree (buf);
659                       buf = NULL;
660                       if (!iso7816_select_application_ext (slot,
661                                                        otp_aid, sizeof otp_aid,
662                                                        1, &buf, &buflen)
663                           && buflen > 3)
664                         card->cardversion = ((buf[0]<<16)|(buf[1]<<8)|buf[2]);
665                     }
666                 }
667               xfree (buf);
668             }
669         }
670       else
671         {
672           unsigned char *atr;
673           size_t atrlen;
674
675           /* This is heuristics to identify different implementations.  */
676           atr = apdu_get_atr (slot, &atrlen);
677           if (atr)
678             {
679               if (atrlen == 21 && atr[2] == 0x11)
680                 card->cardtype = CARDTYPE_GNUK;
681               else if (atrlen == 21 && atr[7] == 0x75)
682                 card->cardtype = CARDTYPE_ZEITCONTROL;
683               xfree (atr);
684             }
685         }
686
687       if (!err && card->cardtype != CARDTYPE_YUBIKEY)
688         err = iso7816_select_file (slot, 0x2F02, 0);
689       if (!err && card->cardtype != CARDTYPE_YUBIKEY)
690         err = iso7816_read_binary (slot, 0, 0, &result, &resultlen);
691       if (!err && card->cardtype != CARDTYPE_YUBIKEY)
692         {
693           size_t n;
694           const unsigned char *p;
695
696           p = find_tlv_unchecked (result, resultlen, 0x5A, &n);
697           if (p)
698             resultlen -= (p-result);
699           if (p && n > resultlen && n == 0x0d && resultlen+1 == n)
700             {
701               /* The object does not fit into the buffer.  This is an
702                  invalid encoding (or the buffer is too short.  However, I
703                  have some test cards with such an invalid encoding and
704                  therefore I use this ugly workaround to return something
705                  I can further experiment with. */
706               log_info ("enabling BMI testcard workaround\n");
707               n--;
708             }
709
710           if (p && n <= resultlen)
711             {
712               /* The GDO file is pretty short, thus we simply reuse it for
713                  storing the serial number. */
714               memmove (result, p, n);
715               card->serialno = result;
716               card->serialnolen = n;
717               err = app_munge_serialno (card);
718               if (err)
719                 goto leave;
720             }
721           else
722             xfree (result);
723           result = NULL;
724         }
725     }
726
727   /* Allocate a new app object.  */
728   app = xtrycalloc (1, sizeof *app);
729   if (!app)
730     {
731       err = gpg_error_from_syserror ();
732       log_info ("error allocating app context: %s\n", gpg_strerror (err));
733       goto leave;
734     }
735   card->app = app;
736   app->card = card;
737
738   /* Figure out the application to use.  */
739   if (want_undefined)
740     {
741       /* We switch to the "undefined" application only if explicitly
742          requested.  */
743       app->apptype = APPTYPE_UNDEFINED;
744       /* Clear the error so that we don't run through the application
745        * selection chain.  */
746       err = 0;
747     }
748   else
749     {
750       /* For certain error codes, there is no need to try more.  */
751       if (gpg_err_code (err) == GPG_ERR_CARD_NOT_PRESENT
752           || gpg_err_code (err) == GPG_ERR_ENODEV)
753         goto leave;
754
755       /* Set a default error so that we run through the application
756        * selection chain.  */
757       err = gpg_error (GPG_ERR_NOT_FOUND);
758     }
759
760   /* Find the first available app if NAME is NULL or the matching
761    * NAME but only if that application is also enabled.  */
762   for (i=0; err && app_priority_list[i].name; i++)
763     {
764       if (is_app_allowed (app_priority_list[i].name)
765           && (!name || !strcmp (name, app_priority_list[i].name)))
766         err = app_priority_list[i].select_func (app);
767     }
768   if (err && name && gpg_err_code (err) != GPG_ERR_OBJ_TERM_STATE)
769     err = gpg_error (GPG_ERR_NOT_SUPPORTED);
770
771  leave:
772   if (err)
773     {
774       if (name)
775         log_info ("can't select application '%s': %s\n",
776                   name, gpg_strerror (err));
777       else
778         log_info ("no supported card application found: %s\n",
779                   gpg_strerror (err));
780       unlock_card (card);
781       xfree (app);
782       xfree (card);
783       return err;
784     }
785
786   card->periodical_check_needed = periodical_check_needed;
787   card->next = card_top;
788   card_top = card;
789
790   unlock_card (card);
791   return 0;
792 }
793
794
795 /* If called with NAME as NULL, select the best fitting application
796  * and return its card context; otherwise select the application with
797  * NAME and return its card context.  Returns an error code and stores
798  * NULL at R_CARD if no application was found or no card is present.  */
799 gpg_error_t
800 select_application (ctrl_t ctrl, const char *name,
801                     int scan, const unsigned char *serialno_bin,
802                     size_t serialno_bin_len)
803 {
804   gpg_error_t err = 0;
805   card_t card, card_prev = NULL;
806
807   card_list_w_lock ();
808
809   ctrl->card_ctx = NULL;
810
811   if (scan || !card_top)
812     {
813       struct dev_list *l;
814       int new_card = 0;
815
816       /* Scan the devices to find new device(s).  */
817       err = apdu_dev_list_start (opt.reader_port, &l);
818       if (err)
819         {
820           card_list_w_unlock ();
821           return err;
822         }
823
824       while (1)
825         {
826           int slot;
827           int periodical_check_needed_this;
828
829           slot = apdu_open_reader (l);
830           if (slot < 0)
831             break;
832
833           periodical_check_needed_this = apdu_connect (slot);
834           if (periodical_check_needed_this < 0)
835             {
836               /* We close a reader with no card.  */
837               err = gpg_error (GPG_ERR_ENODEV);
838             }
839           else
840             {
841               err = app_new_register (slot, ctrl, name,
842                                       periodical_check_needed_this);
843               new_card++;
844             }
845
846           if (err)
847             {
848               pincache_put (ctrl, slot, NULL, NULL, NULL, 0);
849               apdu_close_reader (slot);
850             }
851         }
852
853       apdu_dev_list_finish (l);
854
855       /* If new device(s), kick the scdaemon loop.  */
856       if (new_card)
857         scd_kick_the_loop ();
858     }
859
860   for (card = card_top; card; card = card->next)
861     {
862       lock_card (card, ctrl);
863       if (serialno_bin == NULL)
864         break;
865       if (is_same_serialno (card->serialno, card->serialnolen,
866                             serialno_bin, serialno_bin_len))
867         break;
868       unlock_card (card);
869       card_prev = card;
870     }
871
872   if (card)
873     {
874       err = check_application_conflict (card, name, NULL, 0);
875       if (!err)
876         ctrl->current_apptype = card->app ? card->app->apptype : APPTYPE_NONE;
877       else if (gpg_err_code (err) == GPG_ERR_FALSE)
878         {
879           apptype_t req_apptype = apptype_from_name (name);
880
881           if (!req_apptype)
882             err = gpg_error (GPG_ERR_NOT_FOUND);
883           else
884             {
885               err = select_additional_application_internal (card, req_apptype);
886               if (!err)
887                 ctrl->current_apptype = req_apptype;
888             }
889         }
890
891       if (!err)
892         {
893           card->ref_count++;
894           ctrl->card_ctx = card;
895           if (card_prev)
896             {
897               card_prev->next = card->next;
898               card->next = card_top;
899               card_top = card;
900             }
901         }
902       unlock_card (card);
903     }
904   else
905     err = gpg_error (GPG_ERR_ENODEV);
906
907   card_list_w_unlock ();
908
909   return err;
910 }
911
912
913 /* Switch the current card for the session CTRL and print a SERIALNO
914  * status line on success.  (SERIALNO, SERIALNOLEN) is the binary s/n
915  * of the card to switch to.  */
916 gpg_error_t
917 app_switch_current_card (ctrl_t ctrl,
918                          const unsigned char *serialno, size_t serialnolen)
919 {
920   gpg_error_t err;
921   card_t card, cardtmp;
922
923   card_list_r_lock ();
924
925   cardtmp = ctrl->card_ctx;
926   if (!cardtmp)
927     {
928       err = gpg_error (GPG_ERR_CARD_NOT_INITIALIZED);
929       goto leave;
930     }
931
932   if (serialno && serialnolen)
933     {
934       for (card = card_top; card; card = card->next)
935         {
936           if (is_same_serialno (card->serialno, card->serialnolen,
937                                 serialno, serialnolen))
938             break;
939         }
940       if (!card)
941         {
942           err = gpg_error (GPG_ERR_NOT_FOUND);
943           goto leave;
944         }
945
946       /* Note: We do not lock CARD and CARDTMP here because we only
947        * swap the context of the current session and there is no
948        * chance of a context switch.  This also works if the card
949        * stays the same.  */
950       ctrl->card_ctx = card;
951       card->ref_count++;
952       card_unref_locked (cardtmp);
953     }
954
955   /* Print the status line.  */
956   err = send_serialno_and_app_status (ctrl->card_ctx, 0, ctrl);
957
958  leave:
959   card_list_r_unlock ();
960   return err;
961 }
962
963
964 static gpg_error_t
965 select_additional_application_internal (card_t card, apptype_t req_apptype)
966 {
967   gpg_error_t err = 0;
968   app_t app;
969   int i;
970
971   /* Check that the requested app has not yet been put onto the list.  */
972   for (app = card->app; app; app = app->next)
973     if (app->apptype == req_apptype)
974       {
975         /* We already got this one.  Note that in this case we don't
976          * make it the current one but it doesn't matter because
977          * maybe_switch_app will do that anyway.  */
978         err = 0;
979         app = NULL;
980         goto leave;
981       }
982
983   /* Allocate a new app object.  */
984   app = xtrycalloc (1, sizeof *app);
985   if (!app)
986     {
987       err = gpg_error_from_syserror ();
988       log_info ("error allocating app context: %s\n", gpg_strerror (err));
989       goto leave;
990     }
991   app->card = card;
992
993   /* Find the app and run the select.  */
994   for (i=0; app_priority_list[i].apptype; i++)
995     {
996       if (app_priority_list[i].apptype == req_apptype
997           && is_app_allowed (app_priority_list[i].name))
998         {
999           err = app_priority_list[i].select_func (app);
1000           break;
1001         }
1002     }
1003   if (!app_priority_list[i].apptype
1004       || (err && gpg_err_code (err) != GPG_ERR_OBJ_TERM_STATE))
1005     err = gpg_error (GPG_ERR_NOT_SUPPORTED);
1006
1007   if (err)
1008     goto leave;
1009
1010   /* Add this app.  We make it the current one to avoid an extra
1011    * reselect by maybe_switch_app after the select we just did.  */
1012   app->next = card->app;
1013   card->app = app;
1014   log_info ("added app '%s' to the card context and switched\n",
1015             strapptype (app->apptype));
1016
1017  leave:
1018   if (err)
1019     xfree (app);
1020   return err;
1021 }
1022
1023
1024 /* Add all possible additional applications to the card context but do
1025  * not change the current one.  This currently works only for Yubikeys. */
1026 static gpg_error_t
1027 select_all_additional_applications_internal (ctrl_t ctrl, card_t card)
1028 {
1029   gpg_error_t err = 0;
1030   apptype_t candidates[3];
1031   int i, j;
1032   int any_new = 0;
1033
1034   if (card->cardtype == CARDTYPE_YUBIKEY)
1035     {
1036       candidates[0] = APPTYPE_OPENPGP;
1037       candidates[1] = APPTYPE_PIV;
1038       candidates[2] = APPTYPE_NONE;
1039     }
1040   else
1041     {
1042       candidates[0] = APPTYPE_NONE;
1043     }
1044
1045   /* Find the app and run the select.  */
1046   for (i=0; app_priority_list[i].apptype; i++)
1047     {
1048       app_t app, app_r, app_prev;
1049
1050       for (j=0; candidates[j]; j++)
1051         if (candidates[j] == app_priority_list[i].apptype
1052             && is_app_allowed (app_priority_list[i].name))
1053           break;
1054       if (!candidates[j])
1055         continue;
1056
1057       for (app = card->app; app; app = app->next)
1058         if (app->apptype == candidates[j])
1059           break;
1060       if (app)
1061         continue; /* Already on the list of apps.  */
1062
1063       app = xtrycalloc (1, sizeof *app);
1064       if (!app)
1065         {
1066           err = gpg_error_from_syserror ();
1067           log_info ("error allocating app context: %s\n", gpg_strerror (err));
1068           goto leave;
1069         }
1070       app->card = card;
1071       err = app_priority_list[i].select_func (app);
1072       if (err)
1073         {
1074           log_error ("error selecting additional app '%s': %s - skipped\n",
1075                      strapptype (candidates[j]), gpg_strerror (err));
1076           err = 0;
1077           xfree (app);
1078         }
1079       else
1080         {
1081           /* Append to the list of apps.  */
1082           app_prev = card->app;
1083           for (app_r=app_prev->next; app_r; app_prev=app_r, app_r=app_r->next)
1084             ;
1085           app_prev->next = app;
1086           log_info ("added app '%s' to the card context\n",
1087                     strapptype (app->apptype));
1088           any_new = 1;
1089         }
1090     }
1091
1092   /* If we found a new application we need to reselect the original
1093    * application so that we are in a well defined state.  */
1094   if (!err && any_new && card->app && card->app->fnc.reselect)
1095     err = run_reselect (ctrl, card, card->app, NULL);
1096
1097  leave:
1098   return err;
1099 }
1100
1101
1102 /* This function needs to be called with the NAME of the new
1103  * application to be selected on CARD.  On success the application is
1104  * added to the list of the card's active applications as currently
1105  * active application.  On error no new application is allocated.
1106  * Selecting an already selected application has no effect. */
1107 gpg_error_t
1108 select_additional_application (card_t card, ctrl_t ctrl, const char *name)
1109 {
1110   gpg_error_t err = 0;
1111   apptype_t req_apptype;
1112
1113   if (!name)
1114     req_apptype = 0;
1115   else
1116     {
1117       req_apptype = apptype_from_name (name);
1118       if (!req_apptype)
1119         return gpg_error (GPG_ERR_NOT_FOUND);
1120     }
1121
1122   if (req_apptype)
1123     {
1124       err = select_additional_application_internal (card, req_apptype);
1125       if (!err)
1126         {
1127           ctrl->current_apptype = req_apptype;
1128           if (DBG_APP)
1129             log_debug ("current_apptype is set to %s\n", name);
1130         }
1131     }
1132   else
1133     {
1134       err = select_all_additional_applications_internal (ctrl, card);
1135     }
1136
1137   return err;
1138 }
1139
1140
1141 char *
1142 get_supported_applications (void)
1143 {
1144   int idx;
1145   size_t nbytes;
1146   char *buffer, *p;
1147   const char *s;
1148
1149   for (nbytes=1, idx=0; (s=app_priority_list[idx].name); idx++)
1150     nbytes += strlen (s) + 1 + 1;
1151
1152   buffer = xtrymalloc (nbytes);
1153   if (!buffer)
1154     return NULL;
1155
1156   for (p=buffer, idx=0; (s=app_priority_list[idx].name); idx++)
1157     if (is_app_allowed (s))
1158       p = stpcpy (stpcpy (p, s), ":\n");
1159   *p = 0;
1160
1161   return buffer;
1162 }
1163
1164
1165 /* Deallocate the application.  */
1166 static void
1167 deallocate_card (card_t card)
1168 {
1169   card_t c, c_prev = NULL;
1170   app_t a, anext;
1171
1172   for (c = card_top; c; c = c->next)
1173     if (c == card)
1174       {
1175         if (c_prev == NULL)
1176           card_top = c->next;
1177         else
1178           c_prev->next = c->next;
1179         break;
1180       }
1181     else
1182       c_prev = c;
1183
1184   if (card->ref_count)
1185     log_error ("releasing still used card context (%d)\n", card->ref_count);
1186
1187   for (a = card->app; a; a = anext)
1188     {
1189       if (a->fnc.deinit)
1190         {
1191           a->fnc.deinit (a);
1192           a->fnc.deinit = NULL;
1193         }
1194       anext = a->next;
1195       xfree (a);
1196     }
1197
1198   xfree (card->serialno);
1199   unlock_card (card);
1200   xfree (card);
1201 }
1202
1203
1204 static card_t
1205 do_with_keygrip (ctrl_t ctrl, int action, const char *keygrip_str,
1206                  int capability)
1207 {
1208   int locked = 0;
1209   card_t c;
1210   app_t a, a_prev;
1211
1212   for (c = card_top; c; c = c->next)
1213     {
1214       if (lock_card (c, ctrl))
1215         {
1216           c = NULL;
1217           goto leave_the_loop;
1218         }
1219       locked = 1;
1220       a_prev = NULL;
1221       for (a = c->app; a; a = a->next)
1222         {
1223           if (!a->fnc.with_keygrip || a->need_reset)
1224             continue;
1225
1226           /* Note that we need to do a re-select even for the current
1227            * app because the last selected application (e.g. after
1228            * init) might be a different one and we do not run
1229            * maybe_switch_app here.  Of course we we do this only iff
1230            * we have an additional app. */
1231           if (c->app->next)
1232             {
1233               if (run_reselect (ctrl, c, a, a_prev))
1234                 continue;
1235             }
1236           a_prev = a;
1237
1238           if (DBG_APP)
1239             log_debug ("slot %d, app %s: calling with_keygrip(%s)\n",
1240                        c->slot, xstrapptype (a),
1241                        action == KEYGRIP_ACTION_SEND_DATA? "send_data":
1242                        action == KEYGRIP_ACTION_WRITE_STATUS? "status":
1243                        action == KEYGRIP_ACTION_LOOKUP? "lookup":"?");
1244           if (!a->fnc.with_keygrip (a, ctrl, action, keygrip_str, capability))
1245             goto leave_the_loop; /* ACTION_LOOKUP succeeded.  */
1246         }
1247
1248       /* Select the first app again.  */
1249       if (c->app->next)
1250         run_reselect (ctrl, c, c->app, a_prev);
1251
1252       unlock_card (c);
1253       locked = 0;
1254     }
1255
1256  leave_the_loop:
1257   /* Force switching of the app if the selected one is not the current
1258    * one.  Changing the current apptype is sufficient to do this.  */
1259   if (c && c->app && c->app->apptype != a->apptype)
1260     ctrl->current_apptype = a->apptype;
1261
1262   if (locked && c)
1263     {
1264       unlock_card (c);
1265       locked = 0;
1266     }
1267   return c;
1268 }
1269
1270
1271 /* Locking access to the card-list and CARD, returns CARD.  */
1272 card_t
1273 card_get (ctrl_t ctrl, const char *keygrip)
1274 {
1275   card_t card;
1276
1277   card_list_r_lock ();
1278   if (keygrip)
1279     card = do_with_keygrip (ctrl, KEYGRIP_ACTION_LOOKUP, keygrip, 0);
1280   else
1281     card = ctrl->card_ctx;
1282   if (!card)
1283     {
1284       card_list_r_unlock ();
1285       return NULL;
1286     }
1287
1288   lock_card (card, NULL);
1289   return card;
1290 }
1291
1292 /* Release the lock of CARD and the card-list.  */
1293 void
1294 card_put (card_t card)
1295 {
1296   /* We don't deallocate CARD here.  Instead, we keep it.  This is
1297      useful so that a card does not get reset even if only one session
1298      is using the card - this way the PIN cache and other cached data
1299      are preserved.  */
1300   unlock_card (card);
1301   card_list_r_unlock ();
1302 }
1303
1304
1305 /* This is the same as card_unref but assumes that CARD is already
1306  * locked.  */
1307 void
1308 card_unref_locked (card_t card)
1309 {
1310   if (!card)
1311     return;
1312
1313   if (!card->ref_count)
1314     log_bug ("tried to release an already released card context\n");
1315
1316   --card->ref_count;
1317 }
1318
1319
1320
1321 /* The serial number may need some cosmetics.  Do it here.  This
1322    function shall only be called once after a new serial number has
1323    been put into APP->serialno.
1324
1325    Prefixes we use:
1326
1327      FF 00 00 = For serial numbers starting with an FF
1328      FF 01 00 = Some german p15 cards return an empty serial number so the
1329                 serial number from the EF(TokenInfo) is used instead.
1330      FF 02 00 = Serial number from Yubikey config.
1331                 This is normally not seen because we modify this here
1332                 to an OpenPGP Card s/n.
1333      FF 7F 00 = No serialno.
1334
1335      All other serial numbers not starting with FF are used as they are.
1336 */
1337 gpg_error_t
1338 app_munge_serialno (card_t card)
1339 {
1340   if (card->cardtype == CARDTYPE_YUBIKEY
1341       && card->serialnolen == 3 + 1 + 4
1342       && !memcmp (card->serialno, "\xff\x02\x00", 3))
1343     {
1344       /* An example for a serial number is
1345        *   FF020001008A77C1
1346        *   ~~~~~~--~~~~~~~~
1347        *   !     ! !--------- 4 byte s/n
1348        *   !     !----------- Form factor
1349        *   !----------------- Our prefix
1350        * Yubico seems to use the decimalized version of their S/N
1351        * as the OpenPGP card S/N.  Thus in theory we can contruct the
1352        * number from this information so that we do not rely on having
1353        * the OpenPGP app enabled.
1354        */
1355       unsigned long sn;
1356       sn  = card->serialno[4] * 16777216;
1357       sn += card->serialno[5] * 65536;
1358       sn += card->serialno[6] * 256;
1359       sn += card->serialno[7];
1360       if (sn <= 99999999ul)
1361         {
1362           char *buf = xtrymalloc (16);
1363           if (!buf)
1364             return gpg_error_from_syserror ();
1365           memcpy (buf, "\xD2\x76\x00\x01\x24\x01", 6);
1366           buf[6] = 0; /* Application version which we don't know  */
1367           buf[7] = 0; /* thus we use 0.0 and don't use this directly.  */
1368           buf[8] = 0; /* Manufacturer: Yubico (0x0006).  */
1369           buf[9] = 6;
1370           buf[13] = (sn % 10);
1371           sn /= 10;
1372           buf[13] |= (sn % 10) << 4;
1373           sn /= 10;
1374           buf[12] = (sn % 10);
1375           sn /= 10;
1376           buf[12] |= (sn % 10) << 4;
1377           sn /= 10;
1378           buf[11] = (sn % 10);
1379           sn /= 10;
1380           buf[11] |= (sn % 10) << 4;
1381           sn /= 10;
1382           buf[10] = (sn % 10);
1383           sn /= 10;
1384           buf[10] |= (sn % 10) << 4;
1385           sn /= 10;
1386           buf[14] = 0; /* Last two bytes are RFU.  */
1387           buf[15] = 0;
1388           xfree (card->serialno);
1389           card->serialno = buf;
1390           card->serialnolen = 16;
1391         }
1392     }
1393   else if (card->serialnolen && card->serialno[0] == 0xff)
1394     {
1395       /* The serial number starts with our special prefix.  This
1396          requires that we put our default prefix "FF0000" in front. */
1397       unsigned char *p = xtrymalloc (card->serialnolen + 3);
1398       if (!p)
1399         return gpg_error_from_syserror ();
1400       memcpy (p, "\xff\0", 3);
1401       memcpy (p+3, card->serialno, card->serialnolen);
1402       card->serialnolen += 3;
1403       xfree (card->serialno);
1404       card->serialno = p;
1405     }
1406   else if (!card->serialnolen)
1407     {
1408       unsigned char *p = xtrymalloc (3);
1409       if (!p)
1410         return gpg_error_from_syserror ();
1411       memcpy (p, "\xff\x7f", 3);
1412       card->serialnolen = 3;
1413       xfree (card->serialno);
1414       card->serialno = p;
1415     }
1416   return 0;
1417 }
1418
1419
1420
1421 /* Retrieve the serial number of the card.  The serial number is
1422    returned as a malloced string (hex encoded) in SERIAL.  Caller must
1423    free SERIAL unless the function returns an error.  */
1424 char *
1425 card_get_serialno (card_t card)
1426 {
1427   char *serial;
1428
1429   if (!card)
1430     return NULL;
1431
1432   if (!card->serialnolen)
1433     serial = xtrystrdup ("FF7F00");
1434   else
1435     serial = bin2hex (card->serialno, card->serialnolen, NULL);
1436
1437   return serial;
1438 }
1439
1440 /* Same as card_get_serialno but takes an APP object.  */
1441 char *
1442 app_get_serialno (app_t app)
1443 {
1444   if (!app || !app->card)
1445     {
1446       gpg_err_set_errno (0);
1447       return NULL;
1448     }
1449   return card_get_serialno (app->card);
1450 }
1451
1452
1453 /* Return an allocated string with the serial number in a format to be
1454  * show to the user.  With NOFALLBACK set to true return NULL if such an
1455  * abbreviated S/N is not available, else return the full serial
1456  * number as a hex string.  May return NULL on malloc problem.  */
1457 char *
1458 card_get_dispserialno (card_t card, int nofallback)
1459 {
1460   char *result, *p;
1461   unsigned long sn;
1462
1463   if (card && card->serialno && card->serialnolen == 3+1+4
1464       && !memcmp (card->serialno, "\xff\x02\x00", 3))
1465     {
1466       /* This is a 4 byte S/N of a Yubikey which seems to be printed
1467        * on the token in decimal.  Maybe they will print larger S/N
1468        * also in decimal but we can't be sure, thus do it only for
1469        * these 32 bit numbers.  */
1470       sn  = card->serialno[4] * 16777216;
1471       sn += card->serialno[5] * 65536;
1472       sn += card->serialno[6] * 256;
1473       sn += card->serialno[7];
1474       if ((card->cardversion >> 16) >= 5)
1475         result = xtryasprintf ("%lu %03lu %03lu",
1476                                (sn/1000000ul),
1477                                (sn/1000ul % 1000ul),
1478                                (sn % 1000ul));
1479       else
1480         result = xtryasprintf ("%lu", sn);
1481     }
1482   else if (card && card->cardtype == CARDTYPE_YUBIKEY)
1483     {
1484       /* Get back the printed Yubikey number from the OpenPGP AID
1485        * Example: D2760001240100000006120808620000
1486        */
1487       result = card_get_serialno (card);
1488       if (result && strlen (result) >= 28 && !strncmp (result+16, "0006", 4))
1489         {
1490           sn  = atoi_4 (result+20) * 10000;
1491           sn += atoi_4 (result+24);
1492           if ((card->cardversion >> 16) >= 5)
1493             p = xtryasprintf ("%lu %03lu %03lu",
1494                               (sn/1000000ul),
1495                               (sn/1000ul % 1000ul),
1496                               (sn % 1000ul));
1497           else
1498             p = xtryasprintf ("%lu", sn);
1499           if (p)
1500             {
1501               xfree (result);
1502               result = p;
1503             }
1504         }
1505       else if (nofallback)
1506         {
1507           xfree (result);
1508           result = NULL;
1509         }
1510     }
1511   else if (card && card->app && card->app->apptype == APPTYPE_OPENPGP)
1512     {
1513       /* Extract number from standard OpenPGP AID.  */
1514       result = card_get_serialno (card);
1515       if (result && strlen (result) > 16+12)
1516         {
1517           memcpy (result, result+16, 4);
1518           result[4] = ' ';
1519           memcpy (result+5, result+20, 8);
1520           result[13] = 0;
1521         }
1522       else if (nofallback)
1523         {
1524           xfree (result);
1525           result = NULL;
1526         }
1527     }
1528   else if (nofallback)
1529     result = NULL;  /* No Abbreviated S/N.  */
1530   else
1531     result = card_get_serialno (card);
1532
1533   return result;
1534 }
1535
1536 /* Same as card_get_dispserialno but takes an APP object.  */
1537 char *
1538 app_get_dispserialno (app_t app, int nofallback)
1539 {
1540   if (!app || !app->card)
1541     {
1542       gpg_err_set_errno (0);
1543       return NULL;
1544     }
1545   return card_get_dispserialno (app->card, nofallback);
1546 }
1547
1548
1549 /* Helper to run the reselect function.  */
1550 static gpg_error_t
1551 run_reselect (ctrl_t ctrl, card_t c, app_t a, app_t a_prev)
1552 {
1553   gpg_error_t err;
1554
1555   if (!a->fnc.reselect)
1556     {
1557       log_info ("slot %d, app %s: re-select not implemented\n",
1558                 c->slot, xstrapptype (a));
1559       return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED);
1560     }
1561
1562   /* Give the current app a chance to save some state before another
1563    * app is selected.  We ignore errors here because that state saving
1564    * (e.g. putting PINs into a cache) is a convenience feature and not
1565    * required to always work. */
1566   if (a_prev && a_prev->fnc.prep_reselect)
1567     {
1568       if (a_prev->need_reset)
1569         err = gpg_error (GPG_ERR_CARD_RESET);
1570       else
1571         err = a_prev->fnc.prep_reselect (a_prev, ctrl);
1572       if (err)
1573         log_error ("slot %d, app %s: preparing re-select from %s failed: %s\n",
1574                    c->slot, xstrapptype (a),
1575                    xstrapptype (a_prev), gpg_strerror (err));
1576     }
1577
1578   if (a->need_reset)
1579     err = gpg_error (GPG_ERR_CARD_RESET);
1580   else
1581     err = a->fnc.reselect (a, ctrl);
1582   if (err)
1583     {
1584       log_error ("slot %d, app %s: error re-selecting: %s\n",
1585                      c->slot, xstrapptype (a), gpg_strerror (err));
1586       return err;
1587     }
1588   if (DBG_APP)
1589     log_debug ("slot %d, app %s: re-selected\n", c->slot, xstrapptype (a));
1590
1591   return 0;
1592 }
1593
1594
1595 /*
1596  * Check external interference before each use of the application on
1597  * card.  Returns -1 when detecting some external interference.
1598  * Returns 0 if not.
1599  *
1600  * Note: This kind of detection can't be perfect.  At most, it may be
1601  * possibly useful kludge, in some limited situations.
1602  */
1603 static int
1604 check_external_interference (app_t app, ctrl_t ctrl)
1605 {
1606   /*
1607    * Only when a user is using Yubikey with pcsc-shared configuration,
1608    * we need this detection.  Otherwise, the card/token is under full
1609    * control of scdaemon, there's no problem at all.
1610    */
1611   if (!opt.pcsc_shared || app->card->cardtype != CARDTYPE_YUBIKEY)
1612     return 0;
1613
1614   if (app->fnc.check_aid)
1615     {
1616       unsigned char *aid;
1617       size_t aidlen;
1618       gpg_error_t err;
1619       int slot = app_get_slot (app);
1620
1621       err = iso7816_get_data (slot, 0, 0x004F, &aid, &aidlen);
1622       if (err)
1623         return -1;
1624
1625       err = app->fnc.check_aid (app, ctrl, aid, aidlen);
1626       xfree (aid);
1627       if (err)
1628         return -1;
1629     }
1630
1631   return 0;
1632 }
1633
1634
1635 /* Check that the card has been initialized and whether we need to
1636  * switch to another application on the same card.  Switching means
1637  * that the new active app will be moved to the head of the list at
1638  * CARD->app.  This function must be called with the card lock held. */
1639 static gpg_error_t
1640 maybe_switch_app (ctrl_t ctrl, card_t card, const char *keyref)
1641 {
1642   gpg_error_t err;
1643   app_t app;
1644   app_t app_prev = NULL;
1645   apptype_t apptype;
1646
1647   if (!card->app)
1648     return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED);
1649   if (!ctrl->current_apptype)
1650     {
1651       /* For whatever reasons the current apptype has not been set -
1652        * fix that and use the current app.  */
1653       if (DBG_APP)
1654         log_debug ("slot %d: no current app switching to %s\n",
1655                    card->slot, strapptype (card->app->apptype));
1656       ctrl->current_apptype = card->app->apptype;
1657       return 0;
1658     }
1659   for (app = card->app; app; app = app->next)
1660     if (app->apptype == ctrl->current_apptype)
1661       break;
1662   if (!app)
1663     {
1664       /* The current app is not supported by this card.  Set the first
1665        * app of the card as current.  */
1666       if (DBG_APP)
1667         log_debug ("slot %d: current app %s not available switching to %s\n",
1668                    card->slot, strapptype (ctrl->current_apptype),
1669                    strapptype (card->app->apptype));
1670       ctrl->current_apptype = card->app->apptype;
1671       return 0;
1672     }
1673   if (DBG_APP)
1674     log_debug ("slot %d: have=%s want=%s keyref=%s\n",
1675                card->slot, strapptype (card->app->apptype),
1676                strapptype (ctrl->current_apptype),
1677                keyref? keyref:"[none]");
1678
1679   app = NULL;
1680   if (keyref)
1681     {
1682       /* Switch based on the requested KEYREF.  */
1683       apptype = apptype_from_keyref (keyref);
1684       if (apptype)
1685         {
1686           for (app = card->app; app; app_prev = app, app = app->next)
1687             if (app->apptype == apptype)
1688               break;
1689           if (!app_prev && ctrl->current_apptype == card->app->apptype)
1690             if (check_external_interference (app, ctrl) == 0)
1691               return 0;  /* Already the first app - no need to switch.  */
1692         }
1693       else if (strlen (keyref) == 40)
1694         {
1695           /* This looks like a keygrip.  Iterate over all apps to find
1696            * the corresponding app.  */
1697           for (app = card->app; app; app_prev = app, app = app->next)
1698             if (app->fnc.with_keygrip
1699                 && !app->need_reset
1700                 && !app->fnc.with_keygrip (app, ctrl,
1701                                            KEYGRIP_ACTION_LOOKUP, keyref, 0))
1702               break;
1703           if (!app_prev && ctrl->current_apptype == card->app->apptype)
1704             if (check_external_interference (app, ctrl) == 0)
1705               return 0;   /* Already the first app - no need to switch.  */
1706         }
1707     }
1708
1709   if (!app)
1710     {
1711       /* Switch based on the current application of this connection or
1712        * if a keyref based switch didn't worked.  */
1713       if (ctrl->current_apptype == card->app->apptype)
1714         return 0; /* No need to switch.  */
1715       app_prev = card->app;
1716       for (app = app_prev->next; app; app_prev = app, app = app->next)
1717         if (app->apptype == ctrl->current_apptype)
1718           break;
1719     }
1720   if (!app)
1721     return gpg_error (GPG_ERR_WRONG_CARD);
1722
1723   err = run_reselect (ctrl, card, app, app_prev);
1724   if (err)
1725     return err;
1726
1727   /* Swap APP with the head of the app list if needed.  Note that APP
1728    * is not the head of the list. */
1729   if (app_prev)
1730     {
1731       app_prev->next = app->next;
1732       app->next = card->app;
1733       card->app = app;
1734     }
1735
1736   if (opt.verbose)
1737     log_info ("slot %d, app %s: %s\n",
1738               card->slot, xstrapptype (app),
1739               app_prev? "switched":"re-selected");
1740
1741   ctrl->current_apptype = app->apptype;
1742
1743   return 0;
1744 }
1745
1746
1747 /* Helper for app_write_learn_status.  */
1748 static gpg_error_t
1749 write_learn_status_core (card_t card, app_t app, ctrl_t ctrl,
1750                          unsigned int flags)
1751 {
1752   gpg_error_t err;
1753
1754   /* We do not send CARD and APPTYPE if only keypairinfo is requested.  */
1755   if (!(flags & APP_LEARN_FLAG_KEYPAIRINFO))
1756     {
1757       if (card && card->cardtype)
1758         send_status_direct (ctrl, "CARDTYPE", strcardtype (card->cardtype));
1759       if (card && card->cardversion)
1760         send_status_printf (ctrl, "CARDVERSION", "%X", card->cardversion);
1761       if (app->apptype)
1762         send_status_direct (ctrl, "APPTYPE", strapptype (app->apptype));
1763       if (app->appversion)
1764         send_status_printf (ctrl, "APPVERSION", "%X", app->appversion);
1765     }
1766
1767   if (app->need_reset)
1768     err = gpg_error (GPG_ERR_CARD_RESET);
1769   else
1770     {
1771       err = app->fnc.learn_status (app, ctrl, flags);
1772       if (err && (flags & APP_LEARN_FLAG_REREAD))
1773         app->need_reset = 1;
1774     }
1775   return err;
1776 }
1777
1778
1779 /* Write out the application specific status lines for the LEARN
1780    command. */
1781 gpg_error_t
1782 app_write_learn_status (card_t card, ctrl_t ctrl, unsigned int flags)
1783 {
1784   gpg_error_t err, err2, tmperr;
1785   app_t app, last_app;
1786   int any_reselect = 0;
1787
1788   /* Always make sure that the current app for this connection has
1789    * been selected and is at the top of the list.  */
1790   if ((err = maybe_switch_app (ctrl, card, NULL)))
1791     ;
1792   else if (!card->app->fnc.learn_status)
1793     err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
1794   else
1795     {
1796       err = write_learn_status_core (card, card->app, ctrl, flags);
1797       if (!err && card->app->fnc.reselect && (flags & APP_LEARN_FLAG_MULTI))
1798         {
1799           /* The current app has the reselect feature so that we can
1800            * loop over all other apps which are capable of a reselect
1801            * and finally reselect the first app again.  Note that we
1802            * did the learn for the currently selected card above.  */
1803           app = last_app = card->app;
1804           for (app = app->next; app && !err; app = app->next)
1805             if (app->fnc.reselect)
1806               {
1807                 if (last_app && last_app->fnc.prep_reselect)
1808                   {
1809                     tmperr = last_app->fnc.prep_reselect (last_app, ctrl);
1810                     if (tmperr)
1811                       log_info ("slot %d, app %s:"
1812                                 " preparing re-select from %s failed: %s\n",
1813                                 card->slot, xstrapptype (app),
1814                                 xstrapptype (last_app),
1815                                 gpg_strerror (tmperr));
1816                   }
1817                 any_reselect = 1;
1818                 err = app->fnc.reselect (app, ctrl);
1819                 if (!err)
1820                   {
1821                     last_app = app;
1822                     err = write_learn_status_core (NULL, app, ctrl, flags);
1823                   }
1824               }
1825           app = card->app;
1826           if (any_reselect)
1827             {
1828               if (last_app && last_app->fnc.prep_reselect)
1829                 {
1830                   tmperr = last_app->fnc.prep_reselect (last_app, ctrl);
1831                   if (tmperr)
1832                     log_info ("slot %d, app %s:"
1833                               " preparing re-select from %s failed: %s\n",
1834                               card->slot, xstrapptype (app),
1835                               xstrapptype (last_app), gpg_strerror (tmperr));
1836                 }
1837               err2 = app->fnc.reselect (app, ctrl);
1838               if (err2)
1839                 {
1840                   log_error ("error re-selecting '%s': %s\n",
1841                              strapptype(app->apptype), gpg_strerror (err2));
1842                   if (!err)
1843                     err = err2;
1844                 }
1845             }
1846         }
1847     }
1848
1849   return err;
1850 }
1851
1852
1853 /* Read the certificate with id CERTID (as returned by learn_status in
1854    the CERTINFO status lines) and return it in the freshly allocated
1855    buffer put into CERT and the length of the certificate put into
1856    CERTLEN. */
1857 gpg_error_t
1858 app_readcert (card_t card, ctrl_t ctrl, const char *certid,
1859               unsigned char **cert, size_t *certlen)
1860 {
1861   gpg_error_t err;
1862
1863   if ((err = maybe_switch_app (ctrl, card, certid)))
1864     ;
1865   else if (!card->app->fnc.readcert)
1866     err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
1867   else
1868     {
1869       if (DBG_APP)
1870         log_debug ("slot %d app %s: calling readcert(%s)\n",
1871                    card->slot, xstrapptype (card->app), certid);
1872       if (card->app->need_reset)
1873         err = gpg_error (GPG_ERR_CARD_RESET);
1874       else
1875         err = card->app->fnc.readcert (card->app, certid, cert, certlen);
1876     }
1877
1878   return err;
1879 }
1880
1881
1882 /* Read the key with ID KEYID.  On success a canonical encoded
1883  * S-expression with the public key will get stored at PK and its
1884  * length (for assertions) at PKLEN; the caller must release that
1885  * buffer. On error NULL will be stored at PK and PKLEN and an error
1886  * code returned.  If the key is not required NULL may be passed for
1887  * PK; this makes sense if the APP_READKEY_FLAG_INFO has also been set.
1888  *
1889  * This function might not be supported by all applications.  */
1890 gpg_error_t
1891 app_readkey (card_t card, ctrl_t ctrl, const char *keyid, unsigned int flags,
1892              unsigned char **pk, size_t *pklen)
1893 {
1894   gpg_error_t err;
1895
1896   if (pk)
1897     *pk = NULL;
1898   if (pklen)
1899     *pklen = 0;
1900
1901   if (!keyid)
1902     return gpg_error (GPG_ERR_INV_VALUE);
1903
1904   if ((err = maybe_switch_app (ctrl, card, keyid)))
1905     ;
1906   else if (!card->app->fnc.readkey)
1907     err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
1908   else
1909     {
1910       if (DBG_APP)
1911         log_debug ("slot %d app %s: calling readkey(%s)\n",
1912                    card->slot, xstrapptype (card->app), keyid);
1913       if (card->app->need_reset)
1914         err = gpg_error (GPG_ERR_CARD_RESET);
1915       else
1916         err = card->app->fnc.readkey (card->app, ctrl, keyid, flags, pk, pklen);
1917     }
1918
1919   return err;
1920 }
1921
1922
1923 /* Perform a GETATTR operation.  */
1924 gpg_error_t
1925 app_getattr (card_t card, ctrl_t ctrl, const char *name)
1926 {
1927   gpg_error_t err;
1928
1929   if (!name || !*name)
1930     return gpg_error (GPG_ERR_INV_VALUE);
1931
1932   if ((err = maybe_switch_app (ctrl, card, NULL)))
1933     ;
1934   else if (name && !strcmp (name, "CARDTYPE"))
1935     {
1936       send_status_direct (ctrl, "CARDTYPE", strcardtype (card->cardtype));
1937     }
1938   else if (name && !strcmp (name, "APPTYPE"))
1939     {
1940       send_status_direct (ctrl, "APPTYPE", strapptype (card->app->apptype));
1941     }
1942   else if (name && !strcmp (name, "SERIALNO"))
1943     {
1944       char *serial;
1945
1946       serial = app_get_serialno (card->app);
1947       if (!serial)
1948         err = gpg_error (GPG_ERR_INV_VALUE);
1949       else
1950         {
1951           send_status_direct (ctrl, "SERIALNO", serial);
1952           xfree (serial);
1953         }
1954     }
1955   else if (!card->app->fnc.getattr)
1956     err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
1957   else
1958     {
1959       if (DBG_APP)
1960         log_debug ("slot %d app %s: calling getattr(%s)\n",
1961                    card->slot, xstrapptype (card->app), name);
1962       if (card->app->need_reset)
1963         err = gpg_error (GPG_ERR_CARD_RESET);
1964       else
1965         err = card->app->fnc.getattr (card->app, ctrl, name);
1966     }
1967
1968   return err;
1969 }
1970
1971
1972 /* Perform a SETATTR operation.  */
1973 gpg_error_t
1974 app_setattr (card_t card, ctrl_t ctrl, const char *name,
1975              gpg_error_t (*pincb)(void*, const char *, char **),
1976              void *pincb_arg,
1977              const unsigned char *value, size_t valuelen)
1978 {
1979   gpg_error_t err;
1980
1981   if (!name || !*name || !value)
1982     return gpg_error (GPG_ERR_INV_VALUE);
1983
1984   if ((err = maybe_switch_app (ctrl, card, NULL)))
1985     ;
1986   else if (!card->app->fnc.setattr)
1987     err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
1988   else
1989     {
1990       if (DBG_APP)
1991         log_debug ("slot %d app %s: calling setattr(%s)\n",
1992                    card->slot, xstrapptype (card->app), name);
1993       if (card->app->need_reset)
1994         err = gpg_error (GPG_ERR_CARD_RESET);
1995       else
1996         err = card->app->fnc.setattr (card->app, ctrl, name, pincb, pincb_arg,
1997                                       value, valuelen);
1998     }
1999
2000   return err;
2001 }
2002
2003
2004 /* Create the signature and return the allocated result in OUTDATA.
2005    If a PIN is required the PINCB will be used to ask for the PIN; it
2006    should return the PIN in an allocated buffer and put it into PIN.  */
2007 gpg_error_t
2008 app_sign (card_t card, ctrl_t ctrl, const char *keyidstr, int hashalgo,
2009           gpg_error_t (*pincb)(void*, const char *, char **),
2010           void *pincb_arg,
2011           const void *indata, size_t indatalen,
2012           unsigned char **outdata, size_t *outdatalen )
2013 {
2014   gpg_error_t err;
2015
2016   if (!indata || !indatalen || !outdata || !outdatalen || !pincb)
2017     return gpg_error (GPG_ERR_INV_VALUE);
2018
2019   if ((err = maybe_switch_app (ctrl, card, keyidstr)))
2020     ;
2021   else if (!card->app->fnc.sign)
2022     err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
2023   else
2024     {
2025       if (DBG_APP)
2026         log_debug ("slot %d app %s: calling sign(%s)\n",
2027                    card->slot, xstrapptype (card->app), keyidstr);
2028       if (card->app->need_reset)
2029         err = gpg_error (GPG_ERR_CARD_RESET);
2030       else
2031         err = card->app->fnc.sign (card->app, ctrl, keyidstr, hashalgo,
2032                                    pincb, pincb_arg,
2033                                    indata, indatalen,
2034                                    outdata, outdatalen);
2035     }
2036
2037   if (opt.verbose)
2038     log_info ("operation sign result: %s\n", gpg_strerror (err));
2039   return err;
2040 }
2041
2042
2043 /* Create the signature using the INTERNAL AUTHENTICATE command and
2044    return the allocated result in OUTDATA.  If a PIN is required the
2045    PINCB will be used to ask for the PIN; it should return the PIN in
2046    an allocated buffer and put it into PIN.  */
2047 gpg_error_t
2048 app_auth (card_t card, ctrl_t ctrl, const char *keyidstr,
2049           gpg_error_t (*pincb)(void*, const char *, char **),
2050           void *pincb_arg,
2051           const void *indata, size_t indatalen,
2052           unsigned char **outdata, size_t *outdatalen )
2053 {
2054   gpg_error_t err;
2055
2056   if (!indata || !indatalen || !outdata || !outdatalen || !pincb)
2057     return gpg_error (GPG_ERR_INV_VALUE);
2058
2059   if ((err = maybe_switch_app (ctrl, card, keyidstr)))
2060     ;
2061   else if (!card->app->fnc.auth)
2062     err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
2063   else
2064     {
2065       if (DBG_APP)
2066         log_debug ("slot %d app %s: calling auth(%s)\n",
2067                    card->slot, xstrapptype (card->app), keyidstr);
2068       if (card->app->need_reset)
2069         err = gpg_error (GPG_ERR_CARD_RESET);
2070       else
2071         err = card->app->fnc.auth (card->app, ctrl, keyidstr,
2072                                    pincb, pincb_arg,
2073                                    indata, indatalen,
2074                                    outdata, outdatalen);
2075     }
2076
2077   if (opt.verbose)
2078     log_info ("operation auth result: %s\n", gpg_strerror (err));
2079   return err;
2080 }
2081
2082
2083 /* Decrypt the data in INDATA and return the allocated result in OUTDATA.
2084    If a PIN is required the PINCB will be used to ask for the PIN; it
2085    should return the PIN in an allocated buffer and put it into PIN.  */
2086 gpg_error_t
2087 app_decipher (card_t card, ctrl_t ctrl, const char *keyidstr,
2088               gpg_error_t (*pincb)(void*, const char *, char **),
2089               void *pincb_arg,
2090               const void *indata, size_t indatalen,
2091               unsigned char **outdata, size_t *outdatalen,
2092               unsigned int *r_info)
2093 {
2094   gpg_error_t err;
2095
2096   *r_info = 0;
2097
2098   if (!indata || !indatalen || !outdata || !outdatalen || !pincb)
2099     return gpg_error (GPG_ERR_INV_VALUE);
2100
2101   if ((err = maybe_switch_app (ctrl, card, keyidstr)))
2102     ;
2103   else if (!card->app->fnc.decipher)
2104     err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
2105   else
2106     {
2107       if (DBG_APP)
2108         log_debug ("slot %d app %s: calling decipher(%s)\n",
2109                    card->slot, xstrapptype (card->app), keyidstr);
2110       if (card->app->need_reset)
2111         err = gpg_error (GPG_ERR_CARD_RESET);
2112       else
2113         err = card->app->fnc.decipher (card->app, ctrl, keyidstr,
2114                                        pincb, pincb_arg,
2115                                        indata, indatalen,
2116                                        outdata, outdatalen,
2117                                        r_info);
2118     }
2119
2120   if (opt.verbose)
2121     log_info ("operation decipher result: %s\n", gpg_strerror (err));
2122   return err;
2123 }
2124
2125
2126 /* Perform the WRITECERT operation.  */
2127 gpg_error_t
2128 app_writecert (card_t card, ctrl_t ctrl,
2129                const char *certidstr,
2130                gpg_error_t (*pincb)(void*, const char *, char **),
2131                void *pincb_arg,
2132                const unsigned char *data, size_t datalen)
2133 {
2134   gpg_error_t err;
2135
2136   if (!certidstr || !*certidstr || !pincb)
2137     return gpg_error (GPG_ERR_INV_VALUE);
2138
2139   if ((err = maybe_switch_app (ctrl, card, certidstr)))
2140     ;
2141   else if (!card->app->fnc.writecert)
2142     err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
2143   else
2144     {
2145       if (DBG_APP)
2146         log_debug ("slot %d app %s: calling writecert(%s)\n",
2147                    card->slot, xstrapptype (card->app), certidstr);
2148       if (card->app->need_reset)
2149         err = gpg_error (GPG_ERR_CARD_RESET);
2150       else
2151         err = card->app->fnc.writecert (card->app, ctrl, certidstr,
2152                                         pincb, pincb_arg, data, datalen);
2153     }
2154
2155   if (opt.verbose)
2156     log_info ("operation writecert result: %s\n", gpg_strerror (err));
2157   return err;
2158 }
2159
2160
2161 /* Perform the WRITEKEY operation.  */
2162 gpg_error_t
2163 app_writekey (card_t card, ctrl_t ctrl,
2164               const char *keyidstr, unsigned int flags,
2165               gpg_error_t (*pincb)(void*, const char *, char **),
2166               void *pincb_arg,
2167               const unsigned char *keydata, size_t keydatalen)
2168 {
2169   gpg_error_t err;
2170
2171   if (!keyidstr || !*keyidstr || !pincb)
2172     return gpg_error (GPG_ERR_INV_VALUE);
2173
2174   if ((err = maybe_switch_app (ctrl, card, keyidstr)))
2175     ;
2176   else if (!card->app->fnc.writekey)
2177     err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
2178   else
2179     {
2180       if (DBG_APP)
2181         log_debug ("slot %d app %s: calling writekey(%s)\n",
2182                    card->slot, xstrapptype (card->app), keyidstr);
2183       if (card->app->need_reset)
2184         err = gpg_error (GPG_ERR_CARD_RESET);
2185       else
2186         err = card->app->fnc.writekey (card->app, ctrl, keyidstr, flags,
2187                                        pincb, pincb_arg, keydata, keydatalen);
2188     }
2189
2190   if (opt.verbose)
2191     log_info ("operation writekey result: %s\n", gpg_strerror (err));
2192   return err;
2193 }
2194
2195
2196 /* Perform a GENKEY operation.  */
2197 gpg_error_t
2198 app_genkey (card_t card, ctrl_t ctrl, const char *keynostr,
2199             const char *keytype, unsigned int flags, time_t createtime,
2200             gpg_error_t (*pincb)(void*, const char *, char **),
2201             void *pincb_arg)
2202 {
2203   gpg_error_t err;
2204
2205   if (!keynostr || !*keynostr || !pincb)
2206     return gpg_error (GPG_ERR_INV_VALUE);
2207
2208   if ((err = maybe_switch_app (ctrl, card, keynostr)))
2209     ;
2210   else if (!card->app->fnc.genkey)
2211     err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
2212   else
2213     {
2214       if (DBG_APP)
2215         log_debug ("slot %d app %s: calling genkey(%s)\n",
2216                    card->slot, xstrapptype (card->app), keynostr);
2217       if (card->app->need_reset)
2218         err = gpg_error (GPG_ERR_CARD_RESET);
2219       else
2220         err = card->app->fnc.genkey (card->app, ctrl, keynostr, keytype, flags,
2221                                      createtime, pincb, pincb_arg);
2222     }
2223
2224   if (opt.verbose)
2225     log_info ("operation genkey result: %s\n", gpg_strerror (err));
2226   return err;
2227 }
2228
2229
2230 /* Perform a GET CHALLENGE operation.  This function is special as it
2231    directly accesses the card without any application specific
2232    wrapper. */
2233 gpg_error_t
2234 app_get_challenge (card_t card, ctrl_t ctrl,
2235                    size_t nbytes, unsigned char *buffer)
2236 {
2237   (void)ctrl;
2238   if (!nbytes || !buffer)
2239     return gpg_error (GPG_ERR_INV_VALUE);
2240
2241   return iso7816_get_challenge (card->slot, nbytes, buffer);
2242 }
2243
2244
2245 /* Perform a CHANGE REFERENCE DATA or RESET RETRY COUNTER operation.  */
2246 gpg_error_t
2247 app_change_pin (card_t card, ctrl_t ctrl, const char *chvnostr,
2248                 unsigned int flags,
2249                 gpg_error_t (*pincb)(void*, const char *, char **),
2250                 void *pincb_arg)
2251 {
2252   gpg_error_t err;
2253
2254   if (!chvnostr || !*chvnostr || !pincb)
2255     return gpg_error (GPG_ERR_INV_VALUE);
2256
2257   if ((err = maybe_switch_app (ctrl, card, NULL)))
2258     ;
2259   else if (!card->app->fnc.change_pin)
2260     err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
2261   else
2262     {
2263       if (DBG_APP)
2264         log_debug ("slot %d app %s: calling change_pin(%s)\n",
2265                    card->slot, xstrapptype (card->app), chvnostr);
2266       if (card->app->need_reset)
2267         err = gpg_error (GPG_ERR_CARD_RESET);
2268       else
2269         err = card->app->fnc.change_pin (card->app, ctrl,
2270                                          chvnostr, flags, pincb, pincb_arg);
2271     }
2272
2273   if (opt.verbose)
2274     log_info ("operation change_pin result: %s\n", gpg_strerror (err));
2275   return err;
2276 }
2277
2278
2279 /* Perform a VERIFY operation without doing anything else.  This may
2280    be used to initialize a the PIN cache for long lasting other
2281    operations.  Its use is highly application dependent. */
2282 gpg_error_t
2283 app_check_pin (card_t card, ctrl_t ctrl, const char *keyidstr,
2284                gpg_error_t (*pincb)(void*, const char *, char **),
2285                void *pincb_arg)
2286 {
2287   gpg_error_t err;
2288
2289   if (!keyidstr || !*keyidstr || !pincb)
2290     return gpg_error (GPG_ERR_INV_VALUE);
2291
2292   if ((err = maybe_switch_app (ctrl, card, NULL)))
2293     ;
2294   else if (!card->app->fnc.check_pin)
2295     err = gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
2296   else
2297     {
2298       if (DBG_APP)
2299         log_debug ("slot %d app %s: calling check_pin(%s)\n",
2300                    card->slot, xstrapptype (card->app), keyidstr);
2301       if (card->app->need_reset)
2302         err = gpg_error (GPG_ERR_CARD_RESET);
2303       else
2304         err = card->app->fnc.check_pin (card->app, ctrl, keyidstr,
2305                                         pincb, pincb_arg);
2306     }
2307
2308   if (opt.verbose)
2309     log_info ("operation check_pin result: %s\n", gpg_strerror (err));
2310   return err;
2311 }
2312
2313
2314 static void
2315 report_change (int slot, int old_status, int cur_status)
2316 {
2317   char *homestr, *envstr;
2318   char *fname;
2319   char templ[50];
2320   estream_t fp;
2321
2322   snprintf (templ, sizeof templ, "reader_%d.status", slot);
2323   fname = make_filename (gnupg_homedir (), templ, NULL );
2324   fp = es_fopen (fname, "w");
2325   if (fp)
2326     {
2327       es_fprintf (fp, "%s\n",
2328                (cur_status & 1)? "USABLE":
2329                (cur_status & 4)? "ACTIVE":
2330                (cur_status & 2)? "PRESENT": "NOCARD");
2331       es_fclose (fp);
2332     }
2333   xfree (fname);
2334
2335   homestr = make_filename (gnupg_homedir (), NULL);
2336   if (gpgrt_asprintf (&envstr, "GNUPGHOME=%s", homestr) < 0)
2337     log_error ("out of core while building environment\n");
2338   else
2339     {
2340       gpg_error_t err;
2341       const char *args[9], *envs[2];
2342       char numbuf1[30], numbuf2[30], numbuf3[30];
2343
2344       envs[0] = envstr;
2345       envs[1] = NULL;
2346
2347       sprintf (numbuf1, "%d", slot);
2348       sprintf (numbuf2, "0x%04X", old_status);
2349       sprintf (numbuf3, "0x%04X", cur_status);
2350       args[0] = "--reader-port";
2351       args[1] = numbuf1;
2352       args[2] = "--old-code";
2353       args[3] = numbuf2;
2354       args[4] = "--new-code";
2355       args[5] = numbuf3;
2356       args[6] = "--status";
2357       args[7] = ((cur_status & 1)? "USABLE":
2358                  (cur_status & 4)? "ACTIVE":
2359                  (cur_status & 2)? "PRESENT": "NOCARD");
2360       args[8] = NULL;
2361
2362       fname = make_filename (gnupg_homedir (), "scd-event", NULL);
2363       err = gnupg_spawn_process_detached (fname, args, envs);
2364       if (err && gpg_err_code (err) != GPG_ERR_ENOENT)
2365         log_error ("failed to run event handler '%s': %s\n",
2366                    fname, gpg_strerror (err));
2367       xfree (fname);
2368       xfree (envstr);
2369     }
2370   xfree (homestr);
2371 }
2372
2373
2374 int
2375 scd_update_reader_status_file (void)
2376 {
2377   card_t card, card_next;
2378   int periodical_check_needed = 0;
2379   int reported = 0;
2380
2381   card_list_w_lock ();
2382   for (card = card_top; card; card = card_next)
2383     {
2384       int sw;
2385       unsigned int status;
2386
2387       lock_card (card, NULL);
2388       card_next = card->next;
2389
2390       if (card->reset_requested)
2391         {
2392           /* Here is the post-processing of RESET request.  */
2393           status = 0;
2394           card->reset_requested = 0;
2395         }
2396       else
2397         {
2398           sw = apdu_get_status (card->slot, 0, &status);
2399           if (sw == SW_HOST_NO_READER)
2400             {
2401               /* Most likely the _reader_ has been unplugged.  */
2402               status = 0;
2403             }
2404           else if (sw)
2405             {
2406               /* Get status failed.  Ignore that.  */
2407               if (card->periodical_check_needed)
2408                 periodical_check_needed = 1;
2409               unlock_card (card);
2410               continue;
2411             }
2412         }
2413
2414       if (card->card_status != status)
2415         {
2416           report_change (card->slot, card->card_status, status);
2417           send_client_notifications (card, status == 0);
2418           reported++;
2419
2420           if (status == 0)
2421             {
2422               if (DBG_APP)
2423                 log_debug ("Removal of a card: %d\n", card->slot);
2424               pincache_put (NULL, card->slot, NULL, NULL, NULL, 0);
2425               apdu_close_reader (card->slot);
2426               deallocate_card (card);
2427             }
2428           else
2429             {
2430               card->card_status = status;
2431               if (card->periodical_check_needed)
2432                 periodical_check_needed = 1;
2433               unlock_card (card);
2434             }
2435         }
2436       else
2437         {
2438           if (card->periodical_check_needed)
2439             periodical_check_needed = 1;
2440           unlock_card (card);
2441         }
2442     }
2443
2444   if (reported)
2445     card_list_signal ();
2446
2447   card_list_w_unlock ();
2448
2449   return periodical_check_needed;
2450 }
2451
2452 /* This function must be called once to initialize this module.  This
2453    has to be done before a second thread is spawned.  We can't do the
2454    static initialization because Pth emulation code might not be able
2455    to do a static init; in particular, it is not possible for W32. */
2456 gpg_error_t
2457 initialize_module_command (void)
2458 {
2459   gpg_error_t err;
2460
2461   card_list_lock.num_readers_active = 0;
2462   card_list_lock.num_writers_waiting = 0;
2463   card_list_lock.writer_active = 0;
2464
2465   if (npth_mutex_init (&card_list_lock.lock, NULL))
2466     {
2467       err = gpg_error_from_syserror ();
2468       log_error ("app: error initializing mutex: %s\n", gpg_strerror (err));
2469       return err;
2470     }
2471
2472   err = npth_cond_init (&card_list_lock.cond, NULL);
2473   if (err)
2474     {
2475       err = gpg_error_from_syserror ();
2476       log_error ("npth_cond_init failed: %s\n", gpg_strerror (err));
2477       return err;
2478     }
2479
2480   err = npth_cond_init (&card_list_lock.notify_cond, NULL);
2481   if (err)
2482     {
2483       err = gpg_error_from_syserror ();
2484       log_error ("npth_cond_init failed: %s\n", gpg_strerror (err));
2485       return err;
2486     }
2487
2488   return apdu_init ();
2489 }
2490
2491
2492 /* Sort helper for app_send_card_list.  */
2493 static int
2494 compare_card_list_items (const void *arg_a, const void *arg_b)
2495 {
2496   const card_t a = *(const card_t *)arg_a;
2497   const card_t b = *(const card_t *)arg_b;
2498
2499   return a->slot - b->slot;
2500 }
2501
2502
2503 /* Helper for send_card_and_app_list and app_switch_active_app.  */
2504 static gpg_error_t
2505 send_serialno_and_app_status (card_t card, int with_apps, ctrl_t ctrl)
2506 {
2507   gpg_error_t err;
2508   app_t a;
2509   char *serial;
2510   char *p;
2511   membuf_t mb;
2512   int any = 0;
2513
2514   serial = card_get_serialno (card);
2515   if (!serial)
2516     return 0; /* Oops.  */
2517
2518   if (with_apps)
2519     {
2520       /* Note that in case the additional applications have not yet been
2521        * added to the card context (which is commonly done by means of
2522        * "SERIALNO --all", we do that here.  */
2523       err = select_all_additional_applications_internal (ctrl, card);
2524       if (err)
2525         {
2526           xfree (serial);
2527           return err;
2528         }
2529
2530       init_membuf (&mb, 256);
2531       put_membuf_str (&mb, serial);
2532       for (a = card->app; a; a = a->next)
2533         {
2534           if (!a->fnc.with_keygrip || a->need_reset)
2535             continue;
2536           any = 1;
2537           put_membuf (&mb, " ", 1);
2538           put_membuf_str (&mb, xstrapptype (a));
2539         }
2540       if (!any && card->app)
2541         {
2542           /* No card app supports the with_keygrip function.  Use the
2543            * main app as fallback.  */
2544           put_membuf (&mb, " ", 1);
2545           put_membuf_str (&mb, xstrapptype (card->app));
2546         }
2547       put_membuf (&mb, "", 1);
2548       p = get_membuf (&mb, NULL);
2549       if (!p)
2550         {
2551           err = gpg_error_from_syserror ();
2552           xfree (serial);
2553           return err;
2554         }
2555       send_status_direct (ctrl, "SERIALNO", p);
2556       xfree (p);
2557     }
2558   else
2559     send_status_direct (ctrl, "SERIALNO", serial);
2560
2561   xfree (serial);
2562   return 0;
2563 }
2564
2565
2566 /* Common code for app_send_card_list and app_send_active_apps.  */
2567 static gpg_error_t
2568 send_card_and_app_list (ctrl_t ctrl, card_t wantcard, int with_apps)
2569 {
2570   gpg_error_t err;
2571   card_t c;
2572   card_t *cardlist = NULL;
2573   int n, ncardlist;
2574
2575   card_list_r_lock ();
2576   for (n=0, c = card_top; c; c = c->next)
2577     n++;
2578   if (!n)
2579     {
2580       err = gpg_error (GPG_ERR_CARD_NOT_PRESENT);
2581       goto leave;
2582     }
2583   cardlist = xtrycalloc (n, sizeof *cardlist);
2584   if (!cardlist)
2585     {
2586       err = gpg_error_from_syserror ();
2587       goto leave;
2588     }
2589   for (ncardlist=0, c = card_top; c; c = c->next)
2590     cardlist[ncardlist++] = c;
2591   qsort (cardlist, ncardlist, sizeof *cardlist, compare_card_list_items);
2592
2593   for (n=0; n < ncardlist; n++)
2594     {
2595       if (wantcard && wantcard != cardlist[n])
2596         continue;
2597       err = send_serialno_and_app_status (cardlist[n], with_apps, ctrl);
2598       if (err)
2599         goto leave;
2600     }
2601
2602   err = 0;
2603
2604  leave:
2605   card_list_r_unlock ();
2606   xfree (cardlist);
2607   return err;
2608 }
2609
2610
2611 /* Send status lines with the serialno of all inserted cards.  */
2612 gpg_error_t
2613 app_send_card_list (ctrl_t ctrl)
2614 {
2615   return send_card_and_app_list (ctrl, NULL, 0);
2616 }
2617
2618
2619 /* Send status lines with the serialno and appname of the current card
2620  * or of all cards if CARD is NULL.  */
2621 gpg_error_t
2622 app_send_active_apps (card_t card, ctrl_t ctrl)
2623 {
2624   return send_card_and_app_list (ctrl, card, 1);
2625 }
2626
2627
2628 /* Switch to APPNAME and print a respective status line with that app
2629  * listed first.  If APPNAME is NULL or the empty string no switching
2630  * is done but the status line is printed anyway.  */
2631 gpg_error_t
2632 app_switch_active_app (card_t card, ctrl_t ctrl, const char *appname)
2633 {
2634   gpg_error_t err;
2635   apptype_t apptype;
2636
2637   /* Note that in case the additional applications have not yet been
2638    * added to the card context (which is commonly done by means of
2639    * "SERIALNO --all", we do that here.  */
2640   err = select_all_additional_applications_internal (ctrl, card);
2641   if (err)
2642     goto leave;
2643
2644   if (appname && *appname)
2645     {
2646       apptype = apptype_from_name (appname);
2647       if (!apptype)
2648         {
2649           err = gpg_error (GPG_ERR_NOT_FOUND);
2650           goto leave;
2651         }
2652
2653       ctrl->current_apptype = apptype;
2654       err = maybe_switch_app (ctrl, card, NULL);
2655       if (err)
2656         goto leave;
2657     }
2658
2659   /* Print the status line.  */
2660   err = send_serialno_and_app_status (card, 1, ctrl);
2661
2662  leave:
2663   return err;
2664 }
2665
2666
2667 /* Execute an action for each app.  ACTION can be one of:
2668  *
2669  * - KEYGRIP_ACTION_SEND_DATA
2670  *
2671  *     If KEYGRIP_STR matches a public key of any active application
2672  *     send information as LF terminated data lines about the public
2673  *     key.  The format of these lines is
2674  *         <keygrip> T <serialno> <idstr>
2675  *     If a match was found a pointer to the matching application is
2676  *     returned.  With the KEYGRIP_STR given as NULL, lines for all
2677  *     keys (with CAPABILITY) will be send and the return value is
2678  *     GPG_ERR_TRUE.
2679  *
2680  * - KEYGRIP_ACTION_WRITE_STATUS
2681  *
2682  *     Same as KEYGRIP_ACTION_SEND_DATA but uses status lines instead
2683  *     of data lines.
2684  *
2685  * - KEYGRIP_ACTION_LOOKUP
2686  *
2687  *     Returns a pointer to the application matching KEYGRIP_STR but
2688  *     does not emit any status or data lines.  If no key with that
2689  *     keygrip is available or KEYGRIP_STR is NULL, GPG_ERR_NOT_FOUND
2690  *     is returned.
2691  */
2692 card_t
2693 app_do_with_keygrip (ctrl_t ctrl, int action, const char *keygrip_str,
2694                      int capability)
2695 {
2696   card_t card;
2697
2698   card_list_r_lock ();
2699   card = do_with_keygrip (ctrl, action, keygrip_str, capability);
2700   card_list_r_unlock ();
2701   return card;
2702 }