Coverage Report

Created: 2026-11-10 06:44

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/FreeRDP/libfreerdp/utils/smartcard_call.c
Line
Count
Source
1
/**
2
 * FreeRDP: A Remote Desktop Protocol Implementation
3
 * Smartcard Device Service Virtual Channel
4
 *
5
 * Copyright (C) Alexi Volkov <alexi@myrealbox.com> 2006
6
 * Copyright 2011 O.S. Systems Software Ltda.
7
 * Copyright 2011 Anthony Tong <atong@trustedcs.com>
8
 * Copyright 2015 Thincast Technologies GmbH
9
 * Copyright 2015 DI (FH) Martin Haimberger <martin.haimberger@thincast.com>
10
 * Copyright 2017 Armin Novak <armin.novak@thincast.com>
11
 * Copyright 2017 Thincast Technologies GmbH
12
 *
13
 * Licensed under the Apache License, Version 2.0 (the "License");
14
 * you may not use this file except in compliance with the License.
15
 * You may obtain a copy of the License at
16
 *
17
 *     http://www.apache.org/licenses/LICENSE-2.0
18
 *
19
 * Unless required by applicable law or agreed to in writing, software
20
 * distributed under the License is distributed on an "AS IS" BASIS,
21
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22
 * See the License for the specific language governing permissions and
23
 * limitations under the License.
24
 */
25
26
#include <freerdp/config.h>
27
28
#include <winpr/assert.h>
29
30
#include <winpr/crt.h>
31
#include <winpr/print.h>
32
#include <winpr/stream.h>
33
#include <winpr/library.h>
34
#include <winpr/smartcard.h>
35
#include <winpr/synch.h>
36
#include <winpr/sysinfo.h>
37
#include <winpr/thread.h>
38
#include <winpr/collections.h>
39
40
#include <errno.h>
41
#include <stdlib.h>
42
43
#include <freerdp/freerdp.h>
44
#include <freerdp/channels/rdpdr.h>
45
#include <freerdp/channels/scard.h>
46
47
#include <freerdp/utils/rdpdr_utils.h>
48
#include <freerdp/utils/smartcard_pack.h>
49
#include <freerdp/utils/smartcard_call.h>
50
51
#include "smartcard_pack.h"
52
53
#include <freerdp/log.h>
54
0
#define SCARD_TAG FREERDP_TAG("utils.smartcard.call")
55
56
#if defined(WITH_SMARTCARD_EMULATE)
57
#include <freerdp/emulate/scard/smartcard_emulate.h>
58
59
/* The ternary is fully parenthesized: on _WIN32 wrap() below expands straight to wrap_raw(),
60
 * so an unparenthesized ternary would swallow any operator applied to the result. For example
61
 * `wrap(ctx, SCardIsValidContext, h) == SCARD_S_SUCCESS` would parse as
62
 * `useEmulatedCard ? Emulate_...(h) : (pfn...(h) == SCARD_S_SUCCESS)`, i.e. the comparison only
63
 * applies to the non-emulated branch. */
64
#define wrap_raw(ctx, fkt, ...)                                              \
65
0
  ((ctx)->useEmulatedCard ? Emulate_##fkt((ctx)->emulation, ##__VA_ARGS__) \
66
0
                          : (ctx)->pWinSCardApi->pfn##fkt(__VA_ARGS__))
67
0
#define wrap_ptr(ctx, fkt, ...) wrap_raw(ctx, fkt, ##__VA_ARGS__)
68
#else
69
#define wrap_raw(ctx, fkt, ...) \
70
  ((ctx)->useEmulatedCard ? SCARD_F_INTERNAL_ERROR : (ctx)->pWinSCardApi->pfn##fkt(__VA_ARGS__))
71
#define wrap_ptr(ctx, fkt, ...) \
72
  ((ctx)->useEmulatedCard ? nullptr : (ctx)->pWinSCardApi->pfn##fkt(__VA_ARGS__))
73
#endif
74
75
#if defined(_WIN32)
76
#define wrap(ctx, fkt, ...) wrap_raw(ctx, fkt, ##__VA_ARGS__)
77
#else
78
#define wrap(ctx, fkt, ...)                                               \
79
0
  __extension__({                                                       \
80
0
    LONG defstatus = wrap_raw(ctx, fkt, ##__VA_ARGS__);               \
81
0
    if (defstatus != SCARD_S_SUCCESS)                                 \
82
0
      WLog_Print(ctx->log, WLOG_TRACE, "[" #fkt "] failed with %s", \
83
0
                 SCardGetErrorString(defstatus));                   \
84
0
    defstatus;                                                        \
85
0
  })
86
#endif
87
88
struct s_scard_call_context
89
{
90
  BOOL useEmulatedCard;
91
  HANDLE StartedEvent;
92
  wLinkedList* names;
93
  wHashTable* rgSCardContextList;
94
#if defined(WITH_SMARTCARD_EMULATE)
95
  SmartcardEmulationContext* emulation;
96
#endif
97
  HANDLE hWinSCardLibrary;
98
  SCardApiFunctionTable WinSCardApi;
99
  const SCardApiFunctionTable* pWinSCardApi;
100
  HANDLE stopEvent;
101
  void* userdata;
102
103
  void* (*fn_new)(void*, SCARDCONTEXT);
104
  void (*fn_free)(void*);
105
  wLog* log;
106
  rdpContext* context;
107
108
  /* idle transaction watchdog */
109
  wHashTable* handleStates;
110
  HANDLE watchdogStopEvent;
111
  HANDLE watchdogThread;
112
  UINT64 transactionTimeout;
113
};
114
115
struct s_scard_context_element
116
{
117
  void* context;
118
  void (*fn_free)(void*);
119
};
120
121
static void context_free(void* arg);
122
123
/* Windows resets the card when a transaction is idle for 5 s, pcsc-lite does not.
124
 * FREERDP_SCARD_TRANSACTION_TIMEOUT_MS overrides the timeout, 0 disables it */
125
0
#define SCARD_TRANSACTION_IDLE_TIMEOUT_MS 5000
126
0
#define SCARD_TRANSACTION_WATCHDOG_INTERVAL_MS 250
127
#define SCARD_TRANSACTION_WATCHDOG_MAX_EXPIRED 32
128
129
typedef struct
130
{
131
  BOOL inTransaction;
132
  BOOL disconnected;
133
  UINT32 activeCalls;
134
  UINT32 pendingBegins;
135
  UINT32 abandonedBegins;
136
  UINT64 lastActivity;
137
} scard_handle_state;
138
139
typedef struct
140
{
141
  UINT64 now;
142
  UINT64 timeout;
143
  size_t count;
144
  SCARDHANDLE handles[SCARD_TRANSACTION_WATCHDOG_MAX_EXPIRED];
145
} scard_expired_transactions;
146
147
static void smartcard_handle_activity_begin(scard_call_context* ctx, UINT32 ioControlCode,
148
                                            SCARDHANDLE hCard)
149
0
{
150
0
  WINPR_ASSERT(ctx);
151
152
0
  if (!ctx->handleStates || !hCard)
153
0
    return;
154
155
0
  HashTable_Lock(ctx->handleStates);
156
0
  scard_handle_state* state = HashTable_GetItemValue(ctx->handleStates, (void*)hCard);
157
0
  if (!state)
158
0
  {
159
0
    state = calloc(1, sizeof(scard_handle_state));
160
0
    if (state && !HashTable_Insert(ctx->handleStates, (void*)hCard, state))
161
0
    {
162
0
      free(state);
163
0
      state = nullptr;
164
0
    }
165
0
  }
166
0
  if (state)
167
0
  {
168
0
    state->activeCalls++;
169
0
    state->lastActivity = GetTickCount64();
170
171
0
    switch (ioControlCode)
172
0
    {
173
0
      case SCARD_IOCTL_BEGINTRANSACTION:
174
0
        state->pendingBegins++;
175
0
        break;
176
0
      case SCARD_IOCTL_ENDTRANSACTION:
177
        /* the server gave up waiting, release it when granted */
178
0
        if (state->inTransaction)
179
0
          state->inTransaction = FALSE;
180
0
        else if (state->pendingBegins > state->abandonedBegins)
181
0
          state->abandonedBegins++;
182
0
        break;
183
0
      default:
184
0
        break;
185
0
    }
186
0
  }
187
  // NOLINTNEXTLINE(clang-analyzer-unix.Malloc): HashTable_Insert owns state
188
0
  HashTable_Unlock(ctx->handleStates);
189
0
}
190
191
/* returns TRUE if a transaction the server gave up on was granted */
192
static BOOL smartcard_handle_activity_end(scard_call_context* ctx, UINT32 ioControlCode,
193
                                          SCARDHANDLE hCard, LONG result)
194
0
{
195
0
  BOOL abandoned = FALSE;
196
197
0
  WINPR_ASSERT(ctx);
198
199
0
  if (!ctx->handleStates || !hCard)
200
0
    return FALSE;
201
202
0
  HashTable_Lock(ctx->handleStates);
203
0
  scard_handle_state* state = HashTable_GetItemValue(ctx->handleStates, (void*)hCard);
204
0
  if (state)
205
0
  {
206
0
    if (state->activeCalls > 0)
207
0
      state->activeCalls--;
208
0
    state->lastActivity = GetTickCount64();
209
210
0
    switch (ioControlCode)
211
0
    {
212
0
      case SCARD_IOCTL_BEGINTRANSACTION:
213
0
        if (state->pendingBegins > 0)
214
0
          state->pendingBegins--;
215
0
        if (state->abandonedBegins > 0)
216
0
        {
217
0
          state->abandonedBegins--;
218
0
          abandoned = (result == SCARD_S_SUCCESS);
219
0
        }
220
0
        else if (result == SCARD_S_SUCCESS)
221
0
          state->inTransaction = TRUE;
222
0
        break;
223
0
      case SCARD_IOCTL_DISCONNECT:
224
0
        if (result == SCARD_S_SUCCESS)
225
0
        {
226
0
          state->inTransaction = FALSE;
227
0
          state->disconnected = TRUE;
228
0
        }
229
0
        break;
230
0
      default:
231
0
        break;
232
0
    }
233
234
0
    if (state->disconnected && (state->activeCalls == 0))
235
0
      HashTable_Remove(ctx->handleStates, (void*)hCard);
236
0
  }
237
0
  HashTable_Unlock(ctx->handleStates);
238
0
  return abandoned;
239
0
}
240
241
static BOOL smartcard_collect_expired_transaction(const void* key, void* value, void* arg)
242
0
{
243
0
  scard_handle_state* state = value;
244
0
  scard_expired_transactions* expired = arg;
245
246
0
  WINPR_ASSERT(state);
247
0
  WINPR_ASSERT(expired);
248
249
0
  if (!state->inTransaction || (state->activeCalls > 0))
250
0
    return TRUE;
251
0
  if (expired->now - state->lastActivity < expired->timeout)
252
0
    return TRUE;
253
0
  if (expired->count >= ARRAYSIZE(expired->handles))
254
0
    return FALSE; /* rest on the next round */
255
256
0
  state->inTransaction = FALSE;
257
0
  expired->handles[expired->count++] = (SCARDHANDLE)key;
258
0
  return TRUE;
259
0
}
260
261
static DWORD WINAPI smartcard_transaction_watchdog(LPVOID arg)
262
0
{
263
0
  scard_call_context* ctx = arg;
264
265
0
  WINPR_ASSERT(ctx);
266
267
0
  while (WaitForSingleObject(ctx->watchdogStopEvent, SCARD_TRANSACTION_WATCHDOG_INTERVAL_MS) ==
268
0
         WAIT_TIMEOUT)
269
0
  {
270
0
    scard_expired_transactions expired = WINPR_C_ARRAY_INIT;
271
0
    expired.now = GetTickCount64();
272
0
    expired.timeout = ctx->transactionTimeout;
273
274
0
    if (!HashTable_Foreach(ctx->handleStates, smartcard_collect_expired_transaction, &expired))
275
0
      WLog_Print(ctx->log, WLOG_DEBUG,
276
0
                 "more idle transactions than handled in one round, continuing next round");
277
278
    /* not locked, SCardEndTransaction may block */
279
0
    for (size_t x = 0; x < expired.count; x++)
280
0
    {
281
0
      const SCARDHANDLE hCard = expired.handles[x];
282
283
0
      WLog_Print(ctx->log, WLOG_WARN,
284
0
                 "transaction on hCard 0x%08" PRIxz " idle for more than %" PRIu64
285
0
                 " ms, ending it and resetting the card like Windows does",
286
0
                 (size_t)hCard, ctx->transactionTimeout);
287
288
0
      const LONG rc = wrap(ctx, SCardEndTransaction, hCard, SCARD_RESET_CARD);
289
0
      if (rc == SCARD_E_INVALID_HANDLE)
290
0
        HashTable_Remove(ctx->handleStates, (void*)hCard);
291
0
    }
292
0
  }
293
294
0
  ExitThread(0);
295
0
  return 0;
296
0
}
297
298
static UINT64 smartcard_transaction_timeout(void)
299
0
{
300
  // NOLINTNEXTLINE(concurrency-mt-unsafe)
301
0
  const char* value = getenv("FREERDP_SCARD_TRANSACTION_TIMEOUT_MS");
302
0
  if (!value || !*value)
303
0
    return SCARD_TRANSACTION_IDLE_TIMEOUT_MS;
304
305
0
  char* end = nullptr;
306
0
  errno = 0;
307
0
  const unsigned long long timeout = strtoull(value, &end, 10);
308
0
  if ((errno != 0) || !end || (*end != '\0'))
309
0
    return SCARD_TRANSACTION_IDLE_TIMEOUT_MS;
310
0
  return timeout;
311
0
}
312
313
static BOOL smartcard_transaction_watchdog_start(scard_call_context* ctx)
314
0
{
315
0
  WINPR_ASSERT(ctx);
316
317
0
  if (ctx->useEmulatedCard)
318
0
    return TRUE;
319
320
0
  ctx->handleStates = HashTable_New(TRUE);
321
0
  if (!ctx->handleStates)
322
0
    return FALSE;
323
324
0
  {
325
0
    wObject* obj = HashTable_ValueObject(ctx->handleStates);
326
0
    WINPR_ASSERT(obj);
327
0
    obj->fnObjectFree = free;
328
0
  }
329
330
0
  ctx->transactionTimeout = smartcard_transaction_timeout();
331
0
  if (ctx->transactionTimeout == 0)
332
0
  {
333
0
    WLog_Print(ctx->log, WLOG_DEBUG, "idle transaction watchdog disabled");
334
0
    return TRUE;
335
0
  }
336
337
0
  ctx->watchdogStopEvent = CreateEventA(nullptr, TRUE, FALSE, nullptr);
338
0
  if (!ctx->watchdogStopEvent)
339
0
    return FALSE;
340
341
0
  ctx->watchdogThread = CreateThread(nullptr, 0, smartcard_transaction_watchdog, ctx, 0, nullptr);
342
0
  if (!ctx->watchdogThread)
343
0
    return FALSE;
344
345
0
  WLog_Print(ctx->log, WLOG_DEBUG, "idle transaction watchdog started, timeout %" PRIu64 " ms",
346
0
             ctx->transactionTimeout);
347
0
  return TRUE;
348
0
}
349
350
static void smartcard_transaction_watchdog_stop(scard_call_context* ctx)
351
0
{
352
0
  WINPR_ASSERT(ctx);
353
354
0
  if (ctx->watchdogThread)
355
0
  {
356
0
    (void)SetEvent(ctx->watchdogStopEvent);
357
0
    (void)WaitForSingleObject(ctx->watchdogThread, INFINITE);
358
0
    (void)CloseHandle(ctx->watchdogThread);
359
0
    ctx->watchdogThread = nullptr;
360
0
  }
361
0
  if (ctx->watchdogStopEvent)
362
0
  {
363
0
    (void)CloseHandle(ctx->watchdogStopEvent);
364
0
    ctx->watchdogStopEvent = nullptr;
365
0
  }
366
0
}
367
368
WINPR_ATTR_NODISCARD WINPR_ATTR_NODISCARD static LONG
369
smartcard_EstablishContext_Call(scard_call_context* smartcard, wStream* out,
370
                                SMARTCARD_OPERATION* operation)
371
0
{
372
0
  SCARDCONTEXT hContext = WINPR_C_ARRAY_INIT;
373
0
  EstablishContext_Return ret = WINPR_C_ARRAY_INIT;
374
0
  EstablishContext_Call* call = &operation->call.establishContext;
375
0
  LONG status = ret.ReturnCode =
376
0
      wrap(smartcard, SCardEstablishContext, call->dwScope, nullptr, nullptr, &hContext);
377
378
0
  if (ret.ReturnCode == SCARD_S_SUCCESS)
379
0
  {
380
0
    const void* key = (void*)(size_t)hContext;
381
0
    struct s_scard_context_element* pContext =
382
0
        calloc(1, sizeof(struct s_scard_context_element));
383
0
    if (!pContext)
384
0
      return STATUS_NO_MEMORY;
385
386
0
    pContext->fn_free = smartcard->fn_free;
387
388
0
    if (smartcard->fn_new)
389
0
    {
390
0
      pContext->context = smartcard->fn_new(smartcard->userdata, hContext);
391
0
      if (!pContext->context)
392
0
      {
393
0
        free(pContext);
394
0
        return STATUS_NO_MEMORY;
395
0
      }
396
0
    }
397
398
0
    if (!HashTable_Insert(smartcard->rgSCardContextList, key, (void*)pContext))
399
0
    {
400
0
      WLog_Print(smartcard->log, WLOG_ERROR, "HashTable_Insert failed!");
401
0
      context_free(pContext);
402
0
      return STATUS_INTERNAL_ERROR;
403
0
    }
404
0
  }
405
0
  else
406
0
  {
407
0
    return scard_log_status_error_wlog(smartcard->log, "SCardEstablishContext", status);
408
0
  }
409
410
  // NOLINTNEXTLINE(clang-analyzer-unix.Malloc): HashTable_Insert takes ownership of pContext
411
0
  smartcard_scard_context_native_to_redir(&(ret.hContext), hContext);
412
413
0
  status = smartcard_pack_establish_context_return(out, &ret);
414
0
  if (status != SCARD_S_SUCCESS)
415
0
  {
416
0
    return scard_log_status_error_wlog(smartcard->log,
417
0
                                       "smartcard_pack_establish_context_return", status);
418
0
  }
419
420
0
  return ret.ReturnCode;
421
0
}
422
423
WINPR_ATTR_NODISCARD static LONG smartcard_ReleaseContext_Call(scard_call_context* smartcard,
424
                                                               WINPR_ATTR_UNUSED wStream* out,
425
                                                               SMARTCARD_OPERATION* operation)
426
0
{
427
0
  Long_Return ret = WINPR_C_ARRAY_INIT;
428
429
0
  WINPR_ASSERT(smartcard);
430
0
  WINPR_ASSERT(out);
431
0
  WINPR_ASSERT(operation);
432
433
0
  ret.ReturnCode = wrap(smartcard, SCardReleaseContext, operation->hContext);
434
435
0
  if (ret.ReturnCode == SCARD_S_SUCCESS)
436
0
    HashTable_Remove(smartcard->rgSCardContextList, (void*)operation->hContext);
437
0
  else
438
0
  {
439
0
    return scard_log_status_error_wlog(smartcard->log, "SCardReleaseContext", ret.ReturnCode);
440
0
  }
441
442
0
  smartcard_trace_long_return_int(smartcard->log, &ret, "ReleaseContext");
443
0
  return ret.ReturnCode;
444
0
}
445
446
WINPR_ATTR_NODISCARD static LONG smartcard_IsValidContext_Call(scard_call_context* smartcard,
447
                                                               WINPR_ATTR_UNUSED wStream* out,
448
                                                               SMARTCARD_OPERATION* operation)
449
0
{
450
0
  Long_Return ret = WINPR_C_ARRAY_INIT;
451
452
0
  WINPR_ASSERT(smartcard);
453
0
  WINPR_ASSERT(out);
454
0
  WINPR_ASSERT(operation);
455
456
0
  ret.ReturnCode = wrap(smartcard, SCardIsValidContext, operation->hContext);
457
0
  smartcard_trace_long_return_int(smartcard->log, &ret, "IsValidContext");
458
0
  return ret.ReturnCode;
459
0
}
460
461
WINPR_ATTR_NODISCARD static LONG smartcard_ListReaderGroupsA_Call(scard_call_context* smartcard,
462
                                                                  wStream* out,
463
                                                                  SMARTCARD_OPERATION* operation)
464
0
{
465
0
  LONG status = 0;
466
0
  ListReaderGroups_Return ret = WINPR_C_ARRAY_INIT;
467
0
  LPSTR mszGroups = nullptr;
468
0
  DWORD cchGroups = 0;
469
470
0
  WINPR_ASSERT(smartcard);
471
0
  WINPR_ASSERT(out);
472
0
  WINPR_ASSERT(operation);
473
474
0
  cchGroups = SCARD_AUTOALLOCATE;
475
0
  ret.ReturnCode =
476
0
      wrap(smartcard, SCardListReaderGroupsA, operation->hContext, (LPSTR)&mszGroups, &cchGroups);
477
0
  if ((ret.ReturnCode == SCARD_S_SUCCESS) && (cchGroups == SCARD_AUTOALLOCATE))
478
0
    return SCARD_F_UNKNOWN_ERROR;
479
480
0
  ret.msz = (BYTE*)mszGroups;
481
0
  ret.cBytes = cchGroups;
482
483
0
  status = smartcard_pack_list_reader_groups_return(out, &ret, FALSE);
484
485
0
  if (status != SCARD_S_SUCCESS)
486
0
    return status;
487
488
0
  if (mszGroups)
489
0
    wrap(smartcard, SCardFreeMemory, operation->hContext, mszGroups);
490
491
0
  return ret.ReturnCode;
492
0
}
493
494
WINPR_ATTR_NODISCARD static LONG smartcard_ListReaderGroupsW_Call(scard_call_context* smartcard,
495
                                                                  wStream* out,
496
                                                                  SMARTCARD_OPERATION* operation)
497
0
{
498
0
  LONG status = 0;
499
0
  ListReaderGroups_Return ret = WINPR_C_ARRAY_INIT;
500
0
  LPWSTR mszGroups = nullptr;
501
0
  DWORD cchGroups = 0;
502
503
0
  WINPR_ASSERT(smartcard);
504
0
  WINPR_ASSERT(out);
505
0
  WINPR_ASSERT(operation);
506
507
0
  cchGroups = SCARD_AUTOALLOCATE;
508
0
  status = ret.ReturnCode = wrap(smartcard, SCardListReaderGroupsW, operation->hContext,
509
0
                                 (LPWSTR)&mszGroups, &cchGroups);
510
0
  if ((ret.ReturnCode == SCARD_S_SUCCESS) && (cchGroups == SCARD_AUTOALLOCATE))
511
0
    return SCARD_F_UNKNOWN_ERROR;
512
513
  /* cchGroups is only valid if the call succeeded */
514
0
  if (status != SCARD_S_SUCCESS)
515
0
    return status;
516
517
0
  ret.msz = (BYTE*)mszGroups;
518
519
0
  WINPR_ASSERT(cchGroups < SCARD_AUTOALLOCATE / sizeof(WCHAR));
520
0
  const size_t blen = sizeof(WCHAR) * cchGroups;
521
0
  WINPR_ASSERT(blen <= UINT32_MAX);
522
0
  ret.cBytes = (UINT32)blen;
523
524
0
  status = smartcard_pack_list_reader_groups_return(out, &ret, TRUE);
525
526
0
  if (status != SCARD_S_SUCCESS)
527
0
    return status;
528
529
0
  if (mszGroups)
530
0
    wrap(smartcard, SCardFreeMemory, operation->hContext, mszGroups);
531
532
0
  return ret.ReturnCode;
533
0
}
534
535
WINPR_ATTR_NODISCARD
536
static BOOL filter_match(wLinkedList* list, LPCSTR reader, size_t readerLen)
537
0
{
538
0
  if (readerLen < 1)
539
0
    return FALSE;
540
541
0
  LinkedList_Enumerator_Reset(list);
542
543
0
  while (LinkedList_Enumerator_MoveNext(list))
544
0
  {
545
0
    const char* filter = LinkedList_Enumerator_Current(list);
546
547
0
    if (filter)
548
0
    {
549
0
      if (strstr(reader, filter) != nullptr)
550
0
        return TRUE;
551
0
    }
552
0
  }
553
554
0
  return FALSE;
555
0
}
556
557
WINPR_ATTR_NODISCARD
558
static DWORD filter_device_by_name_a(wLinkedList* list, LPSTR* mszReaders, DWORD cchReaders)
559
0
{
560
0
  size_t rpos = 0;
561
0
  size_t wpos = 0;
562
563
0
  if (*mszReaders == nullptr || LinkedList_Count(list) < 1)
564
0
    return cchReaders;
565
566
0
  do
567
0
  {
568
0
    LPCSTR rreader = &(*mszReaders)[rpos];
569
0
    LPSTR wreader = &(*mszReaders)[wpos];
570
0
    size_t readerLen = strnlen(rreader, cchReaders - rpos);
571
572
0
    rpos += readerLen + 1;
573
574
0
    if (filter_match(list, rreader, readerLen))
575
0
    {
576
0
      if (rreader != wreader)
577
0
        memmove(wreader, rreader, readerLen + 1);
578
579
0
      wpos += readerLen + 1;
580
0
    }
581
0
  } while (rpos < cchReaders);
582
583
  /* this string must be double 0 terminated */
584
0
  if (rpos != wpos)
585
0
  {
586
0
    if (wpos >= cchReaders)
587
0
      return 0;
588
589
0
    (*mszReaders)[wpos++] = '\0';
590
0
  }
591
592
0
  return (DWORD)wpos;
593
0
}
594
595
WINPR_ATTR_NODISCARD
596
static DWORD filter_device_by_name_w(wLinkedList* list, LPWSTR* mszReaders, DWORD cchReaders)
597
0
{
598
0
  DWORD rc = 0;
599
0
  LPSTR readers = nullptr;
600
601
0
  if (LinkedList_Count(list) < 1)
602
0
    return cchReaders;
603
604
0
  readers = ConvertMszWCharNToUtf8Alloc(*mszReaders, cchReaders, nullptr);
605
606
0
  if (!readers)
607
0
  {
608
0
    free(readers);
609
0
    return 0;
610
0
  }
611
612
0
  *mszReaders = nullptr;
613
0
  rc = filter_device_by_name_a(list, &readers, cchReaders);
614
615
0
  *mszReaders = ConvertMszUtf8NToWCharAlloc(readers, rc, nullptr);
616
0
  if (!*mszReaders)
617
0
    rc = 0;
618
619
0
  free(readers);
620
0
  return rc;
621
0
}
622
623
WINPR_ATTR_NODISCARD static LONG smartcard_ListReadersA_Call(scard_call_context* smartcard,
624
                                                             wStream* out,
625
                                                             SMARTCARD_OPERATION* operation)
626
0
{
627
0
  ListReaders_Return ret = WINPR_C_ARRAY_INIT;
628
0
  LPSTR mszReaders = nullptr;
629
630
0
  WINPR_ASSERT(smartcard);
631
0
  WINPR_ASSERT(out);
632
0
  WINPR_ASSERT(operation);
633
634
0
  ListReaders_Call* call = &operation->call.listReaders;
635
0
  DWORD cchReaders = SCARD_AUTOALLOCATE;
636
0
  LONG status = ret.ReturnCode = wrap(smartcard, SCardListReadersA, operation->hContext,
637
0
                                      (LPCSTR)call->mszGroups, (LPSTR)&mszReaders, &cchReaders);
638
0
  if (status == SCARD_S_SUCCESS)
639
0
  {
640
0
    if (cchReaders == SCARD_AUTOALLOCATE)
641
0
      status = SCARD_F_UNKNOWN_ERROR;
642
0
  }
643
644
0
  if (status != SCARD_S_SUCCESS)
645
0
  {
646
0
    (void)scard_log_status_error_wlog(smartcard->log, "SCardListReadersA", status);
647
0
    return smartcard_pack_list_readers_return(out, &ret, FALSE);
648
0
  }
649
650
0
  void* original = mszReaders;
651
0
  cchReaders = filter_device_by_name_a(smartcard->names, &mszReaders, cchReaders);
652
0
  ret.msz = (BYTE*)mszReaders;
653
0
  ret.cBytes = cchReaders;
654
655
0
  status = smartcard_pack_list_readers_return(out, &ret, FALSE);
656
0
  if (original)
657
0
    wrap(smartcard, SCardFreeMemory, operation->hContext, original);
658
659
0
  if (status != SCARD_S_SUCCESS)
660
0
    return scard_log_status_error_wlog(smartcard->log, "smartcard_pack_list_readers_return",
661
0
                                       status);
662
663
0
  return ret.ReturnCode;
664
0
}
665
666
WINPR_ATTR_NODISCARD static LONG smartcard_ListReadersW_Call(scard_call_context* smartcard,
667
                                                             wStream* out,
668
                                                             SMARTCARD_OPERATION* operation)
669
0
{
670
0
  LONG status = 0;
671
0
  ListReaders_Return ret = WINPR_C_ARRAY_INIT;
672
0
  DWORD cchReaders = 0;
673
0
  ListReaders_Call* call = nullptr;
674
0
  union
675
0
  {
676
0
    const BYTE* bp;
677
0
    const char* sz;
678
0
    const WCHAR* wz;
679
0
  } string;
680
0
  union
681
0
  {
682
0
    WCHAR** ppw;
683
0
    WCHAR* pw;
684
0
    CHAR* pc;
685
0
    BYTE* pb;
686
0
  } mszReaders;
687
688
0
  WINPR_ASSERT(smartcard);
689
0
  WINPR_ASSERT(operation);
690
691
0
  call = &operation->call.listReaders;
692
693
0
  string.bp = call->mszGroups;
694
0
  cchReaders = SCARD_AUTOALLOCATE;
695
0
  status = ret.ReturnCode = wrap(smartcard, SCardListReadersW, operation->hContext, string.wz,
696
0
                                 (LPWSTR)&mszReaders.pw, &cchReaders);
697
0
  if (status == SCARD_S_SUCCESS)
698
0
  {
699
0
    if (cchReaders == SCARD_AUTOALLOCATE)
700
0
      status = SCARD_F_UNKNOWN_ERROR;
701
0
  }
702
703
0
  if (status != SCARD_S_SUCCESS)
704
0
  {
705
0
    (void)scard_log_status_error_wlog(smartcard->log, "SCardListReadersW", status);
706
0
    return smartcard_pack_list_readers_return(out, &ret, TRUE);
707
0
  }
708
709
0
  void* original = mszReaders.pb;
710
0
  cchReaders = filter_device_by_name_w(smartcard->names, &mszReaders.pw, cchReaders);
711
0
  ret.msz = mszReaders.pb;
712
0
  ret.cBytes = cchReaders * sizeof(WCHAR);
713
0
  status = smartcard_pack_list_readers_return(out, &ret, TRUE);
714
715
0
  if (original)
716
0
    wrap(smartcard, SCardFreeMemory, operation->hContext, original);
717
718
0
  if (status != SCARD_S_SUCCESS)
719
0
    return status;
720
721
0
  return ret.ReturnCode;
722
0
}
723
724
WINPR_ATTR_NODISCARD static LONG
725
smartcard_IntroduceReaderGroupA_Call(scard_call_context* smartcard, WINPR_ATTR_UNUSED wStream* out,
726
                                     SMARTCARD_OPERATION* operation)
727
0
{
728
0
  Long_Return ret = WINPR_C_ARRAY_INIT;
729
0
  ContextAndStringA_Call* call = nullptr;
730
731
0
  WINPR_ASSERT(smartcard);
732
0
  WINPR_ASSERT(out);
733
0
  WINPR_ASSERT(operation);
734
735
0
  call = &operation->call.contextAndStringA;
736
0
  ret.ReturnCode = wrap(smartcard, SCardIntroduceReaderGroupA, operation->hContext, call->sz);
737
0
  scard_log_status_error_wlog(smartcard->log, "SCardIntroduceReaderGroupA", ret.ReturnCode);
738
0
  smartcard_trace_long_return_int(smartcard->log, &ret, "IntroduceReaderGroupA");
739
0
  return ret.ReturnCode;
740
0
}
741
742
WINPR_ATTR_NODISCARD static LONG
743
smartcard_IntroduceReaderGroupW_Call(scard_call_context* smartcard, WINPR_ATTR_UNUSED wStream* out,
744
                                     SMARTCARD_OPERATION* operation)
745
0
{
746
0
  Long_Return ret = WINPR_C_ARRAY_INIT;
747
0
  ContextAndStringW_Call* call = nullptr;
748
749
0
  WINPR_ASSERT(smartcard);
750
0
  WINPR_ASSERT(out);
751
0
  WINPR_ASSERT(operation);
752
753
0
  call = &operation->call.contextAndStringW;
754
0
  ret.ReturnCode = wrap(smartcard, SCardIntroduceReaderGroupW, operation->hContext, call->sz);
755
0
  scard_log_status_error_wlog(smartcard->log, "SCardIntroduceReaderGroupW", ret.ReturnCode);
756
0
  smartcard_trace_long_return_int(smartcard->log, &ret, "IntroduceReaderGroupW");
757
0
  return ret.ReturnCode;
758
0
}
759
760
WINPR_ATTR_NODISCARD static LONG smartcard_IntroduceReaderA_Call(scard_call_context* smartcard,
761
                                                                 WINPR_ATTR_UNUSED wStream* out,
762
                                                                 SMARTCARD_OPERATION* operation)
763
0
{
764
0
  Long_Return ret = WINPR_C_ARRAY_INIT;
765
0
  ContextAndTwoStringA_Call* call = nullptr;
766
767
0
  WINPR_ASSERT(smartcard);
768
0
  WINPR_ASSERT(out);
769
0
  WINPR_ASSERT(operation);
770
771
0
  call = &operation->call.contextAndTwoStringA;
772
0
  ret.ReturnCode =
773
0
      wrap(smartcard, SCardIntroduceReaderA, operation->hContext, call->sz1, call->sz2);
774
0
  scard_log_status_error_wlog(smartcard->log, "SCardIntroduceReaderA", ret.ReturnCode);
775
0
  smartcard_trace_long_return_int(smartcard->log, &ret, "IntroduceReaderA");
776
0
  return ret.ReturnCode;
777
0
}
778
779
WINPR_ATTR_NODISCARD static LONG smartcard_IntroduceReaderW_Call(scard_call_context* smartcard,
780
                                                                 WINPR_ATTR_UNUSED wStream* out,
781
                                                                 SMARTCARD_OPERATION* operation)
782
0
{
783
0
  Long_Return ret = WINPR_C_ARRAY_INIT;
784
0
  ContextAndTwoStringW_Call* call = nullptr;
785
786
0
  WINPR_ASSERT(smartcard);
787
0
  WINPR_ASSERT(out);
788
0
  WINPR_ASSERT(operation);
789
790
0
  call = &operation->call.contextAndTwoStringW;
791
0
  ret.ReturnCode =
792
0
      wrap(smartcard, SCardIntroduceReaderW, operation->hContext, call->sz1, call->sz2);
793
0
  scard_log_status_error_wlog(smartcard->log, "SCardIntroduceReaderW", ret.ReturnCode);
794
0
  smartcard_trace_long_return_int(smartcard->log, &ret, "IntroduceReaderW");
795
0
  return ret.ReturnCode;
796
0
}
797
798
WINPR_ATTR_NODISCARD static LONG smartcard_ForgetReaderA_Call(scard_call_context* smartcard,
799
                                                              WINPR_ATTR_UNUSED wStream* out,
800
                                                              SMARTCARD_OPERATION* operation)
801
0
{
802
0
  Long_Return ret = WINPR_C_ARRAY_INIT;
803
0
  ContextAndStringA_Call* call = nullptr;
804
805
0
  WINPR_ASSERT(smartcard);
806
0
  WINPR_ASSERT(out);
807
0
  WINPR_ASSERT(operation);
808
809
0
  call = &operation->call.contextAndStringA;
810
0
  ret.ReturnCode = wrap(smartcard, SCardForgetReaderA, operation->hContext, call->sz);
811
0
  scard_log_status_error_wlog(smartcard->log, "SCardForgetReaderA", ret.ReturnCode);
812
0
  smartcard_trace_long_return_int(smartcard->log, &ret, "SCardForgetReaderA");
813
0
  return ret.ReturnCode;
814
0
}
815
816
WINPR_ATTR_NODISCARD static LONG smartcard_ForgetReaderW_Call(scard_call_context* smartcard,
817
                                                              WINPR_ATTR_UNUSED wStream* out,
818
                                                              SMARTCARD_OPERATION* operation)
819
0
{
820
0
  Long_Return ret = WINPR_C_ARRAY_INIT;
821
0
  ContextAndStringW_Call* call = nullptr;
822
823
0
  WINPR_ASSERT(smartcard);
824
0
  WINPR_ASSERT(out);
825
0
  WINPR_ASSERT(operation);
826
827
0
  call = &operation->call.contextAndStringW;
828
0
  ret.ReturnCode = wrap(smartcard, SCardForgetReaderW, operation->hContext, call->sz);
829
0
  scard_log_status_error_wlog(smartcard->log, "SCardForgetReaderW", ret.ReturnCode);
830
0
  smartcard_trace_long_return_int(smartcard->log, &ret, "SCardForgetReaderW");
831
0
  return ret.ReturnCode;
832
0
}
833
834
WINPR_ATTR_NODISCARD static LONG smartcard_AddReaderToGroupA_Call(scard_call_context* smartcard,
835
                                                                  WINPR_ATTR_UNUSED wStream* out,
836
                                                                  SMARTCARD_OPERATION* operation)
837
0
{
838
0
  Long_Return ret = WINPR_C_ARRAY_INIT;
839
0
  ContextAndTwoStringA_Call* call = nullptr;
840
841
0
  WINPR_ASSERT(smartcard);
842
0
  WINPR_ASSERT(out);
843
0
  WINPR_ASSERT(operation);
844
845
0
  call = &operation->call.contextAndTwoStringA;
846
0
  ret.ReturnCode =
847
0
      wrap(smartcard, SCardAddReaderToGroupA, operation->hContext, call->sz1, call->sz2);
848
0
  scard_log_status_error_wlog(smartcard->log, "SCardAddReaderToGroupA", ret.ReturnCode);
849
0
  smartcard_trace_long_return_int(smartcard->log, &ret, "SCardAddReaderToGroupA");
850
0
  return ret.ReturnCode;
851
0
}
852
853
WINPR_ATTR_NODISCARD static LONG smartcard_AddReaderToGroupW_Call(scard_call_context* smartcard,
854
                                                                  WINPR_ATTR_UNUSED wStream* out,
855
                                                                  SMARTCARD_OPERATION* operation)
856
0
{
857
0
  Long_Return ret = WINPR_C_ARRAY_INIT;
858
0
  ContextAndTwoStringW_Call* call = nullptr;
859
860
0
  WINPR_ASSERT(smartcard);
861
0
  WINPR_ASSERT(out);
862
0
  WINPR_ASSERT(operation);
863
864
0
  call = &operation->call.contextAndTwoStringW;
865
0
  ret.ReturnCode =
866
0
      wrap(smartcard, SCardAddReaderToGroupW, operation->hContext, call->sz1, call->sz2);
867
0
  scard_log_status_error_wlog(smartcard->log, "SCardAddReaderToGroupW", ret.ReturnCode);
868
0
  smartcard_trace_long_return_int(smartcard->log, &ret, "SCardAddReaderToGroupA");
869
0
  return ret.ReturnCode;
870
0
}
871
872
WINPR_ATTR_NODISCARD static LONG
873
smartcard_RemoveReaderFromGroupA_Call(scard_call_context* smartcard, WINPR_ATTR_UNUSED wStream* out,
874
                                      SMARTCARD_OPERATION* operation)
875
0
{
876
0
  Long_Return ret = WINPR_C_ARRAY_INIT;
877
0
  ContextAndTwoStringA_Call* call = nullptr;
878
879
0
  WINPR_ASSERT(smartcard);
880
0
  WINPR_ASSERT(out);
881
0
  WINPR_ASSERT(operation);
882
883
0
  call = &operation->call.contextAndTwoStringA;
884
0
  ret.ReturnCode =
885
0
      wrap(smartcard, SCardRemoveReaderFromGroupA, operation->hContext, call->sz1, call->sz2);
886
0
  scard_log_status_error_wlog(smartcard->log, "SCardRemoveReaderFromGroupA", ret.ReturnCode);
887
0
  smartcard_trace_long_return_int(smartcard->log, &ret, "SCardRemoveReaderFromGroupA");
888
0
  return ret.ReturnCode;
889
0
}
890
891
WINPR_ATTR_NODISCARD static LONG
892
smartcard_RemoveReaderFromGroupW_Call(scard_call_context* smartcard, WINPR_ATTR_UNUSED wStream* out,
893
                                      SMARTCARD_OPERATION* operation)
894
0
{
895
0
  Long_Return ret = WINPR_C_ARRAY_INIT;
896
0
  ContextAndTwoStringW_Call* call = nullptr;
897
898
0
  WINPR_ASSERT(smartcard);
899
0
  WINPR_ASSERT(out);
900
0
  WINPR_ASSERT(operation);
901
902
0
  call = &operation->call.contextAndTwoStringW;
903
0
  ret.ReturnCode =
904
0
      wrap(smartcard, SCardRemoveReaderFromGroupW, operation->hContext, call->sz1, call->sz2);
905
0
  scard_log_status_error_wlog(smartcard->log, "SCardRemoveReaderFromGroupW", ret.ReturnCode);
906
0
  smartcard_trace_long_return_int(smartcard->log, &ret, "SCardRemoveReaderFromGroupW");
907
0
  return ret.ReturnCode;
908
0
}
909
910
WINPR_ATTR_NODISCARD static LONG smartcard_LocateCardsA_Call(scard_call_context* smartcard,
911
                                                             wStream* out,
912
                                                             SMARTCARD_OPERATION* operation)
913
0
{
914
0
  LONG status = 0;
915
0
  LocateCards_Return ret = WINPR_C_ARRAY_INIT;
916
0
  LocateCardsA_Call* call = nullptr;
917
918
0
  WINPR_ASSERT(smartcard);
919
0
  WINPR_ASSERT(operation);
920
921
0
  call = &operation->call.locateCardsA;
922
923
0
  ret.ReturnCode = wrap(smartcard, SCardLocateCardsA, operation->hContext, call->mszCards,
924
0
                        call->rgReaderStates, call->cReaders);
925
0
  scard_log_status_error_wlog(smartcard->log, "SCardLocateCardsA", ret.ReturnCode);
926
0
  ret.rgReaderStates = nullptr;
927
928
0
  if (call->cReaders > 0)
929
0
  {
930
0
    ret.rgReaderStates =
931
0
        (ReaderState_Return*)calloc(call->cReaders, sizeof(ReaderState_Return));
932
933
0
    if (!ret.rgReaderStates)
934
0
      return STATUS_NO_MEMORY;
935
0
    ret.cReaders = call->cReaders;
936
0
  }
937
938
0
  for (UINT32 x = 0; x < ret.cReaders; x++)
939
0
  {
940
0
    const LPSCARD_READERSTATEA cstate = &call->rgReaderStates[x];
941
0
    ReaderState_Return* cur = &ret.rgReaderStates[x];
942
943
0
    cur->dwCurrentState = cstate->dwCurrentState;
944
0
    cur->dwEventState = cstate->dwEventState;
945
0
    cur->cbAtr = cstate->cbAtr;
946
0
    CopyMemory(&(cur->rgbAtr), &(cstate->rgbAtr), sizeof(cur->rgbAtr));
947
0
    if (!smartcard_reader_state_return_is_valid(x, cur))
948
0
    {
949
0
      free(ret.rgReaderStates);
950
0
      return SCARD_E_INVALID_ATR;
951
0
    }
952
0
  }
953
954
0
  status = smartcard_pack_locate_cards_return(out, &ret);
955
0
  free(ret.rgReaderStates);
956
957
0
  if (status != SCARD_S_SUCCESS)
958
0
    return status;
959
960
0
  return ret.ReturnCode;
961
0
}
962
963
WINPR_ATTR_NODISCARD static LONG smartcard_LocateCardsW_Call(scard_call_context* smartcard,
964
                                                             wStream* out,
965
                                                             SMARTCARD_OPERATION* operation)
966
0
{
967
0
  LONG status = 0;
968
0
  LocateCards_Return ret = WINPR_C_ARRAY_INIT;
969
970
0
  WINPR_ASSERT(smartcard);
971
0
  WINPR_ASSERT(operation);
972
973
0
  LocateCardsW_Call* call = &operation->call.locateCardsW;
974
975
0
  ret.ReturnCode = wrap(smartcard, SCardLocateCardsW, operation->hContext, call->mszCards,
976
0
                        call->rgReaderStates, call->cReaders);
977
0
  scard_log_status_error_wlog(smartcard->log, "SCardLocateCardsW", ret.ReturnCode);
978
0
  ret.rgReaderStates = nullptr;
979
980
0
  if (call->cReaders > 0)
981
0
  {
982
0
    ret.rgReaderStates =
983
0
        (ReaderState_Return*)calloc(call->cReaders, sizeof(ReaderState_Return));
984
985
0
    if (!ret.rgReaderStates)
986
0
      return STATUS_NO_MEMORY;
987
0
    ret.cReaders = call->cReaders;
988
0
  }
989
990
0
  for (UINT32 x = 0; x < ret.cReaders; x++)
991
0
  {
992
0
    const LPSCARD_READERSTATEW cstate = &call->rgReaderStates[x];
993
0
    ReaderState_Return* cur = &ret.rgReaderStates[x];
994
995
0
    cur->dwCurrentState = cstate->dwCurrentState;
996
0
    cur->dwEventState = cstate->dwEventState;
997
0
    cur->cbAtr = cstate->cbAtr;
998
0
    CopyMemory(&(cur->rgbAtr), &(cstate->rgbAtr), sizeof(cur->rgbAtr));
999
0
    if (!smartcard_reader_state_return_is_valid(x, cur))
1000
0
    {
1001
0
      free(ret.rgReaderStates);
1002
0
      return SCARD_E_INVALID_ATR;
1003
0
    }
1004
0
  }
1005
1006
0
  status = smartcard_pack_locate_cards_return(out, &ret);
1007
0
  free(ret.rgReaderStates);
1008
1009
0
  if (status != SCARD_S_SUCCESS)
1010
0
    return status;
1011
1012
0
  return ret.ReturnCode;
1013
0
}
1014
1015
WINPR_ATTR_NODISCARD static LONG smartcard_ReadCacheA_Call(scard_call_context* smartcard,
1016
                                                           wStream* out,
1017
                                                           SMARTCARD_OPERATION* operation)
1018
0
{
1019
0
  LONG status = 0;
1020
0
  BOOL autoalloc = 0;
1021
0
  ReadCache_Return ret = WINPR_C_ARRAY_INIT;
1022
0
  ReadCacheA_Call* call = nullptr;
1023
1024
0
  WINPR_ASSERT(smartcard);
1025
0
  WINPR_ASSERT(out);
1026
0
  WINPR_ASSERT(operation);
1027
1028
0
  call = &operation->call.readCacheA;
1029
0
  autoalloc = (call->Common.cbDataLen == SCARD_AUTOALLOCATE);
1030
1031
0
  if (!call->Common.fPbDataIsNULL)
1032
0
  {
1033
0
    if (!autoalloc)
1034
0
    {
1035
0
      ret.pbData = calloc(1, call->Common.cbDataLen);
1036
0
      if (!ret.pbData)
1037
0
        return SCARD_F_INTERNAL_ERROR;
1038
0
    }
1039
0
    ret.cbDataLen = call->Common.cbDataLen;
1040
0
  }
1041
1042
0
  if (autoalloc)
1043
0
    ret.ReturnCode = wrap(smartcard, SCardReadCacheA, operation->hContext,
1044
0
                          call->Common.CardIdentifier, call->Common.FreshnessCounter,
1045
0
                          call->szLookupName, (BYTE*)&ret.pbData, &ret.cbDataLen);
1046
0
  else
1047
0
    ret.ReturnCode =
1048
0
        wrap(smartcard, SCardReadCacheA, operation->hContext, call->Common.CardIdentifier,
1049
0
             call->Common.FreshnessCounter, call->szLookupName, ret.pbData, &ret.cbDataLen);
1050
1051
0
  WLog_Print(smartcard->log, WLOG_TRACE, "key=%s, length=%" PRIu32, call->szLookupName,
1052
0
             ret.cbDataLen);
1053
1054
0
  if ((ret.ReturnCode != SCARD_W_CACHE_ITEM_NOT_FOUND) &&
1055
0
      (ret.ReturnCode != SCARD_W_CACHE_ITEM_STALE))
1056
0
  {
1057
0
    scard_log_status_error_wlog(smartcard->log, "SCardReadCacheA", ret.ReturnCode);
1058
0
  }
1059
1060
0
  status = smartcard_pack_read_cache_return(out, &ret);
1061
0
  if (autoalloc)
1062
0
    wrap(smartcard, SCardFreeMemory, operation->hContext, ret.pbData);
1063
0
  else
1064
0
    free(ret.pbData);
1065
0
  if (status != SCARD_S_SUCCESS)
1066
0
    return status;
1067
1068
0
  return ret.ReturnCode;
1069
0
}
1070
1071
WINPR_ATTR_NODISCARD static LONG smartcard_ReadCacheW_Call(scard_call_context* smartcard,
1072
                                                           wStream* out,
1073
                                                           SMARTCARD_OPERATION* operation)
1074
0
{
1075
0
  LONG status = 0;
1076
0
  ReadCache_Return ret = WINPR_C_ARRAY_INIT;
1077
0
  ReadCacheW_Call* call = nullptr;
1078
1079
0
  WINPR_ASSERT(smartcard);
1080
0
  WINPR_ASSERT(out);
1081
0
  WINPR_ASSERT(operation);
1082
1083
0
  call = &operation->call.readCacheW;
1084
1085
0
  if (!call->Common.fPbDataIsNULL)
1086
0
    ret.cbDataLen = SCARD_AUTOALLOCATE;
1087
1088
0
  ret.ReturnCode =
1089
0
      wrap(smartcard, SCardReadCacheW, operation->hContext, call->Common.CardIdentifier,
1090
0
           call->Common.FreshnessCounter, call->szLookupName, (BYTE*)&ret.pbData, &ret.cbDataLen);
1091
1092
0
  if (WLog_IsLevelActive(smartcard->log, WLOG_TRACE))
1093
0
  {
1094
0
    char buffer[128] = WINPR_C_ARRAY_INIT;
1095
0
    (void)ConvertWCharToUtf8(call->szLookupName, buffer, sizeof(buffer));
1096
0
    WLog_Print(smartcard->log, WLOG_TRACE, "key=%s, length=%" PRIu32, buffer, ret.cbDataLen);
1097
0
  }
1098
0
  if ((ret.ReturnCode != SCARD_W_CACHE_ITEM_NOT_FOUND) &&
1099
0
      (ret.ReturnCode != SCARD_W_CACHE_ITEM_STALE))
1100
0
  {
1101
0
    scard_log_status_error_wlog(smartcard->log, "SCardReadCacheW", ret.ReturnCode);
1102
0
  }
1103
1104
0
  status = smartcard_pack_read_cache_return(out, &ret);
1105
1106
0
  wrap(smartcard, SCardFreeMemory, operation->hContext, ret.pbData);
1107
1108
0
  if (status != SCARD_S_SUCCESS)
1109
0
    return status;
1110
1111
0
  return ret.ReturnCode;
1112
0
}
1113
1114
WINPR_ATTR_NODISCARD static LONG smartcard_WriteCacheA_Call(scard_call_context* smartcard,
1115
                                                            WINPR_ATTR_UNUSED wStream* out,
1116
                                                            SMARTCARD_OPERATION* operation)
1117
0
{
1118
0
  Long_Return ret = WINPR_C_ARRAY_INIT;
1119
0
  WriteCacheA_Call* call = nullptr;
1120
1121
0
  WINPR_ASSERT(smartcard);
1122
0
  WINPR_ASSERT(out);
1123
0
  WINPR_ASSERT(operation);
1124
1125
0
  call = &operation->call.writeCacheA;
1126
1127
0
  ret.ReturnCode = wrap(smartcard, SCardWriteCacheA, operation->hContext,
1128
0
                        call->Common.CardIdentifier, call->Common.FreshnessCounter,
1129
0
                        call->szLookupName, call->Common.pbData, call->Common.cbDataLen);
1130
0
  scard_log_status_error_wlog(smartcard->log, "SCardWriteCacheA", ret.ReturnCode);
1131
0
  smartcard_trace_long_return_int(smartcard->log, &ret, "SCardWriteCacheA");
1132
0
  WLog_Print(smartcard->log, WLOG_TRACE, "key=%s, length=%" PRIu32, call->szLookupName,
1133
0
             call->Common.cbDataLen);
1134
0
  return ret.ReturnCode;
1135
0
}
1136
1137
WINPR_ATTR_NODISCARD static LONG smartcard_WriteCacheW_Call(scard_call_context* smartcard,
1138
                                                            WINPR_ATTR_UNUSED wStream* out,
1139
                                                            SMARTCARD_OPERATION* operation)
1140
0
{
1141
0
  Long_Return ret = WINPR_C_ARRAY_INIT;
1142
0
  WriteCacheW_Call* call = nullptr;
1143
1144
0
  WINPR_ASSERT(smartcard);
1145
0
  WINPR_ASSERT(out);
1146
0
  WINPR_ASSERT(operation);
1147
1148
0
  call = &operation->call.writeCacheW;
1149
1150
0
  ret.ReturnCode = wrap(smartcard, SCardWriteCacheW, operation->hContext,
1151
0
                        call->Common.CardIdentifier, call->Common.FreshnessCounter,
1152
0
                        call->szLookupName, call->Common.pbData, call->Common.cbDataLen);
1153
0
  scard_log_status_error_wlog(smartcard->log, "SCardWriteCacheW", ret.ReturnCode);
1154
0
  smartcard_trace_long_return_int(smartcard->log, &ret, "SCardWriteCacheW");
1155
1156
0
  if (WLog_IsLevelActive(smartcard->log, WLOG_TRACE))
1157
0
  {
1158
0
    char buffer[128] = WINPR_C_ARRAY_INIT;
1159
0
    (void)ConvertWCharToUtf8(call->szLookupName, buffer, sizeof(buffer));
1160
0
    WLog_Print(smartcard->log, WLOG_TRACE, "key=%s, length=%" PRIu32, buffer,
1161
0
               call->Common.cbDataLen);
1162
0
  }
1163
0
  return ret.ReturnCode;
1164
0
}
1165
1166
WINPR_ATTR_NODISCARD static LONG smartcard_GetTransmitCount_Call(scard_call_context* smartcard,
1167
                                                                 wStream* out,
1168
                                                                 SMARTCARD_OPERATION* operation)
1169
0
{
1170
0
  LONG status = 0;
1171
0
  GetTransmitCount_Return ret = WINPR_C_ARRAY_INIT;
1172
1173
0
  WINPR_ASSERT(smartcard);
1174
0
  WINPR_ASSERT(out);
1175
0
  WINPR_ASSERT(operation);
1176
1177
0
  ret.ReturnCode = wrap(smartcard, SCardGetTransmitCount, operation->hCard, &ret.cTransmitCount);
1178
0
  scard_log_status_error_wlog(smartcard->log, "SCardGetTransmitCount", ret.ReturnCode);
1179
0
  status = smartcard_pack_get_transmit_count_return(out, &ret);
1180
0
  if (status != SCARD_S_SUCCESS)
1181
0
    return status;
1182
1183
0
  return ret.ReturnCode;
1184
0
}
1185
1186
WINPR_ATTR_NODISCARD static LONG smartcard_ReleaseStartedEvent_Call(scard_call_context* smartcard,
1187
                                                                    wStream* out,
1188
                                                                    SMARTCARD_OPERATION* operation)
1189
0
{
1190
0
  WINPR_UNUSED(smartcard);
1191
0
  WINPR_UNUSED(out);
1192
0
  WINPR_UNUSED(operation);
1193
1194
0
  WLog_Print(smartcard->log, WLOG_WARN,
1195
0
             "According to [MS-RDPESC] 3.1.4 Message Processing Events and Sequencing Rules "
1196
0
             "this is not supported?!?");
1197
0
  return SCARD_E_UNSUPPORTED_FEATURE;
1198
0
}
1199
1200
WINPR_ATTR_NODISCARD static LONG smartcard_GetReaderIcon_Call(scard_call_context* smartcard,
1201
                                                              wStream* out,
1202
                                                              SMARTCARD_OPERATION* operation)
1203
0
{
1204
0
  LONG status = 0;
1205
0
  GetReaderIcon_Return ret = WINPR_C_ARRAY_INIT;
1206
0
  GetReaderIcon_Call* call = nullptr;
1207
1208
0
  WINPR_ASSERT(smartcard);
1209
0
  WINPR_ASSERT(out);
1210
0
  WINPR_ASSERT(operation);
1211
1212
0
  call = &operation->call.getReaderIcon;
1213
1214
0
  ret.cbDataLen = SCARD_AUTOALLOCATE;
1215
0
  ret.ReturnCode = wrap(smartcard, SCardGetReaderIconW, operation->hContext, call->szReaderName,
1216
0
                        (LPBYTE)&ret.pbData, &ret.cbDataLen);
1217
0
  scard_log_status_error_wlog(smartcard->log, "SCardGetReaderIconW", ret.ReturnCode);
1218
0
  if ((ret.ReturnCode == SCARD_S_SUCCESS) && (ret.cbDataLen == SCARD_AUTOALLOCATE))
1219
0
    return SCARD_F_UNKNOWN_ERROR;
1220
1221
0
  status = smartcard_pack_get_reader_icon_return(out, &ret);
1222
0
  wrap(smartcard, SCardFreeMemory, operation->hContext, ret.pbData);
1223
0
  if (status != SCARD_S_SUCCESS)
1224
0
    return status;
1225
1226
0
  return ret.ReturnCode;
1227
0
}
1228
1229
WINPR_ATTR_NODISCARD static LONG smartcard_GetDeviceTypeId_Call(scard_call_context* smartcard,
1230
                                                                wStream* out,
1231
                                                                SMARTCARD_OPERATION* operation)
1232
0
{
1233
0
  LONG status = 0;
1234
0
  GetDeviceTypeId_Return ret = WINPR_C_ARRAY_INIT;
1235
0
  GetDeviceTypeId_Call* call = nullptr;
1236
1237
0
  WINPR_ASSERT(smartcard);
1238
0
  WINPR_ASSERT(out);
1239
0
  WINPR_ASSERT(operation);
1240
1241
0
  call = &operation->call.getDeviceTypeId;
1242
1243
0
  ret.ReturnCode = wrap(smartcard, SCardGetDeviceTypeIdW, operation->hContext, call->szReaderName,
1244
0
                        &ret.dwDeviceId);
1245
0
  scard_log_status_error_wlog(smartcard->log, "SCardGetDeviceTypeIdW", ret.ReturnCode);
1246
1247
0
  status = smartcard_pack_device_type_id_return(out, &ret);
1248
0
  if (status != SCARD_S_SUCCESS)
1249
0
    return status;
1250
1251
0
  return ret.ReturnCode;
1252
0
}
1253
1254
WINPR_ATTR_NODISCARD
1255
static BOOL smartcard_context_was_aborted(scard_call_context* smartcard)
1256
0
{
1257
0
  WINPR_ASSERT(smartcard);
1258
1259
0
  HANDLE handles[] = { smartcard->stopEvent, freerdp_abort_event(smartcard->context) };
1260
0
  const DWORD rc = WaitForMultipleObjects(ARRAYSIZE(handles), handles, FALSE, 0);
1261
0
  return (rc >= WAIT_OBJECT_0) && (rc <= WAIT_OBJECT_0 + ARRAYSIZE(handles));
1262
0
}
1263
1264
/* wait in steps to notice an abort, stopping also cancels the wait */
1265
0
#define SCARD_STATUS_CHANGE_STEP_MS 1000
1266
1267
WINPR_ATTR_NODISCARD
1268
static DWORD smartcard_status_change_step(DWORD dwTimeOut, DWORD waited)
1269
0
{
1270
0
  if (dwTimeOut == INFINITE)
1271
0
    return SCARD_STATUS_CHANGE_STEP_MS;
1272
0
  if (waited >= dwTimeOut)
1273
0
    return 0;
1274
0
  return MIN(dwTimeOut - waited, SCARD_STATUS_CHANGE_STEP_MS);
1275
0
}
1276
1277
WINPR_ATTR_NODISCARD static LONG smartcard_GetStatusChangeA_Call(scard_call_context* smartcard,
1278
                                                                 wStream* out,
1279
                                                                 SMARTCARD_OPERATION* operation)
1280
0
{
1281
0
  LONG status = STATUS_NO_MEMORY;
1282
0
  DWORD dwTimeOut = 0;
1283
0
  GetStatusChange_Return ret = WINPR_C_ARRAY_INIT;
1284
0
  GetStatusChangeA_Call* call = nullptr;
1285
0
  LPSCARD_READERSTATEA rgReaderStates = nullptr;
1286
1287
0
  WINPR_ASSERT(smartcard);
1288
0
  WINPR_ASSERT(out);
1289
0
  WINPR_ASSERT(operation);
1290
1291
0
  call = &operation->call.getStatusChangeA;
1292
0
  dwTimeOut = call->dwTimeOut;
1293
1294
0
  if (call->cReaders > 0)
1295
0
  {
1296
0
    rgReaderStates = calloc(call->cReaders, sizeof(SCARD_READERSTATEA));
1297
0
    ret.rgReaderStates =
1298
0
        (ReaderState_Return*)calloc(call->cReaders, sizeof(ReaderState_Return));
1299
0
    if (!rgReaderStates || !ret.rgReaderStates)
1300
0
      goto fail;
1301
1302
0
    ret.cReaders = call->cReaders;
1303
0
  }
1304
1305
0
  const UINT64 start = GetTickCount64();
1306
0
  for (DWORD waited = 0;;)
1307
0
  {
1308
0
    const DWORD step = smartcard_status_change_step(dwTimeOut, waited);
1309
0
    if (call->cReaders > 0)
1310
0
      memcpy(rgReaderStates, call->rgReaderStates,
1311
0
             call->cReaders * sizeof(SCARD_READERSTATEA));
1312
    /* not wrap(), do not log every step */
1313
0
    ret.ReturnCode = wrap_raw(smartcard, SCardGetStatusChangeA, operation->hContext, step,
1314
0
                              rgReaderStates, call->cReaders);
1315
0
    if (ret.ReturnCode != SCARD_E_TIMEOUT)
1316
0
      break;
1317
0
    if (dwTimeOut != INFINITE)
1318
0
    {
1319
      /* the time really waited, each step also costs a pcscd round trip */
1320
0
      waited = (DWORD)MIN(GetTickCount64() - start, dwTimeOut);
1321
0
      if (waited >= dwTimeOut)
1322
0
        break;
1323
0
    }
1324
0
    if (smartcard_context_was_aborted(smartcard))
1325
0
      break;
1326
0
  }
1327
0
  scard_log_status_error_wlog(smartcard->log, "SCardGetStatusChangeA", ret.ReturnCode);
1328
1329
0
  status = SCARD_E_INVALID_ATR;
1330
0
  for (UINT32 index = 0; index < ret.cReaders; index++)
1331
0
  {
1332
0
    const SCARD_READERSTATEA* cur = &rgReaderStates[index];
1333
0
    ReaderState_Return* rout = &ret.rgReaderStates[index];
1334
1335
0
    rout->dwCurrentState = cur->dwCurrentState;
1336
0
    rout->dwEventState = cur->dwEventState;
1337
0
    rout->cbAtr = cur->cbAtr;
1338
0
    CopyMemory(&(rout->rgbAtr), cur->rgbAtr, sizeof(rout->rgbAtr));
1339
0
    if (!smartcard_reader_state_return_is_valid(index, rout))
1340
0
      goto fail;
1341
0
  }
1342
1343
0
  status = smartcard_pack_get_status_change_return(out, &ret, FALSE);
1344
0
fail:
1345
0
  free(ret.rgReaderStates);
1346
0
  free(rgReaderStates);
1347
0
  if (status != SCARD_S_SUCCESS)
1348
0
    return status;
1349
0
  return ret.ReturnCode;
1350
0
}
1351
1352
WINPR_ATTR_NODISCARD static LONG smartcard_GetStatusChangeW_Call(scard_call_context* smartcard,
1353
                                                                 wStream* out,
1354
                                                                 SMARTCARD_OPERATION* operation)
1355
0
{
1356
0
  LONG status = STATUS_NO_MEMORY;
1357
0
  DWORD dwTimeOut = 0;
1358
0
  GetStatusChange_Return ret = WINPR_C_ARRAY_INIT;
1359
0
  LPSCARD_READERSTATEW rgReaderStates = nullptr;
1360
1361
0
  WINPR_ASSERT(smartcard);
1362
0
  WINPR_ASSERT(out);
1363
0
  WINPR_ASSERT(operation);
1364
1365
0
  GetStatusChangeW_Call* call = &operation->call.getStatusChangeW;
1366
0
  dwTimeOut = call->dwTimeOut;
1367
1368
0
  if (call->cReaders > 0)
1369
0
  {
1370
0
    rgReaderStates = calloc(call->cReaders, sizeof(SCARD_READERSTATEW));
1371
0
    ret.rgReaderStates =
1372
0
        (ReaderState_Return*)calloc(call->cReaders, sizeof(ReaderState_Return));
1373
0
    if (!rgReaderStates || !ret.rgReaderStates)
1374
0
      goto fail;
1375
1376
0
    ret.cReaders = call->cReaders;
1377
0
  }
1378
1379
0
  const UINT64 start = GetTickCount64();
1380
0
  for (DWORD waited = 0;;)
1381
0
  {
1382
0
    const DWORD step = smartcard_status_change_step(dwTimeOut, waited);
1383
0
    if (call->cReaders > 0)
1384
0
      memcpy(rgReaderStates, call->rgReaderStates,
1385
0
             call->cReaders * sizeof(SCARD_READERSTATEW));
1386
    /* not wrap(), do not log every step */
1387
0
    ret.ReturnCode = wrap_raw(smartcard, SCardGetStatusChangeW, operation->hContext, step,
1388
0
                              rgReaderStates, call->cReaders);
1389
0
    if (ret.ReturnCode != SCARD_E_TIMEOUT)
1390
0
      break;
1391
0
    if (dwTimeOut != INFINITE)
1392
0
    {
1393
      /* the time really waited, each step also costs a pcscd round trip */
1394
0
      waited = (DWORD)MIN(GetTickCount64() - start, dwTimeOut);
1395
0
      if (waited >= dwTimeOut)
1396
0
        break;
1397
0
    }
1398
0
    if (smartcard_context_was_aborted(smartcard))
1399
0
      break;
1400
0
  }
1401
0
  scard_log_status_error_wlog(smartcard->log, "SCardGetStatusChangeW", ret.ReturnCode);
1402
1403
0
  status = SCARD_E_INVALID_ATR;
1404
0
  for (UINT32 index = 0; index < ret.cReaders; index++)
1405
0
  {
1406
0
    const SCARD_READERSTATEW* cur = &rgReaderStates[index];
1407
0
    ReaderState_Return* rout = &ret.rgReaderStates[index];
1408
1409
0
    rout->dwCurrentState = cur->dwCurrentState;
1410
0
    rout->dwEventState = cur->dwEventState;
1411
0
    rout->cbAtr = cur->cbAtr;
1412
0
    CopyMemory(&(rout->rgbAtr), cur->rgbAtr, sizeof(rout->rgbAtr));
1413
0
    if (!smartcard_reader_state_return_is_valid(index, rout))
1414
0
      goto fail;
1415
0
  }
1416
1417
0
  status = smartcard_pack_get_status_change_return(out, &ret, TRUE);
1418
0
fail:
1419
0
  free(ret.rgReaderStates);
1420
0
  free(rgReaderStates);
1421
0
  if (status != SCARD_S_SUCCESS)
1422
0
    return status;
1423
0
  return ret.ReturnCode;
1424
0
}
1425
1426
WINPR_ATTR_NODISCARD static LONG smartcard_Cancel_Call(scard_call_context* smartcard,
1427
                                                       WINPR_ATTR_UNUSED wStream* out,
1428
                                                       SMARTCARD_OPERATION* operation)
1429
0
{
1430
0
  Long_Return ret = WINPR_C_ARRAY_INIT;
1431
1432
0
  WINPR_ASSERT(smartcard);
1433
0
  WINPR_ASSERT(out);
1434
0
  WINPR_ASSERT(operation);
1435
1436
0
  ret.ReturnCode = wrap(smartcard, SCardCancel, operation->hContext);
1437
0
  scard_log_status_error_wlog(smartcard->log, "SCardCancel", ret.ReturnCode);
1438
0
  smartcard_trace_long_return_int(smartcard->log, &ret, "Cancel");
1439
0
  return ret.ReturnCode;
1440
0
}
1441
1442
WINPR_ATTR_NODISCARD static LONG
1443
smartcard_ConnectA_Call(scard_call_context* smartcard, wStream* out, SMARTCARD_OPERATION* operation)
1444
0
{
1445
0
  LONG status = 0;
1446
0
  SCARDHANDLE hCard = 0;
1447
0
  Connect_Return ret = WINPR_C_ARRAY_INIT;
1448
0
  ConnectA_Call* call = nullptr;
1449
1450
0
  WINPR_ASSERT(smartcard);
1451
0
  WINPR_ASSERT(out);
1452
0
  WINPR_ASSERT(operation);
1453
1454
0
  call = &operation->call.connectA;
1455
1456
0
  if ((call->Common.dwPreferredProtocols == SCARD_PROTOCOL_UNDEFINED) &&
1457
0
      (call->Common.dwShareMode != SCARD_SHARE_DIRECT))
1458
0
  {
1459
0
    call->Common.dwPreferredProtocols = SCARD_PROTOCOL_Tx;
1460
0
  }
1461
1462
0
  ret.ReturnCode = wrap(smartcard, SCardConnectA, operation->hContext, (char*)call->szReader,
1463
0
                        call->Common.dwShareMode, call->Common.dwPreferredProtocols, &hCard,
1464
0
                        &ret.dwActiveProtocol);
1465
0
  smartcard_scard_context_native_to_redir(&(ret.hContext), operation->hContext);
1466
0
  smartcard_scard_handle_native_to_redir(&(ret.hCard), hCard);
1467
1468
0
  status = smartcard_pack_connect_return(out, &ret);
1469
0
  if (status != SCARD_S_SUCCESS)
1470
0
    goto out_fail;
1471
1472
0
  status = ret.ReturnCode;
1473
0
out_fail:
1474
1475
0
  return status;
1476
0
}
1477
1478
WINPR_ATTR_NODISCARD static LONG
1479
smartcard_ConnectW_Call(scard_call_context* smartcard, wStream* out, SMARTCARD_OPERATION* operation)
1480
0
{
1481
0
  LONG status = 0;
1482
0
  SCARDHANDLE hCard = 0;
1483
0
  Connect_Return ret = WINPR_C_ARRAY_INIT;
1484
0
  ConnectW_Call* call = nullptr;
1485
1486
0
  WINPR_ASSERT(smartcard);
1487
0
  WINPR_ASSERT(out);
1488
0
  WINPR_ASSERT(operation);
1489
1490
0
  call = &operation->call.connectW;
1491
1492
0
  if ((call->Common.dwPreferredProtocols == SCARD_PROTOCOL_UNDEFINED) &&
1493
0
      (call->Common.dwShareMode != SCARD_SHARE_DIRECT))
1494
0
  {
1495
0
    call->Common.dwPreferredProtocols = SCARD_PROTOCOL_Tx;
1496
0
  }
1497
1498
0
  ret.ReturnCode = wrap(smartcard, SCardConnectW, operation->hContext, (WCHAR*)call->szReader,
1499
0
                        call->Common.dwShareMode, call->Common.dwPreferredProtocols, &hCard,
1500
0
                        &ret.dwActiveProtocol);
1501
0
  smartcard_scard_context_native_to_redir(&(ret.hContext), operation->hContext);
1502
0
  smartcard_scard_handle_native_to_redir(&(ret.hCard), hCard);
1503
1504
0
  status = smartcard_pack_connect_return(out, &ret);
1505
0
  if (status != SCARD_S_SUCCESS)
1506
0
    goto out_fail;
1507
1508
0
  status = ret.ReturnCode;
1509
0
out_fail:
1510
1511
0
  return status;
1512
0
}
1513
1514
WINPR_ATTR_NODISCARD static LONG smartcard_Reconnect_Call(scard_call_context* smartcard,
1515
                                                          wStream* out,
1516
                                                          SMARTCARD_OPERATION* operation)
1517
0
{
1518
0
  LONG status = 0;
1519
0
  Reconnect_Return ret = WINPR_C_ARRAY_INIT;
1520
0
  Reconnect_Call* call = nullptr;
1521
1522
0
  WINPR_ASSERT(smartcard);
1523
0
  WINPR_ASSERT(out);
1524
0
  WINPR_ASSERT(operation);
1525
1526
0
  call = &operation->call.reconnect;
1527
0
  ret.ReturnCode =
1528
0
      wrap(smartcard, SCardReconnect, operation->hCard, call->dwShareMode,
1529
0
           call->dwPreferredProtocols, call->dwInitialization, &ret.dwActiveProtocol);
1530
0
  scard_log_status_error_wlog(smartcard->log, "SCardReconnect", ret.ReturnCode);
1531
0
  status = smartcard_pack_reconnect_return(out, &ret);
1532
0
  if (status != SCARD_S_SUCCESS)
1533
0
    return status;
1534
1535
0
  return ret.ReturnCode;
1536
0
}
1537
1538
WINPR_ATTR_NODISCARD static LONG smartcard_Disconnect_Call(scard_call_context* smartcard,
1539
                                                           WINPR_ATTR_UNUSED wStream* out,
1540
                                                           SMARTCARD_OPERATION* operation)
1541
0
{
1542
0
  Long_Return ret = WINPR_C_ARRAY_INIT;
1543
0
  HCardAndDisposition_Call* call = nullptr;
1544
1545
0
  WINPR_ASSERT(smartcard);
1546
0
  WINPR_ASSERT(out);
1547
0
  WINPR_ASSERT(operation);
1548
1549
0
  call = &operation->call.hCardAndDisposition;
1550
1551
0
  ret.ReturnCode = wrap(smartcard, SCardDisconnect, operation->hCard, call->dwDisposition);
1552
0
  scard_log_status_error_wlog(smartcard->log, "SCardDisconnect", ret.ReturnCode);
1553
0
  smartcard_trace_long_return_int(smartcard->log, &ret, "Disconnect");
1554
1555
0
  return ret.ReturnCode;
1556
0
}
1557
1558
WINPR_ATTR_NODISCARD static LONG smartcard_BeginTransaction_Call(scard_call_context* smartcard,
1559
                                                                 WINPR_ATTR_UNUSED wStream* out,
1560
                                                                 SMARTCARD_OPERATION* operation)
1561
0
{
1562
0
  Long_Return ret = WINPR_C_ARRAY_INIT;
1563
1564
0
  WINPR_ASSERT(smartcard);
1565
0
  WINPR_ASSERT(out);
1566
0
  WINPR_ASSERT(operation);
1567
1568
0
  ret.ReturnCode = wrap(smartcard, SCardBeginTransaction, operation->hCard);
1569
0
  scard_log_status_error_wlog(smartcard->log, "SCardBeginTransaction", ret.ReturnCode);
1570
0
  smartcard_trace_long_return_int(smartcard->log, &ret, "BeginTransaction");
1571
0
  return ret.ReturnCode;
1572
0
}
1573
1574
WINPR_ATTR_NODISCARD static LONG smartcard_EndTransaction_Call(scard_call_context* smartcard,
1575
                                                               WINPR_ATTR_UNUSED wStream* out,
1576
                                                               SMARTCARD_OPERATION* operation)
1577
0
{
1578
0
  Long_Return ret = WINPR_C_ARRAY_INIT;
1579
0
  HCardAndDisposition_Call* call = nullptr;
1580
1581
0
  WINPR_ASSERT(smartcard);
1582
0
  WINPR_ASSERT(out);
1583
0
  WINPR_ASSERT(operation);
1584
1585
0
  call = &operation->call.hCardAndDisposition;
1586
1587
0
  ret.ReturnCode = wrap(smartcard, SCardEndTransaction, operation->hCard, call->dwDisposition);
1588
0
  scard_log_status_error_wlog(smartcard->log, "SCardEndTransaction", ret.ReturnCode);
1589
0
  smartcard_trace_long_return_int(smartcard->log, &ret, "EndTransaction");
1590
0
  return ret.ReturnCode;
1591
0
}
1592
1593
WINPR_ATTR_NODISCARD static LONG smartcard_State_Call(scard_call_context* smartcard, wStream* out,
1594
                                                      SMARTCARD_OPERATION* operation)
1595
0
{
1596
0
  LONG status = 0;
1597
0
  State_Return ret = WINPR_C_ARRAY_INIT;
1598
1599
0
  WINPR_ASSERT(smartcard);
1600
0
  WINPR_ASSERT(out);
1601
0
  WINPR_ASSERT(operation);
1602
1603
0
  ret.cbAtrLen = SCARD_ATR_LENGTH;
1604
0
  ret.ReturnCode = wrap(smartcard, SCardState, operation->hCard, &ret.dwState, &ret.dwProtocol,
1605
0
                        (BYTE*)&ret.rgAtr, &ret.cbAtrLen);
1606
1607
0
  scard_log_status_error_wlog(smartcard->log, "SCardState", ret.ReturnCode);
1608
0
  status = smartcard_pack_state_return(out, &ret);
1609
0
  if (status != SCARD_S_SUCCESS)
1610
0
    return status;
1611
1612
0
  return ret.ReturnCode;
1613
0
}
1614
1615
WINPR_ATTR_NODISCARD static LONG smartcard_StatusA_Call(scard_call_context* smartcard, wStream* out,
1616
                                                        SMARTCARD_OPERATION* operation)
1617
0
{
1618
0
  LONG status = 0;
1619
0
  Status_Return ret = WINPR_C_ARRAY_INIT;
1620
0
  DWORD cchReaderLen = 0;
1621
0
  DWORD cbAtrLen = 0;
1622
0
  LPSTR mszReaderNames = nullptr;
1623
0
  Status_Call* call = nullptr;
1624
1625
0
  WINPR_ASSERT(smartcard);
1626
0
  WINPR_ASSERT(out);
1627
0
  WINPR_ASSERT(operation);
1628
1629
0
  call = &operation->call.status;
1630
1631
0
  call->cbAtrLen = 32;
1632
0
  cbAtrLen = call->cbAtrLen;
1633
1634
0
  if (call->fmszReaderNamesIsNULL)
1635
0
    cchReaderLen = 0;
1636
0
  else
1637
0
    cchReaderLen = SCARD_AUTOALLOCATE;
1638
1639
0
  status = ret.ReturnCode =
1640
0
      wrap(smartcard, SCardStatusA, operation->hCard,
1641
0
           call->fmszReaderNamesIsNULL ? nullptr : (LPSTR)&mszReaderNames, &cchReaderLen,
1642
0
           &ret.dwState, &ret.dwProtocol, cbAtrLen ? (BYTE*)&ret.pbAtr : nullptr, &cbAtrLen);
1643
1644
0
  scard_log_status_error_wlog(smartcard->log, "SCardStatusA", status);
1645
0
  if ((ret.ReturnCode == SCARD_S_SUCCESS) && (cchReaderLen == SCARD_AUTOALLOCATE))
1646
0
    return SCARD_F_UNKNOWN_ERROR;
1647
1648
0
  if (status == SCARD_S_SUCCESS)
1649
0
  {
1650
0
    if (!call->fmszReaderNamesIsNULL)
1651
0
      ret.mszReaderNames = (BYTE*)mszReaderNames;
1652
1653
0
    ret.cBytes = cchReaderLen;
1654
1655
0
    if (call->cbAtrLen)
1656
0
      ret.cbAtrLen = cbAtrLen;
1657
0
  }
1658
1659
0
  status = smartcard_pack_status_return(out, &ret, FALSE);
1660
1661
0
  if (mszReaderNames)
1662
0
    wrap(smartcard, SCardFreeMemory, operation->hContext, mszReaderNames);
1663
1664
0
  if (status != SCARD_S_SUCCESS)
1665
0
    return status;
1666
0
  return ret.ReturnCode;
1667
0
}
1668
1669
WINPR_ATTR_NODISCARD static LONG smartcard_StatusW_Call(scard_call_context* smartcard, wStream* out,
1670
                                                        SMARTCARD_OPERATION* operation)
1671
0
{
1672
0
  LONG status = 0;
1673
0
  Status_Return ret = WINPR_C_ARRAY_INIT;
1674
0
  LPWSTR mszReaderNames = nullptr;
1675
0
  Status_Call* call = nullptr;
1676
0
  DWORD cbAtrLen = 0;
1677
1678
0
  WINPR_ASSERT(smartcard);
1679
0
  WINPR_ASSERT(out);
1680
0
  WINPR_ASSERT(operation);
1681
1682
0
  call = &operation->call.status;
1683
1684
  /**
1685
   * [MS-RDPESC]
1686
   * According to 2.2.2.18 Status_Call cbAtrLen is unused an must be ignored upon receipt.
1687
   */
1688
0
  cbAtrLen = call->cbAtrLen = 32;
1689
1690
0
  if (call->fmszReaderNamesIsNULL)
1691
0
    ret.cBytes = 0;
1692
0
  else
1693
0
    ret.cBytes = SCARD_AUTOALLOCATE;
1694
1695
0
  status = ret.ReturnCode =
1696
0
      wrap(smartcard, SCardStatusW, operation->hCard,
1697
0
           call->fmszReaderNamesIsNULL ? nullptr : (LPWSTR)&mszReaderNames, &ret.cBytes,
1698
0
           &ret.dwState, &ret.dwProtocol, (BYTE*)&ret.pbAtr, &cbAtrLen);
1699
0
  scard_log_status_error_wlog(smartcard->log, "SCardStatusW", status);
1700
0
  if ((ret.ReturnCode == SCARD_S_SUCCESS) && (ret.cBytes == SCARD_AUTOALLOCATE))
1701
0
    return SCARD_F_UNKNOWN_ERROR;
1702
1703
0
  size_t blen = 0;
1704
0
  if (status == SCARD_S_SUCCESS)
1705
0
  {
1706
0
    if (!call->fmszReaderNamesIsNULL)
1707
0
      ret.mszReaderNames = (BYTE*)mszReaderNames;
1708
1709
0
    ret.cbAtrLen = cbAtrLen;
1710
0
  }
1711
1712
0
  if (ret.cBytes != SCARD_AUTOALLOCATE)
1713
0
  {
1714
    /* SCardStatusW returns number of characters, we need number of bytes */
1715
0
    WINPR_ASSERT(ret.cBytes < SCARD_AUTOALLOCATE / sizeof(WCHAR));
1716
0
    blen = sizeof(WCHAR) * ret.cBytes;
1717
0
    WINPR_ASSERT(blen <= UINT32_MAX);
1718
0
    ret.cBytes = (UINT32)blen;
1719
0
  }
1720
1721
0
  status = smartcard_pack_status_return(out, &ret, TRUE);
1722
0
  if (status != SCARD_S_SUCCESS)
1723
0
    return status;
1724
1725
0
  if (mszReaderNames)
1726
0
    wrap(smartcard, SCardFreeMemory, operation->hContext, mszReaderNames);
1727
1728
0
  return ret.ReturnCode;
1729
0
}
1730
1731
WINPR_ATTR_NODISCARD static LONG
1732
smartcard_Transmit_Call(scard_call_context* smartcard, wStream* out, SMARTCARD_OPERATION* operation)
1733
0
{
1734
0
  LONG status = 0;
1735
0
  Transmit_Return ret = WINPR_C_ARRAY_INIT;
1736
0
  Transmit_Call* call = nullptr;
1737
1738
0
  WINPR_ASSERT(smartcard);
1739
0
  WINPR_ASSERT(out);
1740
0
  WINPR_ASSERT(operation);
1741
1742
0
  call = &operation->call.transmit;
1743
0
  ret.cbRecvLength = 0;
1744
0
  ret.pbRecvBuffer = nullptr;
1745
1746
0
  if (call->cbRecvLength && !call->fpbRecvBufferIsNULL)
1747
0
  {
1748
0
    if (call->cbRecvLength >= 66560)
1749
0
      call->cbRecvLength = 66560;
1750
1751
0
    const UINT32 cbRecvLength = call->cbRecvLength;
1752
0
    ret.pbRecvBuffer = (BYTE*)calloc(1, cbRecvLength);
1753
1754
0
    if (!ret.pbRecvBuffer)
1755
0
      return STATUS_NO_MEMORY;
1756
0
    ret.cbRecvLength = cbRecvLength;
1757
0
  }
1758
1759
0
  ret.pioRecvPci = call->pioRecvPci;
1760
0
  ret.ReturnCode =
1761
0
      wrap(smartcard, SCardTransmit, operation->hCard, call->pioSendPci, call->pbSendBuffer,
1762
0
           call->cbSendLength, ret.pioRecvPci, ret.pbRecvBuffer, &(ret.cbRecvLength));
1763
1764
0
  scard_log_status_error_wlog(smartcard->log, "SCardTransmit", ret.ReturnCode);
1765
1766
0
  status = smartcard_pack_transmit_return(out, &ret);
1767
0
  free(ret.pbRecvBuffer);
1768
1769
0
  if (status != SCARD_S_SUCCESS)
1770
0
    return status;
1771
0
  return ret.ReturnCode;
1772
0
}
1773
1774
WINPR_ATTR_NODISCARD static LONG smartcard_Control_Call(scard_call_context* smartcard, wStream* out,
1775
                                                        SMARTCARD_OPERATION* operation)
1776
0
{
1777
0
  LONG status = 0;
1778
0
  Control_Return ret = WINPR_C_ARRAY_INIT;
1779
0
  Control_Call* call = nullptr;
1780
1781
0
  WINPR_ASSERT(smartcard);
1782
0
  WINPR_ASSERT(out);
1783
0
  WINPR_ASSERT(operation);
1784
1785
0
  call = &operation->call.control;
1786
0
  ret.pvOutBuffer = (BYTE*)calloc(1, call->cbOutBufferSize);
1787
1788
0
  if (!ret.pvOutBuffer)
1789
0
    return SCARD_E_NO_MEMORY;
1790
0
  ret.cbOutBufferSize = call->cbOutBufferSize;
1791
1792
0
  ret.ReturnCode =
1793
0
      wrap(smartcard, SCardControl, operation->hCard, call->dwControlCode, call->pvInBuffer,
1794
0
           call->cbInBufferSize, ret.pvOutBuffer, call->cbOutBufferSize, &ret.cbOutBufferSize);
1795
0
  scard_log_status_error_wlog(smartcard->log, "SCardControl", ret.ReturnCode);
1796
0
  status = smartcard_pack_control_return(out, &ret);
1797
1798
0
  free(ret.pvOutBuffer);
1799
0
  if (status != SCARD_S_SUCCESS)
1800
0
    return status;
1801
0
  return ret.ReturnCode;
1802
0
}
1803
1804
WINPR_ATTR_NODISCARD static LONG smartcard_GetAttrib_Call(scard_call_context* smartcard,
1805
                                                          wStream* out,
1806
                                                          SMARTCARD_OPERATION* operation)
1807
0
{
1808
0
  BOOL autoAllocate = FALSE;
1809
0
  LONG status = 0;
1810
0
  DWORD cbAttrLen = 0;
1811
0
  LPBYTE pbAttr = nullptr;
1812
0
  GetAttrib_Return ret = WINPR_C_ARRAY_INIT;
1813
0
  const GetAttrib_Call* call = nullptr;
1814
1815
0
  WINPR_ASSERT(smartcard);
1816
0
  WINPR_ASSERT(operation);
1817
1818
0
  call = &operation->call.getAttrib;
1819
1820
0
  if (!call->fpbAttrIsNULL)
1821
0
  {
1822
0
    autoAllocate = (call->cbAttrLen == SCARD_AUTOALLOCATE);
1823
0
    cbAttrLen = call->cbAttrLen;
1824
0
    if (cbAttrLen && !autoAllocate)
1825
0
    {
1826
0
      ret.pbAttr = (BYTE*)calloc(1, cbAttrLen);
1827
1828
0
      if (!ret.pbAttr)
1829
0
        return SCARD_E_NO_MEMORY;
1830
0
    }
1831
1832
0
    pbAttr = autoAllocate ? (LPBYTE) & (ret.pbAttr) : ret.pbAttr;
1833
0
  }
1834
1835
0
  ret.ReturnCode =
1836
0
      wrap(smartcard, SCardGetAttrib, operation->hCard, call->dwAttrId, pbAttr, &cbAttrLen);
1837
0
  scard_log_status_error_wlog(smartcard->log, "SCardGetAttrib", ret.ReturnCode);
1838
0
  if ((ret.ReturnCode == SCARD_S_SUCCESS) && (cbAttrLen == SCARD_AUTOALLOCATE))
1839
0
    return SCARD_F_UNKNOWN_ERROR;
1840
1841
0
  ret.cbAttrLen = cbAttrLen;
1842
1843
0
  status = smartcard_pack_get_attrib_return(out, &ret, call->dwAttrId, call->cbAttrLen);
1844
1845
0
  if (autoAllocate)
1846
0
    wrap(smartcard, SCardFreeMemory, operation->hContext, ret.pbAttr);
1847
0
  else
1848
0
    free(ret.pbAttr);
1849
0
  return status;
1850
0
}
1851
1852
WINPR_ATTR_NODISCARD static LONG smartcard_SetAttrib_Call(scard_call_context* smartcard,
1853
                                                          WINPR_ATTR_UNUSED wStream* out,
1854
                                                          SMARTCARD_OPERATION* operation)
1855
0
{
1856
0
  Long_Return ret = WINPR_C_ARRAY_INIT;
1857
0
  SetAttrib_Call* call = nullptr;
1858
1859
0
  WINPR_ASSERT(smartcard);
1860
0
  WINPR_ASSERT(out);
1861
0
  WINPR_ASSERT(operation);
1862
1863
0
  call = &operation->call.setAttrib;
1864
1865
0
  ret.ReturnCode = wrap(smartcard, SCardSetAttrib, operation->hCard, call->dwAttrId, call->pbAttr,
1866
0
                        call->cbAttrLen);
1867
0
  scard_log_status_error_wlog(smartcard->log, "SCardSetAttrib", ret.ReturnCode);
1868
0
  smartcard_trace_long_return_int(smartcard->log, &ret, "SetAttrib");
1869
1870
0
  return ret.ReturnCode;
1871
0
}
1872
1873
WINPR_ATTR_NODISCARD static LONG smartcard_AccessStartedEvent_Call(scard_call_context* smartcard,
1874
                                                                   WINPR_ATTR_UNUSED wStream* out,
1875
                                                                   SMARTCARD_OPERATION* operation)
1876
0
{
1877
0
  LONG status = SCARD_S_SUCCESS;
1878
1879
0
  WINPR_ASSERT(smartcard);
1880
0
  WINPR_ASSERT(out);
1881
0
  WINPR_UNUSED(operation);
1882
1883
0
  if (!smartcard->StartedEvent)
1884
0
    smartcard->StartedEvent = wrap_ptr(smartcard, SCardAccessStartedEvent);
1885
1886
0
  if (!smartcard->StartedEvent)
1887
0
    status = SCARD_E_NO_SERVICE;
1888
1889
0
  return status;
1890
0
}
1891
1892
WINPR_ATTR_NODISCARD static LONG smartcard_LocateCardsByATRA_Call(scard_call_context* smartcard,
1893
                                                                  wStream* out,
1894
                                                                  SMARTCARD_OPERATION* operation)
1895
0
{
1896
0
  LONG status = SCARD_E_INVALID_HANDLE;
1897
0
  GetStatusChange_Return ret = WINPR_C_ARRAY_INIT;
1898
1899
0
  WINPR_ASSERT(smartcard);
1900
0
  WINPR_ASSERT(operation);
1901
1902
0
  LocateCardsByATRA_Call* call = &operation->call.locateCardsByATRA;
1903
0
  LPSCARD_READERSTATEA states =
1904
0
      (LPSCARD_READERSTATEA)calloc(call->cReaders, sizeof(SCARD_READERSTATEA));
1905
1906
0
  if (!states)
1907
0
    return STATUS_NO_MEMORY;
1908
1909
0
  for (UINT32 i = 0; i < call->cReaders; i++)
1910
0
  {
1911
0
    const LPSCARD_READERSTATEA cstate = &call->rgReaderStates[i];
1912
0
    LPSCARD_READERSTATEA state = &states[i];
1913
1914
0
    state->szReader = cstate->szReader;
1915
0
    state->dwCurrentState = cstate->dwCurrentState;
1916
0
    state->dwEventState = cstate->dwEventState;
1917
0
    state->cbAtr = cstate->cbAtr;
1918
1919
0
    if (state->cbAtr > sizeof(state->rgbAtr))
1920
0
    {
1921
0
      WLog_WARN(SCARD_TAG, "[%" PRIu32 "] val->cbAtr=%" PRIu32 ", max=%" PRIuz, i,
1922
0
                state->cbAtr, sizeof(state->rgbAtr));
1923
0
      goto fail;
1924
0
    }
1925
0
    CopyMemory(&(state->rgbAtr), &(cstate->rgbAtr), sizeof(cstate->rgbAtr));
1926
0
  }
1927
1928
0
  status = ret.ReturnCode = wrap(smartcard, SCardGetStatusChangeA, operation->hContext,
1929
0
                                 0x000001F4, states, call->cReaders);
1930
1931
0
  scard_log_status_error_wlog(smartcard->log, "SCardGetStatusChangeA", status);
1932
0
  for (UINT32 i = 0; i < call->cAtrs; i++)
1933
0
  {
1934
0
    for (UINT32 j = 0; j < call->cReaders; j++)
1935
0
    {
1936
0
      const LocateCards_ATRMask* mask = &call->rgAtrMasks[i];
1937
0
      for (UINT32 k = 0; k < winpr_Data_Get_UINT32(&mask->cbAtr); k++)
1938
0
      {
1939
0
        if ((mask->rgbAtr[k] & mask->rgbMask[k]) !=
1940
0
            (states[j].rgbAtr[k] & mask->rgbMask[k]))
1941
0
        {
1942
0
          break;
1943
0
        }
1944
1945
0
        states[j].dwEventState |= SCARD_STATE_ATRMATCH;
1946
0
      }
1947
0
    }
1948
0
  }
1949
1950
0
  ret.rgReaderStates = nullptr;
1951
1952
0
  if (call->cReaders > 0)
1953
0
    ret.rgReaderStates =
1954
0
        (ReaderState_Return*)calloc(call->cReaders, sizeof(ReaderState_Return));
1955
1956
0
  if (!ret.rgReaderStates)
1957
0
  {
1958
0
    status = STATUS_NO_MEMORY;
1959
0
    goto fail;
1960
0
  }
1961
1962
0
  ret.cReaders = call->cReaders;
1963
1964
0
  status = SCARD_E_INVALID_ATR;
1965
0
  for (UINT32 i = 0; i < ret.cReaders; i++)
1966
0
  {
1967
0
    const LPSCARD_READERSTATEA state = &states[i];
1968
0
    ReaderState_Return* cur = &ret.rgReaderStates[i];
1969
1970
0
    cur->dwCurrentState = state->dwCurrentState;
1971
0
    cur->dwEventState = state->dwEventState;
1972
0
    cur->cbAtr = state->cbAtr;
1973
0
    CopyMemory(&(cur->rgbAtr), &(state->rgbAtr), sizeof(cur->rgbAtr));
1974
1975
0
    if (!smartcard_reader_state_return_is_valid(i, cur))
1976
0
      goto fail;
1977
0
  }
1978
1979
0
  status = smartcard_pack_get_status_change_return(out, &ret, FALSE);
1980
1981
0
fail:
1982
0
  free(states);
1983
0
  free(ret.rgReaderStates);
1984
0
  if (status != SCARD_S_SUCCESS)
1985
0
    return status;
1986
0
  return ret.ReturnCode;
1987
0
}
1988
1989
WINPR_ATTR_NODISCARD static LONG smartcard_LocateCardsByATRW_Call(scard_call_context* smartcard,
1990
                                                                  wStream* out,
1991
                                                                  SMARTCARD_OPERATION* operation)
1992
0
{
1993
0
  LONG status = SCARD_E_INVALID_HANDLE;
1994
0
  GetStatusChange_Return ret = WINPR_C_ARRAY_INIT;
1995
1996
0
  WINPR_ASSERT(smartcard);
1997
0
  WINPR_ASSERT(operation);
1998
1999
0
  LocateCardsByATRW_Call* call = &operation->call.locateCardsByATRW;
2000
0
  LPSCARD_READERSTATEW states =
2001
0
      (LPSCARD_READERSTATEW)calloc(call->cReaders, sizeof(SCARD_READERSTATEW));
2002
2003
0
  if (!states)
2004
0
    return STATUS_NO_MEMORY;
2005
2006
0
  for (UINT32 i = 0; i < call->cReaders; i++)
2007
0
  {
2008
0
    const LPSCARD_READERSTATEW cstate = &call->rgReaderStates[i];
2009
0
    LPSCARD_READERSTATEW state = &states[i];
2010
2011
0
    state->szReader = cstate->szReader;
2012
0
    state->dwCurrentState = cstate->dwCurrentState;
2013
0
    state->dwEventState = cstate->dwEventState;
2014
0
    state->cbAtr = cstate->cbAtr;
2015
2016
0
    if (state->cbAtr > sizeof(state->rgbAtr))
2017
0
    {
2018
0
      WLog_WARN(SCARD_TAG, "[%" PRIu32 "] val->cbAtr=%" PRIu32 ", max=%" PRIuz, i,
2019
0
                state->cbAtr, sizeof(state->rgbAtr));
2020
0
      goto fail;
2021
0
    }
2022
0
    CopyMemory(&(state->rgbAtr), &(cstate->rgbAtr), sizeof(cstate->rgbAtr));
2023
0
  }
2024
2025
0
  status = ret.ReturnCode = wrap(smartcard, SCardGetStatusChangeW, operation->hContext,
2026
0
                                 0x000001F4, states, call->cReaders);
2027
2028
0
  scard_log_status_error_wlog(smartcard->log, "SCardGetStatusChangeW", status);
2029
0
  for (UINT32 i = 0; i < call->cAtrs; i++)
2030
0
  {
2031
0
    for (UINT32 j = 0; j < call->cReaders; j++)
2032
0
    {
2033
0
      const LocateCards_ATRMask* mask = &call->rgAtrMasks[i];
2034
0
      for (UINT32 k = 0; k < winpr_Data_Get_UINT32(&mask->cbAtr); k++)
2035
0
      {
2036
0
        if ((mask->rgbAtr[k] & mask->rgbMask[k]) !=
2037
0
            (states[j].rgbAtr[k] & mask->rgbMask[k]))
2038
0
        {
2039
0
          break;
2040
0
        }
2041
2042
0
        states[j].dwEventState |= SCARD_STATE_ATRMATCH;
2043
0
      }
2044
0
    }
2045
0
  }
2046
2047
0
  ret.rgReaderStates = nullptr;
2048
2049
0
  if (call->cReaders > 0)
2050
0
    ret.rgReaderStates =
2051
0
        (ReaderState_Return*)calloc(call->cReaders, sizeof(ReaderState_Return));
2052
2053
0
  if (!ret.rgReaderStates)
2054
0
  {
2055
0
    status = STATUS_NO_MEMORY;
2056
0
    goto fail;
2057
0
  }
2058
2059
0
  ret.cReaders = call->cReaders;
2060
2061
0
  status = SCARD_E_INVALID_ATR;
2062
0
  for (UINT32 i = 0; i < ret.cReaders; i++)
2063
0
  {
2064
0
    const LPSCARD_READERSTATEW state = &states[i];
2065
0
    ReaderState_Return* cur = &ret.rgReaderStates[i];
2066
2067
0
    cur->dwCurrentState = state->dwCurrentState;
2068
0
    cur->dwEventState = state->dwEventState;
2069
0
    cur->cbAtr = state->cbAtr;
2070
0
    CopyMemory(&(cur->rgbAtr), &(state->rgbAtr), sizeof(cur->rgbAtr));
2071
2072
0
    if (!smartcard_reader_state_return_is_valid(i, cur))
2073
0
      goto fail;
2074
0
  }
2075
2076
0
  status = smartcard_pack_get_status_change_return(out, &ret, FALSE);
2077
2078
0
fail:
2079
0
  free(states);
2080
0
  free(ret.rgReaderStates);
2081
0
  if (status != SCARD_S_SUCCESS)
2082
0
    return status;
2083
0
  return ret.ReturnCode;
2084
0
}
2085
2086
LONG smartcard_irp_device_control_call(scard_call_context* ctx, wStream* out, NTSTATUS* pIoStatus,
2087
                                       SMARTCARD_OPERATION* operation)
2088
0
{
2089
0
  LONG result = 0;
2090
0
  UINT32 offset = 0;
2091
0
  size_t objectBufferLength = 0;
2092
2093
0
  WINPR_ASSERT(ctx);
2094
0
  WINPR_ASSERT(out);
2095
0
  WINPR_ASSERT(pIoStatus);
2096
0
  WINPR_ASSERT(operation);
2097
2098
0
  const UINT32 ioControlCode = operation->ioControlCode;
2099
  /**
2100
   * [MS-RDPESC] 3.2.5.1: Sending Outgoing Messages:
2101
   * the output buffer length SHOULD be set to 2048
2102
   *
2103
   * Since it's a SHOULD and not a MUST, we don't care
2104
   * about it, but we still reserve at least 2048 bytes.
2105
   */
2106
0
  if (!Stream_EnsureRemainingCapacity(out, 2048ull))
2107
0
    return SCARD_E_NO_MEMORY;
2108
2109
  /* Device Control Response */
2110
0
  Stream_Write_UINT32(out, 0);                            /* OutputBufferLength (4 bytes) */
2111
0
  Stream_Zero(out, SMARTCARD_COMMON_TYPE_HEADER_LENGTH);  /* CommonTypeHeader (8 bytes) */
2112
0
  Stream_Zero(out, SMARTCARD_PRIVATE_TYPE_HEADER_LENGTH); /* PrivateTypeHeader (8 bytes) */
2113
0
  Stream_Write_UINT32(out, 0);                            /* Result (4 bytes) */
2114
2115
0
  smartcard_handle_activity_begin(ctx, ioControlCode, operation->hCard);
2116
2117
  /* Call */
2118
0
  switch (ioControlCode)
2119
0
  {
2120
0
    case SCARD_IOCTL_ESTABLISHCONTEXT:
2121
0
      result = smartcard_EstablishContext_Call(ctx, out, operation);
2122
0
      break;
2123
2124
0
    case SCARD_IOCTL_RELEASECONTEXT:
2125
0
      result = smartcard_ReleaseContext_Call(ctx, out, operation);
2126
0
      break;
2127
2128
0
    case SCARD_IOCTL_ISVALIDCONTEXT:
2129
0
      result = smartcard_IsValidContext_Call(ctx, out, operation);
2130
0
      break;
2131
2132
0
    case SCARD_IOCTL_LISTREADERGROUPSA:
2133
0
      result = smartcard_ListReaderGroupsA_Call(ctx, out, operation);
2134
0
      break;
2135
2136
0
    case SCARD_IOCTL_LISTREADERGROUPSW:
2137
0
      result = smartcard_ListReaderGroupsW_Call(ctx, out, operation);
2138
0
      break;
2139
2140
0
    case SCARD_IOCTL_LISTREADERSA:
2141
0
      result = smartcard_ListReadersA_Call(ctx, out, operation);
2142
0
      break;
2143
2144
0
    case SCARD_IOCTL_LISTREADERSW:
2145
0
      result = smartcard_ListReadersW_Call(ctx, out, operation);
2146
0
      break;
2147
2148
0
    case SCARD_IOCTL_INTRODUCEREADERGROUPA:
2149
0
      result = smartcard_IntroduceReaderGroupA_Call(ctx, out, operation);
2150
0
      break;
2151
2152
0
    case SCARD_IOCTL_INTRODUCEREADERGROUPW:
2153
0
      result = smartcard_IntroduceReaderGroupW_Call(ctx, out, operation);
2154
0
      break;
2155
2156
0
    case SCARD_IOCTL_FORGETREADERGROUPA:
2157
0
      result = smartcard_ForgetReaderA_Call(ctx, out, operation);
2158
0
      break;
2159
2160
0
    case SCARD_IOCTL_FORGETREADERGROUPW:
2161
0
      result = smartcard_ForgetReaderW_Call(ctx, out, operation);
2162
0
      break;
2163
2164
0
    case SCARD_IOCTL_INTRODUCEREADERA:
2165
0
      result = smartcard_IntroduceReaderA_Call(ctx, out, operation);
2166
0
      break;
2167
2168
0
    case SCARD_IOCTL_INTRODUCEREADERW:
2169
0
      result = smartcard_IntroduceReaderW_Call(ctx, out, operation);
2170
0
      break;
2171
2172
0
    case SCARD_IOCTL_FORGETREADERA:
2173
0
      result = smartcard_ForgetReaderA_Call(ctx, out, operation);
2174
0
      break;
2175
2176
0
    case SCARD_IOCTL_FORGETREADERW:
2177
0
      result = smartcard_ForgetReaderW_Call(ctx, out, operation);
2178
0
      break;
2179
2180
0
    case SCARD_IOCTL_ADDREADERTOGROUPA:
2181
0
      result = smartcard_AddReaderToGroupA_Call(ctx, out, operation);
2182
0
      break;
2183
2184
0
    case SCARD_IOCTL_ADDREADERTOGROUPW:
2185
0
      result = smartcard_AddReaderToGroupW_Call(ctx, out, operation);
2186
0
      break;
2187
2188
0
    case SCARD_IOCTL_REMOVEREADERFROMGROUPA:
2189
0
      result = smartcard_RemoveReaderFromGroupA_Call(ctx, out, operation);
2190
0
      break;
2191
2192
0
    case SCARD_IOCTL_REMOVEREADERFROMGROUPW:
2193
0
      result = smartcard_RemoveReaderFromGroupW_Call(ctx, out, operation);
2194
0
      break;
2195
2196
0
    case SCARD_IOCTL_LOCATECARDSA:
2197
0
      result = smartcard_LocateCardsA_Call(ctx, out, operation);
2198
0
      break;
2199
2200
0
    case SCARD_IOCTL_LOCATECARDSW:
2201
0
      result = smartcard_LocateCardsW_Call(ctx, out, operation);
2202
0
      break;
2203
2204
0
    case SCARD_IOCTL_GETSTATUSCHANGEA:
2205
0
      result = smartcard_GetStatusChangeA_Call(ctx, out, operation);
2206
0
      break;
2207
2208
0
    case SCARD_IOCTL_GETSTATUSCHANGEW:
2209
0
      result = smartcard_GetStatusChangeW_Call(ctx, out, operation);
2210
0
      break;
2211
2212
0
    case SCARD_IOCTL_CANCEL:
2213
0
      result = smartcard_Cancel_Call(ctx, out, operation);
2214
0
      break;
2215
2216
0
    case SCARD_IOCTL_CONNECTA:
2217
0
      result = smartcard_ConnectA_Call(ctx, out, operation);
2218
0
      break;
2219
2220
0
    case SCARD_IOCTL_CONNECTW:
2221
0
      result = smartcard_ConnectW_Call(ctx, out, operation);
2222
0
      break;
2223
2224
0
    case SCARD_IOCTL_RECONNECT:
2225
0
      result = smartcard_Reconnect_Call(ctx, out, operation);
2226
0
      break;
2227
2228
0
    case SCARD_IOCTL_DISCONNECT:
2229
0
      result = smartcard_Disconnect_Call(ctx, out, operation);
2230
0
      break;
2231
2232
0
    case SCARD_IOCTL_BEGINTRANSACTION:
2233
0
      result = smartcard_BeginTransaction_Call(ctx, out, operation);
2234
0
      break;
2235
2236
0
    case SCARD_IOCTL_ENDTRANSACTION:
2237
0
      result = smartcard_EndTransaction_Call(ctx, out, operation);
2238
0
      break;
2239
2240
0
    case SCARD_IOCTL_STATE:
2241
0
      result = smartcard_State_Call(ctx, out, operation);
2242
0
      break;
2243
2244
0
    case SCARD_IOCTL_STATUSA:
2245
0
      result = smartcard_StatusA_Call(ctx, out, operation);
2246
0
      break;
2247
2248
0
    case SCARD_IOCTL_STATUSW:
2249
0
      result = smartcard_StatusW_Call(ctx, out, operation);
2250
0
      break;
2251
2252
0
    case SCARD_IOCTL_TRANSMIT:
2253
0
      result = smartcard_Transmit_Call(ctx, out, operation);
2254
0
      break;
2255
2256
0
    case SCARD_IOCTL_CONTROL:
2257
0
      result = smartcard_Control_Call(ctx, out, operation);
2258
0
      break;
2259
2260
0
    case SCARD_IOCTL_GETATTRIB:
2261
0
      result = smartcard_GetAttrib_Call(ctx, out, operation);
2262
0
      break;
2263
2264
0
    case SCARD_IOCTL_SETATTRIB:
2265
0
      result = smartcard_SetAttrib_Call(ctx, out, operation);
2266
0
      break;
2267
2268
0
    case SCARD_IOCTL_ACCESSSTARTEDEVENT:
2269
0
      result = smartcard_AccessStartedEvent_Call(ctx, out, operation);
2270
0
      break;
2271
2272
0
    case SCARD_IOCTL_LOCATECARDSBYATRA:
2273
0
      result = smartcard_LocateCardsByATRA_Call(ctx, out, operation);
2274
0
      break;
2275
2276
0
    case SCARD_IOCTL_LOCATECARDSBYATRW:
2277
0
      result = smartcard_LocateCardsByATRW_Call(ctx, out, operation);
2278
0
      break;
2279
2280
0
    case SCARD_IOCTL_READCACHEA:
2281
0
      result = smartcard_ReadCacheA_Call(ctx, out, operation);
2282
0
      break;
2283
2284
0
    case SCARD_IOCTL_READCACHEW:
2285
0
      result = smartcard_ReadCacheW_Call(ctx, out, operation);
2286
0
      break;
2287
2288
0
    case SCARD_IOCTL_WRITECACHEA:
2289
0
      result = smartcard_WriteCacheA_Call(ctx, out, operation);
2290
0
      break;
2291
2292
0
    case SCARD_IOCTL_WRITECACHEW:
2293
0
      result = smartcard_WriteCacheW_Call(ctx, out, operation);
2294
0
      break;
2295
2296
0
    case SCARD_IOCTL_GETTRANSMITCOUNT:
2297
0
      result = smartcard_GetTransmitCount_Call(ctx, out, operation);
2298
0
      break;
2299
2300
0
    case SCARD_IOCTL_RELEASETARTEDEVENT:
2301
0
      result = smartcard_ReleaseStartedEvent_Call(ctx, out, operation);
2302
0
      break;
2303
2304
0
    case SCARD_IOCTL_GETREADERICON:
2305
0
      result = smartcard_GetReaderIcon_Call(ctx, out, operation);
2306
0
      break;
2307
2308
0
    case SCARD_IOCTL_GETDEVICETYPEID:
2309
0
      result = smartcard_GetDeviceTypeId_Call(ctx, out, operation);
2310
0
      break;
2311
2312
0
    default:
2313
0
      result = STATUS_UNSUCCESSFUL;
2314
0
      break;
2315
0
  }
2316
2317
0
  if (smartcard_handle_activity_end(ctx, ioControlCode, operation->hCard, result))
2318
0
  {
2319
0
    WLog_Print(ctx->log, WLOG_WARN,
2320
0
               "transaction on hCard 0x%08" PRIxz
2321
0
               " granted after the server ended it, releasing it",
2322
0
               (size_t)operation->hCard);
2323
0
    const LONG rc = wrap(ctx, SCardEndTransaction, operation->hCard, SCARD_LEAVE_CARD);
2324
0
    scard_log_status_error_wlog(ctx->log, "SCardEndTransaction", rc);
2325
0
    result = SCARD_E_CANCELLED;
2326
0
  }
2327
2328
  /**
2329
   * [MS-RPCE] 2.2.6.3 Primitive Type Serialization
2330
   * The type MUST be aligned on an 8-byte boundary. If the size of the
2331
   * primitive type is not a multiple of 8 bytes, the data MUST be padded.
2332
   */
2333
2334
0
  if ((ioControlCode != SCARD_IOCTL_ACCESSSTARTEDEVENT) &&
2335
0
      (ioControlCode != SCARD_IOCTL_RELEASETARTEDEVENT))
2336
0
  {
2337
0
    offset = (RDPDR_DEVICE_IO_RESPONSE_LENGTH + RDPDR_DEVICE_IO_CONTROL_RSP_HDR_LENGTH);
2338
0
    const LONG rc = smartcard_pack_write_size_align(out, Stream_GetPosition(out) - offset, 8);
2339
0
    if (rc != SCARD_S_SUCCESS)
2340
0
      result = rc;
2341
0
  }
2342
2343
0
  if ((result != SCARD_S_SUCCESS) && (result != SCARD_E_TIMEOUT) &&
2344
0
      (result != SCARD_E_NO_READERS_AVAILABLE) && (result != SCARD_E_NO_SERVICE) &&
2345
0
      (result != SCARD_W_CACHE_ITEM_NOT_FOUND) && (result != SCARD_W_CACHE_ITEM_STALE))
2346
0
  {
2347
0
    scard_log_status_error_wlog(ctx->log, "IRP failure: %s (0x%08" PRIX32 ")", result,
2348
0
                                scard_get_ioctl_string(ioControlCode, TRUE), ioControlCode);
2349
0
  }
2350
2351
0
  *pIoStatus = STATUS_SUCCESS;
2352
2353
0
  if ((result & 0xC0000000L) == 0xC0000000L)
2354
0
  {
2355
    /* NTSTATUS error */
2356
0
    *pIoStatus = result;
2357
2358
0
    scard_log_status_error_wlog(ctx->log, "IRP failure: %s (0x%08" PRIX32 ")", result,
2359
0
                                scard_get_ioctl_string(ioControlCode, TRUE), ioControlCode);
2360
0
  }
2361
2362
0
  Stream_SealLength(out);
2363
0
  size_t outputBufferLength = Stream_Length(out);
2364
0
  size_t dataEndPos = outputBufferLength;
2365
2366
0
  WINPR_ASSERT(outputBufferLength >= RDPDR_DEVICE_IO_RESPONSE_LENGTH + 4U);
2367
0
  outputBufferLength -= (RDPDR_DEVICE_IO_RESPONSE_LENGTH + 4U);
2368
0
  WINPR_ASSERT(outputBufferLength >= RDPDR_DEVICE_IO_RESPONSE_LENGTH);
2369
0
  objectBufferLength = outputBufferLength - RDPDR_DEVICE_IO_RESPONSE_LENGTH;
2370
0
  WINPR_ASSERT(outputBufferLength <= UINT32_MAX);
2371
0
  WINPR_ASSERT(objectBufferLength <= UINT32_MAX);
2372
0
  if (!Stream_SetPosition(out, RDPDR_DEVICE_IO_RESPONSE_LENGTH))
2373
0
    return SCARD_E_BAD_SEEK;
2374
2375
  /* [MS-RDPESC] 3.2.5.2 Processing Incoming Replies
2376
   *
2377
   * if the output buffer is too small, reply with STATUS_BUFFER_TOO_SMALL
2378
   * and a outputBufferLength of 0.
2379
   * The message should then be retransmitted from the server with a doubled
2380
   * buffer size.
2381
   */
2382
0
  if (outputBufferLength > operation->outputBufferLength)
2383
0
  {
2384
0
    WLog_Print(ctx->log, WLOG_DEBUG,
2385
0
               "IRP  warn: expected outputBufferLength %" PRIuz ", but current limit %" PRIu32
2386
0
               ", respond with STATUS_BUFFER_TOO_SMALL for retransmit with larger buffer",
2387
0
               outputBufferLength, operation->outputBufferLength);
2388
2389
0
    *pIoStatus = STATUS_BUFFER_TOO_SMALL;
2390
0
    result = *pIoStatus;
2391
0
    outputBufferLength = 0;
2392
0
    objectBufferLength = 0;
2393
0
  }
2394
0
  else
2395
0
  {
2396
0
    WLog_Print(ctx->log, WLOG_TRACE, "IRP trace: outputBufferLength %" PRIuz ", limit %" PRIu32,
2397
0
               outputBufferLength, operation->outputBufferLength);
2398
0
  }
2399
2400
  /* Device Control Response */
2401
0
  Stream_Write_UINT32(out, (UINT32)outputBufferLength); /* OutputBufferLength (4 bytes) */
2402
0
  smartcard_pack_common_type_header(out);               /* CommonTypeHeader (8 bytes) */
2403
0
  smartcard_pack_private_type_header(
2404
0
      out, (UINT32)objectBufferLength); /* PrivateTypeHeader (8 bytes) */
2405
0
  Stream_Write_INT32(out, result);      /* Result (4 bytes) */
2406
0
  if (result == STATUS_BUFFER_TOO_SMALL)
2407
0
    Stream_SealLength(out);
2408
0
  else if (!Stream_SetPosition(out, dataEndPos))
2409
0
    return SCARD_E_BAD_SEEK;
2410
0
  return SCARD_S_SUCCESS;
2411
0
}
2412
2413
void context_free(void* arg)
2414
0
{
2415
0
  struct s_scard_context_element* element = arg;
2416
0
  if (!arg)
2417
0
    return;
2418
2419
0
  if (element->fn_free)
2420
0
    element->fn_free(element->context);
2421
0
  free(element);
2422
0
}
2423
2424
#if !defined(WITHOUT_FREERDP_3x_DEPRECATED)
2425
scard_call_context* smartcard_call_context_new(const rdpSettings* settings)
2426
0
{
2427
0
  const freerdp* inst = freerdp_settings_get_pointer(settings, FreeRDP_instance);
2428
0
  if (!inst || !inst->context)
2429
0
    return nullptr;
2430
0
  return smartcard_call_context_new_with_context(inst->context);
2431
0
}
2432
#endif
2433
2434
scard_call_context* smartcard_call_context_new_with_context(rdpContext* context)
2435
0
{
2436
0
  WINPR_ASSERT(context);
2437
0
  scard_call_context* ctx = calloc(1, sizeof(scard_call_context));
2438
0
  if (!ctx)
2439
0
    goto fail;
2440
2441
0
  ctx->context = context;
2442
2443
0
  const rdpSettings* settings = context->settings;
2444
0
  WINPR_ASSERT(settings);
2445
2446
0
  ctx->log = WLog_Get(SCARD_TAG);
2447
0
  WINPR_ASSERT(ctx->log);
2448
2449
0
  ctx->stopEvent = CreateEventA(nullptr, TRUE, FALSE, nullptr);
2450
0
  if (!ctx->stopEvent)
2451
0
    goto fail;
2452
2453
0
  ctx->names = LinkedList_New();
2454
0
  if (!ctx->names)
2455
0
    goto fail;
2456
2457
0
#if defined(WITH_SMARTCARD_EMULATE)
2458
0
  ctx->useEmulatedCard = freerdp_settings_get_bool(settings, FreeRDP_SmartcardEmulation);
2459
0
#endif
2460
2461
0
  if (ctx->useEmulatedCard)
2462
0
  {
2463
0
#if defined(WITH_SMARTCARD_EMULATE)
2464
0
    ctx->emulation = Emulate_New(settings);
2465
0
    if (!ctx->emulation)
2466
0
      goto fail;
2467
#else
2468
    WLog_Print(ctx->log, WLOG_ERROR, "Smartcard emulation requested, but not supported!");
2469
    goto fail;
2470
#endif
2471
0
  }
2472
0
  else
2473
0
  {
2474
0
    const char* WinSCardModule = freerdp_settings_get_string(settings, FreeRDP_WinSCardModule);
2475
0
    if (WinSCardModule)
2476
0
    {
2477
0
      ctx->hWinSCardLibrary = LoadLibraryX(WinSCardModule);
2478
2479
0
      if (!ctx->hWinSCardLibrary)
2480
0
      {
2481
0
        WLog_Print(ctx->log, WLOG_ERROR, "Failed to load WinSCard library: '%s'",
2482
0
                   WinSCardModule);
2483
0
        goto fail;
2484
0
      }
2485
2486
0
      if (!WinSCard_LoadApiTableFunctions(&ctx->WinSCardApi, ctx->hWinSCardLibrary))
2487
0
        goto fail;
2488
0
      ctx->pWinSCardApi = &ctx->WinSCardApi;
2489
0
    }
2490
0
    else
2491
0
    {
2492
0
      ctx->pWinSCardApi = WinPR_GetSCardApiFunctionTable();
2493
0
    }
2494
2495
0
    if (!ctx->pWinSCardApi)
2496
0
    {
2497
0
      WLog_Print(ctx->log, WLOG_ERROR, "Failed to load WinSCard API!");
2498
0
      goto fail;
2499
0
    }
2500
0
  }
2501
2502
0
  ctx->rgSCardContextList = HashTable_New(FALSE);
2503
0
  if (!ctx->rgSCardContextList)
2504
0
    goto fail;
2505
2506
0
  {
2507
0
    wObject* obj = HashTable_ValueObject(ctx->rgSCardContextList);
2508
0
    WINPR_ASSERT(obj);
2509
0
    obj->fnObjectFree = context_free;
2510
0
  }
2511
2512
0
  if (!smartcard_transaction_watchdog_start(ctx))
2513
0
  {
2514
0
    WLog_Print(ctx->log, WLOG_ERROR, "Failed to start idle transaction watchdog!");
2515
0
    goto fail;
2516
0
  }
2517
2518
0
  return ctx;
2519
0
fail:
2520
0
  WINPR_PRAGMA_DIAG_PUSH
2521
0
  WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC
2522
0
  smartcard_call_context_free(ctx);
2523
0
  WINPR_PRAGMA_DIAG_POP
2524
0
  return nullptr;
2525
0
}
2526
2527
void smartcard_call_context_free(scard_call_context* ctx)
2528
0
{
2529
0
  if (!ctx)
2530
0
    return;
2531
2532
0
  smartcard_call_context_signal_stop(ctx, FALSE);
2533
2534
  /* uses the WinSCard API */
2535
0
  smartcard_transaction_watchdog_stop(ctx);
2536
2537
0
  LinkedList_Free(ctx->names);
2538
0
  if (ctx->StartedEvent)
2539
0
  {
2540
0
    WINPR_ASSERT(ctx->useEmulatedCard || ctx->pWinSCardApi);
2541
0
    wrap_raw(ctx, SCardReleaseStartedEvent);
2542
0
  }
2543
2544
0
  if (ctx->useEmulatedCard)
2545
0
  {
2546
0
#ifdef WITH_SMARTCARD_EMULATE
2547
0
    if (ctx->emulation)
2548
0
    {
2549
0
      Emulate_Free(ctx->emulation);
2550
0
      ctx->emulation = nullptr;
2551
0
    }
2552
0
#endif
2553
0
  }
2554
2555
0
  if (ctx->hWinSCardLibrary)
2556
0
  {
2557
0
    ZeroMemory(&ctx->WinSCardApi, sizeof(SCardApiFunctionTable));
2558
0
    FreeLibrary(ctx->hWinSCardLibrary);
2559
0
    ctx->hWinSCardLibrary = nullptr;
2560
0
  }
2561
2562
0
  ctx->pWinSCardApi = nullptr;
2563
2564
0
  HashTable_Free(ctx->rgSCardContextList);
2565
0
  HashTable_Free(ctx->handleStates);
2566
0
  (void)CloseHandle(ctx->stopEvent);
2567
0
  free(ctx);
2568
0
}
2569
2570
BOOL smartcard_call_context_add(scard_call_context* ctx, const char* name)
2571
0
{
2572
0
  WINPR_ASSERT(ctx);
2573
0
  WINPR_ASSERT(name);
2574
0
  return LinkedList_AddLast(ctx->names, name);
2575
0
}
2576
2577
BOOL smartcard_call_cancel_context(scard_call_context* ctx, SCARDCONTEXT hContext)
2578
0
{
2579
0
  WINPR_ASSERT(ctx);
2580
0
  if (wrap(ctx, SCardIsValidContext, hContext) == SCARD_S_SUCCESS)
2581
0
  {
2582
0
    wrap(ctx, SCardCancel, hContext);
2583
0
  }
2584
0
  return TRUE;
2585
0
}
2586
2587
BOOL smartcard_call_release_context(scard_call_context* ctx, SCARDCONTEXT hContext)
2588
0
{
2589
0
  WINPR_ASSERT(ctx);
2590
0
  wrap(ctx, SCardReleaseContext, hContext);
2591
0
  return TRUE;
2592
0
}
2593
2594
BOOL smartcard_call_cancel_all_context(scard_call_context* ctx)
2595
0
{
2596
0
  if (!ctx)
2597
0
    return FALSE;
2598
2599
0
  HashTable_Clear(ctx->rgSCardContextList);
2600
0
  return TRUE;
2601
0
}
2602
2603
BOOL smarcard_call_set_callbacks(scard_call_context* ctx, void* userdata,
2604
                                 void* (*fn_new)(void*, SCARDCONTEXT), void (*fn_free)(void*))
2605
0
{
2606
0
  WINPR_ASSERT(ctx);
2607
0
  ctx->userdata = userdata;
2608
0
  ctx->fn_new = fn_new;
2609
0
  ctx->fn_free = fn_free;
2610
0
  return TRUE;
2611
0
}
2612
2613
void* smartcard_call_get_context(scard_call_context* ctx, SCARDCONTEXT hContext)
2614
0
{
2615
0
  struct s_scard_context_element* element = nullptr;
2616
2617
0
  WINPR_ASSERT(ctx);
2618
0
  element = HashTable_GetItemValue(ctx->rgSCardContextList, (void*)hContext);
2619
0
  if (!element)
2620
0
    return nullptr;
2621
0
  return element->context;
2622
0
}
2623
2624
BOOL smartcard_call_is_configured(scard_call_context* ctx)
2625
0
{
2626
0
  WINPR_ASSERT(ctx);
2627
2628
0
#if defined(WITH_SMARTCARD_EMULATE)
2629
0
  if (ctx->useEmulatedCard)
2630
0
    return Emulate_IsConfigured(ctx->emulation);
2631
0
#endif
2632
2633
0
  return FALSE;
2634
0
}
2635
2636
static BOOL smartcard_cancel_context_wait(const void* key, WINPR_ATTR_UNUSED void* value, void* arg)
2637
0
{
2638
0
  scard_call_context* ctx = arg;
2639
0
  WINPR_ASSERT(ctx);
2640
2641
0
  const LONG rc = wrap_raw(ctx, SCardCancel, (SCARDCONTEXT)key);
2642
0
  if (rc != SCARD_S_SUCCESS)
2643
0
    WLog_Print(ctx->log, WLOG_DEBUG, "SCardCancel failed with %s", SCardGetErrorString(rc));
2644
0
  return TRUE;
2645
0
}
2646
2647
BOOL smartcard_call_context_signal_stop(scard_call_context* ctx, BOOL reset)
2648
0
{
2649
0
  WINPR_ASSERT(ctx);
2650
2651
0
  if (!ctx->stopEvent)
2652
0
    return TRUE;
2653
2654
0
  if (reset)
2655
0
    return ResetEvent(ctx->stopEvent);
2656
2657
0
  if (!SetEvent(ctx->stopEvent))
2658
0
    return FALSE;
2659
2660
  /* end pending SCardGetStatusChange calls */
2661
0
  if (ctx->rgSCardContextList && (ctx->useEmulatedCard || ctx->pWinSCardApi))
2662
0
    return HashTable_Foreach(ctx->rgSCardContextList, smartcard_cancel_context_wait, ctx);
2663
0
  return TRUE;
2664
0
}