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