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