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