-
-
Notifications
You must be signed in to change notification settings - Fork 109
/
winscard_clnt.c
3602 lines (3127 loc) · 105 KB
/
winscard_clnt.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* MUSCLE SmartCard Development ( https://pcsclite.apdu.fr/ )
*
* Copyright (C) 1999-2004
* David Corcoran <[email protected]>
* Copyright (C) 2003-2004
* Damien Sauveron <[email protected]>
* Copyright (C) 2005
* Martin Paljak <[email protected]>
* Copyright (C) 2002-2011
* Ludovic Rousseau <[email protected]>
* Copyright (C) 2009
* Jean-Luc Giraud <[email protected]>
*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* @defgroup API API
* @brief Handles smart card reader communications and
* forwarding requests over message queues.
*
* Here is exposed the API for client applications.
*
* \anchor differences
* @attention
* Known \ref differences with Microsoft Windows WinSCard implementation:
*
* -# SCardStatus()
* @par
* SCardStatus() returns a bit field on pcsc-lite but a enumeration on
* Windows.
* @par
* This difference may be resolved in a future version of pcsc-lite.
* The bit-fields would then only contain one bit set.
* @par
* You can have a @b portable code using:
* @code
* if (dwState & SCARD_PRESENT)
* {
* // card is present
* }
* @endcode
* -# \ref SCARD_E_UNSUPPORTED_FEATURE
* @par
* Windows may return ERROR_NOT_SUPPORTED instead of
* \ref SCARD_E_UNSUPPORTED_FEATURE
* @par
* This difference will not be corrected. pcsc-lite only uses
* SCARD_E_* error codes.
* -# \ref SCARD_E_UNSUPPORTED_FEATURE
* @par
* For historical reasons the value of \ref SCARD_E_UNSUPPORTED_FEATURE
* is \p 0x8010001F in pcsc-lite but \p 0x80100022 in Windows WinSCard.
* You should not have any problem if you always use the symbolic name.
* @par
* The value \p 0x8010001F is also used for \ref SCARD_E_UNEXPECTED on
* pcsc-lite but \ref SCARD_E_UNEXPECTED is never returned by
* pcsc-lite. So \p 0x8010001F does always mean
* \ref SCARD_E_UNSUPPORTED_FEATURE.
* @par
* Applications like rdesktop that allow a Windows application to
* talk to pcsc-lite should take care of this difference and convert
* the value between the two worlds.
* -# SCardConnect()
* @par
* If \ref SCARD_SHARE_DIRECT is used the reader is accessed in
* shared mode (like with \ref SCARD_SHARE_SHARED) and not in
* exclusive mode (like with \ref SCARD_SHARE_EXCLUSIVE) as on
* Windows.
* -# SCardConnect() & SCardReconnect()
* @par
* pdwActiveProtocol is not set to \ref SCARD_PROTOCOL_UNDEFINED if
* \ref SCARD_SHARE_DIRECT is used but the card has @b already
* negotiated its protocol.
* -# SCardReconnect()
* @par
* Any PC/SC transaction held by the process is still valid after
* SCardReconnect() returned. On Windows the PC/SC transactions are
* released and a new call to SCardBeginTransaction() must be done.
*/
#include "config.h"
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/un.h>
#include <errno.h>
#include <stddef.h>
#include <sys/time.h>
#include <pthread.h>
#include <sys/wait.h>
#include <stdbool.h>
#include "misc.h"
#include "pcscd.h"
#include "winscard.h"
#include "debuglog.h"
#include "readerfactory.h"
#include "eventhandler.h"
#include "sys_generic.h"
#include "winscard_msg.h"
#include "utils.h"
/* Display, on stderr, a trace of the WinSCard calls with arguments and
* results */
//#define DO_TRACE
/* Profile the execution time of WinSCard calls */
//#define DO_PROFILE
static bool sharing_shall_block = true;
#define COLOR_RED "\33[01;31m"
#define COLOR_GREEN "\33[32m"
#define COLOR_BLUE "\33[34m"
#define COLOR_MAGENTA "\33[35m"
#define COLOR_NORMAL "\33[0m"
#ifdef DO_TRACE
#include <stdio.h>
#include <stdarg.h>
static void trace(const char *func, const char direction, const char *fmt, ...)
{
va_list args;
fprintf(stderr, COLOR_GREEN "%c " COLOR_BLUE "[%lX] " COLOR_GREEN "%s ",
direction, pthread_self(), func);
fprintf(stderr, COLOR_MAGENTA);
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
fprintf(stderr, COLOR_NORMAL "\n");
}
#define API_TRACE_IN(...) trace(__FUNCTION__, '<', __VA_ARGS__);
#define API_TRACE_OUT(...) trace(__FUNCTION__, '>', __VA_ARGS__);
#else
#define API_TRACE_IN(...)
#define API_TRACE_OUT(...)
#endif
#ifdef DO_PROFILE
#define PROFILE_FILE "/tmp/pcsc_profile"
#include <stdio.h>
#include <sys/time.h>
/* we can profile a maximum of 5 simultaneous calls */
#define MAX_THREADS 5
pthread_t threads[MAX_THREADS];
struct timeval profile_time_start[MAX_THREADS];
FILE *profile_fd;
bool profile_tty;
#define PROFILE_START profile_start();
#define PROFILE_END(rv) profile_end(__FUNCTION__, rv);
static void profile_start(void)
{
static bool initialized = false;
pthread_t t;
int i;
if (!initialized)
{
char filename[80];
initialized = true;
sprintf(filename, "%s-%d", PROFILE_FILE, getuid());
profile_fd = fopen(filename, "a+");
if (NULL == profile_fd)
{
fprintf(stderr, COLOR_RED "Can't open %s: %s" COLOR_NORMAL "\n",
PROFILE_FILE, strerror(errno));
exit(-1);
}
fprintf(profile_fd, "\nStart a new profile\n");
if (isatty(fileno(stderr)))
profile_tty = true;
else
profile_tty = false;
}
t = pthread_self();
for (i=0; i<MAX_THREADS; i++)
if (pthread_equal(0, threads[i]))
{
threads[i] = t;
break;
}
gettimeofday(&profile_time_start[i], NULL);
} /* profile_start */
static void profile_end(const char *f, LONG rv)
{
struct timeval profile_time_end;
long d;
pthread_t t;
int i;
gettimeofday(&profile_time_end, NULL);
t = pthread_self();
for (i=0; i<MAX_THREADS; i++)
if (pthread_equal(t, threads[i]))
break;
if (i>=MAX_THREADS)
{
fprintf(stderr, COLOR_BLUE " WARNING: no start info for %s\n", f);
return;
}
d = time_sub(&profile_time_end, &profile_time_start[i]);
/* free this entry */
threads[i] = 0;
if (profile_tty)
{
if (rv != SCARD_S_SUCCESS)
fprintf(stderr,
COLOR_RED "RESULT %s " COLOR_MAGENTA "%ld "
COLOR_BLUE "0x%08lX %s" COLOR_NORMAL "\n",
f, d, rv, pcsc_stringify_error(rv));
else
fprintf(stderr, COLOR_RED "RESULT %s " COLOR_MAGENTA "%ld"
COLOR_NORMAL "\n", f, d);
}
fprintf(profile_fd, "%s %ld\n", f, d);
fflush(profile_fd);
} /* profile_end */
#else
#define PROFILE_START
#define PROFILE_END(rv)
#endif
/**
* Represents an Application Context Channel.
* A channel belongs to an Application Context (\c _psContextMap).
*/
struct _psChannelMap
{
SCARDHANDLE hCard;
LPSTR readerName;
};
typedef struct _psChannelMap CHANNEL_MAP;
static int CHANNEL_MAP_seeker(const void *el, const void *key)
{
const CHANNEL_MAP * channelMap = el;
if ((el == NULL) || (key == NULL))
{
Log3(PCSC_LOG_CRITICAL,
"CHANNEL_MAP_seeker called with NULL pointer: el=%p, key=%p",
el, key);
return 0;
}
if (channelMap->hCard == *(SCARDHANDLE *)key)
return 1;
return 0;
}
/**
* @brief Represents an Application Context on the Client side.
*
* An Application Context contains Channels (\c _psChannelMap).
*/
struct _psContextMap
{
DWORD dwClientID; /**< Client Connection ID */
SCARDCONTEXT hContext; /**< Application Context ID */
pthread_mutex_t mMutex; /**< Mutex for this context */
list_t channelMapList;
bool cancellable; /**< We are in a cancellable call */
};
/**
* @brief Represents an Application Context on the Client side.
*
* typedef of _psContextMap
*/
typedef struct _psContextMap SCONTEXTMAP;
static list_t contextMapList;
static int SCONTEXTMAP_seeker(const void *el, const void *key)
{
const SCONTEXTMAP * contextMap = el;
if ((el == NULL) || (key == NULL))
{
Log3(PCSC_LOG_CRITICAL,
"SCONTEXTMAP_seeker called with NULL pointer: el=%p, key=%p",
el, key);
return 0;
}
if (contextMap->hContext == *(SCARDCONTEXT *) key)
return 1;
return 0;
}
/**
* Make sure the initialization code is executed only once.
*/
static short isExecuted = 0;
/**
* Ensure that some functions be accessed in thread-safe mode.
* These function's names finishes with "TH".
*/
static pthread_mutex_t clientMutex = PTHREAD_MUTEX_INITIALIZER;
/**
* Area used to read status information about the readers.
*/
static READER_STATE readerStates[PCSCLITE_MAX_READERS_CONTEXTS];
/** Protocol Control Information for T=0 */
PCSC_API const SCARD_IO_REQUEST g_rgSCardT0Pci = { SCARD_PROTOCOL_T0, sizeof(SCARD_IO_REQUEST) };
/** Protocol Control Information for T=1 */
PCSC_API const SCARD_IO_REQUEST g_rgSCardT1Pci = { SCARD_PROTOCOL_T1, sizeof(SCARD_IO_REQUEST) };
/** Protocol Control Information for raw access */
PCSC_API const SCARD_IO_REQUEST g_rgSCardRawPci = { SCARD_PROTOCOL_RAW, sizeof(SCARD_IO_REQUEST) };
static LONG SCardAddContext(SCARDCONTEXT, DWORD);
static SCONTEXTMAP * SCardGetAndLockContext(SCARDCONTEXT);
static SCONTEXTMAP * SCardGetContextTH(SCARDCONTEXT);
static void SCardRemoveContext(SCARDCONTEXT);
static void SCardCleanContext(SCONTEXTMAP *);
static LONG SCardAddHandle(SCARDHANDLE, SCONTEXTMAP *, LPCSTR);
static LONG SCardGetContextChannelAndLockFromHandle(SCARDHANDLE,
/*@out@*/ SCONTEXTMAP * *, /*@out@*/ CHANNEL_MAP * *);
static LONG SCardGetContextAndChannelFromHandleTH(SCARDHANDLE,
/*@out@*/ SCONTEXTMAP * *, /*@out@*/ CHANNEL_MAP * *);
static void SCardRemoveHandle(SCARDHANDLE);
static LONG SCardGetSetAttrib(SCARDHANDLE hCard, int command, DWORD dwAttrId,
LPBYTE pbAttr, LPDWORD pcbAttrLen);
static LONG getReaderStates(SCONTEXTMAP * currentContextMap);
static LONG getReaderStatesAndRegisterForEvents(SCONTEXTMAP * currentContextMap);
static LONG unregisterFromEvents(SCONTEXTMAP * currentContextMap);
/*
* Thread safety functions
*/
/**
* @brief Locks a mutex so another thread must wait to use this
* function.
*
* Wrapper to the function pthread_mutex_lock().
*/
inline static void SCardLockThread(void)
{
pthread_mutex_lock(&clientMutex);
}
/**
* @brief Unlocks a mutex so another thread may use the client.
*
* Wrapper to the function pthread_mutex_unlock().
*/
inline static void SCardUnlockThread(void)
{
pthread_mutex_unlock(&clientMutex);
}
/**
* @brief Tell if a context index from the Application Context vector \c
* _psContextMap is valid or not.
*
* @param[in] hContext Application Context whose index will be find.
*
* @return \c true if the context exists
* @return \c false if the context does not exist
*/
static bool SCardGetContextValidity(SCARDCONTEXT hContext)
{
SCONTEXTMAP * currentContextMap;
SCardLockThread();
currentContextMap = SCardGetContextTH(hContext);
SCardUnlockThread();
return currentContextMap != NULL;
}
static LONG SCardEstablishContextTH(DWORD, LPCVOID, LPCVOID,
/*@out@*/ LPSCARDCONTEXT);
/**
* @brief Creates an Application Context to the PC/SC Resource Manager.
*
* This must be the first WinSCard function called in a PC/SC application.
* Each thread of an application shall use its own \ref SCARDCONTEXT, unless
* calling \ref SCardCancel(), which MUST be called with the same context as the
* context used to call \ref SCardGetStatusChange().
*
* @ingroup API
* @param[in] dwScope Scope of the establishment.
* This can either be a local or remote connection.
* - \ref SCARD_SCOPE_USER - Not used.
* - \ref SCARD_SCOPE_TERMINAL - Not used.
* - \ref SCARD_SCOPE_GLOBAL - Not used.
* - \ref SCARD_SCOPE_SYSTEM - Services on the local machine.
* @param[in] pvReserved1 Reserved for future use.
* @param[in] pvReserved2 Reserved for future use.
* @param[out] phContext Returned Application Context.
*
* @return Error code.
* @retval SCARD_S_SUCCESS Successful (\ref SCARD_S_SUCCESS)
* @retval SCARD_E_INVALID_PARAMETER \p phContext is null (\ref SCARD_E_INVALID_PARAMETER)
* @retval SCARD_E_INVALID_VALUE Invalid scope type passed (\ref SCARD_E_INVALID_VALUE )
* @retval SCARD_E_NO_MEMORY There is no free slot to store \p hContext (\ref SCARD_E_NO_MEMORY)
* @retval SCARD_E_NO_SERVICE The server is not running (\ref SCARD_E_NO_SERVICE)
* @retval SCARD_F_COMM_ERROR An internal communications error has been detected (\ref SCARD_F_COMM_ERROR)
* @retval SCARD_F_INTERNAL_ERROR An internal consistency check failed (\ref SCARD_F_INTERNAL_ERROR)
*
* @code
* SCARDCONTEXT hContext;
* LONG rv;
* ...
* rv = SCardEstablishContext(SCARD_SCOPE_SYSTEM, NULL, NULL, &hContext);
* @endcode
*/
LONG SCardEstablishContext(DWORD dwScope, LPCVOID pvReserved1,
LPCVOID pvReserved2, LPSCARDCONTEXT phContext)
{
LONG rv;
API_TRACE_IN("%ld, %p, %p", dwScope, pvReserved1, pvReserved2)
PROFILE_START
/* Check if the server is running */
rv = SCardCheckDaemonAvailability();
if (rv != SCARD_S_SUCCESS)
goto end;
SCardLockThread();
rv = SCardEstablishContextTH(dwScope, pvReserved1,
pvReserved2, phContext);
SCardUnlockThread();
end:
PROFILE_END(rv)
API_TRACE_OUT("%ld", *phContext)
return rv;
}
#ifdef DESTRUCTOR
DESTRUCTOR static void destructor(void)
{
list_destroy(&contextMapList);
}
#endif
/**
* @brief Creates a communication context to the PC/SC Resource
* Manager.
*
* This function should not be called directly. Instead, the thread-safe
* function SCardEstablishContext() should be called.
*
* @param[in] dwScope Scope of the establishment.
* This can either be a local or remote connection.
* - \ref SCARD_SCOPE_USER - Not used.
* - \ref SCARD_SCOPE_TERMINAL - Not used.
* - \ref SCARD_SCOPE_GLOBAL - Not used.
* - \ref SCARD_SCOPE_SYSTEM - Services on the local machine.
* @param[in] pvReserved1 Reserved for future use. Can be used for remote connection.
* @param[in] pvReserved2 Reserved for future use.
* @param[out] phContext Returned reference to this connection.
*
* @return Connection status.
* @retval SCARD_S_SUCCESS Successful (\ref SCARD_S_SUCCESS)
* @retval SCARD_E_INVALID_PARAMETER \p phContext is null. (\ref SCARD_E_INVALID_PARAMETER)
* @retval SCARD_E_INVALID_VALUE Invalid scope type passed (\ref SCARD_E_INVALID_VALUE)
* @retval SCARD_E_NO_MEMORY There is no free slot to store \p hContext (\ref SCARD_E_NO_MEMORY)
* @retval SCARD_E_NO_SERVICE The server is not running (\ref SCARD_E_NO_SERVICE)
* @retval SCARD_F_COMM_ERROR An internal communications error has been detected (\ref SCARD_F_COMM_ERROR)
* @retval SCARD_F_INTERNAL_ERROR An internal consistency check failed (\ref SCARD_F_INTERNAL_ERROR)
* @retval SCARD_W_SECURITY_VIOLATION Access was denied by the daemon (Polkit issue?). (\ref SCARD_W_SECURITY_VIOLATION)
*/
static LONG SCardEstablishContextTH(DWORD dwScope,
/*@unused@*/ LPCVOID pvReserved1,
/*@unused@*/ LPCVOID pvReserved2, LPSCARDCONTEXT phContext)
{
LONG rv;
struct establish_struct scEstablishStruct;
uint32_t dwClientID = 0;
(void)pvReserved1;
(void)pvReserved2;
if (phContext == NULL)
return SCARD_E_INVALID_PARAMETER;
else
*phContext = 0;
/*
* Do this only once:
* - Initialize context list.
*/
if (isExecuted == 0)
{
int lrv;
/* NOTE: The list will be freed only if DESTRUCTOR is defined.
* Applications which load and unload the library may leak
* the list's internal structures. */
lrv = list_init(&contextMapList);
if (lrv < 0)
{
Log2(PCSC_LOG_CRITICAL, "list_init failed with return value: %d",
lrv);
return SCARD_E_NO_MEMORY;
}
lrv = list_attributes_seeker(&contextMapList,
SCONTEXTMAP_seeker);
if (lrv <0)
{
Log2(PCSC_LOG_CRITICAL,
"list_attributes_seeker failed with return value: %d", lrv);
list_destroy(&contextMapList);
return SCARD_E_NO_MEMORY;
}
if (getenv("PCSCLITE_NO_BLOCKING"))
{
Log1(PCSC_LOG_INFO, "Disable shared blocking");
sharing_shall_block = false;
}
isExecuted = 1;
}
/* Establishes a connection to the server */
if (ClientSetupSession(&dwClientID) != 0)
{
return SCARD_E_NO_SERVICE;
}
{ /* exchange client/server protocol versions */
struct version_struct veStr;
veStr.major = PROTOCOL_VERSION_MAJOR;
veStr.minor = PROTOCOL_VERSION_MINOR;
veStr.rv = SCARD_S_SUCCESS;
rv = MessageSendWithHeader(CMD_VERSION, dwClientID, sizeof(veStr),
&veStr);
if (rv != SCARD_S_SUCCESS)
goto cleanup;
/* Read a message from the server */
rv = MessageReceive(&veStr, sizeof(veStr), dwClientID);
if (rv != SCARD_S_SUCCESS)
{
Log1(PCSC_LOG_CRITICAL,
"Your pcscd is too old and does not support CMD_VERSION");
goto cleanup;
}
Log3(PCSC_LOG_INFO, "Server is protocol version %d:%d",
veStr.major, veStr.minor);
if (veStr.rv != SCARD_S_SUCCESS)
{
rv = veStr.rv;
goto cleanup;
}
}
again:
/*
* Try to establish an Application Context with the server
*/
scEstablishStruct.dwScope = dwScope;
scEstablishStruct.hContext = 0;
scEstablishStruct.rv = SCARD_S_SUCCESS;
rv = MessageSendWithHeader(SCARD_ESTABLISH_CONTEXT, dwClientID,
sizeof(scEstablishStruct), (void *) &scEstablishStruct);
if (rv != SCARD_S_SUCCESS)
goto cleanup;
/*
* Read the response from the server
*/
rv = MessageReceive(&scEstablishStruct, sizeof(scEstablishStruct),
dwClientID);
if (rv != SCARD_S_SUCCESS)
goto cleanup;
if (scEstablishStruct.rv != SCARD_S_SUCCESS)
{
rv = scEstablishStruct.rv;
goto cleanup;
}
/* check we do not reuse an existing hContext */
if (NULL != SCardGetContextTH(scEstablishStruct.hContext))
/* we do not need to release the allocated context since
* SCardReleaseContext() does nothing on the server side */
goto again;
*phContext = scEstablishStruct.hContext;
/*
* Allocate the new hContext - if allocator full return an error
*/
rv = SCardAddContext(*phContext, dwClientID);
return rv;
cleanup:
ClientCloseSession(dwClientID);
return rv;
}
/**
* @brief Destroys a communication context to the PC/SC Resource
* Manager. This must be the last function called in a PC/SC application.
*
* @ingroup API
* @param[in] hContext Connection context to be closed.
*
* @return Connection status.
* @retval SCARD_S_SUCCESS Successful (\ref SCARD_S_SUCCESS)
* @retval SCARD_E_NO_SERVICE The server is not running (\ref SCARD_E_NO_SERVICE)
* @retval SCARD_E_INVALID_HANDLE Invalid \p hContext handle (\ref SCARD_E_INVALID_HANDLE)
* @retval SCARD_F_COMM_ERROR An internal communications error has been detected (\ref SCARD_F_COMM_ERROR)
*
* @code
* SCARDCONTEXT hContext;
* LONG rv;
* ...
* rv = SCardEstablishContext(SCARD_SCOPE_SYSTEM, NULL, NULL, &hContext);
* rv = SCardReleaseContext(hContext);
* @endcode
*/
LONG SCardReleaseContext(SCARDCONTEXT hContext)
{
LONG rv;
struct release_struct scReleaseStruct;
SCONTEXTMAP * currentContextMap;
API_TRACE_IN("%ld", hContext)
PROFILE_START
/*
* Make sure this context has been opened
* and get currentContextMap
*/
currentContextMap = SCardGetAndLockContext(hContext);
if (NULL == currentContextMap)
{
rv = SCARD_E_INVALID_HANDLE;
goto error;
}
scReleaseStruct.hContext = hContext;
scReleaseStruct.rv = SCARD_S_SUCCESS;
rv = MessageSendWithHeader(SCARD_RELEASE_CONTEXT,
currentContextMap->dwClientID,
sizeof(scReleaseStruct), (void *) &scReleaseStruct);
if (rv != SCARD_S_SUCCESS)
goto end;
/*
* Read a message from the server
*/
rv = MessageReceive(&scReleaseStruct, sizeof(scReleaseStruct),
currentContextMap->dwClientID);
if (rv != SCARD_S_SUCCESS)
goto end;
rv = scReleaseStruct.rv;
end:
(void)pthread_mutex_unlock(¤tContextMap->mMutex);
/*
* Remove the local context from the stack
*/
SCardLockThread();
SCardRemoveContext(hContext);
SCardUnlockThread();
error:
PROFILE_END(rv)
API_TRACE_OUT("")
return rv;
}
/**
* @brief Establishes a connection to the reader specified in \p * szReader.
*
* @ingroup API
* @param[in] hContext Connection context to the PC/SC Resource Manager.
* @param[in] szReader Reader name to connect to.
* @param[in] dwShareMode Mode of connection type: exclusive or shared.
* - \ref SCARD_SHARE_SHARED - This application will allow others to share
* the reader.
* - \ref SCARD_SHARE_EXCLUSIVE - This application will NOT allow others to
* share the reader.
* - \ref SCARD_SHARE_DIRECT - Direct control of the reader, even without a
* card. \ref SCARD_SHARE_DIRECT can be used before using SCardControl() to
* send control commands to the reader even if a card is not present in the
* reader. Contrary to Windows winscard behavior, the reader is accessed in
* shared mode and not exclusive mode.
* @param[in] dwPreferredProtocols Desired protocol use.
* - 0 - valid only if dwShareMode is SCARD_SHARE_DIRECT
* - \ref SCARD_PROTOCOL_T0 - Use the T=0 protocol.
* - \ref SCARD_PROTOCOL_T1 - Use the T=1 protocol.
* - \ref SCARD_PROTOCOL_RAW - Use with memory type cards.
* \p dwPreferredProtocols is a bit mask of acceptable protocols for the
* connection. You can use (\ref SCARD_PROTOCOL_T0 | \ref SCARD_PROTOCOL_T1) if
* you do not have a preferred protocol.
* @param[out] phCard Handle to this connection.
* @param[out] pdwActiveProtocol Established protocol to this connection.
*
* @return Error code.
* @retval SCARD_S_SUCCESS Successful (\ref SCARD_S_SUCCESS)
* @retval SCARD_E_INVALID_HANDLE Invalid \p hContext handle (\ref SCARD_E_INVALID_HANDLE)
* @retval SCARD_E_INVALID_PARAMETER \p phCard or \p pdwActiveProtocol is NULL (\ref SCARD_E_INVALID_PARAMETER)
* @retval SCARD_E_INVALID_VALUE Invalid sharing mode, requested protocol, or reader name (\ref SCARD_E_INVALID_VALUE)
* @retval SCARD_E_NO_SERVICE The server is not running (\ref SCARD_E_NO_SERVICE)
* @retval SCARD_E_NO_SMARTCARD No smart card present (\ref SCARD_E_NO_SMARTCARD)
* @retval SCARD_E_PROTO_MISMATCH Requested protocol is unknown (\ref SCARD_E_PROTO_MISMATCH)
* @retval SCARD_E_READER_UNAVAILABLE Could not power up the reader or card (\ref SCARD_E_READER_UNAVAILABLE)
* @retval SCARD_E_SHARING_VIOLATION Someone else has exclusive rights (\ref SCARD_E_SHARING_VIOLATION)
* @retval SCARD_E_UNKNOWN_READER \p szReader is NULL (\ref SCARD_E_UNKNOWN_READER)
* @retval SCARD_E_UNSUPPORTED_FEATURE Protocol not supported (\ref SCARD_E_UNSUPPORTED_FEATURE)
* @retval SCARD_F_COMM_ERROR An internal communications error has been detected (\ref SCARD_F_COMM_ERROR)
* @retval SCARD_F_INTERNAL_ERROR An internal consistency check failed (\ref SCARD_F_INTERNAL_ERROR)
* @retval SCARD_W_UNPOWERED_CARD Card is not powered (\ref SCARD_W_UNPOWERED_CARD)
* @retval SCARD_W_UNRESPONSIVE_CARD Card is mute (\ref SCARD_W_UNRESPONSIVE_CARD)
*
* @code
* SCARDCONTEXT hContext;
* SCARDHANDLE hCard;
* DWORD dwActiveProtocol;
* LONG rv;
* ...
* rv = SCardEstablishContext(SCARD_SCOPE_SYSTEM, NULL, NULL, &hContext);
* rv = SCardConnect(hContext, "Reader X", SCARD_SHARE_SHARED,
* SCARD_PROTOCOL_T0, &hCard, &dwActiveProtocol);
* @endcode
*/
LONG SCardConnect(SCARDCONTEXT hContext, LPCSTR szReader,
DWORD dwShareMode, DWORD dwPreferredProtocols, LPSCARDHANDLE phCard,
LPDWORD pdwActiveProtocol)
{
LONG rv;
struct connect_struct scConnectStruct;
SCONTEXTMAP * currentContextMap;
PROFILE_START
API_TRACE_IN("%ld %s %ld %ld", hContext, szReader, dwShareMode, dwPreferredProtocols)
/*
* Check for NULL parameters
*/
if (phCard == NULL || pdwActiveProtocol == NULL)
return SCARD_E_INVALID_PARAMETER;
else
*phCard = 0;
if (szReader == NULL)
return SCARD_E_UNKNOWN_READER;
/*
* Check for uninitialized strings
*/
if (strlen(szReader) > MAX_READERNAME)
return SCARD_E_INVALID_VALUE;
/*
* Make sure this context has been opened
*/
currentContextMap = SCardGetAndLockContext(hContext);
if (NULL == currentContextMap)
return SCARD_E_INVALID_HANDLE;
memset(scConnectStruct.szReader, 0, sizeof scConnectStruct.szReader);
strncpy(scConnectStruct.szReader, szReader, sizeof scConnectStruct.szReader);
scConnectStruct.szReader[sizeof scConnectStruct.szReader -1] = '\0';
scConnectStruct.hContext = hContext;
scConnectStruct.dwShareMode = dwShareMode;
scConnectStruct.dwPreferredProtocols = dwPreferredProtocols;
scConnectStruct.hCard = 0;
scConnectStruct.dwActiveProtocol = 0;
scConnectStruct.rv = SCARD_S_SUCCESS;
rv = MessageSendWithHeader(SCARD_CONNECT, currentContextMap->dwClientID,
sizeof(scConnectStruct), (void *) &scConnectStruct);
if (rv != SCARD_S_SUCCESS)
goto end;
/*
* Read a message from the server
*/
rv = MessageReceive(&scConnectStruct, sizeof(scConnectStruct),
currentContextMap->dwClientID);
if (rv != SCARD_S_SUCCESS)
goto end;
*phCard = scConnectStruct.hCard;
*pdwActiveProtocol = scConnectStruct.dwActiveProtocol;
if (scConnectStruct.rv == SCARD_S_SUCCESS)
{
/*
* Keep track of the handle locally
*/
rv = SCardAddHandle(*phCard, currentContextMap, szReader);
}
else
rv = scConnectStruct.rv;
end:
(void)pthread_mutex_unlock(¤tContextMap->mMutex);
PROFILE_END(rv)
API_TRACE_OUT("%d", *pdwActiveProtocol)
return rv;
}
/**
* @brief Reestablishes a connection to a reader that was
* previously connected to using SCardConnect().
*
* In a multi application environment it is possible for an application to
* reset the card in shared mode. When this occurs any other application trying
* to access certain commands will be returned the value \ref
* SCARD_W_RESET_CARD. When this occurs SCardReconnect() must be called in
* order to acknowledge that the card was reset and allow it to change its
* state accordingly.
*
* @ingroup API
* @param[in] hCard Handle to a previous call to connect.
* @param[in] dwShareMode Mode of connection type: exclusive/shared.
* - \ref SCARD_SHARE_SHARED - This application will allow others to share
* the reader.
* - \ref SCARD_SHARE_EXCLUSIVE - This application will NOT allow others to
* share the reader.
* @param[in] dwPreferredProtocols Desired protocol use.
* - \ref SCARD_PROTOCOL_T0 - Use the T=0 protocol.
* - \ref SCARD_PROTOCOL_T1 - Use the T=1 protocol.
* - \ref SCARD_PROTOCOL_RAW - Use with memory type cards.
* \p dwPreferredProtocols is a bit mask of acceptable protocols for
* the connection. You can use (SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1)
* if you do not have a preferred protocol.
* @param[in] dwInitialization Desired action taken on the card/reader.
* - \ref SCARD_LEAVE_CARD - Do nothing.
* - \ref SCARD_RESET_CARD - Reset the card (warm reset).
* - \ref SCARD_UNPOWER_CARD - Power down the card (cold reset).
* - \ref SCARD_EJECT_CARD - Eject the card.
* @param[out] pdwActiveProtocol Established protocol to this connection.
*
* @return Error code.
* @retval SCARD_S_SUCCESS Successful (\ref SCARD_S_SUCCESS)
* @retval SCARD_E_INVALID_HANDLE Invalid \p hCard handle (\ref SCARD_E_INVALID_HANDLE)
* @retval SCARD_E_INVALID_PARAMETER \p phContext is null. (\ref SCARD_E_INVALID_PARAMETER)
* @retval SCARD_E_INVALID_VALUE Invalid sharing mode, requested protocol, or reader name (\ref SCARD_E_INVALID_VALUE)
* @retval SCARD_E_NO_SERVICE The server is not running (\ref SCARD_E_NO_SERVICE)
* @retval SCARD_E_NO_SMARTCARD No smart card present (\ref SCARD_E_NO_SMARTCARD)
* @retval SCARD_E_PROTO_MISMATCH Requested protocol is unknown (\ref SCARD_E_PROTO_MISMATCH)
* @retval SCARD_E_READER_UNAVAILABLE The reader has been removed (\ref SCARD_E_READER_UNAVAILABLE)
* @retval SCARD_E_SHARING_VIOLATION Someone else has exclusive rights (\ref SCARD_E_SHARING_VIOLATION)
* @retval SCARD_E_UNSUPPORTED_FEATURE Protocol not supported (\ref SCARD_E_UNSUPPORTED_FEATURE)
* @retval SCARD_F_COMM_ERROR An internal communications error has been detected (\ref SCARD_F_COMM_ERROR)
* @retval SCARD_F_INTERNAL_ERROR An internal consistency check failed (\ref SCARD_F_INTERNAL_ERROR)
* @retval SCARD_W_REMOVED_CARD The smart card has been removed (\ref SCARD_W_REMOVED_CARD)
* @retval SCARD_W_UNRESPONSIVE_CARD Card is mute (\ref SCARD_W_UNRESPONSIVE_CARD)
*
* @code
* SCARDCONTEXT hContext;
* SCARDHANDLE hCard;
* DWORD dwActiveProtocol, dwSendLength, dwRecvLength;
* LONG rv;
* BYTE pbRecvBuffer[10];
* BYTE pbSendBuffer[] = {0xC0, 0xA4, 0x00, 0x00, 0x02, 0x3F, 0x00};
* ...
* rv = SCardEstablishContext(SCARD_SCOPE_SYSTEM, NULL, NULL, &hContext);
* rv = SCardConnect(hContext, "Reader X", SCARD_SHARE_SHARED,
* SCARD_PROTOCOL_T0, &hCard, &dwActiveProtocol);
* ...
* dwSendLength = sizeof(pbSendBuffer);
* dwRecvLength = sizeof(pbRecvBuffer);
* rv = SCardTransmit(hCard, SCARD_PCI_T0, pbSendBuffer, dwSendLength,
* &pioRecvPci, pbRecvBuffer, &dwRecvLength);
* / * Card has been reset by another application * /
* if (rv == SCARD_W_RESET_CARD)
* {
* rv = SCardReconnect(hCard, SCARD_SHARE_SHARED, SCARD_PROTOCOL_T0,
* SCARD_RESET_CARD, &dwActiveProtocol);
* }
* @endcode
*/
LONG SCardReconnect(SCARDHANDLE hCard, DWORD dwShareMode,
DWORD dwPreferredProtocols, DWORD dwInitialization,
LPDWORD pdwActiveProtocol)
{
LONG rv;
struct reconnect_struct scReconnectStruct;
SCONTEXTMAP * currentContextMap;
CHANNEL_MAP * pChannelMap;
PROFILE_START
API_TRACE_IN("%ld %ld %ld", hCard, dwShareMode, dwPreferredProtocols)
if (pdwActiveProtocol == NULL)
return SCARD_E_INVALID_PARAMETER;
/* Retry loop for blocking behaviour */
retry:
/*
* Make sure this handle has been opened
*/
rv = SCardGetContextChannelAndLockFromHandle(hCard, ¤tContextMap,
&pChannelMap);
if (rv == -1)
return SCARD_E_INVALID_HANDLE;
scReconnectStruct.hCard = hCard;
scReconnectStruct.dwShareMode = dwShareMode;
scReconnectStruct.dwPreferredProtocols = dwPreferredProtocols;
scReconnectStruct.dwInitialization = dwInitialization;
scReconnectStruct.dwActiveProtocol = *pdwActiveProtocol;
scReconnectStruct.rv = SCARD_S_SUCCESS;
rv = MessageSendWithHeader(SCARD_RECONNECT, currentContextMap->dwClientID,
sizeof(scReconnectStruct), (void *) &scReconnectStruct);
if (rv != SCARD_S_SUCCESS)
goto end;
/*
* Read a message from the server
*/
rv = MessageReceive(&scReconnectStruct, sizeof(scReconnectStruct),
currentContextMap->dwClientID);