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
, char *line
)
344 ctrl_t ctrl
= assuan_get_pointer (ctx
);
354 option_handler (assuan_context_t ctx
, const char *key
, const char *value
)
356 ctrl_t ctrl
= assuan_get_pointer (ctx
);
358 if (!strcmp (key
, "event-signal"))
360 /* A value of 0 is allowed to reset the event signal. */
361 #ifdef HAVE_W32_SYSTEM
363 return gpg_error (GPG_ERR_ASS_PARAMETER
);
364 ctrl
->server_local
->event_signal
= strtoul (value
, NULL
, 16);
366 int i
= *value
? atoi (value
) : -1;
368 return gpg_error (GPG_ERR_ASS_PARAMETER
);
369 ctrl
->server_local
->event_signal
= i
;
377 /* Return the slot of the current reader or open the reader if no
378 other sessions are using a reader. Note, that we currently support
379 only one reader but most of the code (except for this function)
380 should be able to cope with several readers. */
382 get_reader_slot (void)
384 struct slot_status_s
*ss
;
386 ss
= &slot_table
[0]; /* One reader for now. */
388 /* Initialize the item if needed. */
395 /* Try to open the reader. */
397 ss
->slot
= apdu_open_reader (opt
.reader_port
);
399 /* Return the slot_table index. */
403 /* If the card has not yet been opened, do it. Note that this
404 function returns an Assuan error, so don't map the error a second
407 open_card (ctrl_t ctrl
, const char *apptype
)
412 /* If we ever got a card not present error code, return that. Only
413 the SERIALNO command and a reset are able to clear from that
415 if (ctrl
->server_local
->card_removed
)
416 return gpg_error (GPG_ERR_CARD_REMOVED
);
418 if ( IS_LOCKED (ctrl
) )
419 return gpg_error (GPG_ERR_LOCKED
);
421 /* If the application has been marked for release do it now. We
422 can't do it immediately in do_reset because the application may
424 if (ctrl
->server_local
->app_ctx_marked_for_release
)
426 ctrl
->server_local
->app_ctx_marked_for_release
= 0;
427 release_application (ctrl
->app_ctx
);
428 ctrl
->app_ctx
= NULL
;
431 /* If we are already initialized for one specific application we
432 need to check that the client didn't requested a specific
433 application different from the one in use before we continue. */
435 return check_application_conflict (ctrl
, apptype
);
437 /* Setup the slot and select the application. */
438 if (ctrl
->reader_slot
!= -1)
439 slot
= ctrl
->reader_slot
;
441 slot
= get_reader_slot ();
442 ctrl
->reader_slot
= slot
;
444 err
= gpg_error (GPG_ERR_CARD
);
447 /* Fixme: We should move the apdu_connect call to
448 select_application. */
451 ctrl
->server_local
->disconnect_allowed
= 0;
452 sw
= apdu_connect (slot
);
453 if (sw
&& sw
!= SW_HOST_ALREADY_CONNECTED
)
455 if (sw
== SW_HOST_NO_CARD
)
456 err
= gpg_error (GPG_ERR_CARD_NOT_PRESENT
);
458 err
= gpg_error (GPG_ERR_CARD
);
461 err
= select_application (ctrl
, slot
, apptype
, &ctrl
->app_ctx
);
464 TEST_CARD_REMOVAL (ctrl
, err
);
469 /* SERIALNO [APPTYPE]
471 Return the serial number of the card using a status reponse. This
472 function should be used to check for the presence of a card.
474 If APPTYPE is given, an application of that type is selected and an
475 error is returned if the application is not supported or available.
476 The default is to auto-select the application using a hardwired
477 preference system. Note, that a future extension to this function
478 may allow to specify a list and order of applications to try.
480 This function is special in that it can be used to reset the card.
481 Most other functions will return an error when a card change has
482 been detected and the use of this function is therefore required.
484 Background: We want to keep the client clear of handling card
485 changes between operations; i.e. the client can assume that all
486 operations are done on the same card unless he calls this function.
489 cmd_serialno (assuan_context_t ctx
, char *line
)
491 ctrl_t ctrl
= assuan_get_pointer (ctx
);
493 char *serial_and_stamp
;
497 /* Clear the remove flag so that the open_card is able to reread it. */
498 if (ctrl
->server_local
->card_removed
)
500 if ( IS_LOCKED (ctrl
) )
501 return gpg_error (GPG_ERR_LOCKED
);
505 if ((rc
= open_card (ctrl
, *line
? line
:NULL
)))
508 rc
= app_get_serial_and_stamp (ctrl
->app_ctx
, &serial
, &stamp
);
512 rc
= estream_asprintf (&serial_and_stamp
, "%s %lu",
513 serial
, (unsigned long)stamp
);
516 return out_of_core ();
518 assuan_write_status (ctx
, "SERIALNO", serial_and_stamp
);
519 xfree (serial_and_stamp
);
526 /* LEARN [--force] [--keypairinfo]
528 Learn all useful information of the currently inserted card. When
529 used without the force options, the command might do an INQUIRE
532 INQUIRE KNOWNCARDP <hexstring_with_serialNumber> <timestamp>
534 The client should just send an "END" if the processing should go on
535 or a "CANCEL" to force the function to terminate with a Cancel
538 With the option --keypairinfo only KEYPARIINFO lstatus lines are
541 The response of this command is a list of status lines formatted as
546 This returns the type of the application, currently the strings:
548 P15 = PKCS-15 structure used
550 OPENPGP = OpenPGP card
553 are implemented. These strings are aliases for the AID
555 S KEYPAIRINFO <hexstring_with_keygrip> <hexstring_with_id>
557 If there is no certificate yet stored on the card a single "X" is
558 returned as the keygrip. In addition to the keypair info, information
559 about all certificates stored on the card is also returned:
561 S CERTINFO <certtype> <hexstring_with_id>
563 Where CERTTYPE is a number indicating the type of certificate:
565 100 := Regular X.509 cert
566 101 := Trusted X.509 cert
567 102 := Useful X.509 cert
568 110 := Root CA cert in a special format (e.g. DINSIG)
569 111 := Root CA cert as standard X509 cert.
571 For certain cards, more information will be returned:
573 S KEY-FPR <no> <hexstring>
575 For OpenPGP cards this returns the stored fingerprints of the
576 keys. This can be used check whether a key is available on the
577 card. NO may be 1, 2 or 3.
579 S CA-FPR <no> <hexstring>
581 Similar to above, these are the fingerprints of keys assumed to be
584 S DISP-NAME <name_of_card_holder>
586 The name of the card holder as stored on the card; percent
587 escaping takes place, spaces are encoded as '+'
591 The URL to be used for locating the entire public key.
593 Note, that this function may even be used on a locked card.
596 cmd_learn (assuan_context_t ctx
, char *line
)
598 ctrl_t ctrl
= assuan_get_pointer (ctx
);
600 int only_keypairinfo
= has_option (line
, "--keypairinfo");
602 if ((rc
= open_card (ctrl
, NULL
)))
605 /* Unless the force option is used we try a shortcut by identifying
606 the card using a serial number and inquiring the client with
607 that. The client may choose to cancel the operation if he already
608 knows about this card */
609 if (!only_keypairinfo
)
611 char *serial_and_stamp
;
615 rc
= app_get_serial_and_stamp (ctrl
->app_ctx
, &serial
, &stamp
);
618 rc
= estream_asprintf (&serial_and_stamp
, "%s %lu",
619 serial
, (unsigned long)stamp
);
622 return out_of_core ();
624 assuan_write_status (ctx
, "SERIALNO", serial_and_stamp
);
626 if (!has_option (line
, "--force"))
630 rc
= estream_asprintf (&command
, "KNOWNCARDP %s", serial_and_stamp
);
633 xfree (serial_and_stamp
);
634 return out_of_core ();
637 rc
= assuan_inquire (ctx
, command
, NULL
, NULL
, 0);
641 if (gpg_err_code (rc
) != GPG_ERR_ASS_CANCELED
)
642 log_error ("inquire KNOWNCARDP failed: %s\n",
644 xfree (serial_and_stamp
);
647 /* Not canceled, so we have to proceeed. */
649 xfree (serial_and_stamp
);
652 /* Let the application print out its collection of useful status
655 rc
= app_write_learn_status (ctrl
->app_ctx
, ctrl
, only_keypairinfo
);
657 TEST_CARD_REMOVAL (ctrl
, rc
);
663 /* READCERT <hexified_certid>|<keyid>
665 Note, that this function may even be used on a locked card.
668 cmd_readcert (assuan_context_t ctx
, char *line
)
670 ctrl_t ctrl
= assuan_get_pointer (ctx
);
675 if ((rc
= open_card (ctrl
, NULL
)))
678 line
= xstrdup (line
); /* Need a copy of the line. */
679 rc
= app_readcert (ctrl
->app_ctx
, line
, &cert
, &ncert
);
681 log_error ("app_readcert failed: %s\n", gpg_strerror (rc
));
686 rc
= assuan_send_data (ctx
, cert
, ncert
);
692 TEST_CARD_REMOVAL (ctrl
, rc
);
699 Return the public key for the given cert or key ID as an standard
702 Note, that this function may even be used on a locked card.
705 cmd_readkey (assuan_context_t ctx
, char *line
)
707 ctrl_t ctrl
= assuan_get_pointer (ctx
);
709 unsigned char *cert
= NULL
;
711 ksba_cert_t kc
= NULL
;
716 if ((rc
= open_card (ctrl
, NULL
)))
719 line
= xstrdup (line
); /* Need a copy of the line. */
720 /* If the application supports the READKEY function we use that.
721 Otherwise we use the old way by extracting it from the
723 rc
= app_readkey (ctrl
->app_ctx
, line
, &pk
, &pklen
);
725 { /* Yeah, got that key - send it back. */
726 rc
= assuan_send_data (ctx
, pk
, pklen
);
733 if (gpg_err_code (rc
) != GPG_ERR_UNSUPPORTED_OPERATION
)
734 log_error ("app_readkey failed: %s\n", gpg_strerror (rc
));
737 rc
= app_readcert (ctrl
->app_ctx
, line
, &cert
, &ncert
);
739 log_error ("app_readcert failed: %s\n", gpg_strerror (rc
));
746 rc
= ksba_cert_new (&kc
);
752 rc
= ksba_cert_init_from_mem (kc
, cert
, ncert
);
755 log_error ("failed to parse the certificate: %s\n", gpg_strerror (rc
));
759 p
= ksba_cert_get_public_key (kc
);
762 rc
= gpg_error (GPG_ERR_NO_PUBKEY
);
766 n
= gcry_sexp_canon_len (p
, 0, NULL
, NULL
);
767 rc
= assuan_send_data (ctx
, p
, n
);
772 ksba_cert_release (kc
);
774 TEST_CARD_REMOVAL (ctrl
, rc
);
781 /* SETDATA <hexstring>
783 The client should use this command to tell us the data he want to
786 cmd_setdata (assuan_context_t ctx
, char *line
)
788 ctrl_t ctrl
= assuan_get_pointer (ctx
);
793 if (locked_session
&& locked_session
!= ctrl
->server_local
)
794 return gpg_error (GPG_ERR_LOCKED
);
796 /* Parse the hexstring. */
797 for (p
=line
,n
=0; hexdigitp (p
); p
++, n
++)
800 return set_error (GPG_ERR_ASS_PARAMETER
, "invalid hexstring");
802 return set_error (GPG_ERR_ASS_PARAMETER
, "no data given");
804 return set_error (GPG_ERR_ASS_PARAMETER
, "odd number of digits");
806 buf
= xtrymalloc (n
);
808 return out_of_core ();
810 xfree (ctrl
->in_data
.value
);
811 ctrl
->in_data
.value
= buf
;
812 ctrl
->in_data
.valuelen
= n
;
813 for (p
=line
, n
=0; n
< ctrl
->in_data
.valuelen
; p
+= 2, n
++)
821 pin_cb (void *opaque
, const char *info
, char **retstr
)
823 assuan_context_t ctx
= opaque
;
826 unsigned char *value
;
831 /* We prompt for keypad entry. To make sure that the popup has
832 been show we use an inquire and not just a status message.
833 We ignore any value returned. */
836 log_debug ("prompting for keypad entry '%s'\n", info
);
837 rc
= estream_asprintf (&command
, "POPUPKEYPADPROMPT %s", info
);
839 return gpg_error (gpg_err_code_from_errno (errno
));
840 rc
= assuan_inquire (ctx
, command
, &value
, &valuelen
, MAXLEN_PIN
);
845 log_debug ("dismiss keypad entry prompt\n");
846 rc
= assuan_inquire (ctx
, "DISMISSKEYPADPROMPT",
847 &value
, &valuelen
, MAXLEN_PIN
);
855 log_debug ("asking for PIN '%s'\n", info
);
857 rc
= estream_asprintf (&command
, "NEEDPIN %s", info
);
859 return gpg_error (gpg_err_code_from_errno (errno
));
861 /* Fixme: Write an inquire function which returns the result in
862 secure memory and check all further handling of the PIN. */
863 rc
= assuan_inquire (ctx
, command
, &value
, &valuelen
, MAXLEN_PIN
);
868 if (!valuelen
|| value
[valuelen
-1])
870 /* We require that the returned value is an UTF-8 string */
872 return gpg_error (GPG_ERR_INV_RESPONSE
);
874 *retstr
= (char*)value
;
879 /* PKSIGN [--hash=[rmd160|sha{1,224,256,384,512}|md5]] <hexified_id>
881 The --hash option is optional; the default is SHA1.
885 cmd_pksign (assuan_context_t ctx
, char *line
)
887 ctrl_t ctrl
= assuan_get_pointer (ctx
);
889 unsigned char *outdata
;
894 if (has_option (line
, "--hash=rmd160"))
895 hash_algo
= GCRY_MD_RMD160
;
896 else if (has_option (line
, "--hash=sha1"))
897 hash_algo
= GCRY_MD_SHA1
;
898 else if (has_option (line
, "--hash=sha224"))
899 hash_algo
= GCRY_MD_SHA224
;
900 else if (has_option (line
, "--hash=sha256"))
901 hash_algo
= GCRY_MD_SHA256
;
902 else if (has_option (line
, "--hash=sha384"))
903 hash_algo
= GCRY_MD_SHA384
;
904 else if (has_option (line
, "--hash=sha512"))
905 hash_algo
= GCRY_MD_SHA512
;
906 else if (has_option (line
, "--hash=md5"))
907 hash_algo
= GCRY_MD_MD5
;
908 else if (!strstr (line
, "--"))
909 hash_algo
= GCRY_MD_SHA1
;
911 return set_error (GPG_ERR_ASS_PARAMETER
, "invalid hash algorithm");
913 line
= skip_options (line
);
915 if ( IS_LOCKED (ctrl
) )
916 return gpg_error (GPG_ERR_LOCKED
);
918 if ((rc
= open_card (ctrl
, NULL
)))
921 /* We have to use a copy of the key ID because the function may use
922 the pin_cb which in turn uses the assuan line buffer and thus
923 overwriting the original line with the keyid */
924 keyidstr
= xtrystrdup (line
);
926 return out_of_core ();
928 rc
= app_sign (ctrl
->app_ctx
,
931 ctrl
->in_data
.value
, ctrl
->in_data
.valuelen
,
932 &outdata
, &outdatalen
);
937 log_error ("app_sign failed: %s\n", gpg_strerror (rc
));
941 rc
= assuan_send_data (ctx
, outdata
, outdatalen
);
944 return rc
; /* that is already an assuan error code */
947 TEST_CARD_REMOVAL (ctrl
, rc
);
951 /* PKAUTH <hexified_id>
955 cmd_pkauth (assuan_context_t ctx
, char *line
)
957 ctrl_t ctrl
= assuan_get_pointer (ctx
);
959 unsigned char *outdata
;
963 if ( IS_LOCKED (ctrl
) )
964 return gpg_error (GPG_ERR_LOCKED
);
966 if ((rc
= open_card (ctrl
, NULL
)))
970 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION
);
972 /* We have to use a copy of the key ID because the function may use
973 the pin_cb which in turn uses the assuan line buffer and thus
974 overwriting the original line with the keyid */
975 keyidstr
= xtrystrdup (line
);
977 return out_of_core ();
979 rc
= app_auth (ctrl
->app_ctx
,
982 ctrl
->in_data
.value
, ctrl
->in_data
.valuelen
,
983 &outdata
, &outdatalen
);
987 log_error ("app_auth failed: %s\n", gpg_strerror (rc
));
991 rc
= assuan_send_data (ctx
, outdata
, outdatalen
);
994 return rc
; /* that is already an assuan error code */
997 TEST_CARD_REMOVAL (ctrl
, rc
);
1001 /* PKDECRYPT <hexified_id>
1005 cmd_pkdecrypt (assuan_context_t ctx
, char *line
)
1007 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1009 unsigned char *outdata
;
1013 if ( IS_LOCKED (ctrl
) )
1014 return gpg_error (GPG_ERR_LOCKED
);
1016 if ((rc
= open_card (ctrl
, NULL
)))
1019 keyidstr
= xtrystrdup (line
);
1021 return out_of_core ();
1022 rc
= app_decipher (ctrl
->app_ctx
,
1025 ctrl
->in_data
.value
, ctrl
->in_data
.valuelen
,
1026 &outdata
, &outdatalen
);
1031 log_error ("app_decipher failed: %s\n", gpg_strerror (rc
));
1035 rc
= assuan_send_data (ctx
, outdata
, outdatalen
);
1038 return rc
; /* that is already an assuan error code */
1041 TEST_CARD_REMOVAL (ctrl
, rc
);
1048 This command is used to retrieve data from a smartcard. The
1049 allowed names depend on the currently selected smartcard
1050 application. NAME must be percent and '+' escaped. The value is
1051 returned through status message, see the LEARN command for details.
1053 However, the current implementation assumes that Name is not escaped;
1054 this works as long as noone uses arbitrary escaping.
1056 Note, that this function may even be used on a locked card.
1059 cmd_getattr (assuan_context_t ctx
, char *line
)
1061 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1063 const char *keyword
;
1065 if ((rc
= open_card (ctrl
, NULL
)))
1069 for (; *line
&& !spacep (line
); line
++)
1074 /* (We ignore any garbage for now.) */
1076 /* FIXME: Applications should not return sensitive data if the card
1078 rc
= app_getattr (ctrl
->app_ctx
, ctrl
, keyword
);
1080 TEST_CARD_REMOVAL (ctrl
, rc
);
1085 /* SETATTR <name> <value>
1087 This command is used to store data on a a smartcard. The allowed
1088 names and values are depend on the currently selected smartcard
1089 application. NAME and VALUE must be percent and '+' escaped.
1091 However, the current implementation assumes that NAME is not
1092 escaped; this works as long as noone uses arbitrary escaping.
1094 A PIN will be requested for most NAMEs. See the corresponding
1095 setattr function of the actually used application (app-*.c) for
1098 cmd_setattr (assuan_context_t ctx
, char *orig_line
)
1100 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1105 char *line
, *linebuf
;
1107 if ( IS_LOCKED (ctrl
) )
1108 return gpg_error (GPG_ERR_LOCKED
);
1110 if ((rc
= open_card (ctrl
, NULL
)))
1113 /* We need to use a copy of LINE, because PIN_CB uses the same
1114 context and thus reuses the Assuan provided LINE. */
1115 line
= linebuf
= xtrystrdup (orig_line
);
1117 return out_of_core ();
1120 for (keywordlen
=0; *line
&& !spacep (line
); line
++, keywordlen
++)
1124 while (spacep (line
))
1126 nbytes
= percent_plus_unescape_inplace (line
, 0);
1128 rc
= app_setattr (ctrl
->app_ctx
, keyword
, pin_cb
, ctx
,
1129 (const unsigned char*)line
, nbytes
);
1132 TEST_CARD_REMOVAL (ctrl
, rc
);
1138 /* WRITECERT <hexified_certid>
1140 This command is used to store a certifciate on a smartcard. The
1141 allowed certids depend on the currently selected smartcard
1142 application. The actual certifciate is requested using the inquiry
1143 "CERTDATA" and needs to be provided in its raw (e.g. DER) form.
1145 In almost all cases a a PIN will be requested. See the related
1146 writecert function of the actually used application (app-*.c) for
1149 cmd_writecert (assuan_context_t ctx
, char *line
)
1151 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1154 unsigned char *certdata
;
1157 if ( IS_LOCKED (ctrl
) )
1158 return gpg_error (GPG_ERR_LOCKED
);
1160 line
= skip_options (line
);
1163 return set_error (GPG_ERR_ASS_PARAMETER
, "no certid given");
1165 while (*line
&& !spacep (line
))
1169 if ((rc
= open_card (ctrl
, NULL
)))
1173 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION
);
1175 certid
= xtrystrdup (certid
);
1177 return out_of_core ();
1179 /* Now get the actual keydata. */
1180 rc
= assuan_inquire (ctx
, "CERTDATA",
1181 &certdata
, &certdatalen
, MAXLEN_CERTDATA
);
1188 /* Write the certificate to the card. */
1189 rc
= app_writecert (ctrl
->app_ctx
, ctrl
, certid
,
1190 pin_cb
, ctx
, certdata
, certdatalen
);
1194 TEST_CARD_REMOVAL (ctrl
, rc
);
1200 /* WRITEKEY [--force] <keyid>
1202 This command is used to store a secret key on a a smartcard. The
1203 allowed keyids depend on the currently selected smartcard
1204 application. The actual keydata is requested using the inquiry
1205 "KEYDATA" and need to be provided without any protection. With
1206 --force set an existing key under this KEYID will get overwritten.
1207 The keydata is expected to be the usual canonical encoded
1210 A PIN will be requested for most NAMEs. See the corresponding
1211 writekey function of the actually used application (app-*.c) for
1214 cmd_writekey (assuan_context_t ctx
, char *line
)
1216 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1219 int force
= has_option (line
, "--force");
1220 unsigned char *keydata
;
1223 if ( IS_LOCKED (ctrl
) )
1224 return gpg_error (GPG_ERR_LOCKED
);
1226 line
= skip_options (line
);
1229 return set_error (GPG_ERR_ASS_PARAMETER
, "no keyid given");
1231 while (*line
&& !spacep (line
))
1235 if ((rc
= open_card (ctrl
, NULL
)))
1239 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION
);
1241 keyid
= xtrystrdup (keyid
);
1243 return out_of_core ();
1245 /* Now get the actual keydata. */
1246 assuan_begin_confidential (ctx
);
1247 rc
= assuan_inquire (ctx
, "KEYDATA", &keydata
, &keydatalen
, MAXLEN_KEYDATA
);
1248 assuan_end_confidential (ctx
);
1255 /* Write the key to the card. */
1256 rc
= app_writekey (ctrl
->app_ctx
, ctrl
, keyid
, force
? 1:0,
1257 pin_cb
, ctx
, keydata
, keydatalen
);
1261 TEST_CARD_REMOVAL (ctrl
, rc
);
1267 /* GENKEY [--force] [--timestamp=<isodate>] <no>
1269 Generate a key on-card identified by NO, which is application
1270 specific. Return values are application specific. For OpenPGP
1271 cards 2 status lines are returned:
1273 S KEY-FPR <hexstring>
1274 S KEY-CREATED-AT <seconds_since_epoch>
1275 S KEY-DATA [p|n] <hexdata>
1277 --force is required to overwrite an already existing key. The
1278 KEY-CREATED-AT is required for further processing because it is
1279 part of the hashed key material for the fingerprint.
1281 If --timestamp is given an OpenPGP key will be created using this
1282 value. The value needs to be in ISO Format; e.g.
1283 "--timestamp=20030316T120000" and after 1970-01-01 00:00:00.
1285 The public part of the key can also later be retrieved using the
1290 cmd_genkey (assuan_context_t ctx
, char *line
)
1292 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1299 if ( IS_LOCKED (ctrl
) )
1300 return gpg_error (GPG_ERR_LOCKED
);
1302 force
= has_option (line
, "--force");
1304 if ((s
=has_option_name (line
, "--timestamp")))
1307 return set_error (GPG_ERR_ASS_PARAMETER
, "missing value for option");
1308 timestamp
= isotime2epoch (s
+1);
1310 return set_error (GPG_ERR_ASS_PARAMETER
, "invalid time value");
1316 line
= skip_options (line
);
1318 return set_error (GPG_ERR_ASS_PARAMETER
, "no key number given");
1320 while (*line
&& !spacep (line
))
1324 if ((rc
= open_card (ctrl
, NULL
)))
1328 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION
);
1330 keyno
= xtrystrdup (keyno
);
1332 return out_of_core ();
1333 rc
= app_genkey (ctrl
->app_ctx
, ctrl
, keyno
, force
? 1:0,
1334 timestamp
, pin_cb
, ctx
);
1337 TEST_CARD_REMOVAL (ctrl
, rc
);
1344 Get NBYTES of random from the card and send them back as data.
1346 Note, that this function may be even be used on a locked card.
1349 cmd_random (assuan_context_t ctx
, char *line
)
1351 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1354 unsigned char *buffer
;
1357 return set_error (GPG_ERR_ASS_PARAMETER
, "number of requested bytes missing");
1358 nbytes
= strtoul (line
, NULL
, 0);
1360 if ((rc
= open_card (ctrl
, NULL
)))
1364 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION
);
1366 buffer
= xtrymalloc (nbytes
);
1368 return out_of_core ();
1370 rc
= app_get_challenge (ctrl
->app_ctx
, nbytes
, buffer
);
1373 rc
= assuan_send_data (ctx
, buffer
, nbytes
);
1375 return rc
; /* that is already an assuan error code */
1379 TEST_CARD_REMOVAL (ctrl
, rc
);
1384 /* PASSWD [--reset] [--nullpin] <chvno>
1386 Change the PIN or, if --reset is given, reset the retry counter of
1387 the card holder verfication vector CHVNO. The option --nullpin is
1388 used for TCOS cards to set the initial PIN. The format of CHVNO
1389 depends on the card application. */
1391 cmd_passwd (assuan_context_t ctx
, char *line
)
1393 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1396 unsigned int flags
= 0;
1398 if (has_option (line
, "--reset"))
1399 flags
|= APP_CHANGE_FLAG_RESET
;
1400 if (has_option (line
, "--nullpin"))
1401 flags
|= APP_CHANGE_FLAG_NULLPIN
;
1403 if ( IS_LOCKED (ctrl
) )
1404 return gpg_error (GPG_ERR_LOCKED
);
1406 line
= skip_options (line
);
1409 return set_error (GPG_ERR_ASS_PARAMETER
, "no CHV number given");
1411 while (*line
&& !spacep (line
))
1415 if ((rc
= open_card (ctrl
, NULL
)))
1419 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION
);
1421 chvnostr
= xtrystrdup (chvnostr
);
1423 return out_of_core ();
1424 rc
= app_change_pin (ctrl
->app_ctx
, ctrl
, chvnostr
, flags
, pin_cb
, ctx
);
1426 log_error ("command passwd failed: %s\n", gpg_strerror (rc
));
1429 TEST_CARD_REMOVAL (ctrl
, rc
);
1436 Perform a VERIFY operation without doing anything else. This may
1437 be used to initialize a the PIN cache earlier to long lasting
1438 operations. Its use is highly application dependent.
1442 Perform a simple verify operation for CHV1 and CHV2, so that
1443 further operations won't ask for CHV2 and it is possible to do a
1444 cheap check on the PIN: If there is something wrong with the PIN
1445 entry system, only the regular CHV will get blocked and not the
1446 dangerous CHV3. IDSTR is the usual card's serial number in hex
1447 notation; an optional fingerprint part will get ignored. There
1448 is however a special mode if the IDSTR is sffixed with the
1449 literal string "[CHV3]": In this case the Admin PIN is checked
1450 if and only if the retry counter is still at 3.
1454 Any of the valid PIN Ids may be used. These are the strings:
1456 PW1.CH - Global password 1
1457 PW2.CH - Global password 2
1458 PW1.CH.SIG - SigG password 1
1459 PW2.CH.SIG - SigG password 2
1461 For a definitive list, see the implementation in app-nks.c.
1462 Note that we call a PW2.* PIN a "PUK" despite that since TCOS
1463 3.0 they are technically alternative PINs used to mutally
1468 cmd_checkpin (assuan_context_t ctx
, char *line
)
1470 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1474 if ( IS_LOCKED (ctrl
) )
1475 return gpg_error (GPG_ERR_LOCKED
);
1477 if ((rc
= open_card (ctrl
, NULL
)))
1481 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION
);
1483 /* We have to use a copy of the key ID because the function may use
1484 the pin_cb which in turn uses the assuan line buffer and thus
1485 overwriting the original line with the keyid. */
1486 idstr
= xtrystrdup (line
);
1488 return out_of_core ();
1490 rc
= app_check_pin (ctrl
->app_ctx
, idstr
, pin_cb
, ctx
);
1493 log_error ("app_check_pin failed: %s\n", gpg_strerror (rc
));
1495 TEST_CARD_REMOVAL (ctrl
, rc
);
1502 Grant exclusive card access to this session. Note that there is
1503 no lock counter used and a second lock from the same session will
1504 be ignored. A single unlock (or RESET) unlocks the session.
1505 Return GPG_ERR_LOCKED if another session has locked the reader.
1507 If the option --wait is given the command will wait until a
1508 lock has been released.
1511 cmd_lock (assuan_context_t ctx
, char *line
)
1513 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1519 if (locked_session
!= ctrl
->server_local
)
1520 rc
= gpg_error (GPG_ERR_LOCKED
);
1523 locked_session
= ctrl
->server_local
;
1526 if (rc
&& has_option (line
, "--wait"))
1529 pth_sleep (1); /* Better implement an event mechanism. However,
1530 for card operations this should be
1532 /* FIXME: Need to check that the connection is still alive.
1533 This can be done by issuing status messages. */
1536 #endif /*USE_GNU_PTH*/
1539 log_error ("cmd_lock failed: %s\n", gpg_strerror (rc
));
1546 Release exclusive card access.
1549 cmd_unlock (assuan_context_t ctx
, char *line
)
1551 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1558 if (locked_session
!= ctrl
->server_local
)
1559 rc
= gpg_error (GPG_ERR_LOCKED
);
1561 locked_session
= NULL
;
1564 rc
= gpg_error (GPG_ERR_NOT_LOCKED
);
1567 log_error ("cmd_unlock failed: %s\n", gpg_strerror (rc
));
1574 Multi purpose command to return certain information.
1575 Supported values of WHAT are:
1577 version - Return the version of the program.
1578 pid - Return the process id of the server.
1580 socket_name - Return the name of the socket.
1582 status - Return the status of the current slot (in the future, may
1583 also return the status of all slots). The status is a list of
1584 one-character flags. The following flags are currently defined:
1585 'u' Usable card present. This is the normal state during operation.
1586 'r' Card removed. A reset is necessary.
1587 These flags are exclusive.
1589 reader_list - Return a list of detected card readers. Does
1590 currently only work with the internal CCID driver.
1592 deny_admin - Returns OK if admin commands are not allowed or
1593 GPG_ERR_GENERAL if admin commands are allowed.
1595 app_list - Return a list of supported applications. One
1596 application per line, fields delimited by colons,
1597 first field is the name.
1601 cmd_getinfo (assuan_context_t ctx
, char *line
)
1605 if (!strcmp (line
, "version"))
1607 const char *s
= VERSION
;
1608 rc
= assuan_send_data (ctx
, s
, strlen (s
));
1610 else if (!strcmp (line
, "pid"))
1614 snprintf (numbuf
, sizeof numbuf
, "%lu", (unsigned long)getpid ());
1615 rc
= assuan_send_data (ctx
, numbuf
, strlen (numbuf
));
1617 else if (!strcmp (line
, "socket_name"))
1619 const char *s
= scd_get_socket_name ();
1622 rc
= assuan_send_data (ctx
, s
, strlen (s
));
1624 rc
= gpg_error (GPG_ERR_NO_DATA
);
1626 else if (!strcmp (line
, "status"))
1628 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1629 int slot
= ctrl
->reader_slot
;
1632 if (!ctrl
->server_local
->card_removed
&& slot
!= -1)
1634 struct slot_status_s
*ss
;
1636 if (!(slot
>= 0 && slot
< DIM(slot_table
)))
1639 ss
= &slot_table
[slot
];
1644 if (ss
->any
&& (ss
->status
& 1))
1647 rc
= assuan_send_data (ctx
, &flag
, 1);
1649 else if (!strcmp (line
, "reader_list"))
1652 char *s
= ccid_get_reader_list ();
1658 rc
= assuan_send_data (ctx
, s
, strlen (s
));
1660 rc
= gpg_error (GPG_ERR_NO_DATA
);
1663 else if (!strcmp (line
, "deny_admin"))
1664 rc
= opt
.allow_admin
? gpg_error (GPG_ERR_GENERAL
) : 0;
1665 else if (!strcmp (line
, "app_list"))
1667 char *s
= get_supported_applications ();
1669 rc
= assuan_send_data (ctx
, s
, strlen (s
));
1675 rc
= set_error (GPG_ERR_ASS_PARAMETER
, "unknown value for WHAT");
1682 Restart the current connection; this is a kind of warm reset. It
1683 deletes the context used by this connection but does not send a
1684 RESET to the card. Thus the card itself won't get reset.
1686 This is used by gpg-agent to reuse a primary pipe connection and
1687 may be used by clients to backup from a conflict in the serial
1688 command; i.e. to select another application.
1692 cmd_restart (assuan_context_t ctx
, char *line
)
1694 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1700 release_application (ctrl
->app_ctx
);
1701 ctrl
->app_ctx
= NULL
;
1703 if (locked_session
&& ctrl
->server_local
== locked_session
)
1705 locked_session
= NULL
;
1706 log_info ("implicitly unlocking due to RESTART\n");
1714 Disconnect the card if it is not any longer used by other
1715 connections and the backend supports a disconnect operation.
1718 cmd_disconnect (assuan_context_t ctx
, char *line
)
1720 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1724 ctrl
->server_local
->disconnect_allowed
= 1;
1730 /* APDU [--atr] [--more] [--exlen[=N]] [hexstring]
1732 Send an APDU to the current reader. This command bypasses the high
1733 level functions and sends the data directly to the card. HEXSTRING
1734 is expected to be a proper APDU. If HEXSTRING is not given no
1735 commands are set to the card but the command will implictly check
1736 whether the card is ready for use.
1738 Using the option "--atr" returns the ATR of the card as a status
1739 message before any data like this:
1740 S CARD-ATR 3BFA1300FF813180450031C173C00100009000B1
1742 Using the option --more handles the card status word MORE_DATA
1743 (61xx) and concatenates all reponses to one block.
1745 Using the option "--exlen" the returned APDU may use extended
1746 length up to N bytes. If N is not given a default value is used
1750 cmd_apdu (assuan_context_t ctx
, char *line
)
1752 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1754 unsigned char *apdu
;
1761 with_atr
= has_option (line
, "--atr");
1762 handle_more
= has_option (line
, "--more");
1764 if ((s
=has_option_name (line
, "--exlen")))
1767 exlen
= strtoul (s
+1, NULL
, 0);
1774 line
= skip_options (line
);
1776 if ( IS_LOCKED (ctrl
) )
1777 return gpg_error (GPG_ERR_LOCKED
);
1779 if ((rc
= open_card (ctrl
, NULL
)))
1788 atr
= apdu_get_atr (ctrl
->reader_slot
, &atrlen
);
1789 if (!atr
|| atrlen
> sizeof hexbuf
- 2 )
1791 rc
= gpg_error (GPG_ERR_INV_CARD
);
1794 bin2hex (atr
, atrlen
, hexbuf
);
1796 send_status_info (ctrl
, "CARD-ATR", hexbuf
, strlen (hexbuf
), NULL
, 0);
1799 apdu
= hex_to_buffer (line
, &apdulen
);
1802 rc
= gpg_error_from_syserror ();
1807 unsigned char *result
= NULL
;
1810 rc
= apdu_send_direct (ctrl
->reader_slot
, exlen
,
1811 apdu
, apdulen
, handle_more
,
1812 &result
, &resultlen
);
1814 log_error ("apdu_send_direct failed: %s\n", gpg_strerror (rc
));
1817 rc
= assuan_send_data (ctx
, result
, resultlen
);
1824 TEST_CARD_REMOVAL (ctrl
, rc
);
1829 /* KILLSCD - Commit suicide. */
1831 cmd_killscd (assuan_context_t ctx
, char *line
)
1833 ctrl_t ctrl
= assuan_get_pointer (ctx
);
1837 ctrl
->server_local
->stopme
= 1;
1838 return gpg_error (GPG_ERR_EOF
);
1843 /* Tell the assuan library about our commands */
1845 register_commands (assuan_context_t ctx
)
1849 assuan_handler_t handler
;
1851 { "SERIALNO", cmd_serialno
},
1852 { "LEARN", cmd_learn
},
1853 { "READCERT", cmd_readcert
},
1854 { "READKEY", cmd_readkey
},
1855 { "SETDATA", cmd_setdata
},
1856 { "PKSIGN", cmd_pksign
},
1857 { "PKAUTH", cmd_pkauth
},
1858 { "PKDECRYPT", cmd_pkdecrypt
},
1861 { "GETATTR", cmd_getattr
},
1862 { "SETATTR", cmd_setattr
},
1863 { "WRITECERT", cmd_writecert
},
1864 { "WRITEKEY", cmd_writekey
},
1865 { "GENKEY", cmd_genkey
},
1866 { "RANDOM", cmd_random
},
1867 { "PASSWD", cmd_passwd
},
1868 { "CHECKPIN", cmd_checkpin
},
1869 { "LOCK", cmd_lock
},
1870 { "UNLOCK", cmd_unlock
},
1871 { "GETINFO", cmd_getinfo
},
1872 { "RESTART", cmd_restart
},
1873 { "DISCONNECT", cmd_disconnect
},
1874 { "APDU", cmd_apdu
},
1875 { "KILLSCD", cmd_killscd
},
1880 for (i
=0; table
[i
].name
; i
++)
1882 rc
= assuan_register_command (ctx
, table
[i
].name
, table
[i
].handler
);
1886 assuan_set_hello_line (ctx
, "GNU Privacy Guard's Smartcard server ready");
1888 assuan_register_reset_notify (ctx
, reset_notify
);
1889 assuan_register_option_handler (ctx
, option_handler
);
1894 /* Startup the server. If FD is given as -1 this is simple pipe
1895 server, otherwise it is a regular server. Returns true if there
1896 are no more active asessions. */
1898 scd_command_handler (ctrl_t ctrl
, int fd
)
1901 assuan_context_t ctx
= NULL
;
1904 rc
= assuan_new (&ctx
);
1907 log_error ("failed to allocate assuan context: %s\n",
1918 rc
= assuan_init_pipe_server (ctx
, filedes
);
1922 rc
= assuan_init_socket_server_ext (ctx
, INT2FD(fd
), 2);
1926 log_error ("failed to initialize the server: %s\n",
1930 rc
= register_commands (ctx
);
1933 log_error ("failed to register commands with Assuan: %s\n",
1937 assuan_set_pointer (ctx
, ctrl
);
1939 /* Allocate and initialize the server object. Put it into the list
1940 of active sessions. */
1941 ctrl
->server_local
= xcalloc (1, sizeof *ctrl
->server_local
);
1942 ctrl
->server_local
->next_session
= session_list
;
1943 session_list
= ctrl
->server_local
;
1944 ctrl
->server_local
->ctrl_backlink
= ctrl
;
1945 ctrl
->server_local
->assuan_ctx
= ctx
;
1948 assuan_set_log_stream (ctx
, log_get_stream ());
1950 /* We open the reader right at startup so that the ticker is able to
1951 update the status file. */
1952 if (ctrl
->reader_slot
== -1)
1954 ctrl
->reader_slot
= get_reader_slot ();
1957 /* Command processing loop. */
1960 rc
= assuan_accept (ctx
);
1967 log_info ("Assuan accept problem: %s\n", gpg_strerror (rc
));
1971 rc
= assuan_process (ctx
);
1974 log_info ("Assuan processing failed: %s\n", gpg_strerror (rc
));
1979 /* Cleanup. We don't send an explicit reset to the card. */
1982 /* Release the server object. */
1983 if (session_list
== ctrl
->server_local
)
1984 session_list
= ctrl
->server_local
->next_session
;
1987 struct server_local_s
*sl
;
1989 for (sl
=session_list
; sl
->next_session
; sl
= sl
->next_session
)
1990 if (sl
->next_session
== ctrl
->server_local
)
1992 if (!sl
->next_session
)
1994 sl
->next_session
= ctrl
->server_local
->next_session
;
1996 stopme
= ctrl
->server_local
->stopme
;
1997 xfree (ctrl
->server_local
);
1998 ctrl
->server_local
= NULL
;
2000 /* Release the Assuan context. */
2001 assuan_release (ctx
);
2006 /* If there are no more sessions return true. */
2007 return !session_list
;
2011 /* Send a line with status information via assuan and escape all given
2012 buffers. The variable elements are pairs of (char *, size_t),
2013 terminated with a (NULL, 0). */
2015 send_status_info (ctrl_t ctrl
, const char *keyword
, ...)
2018 const unsigned char *value
;
2022 assuan_context_t ctx
= ctrl
->server_local
->assuan_ctx
;
2024 va_start (arg_ptr
, keyword
);
2028 while ( (value
= va_arg (arg_ptr
, const unsigned char *)) )
2030 valuelen
= va_arg (arg_ptr
, size_t);
2032 continue; /* empty buffer */
2038 for ( ; valuelen
&& n
< DIM (buf
)-2; n
++, valuelen
--, value
++)
2040 if (*value
< ' ' || *value
== '+')
2042 sprintf (p
, "%%%02X", *value
);
2045 else if (*value
== ' ')
2052 assuan_write_status (ctx
, keyword
, buf
);
2058 /* Send a ready formatted status line via assuan. */
2060 send_status_direct (ctrl_t ctrl
, const char *keyword
, const char *args
)
2062 assuan_context_t ctx
= ctrl
->server_local
->assuan_ctx
;
2064 if (strchr (args
, '\n'))
2065 log_error ("error: LF detected in status line - not sending\n");
2067 assuan_write_status (ctx
, keyword
, args
);
2071 /* Helper to send the clients a status change notification. */
2073 send_client_notifications (void)
2077 #ifdef HAVE_W32_SYSTEM
2085 struct server_local_s
*sl
;
2087 for (sl
=session_list
; sl
; sl
= sl
->next_session
)
2089 if (sl
->event_signal
&& sl
->assuan_ctx
)
2091 pid_t pid
= assuan_get_pid (sl
->assuan_ctx
);
2092 #ifdef HAVE_W32_SYSTEM
2093 HANDLE handle
= (void *)sl
->event_signal
;
2095 for (kidx
=0; kidx
< killidx
; kidx
++)
2096 if (killed
[kidx
].pid
== pid
2097 && killed
[kidx
].handle
== handle
)
2100 log_info ("event %lx (%p) already triggered for client %d\n",
2101 sl
->event_signal
, handle
, (int)pid
);
2104 log_info ("triggering event %lx (%p) for client %d\n",
2105 sl
->event_signal
, handle
, (int)pid
);
2106 if (!SetEvent (handle
))
2107 log_error ("SetEvent(%lx) failed: %s\n",
2108 sl
->event_signal
, w32_strerror (-1));
2109 if (killidx
< DIM (killed
))
2111 killed
[killidx
].pid
= pid
;
2112 killed
[killidx
].handle
= handle
;
2116 #else /*!HAVE_W32_SYSTEM*/
2117 int signo
= sl
->event_signal
;
2119 if (pid
!= (pid_t
)(-1) && pid
&& signo
> 0)
2121 for (kidx
=0; kidx
< killidx
; kidx
++)
2122 if (killed
[kidx
].pid
== pid
2123 && killed
[kidx
].signo
== signo
)
2126 log_info ("signal %d already sent to client %d\n",
2130 log_info ("sending signal %d to client %d\n",
2133 if (killidx
< DIM (killed
))
2135 killed
[killidx
].pid
= pid
;
2136 killed
[killidx
].signo
= signo
;
2141 #endif /*!HAVE_W32_SYSTEM*/
2148 /* This is the core of scd_update_reader_status_file but the caller
2149 needs to take care of the locking. */
2151 update_reader_status_file (int set_card_removed_flag
)
2154 unsigned int status
, changed
;
2156 /* Make sure that the reader has been opened. Like get_reader_slot,
2157 this part of the code assumes that there is only one reader. */
2158 if (!slot_table
[0].valid
)
2159 (void)get_reader_slot ();
2161 /* Note, that we only try to get the status, because it does not
2162 make sense to wait here for a operation to complete. If we are
2163 busy working with a card, delays in the status file update should
2165 for (idx
=0; idx
< DIM(slot_table
); idx
++)
2167 struct slot_status_s
*ss
= slot_table
+ idx
;
2168 struct server_local_s
*sl
;
2171 if (!ss
->valid
|| ss
->slot
== -1)
2172 continue; /* Not valid or reader not yet open. */
2174 sw_apdu
= apdu_get_status (ss
->slot
, 0, &status
, &changed
);
2175 if (sw_apdu
== SW_HOST_NO_READER
)
2177 /* Most likely the _reader_ has been unplugged. */
2179 changed
= ss
->changed
;
2183 /* Get status failed. Ignore that. */
2187 if (!ss
->any
|| ss
->status
!= status
|| ss
->changed
!= changed
)
2193 log_info ("updating slot %d status: 0x%04X->0x%04X (%u->%u)\n",
2194 ss
->slot
, ss
->status
, status
, ss
->changed
, changed
);
2195 ss
->status
= status
;
2196 ss
->changed
= changed
;
2198 /* FIXME: Should this be IDX instead of ss->slot? This
2199 depends on how client sessions will associate the reader
2200 status with their session. */
2201 snprintf (templ
, sizeof templ
, "reader_%d.status", ss
->slot
);
2202 fname
= make_filename (opt
.homedir
, templ
, NULL
);
2203 fp
= fopen (fname
, "w");
2206 fprintf (fp
, "%s\n",
2207 (status
& 1)? "USABLE":
2208 (status
& 4)? "ACTIVE":
2209 (status
& 2)? "PRESENT": "NOCARD");
2214 /* If a status script is executable, run it. */
2216 const char *args
[9], *envs
[2];
2217 char numbuf1
[30], numbuf2
[30], numbuf3
[30];
2218 char *homestr
, *envstr
;
2221 homestr
= make_filename (opt
.homedir
, NULL
);
2222 if (estream_asprintf (&envstr
, "GNUPGHOME=%s", homestr
) < 0)
2223 log_error ("out of core while building environment\n");
2229 sprintf (numbuf1
, "%d", ss
->slot
);
2230 sprintf (numbuf2
, "0x%04X", ss
->status
);
2231 sprintf (numbuf3
, "0x%04X", status
);
2232 args
[0] = "--reader-port";
2234 args
[2] = "--old-code";
2236 args
[4] = "--new-code";
2238 args
[6] = "--status";
2239 args
[7] = ((status
& 1)? "USABLE":
2240 (status
& 4)? "ACTIVE":
2241 (status
& 2)? "PRESENT": "NOCARD");
2244 fname
= make_filename (opt
.homedir
, "scd-event", NULL
);
2245 err
= gnupg_spawn_process_detached (fname
, args
, envs
);
2246 if (err
&& gpg_err_code (err
) != GPG_ERR_ENOENT
)
2247 log_error ("failed to run event handler `%s': %s\n",
2248 fname
, gpg_strerror (err
));
2255 /* Set the card removed flag for all current sessions. We
2256 will set this on any card change because a reset or
2257 SERIALNO request must be done in any case. */
2258 if (ss
->any
&& set_card_removed_flag
)
2259 update_card_removed (idx
, 1);
2263 /* Send a signal to all clients who applied for it. */
2264 send_client_notifications ();
2267 /* Check whether a disconnect is pending. */
2268 if (opt
.card_timeout
)
2270 for (sl
=session_list
; sl
; sl
= sl
->next_session
)
2271 if (!sl
->disconnect_allowed
)
2273 if (session_list
&& !sl
)
2275 /* FIXME: Use a real timeout. */
2276 /* At least one connection and all allow a disconnect. */
2277 log_info ("disconnecting card in slot %d\n", ss
->slot
);
2278 apdu_disconnect (ss
->slot
);
2285 /* This function is called by the ticker thread to check for changes
2286 of the reader stati. It updates the reader status files and if
2287 requested by the caller also send a signal to the caller. */
2289 scd_update_reader_status_file (void)
2291 if (!pth_mutex_acquire (&status_file_update_lock
, 1, NULL
))
2292 return; /* locked - give up. */
2293 update_reader_status_file (1);
2294 if (!pth_mutex_release (&status_file_update_lock
))
2295 log_error ("failed to release status_file_update lock\n");