]> sigrok.org Git - libserialport.git/blob - serialport.c
Minor cosmetics.
[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, %p", port, result_ptr);
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                 DEBUG("Null port");
266                 RETURN();
267         }
268
269         DEBUG("Freeing port structure");
270
271         if (port->name)
272                 free(port->name);
273
274         free(port);
275
276         RETURN();
277 }
278
279 static struct sp_port **list_append(struct sp_port **list, const char *portname)
280 {
281         void *tmp;
282         unsigned int count;
283
284         for (count = 0; list[count]; count++);
285         if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
286                 goto fail;
287         list = tmp;
288         if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
289                 goto fail;
290         list[count + 1] = NULL;
291         return list;
292
293 fail:
294         sp_free_port_list(list);
295         return NULL;
296 }
297
298 enum sp_return sp_list_ports(struct sp_port ***list_ptr)
299 {
300         struct sp_port **list;
301         int ret = SP_ERR_SUPP;
302
303         TRACE("%p", list_ptr);
304
305         if (!list_ptr)
306                 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
307
308         DEBUG("Enumerating ports");
309
310         if (!(list = malloc(sizeof(struct sp_port **))))
311                 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
312
313         list[0] = NULL;
314
315 #ifdef _WIN32
316         HKEY key;
317         TCHAR *value, *data;
318         DWORD max_value_len, max_data_size, max_data_len;
319         DWORD value_len, data_size, data_len;
320         DWORD type, index = 0;
321         char *name;
322         int name_len;
323
324         ret = SP_OK;
325
326         DEBUG("Opening registry key");
327         if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
328                         0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS) {
329                 SET_FAIL(ret, "RegOpenKeyEx() failed");
330                 goto out_done;
331         }
332         DEBUG("Querying registry key value and data sizes");
333         if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
334                                 &max_value_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS) {
335                 SET_FAIL(ret, "RegQueryInfoKey() failed");
336                 goto out_close;
337         }
338         max_data_len = max_data_size / sizeof(TCHAR);
339         if (!(value = malloc((max_value_len + 1) * sizeof(TCHAR)))) {
340                 SET_ERROR(ret, SP_ERR_MEM, "registry value malloc failed");
341                 goto out_close;
342         }
343         if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR)))) {
344                 SET_ERROR(ret, SP_ERR_MEM, "registry data malloc failed");
345                 goto out_free_value;
346         }
347         DEBUG("Iterating over values");
348         while (
349                 value_len = max_value_len + 1,
350                 data_size = max_data_size,
351                 RegEnumValue(key, index, value, &value_len,
352                         NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
353         {
354                 data_len = data_size / sizeof(TCHAR);
355                 data[data_len] = '\0';
356 #ifdef UNICODE
357                 name_len = WideCharToMultiByte(CP_ACP, 0, data, -1, NULL, 0, NULL, NULL)
358 #else
359                 name_len = data_len + 1;
360 #endif
361                 if (!(name = malloc(name_len))) {
362                         SET_ERROR(ret, SP_ERR_MEM, "registry port name malloc failed");
363                         goto out;
364                 }
365 #ifdef UNICODE
366                 WideCharToMultiByte(CP_ACP, 0, data, -1, name, name_len, NULL, NULL);
367 #else
368                 strcpy(name, data);
369 #endif
370                 if (type == REG_SZ) {
371                         DEBUG("Found port %s", name);
372                         if (!(list = list_append(list, name))) {
373                                 SET_ERROR(ret, SP_ERR_MEM, "list append failed");
374                                 goto out;
375                         }
376                 }
377                 index++;
378         }
379 out:
380         free(data);
381 out_free_value:
382         free(value);
383 out_close:
384         RegCloseKey(key);
385 out_done:
386 #endif
387 #ifdef __APPLE__
388         mach_port_t master;
389         CFMutableDictionaryRef classes;
390         io_iterator_t iter;
391         char *path;
392         io_object_t port;
393         CFTypeRef cf_path;
394         Boolean result;
395
396         ret = SP_OK;
397
398         DEBUG("Getting IOKit master port");
399         if (IOMasterPort(MACH_PORT_NULL, &master) != KERN_SUCCESS) {
400                 SET_FAIL(ret, "IOMasterPort() failed");
401                 goto out_done;
402         }
403
404         DEBUG("Creating matching dictionary");
405         if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue))) {
406                 SET_FAIL(ret, "IOServiceMatching() failed");
407                 goto out_done;
408         }
409
410         CFDictionarySetValue(classes,
411                         CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
412
413         DEBUG("Getting matching services");
414         if (IOServiceGetMatchingServices(master, classes, &iter) != KERN_SUCCESS) {
415                 SET_FAIL(ret, "IOServiceGetMatchingServices() failed");
416                 goto out_done;
417         }
418
419         if (!(path = malloc(PATH_MAX))) {
420                 SET_ERROR(ret, SP_ERR_MEM, "device path malloc failed");
421                 goto out_release;
422         }
423
424         DEBUG("Iterating over results");
425         while ((port = IOIteratorNext(iter))) {
426                 cf_path = IORegistryEntryCreateCFProperty(port,
427                                 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
428                 if (cf_path) {
429                         result = CFStringGetCString(cf_path,
430                                         path, PATH_MAX, kCFStringEncodingASCII);
431                         CFRelease(cf_path);
432                         if (result) {
433                                 DEBUG("Found port %s", path);
434                                 if (!(list = list_append(list, path))) {
435                                         SET_ERROR(ret, SP_ERR_MEM, "list append failed");
436                                         IOObjectRelease(port);
437                                         goto out;
438                                 }
439                         }
440                 }
441                 IOObjectRelease(port);
442         }
443 out:
444         free(path);
445 out_release:
446         IOObjectRelease(iter);
447 out_done:
448 #endif
449 #ifdef __linux__
450         struct udev *ud;
451         struct udev_enumerate *ud_enumerate;
452         struct udev_list_entry *ud_list;
453         struct udev_list_entry *ud_entry;
454         const char *path;
455         struct udev_device *ud_dev, *ud_parent;
456         const char *name;
457         const char *driver;
458         int fd, ioctl_result;
459         struct serial_struct serial_info;
460
461         ret = SP_OK;
462
463         DEBUG("Enumerating tty devices");
464         ud = udev_new();
465         ud_enumerate = udev_enumerate_new(ud);
466         udev_enumerate_add_match_subsystem(ud_enumerate, "tty");
467         udev_enumerate_scan_devices(ud_enumerate);
468         ud_list = udev_enumerate_get_list_entry(ud_enumerate);
469         DEBUG("Iterating over results");
470         udev_list_entry_foreach(ud_entry, ud_list) {
471                 path = udev_list_entry_get_name(ud_entry);
472                 DEBUG("Found device %s", path);
473                 ud_dev = udev_device_new_from_syspath(ud, path);
474                 /* If there is no parent device, this is a virtual tty. */
475                 ud_parent = udev_device_get_parent(ud_dev);
476                 if (ud_parent == NULL) {
477                         DEBUG("No parent device, assuming virtual tty");
478                         udev_device_unref(ud_dev);
479                         continue;
480                 }
481                 name = udev_device_get_devnode(ud_dev);
482                 /* The serial8250 driver has a hardcoded number of ports.
483                  * The only way to tell which actually exist on a given system
484                  * is to try to open them and make an ioctl call. */
485                 driver = udev_device_get_driver(ud_parent);
486                 if (driver && !strcmp(driver, "serial8250")) {
487                         DEBUG("serial8250 device, attempting to open");
488                         if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY)) < 0) {
489                                 DEBUG("open failed, skipping");
490                                 goto skip;
491                         }
492                         ioctl_result = ioctl(fd, TIOCGSERIAL, &serial_info);
493                         close(fd);
494                         if (ioctl_result != 0) {
495                                 DEBUG("ioctl failed, skipping");
496                                 goto skip;
497                         }
498                         if (serial_info.type == PORT_UNKNOWN) {
499                                 DEBUG("port type is unknown, skipping");
500                                 goto skip;
501                         }
502                 }
503                 DEBUG("Found port %s", name);
504                 list = list_append(list, name);
505 skip:
506                 udev_device_unref(ud_dev);
507                 if (!list) {
508                         SET_ERROR(ret, SP_ERR_MEM, "list append failed");
509                         goto out;
510                 }
511         }
512 out:
513         udev_enumerate_unref(ud_enumerate);
514         udev_unref(ud);
515 #endif
516
517         switch (ret) {
518         case SP_OK:
519                 *list_ptr = list;
520                 RETURN_OK();
521         case SP_ERR_SUPP:
522                 DEBUG_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform.");
523         default:
524                 if (list)
525                         sp_free_port_list(list);
526                 *list_ptr = NULL;
527                 return ret;
528         }
529 }
530
531 void sp_free_port_list(struct sp_port **list)
532 {
533         unsigned int i;
534
535         TRACE("%p", list);
536
537         if (!list) {
538                 DEBUG("Null list");
539                 RETURN();
540         }
541
542         DEBUG("Freeing port list");
543
544         for (i = 0; list[i]; i++)
545                 sp_free_port(list[i]);
546         free(list);
547
548         RETURN();
549 }
550
551 #define CHECK_PORT() do { \
552         if (port == NULL) \
553                 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
554         if (port->name == NULL) \
555                 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
556 } while (0)
557 #ifdef _WIN32
558 #define CHECK_PORT_HANDLE() do { \
559         if (port->hdl == INVALID_HANDLE_VALUE) \
560                 RETURN_ERROR(SP_ERR_ARG, "Invalid port handle"); \
561 } while (0)
562 #else
563 #define CHECK_PORT_HANDLE() do { \
564         if (port->fd < 0) \
565                 RETURN_ERROR(SP_ERR_ARG, "Invalid port fd"); \
566 } while (0)
567 #endif
568 #define CHECK_OPEN_PORT() do { \
569         CHECK_PORT(); \
570         CHECK_PORT_HANDLE(); \
571 } while (0)
572
573 enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
574 {
575         struct port_data data;
576         struct sp_port_config config;
577         enum sp_return ret;
578
579         TRACE("%p, 0x%x", port, flags);
580
581         CHECK_PORT();
582
583         if (flags > (SP_MODE_READ | SP_MODE_WRITE | SP_MODE_NONBLOCK))
584                 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
585
586         DEBUG("Opening port %s", port->name);
587
588         port->nonblocking = (flags & SP_MODE_NONBLOCK) ? 1 : 0;
589
590 #ifdef _WIN32
591         DWORD desired_access = 0, flags_and_attributes = 0;
592         COMMTIMEOUTS timeouts;
593         char *escaped_port_name;
594
595         /* Prefix port name with '\\.\' to work with ports above COM9. */
596         if (!(escaped_port_name = malloc(strlen(port->name + 5))))
597                 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
598         sprintf(escaped_port_name, "\\\\.\\%s", port->name);
599
600         /* Map 'flags' to the OS-specific settings. */
601         flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
602         if (flags & SP_MODE_READ)
603                 desired_access |= GENERIC_READ;
604         if (flags & SP_MODE_WRITE)
605                 desired_access |= GENERIC_WRITE;
606         if (flags & SP_MODE_NONBLOCK)
607                 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
608
609         port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
610                          OPEN_EXISTING, flags_and_attributes, 0);
611
612         free(escaped_port_name);
613
614         if (port->hdl == INVALID_HANDLE_VALUE)
615                 RETURN_FAIL("CreateFile() failed");
616
617         /* All timeouts disabled. */
618         timeouts.ReadIntervalTimeout = 0;
619         timeouts.ReadTotalTimeoutMultiplier = 0;
620         timeouts.ReadTotalTimeoutConstant = 0;
621         timeouts.WriteTotalTimeoutMultiplier = 0;
622         timeouts.WriteTotalTimeoutConstant = 0;
623
624         if (port->nonblocking) {
625                 /* Set read timeout such that all reads return immediately. */
626                 timeouts.ReadIntervalTimeout = MAXDWORD;
627                 /* Prepare OVERLAPPED structure for non-blocking writes. */
628                 memset(&port->write_ovl, 0, sizeof(port->write_ovl));
629                 if (!(port->write_ovl.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL))) {
630                         sp_close(port);
631                         RETURN_FAIL("CreateEvent() failed");
632                 }
633                 port->writing = FALSE;
634         }
635
636         if (SetCommTimeouts(port->hdl, &timeouts) == 0) {
637                 sp_close(port);
638                 RETURN_FAIL("SetCommTimeouts() failed");
639         }
640 #else
641         int flags_local = 0;
642
643         /* Map 'flags' to the OS-specific settings. */
644         if (flags & (SP_MODE_READ | SP_MODE_WRITE))
645                 flags_local |= O_RDWR;
646         else if (flags & SP_MODE_READ)
647                 flags_local |= O_RDONLY;
648         else if (flags & SP_MODE_WRITE)
649                 flags_local |= O_WRONLY;
650         if (flags & SP_MODE_NONBLOCK)
651                 flags_local |= O_NONBLOCK;
652
653         if ((port->fd = open(port->name, flags_local)) < 0)
654                 RETURN_FAIL("open() failed");
655 #endif
656
657         ret = get_config(port, &data, &config);
658
659         if (ret < 0) {
660                 sp_close(port);
661                 RETURN_CODEVAL(ret);
662         }
663
664         /* Set sane port settings. */
665 #ifdef _WIN32
666         data.dcb.fBinary = TRUE;
667         data.dcb.fDsrSensitivity = FALSE;
668         data.dcb.fErrorChar = FALSE;
669         data.dcb.fNull = FALSE;
670         data.dcb.fAbortOnError = TRUE;
671 #else
672         /* Turn off all fancy termios tricks, give us a raw channel. */
673         data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
674 #ifdef IUCLC
675         data.term.c_iflag &= ~IUCLC;
676 #endif
677         data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
678 #ifdef OLCUC
679         data.term.c_oflag &= ~OLCUC;
680 #endif
681 #ifdef NLDLY
682         data.term.c_oflag &= ~NLDLY;
683 #endif
684 #ifdef CRDLY
685         data.term.c_oflag &= ~CRDLY;
686 #endif
687 #ifdef TABDLY
688         data.term.c_oflag &= ~TABDLY;
689 #endif
690 #ifdef BSDLY
691         data.term.c_oflag &= ~BSDLY;
692 #endif
693 #ifdef VTDLY
694         data.term.c_oflag &= ~VTDLY;
695 #endif
696 #ifdef FFDLY
697         data.term.c_oflag &= ~FFDLY;
698 #endif
699 #ifdef OFILL
700         data.term.c_oflag &= ~OFILL;
701 #endif
702         data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
703         data.term.c_cc[VMIN] = 0;
704         data.term.c_cc[VTIME] = 0;
705
706         /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
707         data.term.c_cflag |= (CLOCAL | CREAD | HUPCL);
708 #endif
709
710         ret = set_config(port, &data, &config);
711
712         if (ret < 0) {
713                 sp_close(port);
714                 RETURN_CODEVAL(ret);
715         }
716
717         RETURN_OK();
718 }
719
720 enum sp_return sp_close(struct sp_port *port)
721 {
722         TRACE("%p", port);
723
724         CHECK_OPEN_PORT();
725
726         DEBUG("Closing port %s", port->name);
727
728 #ifdef _WIN32
729         /* Returns non-zero upon success, 0 upon failure. */
730         if (CloseHandle(port->hdl) == 0)
731                 RETURN_FAIL("CloseHandle() failed");
732         port->hdl = INVALID_HANDLE_VALUE;
733         if (port->nonblocking) {
734                 /* Close event handle created for overlapped writes. */
735                 if (CloseHandle(port->write_ovl.hEvent) == 0)
736                         RETURN_FAIL("CloseHandle() failed");
737         }
738 #else
739         /* Returns 0 upon success, -1 upon failure. */
740         if (close(port->fd) == -1)
741                 RETURN_FAIL("close() failed");
742         port->fd = -1;
743 #endif
744
745         RETURN_OK();
746 }
747
748 enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
749 {
750         TRACE("%p, 0x%x", port, buffers);
751
752         CHECK_OPEN_PORT();
753
754         if (buffers > SP_BUF_BOTH)
755                 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
756
757         const char *buffer_names[] = {"no", "input", "output", "both"};
758
759         DEBUG("Flushing %s buffers on port %s", buffer_names[buffers], port->name);
760
761 #ifdef _WIN32
762         DWORD flags = 0;
763         if (buffers & SP_BUF_INPUT)
764                 flags |= PURGE_RXCLEAR;
765         if (buffers & SP_BUF_OUTPUT)
766                 flags |= PURGE_TXCLEAR;
767
768         /* Returns non-zero upon success, 0 upon failure. */
769         if (PurgeComm(port->hdl, flags) == 0)
770                 RETURN_FAIL("PurgeComm() failed");
771 #else
772         int flags = 0;
773         if (buffers & SP_BUF_BOTH)
774                 flags = TCIOFLUSH;
775         else if (buffers & SP_BUF_INPUT)
776                 flags = TCIFLUSH;
777         else if (buffers & SP_BUF_OUTPUT)
778                 flags = TCOFLUSH;
779
780         /* Returns 0 upon success, -1 upon failure. */
781         if (tcflush(port->fd, flags) < 0)
782                 RETURN_FAIL("tcflush() failed");
783 #endif
784         RETURN_OK();
785 }
786
787 enum sp_return sp_drain(struct sp_port *port)
788 {
789         TRACE("%p", port);
790
791         CHECK_OPEN_PORT();
792
793         DEBUG("Draining port %s", port->name);
794
795 #ifdef _WIN32
796         /* Returns non-zero upon success, 0 upon failure. */
797         if (FlushFileBuffers(port->hdl) == 0)
798                 RETURN_FAIL("FlushFileBuffers() failed");
799 #else
800         /* Returns 0 upon success, -1 upon failure. */
801         if (tcdrain(port->fd) < 0)
802                 RETURN_FAIL("tcdrain() failed");
803 #endif
804
805         RETURN_OK();
806 }
807
808 enum sp_return sp_write(struct sp_port *port, const void *buf, size_t count)
809 {
810         TRACE("%p, %p, %d", port, buf, count);
811
812         CHECK_OPEN_PORT();
813
814         if (!buf)
815                 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
816
817         DEBUG("Writing up to %d bytes to port %s", count, port->name);
818
819         if (count == 0)
820                 RETURN_VALUE("0", 0);
821
822 #ifdef _WIN32
823         DWORD written = 0;
824         BYTE *ptr = (BYTE *) buf;
825
826         if (port->nonblocking) {
827                 /* Non-blocking write. */
828
829                 /* Check whether previous write is complete. */
830                 if (port->writing) {
831                         if (HasOverlappedIoCompleted(&port->write_ovl)) {
832                                 DEBUG("Previous write completed");
833                                 port->writing = 0;
834                         } else {
835                                 DEBUG("Previous write not complete");
836                                 /* Can't take a new write until the previous one finishes. */
837                                 RETURN_VALUE("0", 0);
838                         }
839                 }
840
841                 /* Keep writing data until the OS has to actually start an async IO for it.
842                  * At that point we know the buffer is full. */
843                 while (written < count)
844                 {
845                         /* Copy first byte of user buffer. */
846                         port->pending_byte = *ptr++;
847
848                         /* Start asynchronous write. */
849                         if (WriteFile(port->hdl, &port->pending_byte, 1, NULL, &port->write_ovl) == 0) {
850                                 if (GetLastError() == ERROR_IO_PENDING) {
851                                         DEBUG("Asynchronous write started");
852                                         port->writing = 1;
853                                         RETURN_VALUE("%d", ++written);
854                                 } else {
855                                         /* Actual failure of some kind. */
856                                         RETURN_FAIL("WriteFile() failed");
857                                 }
858                         } else {
859                                 DEBUG("Single byte written immediately.");
860                                 written++;
861                         }
862                 }
863
864                 DEBUG("All bytes written immediately.");
865
866         } else {
867                 /* Blocking write. */
868                 if (WriteFile(port->hdl, buf, count, &written, NULL) == 0) {
869                         RETURN_FAIL("WriteFile() failed");
870                 }
871         }
872
873         RETURN_VALUE("%d", written);
874 #else
875         /* Returns the number of bytes written, or -1 upon failure. */
876         ssize_t written = write(port->fd, buf, count);
877
878         if (written < 0)
879                 RETURN_FAIL("write() failed");
880         else
881                 RETURN_VALUE("%d", written);
882 #endif
883 }
884
885 enum sp_return sp_read(struct sp_port *port, void *buf, size_t count)
886 {
887         TRACE("%p, %p, %d", port, buf, count);
888
889         CHECK_OPEN_PORT();
890
891         if (!buf)
892                 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
893
894         DEBUG("Reading up to %d bytes from port %s", count, port->name);
895
896 #ifdef _WIN32
897         DWORD bytes_read = 0;
898
899         /* Returns non-zero upon success, 0 upon failure. */
900         if (ReadFile(port->hdl, buf, count, &bytes_read, NULL) == 0)
901                 RETURN_FAIL("ReadFile() failed");
902         RETURN_VALUE("%d", bytes_read);
903 #else
904         ssize_t bytes_read;
905
906         /* Returns the number of bytes read, or -1 upon failure. */
907         if ((bytes_read = read(port->fd, buf, count)) < 0) {
908                 if (port->nonblocking && errno == EAGAIN)
909                         /* Port is opened in nonblocking mode and there are no bytes available. */
910                         bytes_read = 0;
911                 else
912                         /* This is an actual failure. */
913                         RETURN_FAIL("read() failed");
914         }
915         RETURN_VALUE("%d", bytes_read);
916 #endif
917 }
918
919 #ifdef __linux__
920 static enum sp_return get_baudrate(int fd, int *baudrate)
921 {
922         void *data;
923
924         TRACE("%d, %p", fd, baudrate);
925
926         DEBUG("Getting baud rate");
927
928         if (!(data = malloc(get_termios_size())))
929                 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
930
931         if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
932                 free(data);
933                 RETURN_FAIL("getting termios failed");
934         }
935
936         *baudrate = get_termios_speed(data);
937
938         free(data);
939
940         RETURN_OK();
941 }
942
943 static enum sp_return set_baudrate(int fd, int baudrate)
944 {
945         void *data;
946
947         TRACE("%d, %d", fd, baudrate);
948
949         DEBUG("Getting baud rate");
950
951         if (!(data = malloc(get_termios_size())))
952                 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
953
954         if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
955                 free(data);
956                 RETURN_FAIL("getting termios failed");
957         }
958
959         DEBUG("Setting baud rate");
960
961         set_termios_speed(data, baudrate);
962
963         if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
964                 free(data);
965                 RETURN_FAIL("setting termios failed");
966         }
967
968         free(data);
969
970         RETURN_OK();
971 }
972
973 #ifdef USE_TERMIOX
974 static enum sp_return get_flow(int fd, int *flow)
975 {
976         void *data;
977
978         TRACE("%d, %p", fd, flow);
979
980         DEBUG("Getting advanced flow control");
981
982         if (!(data = malloc(get_termiox_size())))
983                 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
984
985         if (ioctl(fd, TCGETX, data) < 0) {
986                 free(data);
987                 RETURN_FAIL("getting termiox failed");
988         }
989
990         *flow = get_termiox_flow(data);
991
992         free(data);
993
994         RETURN_OK();
995 }
996
997 static enum sp_return set_flow(int fd, int flow)
998 {
999         void *data;
1000
1001         TRACE("%d, %d", fd, flow);
1002
1003         DEBUG("Getting advanced flow control");
1004
1005         if (!(data = malloc(get_termiox_size())))
1006                 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1007
1008         if (ioctl(fd, TCGETX, data) < 0) {
1009                 free(data);
1010                 RETURN_FAIL("getting termiox failed");
1011         }
1012
1013         DEBUG("Setting advanced flow control");
1014
1015         set_termiox_flow(data, flow);
1016
1017         if (ioctl(fd, TCSETX, data) < 0) {
1018                 free(data);
1019                 RETURN_FAIL("setting termiox failed");
1020         }
1021
1022         free(data);
1023
1024         RETURN_OK();
1025 }
1026 #endif /* USE_TERMIOX */
1027 #endif /* __linux__ */
1028
1029 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1030         struct sp_port_config *config)
1031 {
1032         unsigned int i;
1033
1034         TRACE("%p, %p, %p", port, data, config);
1035
1036         DEBUG("Getting configuration for port %s", port->name);
1037
1038 #ifdef _WIN32
1039         if (!GetCommState(port->hdl, &data->dcb))
1040                 RETURN_FAIL("GetCommState() failed");
1041
1042         for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1043                 if (data->dcb.BaudRate == std_baudrates[i].index) {
1044                         config->baudrate = std_baudrates[i].value;
1045                         break;
1046                 }
1047         }
1048
1049         if (i == NUM_STD_BAUDRATES)
1050                 /* BaudRate field can be either an index or a custom baud rate. */
1051                 config->baudrate = data->dcb.BaudRate;
1052
1053         config->bits = data->dcb.ByteSize;
1054
1055         if (data->dcb.fParity)
1056                 switch (data->dcb.Parity) {
1057                 case NOPARITY:
1058                         config->parity = SP_PARITY_NONE;
1059                         break;
1060                 case ODDPARITY:
1061                         config->parity = SP_PARITY_ODD;
1062                         break;
1063                 case EVENPARITY:
1064                         config->parity = SP_PARITY_EVEN;
1065                         break;
1066                 case MARKPARITY:
1067                         config->parity = SP_PARITY_MARK;
1068                         break;
1069                 case SPACEPARITY:
1070                         config->parity = SP_PARITY_SPACE;
1071                         break;
1072                 default:
1073                         config->parity = -1;
1074                 }
1075         else
1076                 config->parity = SP_PARITY_NONE;
1077
1078         switch (data->dcb.StopBits) {
1079         case ONESTOPBIT:
1080                 config->stopbits = 1;
1081                 break;
1082         case TWOSTOPBITS:
1083                 config->stopbits = 2;
1084                 break;
1085         default:
1086                 config->stopbits = -1;
1087         }
1088
1089         switch (data->dcb.fRtsControl) {
1090         case RTS_CONTROL_DISABLE:
1091                 config->rts = SP_RTS_OFF;
1092                 break;
1093         case RTS_CONTROL_ENABLE:
1094                 config->rts = SP_RTS_ON;
1095                 break;
1096         case RTS_CONTROL_HANDSHAKE:
1097                 config->rts = SP_RTS_FLOW_CONTROL;
1098                 break;
1099         default:
1100                 config->rts = -1;
1101         }
1102
1103         config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1104
1105         switch (data->dcb.fDtrControl) {
1106         case DTR_CONTROL_DISABLE:
1107                 config->dtr = SP_DTR_OFF;
1108                 break;
1109         case DTR_CONTROL_ENABLE:
1110                 config->dtr = SP_DTR_ON;
1111                 break;
1112         case DTR_CONTROL_HANDSHAKE:
1113                 config->dtr = SP_DTR_FLOW_CONTROL;
1114                 break;
1115         default:
1116                 config->dtr = -1;
1117         }
1118
1119         config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1120
1121         if (data->dcb.fInX) {
1122                 if (data->dcb.fOutX)
1123                         config->xon_xoff = SP_XONXOFF_INOUT;
1124                 else
1125                         config->xon_xoff = SP_XONXOFF_IN;
1126         } else {
1127                 if (data->dcb.fOutX)
1128                         config->xon_xoff = SP_XONXOFF_OUT;
1129                 else
1130                         config->xon_xoff = SP_XONXOFF_DISABLED;
1131         }
1132
1133 #else // !_WIN32
1134
1135         if (tcgetattr(port->fd, &data->term) < 0)
1136                 RETURN_FAIL("tcgetattr() failed");
1137
1138         if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
1139                 RETURN_FAIL("TIOCMGET ioctl failed");
1140
1141 #ifdef USE_TERMIOX
1142         int ret = get_flow(port->fd, &data->flow);
1143
1144         if (ret == SP_ERR_FAIL && errno == EINVAL)
1145                 data->termiox_supported = 0;
1146         else if (ret < 0)
1147                 RETURN_CODEVAL(ret);
1148         else
1149                 data->termiox_supported = 1;
1150 #else
1151         data->termiox_supported = 0;
1152 #endif
1153
1154         for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1155                 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
1156                         config->baudrate = std_baudrates[i].value;
1157                         break;
1158                 }
1159         }
1160
1161         if (i == NUM_STD_BAUDRATES) {
1162 #ifdef __APPLE__
1163                 config->baudrate = (int)data->term.c_ispeed;
1164 #elif defined(__linux__)
1165                 TRY(get_baudrate(port->fd, &config->baudrate));
1166 #else
1167                 config->baudrate = -1;
1168 #endif
1169         }
1170
1171         switch (data->term.c_cflag & CSIZE) {
1172         case CS8:
1173                 config->bits = 8;
1174                 break;
1175         case CS7:
1176                 config->bits = 7;
1177                 break;
1178         case CS6:
1179                 config->bits = 6;
1180                 break;
1181         case CS5:
1182                 config->bits = 5;
1183                 break;
1184         default:
1185                 config->bits = -1;
1186         }
1187
1188         if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1189                 config->parity = SP_PARITY_NONE;
1190         else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1191                 config->parity = -1;
1192 #ifdef CMSPAR
1193         else if (data->term.c_cflag & CMSPAR)
1194                 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
1195 #endif
1196         else
1197                 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1198
1199         config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1200
1201         if (data->term.c_cflag & CRTSCTS) {
1202                 config->rts = SP_RTS_FLOW_CONTROL;
1203                 config->cts = SP_CTS_FLOW_CONTROL;
1204         } else {
1205                 if (data->termiox_supported && data->flow & RTS_FLOW)
1206                         config->rts = SP_RTS_FLOW_CONTROL;
1207                 else
1208                         config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1209
1210                 config->cts = (data->termiox_supported && data->flow & CTS_FLOW) ?
1211                         SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1212         }
1213
1214         if (data->termiox_supported && data->flow & DTR_FLOW)
1215                 config->dtr = SP_DTR_FLOW_CONTROL;
1216         else
1217                 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1218
1219         config->dsr = (data->termiox_supported && data->flow & DSR_FLOW) ?
1220                 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1221
1222         if (data->term.c_iflag & IXOFF) {
1223                 if (data->term.c_iflag & IXON)
1224                         config->xon_xoff = SP_XONXOFF_INOUT;
1225                 else
1226                         config->xon_xoff = SP_XONXOFF_IN;
1227         } else {
1228                 if (data->term.c_iflag & IXON)
1229                         config->xon_xoff = SP_XONXOFF_OUT;
1230                 else
1231                         config->xon_xoff = SP_XONXOFF_DISABLED;
1232         }
1233 #endif
1234
1235         RETURN_OK();
1236 }
1237
1238 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1239         const struct sp_port_config *config)
1240 {
1241         unsigned int i;
1242 #ifdef __APPLE__
1243         BAUD_TYPE baud_nonstd;
1244
1245         baud_nonstd = B0;
1246 #endif
1247 #ifdef __linux__
1248         int baud_nonstd = 0;
1249 #endif
1250
1251         TRACE("%p, %p, %p", port, data, config);
1252
1253         DEBUG("Setting configuration for port %s", port->name);
1254
1255 #ifdef _WIN32
1256         if (config->baudrate >= 0) {
1257                 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1258                         if (config->baudrate == std_baudrates[i].value) {
1259                                 data->dcb.BaudRate = std_baudrates[i].index;
1260                                 break;
1261                         }
1262                 }
1263
1264                 if (i == NUM_STD_BAUDRATES)
1265                         data->dcb.BaudRate = config->baudrate;
1266         }
1267
1268         if (config->bits >= 0)
1269                 data->dcb.ByteSize = config->bits;
1270
1271         if (config->parity >= 0) {
1272                 switch (config->parity) {
1273                 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
1274                 case SP_PARITY_NONE:
1275                         data->dcb.Parity = NOPARITY;
1276                         break;
1277                 case SP_PARITY_ODD:
1278                         data->dcb.Parity = ODDPARITY;
1279                         break;
1280                 case SP_PARITY_EVEN:
1281                         data->dcb.Parity = EVENPARITY;
1282                         break;
1283                 case SP_PARITY_MARK:
1284                         data->dcb.Parity = MARKPARITY;
1285                         break;
1286                 case SP_PARITY_SPACE:
1287                         data->dcb.Parity = SPACEPARITY;
1288                         break;
1289                 default:
1290                         RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1291                 }
1292         }
1293
1294         if (config->stopbits >= 0) {
1295                 switch (config->stopbits) {
1296                 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1297                 case 1:
1298                         data->dcb.StopBits = ONESTOPBIT;
1299                         break;
1300                 case 2:
1301                         data->dcb.StopBits = TWOSTOPBITS;
1302                         break;
1303                 default:
1304                         RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
1305                 }
1306         }
1307
1308         if (config->rts >= 0) {
1309                 switch (config->rts) {
1310                 case SP_RTS_OFF:
1311                         data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
1312                         break;
1313                 case SP_RTS_ON:
1314                         data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
1315                         break;
1316                 case SP_RTS_FLOW_CONTROL:
1317                         data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
1318                         break;
1319                 default:
1320                         RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
1321                 }
1322         }
1323
1324         if (config->cts >= 0) {
1325                 switch (config->cts) {
1326                 case SP_CTS_IGNORE:
1327                         data->dcb.fOutxCtsFlow = FALSE;
1328                         break;
1329                 case SP_CTS_FLOW_CONTROL:
1330                         data->dcb.fOutxCtsFlow = TRUE;
1331                         break;
1332                 default:
1333                         RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
1334                 }
1335         }
1336
1337         if (config->dtr >= 0) {
1338                 switch (config->dtr) {
1339                 case SP_DTR_OFF:
1340                         data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
1341                         break;
1342                 case SP_DTR_ON:
1343                         data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
1344                         break;
1345                 case SP_DTR_FLOW_CONTROL:
1346                         data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
1347                         break;
1348                 default:
1349                         RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
1350                 }
1351         }
1352
1353         if (config->dsr >= 0) {
1354                 switch (config->dsr) {
1355                 case SP_DSR_IGNORE:
1356                         data->dcb.fOutxDsrFlow = FALSE;
1357                         break;
1358                 case SP_DSR_FLOW_CONTROL:
1359                         data->dcb.fOutxDsrFlow = TRUE;
1360                         break;
1361                 default:
1362                         RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
1363                 }
1364         }
1365
1366         if (config->xon_xoff >= 0) {
1367                 switch (config->xon_xoff) {
1368                 case SP_XONXOFF_DISABLED:
1369                         data->dcb.fInX = FALSE;
1370                         data->dcb.fOutX = FALSE;
1371                         break;
1372                 case SP_XONXOFF_IN:
1373                         data->dcb.fInX = TRUE;
1374                         data->dcb.fOutX = FALSE;
1375                         break;
1376                 case SP_XONXOFF_OUT:
1377                         data->dcb.fInX = FALSE;
1378                         data->dcb.fOutX = TRUE;
1379                         break;
1380                 case SP_XONXOFF_INOUT:
1381                         data->dcb.fInX = TRUE;
1382                         data->dcb.fOutX = TRUE;
1383                         break;
1384                 default:
1385                         RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
1386                 }
1387         }
1388
1389         if (!SetCommState(port->hdl, &data->dcb))
1390                 RETURN_FAIL("SetCommState() failed");
1391
1392 #else /* !_WIN32 */
1393
1394         int controlbits;
1395
1396         if (config->baudrate >= 0) {
1397                 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1398                         if (config->baudrate == std_baudrates[i].value) {
1399                                 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
1400                                         RETURN_FAIL("cfsetospeed() failed");
1401
1402                                 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
1403                                         RETURN_FAIL("cfsetispeed() failed");
1404                                 break;
1405                         }
1406                 }
1407
1408                 /* Non-standard baud rate */
1409                 if (i == NUM_STD_BAUDRATES) {
1410 #ifdef __APPLE__
1411                         /* Set "dummy" baud rate. */
1412                         if (cfsetspeed(&data->term, B9600) < 0)
1413                                 RETURN_FAIL("cfsetspeed() failed");
1414                         baud_nonstd = config->baudrate;
1415 #elif defined(__linux__)
1416                         baud_nonstd = 1;
1417 #else
1418                         RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
1419 #endif
1420                 }
1421         }
1422
1423         if (config->bits >= 0) {
1424                 data->term.c_cflag &= ~CSIZE;
1425                 switch (config->bits) {
1426                 case 8:
1427                         data->term.c_cflag |= CS8;
1428                         break;
1429                 case 7:
1430                         data->term.c_cflag |= CS7;
1431                         break;
1432                 case 6:
1433                         data->term.c_cflag |= CS6;
1434                         break;
1435                 case 5:
1436                         data->term.c_cflag |= CS5;
1437                         break;
1438                 default:
1439                         RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
1440                 }
1441         }
1442
1443         if (config->parity >= 0) {
1444                 data->term.c_iflag &= ~IGNPAR;
1445                 data->term.c_cflag &= ~(PARENB | PARODD);
1446 #ifdef CMSPAR
1447                 data->term.c_cflag &= ~CMSPAR;
1448 #endif
1449                 switch (config->parity) {
1450                 case SP_PARITY_NONE:
1451                         data->term.c_iflag |= IGNPAR;
1452                         break;
1453                 case SP_PARITY_EVEN:
1454                         data->term.c_cflag |= PARENB;
1455                         break;
1456                 case SP_PARITY_ODD:
1457                         data->term.c_cflag |= PARENB | PARODD;
1458                         break;
1459                 case SP_PARITY_MARK:
1460                         data->term.c_cflag |= PARENB | PARODD;
1461 #ifdef CMSPAR
1462                         data->term.c_cflag |= CMSPAR;
1463 #endif
1464                         break;
1465                 case SP_PARITY_SPACE:
1466                         data->term.c_cflag |= PARENB;
1467 #ifdef CMSPAR
1468                         data->term.c_cflag |= CMSPAR;
1469 #endif
1470                         break;
1471                 default:
1472                         RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1473                 }
1474         }
1475
1476         if (config->stopbits >= 0) {
1477                 data->term.c_cflag &= ~CSTOPB;
1478                 switch (config->stopbits) {
1479                 case 1:
1480                         data->term.c_cflag &= ~CSTOPB;
1481                         break;
1482                 case 2:
1483                         data->term.c_cflag |= CSTOPB;
1484                         break;
1485                 default:
1486                         RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
1487                 }
1488         }
1489
1490         if (config->rts >= 0 || config->cts >= 0) {
1491                 if (data->termiox_supported) {
1492                         data->flow &= ~(RTS_FLOW | CTS_FLOW);
1493                         switch (config->rts) {
1494                         case SP_RTS_OFF:
1495                         case SP_RTS_ON:
1496                                 controlbits = TIOCM_RTS;
1497                                 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1498                                         RETURN_FAIL("Setting RTS signal level failed");
1499                                 break;
1500                         case SP_RTS_FLOW_CONTROL:
1501                                 data->flow |= RTS_FLOW;
1502                                 break;
1503                         default:
1504                                 break;
1505                         }
1506                         if (config->cts == SP_CTS_FLOW_CONTROL)
1507                                 data->flow |= CTS_FLOW;
1508
1509                         if (data->flow & (RTS_FLOW | CTS_FLOW))
1510                                 data->term.c_iflag |= CRTSCTS;
1511                         else
1512                                 data->term.c_iflag &= ~CRTSCTS;
1513                 } else {
1514                         /* Asymmetric use of RTS/CTS not supported. */
1515                         if (data->term.c_iflag & CRTSCTS) {
1516                                 /* Flow control can only be disabled for both RTS & CTS together. */
1517                                 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
1518                                         if (config->cts != SP_CTS_IGNORE)
1519                                                 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
1520                                 }
1521                                 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
1522                                         if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
1523                                                 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
1524                                 }
1525                         } else {
1526                                 /* Flow control can only be enabled for both RTS & CTS together. */
1527                                 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
1528                                         ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
1529                                         RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
1530                         }
1531
1532                         if (config->rts >= 0) {
1533                                 if (config->rts == SP_RTS_FLOW_CONTROL) {
1534                                         data->term.c_iflag |= CRTSCTS;
1535                                 } else {
1536                                         controlbits = TIOCM_RTS;
1537                                         if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
1538                                                         &controlbits) < 0)
1539                                                 RETURN_FAIL("Setting RTS signal level failed");
1540                                 }
1541                         }
1542                 }
1543         }
1544
1545         if (config->dtr >= 0 || config->dsr >= 0) {
1546                 if (data->termiox_supported) {
1547                         data->flow &= ~(DTR_FLOW | DSR_FLOW);
1548                         switch (config->dtr) {
1549                         case SP_DTR_OFF:
1550                         case SP_DTR_ON:
1551                                 controlbits = TIOCM_DTR;
1552                                 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1553                                         RETURN_FAIL("Setting DTR signal level failed");
1554                                 break;
1555                         case SP_DTR_FLOW_CONTROL:
1556                                 data->flow |= DTR_FLOW;
1557                                 break;
1558                         default:
1559                                 break;
1560                         }
1561                         if (config->dsr == SP_DSR_FLOW_CONTROL)
1562                                 data->flow |= DSR_FLOW;
1563                 } else {
1564                         /* DTR/DSR flow control not supported. */
1565                         if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
1566                                 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
1567
1568                         if (config->dtr >= 0) {
1569                                 controlbits = TIOCM_DTR;
1570                                 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
1571                                                 &controlbits) < 0)
1572                                         RETURN_FAIL("Setting DTR signal level failed");
1573                         }
1574                 }
1575         }
1576
1577         if (config->xon_xoff >= 0) {
1578                 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
1579                 switch (config->xon_xoff) {
1580                 case SP_XONXOFF_DISABLED:
1581                         break;
1582                 case SP_XONXOFF_IN:
1583                         data->term.c_iflag |= IXOFF;
1584                         break;
1585                 case SP_XONXOFF_OUT:
1586                         data->term.c_iflag |= IXON | IXANY;
1587                         break;
1588                 case SP_XONXOFF_INOUT:
1589                         data->term.c_iflag |= IXON | IXOFF | IXANY;
1590                         break;
1591                 default:
1592                         RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
1593                 }
1594         }
1595
1596         if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
1597                 RETURN_FAIL("tcsetattr() failed");
1598
1599 #ifdef __APPLE__
1600         if (baud_nonstd != B0) {
1601                 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
1602                         RETURN_FAIL("IOSSIOSPEED ioctl failed");
1603                 /* Set baud rates in data->term to correct, but incompatible
1604                  * with tcsetattr() value, same as delivered by tcgetattr(). */
1605                 if (cfsetspeed(&data->term, baud_nonstd) < 0)
1606                         RETURN_FAIL("cfsetspeed() failed");
1607         }
1608 #elif defined(__linux__)
1609         if (baud_nonstd)
1610                 TRY(set_baudrate(port->fd, config->baudrate));
1611 #ifdef USE_TERMIOX
1612         if (data->termiox_supported)
1613                 TRY(set_flow(port->fd, data->flow));
1614 #endif
1615 #endif
1616
1617 #endif /* !_WIN32 */
1618
1619         RETURN_OK();
1620 }
1621
1622 enum sp_return sp_new_config(struct sp_port_config **config_ptr)
1623 {
1624         struct sp_port_config *config;
1625
1626         TRACE("%p", config_ptr);
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, %p", config, x); \
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("sp: ", stderr);
1918                 vfprintf(stderr, format, args);
1919         }
1920         va_end(args);
1921 }