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