Imported Upstream version 2.2.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 "app-common.h"
30 #include "iso7816.h"
31 #include "apdu.h"
32 #include "../common/tlv.h"
33
34 static npth_mutex_t app_list_lock;
35 static app_t app_top;
36 \f
37 static void
38 print_progress_line (void *opaque, const char *what, int pc, int cur, int tot)
39 {
40   ctrl_t ctrl = opaque;
41   char line[100];
42
43   if (ctrl)
44     {
45       snprintf (line, sizeof line, "%s %c %d %d", what, pc, cur, tot);
46       send_status_direct (ctrl, "PROGRESS", line);
47     }
48 }
49
50
51 /* Lock the reader SLOT.  This function shall be used right before
52    calling any of the actual application functions to serialize access
53    to the reader.  We do this always even if the reader is not
54    actually used.  This allows an actual connection to assume that it
55    never shares a reader (while performing one command).  Returns 0 on
56    success; only then the unlock_reader function must be called after
57    returning from the handler. */
58 static gpg_error_t
59 lock_app (app_t app, ctrl_t ctrl)
60 {
61   if (npth_mutex_lock (&app->lock))
62     {
63       gpg_error_t err = gpg_error_from_syserror ();
64       log_error ("failed to acquire APP lock for %p: %s\n",
65                  app, gpg_strerror (err));
66       return err;
67     }
68
69   apdu_set_progress_cb (app->slot, print_progress_line, ctrl);
70
71   return 0;
72 }
73
74 /* Release a lock on the reader.  See lock_reader(). */
75 static void
76 unlock_app (app_t app)
77 {
78   apdu_set_progress_cb (app->slot, NULL, NULL);
79
80   if (npth_mutex_unlock (&app->lock))
81     {
82       gpg_error_t err = gpg_error_from_syserror ();
83       log_error ("failed to release APP lock for %p: %s\n",
84                  app, gpg_strerror (err));
85     }
86 }
87
88
89 /* This function may be called to print information pertaining to the
90    current state of this module to the log. */
91 void
92 app_dump_state (void)
93 {
94   app_t a;
95
96   npth_mutex_lock (&app_list_lock);
97   for (a = app_top; a; a = a->next)
98     log_info ("app_dump_state: app=%p type='%s'\n", a, a->apptype);
99   npth_mutex_unlock (&app_list_lock);
100 }
101
102 /* Check whether the application NAME is allowed.  This does not mean
103    we have support for it though.  */
104 static int
105 is_app_allowed (const char *name)
106 {
107   strlist_t l;
108
109   for (l=opt.disabled_applications; l; l = l->next)
110     if (!strcmp (l->d, name))
111       return 0; /* no */
112   return 1; /* yes */
113 }
114
115
116 static gpg_error_t
117 check_conflict (app_t app, const char *name)
118 {
119   if (!app || !name || (app->apptype && !ascii_strcasecmp (app->apptype, name)))
120     return 0;
121
122   log_info ("application '%s' in use - can't switch\n",
123             app->apptype? app->apptype : "<null>");
124
125   return gpg_error (GPG_ERR_CONFLICT);
126 }
127
128 /* This function is used by the serialno command to check for an
129    application conflict which may appear if the serialno command is
130    used to request a specific application and the connection has
131    already done a select_application. */
132 gpg_error_t
133 check_application_conflict (const char *name, app_t app)
134 {
135   return check_conflict (app, name);
136 }
137
138
139 gpg_error_t
140 app_reset (app_t app, ctrl_t ctrl, int send_reset)
141 {
142   gpg_error_t err = 0;
143
144   if (send_reset)
145     {
146       int sw;
147
148       lock_app (app, ctrl);
149       sw = apdu_reset (app->slot);
150       if (sw)
151         err = gpg_error (GPG_ERR_CARD_RESET);
152
153       app->reset_requested = 1;
154       unlock_app (app);
155
156       scd_kick_the_loop ();
157       gnupg_sleep (1);
158     }
159   else
160     {
161       ctrl->app_ctx = NULL;
162       release_application (app, 0);
163     }
164
165   return err;
166 }
167
168 static gpg_error_t
169 app_new_register (int slot, ctrl_t ctrl, const char *name,
170                   int periodical_check_needed)
171 {
172   gpg_error_t err = 0;
173   app_t app = NULL;
174   unsigned char *result = NULL;
175   size_t resultlen;
176   int want_undefined;
177
178   /* Need to allocate a new one.  */
179   app = xtrycalloc (1, sizeof *app);
180   if (!app)
181     {
182       err = gpg_error_from_syserror ();
183       log_info ("error allocating context: %s\n", gpg_strerror (err));
184       return err;
185     }
186
187   app->slot = slot;
188   app->card_status = (unsigned int)-1;
189
190   if (npth_mutex_init (&app->lock, NULL))
191     {
192       err = gpg_error_from_syserror ();
193       log_error ("error initializing mutex: %s\n", gpg_strerror (err));
194       xfree (app);
195       return err;
196     }
197
198   err = lock_app (app, ctrl);
199   if (err)
200     {
201       xfree (app);
202       return err;
203     }
204
205   want_undefined = (name && !strcmp (name, "undefined"));
206
207   /* Try to read the GDO file first to get a default serial number.
208      We skip this if the undefined application has been requested. */
209   if (!want_undefined)
210     {
211       err = iso7816_select_file (slot, 0x3F00, 1);
212       if (!err)
213         err = iso7816_select_file (slot, 0x2F02, 0);
214       if (!err)
215         err = iso7816_read_binary (slot, 0, 0, &result, &resultlen);
216       if (!err)
217         {
218           size_t n;
219           const unsigned char *p;
220
221           p = find_tlv_unchecked (result, resultlen, 0x5A, &n);
222           if (p)
223             resultlen -= (p-result);
224           if (p && n > resultlen && n == 0x0d && resultlen+1 == n)
225             {
226               /* The object it does not fit into the buffer.  This is an
227                  invalid encoding (or the buffer is too short.  However, I
228                  have some test cards with such an invalid encoding and
229                  therefore I use this ugly workaround to return something
230                  I can further experiment with. */
231               log_info ("enabling BMI testcard workaround\n");
232               n--;
233             }
234
235           if (p && n <= resultlen)
236             {
237               /* The GDO file is pretty short, thus we simply reuse it for
238                  storing the serial number. */
239               memmove (result, p, n);
240               app->serialno = result;
241               app->serialnolen = n;
242               err = app_munge_serialno (app);
243               if (err)
244                 goto leave;
245             }
246           else
247             xfree (result);
248           result = NULL;
249         }
250     }
251
252   /* For certain error codes, there is no need to try more.  */
253   if (gpg_err_code (err) == GPG_ERR_CARD_NOT_PRESENT
254       || gpg_err_code (err) == GPG_ERR_ENODEV)
255     goto leave;
256
257   /* Figure out the application to use.  */
258   if (want_undefined)
259     {
260       /* We switch to the "undefined" application only if explicitly
261          requested.  */
262       app->apptype = "UNDEFINED";
263       err = 0;
264     }
265   else
266     err = gpg_error (GPG_ERR_NOT_FOUND);
267
268   if (err && is_app_allowed ("openpgp")
269           && (!name || !strcmp (name, "openpgp")))
270     err = app_select_openpgp (app);
271   if (err && is_app_allowed ("nks") && (!name || !strcmp (name, "nks")))
272     err = app_select_nks (app);
273   if (err && is_app_allowed ("p15") && (!name || !strcmp (name, "p15")))
274     err = app_select_p15 (app);
275   if (err && is_app_allowed ("geldkarte")
276       && (!name || !strcmp (name, "geldkarte")))
277     err = app_select_geldkarte (app);
278   if (err && is_app_allowed ("dinsig") && (!name || !strcmp (name, "dinsig")))
279     err = app_select_dinsig (app);
280   if (err && is_app_allowed ("sc-hsm") && (!name || !strcmp (name, "sc-hsm")))
281     err = app_select_sc_hsm (app);
282   if (err && name && gpg_err_code (err) != GPG_ERR_OBJ_TERM_STATE)
283     err = gpg_error (GPG_ERR_NOT_SUPPORTED);
284
285  leave:
286   if (err)
287     {
288       if (name)
289         log_info ("can't select application '%s': %s\n",
290                   name, gpg_strerror (err));
291       else
292         log_info ("no supported card application found: %s\n",
293                   gpg_strerror (err));
294       unlock_app (app);
295       xfree (app);
296       return err;
297     }
298
299   app->periodical_check_needed = periodical_check_needed;
300
301   npth_mutex_lock (&app_list_lock);
302   app->next = app_top;
303   app_top = app;
304   npth_mutex_unlock (&app_list_lock);
305   unlock_app (app);
306   return 0;
307 }
308
309 /* If called with NAME as NULL, select the best fitting application
310    and return a context; otherwise select the application with NAME
311    and return a context.  Returns an error code and stores NULL at
312    R_APP if no application was found or no card is present. */
313 gpg_error_t
314 select_application (ctrl_t ctrl, const char *name, app_t *r_app,
315                     int scan, const unsigned char *serialno_bin,
316                     size_t serialno_bin_len)
317 {
318   gpg_error_t err = 0;
319   app_t a, a_prev = NULL;
320
321   *r_app = NULL;
322
323   if (scan || !app_top)
324     {
325       struct dev_list *l;
326       int new_app = 0;
327
328       /* Scan the devices to find new device(s).  */
329       err = apdu_dev_list_start (opt.reader_port, &l);
330       if (err)
331         return err;
332
333       while (1)
334         {
335           int slot;
336           int periodical_check_needed_this;
337
338           slot = apdu_open_reader (l, !app_top);
339           if (slot < 0)
340             break;
341
342           periodical_check_needed_this = apdu_connect (slot);
343           if (periodical_check_needed_this < 0)
344             {
345               /* We close a reader with no card.  */
346               err = gpg_error (GPG_ERR_ENODEV);
347             }
348           else
349             {
350               err = app_new_register (slot, ctrl, name,
351                                       periodical_check_needed_this);
352               new_app++;
353             }
354
355           if (err)
356             apdu_close_reader (slot);
357         }
358
359       apdu_dev_list_finish (l);
360
361       /* If new device(s), kick the scdaemon loop.  */
362       if (new_app)
363         scd_kick_the_loop ();
364     }
365
366   npth_mutex_lock (&app_list_lock);
367   for (a = app_top; a; a = a->next)
368     {
369       lock_app (a, ctrl);
370       if (serialno_bin == NULL)
371         break;
372       if (a->serialnolen == serialno_bin_len
373           && !memcmp (a->serialno, serialno_bin, a->serialnolen))
374         break;
375       unlock_app (a);
376       a_prev = a;
377     }
378
379   if (a)
380     {
381       err = check_conflict (a, name);
382       if (!err)
383         {
384           a->ref_count++;
385           *r_app = a;
386           if (a_prev)
387             {
388               a_prev->next = a->next;
389               a->next = app_top;
390               app_top = a;
391             }
392       }
393       unlock_app (a);
394     }
395   else
396     err = gpg_error (GPG_ERR_ENODEV);
397
398   npth_mutex_unlock (&app_list_lock);
399
400   return err;
401 }
402
403
404 char *
405 get_supported_applications (void)
406 {
407   const char *list[] = {
408     "openpgp",
409     "nks",
410     "p15",
411     "geldkarte",
412     "dinsig",
413     "sc-hsm",
414     /* Note: "undefined" is not listed here because it needs special
415        treatment by the client.  */
416     NULL
417   };
418   int idx;
419   size_t nbytes;
420   char *buffer, *p;
421
422   for (nbytes=1, idx=0; list[idx]; idx++)
423     nbytes += strlen (list[idx]) + 1 + 1;
424
425   buffer = xtrymalloc (nbytes);
426   if (!buffer)
427     return NULL;
428
429   for (p=buffer, idx=0; list[idx]; idx++)
430     if (is_app_allowed (list[idx]))
431       p = stpcpy (stpcpy (p, list[idx]), ":\n");
432   *p = 0;
433
434   return buffer;
435 }
436
437
438 /* Deallocate the application.  */
439 static void
440 deallocate_app (app_t app)
441 {
442   app_t a, a_prev = NULL;
443
444   for (a = app_top; a; a = a->next)
445     if (a == app)
446       {
447         if (a_prev == NULL)
448           app_top = a->next;
449         else
450           a_prev->next = a->next;
451         break;
452       }
453     else
454       a_prev = a;
455
456   if (app->ref_count)
457     log_error ("trying to release context used yet (%d)\n", app->ref_count);
458
459   if (app->fnc.deinit)
460     {
461       app->fnc.deinit (app);
462       app->fnc.deinit = NULL;
463     }
464
465   xfree (app->serialno);
466
467   unlock_app (app);
468   xfree (app);
469 }
470
471 /* Free the resources associated with the application APP.  APP is
472    allowed to be NULL in which case this is a no-op.  Note that we are
473    using reference counting to track the users of the application and
474    actually deferring the deallocation to allow for a later reuse by
475    a new connection. */
476 void
477 release_application (app_t app, int locked_already)
478 {
479   if (!app)
480     return;
481
482   /* We don't deallocate app here.  Instead, we keep it.  This is
483      useful so that a card does not get reset even if only one session
484      is using the card - this way the PIN cache and other cached data
485      are preserved.  */
486
487   if (!locked_already)
488     lock_app (app, NULL);
489
490   if (!app->ref_count)
491     log_bug ("trying to release an already released context\n");
492
493   --app->ref_count;
494   if (!locked_already)
495     unlock_app (app);
496 }
497
498
499
500 /* The serial number may need some cosmetics.  Do it here.  This
501    function shall only be called once after a new serial number has
502    been put into APP->serialno.
503
504    Prefixes we use:
505
506      FF 00 00 = For serial numbers starting with an FF
507      FF 01 00 = Some german p15 cards return an empty serial number so the
508                 serial number from the EF(TokenInfo) is used instead.
509      FF 7F 00 = No serialno.
510
511      All other serial number not starting with FF are used as they are.
512 */
513 gpg_error_t
514 app_munge_serialno (app_t app)
515 {
516   if (app->serialnolen && app->serialno[0] == 0xff)
517     {
518       /* The serial number starts with our special prefix.  This
519          requires that we put our default prefix "FF0000" in front. */
520       unsigned char *p = xtrymalloc (app->serialnolen + 3);
521       if (!p)
522         return gpg_error_from_syserror ();
523       memcpy (p, "\xff\0", 3);
524       memcpy (p+3, app->serialno, app->serialnolen);
525       app->serialnolen += 3;
526       xfree (app->serialno);
527       app->serialno = p;
528     }
529   else if (!app->serialnolen)
530     {
531       unsigned char *p = xtrymalloc (3);
532       if (!p)
533         return gpg_error_from_syserror ();
534       memcpy (p, "\xff\x7f", 3);
535       app->serialnolen = 3;
536       xfree (app->serialno);
537       app->serialno = p;
538     }
539   return 0;
540 }
541
542
543
544 /* Retrieve the serial number of the card.  The serial number is
545    returned as a malloced string (hex encoded) in SERIAL.  Caller must
546    free SERIAL unless the function returns an error.  */
547 char *
548 app_get_serialno (app_t app)
549 {
550   char *serial;
551
552   if (!app)
553     return NULL;
554
555   if (!app->serialnolen)
556     serial = xtrystrdup ("FF7F00");
557   else
558     serial = bin2hex (app->serialno, app->serialnolen, NULL);
559
560   return serial;
561 }
562
563
564 /* Write out the application specifig status lines for the LEARN
565    command. */
566 gpg_error_t
567 app_write_learn_status (app_t app, ctrl_t ctrl, unsigned int flags)
568 {
569   gpg_error_t err;
570
571   if (!app)
572     return gpg_error (GPG_ERR_INV_VALUE);
573   if (!app->fnc.learn_status)
574     return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
575
576   /* We do not send APPTYPE if only keypairinfo is requested.  */
577   if (app->apptype && !(flags & 1))
578     send_status_direct (ctrl, "APPTYPE", app->apptype);
579   err = lock_app (app, ctrl);
580   if (err)
581     return err;
582   err = app->fnc.learn_status (app, ctrl, flags);
583   unlock_app (app);
584   return err;
585 }
586
587
588 /* Read the certificate with id CERTID (as returned by learn_status in
589    the CERTINFO status lines) and return it in the freshly allocated
590    buffer put into CERT and the length of the certificate put into
591    CERTLEN. */
592 gpg_error_t
593 app_readcert (app_t app, ctrl_t ctrl, const char *certid,
594               unsigned char **cert, size_t *certlen)
595 {
596   gpg_error_t err;
597
598   if (!app)
599     return gpg_error (GPG_ERR_INV_VALUE);
600   if (!app->ref_count)
601     return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED);
602   if (!app->fnc.readcert)
603     return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
604   err = lock_app (app, ctrl);
605   if (err)
606     return err;
607   err = app->fnc.readcert (app, certid, cert, certlen);
608   unlock_app (app);
609   return err;
610 }
611
612
613 /* Read the key with ID KEYID.  On success a canonical encoded
614    S-expression with the public key will get stored at PK and its
615    length (for assertions) at PKLEN; the caller must release that
616    buffer. On error NULL will be stored at PK and PKLEN and an error
617    code returned.
618
619    This function might not be supported by all applications.  */
620 gpg_error_t
621 app_readkey (app_t app, ctrl_t ctrl, int advanced, const char *keyid,
622              unsigned char **pk, size_t *pklen)
623 {
624   gpg_error_t err;
625
626   if (pk)
627     *pk = NULL;
628   if (pklen)
629     *pklen = 0;
630
631   if (!app || !keyid || !pk || !pklen)
632     return gpg_error (GPG_ERR_INV_VALUE);
633   if (!app->ref_count)
634     return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED);
635   if (!app->fnc.readkey)
636     return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
637   err = lock_app (app, ctrl);
638   if (err)
639     return err;
640   err= app->fnc.readkey (app, advanced, keyid, pk, pklen);
641   unlock_app (app);
642   return err;
643 }
644
645
646 /* Perform a GETATTR operation.  */
647 gpg_error_t
648 app_getattr (app_t app, ctrl_t ctrl, const char *name)
649 {
650   gpg_error_t err;
651
652   if (!app || !name || !*name)
653     return gpg_error (GPG_ERR_INV_VALUE);
654   if (!app->ref_count)
655     return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED);
656
657   if (app->apptype && name && !strcmp (name, "APPTYPE"))
658     {
659       send_status_direct (ctrl, "APPTYPE", app->apptype);
660       return 0;
661     }
662   if (name && !strcmp (name, "SERIALNO"))
663     {
664       char *serial;
665
666       serial = app_get_serialno (app);
667       if (!serial)
668         return gpg_error (GPG_ERR_INV_VALUE);
669
670       send_status_direct (ctrl, "SERIALNO", serial);
671       xfree (serial);
672       return 0;
673     }
674
675   if (!app->fnc.getattr)
676     return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
677   err = lock_app (app, ctrl);
678   if (err)
679     return err;
680   err =  app->fnc.getattr (app, ctrl, name);
681   unlock_app (app);
682   return err;
683 }
684
685 /* Perform a SETATTR operation.  */
686 gpg_error_t
687 app_setattr (app_t app, ctrl_t ctrl, const char *name,
688              gpg_error_t (*pincb)(void*, const char *, char **),
689              void *pincb_arg,
690              const unsigned char *value, size_t valuelen)
691 {
692   gpg_error_t err;
693
694   if (!app || !name || !*name || !value)
695     return gpg_error (GPG_ERR_INV_VALUE);
696   if (!app->ref_count)
697     return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED);
698   if (!app->fnc.setattr)
699     return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
700   err = lock_app (app, ctrl);
701   if (err)
702     return err;
703   err = app->fnc.setattr (app, name, pincb, pincb_arg, value, valuelen);
704   unlock_app (app);
705   return err;
706 }
707
708 /* Create the signature and return the allocated result in OUTDATA.
709    If a PIN is required the PINCB will be used to ask for the PIN; it
710    should return the PIN in an allocated buffer and put it into PIN.  */
711 gpg_error_t
712 app_sign (app_t app, ctrl_t ctrl, const char *keyidstr, int hashalgo,
713           gpg_error_t (*pincb)(void*, const char *, char **),
714           void *pincb_arg,
715           const void *indata, size_t indatalen,
716           unsigned char **outdata, size_t *outdatalen )
717 {
718   gpg_error_t err;
719
720   if (!app || !indata || !indatalen || !outdata || !outdatalen || !pincb)
721     return gpg_error (GPG_ERR_INV_VALUE);
722   if (!app->ref_count)
723     return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED);
724   if (!app->fnc.sign)
725     return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
726   err = lock_app (app, ctrl);
727   if (err)
728     return err;
729   err = app->fnc.sign (app, keyidstr, hashalgo,
730                        pincb, pincb_arg,
731                        indata, indatalen,
732                        outdata, outdatalen);
733   unlock_app (app);
734   if (opt.verbose)
735     log_info ("operation sign result: %s\n", gpg_strerror (err));
736   return err;
737 }
738
739 /* Create the signature using the INTERNAL AUTHENTICATE command and
740    return the allocated result in OUTDATA.  If a PIN is required the
741    PINCB will be used to ask for the PIN; it should return the PIN in
742    an allocated buffer and put it into PIN.  */
743 gpg_error_t
744 app_auth (app_t app, ctrl_t ctrl, const char *keyidstr,
745           gpg_error_t (*pincb)(void*, const char *, char **),
746           void *pincb_arg,
747           const void *indata, size_t indatalen,
748           unsigned char **outdata, size_t *outdatalen )
749 {
750   gpg_error_t err;
751
752   if (!app || !indata || !indatalen || !outdata || !outdatalen || !pincb)
753     return gpg_error (GPG_ERR_INV_VALUE);
754   if (!app->ref_count)
755     return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED);
756   if (!app->fnc.auth)
757     return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
758   err = lock_app (app, ctrl);
759   if (err)
760     return err;
761   err = app->fnc.auth (app, keyidstr,
762                        pincb, pincb_arg,
763                        indata, indatalen,
764                        outdata, outdatalen);
765   unlock_app (app);
766   if (opt.verbose)
767     log_info ("operation auth result: %s\n", gpg_strerror (err));
768   return err;
769 }
770
771
772 /* Decrypt the data in INDATA and return the allocated result in OUTDATA.
773    If a PIN is required the PINCB will be used to ask for the PIN; it
774    should return the PIN in an allocated buffer and put it into PIN.  */
775 gpg_error_t
776 app_decipher (app_t app, ctrl_t ctrl, const char *keyidstr,
777               gpg_error_t (*pincb)(void*, const char *, char **),
778               void *pincb_arg,
779               const void *indata, size_t indatalen,
780               unsigned char **outdata, size_t *outdatalen,
781               unsigned int *r_info)
782 {
783   gpg_error_t err;
784
785   *r_info = 0;
786
787   if (!app || !indata || !indatalen || !outdata || !outdatalen || !pincb)
788     return gpg_error (GPG_ERR_INV_VALUE);
789   if (!app->ref_count)
790     return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED);
791   if (!app->fnc.decipher)
792     return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
793   err = lock_app (app, ctrl);
794   if (err)
795     return err;
796   err = app->fnc.decipher (app, keyidstr,
797                            pincb, pincb_arg,
798                            indata, indatalen,
799                            outdata, outdatalen,
800                            r_info);
801   unlock_app (app);
802   if (opt.verbose)
803     log_info ("operation decipher result: %s\n", gpg_strerror (err));
804   return err;
805 }
806
807
808 /* Perform the WRITECERT operation.  */
809 gpg_error_t
810 app_writecert (app_t app, ctrl_t ctrl,
811               const char *certidstr,
812               gpg_error_t (*pincb)(void*, const char *, char **),
813               void *pincb_arg,
814               const unsigned char *data, size_t datalen)
815 {
816   gpg_error_t err;
817
818   if (!app || !certidstr || !*certidstr || !pincb)
819     return gpg_error (GPG_ERR_INV_VALUE);
820   if (!app->ref_count)
821     return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED);
822   if (!app->fnc.writecert)
823     return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
824   err = lock_app (app, ctrl);
825   if (err)
826     return err;
827   err = app->fnc.writecert (app, ctrl, certidstr,
828                             pincb, pincb_arg, data, datalen);
829   unlock_app (app);
830   if (opt.verbose)
831     log_info ("operation writecert result: %s\n", gpg_strerror (err));
832   return err;
833 }
834
835
836 /* Perform the WRITEKEY operation.  */
837 gpg_error_t
838 app_writekey (app_t app, ctrl_t ctrl,
839               const char *keyidstr, unsigned int flags,
840               gpg_error_t (*pincb)(void*, const char *, char **),
841               void *pincb_arg,
842               const unsigned char *keydata, size_t keydatalen)
843 {
844   gpg_error_t err;
845
846   if (!app || !keyidstr || !*keyidstr || !pincb)
847     return gpg_error (GPG_ERR_INV_VALUE);
848   if (!app->ref_count)
849     return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED);
850   if (!app->fnc.writekey)
851     return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
852   err = lock_app (app, ctrl);
853   if (err)
854     return err;
855   err = app->fnc.writekey (app, ctrl, keyidstr, flags,
856                            pincb, pincb_arg, keydata, keydatalen);
857   unlock_app (app);
858   if (opt.verbose)
859     log_info ("operation writekey result: %s\n", gpg_strerror (err));
860   return err;
861 }
862
863
864 /* Perform a SETATTR operation.  */
865 gpg_error_t
866 app_genkey (app_t app, ctrl_t ctrl, const char *keynostr, unsigned int flags,
867             time_t createtime,
868             gpg_error_t (*pincb)(void*, const char *, char **),
869             void *pincb_arg)
870 {
871   gpg_error_t err;
872
873   if (!app || !keynostr || !*keynostr || !pincb)
874     return gpg_error (GPG_ERR_INV_VALUE);
875   if (!app->ref_count)
876     return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED);
877   if (!app->fnc.genkey)
878     return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
879   err = lock_app (app, ctrl);
880   if (err)
881     return err;
882   err = app->fnc.genkey (app, ctrl, keynostr, flags,
883                          createtime, pincb, pincb_arg);
884   unlock_app (app);
885   if (opt.verbose)
886     log_info ("operation genkey result: %s\n", gpg_strerror (err));
887   return err;
888 }
889
890
891 /* Perform a GET CHALLENGE operation.  This function is special as it
892    directly accesses the card without any application specific
893    wrapper. */
894 gpg_error_t
895 app_get_challenge (app_t app, ctrl_t ctrl, size_t nbytes, unsigned char *buffer)
896 {
897   gpg_error_t err;
898
899   if (!app || !nbytes || !buffer)
900     return gpg_error (GPG_ERR_INV_VALUE);
901   if (!app->ref_count)
902     return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED);
903   err = lock_app (app, ctrl);
904   if (err)
905     return err;
906   err = iso7816_get_challenge (app->slot, nbytes, buffer);
907   unlock_app (app);
908   return err;
909 }
910
911
912
913 /* Perform a CHANGE REFERENCE DATA or RESET RETRY COUNTER operation.  */
914 gpg_error_t
915 app_change_pin (app_t app, ctrl_t ctrl, const char *chvnostr, int reset_mode,
916                 gpg_error_t (*pincb)(void*, const char *, char **),
917                 void *pincb_arg)
918 {
919   gpg_error_t err;
920
921   if (!app || !chvnostr || !*chvnostr || !pincb)
922     return gpg_error (GPG_ERR_INV_VALUE);
923   if (!app->ref_count)
924     return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED);
925   if (!app->fnc.change_pin)
926     return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
927   err = lock_app (app, ctrl);
928   if (err)
929     return err;
930   err = app->fnc.change_pin (app, ctrl, chvnostr, reset_mode,
931                              pincb, pincb_arg);
932   unlock_app (app);
933   if (opt.verbose)
934     log_info ("operation change_pin result: %s\n", gpg_strerror (err));
935   return err;
936 }
937
938
939 /* Perform a VERIFY operation without doing anything lese.  This may
940    be used to initialize a the PIN cache for long lasting other
941    operations.  Its use is highly application dependent. */
942 gpg_error_t
943 app_check_pin (app_t app, ctrl_t ctrl, const char *keyidstr,
944                gpg_error_t (*pincb)(void*, const char *, char **),
945                void *pincb_arg)
946 {
947   gpg_error_t err;
948
949   if (!app || !keyidstr || !*keyidstr || !pincb)
950     return gpg_error (GPG_ERR_INV_VALUE);
951   if (!app->ref_count)
952     return gpg_error (GPG_ERR_CARD_NOT_INITIALIZED);
953   if (!app->fnc.check_pin)
954     return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
955   err = lock_app (app, ctrl);
956   if (err)
957     return err;
958   err = app->fnc.check_pin (app, keyidstr, pincb, pincb_arg);
959   unlock_app (app);
960   if (opt.verbose)
961     log_info ("operation check_pin result: %s\n", gpg_strerror (err));
962   return err;
963 }
964
965 static void
966 report_change (int slot, int old_status, int cur_status)
967 {
968   char *homestr, *envstr;
969   char *fname;
970   char templ[50];
971   FILE *fp;
972
973   snprintf (templ, sizeof templ, "reader_%d.status", slot);
974   fname = make_filename (gnupg_homedir (), templ, NULL );
975   fp = fopen (fname, "w");
976   if (fp)
977     {
978       fprintf (fp, "%s\n",
979                (cur_status & 1)? "USABLE":
980                (cur_status & 4)? "ACTIVE":
981                (cur_status & 2)? "PRESENT": "NOCARD");
982       fclose (fp);
983     }
984   xfree (fname);
985
986   homestr = make_filename (gnupg_homedir (), NULL);
987   if (gpgrt_asprintf (&envstr, "GNUPGHOME=%s", homestr) < 0)
988     log_error ("out of core while building environment\n");
989   else
990     {
991       gpg_error_t err;
992       const char *args[9], *envs[2];
993       char numbuf1[30], numbuf2[30], numbuf3[30];
994
995       envs[0] = envstr;
996       envs[1] = NULL;
997
998       sprintf (numbuf1, "%d", slot);
999       sprintf (numbuf2, "0x%04X", old_status);
1000       sprintf (numbuf3, "0x%04X", cur_status);
1001       args[0] = "--reader-port";
1002       args[1] = numbuf1;
1003       args[2] = "--old-code";
1004       args[3] = numbuf2;
1005       args[4] = "--new-code";
1006       args[5] = numbuf3;
1007       args[6] = "--status";
1008       args[7] = ((cur_status & 1)? "USABLE":
1009                  (cur_status & 4)? "ACTIVE":
1010                  (cur_status & 2)? "PRESENT": "NOCARD");
1011       args[8] = NULL;
1012
1013       fname = make_filename (gnupg_homedir (), "scd-event", NULL);
1014       err = gnupg_spawn_process_detached (fname, args, envs);
1015       if (err && gpg_err_code (err) != GPG_ERR_ENOENT)
1016         log_error ("failed to run event handler '%s': %s\n",
1017                    fname, gpg_strerror (err));
1018       xfree (fname);
1019       xfree (envstr);
1020     }
1021   xfree (homestr);
1022 }
1023
1024 int
1025 scd_update_reader_status_file (void)
1026 {
1027   app_t a, app_next;
1028   int periodical_check_needed = 0;
1029
1030   npth_mutex_lock (&app_list_lock);
1031   for (a = app_top; a; a = app_next)
1032     {
1033       int sw;
1034       unsigned int status;
1035
1036       lock_app (a, NULL);
1037       app_next = a->next;
1038
1039       if (a->reset_requested)
1040         status = 0;
1041       else
1042         {
1043           sw = apdu_get_status (a->slot, 0, &status);
1044           if (sw == SW_HOST_NO_READER)
1045             {
1046               /* Most likely the _reader_ has been unplugged.  */
1047               status = 0;
1048             }
1049           else if (sw)
1050             {
1051               /* Get status failed.  Ignore that.  */
1052               if (a->periodical_check_needed)
1053                 periodical_check_needed = 1;
1054               unlock_app (a);
1055               continue;
1056             }
1057         }
1058
1059       if (a->card_status != status)
1060         {
1061           report_change (a->slot, a->card_status, status);
1062           send_client_notifications (a, status == 0);
1063
1064           if (status == 0)
1065             {
1066               log_debug ("Removal of a card: %d\n", a->slot);
1067               apdu_close_reader (a->slot);
1068               deallocate_app (a);
1069             }
1070           else
1071             {
1072               a->card_status = status;
1073               if (a->periodical_check_needed)
1074                 periodical_check_needed = 1;
1075               unlock_app (a);
1076             }
1077         }
1078       else
1079         {
1080           if (a->periodical_check_needed)
1081             periodical_check_needed = 1;
1082           unlock_app (a);
1083         }
1084     }
1085   npth_mutex_unlock (&app_list_lock);
1086
1087   return periodical_check_needed;
1088 }
1089
1090 /* This function must be called once to initialize this module.  This
1091    has to be done before a second thread is spawned.  We can't do the
1092    static initialization because Pth emulation code might not be able
1093    to do a static init; in particular, it is not possible for W32. */
1094 gpg_error_t
1095 initialize_module_command (void)
1096 {
1097   gpg_error_t err;
1098
1099   if (npth_mutex_init (&app_list_lock, NULL))
1100     {
1101       err = gpg_error_from_syserror ();
1102       log_error ("app: error initializing mutex: %s\n", gpg_strerror (err));
1103       return err;
1104     }
1105
1106   return apdu_init ();
1107 }
1108
1109 void
1110 app_send_card_list (ctrl_t ctrl)
1111 {
1112   app_t a;
1113   char buf[65];
1114
1115   npth_mutex_lock (&app_list_lock);
1116   for (a = app_top; a; a = a->next)
1117     {
1118       if (DIM (buf) < 2 * a->serialnolen + 1)
1119         continue;
1120
1121       bin2hex (a->serialno, a->serialnolen, buf);
1122       send_status_direct (ctrl, "SERIALNO", buf);
1123     }
1124   npth_mutex_unlock (&app_list_lock);
1125 }