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