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