Coverage Report

Created: 2025-07-01 06:46

/src/FreeRDP/channels/serial/client/serial_main.c
Line
Count
Source (jump to first uncovered line)
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
  DWORD BytesReturned = 0;
198
0
  if (!CommDeviceIoControl(serial->hComm, IOCTL_SERIAL_RESET_DEVICE, NULL, 0, NULL, 0,
199
0
                           &BytesReturned, NULL))
200
0
    goto error_handle;
201
202
0
error_handle:
203
0
  Stream_Write_UINT32(irp->output, irp->FileId); /* FileId (4 bytes) */
204
0
  Stream_Write_UINT8(irp->output, 0);            /* Information (1 byte) */
205
0
  return CHANNEL_RC_OK;
206
0
}
207
208
static UINT serial_process_irp_close(SERIAL_DEVICE* serial, IRP* irp)
209
0
{
210
0
  WINPR_ASSERT(serial);
211
0
  WINPR_ASSERT(irp);
212
213
0
  if (!Stream_CheckAndLogRequiredLengthWLog(serial->log, irp->input, 32))
214
0
    return ERROR_INVALID_DATA;
215
216
0
  Stream_Seek(irp->input, 32); /* Padding (32 bytes) */
217
218
0
  close_terminated_irp_thread_handles(serial, TRUE);
219
220
0
  if (!CloseHandle(serial->hComm))
221
0
  {
222
0
    WLog_Print(serial->log, WLOG_WARN, "CloseHandle failure: %s (%" PRIu32 ") closed.",
223
0
               serial->device.name, irp->device->id);
224
0
    irp->IoStatus = STATUS_UNSUCCESSFUL;
225
0
    goto error_handle;
226
0
  }
227
228
0
  WLog_Print(serial->log, WLOG_DEBUG, "%s (DeviceId: %" PRIu32 ", FileId: %" PRIu32 ") closed.",
229
0
             serial->device.name, irp->device->id, irp->FileId);
230
0
  irp->IoStatus = STATUS_SUCCESS;
231
0
error_handle:
232
0
  serial->hComm = NULL;
233
0
  Stream_Zero(irp->output, 5); /* Padding (5 bytes) */
234
0
  return CHANNEL_RC_OK;
235
0
}
236
237
/**
238
 * Function description
239
 *
240
 * @return 0 on success, otherwise a Win32 error code
241
 */
242
static UINT serial_process_irp_read(SERIAL_DEVICE* serial, IRP* irp)
243
0
{
244
0
  UINT32 Length = 0;
245
0
  UINT64 Offset = 0;
246
0
  BYTE* buffer = NULL;
247
0
  DWORD nbRead = 0;
248
249
0
  WINPR_ASSERT(serial);
250
0
  WINPR_ASSERT(irp);
251
252
0
  if (!Stream_CheckAndLogRequiredLengthWLog(serial->log, irp->input, 32))
253
0
    return ERROR_INVALID_DATA;
254
255
0
  Stream_Read_UINT32(irp->input, Length); /* Length (4 bytes) */
256
0
  Stream_Read_UINT64(irp->input, Offset); /* Offset (8 bytes) */
257
0
  (void)Offset; /* [MS-RDPESP] 3.2.5.1.4 Processing a Server Read Request Message
258
                 * ignored */
259
0
  Stream_Seek(irp->input, 20);            /* Padding (20 bytes) */
260
0
  buffer = (BYTE*)calloc(Length, sizeof(BYTE));
261
262
0
  if (buffer == NULL)
263
0
  {
264
0
    irp->IoStatus = STATUS_NO_MEMORY;
265
0
    goto error_handle;
266
0
  }
267
268
  /* MS-RDPESP 3.2.5.1.4: If the Offset field is not set to 0, the value MUST be ignored
269
   * WINPR_ASSERT(Offset == 0);
270
   */
271
0
  WLog_Print(serial->log, WLOG_DEBUG, "reading %" PRIu32 " bytes from %s", Length,
272
0
             serial->device.name);
273
274
  /* FIXME: CommReadFile to be replaced by ReadFile */
275
0
  if (CommReadFile(serial->hComm, buffer, Length, &nbRead, NULL))
276
0
  {
277
0
    irp->IoStatus = STATUS_SUCCESS;
278
0
  }
279
0
  else
280
0
  {
281
0
    WLog_Print(serial->log, WLOG_DEBUG,
282
0
               "read failure to %s, nbRead=%" PRIu32 ", last-error: 0x%08" PRIX32 "",
283
0
               serial->device.name, nbRead, GetLastError());
284
0
    irp->IoStatus = GetLastErrorToIoStatus(serial);
285
0
  }
286
287
0
  WLog_Print(serial->log, WLOG_DEBUG, "%" PRIu32 " bytes read from %s", nbRead,
288
0
             serial->device.name);
289
0
error_handle:
290
0
  Stream_Write_UINT32(irp->output, nbRead); /* Length (4 bytes) */
291
292
0
  if (nbRead > 0)
293
0
  {
294
0
    if (!Stream_EnsureRemainingCapacity(irp->output, nbRead))
295
0
    {
296
0
      WLog_Print(serial->log, WLOG_ERROR, "Stream_EnsureRemainingCapacity failed!");
297
0
      free(buffer);
298
0
      return CHANNEL_RC_NO_MEMORY;
299
0
    }
300
301
0
    Stream_Write(irp->output, buffer, nbRead); /* ReadData */
302
0
  }
303
304
0
  free(buffer);
305
0
  return CHANNEL_RC_OK;
306
0
}
307
308
static UINT serial_process_irp_write(SERIAL_DEVICE* serial, IRP* irp)
309
0
{
310
0
  UINT32 Length = 0;
311
0
  UINT64 Offset = 0;
312
0
  DWORD nbWritten = 0;
313
314
0
  WINPR_ASSERT(serial);
315
0
  WINPR_ASSERT(irp);
316
317
0
  if (!Stream_CheckAndLogRequiredLengthWLog(serial->log, irp->input, 32))
318
0
    return ERROR_INVALID_DATA;
319
320
0
  Stream_Read_UINT32(irp->input, Length); /* Length (4 bytes) */
321
0
  Stream_Read_UINT64(irp->input, Offset); /* Offset (8 bytes) */
322
0
  (void)Offset; /* [MS-RDPESP] 3.2.5.1.4 Processing a Server Read Request Message
323
                 * ignored */
324
0
  if (!Stream_SafeSeek(irp->input, 20))   /* Padding (20 bytes) */
325
0
    return ERROR_INVALID_DATA;
326
327
  /* MS-RDPESP 3.2.5.1.5: The Offset field is ignored
328
   * WINPR_ASSERT(Offset == 0);
329
   *
330
   * Using a serial printer, noticed though this field could be
331
   * set.
332
   */
333
0
  WLog_Print(serial->log, WLOG_DEBUG, "writing %" PRIu32 " bytes to %s", Length,
334
0
             serial->device.name);
335
336
0
  const void* ptr = Stream_ConstPointer(irp->input);
337
0
  if (!Stream_SafeSeek(irp->input, Length))
338
0
    return ERROR_INVALID_DATA;
339
  /* FIXME: CommWriteFile to be replaced by WriteFile */
340
0
  if (CommWriteFile(serial->hComm, ptr, Length, &nbWritten, NULL))
341
0
  {
342
0
    irp->IoStatus = STATUS_SUCCESS;
343
0
  }
344
0
  else
345
0
  {
346
0
    WLog_Print(serial->log, WLOG_DEBUG,
347
0
               "write failure to %s, nbWritten=%" PRIu32 ", last-error: 0x%08" PRIX32 "",
348
0
               serial->device.name, nbWritten, GetLastError());
349
0
    irp->IoStatus = GetLastErrorToIoStatus(serial);
350
0
  }
351
352
0
  WLog_Print(serial->log, WLOG_DEBUG, "%" PRIu32 " bytes written to %s", nbWritten,
353
0
             serial->device.name);
354
0
  Stream_Write_UINT32(irp->output, nbWritten); /* Length (4 bytes) */
355
0
  Stream_Write_UINT8(irp->output, 0);          /* Padding (1 byte) */
356
0
  return CHANNEL_RC_OK;
357
0
}
358
359
/**
360
 * Function description
361
 *
362
 * @return 0 on success, otherwise a Win32 error code
363
 */
364
static UINT serial_process_irp_device_control(SERIAL_DEVICE* serial, IRP* irp)
365
0
{
366
0
  UINT32 IoControlCode = 0;
367
0
  UINT32 InputBufferLength = 0;
368
0
  BYTE* InputBuffer = NULL;
369
0
  UINT32 OutputBufferLength = 0;
370
0
  BYTE* OutputBuffer = NULL;
371
0
  DWORD BytesReturned = 0;
372
373
0
  WINPR_ASSERT(serial);
374
0
  WINPR_ASSERT(irp);
375
376
0
  if (!Stream_CheckAndLogRequiredLengthWLog(serial->log, irp->input, 32))
377
0
    return ERROR_INVALID_DATA;
378
379
0
  Stream_Read_UINT32(irp->input, OutputBufferLength); /* OutputBufferLength (4 bytes) */
380
0
  Stream_Read_UINT32(irp->input, InputBufferLength);  /* InputBufferLength (4 bytes) */
381
0
  Stream_Read_UINT32(irp->input, IoControlCode);      /* IoControlCode (4 bytes) */
382
0
  Stream_Seek(irp->input, 20);                        /* Padding (20 bytes) */
383
384
0
  if (!Stream_CheckAndLogRequiredLengthWLog(serial->log, irp->input, InputBufferLength))
385
0
    return ERROR_INVALID_DATA;
386
387
0
  OutputBuffer = (BYTE*)calloc(OutputBufferLength, sizeof(BYTE));
388
389
0
  if (OutputBuffer == NULL)
390
0
  {
391
0
    irp->IoStatus = STATUS_NO_MEMORY;
392
0
    goto error_handle;
393
0
  }
394
395
0
  InputBuffer = (BYTE*)calloc(InputBufferLength, sizeof(BYTE));
396
397
0
  if (InputBuffer == NULL)
398
0
  {
399
0
    irp->IoStatus = STATUS_NO_MEMORY;
400
0
    goto error_handle;
401
0
  }
402
403
0
  Stream_Read(irp->input, InputBuffer, InputBufferLength);
404
0
  WLog_Print(serial->log, WLOG_DEBUG,
405
0
             "CommDeviceIoControl: CompletionId=%" PRIu32 ", IoControlCode=[0x%" PRIX32 "] %s",
406
0
             irp->CompletionId, IoControlCode, _comm_serial_ioctl_name(IoControlCode));
407
408
  /* FIXME: CommDeviceIoControl to be replaced by DeviceIoControl() */
409
0
  if (CommDeviceIoControl(serial->hComm, IoControlCode, InputBuffer, InputBufferLength,
410
0
                          OutputBuffer, OutputBufferLength, &BytesReturned, NULL))
411
0
  {
412
    /* WLog_Print(serial->log, WLOG_DEBUG, "CommDeviceIoControl: CompletionId=%"PRIu32",
413
     * IoControlCode=[0x%"PRIX32"] %s done", irp->CompletionId, IoControlCode,
414
     * _comm_serial_ioctl_name(IoControlCode)); */
415
0
    irp->IoStatus = STATUS_SUCCESS;
416
0
  }
417
0
  else
418
0
  {
419
0
    WLog_Print(serial->log, WLOG_DEBUG,
420
0
               "CommDeviceIoControl failure: IoControlCode=[0x%" PRIX32
421
0
               "] %s, last-error: 0x%08" PRIX32 "",
422
0
               IoControlCode, _comm_serial_ioctl_name(IoControlCode), GetLastError());
423
0
    irp->IoStatus = GetLastErrorToIoStatus(serial);
424
0
  }
425
426
0
error_handle:
427
  /* FIXME: find out whether it's required or not to get
428
   * BytesReturned == OutputBufferLength when
429
   * CommDeviceIoControl returns FALSE */
430
0
  WINPR_ASSERT(OutputBufferLength == BytesReturned);
431
0
  Stream_Write_UINT32(irp->output, BytesReturned); /* OutputBufferLength (4 bytes) */
432
433
0
  if (BytesReturned > 0)
434
0
  {
435
0
    if (!Stream_EnsureRemainingCapacity(irp->output, BytesReturned))
436
0
    {
437
0
      WLog_Print(serial->log, WLOG_ERROR, "Stream_EnsureRemainingCapacity failed!");
438
0
      free(InputBuffer);
439
0
      free(OutputBuffer);
440
0
      return CHANNEL_RC_NO_MEMORY;
441
0
    }
442
443
0
    Stream_Write(irp->output, OutputBuffer, BytesReturned); /* OutputBuffer */
444
0
  }
445
446
  /* FIXME: Why at least Windows 2008R2 gets lost with this
447
   * extra byte and likely on a IOCTL_SERIAL_SET_BAUD_RATE? The
448
   * extra byte is well required according MS-RDPEFS
449
   * 2.2.1.5.5 */
450
  /* else */
451
  /* { */
452
  /*  Stream_Write_UINT8(irp->output, 0); /\* Padding (1 byte) *\/ */
453
  /* } */
454
0
  free(InputBuffer);
455
0
  free(OutputBuffer);
456
0
  return CHANNEL_RC_OK;
457
0
}
458
459
/**
460
 * Function description
461
 *
462
 * @return 0 on success, otherwise a Win32 error code
463
 */
464
static UINT serial_process_irp(SERIAL_DEVICE* serial, IRP* irp)
465
0
{
466
0
  UINT error = CHANNEL_RC_OK;
467
468
0
  WINPR_ASSERT(serial);
469
0
  WINPR_ASSERT(irp);
470
471
0
  WLog_Print(serial->log, WLOG_DEBUG, "IRP MajorFunction: %s, MinorFunction: 0x%08" PRIX32 "\n",
472
0
             rdpdr_irp_string(irp->MajorFunction), irp->MinorFunction);
473
474
0
  switch (irp->MajorFunction)
475
0
  {
476
0
    case IRP_MJ_CREATE:
477
0
      error = serial_process_irp_create(serial, irp);
478
0
      break;
479
480
0
    case IRP_MJ_CLOSE:
481
0
      error = serial_process_irp_close(serial, irp);
482
0
      break;
483
484
0
    case IRP_MJ_READ:
485
0
      error = serial_process_irp_read(serial, irp);
486
0
      break;
487
488
0
    case IRP_MJ_WRITE:
489
0
      error = serial_process_irp_write(serial, irp);
490
0
      break;
491
492
0
    case IRP_MJ_DEVICE_CONTROL:
493
0
      error = serial_process_irp_device_control(serial, irp);
494
0
      break;
495
496
0
    default:
497
0
      irp->IoStatus = STATUS_NOT_SUPPORTED;
498
0
      break;
499
0
  }
500
501
0
  DWORD level = WLOG_TRACE;
502
0
  if (error)
503
0
    level = WLOG_WARN;
504
505
0
  WLog_Print(serial->log, level,
506
0
             "[%s|0x%08" PRIx32 "] completed with %s [0x%08" PRIx32 "] (IoStatus %s [0x%08" PRIx32
507
0
             "])",
508
0
             rdpdr_irp_string(irp->MajorFunction), irp->MajorFunction, WTSErrorToString(error),
509
0
             error, NtStatus2Tag(irp->IoStatus), irp->IoStatus);
510
511
0
  return error;
512
0
}
513
514
static DWORD WINAPI irp_thread_func(LPVOID arg)
515
0
{
516
0
  IRP_THREAD_DATA* data = (IRP_THREAD_DATA*)arg;
517
0
  UINT error = 0;
518
519
0
  WINPR_ASSERT(data);
520
0
  WINPR_ASSERT(data->serial);
521
0
  WINPR_ASSERT(data->irp);
522
523
  /* blocks until the end of the request */
524
0
  if ((error = serial_process_irp(data->serial, data->irp)))
525
0
  {
526
0
    WLog_Print(data->serial->log, WLOG_ERROR,
527
0
               "serial_process_irp failed with error %" PRIu32 "", error);
528
0
    goto error_out;
529
0
  }
530
531
0
  EnterCriticalSection(&data->serial->TerminatingIrpThreadsLock);
532
0
  WINPR_ASSERT(data->irp->Complete);
533
0
  error = data->irp->Complete(data->irp);
534
0
  LeaveCriticalSection(&data->serial->TerminatingIrpThreadsLock);
535
0
error_out:
536
537
0
  if (error && data->serial->rdpcontext)
538
0
    setChannelError(data->serial->rdpcontext, error, "irp_thread_func reported an error");
539
540
0
  if (error)
541
0
    data->irp->Discard(data->irp);
542
543
  /* NB: At this point, the server might already being reusing
544
   * the CompletionId whereas the thread is not yet
545
   * terminated */
546
0
  free(data);
547
0
  ExitThread(error);
548
0
  return error;
549
0
}
550
551
static void close_unterminated_irp_thread(wListDictionary* list, wLog* log, ULONG_PTR id)
552
0
{
553
0
  WINPR_ASSERT(list);
554
0
  HANDLE self = _GetCurrentThread();
555
0
  HANDLE cirpThread = ListDictionary_GetItemValue(list, (void*)id);
556
0
  if (self == cirpThread)
557
0
    WLog_Print(log, WLOG_DEBUG, "Skipping termination of own IRP thread");
558
0
  else
559
0
    ListDictionary_Remove(list, (void*)id);
560
0
}
561
562
static void close_terminated_irp_thread(wListDictionary* list, wLog* log, ULONG_PTR id)
563
0
{
564
0
  WINPR_ASSERT(list);
565
566
0
  HANDLE cirpThread = ListDictionary_GetItemValue(list, (void*)id);
567
  /* FIXME: not quite sure a zero timeout is a good thing to check whether a thread is
568
   * still alive or not */
569
0
  const DWORD waitResult = WaitForSingleObject(cirpThread, 0);
570
571
0
  if (waitResult == WAIT_OBJECT_0)
572
0
    ListDictionary_Remove(list, (void*)id);
573
0
  else if (waitResult != WAIT_TIMEOUT)
574
0
  {
575
    /* unexpected thread state */
576
0
    WLog_Print(log, WLOG_WARN, "WaitForSingleObject, got an unexpected result=0x%" PRIX32 "\n",
577
0
               waitResult);
578
0
  }
579
0
}
580
581
void close_terminated_irp_thread_handles(SERIAL_DEVICE* serial, BOOL forceClose)
582
0
{
583
0
  WINPR_ASSERT(serial);
584
585
0
  EnterCriticalSection(&serial->TerminatingIrpThreadsLock);
586
587
0
  ULONG_PTR* ids = NULL;
588
0
  const size_t nbIds = ListDictionary_GetKeys(serial->IrpThreads, &ids);
589
590
0
  for (size_t i = 0; i < nbIds; i++)
591
0
  {
592
0
    ULONG_PTR id = ids[i];
593
0
    if (forceClose)
594
0
      close_unterminated_irp_thread(serial->IrpThreads, serial->log, id);
595
0
    else
596
0
      close_terminated_irp_thread(serial->IrpThreads, serial->log, id);
597
0
  }
598
599
0
  free(ids);
600
601
0
  LeaveCriticalSection(&serial->TerminatingIrpThreadsLock);
602
0
}
603
604
static void create_irp_thread(SERIAL_DEVICE* serial, IRP* irp)
605
0
{
606
0
  IRP_THREAD_DATA* data = NULL;
607
0
  HANDLE irpThread = NULL;
608
0
  HANDLE previousIrpThread = NULL;
609
0
  uintptr_t key = 0;
610
611
0
  WINPR_ASSERT(serial);
612
0
  WINPR_ASSERT(irp);
613
614
0
  close_terminated_irp_thread_handles(serial, FALSE);
615
616
  /* NB: At this point and thanks to the synchronization we're
617
   * sure that the incoming IRP uses well a recycled
618
   * CompletionId or the server sent again an IRP already posted
619
   * which didn't get yet a response (this later server behavior
620
   * at least observed with IOCTL_SERIAL_WAIT_ON_MASK and
621
   * mstsc.exe).
622
   *
623
   * FIXME: behavior documented somewhere? behavior not yet
624
   * observed with FreeRDP).
625
   */
626
0
  key = irp->CompletionId + 1ull;
627
0
  previousIrpThread = ListDictionary_GetItemValue(serial->IrpThreads, (void*)key);
628
629
0
  if (previousIrpThread)
630
0
  {
631
    /* Thread still alived <=> Request still pending */
632
0
    WLog_Print(serial->log, WLOG_DEBUG,
633
0
               "IRP recall: IRP with the CompletionId=%" PRIu32 " not yet completed!",
634
0
               irp->CompletionId);
635
0
    WINPR_ASSERT(FALSE); /* unimplemented */
636
    /* TODO: WINPR_ASSERTs that previousIrpThread handles well
637
     * the same request by checking more details. Need an
638
     * access to the IRP object used by previousIrpThread
639
     */
640
    /* TODO: taking over the pending IRP or sending a kind
641
     * of wake up signal to accelerate the pending
642
     * request
643
     *
644
     * To be considered:
645
     *   if (IoControlCode == IOCTL_SERIAL_WAIT_ON_MASK) {
646
     *       pComm->PendingEvents |= SERIAL_EV_FREERDP_*;
647
     *   }
648
     */
649
0
    irp->Discard(irp);
650
0
    return;
651
0
  }
652
653
0
  if (ListDictionary_Count(serial->IrpThreads) >= MAX_IRP_THREADS)
654
0
  {
655
0
    WLog_Print(serial->log, WLOG_WARN,
656
0
               "Number of IRP threads threshold reached: %" PRIuz ", keep on anyway",
657
0
               ListDictionary_Count(serial->IrpThreads));
658
0
    WINPR_ASSERT(FALSE); /* unimplemented */
659
                         /* TODO: MAX_IRP_THREADS has been thought to avoid a
660
                          * flooding of pending requests. Use
661
                          * WaitForMultipleObjects() when available in winpr
662
                          * for threads.
663
                          */
664
0
  }
665
666
  /* error_handle to be used ... */
667
0
  data = (IRP_THREAD_DATA*)calloc(1, sizeof(IRP_THREAD_DATA));
668
669
0
  if (data == NULL)
670
0
  {
671
0
    WLog_Print(serial->log, WLOG_WARN, "Could not allocate a new IRP_THREAD_DATA.");
672
0
    goto error_handle;
673
0
  }
674
675
0
  data->serial = serial;
676
0
  data->irp = irp;
677
  /* data freed by irp_thread_func */
678
0
  irpThread = CreateThread(NULL, 0, irp_thread_func, (void*)data, CREATE_SUSPENDED, NULL);
679
680
0
  if (irpThread == INVALID_HANDLE_VALUE)
681
0
  {
682
0
    WLog_Print(serial->log, WLOG_WARN, "Could not allocate a new IRP thread.");
683
0
    goto error_handle;
684
0
  }
685
686
0
  key = irp->CompletionId + 1ull;
687
688
0
  if (!ListDictionary_Add(serial->IrpThreads, (void*)key, irpThread))
689
0
  {
690
0
    WLog_Print(serial->log, WLOG_ERROR, "ListDictionary_Add failed!");
691
0
    goto error_handle;
692
0
  }
693
694
0
  ResumeThread(irpThread);
695
696
0
  return;
697
0
error_handle:
698
0
  if (irpThread)
699
0
    (void)CloseHandle(irpThread);
700
0
  irp->IoStatus = STATUS_NO_MEMORY;
701
0
  WINPR_ASSERT(irp->Complete);
702
0
  irp->Complete(irp);
703
0
  free(data);
704
0
}
705
706
static DWORD WINAPI serial_thread_func(LPVOID arg)
707
0
{
708
0
  IRP* irp = NULL;
709
0
  wMessage message = { 0 };
710
0
  SERIAL_DEVICE* serial = (SERIAL_DEVICE*)arg;
711
0
  UINT error = CHANNEL_RC_OK;
712
713
0
  WINPR_ASSERT(serial);
714
715
0
  while (1)
716
0
  {
717
0
    if (!MessageQueue_Wait(serial->MainIrpQueue))
718
0
    {
719
0
      WLog_Print(serial->log, WLOG_ERROR, "MessageQueue_Wait failed!");
720
0
      error = ERROR_INTERNAL_ERROR;
721
0
      break;
722
0
    }
723
724
0
    if (!MessageQueue_Peek(serial->MainIrpQueue, &message, TRUE))
725
0
    {
726
0
      WLog_Print(serial->log, WLOG_ERROR, "MessageQueue_Peek failed!");
727
0
      error = ERROR_INTERNAL_ERROR;
728
0
      break;
729
0
    }
730
731
0
    if (message.id == WMQ_QUIT)
732
0
      break;
733
734
0
    irp = (IRP*)message.wParam;
735
736
0
    if (irp)
737
0
      create_irp_thread(serial, irp);
738
0
  }
739
740
0
  ListDictionary_Clear(serial->IrpThreads);
741
0
  if (error && serial->rdpcontext)
742
0
    setChannelError(serial->rdpcontext, error, "serial_thread_func reported an error");
743
744
0
  ExitThread(error);
745
0
  return error;
746
0
}
747
748
/**
749
 * Function description
750
 *
751
 * @return 0 on success, otherwise a Win32 error code
752
 */
753
static UINT serial_irp_request(DEVICE* device, IRP* irp)
754
0
{
755
0
  SERIAL_DEVICE* serial = (SERIAL_DEVICE*)device;
756
0
  WINPR_ASSERT(irp != NULL);
757
0
  WINPR_ASSERT(serial);
758
759
0
  if (irp == NULL)
760
0
    return CHANNEL_RC_OK;
761
762
  /* NB: ENABLE_ASYNCIO is set, (MS-RDPEFS 2.2.2.7.2) this
763
   * allows the server to send multiple simultaneous read or
764
   * write requests.
765
   */
766
767
0
  if (!MessageQueue_Post(serial->MainIrpQueue, NULL, 0, (void*)irp, NULL))
768
0
  {
769
0
    WLog_Print(serial->log, WLOG_ERROR, "MessageQueue_Post failed!");
770
0
    return ERROR_INTERNAL_ERROR;
771
0
  }
772
773
0
  return CHANNEL_RC_OK;
774
0
}
775
776
/**
777
 * Function description
778
 *
779
 * @return 0 on success, otherwise a Win32 error code
780
 */
781
static UINT serial_free(DEVICE* device)
782
0
{
783
0
  UINT error = 0;
784
0
  SERIAL_DEVICE* serial = (SERIAL_DEVICE*)device;
785
0
  if (!serial)
786
0
    return CHANNEL_RC_OK;
787
788
0
  WLog_Print(serial->log, WLOG_DEBUG, "freeing");
789
0
  if (serial->MainIrpQueue)
790
0
    MessageQueue_PostQuit(serial->MainIrpQueue, 0);
791
792
0
  if (serial->MainThread)
793
0
  {
794
0
    if (WaitForSingleObject(serial->MainThread, INFINITE) == WAIT_FAILED)
795
0
    {
796
0
      error = GetLastError();
797
0
      WLog_Print(serial->log, WLOG_ERROR,
798
0
                 "WaitForSingleObject failed with error %" PRIu32 "!", error);
799
0
    }
800
0
    (void)CloseHandle(serial->MainThread);
801
0
  }
802
803
0
  if (serial->hComm)
804
0
    (void)CloseHandle(serial->hComm);
805
806
  /* Clean up resources */
807
0
  Stream_Free(serial->device.data, TRUE);
808
0
  MessageQueue_Free(serial->MainIrpQueue);
809
0
  ListDictionary_Free(serial->IrpThreads);
810
0
  DeleteCriticalSection(&serial->TerminatingIrpThreadsLock);
811
0
  free(serial);
812
0
  return CHANNEL_RC_OK;
813
0
}
814
815
static void serial_message_free(void* obj)
816
0
{
817
0
  wMessage* msg = obj;
818
0
  if (!msg)
819
0
    return;
820
0
  if (msg->id != 0)
821
0
    return;
822
823
0
  IRP* irp = (IRP*)msg->wParam;
824
0
  if (!irp)
825
0
    return;
826
0
  WINPR_ASSERT(irp->Discard);
827
0
  irp->Discard(irp);
828
0
}
829
830
static void irp_thread_close(void* arg)
831
0
{
832
0
  HANDLE hdl = arg;
833
0
  if (hdl)
834
0
  {
835
0
    HANDLE thz = _GetCurrentThread();
836
0
    if (thz == hdl)
837
0
      WLog_WARN(TAG, "closing self, ignoring...");
838
0
    else
839
0
    {
840
0
      (void)TerminateThread(hdl, 0);
841
0
      (void)WaitForSingleObject(hdl, INFINITE);
842
0
      (void)CloseHandle(hdl);
843
0
    }
844
0
  }
845
0
}
846
847
/**
848
 * Function description
849
 *
850
 * @return 0 on success, otherwise a Win32 error code
851
 */
852
FREERDP_ENTRY_POINT(
853
    UINT VCAPITYPE serial_DeviceServiceEntry(PDEVICE_SERVICE_ENTRY_POINTS pEntryPoints))
854
0
{
855
0
  size_t len = 0;
856
0
  SERIAL_DEVICE* serial = NULL;
857
0
  UINT error = CHANNEL_RC_OK;
858
859
0
  WINPR_ASSERT(pEntryPoints);
860
861
0
  RDPDR_SERIAL* device = (RDPDR_SERIAL*)pEntryPoints->device;
862
0
  WINPR_ASSERT(device);
863
864
0
  wLog* log = WLog_Get(TAG);
865
0
  const char* name = device->device.Name;
866
0
  const char* path = device->Path;
867
0
  const char* driver = device->Driver;
868
869
0
  if (!name || (name[0] == '*'))
870
0
  {
871
    /* TODO: implement auto detection of serial ports */
872
0
    WLog_Print(log, WLOG_WARN,
873
0
               "Serial port autodetection not implemented, nothing will be redirected!");
874
0
    return CHANNEL_RC_OK;
875
0
  }
876
877
0
  if ((name && name[0]) && (path && path[0]))
878
0
  {
879
0
    WLog_Print(log, WLOG_DEBUG, "Defining %s as %s", name, path);
880
881
0
    if (!DefineCommDevice(name /* eg: COM1 */, path /* eg: /dev/ttyS0 */))
882
0
    {
883
0
      DWORD status = GetLastError();
884
0
      WLog_Print(log, WLOG_ERROR, "DefineCommDevice failed with %08" PRIx32, status);
885
0
      return ERROR_INTERNAL_ERROR;
886
0
    }
887
888
0
    serial = (SERIAL_DEVICE*)calloc(1, sizeof(SERIAL_DEVICE));
889
890
0
    if (!serial)
891
0
    {
892
0
      WLog_Print(log, WLOG_ERROR, "calloc failed!");
893
0
      return CHANNEL_RC_NO_MEMORY;
894
0
    }
895
896
0
    serial->log = log;
897
0
    serial->device.type = RDPDR_DTYP_SERIAL;
898
0
    serial->device.name = name;
899
0
    serial->device.IRPRequest = serial_irp_request;
900
0
    serial->device.Free = serial_free;
901
0
    serial->rdpcontext = pEntryPoints->rdpcontext;
902
0
    len = strlen(name);
903
0
    serial->device.data = Stream_New(NULL, len + 1);
904
905
0
    if (!serial->device.data)
906
0
    {
907
0
      WLog_Print(serial->log, WLOG_ERROR, "calloc failed!");
908
0
      error = CHANNEL_RC_NO_MEMORY;
909
0
      goto error_out;
910
0
    }
911
912
0
    for (size_t i = 0; i <= len; i++)
913
0
      Stream_Write_INT8(serial->device.data, name[i] < 0 ? '_' : name[i]);
914
915
0
    if (driver != NULL)
916
0
    {
917
0
      if (_stricmp(driver, "Serial") == 0)
918
0
        serial->ServerSerialDriverId = SerialDriverSerialSys;
919
0
      else if (_stricmp(driver, "SerCx") == 0)
920
0
        serial->ServerSerialDriverId = SerialDriverSerCxSys;
921
0
      else if (_stricmp(driver, "SerCx2") == 0)
922
0
        serial->ServerSerialDriverId = SerialDriverSerCx2Sys;
923
0
      else
924
0
      {
925
0
        WLog_Print(serial->log, WLOG_WARN, "Unknown server's serial driver: %s.", driver);
926
0
        WLog_Print(serial->log, WLOG_WARN,
927
0
                   "Valid options are: 'Serial' (default), 'SerCx' and 'SerCx2'");
928
0
        goto error_out;
929
0
      }
930
0
    }
931
0
    else
932
0
    {
933
      /* default driver */
934
0
      serial->ServerSerialDriverId = SerialDriverSerialSys;
935
0
    }
936
937
0
    if (device->Permissive != NULL)
938
0
    {
939
0
      if (_stricmp(device->Permissive, "permissive") == 0)
940
0
      {
941
0
        serial->permissive = TRUE;
942
0
      }
943
0
      else
944
0
      {
945
0
        WLog_Print(serial->log, WLOG_WARN, "Unknown flag: %s", device->Permissive);
946
0
        goto error_out;
947
0
      }
948
0
    }
949
950
0
    WLog_Print(serial->log, WLOG_DEBUG, "Server's serial driver: %s (id: %d)", driver,
951
0
               serial->ServerSerialDriverId);
952
953
0
    serial->MainIrpQueue = MessageQueue_New(NULL);
954
955
0
    if (!serial->MainIrpQueue)
956
0
    {
957
0
      WLog_Print(serial->log, WLOG_ERROR, "MessageQueue_New failed!");
958
0
      error = CHANNEL_RC_NO_MEMORY;
959
0
      goto error_out;
960
0
    }
961
962
0
    {
963
0
      wObject* obj = MessageQueue_Object(serial->MainIrpQueue);
964
0
      WINPR_ASSERT(obj);
965
0
      obj->fnObjectFree = serial_message_free;
966
0
    }
967
968
    /* IrpThreads content only modified by create_irp_thread() */
969
0
    serial->IrpThreads = ListDictionary_New(FALSE);
970
971
0
    if (!serial->IrpThreads)
972
0
    {
973
0
      WLog_Print(serial->log, WLOG_ERROR, "ListDictionary_New failed!");
974
0
      error = CHANNEL_RC_NO_MEMORY;
975
0
      goto error_out;
976
0
    }
977
978
0
    {
979
0
      wObject* obj = ListDictionary_ValueObject(serial->IrpThreads);
980
0
      WINPR_ASSERT(obj);
981
0
      obj->fnObjectFree = irp_thread_close;
982
0
    }
983
984
0
    InitializeCriticalSection(&serial->TerminatingIrpThreadsLock);
985
986
0
    error = pEntryPoints->RegisterDevice(pEntryPoints->devman, &serial->device);
987
0
    if (error != CHANNEL_RC_OK)
988
0
    {
989
0
      WLog_Print(serial->log, WLOG_ERROR,
990
0
                 "EntryPoints->RegisterDevice failed with error %" PRIu32 "!", error);
991
0
      goto error_out;
992
0
    }
993
994
0
    serial->MainThread = CreateThread(NULL, 0, serial_thread_func, serial, 0, NULL);
995
0
    if (!serial->MainThread)
996
0
    {
997
0
      WLog_Print(serial->log, WLOG_ERROR, "CreateThread failed!");
998
0
      error = ERROR_INTERNAL_ERROR;
999
0
      goto error_out;
1000
0
    }
1001
0
  }
1002
1003
0
  return error;
1004
0
error_out:
1005
0
  if (serial)
1006
0
    serial_free(&serial->device);
1007
0
  return error;
1008
0
}