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