summaryrefslogtreecommitdiffstats
path: root/sesman/chansrv/pcsc/xrdp_pcsc.c
blob: 43a95b5f7b0860e6e47177ed925b0a0c21459a07 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/stat.h>

#define PCSC_API

typedef unsigned char BYTE;
typedef BYTE *LPBYTE;
typedef unsigned int LONG;
typedef unsigned int DWORD;
typedef DWORD *LPDWORD;
typedef const void *LPCVOID;
typedef const char *LPCSTR;
typedef char *LPSTR;
typedef void *LPVOID;
typedef const BYTE *LPCBYTE;

typedef LONG SCARDCONTEXT;
typedef SCARDCONTEXT *LPSCARDCONTEXT;

typedef LONG SCARDHANDLE;
typedef SCARDHANDLE *LPSCARDHANDLE;

#define MAX_ATR_SIZE 33

typedef struct _SCARD_READERSTATE
{
    const char *szReader;
    void *pvUserData;
    DWORD dwCurrentState;
    DWORD dwEventState;
    DWORD cbAtr;
    unsigned char rgbAtr[MAX_ATR_SIZE];
} SCARD_READERSTATE, *LPSCARD_READERSTATE;

typedef struct _SCARD_IO_REQUEST
{
    unsigned long dwProtocol;
    unsigned long cbPciLength;
} SCARD_IO_REQUEST, *PSCARD_IO_REQUEST, *LPSCARD_IO_REQUEST;

#define SCARD_PROTOCOL_T0       0x0001 /**< T=0 active protocol. */
#define SCARD_PROTOCOL_T1       0x0002 /**< T=1 active protocol. */
#define SCARD_PROTOCOL_RAW      0x0004 /**< Raw active protocol. */

PCSC_API SCARD_IO_REQUEST g_rgSCardRawPci = { SCARD_PROTOCOL_T0,  8 };
PCSC_API SCARD_IO_REQUEST g_rgSCardT1Pci  = { SCARD_PROTOCOL_T1,  8 };
PCSC_API SCARD_IO_REQUEST g_rgSCardT0Pci  = { SCARD_PROTOCOL_RAW, 8 };

#define LLOG_LEVEL 5
#define LLOGLN(_level, _args) \
  do { if (_level < LLOG_LEVEL) { printf _args ; printf("\n"); } } while (0)

#define SCARD_ESTABLISH_CONTEXT  0x01
#define SCARD_RELEASE_CONTEXT    0x02
#define SCARD_LIST_READERS       0x03
#define SCARD_CONNECT            0x04
#define SCARD_RECONNECT          0x05
#define SCARD_DISCONNECT         0x06
#define SCARD_BEGIN_TRANSACTION  0x07
#define SCARD_END_TRANSACTION    0x08
#define SCARD_TRANSMIT           0x09
#define SCARD_CONTROL            0x0A
#define SCARD_STATUS             0x0B
#define SCARD_GET_STATUS_CHANGE  0x0C
#define SCARD_CANCEL             0x0D
#define SCARD_CANCEL_TRANSACTION 0x0E
#define SCARD_GET_ATTRIB         0x0F
#define SCARD_SET_ATTRIB         0x10

#define SCARD_S_SUCCESS 0x00000000
#define SCARD_F_INTERNAL_ERROR ((LONG)0x80100001)

#define SET_UINT32(_data, _offset, _val) do { \
  (((BYTE*)(_data)) + (_offset))[0] = ((_val) >> 0)  & 0xff; \
  (((BYTE*)(_data)) + (_offset))[1] = ((_val) >> 8)  & 0xff; \
  (((BYTE*)(_data)) + (_offset))[2] = ((_val) >> 16) & 0xff; \
  (((BYTE*)(_data)) + (_offset))[3] = ((_val) >> 24) & 0xff; } while (0)

#define GET_UINT32(_data, _offset) \
  ((((BYTE*)(_data)) + (_offset))[0] << 0)  | \
  ((((BYTE*)(_data)) + (_offset))[1] << 8)  | \
  ((((BYTE*)(_data)) + (_offset))[2] << 16) | \
  ((((BYTE*)(_data)) + (_offset))[3] << 24)

#define LMIN(_val1, _val2) (_val1) < (_val2) ? (_val1) : (_val2)
#define LMAX(_val1, _val2) (_val1) > (_val2) ? (_val1) : (_val2)

static int g_sck = -1; /* unix domain socket */

static pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER;

/* for pcsc_stringify_error */
static char g_error_str[512];

/*****************************************************************************/
static int
get_display_num_from_display(const char *display_text)
{
    int rv;
    int index;
    int mode;
    int host_index;
    int disp_index;
    int scre_index;
    char host[256];
    char disp[256];
    char scre[256];

    memset(host, 0, 256);
    memset(disp, 0, 256);
    memset(scre, 0, 256);

    index = 0;
    host_index = 0;
    disp_index = 0;
    scre_index = 0;
    mode = 0;

    while (display_text[index] != 0)
    {
        if (display_text[index] == ':')
        {
            mode = 1;
        }
        else if (display_text[index] == '.')
        {
            mode = 2;
        }
        else if (mode == 0)
        {
            host[host_index] = display_text[index];
            host_index++;
        }
        else if (mode == 1)
        {
            disp[disp_index] = display_text[index];
            disp_index++;
        }
        else if (mode == 2)
        {
            scre[scre_index] = display_text[index];
            scre_index++;
        }
        index++;
    }
    host[host_index] = 0;
    disp[disp_index] = 0;
    scre[scre_index] = 0;
    LLOGLN(0, ("get_display_num_from_display: host [%s] disp [%s] scre [%s]",
           host, disp, scre));
    rv = atoi(disp);
    return rv;
}

/*****************************************************************************/
static int
connect_to_chansrv(void)
{
    int bytes;
    int dis;
    int error;
    char *xrdp_session;
    char *xrdp_display;
    char *home_str;
    struct sockaddr_un saddr;
    struct sockaddr *psaddr;

    if (g_sck != -1)
    {
        /* already connected */
        return 0;
    }
    xrdp_session = getenv("XRDP_SESSION");
    if (xrdp_session == NULL)
    {
        /* XRDP_SESSION must be set */
        LLOGLN(0, ("connect_to_chansrv: error, not xrdp session"));
        return 1;
    }
    xrdp_display = getenv("DISPLAY");
    if (xrdp_display == NULL)
    {
        /* DISPLAY must be set */
        LLOGLN(0, ("connect_to_chansrv: error, display not set"));
        return 1;
    }
    home_str = getenv("HOME");
    if (home_str == NULL)
    {
        /* HOME must be set */
        LLOGLN(0, ("connect_to_chansrv: error, home not set"));
        return 1;
    }
    dis = get_display_num_from_display(xrdp_display);
    if (dis < 10)
    {
        /* DISPLAY must be > 9 */
        LLOGLN(0, ("connect_to_chansrv: error, display not > 9 %d", dis));
        return 1;
    }
    g_sck = socket(PF_LOCAL, SOCK_STREAM, 0);
    if (g_sck == -1)
    {
        LLOGLN(0, ("connect_to_chansrv: error, socket failed"));
        return 1;
    }
    memset(&saddr, 0, sizeof(struct sockaddr_un));
    saddr.sun_family = AF_UNIX;
    bytes = sizeof(saddr.sun_path);
    snprintf(saddr.sun_path, bytes, "%s/.pcsc%d/pcscd.comm", home_str, dis);
    saddr.sun_path[bytes - 1] = 0;
    LLOGLN(0, ("connect_to_chansrv: connecting to %s", saddr.sun_path));
    psaddr = (struct sockaddr *) &saddr;
    bytes = sizeof(struct sockaddr_un);
    error = connect(g_sck, psaddr, bytes);
    if (error == 0)
    {
    }
    else
    {
        perror("connect_to_chansrv");
        close(g_sck);
        g_sck = -1;
        LLOGLN(0, ("connect_to_chansrv: error, open %s", saddr.sun_path));
        return 1;
    }
    return 0;
}

/*****************************************************************************/
static int
send_message(int code, char *data, int bytes)
{
    char header[8];

    SET_UINT32(header, 0, bytes);
    SET_UINT32(header, 4, code);
    if (send(g_sck, header, 8, 0) != 8)
    {
        return 1;
    }
    if (send(g_sck, data, bytes, 0) != bytes)
    {
        return 1;
    }
    return 0;
}

/*****************************************************************************/
static int
get_message(int *code, char *data, int *bytes)
{
    char header[8];
    int max_bytes;

    if (recv(g_sck, header, 8, 0) != 8)
    {
        return 1;
    }
    max_bytes = *bytes;
    *bytes = GET_UINT32(header, 0);
    *code = GET_UINT32(header, 4);
    if (*bytes > max_bytes)
    {
        return 1;
    }
    if (recv(g_sck, data, *bytes, 0) != *bytes)
    {
        return 1;
    }
    return 0;
}

/*****************************************************************************/
PCSC_API LONG
SCardEstablishContext(DWORD dwScope, LPCVOID pvReserved1, LPCVOID pvReserved2,
                      LPSCARDCONTEXT phContext)
{
    char msg[256];
    DWORD context;
    int code;
    int bytes;
    int status;

    LLOGLN(10, ("SCardEstablishContext:"));
    if (g_sck == -1)
    {
        if (connect_to_chansrv() != 0)
        {
            LLOGLN(0, ("SCardEstablishContext: error, can not connect "
                   "to chansrv"));
            return SCARD_F_INTERNAL_ERROR;
        }
    }
    pthread_mutex_lock(&g_mutex);
    SET_UINT32(msg, 0, dwScope);
    if (send_message(SCARD_ESTABLISH_CONTEXT, msg, 4) != 0)
    {
        LLOGLN(0, ("SCardEstablishContext: error, send_message"));
        pthread_mutex_unlock(&g_mutex);
        return SCARD_F_INTERNAL_ERROR;
    }
    bytes = 256;
    if (get_message(&code, msg, &bytes) != 0)
    {
        LLOGLN(0, ("SCardEstablishContext: error, get_message"));
        pthread_mutex_unlock(&g_mutex);
        return SCARD_F_INTERNAL_ERROR;
    }
    if ((code != SCARD_ESTABLISH_CONTEXT) || (bytes != 8))
    {
        LLOGLN(0, ("SCardEstablishContext: error, bad code"));
        pthread_mutex_unlock(&g_mutex);
        return SCARD_F_INTERNAL_ERROR;
    }
    pthread_mutex_unlock(&g_mutex);
    context = GET_UINT32(msg, 0);
    status = GET_UINT32(msg, 4);
    LLOGLN(10, ("SCardEstablishContext: got context 0x%8.8x", context));
    *phContext = context;
    return status;
}

/*****************************************************************************/
PCSC_API LONG
SCardReleaseContext(SCARDCONTEXT hContext)
{
    char msg[256];
    int code;
    int bytes;
    int status;

    LLOGLN(10, ("SCardReleaseContext:"));
    if (g_sck == -1)
    {
        LLOGLN(0, ("SCardReleaseContext: error, not connected"));
        return SCARD_F_INTERNAL_ERROR;
    }
    pthread_mutex_lock(&g_mutex);
    SET_UINT32(msg, 0, hContext);
    if (send_message(SCARD_RELEASE_CONTEXT, msg, 4) != 0)
    {
        LLOGLN(0, ("SCardReleaseContext: error, send_message"));
        pthread_mutex_unlock(&g_mutex);
        return SCARD_F_INTERNAL_ERROR;
    }
    bytes = 256;
    if (get_message(&code, msg, &bytes) != 0)
    {
        LLOGLN(0, ("SCardReleaseContext: error, get_message"));
        pthread_mutex_unlock(&g_mutex);
        return SCARD_F_INTERNAL_ERROR;
    }
    if ((code != SCARD_RELEASE_CONTEXT) || (bytes != 4))
    {
        LLOGLN(0, ("SCardReleaseContext: error, bad code"));
        pthread_mutex_unlock(&g_mutex);
        return SCARD_F_INTERNAL_ERROR;
    }
    pthread_mutex_unlock(&g_mutex);
    status = GET_UINT32(msg, 0);
    LLOGLN(10, ("SCardReleaseContext: got status 0x%8.8x", status));
    return status;
}

/*****************************************************************************/
PCSC_API LONG
SCardIsValidContext(SCARDCONTEXT hContext)
{
    LLOGLN(10, ("SCardIsValidContext:"));
    if (g_sck == -1)
    {
        LLOGLN(0, ("SCardIsValidContext: error, not connected"));
        return SCARD_F_INTERNAL_ERROR;
    }
    pthread_mutex_lock(&g_mutex);
    pthread_mutex_unlock(&g_mutex);
    return SCARD_S_SUCCESS;
}

/*****************************************************************************/
PCSC_API LONG
SCardConnect(SCARDCONTEXT hContext, LPCSTR szReader, DWORD dwShareMode,
             DWORD dwPreferredProtocols, LPSCARDHANDLE phCard,
             LPDWORD pdwActiveProtocol)
{
    char msg[256];
    int code;
    int bytes;
    int status;
    int offset;

    LLOGLN(10, ("SCardConnect:"));
    LLOGLN(10, ("SCardConnect: hContext %p szReader %s dwShareMode %d "
           "dwPreferredProtocols %d",
           (void*)hContext, szReader, dwShareMode, dwPreferredProtocols));
    if (g_sck == -1)
    {
        LLOGLN(0, ("SCardConnect: error, not connected"));
        return SCARD_F_INTERNAL_ERROR;
    }
    offset = 0;
    SET_UINT32(msg, offset, hContext);
    offset += 4;
    bytes = strlen(szReader);
    if (bytes > 99)
    {
        LLOGLN(0, ("SCardConnect: error, name too long"));
        return SCARD_F_INTERNAL_ERROR;
    }
    memcpy(msg + offset, szReader, bytes);
    memset(msg + offset + bytes, 0, 100 - bytes);
    offset += 100;
    SET_UINT32(msg, offset, dwShareMode);
    offset += 4;
    SET_UINT32(msg, offset, dwPreferredProtocols);
    offset += 4;
    pthread_mutex_lock(&g_mutex);
    if (send_message(SCARD_CONNECT, msg, offset) != 0)
    {
        LLOGLN(0, ("SCardConnect: error, send_message"));
        pthread_mutex_unlock(&g_mutex);
        return SCARD_F_INTERNAL_ERROR;
    }
    bytes = 256;
    if (get_message(&code, msg, &bytes) != 0)
    {
        LLOGLN(0, ("SCardConnect: error, get_message"));
        pthread_mutex_unlock(&g_mutex);
        return SCARD_F_INTERNAL_ERROR;
    }
    if (code != SCARD_CONNECT)
    {
        LLOGLN(0, ("SCardConnect: error, bad code"));
        pthread_mutex_unlock(&g_mutex);
        return SCARD_F_INTERNAL_ERROR;
    }
    pthread_mutex_unlock(&g_mutex);
    *phCard = GET_UINT32(msg, 0);
    *pdwActiveProtocol = GET_UINT32(msg, 4);
    status = GET_UINT32(msg, 8);
    LLOGLN(10, ("SCardReleaseContext: got status 0x%8.8x", status));
    return status;
}

/*****************************************************************************/
PCSC_API LONG
SCardReconnect(SCARDHANDLE hCard, DWORD dwShareMode,
               DWORD dwPreferredProtocols, DWORD dwInitialization,
               LPDWORD pdwActiveProtocol)
{
    LLOGLN(0, ("SCardReconnect:"));
    if (g_sck == -1)
    {
        LLOGLN(0, ("SCardReconnect: error, not connected"));
        return SCARD_F_INTERNAL_ERROR;
    }
    pthread_mutex_lock(&g_mutex);
    pthread_mutex_unlock(&g_mutex);
    return SCARD_S_SUCCESS;
}

/*****************************************************************************/
PCSC_API LONG
SCardDisconnect(SCARDHANDLE hCard, DWORD dwDisposition)
{
    char msg[256];
    int code;
    int bytes;
    int status;

    LLOGLN(10, ("SCardDisconnect:"));
    if (g_sck == -1)
    {
        LLOGLN(0, ("SCardDisconnect: error, not connected"));
        return SCARD_F_INTERNAL_ERROR;
    }
    pthread_mutex_lock(&g_mutex);
    SET_UINT32(msg, 0, hCard);
    SET_UINT32(msg, 4, dwDisposition);
    if (send_message(SCARD_DISCONNECT, msg, 8) != 0)
    {
        LLOGLN(0, ("SCardDisconnect: error, send_message"));
        pthread_mutex_unlock(&g_mutex);
        return SCARD_F_INTERNAL_ERROR;
    }
    bytes = 256;
    if (get_message(&code, msg, &bytes) != 0)
    {
        LLOGLN(0, ("SCardDisconnect: error, get_message"));
        pthread_mutex_unlock(&g_mutex);
        return SCARD_F_INTERNAL_ERROR;
    }
    if ((code != SCARD_DISCONNECT) || (bytes != 4))
    {
        LLOGLN(0, ("SCardDisconnect: error, bad code"));
        pthread_mutex_unlock(&g_mutex);
        return SCARD_F_INTERNAL_ERROR;
    }
    pthread_mutex_unlock(&g_mutex);
    status = GET_UINT32(msg, 0);
    LLOGLN(10, ("SCardDisconnect: got status 0x%8.8x", status));
    return status;
}

/*****************************************************************************/
PCSC_API LONG
SCardBeginTransaction(SCARDHANDLE hCard)
{
    char msg[256];
    int code;
    int bytes;
    int status;

    LLOGLN(10, ("SCardBeginTransaction:"));
    if (g_sck == -1)
    {
        LLOGLN(0, ("SCardBeginTransaction: error, not connected"));
        return SCARD_F_INTERNAL_ERROR;
    }
    pthread_mutex_lock(&g_mutex);
    SET_UINT32(msg, 0, hCard);
    if (send_message(SCARD_BEGIN_TRANSACTION, msg, 4) != 0)
    {
        LLOGLN(0, ("SCardBeginTransaction: error, send_message"));
        pthread_mutex_unlock(&g_mutex);
        return SCARD_F_INTERNAL_ERROR;
    }
    bytes = 256;
    if (get_message(&code, msg, &bytes) != 0)
    {
        LLOGLN(0, ("SCardBeginTransaction: error, get_message"));
        pthread_mutex_unlock(&g_mutex);
        return SCARD_F_INTERNAL_ERROR;
    }
    if ((code != SCARD_BEGIN_TRANSACTION) || (bytes != 4))
    {
        LLOGLN(0, ("SCardBeginTransaction: error, bad code"));
        pthread_mutex_unlock(&g_mutex);
        return SCARD_F_INTERNAL_ERROR;
    }
    pthread_mutex_unlock(&g_mutex);
    status = GET_UINT32(msg, 0);
    LLOGLN(10, ("SCardBeginTransaction: got status 0x%8.8x", status));
    return status;
}

/*****************************************************************************/
PCSC_API LONG
SCardEndTransaction(SCARDHANDLE hCard, DWORD dwDisposition)
{
    char msg[256];
    int code;
    int bytes;
    int status;

    LLOGLN(10, ("SCardEndTransaction:"));
    if (g_sck == -1)
    {
        LLOGLN(0, ("SCardEndTransaction: error, not connected"));
        return SCARD_F_INTERNAL_ERROR;
    }
    pthread_mutex_lock(&g_mutex);
    SET_UINT32(msg, 0, hCard);
    SET_UINT32(msg, 4, dwDisposition);
    if (send_message(SCARD_END_TRANSACTION, msg, 8) != 0)
    {
        LLOGLN(0, ("SCardEndTransaction: error, send_message"));
        pthread_mutex_unlock(&g_mutex);
        return SCARD_F_INTERNAL_ERROR;
    }
    bytes = 256;
    if (get_message(&code, msg, &bytes) != 0)
    {
        LLOGLN(0, ("SCardEndTransaction: error, get_message"));
        pthread_mutex_unlock(&g_mutex);
        return SCARD_F_INTERNAL_ERROR;
    }
    if ((code != SCARD_END_TRANSACTION) || (bytes != 4))
    {
        LLOGLN(0, ("SCardEndTransaction: error, bad code"));
        pthread_mutex_unlock(&g_mutex);
        return SCARD_F_INTERNAL_ERROR;
    }
    pthread_mutex_unlock(&g_mutex);
    status = GET_UINT32(msg, 0);
    LLOGLN(10, ("SCardEndTransaction: got status 0x%8.8x", status));
    return status;
}

/*****************************************************************************/
PCSC_API LONG
SCardStatus(SCARDHANDLE hCard, LPSTR mszReaderName, LPDWORD pcchReaderLen,
            LPDWORD pdwState, LPDWORD pdwProtocol, LPBYTE pbAtr,
            LPDWORD pcbAtrLen)
{
    char *msg;
    int code;
    int bytes;
    int status;
    int offset;
    int cchReaderLen;
    int to_copy;

    LLOGLN(10, ("SCardStatus:"));
    if (g_sck == -1)
    {
        LLOGLN(0, ("SCardStatus: error, not connected"));
        return SCARD_F_INTERNAL_ERROR;
    }
    LLOGLN(10, ("  hCard 0x%8.8x", hCard));
    LLOGLN(10, ("  cchReaderLen %d", *pcchReaderLen));
    LLOGLN(10, ("  cbAtrLen %d", *pcbAtrLen));

    cchReaderLen = *pcchReaderLen;
    msg = (char *) malloc(8192);
    SET_UINT32(msg, 0, hCard);
    SET_UINT32(msg, 4, cchReaderLen);
    SET_UINT32(msg, 8, *pcbAtrLen);
    pthread_mutex_lock(&g_mutex);
    if (send_message(SCARD_STATUS, msg, 12) != 0)
    {
        LLOGLN(0, ("SCardStatus: error, send_message"));
        free(msg);
        pthread_mutex_unlock(&g_mutex);
        return SCARD_F_INTERNAL_ERROR;
    }
    bytes = 8192;
    if (get_message(&code, msg, &bytes) != 0)
    {
        LLOGLN(0, ("SCardStatus: error, get_message"));
        free(msg);
        pthread_mutex_unlock(&g_mutex);
        return SCARD_F_INTERNAL_ERROR;
    }
    if (code != SCARD_STATUS)
    {
        LLOGLN(0, ("SCardStatus: error, bad code"));
        free(msg);
        pthread_mutex_unlock(&g_mutex);
        return SCARD_F_INTERNAL_ERROR;
    }
    pthread_mutex_unlock(&g_mutex);

    LLOGLN(10, ("SCardStatus: cchReaderLen in %d", *pcchReaderLen));
    offset = 0;
    *pcchReaderLen = GET_UINT32(msg, offset);
    LLOGLN(10, ("SCardStatus: cchReaderLen out %d", *pcchReaderLen));
    offset += 4;
    if (cchReaderLen > 0)
    {
        to_copy = cchReaderLen - 1;
        if (*pcchReaderLen < to_copy)
        {
            to_copy = *pcchReaderLen;
        }
        memcpy(mszReaderName, msg + offset, to_copy);
        mszReaderName[to_copy] = 0;
    }
    LLOGLN(10, ("SCardStatus: mszReaderName out %s", mszReaderName));
    offset += *pcchReaderLen;
    *pdwState = GET_UINT32(msg, offset);
    LLOGLN(10, ("SCardStatus: dwState %d", *pdwState));
    offset += 4;
    *pdwProtocol = GET_UINT32(msg, offset);
    LLOGLN(10, ("SCardStatus: dwProtocol %d", *pdwProtocol));
    offset += 4;
    *pcbAtrLen = GET_UINT32(msg, offset);
    offset += 4;
    LLOGLN(10, ("SCardStatus: cbAtrLen %d", *pcbAtrLen));
    memcpy(pbAtr, msg + offset, *pcbAtrLen);
    offset += *pcbAtrLen;
    status = GET_UINT32(msg, offset);
    LLOGLN(10, ("SCardStatus: status %d", status));
    offset += 4;
    free(msg);
    return status;
}

/*****************************************************************************/
PCSC_API LONG
SCardGetStatusChange(SCARDCONTEXT hContext, DWORD dwTimeout,
                     LPSCARD_READERSTATE rgReaderStates, DWORD cReaders)
{
    char *msg;
    int bytes;
    int code;
    int index;
    int offset;
    int str_len;
    int status;

    LLOGLN(10, ("SCardGetStatusChange:"));
    LLOGLN(10, ("  dwTimeout %d cReaders %d", dwTimeout, cReaders));
    if (g_sck == -1)
    {
        LLOGLN(0, ("SCardGetStatusChange: error, not connected"));
        return SCARD_F_INTERNAL_ERROR;
    }
    msg = (char *) malloc(8192);
    SET_UINT32(msg, 0, hContext);
    SET_UINT32(msg, 4, dwTimeout);
    SET_UINT32(msg, 8, cReaders);
    offset = 12;
    for (index = 0; index < cReaders; index++)
    {
        if (rgReaderStates[index].dwCurrentState == 0) /* SCARD_STATE_UNAWARE */
        {
            rgReaderStates[index].dwEventState = 0;
            rgReaderStates[index].cbAtr = 0;
        }
        str_len = strlen(rgReaderStates[index].szReader);
        str_len = LMIN(str_len, 99);
        memset(msg + offset, 0, 100);
        memcpy(msg + offset, rgReaderStates[index].szReader, str_len);
        LLOGLN(10, ("  in szReader       %s", rgReaderStates[index].szReader));
        offset += 100;
        LLOGLN(10, ("  in dwCurrentState 0x%8.8x", rgReaderStates[index].dwCurrentState));
        SET_UINT32(msg, offset, rgReaderStates[index].dwCurrentState);
        offset += 4;
        LLOGLN(10, ("  in dwEventState   0x%8.8x", rgReaderStates[index].dwEventState));
        SET_UINT32(msg, offset, rgReaderStates[index].dwEventState);
        offset += 4;
        LLOGLN(10, ("  in cbAtr          %d", rgReaderStates[index].cbAtr));
        SET_UINT32(msg, offset, rgReaderStates[index].cbAtr);
        offset += 4;
        memset(msg + offset, 0, 36);
        memcpy(msg + offset, rgReaderStates[index].rgbAtr, 33);
        offset += 36;
    }
    pthread_mutex_lock(&g_mutex);
    if (send_message(SCARD_GET_STATUS_CHANGE, msg, offset) != 0)
    {
        LLOGLN(0, ("SCardGetStatusChange: error, send_message"));
        free(msg);
        pthread_mutex_unlock(&g_mutex);
        return SCARD_F_INTERNAL_ERROR;
    }
    bytes = 8192;
    if (get_message(&code, msg, &bytes) != 0)
    {
        LLOGLN(0, ("SCardGetStatusChange: error, get_message"));
        free(msg);
        pthread_mutex_unlock(&g_mutex);
        return SCARD_F_INTERNAL_ERROR;
    }
    if (code != SCARD_GET_STATUS_CHANGE)
    {
        LLOGLN(0, ("SCardGetStatusChange: error, bad code"));
        free(msg);
        pthread_mutex_unlock(&g_mutex);
        return SCARD_F_INTERNAL_ERROR;
    }
    pthread_mutex_unlock(&g_mutex);
    cReaders = GET_UINT32(msg, 0);
    offset = 4;
    LLOGLN(10, ("SCardGetStatusChange: got back cReaders %d", cReaders));
    for (index = 0; index < cReaders; index++)
    {
        LLOGLN(10, ("  out szReader       %s", rgReaderStates[index].szReader));
        rgReaderStates[index].dwCurrentState = GET_UINT32(msg, offset);
        offset += 4;
        LLOGLN(10, ("  out dwCurrentState 0x%8.8x", rgReaderStates[index].dwCurrentState));
        rgReaderStates[index].dwEventState = GET_UINT32(msg, offset);
        offset += 4;
        LLOGLN(10, ("  out dwEventState   0x%8.8x", rgReaderStates[index].dwEventState));
        rgReaderStates[index].cbAtr = GET_UINT32(msg, offset);
        offset += 4;
        LLOGLN(10, ("  out cbAtr          %d", rgReaderStates[index].cbAtr));
        memcpy(rgReaderStates[index].rgbAtr, msg + offset, 33);
        offset += 36;
    }
    status = GET_UINT32(msg, offset);
    offset += 4;
    free(msg);
    return status;
}

/*****************************************************************************/
PCSC_API LONG
SCardControl(SCARDHANDLE hCard, DWORD dwControlCode, LPCVOID pbSendBuffer,
             DWORD cbSendLength, LPVOID pbRecvBuffer, DWORD cbRecvLength,
             LPDWORD lpBytesReturned)
{
    char *msg;
    int bytes;
    int code;
    int offset;
    int status = 0;

    LLOGLN(10, ("SCardControl:"));
    if (g_sck == -1)
    {
        LLOGLN(0, ("SCardControl: error, not connected"));
        return SCARD_F_INTERNAL_ERROR;
    }
    LLOGLN(10, ("  hCard 0x%8.8x", hCard));
    LLOGLN(10, ("  dwControlCode 0x%8.8x", dwControlCode));
    LLOGLN(10, ("  cbSendLength %d", cbSendLength));
    LLOGLN(10, ("  cbRecvLength %d", cbRecvLength));

    /* #define SCARD_CTL_CODE(code) (0x42000000 + (code))
       control_code = (control_code & 0x3ffc) >> 2;
       control_code = SCARD_CTL_CODE(control_code); */

    /* PCSC to Windows control code conversion */
    dwControlCode = dwControlCode - 0x42000000;
    dwControlCode = dwControlCode << 2;
    dwControlCode = dwControlCode | (49 << 16);
    LLOGLN(10, ("  MS dwControlCode 0x%8.8x", dwControlCode));

    msg = (char *) malloc(8192);
    offset = 0;
    SET_UINT32(msg, offset, hCard);
    offset += 4;
    SET_UINT32(msg, offset, dwControlCode);
    offset += 4;
    SET_UINT32(msg, offset, cbSendLength);
    offset += 4;
    memcpy(msg + offset, pbSendBuffer, cbSendLength);
    offset += cbSendLength;
    SET_UINT32(msg, offset, cbRecvLength);
    offset += 4;
    pthread_mutex_lock(&g_mutex);
    if (send_message(SCARD_CONTROL, msg, offset) != 0)
    {
        LLOGLN(0, ("SCardControl: error, send_message"));
        free(msg);
        pthread_mutex_unlock(&g_mutex);
        return SCARD_F_INTERNAL_ERROR;
    }
    bytes = 8192;
    if (get_message(&code, msg, &bytes) != 0)
    {
        LLOGLN(0, ("SCardControl: error, get_message"));
        free(msg);
        pthread_mutex_unlock(&g_mutex);
        return SCARD_F_INTERNAL_ERROR;
    }
    if (code != SCARD_CONTROL)
    {
        LLOGLN(0, ("SCardControl: error, bad code"));
        free(msg);
        pthread_mutex_unlock(&g_mutex);
        return SCARD_F_INTERNAL_ERROR;
    }
    pthread_mutex_unlock(&g_mutex);
    offset = 0;
    *lpBytesReturned = GET_UINT32(msg, offset);
    LLOGLN(10, ("  cbRecvLength %d", *lpBytesReturned));
    offset += 4;
    memcpy(pbRecvBuffer, msg + offset, *lpBytesReturned);
    offset += *lpBytesReturned;
    status = GET_UINT32(msg, offset);
    free(msg);
    return status;
}

/*****************************************************************************/
PCSC_API LONG
SCardTransmit(SCARDHANDLE hCard, const SCARD_IO_REQUEST *pioSendPci,
              LPCBYTE pbSendBuffer, DWORD cbSendLength,
              SCARD_IO_REQUEST *pioRecvPci, LPBYTE pbRecvBuffer,
              LPDWORD pcbRecvLength)
{
    char *msg;
    int bytes;
    int code;
    int offset;
    int status;
    int extra_len;

    LLOGLN(10, ("SCardTransmit:"));
    if (g_sck == -1)
    {
        LLOGLN(0, ("SCardTransmit: error, not connected"));
        return SCARD_F_INTERNAL_ERROR;
    }
    LLOGLN(10, ("  hCard 0x%8.8x", hCard));
    LLOGLN(10, ("  cbSendLength %d", cbSendLength));
    LLOGLN(10, ("  cbRecvLength %d", *pcbRecvLength));
    LLOGLN(10, ("  pioSendPci->dwProtocol %d", (int)(pioSendPci->dwProtocol)));
    LLOGLN(10, ("  pioSendPci->cbPciLength %d", (int)(pioSendPci->cbPciLength)));
    LLOGLN(10, ("  pioRecvPci %p", pioRecvPci));
    if (pioRecvPci != 0)
    {
        LLOGLN(10, ("    pioRecvPci->dwProtocol %d", (int)(pioRecvPci->dwProtocol)));
        LLOGLN(10, ("    pioRecvPci->cbPciLength %d", (int)(pioRecvPci->cbPciLength)));
    }
    msg = (char *) malloc(8192);
    offset = 0;
    SET_UINT32(msg, offset, hCard);
    offset += 4;
    SET_UINT32(msg, offset, pioSendPci->dwProtocol);
    offset += 4;
    SET_UINT32(msg, offset, pioSendPci->cbPciLength);
    offset += 4;
    extra_len = pioSendPci->cbPciLength - 8;
    SET_UINT32(msg, offset, extra_len);
    offset += 4;
    memcpy(msg + offset, pioSendPci + 1, extra_len);
    offset += extra_len;
    SET_UINT32(msg, offset, cbSendLength);
    offset += 4;
    memcpy(msg + offset, pbSendBuffer, cbSendLength);
    offset += cbSendLength;
    if ((pioRecvPci == 0) || (pioRecvPci->cbPciLength < 8))
    {
        SET_UINT32(msg, offset, 0); /* dwProtocol */
        offset += 4;
        SET_UINT32(msg, offset, 0); /* cbPciLength */
        offset += 4;
        SET_UINT32(msg, offset, 0); /* extra_len */
        offset += 4;
    }
    else
    {
        SET_UINT32(msg, offset, pioRecvPci->dwProtocol);
        offset += 4;
        SET_UINT32(msg, offset, pioRecvPci->cbPciLength);
        offset += 4;
        extra_len = pioRecvPci->cbPciLength - 8;
        SET_UINT32(msg, offset, extra_len);
        offset += 4;
        memcpy(msg + offset, pioRecvPci + 1, extra_len);
        offset += extra_len;
    }
    SET_UINT32(msg, offset, *pcbRecvLength);
    offset += 4;
    pthread_mutex_lock(&g_mutex);
    if (send_message(SCARD_TRANSMIT, msg, offset) != 0)
    {
        LLOGLN(0, ("SCardTransmit: error, send_message"));
        free(msg);
        pthread_mutex_unlock(&g_mutex);
        return SCARD_F_INTERNAL_ERROR;
    }
    bytes = 8192;
    if (get_message(&code, msg, &bytes) != 0)
    {
        LLOGLN(0, ("SCardTransmit: error, get_message"));
        free(msg);
        pthread_mutex_unlock(&g_mutex);
        return SCARD_F_INTERNAL_ERROR;
    }
    if (code != SCARD_TRANSMIT)
    {
        LLOGLN(0, ("SCardTransmit: error, bad code"));
        free(msg);
        pthread_mutex_unlock(&g_mutex);
        return SCARD_F_INTERNAL_ERROR;
    }
    pthread_mutex_unlock(&g_mutex);
    offset = 0;
    if (pioRecvPci == 0)
    {
        offset += 8;
        extra_len = GET_UINT32(msg, offset);
        offset += 4;
        offset += extra_len;
    }
    else
    {
        pioRecvPci->dwProtocol = GET_UINT32(msg, offset);
        offset += 4;
        pioRecvPci->cbPciLength = GET_UINT32(msg, offset);
        offset += 4;
        extra_len = GET_UINT32(msg, offset);
        offset += 4;
        offset += extra_len;
    }
    *pcbRecvLength = GET_UINT32(msg, offset);
    offset += 4;
    LLOGLN(10, ("  cbRecvLength %d", *pcbRecvLength));
    memcpy(pbRecvBuffer, msg + offset, *pcbRecvLength);
    offset += *pcbRecvLength;
    status = GET_UINT32(msg, offset);
    free(msg);
    return status;
}

/*****************************************************************************/
PCSC_API LONG
SCardListReaderGroups(SCARDCONTEXT hContext, LPSTR mszGroups,
                      LPDWORD pcchGroups)
{
    LLOGLN(10, ("SCardListReaderGroups:"));
    if (g_sck == -1)
    {
        LLOGLN(0, ("SCardListReaderGroups: error, not connected"));
        return SCARD_F_INTERNAL_ERROR;
    }
    pthread_mutex_lock(&g_mutex);
    pthread_mutex_unlock(&g_mutex);
    return SCARD_S_SUCCESS;
}

/*****************************************************************************/
PCSC_API LONG
SCardListReaders(SCARDCONTEXT hContext, LPCSTR mszGroups, LPSTR mszReaders,
                 LPDWORD pcchReaders)
{
    char* msg;
    char* reader_names;
    int reader_names_index;
    int code;
    int bytes;
    int num_readers;
    int status;
    int offset;
    int index;
    int bytes_groups;
    int val;
    int llen;
    char reader[100];

    LLOGLN(10, ("SCardListReaders:"));
    LLOGLN(10, ("SCardListReaders: mszGroups %s", mszGroups));
    LLOGLN(10, ("SCardListReaders: *pcchReaders %d", *pcchReaders));
    if (g_sck == -1)
    {
        LLOGLN(0, ("SCardListReaders: error, not connected"));
        return SCARD_F_INTERNAL_ERROR;
    }
    msg = (char *) malloc(8192);
    pthread_mutex_lock(&g_mutex);
    offset = 0;
    SET_UINT32(msg, offset, hContext);
    offset += 4;
    bytes_groups = 0;
    if (mszGroups != 0)
    {
        bytes_groups = strlen(mszGroups);
    }
    SET_UINT32(msg, offset, bytes_groups);
    offset += 4;
    memcpy(msg + offset, mszGroups, bytes_groups);
    offset += bytes_groups;
    val = *pcchReaders;
    SET_UINT32(msg, offset, val);
    offset += 4;
    if (send_message(SCARD_LIST_READERS, msg, offset) != 0)
    {
        LLOGLN(0, ("SCardListReaders: error, send_message"));
        free(msg);
        pthread_mutex_unlock(&g_mutex);
        return SCARD_F_INTERNAL_ERROR;
    }
    bytes = 8192;
    if (get_message(&code, msg, &bytes) != 0)
    {
        LLOGLN(0, ("SCardListReaders: error, get_message"));
        free(msg);
        pthread_mutex_unlock(&g_mutex);
        return SCARD_F_INTERNAL_ERROR;
    }
    if (code != SCARD_LIST_READERS)
    {
        LLOGLN(0, ("SCardListReaders: error, bad code"));
        free(msg);
        pthread_mutex_unlock(&g_mutex);
        return SCARD_F_INTERNAL_ERROR;
    }
    pthread_mutex_unlock(&g_mutex);
    offset = 0;
    llen = GET_UINT32(msg, offset);
    offset += 4;
    num_readers = GET_UINT32(msg, offset);
    offset += 4;
    LLOGLN(10, ("SCardListReaders: mszReaders %p pcchReaders %p num_readers %d",
           mszReaders, pcchReaders, num_readers));
    reader_names = (char *) malloc(8192);
    reader_names_index = 0;
    for (index = 0; index < num_readers; index++)
    {
        memcpy(reader, msg + offset, 100);
        bytes = strlen(reader);
        memcpy(reader_names + reader_names_index, reader, bytes);
        reader_names_index += bytes;
        reader_names[reader_names_index] = 0;
        reader_names_index++;
        offset += 100;
        LLOGLN(10, ("SCardListReaders: readername %s", reader));
    }
    reader_names[reader_names_index] = 0;
    reader_names_index++;
    status = GET_UINT32(msg, offset);
    offset += 4;
    if (mszReaders == 0)
    {
        reader_names_index = llen;
    }
    if (pcchReaders != 0)
    {
        *pcchReaders = reader_names_index;
    }
    if (mszReaders != 0)
    {
        memcpy(mszReaders, reader_names, reader_names_index);
    }
    free(msg);
    free(reader_names);
    return status;
}

/*****************************************************************************/
PCSC_API LONG
SCardFreeMemory(SCARDCONTEXT hContext, LPCVOID pvMem)
{
    LLOGLN(0, ("SCardFreeMemory:"));
    if (g_sck == -1)
    {
        LLOGLN(0, ("SCardFreeMemory: error, not connected"));
        return SCARD_F_INTERNAL_ERROR;
    }
    pthread_mutex_lock(&g_mutex);
    pthread_mutex_unlock(&g_mutex);
    return SCARD_S_SUCCESS;
}

/*****************************************************************************/
PCSC_API LONG
SCardCancel(SCARDCONTEXT hContext)
{
    LLOGLN(0, ("SCardCancel:"));
    if (g_sck == -1)
    {
        LLOGLN(0, ("SCardCancel: error, not connected"));
        return SCARD_F_INTERNAL_ERROR;
    }
    pthread_mutex_lock(&g_mutex);
    pthread_mutex_unlock(&g_mutex);
    return SCARD_S_SUCCESS;
}

/*****************************************************************************/
PCSC_API LONG
SCardGetAttrib(SCARDHANDLE hCard, DWORD dwAttrId, LPBYTE pbAttr,
               LPDWORD pcbAttrLen)
{
    LLOGLN(0, ("SCardGetAttrib:"));
    if (g_sck == -1)
    {
        LLOGLN(0, ("SCardGetAttrib: error, not connected"));
        return SCARD_F_INTERNAL_ERROR;
    }
    pthread_mutex_lock(&g_mutex);
    pthread_mutex_unlock(&g_mutex);
    return SCARD_S_SUCCESS;
}

/*****************************************************************************/
PCSC_API LONG
SCardSetAttrib(SCARDHANDLE hCard, DWORD dwAttrId, LPCBYTE pbAttr,
               DWORD cbAttrLen)
{
    LLOGLN(0, ("SCardSetAttrib:"));
    if (g_sck == -1)
    {
        LLOGLN(0, ("SCardSetAttrib: error, not connected"));
        return SCARD_F_INTERNAL_ERROR;
    }
    pthread_mutex_lock(&g_mutex);
    pthread_mutex_unlock(&g_mutex);
    return SCARD_S_SUCCESS;
}

/*****************************************************************************/
PCSC_API char *
pcsc_stringify_error(const long code)
{
    LLOGLN(10, ("pcsc_stringify_error: 0x%8.8x", (int)code));
    switch (code)
    {
        case SCARD_S_SUCCESS:
            snprintf(g_error_str, 511, "Command successful.");
            break;
        case SCARD_F_INTERNAL_ERROR:
            snprintf(g_error_str, 511, "Internal error.");
            break;
        default:
            snprintf(g_error_str, 511, "error 0x%8.8x", (int)code);
            break;
    }
    g_error_str[511] = 0;
    return g_error_str;
}