]> sigrok.org Git - libserialport.git/blame - serialport.c
Make libudev optional.
[libserialport.git] / serialport.c
CommitLineData
74510d4b
ML
1/*
2 * This file is part of the libserialport project.
3 *
4 * Copyright (C) 2010-2012 Bert Vermeulen <bert@biot.com>
5 * Copyright (C) 2010-2012 Uwe Hermann <uwe@hermann-uwe.de>
6 * Copyright (C) 2013 Martin Ling <martin-libserialport@earth.li>
31b3a8f5 7 * Copyright (C) 2013 Matthias Heidbrink <m-sigrok@heidbrink.biz>
74510d4b
ML
8 *
9 * This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU Lesser General Public License as
11 * published by the Free Software Foundation, either version 3 of the
12 * License, or (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU Lesser General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 */
22
23#include <string.h>
24#include <sys/types.h>
25#include <sys/stat.h>
26#include <fcntl.h>
27#include <unistd.h>
3b63f34d
ML
28#include <stdlib.h>
29#include <errno.h>
863b35e6
ML
30#include <stdio.h>
31#include <stdarg.h>
74510d4b
ML
32#ifdef _WIN32
33#include <windows.h>
3b63f34d 34#include <tchar.h>
767c5ba8 35#include <stdio.h>
74510d4b 36#else
8fbf876d 37#include <limits.h>
74510d4b
ML
38#include <termios.h>
39#include <sys/ioctl.h>
e3dcf906
ML
40#include <sys/time.h>
41#include <limits.h>
74510d4b 42#endif
3b63f34d 43#ifdef __APPLE__
1ebf4347
ML
44#include <IOKit/IOKitLib.h>
45#include <IOKit/serial/IOSerialKeys.h>
31b3a8f5 46#include <IOKit/serial/ioss.h>
1ebf4347 47#include <sys/syslimits.h>
3b63f34d
ML
48#endif
49#ifdef __linux__
397d89de 50#ifdef HAVE_LIBUDEV
3b63f34d 51#include "libudev.h"
397d89de 52#endif
4b97c9fc 53#include "linux/serial.h"
7a6d2196 54#include "linux_termios.h"
6c8716e9
UH
55
56/* TCGETX/TCSETX is not available everywhere. */
40978c2b 57#if defined(TCGETX) && defined(TCSETX) && defined(HAVE_TERMIOX)
68ec29db 58#define USE_TERMIOX
40978c2b 59#endif
3b63f34d 60#endif
74510d4b 61
6c8716e9
UH
62/* TIOCINQ/TIOCOUTQ is not available everywhere. */
63#if !defined(TIOCINQ) && defined(FIONREAD)
64#define TIOCINQ FIONREAD
65#endif
66#if !defined(TIOCOUTQ) && defined(FIONWRITE)
67#define TIOCOUTQ FIONWRITE
68#endif
69
71c8a9b9
UH
70#ifndef _WIN32
71#include "linux_termios.h"
72#endif
73
f6a1fb65 74#include "libserialport.h"
74510d4b 75
1c5aae9d
ML
76struct sp_port {
77 char *name;
78#ifdef _WIN32
79 HANDLE hdl;
e3dcf906 80 COMMTIMEOUTS timeouts;
a3cb91f5 81 OVERLAPPED write_ovl;
e3dcf906 82 OVERLAPPED read_ovl;
0765af56 83 BYTE pending_byte;
a3cb91f5 84 BOOL writing;
1c5aae9d
ML
85#else
86 int fd;
87#endif
88};
89
9b1502ef
ML
90struct sp_port_config {
91 int baudrate;
92 int bits;
93 enum sp_parity parity;
94 int stopbits;
95 enum sp_rts rts;
96 enum sp_cts cts;
97 enum sp_dtr dtr;
98 enum sp_dsr dsr;
99 enum sp_xonxoff xon_xoff;
100};
101
8f189c4c 102struct port_data {
8094e4a0
ML
103#ifdef _WIN32
104 DCB dcb;
105#else
106 struct termios term;
824dcb45 107 int controlbits;
68ec29db 108 int termiox_supported;
40978c2b
ML
109 int flow;
110#endif
8094e4a0
ML
111};
112
da2748bf
ML
113/* Standard baud rates. */
114#ifdef _WIN32
115#define BAUD_TYPE DWORD
116#define BAUD(n) {CBR_##n, n}
117#else
118#define BAUD_TYPE speed_t
119#define BAUD(n) {B##n, n}
120#endif
121
122struct std_baudrate {
123 BAUD_TYPE index;
124 int value;
125};
126
127const struct std_baudrate std_baudrates[] = {
128#ifdef _WIN32
129 /*
130 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
131 * have documented CBR_* macros.
132 */
133 BAUD(110), BAUD(300), BAUD(600), BAUD(1200), BAUD(2400), BAUD(4800),
134 BAUD(9600), BAUD(14400), BAUD(19200), BAUD(38400), BAUD(57600),
eac329d2 135 BAUD(115200), BAUD(128000), BAUD(256000),
da2748bf 136#else
eac329d2
UH
137 BAUD(50), BAUD(75), BAUD(110), BAUD(134), BAUD(150), BAUD(200),
138 BAUD(300), BAUD(600), BAUD(1200), BAUD(1800), BAUD(2400), BAUD(4800),
139 BAUD(9600), BAUD(19200), BAUD(38400), BAUD(57600), BAUD(115200),
140 BAUD(230400),
da2748bf 141#if !defined(__APPLE__) && !defined(__OpenBSD__)
eac329d2 142 BAUD(460800),
da2748bf
ML
143#endif
144#endif
145};
146
863b35e6
ML
147void (*sp_debug_handler)(const char *format, ...) = sp_default_debug_handler;
148
da2748bf
ML
149#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
150#define NUM_STD_BAUDRATES ARRAY_SIZE(std_baudrates)
151
92f756f8
ML
152/* Debug output macros. */
153#define DEBUG(fmt, ...) do { if (sp_debug_handler) sp_debug_handler(fmt ".\n", ##__VA_ARGS__); } while (0)
154#define DEBUG_ERROR(err, msg) DEBUG("%s returning " #err ": " msg, __func__)
155#define DEBUG_FAIL(msg) do { \
156 char *errmsg = sp_last_error_message(); \
157 DEBUG("%s returning SP_ERR_FAIL: " msg ": %s", __func__, errmsg); \
158 sp_free_error_message(errmsg); \
159} while (0);
160#define RETURN() do { DEBUG("%s returning", __func__); return; } while(0)
161#define RETURN_CODE(x) do { DEBUG("%s returning " #x, __func__); return x; } while (0)
162#define RETURN_CODEVAL(x) do { \
163 switch (x) { \
164 case SP_OK: RETURN_CODE(SP_OK); \
165 case SP_ERR_ARG: RETURN_CODE(SP_ERR_ARG); \
166 case SP_ERR_FAIL: RETURN_CODE(SP_ERR_FAIL); \
167 case SP_ERR_MEM: RETURN_CODE(SP_ERR_MEM); \
168 case SP_ERR_SUPP: RETURN_CODE(SP_ERR_SUPP); \
169 } \
170} while (0)
171#define RETURN_OK() RETURN_CODE(SP_OK);
172#define RETURN_ERROR(err, msg) do { DEBUG_ERROR(err, msg); return err; } while (0)
173#define RETURN_FAIL(msg) do { DEBUG_FAIL(msg); return SP_ERR_FAIL; } while (0)
174#define RETURN_VALUE(fmt, x) do { DEBUG("%s returning " fmt, __func__, x); return x; } while (0)
175#define SET_ERROR(val, err, msg) do { DEBUG_ERROR(err, msg); val = err; } while (0)
aac4d7f2 176#define SET_FAIL(val, msg) do { DEBUG_FAIL(msg); val = SP_ERR_FAIL; } while (0)
92f756f8
ML
177#define TRACE(fmt, ...) DEBUG("%s(" fmt ") called", __func__, ##__VA_ARGS__)
178
64690702
ML
179#define TRY(x) do { int ret = x; if (ret != SP_OK) RETURN_CODEVAL(ret); } while (0)
180
348e23cc 181/* Helper functions. */
348e23cc 182static struct sp_port **list_append(struct sp_port **list, const char *portname);
eb6ed20f
ML
183static enum sp_return get_config(struct sp_port *port, struct port_data *data,
184 struct sp_port_config *config);
185static enum sp_return set_config(struct sp_port *port, struct port_data *data,
186 const struct sp_port_config *config);
80186526 187
eb6ed20f 188enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
d54e9004
ML
189{
190 struct sp_port *port;
5919c913 191 int len;
d54e9004 192
c33efc48
ML
193 TRACE("%s, %p", portname, port_ptr);
194
32b5ac05 195 if (!port_ptr)
c33efc48 196 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
32b5ac05 197
77f262c4
ML
198 *port_ptr = NULL;
199
d4babed2 200 if (!portname)
c33efc48 201 RETURN_ERROR(SP_ERR_ARG, "Null port name");
d4babed2 202
ea667be7
ML
203 DEBUG("Building structure for port %s", portname);
204
d54e9004 205 if (!(port = malloc(sizeof(struct sp_port))))
c33efc48 206 RETURN_ERROR(SP_ERR_MEM, "Port structure malloc failed");
d54e9004 207
5919c913
ML
208 len = strlen(portname) + 1;
209
eac329d2 210 if (!(port->name = malloc(len))) {
d54e9004 211 free(port);
c33efc48 212 RETURN_ERROR(SP_ERR_MEM, "Port name malloc failed");
d54e9004
ML
213 }
214
215 memcpy(port->name, portname, len);
216
8f471c66
ML
217#ifdef _WIN32
218 port->hdl = INVALID_HANDLE_VALUE;
219#else
220 port->fd = -1;
221#endif
222
77f262c4
ML
223 *port_ptr = port;
224
c33efc48 225 RETURN_OK();
d54e9004
ML
226}
227
1c5aae9d
ML
228char *sp_get_port_name(const struct sp_port *port)
229{
230 TRACE("%p", port);
231
232 if (!port)
233 return NULL;
234
235 RETURN_VALUE("%s", port->name);
236}
237
3c126654
ML
238enum sp_return sp_get_port_handle(const struct sp_port *port, void *result_ptr)
239{
00d8c56d 240 TRACE("%p, %p", port, result_ptr);
3c126654
ML
241
242 if (!port)
243 RETURN_ERROR(SP_ERR_ARG, "Null port");
244
245#ifdef _WIN32
246 HANDLE *handle_ptr = result_ptr;
247 *handle_ptr = port->hdl;
248#else
249 int *fd_ptr = result_ptr;
250 *fd_ptr = port->fd;
251#endif
252
253 RETURN_OK();
254}
255
eb6ed20f 256enum sp_return sp_copy_port(const struct sp_port *port, struct sp_port **copy_ptr)
32b5ac05 257{
c33efc48
ML
258 TRACE("%p, %p", port, copy_ptr);
259
32b5ac05 260 if (!copy_ptr)
c33efc48 261 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
32b5ac05
ML
262
263 *copy_ptr = NULL;
264
c33efc48
ML
265 if (!port)
266 RETURN_ERROR(SP_ERR_ARG, "Null port");
267
268 if (!port->name)
269 RETURN_ERROR(SP_ERR_ARG, "Null port name");
32b5ac05 270
ea667be7
ML
271 DEBUG("Copying port structure");
272
c33efc48 273 RETURN_VALUE("%p", sp_get_port_by_name(port->name, copy_ptr));
32b5ac05
ML
274}
275
e3b2f7a4
ML
276void sp_free_port(struct sp_port *port)
277{
c33efc48
ML
278 TRACE("%p", port);
279
00d8c56d 280 if (!port) {
c33efc48
ML
281 DEBUG("Null port");
282 RETURN();
283 }
e3b2f7a4 284
ea667be7
ML
285 DEBUG("Freeing port structure");
286
e3b2f7a4
ML
287 if (port->name)
288 free(port->name);
289
290 free(port);
c33efc48
ML
291
292 RETURN();
e3b2f7a4
ML
293}
294
348e23cc 295static struct sp_port **list_append(struct sp_port **list, const char *portname)
3b63f34d
ML
296{
297 void *tmp;
298 unsigned int count;
f92f1f0c 299
3b63f34d 300 for (count = 0; list[count]; count++);
d54e9004 301 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
3b63f34d
ML
302 goto fail;
303 list = tmp;
77f262c4 304 if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
3b63f34d 305 goto fail;
db2794ce 306 list[count + 1] = NULL;
3b63f34d 307 return list;
f92f1f0c 308
3b63f34d
ML
309fail:
310 sp_free_port_list(list);
311 return NULL;
312}
313
eb6ed20f 314enum sp_return sp_list_ports(struct sp_port ***list_ptr)
3b63f34d 315{
d54e9004 316 struct sp_port **list;
6b93ede4 317 int ret = SP_ERR_SUPP;
24c1a4bb 318
c33efc48
ML
319 TRACE("%p", list_ptr);
320
dec10e31
ML
321 if (!list_ptr)
322 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
323
ea667be7
ML
324 DEBUG("Enumerating ports");
325
d54e9004 326 if (!(list = malloc(sizeof(struct sp_port **))))
c33efc48 327 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
24c1a4bb
ML
328
329 list[0] = NULL;
3b63f34d
ML
330
331#ifdef _WIN32
332 HKEY key;
bdfb5b8c
ML
333 TCHAR *value, *data;
334 DWORD max_value_len, max_data_size, max_data_len;
335 DWORD value_len, data_size, data_len;
3b63f34d 336 DWORD type, index = 0;
8b532d9c
ML
337 char *name;
338 int name_len;
3b63f34d 339
6b93ede4
ML
340 ret = SP_OK;
341
ea667be7 342 DEBUG("Opening registry key");
3b63f34d 343 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
eac329d2 344 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS) {
c33efc48 345 SET_FAIL(ret, "RegOpenKeyEx() failed");
77f262c4
ML
346 goto out_done;
347 }
ea667be7 348 DEBUG("Querying registry key value and data sizes");
3b63f34d 349 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
eac329d2 350 &max_value_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS) {
c33efc48 351 SET_FAIL(ret, "RegQueryInfoKey() failed");
3b63f34d 352 goto out_close;
77f262c4 353 }
3b63f34d 354 max_data_len = max_data_size / sizeof(TCHAR);
eac329d2 355 if (!(value = malloc((max_value_len + 1) * sizeof(TCHAR)))) {
c33efc48 356 SET_ERROR(ret, SP_ERR_MEM, "registry value malloc failed");
3b63f34d 357 goto out_close;
77f262c4 358 }
eac329d2 359 if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR)))) {
c33efc48 360 SET_ERROR(ret, SP_ERR_MEM, "registry data malloc failed");
bdfb5b8c 361 goto out_free_value;
77f262c4 362 }
ea667be7 363 DEBUG("Iterating over values");
3b63f34d 364 while (
d9573bad 365 value_len = max_value_len + 1,
3b63f34d 366 data_size = max_data_size,
bdfb5b8c 367 RegEnumValue(key, index, value, &value_len,
3b63f34d
ML
368 NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
369 {
370 data_len = data_size / sizeof(TCHAR);
371 data[data_len] = '\0';
8b532d9c
ML
372#ifdef UNICODE
373 name_len = WideCharToMultiByte(CP_ACP, 0, data, -1, NULL, 0, NULL, NULL)
374#else
375 name_len = data_len + 1;
376#endif
eac329d2 377 if (!(name = malloc(name_len))) {
c33efc48 378 SET_ERROR(ret, SP_ERR_MEM, "registry port name malloc failed");
8b532d9c 379 goto out;
77f262c4 380 }
8b532d9c
ML
381#ifdef UNICODE
382 WideCharToMultiByte(CP_ACP, 0, data, -1, name, name_len, NULL, NULL);
383#else
384 strcpy(name, data);
385#endif
c33efc48
ML
386 if (type == REG_SZ) {
387 DEBUG("Found port %s", name);
388 if (!(list = list_append(list, name))) {
389 SET_ERROR(ret, SP_ERR_MEM, "list append failed");
390 goto out;
391 }
77f262c4 392 }
3b63f34d
ML
393 index++;
394 }
395out:
396 free(data);
bdfb5b8c
ML
397out_free_value:
398 free(value);
3b63f34d
ML
399out_close:
400 RegCloseKey(key);
77f262c4 401out_done:
3b63f34d
ML
402#endif
403#ifdef __APPLE__
404 mach_port_t master;
405 CFMutableDictionaryRef classes;
406 io_iterator_t iter;
407 char *path;
408 io_object_t port;
409 CFTypeRef cf_path;
410 Boolean result;
411
6b93ede4
ML
412 ret = SP_OK;
413
ea667be7 414 DEBUG("Getting IOKit master port");
eac329d2 415 if (IOMasterPort(MACH_PORT_NULL, &master) != KERN_SUCCESS) {
c33efc48 416 SET_FAIL(ret, "IOMasterPort() failed");
77f262c4
ML
417 goto out_done;
418 }
3b63f34d 419
ea667be7 420 DEBUG("Creating matching dictionary");
eac329d2 421 if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue))) {
c33efc48 422 SET_FAIL(ret, "IOServiceMatching() failed");
77f262c4
ML
423 goto out_done;
424 }
3b63f34d
ML
425
426 CFDictionarySetValue(classes,
427 CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
428
ea667be7 429 DEBUG("Getting matching services");
eac329d2 430 if (IOServiceGetMatchingServices(master, classes, &iter) != KERN_SUCCESS) {
c33efc48 431 SET_FAIL(ret, "IOServiceGetMatchingServices() failed");
77f262c4
ML
432 goto out_done;
433 }
3b63f34d 434
eac329d2 435 if (!(path = malloc(PATH_MAX))) {
c33efc48 436 SET_ERROR(ret, SP_ERR_MEM, "device path malloc failed");
3b63f34d 437 goto out_release;
77f262c4 438 }
3b63f34d 439
ea667be7 440 DEBUG("Iterating over results");
1ebf4347 441 while ((port = IOIteratorNext(iter))) {
3b63f34d
ML
442 cf_path = IORegistryEntryCreateCFProperty(port,
443 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
444 if (cf_path) {
445 result = CFStringGetCString(cf_path,
446 path, PATH_MAX, kCFStringEncodingASCII);
447 CFRelease(cf_path);
c33efc48
ML
448 if (result) {
449 DEBUG("Found port %s", path);
450 if (!(list = list_append(list, path))) {
451 SET_ERROR(ret, SP_ERR_MEM, "list append failed");
452 IOObjectRelease(port);
453 goto out;
454 }
77f262c4 455 }
3b63f34d
ML
456 }
457 IOObjectRelease(port);
458 }
3b63f34d
ML
459out:
460 free(path);
461out_release:
462 IOObjectRelease(iter);
77f262c4 463out_done:
3b63f34d 464#endif
397d89de 465#if defined(__linux__) && defined(HAVE_LIBUDEV)
3b63f34d
ML
466 struct udev *ud;
467 struct udev_enumerate *ud_enumerate;
468 struct udev_list_entry *ud_list;
469 struct udev_list_entry *ud_entry;
470 const char *path;
08fe0bdb 471 struct udev_device *ud_dev, *ud_parent;
3b63f34d 472 const char *name;
4b97c9fc
ML
473 const char *driver;
474 int fd, ioctl_result;
475 struct serial_struct serial_info;
3b63f34d 476
6b93ede4
ML
477 ret = SP_OK;
478
ea667be7 479 DEBUG("Enumerating tty devices");
3b63f34d
ML
480 ud = udev_new();
481 ud_enumerate = udev_enumerate_new(ud);
482 udev_enumerate_add_match_subsystem(ud_enumerate, "tty");
483 udev_enumerate_scan_devices(ud_enumerate);
484 ud_list = udev_enumerate_get_list_entry(ud_enumerate);
ea667be7 485 DEBUG("Iterating over results");
eac329d2 486 udev_list_entry_foreach(ud_entry, ud_list) {
3b63f34d 487 path = udev_list_entry_get_name(ud_entry);
ea667be7 488 DEBUG("Found device %s", path);
3b63f34d 489 ud_dev = udev_device_new_from_syspath(ud, path);
08fe0bdb
ML
490 /* If there is no parent device, this is a virtual tty. */
491 ud_parent = udev_device_get_parent(ud_dev);
eac329d2 492 if (ud_parent == NULL) {
ea667be7 493 DEBUG("No parent device, assuming virtual tty");
08fe0bdb
ML
494 udev_device_unref(ud_dev);
495 continue;
496 }
3b63f34d 497 name = udev_device_get_devnode(ud_dev);
4b97c9fc
ML
498 /* The serial8250 driver has a hardcoded number of ports.
499 * The only way to tell which actually exist on a given system
500 * is to try to open them and make an ioctl call. */
501 driver = udev_device_get_driver(ud_parent);
eac329d2 502 if (driver && !strcmp(driver, "serial8250")) {
ea667be7
ML
503 DEBUG("serial8250 device, attempting to open");
504 if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY)) < 0) {
505 DEBUG("open failed, skipping");
4b97c9fc 506 goto skip;
ea667be7 507 }
4b97c9fc
ML
508 ioctl_result = ioctl(fd, TIOCGSERIAL, &serial_info);
509 close(fd);
ea667be7
ML
510 if (ioctl_result != 0) {
511 DEBUG("ioctl failed, skipping");
4b97c9fc 512 goto skip;
ea667be7
ML
513 }
514 if (serial_info.type == PORT_UNKNOWN) {
515 DEBUG("port type is unknown, skipping");
4b97c9fc 516 goto skip;
ea667be7 517 }
4b97c9fc 518 }
c33efc48 519 DEBUG("Found port %s", name);
348e23cc 520 list = list_append(list, name);
4b97c9fc 521skip:
3b63f34d 522 udev_device_unref(ud_dev);
eac329d2 523 if (!list) {
c33efc48 524 SET_ERROR(ret, SP_ERR_MEM, "list append failed");
3b63f34d 525 goto out;
77f262c4 526 }
3b63f34d
ML
527 }
528out:
529 udev_enumerate_unref(ud_enumerate);
530 udev_unref(ud);
3b63f34d 531#endif
77f262c4 532
6b93ede4
ML
533 switch (ret) {
534 case SP_OK:
77f262c4 535 *list_ptr = list;
c33efc48 536 RETURN_OK();
6b93ede4
ML
537 case SP_ERR_SUPP:
538 DEBUG_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform.");
539 default:
77f262c4
ML
540 if (list)
541 sp_free_port_list(list);
77f262c4 542 *list_ptr = NULL;
c33efc48 543 return ret;
77f262c4 544 }
3b63f34d
ML
545}
546
d54e9004 547void sp_free_port_list(struct sp_port **list)
3b63f34d
ML
548{
549 unsigned int i;
f92f1f0c 550
c33efc48
ML
551 TRACE("%p", list);
552
dec10e31
ML
553 if (!list) {
554 DEBUG("Null list");
555 RETURN();
556 }
557
ea667be7
ML
558 DEBUG("Freeing port list");
559
3b63f34d 560 for (i = 0; list[i]; i++)
e3b2f7a4 561 sp_free_port(list[i]);
3b63f34d 562 free(list);
c33efc48
ML
563
564 RETURN();
3b63f34d
ML
565}
566
c33efc48
ML
567#define CHECK_PORT() do { \
568 if (port == NULL) \
569 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
dec10e31
ML
570 if (port->name == NULL) \
571 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
572} while (0)
573#ifdef _WIN32
574#define CHECK_PORT_HANDLE() do { \
c33efc48
ML
575 if (port->hdl == INVALID_HANDLE_VALUE) \
576 RETURN_ERROR(SP_ERR_ARG, "Invalid port handle"); \
dec10e31 577} while (0)
74510d4b 578#else
dec10e31 579#define CHECK_PORT_HANDLE() do { \
c33efc48
ML
580 if (port->fd < 0) \
581 RETURN_ERROR(SP_ERR_ARG, "Invalid port fd"); \
dec10e31 582} while (0)
74510d4b 583#endif
dec10e31
ML
584#define CHECK_OPEN_PORT() do { \
585 CHECK_PORT(); \
586 CHECK_PORT_HANDLE(); \
587} while (0)
74510d4b 588
eb6ed20f 589enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
74510d4b 590{
bccc7c9f
ML
591 struct port_data data;
592 struct sp_port_config config;
593 enum sp_return ret;
594
00d8c56d 595 TRACE("%p, 0x%x", port, flags);
c33efc48 596
dec10e31
ML
597 CHECK_PORT();
598
e3dcf906 599 if (flags > (SP_MODE_READ | SP_MODE_WRITE))
dec10e31 600 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
74510d4b 601
ea667be7
ML
602 DEBUG("Opening port %s", port->name);
603
74510d4b
ML
604#ifdef _WIN32
605 DWORD desired_access = 0, flags_and_attributes = 0;
99945a1f
ML
606 char *escaped_port_name;
607
608 /* Prefix port name with '\\.\' to work with ports above COM9. */
609 if (!(escaped_port_name = malloc(strlen(port->name + 5))))
c33efc48 610 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
99945a1f
ML
611 sprintf(escaped_port_name, "\\\\.\\%s", port->name);
612
74510d4b 613 /* Map 'flags' to the OS-specific settings. */
e3dcf906 614 flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
a036341b
ML
615 if (flags & SP_MODE_READ)
616 desired_access |= GENERIC_READ;
617 if (flags & SP_MODE_WRITE)
74510d4b 618 desired_access |= GENERIC_WRITE;
74510d4b 619
99945a1f 620 port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
74510d4b 621 OPEN_EXISTING, flags_and_attributes, 0);
99945a1f
ML
622
623 free(escaped_port_name);
624
74510d4b 625 if (port->hdl == INVALID_HANDLE_VALUE)
e3dcf906
ML
626 RETURN_FAIL("port CreateFile() failed");
627
628 /* All timeouts initially disabled. */
629 port->timeouts.ReadIntervalTimeout = 0;
630 port->timeouts.ReadTotalTimeoutMultiplier = 0;
631 port->timeouts.ReadTotalTimeoutConstant = 0;
632 port->timeouts.WriteTotalTimeoutMultiplier = 0;
633 port->timeouts.WriteTotalTimeoutConstant = 0;
a3cb91f5 634
e3dcf906 635 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
a3cb91f5
ML
636 sp_close(port);
637 RETURN_FAIL("SetCommTimeouts() failed");
638 }
e3dcf906
ML
639
640 /* Prepare OVERLAPPED structures. */
641 memset(&port->read_ovl, 0, sizeof(port->read_ovl));
642 memset(&port->write_ovl, 0, sizeof(port->write_ovl));
643 port->read_ovl.hEvent = INVALID_HANDLE_VALUE;
644 port->write_ovl.hEvent = INVALID_HANDLE_VALUE;
645 if ((port->read_ovl.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL)) == INVALID_HANDLE_VALUE) {
646 sp_close(port);
647 RETURN_FAIL("read event CreateEvent() failed");
648 }
649 if ((port->write_ovl.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL)) == INVALID_HANDLE_VALUE) {
650 sp_close(port);
651 RETURN_FAIL("write event CreateEvent() failed");
652 }
653
654 port->writing = FALSE;
655
74510d4b 656#else
e3dcf906 657 int flags_local = O_NONBLOCK | O_NOCTTY;
f92f1f0c 658
74510d4b 659 /* Map 'flags' to the OS-specific settings. */
a036341b 660 if (flags & (SP_MODE_READ | SP_MODE_WRITE))
74510d4b 661 flags_local |= O_RDWR;
a036341b 662 else if (flags & SP_MODE_READ)
74510d4b 663 flags_local |= O_RDONLY;
a036341b
ML
664 else if (flags & SP_MODE_WRITE)
665 flags_local |= O_WRONLY;
74510d4b
ML
666
667 if ((port->fd = open(port->name, flags_local)) < 0)
c33efc48 668 RETURN_FAIL("open() failed");
bccc7c9f 669#endif
9cb98459 670
e33ab9aa
ML
671 ret = get_config(port, &data, &config);
672
eac329d2 673 if (ret < 0) {
e33ab9aa 674 sp_close(port);
c33efc48 675 RETURN_CODEVAL(ret);
e33ab9aa 676 }
9cb98459 677
bccc7c9f
ML
678 /* Set sane port settings. */
679#ifdef _WIN32
680 data.dcb.fBinary = TRUE;
681 data.dcb.fDsrSensitivity = FALSE;
682 data.dcb.fErrorChar = FALSE;
683 data.dcb.fNull = FALSE;
684 data.dcb.fAbortOnError = TRUE;
685#else
b251be4b 686 /* Turn off all fancy termios tricks, give us a raw channel. */
c3e05092
UH
687 data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
688#ifdef IUCLC
689 data.term.c_iflag &= ~IUCLC;
690#endif
691 data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
692#ifdef OLCUC
693 data.term.c_oflag &= ~OLCUC;
694#endif
695#ifdef NLDLY
696 data.term.c_oflag &= ~NLDLY;
697#endif
698#ifdef CRDLY
699 data.term.c_oflag &= ~CRDLY;
700#endif
701#ifdef TABDLY
702 data.term.c_oflag &= ~TABDLY;
703#endif
704#ifdef BSDLY
705 data.term.c_oflag &= ~BSDLY;
706#endif
707#ifdef VTDLY
708 data.term.c_oflag &= ~VTDLY;
709#endif
710#ifdef FFDLY
711 data.term.c_oflag &= ~FFDLY;
712#endif
b251be4b 713#ifdef OFILL
9cb98459
ML
714 data.term.c_oflag &= ~OFILL;
715#endif
c3e05092 716 data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
e3dcf906 717 data.term.c_cc[VMIN] = 0;
b251be4b 718 data.term.c_cc[VTIME] = 0;
9cb98459 719
b251be4b
ML
720 /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
721 data.term.c_cflag |= (CLOCAL | CREAD | HUPCL);
bccc7c9f 722#endif
9cb98459 723
e33ab9aa
ML
724 ret = set_config(port, &data, &config);
725
eac329d2 726 if (ret < 0) {
e33ab9aa 727 sp_close(port);
c33efc48 728 RETURN_CODEVAL(ret);
e33ab9aa 729 }
74510d4b 730
c33efc48 731 RETURN_OK();
74510d4b
ML
732}
733
eb6ed20f 734enum sp_return sp_close(struct sp_port *port)
74510d4b 735{
c33efc48
ML
736 TRACE("%p", port);
737
dec10e31 738 CHECK_OPEN_PORT();
74510d4b 739
ea667be7
ML
740 DEBUG("Closing port %s", port->name);
741
74510d4b
ML
742#ifdef _WIN32
743 /* Returns non-zero upon success, 0 upon failure. */
744 if (CloseHandle(port->hdl) == 0)
e3dcf906 745 RETURN_FAIL("port CloseHandle() failed");
8f471c66 746 port->hdl = INVALID_HANDLE_VALUE;
e3dcf906
ML
747 /* Close event handle created for overlapped reads. */
748 if (port->read_ovl.hEvent != INVALID_HANDLE_VALUE && CloseHandle(port->read_ovl.hEvent) == 0)
749 RETURN_FAIL("read event CloseHandle() failed");
750 /* Close event handle created for overlapped writes. */
751 if (port->write_ovl.hEvent != INVALID_HANDLE_VALUE && CloseHandle(port->write_ovl.hEvent) == 0)
752 RETURN_FAIL("write event CloseHandle() failed");
74510d4b
ML
753#else
754 /* Returns 0 upon success, -1 upon failure. */
755 if (close(port->fd) == -1)
c33efc48 756 RETURN_FAIL("close() failed");
8f471c66 757 port->fd = -1;
74510d4b
ML
758#endif
759
c33efc48 760 RETURN_OK();
74510d4b
ML
761}
762
fd8fd11a 763enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
74510d4b 764{
00d8c56d 765 TRACE("%p, 0x%x", port, buffers);
c33efc48 766
dec10e31
ML
767 CHECK_OPEN_PORT();
768
769 if (buffers > SP_BUF_BOTH)
770 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
74510d4b 771
0ba3e49b 772 const char *buffer_names[] = {"no", "input", "output", "both"};
ea667be7
ML
773
774 DEBUG("Flushing %s buffers on port %s", buffer_names[buffers], port->name);
775
74510d4b 776#ifdef _WIN32
fd8fd11a
ML
777 DWORD flags = 0;
778 if (buffers & SP_BUF_INPUT)
779 flags |= PURGE_RXCLEAR;
780 if (buffers & SP_BUF_OUTPUT)
781 flags |= PURGE_TXCLEAR;
782
74510d4b 783 /* Returns non-zero upon success, 0 upon failure. */
fd8fd11a 784 if (PurgeComm(port->hdl, flags) == 0)
c33efc48 785 RETURN_FAIL("PurgeComm() failed");
74510d4b 786#else
fd8fd11a
ML
787 int flags = 0;
788 if (buffers & SP_BUF_BOTH)
789 flags = TCIOFLUSH;
790 else if (buffers & SP_BUF_INPUT)
791 flags = TCIFLUSH;
82f424e6 792 else if (buffers & SP_BUF_OUTPUT)
fd8fd11a
ML
793 flags = TCOFLUSH;
794
74510d4b 795 /* Returns 0 upon success, -1 upon failure. */
fd8fd11a 796 if (tcflush(port->fd, flags) < 0)
c33efc48 797 RETURN_FAIL("tcflush() failed");
74510d4b 798#endif
c33efc48 799 RETURN_OK();
74510d4b
ML
800}
801
69a3739c
ML
802enum sp_return sp_drain(struct sp_port *port)
803{
c33efc48
ML
804 TRACE("%p", port);
805
dec10e31 806 CHECK_OPEN_PORT();
69a3739c 807
ea667be7
ML
808 DEBUG("Draining port %s", port->name);
809
69a3739c
ML
810#ifdef _WIN32
811 /* Returns non-zero upon success, 0 upon failure. */
812 if (FlushFileBuffers(port->hdl) == 0)
c33efc48 813 RETURN_FAIL("FlushFileBuffers() failed");
2c827b21 814 RETURN_OK();
69a3739c 815#else
2c827b21
ML
816 int result;
817 while (1) {
818 result = tcdrain(port->fd);
819 if (result < 0) {
820 if (errno == EINTR) {
821 DEBUG("tcdrain() was interrupted");
822 continue;
823 } else {
824 RETURN_FAIL("tcdrain() failed");
825 }
826 } else {
827 RETURN_OK();
828 }
829 }
69a3739c 830#endif
69a3739c
ML
831}
832
e3dcf906
ML
833enum sp_return sp_blocking_write(struct sp_port *port, const void *buf, size_t count, unsigned int timeout)
834{
835 TRACE("%p, %p, %d, %d", port, buf, count, timeout);
836
837 CHECK_OPEN_PORT();
838
839 if (!buf)
840 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
841
842 if (timeout)
843 DEBUG("Writing %d bytes to port %s, timeout %d ms", count, port->name, timeout);
844 else
845 DEBUG("Writing %d bytes to port %s, no timeout", count, port->name);
846
847 if (count == 0)
848 RETURN_VALUE("0", 0);
849
850#ifdef _WIN32
851 DWORD bytes_written = 0;
852 BOOL result;
853
854 /* Wait for previous non-blocking write to complete, if any. */
855 if (port->writing) {
856 DEBUG("Waiting for previous write to complete");
857 result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
858 port->writing = 0;
859 if (!result)
860 RETURN_FAIL("Previous write failed to complete");
861 DEBUG("Previous write completed");
862 }
863
864 /* Set timeout. */
865 port->timeouts.WriteTotalTimeoutConstant = timeout;
866 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
867 RETURN_FAIL("SetCommTimeouts() failed");
868
869 /* Start write. */
870 if (WriteFile(port->hdl, buf, count, NULL, &port->write_ovl) == 0) {
871 if (GetLastError() == ERROR_IO_PENDING) {
872 DEBUG("Waiting for write to complete");
873 GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
874 DEBUG("Write completed, %d/%d bytes written", bytes_written, count);
875 RETURN_VALUE("%d", bytes_written);
876 } else {
877 RETURN_FAIL("WriteFile() failed");
878 }
879 } else {
880 DEBUG("Write completed immediately");
881 RETURN_VALUE("%d", count);
882 }
883#else
884 size_t bytes_written = 0;
885 unsigned char *ptr = (unsigned char *) buf;
886 struct timeval start, delta, now, end = {0, 0};
887 fd_set fds;
888 int result;
889
890 if (timeout) {
891 /* Get time at start of operation. */
892 gettimeofday(&start, NULL);
893 /* Define duration of timeout. */
894 delta.tv_sec = timeout / 1000;
1b342042 895 delta.tv_usec = (timeout % 1000) * 1000;
e3dcf906
ML
896 /* Calculate time at which we should give up. */
897 timeradd(&start, &delta, &end);
898 }
899
900 /* Loop until we have written the requested number of bytes. */
901 while (bytes_written < count)
902 {
903 /* Wait until space is available. */
904 FD_ZERO(&fds);
905 FD_SET(port->fd, &fds);
906 if (timeout) {
907 gettimeofday(&now, NULL);
908 if (timercmp(&now, &end, >)) {
909 DEBUG("write timed out");
910 RETURN_VALUE("%d", bytes_written);
911 }
912 timersub(&end, &now, &delta);
913 }
914 result = select(port->fd + 1, NULL, &fds, NULL, timeout ? &delta : NULL);
63a17c64
ML
915 if (result < 0) {
916 if (errno == EINTR) {
917 DEBUG("select() call was interrupted, repeating");
918 continue;
919 } else {
920 RETURN_FAIL("select() failed");
921 }
922 } else if (result == 0) {
e3dcf906
ML
923 DEBUG("write timed out");
924 RETURN_VALUE("%d", bytes_written);
925 }
926
927 /* Do write. */
928 result = write(port->fd, ptr, count - bytes_written);
929
930 if (result < 0) {
931 if (errno == EAGAIN)
932 /* This shouldn't happen because we did a select() first, but handle anyway. */
933 continue;
934 else
935 /* This is an actual failure. */
936 RETURN_FAIL("write() failed");
937 }
938
939 bytes_written += result;
940 ptr += result;
941 }
942
943 RETURN_VALUE("%d", bytes_written);
944#endif
945}
946
947enum sp_return sp_nonblocking_write(struct sp_port *port, const void *buf, size_t count)
74510d4b 948{
c33efc48
ML
949 TRACE("%p, %p, %d", port, buf, count);
950
dec10e31 951 CHECK_OPEN_PORT();
74510d4b
ML
952
953 if (!buf)
c33efc48 954 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
74510d4b 955
ea667be7
ML
956 DEBUG("Writing up to %d bytes to port %s", count, port->name);
957
a3cb91f5
ML
958 if (count == 0)
959 RETURN_VALUE("0", 0);
960
74510d4b
ML
961#ifdef _WIN32
962 DWORD written = 0;
0765af56 963 BYTE *ptr = (BYTE *) buf;
f92f1f0c 964
e3dcf906
ML
965 /* Check whether previous write is complete. */
966 if (port->writing) {
967 if (HasOverlappedIoCompleted(&port->write_ovl)) {
968 DEBUG("Previous write completed");
969 port->writing = 0;
970 } else {
971 DEBUG("Previous write not complete");
972 /* Can't take a new write until the previous one finishes. */
973 RETURN_VALUE("0", 0);
a3cb91f5 974 }
e3dcf906 975 }
a3cb91f5 976
e3dcf906
ML
977 /* Set timeout. */
978 port->timeouts.WriteTotalTimeoutConstant = 0;
979 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
980 RETURN_FAIL("SetCommTimeouts() failed");
981
982 /* Keep writing data until the OS has to actually start an async IO for it.
983 * At that point we know the buffer is full. */
984 while (written < count)
985 {
986 /* Copy first byte of user buffer. */
987 port->pending_byte = *ptr++;
988
989 /* Start asynchronous write. */
990 if (WriteFile(port->hdl, &port->pending_byte, 1, NULL, &port->write_ovl) == 0) {
991 if (GetLastError() == ERROR_IO_PENDING) {
992 DEBUG("Asynchronous write started");
993 port->writing = 1;
994 RETURN_VALUE("%d", ++written);
a3cb91f5 995 } else {
e3dcf906
ML
996 /* Actual failure of some kind. */
997 RETURN_FAIL("WriteFile() failed");
a3cb91f5 998 }
e3dcf906
ML
999 } else {
1000 DEBUG("Single byte written immediately.");
1001 written++;
a3cb91f5
ML
1002 }
1003 }
1004
e3dcf906
ML
1005 DEBUG("All bytes written immediately.");
1006
c33efc48 1007 RETURN_VALUE("%d", written);
74510d4b
ML
1008#else
1009 /* Returns the number of bytes written, or -1 upon failure. */
1010 ssize_t written = write(port->fd, buf, count);
f92f1f0c 1011
74510d4b 1012 if (written < 0)
c33efc48 1013 RETURN_FAIL("write() failed");
74510d4b 1014 else
c33efc48 1015 RETURN_VALUE("%d", written);
74510d4b
ML
1016#endif
1017}
1018
e3dcf906
ML
1019enum sp_return sp_blocking_read(struct sp_port *port, void *buf, size_t count, unsigned int timeout)
1020{
1021 TRACE("%p, %p, %d, %d", port, buf, count, timeout);
1022
1023 CHECK_OPEN_PORT();
1024
1025 if (!buf)
1026 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1027
1028 if (timeout)
1029 DEBUG("Reading %d bytes from port %s, timeout %d ms", count, port->name, timeout);
1030 else
1031 DEBUG("Reading %d bytes from port %s, no timeout", count, port->name);
1032
1033 if (count == 0)
1034 RETURN_VALUE("0", 0);
1035
1036#ifdef _WIN32
1037 DWORD bytes_read = 0;
1038
1039 /* Set timeout. */
1040 port->timeouts.ReadIntervalTimeout = 0;
1041 port->timeouts.ReadTotalTimeoutConstant = timeout;
1042 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1043 RETURN_FAIL("SetCommTimeouts() failed");
1044
1045 /* Start read. */
1046 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0) {
1047 if (GetLastError() == ERROR_IO_PENDING) {
1048 DEBUG("Waiting for read to complete");
1049 GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE);
1050 DEBUG("Read completed, %d/%d bytes read", bytes_read, count);
1051 RETURN_VALUE("%d", bytes_read);
1052 } else {
1053 RETURN_FAIL("ReadFile() failed");
1054 }
1055 } else {
1056 DEBUG("Read completed immediately");
1057 RETURN_VALUE("%d", count);
1058 }
1059#else
1060 size_t bytes_read = 0;
1061 unsigned char *ptr = (unsigned char *) buf;
1062 struct timeval start, delta, now, end = {0, 0};
1063 fd_set fds;
1064 int result;
1065
1066 if (timeout) {
1067 /* Get time at start of operation. */
1068 gettimeofday(&start, NULL);
1069 /* Define duration of timeout. */
1070 delta.tv_sec = timeout / 1000;
1b342042 1071 delta.tv_usec = (timeout % 1000) * 1000;
e3dcf906
ML
1072 /* Calculate time at which we should give up. */
1073 timeradd(&start, &delta, &end);
1074 }
1075
1076 /* Loop until we have the requested number of bytes. */
1077 while (bytes_read < count)
1078 {
1079 /* Wait until data is available. */
1080 FD_ZERO(&fds);
1081 FD_SET(port->fd, &fds);
1082 if (timeout) {
1083 gettimeofday(&now, NULL);
1084 if (timercmp(&now, &end, >))
1085 /* Timeout has expired. */
1086 RETURN_VALUE("%d", bytes_read);
1087 timersub(&end, &now, &delta);
1088 }
1089 result = select(port->fd + 1, &fds, NULL, NULL, timeout ? &delta : NULL);
63a17c64
ML
1090 if (result < 0) {
1091 if (errno == EINTR) {
1092 DEBUG("select() call was interrupted, repeating");
1093 continue;
1094 } else {
1095 RETURN_FAIL("select() failed");
1096 }
1097 } else if (result == 0) {
e3dcf906
ML
1098 DEBUG("read timed out");
1099 RETURN_VALUE("%d", bytes_read);
1100 }
1101
1102 /* Do read. */
1103 result = read(port->fd, ptr, count - bytes_read);
1104
1105 if (result < 0) {
1106 if (errno == EAGAIN)
1107 /* This shouldn't happen because we did a select() first, but handle anyway. */
1108 continue;
1109 else
1110 /* This is an actual failure. */
1111 RETURN_FAIL("read() failed");
1112 }
1113
1114 bytes_read += result;
1115 ptr += result;
1116 }
1117
1118 RETURN_VALUE("%d", bytes_read);
1119#endif
1120}
1121
1122enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf, size_t count)
74510d4b 1123{
c33efc48
ML
1124 TRACE("%p, %p, %d", port, buf, count);
1125
dec10e31 1126 CHECK_OPEN_PORT();
74510d4b
ML
1127
1128 if (!buf)
c33efc48 1129 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
74510d4b 1130
ea667be7
ML
1131 DEBUG("Reading up to %d bytes from port %s", count, port->name);
1132
74510d4b 1133#ifdef _WIN32
e3dcf906 1134 DWORD bytes_read;
f92f1f0c 1135
e3dcf906
ML
1136 /* Set timeout. */
1137 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1138 port->timeouts.ReadTotalTimeoutConstant = 0;
1139 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1140 RETURN_FAIL("SetCommTimeouts() failed");
1141
1142 /* Do read. */
1143 if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0)
c33efc48 1144 RETURN_FAIL("ReadFile() failed");
e3dcf906
ML
1145
1146 /* Get number of bytes read. */
1147 GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE);
1148
c33efc48 1149 RETURN_VALUE("%d", bytes_read);
74510d4b
ML
1150#else
1151 ssize_t bytes_read;
f92f1f0c 1152
74510d4b 1153 /* Returns the number of bytes read, or -1 upon failure. */
33d5ff47 1154 if ((bytes_read = read(port->fd, buf, count)) < 0) {
e3dcf906
ML
1155 if (errno == EAGAIN)
1156 /* No bytes available. */
33d5ff47
ML
1157 bytes_read = 0;
1158 else
1159 /* This is an actual failure. */
1160 RETURN_FAIL("read() failed");
1161 }
c33efc48 1162 RETURN_VALUE("%d", bytes_read);
74510d4b
ML
1163#endif
1164}
1165
3353c22f
ML
1166enum sp_return sp_input_waiting(struct sp_port *port)
1167{
1168 TRACE("%p", port);
1169
1170 CHECK_OPEN_PORT();
1171
1172 DEBUG("Checking input bytes waiting on port %s", port->name);
1173
1174#ifdef _WIN32
1175 DWORD errors;
1176 COMSTAT comstat;
1177
1178 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1179 RETURN_FAIL("ClearComError() failed");
1180 RETURN_VALUE("%d", comstat.cbInQue);
1181#else
1182 int bytes_waiting;
1183 if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1184 RETURN_FAIL("TIOCINQ ioctl failed");
1185 RETURN_VALUE("%d", bytes_waiting);
1186#endif
1187}
1188
1189enum sp_return sp_output_waiting(struct sp_port *port)
1190{
1191 TRACE("%p", port);
1192
1193 CHECK_OPEN_PORT();
1194
1195 DEBUG("Checking output bytes waiting on port %s", port->name);
1196
1197#ifdef _WIN32
1198 DWORD errors;
1199 COMSTAT comstat;
1200
1201 if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1202 RETURN_FAIL("ClearComError() failed");
1203 RETURN_VALUE("%d", comstat.cbOutQue);
1204#else
1205 int bytes_waiting;
1206 if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1207 RETURN_FAIL("TIOCOUTQ ioctl failed");
1208 RETURN_VALUE("%d", bytes_waiting);
1209#endif
1210}
1211
7a6d2196
ML
1212#ifdef __linux__
1213static enum sp_return get_baudrate(int fd, int *baudrate)
1214{
1215 void *data;
1216
c33efc48
ML
1217 TRACE("%d, %p", fd, baudrate);
1218
ea667be7
ML
1219 DEBUG("Getting baud rate");
1220
7a6d2196 1221 if (!(data = malloc(get_termios_size())))
c33efc48 1222 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
7a6d2196 1223
8d43110a
ML
1224 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1225 free(data);
c33efc48 1226 RETURN_FAIL("getting termios failed");
8d43110a 1227 }
7a6d2196
ML
1228
1229 *baudrate = get_termios_speed(data);
1230
8d43110a
ML
1231 free(data);
1232
c33efc48 1233 RETURN_OK();
7a6d2196
ML
1234}
1235
1236static enum sp_return set_baudrate(int fd, int baudrate)
1237{
1238 void *data;
1239
c33efc48
ML
1240 TRACE("%d, %d", fd, baudrate);
1241
ea667be7
ML
1242 DEBUG("Getting baud rate");
1243
7a6d2196 1244 if (!(data = malloc(get_termios_size())))
c33efc48 1245 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
7a6d2196 1246
8d43110a
ML
1247 if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1248 free(data);
c33efc48 1249 RETURN_FAIL("getting termios failed");
8d43110a 1250 }
7a6d2196 1251
ea667be7
ML
1252 DEBUG("Setting baud rate");
1253
7a6d2196
ML
1254 set_termios_speed(data, baudrate);
1255
8d43110a
ML
1256 if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1257 free(data);
c33efc48 1258 RETURN_FAIL("setting termios failed");
8d43110a
ML
1259 }
1260
1261 free(data);
7a6d2196 1262
c33efc48 1263 RETURN_OK();
7a6d2196 1264}
40978c2b
ML
1265
1266#ifdef USE_TERMIOX
1267static enum sp_return get_flow(int fd, int *flow)
1268{
1269 void *data;
1270
c33efc48
ML
1271 TRACE("%d, %p", fd, flow);
1272
ea667be7
ML
1273 DEBUG("Getting advanced flow control");
1274
40978c2b 1275 if (!(data = malloc(get_termiox_size())))
c33efc48 1276 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
40978c2b 1277
8d43110a
ML
1278 if (ioctl(fd, TCGETX, data) < 0) {
1279 free(data);
c33efc48 1280 RETURN_FAIL("getting termiox failed");
8d43110a 1281 }
40978c2b
ML
1282
1283 *flow = get_termiox_flow(data);
1284
8d43110a
ML
1285 free(data);
1286
c33efc48 1287 RETURN_OK();
40978c2b
ML
1288}
1289
1290static enum sp_return set_flow(int fd, int flow)
1291{
1292 void *data;
1293
c33efc48
ML
1294 TRACE("%d, %d", fd, flow);
1295
ea667be7
ML
1296 DEBUG("Getting advanced flow control");
1297
40978c2b 1298 if (!(data = malloc(get_termiox_size())))
c33efc48 1299 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
40978c2b 1300
8d43110a
ML
1301 if (ioctl(fd, TCGETX, data) < 0) {
1302 free(data);
c33efc48 1303 RETURN_FAIL("getting termiox failed");
8d43110a 1304 }
40978c2b 1305
ea667be7
ML
1306 DEBUG("Setting advanced flow control");
1307
40978c2b
ML
1308 set_termiox_flow(data, flow);
1309
8d43110a
ML
1310 if (ioctl(fd, TCSETX, data) < 0) {
1311 free(data);
c33efc48 1312 RETURN_FAIL("setting termiox failed");
8d43110a
ML
1313 }
1314
1315 free(data);
40978c2b 1316
c33efc48 1317 RETURN_OK();
40978c2b
ML
1318}
1319#endif /* USE_TERMIOX */
1320#endif /* __linux__ */
7a6d2196 1321
eb6ed20f
ML
1322static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1323 struct sp_port_config *config)
8094e4a0 1324{
da2748bf 1325 unsigned int i;
cbf628c7 1326
c33efc48
ML
1327 TRACE("%p, %p, %p", port, data, config);
1328
ea667be7
ML
1329 DEBUG("Getting configuration for port %s", port->name);
1330
8094e4a0 1331#ifdef _WIN32
e33ab9aa 1332 if (!GetCommState(port->hdl, &data->dcb))
c33efc48 1333 RETURN_FAIL("GetCommState() failed");
8094e4a0 1334
067417af 1335 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
e33ab9aa 1336 if (data->dcb.BaudRate == std_baudrates[i].index) {
067417af
ML
1337 config->baudrate = std_baudrates[i].value;
1338 break;
1339 }
1340 }
1341
1342 if (i == NUM_STD_BAUDRATES)
1343 /* BaudRate field can be either an index or a custom baud rate. */
e33ab9aa 1344 config->baudrate = data->dcb.BaudRate;
067417af 1345
e33ab9aa 1346 config->bits = data->dcb.ByteSize;
067417af 1347
e33ab9aa
ML
1348 if (data->dcb.fParity)
1349 switch (data->dcb.Parity) {
067417af
ML
1350 case NOPARITY:
1351 config->parity = SP_PARITY_NONE;
1352 break;
e432ce60
ML
1353 case ODDPARITY:
1354 config->parity = SP_PARITY_ODD;
1355 break;
067417af
ML
1356 case EVENPARITY:
1357 config->parity = SP_PARITY_EVEN;
1358 break;
e432ce60
ML
1359 case MARKPARITY:
1360 config->parity = SP_PARITY_MARK;
1361 break;
1362 case SPACEPARITY:
1363 config->parity = SP_PARITY_SPACE;
067417af
ML
1364 break;
1365 default:
1366 config->parity = -1;
1367 }
1368 else
1369 config->parity = SP_PARITY_NONE;
1370
e33ab9aa 1371 switch (data->dcb.StopBits) {
067417af
ML
1372 case ONESTOPBIT:
1373 config->stopbits = 1;
1374 break;
1375 case TWOSTOPBITS:
1376 config->stopbits = 2;
1377 break;
1378 default:
1379 config->stopbits = -1;
1380 }
1381
e33ab9aa 1382 switch (data->dcb.fRtsControl) {
eac329d2
UH
1383 case RTS_CONTROL_DISABLE:
1384 config->rts = SP_RTS_OFF;
1385 break;
1386 case RTS_CONTROL_ENABLE:
1387 config->rts = SP_RTS_ON;
1388 break;
1389 case RTS_CONTROL_HANDSHAKE:
1390 config->rts = SP_RTS_FLOW_CONTROL;
1391 break;
1392 default:
1393 config->rts = -1;
067417af
ML
1394 }
1395
e33ab9aa 1396 config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
067417af 1397
e33ab9aa 1398 switch (data->dcb.fDtrControl) {
eac329d2
UH
1399 case DTR_CONTROL_DISABLE:
1400 config->dtr = SP_DTR_OFF;
1401 break;
1402 case DTR_CONTROL_ENABLE:
1403 config->dtr = SP_DTR_ON;
1404 break;
1405 case DTR_CONTROL_HANDSHAKE:
1406 config->dtr = SP_DTR_FLOW_CONTROL;
1407 break;
1408 default:
1409 config->dtr = -1;
067417af
ML
1410 }
1411
e33ab9aa
ML
1412 config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1413
c6754b45
ML
1414 if (data->dcb.fInX) {
1415 if (data->dcb.fOutX)
1416 config->xon_xoff = SP_XONXOFF_INOUT;
1417 else
1418 config->xon_xoff = SP_XONXOFF_IN;
1419 } else {
1420 if (data->dcb.fOutX)
1421 config->xon_xoff = SP_XONXOFF_OUT;
1422 else
1423 config->xon_xoff = SP_XONXOFF_DISABLED;
1424 }
1425
e33ab9aa
ML
1426#else // !_WIN32
1427
1428 if (tcgetattr(port->fd, &data->term) < 0)
c33efc48 1429 RETURN_FAIL("tcgetattr() failed");
e33ab9aa
ML
1430
1431 if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
c33efc48 1432 RETURN_FAIL("TIOCMGET ioctl failed");
40978c2b
ML
1433
1434#ifdef USE_TERMIOX
68ec29db
ML
1435 int ret = get_flow(port->fd, &data->flow);
1436
1437 if (ret == SP_ERR_FAIL && errno == EINVAL)
1438 data->termiox_supported = 0;
1439 else if (ret < 0)
c33efc48 1440 RETURN_CODEVAL(ret);
68ec29db
ML
1441 else
1442 data->termiox_supported = 1;
1443#else
1444 data->termiox_supported = 0;
40978c2b
ML
1445#endif
1446
067417af 1447 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
e33ab9aa 1448 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
067417af
ML
1449 config->baudrate = std_baudrates[i].value;
1450 break;
1451 }
1452 }
1453
31b3a8f5
MH
1454 if (i == NUM_STD_BAUDRATES) {
1455#ifdef __APPLE__
1456 config->baudrate = (int)data->term.c_ispeed;
7a6d2196
ML
1457#elif defined(__linux__)
1458 TRY(get_baudrate(port->fd, &config->baudrate));
31b3a8f5 1459#else
067417af 1460 config->baudrate = -1;
31b3a8f5
MH
1461#endif
1462 }
067417af 1463
e33ab9aa 1464 switch (data->term.c_cflag & CSIZE) {
067417af
ML
1465 case CS8:
1466 config->bits = 8;
1467 break;
1468 case CS7:
1469 config->bits = 7;
1470 break;
1471 case CS6:
1472 config->bits = 6;
1473 break;
1474 case CS5:
1475 config->bits = 5;
1476 break;
1477 default:
1478 config->bits = -1;
1479 }
1480
e33ab9aa 1481 if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
067417af 1482 config->parity = SP_PARITY_NONE;
e33ab9aa 1483 else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
067417af 1484 config->parity = -1;
c3e05092 1485#ifdef CMSPAR
e432ce60
ML
1486 else if (data->term.c_cflag & CMSPAR)
1487 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
c3e05092 1488#endif
067417af 1489 else
e33ab9aa 1490 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
067417af 1491
e33ab9aa 1492 config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
067417af 1493
e33ab9aa 1494 if (data->term.c_cflag & CRTSCTS) {
067417af
ML
1495 config->rts = SP_RTS_FLOW_CONTROL;
1496 config->cts = SP_CTS_FLOW_CONTROL;
1497 } else {
68ec29db 1498 if (data->termiox_supported && data->flow & RTS_FLOW)
40978c2b
ML
1499 config->rts = SP_RTS_FLOW_CONTROL;
1500 else
1501 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1502
68ec29db
ML
1503 config->cts = (data->termiox_supported && data->flow & CTS_FLOW) ?
1504 SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
067417af
ML
1505 }
1506
68ec29db 1507 if (data->termiox_supported && data->flow & DTR_FLOW)
40978c2b
ML
1508 config->dtr = SP_DTR_FLOW_CONTROL;
1509 else
1510 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1511
68ec29db
ML
1512 config->dsr = (data->termiox_supported && data->flow & DSR_FLOW) ?
1513 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
705bdc69 1514
e29b93a5
ML
1515 if (data->term.c_iflag & IXOFF) {
1516 if (data->term.c_iflag & IXON)
1517 config->xon_xoff = SP_XONXOFF_INOUT;
1518 else
1519 config->xon_xoff = SP_XONXOFF_IN;
1520 } else {
1521 if (data->term.c_iflag & IXON)
1522 config->xon_xoff = SP_XONXOFF_OUT;
1523 else
1524 config->xon_xoff = SP_XONXOFF_DISABLED;
1525 }
067417af
ML
1526#endif
1527
c33efc48 1528 RETURN_OK();
067417af
ML
1529}
1530
7a6d2196 1531static enum sp_return set_config(struct sp_port *port, struct port_data *data,
eb6ed20f 1532 const struct sp_port_config *config)
18fc2dd1 1533{
e33ab9aa 1534 unsigned int i;
31b3a8f5
MH
1535#ifdef __APPLE__
1536 BAUD_TYPE baud_nonstd;
1537
1538 baud_nonstd = B0;
1539#endif
7a6d2196
ML
1540#ifdef __linux__
1541 int baud_nonstd = 0;
1542#endif
18fc2dd1 1543
c33efc48
ML
1544 TRACE("%p, %p, %p", port, data, config);
1545
ea667be7
ML
1546 DEBUG("Setting configuration for port %s", port->name);
1547
e33ab9aa 1548#ifdef _WIN32
eac329d2 1549 if (config->baudrate >= 0) {
e33ab9aa
ML
1550 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1551 if (config->baudrate == std_baudrates[i].value) {
1552 data->dcb.BaudRate = std_baudrates[i].index;
1553 break;
1554 }
1555 }
18fc2dd1 1556
e33ab9aa
ML
1557 if (i == NUM_STD_BAUDRATES)
1558 data->dcb.BaudRate = config->baudrate;
1559 }
18fc2dd1 1560
e33ab9aa
ML
1561 if (config->bits >= 0)
1562 data->dcb.ByteSize = config->bits;
1563
1564 if (config->parity >= 0) {
1565 switch (config->parity) {
1566 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
1567 case SP_PARITY_NONE:
1568 data->dcb.Parity = NOPARITY;
1569 break;
e432ce60
ML
1570 case SP_PARITY_ODD:
1571 data->dcb.Parity = ODDPARITY;
1572 break;
e33ab9aa
ML
1573 case SP_PARITY_EVEN:
1574 data->dcb.Parity = EVENPARITY;
1575 break;
e432ce60
ML
1576 case SP_PARITY_MARK:
1577 data->dcb.Parity = MARKPARITY;
1578 break;
1579 case SP_PARITY_SPACE:
1580 data->dcb.Parity = SPACEPARITY;
e33ab9aa
ML
1581 break;
1582 default:
c33efc48 1583 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
e33ab9aa 1584 }
18fc2dd1
ML
1585 }
1586
e33ab9aa
ML
1587 if (config->stopbits >= 0) {
1588 switch (config->stopbits) {
1589 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1590 case 1:
1591 data->dcb.StopBits = ONESTOPBIT;
1592 break;
1593 case 2:
1594 data->dcb.StopBits = TWOSTOPBITS;
1595 break;
1596 default:
c33efc48 1597 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
e33ab9aa
ML
1598 }
1599 }
1600
1601 if (config->rts >= 0) {
1602 switch (config->rts) {
1603 case SP_RTS_OFF:
1604 data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
1605 break;
1606 case SP_RTS_ON:
1607 data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
1608 break;
1609 case SP_RTS_FLOW_CONTROL:
1610 data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
1611 break;
1612 default:
c33efc48 1613 RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
e33ab9aa
ML
1614 }
1615 }
1616
1617 if (config->cts >= 0) {
1618 switch (config->cts) {
1619 case SP_CTS_IGNORE:
1620 data->dcb.fOutxCtsFlow = FALSE;
1621 break;
1622 case SP_CTS_FLOW_CONTROL:
1623 data->dcb.fOutxCtsFlow = TRUE;
1624 break;
1625 default:
c33efc48 1626 RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
e33ab9aa
ML
1627 }
1628 }
1629
1630 if (config->dtr >= 0) {
1631 switch (config->dtr) {
1632 case SP_DTR_OFF:
1633 data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
1634 break;
1635 case SP_DTR_ON:
1636 data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
1637 break;
1638 case SP_DTR_FLOW_CONTROL:
1639 data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
1640 break;
1641 default:
c33efc48 1642 RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
e33ab9aa
ML
1643 }
1644 }
1645
1646 if (config->dsr >= 0) {
1647 switch (config->dsr) {
1648 case SP_DSR_IGNORE:
1649 data->dcb.fOutxDsrFlow = FALSE;
1650 break;
1651 case SP_DSR_FLOW_CONTROL:
1652 data->dcb.fOutxDsrFlow = TRUE;
1653 break;
1654 default:
c33efc48 1655 RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
e33ab9aa 1656 }
18fc2dd1
ML
1657 }
1658
e33ab9aa
ML
1659 if (config->xon_xoff >= 0) {
1660 switch (config->xon_xoff) {
1661 case SP_XONXOFF_DISABLED:
1662 data->dcb.fInX = FALSE;
1663 data->dcb.fOutX = FALSE;
1664 break;
1665 case SP_XONXOFF_IN:
1666 data->dcb.fInX = TRUE;
1667 data->dcb.fOutX = FALSE;
1668 break;
1669 case SP_XONXOFF_OUT:
1670 data->dcb.fInX = FALSE;
1671 data->dcb.fOutX = TRUE;
1672 break;
1673 case SP_XONXOFF_INOUT:
1674 data->dcb.fInX = TRUE;
1675 data->dcb.fOutX = TRUE;
1676 break;
1677 default:
c33efc48 1678 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
e33ab9aa
ML
1679 }
1680 }
1681
1682 if (!SetCommState(port->hdl, &data->dcb))
c33efc48 1683 RETURN_FAIL("SetCommState() failed");
e33ab9aa 1684
31b3a8f5 1685#else /* !_WIN32 */
e33ab9aa 1686
7a6d2196
ML
1687 int controlbits;
1688
eac329d2 1689 if (config->baudrate >= 0) {
e33ab9aa
ML
1690 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1691 if (config->baudrate == std_baudrates[i].value) {
1692 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
c33efc48 1693 RETURN_FAIL("cfsetospeed() failed");
e33ab9aa
ML
1694
1695 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
c33efc48 1696 RETURN_FAIL("cfsetispeed() failed");
e33ab9aa
ML
1697 break;
1698 }
1699 }
1700
31b3a8f5
MH
1701 /* Non-standard baud rate */
1702 if (i == NUM_STD_BAUDRATES) {
1703#ifdef __APPLE__
24abdb68 1704 /* Set "dummy" baud rate. */
31b3a8f5 1705 if (cfsetspeed(&data->term, B9600) < 0)
c33efc48 1706 RETURN_FAIL("cfsetspeed() failed");
31b3a8f5 1707 baud_nonstd = config->baudrate;
7a6d2196
ML
1708#elif defined(__linux__)
1709 baud_nonstd = 1;
31b3a8f5 1710#else
c33efc48 1711 RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
31b3a8f5
MH
1712#endif
1713 }
e33ab9aa
ML
1714 }
1715
1716 if (config->bits >= 0) {
1717 data->term.c_cflag &= ~CSIZE;
1718 switch (config->bits) {
1719 case 8:
1720 data->term.c_cflag |= CS8;
1721 break;
1722 case 7:
1723 data->term.c_cflag |= CS7;
1724 break;
1725 case 6:
1726 data->term.c_cflag |= CS6;
1727 break;
23922313
UH
1728 case 5:
1729 data->term.c_cflag |= CS5;
1730 break;
e33ab9aa 1731 default:
c33efc48 1732 RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
e33ab9aa
ML
1733 }
1734 }
1735
1736 if (config->parity >= 0) {
1737 data->term.c_iflag &= ~IGNPAR;
c3e05092
UH
1738 data->term.c_cflag &= ~(PARENB | PARODD);
1739#ifdef CMSPAR
1740 data->term.c_cflag &= ~CMSPAR;
1741#endif
e33ab9aa
ML
1742 switch (config->parity) {
1743 case SP_PARITY_NONE:
1744 data->term.c_iflag |= IGNPAR;
1745 break;
1746 case SP_PARITY_EVEN:
1747 data->term.c_cflag |= PARENB;
1748 break;
1749 case SP_PARITY_ODD:
1750 data->term.c_cflag |= PARENB | PARODD;
1751 break;
afb518f0 1752#ifdef CMSPAR
e432ce60 1753 case SP_PARITY_MARK:
c3e05092 1754 data->term.c_cflag |= PARENB | PARODD;
c3e05092 1755 data->term.c_cflag |= CMSPAR;
e432ce60
ML
1756 break;
1757 case SP_PARITY_SPACE:
c3e05092 1758 data->term.c_cflag |= PARENB;
c3e05092 1759 data->term.c_cflag |= CMSPAR;
e432ce60 1760 break;
afb518f0
ML
1761#else
1762 case SP_PARITY_MARK:
1763 case SP_PARITY_SPACE:
1764 RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
1765#endif
e33ab9aa 1766 default:
c33efc48 1767 RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
e33ab9aa
ML
1768 }
1769 }
1770
1771 if (config->stopbits >= 0) {
1772 data->term.c_cflag &= ~CSTOPB;
1773 switch (config->stopbits) {
1774 case 1:
1775 data->term.c_cflag &= ~CSTOPB;
1776 break;
1777 case 2:
1778 data->term.c_cflag |= CSTOPB;
1779 break;
1780 default:
c33efc48 1781 RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
e33ab9aa
ML
1782 }
1783 }
1784
eac329d2 1785 if (config->rts >= 0 || config->cts >= 0) {
68ec29db
ML
1786 if (data->termiox_supported) {
1787 data->flow &= ~(RTS_FLOW | CTS_FLOW);
1788 switch (config->rts) {
1789 case SP_RTS_OFF:
1790 case SP_RTS_ON:
1791 controlbits = TIOCM_RTS;
1792 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
c33efc48 1793 RETURN_FAIL("Setting RTS signal level failed");
68ec29db
ML
1794 break;
1795 case SP_RTS_FLOW_CONTROL:
1796 data->flow |= RTS_FLOW;
1797 break;
1798 default:
1799 break;
e33ab9aa 1800 }
68ec29db
ML
1801 if (config->cts == SP_CTS_FLOW_CONTROL)
1802 data->flow |= CTS_FLOW;
e33ab9aa 1803
68ec29db 1804 if (data->flow & (RTS_FLOW | CTS_FLOW))
e33ab9aa 1805 data->term.c_iflag |= CRTSCTS;
68ec29db
ML
1806 else
1807 data->term.c_iflag &= ~CRTSCTS;
1808 } else {
1809 /* Asymmetric use of RTS/CTS not supported. */
1810 if (data->term.c_iflag & CRTSCTS) {
1811 /* Flow control can only be disabled for both RTS & CTS together. */
1812 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
1813 if (config->cts != SP_CTS_IGNORE)
c33efc48 1814 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
68ec29db
ML
1815 }
1816 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
1817 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
c33efc48 1818 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
68ec29db 1819 }
e33ab9aa 1820 } else {
68ec29db
ML
1821 /* Flow control can only be enabled for both RTS & CTS together. */
1822 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
1823 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
c33efc48 1824 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
68ec29db
ML
1825 }
1826
1827 if (config->rts >= 0) {
1828 if (config->rts == SP_RTS_FLOW_CONTROL) {
1829 data->term.c_iflag |= CRTSCTS;
1830 } else {
1831 controlbits = TIOCM_RTS;
1832 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
1833 &controlbits) < 0)
c33efc48 1834 RETURN_FAIL("Setting RTS signal level failed");
68ec29db 1835 }
e33ab9aa
ML
1836 }
1837 }
1838 }
1839
eac329d2 1840 if (config->dtr >= 0 || config->dsr >= 0) {
68ec29db
ML
1841 if (data->termiox_supported) {
1842 data->flow &= ~(DTR_FLOW | DSR_FLOW);
1843 switch (config->dtr) {
1844 case SP_DTR_OFF:
1845 case SP_DTR_ON:
1846 controlbits = TIOCM_DTR;
1847 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
c33efc48 1848 RETURN_FAIL("Setting DTR signal level failed");
68ec29db
ML
1849 break;
1850 case SP_DTR_FLOW_CONTROL:
1851 data->flow |= DTR_FLOW;
1852 break;
1853 default:
1854 break;
1855 }
1856 if (config->dsr == SP_DSR_FLOW_CONTROL)
1857 data->flow |= DSR_FLOW;
1858 } else {
1859 /* DTR/DSR flow control not supported. */
1860 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
c33efc48 1861 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
e33ab9aa 1862
68ec29db
ML
1863 if (config->dtr >= 0) {
1864 controlbits = TIOCM_DTR;
1865 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
1866 &controlbits) < 0)
c33efc48 1867 RETURN_FAIL("Setting DTR signal level failed");
68ec29db 1868 }
e33ab9aa
ML
1869 }
1870 }
1871
1872 if (config->xon_xoff >= 0) {
1873 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
1874 switch (config->xon_xoff) {
1875 case SP_XONXOFF_DISABLED:
1876 break;
1877 case SP_XONXOFF_IN:
1878 data->term.c_iflag |= IXOFF;
1879 break;
1880 case SP_XONXOFF_OUT:
1881 data->term.c_iflag |= IXON | IXANY;
1882 break;
1883 case SP_XONXOFF_INOUT:
1884 data->term.c_iflag |= IXON | IXOFF | IXANY;
1885 break;
1886 default:
c33efc48 1887 RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
e33ab9aa
ML
1888 }
1889 }
1890
3f5c06d0 1891 if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
c33efc48 1892 RETURN_FAIL("tcsetattr() failed");
31b3a8f5
MH
1893
1894#ifdef __APPLE__
1895 if (baud_nonstd != B0) {
1896 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
c33efc48 1897 RETURN_FAIL("IOSSIOSPEED ioctl failed");
31b3a8f5
MH
1898 /* Set baud rates in data->term to correct, but incompatible
1899 * with tcsetattr() value, same as delivered by tcgetattr(). */
1900 if (cfsetspeed(&data->term, baud_nonstd) < 0)
c33efc48 1901 RETURN_FAIL("cfsetspeed() failed");
31b3a8f5 1902 }
7a6d2196
ML
1903#elif defined(__linux__)
1904 if (baud_nonstd)
1905 TRY(set_baudrate(port->fd, config->baudrate));
40978c2b 1906#ifdef USE_TERMIOX
68ec29db
ML
1907 if (data->termiox_supported)
1908 TRY(set_flow(port->fd, data->flow));
40978c2b 1909#endif
7a6d2196 1910#endif
31b3a8f5
MH
1911
1912#endif /* !_WIN32 */
e33ab9aa 1913
c33efc48 1914 RETURN_OK();
e33ab9aa
ML
1915}
1916
9b1502ef
ML
1917enum sp_return sp_new_config(struct sp_port_config **config_ptr)
1918{
59131d60 1919 struct sp_port_config *config;
9b1502ef 1920
00d8c56d
UH
1921 TRACE("%p", config_ptr);
1922
9b1502ef
ML
1923 if (!config_ptr)
1924 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
1925
59131d60
ML
1926 *config_ptr = NULL;
1927
1928 if (!(config = malloc(sizeof(struct sp_port_config))))
9b1502ef
ML
1929 RETURN_ERROR(SP_ERR_MEM, "config malloc failed");
1930
59131d60
ML
1931 config->baudrate = -1;
1932 config->bits = -1;
1933 config->parity = -1;
1934 config->stopbits = -1;
1935 config->rts = -1;
1936 config->cts = -1;
1937 config->dtr = -1;
1938 config->dsr = -1;
1939
1940 *config_ptr = config;
1941
9b1502ef
ML
1942 RETURN_OK();
1943}
1944
1945void sp_free_config(struct sp_port_config *config)
1946{
1947 TRACE("%p", config);
1948
1949 if (!config)
1950 DEBUG("Null config");
1951 else
1952 free(config);
1953
1954 RETURN();
1955}
1956
70cd37de
ML
1957enum sp_return sp_get_config(struct sp_port *port, struct sp_port_config *config)
1958{
1959 struct port_data data;
1960
1961 TRACE("%p, %p", port, config);
1962
1963 CHECK_OPEN_PORT();
1964
1965 if (!config)
9b1502ef 1966 RETURN_ERROR(SP_ERR_ARG, "Null config");
70cd37de
ML
1967
1968 TRY(get_config(port, &data, config));
1969
1970 RETURN_OK();
1971}
1972
eb6ed20f 1973enum sp_return sp_set_config(struct sp_port *port, const struct sp_port_config *config)
e33ab9aa 1974{
8f189c4c 1975 struct port_data data;
e33ab9aa
ML
1976 struct sp_port_config prev_config;
1977
c33efc48
ML
1978 TRACE("%p, %p", port, config);
1979
dec10e31 1980 CHECK_OPEN_PORT();
823690ae
ML
1981
1982 if (!config)
c33efc48 1983 RETURN_ERROR(SP_ERR_ARG, "Null config");
823690ae 1984
e33ab9aa
ML
1985 TRY(get_config(port, &data, &prev_config));
1986 TRY(set_config(port, &data, config));
74510d4b 1987
c33efc48 1988 RETURN_OK();
74510d4b
ML
1989}
1990
9b1502ef
ML
1991#define CREATE_ACCESSORS(x, type) \
1992enum sp_return sp_set_##x(struct sp_port *port, type x) { \
8f189c4c 1993 struct port_data data; \
e33ab9aa 1994 struct sp_port_config config; \
c33efc48 1995 TRACE("%p, %d", port, x); \
dec10e31 1996 CHECK_OPEN_PORT(); \
e33ab9aa
ML
1997 TRY(get_config(port, &data, &config)); \
1998 config.x = x; \
1999 TRY(set_config(port, &data, &config)); \
c33efc48 2000 RETURN_OK(); \
9b1502ef
ML
2001} \
2002enum sp_return sp_get_config_##x(const struct sp_port_config *config, type *x) { \
00d8c56d 2003 TRACE("%p, %p", config, x); \
9b1502ef
ML
2004 if (!config) \
2005 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2006 *x = config->x; \
2007 RETURN_OK(); \
2008} \
2009enum sp_return sp_set_config_##x(struct sp_port_config *config, type x) { \
2010 TRACE("%p, %d", config, x); \
2011 if (!config) \
2012 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2013 config->x = x; \
2014 RETURN_OK(); \
9069c2fb
ML
2015}
2016
9b1502ef
ML
2017CREATE_ACCESSORS(baudrate, int)
2018CREATE_ACCESSORS(bits, int)
2019CREATE_ACCESSORS(parity, enum sp_parity)
2020CREATE_ACCESSORS(stopbits, int)
2021CREATE_ACCESSORS(rts, enum sp_rts)
2022CREATE_ACCESSORS(cts, enum sp_cts)
2023CREATE_ACCESSORS(dtr, enum sp_dtr)
2024CREATE_ACCESSORS(dsr, enum sp_dsr)
2025CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2026
2027enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config, enum sp_flowcontrol flowcontrol)
e33ab9aa 2028{
9b1502ef
ML
2029 if (!config)
2030 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
dec10e31
ML
2031
2032 if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2033 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
823690ae 2034
e33ab9aa 2035 if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
9b1502ef 2036 config->xon_xoff = SP_XONXOFF_INOUT;
e33ab9aa 2037 else
9b1502ef 2038 config->xon_xoff = SP_XONXOFF_DISABLED;
e33ab9aa
ML
2039
2040 if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
9b1502ef
ML
2041 config->rts = SP_RTS_FLOW_CONTROL;
2042 config->cts = SP_CTS_FLOW_CONTROL;
e33ab9aa 2043 } else {
9b1502ef
ML
2044 if (config->rts == SP_RTS_FLOW_CONTROL)
2045 config->rts = SP_RTS_ON;
2046 config->cts = SP_CTS_IGNORE;
e33ab9aa
ML
2047 }
2048
2049 if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
9b1502ef
ML
2050 config->dtr = SP_DTR_FLOW_CONTROL;
2051 config->dsr = SP_DSR_FLOW_CONTROL;
e33ab9aa 2052 } else {
9b1502ef
ML
2053 if (config->dtr == SP_DTR_FLOW_CONTROL)
2054 config->dtr = SP_DTR_ON;
2055 config->dsr = SP_DSR_IGNORE;
e33ab9aa
ML
2056 }
2057
9b1502ef
ML
2058 RETURN_OK();
2059}
2060
2061enum sp_return sp_set_flowcontrol(struct sp_port *port, enum sp_flowcontrol flowcontrol)
2062{
2063 struct port_data data;
2064 struct sp_port_config config;
2065
2066 TRACE("%p, %d", port, flowcontrol);
2067
2068 CHECK_OPEN_PORT();
2069
2070 TRY(get_config(port, &data, &config));
2071
2072 TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2073
e33ab9aa
ML
2074 TRY(set_config(port, &data, &config));
2075
c33efc48 2076 RETURN_OK();
e33ab9aa
ML
2077}
2078
8cf7c697
ML
2079enum sp_return sp_get_signals(struct sp_port *port, enum sp_signal *signals)
2080{
c33efc48
ML
2081 TRACE("%p, %p", port, signals);
2082
dec10e31 2083 CHECK_OPEN_PORT();
8cf7c697
ML
2084
2085 if (!signals)
c33efc48 2086 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
8cf7c697 2087
ea667be7
ML
2088 DEBUG("Getting control signals for port %s", port->name);
2089
8cf7c697
ML
2090 *signals = 0;
2091#ifdef _WIN32
2092 DWORD bits;
2093 if (GetCommModemStatus(port->hdl, &bits) == 0)
c33efc48 2094 RETURN_FAIL("GetCommModemStatus() failed");
8cf7c697
ML
2095 if (bits & MS_CTS_ON)
2096 *signals |= SP_SIG_CTS;
2097 if (bits & MS_DSR_ON)
2098 *signals |= SP_SIG_DSR;
8cf7c697 2099 if (bits & MS_RLSD_ON)
a6cda1e8
ML
2100 *signals |= SP_SIG_DCD;
2101 if (bits & MS_RING_ON)
8cf7c697
ML
2102 *signals |= SP_SIG_RI;
2103#else
2104 int bits;
2105 if (ioctl(port->fd, TIOCMGET, &bits) < 0)
c33efc48 2106 RETURN_FAIL("TIOCMGET ioctl failed");
8cf7c697
ML
2107 if (bits & TIOCM_CTS)
2108 *signals |= SP_SIG_CTS;
2109 if (bits & TIOCM_DSR)
2110 *signals |= SP_SIG_DSR;
2111 if (bits & TIOCM_CAR)
2112 *signals |= SP_SIG_DCD;
2113 if (bits & TIOCM_RNG)
2114 *signals |= SP_SIG_RI;
2115#endif
c33efc48 2116 RETURN_OK();
8cf7c697
ML
2117}
2118
90cc3ee6
ML
2119enum sp_return sp_start_break(struct sp_port *port)
2120{
c33efc48
ML
2121 TRACE("%p", port);
2122
dec10e31 2123 CHECK_OPEN_PORT();
90cc3ee6
ML
2124#ifdef _WIN32
2125 if (SetCommBreak(port->hdl) == 0)
c33efc48 2126 RETURN_FAIL("SetCommBreak() failed");
90cc3ee6
ML
2127#else
2128 if (ioctl(port->fd, TIOCSBRK, 1) < 0)
c33efc48 2129 RETURN_FAIL("TIOCSBRK ioctl failed");
90cc3ee6
ML
2130#endif
2131
c33efc48 2132 RETURN_OK();
90cc3ee6
ML
2133}
2134
2135enum sp_return sp_end_break(struct sp_port *port)
2136{
c33efc48
ML
2137 TRACE("%p", port);
2138
dec10e31 2139 CHECK_OPEN_PORT();
90cc3ee6
ML
2140#ifdef _WIN32
2141 if (ClearCommBreak(port->hdl) == 0)
c33efc48 2142 RETURN_FAIL("ClearCommBreak() failed");
90cc3ee6
ML
2143#else
2144 if (ioctl(port->fd, TIOCCBRK, 1) < 0)
c33efc48 2145 RETURN_FAIL("TIOCCBRK ioctl failed");
90cc3ee6
ML
2146#endif
2147
c33efc48 2148 RETURN_OK();
90cc3ee6
ML
2149}
2150
74510d4b
ML
2151int sp_last_error_code(void)
2152{
c33efc48 2153 TRACE("");
74510d4b 2154#ifdef _WIN32
c33efc48 2155 RETURN_VALUE("%d", GetLastError());
74510d4b 2156#else
c33efc48 2157 RETURN_VALUE("%d", errno);
74510d4b
ML
2158#endif
2159}
2160
74510d4b
ML
2161char *sp_last_error_message(void)
2162{
c33efc48
ML
2163 TRACE("");
2164
74510d4b
ML
2165#ifdef _WIN32
2166 LPVOID message;
2167 DWORD error = GetLastError();
2168
2169 FormatMessage(
2170 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2171 FORMAT_MESSAGE_FROM_SYSTEM |
2172 FORMAT_MESSAGE_IGNORE_INSERTS,
2173 NULL,
2174 error,
2175 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2176 (LPTSTR) &message,
2177 0, NULL );
2178
c33efc48 2179 RETURN_VALUE("%s", message);
74510d4b 2180#else
c33efc48 2181 RETURN_VALUE("%s", strerror(errno));
74510d4b
ML
2182#endif
2183}
2184
74510d4b
ML
2185void sp_free_error_message(char *message)
2186{
c33efc48
ML
2187 TRACE("%s", message);
2188
74510d4b
ML
2189#ifdef _WIN32
2190 LocalFree(message);
64eec30d
ML
2191#else
2192 (void)message;
74510d4b 2193#endif
c33efc48
ML
2194
2195 RETURN();
74510d4b 2196}
863b35e6
ML
2197
2198void sp_set_debug_handler(void (*handler)(const char *format, ...))
2199{
c33efc48
ML
2200 TRACE("%p", handler);
2201
863b35e6 2202 sp_debug_handler = handler;
c33efc48
ML
2203
2204 RETURN();
863b35e6
ML
2205}
2206
2207void sp_default_debug_handler(const char *format, ...)
2208{
2209 va_list args;
2210 va_start(args, format);
2211 if (getenv("LIBSERIALPORT_DEBUG")) {
dd7742fb 2212 fputs("sp: ", stderr);
863b35e6
ML
2213 vfprintf(stderr, format, args);
2214 }
2215 va_end(args);
2216}