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