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/>.
36 #include "app-common.h"
37 #include "apdu.h" /* Required for apdu_*_reader (). */
40 #include "ccid-driver.h"
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) \
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); \
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). */
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. */
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
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. */
109 int event_signal
; /* Or 0 if not used. */
112 /* True if the card has been removed and a reset is required to
113 continue operation. */
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
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
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. */
160 initialize_module_command (void)
162 static int initialized
;
166 if (pth_mutex_init (&status_file_update_lock
))
172 /* Update the CARD_REMOVED element of all sessions using the reader
173 given by SLOT to VALUE. */
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. */
187 application_notify_card_reset (slot
);
192 /* Check whether the option NAME appears in LINE. Returns 1 or 0. */
194 has_option (const char *line
, const char *name
)
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
210 has_option_name (const char *line
, const char *name
)
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. */
225 skip_options (char *line
)
227 while ( *line
== '-' && line
[1] == '-' )
229 while (*line
&& !spacep (line
))
231 while (spacep (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
;
250 buffer
= xtrymalloc (strlen (string
)+1);
253 for (s
=string
, n
=0; *s
; s
++)
255 if (spacep (s
) || *s
== ':')
257 if (hexdigitp (s
) && hexdigitp (s
+1))
259 buffer
[n
++] = xtoi_2 (s
);
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. */
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
))))
282 /* If there is an active application, release it. Tell all other
283 sessions using the same application to release the
287 release_application (ctrl
->app_ctx
);
288 ctrl
->app_ctx
= NULL
;
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
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;
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;
342 reset_notify (assuan_context_t ctx
)
344 ctrl_t ctrl
= assuan_get_pointer (ctx
);
351 option_handler (assuan_context_t ctx
, const char *key
, const char *value
)
353 ctrl_t ctrl
= assuan_get_pointer (ctx
);
355 if (!strcmp (key
, "event-signal"))
357 /* A value of 0 is allowed to reset the event signal. */
358 #ifdef HAVE_W32_SYSTEM
360 return gpg_error (GPG_ERR_ASS_PARAMETER
);
361 ctrl
->server_local
->event_signal
= strtoul (value
, NULL
, 16);
363 int i
= *value
? atoi (value
) : -1;
365 return gpg_error (GPG_ERR_ASS_PARAMETER
);
366 ctrl
->server_local
->event_signal
= i
;
374 /* Return the slot of the current reader or open the reader if no
375 other sessions are using a reader. Note, that we currently support
376 only one reader but most of the code (except for this function)
377 should be able to cope with several readers. */
379 get_reader_slot (void)
381 struct slot_status_s
*ss
;
383 ss
= &slot_table
[0]; /* One reader for now. */
385 /* Initialize the item if needed. */
392 /* Try to open the reader. */
394 ss
->slot
= apdu_open_reader (opt
.reader_port
);
396 /* Return the slot_table index. */
400 /* If the card has not yet been opened, do it. Note that this
401 function returns an Assuan error, so don't map the error a second
404 open_card (ctrl_t ctrl
, const char *apptype
)
409 /* If we ever got a card not present error code, return that. Only
410 the SERIALNO command and a reset are able to clear from that
412 if (ctrl
->server_local
->card_removed
)
413 return gpg_error (GPG_ERR_CARD_REMOVED
);
415 if ( IS_LOCKED (ctrl
) )
416 return gpg_error (GPG_ERR_LOCKED
);
418 /* If the application has been marked for release do it now. We
419 can't do it immediately in do_reset because the application may
421 if (ctrl
->server_local
->app_ctx_marked_for_release
)
423 ctrl
->server_local
->app_ctx_marked_for_release
= 0;
424 release_application (ctrl
->app_ctx
);
425 ctrl
->app_ctx
= NULL
;
428 /* If we are already initialized for one specific application we
429 need to check that the client didn't requested a specific
430 application different from the one in use before we continue. */
432 return check_application_conflict (ctrl
, apptype
);
434 /* Setup the slot and select the application. */
435 if (ctrl
->reader_slot
!= -1)
436 slot
= ctrl
->reader_slot
;
438 slot
= get_reader_slot ();
439 ctrl
->reader_slot
= slot
;
441 err
= gpg_error (GPG_ERR_CARD
);
444 /* Fixme: We should move the apdu_connect call to
445 select_application. */
448 ctrl
->server_local
->disconnect_allowed
= 0;
449 sw
= apdu_connect (slot
);
450 if (sw
&& sw
!= SW_HOST_ALREADY_CONNECTED
)
452 if (sw
== SW_HOST_NO_CARD
)
453 err
= gpg_error (GPG_ERR_CARD_NOT_PRESENT
);
455 err
= gpg_error (GPG_ERR_CARD
);
458 err
= select_application (ctrl
, slot
, apptype
, &ctrl
->app_ctx
);
461 TEST_CARD_REMOVAL (ctrl
, err
);
466 /* SERIALNO [APPTYPE]
468 Return the serial number of the card using a status reponse. This
469 function should be used to check for the presence of a card.
471 If APPTYPE is given, an application of that type is selected and an
472 error is returned if the application is not supported or available.
473 The default is to auto-select the application using a hardwired
474 preference system. Note, that a future extension to this function
475 may allow to specify a list and order of applications to try.
477 This function is special in that it can be used to reset the card.
478 Most other functions will return an error when a card change has
479 been detected and the use of this function is therefore required.
481 Background: We want to keep the client clear of handling card
482 changes between operations; i.e. the client can assume that all
483 operations are done on the same card unless he calls this function.
486 cmd_serialno (assuan_context_t ctx
, char *line
)
488 ctrl_t ctrl
= assuan_get_pointer (ctx
);
490 char *serial_and_stamp
;
494 /* Clear the remove flag so that the open_card is able to reread it. */
495 if (ctrl
->server_local
->card_removed
)
497 if ( IS_LOCKED (ctrl
) )
498 return gpg_error (GPG_ERR_LOCKED
);
502 if ((rc
= open_card (ctrl
, *line
? line
:NULL
)))
505 rc
= app_get_serial_and_stamp (ctrl
->app_ctx
, &serial
, &stamp
);
509 rc
= estream_asprintf (&serial_and_stamp
, "%s %lu",
510 serial
, (unsigned long)stamp
);
513 return out_of_core ();
515 assuan_write_status (ctx
, "SERIALNO", serial_and_stamp
);
516 xfree (serial_and_stamp
);
523 /* LEARN [--force] [--keypairinfo]
525 Learn all useful information of the currently inserted card. When
526 used without the force options, the command might do an INQUIRE
529 INQUIRE KNOWNCARDP <hexstring_with_serialNumber> <timestamp>
531 The client should just send an "END" if the processing should go on
532 or a "CANCEL" to force the function to terminate with a Cancel
535 With the option --keypairinfo only KEYPARIINFO lstatus lines are
538 The response of this command is a list of status lines formatted as
543 This returns the type of the application, currently the strings:
545 P15 = PKCS-15 structure used
547 OPENPGP = OpenPGP card
550 are implemented. These strings are aliases for the AID
552 S KEYPAIRINFO <hexstring_with_keygrip> <hexstring_with_id>
554 If there is no certificate yet stored on the card a single "X" is
555 returned as the keygrip. In addition to the keypair info, information
556 about all certificates stored on the card is also returned:
558 S CERTINFO <certtype> <hexstring_with_id>
560 Where CERTTYPE is a number indicating the type of certificate:
562 100 := Regular X.509 cert
563 101 := Trusted X.509 cert
564 102 := Useful X.509 cert
565 110 := Root CA cert in a special format (e.g. DINSIG)
566 111 := Root CA cert as standard X509 cert.
568 For certain cards, more information will be returned:
570 S KEY-FPR <no> <hexstring>
572 For OpenPGP cards this returns the stored fingerprints of the
573 keys. This can be used check whether a key is available on the
574 card. NO may be 1, 2 or 3.
576 S CA-FPR <no> <hexstring>
578 Similar to above, these are the fingerprints of keys assumed to be
581 S DISP-NAME <name_of_card_holder>
583 The name of the card holder as stored on the card; percent
584 escaping takes place, spaces are encoded as '+'
588 The URL to be used for locating the entire public key.
590 Note, that this function may even be used on a locked card.
593 cmd_learn (assuan_context_t ctx
, char *line
)
595 ctrl_t ctrl
= assuan_get_pointer (ctx
);
597 int only_keypairinfo
= has_option (line
, "--keypairinfo");
599 if ((rc
= open_card (ctrl
, NULL
)))
602 /* Unless the force option is used we try a shortcut by identifying
603 the card using a serial number and inquiring the client with
604 that. The client may choose to cancel the operation if he already
605 knows about this card */
606 if (!only_keypairinfo
)
608 char *serial_and_stamp
;
612 rc
= app_get_serial_and_stamp (ctrl
->app_ctx
, &serial
, &stamp
);
615 rc
= estream_asprintf (&serial_and_stamp
, "%s %lu",
616 serial
, (unsigned long)stamp
);
619 return out_of_core ();
621 assuan_write_status (ctx
, "SERIALNO", serial_and_stamp
);
623 if (!has_option (line
, "--force"))
627 rc
= estream_asprintf (&command
, "KNOWNCARDP %s", serial_and_stamp
);
630 xfree (serial_and_stamp
);
631 return out_of_core ();
634 rc
= assuan_inquire (ctx
, command
, NULL
, NULL
, 0);
638 if (gpg_err_code (rc
) != GPG_ERR_ASS_CANCELED
)
639 log_error ("inquire KNOWNCARDP failed: %s\n",
641 xfree (serial_and_stamp
);
644 /* Not canceled, so we have to proceeed. */
646 xfree (serial_and_stamp
);
649 /* Let the application print out its collection of useful status
652 rc
= app_write_learn_status (ctrl
->app_ctx
, ctrl
, only_keypairinfo
);
654 TEST_CARD_REMOVAL (ctrl
, rc
);
660 /* READCERT <hexified_certid>|<keyid>
662 Note, that this function may even be used on a locked card.
665 cmd_readcert (assuan_context_t ctx
, char *line
)
667 ctrl_t ctrl
= assuan_get_pointer (ctx
);
672 if ((rc
= open_card (ctrl
, NULL
)))
675 line
= xstrdup (line
); /* Need a copy of the line. */
676 rc
= app_readcert (ctrl
->app_ctx
, line
, &cert
, &ncert
);
678 log_error ("app_readcert failed: %s\n", gpg_strerror (rc
));
683 rc
= assuan_send_data (ctx
, cert
, ncert
);
689 TEST_CARD_REMOVAL (ctrl
, rc
);
696 Return the public key for the given cert or key ID as an standard
699 Note, that this function may even be used on a locked card.
702 cmd_readkey (assuan_context_t ctx
, char *line
)
704 ctrl_t ctrl
= assuan_get_pointer (ctx
);
706 unsigned char *cert
= NULL
;
708 ksba_cert_t kc
= NULL
;
713 if ((rc
= open_card (ctrl
, NULL
)))
716 line
= xstrdup (line
); /* Need a copy of the line. */
717 /* If the application supports the READKEY function we use that.
718 Otherwise we use the old way by extracting it from the
720 rc
= app_readkey (ctrl
->app_ctx
, line
, &pk
, &pklen
);
722 { /* Yeah, got that key - send it back. */
723 rc
= assuan_send_data (ctx
, pk
, pklen
);
730 if (gpg_err_code (rc
) != GPG_ERR_UNSUPPORTED_OPERATION
)
731 log_error ("app_readkey failed: %s\n", gpg_strerror (rc
));
734 rc
= app_readcert (ctrl
->app_ctx
, line
, &cert
, &ncert
);
736 log_error ("app_readcert failed: %s\n", gpg_strerror (rc
));
743 rc
= ksba_cert_new (&kc
);
749 rc
= ksba_cert_init_from_mem (kc
, cert
, ncert
);
752 log_error ("failed to parse the certificate: %s\n", gpg_strerror (rc
));
756 p
= ksba_cert_get_public_key (kc
);
759 rc
= gpg_error (GPG_ERR_NO_PUBKEY
);
763 n
= gcry_sexp_canon_len (p
, 0, NULL
, NULL
);
764 rc
= assuan_send_data (ctx
, p
, n
);
769 ksba_cert_release (kc
);
771 TEST_CARD_REMOVAL (ctrl
, rc
);
778 /* SETDATA <hexstring>
780 The client should use this command to tell us the data he want to
783 cmd_setdata (assuan_context_t ctx
, char *line
)
785 ctrl_t ctrl
= assuan_get_pointer (ctx
);
790 if (locked_session
&& locked_session
!= ctrl
->server_local
)
791 return gpg_error (GPG_ERR_LOCKED
);
793 /* Parse the hexstring. */
794 for (p
=line
,n
=0; hexdigitp (p
); p
++, n
++)
797 return set_error (GPG_ERR_ASS_PARAMETER
, "invalid hexstring");
799 return set_error (GPG_ERR_ASS_PARAMETER
, "no data given");
801 return set_error (GPG_ERR_ASS_PARAMETER
, "odd number of digits");
803 buf
= xtrymalloc (n
);
805 return out_of_core ();
807 xfree (ctrl
->in_data
.value
);
808 ctrl
->in_data
.value
= buf
;
809 ctrl
->in_data
.valuelen
= n
;
810 for (p
=line
, n
=0; n
< ctrl
->in_data
.valuelen
; p
+= 2, n
++)
818 pin_cb (void *opaque
, const char *info
, char **retstr
)
820 assuan_context_t ctx
= opaque
;
823 unsigned char *value
;
828 /* We prompt for keypad entry. To make sure that the popup has
829 been show we use an inquire and not just a status message.
830 We ignore any value returned. */
833 log_debug ("prompting for keypad entry '%s'\n", info
);
834 rc
= estream_asprintf (&command
, "POPUPKEYPADPROMPT %s", info
);
836 return gpg_error (gpg_err_code_from_errno (errno
));
837 rc
= assuan_inquire (ctx
, command
, &value
, &valuelen
, MAXLEN_PIN
);
842 log_debug ("dismiss keypad entry prompt\n");
843 rc
= assuan_inquire (ctx
, "DISMISSKEYPADPROMPT",
844 &value
, &valuelen
, MAXLEN_PIN
);
852 log_debug ("asking for PIN '%s'\n", info
);
854 rc
= estream_asprintf (&command
, "NEEDPIN %s", info
);
856 return gpg_error (gpg_err_code_from_errno (errno
));
858 /* Fixme: Write an inquire function which returns the result in
859 secure memory and check all further handling of the PIN. */
860 rc
= assuan_inquire (ctx
, command
, &value
, &valuelen
, MAXLEN_PIN
);
865 if (!valuelen
|| value
[valuelen
-1])
867 /* We require that the returned value is an UTF-8 string */
869 return gpg_error (GPG_ERR_INV_RESPONSE
);
871 *retstr
= (char*)value
;
876 /* PKSIGN [--hash=[rmd160|sha{1,224,256,384,512}|md5]] <hexified_id>
878 The --hash option is optional; the default is SHA1.
882 cmd_pksign (assuan_context_t ctx
, char *line
)
884 ctrl_t ctrl
= assuan_get_pointer (ctx
);
886 unsigned char *outdata
;
891 if (has_option (line
, "--hash=rmd160"))
892 hash_algo
= GCRY_MD_RMD160
;
893 else if (has_option (line
, "--hash=sha1"))
894 hash_algo
= GCRY_MD_SHA1
;
895 else if (has_option (line
, "--hash=sha224"))
896 hash_algo
= GCRY_MD_SHA224
;
897 else if (has_option (line
, "--hash=sha256"))
898 hash_algo
= GCRY_MD_SHA256
;
899 else if (has_option (line
, "--hash=sha384"))
900 hash_algo
= GCRY_MD_SHA384
;
901 else if (has_option (line
, "--hash=sha512"))
902 hash_algo
= GCRY_MD_SHA512
;
903 else if (has_option (line
, "--hash=md5"))
904 hash_algo
= GCRY_MD_MD5
;
905 else if (!strstr (line
, "--"))
906 hash_algo
= GCRY_MD_SHA1
;
908 return set_error (GPG_ERR_ASS_PARAMETER
, "invalid hash algorithm");
910 line
= skip_options (line
);
912 if ( IS_LOCKED (ctrl
) )
913 return gpg_error (GPG_ERR_LOCKED
);
915 if ((rc
= open_card (ctrl
, NULL
)))
918 /* We have to use a copy of the key ID because the function may use
919 the pin_cb which in turn uses the assuan line buffer and thus
920 overwriting the original line with the keyid */
921 keyidstr
= xtrystrdup (line
);
923 return out_of_core ();
925 rc
= app_sign (ctrl
->app_ctx
,
928 ctrl
->in_data
.value
, ctrl
->in_data
.valuelen
,
929 &outdata
, &outdatalen
);
934 log_error ("app_sign failed: %s\n", gpg_strerror (rc
));
938 rc
= assuan_send_data (ctx
, outdata
, outdatalen
);
941 return rc
; /* that is already an assuan error code */
944 TEST_CARD_REMOVAL (ctrl
, rc
);
948 /* PKAUTH <hexified_id>
952 cmd_pkauth (assuan_context_t ctx
, char *line
)
954 ctrl_t ctrl
= assuan_get_pointer (ctx
);
956 unsigned char *outdata
;
960 if ( IS_LOCKED (ctrl
) )
961 return gpg_error (GPG_ERR_LOCKED
);
963 if ((rc
= open_card (ctrl
, NULL
)))
967 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION
);
969 /* We have to use a copy of the key ID because the function may use
970 the pin_cb which in turn uses the assuan line buffer and thus
971 overwriting the original line with the keyid */
972 keyidstr
= xtrystrdup (line
);
974 return out_of_core ();
976 rc
= app_auth (ctrl
->app_ctx
,
979 ctrl
->in_data
.value
, ctrl
->in_data
.valuelen
,
980 &outdata
, &outdatalen
);
984 log_error ("app_auth failed: %s\n", gpg_strerror (rc
));
988 rc
= assuan_send_data (ctx
, outdata
, outdatalen
);
991 return rc
; /* that is already an assuan error code */
994 TEST_CARD_REMOVAL (ctrl
, rc
);
998 /* PKDECRYPT <hexified_id>
1002 cmd_pkdecrypt (assuan_context_t ctx
, char *line
)
1004 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1006 unsigned char *outdata
;
1010 if ( IS_LOCKED (ctrl
) )
1011 return gpg_error (GPG_ERR_LOCKED
);
1013 if ((rc
= open_card (ctrl
, NULL
)))
1016 keyidstr
= xtrystrdup (line
);
1018 return out_of_core ();
1019 rc
= app_decipher (ctrl
->app_ctx
,
1022 ctrl
->in_data
.value
, ctrl
->in_data
.valuelen
,
1023 &outdata
, &outdatalen
);
1028 log_error ("app_decipher failed: %s\n", gpg_strerror (rc
));
1032 rc
= assuan_send_data (ctx
, outdata
, outdatalen
);
1035 return rc
; /* that is already an assuan error code */
1038 TEST_CARD_REMOVAL (ctrl
, rc
);
1045 This command is used to retrieve data from a smartcard. The
1046 allowed names depend on the currently selected smartcard
1047 application. NAME must be percent and '+' escaped. The value is
1048 returned through status message, see the LEARN command for details.
1050 However, the current implementation assumes that Name is not escaped;
1051 this works as long as noone uses arbitrary escaping.
1053 Note, that this function may even be used on a locked card.
1056 cmd_getattr (assuan_context_t ctx
, char *line
)
1058 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1060 const char *keyword
;
1062 if ((rc
= open_card (ctrl
, NULL
)))
1066 for (; *line
&& !spacep (line
); line
++)
1071 /* (We ignore any garbage for now.) */
1073 /* FIXME: Applications should not return sensitive data if the card
1075 rc
= app_getattr (ctrl
->app_ctx
, ctrl
, keyword
);
1077 TEST_CARD_REMOVAL (ctrl
, rc
);
1082 /* SETATTR <name> <value>
1084 This command is used to store data on a a smartcard. The allowed
1085 names and values are depend on the currently selected smartcard
1086 application. NAME and VALUE must be percent and '+' escaped.
1088 However, the current implementation assumes that NAME is not
1089 escaped; this works as long as noone uses arbitrary escaping.
1091 A PIN will be requested for most NAMEs. See the corresponding
1092 setattr function of the actually used application (app-*.c) for
1095 cmd_setattr (assuan_context_t ctx
, char *orig_line
)
1097 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1102 char *line
, *linebuf
;
1104 if ( IS_LOCKED (ctrl
) )
1105 return gpg_error (GPG_ERR_LOCKED
);
1107 if ((rc
= open_card (ctrl
, NULL
)))
1110 /* We need to use a copy of LINE, because PIN_CB uses the same
1111 context and thus reuses the Assuan provided LINE. */
1112 line
= linebuf
= xtrystrdup (orig_line
);
1114 return out_of_core ();
1117 for (keywordlen
=0; *line
&& !spacep (line
); line
++, keywordlen
++)
1121 while (spacep (line
))
1123 nbytes
= percent_plus_unescape_inplace (line
, 0);
1125 rc
= app_setattr (ctrl
->app_ctx
, keyword
, pin_cb
, ctx
,
1126 (const unsigned char*)line
, nbytes
);
1129 TEST_CARD_REMOVAL (ctrl
, rc
);
1135 /* WRITECERT <hexified_certid>
1137 This command is used to store a certifciate on a smartcard. The
1138 allowed certids depend on the currently selected smartcard
1139 application. The actual certifciate is requested using the inquiry
1140 "CERTDATA" and needs to be provided in its raw (e.g. DER) form.
1142 In almost all cases a a PIN will be requested. See the related
1143 writecert function of the actually used application (app-*.c) for
1146 cmd_writecert (assuan_context_t ctx
, char *line
)
1148 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1151 unsigned char *certdata
;
1154 if ( IS_LOCKED (ctrl
) )
1155 return gpg_error (GPG_ERR_LOCKED
);
1157 line
= skip_options (line
);
1160 return set_error (GPG_ERR_ASS_PARAMETER
, "no certid given");
1162 while (*line
&& !spacep (line
))
1166 if ((rc
= open_card (ctrl
, NULL
)))
1170 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION
);
1172 certid
= xtrystrdup (certid
);
1174 return out_of_core ();
1176 /* Now get the actual keydata. */
1177 rc
= assuan_inquire (ctx
, "CERTDATA",
1178 &certdata
, &certdatalen
, MAXLEN_CERTDATA
);
1185 /* Write the certificate to the card. */
1186 rc
= app_writecert (ctrl
->app_ctx
, ctrl
, certid
,
1187 pin_cb
, ctx
, certdata
, certdatalen
);
1191 TEST_CARD_REMOVAL (ctrl
, rc
);
1197 /* WRITEKEY [--force] <keyid>
1199 This command is used to store a secret key on a a smartcard. The
1200 allowed keyids depend on the currently selected smartcard
1201 application. The actual keydata is requested using the inquiry
1202 "KEYDATA" and need to be provided without any protection. With
1203 --force set an existing key under this KEYID will get overwritten.
1204 The keydata is expected to be the usual canonical encoded
1207 A PIN will be requested for most NAMEs. See the corresponding
1208 writekey function of the actually used application (app-*.c) for
1211 cmd_writekey (assuan_context_t ctx
, char *line
)
1213 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1216 int force
= has_option (line
, "--force");
1217 unsigned char *keydata
;
1220 if ( IS_LOCKED (ctrl
) )
1221 return gpg_error (GPG_ERR_LOCKED
);
1223 line
= skip_options (line
);
1226 return set_error (GPG_ERR_ASS_PARAMETER
, "no keyid given");
1228 while (*line
&& !spacep (line
))
1232 if ((rc
= open_card (ctrl
, NULL
)))
1236 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION
);
1238 keyid
= xtrystrdup (keyid
);
1240 return out_of_core ();
1242 /* Now get the actual keydata. */
1243 assuan_begin_confidential (ctx
);
1244 rc
= assuan_inquire (ctx
, "KEYDATA", &keydata
, &keydatalen
, MAXLEN_KEYDATA
);
1245 assuan_end_confidential (ctx
);
1252 /* Write the key to the card. */
1253 rc
= app_writekey (ctrl
->app_ctx
, ctrl
, keyid
, force
? 1:0,
1254 pin_cb
, ctx
, keydata
, keydatalen
);
1258 TEST_CARD_REMOVAL (ctrl
, rc
);
1264 /* GENKEY [--force] [--timestamp=<isodate>] <no>
1266 Generate a key on-card identified by NO, which is application
1267 specific. Return values are application specific. For OpenPGP
1268 cards 2 status lines are returned:
1270 S KEY-FPR <hexstring>
1271 S KEY-CREATED-AT <seconds_since_epoch>
1272 S KEY-DATA [p|n] <hexdata>
1274 --force is required to overwrite an already existing key. The
1275 KEY-CREATED-AT is required for further processing because it is
1276 part of the hashed key material for the fingerprint.
1278 If --timestamp is given an OpenPGP key will be created using this
1279 value. The value needs to be in ISO Format; e.g.
1280 "--timestamp=20030316T120000" and after 1970-01-01 00:00:00.
1282 The public part of the key can also later be retrieved using the
1287 cmd_genkey (assuan_context_t ctx
, char *line
)
1289 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1296 if ( IS_LOCKED (ctrl
) )
1297 return gpg_error (GPG_ERR_LOCKED
);
1299 force
= has_option (line
, "--force");
1301 if ((s
=has_option_name (line
, "--timestamp")))
1304 return set_error (GPG_ERR_ASS_PARAMETER
, "missing value for option");
1305 timestamp
= isotime2epoch (s
+1);
1307 return set_error (GPG_ERR_ASS_PARAMETER
, "invalid time value");
1313 line
= skip_options (line
);
1315 return set_error (GPG_ERR_ASS_PARAMETER
, "no key number given");
1317 while (*line
&& !spacep (line
))
1321 if ((rc
= open_card (ctrl
, NULL
)))
1325 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION
);
1327 keyno
= xtrystrdup (keyno
);
1329 return out_of_core ();
1330 rc
= app_genkey (ctrl
->app_ctx
, ctrl
, keyno
, force
? 1:0,
1331 timestamp
, pin_cb
, ctx
);
1334 TEST_CARD_REMOVAL (ctrl
, rc
);
1341 Get NBYTES of random from the card and send them back as data.
1343 Note, that this function may be even be used on a locked card.
1346 cmd_random (assuan_context_t ctx
, char *line
)
1348 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1351 unsigned char *buffer
;
1354 return set_error (GPG_ERR_ASS_PARAMETER
, "number of requested bytes missing");
1355 nbytes
= strtoul (line
, NULL
, 0);
1357 if ((rc
= open_card (ctrl
, NULL
)))
1361 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION
);
1363 buffer
= xtrymalloc (nbytes
);
1365 return out_of_core ();
1367 rc
= app_get_challenge (ctrl
->app_ctx
, nbytes
, buffer
);
1370 rc
= assuan_send_data (ctx
, buffer
, nbytes
);
1372 return rc
; /* that is already an assuan error code */
1376 TEST_CARD_REMOVAL (ctrl
, rc
);
1381 /* PASSWD [--reset] [--nullpin] <chvno>
1383 Change the PIN or, if --reset is given, reset the retry counter of
1384 the card holder verfication vector CHVNO. The option --nullpin is
1385 used for TCOS cards to set the initial PIN. The format of CHVNO
1386 depends on the card application. */
1388 cmd_passwd (assuan_context_t ctx
, char *line
)
1390 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1393 unsigned int flags
= 0;
1395 if (has_option (line
, "--reset"))
1396 flags
|= APP_CHANGE_FLAG_RESET
;
1397 if (has_option (line
, "--nullpin"))
1398 flags
|= APP_CHANGE_FLAG_NULLPIN
;
1400 if ( IS_LOCKED (ctrl
) )
1401 return gpg_error (GPG_ERR_LOCKED
);
1403 line
= skip_options (line
);
1406 return set_error (GPG_ERR_ASS_PARAMETER
, "no CHV number given");
1408 while (*line
&& !spacep (line
))
1412 if ((rc
= open_card (ctrl
, NULL
)))
1416 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION
);
1418 chvnostr
= xtrystrdup (chvnostr
);
1420 return out_of_core ();
1421 rc
= app_change_pin (ctrl
->app_ctx
, ctrl
, chvnostr
, flags
, pin_cb
, ctx
);
1423 log_error ("command passwd failed: %s\n", gpg_strerror (rc
));
1426 TEST_CARD_REMOVAL (ctrl
, rc
);
1433 Perform a VERIFY operation without doing anything else. This may
1434 be used to initialize a the PIN cache earlier to long lasting
1435 operations. Its use is highly application dependent.
1439 Perform a simple verify operation for CHV1 and CHV2, so that
1440 further operations won't ask for CHV2 and it is possible to do a
1441 cheap check on the PIN: If there is something wrong with the PIN
1442 entry system, only the regular CHV will get blocked and not the
1443 dangerous CHV3. IDSTR is the usual card's serial number in hex
1444 notation; an optional fingerprint part will get ignored. There
1445 is however a special mode if the IDSTR is sffixed with the
1446 literal string "[CHV3]": In this case the Admin PIN is checked
1447 if and only if the retry counter is still at 3.
1451 Any of the valid PIN Ids may be used. These are the strings:
1453 PW1.CH - Global password 1
1454 PW2.CH - Global password 2
1455 PW1.CH.SIG - SigG password 1
1456 PW2.CH.SIG - SigG password 2
1458 For a definitive list, see the implementation in app-nks.c.
1459 Note that we call a PW2.* PIN a "PUK" despite that since TCOS
1460 3.0 they are technically alternative PINs used to mutally
1465 cmd_checkpin (assuan_context_t ctx
, char *line
)
1467 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1471 if ( IS_LOCKED (ctrl
) )
1472 return gpg_error (GPG_ERR_LOCKED
);
1474 if ((rc
= open_card (ctrl
, NULL
)))
1478 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION
);
1480 /* We have to use a copy of the key ID because the function may use
1481 the pin_cb which in turn uses the assuan line buffer and thus
1482 overwriting the original line with the keyid. */
1483 idstr
= xtrystrdup (line
);
1485 return out_of_core ();
1487 rc
= app_check_pin (ctrl
->app_ctx
, idstr
, pin_cb
, ctx
);
1490 log_error ("app_check_pin failed: %s\n", gpg_strerror (rc
));
1492 TEST_CARD_REMOVAL (ctrl
, rc
);
1499 Grant exclusive card access to this session. Note that there is
1500 no lock counter used and a second lock from the same session will
1501 be ignored. A single unlock (or RESET) unlocks the session.
1502 Return GPG_ERR_LOCKED if another session has locked the reader.
1504 If the option --wait is given the command will wait until a
1505 lock has been released.
1508 cmd_lock (assuan_context_t ctx
, char *line
)
1510 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1516 if (locked_session
!= ctrl
->server_local
)
1517 rc
= gpg_error (GPG_ERR_LOCKED
);
1520 locked_session
= ctrl
->server_local
;
1523 if (rc
&& has_option (line
, "--wait"))
1526 pth_sleep (1); /* Better implement an event mechanism. However,
1527 for card operations this should be
1529 /* FIXME: Need to check that the connection is still alive.
1530 This can be done by issuing status messages. */
1533 #endif /*USE_GNU_PTH*/
1536 log_error ("cmd_lock failed: %s\n", gpg_strerror (rc
));
1543 Release exclusive card access.
1546 cmd_unlock (assuan_context_t ctx
, char *line
)
1548 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1555 if (locked_session
!= ctrl
->server_local
)
1556 rc
= gpg_error (GPG_ERR_LOCKED
);
1558 locked_session
= NULL
;
1561 rc
= gpg_error (GPG_ERR_NOT_LOCKED
);
1564 log_error ("cmd_unlock failed: %s\n", gpg_strerror (rc
));
1571 Multi purpose command to return certain information.
1572 Supported values of WHAT are:
1574 version - Return the version of the program.
1575 pid - Return the process id of the server.
1577 socket_name - Return the name of the socket.
1579 status - Return the status of the current slot (in the future, may
1580 also return the status of all slots). The status is a list of
1581 one-character flags. The following flags are currently defined:
1582 'u' Usable card present. This is the normal state during operation.
1583 'r' Card removed. A reset is necessary.
1584 These flags are exclusive.
1586 reader_list - Return a list of detected card readers. Does
1587 currently only work with the internal CCID driver.
1589 deny_admin - Returns OK if admin commands are not allowed or
1590 GPG_ERR_GENERAL if admin commands are allowed.
1592 app_list - Return a list of supported applications. One
1593 application per line, fields delimited by colons,
1594 first field is the name.
1598 cmd_getinfo (assuan_context_t ctx
, char *line
)
1602 if (!strcmp (line
, "version"))
1604 const char *s
= VERSION
;
1605 rc
= assuan_send_data (ctx
, s
, strlen (s
));
1607 else if (!strcmp (line
, "pid"))
1611 snprintf (numbuf
, sizeof numbuf
, "%lu", (unsigned long)getpid ());
1612 rc
= assuan_send_data (ctx
, numbuf
, strlen (numbuf
));
1614 else if (!strcmp (line
, "socket_name"))
1616 const char *s
= scd_get_socket_name ();
1619 rc
= assuan_send_data (ctx
, s
, strlen (s
));
1621 rc
= gpg_error (GPG_ERR_NO_DATA
);
1623 else if (!strcmp (line
, "status"))
1625 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1626 int slot
= ctrl
->reader_slot
;
1629 if (!ctrl
->server_local
->card_removed
&& slot
!= -1)
1631 struct slot_status_s
*ss
;
1633 if (!(slot
>= 0 && slot
< DIM(slot_table
)))
1636 ss
= &slot_table
[slot
];
1641 if (ss
->any
&& (ss
->status
& 1))
1644 rc
= assuan_send_data (ctx
, &flag
, 1);
1646 else if (!strcmp (line
, "reader_list"))
1649 char *s
= ccid_get_reader_list ();
1655 rc
= assuan_send_data (ctx
, s
, strlen (s
));
1657 rc
= gpg_error (GPG_ERR_NO_DATA
);
1660 else if (!strcmp (line
, "deny_admin"))
1661 rc
= opt
.allow_admin
? gpg_error (GPG_ERR_GENERAL
) : 0;
1662 else if (!strcmp (line
, "app_list"))
1664 char *s
= get_supported_applications ();
1666 rc
= assuan_send_data (ctx
, s
, strlen (s
));
1672 rc
= set_error (GPG_ERR_ASS_PARAMETER
, "unknown value for WHAT");
1679 Restart the current connection; this is a kind of warm reset. It
1680 deletes the context used by this connection but does not send a
1681 RESET to the card. Thus the card itself won't get reset.
1683 This is used by gpg-agent to reuse a primary pipe connection and
1684 may be used by clients to backup from a conflict in the serial
1685 command; i.e. to select another application.
1689 cmd_restart (assuan_context_t ctx
, char *line
)
1691 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1697 release_application (ctrl
->app_ctx
);
1698 ctrl
->app_ctx
= NULL
;
1700 if (locked_session
&& ctrl
->server_local
== locked_session
)
1702 locked_session
= NULL
;
1703 log_info ("implicitly unlocking due to RESTART\n");
1711 Disconnect the card if it is not any longer used by other
1712 connections and the backend supports a disconnect operation.
1715 cmd_disconnect (assuan_context_t ctx
, char *line
)
1717 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1721 ctrl
->server_local
->disconnect_allowed
= 1;
1727 /* APDU [--atr] [--more] [--exlen[=N]] [hexstring]
1729 Send an APDU to the current reader. This command bypasses the high
1730 level functions and sends the data directly to the card. HEXSTRING
1731 is expected to be a proper APDU. If HEXSTRING is not given no
1732 commands are set to the card but the command will implictly check
1733 whether the card is ready for use.
1735 Using the option "--atr" returns the ATR of the card as a status
1736 message before any data like this:
1737 S CARD-ATR 3BFA1300FF813180450031C173C00100009000B1
1739 Using the option --more handles the card status word MORE_DATA
1740 (61xx) and concatenates all reponses to one block.
1742 Using the option "--exlen" the returned APDU may use extended
1743 length up to N bytes. If N is not given a default value is used
1747 cmd_apdu (assuan_context_t ctx
, char *line
)
1749 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1751 unsigned char *apdu
;
1758 with_atr
= has_option (line
, "--atr");
1759 handle_more
= has_option (line
, "--more");
1761 if ((s
=has_option_name (line
, "--exlen")))
1764 exlen
= strtoul (s
+1, NULL
, 0);
1771 line
= skip_options (line
);
1773 if ( IS_LOCKED (ctrl
) )
1774 return gpg_error (GPG_ERR_LOCKED
);
1776 if ((rc
= open_card (ctrl
, NULL
)))
1785 atr
= apdu_get_atr (ctrl
->reader_slot
, &atrlen
);
1786 if (!atr
|| atrlen
> sizeof hexbuf
- 2 )
1788 rc
= gpg_error (GPG_ERR_INV_CARD
);
1791 bin2hex (atr
, atrlen
, hexbuf
);
1793 send_status_info (ctrl
, "CARD-ATR", hexbuf
, strlen (hexbuf
), NULL
, 0);
1796 apdu
= hex_to_buffer (line
, &apdulen
);
1799 rc
= gpg_error_from_syserror ();
1804 unsigned char *result
= NULL
;
1807 rc
= apdu_send_direct (ctrl
->reader_slot
, exlen
,
1808 apdu
, apdulen
, handle_more
,
1809 &result
, &resultlen
);
1811 log_error ("apdu_send_direct failed: %s\n", gpg_strerror (rc
));
1814 rc
= assuan_send_data (ctx
, result
, resultlen
);
1821 TEST_CARD_REMOVAL (ctrl
, rc
);
1826 /* KILLSCD - Commit suicide. */
1828 cmd_killscd (assuan_context_t ctx
, char *line
)
1830 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1834 ctrl
->server_local
->stopme
= 1;
1835 return gpg_error (GPG_ERR_EOF
);
1840 /* Tell the assuan library about our commands */
1842 register_commands (assuan_context_t ctx
)
1846 gpg_error_t (*handler
)(assuan_context_t
, char *line
);
1848 { "SERIALNO", cmd_serialno
},
1849 { "LEARN", cmd_learn
},
1850 { "READCERT", cmd_readcert
},
1851 { "READKEY", cmd_readkey
},
1852 { "SETDATA", cmd_setdata
},
1853 { "PKSIGN", cmd_pksign
},
1854 { "PKAUTH", cmd_pkauth
},
1855 { "PKDECRYPT", cmd_pkdecrypt
},
1858 { "GETATTR", cmd_getattr
},
1859 { "SETATTR", cmd_setattr
},
1860 { "WRITECERT", cmd_writecert
},
1861 { "WRITEKEY", cmd_writekey
},
1862 { "GENKEY", cmd_genkey
},
1863 { "RANDOM", cmd_random
},
1864 { "PASSWD", cmd_passwd
},
1865 { "CHECKPIN", cmd_checkpin
},
1866 { "LOCK", cmd_lock
},
1867 { "UNLOCK", cmd_unlock
},
1868 { "GETINFO", cmd_getinfo
},
1869 { "RESTART", cmd_restart
},
1870 { "DISCONNECT", cmd_disconnect
},
1871 { "APDU", cmd_apdu
},
1872 { "KILLSCD", cmd_killscd
},
1877 for (i
=0; table
[i
].name
; i
++)
1879 rc
= assuan_register_command (ctx
, table
[i
].name
, table
[i
].handler
);
1883 assuan_set_hello_line (ctx
, "GNU Privacy Guard's Smartcard server ready");
1885 assuan_register_reset_notify (ctx
, reset_notify
);
1886 assuan_register_option_handler (ctx
, option_handler
);
1891 /* Startup the server. If FD is given as -1 this is simple pipe
1892 server, otherwise it is a regular server. Returns true if there
1893 are no more active asessions. */
1895 scd_command_handler (ctrl_t ctrl
, int fd
)
1898 assuan_context_t ctx
= NULL
;
1901 rc
= assuan_new (&ctx
);
1904 log_error ("failed to allocate assuan context: %s\n",
1915 rc
= assuan_init_pipe_server (ctx
, filedes
);
1919 rc
= assuan_init_socket_server_ext (ctx
, INT2FD(fd
), 2);
1923 log_error ("failed to initialize the server: %s\n",
1927 rc
= register_commands (ctx
);
1930 log_error ("failed to register commands with Assuan: %s\n",
1934 assuan_set_pointer (ctx
, ctrl
);
1936 /* Allocate and initialize the server object. Put it into the list
1937 of active sessions. */
1938 ctrl
->server_local
= xcalloc (1, sizeof *ctrl
->server_local
);
1939 ctrl
->server_local
->next_session
= session_list
;
1940 session_list
= ctrl
->server_local
;
1941 ctrl
->server_local
->ctrl_backlink
= ctrl
;
1942 ctrl
->server_local
->assuan_ctx
= ctx
;
1945 assuan_set_log_stream (ctx
, log_get_stream ());
1947 /* We open the reader right at startup so that the ticker is able to
1948 update the status file. */
1949 if (ctrl
->reader_slot
== -1)
1951 ctrl
->reader_slot
= get_reader_slot ();
1954 /* Command processing loop. */
1957 rc
= assuan_accept (ctx
);
1964 log_info ("Assuan accept problem: %s\n", gpg_strerror (rc
));
1968 rc
= assuan_process (ctx
);
1971 log_info ("Assuan processing failed: %s\n", gpg_strerror (rc
));
1976 /* Cleanup. We don't send an explicit reset to the card. */
1979 /* Release the server object. */
1980 if (session_list
== ctrl
->server_local
)
1981 session_list
= ctrl
->server_local
->next_session
;
1984 struct server_local_s
*sl
;
1986 for (sl
=session_list
; sl
->next_session
; sl
= sl
->next_session
)
1987 if (sl
->next_session
== ctrl
->server_local
)
1989 if (!sl
->next_session
)
1991 sl
->next_session
= ctrl
->server_local
->next_session
;
1993 stopme
= ctrl
->server_local
->stopme
;
1994 xfree (ctrl
->server_local
);
1995 ctrl
->server_local
= NULL
;
1997 /* Release the Assuan context. */
1998 assuan_release (ctx
);
2003 /* If there are no more sessions return true. */
2004 return !session_list
;
2008 /* Send a line with status information via assuan and escape all given
2009 buffers. The variable elements are pairs of (char *, size_t),
2010 terminated with a (NULL, 0). */
2012 send_status_info (ctrl_t ctrl
, const char *keyword
, ...)
2015 const unsigned char *value
;
2019 assuan_context_t ctx
= ctrl
->server_local
->assuan_ctx
;
2021 va_start (arg_ptr
, keyword
);
2025 while ( (value
= va_arg (arg_ptr
, const unsigned char *)) )
2027 valuelen
= va_arg (arg_ptr
, size_t);
2029 continue; /* empty buffer */
2035 for ( ; valuelen
&& n
< DIM (buf
)-2; n
++, valuelen
--, value
++)
2037 if (*value
< ' ' || *value
== '+')
2039 sprintf (p
, "%%%02X", *value
);
2042 else if (*value
== ' ')
2049 assuan_write_status (ctx
, keyword
, buf
);
2055 /* Send a ready formatted status line via assuan. */
2057 send_status_direct (ctrl_t ctrl
, const char *keyword
, const char *args
)
2059 assuan_context_t ctx
= ctrl
->server_local
->assuan_ctx
;
2061 if (strchr (args
, '\n'))
2062 log_error ("error: LF detected in status line - not sending\n");
2064 assuan_write_status (ctx
, keyword
, args
);
2068 /* Helper to send the clients a status change notification. */
2070 send_client_notifications (void)
2074 #ifdef HAVE_W32_SYSTEM
2082 struct server_local_s
*sl
;
2084 for (sl
=session_list
; sl
; sl
= sl
->next_session
)
2086 if (sl
->event_signal
&& sl
->assuan_ctx
)
2088 pid_t pid
= assuan_get_pid (sl
->assuan_ctx
);
2089 #ifdef HAVE_W32_SYSTEM
2090 HANDLE handle
= (void *)sl
->event_signal
;
2092 for (kidx
=0; kidx
< killidx
; kidx
++)
2093 if (killed
[kidx
].pid
== pid
2094 && killed
[kidx
].handle
== handle
)
2097 log_info ("event %lx (%p) already triggered for client %d\n",
2098 sl
->event_signal
, handle
, (int)pid
);
2101 log_info ("triggering event %lx (%p) for client %d\n",
2102 sl
->event_signal
, handle
, (int)pid
);
2103 if (!SetEvent (handle
))
2104 log_error ("SetEvent(%lx) failed: %s\n",
2105 sl
->event_signal
, w32_strerror (-1));
2106 if (killidx
< DIM (killed
))
2108 killed
[killidx
].pid
= pid
;
2109 killed
[killidx
].handle
= handle
;
2113 #else /*!HAVE_W32_SYSTEM*/
2114 int signo
= sl
->event_signal
;
2116 if (pid
!= (pid_t
)(-1) && pid
&& signo
> 0)
2118 for (kidx
=0; kidx
< killidx
; kidx
++)
2119 if (killed
[kidx
].pid
== pid
2120 && killed
[kidx
].signo
== signo
)
2123 log_info ("signal %d already sent to client %d\n",
2127 log_info ("sending signal %d to client %d\n",
2130 if (killidx
< DIM (killed
))
2132 killed
[killidx
].pid
= pid
;
2133 killed
[killidx
].signo
= signo
;
2138 #endif /*!HAVE_W32_SYSTEM*/
2145 /* This is the core of scd_update_reader_status_file but the caller
2146 needs to take care of the locking. */
2148 update_reader_status_file (int set_card_removed_flag
)
2151 unsigned int status
, changed
;
2153 /* Make sure that the reader has been opened. Like get_reader_slot,
2154 this part of the code assumes that there is only one reader. */
2155 if (!slot_table
[0].valid
)
2156 (void)get_reader_slot ();
2158 /* Note, that we only try to get the status, because it does not
2159 make sense to wait here for a operation to complete. If we are
2160 busy working with a card, delays in the status file update should
2162 for (idx
=0; idx
< DIM(slot_table
); idx
++)
2164 struct slot_status_s
*ss
= slot_table
+ idx
;
2165 struct server_local_s
*sl
;
2168 if (!ss
->valid
|| ss
->slot
== -1)
2169 continue; /* Not valid or reader not yet open. */
2171 sw_apdu
= apdu_get_status (ss
->slot
, 0, &status
, &changed
);
2172 if (sw_apdu
== SW_HOST_NO_READER
)
2174 /* Most likely the _reader_ has been unplugged. */
2176 changed
= ss
->changed
;
2180 /* Get status failed. Ignore that. */
2184 if (!ss
->any
|| ss
->status
!= status
|| ss
->changed
!= changed
)
2190 log_info ("updating slot %d status: 0x%04X->0x%04X (%u->%u)\n",
2191 ss
->slot
, ss
->status
, status
, ss
->changed
, changed
);
2192 ss
->status
= status
;
2193 ss
->changed
= changed
;
2195 /* FIXME: Should this be IDX instead of ss->slot? This
2196 depends on how client sessions will associate the reader
2197 status with their session. */
2198 snprintf (templ
, sizeof templ
, "reader_%d.status", ss
->slot
);
2199 fname
= make_filename (opt
.homedir
, templ
, NULL
);
2200 fp
= fopen (fname
, "w");
2203 fprintf (fp
, "%s\n",
2204 (status
& 1)? "USABLE":
2205 (status
& 4)? "ACTIVE":
2206 (status
& 2)? "PRESENT": "NOCARD");
2211 /* If a status script is executable, run it. */
2213 const char *args
[9], *envs
[2];
2214 char numbuf1
[30], numbuf2
[30], numbuf3
[30];
2215 char *homestr
, *envstr
;
2218 homestr
= make_filename (opt
.homedir
, NULL
);
2219 if (estream_asprintf (&envstr
, "GNUPGHOME=%s", homestr
) < 0)
2220 log_error ("out of core while building environment\n");
2226 sprintf (numbuf1
, "%d", ss
->slot
);
2227 sprintf (numbuf2
, "0x%04X", ss
->status
);
2228 sprintf (numbuf3
, "0x%04X", status
);
2229 args
[0] = "--reader-port";
2231 args
[2] = "--old-code";
2233 args
[4] = "--new-code";
2235 args
[6] = "--status";
2236 args
[7] = ((status
& 1)? "USABLE":
2237 (status
& 4)? "ACTIVE":
2238 (status
& 2)? "PRESENT": "NOCARD");
2241 fname
= make_filename (opt
.homedir
, "scd-event", NULL
);
2242 err
= gnupg_spawn_process_detached (fname
, args
, envs
);
2243 if (err
&& gpg_err_code (err
) != GPG_ERR_ENOENT
)
2244 log_error ("failed to run event handler `%s': %s\n",
2245 fname
, gpg_strerror (err
));
2252 /* Set the card removed flag for all current sessions. We
2253 will set this on any card change because a reset or
2254 SERIALNO request must be done in any case. */
2255 if (ss
->any
&& set_card_removed_flag
)
2256 update_card_removed (idx
, 1);
2260 /* Send a signal to all clients who applied for it. */
2261 send_client_notifications ();
2264 /* Check whether a disconnect is pending. */
2265 if (opt
.card_timeout
)
2267 for (sl
=session_list
; sl
; sl
= sl
->next_session
)
2268 if (!sl
->disconnect_allowed
)
2270 if (session_list
&& !sl
)
2272 /* FIXME: Use a real timeout. */
2273 /* At least one connection and all allow a disconnect. */
2274 log_info ("disconnecting card in slot %d\n", ss
->slot
);
2275 apdu_disconnect (ss
->slot
);
2282 /* This function is called by the ticker thread to check for changes
2283 of the reader stati. It updates the reader status files and if
2284 requested by the caller also send a signal to the caller. */
2286 scd_update_reader_status_file (void)
2288 if (!pth_mutex_acquire (&status_file_update_lock
, 1, NULL
))
2289 return; /* locked - give up. */
2290 update_reader_status_file (1);
2291 if (!pth_mutex_release (&status_file_update_lock
))
2292 log_error ("failed to release status_file_update lock\n");