Coverage Report

Created: 2026-01-09 06:49

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/FreeRDP/channels/serial/client/serial_main.c
Line
Count
Source
1
/**
2
 * FreeRDP: A Remote Desktop Protocol Implementation
3
 * Serial Port Device Service Virtual Channel
4
 *
5
 * Copyright 2011 O.S. Systems Software Ltda.
6
 * Copyright 2011 Eduardo Fiss Beloni <beloni@ossystems.com.br>
7
 * Copyright 2014 Hewlett-Packard Development Company, L.P.
8
 *
9
 * Licensed under the Apache License, Version 2.0 (the "License");
10
 * you may not use this file except in compliance with the License.
11
 * You may obtain a copy of the License at
12
 *
13
 *     http://www.apache.org/licenses/LICENSE-2.0
14
 *
15
 * Unless required by applicable law or agreed to in writing, software
16
 * distributed under the License is distributed on an "AS IS" BASIS,
17
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
 * See the License for the specific language governing permissions and
19
 * limitations under the License.
20
 */
21
22
#include <freerdp/config.h>
23
24
#include <errno.h>
25
#include <stdio.h>
26
#include <stdint.h>
27
#include <stdlib.h>
28
#include <string.h>
29
30
#include <winpr/collections.h>
31
#include <winpr/comm.h>
32
#include <winpr/crt.h>
33
#include <winpr/stream.h>
34
#include <winpr/synch.h>
35
#include <winpr/thread.h>
36
#include <winpr/wlog.h>
37
#include <winpr/assert.h>
38
39
#include <freerdp/freerdp.h>
40
#include <freerdp/channels/rdpdr.h>
41
#include <freerdp/channels/log.h>
42
#include <freerdp/utils/rdpdr_utils.h>
43
44
0
#define TAG CHANNELS_TAG("serial.client")
45
46
0
#define MAX_IRP_THREADS 5
47
48
typedef struct
49
{
50
  DEVICE device;
51
  BOOL permissive;
52
  SERIAL_DRIVER_ID ServerSerialDriverId;
53
  HANDLE hComm;
54
55
  wLog* log;
56
  HANDLE MainThread;
57
  wMessageQueue* MainIrpQueue;
58
59
  /* one thread per pending IRP and indexed according their CompletionId */
60
  wListDictionary* IrpThreads;
61
  CRITICAL_SECTION TerminatingIrpThreadsLock;
62
  rdpContext* rdpcontext;
63
} SERIAL_DEVICE;
64
65
typedef struct
66
{
67
  SERIAL_DEVICE* serial;
68
  IRP* irp;
69
} IRP_THREAD_DATA;
70
71
static void close_terminated_irp_thread_handles(SERIAL_DEVICE* serial, BOOL forceClose);
72
static NTSTATUS GetLastErrorToIoStatus(SERIAL_DEVICE* serial)
73
0
{
74
  /* http://msdn.microsoft.com/en-us/library/ff547466%28v=vs.85%29.aspx#generic_status_values_for_serial_device_control_requests
75
   */
76
0
  switch (GetLastError())
77
0
  {
78
0
    case ERROR_BAD_DEVICE:
79
0
      return STATUS_INVALID_DEVICE_REQUEST;
80
81
0
    case ERROR_CALL_NOT_IMPLEMENTED:
82
0
      return STATUS_NOT_IMPLEMENTED;
83
84
0
    case ERROR_CANCELLED:
85
0
      return STATUS_CANCELLED;
86
87
0
    case ERROR_INSUFFICIENT_BUFFER:
88
0
      return STATUS_BUFFER_TOO_SMALL; /* NB: STATUS_BUFFER_SIZE_TOO_SMALL not defined  */
89
90
0
    case ERROR_INVALID_DEVICE_OBJECT_PARAMETER: /* eg: SerCx2.sys' _purge() */
91
0
      return STATUS_INVALID_DEVICE_STATE;
92
93
0
    case ERROR_INVALID_HANDLE:
94
0
      return STATUS_INVALID_DEVICE_REQUEST;
95
96
0
    case ERROR_INVALID_PARAMETER:
97
0
      return STATUS_INVALID_PARAMETER;
98
99
0
    case ERROR_IO_DEVICE:
100
0
      return STATUS_IO_DEVICE_ERROR;
101
102
0
    case ERROR_IO_PENDING:
103
0
      return STATUS_PENDING;
104
105
0
    case ERROR_NOT_SUPPORTED:
106
0
      return STATUS_NOT_SUPPORTED;
107
108
0
    case ERROR_TIMEOUT:
109
0
      return STATUS_TIMEOUT;
110
0
    default:
111
0
      break;
112
0
  }
113
114
0
  WLog_Print(serial->log, WLOG_DEBUG, "unexpected last-error: 0x%08" PRIX32 "", GetLastError());
115
0
  return STATUS_UNSUCCESSFUL;
116
0
}
117
118
static UINT serial_process_irp_create(SERIAL_DEVICE* serial, IRP* irp)
119
0
{
120
0
  DWORD DesiredAccess = 0;
121
0
  DWORD SharedAccess = 0;
122
0
  DWORD CreateDisposition = 0;
123
0
  UINT32 PathLength = 0;
124
125
0
  WINPR_ASSERT(serial);
126
0
  WINPR_ASSERT(irp);
127
128
0
  if (!Stream_CheckAndLogRequiredLengthWLog(serial->log, irp->input, 32))
129
0
    return ERROR_INVALID_DATA;
130
131
0
  Stream_Read_UINT32(irp->input, DesiredAccess);     /* DesiredAccess (4 bytes) */
132
0
  Stream_Seek_UINT64(irp->input);                    /* AllocationSize (8 bytes) */
133
0
  Stream_Seek_UINT32(irp->input);                    /* FileAttributes (4 bytes) */
134
0
  Stream_Read_UINT32(irp->input, SharedAccess);      /* SharedAccess (4 bytes) */
135
0
  Stream_Read_UINT32(irp->input, CreateDisposition); /* CreateDisposition (4 bytes) */
136
0
  Stream_Seek_UINT32(irp->input);                    /* CreateOptions (4 bytes) */
137
0
  Stream_Read_UINT32(irp->input, PathLength);        /* PathLength (4 bytes) */
138
139
0
  if (!Stream_SafeSeek(irp->input, PathLength)) /* Path (variable) */
140
0
    return ERROR_INVALID_DATA;
141
142
0
  WINPR_ASSERT(PathLength == 0); /* MS-RDPESP 2.2.2.2 */
143
0
#ifndef _WIN32
144
  /* Windows 2012 server sends on a first call :
145
   *     DesiredAccess     = 0x00100080: SYNCHRONIZE | FILE_READ_ATTRIBUTES
146
   *     SharedAccess      = 0x00000007: FILE_SHARE_DELETE | FILE_SHARE_WRITE | FILE_SHARE_READ
147
   *     CreateDisposition = 0x00000001: CREATE_NEW
148
   *
149
   * then Windows 2012 sends :
150
   *     DesiredAccess     = 0x00120089: SYNCHRONIZE | READ_CONTROL | FILE_READ_ATTRIBUTES |
151
   * FILE_READ_EA | FILE_READ_DATA SharedAccess      = 0x00000007: FILE_SHARE_DELETE |
152
   * FILE_SHARE_WRITE | FILE_SHARE_READ CreateDisposition = 0x00000001: CREATE_NEW
153
   *
154
   * WINPR_ASSERT(DesiredAccess == (GENERIC_READ | GENERIC_WRITE));
155
   * WINPR_ASSERT(SharedAccess == 0);
156
   * WINPR_ASSERT(CreateDisposition == OPEN_EXISTING);
157
   *
158
   */
159
0
  WLog_Print(serial->log, WLOG_DEBUG,
160
0
             "DesiredAccess: 0x%" PRIX32 ", SharedAccess: 0x%" PRIX32
161
0
             ", CreateDisposition: 0x%" PRIX32 "",
162
0
             DesiredAccess, SharedAccess, CreateDisposition);
163
  /* FIXME: As of today only the flags below are supported by CommCreateFileA: */
164
0
  DesiredAccess = GENERIC_READ | GENERIC_WRITE;
165
0
  SharedAccess = 0;
166
0
  CreateDisposition = OPEN_EXISTING;
167
0
#endif
168
0
  serial->hComm = winpr_CreateFile(serial->device.name, DesiredAccess, SharedAccess,
169
0
                                   NULL,                 /* SecurityAttributes */
170
0
                                   CreateDisposition, 0, /* FlagsAndAttributes */
171
0
                                   NULL);                /* TemplateFile */
172
173
0
  if (!serial->hComm || (serial->hComm == INVALID_HANDLE_VALUE))
174
0
  {
175
0
    WLog_Print(serial->log, WLOG_WARN, "CreateFile failure: %s last-error: 0x%08" PRIX32 "",
176
0
               serial->device.name, GetLastError());
177
0
    irp->IoStatus = STATUS_UNSUCCESSFUL;
178
0
    goto error_handle;
179
0
  }
180
181
0
  _comm_setServerSerialDriver(serial->hComm, serial->ServerSerialDriverId);
182
0
  _comm_set_permissive(serial->hComm, serial->permissive);
183
  /* NOTE: binary mode/raw mode required for the redirection. On
184
   * Linux, CommCreateFileA forces this setting.
185
   */
186
  /* ZeroMemory(&dcb, sizeof(DCB)); */
187
  /* dcb.DCBlength = sizeof(DCB); */
188
  /* GetCommState(serial->hComm, &dcb); */
189
  /* dcb.fBinary = TRUE; */
190
  /* SetCommState(serial->hComm, &dcb); */
191
0
  WINPR_ASSERT(irp->FileId == 0);
192
0
  irp->FileId = irp->devman->id_sequence++; /* FIXME: why not ((WINPR_COMM*)hComm)->fd? */
193
0
  irp->IoStatus = STATUS_SUCCESS;
194
0
  WLog_Print(serial->log, WLOG_DEBUG, "%s (DeviceId: %" PRIu32 ", FileId: %" PRIu32 ") created.",
195
0
             serial->device.name, irp->device->id, irp->FileId);
196
197
0
  {
198
0
    DWORD BytesReturned = 0;
199
0
    if (!CommDeviceIoControl(serial->hComm, IOCTL_SERIAL_RESET_DEVICE, NULL, 0, NULL, 0,
200
0
                             &BytesReturned, NULL))
201
0
      goto error_handle;
202
0
  }
203
204
0
error_handle:
205
0
  Stream_Write_UINT32(irp->output, irp->FileId); /* FileId (4 bytes) */
206
0
  Stream_Write_UINT8(irp->output, 0);            /* Information (1 byte) */
207
0
  return CHANNEL_RC_OK;
208
0
}
209
210
static UINT serial_process_irp_close(SERIAL_DEVICE* serial, IRP* irp)
211
0
{
212
0
  WINPR_ASSERT(serial);
213
0
  WINPR_ASSERT(irp);
214
215
0
  if (!Stream_CheckAndLogRequiredLengthWLog(serial->log, irp->input, 32))
216
0
    return ERROR_INVALID_DATA;
217
218
0
  Stream_Seek(irp->input, 32); /* Padding (32 bytes) */
219
220
0
  close_terminated_irp_thread_handles(serial, TRUE);
221
222
0
  if (!CloseHandle(serial->hComm))
223
0
  {
224
0
    WLog_Print(serial->log, WLOG_WARN, "CloseHandle failure: %s (%" PRIu32 ") closed.",
225
0
               serial->device.name, irp->device->id);
226
0
    irp->IoStatus = STATUS_UNSUCCESSFUL;
227
0
    goto error_handle;
228
0
  }
229
230
0
  WLog_Print(serial->log, WLOG_DEBUG, "%s (DeviceId: %" PRIu32 ", FileId: %" PRIu32 ") closed.",
231
0
             serial->device.name, irp->device->id, irp->FileId);
232
0
  irp->IoStatus = STATUS_SUCCESS;
233
0
error_handle:
234
0
  serial->hComm = NULL;
235
0
  Stream_Zero(irp->output, 5); /* Padding (5 bytes) */
236
0
  return CHANNEL_RC_OK;
237
0
}
238
239
/**
240
 * Function description
241
 *
242
 * @return 0 on success, otherwise a Win32 error code
243
 */
244
static UINT serial_process_irp_read(SERIAL_DEVICE* serial, IRP* irp)
245
0
{
246
0
  UINT32 Length = 0;
247
0
  UINT64 Offset = 0;
248
0
  BYTE* buffer = NULL;
249
0
  DWORD nbRead = 0;
250
251
0
  WINPR_ASSERT(serial);
252
0
  WINPR_ASSERT(irp);
253
254
0
  if (!Stream_CheckAndLogRequiredLengthWLog(serial->log, irp->input, 32))
255
0
    return ERROR_INVALID_DATA;
256
257
0
  Stream_Read_UINT32(irp->input, Length); /* Length (4 bytes) */
258
0
  Stream_Read_UINT64(irp->input, Offset); /* Offset (8 bytes) */
259
0
  (void)Offset;                /* [MS-RDPESP] 3.2.5.1.4 Processing a Server Read Request Message
260
                                * ignored */
261
0
  Stream_Seek(irp->input, 20); /* Padding (20 bytes) */
262
0
  buffer = (BYTE*)calloc(Length, sizeof(BYTE));
263
264
0
  if (buffer == NULL)
265
0
  {
266
0
    irp->IoStatus = STATUS_NO_MEMORY;
267
0
    goto error_handle;
268
0
  }
269
270
  /* MS-RDPESP 3.2.5.1.4: If the Offset field is not set to 0, the value MUST be ignored
271
   * WINPR_ASSERT(Offset == 0);
272
   */
273
0
  WLog_Print(serial->log, WLOG_DEBUG, "reading %" PRIu32 " bytes from %s", Length,
274
0
             serial->device.name);
275
276
  /* FIXME: CommReadFile to be replaced by ReadFile */
277
0
  if (CommReadFile(serial->hComm, buffer, Length, &nbRead, NULL))
278
0
  {
279
0
    irp->IoStatus = STATUS_SUCCESS;
280
0
  }
281
0
  else
282
0
  {
283
0
    WLog_Print(serial->log, WLOG_DEBUG,
284
0
               "read failure to %s, nbRead=%" PRIu32 ", last-error: 0x%08" PRIX32 "",
285
0
               serial->device.name, nbRead, GetLastError());
286
0
    irp->IoStatus = GetLastErrorToIoStatus(serial);
287
0
  }
288
289
0
  WLog_Print(serial->log, WLOG_DEBUG, "%" PRIu32 " bytes read from %s", nbRead,
290
0
             serial->device.name);
291
0
error_handle:
292
0
  Stream_Write_UINT32(irp->output, nbRead); /* Length (4 bytes) */
293
294
0
  if (nbRead > 0)
295
0
  {
296
0
    if (!Stream_EnsureRemainingCapacity(irp->output, nbRead))
297
0
    {
298
0
      WLog_Print(serial->log, WLOG_ERROR, "Stream_EnsureRemainingCapacity failed!");
299
0
      free(buffer);
300
0
      return CHANNEL_RC_NO_MEMORY;
301
0
    }
302
303
0
    Stream_Write(irp->output, buffer, nbRead); /* ReadData */
304
0
  }
305
306
0
  free(buffer);
307
0
  return CHANNEL_RC_OK;
308
0
}
309
310
static UINT serial_process_irp_write(SERIAL_DEVICE* serial, IRP* irp)
311
0
{
312
0
  UINT32 Length = 0;
313
0
  UINT64 Offset = 0;
314
0
  DWORD nbWritten = 0;
315
316
0
  WINPR_ASSERT(serial);
317
0
  WINPR_ASSERT(irp);
318
319
0
  if (!Stream_CheckAndLogRequiredLengthWLog(serial->log, irp->input, 32))
320
0
    return ERROR_INVALID_DATA;
321
322
0
  Stream_Read_UINT32(irp->input, Length); /* Length (4 bytes) */
323
0
  Stream_Read_UINT64(irp->input, Offset); /* Offset (8 bytes) */
324
0
  (void)Offset; /* [MS-RDPESP] 3.2.5.1.4 Processing a Server Read Request Message
325
                 * ignored */
326
0
  if (!Stream_SafeSeek(irp->input, 20)) /* Padding (20 bytes) */
327
0
    return ERROR_INVALID_DATA;
328
329
  /* MS-RDPESP 3.2.5.1.5: The Offset field is ignored
330
   * WINPR_ASSERT(Offset == 0);
331
   *
332
   * Using a serial printer, noticed though this field could be
333
   * set.
334
   */
335
0
  WLog_Print(serial->log, WLOG_DEBUG, "writing %" PRIu32 " bytes to %s", Length,
336
0
             serial->device.name);
337
338
0
  const void* ptr = Stream_ConstPointer(irp->input);
339
0
  if (!Stream_SafeSeek(irp->input, Length))
340
0
    return ERROR_INVALID_DATA;
341
  /* FIXME: CommWriteFile to be replaced by WriteFile */
342
0
  if (CommWriteFile(serial->hComm, ptr, Length, &nbWritten, NULL))
343
0
  {
344
0
    irp->IoStatus = STATUS_SUCCESS;
345
0
  }
346
0
  else
347
0
  {
348
0
    WLog_Print(serial->log, WLOG_DEBUG,
349
0
               "write failure to %s, nbWritten=%" PRIu32 ", last-error: 0x%08" PRIX32 "",
350
0
               serial->device.name, nbWritten, GetLastError());
351
0
    irp->IoStatus = GetLastErrorToIoStatus(serial);
352
0
  }
353
354
0
  WLog_Print(serial->log, WLOG_DEBUG, "%" PRIu32 " bytes written to %s", nbWritten,
355
0
             serial->device.name);
356
0
  Stream_Write_UINT32(irp->output, nbWritten); /* Length (4 bytes) */
357
0
  Stream_Write_UINT8(irp->output, 0);          /* Padding (1 byte) */
358
0
  return CHANNEL_RC_OK;
359
0
}
360
361
/**
362
 * Function description
363
 *
364
 * @return 0 on success, otherwise a Win32 error code
365
 */
366
static UINT serial_process_irp_device_control(SERIAL_DEVICE* serial, IRP* irp)
367
0
{
368
0
  UINT32 IoControlCode = 0;
369
0
  UINT32 InputBufferLength = 0;
370
0
  BYTE* InputBuffer = NULL;
371
0
  UINT32 OutputBufferLength = 0;
372
0
  BYTE* OutputBuffer = NULL;
373
0
  DWORD BytesReturned = 0;
374
375
0
  WINPR_ASSERT(serial);
376
0
  WINPR_ASSERT(irp);
377
378
0
  if (!Stream_CheckAndLogRequiredLengthWLog(serial->log, irp->input, 32))
379
0
    return ERROR_INVALID_DATA;
380
381
0
  Stream_Read_UINT32(irp->input, OutputBufferLength); /* OutputBufferLength (4 bytes) */
382
0
  Stream_Read_UINT32(irp->input, InputBufferLength);  /* InputBufferLength (4 bytes) */
383
0
  Stream_Read_UINT32(irp->input, IoControlCode);      /* IoControlCode (4 bytes) */
384
0
  Stream_Seek(irp->input, 20);                        /* Padding (20 bytes) */
385
386
0
  if (!Stream_CheckAndLogRequiredLengthWLog(serial->log, irp->input, InputBufferLength))
387
0
    return ERROR_INVALID_DATA;
388
389
0
  OutputBuffer = (BYTE*)calloc(OutputBufferLength, sizeof(BYTE));
390
391
0
  if (OutputBuffer == NULL)
392
0
  {
393
0
    irp->IoStatus = STATUS_NO_MEMORY;
394
0
    goto error_handle;
395
0
  }
396
397
0
  InputBuffer = (BYTE*)calloc(InputBufferLength, sizeof(BYTE));
398
399
0
  if (InputBuffer == NULL)
400
0
  {
401
0
    irp->IoStatus = STATUS_NO_MEMORY;
402
0
    goto error_handle;
403
0
  }
404
405
0
  Stream_Read(irp->input, InputBuffer, InputBufferLength);
406
0
  WLog_Print(serial->log, WLOG_DEBUG,
407
0
             "CommDeviceIoControl: CompletionId=%" PRIu32 ", IoControlCode=[0x%" PRIX32 "] %s",
408
0
             irp->CompletionId, IoControlCode, _comm_serial_ioctl_name(IoControlCode));
409
410
  /* FIXME: CommDeviceIoControl to be replaced by DeviceIoControl() */
411
0
  if (CommDeviceIoControl(serial->hComm, IoControlCode, InputBuffer, InputBufferLength,
412
0
                          OutputBuffer, OutputBufferLength, &BytesReturned, NULL))
413
0
  {
414
    /* WLog_Print(serial->log, WLOG_DEBUG, "CommDeviceIoControl: CompletionId=%"PRIu32",
415
     * IoControlCode=[0x%"PRIX32"] %s done", irp->CompletionId, IoControlCode,
416
     * _comm_serial_ioctl_name(IoControlCode)); */
417
0
    irp->IoStatus = STATUS_SUCCESS;
418
0
  }
419
0
  else
420
0
  {
421
0
    WLog_Print(serial->log, WLOG_DEBUG,
422
0
               "CommDeviceIoControl failure: IoControlCode=[0x%" PRIX32
423
0
               "] %s, last-error: 0x%08" PRIX32 "",
424
0
               IoControlCode, _comm_serial_ioctl_name(IoControlCode), GetLastError());
425
0
    irp->IoStatus = GetLastErrorToIoStatus(serial);
426
0
  }
427
428
0
error_handle:
429
  /* FIXME: find out whether it's required or not to get
430
   * BytesReturned == OutputBufferLength when
431
   * CommDeviceIoControl returns FALSE */
432
0
  WINPR_ASSERT(OutputBufferLength == BytesReturned);
433
0
  Stream_Write_UINT32(irp->output, BytesReturned); /* OutputBufferLength (4 bytes) */
434
435
0
  if (BytesReturned > 0)
436
0
  {
437
0
    if (!Stream_EnsureRemainingCapacity(irp->output, BytesReturned))
438
0
    {
439
0
      WLog_Print(serial->log, WLOG_ERROR, "Stream_EnsureRemainingCapacity failed!");
440
0
      free(InputBuffer);
441
0
      free(OutputBuffer);
442
0
      return CHANNEL_RC_NO_MEMORY;
443
0
    }
444
445
0
    Stream_Write(irp->output, OutputBuffer, BytesReturned); /* OutputBuffer */
446
0
  }
447
448
  /* FIXME: Why at least Windows 2008R2 gets lost with this
449
   * extra byte and likely on a IOCTL_SERIAL_SET_BAUD_RATE? The
450
   * extra byte is well required according MS-RDPEFS
451
   * 2.2.1.5.5 */
452
  /* else */
453
  /* { */
454
  /*  Stream_Write_UINT8(irp->output, 0); /\* Padding (1 byte) *\/ */
455
  /* } */
456
0
  free(InputBuffer);
457
0
  free(OutputBuffer);
458
0
  return CHANNEL_RC_OK;
459
0
}
460
461
/**
462
 * Function description
463
 *
464
 * @return 0 on success, otherwise a Win32 error code
465
 */
466
static UINT serial_process_irp(SERIAL_DEVICE* serial, IRP* irp)
467
0
{
468
0
  UINT error = CHANNEL_RC_OK;
469
470
0
  WINPR_ASSERT(serial);
471
0
  WINPR_ASSERT(irp);
472
473
0
  WLog_Print(serial->log, WLOG_DEBUG, "IRP MajorFunction: %s, MinorFunction: 0x%08" PRIX32 "\n",
474
0
             rdpdr_irp_string(irp->MajorFunction), irp->MinorFunction);
475
476
0
  switch (irp->MajorFunction)
477
0
  {
478
0
    case IRP_MJ_CREATE:
479
0
      error = serial_process_irp_create(serial, irp);
480
0
      break;
481
482
0
    case IRP_MJ_CLOSE:
483
0
      error = serial_process_irp_close(serial, irp);
484
0
      break;
485
486
0
    case IRP_MJ_READ:
487
0
      error = serial_process_irp_read(serial, irp);
488
0
      break;
489
490
0
    case IRP_MJ_WRITE:
491
0
      error = serial_process_irp_write(serial, irp);
492
0
      break;
493
494
0
    case IRP_MJ_DEVICE_CONTROL:
495
0
      error = serial_process_irp_device_control(serial, irp);
496
0
      break;
497
498
0
    default:
499
0
      irp->IoStatus = STATUS_NOT_SUPPORTED;
500
0
      break;
501
0
  }
502
503
0
  DWORD level = WLOG_TRACE;
504
0
  if (error)
505
0
    level = WLOG_WARN;
506
507
0
  WLog_Print(serial->log, level,
508
0
             "[%s|0x%08" PRIx32 "] completed with %s [0x%08" PRIx32 "] (IoStatus %s [0x%08" PRIx32
509
0
             "])",
510
0
             rdpdr_irp_string(irp->MajorFunction), irp->MajorFunction, WTSErrorToString(error),
511
0
             error, NtStatus2Tag(irp->IoStatus), WINPR_CXX_COMPAT_CAST(UINT32, irp->IoStatus));
512
513
0
  return error;
514
0
}
515
516
static DWORD WINAPI irp_thread_func(LPVOID arg)
517
0
{
518
0
  IRP_THREAD_DATA* data = (IRP_THREAD_DATA*)arg;
519
0
  UINT error = 0;
520
521
0
  WINPR_ASSERT(data);
522
0
  WINPR_ASSERT(data->serial);
523
0
  WINPR_ASSERT(data->irp);
524
525
  /* blocks until the end of the request */
526
0
  if ((error = serial_process_irp(data->serial, data->irp)))
527
0
  {
528
0
    WLog_Print(data->serial->log, WLOG_ERROR,
529
0
               "serial_process_irp failed with error %" PRIu32 "", error);
530
0
    goto error_out;
531
0
  }
532
533
0
  EnterCriticalSection(&data->serial->TerminatingIrpThreadsLock);
534
0
  WINPR_ASSERT(data->irp->Complete);
535
0
  error = data->irp->Complete(data->irp);
536
0
  LeaveCriticalSection(&data->serial->TerminatingIrpThreadsLock);
537
0
error_out:
538
539
0
  if (error && data->serial->rdpcontext)
540
0
    setChannelError(data->serial->rdpcontext, error, "irp_thread_func reported an error");
541
542
0
  if (error)
543
0
    data->irp->Discard(data->irp);
544
545
  /* NB: At this point, the server might already being reusing
546
   * the CompletionId whereas the thread is not yet
547
   * terminated */
548
0
  free(data);
549
0
  ExitThread(error);
550
0
  return error;
551
0
}
552
553
static void close_unterminated_irp_thread(wListDictionary* list, wLog* log, ULONG_PTR id)
554
0
{
555
0
  WINPR_ASSERT(list);
556
0
  HANDLE self = _GetCurrentThread();
557
0
  HANDLE cirpThread = ListDictionary_GetItemValue(list, (void*)id);
558
0
  if (self == cirpThread)
559
0
    WLog_Print(log, WLOG_DEBUG, "Skipping termination of own IRP thread");
560
0
  else
561
0
    ListDictionary_Remove(list, (void*)id);
562
0
}
563
564
static void close_terminated_irp_thread(wListDictionary* list, wLog* log, ULONG_PTR id)
565
0
{
566
0
  WINPR_ASSERT(list);
567
568
0
  HANDLE cirpThread = ListDictionary_GetItemValue(list, (void*)id);
569
  /* FIXME: not quite sure a zero timeout is a good thing to check whether a thread is
570
   * still alive or not */
571
0
  const DWORD waitResult = WaitForSingleObject(cirpThread, 0);
572
573
0
  if (waitResult == WAIT_OBJECT_0)
574
0
    ListDictionary_Remove(list, (void*)id);
575
0
  else if (waitResult != WAIT_TIMEOUT)
576
0
  {
577
    /* unexpected thread state */
578
0
    WLog_Print(log, WLOG_WARN, "WaitForSingleObject, got an unexpected result=0x%" PRIX32 "\n",
579
0
               waitResult);
580
0
  }
581
0
}
582
583
void close_terminated_irp_thread_handles(SERIAL_DEVICE* serial, BOOL forceClose)
584
0
{
585
0
  WINPR_ASSERT(serial);
586
587
0
  EnterCriticalSection(&serial->TerminatingIrpThreadsLock);
588
589
0
  ULONG_PTR* ids = NULL;
590
0
  const size_t nbIds = ListDictionary_GetKeys(serial->IrpThreads, &ids);
591
592
0
  for (size_t i = 0; i < nbIds; i++)
593
0
  {
594
0
    ULONG_PTR id = ids[i];
595
0
    if (forceClose)
596
0
      close_unterminated_irp_thread(serial->IrpThreads, serial->log, id);
597
0
    else
598
0
      close_terminated_irp_thread(serial->IrpThreads, serial->log, id);
599
0
  }
600
601
0
  free(ids);
602
603
0
  LeaveCriticalSection(&serial->TerminatingIrpThreadsLock);
604
0
}
605
606
static void create_irp_thread(SERIAL_DEVICE* serial, IRP* irp)
607
0
{
608
0
  IRP_THREAD_DATA* data = NULL;
609
0
  HANDLE irpThread = NULL;
610
0
  HANDLE previousIrpThread = NULL;
611
0
  uintptr_t key = 0;
612
613
0
  WINPR_ASSERT(serial);
614
0
  WINPR_ASSERT(irp);
615
616
0
  close_terminated_irp_thread_handles(serial, FALSE);
617
618
  /* NB: At this point and thanks to the synchronization we're
619
   * sure that the incoming IRP uses well a recycled
620
   * CompletionId or the server sent again an IRP already posted
621
   * which didn't get yet a response (this later server behavior
622
   * at least observed with IOCTL_SERIAL_WAIT_ON_MASK and
623
   * mstsc.exe).
624
   *
625
   * FIXME: behavior documented somewhere? behavior not yet
626
   * observed with FreeRDP).
627
   */
628
0
  key = irp->CompletionId + 1ull;
629
0
  previousIrpThread = ListDictionary_GetItemValue(serial->IrpThreads, (void*)key);
630
631
0
  if (previousIrpThread)
632
0
  {
633
    /* Thread still alived <=> Request still pending */
634
0
    WLog_Print(serial->log, WLOG_DEBUG,
635
0
               "IRP recall: IRP with the CompletionId=%" PRIu32 " not yet completed!",
636
0
               irp->CompletionId);
637
0
    WINPR_ASSERT(FALSE); /* unimplemented */
638
    /* TODO: WINPR_ASSERTs that previousIrpThread handles well
639
     * the same request by checking more details. Need an
640
     * access to the IRP object used by previousIrpThread
641
     */
642
    /* TODO: taking over the pending IRP or sending a kind
643
     * of wake up signal to accelerate the pending
644
     * request
645
     *
646
     * To be considered:
647
     *   if (IoControlCode == IOCTL_SERIAL_WAIT_ON_MASK) {
648
     *       pComm->PendingEvents |= SERIAL_EV_FREERDP_*;
649
     *   }
650
     */
651
0
    irp->Discard(irp);
652
0
    return;
653
0
  }
654
655
0
  if (ListDictionary_Count(serial->IrpThreads) >= MAX_IRP_THREADS)
656
0
  {
657
0
    WLog_Print(serial->log, WLOG_WARN,
658
0
               "Number of IRP threads threshold reached: %" PRIuz ", keep on anyway",
659
0
               ListDictionary_Count(serial->IrpThreads));
660
0
    WINPR_ASSERT(FALSE); /* unimplemented */
661
                         /* TODO: MAX_IRP_THREADS has been thought to avoid a
662
                          * flooding of pending requests. Use
663
                          * WaitForMultipleObjects() when available in winpr
664
                          * for threads.
665
                          */
666
0
  }
667
668
  /* error_handle to be used ... */
669
0
  data = (IRP_THREAD_DATA*)calloc(1, sizeof(IRP_THREAD_DATA));
670
671
0
  if (data == NULL)
672
0
  {
673
0
    WLog_Print(serial->log, WLOG_WARN, "Could not allocate a new IRP_THREAD_DATA.");
674
0
    goto error_handle;
675
0
  }
676
677
0
  data->serial = serial;
678
0
  data->irp = irp;
679
  /* data freed by irp_thread_func */
680
0
  irpThread = CreateThread(NULL, 0, irp_thread_func, (void*)data, CREATE_SUSPENDED, NULL);
681
682
0
  if (irpThread == INVALID_HANDLE_VALUE)
683
0
  {
684
0
    WLog_Print(serial->log, WLOG_WARN, "Could not allocate a new IRP thread.");
685
0
    goto error_handle;
686
0
  }
687
688
0
  key = irp->CompletionId + 1ull;
689
690
0
  if (!ListDictionary_Add(serial->IrpThreads, (void*)key, irpThread))
691
0
  {
692
0
    WLog_Print(serial->log, WLOG_ERROR, "ListDictionary_Add failed!");
693
0
    goto error_handle;
694
0
  }
695
696
0
  ResumeThread(irpThread);
697
698
0
  return;
699
0
error_handle:
700
0
  if (irpThread)
701
0
    (void)CloseHandle(irpThread);
702
0
  irp->IoStatus = STATUS_NO_MEMORY;
703
0
  WINPR_ASSERT(irp->Complete);
704
0
  irp->Complete(irp);
705
0
  free(data);
706
0
}
707
708
static DWORD WINAPI serial_thread_func(LPVOID arg)
709
0
{
710
0
  IRP* irp = NULL;
711
0
  wMessage message = { 0 };
712
0
  SERIAL_DEVICE* serial = (SERIAL_DEVICE*)arg;
713
0
  UINT error = CHANNEL_RC_OK;
714
715
0
  WINPR_ASSERT(serial);
716
717
0
  while (1)
718
0
  {
719
0
    if (!MessageQueue_Wait(serial->MainIrpQueue))
720
0
    {
721
0
      WLog_Print(serial->log, WLOG_ERROR, "MessageQueue_Wait failed!");
722
0
      error = ERROR_INTERNAL_ERROR;
723
0
      break;
724
0
    }
725
726
0
    if (!MessageQueue_Peek(serial->MainIrpQueue, &message, TRUE))
727
0
    {
728
0
      WLog_Print(serial->log, WLOG_ERROR, "MessageQueue_Peek failed!");
729
0
      error = ERROR_INTERNAL_ERROR;
730
0
      break;
731
0
    }
732
733
0
    if (message.id == WMQ_QUIT)
734
0
      break;
735
736
0
    irp = (IRP*)message.wParam;
737
738
0
    if (irp)
739
0
      create_irp_thread(serial, irp);
740
0
  }
741
742
0
  ListDictionary_Clear(serial->IrpThreads);
743
0
  if (error && serial->rdpcontext)
744
0
    setChannelError(serial->rdpcontext, error, "serial_thread_func reported an error");
745
746
0
  ExitThread(error);
747
0
  return error;
748
0
}
749
750
/**
751
 * Function description
752
 *
753
 * @return 0 on success, otherwise a Win32 error code
754
 */
755
static UINT serial_irp_request(DEVICE* device, IRP* irp)
756
0
{
757
0
  SERIAL_DEVICE* serial = (SERIAL_DEVICE*)device;
758
0
  WINPR_ASSERT(irp != NULL);
759
0
  WINPR_ASSERT(serial);
760
761
0
  if (irp == NULL)
762
0
    return CHANNEL_RC_OK;
763
764
  /* NB: ENABLE_ASYNCIO is set, (MS-RDPEFS 2.2.2.7.2) this
765
   * allows the server to send multiple simultaneous read or
766
   * write requests.
767
   */
768
769
0
  if (!MessageQueue_Post(serial->MainIrpQueue, NULL, 0, (void*)irp, NULL))
770
0
  {
771
0
    WLog_Print(serial->log, WLOG_ERROR, "MessageQueue_Post failed!");
772
0
    return ERROR_INTERNAL_ERROR;
773
0
  }
774
775
0
  return CHANNEL_RC_OK;
776
0
}
777
778
/**
779
 * Function description
780
 *
781
 * @return 0 on success, otherwise a Win32 error code
782
 */
783
static UINT serial_free(DEVICE* device)
784
0
{
785
0
  UINT error = 0;
786
0
  SERIAL_DEVICE* serial = (SERIAL_DEVICE*)device;
787
0
  if (!serial)
788
0
    return CHANNEL_RC_OK;
789
790
0
  WLog_Print(serial->log, WLOG_DEBUG, "freeing");
791
0
  if (serial->MainIrpQueue)
792
0
    MessageQueue_PostQuit(serial->MainIrpQueue, 0);
793
794
0
  if (serial->MainThread)
795
0
  {
796
0
    if (WaitForSingleObject(serial->MainThread, INFINITE) == WAIT_FAILED)
797
0
    {
798
0
      error = GetLastError();
799
0
      WLog_Print(serial->log, WLOG_ERROR,
800
0
                 "WaitForSingleObject failed with error %" PRIu32 "!", error);
801
0
    }
802
0
    (void)CloseHandle(serial->MainThread);
803
0
  }
804
805
0
  if (serial->hComm)
806
0
    (void)CloseHandle(serial->hComm);
807
808
  /* Clean up resources */
809
0
  Stream_Free(serial->device.data, TRUE);
810
0
  MessageQueue_Free(serial->MainIrpQueue);
811
0
  ListDictionary_Free(serial->IrpThreads);
812
0
  DeleteCriticalSection(&serial->TerminatingIrpThreadsLock);
813
0
  free(serial);
814
0
  return CHANNEL_RC_OK;
815
0
}
816
817
static void serial_message_free(void* obj)
818
0
{
819
0
  wMessage* msg = obj;
820
0
  if (!msg)
821
0
    return;
822
0
  if (msg->id != 0)
823
0
    return;
824
825
0
  IRP* irp = (IRP*)msg->wParam;
826
0
  if (!irp)
827
0
    return;
828
0
  WINPR_ASSERT(irp->Discard);
829
0
  irp->Discard(irp);
830
0
}
831
832
static void irp_thread_close(void* arg)
833
0
{
834
0
  HANDLE hdl = arg;
835
0
  if (hdl)
836
0
  {
837
0
    HANDLE thz = _GetCurrentThread();
838
0
    if (thz == hdl)
839
0
      WLog_WARN(TAG, "closing self, ignoring...");
840
0
    else
841
0
    {
842
0
      (void)TerminateThread(hdl, 0);
843
0
      (void)WaitForSingleObject(hdl, INFINITE);
844
0
      (void)CloseHandle(hdl);
845
0
    }
846
0
  }
847
0
}
848
849
/**
850
 * Function description
851
 *
852
 * @return 0 on success, otherwise a Win32 error code
853
 */
854
FREERDP_ENTRY_POINT(
855
    UINT VCAPITYPE serial_DeviceServiceEntry(PDEVICE_SERVICE_ENTRY_POINTS pEntryPoints))
856
0
{
857
0
  size_t len = 0;
858
0
  SERIAL_DEVICE* serial = NULL;
859
0
  UINT error = CHANNEL_RC_OK;
860
861
0
  WINPR_ASSERT(pEntryPoints);
862
863
0
  RDPDR_SERIAL* device = (RDPDR_SERIAL*)pEntryPoints->device;
864
0
  WINPR_ASSERT(device);
865
866
0
  wLog* log = WLog_Get(TAG);
867
0
  const char* name = device->device.Name;
868
0
  const char* path = device->Path;
869
0
  const char* driver = device->Driver;
870
871
0
  if (!name || (name[0] == '*'))
872
0
  {
873
    /* TODO: implement auto detection of serial ports */
874
0
    WLog_Print(log, WLOG_WARN,
875
0
               "Serial port autodetection not implemented, nothing will be redirected!");
876
0
    return CHANNEL_RC_OK;
877
0
  }
878
879
0
  if ((name && name[0]) && (path && path[0]))
880
0
  {
881
0
    WLog_Print(log, WLOG_DEBUG, "Defining %s as %s", name, path);
882
883
0
    if (!DefineCommDevice(name /* eg: COM1 */, path /* eg: /dev/ttyS0 */))
884
0
    {
885
0
      DWORD status = GetLastError();
886
0
      WLog_Print(log, WLOG_ERROR, "DefineCommDevice failed with %08" PRIx32, status);
887
0
      return ERROR_INTERNAL_ERROR;
888
0
    }
889
890
0
    serial = (SERIAL_DEVICE*)calloc(1, sizeof(SERIAL_DEVICE));
891
892
0
    if (!serial)
893
0
    {
894
0
      WLog_Print(log, WLOG_ERROR, "calloc failed!");
895
0
      return CHANNEL_RC_NO_MEMORY;
896
0
    }
897
898
0
    serial->log = log;
899
0
    serial->device.type = RDPDR_DTYP_SERIAL;
900
0
    serial->device.name = name;
901
0
    serial->device.IRPRequest = serial_irp_request;
902
0
    serial->device.Free = serial_free;
903
0
    serial->rdpcontext = pEntryPoints->rdpcontext;
904
0
    len = strlen(name);
905
0
    serial->device.data = Stream_New(NULL, len + 1);
906
907
0
    if (!serial->device.data)
908
0
    {
909
0
      WLog_Print(serial->log, WLOG_ERROR, "calloc failed!");
910
0
      error = CHANNEL_RC_NO_MEMORY;
911
0
      goto error_out;
912
0
    }
913
914
0
    for (size_t i = 0; i <= len; i++)
915
0
      Stream_Write_INT8(serial->device.data, name[i] < 0 ? '_' : name[i]);
916
917
0
    if (driver != NULL)
918
0
    {
919
0
      if (_stricmp(driver, "Serial") == 0)
920
0
        serial->ServerSerialDriverId = SerialDriverSerialSys;
921
0
      else if (_stricmp(driver, "SerCx") == 0)
922
0
        serial->ServerSerialDriverId = SerialDriverSerCxSys;
923
0
      else if (_stricmp(driver, "SerCx2") == 0)
924
0
        serial->ServerSerialDriverId = SerialDriverSerCx2Sys;
925
0
      else
926
0
      {
927
0
        WLog_Print(serial->log, WLOG_WARN, "Unknown server's serial driver: %s.", driver);
928
0
        WLog_Print(serial->log, WLOG_WARN,
929
0
                   "Valid options are: 'Serial' (default), 'SerCx' and 'SerCx2'");
930
0
        goto error_out;
931
0
      }
932
0
    }
933
0
    else
934
0
    {
935
      /* default driver */
936
0
      serial->ServerSerialDriverId = SerialDriverSerialSys;
937
0
    }
938
939
0
    if (device->Permissive != NULL)
940
0
    {
941
0
      if (_stricmp(device->Permissive, "permissive") == 0)
942
0
      {
943
0
        serial->permissive = TRUE;
944
0
      }
945
0
      else
946
0
      {
947
0
        WLog_Print(serial->log, WLOG_WARN, "Unknown flag: %s", device->Permissive);
948
0
        goto error_out;
949
0
      }
950
0
    }
951
952
0
    WLog_Print(serial->log, WLOG_DEBUG, "Server's serial driver: %s (id: %u)", driver,
953
0
               serial->ServerSerialDriverId);
954
955
0
    serial->MainIrpQueue = MessageQueue_New(NULL);
956
957
0
    if (!serial->MainIrpQueue)
958
0
    {
959
0
      WLog_Print(serial->log, WLOG_ERROR, "MessageQueue_New failed!");
960
0
      error = CHANNEL_RC_NO_MEMORY;
961
0
      goto error_out;
962
0
    }
963
964
0
    {
965
0
      wObject* obj = MessageQueue_Object(serial->MainIrpQueue);
966
0
      WINPR_ASSERT(obj);
967
0
      obj->fnObjectFree = serial_message_free;
968
0
    }
969
970
    /* IrpThreads content only modified by create_irp_thread() */
971
0
    serial->IrpThreads = ListDictionary_New(FALSE);
972
973
0
    if (!serial->IrpThreads)
974
0
    {
975
0
      WLog_Print(serial->log, WLOG_ERROR, "ListDictionary_New failed!");
976
0
      error = CHANNEL_RC_NO_MEMORY;
977
0
      goto error_out;
978
0
    }
979
980
0
    {
981
0
      wObject* obj = ListDictionary_ValueObject(serial->IrpThreads);
982
0
      WINPR_ASSERT(obj);
983
0
      obj->fnObjectFree = irp_thread_close;
984
0
    }
985
986
0
    InitializeCriticalSection(&serial->TerminatingIrpThreadsLock);
987
988
0
    error = pEntryPoints->RegisterDevice(pEntryPoints->devman, &serial->device);
989
0
    if (error != CHANNEL_RC_OK)
990
0
    {
991
0
      WLog_Print(serial->log, WLOG_ERROR,
992
0
                 "EntryPoints->RegisterDevice failed with error %" PRIu32 "!", error);
993
0
      goto error_out;
994
0
    }
995
996
0
    serial->MainThread = CreateThread(NULL, 0, serial_thread_func, serial, 0, NULL);
997
0
    if (!serial->MainThread)
998
0
    {
999
0
      WLog_Print(serial->log, WLOG_ERROR, "CreateThread failed!");
1000
0
      error = ERROR_INTERNAL_ERROR;
1001
0
      goto error_out;
1002
0
    }
1003
0
  }
1004
1005
0
  return error;
1006
0
error_out:
1007
0
  if (serial)
1008
0
    serial_free(&serial->device);
1009
0
  return error;
1010
0
}