Coverage Report

Created: 2025-08-26 06:37

/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
#if defined(WINPR_HAVE_SYS_EVENTFD_H)
31
#include <sys/eventfd.h>
32
#endif
33
#include <sys/ioctl.h>
34
#include <sys/stat.h>
35
#include <sys/types.h>
36
#include <termios.h>
37
#include <unistd.h>
38
39
#include <winpr/crt.h>
40
#include <winpr/comm.h>
41
#include <winpr/tchar.h>
42
#include <winpr/wlog.h>
43
#include <winpr/handle.h>
44
45
#include "comm_ioctl.h"
46
47
#include "../log.h"
48
0
#define TAG WINPR_TAG("comm")
49
50
/**
51
 * Communication Resources:
52
 * http://msdn.microsoft.com/en-us/library/windows/desktop/aa363196/
53
 */
54
55
#include "comm.h"
56
57
static wLog* sLog = NULL;
58
59
struct comm_device
60
{
61
  LPTSTR name;
62
  LPTSTR path;
63
};
64
65
typedef struct comm_device COMM_DEVICE;
66
67
/* FIXME: get a clever data structure, see also io.h functions */
68
/* _CommDevices is a NULL-terminated array with a maximum of COMM_DEVICE_MAX COMM_DEVICE */
69
0
#define COMM_DEVICE_MAX 128
70
static COMM_DEVICE** sCommDevices = NULL;
71
static CRITICAL_SECTION sCommDevicesLock = { 0 };
72
73
static pthread_once_t sCommInitialized = PTHREAD_ONCE_INIT;
74
75
static const _SERIAL_IOCTL_NAME S_SERIAL_IOCTL_NAMES[] = {
76
  { IOCTL_SERIAL_SET_BAUD_RATE, "IOCTL_SERIAL_SET_BAUD_RATE" },
77
  { IOCTL_SERIAL_GET_BAUD_RATE, "IOCTL_SERIAL_GET_BAUD_RATE" },
78
  { IOCTL_SERIAL_SET_LINE_CONTROL, "IOCTL_SERIAL_SET_LINE_CONTROL" },
79
  { IOCTL_SERIAL_GET_LINE_CONTROL, "IOCTL_SERIAL_GET_LINE_CONTROL" },
80
  { IOCTL_SERIAL_SET_TIMEOUTS, "IOCTL_SERIAL_SET_TIMEOUTS" },
81
  { IOCTL_SERIAL_GET_TIMEOUTS, "IOCTL_SERIAL_GET_TIMEOUTS" },
82
  { IOCTL_SERIAL_GET_CHARS, "IOCTL_SERIAL_GET_CHARS" },
83
  { IOCTL_SERIAL_SET_CHARS, "IOCTL_SERIAL_SET_CHARS" },
84
  { IOCTL_SERIAL_SET_DTR, "IOCTL_SERIAL_SET_DTR" },
85
  { IOCTL_SERIAL_CLR_DTR, "IOCTL_SERIAL_CLR_DTR" },
86
  { IOCTL_SERIAL_RESET_DEVICE, "IOCTL_SERIAL_RESET_DEVICE" },
87
  { IOCTL_SERIAL_SET_RTS, "IOCTL_SERIAL_SET_RTS" },
88
  { IOCTL_SERIAL_CLR_RTS, "IOCTL_SERIAL_CLR_RTS" },
89
  { IOCTL_SERIAL_SET_XOFF, "IOCTL_SERIAL_SET_XOFF" },
90
  { IOCTL_SERIAL_SET_XON, "IOCTL_SERIAL_SET_XON" },
91
  { IOCTL_SERIAL_SET_BREAK_ON, "IOCTL_SERIAL_SET_BREAK_ON" },
92
  { IOCTL_SERIAL_SET_BREAK_OFF, "IOCTL_SERIAL_SET_BREAK_OFF" },
93
  { IOCTL_SERIAL_SET_QUEUE_SIZE, "IOCTL_SERIAL_SET_QUEUE_SIZE" },
94
  { IOCTL_SERIAL_GET_WAIT_MASK, "IOCTL_SERIAL_GET_WAIT_MASK" },
95
  { IOCTL_SERIAL_SET_WAIT_MASK, "IOCTL_SERIAL_SET_WAIT_MASK" },
96
  { IOCTL_SERIAL_WAIT_ON_MASK, "IOCTL_SERIAL_WAIT_ON_MASK" },
97
  { IOCTL_SERIAL_IMMEDIATE_CHAR, "IOCTL_SERIAL_IMMEDIATE_CHAR" },
98
  { IOCTL_SERIAL_PURGE, "IOCTL_SERIAL_PURGE" },
99
  { IOCTL_SERIAL_GET_HANDFLOW, "IOCTL_SERIAL_GET_HANDFLOW" },
100
  { IOCTL_SERIAL_SET_HANDFLOW, "IOCTL_SERIAL_SET_HANDFLOW" },
101
  { IOCTL_SERIAL_GET_MODEMSTATUS, "IOCTL_SERIAL_GET_MODEMSTATUS" },
102
  { IOCTL_SERIAL_GET_DTRRTS, "IOCTL_SERIAL_GET_DTRRTS" },
103
  { IOCTL_SERIAL_GET_COMMSTATUS, "IOCTL_SERIAL_GET_COMMSTATUS" },
104
  { IOCTL_SERIAL_GET_PROPERTIES, "IOCTL_SERIAL_GET_PROPERTIES" },
105
  // {IOCTL_SERIAL_XOFF_COUNTER,  "IOCTL_SERIAL_XOFF_COUNTER"},
106
  // {IOCTL_SERIAL_LSRMST_INSERT, "IOCTL_SERIAL_LSRMST_INSERT"},
107
  { IOCTL_SERIAL_CONFIG_SIZE, "IOCTL_SERIAL_CONFIG_SIZE" },
108
  // {IOCTL_SERIAL_GET_STATS, "IOCTL_SERIAL_GET_STATS"},
109
  // {IOCTL_SERIAL_CLEAR_STATS, "IOCTL_SERIAL_CLEAR_STATS"},
110
  // {IOCTL_SERIAL_GET_MODEM_CONTROL,"IOCTL_SERIAL_GET_MODEM_CONTROL"},
111
  // {IOCTL_SERIAL_SET_MODEM_CONTROL,"IOCTL_SERIAL_SET_MODEM_CONTROL"},
112
  // {IOCTL_SERIAL_SET_FIFO_CONTROL,  "IOCTL_SERIAL_SET_FIFO_CONTROL"},
113
114
  // {IOCTL_PAR_QUERY_INFORMATION,  "IOCTL_PAR_QUERY_INFORMATION"},
115
  // {IOCTL_PAR_SET_INFORMATION,  "IOCTL_PAR_SET_INFORMATION"},
116
  // {IOCTL_PAR_QUERY_DEVICE_ID,  "IOCTL_PAR_QUERY_DEVICE_ID"},
117
  // {IOCTL_PAR_QUERY_DEVICE_ID_SIZE,"IOCTL_PAR_QUERY_DEVICE_ID_SIZE"},
118
  // {IOCTL_IEEE1284_GET_MODE,  "IOCTL_IEEE1284_GET_MODE"},
119
  // {IOCTL_IEEE1284_NEGOTIATE, "IOCTL_IEEE1284_NEGOTIATE"},
120
  // {IOCTL_PAR_SET_WRITE_ADDRESS,  "IOCTL_PAR_SET_WRITE_ADDRESS"},
121
  // {IOCTL_PAR_SET_READ_ADDRESS, "IOCTL_PAR_SET_READ_ADDRESS"},
122
  // {IOCTL_PAR_GET_DEVICE_CAPS,  "IOCTL_PAR_GET_DEVICE_CAPS"},
123
  // {IOCTL_PAR_GET_DEFAULT_MODES,  "IOCTL_PAR_GET_DEFAULT_MODES"},
124
  // {IOCTL_PAR_QUERY_RAW_DEVICE_ID, "IOCTL_PAR_QUERY_RAW_DEVICE_ID"},
125
  // {IOCTL_PAR_IS_PORT_FREE, "IOCTL_PAR_IS_PORT_FREE"},
126
127
  { IOCTL_USBPRINT_GET_1284_ID, "IOCTL_USBPRINT_GET_1284_ID" }
128
};
129
130
const char* _comm_serial_ioctl_name(ULONG number)
131
0
{
132
0
  for (size_t x = 0; x < ARRAYSIZE(S_SERIAL_IOCTL_NAMES); x++)
133
0
  {
134
0
    const _SERIAL_IOCTL_NAME* cur = &S_SERIAL_IOCTL_NAMES[x];
135
0
    if (cur->number == number)
136
0
      return cur->name;
137
0
  }
138
139
0
  return "(unknown ioctl name)";
140
0
}
141
142
static int CommGetFd(HANDLE handle)
143
0
{
144
0
  WINPR_COMM* comm = (WINPR_COMM*)handle;
145
146
0
  if (!CommIsHandled(handle))
147
0
    return -1;
148
149
0
  return comm->fd;
150
0
}
151
152
const HANDLE_CREATOR* GetCommHandleCreator(void)
153
0
{
154
0
#if defined(WINPR_HAVE_SERIAL_SUPPORT)
155
0
  static const HANDLE_CREATOR sCommHandleCreator = { .IsHandled = IsCommDevice,
156
0
                                                   .CreateFileA = CommCreateFileA };
157
0
  return &sCommHandleCreator;
158
#else
159
  return NULL;
160
#endif
161
0
}
162
163
static void CommInit(void)
164
0
{
165
  /* NB: error management to be done outside of this function */
166
0
  WINPR_ASSERT(sLog == NULL);
167
0
  WINPR_ASSERT(sCommDevices == NULL);
168
0
  sCommDevices = (COMM_DEVICE**)calloc(COMM_DEVICE_MAX + 1, sizeof(COMM_DEVICE*));
169
170
0
  if (!sCommDevices)
171
0
    return;
172
173
0
  if (!InitializeCriticalSectionEx(&sCommDevicesLock, 0, 0))
174
0
  {
175
0
    free((void*)sCommDevices);
176
0
    sCommDevices = NULL;
177
0
    return;
178
0
  }
179
180
0
  sLog = WLog_Get(TAG);
181
0
  WINPR_ASSERT(sLog != NULL);
182
0
}
183
184
/**
185
 * Returns TRUE when the comm module is correctly initialized, FALSE otherwise
186
 * with ERROR_DLL_INIT_FAILED set as the last error.
187
 */
188
static BOOL CommInitialized(void)
189
0
{
190
0
  if (pthread_once(&sCommInitialized, CommInit) != 0)
191
0
  {
192
0
    SetLastError(ERROR_DLL_INIT_FAILED);
193
0
    return FALSE;
194
0
  }
195
196
0
  return TRUE;
197
0
}
198
199
WINPR_ATTR_FORMAT_ARG(5, 6)
200
void CommLog_PrintEx(DWORD level, const char* file, size_t line, const char* fkt,
201
                     WINPR_FORMAT_ARG const char* fmt, ...)
202
0
{
203
0
  if (!CommInitialized())
204
0
    return;
205
206
0
  if (!WLog_IsLevelActive(sLog, level))
207
0
    return;
208
0
  va_list ap = { 0 };
209
0
  va_start(ap, fmt);
210
0
  WLog_PrintTextMessageVA(sLog, level, line, file, fkt, fmt, ap);
211
0
  va_end(ap);
212
0
}
213
214
BOOL BuildCommDCBA(WINPR_ATTR_UNUSED LPCSTR lpDef, WINPR_ATTR_UNUSED LPDCB lpDCB)
215
0
{
216
0
  if (!CommInitialized())
217
0
    return FALSE;
218
219
  /* TODO: not implemented */
220
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
221
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
222
0
  return FALSE;
223
0
}
224
225
BOOL BuildCommDCBW(WINPR_ATTR_UNUSED LPCWSTR lpDef, WINPR_ATTR_UNUSED LPDCB lpDCB)
226
0
{
227
0
  if (!CommInitialized())
228
0
    return FALSE;
229
230
  /* TODO: not implemented */
231
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
232
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
233
0
  return FALSE;
234
0
}
235
236
BOOL BuildCommDCBAndTimeoutsA(WINPR_ATTR_UNUSED LPCSTR lpDef, WINPR_ATTR_UNUSED LPDCB lpDCB,
237
                              WINPR_ATTR_UNUSED LPCOMMTIMEOUTS lpCommTimeouts)
238
0
{
239
0
  if (!CommInitialized())
240
0
    return FALSE;
241
242
  /* TODO: not implemented */
243
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
244
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
245
0
  return FALSE;
246
0
}
247
248
BOOL BuildCommDCBAndTimeoutsW(WINPR_ATTR_UNUSED LPCWSTR lpDef, WINPR_ATTR_UNUSED LPDCB lpDCB,
249
                              WINPR_ATTR_UNUSED LPCOMMTIMEOUTS lpCommTimeouts)
250
0
{
251
0
  if (!CommInitialized())
252
0
    return FALSE;
253
254
  /* TODO: not implemented */
255
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
256
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
257
0
  return FALSE;
258
0
}
259
260
BOOL CommConfigDialogA(WINPR_ATTR_UNUSED LPCSTR lpszName, WINPR_ATTR_UNUSED HWND hWnd,
261
                       WINPR_ATTR_UNUSED LPCOMMCONFIG lpCC)
262
0
{
263
0
  if (!CommInitialized())
264
0
    return FALSE;
265
266
  /* TODO: not implemented */
267
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
268
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
269
0
  return FALSE;
270
0
}
271
272
BOOL CommConfigDialogW(WINPR_ATTR_UNUSED LPCWSTR lpszName, WINPR_ATTR_UNUSED HWND hWnd,
273
                       WINPR_ATTR_UNUSED LPCOMMCONFIG lpCC)
274
0
{
275
0
  if (!CommInitialized())
276
0
    return FALSE;
277
278
  /* TODO: not implemented */
279
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
280
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
281
0
  return FALSE;
282
0
}
283
284
BOOL GetCommConfig(HANDLE hCommDev, WINPR_ATTR_UNUSED LPCOMMCONFIG lpCC,
285
                   WINPR_ATTR_UNUSED LPDWORD lpdwSize)
286
0
{
287
0
  WINPR_COMM* pComm = (WINPR_COMM*)hCommDev;
288
289
0
  if (!CommInitialized())
290
0
    return FALSE;
291
292
  /* TODO: not implemented */
293
294
0
  if (!pComm)
295
0
    return FALSE;
296
297
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
298
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
299
0
  return FALSE;
300
0
}
301
302
BOOL SetCommConfig(HANDLE hCommDev, WINPR_ATTR_UNUSED LPCOMMCONFIG lpCC,
303
                   WINPR_ATTR_UNUSED DWORD dwSize)
304
0
{
305
0
  WINPR_COMM* pComm = (WINPR_COMM*)hCommDev;
306
307
0
  if (!CommInitialized())
308
0
    return FALSE;
309
310
  /* TODO: not implemented */
311
312
0
  if (!pComm)
313
0
    return FALSE;
314
315
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
316
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
317
0
  return FALSE;
318
0
}
319
320
BOOL GetCommMask(HANDLE hFile, WINPR_ATTR_UNUSED PDWORD lpEvtMask)
321
0
{
322
0
  WINPR_COMM* pComm = (WINPR_COMM*)hFile;
323
324
0
  if (!CommInitialized())
325
0
    return FALSE;
326
327
  /* TODO: not implemented */
328
329
0
  if (!pComm)
330
0
    return FALSE;
331
332
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
333
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
334
0
  return FALSE;
335
0
}
336
337
BOOL SetCommMask(HANDLE hFile, WINPR_ATTR_UNUSED DWORD dwEvtMask)
338
0
{
339
0
  WINPR_COMM* pComm = (WINPR_COMM*)hFile;
340
341
0
  if (!CommInitialized())
342
0
    return FALSE;
343
344
  /* TODO: not implemented */
345
346
0
  if (!pComm)
347
0
    return FALSE;
348
349
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
350
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
351
0
  return FALSE;
352
0
}
353
354
BOOL GetCommModemStatus(HANDLE hFile, WINPR_ATTR_UNUSED PDWORD lpModemStat)
355
0
{
356
0
  WINPR_COMM* pComm = (WINPR_COMM*)hFile;
357
358
0
  if (!CommInitialized())
359
0
    return FALSE;
360
361
  /* TODO: not implemented */
362
363
0
  if (!pComm)
364
0
    return FALSE;
365
366
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
367
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
368
0
  return FALSE;
369
0
}
370
371
/**
372
 * ERRORS:
373
 *   ERROR_DLL_INIT_FAILED
374
 *   ERROR_INVALID_HANDLE
375
 */
376
BOOL GetCommProperties(HANDLE hFile, LPCOMMPROP lpCommProp)
377
0
{
378
0
  WINPR_COMM* pComm = (WINPR_COMM*)hFile;
379
0
  DWORD bytesReturned = 0;
380
381
0
  if (!CommIsHandleValid(hFile))
382
0
    return FALSE;
383
384
0
  if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_GET_PROPERTIES, NULL, 0, lpCommProp,
385
0
                           sizeof(COMMPROP), &bytesReturned, NULL))
386
0
  {
387
0
    CommLog_Print(WLOG_WARN, "GetCommProperties failure.");
388
0
    return FALSE;
389
0
  }
390
391
0
  return TRUE;
392
0
}
393
394
/**
395
 *
396
 *
397
 * ERRORS:
398
 *   ERROR_INVALID_HANDLE
399
 *   ERROR_INVALID_DATA
400
 *   ERROR_IO_DEVICE
401
 *   ERROR_OUTOFMEMORY
402
 */
403
BOOL GetCommState(HANDLE hFile, LPDCB lpDCB)
404
0
{
405
0
  DCB* lpLocalDcb = NULL;
406
0
  struct termios currentState;
407
0
  WINPR_COMM* pComm = (WINPR_COMM*)hFile;
408
0
  DWORD bytesReturned = 0;
409
410
0
  if (!CommIsHandleValid(hFile))
411
0
    return FALSE;
412
413
0
  if (!lpDCB)
414
0
  {
415
0
    SetLastError(ERROR_INVALID_DATA);
416
0
    return FALSE;
417
0
  }
418
419
0
  if (lpDCB->DCBlength < sizeof(DCB))
420
0
  {
421
0
    SetLastError(ERROR_INVALID_DATA);
422
0
    return FALSE;
423
0
  }
424
425
0
  if (tcgetattr(pComm->fd, &currentState) < 0)
426
0
  {
427
0
    SetLastError(ERROR_IO_DEVICE);
428
0
    return FALSE;
429
0
  }
430
431
0
  lpLocalDcb = (DCB*)calloc(1, lpDCB->DCBlength);
432
433
0
  if (lpLocalDcb == NULL)
434
0
  {
435
0
    SetLastError(ERROR_OUTOFMEMORY);
436
0
    return FALSE;
437
0
  }
438
439
  /* error_handle */
440
0
  lpLocalDcb->DCBlength = lpDCB->DCBlength;
441
0
  SERIAL_BAUD_RATE baudRate;
442
443
0
  if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_GET_BAUD_RATE, NULL, 0, &baudRate,
444
0
                           sizeof(SERIAL_BAUD_RATE), &bytesReturned, NULL))
445
0
  {
446
0
    CommLog_Print(WLOG_WARN, "GetCommState failure: could not get the baud rate.");
447
0
    goto error_handle;
448
0
  }
449
450
0
  lpLocalDcb->BaudRate = baudRate.BaudRate;
451
0
  lpLocalDcb->fBinary = (currentState.c_cflag & ICANON) == 0;
452
453
0
  if (!lpLocalDcb->fBinary)
454
0
  {
455
0
    CommLog_Print(WLOG_WARN, "Unexpected nonbinary mode, consider to unset the ICANON flag.");
456
0
  }
457
458
0
  lpLocalDcb->fParity = (currentState.c_iflag & INPCK) != 0;
459
0
  SERIAL_HANDFLOW handflow;
460
461
0
  if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_GET_HANDFLOW, NULL, 0, &handflow,
462
0
                           sizeof(SERIAL_HANDFLOW), &bytesReturned, NULL))
463
0
  {
464
0
    CommLog_Print(WLOG_WARN, "GetCommState failure: could not get the handflow settings.");
465
0
    goto error_handle;
466
0
  }
467
468
0
  lpLocalDcb->fOutxCtsFlow = (handflow.ControlHandShake & SERIAL_CTS_HANDSHAKE) != 0;
469
0
  lpLocalDcb->fOutxDsrFlow = (handflow.ControlHandShake & SERIAL_DSR_HANDSHAKE) != 0;
470
471
0
  if (handflow.ControlHandShake & SERIAL_DTR_HANDSHAKE)
472
0
  {
473
0
    lpLocalDcb->fDtrControl = DTR_CONTROL_HANDSHAKE;
474
0
  }
475
0
  else if (handflow.ControlHandShake & SERIAL_DTR_CONTROL)
476
0
  {
477
0
    lpLocalDcb->fDtrControl = DTR_CONTROL_ENABLE;
478
0
  }
479
0
  else
480
0
  {
481
0
    lpLocalDcb->fDtrControl = DTR_CONTROL_DISABLE;
482
0
  }
483
484
0
  lpLocalDcb->fDsrSensitivity = (handflow.ControlHandShake & SERIAL_DSR_SENSITIVITY) != 0;
485
0
  lpLocalDcb->fTXContinueOnXoff = (handflow.FlowReplace & SERIAL_XOFF_CONTINUE) != 0;
486
0
  lpLocalDcb->fOutX = (handflow.FlowReplace & SERIAL_AUTO_TRANSMIT) != 0;
487
0
  lpLocalDcb->fInX = (handflow.FlowReplace & SERIAL_AUTO_RECEIVE) != 0;
488
0
  lpLocalDcb->fErrorChar = (handflow.FlowReplace & SERIAL_ERROR_CHAR) != 0;
489
0
  lpLocalDcb->fNull = (handflow.FlowReplace & SERIAL_NULL_STRIPPING) != 0;
490
491
0
  if (handflow.FlowReplace & SERIAL_RTS_HANDSHAKE)
492
0
  {
493
0
    lpLocalDcb->fRtsControl = RTS_CONTROL_HANDSHAKE;
494
0
  }
495
0
  else if (handflow.FlowReplace & SERIAL_RTS_CONTROL)
496
0
  {
497
0
    lpLocalDcb->fRtsControl = RTS_CONTROL_ENABLE;
498
0
  }
499
0
  else
500
0
  {
501
0
    lpLocalDcb->fRtsControl = RTS_CONTROL_DISABLE;
502
0
  }
503
504
  // FIXME: how to get the RTS_CONTROL_TOGGLE state? Does it match the UART 16750's Autoflow
505
  // Control Enabled bit in its Modem Control Register (MCR)
506
0
  lpLocalDcb->fAbortOnError = (handflow.ControlHandShake & SERIAL_ERROR_ABORT) != 0;
507
  /* lpLocalDcb->fDummy2 not used */
508
0
  lpLocalDcb->wReserved = 0; /* must be zero */
509
0
  lpLocalDcb->XonLim = WINPR_ASSERTING_INT_CAST(WORD, handflow.XonLimit);
510
0
  lpLocalDcb->XoffLim = WINPR_ASSERTING_INT_CAST(WORD, handflow.XoffLimit);
511
0
  SERIAL_LINE_CONTROL lineControl = { 0 };
512
513
0
  if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_GET_LINE_CONTROL, NULL, 0, &lineControl,
514
0
                           sizeof(SERIAL_LINE_CONTROL), &bytesReturned, NULL))
515
0
  {
516
0
    CommLog_Print(WLOG_WARN, "GetCommState failure: could not get the control settings.");
517
0
    goto error_handle;
518
0
  }
519
520
0
  lpLocalDcb->ByteSize = lineControl.WordLength;
521
0
  lpLocalDcb->Parity = lineControl.Parity;
522
0
  lpLocalDcb->StopBits = lineControl.StopBits;
523
0
  SERIAL_CHARS serialChars;
524
525
0
  if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_GET_CHARS, NULL, 0, &serialChars,
526
0
                           sizeof(SERIAL_CHARS), &bytesReturned, NULL))
527
0
  {
528
0
    CommLog_Print(WLOG_WARN, "GetCommState failure: could not get the serial chars.");
529
0
    goto error_handle;
530
0
  }
531
532
0
  lpLocalDcb->XonChar = serialChars.XonChar;
533
0
  lpLocalDcb->XoffChar = serialChars.XoffChar;
534
0
  lpLocalDcb->ErrorChar = serialChars.ErrorChar;
535
0
  lpLocalDcb->EofChar = serialChars.EofChar;
536
0
  lpLocalDcb->EvtChar = serialChars.EventChar;
537
0
  memcpy(lpDCB, lpLocalDcb, lpDCB->DCBlength);
538
0
  free(lpLocalDcb);
539
0
  return TRUE;
540
0
error_handle:
541
0
  free(lpLocalDcb);
542
0
  return FALSE;
543
0
}
544
545
/**
546
 * @return TRUE on success, FALSE otherwise.
547
 *
548
 * As of today, SetCommState() can fail half-way with some settings
549
 * applied and some others not. SetCommState() returns on the first
550
 * failure met. FIXME: or is it correct?
551
 *
552
 * ERRORS:
553
 *   ERROR_INVALID_HANDLE
554
 *   ERROR_IO_DEVICE
555
 */
556
BOOL SetCommState(HANDLE hFile, LPDCB lpDCB)
557
0
{
558
0
  struct termios upcomingTermios = { 0 };
559
0
  WINPR_COMM* pComm = (WINPR_COMM*)hFile;
560
0
  DWORD bytesReturned = 0;
561
562
  /* FIXME: validate changes according GetCommProperties? */
563
564
0
  if (!CommIsHandleValid(hFile))
565
0
    return FALSE;
566
567
0
  if (!lpDCB)
568
0
  {
569
0
    SetLastError(ERROR_INVALID_DATA);
570
0
    return FALSE;
571
0
  }
572
573
  /* NB: did the choice to call ioctls first when available and
574
     then to setup upcomingTermios. Don't mix both stages. */
575
  /** ioctl calls stage **/
576
0
  SERIAL_BAUD_RATE baudRate;
577
0
  baudRate.BaudRate = lpDCB->BaudRate;
578
579
0
  if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_SET_BAUD_RATE, &baudRate, sizeof(SERIAL_BAUD_RATE),
580
0
                           NULL, 0, &bytesReturned, NULL))
581
0
  {
582
0
    CommLog_Print(WLOG_WARN, "SetCommState failure: could not set the baud rate.");
583
0
    return FALSE;
584
0
  }
585
586
0
  SERIAL_CHARS serialChars;
587
588
0
  if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_GET_CHARS, NULL, 0, &serialChars,
589
0
                           sizeof(SERIAL_CHARS), &bytesReturned,
590
0
                           NULL)) /* as of today, required for BreakChar */
591
0
  {
592
0
    CommLog_Print(WLOG_WARN, "SetCommState failure: could not get the initial serial chars.");
593
0
    return FALSE;
594
0
  }
595
596
0
  serialChars.XonChar = lpDCB->XonChar;
597
0
  serialChars.XoffChar = lpDCB->XoffChar;
598
0
  serialChars.ErrorChar = lpDCB->ErrorChar;
599
0
  serialChars.EofChar = lpDCB->EofChar;
600
0
  serialChars.EventChar = lpDCB->EvtChar;
601
602
0
  if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_SET_CHARS, &serialChars, sizeof(SERIAL_CHARS),
603
0
                           NULL, 0, &bytesReturned, NULL))
604
0
  {
605
0
    CommLog_Print(WLOG_WARN, "SetCommState failure: could not set the serial chars.");
606
0
    return FALSE;
607
0
  }
608
609
0
  SERIAL_LINE_CONTROL lineControl;
610
0
  lineControl.StopBits = lpDCB->StopBits;
611
0
  lineControl.Parity = lpDCB->Parity;
612
0
  lineControl.WordLength = lpDCB->ByteSize;
613
614
0
  if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_SET_LINE_CONTROL, &lineControl,
615
0
                           sizeof(SERIAL_LINE_CONTROL), NULL, 0, &bytesReturned, NULL))
616
0
  {
617
0
    CommLog_Print(WLOG_WARN, "SetCommState failure: could not set the control settings.");
618
0
    return FALSE;
619
0
  }
620
621
0
  SERIAL_HANDFLOW handflow = { 0 };
622
623
0
  if (lpDCB->fOutxCtsFlow)
624
0
  {
625
0
    handflow.ControlHandShake |= SERIAL_CTS_HANDSHAKE;
626
0
  }
627
628
0
  if (lpDCB->fOutxDsrFlow)
629
0
  {
630
0
    handflow.ControlHandShake |= SERIAL_DSR_HANDSHAKE;
631
0
  }
632
633
0
  switch (lpDCB->fDtrControl)
634
0
  {
635
0
    case SERIAL_DTR_HANDSHAKE:
636
0
      handflow.ControlHandShake |= DTR_CONTROL_HANDSHAKE;
637
0
      break;
638
639
0
    case SERIAL_DTR_CONTROL:
640
0
      handflow.ControlHandShake |= DTR_CONTROL_ENABLE;
641
0
      break;
642
643
0
    case DTR_CONTROL_DISABLE:
644
      /* do nothing since handflow is init-zeroed */
645
0
      break;
646
647
0
    default:
648
0
      CommLog_Print(WLOG_WARN, "Unexpected fDtrControl value: %" PRId32 "\n",
649
0
                    lpDCB->fDtrControl);
650
0
      return FALSE;
651
0
  }
652
653
0
  if (lpDCB->fDsrSensitivity)
654
0
  {
655
0
    handflow.ControlHandShake |= SERIAL_DSR_SENSITIVITY;
656
0
  }
657
658
0
  if (lpDCB->fTXContinueOnXoff)
659
0
  {
660
0
    handflow.FlowReplace |= SERIAL_XOFF_CONTINUE;
661
0
  }
662
663
0
  if (lpDCB->fOutX)
664
0
  {
665
0
    handflow.FlowReplace |= SERIAL_AUTO_TRANSMIT;
666
0
  }
667
668
0
  if (lpDCB->fInX)
669
0
  {
670
0
    handflow.FlowReplace |= SERIAL_AUTO_RECEIVE;
671
0
  }
672
673
0
  if (lpDCB->fErrorChar)
674
0
  {
675
0
    handflow.FlowReplace |= SERIAL_ERROR_CHAR;
676
0
  }
677
678
0
  if (lpDCB->fNull)
679
0
  {
680
0
    handflow.FlowReplace |= SERIAL_NULL_STRIPPING;
681
0
  }
682
683
0
  switch (lpDCB->fRtsControl)
684
0
  {
685
0
    case RTS_CONTROL_TOGGLE:
686
0
      CommLog_Print(WLOG_WARN, "Unsupported RTS_CONTROL_TOGGLE feature");
687
      // FIXME: see also GetCommState()
688
0
      return FALSE;
689
690
0
    case RTS_CONTROL_HANDSHAKE:
691
0
      handflow.FlowReplace |= SERIAL_RTS_HANDSHAKE;
692
0
      break;
693
694
0
    case RTS_CONTROL_ENABLE:
695
0
      handflow.FlowReplace |= SERIAL_RTS_CONTROL;
696
0
      break;
697
698
0
    case RTS_CONTROL_DISABLE:
699
      /* do nothing since handflow is init-zeroed */
700
0
      break;
701
702
0
    default:
703
0
      CommLog_Print(WLOG_WARN, "Unexpected fRtsControl value: %" PRId32 "\n",
704
0
                    lpDCB->fRtsControl);
705
0
      return FALSE;
706
0
  }
707
708
0
  if (lpDCB->fAbortOnError)
709
0
  {
710
0
    handflow.ControlHandShake |= SERIAL_ERROR_ABORT;
711
0
  }
712
713
  /* lpDCB->fDummy2 not used */
714
  /* lpLocalDcb->wReserved  ignored */
715
0
  handflow.XonLimit = lpDCB->XonLim;
716
0
  handflow.XoffLimit = lpDCB->XoffLim;
717
718
0
  if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_SET_HANDFLOW, &handflow, sizeof(SERIAL_HANDFLOW),
719
0
                           NULL, 0, &bytesReturned, NULL))
720
0
  {
721
0
    CommLog_Print(WLOG_WARN, "SetCommState failure: could not set the handflow settings.");
722
0
    return FALSE;
723
0
  }
724
725
  /** upcomingTermios stage **/
726
727
0
  if (tcgetattr(pComm->fd, &upcomingTermios) <
728
0
      0) /* NB: preserves current settings not directly handled by the Communication Functions */
729
0
  {
730
0
    SetLastError(ERROR_IO_DEVICE);
731
0
    return FALSE;
732
0
  }
733
734
0
  if (lpDCB->fBinary)
735
0
  {
736
0
    upcomingTermios.c_lflag &= (tcflag_t)~ICANON;
737
0
  }
738
0
  else
739
0
  {
740
0
    upcomingTermios.c_lflag |= ICANON;
741
0
    CommLog_Print(WLOG_WARN, "Unexpected nonbinary mode, consider to unset the ICANON flag.");
742
0
  }
743
744
0
  if (lpDCB->fParity)
745
0
  {
746
0
    upcomingTermios.c_iflag |= INPCK;
747
0
  }
748
0
  else
749
0
  {
750
0
    upcomingTermios.c_iflag &= (tcflag_t)~INPCK;
751
0
  }
752
753
  /* http://msdn.microsoft.com/en-us/library/windows/desktop/aa363423%28v=vs.85%29.aspx
754
   *
755
   * The SetCommState function reconfigures the communications
756
   * resource, but it does not affect the internal output and
757
   * input buffers of the specified driver. The buffers are not
758
   * flushed, and pending read and write operations are not
759
   * terminated prematurely.
760
   *
761
   * TCSANOW matches the best this definition
762
   */
763
764
0
  if (comm_ioctl_tcsetattr(pComm->fd, TCSANOW, &upcomingTermios) < 0)
765
0
  {
766
0
    SetLastError(ERROR_IO_DEVICE);
767
0
    return FALSE;
768
0
  }
769
770
0
  return TRUE;
771
0
}
772
773
/**
774
 * ERRORS:
775
 *   ERROR_INVALID_HANDLE
776
 */
777
BOOL GetCommTimeouts(HANDLE hFile, LPCOMMTIMEOUTS lpCommTimeouts)
778
0
{
779
0
  WINPR_COMM* pComm = (WINPR_COMM*)hFile;
780
0
  DWORD bytesReturned = 0;
781
782
0
  if (!CommIsHandleValid(hFile))
783
0
    return FALSE;
784
785
  /* as of today, SERIAL_TIMEOUTS and COMMTIMEOUTS structures are identical */
786
787
0
  if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_GET_TIMEOUTS, NULL, 0, lpCommTimeouts,
788
0
                           sizeof(COMMTIMEOUTS), &bytesReturned, NULL))
789
0
  {
790
0
    CommLog_Print(WLOG_WARN, "GetCommTimeouts failure.");
791
0
    return FALSE;
792
0
  }
793
794
0
  return TRUE;
795
0
}
796
797
/**
798
 * ERRORS:
799
 *   ERROR_INVALID_HANDLE
800
 */
801
BOOL SetCommTimeouts(HANDLE hFile, LPCOMMTIMEOUTS lpCommTimeouts)
802
0
{
803
0
  WINPR_COMM* pComm = (WINPR_COMM*)hFile;
804
0
  DWORD bytesReturned = 0;
805
806
0
  if (!CommIsHandleValid(hFile))
807
0
    return FALSE;
808
809
  /* as of today, SERIAL_TIMEOUTS and COMMTIMEOUTS structures are identical */
810
811
0
  if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_SET_TIMEOUTS, lpCommTimeouts, sizeof(COMMTIMEOUTS),
812
0
                           NULL, 0, &bytesReturned, NULL))
813
0
  {
814
0
    CommLog_Print(WLOG_WARN, "SetCommTimeouts failure.");
815
0
    return FALSE;
816
0
  }
817
818
0
  return TRUE;
819
0
}
820
821
BOOL GetDefaultCommConfigA(WINPR_ATTR_UNUSED LPCSTR lpszName, WINPR_ATTR_UNUSED LPCOMMCONFIG lpCC,
822
                           WINPR_ATTR_UNUSED LPDWORD lpdwSize)
823
0
{
824
0
  if (!CommInitialized())
825
0
    return FALSE;
826
827
  /* TODO: not implemented */
828
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
829
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
830
0
  return FALSE;
831
0
}
832
833
BOOL GetDefaultCommConfigW(WINPR_ATTR_UNUSED LPCWSTR lpszName, WINPR_ATTR_UNUSED LPCOMMCONFIG lpCC,
834
                           WINPR_ATTR_UNUSED LPDWORD lpdwSize)
835
0
{
836
0
  if (!CommInitialized())
837
0
    return FALSE;
838
839
  /* TODO: not implemented */
840
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
841
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
842
0
  return FALSE;
843
0
}
844
845
BOOL SetDefaultCommConfigA(WINPR_ATTR_UNUSED LPCSTR lpszName, WINPR_ATTR_UNUSED LPCOMMCONFIG lpCC,
846
                           WINPR_ATTR_UNUSED DWORD dwSize)
847
0
{
848
0
  if (!CommInitialized())
849
0
    return FALSE;
850
851
  /* TODO: not implemented */
852
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
853
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
854
0
  return FALSE;
855
0
}
856
857
BOOL SetDefaultCommConfigW(WINPR_ATTR_UNUSED LPCWSTR lpszName, WINPR_ATTR_UNUSED LPCOMMCONFIG lpCC,
858
                           WINPR_ATTR_UNUSED DWORD dwSize)
859
0
{
860
0
  if (!CommInitialized())
861
0
    return FALSE;
862
863
  /* TODO: not implemented */
864
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
865
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
866
0
  return FALSE;
867
0
}
868
869
BOOL SetCommBreak(HANDLE hFile)
870
0
{
871
0
  WINPR_COMM* pComm = (WINPR_COMM*)hFile;
872
873
0
  if (!CommInitialized())
874
0
    return FALSE;
875
876
  /* TODO: not implemented */
877
878
0
  if (!pComm)
879
0
    return FALSE;
880
881
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
882
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
883
0
  return FALSE;
884
0
}
885
886
BOOL ClearCommBreak(HANDLE hFile)
887
0
{
888
0
  WINPR_COMM* pComm = (WINPR_COMM*)hFile;
889
890
0
  if (!CommInitialized())
891
0
    return FALSE;
892
893
  /* TODO: not implemented */
894
895
0
  if (!pComm)
896
0
    return FALSE;
897
898
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
899
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
900
0
  return FALSE;
901
0
}
902
903
BOOL ClearCommError(HANDLE hFile, WINPR_ATTR_UNUSED PDWORD lpErrors,
904
                    WINPR_ATTR_UNUSED LPCOMSTAT lpStat)
905
0
{
906
0
  WINPR_COMM* pComm = (WINPR_COMM*)hFile;
907
908
0
  if (!CommInitialized())
909
0
    return FALSE;
910
911
  /* TODO: not implemented */
912
913
0
  if (!pComm)
914
0
    return FALSE;
915
916
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
917
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
918
0
  return FALSE;
919
0
}
920
921
BOOL PurgeComm(HANDLE hFile, DWORD dwFlags)
922
0
{
923
0
  WINPR_COMM* pComm = (WINPR_COMM*)hFile;
924
0
  DWORD bytesReturned = 0;
925
926
0
  if (!CommIsHandleValid(hFile))
927
0
    return FALSE;
928
929
0
  if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_PURGE, &dwFlags, sizeof(DWORD), NULL, 0,
930
0
                           &bytesReturned, NULL))
931
0
  {
932
0
    CommLog_Print(WLOG_WARN, "PurgeComm failure.");
933
0
    return FALSE;
934
0
  }
935
936
0
  return TRUE;
937
0
}
938
939
BOOL SetupComm(HANDLE hFile, DWORD dwInQueue, DWORD dwOutQueue)
940
0
{
941
0
  WINPR_COMM* pComm = (WINPR_COMM*)hFile;
942
0
  SERIAL_QUEUE_SIZE queueSize;
943
0
  DWORD bytesReturned = 0;
944
945
0
  if (!CommIsHandleValid(hFile))
946
0
    return FALSE;
947
948
0
  queueSize.InSize = dwInQueue;
949
0
  queueSize.OutSize = dwOutQueue;
950
951
0
  if (!CommDeviceIoControl(pComm, IOCTL_SERIAL_SET_QUEUE_SIZE, &queueSize,
952
0
                           sizeof(SERIAL_QUEUE_SIZE), NULL, 0, &bytesReturned, NULL))
953
0
  {
954
0
    CommLog_Print(WLOG_WARN, "SetCommTimeouts failure.");
955
0
    return FALSE;
956
0
  }
957
958
0
  return TRUE;
959
0
}
960
961
BOOL EscapeCommFunction(HANDLE hFile, WINPR_ATTR_UNUSED DWORD dwFunc)
962
0
{
963
0
  WINPR_COMM* pComm = (WINPR_COMM*)hFile;
964
965
0
  if (!CommInitialized())
966
0
    return FALSE;
967
968
  /* TODO: not implemented */
969
970
0
  if (!pComm)
971
0
    return FALSE;
972
973
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
974
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
975
0
  return FALSE;
976
0
}
977
978
BOOL TransmitCommChar(HANDLE hFile, WINPR_ATTR_UNUSED char cChar)
979
0
{
980
0
  WINPR_COMM* pComm = (WINPR_COMM*)hFile;
981
982
0
  if (!CommInitialized())
983
0
    return FALSE;
984
985
  /* TODO: not implemented */
986
987
0
  if (!pComm)
988
0
    return FALSE;
989
990
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
991
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
992
0
  return FALSE;
993
0
}
994
995
BOOL WaitCommEvent(HANDLE hFile, WINPR_ATTR_UNUSED PDWORD lpEvtMask,
996
                   WINPR_ATTR_UNUSED LPOVERLAPPED lpOverlapped)
997
0
{
998
0
  WINPR_COMM* pComm = (WINPR_COMM*)hFile;
999
1000
0
  if (!CommInitialized())
1001
0
    return FALSE;
1002
1003
  /* TODO: not implemented */
1004
1005
0
  if (!pComm)
1006
0
    return FALSE;
1007
1008
0
  CommLog_Print(WLOG_ERROR, "Not implemented");
1009
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1010
0
  return FALSE;
1011
0
}
1012
1013
/**
1014
 * Returns TRUE on success, FALSE otherwise. To get extended error
1015
 * information, call GetLastError.
1016
 *
1017
 * ERRORS:
1018
 *   ERROR_DLL_INIT_FAILED
1019
 *   ERROR_OUTOFMEMORY was not possible to get mappings.
1020
 *   ERROR_INVALID_DATA was not possible to add the device.
1021
 */
1022
BOOL DefineCommDevice(/* DWORD dwFlags,*/ LPCTSTR lpDeviceName, LPCTSTR lpTargetPath)
1023
0
{
1024
0
  LPTSTR storedDeviceName = NULL;
1025
0
  LPTSTR storedTargetPath = NULL;
1026
1027
0
  if (!CommInitialized())
1028
0
    return FALSE;
1029
1030
0
  EnterCriticalSection(&sCommDevicesLock);
1031
1032
0
  if (sCommDevices == NULL)
1033
0
  {
1034
0
    SetLastError(ERROR_DLL_INIT_FAILED);
1035
0
    goto error_handle;
1036
0
  }
1037
1038
0
  storedDeviceName = _tcsdup(lpDeviceName);
1039
1040
0
  if (storedDeviceName == NULL)
1041
0
  {
1042
0
    SetLastError(ERROR_OUTOFMEMORY);
1043
0
    goto error_handle;
1044
0
  }
1045
1046
0
  storedTargetPath = _tcsdup(lpTargetPath);
1047
1048
0
  if (storedTargetPath == NULL)
1049
0
  {
1050
0
    SetLastError(ERROR_OUTOFMEMORY);
1051
0
    goto error_handle;
1052
0
  }
1053
1054
0
  int i = 0;
1055
0
  for (; i < COMM_DEVICE_MAX; i++)
1056
0
  {
1057
0
    if (sCommDevices[i] != NULL)
1058
0
    {
1059
0
      if (_tcscmp(sCommDevices[i]->name, storedDeviceName) == 0)
1060
0
      {
1061
        /* take over the emplacement */
1062
0
        free(sCommDevices[i]->name);
1063
0
        free(sCommDevices[i]->path);
1064
0
        sCommDevices[i]->name = storedDeviceName;
1065
0
        sCommDevices[i]->path = storedTargetPath;
1066
0
        break;
1067
0
      }
1068
0
    }
1069
0
    else
1070
0
    {
1071
      /* new emplacement */
1072
0
      sCommDevices[i] = (COMM_DEVICE*)calloc(1, sizeof(COMM_DEVICE));
1073
1074
0
      if (sCommDevices[i] == NULL)
1075
0
      {
1076
0
        SetLastError(ERROR_OUTOFMEMORY);
1077
0
        goto error_handle;
1078
0
      }
1079
1080
0
      sCommDevices[i]->name = storedDeviceName;
1081
0
      sCommDevices[i]->path = storedTargetPath;
1082
0
      break;
1083
0
    }
1084
0
  }
1085
1086
0
  if (i == COMM_DEVICE_MAX)
1087
0
  {
1088
0
    SetLastError(ERROR_OUTOFMEMORY);
1089
0
    goto error_handle;
1090
0
  }
1091
1092
0
  LeaveCriticalSection(&sCommDevicesLock);
1093
0
  return TRUE;
1094
0
error_handle:
1095
0
  free(storedDeviceName);
1096
0
  free(storedTargetPath);
1097
0
  LeaveCriticalSection(&sCommDevicesLock);
1098
0
  return FALSE;
1099
0
}
1100
1101
/**
1102
 * Returns the number of target paths in the buffer pointed to by
1103
 * lpTargetPath.
1104
 *
1105
 * The current implementation returns in any case 0 and 1 target
1106
 * path. A NULL lpDeviceName is not supported yet to get all the
1107
 * paths.
1108
 *
1109
 * ERRORS:
1110
 *   ERROR_SUCCESS
1111
 *   ERROR_DLL_INIT_FAILED
1112
 *   ERROR_OUTOFMEMORY was not possible to get mappings.
1113
 *   ERROR_NOT_SUPPORTED equivalent QueryDosDevice feature not supported.
1114
 *   ERROR_INVALID_DATA was not possible to retrieve any device information.
1115
 *   ERROR_INSUFFICIENT_BUFFER too small lpTargetPath
1116
 */
1117
DWORD QueryCommDevice(LPCTSTR lpDeviceName, LPTSTR lpTargetPath, DWORD ucchMax)
1118
0
{
1119
0
  LPTSTR storedTargetPath = NULL;
1120
0
  SetLastError(ERROR_SUCCESS);
1121
1122
0
  if (!CommInitialized())
1123
0
    return 0;
1124
1125
0
  if (sCommDevices == NULL)
1126
0
  {
1127
0
    SetLastError(ERROR_DLL_INIT_FAILED);
1128
0
    return 0;
1129
0
  }
1130
1131
0
  if (lpDeviceName == NULL || lpTargetPath == NULL)
1132
0
  {
1133
0
    SetLastError(ERROR_NOT_SUPPORTED);
1134
0
    return 0;
1135
0
  }
1136
1137
0
  EnterCriticalSection(&sCommDevicesLock);
1138
0
  storedTargetPath = NULL;
1139
1140
0
  for (int i = 0; i < COMM_DEVICE_MAX; i++)
1141
0
  {
1142
0
    if (sCommDevices[i] != NULL)
1143
0
    {
1144
0
      if (_tcscmp(sCommDevices[i]->name, lpDeviceName) == 0)
1145
0
      {
1146
0
        storedTargetPath = sCommDevices[i]->path;
1147
0
        break;
1148
0
      }
1149
1150
0
      continue;
1151
0
    }
1152
1153
0
    break;
1154
0
  }
1155
1156
0
  LeaveCriticalSection(&sCommDevicesLock);
1157
1158
0
  if (storedTargetPath == NULL)
1159
0
  {
1160
0
    SetLastError(ERROR_INVALID_DATA);
1161
0
    return 0;
1162
0
  }
1163
1164
0
  const size_t size = _tcsnlen(storedTargetPath, ucchMax);
1165
0
  if (size + 2 > ucchMax)
1166
0
  {
1167
0
    SetLastError(ERROR_INSUFFICIENT_BUFFER);
1168
0
    return 0;
1169
0
  }
1170
1171
0
  _tcsncpy(lpTargetPath, storedTargetPath, size + 1);
1172
0
  lpTargetPath[size + 2] = '\0'; /* 2nd final '\0' */
1173
0
  return (DWORD)size + 2UL;
1174
0
}
1175
1176
/**
1177
 * Checks whether lpDeviceName is a valid and registered Communication device.
1178
 */
1179
BOOL IsCommDevice(LPCTSTR lpDeviceName)
1180
0
{
1181
0
  TCHAR lpTargetPath[MAX_PATH];
1182
1183
0
  if (!CommInitialized())
1184
0
    return FALSE;
1185
1186
0
  if (QueryCommDevice(lpDeviceName, lpTargetPath, MAX_PATH) > 0)
1187
0
  {
1188
0
    return TRUE;
1189
0
  }
1190
1191
0
  return FALSE;
1192
0
}
1193
1194
/**
1195
 * Sets
1196
 */
1197
void _comm_setServerSerialDriver(HANDLE hComm, SERIAL_DRIVER_ID driverId)
1198
0
{
1199
0
  ULONG Type = 0;
1200
0
  WINPR_HANDLE* Object = NULL;
1201
0
  WINPR_COMM* pComm = NULL;
1202
1203
0
  if (!CommInitialized())
1204
0
    return;
1205
1206
0
  if (!winpr_Handle_GetInfo(hComm, &Type, &Object))
1207
0
  {
1208
0
    CommLog_Print(WLOG_WARN, "_comm_setServerSerialDriver failure");
1209
0
    return;
1210
0
  }
1211
1212
0
  pComm = (WINPR_COMM*)Object;
1213
0
  pComm->serverSerialDriverId = driverId;
1214
0
}
1215
1216
static HANDLE_OPS ops = { CommIsHandled, CommCloseHandle,
1217
                        CommGetFd,     NULL, /* CleanupHandle */
1218
                        NULL,          NULL,
1219
                        NULL,          NULL,
1220
                        NULL,          NULL,
1221
                        NULL,          NULL,
1222
                        NULL,          NULL,
1223
                        NULL,          NULL,
1224
                        NULL,          NULL,
1225
                        NULL,          NULL,
1226
                        NULL };
1227
1228
/**
1229
 * http://msdn.microsoft.com/en-us/library/windows/desktop/aa363198%28v=vs.85%29.aspx
1230
 *
1231
 * @param lpDeviceName e.g. COM1, ...
1232
 *
1233
 * @param dwDesiredAccess expects GENERIC_READ | GENERIC_WRITE, a
1234
 * warning message is printed otherwise. TODO: better support.
1235
 *
1236
 * @param dwShareMode must be zero, INVALID_HANDLE_VALUE is returned
1237
 * otherwise and GetLastError() should return ERROR_SHARING_VIOLATION.
1238
 *
1239
 * @param lpSecurityAttributes NULL expected, a warning message is printed
1240
 * otherwise. TODO: better support.
1241
 *
1242
 * @param dwCreationDisposition must be OPEN_EXISTING. If the
1243
 * communication device doesn't exist INVALID_HANDLE_VALUE is returned
1244
 * and GetLastError() returns ERROR_FILE_NOT_FOUND.
1245
 *
1246
 * @param dwFlagsAndAttributes zero expected, a warning message is
1247
 * printed otherwise.
1248
 *
1249
 * @param hTemplateFile must be NULL.
1250
 *
1251
 * @return INVALID_HANDLE_VALUE on error.
1252
 */
1253
HANDLE CommCreateFileA(LPCSTR lpDeviceName, DWORD dwDesiredAccess, DWORD dwShareMode,
1254
                       LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition,
1255
                       DWORD dwFlagsAndAttributes, HANDLE hTemplateFile)
1256
0
{
1257
0
  CHAR devicePath[MAX_PATH] = { 0 };
1258
0
  struct stat deviceStat = { 0 };
1259
0
  WINPR_COMM* pComm = NULL;
1260
0
  struct termios upcomingTermios = { 0 };
1261
1262
0
  if (!CommInitialized())
1263
0
    return INVALID_HANDLE_VALUE;
1264
1265
0
  if (dwDesiredAccess != (GENERIC_READ | GENERIC_WRITE))
1266
0
  {
1267
0
    CommLog_Print(WLOG_WARN, "unexpected access to the device: 0x%08" PRIX32 "",
1268
0
                  dwDesiredAccess);
1269
0
  }
1270
1271
0
  if (dwShareMode != 0)
1272
0
  {
1273
0
    SetLastError(ERROR_SHARING_VIOLATION);
1274
0
    return INVALID_HANDLE_VALUE;
1275
0
  }
1276
1277
  /* TODO: Prevents other processes from opening a file or
1278
   * device if they request delete, read, or write access. */
1279
1280
0
  if (lpSecurityAttributes != NULL)
1281
0
  {
1282
0
    CommLog_Print(WLOG_WARN, "unexpected security attributes, nLength=%" PRIu32 "",
1283
0
                  lpSecurityAttributes->nLength);
1284
0
  }
1285
1286
0
  if (dwCreationDisposition != OPEN_EXISTING)
1287
0
  {
1288
0
    SetLastError(ERROR_FILE_NOT_FOUND); /* FIXME: ERROR_NOT_SUPPORTED better? */
1289
0
    return INVALID_HANDLE_VALUE;
1290
0
  }
1291
1292
0
  if (QueryCommDevice(lpDeviceName, devicePath, MAX_PATH) <= 0)
1293
0
  {
1294
    /* SetLastError(GetLastError()); */
1295
0
    return INVALID_HANDLE_VALUE;
1296
0
  }
1297
1298
0
  if (stat(devicePath, &deviceStat) < 0)
1299
0
  {
1300
0
    CommLog_Print(WLOG_WARN, "device not found %s", devicePath);
1301
0
    SetLastError(ERROR_FILE_NOT_FOUND);
1302
0
    return INVALID_HANDLE_VALUE;
1303
0
  }
1304
1305
0
  if (!S_ISCHR(deviceStat.st_mode))
1306
0
  {
1307
0
    CommLog_Print(WLOG_WARN, "bad device %s", devicePath);
1308
0
    SetLastError(ERROR_BAD_DEVICE);
1309
0
    return INVALID_HANDLE_VALUE;
1310
0
  }
1311
1312
0
  if (dwFlagsAndAttributes != 0)
1313
0
  {
1314
0
    CommLog_Print(WLOG_WARN, "unexpected flags and attributes: 0x%08" PRIX32 "",
1315
0
                  dwFlagsAndAttributes);
1316
0
  }
1317
1318
0
  if (hTemplateFile != NULL)
1319
0
  {
1320
0
    SetLastError(ERROR_NOT_SUPPORTED); /* FIXME: other proper error? */
1321
0
    return INVALID_HANDLE_VALUE;
1322
0
  }
1323
1324
0
  pComm = (WINPR_COMM*)calloc(1, sizeof(WINPR_COMM));
1325
1326
0
  if (pComm == NULL)
1327
0
  {
1328
0
    SetLastError(ERROR_OUTOFMEMORY);
1329
0
    return INVALID_HANDLE_VALUE;
1330
0
  }
1331
1332
0
  WINPR_HANDLE_SET_TYPE_AND_MODE(pComm, HANDLE_TYPE_COMM, WINPR_FD_READ);
1333
0
  pComm->common.ops = &ops;
1334
  /* error_handle */
1335
0
  pComm->fd = open(devicePath, O_RDWR | O_NOCTTY | O_NONBLOCK);
1336
1337
0
  if (pComm->fd < 0)
1338
0
  {
1339
0
    CommLog_Print(WLOG_WARN, "failed to open device %s", devicePath);
1340
0
    SetLastError(ERROR_BAD_DEVICE);
1341
0
    goto error_handle;
1342
0
  }
1343
1344
0
  pComm->fd_read = open(devicePath, O_RDONLY | O_NOCTTY | O_NONBLOCK);
1345
1346
0
  if (pComm->fd_read < 0)
1347
0
  {
1348
0
    CommLog_Print(WLOG_WARN, "failed to open fd_read, device: %s", devicePath);
1349
0
    SetLastError(ERROR_BAD_DEVICE);
1350
0
    goto error_handle;
1351
0
  }
1352
1353
0
#if defined(WINPR_HAVE_SYS_EVENTFD_H)
1354
0
  pComm->fd_read_event = eventfd(
1355
0
      0, EFD_NONBLOCK); /* EFD_NONBLOCK required because a read() is not always expected */
1356
0
#endif
1357
1358
0
  if (pComm->fd_read_event < 0)
1359
0
  {
1360
0
    CommLog_Print(WLOG_WARN, "failed to open fd_read_event, device: %s", devicePath);
1361
0
    SetLastError(ERROR_BAD_DEVICE);
1362
0
    goto error_handle;
1363
0
  }
1364
1365
0
  InitializeCriticalSection(&pComm->ReadLock);
1366
0
  pComm->fd_write = open(devicePath, O_WRONLY | O_NOCTTY | O_NONBLOCK);
1367
1368
0
  if (pComm->fd_write < 0)
1369
0
  {
1370
0
    CommLog_Print(WLOG_WARN, "failed to open fd_write, device: %s", devicePath);
1371
0
    SetLastError(ERROR_BAD_DEVICE);
1372
0
    goto error_handle;
1373
0
  }
1374
1375
0
#if defined(WINPR_HAVE_SYS_EVENTFD_H)
1376
0
  pComm->fd_write_event = eventfd(
1377
0
      0, EFD_NONBLOCK); /* EFD_NONBLOCK required because a read() is not always expected */
1378
0
#endif
1379
1380
0
  if (pComm->fd_write_event < 0)
1381
0
  {
1382
0
    CommLog_Print(WLOG_WARN, "failed to open fd_write_event, device: %s", devicePath);
1383
0
    SetLastError(ERROR_BAD_DEVICE);
1384
0
    goto error_handle;
1385
0
  }
1386
1387
0
  InitializeCriticalSection(&pComm->WriteLock);
1388
  /* can also be setup later on with _comm_setServerSerialDriver() */
1389
0
  pComm->serverSerialDriverId = SerialDriverUnknown;
1390
0
  InitializeCriticalSection(&pComm->EventsLock);
1391
1392
0
  (void)CommUpdateIOCount(pComm, TRUE);
1393
1394
  /* The binary/raw mode is required for the redirection but
1395
   * only flags that are not handle somewhere-else, except
1396
   * ICANON, are forced here. */
1397
0
  ZeroMemory(&upcomingTermios, sizeof(struct termios));
1398
1399
0
  if (tcgetattr(pComm->fd, &upcomingTermios) < 0)
1400
0
  {
1401
0
    SetLastError(ERROR_IO_DEVICE);
1402
0
    goto error_handle;
1403
0
  }
1404
1405
0
  upcomingTermios.c_iflag &=
1406
0
      (tcflag_t) ~(/*IGNBRK |*/ BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL /*| IXON*/);
1407
0
  upcomingTermios.c_oflag = 0; /* <=> &= ~OPOST */
1408
0
  upcomingTermios.c_lflag = 0; /* <=> &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN); */
1409
  /* upcomingTermios.c_cflag &= ~(CSIZE | PARENB); */
1410
  /* upcomingTermios.c_cflag |= CS8; */
1411
  /* About missing flags recommended by termios(3):
1412
   *
1413
   *   IGNBRK and IXON, see: IOCTL_SERIAL_SET_HANDFLOW
1414
   *   CSIZE, PARENB and CS8, see: IOCTL_SERIAL_SET_LINE_CONTROL
1415
   */
1416
  /* a few more settings required for the redirection */
1417
0
  upcomingTermios.c_cflag |= CLOCAL | CREAD;
1418
1419
0
  if (comm_ioctl_tcsetattr(pComm->fd, TCSANOW, &upcomingTermios) < 0)
1420
0
  {
1421
0
    SetLastError(ERROR_IO_DEVICE);
1422
0
    goto error_handle;
1423
0
  }
1424
1425
0
  return (HANDLE)pComm;
1426
0
error_handle:
1427
0
  WINPR_PRAGMA_DIAG_PUSH
1428
0
  WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC(void) CloseHandle(pComm);
1429
0
  WINPR_PRAGMA_DIAG_POP
1430
0
  return INVALID_HANDLE_VALUE;
1431
0
}
1432
1433
BOOL CommIsHandled(HANDLE handle)
1434
0
{
1435
0
  if (!CommInitialized())
1436
0
    return FALSE;
1437
1438
0
  return WINPR_HANDLE_IS_HANDLED(handle, HANDLE_TYPE_COMM, TRUE);
1439
0
}
1440
1441
BOOL CommIsHandleValid(HANDLE handle)
1442
0
{
1443
0
  WINPR_COMM* pComm = (WINPR_COMM*)handle;
1444
0
  if (!CommIsHandled(handle))
1445
0
    return FALSE;
1446
0
  if (pComm->fd <= 0)
1447
0
  {
1448
0
    SetLastError(ERROR_INVALID_HANDLE);
1449
0
    return FALSE;
1450
0
  }
1451
0
  return TRUE;
1452
0
}
1453
1454
BOOL CommCloseHandle(HANDLE handle)
1455
0
{
1456
0
  WINPR_COMM* pComm = (WINPR_COMM*)handle;
1457
1458
0
  if (!CommIsHandled(handle))
1459
0
    return FALSE;
1460
1461
0
  DeleteCriticalSection(&pComm->ReadLock);
1462
0
  DeleteCriticalSection(&pComm->WriteLock);
1463
0
  DeleteCriticalSection(&pComm->EventsLock);
1464
1465
0
  if (pComm->fd > 0)
1466
0
    close(pComm->fd);
1467
1468
0
  if (pComm->fd_write > 0)
1469
0
    close(pComm->fd_write);
1470
1471
0
  if (pComm->fd_write_event > 0)
1472
0
    close(pComm->fd_write_event);
1473
1474
0
  if (pComm->fd_read > 0)
1475
0
    close(pComm->fd_read);
1476
1477
0
  if (pComm->fd_read_event > 0)
1478
0
    close(pComm->fd_read_event);
1479
1480
0
  free(pComm);
1481
0
  return TRUE;
1482
0
}
1483
1484
#if defined(WINPR_HAVE_SYS_EVENTFD_H)
1485
#ifndef WITH_EVENTFD_READ_WRITE
1486
int eventfd_read(int fd, eventfd_t* value)
1487
{
1488
  return (read(fd, value, sizeof(*value)) == sizeof(*value)) ? 0 : -1;
1489
}
1490
1491
int eventfd_write(int fd, eventfd_t value)
1492
{
1493
  return (write(fd, &value, sizeof(value)) == sizeof(value)) ? 0 : -1;
1494
}
1495
#endif
1496
#endif
1497
1498
static const char* CommIoCtlToStr(unsigned long int io)
1499
0
{
1500
0
  switch (io)
1501
0
  {
1502
0
#if defined(WINPR_HAVE_SERIAL_SUPPORT)
1503
0
#if defined(TCGETS)
1504
0
    case TCGETS:
1505
0
      return "TCGETS";
1506
0
#endif
1507
0
#if defined(TCSETS)
1508
0
    case TCSETS:
1509
0
      return "TCSETS";
1510
0
#endif
1511
0
#if defined(TCSETSW)
1512
0
    case TCSETSW:
1513
0
      return "TCSETSW";
1514
0
#endif
1515
0
#if defined(TCSETSF)
1516
0
    case TCSETSF:
1517
0
      return "TCSETSF";
1518
0
#endif
1519
0
#if defined(TCGETA)
1520
0
    case TCGETA:
1521
0
      return "TCGETA";
1522
0
#endif
1523
0
#if defined(TCSETA)
1524
0
    case TCSETA:
1525
0
      return "TCSETA";
1526
0
#endif
1527
0
#if defined(TCSETAW)
1528
0
    case TCSETAW:
1529
0
      return "TCSETAW";
1530
0
#endif
1531
0
#if defined(TCSETAF)
1532
0
    case TCSETAF:
1533
0
      return "TCSETAF";
1534
0
#endif
1535
0
#if defined(TCSBRK)
1536
0
    case TCSBRK:
1537
0
      return "TCSBRK";
1538
0
#endif
1539
0
#if defined(TCXONC)
1540
0
    case TCXONC:
1541
0
      return "TCXONC";
1542
0
#endif
1543
0
#if defined(TCFLSH)
1544
0
    case TCFLSH:
1545
0
      return "TCFLSH";
1546
0
#endif
1547
0
#if defined(TIOCEXCL)
1548
0
    case TIOCEXCL:
1549
0
      return "TIOCEXCL";
1550
0
#endif
1551
0
#if defined(TIOCNXCL)
1552
0
    case TIOCNXCL:
1553
0
      return "TIOCNXCL";
1554
0
#endif
1555
0
#if defined(TIOCSCTTY)
1556
0
    case TIOCSCTTY:
1557
0
      return "TIOCSCTTY";
1558
0
#endif
1559
0
#if defined(TIOCGPGRP)
1560
0
    case TIOCGPGRP:
1561
0
      return "TIOCGPGRP";
1562
0
#endif
1563
0
#if defined(TIOCSPGRP)
1564
0
    case TIOCSPGRP:
1565
0
      return "TIOCSPGRP";
1566
0
#endif
1567
0
#if defined(TIOCOUTQ)
1568
0
    case TIOCOUTQ:
1569
0
      return "TIOCOUTQ";
1570
0
#endif
1571
0
#if defined(TIOCSTI)
1572
0
    case TIOCSTI:
1573
0
      return "TIOCSTI";
1574
0
#endif
1575
0
#if defined(TIOCGWINSZ)
1576
0
    case TIOCGWINSZ:
1577
0
      return "TIOCGWINSZ";
1578
0
#endif
1579
0
#if defined(TIOCSWINSZ)
1580
0
    case TIOCSWINSZ:
1581
0
      return "TIOCSWINSZ";
1582
0
#endif
1583
0
#if defined(TIOCMGET)
1584
0
    case TIOCMGET:
1585
0
      return "TIOCMGET";
1586
0
#endif
1587
0
#if defined(TIOCMBIS)
1588
0
    case TIOCMBIS:
1589
0
      return "TIOCMBIS";
1590
0
#endif
1591
0
#if defined(TIOCMBIC)
1592
0
    case TIOCMBIC:
1593
0
      return "TIOCMBIC";
1594
0
#endif
1595
0
#if defined(TIOCMSET)
1596
0
    case TIOCMSET:
1597
0
      return "TIOCMSET";
1598
0
#endif
1599
0
#if defined(TIOCGSOFTCAR)
1600
0
    case TIOCGSOFTCAR:
1601
0
      return "TIOCGSOFTCAR";
1602
0
#endif
1603
0
#if defined(TIOCSSOFTCAR)
1604
0
    case TIOCSSOFTCAR:
1605
0
      return "TIOCSSOFTCAR";
1606
0
#endif
1607
0
#if defined(FIONREAD)
1608
0
    case FIONREAD:
1609
0
      return "FIONREAD/TIOCINQ";
1610
0
#endif
1611
0
#if defined(TIOCLINUX)
1612
0
    case TIOCLINUX:
1613
0
      return "TIOCLINUX";
1614
0
#endif
1615
0
#if defined(TIOCCONS)
1616
0
    case TIOCCONS:
1617
0
      return "TIOCCONS";
1618
0
#endif
1619
0
#if defined(TIOCGSERIAL)
1620
0
    case TIOCGSERIAL:
1621
0
      return "TIOCGSERIAL";
1622
0
#endif
1623
0
#if defined(TIOCSSERIAL)
1624
0
    case TIOCSSERIAL:
1625
0
      return "TIOCSSERIAL";
1626
0
#endif
1627
0
#if defined(TIOCPKT)
1628
0
    case TIOCPKT:
1629
0
      return "TIOCPKT";
1630
0
#endif
1631
0
#if defined(FIONBIO)
1632
0
    case FIONBIO:
1633
0
      return "FIONBIO";
1634
0
#endif
1635
0
#if defined(TIOCNOTTY)
1636
0
    case TIOCNOTTY:
1637
0
      return "TIOCNOTTY";
1638
0
#endif
1639
0
#if defined(TIOCSETD)
1640
0
    case TIOCSETD:
1641
0
      return "TIOCSETD";
1642
0
#endif
1643
0
#if defined(TIOCGETD)
1644
0
    case TIOCGETD:
1645
0
      return "TIOCGETD";
1646
0
#endif
1647
0
#if defined(TCSBRKP)
1648
0
    case TCSBRKP:
1649
0
      return "TCSBRKP";
1650
0
#endif
1651
0
#if defined(TIOCSBRK)
1652
0
    case TIOCSBRK:
1653
0
      return "TIOCSBRK";
1654
0
#endif
1655
0
#if defined(TIOCCBRK)
1656
0
    case TIOCCBRK:
1657
0
      return "TIOCCBRK";
1658
0
#endif
1659
0
#if defined(TIOCGSID)
1660
0
    case TIOCGSID:
1661
0
      return "TIOCGSID";
1662
0
#endif
1663
0
#if defined(TIOCGRS485)
1664
0
    case TIOCGRS485:
1665
0
      return "TIOCGRS485";
1666
0
#endif
1667
0
#if defined(TIOCSRS485)
1668
0
    case TIOCSRS485:
1669
0
      return "TIOCSRS485";
1670
0
#endif
1671
0
#if defined(TIOCSPTLCK)
1672
0
    case TIOCSPTLCK:
1673
0
      return "TIOCSPTLCK";
1674
0
#endif
1675
0
#if defined(TCGETX)
1676
0
    case TCGETX:
1677
0
      return "TCGETX";
1678
0
#endif
1679
0
#if defined(TCSETX)
1680
0
    case TCSETX:
1681
0
      return "TCSETX";
1682
0
#endif
1683
0
#if defined(TCSETXF)
1684
0
    case TCSETXF:
1685
0
      return "TCSETXF";
1686
0
#endif
1687
0
#if defined(TCSETXW)
1688
0
    case TCSETXW:
1689
0
      return "TCSETXW";
1690
0
#endif
1691
0
#if defined(TIOCSIG)
1692
0
    case TIOCSIG:
1693
0
      return "TIOCSIG";
1694
0
#endif
1695
0
#if defined(TIOCVHANGUP)
1696
0
    case TIOCVHANGUP:
1697
0
      return "TIOCVHANGUP";
1698
0
#endif
1699
0
#if defined(TIOCGPTPEER)
1700
0
    case TIOCGPTPEER:
1701
0
      return "TIOCGPTPEER";
1702
0
#endif
1703
0
#if defined(FIONCLEX)
1704
0
    case FIONCLEX:
1705
0
      return "FIONCLEX";
1706
0
#endif
1707
0
#if defined(FIOCLEX)
1708
0
    case FIOCLEX:
1709
0
      return "FIOCLEX";
1710
0
#endif
1711
0
#if defined(FIOASYNC)
1712
0
    case FIOASYNC:
1713
0
      return "FIOASYNC";
1714
0
#endif
1715
0
#if defined(TIOCSERCONFIG)
1716
0
    case TIOCSERCONFIG:
1717
0
      return "TIOCSERCONFIG";
1718
0
#endif
1719
0
#if defined(TIOCSERGWILD)
1720
0
    case TIOCSERGWILD:
1721
0
      return "TIOCSERGWILD";
1722
0
#endif
1723
0
#if defined(TIOCSERSWILD)
1724
0
    case TIOCSERSWILD:
1725
0
      return "TIOCSERSWILD";
1726
0
#endif
1727
0
#if defined(TIOCGLCKTRMIOS)
1728
0
    case TIOCGLCKTRMIOS:
1729
0
      return "TIOCGLCKTRMIOS";
1730
0
#endif
1731
0
#if defined(TIOCSLCKTRMIOS)
1732
0
    case TIOCSLCKTRMIOS:
1733
0
      return "TIOCSLCKTRMIOS";
1734
0
#endif
1735
0
#if defined(TIOCSERGSTRUCT)
1736
0
    case TIOCSERGSTRUCT:
1737
0
      return "TIOCSERGSTRUCT";
1738
0
#endif
1739
0
#if defined(TIOCSERGETLSR)
1740
0
    case TIOCSERGETLSR:
1741
0
      return "TIOCSERGETLSR";
1742
0
#endif
1743
0
#if defined(TIOCSERGETMULTI)
1744
0
    case TIOCSERGETMULTI:
1745
0
      return "TIOCSERGETMULTI";
1746
0
#endif
1747
0
#if defined(TIOCSERSETMULTI)
1748
0
    case TIOCSERSETMULTI:
1749
0
      return "TIOCSERSETMULTI";
1750
0
#endif
1751
0
#if defined(TIOCMIWAIT)
1752
0
    case TIOCMIWAIT:
1753
0
      return "TIOCMIWAIT";
1754
0
#endif
1755
0
#if defined(TIOCGICOUNT)
1756
0
    case TIOCGICOUNT:
1757
0
      return "TIOCGICOUNT";
1758
0
#endif
1759
0
#if defined(FIOQSIZE)
1760
0
    case FIOQSIZE:
1761
0
      return "FIOQSIZE";
1762
0
#endif
1763
0
#if defined(TIOCPKT_DATA)
1764
0
    case TIOCPKT_DATA:
1765
0
      return "TIOCPKT_DATA";
1766
0
#endif
1767
0
#if defined(TIOCPKT_FLUSHWRITE)
1768
0
    case TIOCPKT_FLUSHWRITE:
1769
0
      return "TIOCPKT_FLUSHWRITE";
1770
0
#endif
1771
0
#if defined(TIOCPKT_STOP)
1772
0
    case TIOCPKT_STOP:
1773
0
      return "TIOCPKT_STOP";
1774
0
#endif
1775
0
#if defined(TIOCPKT_START)
1776
0
    case TIOCPKT_START:
1777
0
      return "TIOCPKT_START";
1778
0
#endif
1779
0
#if defined(TIOCPKT_NOSTOP)
1780
0
    case TIOCPKT_NOSTOP:
1781
0
      return "TIOCPKT_NOSTOP";
1782
0
#endif
1783
0
#if defined(TIOCPKT_DOSTOP)
1784
0
    case TIOCPKT_DOSTOP:
1785
0
      return "TIOCPKT_DOSTOP";
1786
0
#endif
1787
0
#if defined(TIOCPKT_IOCTL)
1788
0
    case TIOCPKT_IOCTL:
1789
0
      return "TIOCPKT_IOCTL";
1790
0
#endif
1791
0
#endif
1792
0
    default:
1793
0
      return "UNKNOWN";
1794
0
  }
1795
0
}
1796
1797
static BOOL CommStatusErrorEx(WINPR_COMM* pComm, unsigned long int ctl, const char* file,
1798
                              const char* fkt, size_t line)
1799
0
{
1800
0
  WINPR_ASSERT(pComm);
1801
0
  BOOL rc = pComm->permissive ? TRUE : FALSE;
1802
0
  const DWORD level = rc ? WLOG_DEBUG : WLOG_WARN;
1803
0
  char ebuffer[256] = { 0 };
1804
0
  const char* str = CommIoCtlToStr(ctl);
1805
1806
0
  if (CommInitialized())
1807
0
  {
1808
0
    if (WLog_IsLevelActive(sLog, level))
1809
0
    {
1810
0
      WLog_PrintTextMessage(sLog, level, line, file, fkt,
1811
0
                            "%s [0x%08lx] ioctl failed, errno=[%d] %s.", str, ctl, errno,
1812
0
                            winpr_strerror(errno, ebuffer, sizeof(ebuffer)));
1813
0
    }
1814
0
  }
1815
1816
0
  if (!rc)
1817
0
    SetLastError(ERROR_IO_DEVICE);
1818
1819
0
  return rc;
1820
0
}
1821
1822
BOOL CommIoCtl_int(WINPR_COMM* pComm, unsigned long int ctl, void* data, const char* file,
1823
                   const char* fkt, size_t line)
1824
0
{
1825
0
  if (ioctl(pComm->fd, ctl, data) < 0)
1826
0
  {
1827
0
    if (!CommStatusErrorEx(pComm, ctl, file, fkt, line))
1828
0
      return FALSE;
1829
0
  }
1830
0
  return TRUE;
1831
0
}
1832
1833
BOOL CommUpdateIOCount(WINPR_ATTR_UNUSED HANDLE handle, WINPR_ATTR_UNUSED BOOL checkSupportStatus)
1834
0
{
1835
0
  WINPR_COMM* pComm = (WINPR_COMM*)handle;
1836
0
  WINPR_ASSERT(pComm);
1837
1838
0
#if defined(WINPR_HAVE_COMM_COUNTERS)
1839
0
  ZeroMemory(&(pComm->counters), sizeof(struct serial_icounter_struct));
1840
0
  if (pComm->TIOCGICOUNTSupported || checkSupportStatus)
1841
0
  {
1842
0
    const int rc = ioctl(pComm->fd, TIOCGICOUNT, &(pComm->counters));
1843
0
    if (checkSupportStatus)
1844
0
      pComm->TIOCGICOUNTSupported = rc >= 0;
1845
0
    else if (rc < 0)
1846
0
    {
1847
0
      if (!CommStatusErrorEx(pComm, TIOCGICOUNT, __FILE__, __func__, __LINE__))
1848
0
        return FALSE;
1849
0
    }
1850
0
  }
1851
0
#endif
1852
0
  return TRUE;
1853
0
}
1854
1855
static const char* CommSerialEvFlagString(ULONG flag)
1856
0
{
1857
0
  switch (flag)
1858
0
  {
1859
0
    case SERIAL_EV_RXCHAR:
1860
0
      return "SERIAL_EV_RXCHAR";
1861
0
    case SERIAL_EV_RXFLAG:
1862
0
      return "SERIAL_EV_RXFLAG";
1863
0
    case SERIAL_EV_TXEMPTY:
1864
0
      return "SERIAL_EV_TXEMPTY";
1865
0
    case SERIAL_EV_CTS:
1866
0
      return "SERIAL_EV_CTS ";
1867
0
    case SERIAL_EV_DSR:
1868
0
      return "SERIAL_EV_DSR ";
1869
0
    case SERIAL_EV_RLSD:
1870
0
      return "SERIAL_EV_RLSD";
1871
0
    case SERIAL_EV_BREAK:
1872
0
      return "SERIAL_EV_BREAK";
1873
0
    case SERIAL_EV_ERR:
1874
0
      return "SERIAL_EV_ERR ";
1875
0
    case SERIAL_EV_RING:
1876
0
      return "SERIAL_EV_RING";
1877
0
    case SERIAL_EV_PERR:
1878
0
      return "SERIAL_EV_PERR";
1879
0
    case SERIAL_EV_RX80FULL:
1880
0
      return "SERIAL_EV_RX80FULL";
1881
0
    case SERIAL_EV_EVENT1:
1882
0
      return "SERIAL_EV_EVENT1";
1883
0
    case SERIAL_EV_EVENT2:
1884
0
      return "SERIAL_EV_EVENT2";
1885
0
    case SERIAL_EV_WINPR_WAITING:
1886
0
      return "SERIAL_EV_WINPR_WAITING";
1887
0
    case SERIAL_EV_WINPR_STOP:
1888
0
      return "SERIAL_EV_WINPR_STOP";
1889
0
    default:
1890
0
      return "SERIAL_EV_UNKNOWN";
1891
0
  }
1892
0
}
1893
1894
const char* CommSerialEvString(ULONG status, char* buffer, size_t size)
1895
0
{
1896
0
  const ULONG flags[] = { SERIAL_EV_RXCHAR, SERIAL_EV_RXFLAG,        SERIAL_EV_TXEMPTY,
1897
0
                        SERIAL_EV_CTS,    SERIAL_EV_DSR,           SERIAL_EV_RLSD,
1898
0
                        SERIAL_EV_BREAK,  SERIAL_EV_ERR,           SERIAL_EV_RING,
1899
0
                        SERIAL_EV_PERR,   SERIAL_EV_RX80FULL,      SERIAL_EV_EVENT1,
1900
0
                        SERIAL_EV_EVENT2, SERIAL_EV_WINPR_WAITING, SERIAL_EV_WINPR_STOP };
1901
1902
0
  winpr_str_append("{", buffer, size, "");
1903
1904
0
  const char* sep = "";
1905
0
  for (size_t x = 0; x < ARRAYSIZE(flags); x++)
1906
0
  {
1907
0
    const ULONG flag = flags[x];
1908
0
    if (status & flag)
1909
0
    {
1910
0
      winpr_str_append(CommSerialEvFlagString(flag), buffer, size, sep);
1911
0
      sep = "|";
1912
0
    }
1913
0
  }
1914
1915
0
  char number[32] = { 0 };
1916
0
  (void)_snprintf(number, sizeof(number), "}[0x%08" PRIx32 "]", status);
1917
0
  winpr_str_append(number, buffer, size, "");
1918
0
  return buffer;
1919
0
}