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