1 /* command.c - SCdaemon command handler
2 * Copyright (C) 2001, 2002, 2003, 2004, 2005,
3 * 2007, 2008, 2009, 2011 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/>.
36 #include "app-common.h"
38 #include "apdu.h" /* Required for apdu_*_reader (). */
42 #include "ccid-driver.h"
46 /* Maximum length allowed as a PIN; used for INQUIRE NEEDPIN */
47 #define MAXLEN_PIN 100
49 /* Maximum allowed size of key data as used in inquiries. */
50 #define MAXLEN_KEYDATA 4096
52 /* Maximum allowed total data size for SETDATA. */
53 #define MAXLEN_SETDATA 4096
55 /* Maximum allowed size of certificate data as used in inquiries. */
56 #define MAXLEN_CERTDATA 16384
59 #define set_error(e,t) assuan_set_error (ctx, gpg_error (e), (t))
62 /* Macro to flag a removed card. ENODEV is also tested to catch teh
63 case of a removed reader. */
64 #define TEST_CARD_REMOVAL(c,r) \
67 if (gpg_err_code (_r) == GPG_ERR_CARD_NOT_PRESENT \
68 || gpg_err_code (_r) == GPG_ERR_CARD_REMOVED \
69 || gpg_err_code (_r) == GPG_ERR_CARD_RESET \
70 || gpg_err_code (_r) == GPG_ERR_ENODEV ) \
71 update_card_removed ((c)->server_local->vreader_idx, 1); \
74 #define IS_LOCKED(c) \
76 && locked_session != (c)->server_local \
77 && (c)->server_local->vreader_idx != -1 \
78 && locked_session->ctrl_backlink \
79 && ((c)->server_local->vreader_idx \
80 == locked_session->ctrl_backlink->server_local->vreader_idx))
83 /* This structure is used to keep track of user readers. To
84 eventually accommodate this structure for RFID cards, where more
85 than one card is used per reader, we name it virtual reader. */
88 int valid; /* True if the other objects are valid. */
89 int slot; /* APDU slot number of the reader or -1 if not open. */
91 int reset_failed; /* A reset failed. */
93 int any; /* Flag indicating whether any status check has been
94 done. This is set once to indicate that the status
95 tracking for the slot has been initialized. */
96 unsigned int status; /* Last status of the reader. */
97 unsigned int changed; /* Last change counter of the reader. */
101 /* Data used to associate an Assuan context with local server data.
102 This object describes the local properties of one session. */
103 struct server_local_s
105 /* We keep a list of all active sessions with the anchor at
106 SESSION_LIST (see below). This field is used for linking. */
107 struct server_local_s *next_session;
109 /* This object is usually assigned to a CTRL object (which is
110 globally visible). While enumerating all sessions we sometimes
111 need to access data of the CTRL object; thus we keep a
113 ctrl_t ctrl_backlink;
115 /* The Assuan context used by this session/server. */
116 assuan_context_t assuan_ctx;
118 #ifdef HAVE_W32_SYSTEM
119 unsigned long event_signal; /* Or 0 if not used. */
121 int event_signal; /* Or 0 if not used. */
124 /* Index into the vreader table (command.c) or -1 if not open. */
127 /* True if the card has been removed and a reset is required to
128 continue operation. */
131 /* Flag indicating that the application context needs to be released
132 at the next opportunity. */
133 int app_ctx_marked_for_release;
135 /* A disconnect command has been sent. */
136 int disconnect_allowed;
138 /* If set to true we will be terminate ourself at the end of the
145 /* The table with information on all used virtual readers. */
146 static struct vreader_s vreader_table[10];
149 /* To keep track of all running sessions, we link all active server
150 contexts and the anchor in this variable. */
151 static struct server_local_s *session_list;
153 /* If a session has been locked we store a link to its server object
155 static struct server_local_s *locked_session;
157 /* While doing a reset we need to make sure that the ticker does not
158 call scd_update_reader_status_file while we are using it. */
159 static npth_mutex_t status_file_update_lock;
162 /*-- Local prototypes --*/
163 static void update_reader_status_file (int set_card_removed_flag);
168 /* This function must be called once to initialize this module. This
169 has to be done before a second thread is spawned. We can't do the
170 static initialization because Pth emulation code might not be able
171 to do a static init; in particular, it is not possible for W32. */
173 initialize_module_command (void)
175 static int initialized;
180 err = npth_mutex_init (&status_file_update_lock, NULL);
187 /* Helper to return the slot number for a given virtual reader index
188 VRDR. In case on an error -1 is returned. */
190 vreader_slot (int vrdr)
192 if (vrdr == -1 || !(vrdr >= 0 && vrdr < DIM(vreader_table)))
194 if (!vreader_table [vrdr].valid)
196 return vreader_table[vrdr].slot;
200 /* Update the CARD_REMOVED element of all sessions using the virtual
201 reader given by VRDR to VALUE. */
203 update_card_removed (int vrdr, int value)
205 struct server_local_s *sl;
210 for (sl=session_list; sl; sl = sl->next_session)
211 if (sl->ctrl_backlink
212 && sl->ctrl_backlink->server_local->vreader_idx == vrdr)
214 sl->card_removed = value;
216 /* Let the card application layer know about the removal. */
218 application_notify_card_reset (vreader_slot (vrdr));
222 /* Check whether the option NAME appears in LINE. Returns 1 or 0. */
224 has_option (const char *line, const char *name)
227 int n = strlen (name);
229 s = strstr (line, name);
230 return (s && (s == line || spacep (s-1)) && (!s[n] || spacep (s+n)));
233 /* Same as has_option but does only test for the name of the option
234 and ignores an argument, i.e. with NAME being "--hash" it would
235 return a pointer for "--hash" as well as for "--hash=foo". If
236 there is no such option NULL is returned. The pointer returned
237 points right behind the option name, this may be an equal sign, Nul
240 has_option_name (const char *line, const char *name)
243 int n = strlen (name);
245 s = strstr (line, name);
246 return (s && (s == line || spacep (s-1))
247 && (!s[n] || spacep (s+n) || s[n] == '=')) ? (s+n) : NULL;
251 /* Skip over options. It is assumed that leading spaces have been
252 removed (this is the case for lines passed to a handler from
253 assuan). Blanks after the options are also removed. */
255 skip_options (char *line)
257 while ( *line == '-' && line[1] == '-' )
259 while (*line && !spacep (line))
261 while (spacep (line))
269 /* Convert the STRING into a newly allocated buffer while translating
270 the hex numbers. Stops at the first invalid character. Blanks and
271 colons are allowed to separate the hex digits. Returns NULL on
272 error or a newly malloced buffer and its length in LENGTH. */
273 static unsigned char *
274 hex_to_buffer (const char *string, size_t *r_length)
276 unsigned char *buffer;
280 buffer = xtrymalloc (strlen (string)+1);
283 for (s=string, n=0; *s; s++)
285 if (spacep (s) || *s == ':')
287 if (hexdigitp (s) && hexdigitp (s+1))
289 buffer[n++] = xtoi_2 (s);
301 /* Reset the card and free the application context. With SEND_RESET
302 set to true actually send a RESET to the reader; this is the normal
303 way of calling the function. */
305 do_reset (ctrl_t ctrl, int send_reset)
307 int vrdr = ctrl->server_local->vreader_idx;
311 if (!(vrdr == -1 || (vrdr >= 0 && vrdr < DIM(vreader_table))))
314 /* If there is an active application, release it. Tell all other
315 sessions using the same application to release the
319 release_application (ctrl->app_ctx);
320 ctrl->app_ctx = NULL;
323 struct server_local_s *sl;
325 for (sl=session_list; sl; sl = sl->next_session)
326 if (sl->ctrl_backlink
327 && sl->ctrl_backlink->server_local->vreader_idx == vrdr)
329 sl->app_ctx_marked_for_release = 1;
334 /* If we want a real reset for the card, send the reset APDU and
335 tell the application layer about it. */
336 slot = vreader_slot (vrdr);
337 if (slot != -1 && send_reset && !IS_LOCKED (ctrl) )
339 application_notify_card_reset (slot);
340 switch (apdu_reset (slot))
344 case SW_HOST_NO_CARD:
345 case SW_HOST_CARD_INACTIVE:
348 apdu_close_reader (slot);
349 vreader_table[vrdr].slot = slot = -1;
354 /* If we hold a lock, unlock now. */
355 if (locked_session && ctrl->server_local == locked_session)
357 locked_session = NULL;
358 log_info ("implicitly unlocking due to RESET\n");
361 /* Reset the card removed flag for the current reader. We need to
362 take the lock here so that the ticker thread won't concurrently
363 try to update the file. Calling update_reader_status_file is
364 required to get hold of the new status of the card in the vreader
366 err = npth_mutex_lock (&status_file_update_lock);
369 log_error ("failed to acquire status_file_update lock\n");
370 ctrl->server_local->vreader_idx = -1;
373 update_reader_status_file (0); /* Update slot status table. */
374 update_card_removed (vrdr, 0); /* Clear card_removed flag. */
375 err = npth_mutex_unlock (&status_file_update_lock);
377 log_error ("failed to release status_file_update lock: %s\n",
380 /* Do this last, so that the update_card_removed above does its job. */
381 ctrl->server_local->vreader_idx = -1;
386 reset_notify (assuan_context_t ctx, char *line)
388 ctrl_t ctrl = assuan_get_pointer (ctx);
398 option_handler (assuan_context_t ctx, const char *key, const char *value)
400 ctrl_t ctrl = assuan_get_pointer (ctx);
402 if (!strcmp (key, "event-signal"))
404 /* A value of 0 is allowed to reset the event signal. */
405 #ifdef HAVE_W32_SYSTEM
407 return gpg_error (GPG_ERR_ASS_PARAMETER);
408 ctrl->server_local->event_signal = strtoul (value, NULL, 16);
410 int i = *value? atoi (value) : -1;
412 return gpg_error (GPG_ERR_ASS_PARAMETER);
413 ctrl->server_local->event_signal = i;
421 /* Return the index of the current reader or open the reader if no
422 other sessions are using that reader. If it is not possible to
423 open the reader -1 is returned. Note, that we currently support
424 only one reader but most of the code (except for this function)
425 should be able to cope with several readers. */
427 get_current_reader (void)
429 struct vreader_s *vr;
431 /* We only support one reader for now. */
432 vr = &vreader_table[0];
434 /* Initialize the vreader item if not yet done. */
441 /* Try to open the reader. */
444 vr->slot = apdu_open_reader (opt.reader_port);
446 /* If we still don't have a slot, we have no readers.
447 Invalidate for now until a reader is attached. */
454 /* Return the vreader index or -1. */
455 return vr->valid ? 0 : -1;
459 /* If the card has not yet been opened, do it. */
461 open_card (ctrl_t ctrl, const char *apptype)
466 /* If we ever got a card not present error code, return that. Only
467 the SERIALNO command and a reset are able to clear from that
469 if (ctrl->server_local->card_removed)
470 return gpg_error (GPG_ERR_CARD_REMOVED);
472 if ( IS_LOCKED (ctrl) )
473 return gpg_error (GPG_ERR_LOCKED);
475 /* If the application has been marked for release do it now. We
476 can't do it immediately in do_reset because the application may
478 if (ctrl->server_local->app_ctx_marked_for_release)
480 ctrl->server_local->app_ctx_marked_for_release = 0;
481 release_application (ctrl->app_ctx);
482 ctrl->app_ctx = NULL;
485 /* If we are already initialized for one specific application we
486 need to check that the client didn't requested a specific
487 application different from the one in use before we continue. */
490 return check_application_conflict
491 (ctrl, vreader_slot (ctrl->server_local->vreader_idx), apptype);
494 /* Setup the vreader and select the application. */
495 if (ctrl->server_local->vreader_idx != -1)
496 vrdr = ctrl->server_local->vreader_idx;
498 vrdr = get_current_reader ();
499 ctrl->server_local->vreader_idx = vrdr;
501 err = gpg_error (GPG_ERR_CARD);
504 /* Fixme: We should move the apdu_connect call to
505 select_application. */
507 int slot = vreader_slot (vrdr);
509 ctrl->server_local->disconnect_allowed = 0;
510 sw = apdu_connect (slot);
511 if (sw && sw != SW_HOST_ALREADY_CONNECTED)
513 if (sw == SW_HOST_NO_CARD)
514 err = gpg_error (GPG_ERR_CARD_NOT_PRESENT);
515 else if (sw == SW_HOST_CARD_INACTIVE)
516 err = gpg_error (GPG_ERR_CARD_RESET);
518 err = gpg_error (GPG_ERR_CARD);
521 err = select_application (ctrl, slot, apptype, &ctrl->app_ctx);
524 TEST_CARD_REMOVAL (ctrl, err);
529 static const char hlp_serialno[] =
530 "SERIALNO [<apptype>]\n"
532 "Return the serial number of the card using a status reponse. This\n"
533 "function should be used to check for the presence of a card.\n"
535 "If APPTYPE is given, an application of that type is selected and an\n"
536 "error is returned if the application is not supported or available.\n"
537 "The default is to auto-select the application using a hardwired\n"
538 "preference system. Note, that a future extension to this function\n"
539 "may allow to specify a list and order of applications to try.\n"
541 "This function is special in that it can be used to reset the card.\n"
542 "Most other functions will return an error when a card change has\n"
543 "been detected and the use of this function is therefore required.\n"
545 "Background: We want to keep the client clear of handling card\n"
546 "changes between operations; i.e. the client can assume that all\n"
547 "operations are done on the same card unless he calls this function.";
549 cmd_serialno (assuan_context_t ctx, char *line)
551 ctrl_t ctrl = assuan_get_pointer (ctx);
557 /* Clear the remove flag so that the open_card is able to reread it. */
559 if (ctrl->server_local->card_removed)
561 if ( IS_LOCKED (ctrl) )
562 return gpg_error (GPG_ERR_LOCKED);
566 if ((rc = open_card (ctrl, *line? line:NULL)))
568 /* In case of an inactive card, retry once. */
569 if (gpg_err_code (rc) == GPG_ERR_CARD_RESET && retries++ < 1)
574 rc = app_get_serial_and_stamp (ctrl->app_ctx, &serial, &stamp);
578 rc = print_assuan_status (ctx, "SERIALNO", "%s %lu",
579 serial, (unsigned long)stamp);
585 static const char hlp_learn[] =
586 "LEARN [--force] [--keypairinfo]\n"
588 "Learn all useful information of the currently inserted card. When\n"
589 "used without the force options, the command might do an INQUIRE\n"
592 " INQUIRE KNOWNCARDP <hexstring_with_serialNumber> <timestamp>\n"
594 "The client should just send an \"END\" if the processing should go on\n"
595 "or a \"CANCEL\" to force the function to terminate with a Cancel\n"
598 "With the option --keypairinfo only KEYPARIINFO lstatus lines are\n"
601 "The response of this command is a list of status lines formatted as\n"
604 " S APPTYPE <apptype>\n"
606 "This returns the type of the application, currently the strings:\n"
608 " P15 = PKCS-15 structure used\n"
609 " DINSIG = DIN SIG\n"
610 " OPENPGP = OpenPGP card\n"
611 " NKS = NetKey card\n"
613 "are implemented. These strings are aliases for the AID\n"
615 " S KEYPAIRINFO <hexstring_with_keygrip> <hexstring_with_id>\n"
617 "If there is no certificate yet stored on the card a single 'X' is\n"
618 "returned as the keygrip. In addition to the keypair info, information\n"
619 "about all certificates stored on the card is also returned:\n"
621 " S CERTINFO <certtype> <hexstring_with_id>\n"
623 "Where CERTTYPE is a number indicating the type of certificate:\n"
625 " 100 := Regular X.509 cert\n"
626 " 101 := Trusted X.509 cert\n"
627 " 102 := Useful X.509 cert\n"
628 " 110 := Root CA cert in a special format (e.g. DINSIG)\n"
629 " 111 := Root CA cert as standard X509 cert.\n"
631 "For certain cards, more information will be returned:\n"
633 " S KEY-FPR <no> <hexstring>\n"
635 "For OpenPGP cards this returns the stored fingerprints of the\n"
636 "keys. This can be used check whether a key is available on the\n"
637 "card. NO may be 1, 2 or 3.\n"
639 " S CA-FPR <no> <hexstring>\n"
641 "Similar to above, these are the fingerprints of keys assumed to be\n"
642 "ultimately trusted.\n"
644 " S DISP-NAME <name_of_card_holder>\n"
646 "The name of the card holder as stored on the card; percent\n"
647 "escaping takes place, spaces are encoded as '+'\n"
649 " S PUBKEY-URL <url>\n"
651 "The URL to be used for locating the entire public key.\n"
653 "Note, that this function may even be used on a locked card.";
655 cmd_learn (assuan_context_t ctx, char *line)
657 ctrl_t ctrl = assuan_get_pointer (ctx);
659 int only_keypairinfo = has_option (line, "--keypairinfo");
661 if ((rc = open_card (ctrl, NULL)))
664 /* Unless the force option is used we try a shortcut by identifying
665 the card using a serial number and inquiring the client with
666 that. The client may choose to cancel the operation if he already
667 knows about this card */
668 if (!only_keypairinfo)
673 rc = app_get_serial_and_stamp (ctrl->app_ctx, &serial, &stamp);
677 rc = print_assuan_status (ctx, "SERIALNO", "%s %lu",
678 serial, (unsigned long)stamp);
682 return out_of_core ();
685 if (!has_option (line, "--force"))
689 rc = gpgrt_asprintf (&command, "KNOWNCARDP %s %lu",
690 serial, (unsigned long)stamp);
694 return out_of_core ();
696 rc = assuan_inquire (ctx, command, NULL, NULL, 0);
700 if (gpg_err_code (rc) != GPG_ERR_ASS_CANCELED)
701 log_error ("inquire KNOWNCARDP failed: %s\n",
706 /* Not canceled, so we have to proceeed. */
711 /* Let the application print out its collection of useful status
714 rc = app_write_learn_status (ctrl->app_ctx, ctrl, only_keypairinfo);
716 TEST_CARD_REMOVAL (ctrl, rc);
722 static const char hlp_readcert[] =
723 "READCERT <hexified_certid>|<keyid>\n"
725 "Note, that this function may even be used on a locked card.";
727 cmd_readcert (assuan_context_t ctx, char *line)
729 ctrl_t ctrl = assuan_get_pointer (ctx);
734 if ((rc = open_card (ctrl, NULL)))
737 line = xstrdup (line); /* Need a copy of the line. */
738 rc = app_readcert (ctrl->app_ctx, line, &cert, &ncert);
740 log_error ("app_readcert failed: %s\n", gpg_strerror (rc));
745 rc = assuan_send_data (ctx, cert, ncert);
751 TEST_CARD_REMOVAL (ctrl, rc);
756 static const char hlp_readkey[] =
759 "Return the public key for the given cert or key ID as a standard\n"
762 "Note, that this function may even be used on a locked card.";
764 cmd_readkey (assuan_context_t ctx, char *line)
766 ctrl_t ctrl = assuan_get_pointer (ctx);
768 unsigned char *cert = NULL;
770 ksba_cert_t kc = NULL;
775 if ((rc = open_card (ctrl, NULL)))
778 line = xstrdup (line); /* Need a copy of the line. */
779 /* If the application supports the READKEY function we use that.
780 Otherwise we use the old way by extracting it from the
782 rc = app_readkey (ctrl->app_ctx, line, &pk, &pklen);
784 { /* Yeah, got that key - send it back. */
785 rc = assuan_send_data (ctx, pk, pklen);
792 if (gpg_err_code (rc) != GPG_ERR_UNSUPPORTED_OPERATION)
793 log_error ("app_readkey failed: %s\n", gpg_strerror (rc));
796 rc = app_readcert (ctrl->app_ctx, line, &cert, &ncert);
798 log_error ("app_readcert failed: %s\n", gpg_strerror (rc));
805 rc = ksba_cert_new (&kc);
809 rc = ksba_cert_init_from_mem (kc, cert, ncert);
812 log_error ("failed to parse the certificate: %s\n", gpg_strerror (rc));
816 p = ksba_cert_get_public_key (kc);
819 rc = gpg_error (GPG_ERR_NO_PUBKEY);
823 n = gcry_sexp_canon_len (p, 0, NULL, NULL);
824 rc = assuan_send_data (ctx, p, n);
829 ksba_cert_release (kc);
831 TEST_CARD_REMOVAL (ctrl, rc);
837 static const char hlp_setdata[] =
838 "SETDATA [--append] <hexstring>\n"
840 "The client should use this command to tell us the data he want to sign.\n"
841 "With the option --append, the data is appended to the data set by a\n"
842 "previous SETDATA command.";
844 cmd_setdata (assuan_context_t ctx, char *line)
846 ctrl_t ctrl = assuan_get_pointer (ctx);
852 append = (ctrl->in_data.value && has_option (line, "--append"));
854 line = skip_options (line);
856 if (locked_session && locked_session != ctrl->server_local)
857 return gpg_error (GPG_ERR_LOCKED);
859 /* Parse the hexstring. */
860 for (p=line,n=0; hexdigitp (p); p++, n++)
863 return set_error (GPG_ERR_ASS_PARAMETER, "invalid hexstring");
865 return set_error (GPG_ERR_ASS_PARAMETER, "no data given");
867 return set_error (GPG_ERR_ASS_PARAMETER, "odd number of digits");
871 if (ctrl->in_data.valuelen + n > MAXLEN_SETDATA)
872 return set_error (GPG_ERR_TOO_LARGE,
873 "limit on total size of data reached");
874 buf = xtrymalloc (ctrl->in_data.valuelen + n);
877 buf = xtrymalloc (n);
879 return out_of_core ();
883 memcpy (buf, ctrl->in_data.value, ctrl->in_data.valuelen);
884 off = ctrl->in_data.valuelen;
888 for (p=line, i=0; i < n; p += 2, i++)
889 buf[off+i] = xtoi_2 (p);
891 xfree (ctrl->in_data.value);
892 ctrl->in_data.value = buf;
893 ctrl->in_data.valuelen = off+n;
900 pin_cb (void *opaque, const char *info, char **retstr)
902 assuan_context_t ctx = opaque;
905 unsigned char *value;
910 /* We prompt for pinpad entry. To make sure that the popup has
911 been show we use an inquire and not just a status message.
912 We ignore any value returned. */
915 log_debug ("prompting for pinpad entry '%s'\n", info);
916 rc = gpgrt_asprintf (&command, "POPUPPINPADPROMPT %s", info);
918 return gpg_error (gpg_err_code_from_errno (errno));
919 rc = assuan_inquire (ctx, command, &value, &valuelen, MAXLEN_PIN);
924 log_debug ("dismiss pinpad entry prompt\n");
925 rc = assuan_inquire (ctx, "DISMISSPINPADPROMPT",
926 &value, &valuelen, MAXLEN_PIN);
934 log_debug ("asking for PIN '%s'\n", info);
936 rc = gpgrt_asprintf (&command, "NEEDPIN %s", info);
938 return gpg_error (gpg_err_code_from_errno (errno));
940 /* Fixme: Write an inquire function which returns the result in
941 secure memory and check all further handling of the PIN. */
942 rc = assuan_inquire (ctx, command, &value, &valuelen, MAXLEN_PIN);
947 if (!valuelen || value[valuelen-1])
949 /* We require that the returned value is an UTF-8 string */
951 return gpg_error (GPG_ERR_INV_RESPONSE);
953 *retstr = (char*)value;
958 static const char hlp_pksign[] =
959 "PKSIGN [--hash=[rmd160|sha{1,224,256,384,512}|md5]] <hexified_id>\n"
961 "The --hash option is optional; the default is SHA1.";
963 cmd_pksign (assuan_context_t ctx, char *line)
965 ctrl_t ctrl = assuan_get_pointer (ctx);
967 unsigned char *outdata;
972 if (has_option (line, "--hash=rmd160"))
973 hash_algo = GCRY_MD_RMD160;
974 else if (has_option (line, "--hash=sha1"))
975 hash_algo = GCRY_MD_SHA1;
976 else if (has_option (line, "--hash=sha224"))
977 hash_algo = GCRY_MD_SHA224;
978 else if (has_option (line, "--hash=sha256"))
979 hash_algo = GCRY_MD_SHA256;
980 else if (has_option (line, "--hash=sha384"))
981 hash_algo = GCRY_MD_SHA384;
982 else if (has_option (line, "--hash=sha512"))
983 hash_algo = GCRY_MD_SHA512;
984 else if (has_option (line, "--hash=md5"))
985 hash_algo = GCRY_MD_MD5;
986 else if (!strstr (line, "--"))
987 hash_algo = GCRY_MD_SHA1;
989 return set_error (GPG_ERR_ASS_PARAMETER, "invalid hash algorithm");
991 line = skip_options (line);
993 if ( IS_LOCKED (ctrl) )
994 return gpg_error (GPG_ERR_LOCKED);
996 if ((rc = open_card (ctrl, NULL)))
999 /* We have to use a copy of the key ID because the function may use
1000 the pin_cb which in turn uses the assuan line buffer and thus
1001 overwriting the original line with the keyid */
1002 keyidstr = xtrystrdup (line);
1004 return out_of_core ();
1006 rc = app_sign (ctrl->app_ctx,
1007 keyidstr, hash_algo,
1009 ctrl->in_data.value, ctrl->in_data.valuelen,
1010 &outdata, &outdatalen);
1015 log_error ("app_sign failed: %s\n", gpg_strerror (rc));
1019 rc = assuan_send_data (ctx, outdata, outdatalen);
1022 return rc; /* that is already an assuan error code */
1025 TEST_CARD_REMOVAL (ctrl, rc);
1030 static const char hlp_pkauth[] =
1031 "PKAUTH <hexified_id>";
1033 cmd_pkauth (assuan_context_t ctx, char *line)
1035 ctrl_t ctrl = assuan_get_pointer (ctx);
1037 unsigned char *outdata;
1041 if ( IS_LOCKED (ctrl) )
1042 return gpg_error (GPG_ERR_LOCKED);
1044 if ((rc = open_card (ctrl, NULL)))
1048 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
1050 /* We have to use a copy of the key ID because the function may use
1051 the pin_cb which in turn uses the assuan line buffer and thus
1052 overwriting the original line with the keyid */
1053 keyidstr = xtrystrdup (line);
1055 return out_of_core ();
1057 rc = app_auth (ctrl->app_ctx,
1060 ctrl->in_data.value, ctrl->in_data.valuelen,
1061 &outdata, &outdatalen);
1065 log_error ("app_auth failed: %s\n", gpg_strerror (rc));
1069 rc = assuan_send_data (ctx, outdata, outdatalen);
1072 return rc; /* that is already an assuan error code */
1075 TEST_CARD_REMOVAL (ctrl, rc);
1080 static const char hlp_pkdecrypt[] =
1081 "PKDECRYPT <hexified_id>";
1083 cmd_pkdecrypt (assuan_context_t ctx, char *line)
1085 ctrl_t ctrl = assuan_get_pointer (ctx);
1087 unsigned char *outdata;
1090 unsigned int infoflags;
1092 if ( IS_LOCKED (ctrl) )
1093 return gpg_error (GPG_ERR_LOCKED);
1095 if ((rc = open_card (ctrl, NULL)))
1098 keyidstr = xtrystrdup (line);
1100 return out_of_core ();
1101 rc = app_decipher (ctrl->app_ctx,
1104 ctrl->in_data.value, ctrl->in_data.valuelen,
1105 &outdata, &outdatalen, &infoflags);
1110 log_error ("app_decipher failed: %s\n", gpg_strerror (rc));
1114 /* If the card driver told us that there is no padding, send a
1115 status line. If there is a padding it is assumed that the
1116 caller knows what padding is used. It would have been better
1117 to always send that information but for backward
1118 compatibility we can't do that. */
1119 if ((infoflags & APP_DECIPHER_INFO_NOPAD))
1120 send_status_direct (ctrl, "PADDING", "0");
1121 rc = assuan_send_data (ctx, outdata, outdatalen);
1124 return rc; /* that is already an assuan error code */
1127 TEST_CARD_REMOVAL (ctrl, rc);
1132 static const char hlp_getattr[] =
1135 "This command is used to retrieve data from a smartcard. The\n"
1136 "allowed names depend on the currently selected smartcard\n"
1137 "application. NAME must be percent and '+' escaped. The value is\n"
1138 "returned through status message, see the LEARN command for details.\n"
1140 "However, the current implementation assumes that Name is not escaped;\n"
1141 "this works as long as noone uses arbitrary escaping. \n"
1143 "Note, that this function may even be used on a locked card.";
1145 cmd_getattr (assuan_context_t ctx, char *line)
1147 ctrl_t ctrl = assuan_get_pointer (ctx);
1149 const char *keyword;
1151 if ((rc = open_card (ctrl, NULL)))
1155 for (; *line && !spacep (line); line++)
1160 /* (We ignore any garbage for now.) */
1162 /* FIXME: Applications should not return sensitive data if the card
1164 rc = app_getattr (ctrl->app_ctx, ctrl, keyword);
1166 TEST_CARD_REMOVAL (ctrl, rc);
1171 static const char hlp_setattr[] =
1172 "SETATTR <name> <value> \n"
1174 "This command is used to store data on a a smartcard. The allowed\n"
1175 "names and values are depend on the currently selected smartcard\n"
1176 "application. NAME and VALUE must be percent and '+' escaped.\n"
1178 "However, the current implementation assumes that NAME is not\n"
1179 "escaped; this works as long as noone uses arbitrary escaping.\n"
1181 "A PIN will be requested for most NAMEs. See the corresponding\n"
1182 "setattr function of the actually used application (app-*.c) for\n"
1185 cmd_setattr (assuan_context_t ctx, char *orig_line)
1187 ctrl_t ctrl = assuan_get_pointer (ctx);
1192 char *line, *linebuf;
1194 if ( IS_LOCKED (ctrl) )
1195 return gpg_error (GPG_ERR_LOCKED);
1197 if ((rc = open_card (ctrl, NULL)))
1200 /* We need to use a copy of LINE, because PIN_CB uses the same
1201 context and thus reuses the Assuan provided LINE. */
1202 line = linebuf = xtrystrdup (orig_line);
1204 return out_of_core ();
1207 for (keywordlen=0; *line && !spacep (line); line++, keywordlen++)
1211 while (spacep (line))
1213 nbytes = percent_plus_unescape_inplace (line, 0);
1215 rc = app_setattr (ctrl->app_ctx, keyword, pin_cb, ctx,
1216 (const unsigned char*)line, nbytes);
1219 TEST_CARD_REMOVAL (ctrl, rc);
1224 static const char hlp_writecert[] =
1225 "WRITECERT <hexified_certid>\n"
1227 "This command is used to store a certifciate on a smartcard. The\n"
1228 "allowed certids depend on the currently selected smartcard\n"
1229 "application. The actual certifciate is requested using the inquiry\n"
1230 "\"CERTDATA\" and needs to be provided in its raw (e.g. DER) form.\n"
1232 "In almost all cases a a PIN will be requested. See the related\n"
1233 "writecert function of the actually used application (app-*.c) for\n"
1236 cmd_writecert (assuan_context_t ctx, char *line)
1238 ctrl_t ctrl = assuan_get_pointer (ctx);
1241 unsigned char *certdata;
1244 if ( IS_LOCKED (ctrl) )
1245 return gpg_error (GPG_ERR_LOCKED);
1247 line = skip_options (line);
1250 return set_error (GPG_ERR_ASS_PARAMETER, "no certid given");
1252 while (*line && !spacep (line))
1256 if ((rc = open_card (ctrl, NULL)))
1260 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
1262 certid = xtrystrdup (certid);
1264 return out_of_core ();
1266 /* Now get the actual keydata. */
1267 rc = assuan_inquire (ctx, "CERTDATA",
1268 &certdata, &certdatalen, MAXLEN_CERTDATA);
1275 /* Write the certificate to the card. */
1276 rc = app_writecert (ctrl->app_ctx, ctrl, certid,
1277 pin_cb, ctx, certdata, certdatalen);
1281 TEST_CARD_REMOVAL (ctrl, rc);
1286 static const char hlp_writekey[] =
1287 "WRITEKEY [--force] <keyid> \n"
1289 "This command is used to store a secret key on a a smartcard. The\n"
1290 "allowed keyids depend on the currently selected smartcard\n"
1291 "application. The actual keydata is requested using the inquiry\n"
1292 "\"KEYDATA\" and need to be provided without any protection. With\n"
1293 "--force set an existing key under this KEYID will get overwritten.\n"
1294 "The keydata is expected to be the usual canonical encoded\n"
1297 "A PIN will be requested for most NAMEs. See the corresponding\n"
1298 "writekey function of the actually used application (app-*.c) for\n"
1301 cmd_writekey (assuan_context_t ctx, char *line)
1303 ctrl_t ctrl = assuan_get_pointer (ctx);
1306 int force = has_option (line, "--force");
1307 unsigned char *keydata;
1310 if ( IS_LOCKED (ctrl) )
1311 return gpg_error (GPG_ERR_LOCKED);
1313 line = skip_options (line);
1316 return set_error (GPG_ERR_ASS_PARAMETER, "no keyid given");
1318 while (*line && !spacep (line))
1322 if ((rc = open_card (ctrl, NULL)))
1326 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
1328 keyid = xtrystrdup (keyid);
1330 return out_of_core ();
1332 /* Now get the actual keydata. */
1333 assuan_begin_confidential (ctx);
1334 rc = assuan_inquire (ctx, "KEYDATA", &keydata, &keydatalen, MAXLEN_KEYDATA);
1335 assuan_end_confidential (ctx);
1342 /* Write the key to the card. */
1343 rc = app_writekey (ctrl->app_ctx, ctrl, keyid, force? 1:0,
1344 pin_cb, ctx, keydata, keydatalen);
1348 TEST_CARD_REMOVAL (ctrl, rc);
1353 static const char hlp_genkey[] =
1354 "GENKEY [--force] [--timestamp=<isodate>] <no>\n"
1356 "Generate a key on-card identified by NO, which is application\n"
1357 "specific. Return values are application specific. For OpenPGP\n"
1358 "cards 3 status lines are returned:\n"
1360 " S KEY-FPR <hexstring>\n"
1361 " S KEY-CREATED-AT <seconds_since_epoch>\n"
1362 " S KEY-DATA [-|p|n] <hexdata>\n"
1364 " 'p' and 'n' are the names of the RSA parameters; '-' is used to\n"
1365 " indicate that HEXDATA is the first chunk of a parameter given\n"
1366 " by the next KEY-DATA.\n"
1368 "--force is required to overwrite an already existing key. The\n"
1369 "KEY-CREATED-AT is required for further processing because it is\n"
1370 "part of the hashed key material for the fingerprint.\n"
1372 "If --timestamp is given an OpenPGP key will be created using this\n"
1373 "value. The value needs to be in ISO Format; e.g.\n"
1374 "\"--timestamp=20030316T120000\" and after 1970-01-01 00:00:00.\n"
1376 "The public part of the key can also later be retrieved using the\n"
1379 cmd_genkey (assuan_context_t ctx, char *line)
1381 ctrl_t ctrl = assuan_get_pointer (ctx);
1388 if ( IS_LOCKED (ctrl) )
1389 return gpg_error (GPG_ERR_LOCKED);
1391 force = has_option (line, "--force");
1393 if ((s=has_option_name (line, "--timestamp")))
1396 return set_error (GPG_ERR_ASS_PARAMETER, "missing value for option");
1397 timestamp = isotime2epoch (s+1);
1399 return set_error (GPG_ERR_ASS_PARAMETER, "invalid time value");
1405 line = skip_options (line);
1407 return set_error (GPG_ERR_ASS_PARAMETER, "no key number given");
1409 while (*line && !spacep (line))
1413 if ((rc = open_card (ctrl, NULL)))
1417 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
1419 keyno = xtrystrdup (keyno);
1421 return out_of_core ();
1422 rc = app_genkey (ctrl->app_ctx, ctrl, keyno, force? 1:0,
1423 timestamp, pin_cb, ctx);
1426 TEST_CARD_REMOVAL (ctrl, rc);
1431 static const char hlp_random[] =
1434 "Get NBYTES of random from the card and send them back as data.\n"
1435 "This usually involves EEPROM write on the card and thus excessive\n"
1436 "use of this command may destroy the card.\n"
1438 "Note, that this function may be even be used on a locked card.";
1440 cmd_random (assuan_context_t ctx, char *line)
1442 ctrl_t ctrl = assuan_get_pointer (ctx);
1445 unsigned char *buffer;
1448 return set_error (GPG_ERR_ASS_PARAMETER,
1449 "number of requested bytes missing");
1450 nbytes = strtoul (line, NULL, 0);
1452 if ((rc = open_card (ctrl, NULL)))
1456 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
1458 buffer = xtrymalloc (nbytes);
1460 return out_of_core ();
1462 rc = app_get_challenge (ctrl->app_ctx, nbytes, buffer);
1465 rc = assuan_send_data (ctx, buffer, nbytes);
1467 return rc; /* that is already an assuan error code */
1471 TEST_CARD_REMOVAL (ctrl, rc);
1477 static const char hlp_passwd[] =
1478 "PASSWD [--reset] [--nullpin] <chvno>\n"
1480 "Change the PIN or, if --reset is given, reset the retry counter of\n"
1481 "the card holder verfication vector CHVNO. The option --nullpin is\n"
1482 "used for TCOS cards to set the initial PIN. The format of CHVNO\n"
1483 "depends on the card application.";
1485 cmd_passwd (assuan_context_t ctx, char *line)
1487 ctrl_t ctrl = assuan_get_pointer (ctx);
1490 unsigned int flags = 0;
1492 if (has_option (line, "--reset"))
1493 flags |= APP_CHANGE_FLAG_RESET;
1494 if (has_option (line, "--nullpin"))
1495 flags |= APP_CHANGE_FLAG_NULLPIN;
1497 if ( IS_LOCKED (ctrl) )
1498 return gpg_error (GPG_ERR_LOCKED);
1500 line = skip_options (line);
1503 return set_error (GPG_ERR_ASS_PARAMETER, "no CHV number given");
1505 while (*line && !spacep (line))
1509 if ((rc = open_card (ctrl, NULL)))
1513 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
1515 chvnostr = xtrystrdup (chvnostr);
1517 return out_of_core ();
1518 rc = app_change_pin (ctrl->app_ctx, ctrl, chvnostr, flags, pin_cb, ctx);
1520 log_error ("command passwd failed: %s\n", gpg_strerror (rc));
1523 TEST_CARD_REMOVAL (ctrl, rc);
1528 static const char hlp_checkpin[] =
1529 "CHECKPIN <idstr>\n"
1531 "Perform a VERIFY operation without doing anything else. This may\n"
1532 "be used to initialize a the PIN cache earlier to long lasting\n"
1533 "operations. Its use is highly application dependent.\n"
1537 " Perform a simple verify operation for CHV1 and CHV2, so that\n"
1538 " further operations won't ask for CHV2 and it is possible to do a\n"
1539 " cheap check on the PIN: If there is something wrong with the PIN\n"
1540 " entry system, only the regular CHV will get blocked and not the\n"
1541 " dangerous CHV3. IDSTR is the usual card's serial number in hex\n"
1542 " notation; an optional fingerprint part will get ignored. There\n"
1543 " is however a special mode if the IDSTR is sffixed with the\n"
1544 " literal string \"[CHV3]\": In this case the Admin PIN is checked\n"
1545 " if and only if the retry counter is still at 3.\n"
1549 " Any of the valid PIN Ids may be used. These are the strings:\n"
1551 " PW1.CH - Global password 1\n"
1552 " PW2.CH - Global password 2\n"
1553 " PW1.CH.SIG - SigG password 1\n"
1554 " PW2.CH.SIG - SigG password 2\n"
1556 " For a definitive list, see the implementation in app-nks.c.\n"
1557 " Note that we call a PW2.* PIN a \"PUK\" despite that since TCOS\n"
1558 " 3.0 they are technically alternative PINs used to mutally\n"
1559 " unblock each other.";
1561 cmd_checkpin (assuan_context_t ctx, char *line)
1563 ctrl_t ctrl = assuan_get_pointer (ctx);
1567 if ( IS_LOCKED (ctrl) )
1568 return gpg_error (GPG_ERR_LOCKED);
1570 if ((rc = open_card (ctrl, NULL)))
1574 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
1576 /* We have to use a copy of the key ID because the function may use
1577 the pin_cb which in turn uses the assuan line buffer and thus
1578 overwriting the original line with the keyid. */
1579 idstr = xtrystrdup (line);
1581 return out_of_core ();
1583 rc = app_check_pin (ctrl->app_ctx, idstr, pin_cb, ctx);
1586 log_error ("app_check_pin failed: %s\n", gpg_strerror (rc));
1588 TEST_CARD_REMOVAL (ctrl, rc);
1593 static const char hlp_lock[] =
1596 "Grant exclusive card access to this session. Note that there is\n"
1597 "no lock counter used and a second lock from the same session will\n"
1598 "be ignored. A single unlock (or RESET) unlocks the session.\n"
1599 "Return GPG_ERR_LOCKED if another session has locked the reader.\n"
1601 "If the option --wait is given the command will wait until a\n"
1602 "lock has been released.";
1604 cmd_lock (assuan_context_t ctx, char *line)
1606 ctrl_t ctrl = assuan_get_pointer (ctx);
1612 if (locked_session != ctrl->server_local)
1613 rc = gpg_error (GPG_ERR_LOCKED);
1616 locked_session = ctrl->server_local;
1619 if (rc && has_option (line, "--wait"))
1622 npth_sleep (1); /* Better implement an event mechanism. However,
1623 for card operations this should be
1625 /* FIXME: Need to check that the connection is still alive.
1626 This can be done by issuing status messages. */
1632 log_error ("cmd_lock failed: %s\n", gpg_strerror (rc));
1637 static const char hlp_unlock[] =
1640 "Release exclusive card access.";
1642 cmd_unlock (assuan_context_t ctx, char *line)
1644 ctrl_t ctrl = assuan_get_pointer (ctx);
1651 if (locked_session != ctrl->server_local)
1652 rc = gpg_error (GPG_ERR_LOCKED);
1654 locked_session = NULL;
1657 rc = gpg_error (GPG_ERR_NOT_LOCKED);
1660 log_error ("cmd_unlock failed: %s\n", gpg_strerror (rc));
1665 static const char hlp_getinfo[] =
1668 "Multi purpose command to return certain information. \n"
1669 "Supported values of WHAT are:\n"
1671 "version - Return the version of the program.\n"
1672 "pid - Return the process id of the server.\n"
1674 "socket_name - Return the name of the socket.\n"
1676 "status - Return the status of the current reader (in the future, may\n"
1677 "also return the status of all readers). The status is a list of\n"
1678 "one-character flags. The following flags are currently defined:\n"
1679 " 'u' Usable card present. This is the normal state during operation.\n"
1680 " 'r' Card removed. A reset is necessary.\n"
1681 "These flags are exclusive.\n"
1683 "reader_list - Return a list of detected card readers. Does\n"
1684 " currently only work with the internal CCID driver.\n"
1686 "deny_admin - Returns OK if admin commands are not allowed or\n"
1687 " GPG_ERR_GENERAL if admin commands are allowed.\n"
1689 "app_list - Return a list of supported applications. One\n"
1690 " application per line, fields delimited by colons,\n"
1691 " first field is the name.";
1693 cmd_getinfo (assuan_context_t ctx, char *line)
1697 if (!strcmp (line, "version"))
1699 const char *s = VERSION;
1700 rc = assuan_send_data (ctx, s, strlen (s));
1702 else if (!strcmp (line, "pid"))
1706 snprintf (numbuf, sizeof numbuf, "%lu", (unsigned long)getpid ());
1707 rc = assuan_send_data (ctx, numbuf, strlen (numbuf));
1709 else if (!strcmp (line, "socket_name"))
1711 const char *s = scd_get_socket_name ();
1714 rc = assuan_send_data (ctx, s, strlen (s));
1716 rc = gpg_error (GPG_ERR_NO_DATA);
1718 else if (!strcmp (line, "status"))
1720 ctrl_t ctrl = assuan_get_pointer (ctx);
1721 int vrdr = ctrl->server_local->vreader_idx;
1724 if (!ctrl->server_local->card_removed && vrdr != -1)
1726 struct vreader_s *vr;
1728 if (!(vrdr >= 0 && vrdr < DIM(vreader_table)))
1731 vr = &vreader_table[vrdr];
1732 if (vr->valid && vr->any && (vr->status & 1))
1735 rc = assuan_send_data (ctx, &flag, 1);
1737 else if (!strcmp (line, "reader_list"))
1740 char *s = ccid_get_reader_list ();
1746 rc = assuan_send_data (ctx, s, strlen (s));
1748 rc = gpg_error (GPG_ERR_NO_DATA);
1751 else if (!strcmp (line, "deny_admin"))
1752 rc = opt.allow_admin? gpg_error (GPG_ERR_GENERAL) : 0;
1753 else if (!strcmp (line, "app_list"))
1755 char *s = get_supported_applications ();
1757 rc = assuan_send_data (ctx, s, strlen (s));
1763 rc = set_error (GPG_ERR_ASS_PARAMETER, "unknown value for WHAT");
1768 static const char hlp_restart[] =
1771 "Restart the current connection; this is a kind of warm reset. It\n"
1772 "deletes the context used by this connection but does not send a\n"
1773 "RESET to the card. Thus the card itself won't get reset. \n"
1775 "This is used by gpg-agent to reuse a primary pipe connection and\n"
1776 "may be used by clients to backup from a conflict in the serial\n"
1777 "command; i.e. to select another application.";
1779 cmd_restart (assuan_context_t ctx, char *line)
1781 ctrl_t ctrl = assuan_get_pointer (ctx);
1787 release_application (ctrl->app_ctx);
1788 ctrl->app_ctx = NULL;
1790 if (locked_session && ctrl->server_local == locked_session)
1792 locked_session = NULL;
1793 log_info ("implicitly unlocking due to RESTART\n");
1799 static const char hlp_disconnect[] =
1802 "Disconnect the card if it is not any longer used by other\n"
1803 "connections and the backend supports a disconnect operation.";
1805 cmd_disconnect (assuan_context_t ctx, char *line)
1807 ctrl_t ctrl = assuan_get_pointer (ctx);
1811 ctrl->server_local->disconnect_allowed = 1;
1817 static const char hlp_apdu[] =
1818 "APDU [--[dump-]atr] [--more] [--exlen[=N]] [hexstring]\n"
1820 "Send an APDU to the current reader. This command bypasses the high\n"
1821 "level functions and sends the data directly to the card. HEXSTRING\n"
1822 "is expected to be a proper APDU. If HEXSTRING is not given no\n"
1823 "commands are set to the card but the command will implictly check\n"
1824 "whether the card is ready for use. \n"
1826 "Using the option \"--atr\" returns the ATR of the card as a status\n"
1827 "message before any data like this:\n"
1828 " S CARD-ATR 3BFA1300FF813180450031C173C00100009000B1\n"
1830 "Using the option --more handles the card status word MORE_DATA\n"
1831 "(61xx) and concatenates all reponses to one block.\n"
1833 "Using the option \"--exlen\" the returned APDU may use extended\n"
1834 "length up to N bytes. If N is not given a default value is used\n"
1835 "(currently 4096).";
1837 cmd_apdu (assuan_context_t ctx, char *line)
1839 ctrl_t ctrl = assuan_get_pointer (ctx);
1841 unsigned char *apdu;
1849 if (has_option (line, "--dump-atr"))
1852 with_atr = has_option (line, "--atr");
1853 handle_more = has_option (line, "--more");
1855 if ((s=has_option_name (line, "--exlen")))
1858 exlen = strtoul (s+1, NULL, 0);
1865 line = skip_options (line);
1867 if ( IS_LOCKED (ctrl) )
1868 return gpg_error (GPG_ERR_LOCKED);
1870 if ((rc = open_card (ctrl, NULL)))
1873 slot = vreader_slot (ctrl->server_local->vreader_idx);
1881 atr = apdu_get_atr (slot, &atrlen);
1882 if (!atr || atrlen > sizeof hexbuf - 2 )
1884 rc = gpg_error (GPG_ERR_INV_CARD);
1889 char *string, *p, *pend;
1891 string = atr_dump (atr, atrlen);
1894 for (rc=0, p=string; !rc && (pend = strchr (p, '\n')); p = pend+1)
1896 rc = assuan_send_data (ctx, p, pend - p + 1);
1898 rc = assuan_send_data (ctx, NULL, 0);
1901 rc = assuan_send_data (ctx, p, strlen (p));
1909 bin2hex (atr, atrlen, hexbuf);
1910 send_status_info (ctrl, "CARD-ATR", hexbuf, strlen (hexbuf), NULL, 0);
1915 apdu = hex_to_buffer (line, &apdulen);
1918 rc = gpg_error_from_syserror ();
1923 unsigned char *result = NULL;
1926 rc = apdu_send_direct (slot, exlen,
1927 apdu, apdulen, handle_more,
1928 &result, &resultlen);
1930 log_error ("apdu_send_direct failed: %s\n", gpg_strerror (rc));
1933 rc = assuan_send_data (ctx, result, resultlen);
1940 TEST_CARD_REMOVAL (ctrl, rc);
1945 static const char hlp_killscd[] =
1950 cmd_killscd (assuan_context_t ctx, char *line)
1952 ctrl_t ctrl = assuan_get_pointer (ctx);
1956 ctrl->server_local->stopme = 1;
1957 assuan_set_flag (ctx, ASSUAN_FORCE_CLOSE, 1);
1963 /* Tell the assuan library about our commands */
1965 register_commands (assuan_context_t ctx)
1969 assuan_handler_t handler;
1970 const char * const help;
1972 { "SERIALNO", cmd_serialno, hlp_serialno },
1973 { "LEARN", cmd_learn, hlp_learn },
1974 { "READCERT", cmd_readcert, hlp_readcert },
1975 { "READKEY", cmd_readkey, hlp_readkey },
1976 { "SETDATA", cmd_setdata, hlp_setdata },
1977 { "PKSIGN", cmd_pksign, hlp_pksign },
1978 { "PKAUTH", cmd_pkauth, hlp_pkauth },
1979 { "PKDECRYPT", cmd_pkdecrypt,hlp_pkdecrypt },
1982 { "GETATTR", cmd_getattr, hlp_getattr },
1983 { "SETATTR", cmd_setattr, hlp_setattr },
1984 { "WRITECERT", cmd_writecert,hlp_writecert },
1985 { "WRITEKEY", cmd_writekey, hlp_writekey },
1986 { "GENKEY", cmd_genkey, hlp_genkey },
1987 { "RANDOM", cmd_random, hlp_random },
1988 { "PASSWD", cmd_passwd, hlp_passwd },
1989 { "CHECKPIN", cmd_checkpin, hlp_checkpin },
1990 { "LOCK", cmd_lock, hlp_lock },
1991 { "UNLOCK", cmd_unlock, hlp_unlock },
1992 { "GETINFO", cmd_getinfo, hlp_getinfo },
1993 { "RESTART", cmd_restart, hlp_restart },
1994 { "DISCONNECT", cmd_disconnect,hlp_disconnect },
1995 { "APDU", cmd_apdu, hlp_apdu },
1996 { "KILLSCD", cmd_killscd, hlp_killscd },
2001 for (i=0; table[i].name; i++)
2003 rc = assuan_register_command (ctx, table[i].name, table[i].handler,
2008 assuan_set_hello_line (ctx, "GNU Privacy Guard's Smartcard server ready");
2010 assuan_register_reset_notify (ctx, reset_notify);
2011 assuan_register_option_handler (ctx, option_handler);
2016 /* Startup the server. If FD is given as -1 this is simple pipe
2017 server, otherwise it is a regular server. Returns true if there
2018 are no more active asessions. */
2020 scd_command_handler (ctrl_t ctrl, int fd)
2023 assuan_context_t ctx = NULL;
2026 rc = assuan_new (&ctx);
2029 log_error ("failed to allocate assuan context: %s\n",
2036 assuan_fd_t filedes[2];
2038 filedes[0] = assuan_fdopen (0);
2039 filedes[1] = assuan_fdopen (1);
2040 rc = assuan_init_pipe_server (ctx, filedes);
2044 rc = assuan_init_socket_server (ctx, INT2FD(fd),
2045 ASSUAN_SOCKET_SERVER_ACCEPTED);
2049 log_error ("failed to initialize the server: %s\n",
2053 rc = register_commands (ctx);
2056 log_error ("failed to register commands with Assuan: %s\n",
2060 assuan_set_pointer (ctx, ctrl);
2062 /* Allocate and initialize the server object. Put it into the list
2063 of active sessions. */
2064 ctrl->server_local = xcalloc (1, sizeof *ctrl->server_local);
2065 ctrl->server_local->next_session = session_list;
2066 session_list = ctrl->server_local;
2067 ctrl->server_local->ctrl_backlink = ctrl;
2068 ctrl->server_local->assuan_ctx = ctx;
2069 ctrl->server_local->vreader_idx = -1;
2071 /* We open the reader right at startup so that the ticker is able to
2072 update the status file. */
2073 if (ctrl->server_local->vreader_idx == -1)
2075 ctrl->server_local->vreader_idx = get_current_reader ();
2078 /* Command processing loop. */
2081 rc = assuan_accept (ctx);
2088 log_info ("Assuan accept problem: %s\n", gpg_strerror (rc));
2092 rc = assuan_process (ctx);
2095 log_info ("Assuan processing failed: %s\n", gpg_strerror (rc));
2100 /* Cleanup. We don't send an explicit reset to the card. */
2103 /* Release the server object. */
2104 if (session_list == ctrl->server_local)
2105 session_list = ctrl->server_local->next_session;
2108 struct server_local_s *sl;
2110 for (sl=session_list; sl->next_session; sl = sl->next_session)
2111 if (sl->next_session == ctrl->server_local)
2113 if (!sl->next_session)
2115 sl->next_session = ctrl->server_local->next_session;
2117 stopme = ctrl->server_local->stopme;
2118 xfree (ctrl->server_local);
2119 ctrl->server_local = NULL;
2121 /* Release the Assuan context. */
2122 assuan_release (ctx);
2127 /* If there are no more sessions return true. */
2128 return !session_list;
2132 /* Send a line with status information via assuan and escape all given
2133 buffers. The variable elements are pairs of (char *, size_t),
2134 terminated with a (NULL, 0). */
2136 send_status_info (ctrl_t ctrl, const char *keyword, ...)
2139 const unsigned char *value;
2143 assuan_context_t ctx = ctrl->server_local->assuan_ctx;
2145 va_start (arg_ptr, keyword);
2149 while ( (value = va_arg (arg_ptr, const unsigned char *)) )
2151 valuelen = va_arg (arg_ptr, size_t);
2153 continue; /* empty buffer */
2159 for ( ; valuelen && n < DIM (buf)-2; n++, valuelen--, value++)
2161 if (*value < ' ' || *value == '+')
2163 sprintf (p, "%%%02X", *value);
2166 else if (*value == ' ')
2173 assuan_write_status (ctx, keyword, buf);
2179 /* Send a ready formatted status line via assuan. */
2181 send_status_direct (ctrl_t ctrl, const char *keyword, const char *args)
2183 assuan_context_t ctx = ctrl->server_local->assuan_ctx;
2185 if (strchr (args, '\n'))
2186 log_error ("error: LF detected in status line - not sending\n");
2188 assuan_write_status (ctx, keyword, args);
2192 /* Helper to send the clients a status change notification. */
2194 send_client_notifications (void)
2198 #ifdef HAVE_W32_SYSTEM
2206 struct server_local_s *sl;
2208 for (sl=session_list; sl; sl = sl->next_session)
2210 if (sl->event_signal && sl->assuan_ctx)
2212 pid_t pid = assuan_get_pid (sl->assuan_ctx);
2213 #ifdef HAVE_W32_SYSTEM
2214 HANDLE handle = (void *)sl->event_signal;
2216 for (kidx=0; kidx < killidx; kidx++)
2217 if (killed[kidx].pid == pid
2218 && killed[kidx].handle == handle)
2221 log_info ("event %lx (%p) already triggered for client %d\n",
2222 sl->event_signal, handle, (int)pid);
2225 log_info ("triggering event %lx (%p) for client %d\n",
2226 sl->event_signal, handle, (int)pid);
2227 if (!SetEvent (handle))
2228 log_error ("SetEvent(%lx) failed: %s\n",
2229 sl->event_signal, w32_strerror (-1));
2230 if (killidx < DIM (killed))
2232 killed[killidx].pid = pid;
2233 killed[killidx].handle = handle;
2237 #else /*!HAVE_W32_SYSTEM*/
2238 int signo = sl->event_signal;
2240 if (pid != (pid_t)(-1) && pid && signo > 0)
2242 for (kidx=0; kidx < killidx; kidx++)
2243 if (killed[kidx].pid == pid
2244 && killed[kidx].signo == signo)
2247 log_info ("signal %d already sent to client %d\n",
2251 log_info ("sending signal %d to client %d\n",
2254 if (killidx < DIM (killed))
2256 killed[killidx].pid = pid;
2257 killed[killidx].signo = signo;
2262 #endif /*!HAVE_W32_SYSTEM*/
2269 /* This is the core of scd_update_reader_status_file but the caller
2270 needs to take care of the locking. */
2272 update_reader_status_file (int set_card_removed_flag)
2275 unsigned int status, changed;
2277 /* Note, that we only try to get the status, because it does not
2278 make sense to wait here for a operation to complete. If we are
2279 busy working with a card, delays in the status file update should
2281 for (idx=0; idx < DIM(vreader_table); idx++)
2283 struct vreader_s *vr = vreader_table + idx;
2284 struct server_local_s *sl;
2287 if (!vr->valid || vr->slot == -1)
2288 continue; /* Not valid or reader not yet open. */
2290 sw_apdu = apdu_get_status (vr->slot, 0, &status, &changed);
2291 if (sw_apdu == SW_HOST_NO_READER)
2293 /* Most likely the _reader_ has been unplugged. */
2294 application_notify_card_reset (vr->slot);
2295 apdu_close_reader (vr->slot);
2298 changed = vr->changed;
2302 /* Get status failed. Ignore that. */
2306 if (!vr->any || vr->status != status || vr->changed != changed )
2312 log_info ("updating reader %d (%d) status: 0x%04X->0x%04X (%u->%u)\n",
2313 idx, vr->slot, vr->status, status, vr->changed, changed);
2314 vr->status = status;
2315 vr->changed = changed;
2317 /* FIXME: Should this be IDX instead of vr->slot? This
2318 depends on how client sessions will associate the reader
2319 status with their session. */
2320 snprintf (templ, sizeof templ, "reader_%d.status", vr->slot);
2321 fname = make_filename (opt.homedir, templ, NULL );
2322 fp = fopen (fname, "w");
2325 fprintf (fp, "%s\n",
2326 (status & 1)? "USABLE":
2327 (status & 4)? "ACTIVE":
2328 (status & 2)? "PRESENT": "NOCARD");
2333 /* If a status script is executable, run it. */
2335 const char *args[9], *envs[2];
2336 char numbuf1[30], numbuf2[30], numbuf3[30];
2337 char *homestr, *envstr;
2340 homestr = make_filename (opt.homedir, NULL);
2341 if (gpgrt_asprintf (&envstr, "GNUPGHOME=%s", homestr) < 0)
2342 log_error ("out of core while building environment\n");
2348 sprintf (numbuf1, "%d", vr->slot);
2349 sprintf (numbuf2, "0x%04X", vr->status);
2350 sprintf (numbuf3, "0x%04X", status);
2351 args[0] = "--reader-port";
2353 args[2] = "--old-code";
2355 args[4] = "--new-code";
2357 args[6] = "--status";
2358 args[7] = ((status & 1)? "USABLE":
2359 (status & 4)? "ACTIVE":
2360 (status & 2)? "PRESENT": "NOCARD");
2363 fname = make_filename (opt.homedir, "scd-event", NULL);
2364 err = gnupg_spawn_process_detached (fname, args, envs);
2365 if (err && gpg_err_code (err) != GPG_ERR_ENOENT)
2366 log_error ("failed to run event handler '%s': %s\n",
2367 fname, gpg_strerror (err));
2374 /* Set the card removed flag for all current sessions. */
2375 if (vr->any && vr->status == 0 && set_card_removed_flag)
2376 update_card_removed (idx, 1);
2380 /* Send a signal to all clients who applied for it. */
2381 send_client_notifications ();
2384 /* Check whether a disconnect is pending. */
2385 if (opt.card_timeout)
2387 for (sl=session_list; sl; sl = sl->next_session)
2388 if (!sl->disconnect_allowed)
2390 if (session_list && !sl)
2392 /* FIXME: Use a real timeout. */
2393 /* At least one connection and all allow a disconnect. */
2394 log_info ("disconnecting card in reader %d (%d)\n",
2396 apdu_disconnect (vr->slot);
2403 /* This function is called by the ticker thread to check for changes
2404 of the reader stati. It updates the reader status files and if
2405 requested by the caller also send a signal to the caller. */
2407 scd_update_reader_status_file (void)
2410 err = npth_mutex_lock (&status_file_update_lock);
2412 return; /* locked - give up. */
2413 update_reader_status_file (1);
2414 err = npth_mutex_unlock (&status_file_update_lock);
2416 log_error ("failed to release status_file_update lock: %s\n",