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/>.
37 #include "app-common.h"
38 #include "apdu.h" /* Required for apdu_*_reader (). */
41 #include "ccid-driver.h"
44 /* Maximum length allowed as a PIN; used for INQUIRE NEEDPIN */
45 #define MAXLEN_PIN 100
47 /* Maximum allowed size of key data as used in inquiries. */
48 #define MAXLEN_KEYDATA 4096
50 /* Maximum allowed size of certificate data as used in inquiries. */
51 #define MAXLEN_CERTDATA 16384
54 #define set_error(e,t) assuan_set_error (ctx, gpg_error (e), (t))
57 /* Macro to flag a removed card. */
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 update_card_removed ((c)->reader_slot, 1); \
66 #define IS_LOCKED(c) \
67 (locked_session && locked_session != (c)->server_local \
68 && (c)->reader_slot != -1 && locked_session->ctrl_backlink \
69 && (c)->reader_slot == locked_session->ctrl_backlink->reader_slot)
72 /* This structure is used to keep track of open readers (slots). */
75 int valid
; /* True if the other objects are valid. */
76 int slot
; /* Slot number of the reader or -1 if not open. */
78 int reset_failed
; /* A reset failed. */
80 int any
; /* Flag indicating whether any status check has been
81 done. This is set once to indicate that the status
82 tracking for the slot has been initialized. */
83 unsigned int status
; /* Last status of the slot. */
84 unsigned int changed
; /* Last change counter of the slot. */
88 /* Data used to associate an Assuan context with local server data.
89 This object describes the local properties of one session. */
92 /* We keep a list of all active sessions with the anchor at
93 SESSION_LIST (see below). This field is used for linking. */
94 struct server_local_s
*next_session
;
96 /* This object is usually assigned to a CTRL object (which is
97 globally visible). While enumerating all sessions we sometimes
98 need to access data of the CTRL object; thus we keep a
100 ctrl_t ctrl_backlink
;
102 /* The Assuan context used by this session/server. */
103 assuan_context_t assuan_ctx
;
105 #ifdef HAVE_W32_SYSTEM
106 unsigned long event_signal
; /* Or 0 if not used. */
108 int event_signal
; /* Or 0 if not used. */
111 /* True if the card has been removed and a reset is required to
112 continue operation. */
115 /* A disconnect command has been sent. */
116 int disconnect_allowed
;
118 /* If set to true we will be terminate ourself at the end of the
125 /* The table with information on all used slots. FIXME: This is a
126 different slot number than the one used by the APDU layer, and
127 should be renamed. */
128 static struct slot_status_s slot_table
[10];
131 /* To keep track of all running sessions, we link all active server
132 contexts and the anchor in this variable. */
133 static struct server_local_s
*session_list
;
135 /* If a session has been locked we store a link to its server object
137 static struct server_local_s
*locked_session
;
139 /* While doing a reset we need to make sure that the ticker does not
140 call scd_update_reader_status_file while we are using it. */
141 static pth_mutex_t status_file_update_lock
;
144 /*-- Local prototypes --*/
145 static void update_reader_status_file (int set_card_removed_flag
);
150 /* This function must be called once to initialize this module. This
151 has to be done before a second thread is spawned. We can't do the
152 static initialization because Pth emulation code might not be able
153 to do a static init; in particular, it is not possible for W32. */
155 initialize_module_command (void)
157 static int initialized
;
161 if (pth_mutex_init (&status_file_update_lock
))
167 /* Update the CARD_REMOVED element of all sessions using the reader
168 given by SLOT to VALUE */
170 update_card_removed (int slot
, int value
)
172 struct server_local_s
*sl
;
174 for (sl
=session_list
; sl
; sl
= sl
->next_session
)
175 if (sl
->ctrl_backlink
176 && sl
->ctrl_backlink
->reader_slot
== slot
)
178 sl
->card_removed
= value
;
180 /* Let the card application layer know about the removal. */
182 application_notify_card_reset (slot
);
187 /* Check whether the option NAME appears in LINE. Returns 1 or 0. */
189 has_option (const char *line
, const char *name
)
192 int n
= strlen (name
);
194 s
= strstr (line
, name
);
195 return (s
&& (s
== line
|| spacep (s
-1)) && (!s
[n
] || spacep (s
+n
)));
198 /* Same as has_option but does only test for the name of the option
199 and ignores an argument, i.e. with NAME being "--hash" it would
200 return a pointer for "--hash" as well as for "--hash=foo". If
201 thhere is no such option NULL is returned. The pointer returned
202 points right behind the option name, this may be an equal sign, Nul
205 has_option_name (const char *line
, const char *name
)
208 int n
= strlen (name
);
210 s
= strstr (line
, name
);
211 return (s
&& (s
== line
|| spacep (s
-1))
212 && (!s
[n
] || spacep (s
+n
) || s
[n
] == '=')) ? (s
+n
) : NULL
;
216 /* Skip over options. It is assumed that leading spaces have been
217 removed (this is the case for lines passed to a handler from
218 assuan). Blanks after the options are also removed. */
220 skip_options (char *line
)
222 while ( *line
== '-' && line
[1] == '-' )
224 while (*line
&& !spacep (line
))
226 while (spacep (line
))
234 /* Convert the STRING into a newly allocated buffer while translating
235 the hex numbers. Stops at the first invalid character. Blanks and
236 colons are allowed to separate the hex digits. Returns NULL on
237 error or a newly malloced buffer and its length in LENGTH. */
238 static unsigned char *
239 hex_to_buffer (const char *string
, size_t *r_length
)
241 unsigned char *buffer
;
245 buffer
= xtrymalloc (strlen (string
)+1);
248 for (s
=string
, n
=0; *s
; s
++)
250 if (spacep (s
) || *s
== ':')
252 if (hexdigitp (s
) && hexdigitp (s
+1))
254 buffer
[n
++] = xtoi_2 (s
);
266 /* Reset the card and free the application context. With SEND_RESET
267 set to true actually send a RESET to the reader; this is the normal
268 way of calling the function. */
270 do_reset (ctrl_t ctrl
, int send_reset
)
272 int slot
= ctrl
->reader_slot
;
274 if (!(slot
== -1 || (slot
>= 0 && slot
< DIM(slot_table
))))
277 /* If there is an active application, release it. */
280 release_application (ctrl
->app_ctx
);
281 ctrl
->app_ctx
= NULL
;
284 /* If we want a real reset for the card, send the reset APDU and
285 tell the application layer about it. */
286 if (slot
!= -1 && send_reset
&& !IS_LOCKED (ctrl
) )
288 if (apdu_reset (slot
))
290 slot_table
[slot
].reset_failed
= 1;
292 application_notify_card_reset (slot
);
295 /* If we hold a lock, unlock now. */
296 if (locked_session
&& ctrl
->server_local
== locked_session
)
298 locked_session
= NULL
;
299 log_info ("implicitly unlocking due to RESET\n");
302 /* Reset the card removed flag for the current reader. We need to
303 take the lock here so that the ticker thread won't concurrently
304 try to update the file. Calling update_reader_status_file is
305 required to get hold of the new status of the card in the slot
307 if (!pth_mutex_acquire (&status_file_update_lock
, 0, NULL
))
309 log_error ("failed to acquire status_fle_update lock\n");
310 ctrl
->reader_slot
= -1;
313 update_reader_status_file (0); /* Update slot status table. */
314 update_card_removed (slot
, 0); /* Clear card_removed flag. */
315 if (!pth_mutex_release (&status_file_update_lock
))
316 log_error ("failed to release status_file_update lock\n");
318 /* Do this last, so that the update_card_removed above does its job. */
319 ctrl
->reader_slot
= -1;
324 reset_notify (assuan_context_t ctx
)
326 ctrl_t ctrl
= assuan_get_pointer (ctx
);
333 option_handler (assuan_context_t ctx
, const char *key
, const char *value
)
335 ctrl_t ctrl
= assuan_get_pointer (ctx
);
337 if (!strcmp (key
, "event-signal"))
339 /* A value of 0 is allowed to reset the event signal. */
340 #ifdef HAVE_W32_SYSTEM
342 return gpg_error (GPG_ERR_ASS_PARAMETER
);
343 ctrl
->server_local
->event_signal
= strtoul (value
, NULL
, 16);
345 int i
= *value
? atoi (value
) : -1;
347 return gpg_error (GPG_ERR_ASS_PARAMETER
);
348 ctrl
->server_local
->event_signal
= i
;
356 /* Return the slot of the current reader or open the reader if no
357 other sessions are using a reader. Note, that we currently support
358 only one reader but most of the code (except for this function)
359 should be able to cope with several readers. */
361 get_reader_slot (void)
363 struct slot_status_s
*ss
;
365 ss
= &slot_table
[0]; /* One reader for now. */
367 /* Initialize the item if needed. */
374 /* Try to open the reader. */
376 ss
->slot
= apdu_open_reader (opt
.reader_port
);
378 /* Return the slot_table index. */
382 /* If the card has not yet been opened, do it. Note that this
383 function returns an Assuan error, so don't map the error a second
385 static assuan_error_t
386 open_card (ctrl_t ctrl
, const char *apptype
)
391 /* If we ever got a card not present error code, return that. Only
392 the SERIALNO command and a reset are able to clear from that
394 if (ctrl
->server_local
->card_removed
)
395 return gpg_error (GPG_ERR_CARD_REMOVED
);
397 if ( IS_LOCKED (ctrl
) )
398 return gpg_error (GPG_ERR_LOCKED
);
402 /* Already initialized for one specific application. Need to
403 check that the client didn't requested a specific application
404 different from the one in use. */
405 return check_application_conflict (ctrl
, apptype
);
408 if (ctrl
->reader_slot
!= -1)
409 slot
= ctrl
->reader_slot
;
411 slot
= get_reader_slot ();
412 ctrl
->reader_slot
= slot
;
414 err
= gpg_error (GPG_ERR_CARD
);
417 /* Fixme: We should move the apdu_connect call to
418 select_application. */
421 ctrl
->server_local
->disconnect_allowed
= 0;
422 sw
= apdu_connect (slot
);
423 if (sw
&& sw
!= SW_HOST_ALREADY_CONNECTED
)
425 if (sw
== SW_HOST_NO_CARD
)
426 err
= gpg_error (GPG_ERR_CARD_NOT_PRESENT
);
428 err
= gpg_error (GPG_ERR_CARD
);
431 err
= select_application (ctrl
, slot
, apptype
, &ctrl
->app_ctx
);
434 TEST_CARD_REMOVAL (ctrl
, err
);
439 /* Do the percent and plus/space unescaping in place and return the
440 length of the valid buffer. */
442 percent_plus_unescape (unsigned char *string
)
444 unsigned char *p
= string
;
449 if (*string
== '%' && string
[1] && string
[2])
452 *p
++ = xtoi_2 (string
);
456 else if (*string
== '+')
474 /* SERIALNO [APPTYPE]
476 Return the serial number of the card using a status reponse. This
477 function should be used to check for the presence of a card.
479 If APPTYPE is given, an application of that type is selected and an
480 error is returned if the application is not supported or available.
481 The default is to auto-select the application using a hardwired
482 preference system. Note, that a future extension to this function
483 may allow to specify a list and order of applications to try.
485 This function is special in that it can be used to reset the card.
486 Most other functions will return an error when a card change has
487 been detected and the use of this function is therefore required.
489 Background: We want to keep the client clear of handling card
490 changes between operations; i.e. the client can assume that all
491 operations are done on the same card unless he calls this function.
494 cmd_serialno (assuan_context_t ctx
, char *line
)
496 ctrl_t ctrl
= assuan_get_pointer (ctx
);
498 char *serial_and_stamp
;
502 /* Clear the remove flag so that the open_card is able to reread it. */
503 if (ctrl
->server_local
->card_removed
)
505 if ( IS_LOCKED (ctrl
) )
506 return gpg_error (GPG_ERR_LOCKED
);
510 if ((rc
= open_card (ctrl
, *line
? line
:NULL
)))
513 rc
= app_get_serial_and_stamp (ctrl
->app_ctx
, &serial
, &stamp
);
517 rc
= estream_asprintf (&serial_and_stamp
, "%s %lu",
518 serial
, (unsigned long)stamp
);
521 return out_of_core ();
523 assuan_write_status (ctx
, "SERIALNO", serial_and_stamp
);
524 xfree (serial_and_stamp
);
531 /* LEARN [--force] [--keypairinfo]
533 Learn all useful information of the currently inserted card. When
534 used without the force options, the command might do an INQUIRE
537 INQUIRE KNOWNCARDP <hexstring_with_serialNumber> <timestamp>
539 The client should just send an "END" if the processing should go on
540 or a "CANCEL" to force the function to terminate with a Cancel
543 With the option --keypairinfo only KEYPARIINFO lstatus lines are
546 The response of this command is a list of status lines formatted as
551 This returns the type of the application, currently the strings:
553 P15 = PKCS-15 structure used
555 OPENPGP = OpenPGP card
558 are implemented. These strings are aliases for the AID
560 S KEYPAIRINFO <hexstring_with_keygrip> <hexstring_with_id>
562 If there is no certificate yet stored on the card a single "X" is
563 returned as the keygrip. In addition to the keypair info, information
564 about all certificates stored on the card is also returned:
566 S CERTINFO <certtype> <hexstring_with_id>
568 Where CERTTYPE is a number indicating the type of certificate:
570 100 := Regular X.509 cert
571 101 := Trusted X.509 cert
572 102 := Useful X.509 cert
573 110 := Root CA cert (e.g. DINSIG)
575 For certain cards, more information will be returned:
577 S KEY-FPR <no> <hexstring>
579 For OpenPGP cards this returns the stored fingerprints of the
580 keys. This can be used check whether a key is available on the
581 card. NO may be 1, 2 or 3.
583 S CA-FPR <no> <hexstring>
585 Similar to above, these are the fingerprints of keys assumed to be
588 S DISP-NAME <name_of_card_holder>
590 The name of the card holder as stored on the card; percent
591 escaping takes place, spaces are encoded as '+'
595 The URL to be used for locating the entire public key.
597 Note, that this function may even be used on a locked card.
600 cmd_learn (assuan_context_t ctx
, char *line
)
602 ctrl_t ctrl
= assuan_get_pointer (ctx
);
604 int only_keypairinfo
= has_option (line
, "--keypairinfo");
606 if ((rc
= open_card (ctrl
, NULL
)))
609 /* Unless the force option is used we try a shortcut by identifying
610 the card using a serial number and inquiring the client with
611 that. The client may choose to cancel the operation if he already
612 knows about this card */
613 if (!only_keypairinfo
)
615 char *serial_and_stamp
;
619 rc
= app_get_serial_and_stamp (ctrl
->app_ctx
, &serial
, &stamp
);
622 rc
= estream_asprintf (&serial_and_stamp
, "%s %lu",
623 serial
, (unsigned long)stamp
);
626 return out_of_core ();
628 assuan_write_status (ctx
, "SERIALNO", serial_and_stamp
);
630 if (!has_option (line
, "--force"))
634 rc
= estream_asprintf (&command
, "KNOWNCARDP %s", serial_and_stamp
);
637 xfree (serial_and_stamp
);
638 return out_of_core ();
641 rc
= assuan_inquire (ctx
, command
, NULL
, NULL
, 0);
645 if (gpg_err_code (rc
) != GPG_ERR_ASS_CANCELED
)
646 log_error ("inquire KNOWNCARDP failed: %s\n",
648 xfree (serial_and_stamp
);
651 /* Not canceled, so we have to proceeed. */
653 xfree (serial_and_stamp
);
656 /* Let the application print out its collection of useful status
659 rc
= app_write_learn_status (ctrl
->app_ctx
, ctrl
, only_keypairinfo
);
661 TEST_CARD_REMOVAL (ctrl
, rc
);
667 /* READCERT <hexified_certid>|<keyid>
669 Note, that this function may even be used on a locked card.
672 cmd_readcert (assuan_context_t ctx
, char *line
)
674 ctrl_t ctrl
= assuan_get_pointer (ctx
);
679 if ((rc
= open_card (ctrl
, NULL
)))
682 line
= xstrdup (line
); /* Need a copy of the line. */
683 rc
= app_readcert (ctrl
->app_ctx
, line
, &cert
, &ncert
);
685 log_error ("app_readcert failed: %s\n", gpg_strerror (rc
));
690 rc
= assuan_send_data (ctx
, cert
, ncert
);
696 TEST_CARD_REMOVAL (ctrl
, rc
);
703 Return the public key for the given cert or key ID as an standard
706 Note, that this function may even be used on a locked card.
709 cmd_readkey (assuan_context_t ctx
, char *line
)
711 ctrl_t ctrl
= assuan_get_pointer (ctx
);
713 unsigned char *cert
= NULL
;
715 ksba_cert_t kc
= NULL
;
720 if ((rc
= open_card (ctrl
, NULL
)))
723 line
= xstrdup (line
); /* Need a copy of the line. */
724 /* If the application supports the READKEY function we use that.
725 Otherwise we use the old way by extracting it from the
727 rc
= app_readkey (ctrl
->app_ctx
, line
, &pk
, &pklen
);
729 { /* Yeah, got that key - send it back. */
730 rc
= assuan_send_data (ctx
, pk
, pklen
);
737 if (gpg_err_code (rc
) != GPG_ERR_UNSUPPORTED_OPERATION
)
738 log_error ("app_readkey failed: %s\n", gpg_strerror (rc
));
741 rc
= app_readcert (ctrl
->app_ctx
, line
, &cert
, &ncert
);
743 log_error ("app_readcert failed: %s\n", gpg_strerror (rc
));
750 rc
= ksba_cert_new (&kc
);
756 rc
= ksba_cert_init_from_mem (kc
, cert
, ncert
);
759 log_error ("failed to parse the certificate: %s\n", gpg_strerror (rc
));
763 p
= ksba_cert_get_public_key (kc
);
766 rc
= gpg_error (GPG_ERR_NO_PUBKEY
);
770 n
= gcry_sexp_canon_len (p
, 0, NULL
, NULL
);
771 rc
= assuan_send_data (ctx
, p
, n
);
776 ksba_cert_release (kc
);
778 TEST_CARD_REMOVAL (ctrl
, rc
);
785 /* SETDATA <hexstring>
787 The client should use this command to tell us the data he want to
790 cmd_setdata (assuan_context_t ctx
, char *line
)
792 ctrl_t ctrl
= assuan_get_pointer (ctx
);
797 if (locked_session
&& locked_session
!= ctrl
->server_local
)
798 return gpg_error (GPG_ERR_LOCKED
);
800 /* Parse the hexstring. */
801 for (p
=line
,n
=0; hexdigitp (p
); p
++, n
++)
804 return set_error (GPG_ERR_ASS_PARAMETER
, "invalid hexstring");
806 return set_error (GPG_ERR_ASS_PARAMETER
, "no data given");
808 return set_error (GPG_ERR_ASS_PARAMETER
, "odd number of digits");
810 buf
= xtrymalloc (n
);
812 return out_of_core ();
814 ctrl
->in_data
.value
= buf
;
815 ctrl
->in_data
.valuelen
= n
;
816 for (p
=line
, n
=0; n
< ctrl
->in_data
.valuelen
; p
+= 2, n
++)
824 pin_cb (void *opaque
, const char *info
, char **retstr
)
826 assuan_context_t ctx
= opaque
;
829 unsigned char *value
;
834 /* We prompt for keypad entry. To make sure that the popup has
835 been show we use an inquire and not just a status message.
836 We ignore any value returned. */
839 log_debug ("prompting for keypad entry '%s'\n", info
);
840 rc
= estream_asprintf (&command
, "POPUPKEYPADPROMPT %s", info
);
842 return gpg_error (gpg_err_code_from_errno (errno
));
843 rc
= assuan_inquire (ctx
, command
, &value
, &valuelen
, MAXLEN_PIN
);
848 log_debug ("dismiss keypad entry prompt\n");
849 rc
= assuan_inquire (ctx
, "DISMISSKEYPADPROMPT",
850 &value
, &valuelen
, MAXLEN_PIN
);
858 log_debug ("asking for PIN '%s'\n", info
);
860 rc
= estream_asprintf (&command
, "NEEDPIN %s", info
);
862 return gpg_error (gpg_err_code_from_errno (errno
));
864 /* Fixme: Write an inquire function which returns the result in
865 secure memory and check all further handling of the PIN. */
866 rc
= assuan_inquire (ctx
, command
, &value
, &valuelen
, MAXLEN_PIN
);
871 if (!valuelen
|| value
[valuelen
-1])
873 /* We require that the returned value is an UTF-8 string */
875 return gpg_error (GPG_ERR_INV_RESPONSE
);
877 *retstr
= (char*)value
;
882 /* PKSIGN [--hash=[rmd160|sha1|md5]] <hexified_id>
884 The --hash option is optional; the default is SHA1.
888 cmd_pksign (assuan_context_t ctx
, char *line
)
890 ctrl_t ctrl
= assuan_get_pointer (ctx
);
892 unsigned char *outdata
;
897 if (has_option (line
, "--hash=rmd160"))
898 hash_algo
= GCRY_MD_RMD160
;
899 else if (has_option (line
, "--hash=sha1"))
900 hash_algo
= GCRY_MD_SHA1
;
901 else if (has_option (line
, "--hash=md5"))
902 hash_algo
= GCRY_MD_MD5
;
903 else if (!strstr (line
, "--"))
904 hash_algo
= GCRY_MD_SHA1
;
906 return set_error (GPG_ERR_ASS_PARAMETER
, "invalid hash algorithm");
908 line
= skip_options (line
);
910 if ( IS_LOCKED (ctrl
) )
911 return gpg_error (GPG_ERR_LOCKED
);
913 if ((rc
= open_card (ctrl
, NULL
)))
916 /* We have to use a copy of the key ID because the function may use
917 the pin_cb which in turn uses the assuan line buffer and thus
918 overwriting the original line with the keyid */
919 keyidstr
= xtrystrdup (line
);
921 return out_of_core ();
923 rc
= app_sign (ctrl
->app_ctx
,
926 ctrl
->in_data
.value
, ctrl
->in_data
.valuelen
,
927 &outdata
, &outdatalen
);
932 log_error ("card_sign failed: %s\n", gpg_strerror (rc
));
936 rc
= assuan_send_data (ctx
, outdata
, outdatalen
);
939 return rc
; /* that is already an assuan error code */
942 TEST_CARD_REMOVAL (ctrl
, rc
);
946 /* PKAUTH <hexified_id>
950 cmd_pkauth (assuan_context_t ctx
, char *line
)
952 ctrl_t ctrl
= assuan_get_pointer (ctx
);
954 unsigned char *outdata
;
958 if ( IS_LOCKED (ctrl
) )
959 return gpg_error (GPG_ERR_LOCKED
);
961 if ((rc
= open_card (ctrl
, NULL
)))
965 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION
);
967 /* We have to use a copy of the key ID because the function may use
968 the pin_cb which in turn uses the assuan line buffer and thus
969 overwriting the original line with the keyid */
970 keyidstr
= xtrystrdup (line
);
972 return out_of_core ();
974 rc
= app_auth (ctrl
->app_ctx
,
977 ctrl
->in_data
.value
, ctrl
->in_data
.valuelen
,
978 &outdata
, &outdatalen
);
982 log_error ("app_auth_sign failed: %s\n", gpg_strerror (rc
));
986 rc
= assuan_send_data (ctx
, outdata
, outdatalen
);
989 return rc
; /* that is already an assuan error code */
992 TEST_CARD_REMOVAL (ctrl
, rc
);
996 /* PKDECRYPT <hexified_id>
1000 cmd_pkdecrypt (assuan_context_t ctx
, char *line
)
1002 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1004 unsigned char *outdata
;
1008 if ( IS_LOCKED (ctrl
) )
1009 return gpg_error (GPG_ERR_LOCKED
);
1011 if ((rc
= open_card (ctrl
, NULL
)))
1014 keyidstr
= xtrystrdup (line
);
1016 return out_of_core ();
1017 rc
= app_decipher (ctrl
->app_ctx
,
1020 ctrl
->in_data
.value
, ctrl
->in_data
.valuelen
,
1021 &outdata
, &outdatalen
);
1026 log_error ("card_create_signature failed: %s\n", gpg_strerror (rc
));
1030 rc
= assuan_send_data (ctx
, outdata
, outdatalen
);
1033 return rc
; /* that is already an assuan error code */
1036 TEST_CARD_REMOVAL (ctrl
, rc
);
1043 This command is used to retrieve data from a smartcard. The
1044 allowed names depend on the currently selected smartcard
1045 application. NAME must be percent and '+' escaped. The value is
1046 returned through status message, see the LEARN command for details.
1048 However, the current implementation assumes that Name is not escaped;
1049 this works as long as noone uses arbitrary escaping.
1051 Note, that this function may even be used on a locked card.
1054 cmd_getattr (assuan_context_t ctx
, char *line
)
1056 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1058 const char *keyword
;
1060 if ((rc
= open_card (ctrl
, NULL
)))
1064 for (; *line
&& !spacep (line
); line
++)
1069 /* (We ignore any garbage for now.) */
1071 /* FIXME: Applications should not return sensitive data if the card
1073 rc
= app_getattr (ctrl
->app_ctx
, ctrl
, keyword
);
1075 TEST_CARD_REMOVAL (ctrl
, rc
);
1080 /* SETATTR <name> <value>
1082 This command is used to store data on a a smartcard. The allowed
1083 names and values are depend on the currently selected smartcard
1084 application. NAME and VALUE must be percent and '+' escaped.
1086 However, the current implementation assumes that NAME is not
1087 escaped; this works as long as noone uses arbitrary escaping.
1089 A PIN will be requested for most NAMEs. See the corresponding
1090 setattr function of the actually used application (app-*.c) for
1093 cmd_setattr (assuan_context_t ctx
, char *orig_line
)
1095 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1100 char *line
, *linebuf
;
1102 if ( IS_LOCKED (ctrl
) )
1103 return gpg_error (GPG_ERR_LOCKED
);
1105 if ((rc
= open_card (ctrl
, NULL
)))
1108 /* We need to use a copy of LINE, because PIN_CB uses the same
1109 context and thus reuses the Assuan provided LINE. */
1110 line
= linebuf
= xtrystrdup (orig_line
);
1112 return out_of_core ();
1115 for (keywordlen
=0; *line
&& !spacep (line
); line
++, keywordlen
++)
1119 while (spacep (line
))
1121 nbytes
= percent_plus_unescape ((unsigned char*)line
);
1123 rc
= app_setattr (ctrl
->app_ctx
, keyword
, pin_cb
, ctx
,
1124 (const unsigned char*)line
, nbytes
);
1127 TEST_CARD_REMOVAL (ctrl
, rc
);
1133 /* WRITECERT <hexified_certid>
1135 This command is used to store a certifciate on a smartcard. The
1136 allowed certids depend on the currently selected smartcard
1137 application. The actual certifciate is requested using the inquiry
1138 "CERTDATA" and needs to be provided in its raw (e.g. DER) form.
1140 In almost all cases a a PIN will be requested. See the related
1141 writecert function of the actually used application (app-*.c) for
1144 cmd_writecert (assuan_context_t ctx
, char *line
)
1146 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1149 unsigned char *certdata
;
1152 if ( IS_LOCKED (ctrl
) )
1153 return gpg_error (GPG_ERR_LOCKED
);
1155 line
= skip_options (line
);
1158 return set_error (GPG_ERR_ASS_PARAMETER
, "no certid given");
1160 while (*line
&& !spacep (line
))
1164 if ((rc
= open_card (ctrl
, NULL
)))
1168 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION
);
1170 certid
= xtrystrdup (certid
);
1172 return out_of_core ();
1174 /* Now get the actual keydata. */
1175 rc
= assuan_inquire (ctx
, "CERTDATA",
1176 &certdata
, &certdatalen
, MAXLEN_CERTDATA
);
1183 /* Write the certificate to the card. */
1184 rc
= app_writecert (ctrl
->app_ctx
, ctrl
, certid
,
1185 pin_cb
, ctx
, certdata
, certdatalen
);
1189 TEST_CARD_REMOVAL (ctrl
, rc
);
1195 /* WRITEKEY [--force] <keyid>
1197 This command is used to store a secret key on a a smartcard. The
1198 allowed keyids depend on the currently selected smartcard
1199 application. The actual keydata is requested using the inquiry
1200 "KEYDATA" and need to be provided without any protection. With
1201 --force set an existing key under this KEYID will get overwritten.
1202 The keydata is expected to be the usual canonical encoded
1205 A PIN will be requested for most NAMEs. See the corresponding
1206 writekey function of the actually used application (app-*.c) for
1209 cmd_writekey (assuan_context_t ctx
, char *line
)
1211 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1214 int force
= has_option (line
, "--force");
1215 unsigned char *keydata
;
1218 if ( IS_LOCKED (ctrl
) )
1219 return gpg_error (GPG_ERR_LOCKED
);
1221 line
= skip_options (line
);
1224 return set_error (GPG_ERR_ASS_PARAMETER
, "no keyid given");
1226 while (*line
&& !spacep (line
))
1230 if ((rc
= open_card (ctrl
, NULL
)))
1234 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION
);
1236 keyid
= xtrystrdup (keyid
);
1238 return out_of_core ();
1240 /* Now get the actual keydata. */
1241 assuan_begin_confidential (ctx
);
1242 rc
= assuan_inquire (ctx
, "KEYDATA", &keydata
, &keydatalen
, MAXLEN_KEYDATA
);
1243 assuan_end_confidential (ctx
);
1250 /* Write the key to the card. */
1251 rc
= app_writekey (ctrl
->app_ctx
, ctrl
, keyid
, force
? 1:0,
1252 pin_cb
, ctx
, keydata
, keydatalen
);
1256 TEST_CARD_REMOVAL (ctrl
, rc
);
1262 /* GENKEY [--force] [--timestamp=<isodate>] <no>
1264 Generate a key on-card identified by NO, which is application
1265 specific. Return values are application specific. For OpenPGP
1266 cards 2 status lines are returned:
1268 S KEY-FPR <hexstring>
1269 S KEY-CREATED-AT <seconds_since_epoch>
1270 S KEY-DATA [p|n] <hexdata>
1272 --force is required to overwrite an already existing key. The
1273 KEY-CREATED-AT is required for further processing because it is
1274 part of the hashed key material for the fingerprint.
1276 If --timestamp is given an OpenPGP key will be created using this
1277 value. The value needs to be in ISO Format; e.g.
1278 "--timestamp=20030316T120000" and after 1970-01-01 00:00:00.
1280 The public part of the key can also later be retrieved using the
1285 cmd_genkey (assuan_context_t ctx
, char *line
)
1287 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1294 if ( IS_LOCKED (ctrl
) )
1295 return gpg_error (GPG_ERR_LOCKED
);
1297 force
= has_option (line
, "--force");
1299 if ((s
=has_option_name (line
, "--timestamp")))
1302 return set_error (GPG_ERR_ASS_PARAMETER
, "missing value for option");
1303 timestamp
= isotime2epoch (s
+1);
1305 return set_error (GPG_ERR_ASS_PARAMETER
, "invalid time value");
1311 line
= skip_options (line
);
1313 return set_error (GPG_ERR_ASS_PARAMETER
, "no key number given");
1315 while (*line
&& !spacep (line
))
1319 if ((rc
= open_card (ctrl
, NULL
)))
1323 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION
);
1325 keyno
= xtrystrdup (keyno
);
1327 return out_of_core ();
1328 rc
= app_genkey (ctrl
->app_ctx
, ctrl
, keyno
, force
? 1:0,
1329 timestamp
, pin_cb
, ctx
);
1332 TEST_CARD_REMOVAL (ctrl
, rc
);
1339 Get NBYTES of random from the card and send them back as data.
1341 Note, that this function may be even be used on a locked card.
1344 cmd_random (assuan_context_t ctx
, char *line
)
1346 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1349 unsigned char *buffer
;
1352 return set_error (GPG_ERR_ASS_PARAMETER
, "number of requested bytes missing");
1353 nbytes
= strtoul (line
, NULL
, 0);
1355 if ((rc
= open_card (ctrl
, NULL
)))
1359 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION
);
1361 buffer
= xtrymalloc (nbytes
);
1363 return out_of_core ();
1365 rc
= app_get_challenge (ctrl
->app_ctx
, nbytes
, buffer
);
1368 rc
= assuan_send_data (ctx
, buffer
, nbytes
);
1370 return rc
; /* that is already an assuan error code */
1374 TEST_CARD_REMOVAL (ctrl
, rc
);
1379 /* PASSWD [--reset] [--nullpin] <chvno>
1381 Change the PIN or, if --reset is given, reset the retry counter of
1382 the card holder verfication vector CHVNO. The option --nullpin is
1383 used for TCOS cards to set the initial PIN. The format of CHVNO
1384 depends on the card application. */
1386 cmd_passwd (assuan_context_t ctx
, char *line
)
1388 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1391 unsigned int flags
= 0;
1393 if (has_option (line
, "--reset"))
1394 flags
|= APP_CHANGE_FLAG_RESET
;
1395 if (has_option (line
, "--nullpin"))
1396 flags
|= APP_CHANGE_FLAG_NULLPIN
;
1398 if ( IS_LOCKED (ctrl
) )
1399 return gpg_error (GPG_ERR_LOCKED
);
1401 line
= skip_options (line
);
1404 return set_error (GPG_ERR_ASS_PARAMETER
, "no CHV number given");
1406 while (*line
&& !spacep (line
))
1410 if ((rc
= open_card (ctrl
, NULL
)))
1414 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION
);
1416 chvnostr
= xtrystrdup (chvnostr
);
1418 return out_of_core ();
1419 rc
= app_change_pin (ctrl
->app_ctx
, ctrl
, chvnostr
, flags
, pin_cb
, ctx
);
1421 log_error ("command passwd failed: %s\n", gpg_strerror (rc
));
1424 TEST_CARD_REMOVAL (ctrl
, rc
);
1431 Perform a VERIFY operation without doing anything else. This may
1432 be used to initialize a the PIN cache earlier to long lasting
1433 operations. Its use is highly application dependent.
1437 Perform a simple verify operation for CHV1 and CHV2, so that
1438 further operations won't ask for CHV2 and it is possible to do a
1439 cheap check on the PIN: If there is something wrong with the PIN
1440 entry system, only the regular CHV will get blocked and not the
1441 dangerous CHV3. IDSTR is the usual card's serial number in hex
1442 notation; an optional fingerprint part will get ignored. There
1443 is however a special mode if the IDSTR is sffixed with the
1444 literal string "[CHV3]": In this case the Admin PIN is checked
1445 if and only if the retry counter is still at 3.
1449 Any of the valid PIN Ids may be used. These are the strings:
1451 PW1.CH - Global password 1
1452 PW2.CH - Global password 2
1453 PW1.CH.SIG - SigG password 1
1454 PW2.CH.SIG - SigG password 2
1456 For a definitive list, see the implementation in app-nks.c.
1457 Note that we call a PW2.* PIN a "PUK" despite that since TCOS
1458 3.0 they are technically alternative PINs used to mutally
1463 cmd_checkpin (assuan_context_t ctx
, char *line
)
1465 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1469 if ( IS_LOCKED (ctrl
) )
1470 return gpg_error (GPG_ERR_LOCKED
);
1472 if ((rc
= open_card (ctrl
, NULL
)))
1476 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION
);
1478 /* We have to use a copy of the key ID because the function may use
1479 the pin_cb which in turn uses the assuan line buffer and thus
1480 overwriting the original line with the keyid. */
1481 idstr
= xtrystrdup (line
);
1483 return out_of_core ();
1485 rc
= app_check_pin (ctrl
->app_ctx
, idstr
, pin_cb
, ctx
);
1488 log_error ("app_check_pin failed: %s\n", gpg_strerror (rc
));
1490 TEST_CARD_REMOVAL (ctrl
, rc
);
1497 Grant exclusive card access to this session. Note that there is
1498 no lock counter used and a second lock from the same session will
1499 be ignored. A single unlock (or RESET) unlocks the session.
1500 Return GPG_ERR_LOCKED if another session has locked the reader.
1502 If the option --wait is given the command will wait until a
1503 lock has been released.
1506 cmd_lock (assuan_context_t ctx
, char *line
)
1508 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1514 if (locked_session
!= ctrl
->server_local
)
1515 rc
= gpg_error (GPG_ERR_LOCKED
);
1518 locked_session
= ctrl
->server_local
;
1521 if (rc
&& has_option (line
, "--wait"))
1524 pth_sleep (1); /* Better implement an event mechanism. However,
1525 for card operations this should be
1527 /* FIXME: Need to check that the connection is still alive.
1528 This can be done by issuing status messages. */
1531 #endif /*USE_GNU_PTH*/
1534 log_error ("cmd_lock failed: %s\n", gpg_strerror (rc
));
1541 Release exclusive card access.
1544 cmd_unlock (assuan_context_t ctx
, char *line
)
1546 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1553 if (locked_session
!= ctrl
->server_local
)
1554 rc
= gpg_error (GPG_ERR_LOCKED
);
1556 locked_session
= NULL
;
1559 rc
= gpg_error (GPG_ERR_NOT_LOCKED
);
1562 log_error ("cmd_unlock failed: %s\n", gpg_strerror (rc
));
1569 Multi purpose command to return certain information.
1570 Supported values of WHAT are:
1572 version - Return the version of the program.
1573 pid - Return the process id of the server.
1575 socket_name - Return the name of the socket.
1577 status - Return the status of the current slot (in the future, may
1578 also return the status of all slots). The status is a list of
1579 one-character flags. The following flags are currently defined:
1580 'u' Usable card present. This is the normal state during operation.
1581 'r' Card removed. A reset is necessary.
1582 These flags are exclusive.
1584 reader_list - Return a list of detected card readers. Does
1585 currently only work with the internal CCID driver.
1587 deny_admin - Returns OK if admin commands are not allowed or
1588 GPG_ERR_GENERAL if admin commands are allowed.
1590 app_list - Return a list of supported applications. One
1591 application per line, fields delimited by colons,
1592 first field is the name.
1596 cmd_getinfo (assuan_context_t ctx
, char *line
)
1600 if (!strcmp (line
, "version"))
1602 const char *s
= VERSION
;
1603 rc
= assuan_send_data (ctx
, s
, strlen (s
));
1605 else if (!strcmp (line
, "pid"))
1609 snprintf (numbuf
, sizeof numbuf
, "%lu", (unsigned long)getpid ());
1610 rc
= assuan_send_data (ctx
, numbuf
, strlen (numbuf
));
1612 else if (!strcmp (line
, "socket_name"))
1614 const char *s
= scd_get_socket_name ();
1617 rc
= assuan_send_data (ctx
, s
, strlen (s
));
1619 rc
= gpg_error (GPG_ERR_NO_DATA
);
1621 else if (!strcmp (line
, "status"))
1623 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1624 int slot
= ctrl
->reader_slot
;
1627 if (!ctrl
->server_local
->card_removed
&& slot
!= -1)
1629 struct slot_status_s
*ss
;
1631 if (!(slot
>= 0 && slot
< DIM(slot_table
)))
1634 ss
= &slot_table
[slot
];
1639 if (ss
->any
&& (ss
->status
& 1))
1642 rc
= assuan_send_data (ctx
, &flag
, 1);
1644 else if (!strcmp (line
, "reader_list"))
1647 char *s
= ccid_get_reader_list ();
1653 rc
= assuan_send_data (ctx
, s
, strlen (s
));
1655 rc
= gpg_error (GPG_ERR_NO_DATA
);
1658 else if (!strcmp (line
, "deny_admin"))
1659 rc
= opt
.allow_admin
? gpg_error (GPG_ERR_GENERAL
) : 0;
1660 else if (!strcmp (line
, "app_list"))
1662 char *s
= get_supported_applications ();
1664 rc
= assuan_send_data (ctx
, s
, strlen (s
));
1670 rc
= set_error (GPG_ERR_ASS_PARAMETER
, "unknown value for WHAT");
1677 Restart the current connection; this is a kind of warm reset. It
1678 deletes the context used by this connection but does not send a
1679 RESET to the card. Thus the card itself won't get reset.
1681 This is used by gpg-agent to reuse a primary pipe connection and
1682 may be used by clients to backup from a conflict in the serial
1683 command; i.e. to select another application.
1687 cmd_restart (assuan_context_t ctx
, char *line
)
1689 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1695 release_application (ctrl
->app_ctx
);
1696 ctrl
->app_ctx
= NULL
;
1698 if (locked_session
&& ctrl
->server_local
== locked_session
)
1700 locked_session
= NULL
;
1701 log_info ("implicitly unlocking due to RESTART\n");
1709 Disconnect the card if it is not any longer used by other
1710 connections and the backend supports a disconnect operation.
1713 cmd_disconnect (assuan_context_t ctx
, char *line
)
1715 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1719 ctrl
->server_local
->disconnect_allowed
= 1;
1725 /* APDU [--atr] [--more] [hexstring]
1727 Send an APDU to the current reader. This command bypasses the high
1728 level functions and sends the data directly to the card. HEXSTRING
1729 is expected to be a proper APDU. If HEXSTRING is not given no
1730 commands are set to the card but the command will implictly check
1731 whether the card is ready for use.
1733 Using the option "--atr" returns the ATR of the card as a status
1734 message before any data like this:
1735 S CARD-ATR 3BFA1300FF813180450031C173C00100009000B1
1737 Using the option --more handles the card status word MORE_DATA
1738 (61xx) and concatenate all reponses to one block.
1742 cmd_apdu (assuan_context_t ctx
, char *line
)
1744 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1746 unsigned char *apdu
;
1751 with_atr
= has_option (line
, "--atr");
1752 handle_more
= has_option (line
, "--more");
1754 line
= skip_options (line
);
1756 if ( IS_LOCKED (ctrl
) )
1757 return gpg_error (GPG_ERR_LOCKED
);
1759 if ((rc
= open_card (ctrl
, NULL
)))
1768 atr
= apdu_get_atr (ctrl
->reader_slot
, &atrlen
);
1769 if (!atr
|| atrlen
> sizeof hexbuf
- 2 )
1771 rc
= gpg_error (GPG_ERR_INV_CARD
);
1774 bin2hex (atr
, atrlen
, hexbuf
);
1776 send_status_info (ctrl
, "CARD-ATR", hexbuf
, strlen (hexbuf
), NULL
, 0);
1779 apdu
= hex_to_buffer (line
, &apdulen
);
1782 rc
= gpg_error_from_syserror ();
1787 unsigned char *result
= NULL
;
1790 rc
= apdu_send_direct (ctrl
->reader_slot
, apdu
, apdulen
, handle_more
,
1791 &result
, &resultlen
);
1793 log_error ("apdu_send_direct failed: %s\n", gpg_strerror (rc
));
1796 rc
= assuan_send_data (ctx
, result
, resultlen
);
1803 TEST_CARD_REMOVAL (ctrl
, rc
);
1808 /* KILLSCD - Commit suicide. */
1810 cmd_killscd (assuan_context_t ctx
, char *line
)
1812 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1816 ctrl
->server_local
->stopme
= 1;
1817 return gpg_error (GPG_ERR_EOF
);
1822 /* Tell the assuan library about our commands */
1824 register_commands (assuan_context_t ctx
)
1828 int (*handler
)(assuan_context_t
, char *line
);
1830 { "SERIALNO", cmd_serialno
},
1831 { "LEARN", cmd_learn
},
1832 { "READCERT", cmd_readcert
},
1833 { "READKEY", cmd_readkey
},
1834 { "SETDATA", cmd_setdata
},
1835 { "PKSIGN", cmd_pksign
},
1836 { "PKAUTH", cmd_pkauth
},
1837 { "PKDECRYPT", cmd_pkdecrypt
},
1840 { "GETATTR", cmd_getattr
},
1841 { "SETATTR", cmd_setattr
},
1842 { "WRITECERT", cmd_writecert
},
1843 { "WRITEKEY", cmd_writekey
},
1844 { "GENKEY", cmd_genkey
},
1845 { "RANDOM", cmd_random
},
1846 { "PASSWD", cmd_passwd
},
1847 { "CHECKPIN", cmd_checkpin
},
1848 { "LOCK", cmd_lock
},
1849 { "UNLOCK", cmd_unlock
},
1850 { "GETINFO", cmd_getinfo
},
1851 { "RESTART", cmd_restart
},
1852 { "DISCONNECT", cmd_disconnect
},
1853 { "APDU", cmd_apdu
},
1854 { "KILLSCD", cmd_killscd
},
1859 for (i
=0; table
[i
].name
; i
++)
1861 rc
= assuan_register_command (ctx
, table
[i
].name
, table
[i
].handler
);
1865 assuan_set_hello_line (ctx
, "GNU Privacy Guard's Smartcard server ready");
1867 assuan_register_reset_notify (ctx
, reset_notify
);
1868 assuan_register_option_handler (ctx
, option_handler
);
1873 /* Startup the server. If FD is given as -1 this is simple pipe
1874 server, otherwise it is a regular server. Returns true if there
1875 are no more active asessions. */
1877 scd_command_handler (ctrl_t ctrl
, int fd
)
1880 assuan_context_t ctx
;
1889 rc
= assuan_init_pipe_server (&ctx
, filedes
);
1893 rc
= assuan_init_socket_server_ext (&ctx
, INT2FD(fd
), 2);
1897 log_error ("failed to initialize the server: %s\n",
1901 rc
= register_commands (ctx
);
1904 log_error ("failed to register commands with Assuan: %s\n",
1908 assuan_set_pointer (ctx
, ctrl
);
1910 /* Allocate and initialize the server object. Put it into the list
1911 of active sessions. */
1912 ctrl
->server_local
= xcalloc (1, sizeof *ctrl
->server_local
);
1913 ctrl
->server_local
->next_session
= session_list
;
1914 session_list
= ctrl
->server_local
;
1915 ctrl
->server_local
->ctrl_backlink
= ctrl
;
1916 ctrl
->server_local
->assuan_ctx
= ctx
;
1919 assuan_set_log_stream (ctx
, log_get_stream ());
1921 /* We open the reader right at startup so that the ticker is able to
1922 update the status file. */
1923 if (ctrl
->reader_slot
== -1)
1925 ctrl
->reader_slot
= get_reader_slot ();
1928 /* Command processing loop. */
1931 rc
= assuan_accept (ctx
);
1938 log_info ("Assuan accept problem: %s\n", gpg_strerror (rc
));
1942 rc
= assuan_process (ctx
);
1945 log_info ("Assuan processing failed: %s\n", gpg_strerror (rc
));
1950 /* Cleanup. We don't send an explicit reset to the card. */
1953 /* Release the server object. */
1954 if (session_list
== ctrl
->server_local
)
1955 session_list
= ctrl
->server_local
->next_session
;
1958 struct server_local_s
*sl
;
1960 for (sl
=session_list
; sl
->next_session
; sl
= sl
->next_session
)
1961 if (sl
->next_session
== ctrl
->server_local
)
1963 if (!sl
->next_session
)
1965 sl
->next_session
= ctrl
->server_local
->next_session
;
1967 stopme
= ctrl
->server_local
->stopme
;
1968 xfree (ctrl
->server_local
);
1969 ctrl
->server_local
= NULL
;
1971 /* Release the Assuan context. */
1972 assuan_deinit_server (ctx
);
1977 /* If there are no more sessions return true. */
1978 return !session_list
;
1982 /* Send a line with status information via assuan and escape all given
1983 buffers. The variable elements are pairs of (char *, size_t),
1984 terminated with a (NULL, 0). */
1986 send_status_info (ctrl_t ctrl
, const char *keyword
, ...)
1989 const unsigned char *value
;
1993 assuan_context_t ctx
= ctrl
->server_local
->assuan_ctx
;
1995 va_start (arg_ptr
, keyword
);
1999 while ( (value
= va_arg (arg_ptr
, const unsigned char *)) )
2001 valuelen
= va_arg (arg_ptr
, size_t);
2003 continue; /* empty buffer */
2009 for ( ; valuelen
&& n
< DIM (buf
)-2; n
++, valuelen
--, value
++)
2011 if (*value
< ' ' || *value
== '+')
2013 sprintf (p
, "%%%02X", *value
);
2016 else if (*value
== ' ')
2023 assuan_write_status (ctx
, keyword
, buf
);
2029 /* Send a ready formatted status line via assuan. */
2031 send_status_direct (ctrl_t ctrl
, const char *keyword
, const char *args
)
2033 assuan_context_t ctx
= ctrl
->server_local
->assuan_ctx
;
2035 if (strchr (args
, '\n'))
2036 log_error ("error: LF detected in status line - not sending\n");
2038 assuan_write_status (ctx
, keyword
, args
);
2042 /* Helper to send the clients a status change notification. */
2044 send_client_notifications (void)
2048 #ifdef HAVE_W32_SYSTEM
2056 struct server_local_s
*sl
;
2058 for (sl
=session_list
; sl
; sl
= sl
->next_session
)
2060 if (sl
->event_signal
&& sl
->assuan_ctx
)
2062 pid_t pid
= assuan_get_pid (sl
->assuan_ctx
);
2063 #ifdef HAVE_W32_SYSTEM
2064 HANDLE handle
= (void *)sl
->event_signal
;
2066 for (kidx
=0; kidx
< killidx
; kidx
++)
2067 if (killed
[kidx
].pid
== pid
2068 && killed
[kidx
].handle
== handle
)
2071 log_info ("event %lx (%p) already triggered for client %d\n",
2072 sl
->event_signal
, handle
, (int)pid
);
2075 log_info ("triggering event %lx (%p) for client %d\n",
2076 sl
->event_signal
, handle
, (int)pid
);
2077 if (!SetEvent (handle
))
2078 log_error ("SetEvent(%lx) failed: %s\n",
2079 sl
->event_signal
, w32_strerror (-1));
2080 if (killidx
< DIM (killed
))
2082 killed
[killidx
].pid
= pid
;
2083 killed
[killidx
].handle
= handle
;
2087 #else /*!HAVE_W32_SYSTEM*/
2088 int signo
= sl
->event_signal
;
2090 if (pid
!= (pid_t
)(-1) && pid
&& signo
> 0)
2092 for (kidx
=0; kidx
< killidx
; kidx
++)
2093 if (killed
[kidx
].pid
== pid
2094 && killed
[kidx
].signo
== signo
)
2097 log_info ("signal %d already sent to client %d\n",
2101 log_info ("sending signal %d to client %d\n",
2104 if (killidx
< DIM (killed
))
2106 killed
[killidx
].pid
= pid
;
2107 killed
[killidx
].signo
= signo
;
2112 #endif /*!HAVE_W32_SYSTEM*/
2119 /* This is the core of scd_update_reader_status_file but the caller
2120 needs to take care of the locking. */
2122 update_reader_status_file (int set_card_removed_flag
)
2125 unsigned int status
, changed
;
2127 /* Make sure that the reader has been opened. Like get_reader_slot,
2128 this part of the code assumes that there is only one reader. */
2129 if (!slot_table
[0].valid
)
2130 (void)get_reader_slot ();
2132 /* Note, that we only try to get the status, because it does not
2133 make sense to wait here for a operation to complete. If we are
2134 busy working with a card, delays in the status file update should
2136 for (idx
=0; idx
< DIM(slot_table
); idx
++)
2138 struct slot_status_s
*ss
= slot_table
+ idx
;
2139 struct server_local_s
*sl
;
2142 if (!ss
->valid
|| ss
->slot
== -1)
2143 continue; /* Not valid or reader not yet open. */
2145 sw_apdu
= apdu_get_status (ss
->slot
, 0, &status
, &changed
);
2148 /* Get status failed. Ignore that. */
2152 if (!ss
->any
|| ss
->status
!= status
|| ss
->changed
!= changed
)
2158 log_info ("updating slot %d status: 0x%04X->0x%04X (%u->%u)\n",
2159 ss
->slot
, ss
->status
, status
, ss
->changed
, changed
);
2160 ss
->status
= status
;
2161 ss
->changed
= changed
;
2163 /* FIXME: Should this be IDX instead of ss->slot? This
2164 depends on how client sessions will associate the reader
2165 status with their session. */
2166 snprintf (templ
, sizeof templ
, "reader_%d.status", ss
->slot
);
2167 fname
= make_filename (opt
.homedir
, templ
, NULL
);
2168 fp
= fopen (fname
, "w");
2171 fprintf (fp
, "%s\n",
2172 (status
& 1)? "USABLE":
2173 (status
& 4)? "ACTIVE":
2174 (status
& 2)? "PRESENT": "NOCARD");
2179 /* If a status script is executable, run it. */
2181 const char *args
[9], *envs
[2];
2182 char numbuf1
[30], numbuf2
[30], numbuf3
[30];
2183 char *homestr
, *envstr
;
2186 homestr
= make_filename (opt
.homedir
, NULL
);
2187 if (estream_asprintf (&envstr
, "GNUPGHOME=%s", homestr
) < 0)
2188 log_error ("out of core while building environment\n");
2194 sprintf (numbuf1
, "%d", ss
->slot
);
2195 sprintf (numbuf2
, "0x%04X", ss
->status
);
2196 sprintf (numbuf3
, "0x%04X", status
);
2197 args
[0] = "--reader-port";
2199 args
[2] = "--old-code";
2201 args
[4] = "--new-code";
2203 args
[6] = "--status";
2204 args
[7] = ((status
& 1)? "USABLE":
2205 (status
& 4)? "ACTIVE":
2206 (status
& 2)? "PRESENT": "NOCARD");
2209 fname
= make_filename (opt
.homedir
, "scd-event", NULL
);
2210 err
= gnupg_spawn_process_detached (fname
, args
, envs
);
2211 if (err
&& gpg_err_code (err
) != GPG_ERR_ENOENT
)
2212 log_error ("failed to run event handler `%s': %s\n",
2213 fname
, gpg_strerror (err
));
2220 /* Set the card removed flag for all current sessions. We
2221 will set this on any card change because a reset or
2222 SERIALNO request must be done in any case. */
2223 if (ss
->any
&& set_card_removed_flag
)
2224 update_card_removed (idx
, 1);
2228 /* Send a signal to all clients who applied for it. */
2229 send_client_notifications ();
2232 /* Check whether a disconnect is pending. */
2233 if (opt
.card_timeout
)
2235 for (sl
=session_list
; sl
; sl
= sl
->next_session
)
2236 if (!sl
->disconnect_allowed
)
2238 if (session_list
&& !sl
)
2240 /* FIXME: Use a real timeout. */
2241 /* At least one connection and all allow a disconnect. */
2242 log_info ("disconnecting card in slot %d\n", ss
->slot
);
2243 apdu_disconnect (ss
->slot
);
2250 /* This function is called by the ticker thread to check for changes
2251 of the reader stati. It updates the reader status files and if
2252 requested by the caller also send a signal to the caller. */
2254 scd_update_reader_status_file (void)
2256 if (!pth_mutex_acquire (&status_file_update_lock
, 1, NULL
))
2257 return; /* locked - give up. */
2258 update_reader_status_file (1);
2259 if (!pth_mutex_release (&status_file_update_lock
))
2260 log_error ("failed to release status_file_update lock\n");