[scd] Memory leak fix.
[gnupg.git] / scd / command.c
blobb70455eecc94231003ea087fd927e98e4b3c2f5f
1 /* command.c - SCdaemon command handler
2 * Copyright (C) 2001, 2002, 2003, 2004, 2005,
3 * 2007, 2008, 2009 Free Software Foundation, Inc.
5 * This file is part of GnuPG.
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * GnuPG is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, see <http://www.gnu.org/licenses/>.
21 #include <config.h>
22 #include <errno.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <ctype.h>
27 #include <unistd.h>
28 #include <signal.h>
29 #ifdef USE_GNU_PTH
30 # include <pth.h>
31 #endif
33 #include "scdaemon.h"
34 #include <assuan.h>
35 #include <ksba.h>
36 #include "app-common.h"
37 #include "apdu.h" /* Required for apdu_*_reader (). */
38 #include "exechelp.h"
39 #ifdef HAVE_LIBUSB
40 #include "ccid-driver.h"
41 #endif
43 /* Maximum length allowed as a PIN; used for INQUIRE NEEDPIN */
44 #define MAXLEN_PIN 100
46 /* Maximum allowed size of key data as used in inquiries. */
47 #define MAXLEN_KEYDATA 4096
49 /* Maximum allowed size of certificate data as used in inquiries. */
50 #define MAXLEN_CERTDATA 16384
53 #define set_error(e,t) assuan_set_error (ctx, gpg_error (e), (t))
56 /* Macro to flag a removed card. ENODEV is also tested to catch teh
57 case of a removed reader. */
58 #define TEST_CARD_REMOVAL(c,r) \
59 do { \
60 int _r = (r); \
61 if (gpg_err_code (_r) == GPG_ERR_CARD_NOT_PRESENT \
62 || gpg_err_code (_r) == GPG_ERR_CARD_REMOVED \
63 || gpg_err_code (_r) == GPG_ERR_ENODEV ) \
64 update_card_removed ((c)->reader_slot, 1); \
65 } while (0)
67 #define IS_LOCKED(c) \
68 (locked_session && locked_session != (c)->server_local \
69 && (c)->reader_slot != -1 && locked_session->ctrl_backlink \
70 && (c)->reader_slot == locked_session->ctrl_backlink->reader_slot)
73 /* This structure is used to keep track of open readers (slots). */
74 struct slot_status_s
76 int valid; /* True if the other objects are valid. */
77 int slot; /* Slot number of the reader or -1 if not open. */
79 int reset_failed; /* A reset failed. */
81 int any; /* Flag indicating whether any status check has been
82 done. This is set once to indicate that the status
83 tracking for the slot has been initialized. */
84 unsigned int status; /* Last status of the slot. */
85 unsigned int changed; /* Last change counter of the slot. */
89 /* Data used to associate an Assuan context with local server data.
90 This object describes the local properties of one session. */
91 struct server_local_s
93 /* We keep a list of all active sessions with the anchor at
94 SESSION_LIST (see below). This field is used for linking. */
95 struct server_local_s *next_session;
97 /* This object is usually assigned to a CTRL object (which is
98 globally visible). While enumerating all sessions we sometimes
99 need to access data of the CTRL object; thus we keep a
100 backpointer here. */
101 ctrl_t ctrl_backlink;
103 /* The Assuan context used by this session/server. */
104 assuan_context_t assuan_ctx;
106 #ifdef HAVE_W32_SYSTEM
107 unsigned long event_signal; /* Or 0 if not used. */
108 #else
109 int event_signal; /* Or 0 if not used. */
110 #endif
112 /* True if the card has been removed and a reset is required to
113 continue operation. */
114 int card_removed;
116 /* Flag indicating that the application context needs to be released
117 at the next opportunity. */
118 int app_ctx_marked_for_release;
120 /* A disconnect command has been sent. */
121 int disconnect_allowed;
123 /* If set to true we will be terminate ourself at the end of the
124 this session. */
125 int stopme;
130 /* The table with information on all used slots. FIXME: This is a
131 different slot number than the one used by the APDU layer, and
132 should be renamed. */
133 static struct slot_status_s slot_table[10];
136 /* To keep track of all running sessions, we link all active server
137 contexts and the anchor in this variable. */
138 static struct server_local_s *session_list;
140 /* If a session has been locked we store a link to its server object
141 in this variable. */
142 static struct server_local_s *locked_session;
144 /* While doing a reset we need to make sure that the ticker does not
145 call scd_update_reader_status_file while we are using it. */
146 static pth_mutex_t status_file_update_lock;
149 /*-- Local prototypes --*/
150 static void update_reader_status_file (int set_card_removed_flag);
155 /* This function must be called once to initialize this module. This
156 has to be done before a second thread is spawned. We can't do the
157 static initialization because Pth emulation code might not be able
158 to do a static init; in particular, it is not possible for W32. */
159 void
160 initialize_module_command (void)
162 static int initialized;
164 if (!initialized)
166 if (pth_mutex_init (&status_file_update_lock))
167 initialized = 1;
172 /* Update the CARD_REMOVED element of all sessions using the reader
173 given by SLOT to VALUE. */
174 static void
175 update_card_removed (int slot, int value)
177 struct server_local_s *sl;
179 for (sl=session_list; sl; sl = sl->next_session)
180 if (sl->ctrl_backlink
181 && sl->ctrl_backlink->reader_slot == slot)
183 sl->card_removed = value;
185 /* Let the card application layer know about the removal. */
186 if (value)
187 application_notify_card_reset (slot);
192 /* Check whether the option NAME appears in LINE. Returns 1 or 0. */
193 static int
194 has_option (const char *line, const char *name)
196 const char *s;
197 int n = strlen (name);
199 s = strstr (line, name);
200 return (s && (s == line || spacep (s-1)) && (!s[n] || spacep (s+n)));
203 /* Same as has_option but does only test for the name of the option
204 and ignores an argument, i.e. with NAME being "--hash" it would
205 return a pointer for "--hash" as well as for "--hash=foo". If
206 there is no such option NULL is returned. The pointer returned
207 points right behind the option name, this may be an equal sign, Nul
208 or a space. */
209 static const char *
210 has_option_name (const char *line, const char *name)
212 const char *s;
213 int n = strlen (name);
215 s = strstr (line, name);
216 return (s && (s == line || spacep (s-1))
217 && (!s[n] || spacep (s+n) || s[n] == '=')) ? (s+n) : NULL;
221 /* Skip over options. It is assumed that leading spaces have been
222 removed (this is the case for lines passed to a handler from
223 assuan). Blanks after the options are also removed. */
224 static char *
225 skip_options (char *line)
227 while ( *line == '-' && line[1] == '-' )
229 while (*line && !spacep (line))
230 line++;
231 while (spacep (line))
232 line++;
234 return line;
239 /* Convert the STRING into a newly allocated buffer while translating
240 the hex numbers. Stops at the first invalid character. Blanks and
241 colons are allowed to separate the hex digits. Returns NULL on
242 error or a newly malloced buffer and its length in LENGTH. */
243 static unsigned char *
244 hex_to_buffer (const char *string, size_t *r_length)
246 unsigned char *buffer;
247 const char *s;
248 size_t n;
250 buffer = xtrymalloc (strlen (string)+1);
251 if (!buffer)
252 return NULL;
253 for (s=string, n=0; *s; s++)
255 if (spacep (s) || *s == ':')
256 continue;
257 if (hexdigitp (s) && hexdigitp (s+1))
259 buffer[n++] = xtoi_2 (s);
260 s++;
262 else
263 break;
265 *r_length = n;
266 return buffer;
271 /* Reset the card and free the application context. With SEND_RESET
272 set to true actually send a RESET to the reader; this is the normal
273 way of calling the function. */
274 static void
275 do_reset (ctrl_t ctrl, int send_reset)
277 int slot = ctrl->reader_slot;
279 if (!(slot == -1 || (slot >= 0 && slot < DIM(slot_table))))
280 BUG ();
282 /* If there is an active application, release it. Tell all other
283 sessions using the same application to release the
284 application. */
285 if (ctrl->app_ctx)
287 release_application (ctrl->app_ctx);
288 ctrl->app_ctx = NULL;
289 if (send_reset)
291 struct server_local_s *sl;
293 for (sl=session_list; sl; sl = sl->next_session)
294 if (sl->ctrl_backlink
295 && sl->ctrl_backlink->reader_slot == slot)
297 sl->app_ctx_marked_for_release = 1;
302 /* If we want a real reset for the card, send the reset APDU and
303 tell the application layer about it. */
304 if (slot != -1 && send_reset && !IS_LOCKED (ctrl) )
306 if (apdu_reset (slot))
308 slot_table[slot].reset_failed = 1;
310 application_notify_card_reset (slot);
313 /* If we hold a lock, unlock now. */
314 if (locked_session && ctrl->server_local == locked_session)
316 locked_session = NULL;
317 log_info ("implicitly unlocking due to RESET\n");
320 /* Reset the card removed flag for the current reader. We need to
321 take the lock here so that the ticker thread won't concurrently
322 try to update the file. Calling update_reader_status_file is
323 required to get hold of the new status of the card in the slot
324 table. */
325 if (!pth_mutex_acquire (&status_file_update_lock, 0, NULL))
327 log_error ("failed to acquire status_fle_update lock\n");
328 ctrl->reader_slot = -1;
329 return;
331 update_reader_status_file (0); /* Update slot status table. */
332 update_card_removed (slot, 0); /* Clear card_removed flag. */
333 if (!pth_mutex_release (&status_file_update_lock))
334 log_error ("failed to release status_file_update lock\n");
336 /* Do this last, so that the update_card_removed above does its job. */
337 ctrl->reader_slot = -1;
341 static void
342 reset_notify (assuan_context_t ctx)
344 ctrl_t ctrl = assuan_get_pointer (ctx);
346 do_reset (ctrl, 1);
350 static gpg_error_t
351 option_handler (assuan_context_t ctx, const char *key, const char *value)
353 ctrl_t ctrl = assuan_get_pointer (ctx);
355 if (!strcmp (key, "event-signal"))
357 /* A value of 0 is allowed to reset the event signal. */
358 #ifdef HAVE_W32_SYSTEM
359 if (!*value)
360 return gpg_error (GPG_ERR_ASS_PARAMETER);
361 ctrl->server_local->event_signal = strtoul (value, NULL, 16);
362 #else
363 int i = *value? atoi (value) : -1;
364 if (i < 0)
365 return gpg_error (GPG_ERR_ASS_PARAMETER);
366 ctrl->server_local->event_signal = i;
367 #endif
370 return 0;
374 /* Return the slot of the current reader or open the reader if no
375 other sessions are using a reader. Note, that we currently support
376 only one reader but most of the code (except for this function)
377 should be able to cope with several readers. */
378 static int
379 get_reader_slot (void)
381 struct slot_status_s *ss;
383 ss = &slot_table[0]; /* One reader for now. */
385 /* Initialize the item if needed. */
386 if (!ss->valid)
388 ss->slot = -1;
389 ss->valid = 1;
392 /* Try to open the reader. */
393 if (ss->slot == -1)
394 ss->slot = apdu_open_reader (opt.reader_port);
396 /* Return the slot_table index. */
397 return 0;
400 /* If the card has not yet been opened, do it. Note that this
401 function returns an Assuan error, so don't map the error a second
402 time. */
403 static gpg_error_t
404 open_card (ctrl_t ctrl, const char *apptype)
406 gpg_error_t err;
407 int slot;
409 /* If we ever got a card not present error code, return that. Only
410 the SERIALNO command and a reset are able to clear from that
411 state. */
412 if (ctrl->server_local->card_removed)
413 return gpg_error (GPG_ERR_CARD_REMOVED);
415 if ( IS_LOCKED (ctrl) )
416 return gpg_error (GPG_ERR_LOCKED);
418 /* If the application has been marked for release do it now. We
419 can't do it immediately in do_reset because the application may
420 still be in use. */
421 if (ctrl->server_local->app_ctx_marked_for_release)
423 ctrl->server_local->app_ctx_marked_for_release = 0;
424 release_application (ctrl->app_ctx);
425 ctrl->app_ctx = NULL;
428 /* If we are already initialized for one specific application we
429 need to check that the client didn't requested a specific
430 application different from the one in use before we continue. */
431 if (ctrl->app_ctx)
432 return check_application_conflict (ctrl, apptype);
434 /* Setup the slot and select the application. */
435 if (ctrl->reader_slot != -1)
436 slot = ctrl->reader_slot;
437 else
438 slot = get_reader_slot ();
439 ctrl->reader_slot = slot;
440 if (slot == -1)
441 err = gpg_error (GPG_ERR_CARD);
442 else
444 /* Fixme: We should move the apdu_connect call to
445 select_application. */
446 int sw;
448 ctrl->server_local->disconnect_allowed = 0;
449 sw = apdu_connect (slot);
450 if (sw && sw != SW_HOST_ALREADY_CONNECTED)
452 if (sw == SW_HOST_NO_CARD)
453 err = gpg_error (GPG_ERR_CARD_NOT_PRESENT);
454 else
455 err = gpg_error (GPG_ERR_CARD);
457 else
458 err = select_application (ctrl, slot, apptype, &ctrl->app_ctx);
461 TEST_CARD_REMOVAL (ctrl, err);
462 return err;
466 /* SERIALNO [APPTYPE]
468 Return the serial number of the card using a status reponse. This
469 function should be used to check for the presence of a card.
471 If APPTYPE is given, an application of that type is selected and an
472 error is returned if the application is not supported or available.
473 The default is to auto-select the application using a hardwired
474 preference system. Note, that a future extension to this function
475 may allow to specify a list and order of applications to try.
477 This function is special in that it can be used to reset the card.
478 Most other functions will return an error when a card change has
479 been detected and the use of this function is therefore required.
481 Background: We want to keep the client clear of handling card
482 changes between operations; i.e. the client can assume that all
483 operations are done on the same card unless he calls this function.
485 static gpg_error_t
486 cmd_serialno (assuan_context_t ctx, char *line)
488 ctrl_t ctrl = assuan_get_pointer (ctx);
489 int rc = 0;
490 char *serial_and_stamp;
491 char *serial;
492 time_t stamp;
494 /* Clear the remove flag so that the open_card is able to reread it. */
495 if (ctrl->server_local->card_removed)
497 if ( IS_LOCKED (ctrl) )
498 return gpg_error (GPG_ERR_LOCKED);
499 do_reset (ctrl, 1);
502 if ((rc = open_card (ctrl, *line? line:NULL)))
503 return rc;
505 rc = app_get_serial_and_stamp (ctrl->app_ctx, &serial, &stamp);
506 if (rc)
507 return rc;
509 rc = estream_asprintf (&serial_and_stamp, "%s %lu",
510 serial, (unsigned long)stamp);
511 xfree (serial);
512 if (rc < 0)
513 return out_of_core ();
514 rc = 0;
515 assuan_write_status (ctx, "SERIALNO", serial_and_stamp);
516 xfree (serial_and_stamp);
517 return 0;
523 /* LEARN [--force] [--keypairinfo]
525 Learn all useful information of the currently inserted card. When
526 used without the force options, the command might do an INQUIRE
527 like this:
529 INQUIRE KNOWNCARDP <hexstring_with_serialNumber> <timestamp>
531 The client should just send an "END" if the processing should go on
532 or a "CANCEL" to force the function to terminate with a Cancel
533 error message.
535 With the option --keypairinfo only KEYPARIINFO lstatus lines are
536 returned.
538 The response of this command is a list of status lines formatted as
539 this:
541 S APPTYPE <apptype>
543 This returns the type of the application, currently the strings:
545 P15 = PKCS-15 structure used
546 DINSIG = DIN SIG
547 OPENPGP = OpenPGP card
548 NKS = NetKey card
550 are implemented. These strings are aliases for the AID
552 S KEYPAIRINFO <hexstring_with_keygrip> <hexstring_with_id>
554 If there is no certificate yet stored on the card a single "X" is
555 returned as the keygrip. In addition to the keypair info, information
556 about all certificates stored on the card is also returned:
558 S CERTINFO <certtype> <hexstring_with_id>
560 Where CERTTYPE is a number indicating the type of certificate:
561 0 := Unknown
562 100 := Regular X.509 cert
563 101 := Trusted X.509 cert
564 102 := Useful X.509 cert
565 110 := Root CA cert in a special format (e.g. DINSIG)
566 111 := Root CA cert as standard X509 cert.
568 For certain cards, more information will be returned:
570 S KEY-FPR <no> <hexstring>
572 For OpenPGP cards this returns the stored fingerprints of the
573 keys. This can be used check whether a key is available on the
574 card. NO may be 1, 2 or 3.
576 S CA-FPR <no> <hexstring>
578 Similar to above, these are the fingerprints of keys assumed to be
579 ultimately trusted.
581 S DISP-NAME <name_of_card_holder>
583 The name of the card holder as stored on the card; percent
584 escaping takes place, spaces are encoded as '+'
586 S PUBKEY-URL <url>
588 The URL to be used for locating the entire public key.
590 Note, that this function may even be used on a locked card.
592 static gpg_error_t
593 cmd_learn (assuan_context_t ctx, char *line)
595 ctrl_t ctrl = assuan_get_pointer (ctx);
596 int rc = 0;
597 int only_keypairinfo = has_option (line, "--keypairinfo");
599 if ((rc = open_card (ctrl, NULL)))
600 return rc;
602 /* Unless the force option is used we try a shortcut by identifying
603 the card using a serial number and inquiring the client with
604 that. The client may choose to cancel the operation if he already
605 knows about this card */
606 if (!only_keypairinfo)
608 char *serial_and_stamp;
609 char *serial;
610 time_t stamp;
612 rc = app_get_serial_and_stamp (ctrl->app_ctx, &serial, &stamp);
613 if (rc)
614 return rc;
615 rc = estream_asprintf (&serial_and_stamp, "%s %lu",
616 serial, (unsigned long)stamp);
617 xfree (serial);
618 if (rc < 0)
619 return out_of_core ();
620 rc = 0;
621 assuan_write_status (ctx, "SERIALNO", serial_and_stamp);
623 if (!has_option (line, "--force"))
625 char *command;
627 rc = estream_asprintf (&command, "KNOWNCARDP %s", serial_and_stamp);
628 if (rc < 0)
630 xfree (serial_and_stamp);
631 return out_of_core ();
633 rc = 0;
634 rc = assuan_inquire (ctx, command, NULL, NULL, 0);
635 xfree (command);
636 if (rc)
638 if (gpg_err_code (rc) != GPG_ERR_ASS_CANCELED)
639 log_error ("inquire KNOWNCARDP failed: %s\n",
640 gpg_strerror (rc));
641 xfree (serial_and_stamp);
642 return rc;
644 /* Not canceled, so we have to proceeed. */
646 xfree (serial_and_stamp);
649 /* Let the application print out its collection of useful status
650 information. */
651 if (!rc)
652 rc = app_write_learn_status (ctrl->app_ctx, ctrl, only_keypairinfo);
654 TEST_CARD_REMOVAL (ctrl, rc);
655 return rc;
660 /* READCERT <hexified_certid>|<keyid>
662 Note, that this function may even be used on a locked card.
664 static gpg_error_t
665 cmd_readcert (assuan_context_t ctx, char *line)
667 ctrl_t ctrl = assuan_get_pointer (ctx);
668 int rc;
669 unsigned char *cert;
670 size_t ncert;
672 if ((rc = open_card (ctrl, NULL)))
673 return rc;
675 line = xstrdup (line); /* Need a copy of the line. */
676 rc = app_readcert (ctrl->app_ctx, line, &cert, &ncert);
677 if (rc)
678 log_error ("app_readcert failed: %s\n", gpg_strerror (rc));
679 xfree (line);
680 line = NULL;
681 if (!rc)
683 rc = assuan_send_data (ctx, cert, ncert);
684 xfree (cert);
685 if (rc)
686 return rc;
689 TEST_CARD_REMOVAL (ctrl, rc);
690 return rc;
694 /* READKEY <keyid>
696 Return the public key for the given cert or key ID as an standard
697 S-Expression.
699 Note, that this function may even be used on a locked card.
701 static gpg_error_t
702 cmd_readkey (assuan_context_t ctx, char *line)
704 ctrl_t ctrl = assuan_get_pointer (ctx);
705 int rc;
706 unsigned char *cert = NULL;
707 size_t ncert, n;
708 ksba_cert_t kc = NULL;
709 ksba_sexp_t p;
710 unsigned char *pk;
711 size_t pklen;
713 if ((rc = open_card (ctrl, NULL)))
714 return rc;
716 line = xstrdup (line); /* Need a copy of the line. */
717 /* If the application supports the READKEY function we use that.
718 Otherwise we use the old way by extracting it from the
719 certificate. */
720 rc = app_readkey (ctrl->app_ctx, line, &pk, &pklen);
721 if (!rc)
722 { /* Yeah, got that key - send it back. */
723 rc = assuan_send_data (ctx, pk, pklen);
724 xfree (pk);
725 xfree (line);
726 line = NULL;
727 goto leave;
730 if (gpg_err_code (rc) != GPG_ERR_UNSUPPORTED_OPERATION)
731 log_error ("app_readkey failed: %s\n", gpg_strerror (rc));
732 else
734 rc = app_readcert (ctrl->app_ctx, line, &cert, &ncert);
735 if (rc)
736 log_error ("app_readcert failed: %s\n", gpg_strerror (rc));
738 xfree (line);
739 line = NULL;
740 if (rc)
741 goto leave;
743 rc = ksba_cert_new (&kc);
744 if (rc)
746 xfree (cert);
747 goto leave;
749 rc = ksba_cert_init_from_mem (kc, cert, ncert);
750 if (rc)
752 log_error ("failed to parse the certificate: %s\n", gpg_strerror (rc));
753 goto leave;
756 p = ksba_cert_get_public_key (kc);
757 if (!p)
759 rc = gpg_error (GPG_ERR_NO_PUBKEY);
760 goto leave;
763 n = gcry_sexp_canon_len (p, 0, NULL, NULL);
764 rc = assuan_send_data (ctx, p, n);
765 xfree (p);
768 leave:
769 ksba_cert_release (kc);
770 xfree (cert);
771 TEST_CARD_REMOVAL (ctrl, rc);
772 return rc;
778 /* SETDATA <hexstring>
780 The client should use this command to tell us the data he want to
781 sign. */
782 static gpg_error_t
783 cmd_setdata (assuan_context_t ctx, char *line)
785 ctrl_t ctrl = assuan_get_pointer (ctx);
786 int n;
787 char *p;
788 unsigned char *buf;
790 if (locked_session && locked_session != ctrl->server_local)
791 return gpg_error (GPG_ERR_LOCKED);
793 /* Parse the hexstring. */
794 for (p=line,n=0; hexdigitp (p); p++, n++)
796 if (*p)
797 return set_error (GPG_ERR_ASS_PARAMETER, "invalid hexstring");
798 if (!n)
799 return set_error (GPG_ERR_ASS_PARAMETER, "no data given");
800 if ((n&1))
801 return set_error (GPG_ERR_ASS_PARAMETER, "odd number of digits");
802 n /= 2;
803 buf = xtrymalloc (n);
804 if (!buf)
805 return out_of_core ();
807 xfree (ctrl->in_data.value);
808 ctrl->in_data.value = buf;
809 ctrl->in_data.valuelen = n;
810 for (p=line, n=0; n < ctrl->in_data.valuelen; p += 2, n++)
811 buf[n] = xtoi_2 (p);
812 return 0;
817 static gpg_error_t
818 pin_cb (void *opaque, const char *info, char **retstr)
820 assuan_context_t ctx = opaque;
821 char *command;
822 int rc;
823 unsigned char *value;
824 size_t valuelen;
826 if (!retstr)
828 /* We prompt for keypad entry. To make sure that the popup has
829 been show we use an inquire and not just a status message.
830 We ignore any value returned. */
831 if (info)
833 log_debug ("prompting for keypad entry '%s'\n", info);
834 rc = estream_asprintf (&command, "POPUPKEYPADPROMPT %s", info);
835 if (rc < 0)
836 return gpg_error (gpg_err_code_from_errno (errno));
837 rc = assuan_inquire (ctx, command, &value, &valuelen, MAXLEN_PIN);
838 xfree (command);
840 else
842 log_debug ("dismiss keypad entry prompt\n");
843 rc = assuan_inquire (ctx, "DISMISSKEYPADPROMPT",
844 &value, &valuelen, MAXLEN_PIN);
846 if (!rc)
847 xfree (value);
848 return rc;
851 *retstr = NULL;
852 log_debug ("asking for PIN '%s'\n", info);
854 rc = estream_asprintf (&command, "NEEDPIN %s", info);
855 if (rc < 0)
856 return gpg_error (gpg_err_code_from_errno (errno));
858 /* Fixme: Write an inquire function which returns the result in
859 secure memory and check all further handling of the PIN. */
860 rc = assuan_inquire (ctx, command, &value, &valuelen, MAXLEN_PIN);
861 xfree (command);
862 if (rc)
863 return rc;
865 if (!valuelen || value[valuelen-1])
867 /* We require that the returned value is an UTF-8 string */
868 xfree (value);
869 return gpg_error (GPG_ERR_INV_RESPONSE);
871 *retstr = (char*)value;
872 return 0;
876 /* PKSIGN [--hash=[rmd160|sha{1,224,256,384,512}|md5]] <hexified_id>
878 The --hash option is optional; the default is SHA1.
881 static gpg_error_t
882 cmd_pksign (assuan_context_t ctx, char *line)
884 ctrl_t ctrl = assuan_get_pointer (ctx);
885 int rc;
886 unsigned char *outdata;
887 size_t outdatalen;
888 char *keyidstr;
889 int hash_algo;
891 if (has_option (line, "--hash=rmd160"))
892 hash_algo = GCRY_MD_RMD160;
893 else if (has_option (line, "--hash=sha1"))
894 hash_algo = GCRY_MD_SHA1;
895 else if (has_option (line, "--hash=sha224"))
896 hash_algo = GCRY_MD_SHA224;
897 else if (has_option (line, "--hash=sha256"))
898 hash_algo = GCRY_MD_SHA256;
899 else if (has_option (line, "--hash=sha384"))
900 hash_algo = GCRY_MD_SHA384;
901 else if (has_option (line, "--hash=sha512"))
902 hash_algo = GCRY_MD_SHA512;
903 else if (has_option (line, "--hash=md5"))
904 hash_algo = GCRY_MD_MD5;
905 else if (!strstr (line, "--"))
906 hash_algo = GCRY_MD_SHA1;
907 else
908 return set_error (GPG_ERR_ASS_PARAMETER, "invalid hash algorithm");
910 line = skip_options (line);
912 if ( IS_LOCKED (ctrl) )
913 return gpg_error (GPG_ERR_LOCKED);
915 if ((rc = open_card (ctrl, NULL)))
916 return rc;
918 /* We have to use a copy of the key ID because the function may use
919 the pin_cb which in turn uses the assuan line buffer and thus
920 overwriting the original line with the keyid */
921 keyidstr = xtrystrdup (line);
922 if (!keyidstr)
923 return out_of_core ();
925 rc = app_sign (ctrl->app_ctx,
926 keyidstr, hash_algo,
927 pin_cb, ctx,
928 ctrl->in_data.value, ctrl->in_data.valuelen,
929 &outdata, &outdatalen);
931 xfree (keyidstr);
932 if (rc)
934 log_error ("app_sign failed: %s\n", gpg_strerror (rc));
936 else
938 rc = assuan_send_data (ctx, outdata, outdatalen);
939 xfree (outdata);
940 if (rc)
941 return rc; /* that is already an assuan error code */
944 TEST_CARD_REMOVAL (ctrl, rc);
945 return rc;
948 /* PKAUTH <hexified_id>
951 static gpg_error_t
952 cmd_pkauth (assuan_context_t ctx, char *line)
954 ctrl_t ctrl = assuan_get_pointer (ctx);
955 int rc;
956 unsigned char *outdata;
957 size_t outdatalen;
958 char *keyidstr;
960 if ( IS_LOCKED (ctrl) )
961 return gpg_error (GPG_ERR_LOCKED);
963 if ((rc = open_card (ctrl, NULL)))
964 return rc;
966 if (!ctrl->app_ctx)
967 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
969 /* We have to use a copy of the key ID because the function may use
970 the pin_cb which in turn uses the assuan line buffer and thus
971 overwriting the original line with the keyid */
972 keyidstr = xtrystrdup (line);
973 if (!keyidstr)
974 return out_of_core ();
976 rc = app_auth (ctrl->app_ctx,
977 keyidstr,
978 pin_cb, ctx,
979 ctrl->in_data.value, ctrl->in_data.valuelen,
980 &outdata, &outdatalen);
981 xfree (keyidstr);
982 if (rc)
984 log_error ("app_auth failed: %s\n", gpg_strerror (rc));
986 else
988 rc = assuan_send_data (ctx, outdata, outdatalen);
989 xfree (outdata);
990 if (rc)
991 return rc; /* that is already an assuan error code */
994 TEST_CARD_REMOVAL (ctrl, rc);
995 return rc;
998 /* PKDECRYPT <hexified_id>
1001 static gpg_error_t
1002 cmd_pkdecrypt (assuan_context_t ctx, char *line)
1004 ctrl_t ctrl = assuan_get_pointer (ctx);
1005 int rc;
1006 unsigned char *outdata;
1007 size_t outdatalen;
1008 char *keyidstr;
1010 if ( IS_LOCKED (ctrl) )
1011 return gpg_error (GPG_ERR_LOCKED);
1013 if ((rc = open_card (ctrl, NULL)))
1014 return rc;
1016 keyidstr = xtrystrdup (line);
1017 if (!keyidstr)
1018 return out_of_core ();
1019 rc = app_decipher (ctrl->app_ctx,
1020 keyidstr,
1021 pin_cb, ctx,
1022 ctrl->in_data.value, ctrl->in_data.valuelen,
1023 &outdata, &outdatalen);
1025 xfree (keyidstr);
1026 if (rc)
1028 log_error ("app_decipher failed: %s\n", gpg_strerror (rc));
1030 else
1032 rc = assuan_send_data (ctx, outdata, outdatalen);
1033 xfree (outdata);
1034 if (rc)
1035 return rc; /* that is already an assuan error code */
1038 TEST_CARD_REMOVAL (ctrl, rc);
1039 return rc;
1043 /* GETATTR <name>
1045 This command is used to retrieve data from a smartcard. The
1046 allowed names depend on the currently selected smartcard
1047 application. NAME must be percent and '+' escaped. The value is
1048 returned through status message, see the LEARN command for details.
1050 However, the current implementation assumes that Name is not escaped;
1051 this works as long as noone uses arbitrary escaping.
1053 Note, that this function may even be used on a locked card.
1055 static gpg_error_t
1056 cmd_getattr (assuan_context_t ctx, char *line)
1058 ctrl_t ctrl = assuan_get_pointer (ctx);
1059 int rc;
1060 const char *keyword;
1062 if ((rc = open_card (ctrl, NULL)))
1063 return rc;
1065 keyword = line;
1066 for (; *line && !spacep (line); line++)
1068 if (*line)
1069 *line++ = 0;
1071 /* (We ignore any garbage for now.) */
1073 /* FIXME: Applications should not return sensitive data if the card
1074 is locked. */
1075 rc = app_getattr (ctrl->app_ctx, ctrl, keyword);
1077 TEST_CARD_REMOVAL (ctrl, rc);
1078 return rc;
1082 /* SETATTR <name> <value>
1084 This command is used to store data on a a smartcard. The allowed
1085 names and values are depend on the currently selected smartcard
1086 application. NAME and VALUE must be percent and '+' escaped.
1088 However, the current implementation assumes that NAME is not
1089 escaped; this works as long as noone uses arbitrary escaping.
1091 A PIN will be requested for most NAMEs. See the corresponding
1092 setattr function of the actually used application (app-*.c) for
1093 details. */
1094 static gpg_error_t
1095 cmd_setattr (assuan_context_t ctx, char *orig_line)
1097 ctrl_t ctrl = assuan_get_pointer (ctx);
1098 int rc;
1099 char *keyword;
1100 int keywordlen;
1101 size_t nbytes;
1102 char *line, *linebuf;
1104 if ( IS_LOCKED (ctrl) )
1105 return gpg_error (GPG_ERR_LOCKED);
1107 if ((rc = open_card (ctrl, NULL)))
1108 return rc;
1110 /* We need to use a copy of LINE, because PIN_CB uses the same
1111 context and thus reuses the Assuan provided LINE. */
1112 line = linebuf = xtrystrdup (orig_line);
1113 if (!line)
1114 return out_of_core ();
1116 keyword = line;
1117 for (keywordlen=0; *line && !spacep (line); line++, keywordlen++)
1119 if (*line)
1120 *line++ = 0;
1121 while (spacep (line))
1122 line++;
1123 nbytes = percent_plus_unescape_inplace (line, 0);
1125 rc = app_setattr (ctrl->app_ctx, keyword, pin_cb, ctx,
1126 (const unsigned char*)line, nbytes);
1127 xfree (linebuf);
1129 TEST_CARD_REMOVAL (ctrl, rc);
1130 return rc;
1135 /* WRITECERT <hexified_certid>
1137 This command is used to store a certifciate on a smartcard. The
1138 allowed certids depend on the currently selected smartcard
1139 application. The actual certifciate is requested using the inquiry
1140 "CERTDATA" and needs to be provided in its raw (e.g. DER) form.
1142 In almost all cases a a PIN will be requested. See the related
1143 writecert function of the actually used application (app-*.c) for
1144 details. */
1145 static gpg_error_t
1146 cmd_writecert (assuan_context_t ctx, char *line)
1148 ctrl_t ctrl = assuan_get_pointer (ctx);
1149 int rc;
1150 char *certid;
1151 unsigned char *certdata;
1152 size_t certdatalen;
1154 if ( IS_LOCKED (ctrl) )
1155 return gpg_error (GPG_ERR_LOCKED);
1157 line = skip_options (line);
1159 if (!*line)
1160 return set_error (GPG_ERR_ASS_PARAMETER, "no certid given");
1161 certid = line;
1162 while (*line && !spacep (line))
1163 line++;
1164 *line = 0;
1166 if ((rc = open_card (ctrl, NULL)))
1167 return rc;
1169 if (!ctrl->app_ctx)
1170 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
1172 certid = xtrystrdup (certid);
1173 if (!certid)
1174 return out_of_core ();
1176 /* Now get the actual keydata. */
1177 rc = assuan_inquire (ctx, "CERTDATA",
1178 &certdata, &certdatalen, MAXLEN_CERTDATA);
1179 if (rc)
1181 xfree (certid);
1182 return rc;
1185 /* Write the certificate to the card. */
1186 rc = app_writecert (ctrl->app_ctx, ctrl, certid,
1187 pin_cb, ctx, certdata, certdatalen);
1188 xfree (certid);
1189 xfree (certdata);
1191 TEST_CARD_REMOVAL (ctrl, rc);
1192 return rc;
1197 /* WRITEKEY [--force] <keyid>
1199 This command is used to store a secret key on a a smartcard. The
1200 allowed keyids depend on the currently selected smartcard
1201 application. The actual keydata is requested using the inquiry
1202 "KEYDATA" and need to be provided without any protection. With
1203 --force set an existing key under this KEYID will get overwritten.
1204 The keydata is expected to be the usual canonical encoded
1205 S-expression.
1207 A PIN will be requested for most NAMEs. See the corresponding
1208 writekey function of the actually used application (app-*.c) for
1209 details. */
1210 static gpg_error_t
1211 cmd_writekey (assuan_context_t ctx, char *line)
1213 ctrl_t ctrl = assuan_get_pointer (ctx);
1214 int rc;
1215 char *keyid;
1216 int force = has_option (line, "--force");
1217 unsigned char *keydata;
1218 size_t keydatalen;
1220 if ( IS_LOCKED (ctrl) )
1221 return gpg_error (GPG_ERR_LOCKED);
1223 line = skip_options (line);
1225 if (!*line)
1226 return set_error (GPG_ERR_ASS_PARAMETER, "no keyid given");
1227 keyid = line;
1228 while (*line && !spacep (line))
1229 line++;
1230 *line = 0;
1232 if ((rc = open_card (ctrl, NULL)))
1233 return rc;
1235 if (!ctrl->app_ctx)
1236 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
1238 keyid = xtrystrdup (keyid);
1239 if (!keyid)
1240 return out_of_core ();
1242 /* Now get the actual keydata. */
1243 assuan_begin_confidential (ctx);
1244 rc = assuan_inquire (ctx, "KEYDATA", &keydata, &keydatalen, MAXLEN_KEYDATA);
1245 assuan_end_confidential (ctx);
1246 if (rc)
1248 xfree (keyid);
1249 return rc;
1252 /* Write the key to the card. */
1253 rc = app_writekey (ctrl->app_ctx, ctrl, keyid, force? 1:0,
1254 pin_cb, ctx, keydata, keydatalen);
1255 xfree (keyid);
1256 xfree (keydata);
1258 TEST_CARD_REMOVAL (ctrl, rc);
1259 return rc;
1264 /* GENKEY [--force] [--timestamp=<isodate>] <no>
1266 Generate a key on-card identified by NO, which is application
1267 specific. Return values are application specific. For OpenPGP
1268 cards 2 status lines are returned:
1270 S KEY-FPR <hexstring>
1271 S KEY-CREATED-AT <seconds_since_epoch>
1272 S KEY-DATA [p|n] <hexdata>
1274 --force is required to overwrite an already existing key. The
1275 KEY-CREATED-AT is required for further processing because it is
1276 part of the hashed key material for the fingerprint.
1278 If --timestamp is given an OpenPGP key will be created using this
1279 value. The value needs to be in ISO Format; e.g.
1280 "--timestamp=20030316T120000" and after 1970-01-01 00:00:00.
1282 The public part of the key can also later be retrieved using the
1283 READKEY command.
1286 static gpg_error_t
1287 cmd_genkey (assuan_context_t ctx, char *line)
1289 ctrl_t ctrl = assuan_get_pointer (ctx);
1290 int rc;
1291 char *keyno;
1292 int force;
1293 const char *s;
1294 time_t timestamp;
1296 if ( IS_LOCKED (ctrl) )
1297 return gpg_error (GPG_ERR_LOCKED);
1299 force = has_option (line, "--force");
1301 if ((s=has_option_name (line, "--timestamp")))
1303 if (*s != '=')
1304 return set_error (GPG_ERR_ASS_PARAMETER, "missing value for option");
1305 timestamp = isotime2epoch (s+1);
1306 if (timestamp < 1)
1307 return set_error (GPG_ERR_ASS_PARAMETER, "invalid time value");
1309 else
1310 timestamp = 0;
1313 line = skip_options (line);
1314 if (!*line)
1315 return set_error (GPG_ERR_ASS_PARAMETER, "no key number given");
1316 keyno = line;
1317 while (*line && !spacep (line))
1318 line++;
1319 *line = 0;
1321 if ((rc = open_card (ctrl, NULL)))
1322 return rc;
1324 if (!ctrl->app_ctx)
1325 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
1327 keyno = xtrystrdup (keyno);
1328 if (!keyno)
1329 return out_of_core ();
1330 rc = app_genkey (ctrl->app_ctx, ctrl, keyno, force? 1:0,
1331 timestamp, pin_cb, ctx);
1332 xfree (keyno);
1334 TEST_CARD_REMOVAL (ctrl, rc);
1335 return rc;
1339 /* RANDOM <nbytes>
1341 Get NBYTES of random from the card and send them back as data.
1343 Note, that this function may be even be used on a locked card.
1345 static gpg_error_t
1346 cmd_random (assuan_context_t ctx, char *line)
1348 ctrl_t ctrl = assuan_get_pointer (ctx);
1349 int rc;
1350 size_t nbytes;
1351 unsigned char *buffer;
1353 if (!*line)
1354 return set_error (GPG_ERR_ASS_PARAMETER, "number of requested bytes missing");
1355 nbytes = strtoul (line, NULL, 0);
1357 if ((rc = open_card (ctrl, NULL)))
1358 return rc;
1360 if (!ctrl->app_ctx)
1361 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
1363 buffer = xtrymalloc (nbytes);
1364 if (!buffer)
1365 return out_of_core ();
1367 rc = app_get_challenge (ctrl->app_ctx, nbytes, buffer);
1368 if (!rc)
1370 rc = assuan_send_data (ctx, buffer, nbytes);
1371 xfree (buffer);
1372 return rc; /* that is already an assuan error code */
1374 xfree (buffer);
1376 TEST_CARD_REMOVAL (ctrl, rc);
1377 return rc;
1381 /* PASSWD [--reset] [--nullpin] <chvno>
1383 Change the PIN or, if --reset is given, reset the retry counter of
1384 the card holder verfication vector CHVNO. The option --nullpin is
1385 used for TCOS cards to set the initial PIN. The format of CHVNO
1386 depends on the card application. */
1387 static gpg_error_t
1388 cmd_passwd (assuan_context_t ctx, char *line)
1390 ctrl_t ctrl = assuan_get_pointer (ctx);
1391 int rc;
1392 char *chvnostr;
1393 unsigned int flags = 0;
1395 if (has_option (line, "--reset"))
1396 flags |= APP_CHANGE_FLAG_RESET;
1397 if (has_option (line, "--nullpin"))
1398 flags |= APP_CHANGE_FLAG_NULLPIN;
1400 if ( IS_LOCKED (ctrl) )
1401 return gpg_error (GPG_ERR_LOCKED);
1403 line = skip_options (line);
1405 if (!*line)
1406 return set_error (GPG_ERR_ASS_PARAMETER, "no CHV number given");
1407 chvnostr = line;
1408 while (*line && !spacep (line))
1409 line++;
1410 *line = 0;
1412 if ((rc = open_card (ctrl, NULL)))
1413 return rc;
1415 if (!ctrl->app_ctx)
1416 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
1418 chvnostr = xtrystrdup (chvnostr);
1419 if (!chvnostr)
1420 return out_of_core ();
1421 rc = app_change_pin (ctrl->app_ctx, ctrl, chvnostr, flags, pin_cb, ctx);
1422 if (rc)
1423 log_error ("command passwd failed: %s\n", gpg_strerror (rc));
1424 xfree (chvnostr);
1426 TEST_CARD_REMOVAL (ctrl, rc);
1427 return rc;
1431 /* CHECKPIN <idstr>
1433 Perform a VERIFY operation without doing anything else. This may
1434 be used to initialize a the PIN cache earlier to long lasting
1435 operations. Its use is highly application dependent.
1437 For OpenPGP:
1439 Perform a simple verify operation for CHV1 and CHV2, so that
1440 further operations won't ask for CHV2 and it is possible to do a
1441 cheap check on the PIN: If there is something wrong with the PIN
1442 entry system, only the regular CHV will get blocked and not the
1443 dangerous CHV3. IDSTR is the usual card's serial number in hex
1444 notation; an optional fingerprint part will get ignored. There
1445 is however a special mode if the IDSTR is sffixed with the
1446 literal string "[CHV3]": In this case the Admin PIN is checked
1447 if and only if the retry counter is still at 3.
1449 For Netkey:
1451 Any of the valid PIN Ids may be used. These are the strings:
1453 PW1.CH - Global password 1
1454 PW2.CH - Global password 2
1455 PW1.CH.SIG - SigG password 1
1456 PW2.CH.SIG - SigG password 2
1458 For a definitive list, see the implementation in app-nks.c.
1459 Note that we call a PW2.* PIN a "PUK" despite that since TCOS
1460 3.0 they are technically alternative PINs used to mutally
1461 unblock each other.
1464 static gpg_error_t
1465 cmd_checkpin (assuan_context_t ctx, char *line)
1467 ctrl_t ctrl = assuan_get_pointer (ctx);
1468 int rc;
1469 char *idstr;
1471 if ( IS_LOCKED (ctrl) )
1472 return gpg_error (GPG_ERR_LOCKED);
1474 if ((rc = open_card (ctrl, NULL)))
1475 return rc;
1477 if (!ctrl->app_ctx)
1478 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
1480 /* We have to use a copy of the key ID because the function may use
1481 the pin_cb which in turn uses the assuan line buffer and thus
1482 overwriting the original line with the keyid. */
1483 idstr = xtrystrdup (line);
1484 if (!idstr)
1485 return out_of_core ();
1487 rc = app_check_pin (ctrl->app_ctx, idstr, pin_cb, ctx);
1488 xfree (idstr);
1489 if (rc)
1490 log_error ("app_check_pin failed: %s\n", gpg_strerror (rc));
1492 TEST_CARD_REMOVAL (ctrl, rc);
1493 return rc;
1497 /* LOCK [--wait]
1499 Grant exclusive card access to this session. Note that there is
1500 no lock counter used and a second lock from the same session will
1501 be ignored. A single unlock (or RESET) unlocks the session.
1502 Return GPG_ERR_LOCKED if another session has locked the reader.
1504 If the option --wait is given the command will wait until a
1505 lock has been released.
1507 static gpg_error_t
1508 cmd_lock (assuan_context_t ctx, char *line)
1510 ctrl_t ctrl = assuan_get_pointer (ctx);
1511 int rc = 0;
1513 retry:
1514 if (locked_session)
1516 if (locked_session != ctrl->server_local)
1517 rc = gpg_error (GPG_ERR_LOCKED);
1519 else
1520 locked_session = ctrl->server_local;
1522 #ifdef USE_GNU_PTH
1523 if (rc && has_option (line, "--wait"))
1525 rc = 0;
1526 pth_sleep (1); /* Better implement an event mechanism. However,
1527 for card operations this should be
1528 sufficient. */
1529 /* FIXME: Need to check that the connection is still alive.
1530 This can be done by issuing status messages. */
1531 goto retry;
1533 #endif /*USE_GNU_PTH*/
1535 if (rc)
1536 log_error ("cmd_lock failed: %s\n", gpg_strerror (rc));
1537 return rc;
1541 /* UNLOCK
1543 Release exclusive card access.
1545 static gpg_error_t
1546 cmd_unlock (assuan_context_t ctx, char *line)
1548 ctrl_t ctrl = assuan_get_pointer (ctx);
1549 int rc = 0;
1551 (void)line;
1553 if (locked_session)
1555 if (locked_session != ctrl->server_local)
1556 rc = gpg_error (GPG_ERR_LOCKED);
1557 else
1558 locked_session = NULL;
1560 else
1561 rc = gpg_error (GPG_ERR_NOT_LOCKED);
1563 if (rc)
1564 log_error ("cmd_unlock failed: %s\n", gpg_strerror (rc));
1565 return rc;
1569 /* GETINFO <what>
1571 Multi purpose command to return certain information.
1572 Supported values of WHAT are:
1574 version - Return the version of the program.
1575 pid - Return the process id of the server.
1577 socket_name - Return the name of the socket.
1579 status - Return the status of the current slot (in the future, may
1580 also return the status of all slots). The status is a list of
1581 one-character flags. The following flags are currently defined:
1582 'u' Usable card present. This is the normal state during operation.
1583 'r' Card removed. A reset is necessary.
1584 These flags are exclusive.
1586 reader_list - Return a list of detected card readers. Does
1587 currently only work with the internal CCID driver.
1589 deny_admin - Returns OK if admin commands are not allowed or
1590 GPG_ERR_GENERAL if admin commands are allowed.
1592 app_list - Return a list of supported applications. One
1593 application per line, fields delimited by colons,
1594 first field is the name.
1597 static gpg_error_t
1598 cmd_getinfo (assuan_context_t ctx, char *line)
1600 int rc = 0;
1602 if (!strcmp (line, "version"))
1604 const char *s = VERSION;
1605 rc = assuan_send_data (ctx, s, strlen (s));
1607 else if (!strcmp (line, "pid"))
1609 char numbuf[50];
1611 snprintf (numbuf, sizeof numbuf, "%lu", (unsigned long)getpid ());
1612 rc = assuan_send_data (ctx, numbuf, strlen (numbuf));
1614 else if (!strcmp (line, "socket_name"))
1616 const char *s = scd_get_socket_name ();
1618 if (s)
1619 rc = assuan_send_data (ctx, s, strlen (s));
1620 else
1621 rc = gpg_error (GPG_ERR_NO_DATA);
1623 else if (!strcmp (line, "status"))
1625 ctrl_t ctrl = assuan_get_pointer (ctx);
1626 int slot = ctrl->reader_slot;
1627 char flag = 'r';
1629 if (!ctrl->server_local->card_removed && slot != -1)
1631 struct slot_status_s *ss;
1633 if (!(slot >= 0 && slot < DIM(slot_table)))
1634 BUG ();
1636 ss = &slot_table[slot];
1638 if (!ss->valid)
1639 BUG ();
1641 if (ss->any && (ss->status & 1))
1642 flag = 'u';
1644 rc = assuan_send_data (ctx, &flag, 1);
1646 else if (!strcmp (line, "reader_list"))
1648 #ifdef HAVE_LIBUSB
1649 char *s = ccid_get_reader_list ();
1650 #else
1651 char *s = NULL;
1652 #endif
1654 if (s)
1655 rc = assuan_send_data (ctx, s, strlen (s));
1656 else
1657 rc = gpg_error (GPG_ERR_NO_DATA);
1658 xfree (s);
1660 else if (!strcmp (line, "deny_admin"))
1661 rc = opt.allow_admin? gpg_error (GPG_ERR_GENERAL) : 0;
1662 else if (!strcmp (line, "app_list"))
1664 char *s = get_supported_applications ();
1665 if (s)
1666 rc = assuan_send_data (ctx, s, strlen (s));
1667 else
1668 rc = 0;
1669 xfree (s);
1671 else
1672 rc = set_error (GPG_ERR_ASS_PARAMETER, "unknown value for WHAT");
1673 return rc;
1677 /* RESTART
1679 Restart the current connection; this is a kind of warm reset. It
1680 deletes the context used by this connection but does not send a
1681 RESET to the card. Thus the card itself won't get reset.
1683 This is used by gpg-agent to reuse a primary pipe connection and
1684 may be used by clients to backup from a conflict in the serial
1685 command; i.e. to select another application.
1688 static gpg_error_t
1689 cmd_restart (assuan_context_t ctx, char *line)
1691 ctrl_t ctrl = assuan_get_pointer (ctx);
1693 (void)line;
1695 if (ctrl->app_ctx)
1697 release_application (ctrl->app_ctx);
1698 ctrl->app_ctx = NULL;
1700 if (locked_session && ctrl->server_local == locked_session)
1702 locked_session = NULL;
1703 log_info ("implicitly unlocking due to RESTART\n");
1705 return 0;
1709 /* DISCONNECT
1711 Disconnect the card if it is not any longer used by other
1712 connections and the backend supports a disconnect operation.
1714 static gpg_error_t
1715 cmd_disconnect (assuan_context_t ctx, char *line)
1717 ctrl_t ctrl = assuan_get_pointer (ctx);
1719 (void)line;
1721 ctrl->server_local->disconnect_allowed = 1;
1722 return 0;
1727 /* APDU [--atr] [--more] [--exlen[=N]] [hexstring]
1729 Send an APDU to the current reader. This command bypasses the high
1730 level functions and sends the data directly to the card. HEXSTRING
1731 is expected to be a proper APDU. If HEXSTRING is not given no
1732 commands are set to the card but the command will implictly check
1733 whether the card is ready for use.
1735 Using the option "--atr" returns the ATR of the card as a status
1736 message before any data like this:
1737 S CARD-ATR 3BFA1300FF813180450031C173C00100009000B1
1739 Using the option --more handles the card status word MORE_DATA
1740 (61xx) and concatenates all reponses to one block.
1742 Using the option "--exlen" the returned APDU may use extended
1743 length up to N bytes. If N is not given a default value is used
1744 (currently 4096).
1746 static gpg_error_t
1747 cmd_apdu (assuan_context_t ctx, char *line)
1749 ctrl_t ctrl = assuan_get_pointer (ctx);
1750 int rc;
1751 unsigned char *apdu;
1752 size_t apdulen;
1753 int with_atr;
1754 int handle_more;
1755 const char *s;
1756 size_t exlen;
1758 with_atr = has_option (line, "--atr");
1759 handle_more = has_option (line, "--more");
1761 if ((s=has_option_name (line, "--exlen")))
1763 if (*s == '=')
1764 exlen = strtoul (s+1, NULL, 0);
1765 else
1766 exlen = 4096;
1768 else
1769 exlen = 0;
1771 line = skip_options (line);
1773 if ( IS_LOCKED (ctrl) )
1774 return gpg_error (GPG_ERR_LOCKED);
1776 if ((rc = open_card (ctrl, NULL)))
1777 return rc;
1779 if (with_atr)
1781 unsigned char *atr;
1782 size_t atrlen;
1783 char hexbuf[400];
1785 atr = apdu_get_atr (ctrl->reader_slot, &atrlen);
1786 if (!atr || atrlen > sizeof hexbuf - 2 )
1788 rc = gpg_error (GPG_ERR_INV_CARD);
1789 goto leave;
1791 bin2hex (atr, atrlen, hexbuf);
1792 xfree (atr);
1793 send_status_info (ctrl, "CARD-ATR", hexbuf, strlen (hexbuf), NULL, 0);
1796 apdu = hex_to_buffer (line, &apdulen);
1797 if (!apdu)
1799 rc = gpg_error_from_syserror ();
1800 goto leave;
1802 if (apdulen)
1804 unsigned char *result = NULL;
1805 size_t resultlen;
1807 rc = apdu_send_direct (ctrl->reader_slot, exlen,
1808 apdu, apdulen, handle_more,
1809 &result, &resultlen);
1810 if (rc)
1811 log_error ("apdu_send_direct failed: %s\n", gpg_strerror (rc));
1812 else
1814 rc = assuan_send_data (ctx, result, resultlen);
1815 xfree (result);
1818 xfree (apdu);
1820 leave:
1821 TEST_CARD_REMOVAL (ctrl, rc);
1822 return rc;
1826 /* KILLSCD - Commit suicide. */
1827 static gpg_error_t
1828 cmd_killscd (assuan_context_t ctx, char *line)
1830 ctrl_t ctrl = assuan_get_pointer (ctx);
1832 (void)line;
1834 ctrl->server_local->stopme = 1;
1835 return gpg_error (GPG_ERR_EOF);
1840 /* Tell the assuan library about our commands */
1841 static int
1842 register_commands (assuan_context_t ctx)
1844 static struct {
1845 const char *name;
1846 gpg_error_t (*handler)(assuan_context_t, char *line);
1847 } table[] = {
1848 { "SERIALNO", cmd_serialno },
1849 { "LEARN", cmd_learn },
1850 { "READCERT", cmd_readcert },
1851 { "READKEY", cmd_readkey },
1852 { "SETDATA", cmd_setdata },
1853 { "PKSIGN", cmd_pksign },
1854 { "PKAUTH", cmd_pkauth },
1855 { "PKDECRYPT", cmd_pkdecrypt },
1856 { "INPUT", NULL },
1857 { "OUTPUT", NULL },
1858 { "GETATTR", cmd_getattr },
1859 { "SETATTR", cmd_setattr },
1860 { "WRITECERT", cmd_writecert },
1861 { "WRITEKEY", cmd_writekey },
1862 { "GENKEY", cmd_genkey },
1863 { "RANDOM", cmd_random },
1864 { "PASSWD", cmd_passwd },
1865 { "CHECKPIN", cmd_checkpin },
1866 { "LOCK", cmd_lock },
1867 { "UNLOCK", cmd_unlock },
1868 { "GETINFO", cmd_getinfo },
1869 { "RESTART", cmd_restart },
1870 { "DISCONNECT", cmd_disconnect },
1871 { "APDU", cmd_apdu },
1872 { "KILLSCD", cmd_killscd },
1873 { NULL }
1875 int i, rc;
1877 for (i=0; table[i].name; i++)
1879 rc = assuan_register_command (ctx, table[i].name, table[i].handler);
1880 if (rc)
1881 return rc;
1883 assuan_set_hello_line (ctx, "GNU Privacy Guard's Smartcard server ready");
1885 assuan_register_reset_notify (ctx, reset_notify);
1886 assuan_register_option_handler (ctx, option_handler);
1887 return 0;
1891 /* Startup the server. If FD is given as -1 this is simple pipe
1892 server, otherwise it is a regular server. Returns true if there
1893 are no more active asessions. */
1895 scd_command_handler (ctrl_t ctrl, int fd)
1897 int rc;
1898 assuan_context_t ctx = NULL;
1899 int stopme;
1901 rc = assuan_new (&ctx);
1902 if (rc)
1904 log_error ("failed to allocate assuan context: %s\n",
1905 gpg_strerror (rc));
1906 scd_exit (2);
1909 if (fd == -1)
1911 int filedes[2];
1913 filedes[0] = 0;
1914 filedes[1] = 1;
1915 rc = assuan_init_pipe_server (ctx, filedes);
1917 else
1919 rc = assuan_init_socket_server_ext (ctx, INT2FD(fd), 2);
1921 if (rc)
1923 log_error ("failed to initialize the server: %s\n",
1924 gpg_strerror(rc));
1925 scd_exit (2);
1927 rc = register_commands (ctx);
1928 if (rc)
1930 log_error ("failed to register commands with Assuan: %s\n",
1931 gpg_strerror(rc));
1932 scd_exit (2);
1934 assuan_set_pointer (ctx, ctrl);
1936 /* Allocate and initialize the server object. Put it into the list
1937 of active sessions. */
1938 ctrl->server_local = xcalloc (1, sizeof *ctrl->server_local);
1939 ctrl->server_local->next_session = session_list;
1940 session_list = ctrl->server_local;
1941 ctrl->server_local->ctrl_backlink = ctrl;
1942 ctrl->server_local->assuan_ctx = ctx;
1944 if (DBG_ASSUAN)
1945 assuan_set_log_stream (ctx, log_get_stream ());
1947 /* We open the reader right at startup so that the ticker is able to
1948 update the status file. */
1949 if (ctrl->reader_slot == -1)
1951 ctrl->reader_slot = get_reader_slot ();
1954 /* Command processing loop. */
1955 for (;;)
1957 rc = assuan_accept (ctx);
1958 if (rc == -1)
1960 break;
1962 else if (rc)
1964 log_info ("Assuan accept problem: %s\n", gpg_strerror (rc));
1965 break;
1968 rc = assuan_process (ctx);
1969 if (rc)
1971 log_info ("Assuan processing failed: %s\n", gpg_strerror (rc));
1972 continue;
1976 /* Cleanup. We don't send an explicit reset to the card. */
1977 do_reset (ctrl, 0);
1979 /* Release the server object. */
1980 if (session_list == ctrl->server_local)
1981 session_list = ctrl->server_local->next_session;
1982 else
1984 struct server_local_s *sl;
1986 for (sl=session_list; sl->next_session; sl = sl->next_session)
1987 if (sl->next_session == ctrl->server_local)
1988 break;
1989 if (!sl->next_session)
1990 BUG ();
1991 sl->next_session = ctrl->server_local->next_session;
1993 stopme = ctrl->server_local->stopme;
1994 xfree (ctrl->server_local);
1995 ctrl->server_local = NULL;
1997 /* Release the Assuan context. */
1998 assuan_release (ctx);
2000 if (stopme)
2001 scd_exit (0);
2003 /* If there are no more sessions return true. */
2004 return !session_list;
2008 /* Send a line with status information via assuan and escape all given
2009 buffers. The variable elements are pairs of (char *, size_t),
2010 terminated with a (NULL, 0). */
2011 void
2012 send_status_info (ctrl_t ctrl, const char *keyword, ...)
2014 va_list arg_ptr;
2015 const unsigned char *value;
2016 size_t valuelen;
2017 char buf[950], *p;
2018 size_t n;
2019 assuan_context_t ctx = ctrl->server_local->assuan_ctx;
2021 va_start (arg_ptr, keyword);
2023 p = buf;
2024 n = 0;
2025 while ( (value = va_arg (arg_ptr, const unsigned char *)) )
2027 valuelen = va_arg (arg_ptr, size_t);
2028 if (!valuelen)
2029 continue; /* empty buffer */
2030 if (n)
2032 *p++ = ' ';
2033 n++;
2035 for ( ; valuelen && n < DIM (buf)-2; n++, valuelen--, value++)
2037 if (*value < ' ' || *value == '+')
2039 sprintf (p, "%%%02X", *value);
2040 p += 3;
2042 else if (*value == ' ')
2043 *p++ = '+';
2044 else
2045 *p++ = *value;
2048 *p = 0;
2049 assuan_write_status (ctx, keyword, buf);
2051 va_end (arg_ptr);
2055 /* Send a ready formatted status line via assuan. */
2056 void
2057 send_status_direct (ctrl_t ctrl, const char *keyword, const char *args)
2059 assuan_context_t ctx = ctrl->server_local->assuan_ctx;
2061 if (strchr (args, '\n'))
2062 log_error ("error: LF detected in status line - not sending\n");
2063 else
2064 assuan_write_status (ctx, keyword, args);
2068 /* Helper to send the clients a status change notification. */
2069 static void
2070 send_client_notifications (void)
2072 struct {
2073 pid_t pid;
2074 #ifdef HAVE_W32_SYSTEM
2075 HANDLE handle;
2076 #else
2077 int signo;
2078 #endif
2079 } killed[50];
2080 int killidx = 0;
2081 int kidx;
2082 struct server_local_s *sl;
2084 for (sl=session_list; sl; sl = sl->next_session)
2086 if (sl->event_signal && sl->assuan_ctx)
2088 pid_t pid = assuan_get_pid (sl->assuan_ctx);
2089 #ifdef HAVE_W32_SYSTEM
2090 HANDLE handle = (void *)sl->event_signal;
2092 for (kidx=0; kidx < killidx; kidx++)
2093 if (killed[kidx].pid == pid
2094 && killed[kidx].handle == handle)
2095 break;
2096 if (kidx < killidx)
2097 log_info ("event %lx (%p) already triggered for client %d\n",
2098 sl->event_signal, handle, (int)pid);
2099 else
2101 log_info ("triggering event %lx (%p) for client %d\n",
2102 sl->event_signal, handle, (int)pid);
2103 if (!SetEvent (handle))
2104 log_error ("SetEvent(%lx) failed: %s\n",
2105 sl->event_signal, w32_strerror (-1));
2106 if (killidx < DIM (killed))
2108 killed[killidx].pid = pid;
2109 killed[killidx].handle = handle;
2110 killidx++;
2113 #else /*!HAVE_W32_SYSTEM*/
2114 int signo = sl->event_signal;
2116 if (pid != (pid_t)(-1) && pid && signo > 0)
2118 for (kidx=0; kidx < killidx; kidx++)
2119 if (killed[kidx].pid == pid
2120 && killed[kidx].signo == signo)
2121 break;
2122 if (kidx < killidx)
2123 log_info ("signal %d already sent to client %d\n",
2124 signo, (int)pid);
2125 else
2127 log_info ("sending signal %d to client %d\n",
2128 signo, (int)pid);
2129 kill (pid, signo);
2130 if (killidx < DIM (killed))
2132 killed[killidx].pid = pid;
2133 killed[killidx].signo = signo;
2134 killidx++;
2138 #endif /*!HAVE_W32_SYSTEM*/
2145 /* This is the core of scd_update_reader_status_file but the caller
2146 needs to take care of the locking. */
2147 static void
2148 update_reader_status_file (int set_card_removed_flag)
2150 int idx;
2151 unsigned int status, changed;
2153 /* Make sure that the reader has been opened. Like get_reader_slot,
2154 this part of the code assumes that there is only one reader. */
2155 if (!slot_table[0].valid)
2156 (void)get_reader_slot ();
2158 /* Note, that we only try to get the status, because it does not
2159 make sense to wait here for a operation to complete. If we are
2160 busy working with a card, delays in the status file update should
2161 be acceptable. */
2162 for (idx=0; idx < DIM(slot_table); idx++)
2164 struct slot_status_s *ss = slot_table + idx;
2165 struct server_local_s *sl;
2166 int sw_apdu;
2168 if (!ss->valid || ss->slot == -1)
2169 continue; /* Not valid or reader not yet open. */
2171 sw_apdu = apdu_get_status (ss->slot, 0, &status, &changed);
2172 if (sw_apdu == SW_HOST_NO_READER)
2174 /* Most likely the _reader_ has been unplugged. */
2175 status = 0;
2176 changed = ss->changed;
2178 else if (sw_apdu)
2180 /* Get status failed. Ignore that. */
2181 continue;
2184 if (!ss->any || ss->status != status || ss->changed != changed )
2186 char *fname;
2187 char templ[50];
2188 FILE *fp;
2190 log_info ("updating slot %d status: 0x%04X->0x%04X (%u->%u)\n",
2191 ss->slot, ss->status, status, ss->changed, changed);
2192 ss->status = status;
2193 ss->changed = changed;
2195 /* FIXME: Should this be IDX instead of ss->slot? This
2196 depends on how client sessions will associate the reader
2197 status with their session. */
2198 snprintf (templ, sizeof templ, "reader_%d.status", ss->slot);
2199 fname = make_filename (opt.homedir, templ, NULL );
2200 fp = fopen (fname, "w");
2201 if (fp)
2203 fprintf (fp, "%s\n",
2204 (status & 1)? "USABLE":
2205 (status & 4)? "ACTIVE":
2206 (status & 2)? "PRESENT": "NOCARD");
2207 fclose (fp);
2209 xfree (fname);
2211 /* If a status script is executable, run it. */
2213 const char *args[9], *envs[2];
2214 char numbuf1[30], numbuf2[30], numbuf3[30];
2215 char *homestr, *envstr;
2216 gpg_error_t err;
2218 homestr = make_filename (opt.homedir, NULL);
2219 if (estream_asprintf (&envstr, "GNUPGHOME=%s", homestr) < 0)
2220 log_error ("out of core while building environment\n");
2221 else
2223 envs[0] = envstr;
2224 envs[1] = NULL;
2226 sprintf (numbuf1, "%d", ss->slot);
2227 sprintf (numbuf2, "0x%04X", ss->status);
2228 sprintf (numbuf3, "0x%04X", status);
2229 args[0] = "--reader-port";
2230 args[1] = numbuf1;
2231 args[2] = "--old-code";
2232 args[3] = numbuf2;
2233 args[4] = "--new-code";
2234 args[5] = numbuf3;
2235 args[6] = "--status";
2236 args[7] = ((status & 1)? "USABLE":
2237 (status & 4)? "ACTIVE":
2238 (status & 2)? "PRESENT": "NOCARD");
2239 args[8] = NULL;
2241 fname = make_filename (opt.homedir, "scd-event", NULL);
2242 err = gnupg_spawn_process_detached (fname, args, envs);
2243 if (err && gpg_err_code (err) != GPG_ERR_ENOENT)
2244 log_error ("failed to run event handler `%s': %s\n",
2245 fname, gpg_strerror (err));
2246 xfree (fname);
2247 xfree (envstr);
2249 xfree (homestr);
2252 /* Set the card removed flag for all current sessions. We
2253 will set this on any card change because a reset or
2254 SERIALNO request must be done in any case. */
2255 if (ss->any && set_card_removed_flag)
2256 update_card_removed (idx, 1);
2258 ss->any = 1;
2260 /* Send a signal to all clients who applied for it. */
2261 send_client_notifications ();
2264 /* Check whether a disconnect is pending. */
2265 if (opt.card_timeout)
2267 for (sl=session_list; sl; sl = sl->next_session)
2268 if (!sl->disconnect_allowed)
2269 break;
2270 if (session_list && !sl)
2272 /* FIXME: Use a real timeout. */
2273 /* At least one connection and all allow a disconnect. */
2274 log_info ("disconnecting card in slot %d\n", ss->slot);
2275 apdu_disconnect (ss->slot);
2282 /* This function is called by the ticker thread to check for changes
2283 of the reader stati. It updates the reader status files and if
2284 requested by the caller also send a signal to the caller. */
2285 void
2286 scd_update_reader_status_file (void)
2288 if (!pth_mutex_acquire (&status_file_update_lock, 1, NULL))
2289 return; /* locked - give up. */
2290 update_reader_status_file (1);
2291 if (!pth_mutex_release (&status_file_update_lock))
2292 log_error ("failed to release status_file_update lock\n");