Coverage Report

Created: 2024-09-08 06:18

/src/FreeRDP/winpr/libwinpr/comm/comm.c
Line
Count
Source (jump to first uncovered line)
1
/**
2
 * WinPR: Windows Portable Runtime
3
 * Serial Communication API
4
 *
5
 * Copyright 2011 O.S. Systems Software Ltda.
6
 * Copyright 2011 Eduardo Fiss Beloni <beloni@ossystems.com.br>
7
 * Copyright 2014 Marc-Andre Moreau <marcandre.moreau@gmail.com>
8
 * Copyright 2014 Hewlett-Packard Development Company, L.P.
9
 *
10
 * Licensed under the Apache License, Version 2.0 (the "License");
11
 * you may not use this file except in compliance with the License.
12
 * You may obtain a copy of the License at
13
 *
14
 *     http://www.apache.org/licenses/LICENSE-2.0
15
 *
16
 * Unless required by applicable law or agreed to in writing, software
17
 * distributed under the License is distributed on an "AS IS" BASIS,
18
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
 * See the License for the specific language governing permissions and
20
 * limitations under the License.
21
 */
22
23
#include <winpr/config.h>
24
25
#include <winpr/assert.h>
26
#include <errno.h>
27
#include <fcntl.h>
28
#include <pthread.h>
29
#include <stdarg.h>
30
#include <sys/ioctl.h>
31
#include <sys/stat.h>
32
#include <sys/types.h>
33
#include <termios.h>
34
#include <unistd.h>
35
36
#include <winpr/crt.h>
37
#include <winpr/comm.h>
38
#include <winpr/tchar.h>
39
#include <winpr/wlog.h>
40
#include <winpr/handle.h>
41
42
#include "comm_ioctl.h"
43
44
#include "../log.h"
45
0
#define TAG WINPR_TAG("comm")
46
47
/**
48
 * Communication Resources:
49
 * http://msdn.microsoft.com/en-us/library/windows/desktop/aa363196/
50
 */
51
52
#include "comm.h"
53
54
static wLog* sLog = NULL;
55
56
struct comm_device
57
{
58
  LPTSTR name;
59
  LPTSTR path;
60
};
61
62
typedef struct comm_device COMM_DEVICE;
63
64
/* FIXME: get a clever data structure, see also io.h functions */
65
/* _CommDevices is a NULL-terminated array with a maximun of COMM_DEVICE_MAX COMM_DEVICE */
66
0
#define COMM_DEVICE_MAX 128
67
static COMM_DEVICE** sCommDevices = NULL;
68
static CRITICAL_SECTION sCommDevicesLock;
69
70
static HANDLE_CREATOR sCommHandleCreator = { 0 };
71
72
static pthread_once_t sCommInitialized = PTHREAD_ONCE_INIT;
73
74
static int CommGetFd(HANDLE handle)
75
0
{
76
0
  WINPR_COMM* comm = (WINPR_COMM*)handle;
77
78
0
  if (!CommIsHandled(handle))
79
0
    return -1;
80
81
0
  return comm->fd;
82
0
}
83
84
HANDLE_CREATOR* GetCommHandleCreator(void)
85
0
{
86
0
  sCommHandleCreator.IsHandled = IsCommDevice;
87
0
  sCommHandleCreator.CreateFileA = CommCreateFileA;
88
0
  return &sCommHandleCreator;
89
0
}
90
91
static void CommInit(void)
92
0
{
93
  /* NB: error management to be done outside of this function */
94
0
  WINPR_ASSERT(sLog == NULL);
95
0
  WINPR_ASSERT(sCommDevices == NULL);
96
0
  sCommDevices = (COMM_DEVICE**)calloc(COMM_DEVICE_MAX + 1, sizeof(COMM_DEVICE*));
97
98
0
  if (!sCommDevices)
99
0
    return;
100
101
0
  if (!InitializeCriticalSectionEx(&sCommDevicesLock, 0, 0))
102
0
  {
103
0
    free(sCommDevices);
104
0
    sCommDevices = NULL;
105
0
    return;
106
0
  }
107
108
0
  sLog = WLog_Get(TAG);
109
0
  WINPR_ASSERT(sLog != NULL);
110
0
}
111
112
/**
113
 * Returns TRUE when the comm module is correctly intialized, FALSE otherwise
114
 * with ERROR_DLL_INIT_FAILED set as the last error.
115
 */
116
static BOOL CommInitialized(void)
117
0
{
118
0
  if (pthread_once(&sCommInitialized, CommInit) != 0)
119
0
  {
120
0
    SetLastError(ERROR_DLL_INIT_FAILED);
121
0
    return FALSE;
122
0
  }
123
124
0
  return TRUE;
125
0
}
126
127
void CommLog_Print(DWORD level, ...)
128
0
{
129
0
  if (!CommInitialized())
130
0
    return;
131
132
0
  va_list ap;
133
0
  va_start(ap, level);
134
0
  WLog_PrintVA(sLog, level, ap);
135
0
  va_end(ap);
136
0
}
137
138
BOOL BuildCommDCBA(LPCSTR lpDef, LPDCB lpDCB)
139
0
{
140
0
  if (!CommInitialized())
141
0
    return FALSE;
142
143
  /* TODO: not implemented */
144
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
145
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
146
0
  return FALSE;
147
0
}
148
149
BOOL BuildCommDCBW(LPCWSTR lpDef, LPDCB lpDCB)
150
0
{
151
0
  if (!CommInitialized())
152
0
    return FALSE;
153
154
  /* TODO: not implemented */
155
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
156
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
157
0
  return FALSE;
158
0
}
159
160
BOOL BuildCommDCBAndTimeoutsA(LPCSTR lpDef, LPDCB lpDCB, LPCOMMTIMEOUTS lpCommTimeouts)
161
0
{
162
0
  if (!CommInitialized())
163
0
    return FALSE;
164
165
  /* TODO: not implemented */
166
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
167
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
168
0
  return FALSE;
169
0
}
170
171
BOOL BuildCommDCBAndTimeoutsW(LPCWSTR lpDef, LPDCB lpDCB, LPCOMMTIMEOUTS lpCommTimeouts)
172
0
{
173
0
  if (!CommInitialized())
174
0
    return FALSE;
175
176
  /* TODO: not implemented */
177
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
178
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
179
0
  return FALSE;
180
0
}
181
182
BOOL CommConfigDialogA(LPCSTR lpszName, HWND hWnd, LPCOMMCONFIG lpCC)
183
0
{
184
0
  if (!CommInitialized())
185
0
    return FALSE;
186
187
  /* TODO: not implemented */
188
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
189
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
190
0
  return FALSE;
191
0
}
192
193
BOOL CommConfigDialogW(LPCWSTR lpszName, HWND hWnd, LPCOMMCONFIG lpCC)
194
0
{
195
0
  if (!CommInitialized())
196
0
    return FALSE;
197
198
  /* TODO: not implemented */
199
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
200
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
201
0
  return FALSE;
202
0
}
203
204
BOOL GetCommConfig(HANDLE hCommDev, LPCOMMCONFIG lpCC, LPDWORD lpdwSize)
205
0
{
206
0
  WINPR_COMM* pComm = (WINPR_COMM*)hCommDev;
207
208
0
  if (!CommInitialized())
209
0
    return FALSE;
210
211
  /* TODO: not implemented */
212
213
0
  if (!pComm)
214
0
    return FALSE;
215
216
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
217
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
218
0
  return FALSE;
219
0
}
220
221
BOOL SetCommConfig(HANDLE hCommDev, LPCOMMCONFIG lpCC, DWORD dwSize)
222
0
{
223
0
  WINPR_COMM* pComm = (WINPR_COMM*)hCommDev;
224
225
0
  if (!CommInitialized())
226
0
    return FALSE;
227
228
  /* TODO: not implemented */
229
230
0
  if (!pComm)
231
0
    return FALSE;
232
233
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
234
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
235
0
  return FALSE;
236
0
}
237
238
BOOL GetCommMask(HANDLE hFile, PDWORD lpEvtMask)
239
0
{
240
0
  WINPR_COMM* pComm = (WINPR_COMM*)hFile;
241
242
0
  if (!CommInitialized())
243
0
    return FALSE;
244
245
  /* TODO: not implemented */
246
247
0
  if (!pComm)
248
0
    return FALSE;
249
250
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
251
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
252
0
  return FALSE;
253
0
}
254
255
BOOL SetCommMask(HANDLE hFile, DWORD dwEvtMask)
256
0
{
257
0
  WINPR_COMM* pComm = (WINPR_COMM*)hFile;
258
259
0
  if (!CommInitialized())
260
0
    return FALSE;
261
262
  /* TODO: not implemented */
263
264
0
  if (!pComm)
265
0
    return FALSE;
266
267
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
268
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
269
0
  return FALSE;
270
0
}
271
272
BOOL GetCommModemStatus(HANDLE hFile, PDWORD lpModemStat)
273
0
{
274
0
  WINPR_COMM* pComm = (WINPR_COMM*)hFile;
275
276
0
  if (!CommInitialized())
277
0
    return FALSE;
278
279
  /* TODO: not implemented */
280
281
0
  if (!pComm)
282
0
    return FALSE;
283
284
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
285
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
286
0
  return FALSE;
287
0
}
288
289
/**
290
 * ERRORS:
291
 *   ERROR_DLL_INIT_FAILED
292
 *   ERROR_INVALID_HANDLE
293
 */
294
BOOL GetCommProperties(HANDLE hFile, LPCOMMPROP lpCommProp)
295
0
{
296
0
  WINPR_COMM* pComm = (WINPR_COMM*)hFile;
297
0
  DWORD bytesReturned = 0;
298
299
0
  if (!CommIsHandleValid(hFile))
300
0
    return FALSE;
301
302
0
  if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_GET_PROPERTIES, NULL, 0, lpCommProp,
303
0
                           sizeof(COMMPROP), &bytesReturned, NULL))
304
0
  {
305
0
    CommLog_Print(WLOG_WARN, "GetCommProperties failure.");
306
0
    return FALSE;
307
0
  }
308
309
0
  return TRUE;
310
0
}
311
312
/**
313
 *
314
 *
315
 * ERRORS:
316
 *   ERROR_INVALID_HANDLE
317
 *   ERROR_INVALID_DATA
318
 *   ERROR_IO_DEVICE
319
 *   ERROR_OUTOFMEMORY
320
 */
321
BOOL GetCommState(HANDLE hFile, LPDCB lpDCB)
322
0
{
323
0
  DCB* lpLocalDcb = NULL;
324
0
  struct termios currentState;
325
0
  WINPR_COMM* pComm = (WINPR_COMM*)hFile;
326
0
  DWORD bytesReturned = 0;
327
328
0
  if (!CommIsHandleValid(hFile))
329
0
    return FALSE;
330
331
0
  if (!lpDCB)
332
0
  {
333
0
    SetLastError(ERROR_INVALID_DATA);
334
0
    return FALSE;
335
0
  }
336
337
0
  if (lpDCB->DCBlength < sizeof(DCB))
338
0
  {
339
0
    SetLastError(ERROR_INVALID_DATA);
340
0
    return FALSE;
341
0
  }
342
343
0
  if (tcgetattr(pComm->fd, &currentState) < 0)
344
0
  {
345
0
    SetLastError(ERROR_IO_DEVICE);
346
0
    return FALSE;
347
0
  }
348
349
0
  lpLocalDcb = (DCB*)calloc(1, lpDCB->DCBlength);
350
351
0
  if (lpLocalDcb == NULL)
352
0
  {
353
0
    SetLastError(ERROR_OUTOFMEMORY);
354
0
    return FALSE;
355
0
  }
356
357
  /* error_handle */
358
0
  lpLocalDcb->DCBlength = lpDCB->DCBlength;
359
0
  SERIAL_BAUD_RATE baudRate;
360
361
0
  if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_GET_BAUD_RATE, NULL, 0, &baudRate,
362
0
                           sizeof(SERIAL_BAUD_RATE), &bytesReturned, NULL))
363
0
  {
364
0
    CommLog_Print(WLOG_WARN, "GetCommState failure: could not get the baud rate.");
365
0
    goto error_handle;
366
0
  }
367
368
0
  lpLocalDcb->BaudRate = baudRate.BaudRate;
369
0
  lpLocalDcb->fBinary = (currentState.c_cflag & ICANON) == 0;
370
371
0
  if (!lpLocalDcb->fBinary)
372
0
  {
373
0
    CommLog_Print(WLOG_WARN, "Unexpected nonbinary mode, consider to unset the ICANON flag.");
374
0
  }
375
376
0
  lpLocalDcb->fParity = (currentState.c_iflag & INPCK) != 0;
377
0
  SERIAL_HANDFLOW handflow;
378
379
0
  if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_GET_HANDFLOW, NULL, 0, &handflow,
380
0
                           sizeof(SERIAL_HANDFLOW), &bytesReturned, NULL))
381
0
  {
382
0
    CommLog_Print(WLOG_WARN, "GetCommState failure: could not get the handflow settings.");
383
0
    goto error_handle;
384
0
  }
385
386
0
  lpLocalDcb->fOutxCtsFlow = (handflow.ControlHandShake & SERIAL_CTS_HANDSHAKE) != 0;
387
0
  lpLocalDcb->fOutxDsrFlow = (handflow.ControlHandShake & SERIAL_DSR_HANDSHAKE) != 0;
388
389
0
  if (handflow.ControlHandShake & SERIAL_DTR_HANDSHAKE)
390
0
  {
391
0
    lpLocalDcb->fDtrControl = DTR_CONTROL_HANDSHAKE;
392
0
  }
393
0
  else if (handflow.ControlHandShake & SERIAL_DTR_CONTROL)
394
0
  {
395
0
    lpLocalDcb->fDtrControl = DTR_CONTROL_ENABLE;
396
0
  }
397
0
  else
398
0
  {
399
0
    lpLocalDcb->fDtrControl = DTR_CONTROL_DISABLE;
400
0
  }
401
402
0
  lpLocalDcb->fDsrSensitivity = (handflow.ControlHandShake & SERIAL_DSR_SENSITIVITY) != 0;
403
0
  lpLocalDcb->fTXContinueOnXoff = (handflow.FlowReplace & SERIAL_XOFF_CONTINUE) != 0;
404
0
  lpLocalDcb->fOutX = (handflow.FlowReplace & SERIAL_AUTO_TRANSMIT) != 0;
405
0
  lpLocalDcb->fInX = (handflow.FlowReplace & SERIAL_AUTO_RECEIVE) != 0;
406
0
  lpLocalDcb->fErrorChar = (handflow.FlowReplace & SERIAL_ERROR_CHAR) != 0;
407
0
  lpLocalDcb->fNull = (handflow.FlowReplace & SERIAL_NULL_STRIPPING) != 0;
408
409
0
  if (handflow.FlowReplace & SERIAL_RTS_HANDSHAKE)
410
0
  {
411
0
    lpLocalDcb->fRtsControl = RTS_CONTROL_HANDSHAKE;
412
0
  }
413
0
  else if (handflow.FlowReplace & SERIAL_RTS_CONTROL)
414
0
  {
415
0
    lpLocalDcb->fRtsControl = RTS_CONTROL_ENABLE;
416
0
  }
417
0
  else
418
0
  {
419
0
    lpLocalDcb->fRtsControl = RTS_CONTROL_DISABLE;
420
0
  }
421
422
  // FIXME: how to get the RTS_CONTROL_TOGGLE state? Does it match the UART 16750's Autoflow
423
  // Control Enabled bit in its Modem Control Register (MCR)
424
0
  lpLocalDcb->fAbortOnError = (handflow.ControlHandShake & SERIAL_ERROR_ABORT) != 0;
425
  /* lpLocalDcb->fDummy2 not used */
426
0
  lpLocalDcb->wReserved = 0; /* must be zero */
427
0
  lpLocalDcb->XonLim = handflow.XonLimit;
428
0
  lpLocalDcb->XoffLim = handflow.XoffLimit;
429
0
  SERIAL_LINE_CONTROL lineControl;
430
431
0
  if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_GET_LINE_CONTROL, NULL, 0, &lineControl,
432
0
                           sizeof(SERIAL_LINE_CONTROL), &bytesReturned, NULL))
433
0
  {
434
0
    CommLog_Print(WLOG_WARN, "GetCommState failure: could not get the control settings.");
435
0
    goto error_handle;
436
0
  }
437
438
0
  lpLocalDcb->ByteSize = lineControl.WordLength;
439
0
  lpLocalDcb->Parity = lineControl.Parity;
440
0
  lpLocalDcb->StopBits = lineControl.StopBits;
441
0
  SERIAL_CHARS serialChars;
442
443
0
  if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_GET_CHARS, NULL, 0, &serialChars,
444
0
                           sizeof(SERIAL_CHARS), &bytesReturned, NULL))
445
0
  {
446
0
    CommLog_Print(WLOG_WARN, "GetCommState failure: could not get the serial chars.");
447
0
    goto error_handle;
448
0
  }
449
450
0
  lpLocalDcb->XonChar = serialChars.XonChar;
451
0
  lpLocalDcb->XoffChar = serialChars.XoffChar;
452
0
  lpLocalDcb->ErrorChar = serialChars.ErrorChar;
453
0
  lpLocalDcb->EofChar = serialChars.EofChar;
454
0
  lpLocalDcb->EvtChar = serialChars.EventChar;
455
0
  memcpy(lpDCB, lpLocalDcb, lpDCB->DCBlength);
456
0
  free(lpLocalDcb);
457
0
  return TRUE;
458
0
error_handle:
459
0
  free(lpLocalDcb);
460
0
  return FALSE;
461
0
}
462
463
/**
464
 * @return TRUE on success, FALSE otherwise.
465
 *
466
 * As of today, SetCommState() can fail half-way with some settings
467
 * applied and some others not. SetCommState() returns on the first
468
 * failure met. FIXME: or is it correct?
469
 *
470
 * ERRORS:
471
 *   ERROR_INVALID_HANDLE
472
 *   ERROR_IO_DEVICE
473
 */
474
BOOL SetCommState(HANDLE hFile, LPDCB lpDCB)
475
0
{
476
0
  struct termios upcomingTermios = { 0 };
477
0
  WINPR_COMM* pComm = (WINPR_COMM*)hFile;
478
0
  DWORD bytesReturned = 0;
479
480
  /* FIXME: validate changes according GetCommProperties? */
481
482
0
  if (!CommIsHandleValid(hFile))
483
0
    return FALSE;
484
485
0
  if (!lpDCB)
486
0
  {
487
0
    SetLastError(ERROR_INVALID_DATA);
488
0
    return FALSE;
489
0
  }
490
491
  /* NB: did the choice to call ioctls first when available and
492
     then to setup upcomingTermios. Don't mix both stages. */
493
  /** ioctl calls stage **/
494
0
  SERIAL_BAUD_RATE baudRate;
495
0
  baudRate.BaudRate = lpDCB->BaudRate;
496
497
0
  if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_SET_BAUD_RATE, &baudRate, sizeof(SERIAL_BAUD_RATE),
498
0
                           NULL, 0, &bytesReturned, NULL))
499
0
  {
500
0
    CommLog_Print(WLOG_WARN, "SetCommState failure: could not set the baud rate.");
501
0
    return FALSE;
502
0
  }
503
504
0
  SERIAL_CHARS serialChars;
505
506
0
  if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_GET_CHARS, NULL, 0, &serialChars,
507
0
                           sizeof(SERIAL_CHARS), &bytesReturned,
508
0
                           NULL)) /* as of today, required for BreakChar */
509
0
  {
510
0
    CommLog_Print(WLOG_WARN, "SetCommState failure: could not get the initial serial chars.");
511
0
    return FALSE;
512
0
  }
513
514
0
  serialChars.XonChar = lpDCB->XonChar;
515
0
  serialChars.XoffChar = lpDCB->XoffChar;
516
0
  serialChars.ErrorChar = lpDCB->ErrorChar;
517
0
  serialChars.EofChar = lpDCB->EofChar;
518
0
  serialChars.EventChar = lpDCB->EvtChar;
519
520
0
  if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_SET_CHARS, &serialChars, sizeof(SERIAL_CHARS),
521
0
                           NULL, 0, &bytesReturned, NULL))
522
0
  {
523
0
    CommLog_Print(WLOG_WARN, "SetCommState failure: could not set the serial chars.");
524
0
    return FALSE;
525
0
  }
526
527
0
  SERIAL_LINE_CONTROL lineControl;
528
0
  lineControl.StopBits = lpDCB->StopBits;
529
0
  lineControl.Parity = lpDCB->Parity;
530
0
  lineControl.WordLength = lpDCB->ByteSize;
531
532
0
  if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_SET_LINE_CONTROL, &lineControl,
533
0
                           sizeof(SERIAL_LINE_CONTROL), NULL, 0, &bytesReturned, NULL))
534
0
  {
535
0
    CommLog_Print(WLOG_WARN, "SetCommState failure: could not set the control settings.");
536
0
    return FALSE;
537
0
  }
538
539
0
  SERIAL_HANDFLOW handflow = { 0 };
540
541
0
  if (lpDCB->fOutxCtsFlow)
542
0
  {
543
0
    handflow.ControlHandShake |= SERIAL_CTS_HANDSHAKE;
544
0
  }
545
546
0
  if (lpDCB->fOutxDsrFlow)
547
0
  {
548
0
    handflow.ControlHandShake |= SERIAL_DSR_HANDSHAKE;
549
0
  }
550
551
0
  switch (lpDCB->fDtrControl)
552
0
  {
553
0
    case SERIAL_DTR_HANDSHAKE:
554
0
      handflow.ControlHandShake |= DTR_CONTROL_HANDSHAKE;
555
0
      break;
556
557
0
    case SERIAL_DTR_CONTROL:
558
0
      handflow.ControlHandShake |= DTR_CONTROL_ENABLE;
559
0
      break;
560
561
0
    case DTR_CONTROL_DISABLE:
562
      /* do nothing since handflow is init-zeroed */
563
0
      break;
564
565
0
    default:
566
0
      CommLog_Print(WLOG_WARN, "Unexpected fDtrControl value: %" PRIu32 "\n",
567
0
                    lpDCB->fDtrControl);
568
0
      return FALSE;
569
0
  }
570
571
0
  if (lpDCB->fDsrSensitivity)
572
0
  {
573
0
    handflow.ControlHandShake |= SERIAL_DSR_SENSITIVITY;
574
0
  }
575
576
0
  if (lpDCB->fTXContinueOnXoff)
577
0
  {
578
0
    handflow.FlowReplace |= SERIAL_XOFF_CONTINUE;
579
0
  }
580
581
0
  if (lpDCB->fOutX)
582
0
  {
583
0
    handflow.FlowReplace |= SERIAL_AUTO_TRANSMIT;
584
0
  }
585
586
0
  if (lpDCB->fInX)
587
0
  {
588
0
    handflow.FlowReplace |= SERIAL_AUTO_RECEIVE;
589
0
  }
590
591
0
  if (lpDCB->fErrorChar)
592
0
  {
593
0
    handflow.FlowReplace |= SERIAL_ERROR_CHAR;
594
0
  }
595
596
0
  if (lpDCB->fNull)
597
0
  {
598
0
    handflow.FlowReplace |= SERIAL_NULL_STRIPPING;
599
0
  }
600
601
0
  switch (lpDCB->fRtsControl)
602
0
  {
603
0
    case RTS_CONTROL_TOGGLE:
604
0
      CommLog_Print(WLOG_WARN, "Unsupported RTS_CONTROL_TOGGLE feature");
605
      // FIXME: see also GetCommState()
606
0
      return FALSE;
607
608
0
    case RTS_CONTROL_HANDSHAKE:
609
0
      handflow.FlowReplace |= SERIAL_RTS_HANDSHAKE;
610
0
      break;
611
612
0
    case RTS_CONTROL_ENABLE:
613
0
      handflow.FlowReplace |= SERIAL_RTS_CONTROL;
614
0
      break;
615
616
0
    case RTS_CONTROL_DISABLE:
617
      /* do nothing since handflow is init-zeroed */
618
0
      break;
619
620
0
    default:
621
0
      CommLog_Print(WLOG_WARN, "Unexpected fRtsControl value: %" PRIu32 "\n",
622
0
                    lpDCB->fRtsControl);
623
0
      return FALSE;
624
0
  }
625
626
0
  if (lpDCB->fAbortOnError)
627
0
  {
628
0
    handflow.ControlHandShake |= SERIAL_ERROR_ABORT;
629
0
  }
630
631
  /* lpDCB->fDummy2 not used */
632
  /* lpLocalDcb->wReserved  ignored */
633
0
  handflow.XonLimit = lpDCB->XonLim;
634
0
  handflow.XoffLimit = lpDCB->XoffLim;
635
636
0
  if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_SET_HANDFLOW, &handflow, sizeof(SERIAL_HANDFLOW),
637
0
                           NULL, 0, &bytesReturned, NULL))
638
0
  {
639
0
    CommLog_Print(WLOG_WARN, "SetCommState failure: could not set the handflow settings.");
640
0
    return FALSE;
641
0
  }
642
643
  /** upcomingTermios stage **/
644
645
0
  if (tcgetattr(pComm->fd, &upcomingTermios) <
646
0
      0) /* NB: preserves current settings not directly handled by the Communication Functions */
647
0
  {
648
0
    SetLastError(ERROR_IO_DEVICE);
649
0
    return FALSE;
650
0
  }
651
652
0
  if (lpDCB->fBinary)
653
0
  {
654
0
    upcomingTermios.c_lflag &= ~ICANON;
655
0
  }
656
0
  else
657
0
  {
658
0
    upcomingTermios.c_lflag |= ICANON;
659
0
    CommLog_Print(WLOG_WARN, "Unexpected nonbinary mode, consider to unset the ICANON flag.");
660
0
  }
661
662
0
  if (lpDCB->fParity)
663
0
  {
664
0
    upcomingTermios.c_iflag |= INPCK;
665
0
  }
666
0
  else
667
0
  {
668
0
    upcomingTermios.c_iflag &= ~INPCK;
669
0
  }
670
671
  /* http://msdn.microsoft.com/en-us/library/windows/desktop/aa363423%28v=vs.85%29.aspx
672
   *
673
   * The SetCommState function reconfigures the communications
674
   * resource, but it does not affect the internal output and
675
   * input buffers of the specified driver. The buffers are not
676
   * flushed, and pending read and write operations are not
677
   * terminated prematurely.
678
   *
679
   * TCSANOW matches the best this definition
680
   */
681
682
0
  if (_comm_ioctl_tcsetattr(pComm->fd, TCSANOW, &upcomingTermios) < 0)
683
0
  {
684
0
    SetLastError(ERROR_IO_DEVICE);
685
0
    return FALSE;
686
0
  }
687
688
0
  return TRUE;
689
0
}
690
691
/**
692
 * ERRORS:
693
 *   ERROR_INVALID_HANDLE
694
 */
695
BOOL GetCommTimeouts(HANDLE hFile, LPCOMMTIMEOUTS lpCommTimeouts)
696
0
{
697
0
  WINPR_COMM* pComm = (WINPR_COMM*)hFile;
698
0
  DWORD bytesReturned = 0;
699
700
0
  if (!CommIsHandleValid(hFile))
701
0
    return FALSE;
702
703
  /* as of today, SERIAL_TIMEOUTS and COMMTIMEOUTS structures are identical */
704
705
0
  if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_GET_TIMEOUTS, NULL, 0, lpCommTimeouts,
706
0
                           sizeof(COMMTIMEOUTS), &bytesReturned, NULL))
707
0
  {
708
0
    CommLog_Print(WLOG_WARN, "GetCommTimeouts failure.");
709
0
    return FALSE;
710
0
  }
711
712
0
  return TRUE;
713
0
}
714
715
/**
716
 * ERRORS:
717
 *   ERROR_INVALID_HANDLE
718
 */
719
BOOL SetCommTimeouts(HANDLE hFile, LPCOMMTIMEOUTS lpCommTimeouts)
720
0
{
721
0
  WINPR_COMM* pComm = (WINPR_COMM*)hFile;
722
0
  DWORD bytesReturned = 0;
723
724
0
  if (!CommIsHandleValid(hFile))
725
0
    return FALSE;
726
727
  /* as of today, SERIAL_TIMEOUTS and COMMTIMEOUTS structures are identical */
728
729
0
  if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_SET_TIMEOUTS, lpCommTimeouts, sizeof(COMMTIMEOUTS),
730
0
                           NULL, 0, &bytesReturned, NULL))
731
0
  {
732
0
    CommLog_Print(WLOG_WARN, "SetCommTimeouts failure.");
733
0
    return FALSE;
734
0
  }
735
736
0
  return TRUE;
737
0
}
738
739
BOOL GetDefaultCommConfigA(LPCSTR lpszName, LPCOMMCONFIG lpCC, LPDWORD lpdwSize)
740
0
{
741
0
  if (!CommInitialized())
742
0
    return FALSE;
743
744
  /* TODO: not implemented */
745
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
746
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
747
0
  return FALSE;
748
0
}
749
750
BOOL GetDefaultCommConfigW(LPCWSTR lpszName, LPCOMMCONFIG lpCC, LPDWORD lpdwSize)
751
0
{
752
0
  if (!CommInitialized())
753
0
    return FALSE;
754
755
  /* TODO: not implemented */
756
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
757
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
758
0
  return FALSE;
759
0
}
760
761
BOOL SetDefaultCommConfigA(LPCSTR lpszName, LPCOMMCONFIG lpCC, DWORD dwSize)
762
0
{
763
0
  if (!CommInitialized())
764
0
    return FALSE;
765
766
  /* TODO: not implemented */
767
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
768
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
769
0
  return FALSE;
770
0
}
771
772
BOOL SetDefaultCommConfigW(LPCWSTR lpszName, LPCOMMCONFIG lpCC, DWORD dwSize)
773
0
{
774
0
  if (!CommInitialized())
775
0
    return FALSE;
776
777
  /* TODO: not implemented */
778
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
779
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
780
0
  return FALSE;
781
0
}
782
783
BOOL SetCommBreak(HANDLE hFile)
784
0
{
785
0
  WINPR_COMM* pComm = (WINPR_COMM*)hFile;
786
787
0
  if (!CommInitialized())
788
0
    return FALSE;
789
790
  /* TODO: not implemented */
791
792
0
  if (!pComm)
793
0
    return FALSE;
794
795
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
796
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
797
0
  return FALSE;
798
0
}
799
800
BOOL ClearCommBreak(HANDLE hFile)
801
0
{
802
0
  WINPR_COMM* pComm = (WINPR_COMM*)hFile;
803
804
0
  if (!CommInitialized())
805
0
    return FALSE;
806
807
  /* TODO: not implemented */
808
809
0
  if (!pComm)
810
0
    return FALSE;
811
812
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
813
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
814
0
  return FALSE;
815
0
}
816
817
BOOL ClearCommError(HANDLE hFile, PDWORD lpErrors, LPCOMSTAT lpStat)
818
0
{
819
0
  WINPR_COMM* pComm = (WINPR_COMM*)hFile;
820
821
0
  if (!CommInitialized())
822
0
    return FALSE;
823
824
  /* TODO: not implemented */
825
826
0
  if (!pComm)
827
0
    return FALSE;
828
829
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
830
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
831
0
  return FALSE;
832
0
}
833
834
BOOL PurgeComm(HANDLE hFile, DWORD dwFlags)
835
0
{
836
0
  WINPR_COMM* pComm = (WINPR_COMM*)hFile;
837
0
  DWORD bytesReturned = 0;
838
839
0
  if (!CommIsHandleValid(hFile))
840
0
    return FALSE;
841
842
0
  if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_PURGE, &dwFlags, sizeof(DWORD), NULL, 0,
843
0
                           &bytesReturned, NULL))
844
0
  {
845
0
    CommLog_Print(WLOG_WARN, "PurgeComm failure.");
846
0
    return FALSE;
847
0
  }
848
849
0
  return TRUE;
850
0
}
851
852
BOOL SetupComm(HANDLE hFile, DWORD dwInQueue, DWORD dwOutQueue)
853
0
{
854
0
  WINPR_COMM* pComm = (WINPR_COMM*)hFile;
855
0
  SERIAL_QUEUE_SIZE queueSize;
856
0
  DWORD bytesReturned = 0;
857
858
0
  if (!CommIsHandleValid(hFile))
859
0
    return FALSE;
860
861
0
  queueSize.InSize = dwInQueue;
862
0
  queueSize.OutSize = dwOutQueue;
863
864
0
  if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_SET_QUEUE_SIZE, &queueSize,
865
0
                           sizeof(SERIAL_QUEUE_SIZE), NULL, 0, &bytesReturned, NULL))
866
0
  {
867
0
    CommLog_Print(WLOG_WARN, "SetCommTimeouts failure.");
868
0
    return FALSE;
869
0
  }
870
871
0
  return TRUE;
872
0
}
873
874
BOOL EscapeCommFunction(HANDLE hFile, DWORD dwFunc)
875
0
{
876
0
  WINPR_COMM* pComm = (WINPR_COMM*)hFile;
877
878
0
  if (!CommInitialized())
879
0
    return FALSE;
880
881
  /* TODO: not implemented */
882
883
0
  if (!pComm)
884
0
    return FALSE;
885
886
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
887
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
888
0
  return FALSE;
889
0
}
890
891
BOOL TransmitCommChar(HANDLE hFile, char cChar)
892
0
{
893
0
  WINPR_COMM* pComm = (WINPR_COMM*)hFile;
894
895
0
  if (!CommInitialized())
896
0
    return FALSE;
897
898
  /* TODO: not implemented */
899
900
0
  if (!pComm)
901
0
    return FALSE;
902
903
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
904
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
905
0
  return FALSE;
906
0
}
907
908
BOOL WaitCommEvent(HANDLE hFile, PDWORD lpEvtMask, LPOVERLAPPED lpOverlapped)
909
0
{
910
0
  WINPR_COMM* pComm = (WINPR_COMM*)hFile;
911
912
0
  if (!CommInitialized())
913
0
    return FALSE;
914
915
  /* TODO: not implemented */
916
917
0
  if (!pComm)
918
0
    return FALSE;
919
920
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
921
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
922
0
  return FALSE;
923
0
}
924
925
/**
926
 * Returns TRUE on success, FALSE otherwise. To get extended error
927
 * information, call GetLastError.
928
 *
929
 * ERRORS:
930
 *   ERROR_DLL_INIT_FAILED
931
 *   ERROR_OUTOFMEMORY was not possible to get mappings.
932
 *   ERROR_INVALID_DATA was not possible to add the device.
933
 */
934
BOOL DefineCommDevice(/* DWORD dwFlags,*/ LPCTSTR lpDeviceName, LPCTSTR lpTargetPath)
935
0
{
936
0
  LPTSTR storedDeviceName = NULL;
937
0
  LPTSTR storedTargetPath = NULL;
938
939
0
  if (!CommInitialized())
940
0
    return FALSE;
941
942
0
  EnterCriticalSection(&sCommDevicesLock);
943
944
0
  if (sCommDevices == NULL)
945
0
  {
946
0
    SetLastError(ERROR_DLL_INIT_FAILED);
947
0
    goto error_handle;
948
0
  }
949
950
0
  storedDeviceName = _tcsdup(lpDeviceName);
951
952
0
  if (storedDeviceName == NULL)
953
0
  {
954
0
    SetLastError(ERROR_OUTOFMEMORY);
955
0
    goto error_handle;
956
0
  }
957
958
0
  storedTargetPath = _tcsdup(lpTargetPath);
959
960
0
  if (storedTargetPath == NULL)
961
0
  {
962
0
    SetLastError(ERROR_OUTOFMEMORY);
963
0
    goto error_handle;
964
0
  }
965
966
0
  int i = 0;
967
0
  for (; i < COMM_DEVICE_MAX; i++)
968
0
  {
969
0
    if (sCommDevices[i] != NULL)
970
0
    {
971
0
      if (_tcscmp(sCommDevices[i]->name, storedDeviceName) == 0)
972
0
      {
973
        /* take over the emplacement */
974
0
        free(sCommDevices[i]->name);
975
0
        free(sCommDevices[i]->path);
976
0
        sCommDevices[i]->name = storedDeviceName;
977
0
        sCommDevices[i]->path = storedTargetPath;
978
0
        break;
979
0
      }
980
0
    }
981
0
    else
982
0
    {
983
      /* new emplacement */
984
0
      sCommDevices[i] = (COMM_DEVICE*)calloc(1, sizeof(COMM_DEVICE));
985
986
0
      if (sCommDevices[i] == NULL)
987
0
      {
988
0
        SetLastError(ERROR_OUTOFMEMORY);
989
0
        goto error_handle;
990
0
      }
991
992
0
      sCommDevices[i]->name = storedDeviceName;
993
0
      sCommDevices[i]->path = storedTargetPath;
994
0
      break;
995
0
    }
996
0
  }
997
998
0
  if (i == COMM_DEVICE_MAX)
999
0
  {
1000
0
    SetLastError(ERROR_OUTOFMEMORY);
1001
0
    goto error_handle;
1002
0
  }
1003
1004
0
  LeaveCriticalSection(&sCommDevicesLock);
1005
0
  return TRUE;
1006
0
error_handle:
1007
0
  free(storedDeviceName);
1008
0
  free(storedTargetPath);
1009
0
  LeaveCriticalSection(&sCommDevicesLock);
1010
0
  return FALSE;
1011
0
}
1012
1013
/**
1014
 * Returns the number of target paths in the buffer pointed to by
1015
 * lpTargetPath.
1016
 *
1017
 * The current implementation returns in any case 0 and 1 target
1018
 * path. A NULL lpDeviceName is not supported yet to get all the
1019
 * paths.
1020
 *
1021
 * ERRORS:
1022
 *   ERROR_SUCCESS
1023
 *   ERROR_DLL_INIT_FAILED
1024
 *   ERROR_OUTOFMEMORY was not possible to get mappings.
1025
 *   ERROR_NOT_SUPPORTED equivalent QueryDosDevice feature not supported.
1026
 *   ERROR_INVALID_DATA was not possible to retrieve any device information.
1027
 *   ERROR_INSUFFICIENT_BUFFER too small lpTargetPath
1028
 */
1029
DWORD QueryCommDevice(LPCTSTR lpDeviceName, LPTSTR lpTargetPath, DWORD ucchMax)
1030
0
{
1031
0
  LPTSTR storedTargetPath = NULL;
1032
0
  SetLastError(ERROR_SUCCESS);
1033
1034
0
  if (!CommInitialized())
1035
0
    return 0;
1036
1037
0
  if (sCommDevices == NULL)
1038
0
  {
1039
0
    SetLastError(ERROR_DLL_INIT_FAILED);
1040
0
    return 0;
1041
0
  }
1042
1043
0
  if (lpDeviceName == NULL || lpTargetPath == NULL)
1044
0
  {
1045
0
    SetLastError(ERROR_NOT_SUPPORTED);
1046
0
    return 0;
1047
0
  }
1048
1049
0
  EnterCriticalSection(&sCommDevicesLock);
1050
0
  storedTargetPath = NULL;
1051
1052
0
  for (int i = 0; i < COMM_DEVICE_MAX; i++)
1053
0
  {
1054
0
    if (sCommDevices[i] != NULL)
1055
0
    {
1056
0
      if (_tcscmp(sCommDevices[i]->name, lpDeviceName) == 0)
1057
0
      {
1058
0
        storedTargetPath = sCommDevices[i]->path;
1059
0
        break;
1060
0
      }
1061
1062
0
      continue;
1063
0
    }
1064
1065
0
    break;
1066
0
  }
1067
1068
0
  LeaveCriticalSection(&sCommDevicesLock);
1069
1070
0
  if (storedTargetPath == NULL)
1071
0
  {
1072
0
    SetLastError(ERROR_INVALID_DATA);
1073
0
    return 0;
1074
0
  }
1075
1076
0
  if (_tcslen(storedTargetPath) + 2 > ucchMax)
1077
0
  {
1078
0
    SetLastError(ERROR_INSUFFICIENT_BUFFER);
1079
0
    return 0;
1080
0
  }
1081
1082
0
  _tcscpy(lpTargetPath, storedTargetPath);
1083
0
  lpTargetPath[_tcslen(storedTargetPath) + 1] = '\0'; /* 2nd final '\0' */
1084
0
  return _tcslen(lpTargetPath) + 2;
1085
0
}
1086
1087
/**
1088
 * Checks whether lpDeviceName is a valid and registered Communication device.
1089
 */
1090
BOOL IsCommDevice(LPCTSTR lpDeviceName)
1091
0
{
1092
0
  TCHAR lpTargetPath[MAX_PATH];
1093
1094
0
  if (!CommInitialized())
1095
0
    return FALSE;
1096
1097
0
  if (QueryCommDevice(lpDeviceName, lpTargetPath, MAX_PATH) > 0)
1098
0
  {
1099
0
    return TRUE;
1100
0
  }
1101
1102
0
  return FALSE;
1103
0
}
1104
1105
/**
1106
 * Sets
1107
 */
1108
void _comm_setServerSerialDriver(HANDLE hComm, SERIAL_DRIVER_ID driverId)
1109
0
{
1110
0
  ULONG Type = 0;
1111
0
  WINPR_HANDLE* Object = NULL;
1112
0
  WINPR_COMM* pComm = NULL;
1113
1114
0
  if (!CommInitialized())
1115
0
    return;
1116
1117
0
  if (!winpr_Handle_GetInfo(hComm, &Type, &Object))
1118
0
  {
1119
0
    CommLog_Print(WLOG_WARN, "_comm_setServerSerialDriver failure");
1120
0
    return;
1121
0
  }
1122
1123
0
  pComm = (WINPR_COMM*)Object;
1124
0
  pComm->serverSerialDriverId = driverId;
1125
0
}
1126
1127
static HANDLE_OPS ops = { CommIsHandled, CommCloseHandle,
1128
                        CommGetFd,     NULL, /* CleanupHandle */
1129
                        NULL,          NULL,
1130
                        NULL,          NULL,
1131
                        NULL,          NULL,
1132
                        NULL,          NULL,
1133
                        NULL,          NULL,
1134
                        NULL,          NULL,
1135
                        NULL,          NULL,
1136
                        NULL,          NULL,
1137
                        NULL };
1138
1139
/**
1140
 * http://msdn.microsoft.com/en-us/library/windows/desktop/aa363198%28v=vs.85%29.aspx
1141
 *
1142
 * @param lpDeviceName e.g. COM1, ...
1143
 *
1144
 * @param dwDesiredAccess expects GENERIC_READ | GENERIC_WRITE, a
1145
 * warning message is printed otherwise. TODO: better support.
1146
 *
1147
 * @param dwShareMode must be zero, INVALID_HANDLE_VALUE is returned
1148
 * otherwise and GetLastError() should return ERROR_SHARING_VIOLATION.
1149
 *
1150
 * @param lpSecurityAttributes NULL expected, a warning message is printed
1151
 * otherwise. TODO: better support.
1152
 *
1153
 * @param dwCreationDisposition must be OPEN_EXISTING. If the
1154
 * communication device doesn't exist INVALID_HANDLE_VALUE is returned
1155
 * and GetLastError() returns ERROR_FILE_NOT_FOUND.
1156
 *
1157
 * @param dwFlagsAndAttributes zero expected, a warning message is
1158
 * printed otherwise.
1159
 *
1160
 * @param hTemplateFile must be NULL.
1161
 *
1162
 * @return INVALID_HANDLE_VALUE on error.
1163
 */
1164
HANDLE CommCreateFileA(LPCSTR lpDeviceName, DWORD dwDesiredAccess, DWORD dwShareMode,
1165
                       LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition,
1166
                       DWORD dwFlagsAndAttributes, HANDLE hTemplateFile)
1167
0
{
1168
0
  CHAR devicePath[MAX_PATH] = { 0 };
1169
0
  struct stat deviceStat = { 0 };
1170
0
  WINPR_COMM* pComm = NULL;
1171
0
  struct termios upcomingTermios = { 0 };
1172
1173
0
  if (!CommInitialized())
1174
0
    return INVALID_HANDLE_VALUE;
1175
1176
0
  if (dwDesiredAccess != (GENERIC_READ | GENERIC_WRITE))
1177
0
  {
1178
0
    CommLog_Print(WLOG_WARN, "unexpected access to the device: 0x%08" PRIX32 "",
1179
0
                  dwDesiredAccess);
1180
0
  }
1181
1182
0
  if (dwShareMode != 0)
1183
0
  {
1184
0
    SetLastError(ERROR_SHARING_VIOLATION);
1185
0
    return INVALID_HANDLE_VALUE;
1186
0
  }
1187
1188
  /* TODO: Prevents other processes from opening a file or
1189
   * device if they request delete, read, or write access. */
1190
1191
0
  if (lpSecurityAttributes != NULL)
1192
0
  {
1193
0
    CommLog_Print(WLOG_WARN, "unexpected security attributes, nLength=%" PRIu32 "",
1194
0
                  lpSecurityAttributes->nLength);
1195
0
  }
1196
1197
0
  if (dwCreationDisposition != OPEN_EXISTING)
1198
0
  {
1199
0
    SetLastError(ERROR_FILE_NOT_FOUND); /* FIXME: ERROR_NOT_SUPPORTED better? */
1200
0
    return INVALID_HANDLE_VALUE;
1201
0
  }
1202
1203
0
  if (QueryCommDevice(lpDeviceName, devicePath, MAX_PATH) <= 0)
1204
0
  {
1205
    /* SetLastError(GetLastError()); */
1206
0
    return INVALID_HANDLE_VALUE;
1207
0
  }
1208
1209
0
  if (stat(devicePath, &deviceStat) < 0)
1210
0
  {
1211
0
    CommLog_Print(WLOG_WARN, "device not found %s", devicePath);
1212
0
    SetLastError(ERROR_FILE_NOT_FOUND);
1213
0
    return INVALID_HANDLE_VALUE;
1214
0
  }
1215
1216
0
  if (!S_ISCHR(deviceStat.st_mode))
1217
0
  {
1218
0
    CommLog_Print(WLOG_WARN, "bad device %s", devicePath);
1219
0
    SetLastError(ERROR_BAD_DEVICE);
1220
0
    return INVALID_HANDLE_VALUE;
1221
0
  }
1222
1223
0
  if (dwFlagsAndAttributes != 0)
1224
0
  {
1225
0
    CommLog_Print(WLOG_WARN, "unexpected flags and attributes: 0x%08" PRIX32 "",
1226
0
                  dwFlagsAndAttributes);
1227
0
  }
1228
1229
0
  if (hTemplateFile != NULL)
1230
0
  {
1231
0
    SetLastError(ERROR_NOT_SUPPORTED); /* FIXME: other proper error? */
1232
0
    return INVALID_HANDLE_VALUE;
1233
0
  }
1234
1235
0
  pComm = (WINPR_COMM*)calloc(1, sizeof(WINPR_COMM));
1236
1237
0
  if (pComm == NULL)
1238
0
  {
1239
0
    SetLastError(ERROR_OUTOFMEMORY);
1240
0
    return INVALID_HANDLE_VALUE;
1241
0
  }
1242
1243
0
  WINPR_HANDLE_SET_TYPE_AND_MODE(pComm, HANDLE_TYPE_COMM, WINPR_FD_READ);
1244
0
  pComm->common.ops = &ops;
1245
  /* error_handle */
1246
0
  pComm->fd = open(devicePath, O_RDWR | O_NOCTTY | O_NONBLOCK);
1247
1248
0
  if (pComm->fd < 0)
1249
0
  {
1250
0
    CommLog_Print(WLOG_WARN, "failed to open device %s", devicePath);
1251
0
    SetLastError(ERROR_BAD_DEVICE);
1252
0
    goto error_handle;
1253
0
  }
1254
1255
0
  pComm->fd_read = open(devicePath, O_RDONLY | O_NOCTTY | O_NONBLOCK);
1256
1257
0
  if (pComm->fd_read < 0)
1258
0
  {
1259
0
    CommLog_Print(WLOG_WARN, "failed to open fd_read, device: %s", devicePath);
1260
0
    SetLastError(ERROR_BAD_DEVICE);
1261
0
    goto error_handle;
1262
0
  }
1263
1264
0
  pComm->fd_read_event = eventfd(
1265
0
      0, EFD_NONBLOCK); /* EFD_NONBLOCK required because a read() is not always expected */
1266
1267
0
  if (pComm->fd_read_event < 0)
1268
0
  {
1269
0
    CommLog_Print(WLOG_WARN, "failed to open fd_read_event, device: %s", devicePath);
1270
0
    SetLastError(ERROR_BAD_DEVICE);
1271
0
    goto error_handle;
1272
0
  }
1273
1274
0
  InitializeCriticalSection(&pComm->ReadLock);
1275
0
  pComm->fd_write = open(devicePath, O_WRONLY | O_NOCTTY | O_NONBLOCK);
1276
1277
0
  if (pComm->fd_write < 0)
1278
0
  {
1279
0
    CommLog_Print(WLOG_WARN, "failed to open fd_write, device: %s", devicePath);
1280
0
    SetLastError(ERROR_BAD_DEVICE);
1281
0
    goto error_handle;
1282
0
  }
1283
1284
0
  pComm->fd_write_event = eventfd(
1285
0
      0, EFD_NONBLOCK); /* EFD_NONBLOCK required because a read() is not always expected */
1286
1287
0
  if (pComm->fd_write_event < 0)
1288
0
  {
1289
0
    CommLog_Print(WLOG_WARN, "failed to open fd_write_event, device: %s", devicePath);
1290
0
    SetLastError(ERROR_BAD_DEVICE);
1291
0
    goto error_handle;
1292
0
  }
1293
1294
0
  InitializeCriticalSection(&pComm->WriteLock);
1295
  /* can also be setup later on with _comm_setServerSerialDriver() */
1296
0
  pComm->serverSerialDriverId = SerialDriverUnknown;
1297
0
  InitializeCriticalSection(&pComm->EventsLock);
1298
1299
0
  if (ioctl(pComm->fd, TIOCGICOUNT, &(pComm->counters)) < 0)
1300
0
  {
1301
0
    char ebuffer[256] = { 0 };
1302
0
    CommLog_Print(WLOG_WARN, "TIOCGICOUNT ioctl failed, errno=[%d] %s.", errno,
1303
0
                  winpr_strerror(errno, ebuffer, sizeof(ebuffer)));
1304
0
    CommLog_Print(WLOG_WARN, "could not read counters.");
1305
    /* could not initialize counters but keep on.
1306
     *
1307
     * Not all drivers, especially for USB to serial
1308
     * adapters (e.g. those based on pl2303), does support
1309
     * this call.
1310
     */
1311
0
    ZeroMemory(&(pComm->counters), sizeof(struct serial_icounter_struct));
1312
0
  }
1313
1314
  /* The binary/raw mode is required for the redirection but
1315
   * only flags that are not handle somewhere-else, except
1316
   * ICANON, are forced here. */
1317
0
  ZeroMemory(&upcomingTermios, sizeof(struct termios));
1318
1319
0
  if (tcgetattr(pComm->fd, &upcomingTermios) < 0)
1320
0
  {
1321
0
    SetLastError(ERROR_IO_DEVICE);
1322
0
    goto error_handle;
1323
0
  }
1324
1325
0
  upcomingTermios.c_iflag &=
1326
0
      ~(/*IGNBRK |*/ BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL /*| IXON*/);
1327
0
  upcomingTermios.c_oflag = 0; /* <=> &= ~OPOST */
1328
0
  upcomingTermios.c_lflag = 0; /* <=> &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN); */
1329
  /* upcomingTermios.c_cflag &= ~(CSIZE | PARENB); */
1330
  /* upcomingTermios.c_cflag |= CS8; */
1331
  /* About missing flags recommended by termios(3):
1332
   *
1333
   *   IGNBRK and IXON, see: IOCTL_SERIAL_SET_HANDFLOW
1334
   *   CSIZE, PARENB and CS8, see: IOCTL_SERIAL_SET_LINE_CONTROL
1335
   */
1336
  /* a few more settings required for the redirection */
1337
0
  upcomingTermios.c_cflag |= CLOCAL | CREAD;
1338
1339
0
  if (_comm_ioctl_tcsetattr(pComm->fd, TCSANOW, &upcomingTermios) < 0)
1340
0
  {
1341
0
    SetLastError(ERROR_IO_DEVICE);
1342
0
    goto error_handle;
1343
0
  }
1344
1345
0
  return (HANDLE)pComm;
1346
0
error_handle:
1347
0
  WINPR_PRAGMA_DIAG_PUSH
1348
0
  WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC
1349
0
  CloseHandle(pComm);
1350
0
  WINPR_PRAGMA_DIAG_POP
1351
0
  return INVALID_HANDLE_VALUE;
1352
0
}
1353
1354
BOOL CommIsHandled(HANDLE handle)
1355
0
{
1356
0
  if (!CommInitialized())
1357
0
    return FALSE;
1358
1359
0
  return WINPR_HANDLE_IS_HANDLED(handle, HANDLE_TYPE_COMM, TRUE);
1360
0
}
1361
1362
BOOL CommIsHandleValid(HANDLE handle)
1363
0
{
1364
0
  WINPR_COMM* pComm = (WINPR_COMM*)handle;
1365
0
  if (!CommIsHandled(handle))
1366
0
    return FALSE;
1367
0
  if (pComm->fd <= 0)
1368
0
  {
1369
0
    SetLastError(ERROR_INVALID_HANDLE);
1370
0
    return FALSE;
1371
0
  }
1372
0
  return TRUE;
1373
0
}
1374
1375
BOOL CommCloseHandle(HANDLE handle)
1376
0
{
1377
0
  WINPR_COMM* pComm = (WINPR_COMM*)handle;
1378
1379
0
  if (!CommIsHandled(handle))
1380
0
    return FALSE;
1381
1382
0
  DeleteCriticalSection(&pComm->ReadLock);
1383
0
  DeleteCriticalSection(&pComm->WriteLock);
1384
0
  DeleteCriticalSection(&pComm->EventsLock);
1385
1386
0
  if (pComm->fd > 0)
1387
0
    close(pComm->fd);
1388
1389
0
  if (pComm->fd_write > 0)
1390
0
    close(pComm->fd_write);
1391
1392
0
  if (pComm->fd_write_event > 0)
1393
0
    close(pComm->fd_write_event);
1394
1395
0
  if (pComm->fd_read > 0)
1396
0
    close(pComm->fd_read);
1397
1398
0
  if (pComm->fd_read_event > 0)
1399
0
    close(pComm->fd_read_event);
1400
1401
0
  free(pComm);
1402
0
  return TRUE;
1403
0
}
1404
1405
#ifndef WITH_EVENTFD_READ_WRITE
1406
int eventfd_read(int fd, eventfd_t* value)
1407
{
1408
  return (read(fd, value, sizeof(*value)) == sizeof(*value)) ? 0 : -1;
1409
}
1410
1411
int eventfd_write(int fd, eventfd_t value)
1412
{
1413
  return (write(fd, &value, sizeof(value)) == sizeof(value)) ? 0 : -1;
1414
}
1415
#endif