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