agent/
[gnupg.git] / scd / command.c
blobf12f11acf39aab8b7a777624cad2c29851a47170
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 gpg_error_t
342 reset_notify (assuan_context_t ctx, char *line)
344 ctrl_t ctrl = assuan_get_pointer (ctx);
346 (void) line;
348 do_reset (ctrl, 1);
349 return 0;
353 static gpg_error_t
354 option_handler (assuan_context_t ctx, const char *key, const char *value)
356 ctrl_t ctrl = assuan_get_pointer (ctx);
358 if (!strcmp (key, "event-signal"))
360 /* A value of 0 is allowed to reset the event signal. */
361 #ifdef HAVE_W32_SYSTEM
362 if (!*value)
363 return gpg_error (GPG_ERR_ASS_PARAMETER);
364 ctrl->server_local->event_signal = strtoul (value, NULL, 16);
365 #else
366 int i = *value? atoi (value) : -1;
367 if (i < 0)
368 return gpg_error (GPG_ERR_ASS_PARAMETER);
369 ctrl->server_local->event_signal = i;
370 #endif
373 return 0;
377 /* Return the slot of the current reader or open the reader if no
378 other sessions are using a reader. Note, that we currently support
379 only one reader but most of the code (except for this function)
380 should be able to cope with several readers. */
381 static int
382 get_reader_slot (void)
384 struct slot_status_s *ss;
386 ss = &slot_table[0]; /* One reader for now. */
388 /* Initialize the item if needed. */
389 if (!ss->valid)
391 ss->slot = -1;
392 ss->valid = 1;
395 /* Try to open the reader. */
396 if (ss->slot == -1)
397 ss->slot = apdu_open_reader (opt.reader_port);
399 /* Return the slot_table index. */
400 return 0;
403 /* If the card has not yet been opened, do it. Note that this
404 function returns an Assuan error, so don't map the error a second
405 time. */
406 static gpg_error_t
407 open_card (ctrl_t ctrl, const char *apptype)
409 gpg_error_t err;
410 int slot;
412 /* If we ever got a card not present error code, return that. Only
413 the SERIALNO command and a reset are able to clear from that
414 state. */
415 if (ctrl->server_local->card_removed)
416 return gpg_error (GPG_ERR_CARD_REMOVED);
418 if ( IS_LOCKED (ctrl) )
419 return gpg_error (GPG_ERR_LOCKED);
421 /* If the application has been marked for release do it now. We
422 can't do it immediately in do_reset because the application may
423 still be in use. */
424 if (ctrl->server_local->app_ctx_marked_for_release)
426 ctrl->server_local->app_ctx_marked_for_release = 0;
427 release_application (ctrl->app_ctx);
428 ctrl->app_ctx = NULL;
431 /* If we are already initialized for one specific application we
432 need to check that the client didn't requested a specific
433 application different from the one in use before we continue. */
434 if (ctrl->app_ctx)
435 return check_application_conflict (ctrl, apptype);
437 /* Setup the slot and select the application. */
438 if (ctrl->reader_slot != -1)
439 slot = ctrl->reader_slot;
440 else
441 slot = get_reader_slot ();
442 ctrl->reader_slot = slot;
443 if (slot == -1)
444 err = gpg_error (GPG_ERR_CARD);
445 else
447 /* Fixme: We should move the apdu_connect call to
448 select_application. */
449 int sw;
451 ctrl->server_local->disconnect_allowed = 0;
452 sw = apdu_connect (slot);
453 if (sw && sw != SW_HOST_ALREADY_CONNECTED)
455 if (sw == SW_HOST_NO_CARD)
456 err = gpg_error (GPG_ERR_CARD_NOT_PRESENT);
457 else
458 err = gpg_error (GPG_ERR_CARD);
460 else
461 err = select_application (ctrl, slot, apptype, &ctrl->app_ctx);
464 TEST_CARD_REMOVAL (ctrl, err);
465 return err;
469 /* SERIALNO [APPTYPE]
471 Return the serial number of the card using a status reponse. This
472 function should be used to check for the presence of a card.
474 If APPTYPE is given, an application of that type is selected and an
475 error is returned if the application is not supported or available.
476 The default is to auto-select the application using a hardwired
477 preference system. Note, that a future extension to this function
478 may allow to specify a list and order of applications to try.
480 This function is special in that it can be used to reset the card.
481 Most other functions will return an error when a card change has
482 been detected and the use of this function is therefore required.
484 Background: We want to keep the client clear of handling card
485 changes between operations; i.e. the client can assume that all
486 operations are done on the same card unless he calls this function.
488 static gpg_error_t
489 cmd_serialno (assuan_context_t ctx, char *line)
491 ctrl_t ctrl = assuan_get_pointer (ctx);
492 int rc = 0;
493 char *serial_and_stamp;
494 char *serial;
495 time_t stamp;
497 /* Clear the remove flag so that the open_card is able to reread it. */
498 if (ctrl->server_local->card_removed)
500 if ( IS_LOCKED (ctrl) )
501 return gpg_error (GPG_ERR_LOCKED);
502 do_reset (ctrl, 1);
505 if ((rc = open_card (ctrl, *line? line:NULL)))
506 return rc;
508 rc = app_get_serial_and_stamp (ctrl->app_ctx, &serial, &stamp);
509 if (rc)
510 return rc;
512 rc = estream_asprintf (&serial_and_stamp, "%s %lu",
513 serial, (unsigned long)stamp);
514 xfree (serial);
515 if (rc < 0)
516 return out_of_core ();
517 rc = 0;
518 assuan_write_status (ctx, "SERIALNO", serial_and_stamp);
519 xfree (serial_and_stamp);
520 return 0;
526 /* LEARN [--force] [--keypairinfo]
528 Learn all useful information of the currently inserted card. When
529 used without the force options, the command might do an INQUIRE
530 like this:
532 INQUIRE KNOWNCARDP <hexstring_with_serialNumber> <timestamp>
534 The client should just send an "END" if the processing should go on
535 or a "CANCEL" to force the function to terminate with a Cancel
536 error message.
538 With the option --keypairinfo only KEYPARIINFO lstatus lines are
539 returned.
541 The response of this command is a list of status lines formatted as
542 this:
544 S APPTYPE <apptype>
546 This returns the type of the application, currently the strings:
548 P15 = PKCS-15 structure used
549 DINSIG = DIN SIG
550 OPENPGP = OpenPGP card
551 NKS = NetKey card
553 are implemented. These strings are aliases for the AID
555 S KEYPAIRINFO <hexstring_with_keygrip> <hexstring_with_id>
557 If there is no certificate yet stored on the card a single "X" is
558 returned as the keygrip. In addition to the keypair info, information
559 about all certificates stored on the card is also returned:
561 S CERTINFO <certtype> <hexstring_with_id>
563 Where CERTTYPE is a number indicating the type of certificate:
564 0 := Unknown
565 100 := Regular X.509 cert
566 101 := Trusted X.509 cert
567 102 := Useful X.509 cert
568 110 := Root CA cert in a special format (e.g. DINSIG)
569 111 := Root CA cert as standard X509 cert.
571 For certain cards, more information will be returned:
573 S KEY-FPR <no> <hexstring>
575 For OpenPGP cards this returns the stored fingerprints of the
576 keys. This can be used check whether a key is available on the
577 card. NO may be 1, 2 or 3.
579 S CA-FPR <no> <hexstring>
581 Similar to above, these are the fingerprints of keys assumed to be
582 ultimately trusted.
584 S DISP-NAME <name_of_card_holder>
586 The name of the card holder as stored on the card; percent
587 escaping takes place, spaces are encoded as '+'
589 S PUBKEY-URL <url>
591 The URL to be used for locating the entire public key.
593 Note, that this function may even be used on a locked card.
595 static gpg_error_t
596 cmd_learn (assuan_context_t ctx, char *line)
598 ctrl_t ctrl = assuan_get_pointer (ctx);
599 int rc = 0;
600 int only_keypairinfo = has_option (line, "--keypairinfo");
602 if ((rc = open_card (ctrl, NULL)))
603 return rc;
605 /* Unless the force option is used we try a shortcut by identifying
606 the card using a serial number and inquiring the client with
607 that. The client may choose to cancel the operation if he already
608 knows about this card */
609 if (!only_keypairinfo)
611 char *serial_and_stamp;
612 char *serial;
613 time_t stamp;
615 rc = app_get_serial_and_stamp (ctrl->app_ctx, &serial, &stamp);
616 if (rc)
617 return rc;
618 rc = estream_asprintf (&serial_and_stamp, "%s %lu",
619 serial, (unsigned long)stamp);
620 xfree (serial);
621 if (rc < 0)
622 return out_of_core ();
623 rc = 0;
624 assuan_write_status (ctx, "SERIALNO", serial_and_stamp);
626 if (!has_option (line, "--force"))
628 char *command;
630 rc = estream_asprintf (&command, "KNOWNCARDP %s", serial_and_stamp);
631 if (rc < 0)
633 xfree (serial_and_stamp);
634 return out_of_core ();
636 rc = 0;
637 rc = assuan_inquire (ctx, command, NULL, NULL, 0);
638 xfree (command);
639 if (rc)
641 if (gpg_err_code (rc) != GPG_ERR_ASS_CANCELED)
642 log_error ("inquire KNOWNCARDP failed: %s\n",
643 gpg_strerror (rc));
644 xfree (serial_and_stamp);
645 return rc;
647 /* Not canceled, so we have to proceeed. */
649 xfree (serial_and_stamp);
652 /* Let the application print out its collection of useful status
653 information. */
654 if (!rc)
655 rc = app_write_learn_status (ctrl->app_ctx, ctrl, only_keypairinfo);
657 TEST_CARD_REMOVAL (ctrl, rc);
658 return rc;
663 /* READCERT <hexified_certid>|<keyid>
665 Note, that this function may even be used on a locked card.
667 static gpg_error_t
668 cmd_readcert (assuan_context_t ctx, char *line)
670 ctrl_t ctrl = assuan_get_pointer (ctx);
671 int rc;
672 unsigned char *cert;
673 size_t ncert;
675 if ((rc = open_card (ctrl, NULL)))
676 return rc;
678 line = xstrdup (line); /* Need a copy of the line. */
679 rc = app_readcert (ctrl->app_ctx, line, &cert, &ncert);
680 if (rc)
681 log_error ("app_readcert failed: %s\n", gpg_strerror (rc));
682 xfree (line);
683 line = NULL;
684 if (!rc)
686 rc = assuan_send_data (ctx, cert, ncert);
687 xfree (cert);
688 if (rc)
689 return rc;
692 TEST_CARD_REMOVAL (ctrl, rc);
693 return rc;
697 /* READKEY <keyid>
699 Return the public key for the given cert or key ID as an standard
700 S-Expression.
702 Note, that this function may even be used on a locked card.
704 static gpg_error_t
705 cmd_readkey (assuan_context_t ctx, char *line)
707 ctrl_t ctrl = assuan_get_pointer (ctx);
708 int rc;
709 unsigned char *cert = NULL;
710 size_t ncert, n;
711 ksba_cert_t kc = NULL;
712 ksba_sexp_t p;
713 unsigned char *pk;
714 size_t pklen;
716 if ((rc = open_card (ctrl, NULL)))
717 return rc;
719 line = xstrdup (line); /* Need a copy of the line. */
720 /* If the application supports the READKEY function we use that.
721 Otherwise we use the old way by extracting it from the
722 certificate. */
723 rc = app_readkey (ctrl->app_ctx, line, &pk, &pklen);
724 if (!rc)
725 { /* Yeah, got that key - send it back. */
726 rc = assuan_send_data (ctx, pk, pklen);
727 xfree (pk);
728 xfree (line);
729 line = NULL;
730 goto leave;
733 if (gpg_err_code (rc) != GPG_ERR_UNSUPPORTED_OPERATION)
734 log_error ("app_readkey failed: %s\n", gpg_strerror (rc));
735 else
737 rc = app_readcert (ctrl->app_ctx, line, &cert, &ncert);
738 if (rc)
739 log_error ("app_readcert failed: %s\n", gpg_strerror (rc));
741 xfree (line);
742 line = NULL;
743 if (rc)
744 goto leave;
746 rc = ksba_cert_new (&kc);
747 if (rc)
749 xfree (cert);
750 goto leave;
752 rc = ksba_cert_init_from_mem (kc, cert, ncert);
753 if (rc)
755 log_error ("failed to parse the certificate: %s\n", gpg_strerror (rc));
756 goto leave;
759 p = ksba_cert_get_public_key (kc);
760 if (!p)
762 rc = gpg_error (GPG_ERR_NO_PUBKEY);
763 goto leave;
766 n = gcry_sexp_canon_len (p, 0, NULL, NULL);
767 rc = assuan_send_data (ctx, p, n);
768 xfree (p);
771 leave:
772 ksba_cert_release (kc);
773 xfree (cert);
774 TEST_CARD_REMOVAL (ctrl, rc);
775 return rc;
781 /* SETDATA <hexstring>
783 The client should use this command to tell us the data he want to
784 sign. */
785 static gpg_error_t
786 cmd_setdata (assuan_context_t ctx, char *line)
788 ctrl_t ctrl = assuan_get_pointer (ctx);
789 int n;
790 char *p;
791 unsigned char *buf;
793 if (locked_session && locked_session != ctrl->server_local)
794 return gpg_error (GPG_ERR_LOCKED);
796 /* Parse the hexstring. */
797 for (p=line,n=0; hexdigitp (p); p++, n++)
799 if (*p)
800 return set_error (GPG_ERR_ASS_PARAMETER, "invalid hexstring");
801 if (!n)
802 return set_error (GPG_ERR_ASS_PARAMETER, "no data given");
803 if ((n&1))
804 return set_error (GPG_ERR_ASS_PARAMETER, "odd number of digits");
805 n /= 2;
806 buf = xtrymalloc (n);
807 if (!buf)
808 return out_of_core ();
810 xfree (ctrl->in_data.value);
811 ctrl->in_data.value = buf;
812 ctrl->in_data.valuelen = n;
813 for (p=line, n=0; n < ctrl->in_data.valuelen; p += 2, n++)
814 buf[n] = xtoi_2 (p);
815 return 0;
820 static gpg_error_t
821 pin_cb (void *opaque, const char *info, char **retstr)
823 assuan_context_t ctx = opaque;
824 char *command;
825 int rc;
826 unsigned char *value;
827 size_t valuelen;
829 if (!retstr)
831 /* We prompt for keypad entry. To make sure that the popup has
832 been show we use an inquire and not just a status message.
833 We ignore any value returned. */
834 if (info)
836 log_debug ("prompting for keypad entry '%s'\n", info);
837 rc = estream_asprintf (&command, "POPUPKEYPADPROMPT %s", info);
838 if (rc < 0)
839 return gpg_error (gpg_err_code_from_errno (errno));
840 rc = assuan_inquire (ctx, command, &value, &valuelen, MAXLEN_PIN);
841 xfree (command);
843 else
845 log_debug ("dismiss keypad entry prompt\n");
846 rc = assuan_inquire (ctx, "DISMISSKEYPADPROMPT",
847 &value, &valuelen, MAXLEN_PIN);
849 if (!rc)
850 xfree (value);
851 return rc;
854 *retstr = NULL;
855 log_debug ("asking for PIN '%s'\n", info);
857 rc = estream_asprintf (&command, "NEEDPIN %s", info);
858 if (rc < 0)
859 return gpg_error (gpg_err_code_from_errno (errno));
861 /* Fixme: Write an inquire function which returns the result in
862 secure memory and check all further handling of the PIN. */
863 rc = assuan_inquire (ctx, command, &value, &valuelen, MAXLEN_PIN);
864 xfree (command);
865 if (rc)
866 return rc;
868 if (!valuelen || value[valuelen-1])
870 /* We require that the returned value is an UTF-8 string */
871 xfree (value);
872 return gpg_error (GPG_ERR_INV_RESPONSE);
874 *retstr = (char*)value;
875 return 0;
879 /* PKSIGN [--hash=[rmd160|sha{1,224,256,384,512}|md5]] <hexified_id>
881 The --hash option is optional; the default is SHA1.
884 static gpg_error_t
885 cmd_pksign (assuan_context_t ctx, char *line)
887 ctrl_t ctrl = assuan_get_pointer (ctx);
888 int rc;
889 unsigned char *outdata;
890 size_t outdatalen;
891 char *keyidstr;
892 int hash_algo;
894 if (has_option (line, "--hash=rmd160"))
895 hash_algo = GCRY_MD_RMD160;
896 else if (has_option (line, "--hash=sha1"))
897 hash_algo = GCRY_MD_SHA1;
898 else if (has_option (line, "--hash=sha224"))
899 hash_algo = GCRY_MD_SHA224;
900 else if (has_option (line, "--hash=sha256"))
901 hash_algo = GCRY_MD_SHA256;
902 else if (has_option (line, "--hash=sha384"))
903 hash_algo = GCRY_MD_SHA384;
904 else if (has_option (line, "--hash=sha512"))
905 hash_algo = GCRY_MD_SHA512;
906 else if (has_option (line, "--hash=md5"))
907 hash_algo = GCRY_MD_MD5;
908 else if (!strstr (line, "--"))
909 hash_algo = GCRY_MD_SHA1;
910 else
911 return set_error (GPG_ERR_ASS_PARAMETER, "invalid hash algorithm");
913 line = skip_options (line);
915 if ( IS_LOCKED (ctrl) )
916 return gpg_error (GPG_ERR_LOCKED);
918 if ((rc = open_card (ctrl, NULL)))
919 return rc;
921 /* We have to use a copy of the key ID because the function may use
922 the pin_cb which in turn uses the assuan line buffer and thus
923 overwriting the original line with the keyid */
924 keyidstr = xtrystrdup (line);
925 if (!keyidstr)
926 return out_of_core ();
928 rc = app_sign (ctrl->app_ctx,
929 keyidstr, hash_algo,
930 pin_cb, ctx,
931 ctrl->in_data.value, ctrl->in_data.valuelen,
932 &outdata, &outdatalen);
934 xfree (keyidstr);
935 if (rc)
937 log_error ("app_sign failed: %s\n", gpg_strerror (rc));
939 else
941 rc = assuan_send_data (ctx, outdata, outdatalen);
942 xfree (outdata);
943 if (rc)
944 return rc; /* that is already an assuan error code */
947 TEST_CARD_REMOVAL (ctrl, rc);
948 return rc;
951 /* PKAUTH <hexified_id>
954 static gpg_error_t
955 cmd_pkauth (assuan_context_t ctx, char *line)
957 ctrl_t ctrl = assuan_get_pointer (ctx);
958 int rc;
959 unsigned char *outdata;
960 size_t outdatalen;
961 char *keyidstr;
963 if ( IS_LOCKED (ctrl) )
964 return gpg_error (GPG_ERR_LOCKED);
966 if ((rc = open_card (ctrl, NULL)))
967 return rc;
969 if (!ctrl->app_ctx)
970 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
972 /* We have to use a copy of the key ID because the function may use
973 the pin_cb which in turn uses the assuan line buffer and thus
974 overwriting the original line with the keyid */
975 keyidstr = xtrystrdup (line);
976 if (!keyidstr)
977 return out_of_core ();
979 rc = app_auth (ctrl->app_ctx,
980 keyidstr,
981 pin_cb, ctx,
982 ctrl->in_data.value, ctrl->in_data.valuelen,
983 &outdata, &outdatalen);
984 xfree (keyidstr);
985 if (rc)
987 log_error ("app_auth failed: %s\n", gpg_strerror (rc));
989 else
991 rc = assuan_send_data (ctx, outdata, outdatalen);
992 xfree (outdata);
993 if (rc)
994 return rc; /* that is already an assuan error code */
997 TEST_CARD_REMOVAL (ctrl, rc);
998 return rc;
1001 /* PKDECRYPT <hexified_id>
1004 static gpg_error_t
1005 cmd_pkdecrypt (assuan_context_t ctx, char *line)
1007 ctrl_t ctrl = assuan_get_pointer (ctx);
1008 int rc;
1009 unsigned char *outdata;
1010 size_t outdatalen;
1011 char *keyidstr;
1013 if ( IS_LOCKED (ctrl) )
1014 return gpg_error (GPG_ERR_LOCKED);
1016 if ((rc = open_card (ctrl, NULL)))
1017 return rc;
1019 keyidstr = xtrystrdup (line);
1020 if (!keyidstr)
1021 return out_of_core ();
1022 rc = app_decipher (ctrl->app_ctx,
1023 keyidstr,
1024 pin_cb, ctx,
1025 ctrl->in_data.value, ctrl->in_data.valuelen,
1026 &outdata, &outdatalen);
1028 xfree (keyidstr);
1029 if (rc)
1031 log_error ("app_decipher failed: %s\n", gpg_strerror (rc));
1033 else
1035 rc = assuan_send_data (ctx, outdata, outdatalen);
1036 xfree (outdata);
1037 if (rc)
1038 return rc; /* that is already an assuan error code */
1041 TEST_CARD_REMOVAL (ctrl, rc);
1042 return rc;
1046 /* GETATTR <name>
1048 This command is used to retrieve data from a smartcard. The
1049 allowed names depend on the currently selected smartcard
1050 application. NAME must be percent and '+' escaped. The value is
1051 returned through status message, see the LEARN command for details.
1053 However, the current implementation assumes that Name is not escaped;
1054 this works as long as noone uses arbitrary escaping.
1056 Note, that this function may even be used on a locked card.
1058 static gpg_error_t
1059 cmd_getattr (assuan_context_t ctx, char *line)
1061 ctrl_t ctrl = assuan_get_pointer (ctx);
1062 int rc;
1063 const char *keyword;
1065 if ((rc = open_card (ctrl, NULL)))
1066 return rc;
1068 keyword = line;
1069 for (; *line && !spacep (line); line++)
1071 if (*line)
1072 *line++ = 0;
1074 /* (We ignore any garbage for now.) */
1076 /* FIXME: Applications should not return sensitive data if the card
1077 is locked. */
1078 rc = app_getattr (ctrl->app_ctx, ctrl, keyword);
1080 TEST_CARD_REMOVAL (ctrl, rc);
1081 return rc;
1085 /* SETATTR <name> <value>
1087 This command is used to store data on a a smartcard. The allowed
1088 names and values are depend on the currently selected smartcard
1089 application. NAME and VALUE must be percent and '+' escaped.
1091 However, the current implementation assumes that NAME is not
1092 escaped; this works as long as noone uses arbitrary escaping.
1094 A PIN will be requested for most NAMEs. See the corresponding
1095 setattr function of the actually used application (app-*.c) for
1096 details. */
1097 static gpg_error_t
1098 cmd_setattr (assuan_context_t ctx, char *orig_line)
1100 ctrl_t ctrl = assuan_get_pointer (ctx);
1101 int rc;
1102 char *keyword;
1103 int keywordlen;
1104 size_t nbytes;
1105 char *line, *linebuf;
1107 if ( IS_LOCKED (ctrl) )
1108 return gpg_error (GPG_ERR_LOCKED);
1110 if ((rc = open_card (ctrl, NULL)))
1111 return rc;
1113 /* We need to use a copy of LINE, because PIN_CB uses the same
1114 context and thus reuses the Assuan provided LINE. */
1115 line = linebuf = xtrystrdup (orig_line);
1116 if (!line)
1117 return out_of_core ();
1119 keyword = line;
1120 for (keywordlen=0; *line && !spacep (line); line++, keywordlen++)
1122 if (*line)
1123 *line++ = 0;
1124 while (spacep (line))
1125 line++;
1126 nbytes = percent_plus_unescape_inplace (line, 0);
1128 rc = app_setattr (ctrl->app_ctx, keyword, pin_cb, ctx,
1129 (const unsigned char*)line, nbytes);
1130 xfree (linebuf);
1132 TEST_CARD_REMOVAL (ctrl, rc);
1133 return rc;
1138 /* WRITECERT <hexified_certid>
1140 This command is used to store a certifciate on a smartcard. The
1141 allowed certids depend on the currently selected smartcard
1142 application. The actual certifciate is requested using the inquiry
1143 "CERTDATA" and needs to be provided in its raw (e.g. DER) form.
1145 In almost all cases a a PIN will be requested. See the related
1146 writecert function of the actually used application (app-*.c) for
1147 details. */
1148 static gpg_error_t
1149 cmd_writecert (assuan_context_t ctx, char *line)
1151 ctrl_t ctrl = assuan_get_pointer (ctx);
1152 int rc;
1153 char *certid;
1154 unsigned char *certdata;
1155 size_t certdatalen;
1157 if ( IS_LOCKED (ctrl) )
1158 return gpg_error (GPG_ERR_LOCKED);
1160 line = skip_options (line);
1162 if (!*line)
1163 return set_error (GPG_ERR_ASS_PARAMETER, "no certid given");
1164 certid = line;
1165 while (*line && !spacep (line))
1166 line++;
1167 *line = 0;
1169 if ((rc = open_card (ctrl, NULL)))
1170 return rc;
1172 if (!ctrl->app_ctx)
1173 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
1175 certid = xtrystrdup (certid);
1176 if (!certid)
1177 return out_of_core ();
1179 /* Now get the actual keydata. */
1180 rc = assuan_inquire (ctx, "CERTDATA",
1181 &certdata, &certdatalen, MAXLEN_CERTDATA);
1182 if (rc)
1184 xfree (certid);
1185 return rc;
1188 /* Write the certificate to the card. */
1189 rc = app_writecert (ctrl->app_ctx, ctrl, certid,
1190 pin_cb, ctx, certdata, certdatalen);
1191 xfree (certid);
1192 xfree (certdata);
1194 TEST_CARD_REMOVAL (ctrl, rc);
1195 return rc;
1200 /* WRITEKEY [--force] <keyid>
1202 This command is used to store a secret key on a a smartcard. The
1203 allowed keyids depend on the currently selected smartcard
1204 application. The actual keydata is requested using the inquiry
1205 "KEYDATA" and need to be provided without any protection. With
1206 --force set an existing key under this KEYID will get overwritten.
1207 The keydata is expected to be the usual canonical encoded
1208 S-expression.
1210 A PIN will be requested for most NAMEs. See the corresponding
1211 writekey function of the actually used application (app-*.c) for
1212 details. */
1213 static gpg_error_t
1214 cmd_writekey (assuan_context_t ctx, char *line)
1216 ctrl_t ctrl = assuan_get_pointer (ctx);
1217 int rc;
1218 char *keyid;
1219 int force = has_option (line, "--force");
1220 unsigned char *keydata;
1221 size_t keydatalen;
1223 if ( IS_LOCKED (ctrl) )
1224 return gpg_error (GPG_ERR_LOCKED);
1226 line = skip_options (line);
1228 if (!*line)
1229 return set_error (GPG_ERR_ASS_PARAMETER, "no keyid given");
1230 keyid = line;
1231 while (*line && !spacep (line))
1232 line++;
1233 *line = 0;
1235 if ((rc = open_card (ctrl, NULL)))
1236 return rc;
1238 if (!ctrl->app_ctx)
1239 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
1241 keyid = xtrystrdup (keyid);
1242 if (!keyid)
1243 return out_of_core ();
1245 /* Now get the actual keydata. */
1246 assuan_begin_confidential (ctx);
1247 rc = assuan_inquire (ctx, "KEYDATA", &keydata, &keydatalen, MAXLEN_KEYDATA);
1248 assuan_end_confidential (ctx);
1249 if (rc)
1251 xfree (keyid);
1252 return rc;
1255 /* Write the key to the card. */
1256 rc = app_writekey (ctrl->app_ctx, ctrl, keyid, force? 1:0,
1257 pin_cb, ctx, keydata, keydatalen);
1258 xfree (keyid);
1259 xfree (keydata);
1261 TEST_CARD_REMOVAL (ctrl, rc);
1262 return rc;
1267 /* GENKEY [--force] [--timestamp=<isodate>] <no>
1269 Generate a key on-card identified by NO, which is application
1270 specific. Return values are application specific. For OpenPGP
1271 cards 2 status lines are returned:
1273 S KEY-FPR <hexstring>
1274 S KEY-CREATED-AT <seconds_since_epoch>
1275 S KEY-DATA [p|n] <hexdata>
1277 --force is required to overwrite an already existing key. The
1278 KEY-CREATED-AT is required for further processing because it is
1279 part of the hashed key material for the fingerprint.
1281 If --timestamp is given an OpenPGP key will be created using this
1282 value. The value needs to be in ISO Format; e.g.
1283 "--timestamp=20030316T120000" and after 1970-01-01 00:00:00.
1285 The public part of the key can also later be retrieved using the
1286 READKEY command.
1289 static gpg_error_t
1290 cmd_genkey (assuan_context_t ctx, char *line)
1292 ctrl_t ctrl = assuan_get_pointer (ctx);
1293 int rc;
1294 char *keyno;
1295 int force;
1296 const char *s;
1297 time_t timestamp;
1299 if ( IS_LOCKED (ctrl) )
1300 return gpg_error (GPG_ERR_LOCKED);
1302 force = has_option (line, "--force");
1304 if ((s=has_option_name (line, "--timestamp")))
1306 if (*s != '=')
1307 return set_error (GPG_ERR_ASS_PARAMETER, "missing value for option");
1308 timestamp = isotime2epoch (s+1);
1309 if (timestamp < 1)
1310 return set_error (GPG_ERR_ASS_PARAMETER, "invalid time value");
1312 else
1313 timestamp = 0;
1316 line = skip_options (line);
1317 if (!*line)
1318 return set_error (GPG_ERR_ASS_PARAMETER, "no key number given");
1319 keyno = line;
1320 while (*line && !spacep (line))
1321 line++;
1322 *line = 0;
1324 if ((rc = open_card (ctrl, NULL)))
1325 return rc;
1327 if (!ctrl->app_ctx)
1328 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
1330 keyno = xtrystrdup (keyno);
1331 if (!keyno)
1332 return out_of_core ();
1333 rc = app_genkey (ctrl->app_ctx, ctrl, keyno, force? 1:0,
1334 timestamp, pin_cb, ctx);
1335 xfree (keyno);
1337 TEST_CARD_REMOVAL (ctrl, rc);
1338 return rc;
1342 /* RANDOM <nbytes>
1344 Get NBYTES of random from the card and send them back as data.
1346 Note, that this function may be even be used on a locked card.
1348 static gpg_error_t
1349 cmd_random (assuan_context_t ctx, char *line)
1351 ctrl_t ctrl = assuan_get_pointer (ctx);
1352 int rc;
1353 size_t nbytes;
1354 unsigned char *buffer;
1356 if (!*line)
1357 return set_error (GPG_ERR_ASS_PARAMETER, "number of requested bytes missing");
1358 nbytes = strtoul (line, NULL, 0);
1360 if ((rc = open_card (ctrl, NULL)))
1361 return rc;
1363 if (!ctrl->app_ctx)
1364 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
1366 buffer = xtrymalloc (nbytes);
1367 if (!buffer)
1368 return out_of_core ();
1370 rc = app_get_challenge (ctrl->app_ctx, nbytes, buffer);
1371 if (!rc)
1373 rc = assuan_send_data (ctx, buffer, nbytes);
1374 xfree (buffer);
1375 return rc; /* that is already an assuan error code */
1377 xfree (buffer);
1379 TEST_CARD_REMOVAL (ctrl, rc);
1380 return rc;
1384 /* PASSWD [--reset] [--nullpin] <chvno>
1386 Change the PIN or, if --reset is given, reset the retry counter of
1387 the card holder verfication vector CHVNO. The option --nullpin is
1388 used for TCOS cards to set the initial PIN. The format of CHVNO
1389 depends on the card application. */
1390 static gpg_error_t
1391 cmd_passwd (assuan_context_t ctx, char *line)
1393 ctrl_t ctrl = assuan_get_pointer (ctx);
1394 int rc;
1395 char *chvnostr;
1396 unsigned int flags = 0;
1398 if (has_option (line, "--reset"))
1399 flags |= APP_CHANGE_FLAG_RESET;
1400 if (has_option (line, "--nullpin"))
1401 flags |= APP_CHANGE_FLAG_NULLPIN;
1403 if ( IS_LOCKED (ctrl) )
1404 return gpg_error (GPG_ERR_LOCKED);
1406 line = skip_options (line);
1408 if (!*line)
1409 return set_error (GPG_ERR_ASS_PARAMETER, "no CHV number given");
1410 chvnostr = line;
1411 while (*line && !spacep (line))
1412 line++;
1413 *line = 0;
1415 if ((rc = open_card (ctrl, NULL)))
1416 return rc;
1418 if (!ctrl->app_ctx)
1419 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
1421 chvnostr = xtrystrdup (chvnostr);
1422 if (!chvnostr)
1423 return out_of_core ();
1424 rc = app_change_pin (ctrl->app_ctx, ctrl, chvnostr, flags, pin_cb, ctx);
1425 if (rc)
1426 log_error ("command passwd failed: %s\n", gpg_strerror (rc));
1427 xfree (chvnostr);
1429 TEST_CARD_REMOVAL (ctrl, rc);
1430 return rc;
1434 /* CHECKPIN <idstr>
1436 Perform a VERIFY operation without doing anything else. This may
1437 be used to initialize a the PIN cache earlier to long lasting
1438 operations. Its use is highly application dependent.
1440 For OpenPGP:
1442 Perform a simple verify operation for CHV1 and CHV2, so that
1443 further operations won't ask for CHV2 and it is possible to do a
1444 cheap check on the PIN: If there is something wrong with the PIN
1445 entry system, only the regular CHV will get blocked and not the
1446 dangerous CHV3. IDSTR is the usual card's serial number in hex
1447 notation; an optional fingerprint part will get ignored. There
1448 is however a special mode if the IDSTR is sffixed with the
1449 literal string "[CHV3]": In this case the Admin PIN is checked
1450 if and only if the retry counter is still at 3.
1452 For Netkey:
1454 Any of the valid PIN Ids may be used. These are the strings:
1456 PW1.CH - Global password 1
1457 PW2.CH - Global password 2
1458 PW1.CH.SIG - SigG password 1
1459 PW2.CH.SIG - SigG password 2
1461 For a definitive list, see the implementation in app-nks.c.
1462 Note that we call a PW2.* PIN a "PUK" despite that since TCOS
1463 3.0 they are technically alternative PINs used to mutally
1464 unblock each other.
1467 static gpg_error_t
1468 cmd_checkpin (assuan_context_t ctx, char *line)
1470 ctrl_t ctrl = assuan_get_pointer (ctx);
1471 int rc;
1472 char *idstr;
1474 if ( IS_LOCKED (ctrl) )
1475 return gpg_error (GPG_ERR_LOCKED);
1477 if ((rc = open_card (ctrl, NULL)))
1478 return rc;
1480 if (!ctrl->app_ctx)
1481 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
1483 /* We have to use a copy of the key ID because the function may use
1484 the pin_cb which in turn uses the assuan line buffer and thus
1485 overwriting the original line with the keyid. */
1486 idstr = xtrystrdup (line);
1487 if (!idstr)
1488 return out_of_core ();
1490 rc = app_check_pin (ctrl->app_ctx, idstr, pin_cb, ctx);
1491 xfree (idstr);
1492 if (rc)
1493 log_error ("app_check_pin failed: %s\n", gpg_strerror (rc));
1495 TEST_CARD_REMOVAL (ctrl, rc);
1496 return rc;
1500 /* LOCK [--wait]
1502 Grant exclusive card access to this session. Note that there is
1503 no lock counter used and a second lock from the same session will
1504 be ignored. A single unlock (or RESET) unlocks the session.
1505 Return GPG_ERR_LOCKED if another session has locked the reader.
1507 If the option --wait is given the command will wait until a
1508 lock has been released.
1510 static gpg_error_t
1511 cmd_lock (assuan_context_t ctx, char *line)
1513 ctrl_t ctrl = assuan_get_pointer (ctx);
1514 int rc = 0;
1516 retry:
1517 if (locked_session)
1519 if (locked_session != ctrl->server_local)
1520 rc = gpg_error (GPG_ERR_LOCKED);
1522 else
1523 locked_session = ctrl->server_local;
1525 #ifdef USE_GNU_PTH
1526 if (rc && has_option (line, "--wait"))
1528 rc = 0;
1529 pth_sleep (1); /* Better implement an event mechanism. However,
1530 for card operations this should be
1531 sufficient. */
1532 /* FIXME: Need to check that the connection is still alive.
1533 This can be done by issuing status messages. */
1534 goto retry;
1536 #endif /*USE_GNU_PTH*/
1538 if (rc)
1539 log_error ("cmd_lock failed: %s\n", gpg_strerror (rc));
1540 return rc;
1544 /* UNLOCK
1546 Release exclusive card access.
1548 static gpg_error_t
1549 cmd_unlock (assuan_context_t ctx, char *line)
1551 ctrl_t ctrl = assuan_get_pointer (ctx);
1552 int rc = 0;
1554 (void)line;
1556 if (locked_session)
1558 if (locked_session != ctrl->server_local)
1559 rc = gpg_error (GPG_ERR_LOCKED);
1560 else
1561 locked_session = NULL;
1563 else
1564 rc = gpg_error (GPG_ERR_NOT_LOCKED);
1566 if (rc)
1567 log_error ("cmd_unlock failed: %s\n", gpg_strerror (rc));
1568 return rc;
1572 /* GETINFO <what>
1574 Multi purpose command to return certain information.
1575 Supported values of WHAT are:
1577 version - Return the version of the program.
1578 pid - Return the process id of the server.
1580 socket_name - Return the name of the socket.
1582 status - Return the status of the current slot (in the future, may
1583 also return the status of all slots). The status is a list of
1584 one-character flags. The following flags are currently defined:
1585 'u' Usable card present. This is the normal state during operation.
1586 'r' Card removed. A reset is necessary.
1587 These flags are exclusive.
1589 reader_list - Return a list of detected card readers. Does
1590 currently only work with the internal CCID driver.
1592 deny_admin - Returns OK if admin commands are not allowed or
1593 GPG_ERR_GENERAL if admin commands are allowed.
1595 app_list - Return a list of supported applications. One
1596 application per line, fields delimited by colons,
1597 first field is the name.
1600 static gpg_error_t
1601 cmd_getinfo (assuan_context_t ctx, char *line)
1603 int rc = 0;
1605 if (!strcmp (line, "version"))
1607 const char *s = VERSION;
1608 rc = assuan_send_data (ctx, s, strlen (s));
1610 else if (!strcmp (line, "pid"))
1612 char numbuf[50];
1614 snprintf (numbuf, sizeof numbuf, "%lu", (unsigned long)getpid ());
1615 rc = assuan_send_data (ctx, numbuf, strlen (numbuf));
1617 else if (!strcmp (line, "socket_name"))
1619 const char *s = scd_get_socket_name ();
1621 if (s)
1622 rc = assuan_send_data (ctx, s, strlen (s));
1623 else
1624 rc = gpg_error (GPG_ERR_NO_DATA);
1626 else if (!strcmp (line, "status"))
1628 ctrl_t ctrl = assuan_get_pointer (ctx);
1629 int slot = ctrl->reader_slot;
1630 char flag = 'r';
1632 if (!ctrl->server_local->card_removed && slot != -1)
1634 struct slot_status_s *ss;
1636 if (!(slot >= 0 && slot < DIM(slot_table)))
1637 BUG ();
1639 ss = &slot_table[slot];
1641 if (!ss->valid)
1642 BUG ();
1644 if (ss->any && (ss->status & 1))
1645 flag = 'u';
1647 rc = assuan_send_data (ctx, &flag, 1);
1649 else if (!strcmp (line, "reader_list"))
1651 #ifdef HAVE_LIBUSB
1652 char *s = ccid_get_reader_list ();
1653 #else
1654 char *s = NULL;
1655 #endif
1657 if (s)
1658 rc = assuan_send_data (ctx, s, strlen (s));
1659 else
1660 rc = gpg_error (GPG_ERR_NO_DATA);
1661 xfree (s);
1663 else if (!strcmp (line, "deny_admin"))
1664 rc = opt.allow_admin? gpg_error (GPG_ERR_GENERAL) : 0;
1665 else if (!strcmp (line, "app_list"))
1667 char *s = get_supported_applications ();
1668 if (s)
1669 rc = assuan_send_data (ctx, s, strlen (s));
1670 else
1671 rc = 0;
1672 xfree (s);
1674 else
1675 rc = set_error (GPG_ERR_ASS_PARAMETER, "unknown value for WHAT");
1676 return rc;
1680 /* RESTART
1682 Restart the current connection; this is a kind of warm reset. It
1683 deletes the context used by this connection but does not send a
1684 RESET to the card. Thus the card itself won't get reset.
1686 This is used by gpg-agent to reuse a primary pipe connection and
1687 may be used by clients to backup from a conflict in the serial
1688 command; i.e. to select another application.
1691 static gpg_error_t
1692 cmd_restart (assuan_context_t ctx, char *line)
1694 ctrl_t ctrl = assuan_get_pointer (ctx);
1696 (void)line;
1698 if (ctrl->app_ctx)
1700 release_application (ctrl->app_ctx);
1701 ctrl->app_ctx = NULL;
1703 if (locked_session && ctrl->server_local == locked_session)
1705 locked_session = NULL;
1706 log_info ("implicitly unlocking due to RESTART\n");
1708 return 0;
1712 /* DISCONNECT
1714 Disconnect the card if it is not any longer used by other
1715 connections and the backend supports a disconnect operation.
1717 static gpg_error_t
1718 cmd_disconnect (assuan_context_t ctx, char *line)
1720 ctrl_t ctrl = assuan_get_pointer (ctx);
1722 (void)line;
1724 ctrl->server_local->disconnect_allowed = 1;
1725 return 0;
1730 /* APDU [--atr] [--more] [--exlen[=N]] [hexstring]
1732 Send an APDU to the current reader. This command bypasses the high
1733 level functions and sends the data directly to the card. HEXSTRING
1734 is expected to be a proper APDU. If HEXSTRING is not given no
1735 commands are set to the card but the command will implictly check
1736 whether the card is ready for use.
1738 Using the option "--atr" returns the ATR of the card as a status
1739 message before any data like this:
1740 S CARD-ATR 3BFA1300FF813180450031C173C00100009000B1
1742 Using the option --more handles the card status word MORE_DATA
1743 (61xx) and concatenates all reponses to one block.
1745 Using the option "--exlen" the returned APDU may use extended
1746 length up to N bytes. If N is not given a default value is used
1747 (currently 4096).
1749 static gpg_error_t
1750 cmd_apdu (assuan_context_t ctx, char *line)
1752 ctrl_t ctrl = assuan_get_pointer (ctx);
1753 int rc;
1754 unsigned char *apdu;
1755 size_t apdulen;
1756 int with_atr;
1757 int handle_more;
1758 const char *s;
1759 size_t exlen;
1761 with_atr = has_option (line, "--atr");
1762 handle_more = has_option (line, "--more");
1764 if ((s=has_option_name (line, "--exlen")))
1766 if (*s == '=')
1767 exlen = strtoul (s+1, NULL, 0);
1768 else
1769 exlen = 4096;
1771 else
1772 exlen = 0;
1774 line = skip_options (line);
1776 if ( IS_LOCKED (ctrl) )
1777 return gpg_error (GPG_ERR_LOCKED);
1779 if ((rc = open_card (ctrl, NULL)))
1780 return rc;
1782 if (with_atr)
1784 unsigned char *atr;
1785 size_t atrlen;
1786 char hexbuf[400];
1788 atr = apdu_get_atr (ctrl->reader_slot, &atrlen);
1789 if (!atr || atrlen > sizeof hexbuf - 2 )
1791 rc = gpg_error (GPG_ERR_INV_CARD);
1792 goto leave;
1794 bin2hex (atr, atrlen, hexbuf);
1795 xfree (atr);
1796 send_status_info (ctrl, "CARD-ATR", hexbuf, strlen (hexbuf), NULL, 0);
1799 apdu = hex_to_buffer (line, &apdulen);
1800 if (!apdu)
1802 rc = gpg_error_from_syserror ();
1803 goto leave;
1805 if (apdulen)
1807 unsigned char *result = NULL;
1808 size_t resultlen;
1810 rc = apdu_send_direct (ctrl->reader_slot, exlen,
1811 apdu, apdulen, handle_more,
1812 &result, &resultlen);
1813 if (rc)
1814 log_error ("apdu_send_direct failed: %s\n", gpg_strerror (rc));
1815 else
1817 rc = assuan_send_data (ctx, result, resultlen);
1818 xfree (result);
1821 xfree (apdu);
1823 leave:
1824 TEST_CARD_REMOVAL (ctrl, rc);
1825 return rc;
1829 /* KILLSCD - Commit suicide. */
1830 static gpg_error_t
1831 cmd_killscd (assuan_context_t ctx, char *line)
1833 ctrl_t ctrl = assuan_get_pointer (ctx);
1835 (void)line;
1837 ctrl->server_local->stopme = 1;
1838 return gpg_error (GPG_ERR_EOF);
1843 /* Tell the assuan library about our commands */
1844 static int
1845 register_commands (assuan_context_t ctx)
1847 static struct {
1848 const char *name;
1849 assuan_handler_t handler;
1850 } table[] = {
1851 { "SERIALNO", cmd_serialno },
1852 { "LEARN", cmd_learn },
1853 { "READCERT", cmd_readcert },
1854 { "READKEY", cmd_readkey },
1855 { "SETDATA", cmd_setdata },
1856 { "PKSIGN", cmd_pksign },
1857 { "PKAUTH", cmd_pkauth },
1858 { "PKDECRYPT", cmd_pkdecrypt },
1859 { "INPUT", NULL },
1860 { "OUTPUT", NULL },
1861 { "GETATTR", cmd_getattr },
1862 { "SETATTR", cmd_setattr },
1863 { "WRITECERT", cmd_writecert },
1864 { "WRITEKEY", cmd_writekey },
1865 { "GENKEY", cmd_genkey },
1866 { "RANDOM", cmd_random },
1867 { "PASSWD", cmd_passwd },
1868 { "CHECKPIN", cmd_checkpin },
1869 { "LOCK", cmd_lock },
1870 { "UNLOCK", cmd_unlock },
1871 { "GETINFO", cmd_getinfo },
1872 { "RESTART", cmd_restart },
1873 { "DISCONNECT", cmd_disconnect },
1874 { "APDU", cmd_apdu },
1875 { "KILLSCD", cmd_killscd },
1876 { NULL }
1878 int i, rc;
1880 for (i=0; table[i].name; i++)
1882 rc = assuan_register_command (ctx, table[i].name, table[i].handler);
1883 if (rc)
1884 return rc;
1886 assuan_set_hello_line (ctx, "GNU Privacy Guard's Smartcard server ready");
1888 assuan_register_reset_notify (ctx, reset_notify);
1889 assuan_register_option_handler (ctx, option_handler);
1890 return 0;
1894 /* Startup the server. If FD is given as -1 this is simple pipe
1895 server, otherwise it is a regular server. Returns true if there
1896 are no more active asessions. */
1898 scd_command_handler (ctrl_t ctrl, int fd)
1900 int rc;
1901 assuan_context_t ctx = NULL;
1902 int stopme;
1904 rc = assuan_new (&ctx);
1905 if (rc)
1907 log_error ("failed to allocate assuan context: %s\n",
1908 gpg_strerror (rc));
1909 scd_exit (2);
1912 if (fd == -1)
1914 int filedes[2];
1916 filedes[0] = 0;
1917 filedes[1] = 1;
1918 rc = assuan_init_pipe_server (ctx, filedes);
1920 else
1922 rc = assuan_init_socket_server_ext (ctx, INT2FD(fd), 2);
1924 if (rc)
1926 log_error ("failed to initialize the server: %s\n",
1927 gpg_strerror(rc));
1928 scd_exit (2);
1930 rc = register_commands (ctx);
1931 if (rc)
1933 log_error ("failed to register commands with Assuan: %s\n",
1934 gpg_strerror(rc));
1935 scd_exit (2);
1937 assuan_set_pointer (ctx, ctrl);
1939 /* Allocate and initialize the server object. Put it into the list
1940 of active sessions. */
1941 ctrl->server_local = xcalloc (1, sizeof *ctrl->server_local);
1942 ctrl->server_local->next_session = session_list;
1943 session_list = ctrl->server_local;
1944 ctrl->server_local->ctrl_backlink = ctrl;
1945 ctrl->server_local->assuan_ctx = ctx;
1947 if (DBG_ASSUAN)
1948 assuan_set_log_stream (ctx, log_get_stream ());
1950 /* We open the reader right at startup so that the ticker is able to
1951 update the status file. */
1952 if (ctrl->reader_slot == -1)
1954 ctrl->reader_slot = get_reader_slot ();
1957 /* Command processing loop. */
1958 for (;;)
1960 rc = assuan_accept (ctx);
1961 if (rc == -1)
1963 break;
1965 else if (rc)
1967 log_info ("Assuan accept problem: %s\n", gpg_strerror (rc));
1968 break;
1971 rc = assuan_process (ctx);
1972 if (rc)
1974 log_info ("Assuan processing failed: %s\n", gpg_strerror (rc));
1975 continue;
1979 /* Cleanup. We don't send an explicit reset to the card. */
1980 do_reset (ctrl, 0);
1982 /* Release the server object. */
1983 if (session_list == ctrl->server_local)
1984 session_list = ctrl->server_local->next_session;
1985 else
1987 struct server_local_s *sl;
1989 for (sl=session_list; sl->next_session; sl = sl->next_session)
1990 if (sl->next_session == ctrl->server_local)
1991 break;
1992 if (!sl->next_session)
1993 BUG ();
1994 sl->next_session = ctrl->server_local->next_session;
1996 stopme = ctrl->server_local->stopme;
1997 xfree (ctrl->server_local);
1998 ctrl->server_local = NULL;
2000 /* Release the Assuan context. */
2001 assuan_release (ctx);
2003 if (stopme)
2004 scd_exit (0);
2006 /* If there are no more sessions return true. */
2007 return !session_list;
2011 /* Send a line with status information via assuan and escape all given
2012 buffers. The variable elements are pairs of (char *, size_t),
2013 terminated with a (NULL, 0). */
2014 void
2015 send_status_info (ctrl_t ctrl, const char *keyword, ...)
2017 va_list arg_ptr;
2018 const unsigned char *value;
2019 size_t valuelen;
2020 char buf[950], *p;
2021 size_t n;
2022 assuan_context_t ctx = ctrl->server_local->assuan_ctx;
2024 va_start (arg_ptr, keyword);
2026 p = buf;
2027 n = 0;
2028 while ( (value = va_arg (arg_ptr, const unsigned char *)) )
2030 valuelen = va_arg (arg_ptr, size_t);
2031 if (!valuelen)
2032 continue; /* empty buffer */
2033 if (n)
2035 *p++ = ' ';
2036 n++;
2038 for ( ; valuelen && n < DIM (buf)-2; n++, valuelen--, value++)
2040 if (*value < ' ' || *value == '+')
2042 sprintf (p, "%%%02X", *value);
2043 p += 3;
2045 else if (*value == ' ')
2046 *p++ = '+';
2047 else
2048 *p++ = *value;
2051 *p = 0;
2052 assuan_write_status (ctx, keyword, buf);
2054 va_end (arg_ptr);
2058 /* Send a ready formatted status line via assuan. */
2059 void
2060 send_status_direct (ctrl_t ctrl, const char *keyword, const char *args)
2062 assuan_context_t ctx = ctrl->server_local->assuan_ctx;
2064 if (strchr (args, '\n'))
2065 log_error ("error: LF detected in status line - not sending\n");
2066 else
2067 assuan_write_status (ctx, keyword, args);
2071 /* Helper to send the clients a status change notification. */
2072 static void
2073 send_client_notifications (void)
2075 struct {
2076 pid_t pid;
2077 #ifdef HAVE_W32_SYSTEM
2078 HANDLE handle;
2079 #else
2080 int signo;
2081 #endif
2082 } killed[50];
2083 int killidx = 0;
2084 int kidx;
2085 struct server_local_s *sl;
2087 for (sl=session_list; sl; sl = sl->next_session)
2089 if (sl->event_signal && sl->assuan_ctx)
2091 pid_t pid = assuan_get_pid (sl->assuan_ctx);
2092 #ifdef HAVE_W32_SYSTEM
2093 HANDLE handle = (void *)sl->event_signal;
2095 for (kidx=0; kidx < killidx; kidx++)
2096 if (killed[kidx].pid == pid
2097 && killed[kidx].handle == handle)
2098 break;
2099 if (kidx < killidx)
2100 log_info ("event %lx (%p) already triggered for client %d\n",
2101 sl->event_signal, handle, (int)pid);
2102 else
2104 log_info ("triggering event %lx (%p) for client %d\n",
2105 sl->event_signal, handle, (int)pid);
2106 if (!SetEvent (handle))
2107 log_error ("SetEvent(%lx) failed: %s\n",
2108 sl->event_signal, w32_strerror (-1));
2109 if (killidx < DIM (killed))
2111 killed[killidx].pid = pid;
2112 killed[killidx].handle = handle;
2113 killidx++;
2116 #else /*!HAVE_W32_SYSTEM*/
2117 int signo = sl->event_signal;
2119 if (pid != (pid_t)(-1) && pid && signo > 0)
2121 for (kidx=0; kidx < killidx; kidx++)
2122 if (killed[kidx].pid == pid
2123 && killed[kidx].signo == signo)
2124 break;
2125 if (kidx < killidx)
2126 log_info ("signal %d already sent to client %d\n",
2127 signo, (int)pid);
2128 else
2130 log_info ("sending signal %d to client %d\n",
2131 signo, (int)pid);
2132 kill (pid, signo);
2133 if (killidx < DIM (killed))
2135 killed[killidx].pid = pid;
2136 killed[killidx].signo = signo;
2137 killidx++;
2141 #endif /*!HAVE_W32_SYSTEM*/
2148 /* This is the core of scd_update_reader_status_file but the caller
2149 needs to take care of the locking. */
2150 static void
2151 update_reader_status_file (int set_card_removed_flag)
2153 int idx;
2154 unsigned int status, changed;
2156 /* Make sure that the reader has been opened. Like get_reader_slot,
2157 this part of the code assumes that there is only one reader. */
2158 if (!slot_table[0].valid)
2159 (void)get_reader_slot ();
2161 /* Note, that we only try to get the status, because it does not
2162 make sense to wait here for a operation to complete. If we are
2163 busy working with a card, delays in the status file update should
2164 be acceptable. */
2165 for (idx=0; idx < DIM(slot_table); idx++)
2167 struct slot_status_s *ss = slot_table + idx;
2168 struct server_local_s *sl;
2169 int sw_apdu;
2171 if (!ss->valid || ss->slot == -1)
2172 continue; /* Not valid or reader not yet open. */
2174 sw_apdu = apdu_get_status (ss->slot, 0, &status, &changed);
2175 if (sw_apdu == SW_HOST_NO_READER)
2177 /* Most likely the _reader_ has been unplugged. */
2178 status = 0;
2179 changed = ss->changed;
2181 else if (sw_apdu)
2183 /* Get status failed. Ignore that. */
2184 continue;
2187 if (!ss->any || ss->status != status || ss->changed != changed )
2189 char *fname;
2190 char templ[50];
2191 FILE *fp;
2193 log_info ("updating slot %d status: 0x%04X->0x%04X (%u->%u)\n",
2194 ss->slot, ss->status, status, ss->changed, changed);
2195 ss->status = status;
2196 ss->changed = changed;
2198 /* FIXME: Should this be IDX instead of ss->slot? This
2199 depends on how client sessions will associate the reader
2200 status with their session. */
2201 snprintf (templ, sizeof templ, "reader_%d.status", ss->slot);
2202 fname = make_filename (opt.homedir, templ, NULL );
2203 fp = fopen (fname, "w");
2204 if (fp)
2206 fprintf (fp, "%s\n",
2207 (status & 1)? "USABLE":
2208 (status & 4)? "ACTIVE":
2209 (status & 2)? "PRESENT": "NOCARD");
2210 fclose (fp);
2212 xfree (fname);
2214 /* If a status script is executable, run it. */
2216 const char *args[9], *envs[2];
2217 char numbuf1[30], numbuf2[30], numbuf3[30];
2218 char *homestr, *envstr;
2219 gpg_error_t err;
2221 homestr = make_filename (opt.homedir, NULL);
2222 if (estream_asprintf (&envstr, "GNUPGHOME=%s", homestr) < 0)
2223 log_error ("out of core while building environment\n");
2224 else
2226 envs[0] = envstr;
2227 envs[1] = NULL;
2229 sprintf (numbuf1, "%d", ss->slot);
2230 sprintf (numbuf2, "0x%04X", ss->status);
2231 sprintf (numbuf3, "0x%04X", status);
2232 args[0] = "--reader-port";
2233 args[1] = numbuf1;
2234 args[2] = "--old-code";
2235 args[3] = numbuf2;
2236 args[4] = "--new-code";
2237 args[5] = numbuf3;
2238 args[6] = "--status";
2239 args[7] = ((status & 1)? "USABLE":
2240 (status & 4)? "ACTIVE":
2241 (status & 2)? "PRESENT": "NOCARD");
2242 args[8] = NULL;
2244 fname = make_filename (opt.homedir, "scd-event", NULL);
2245 err = gnupg_spawn_process_detached (fname, args, envs);
2246 if (err && gpg_err_code (err) != GPG_ERR_ENOENT)
2247 log_error ("failed to run event handler `%s': %s\n",
2248 fname, gpg_strerror (err));
2249 xfree (fname);
2250 xfree (envstr);
2252 xfree (homestr);
2255 /* Set the card removed flag for all current sessions. We
2256 will set this on any card change because a reset or
2257 SERIALNO request must be done in any case. */
2258 if (ss->any && set_card_removed_flag)
2259 update_card_removed (idx, 1);
2261 ss->any = 1;
2263 /* Send a signal to all clients who applied for it. */
2264 send_client_notifications ();
2267 /* Check whether a disconnect is pending. */
2268 if (opt.card_timeout)
2270 for (sl=session_list; sl; sl = sl->next_session)
2271 if (!sl->disconnect_allowed)
2272 break;
2273 if (session_list && !sl)
2275 /* FIXME: Use a real timeout. */
2276 /* At least one connection and all allow a disconnect. */
2277 log_info ("disconnecting card in slot %d\n", ss->slot);
2278 apdu_disconnect (ss->slot);
2285 /* This function is called by the ticker thread to check for changes
2286 of the reader stati. It updates the reader status files and if
2287 requested by the caller also send a signal to the caller. */
2288 void
2289 scd_update_reader_status_file (void)
2291 if (!pth_mutex_acquire (&status_file_update_lock, 1, NULL))
2292 return; /* locked - give up. */
2293 update_reader_status_file (1);
2294 if (!pth_mutex_release (&status_file_update_lock))
2295 log_error ("failed to release status_file_update lock\n");