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