]> sigrok.org Git - libserialport.git/blob - serialport.c
Fix building for Android.
[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 <limits.h>
38 #include <termios.h>
39 #include <sys/ioctl.h>
40 #include <sys/time.h>
41 #include <limits.h>
42 #endif
43 #ifdef __APPLE__
44 #include <IOKit/IOKitLib.h>
45 #include <IOKit/serial/IOSerialKeys.h>
46 #include <IOKit/serial/ioss.h>
47 #include <sys/syslimits.h>
48 #endif
49 #ifdef __linux__
50 #ifdef HAVE_LIBUDEV
51 #include "libudev.h"
52 #endif
53 #ifndef __ANDROID__
54 #include "linux/serial.h"
55 #endif
56 #include "linux_termios.h"
57
58 /* TCGETX/TCSETX is not available everywhere. */
59 #if defined(TCGETX) && defined(TCSETX) && defined(HAVE_TERMIOX)
60 #define USE_TERMIOX
61 #endif
62 #endif
63
64 /* TIOCINQ/TIOCOUTQ is not available everywhere. */
65 #if !defined(TIOCINQ) && defined(FIONREAD)
66 #define TIOCINQ FIONREAD
67 #endif
68 #if !defined(TIOCOUTQ) && defined(FIONWRITE)
69 #define TIOCOUTQ FIONWRITE
70 #endif
71
72 #ifndef _WIN32
73 #include "linux_termios.h"
74 #endif
75
76 #include "libserialport.h"
77
78 struct sp_port {
79         char *name;
80 #ifdef _WIN32
81         HANDLE hdl;
82         COMMTIMEOUTS timeouts;
83         OVERLAPPED write_ovl;
84         OVERLAPPED read_ovl;
85         BYTE pending_byte;
86         BOOL writing;
87 #else
88         int fd;
89 #endif
90 };
91
92 struct sp_port_config {
93         int baudrate;
94         int bits;
95         enum sp_parity parity;
96         int stopbits;
97         enum sp_rts rts;
98         enum sp_cts cts;
99         enum sp_dtr dtr;
100         enum sp_dsr dsr;
101         enum sp_xonxoff xon_xoff;
102 };
103
104 struct port_data {
105 #ifdef _WIN32
106         DCB dcb;
107 #else
108         struct termios term;
109         int controlbits;
110         int termiox_supported;
111         int flow;
112 #endif
113 };
114
115 /* Standard baud rates. */
116 #ifdef _WIN32
117 #define BAUD_TYPE DWORD
118 #define BAUD(n) {CBR_##n, n}
119 #else
120 #define BAUD_TYPE speed_t
121 #define BAUD(n) {B##n, n}
122 #endif
123
124 struct std_baudrate {
125         BAUD_TYPE index;
126         int value;
127 };
128
129 const struct std_baudrate std_baudrates[] = {
130 #ifdef _WIN32
131         /*
132          * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
133          * have documented CBR_* macros.
134          */
135         BAUD(110), BAUD(300), BAUD(600), BAUD(1200), BAUD(2400), BAUD(4800),
136         BAUD(9600), BAUD(14400), BAUD(19200), BAUD(38400), BAUD(57600),
137         BAUD(115200), BAUD(128000), BAUD(256000),
138 #else
139         BAUD(50), BAUD(75), BAUD(110), BAUD(134), BAUD(150), BAUD(200),
140         BAUD(300), BAUD(600), BAUD(1200), BAUD(1800), BAUD(2400), BAUD(4800),
141         BAUD(9600), BAUD(19200), BAUD(38400), BAUD(57600), BAUD(115200),
142         BAUD(230400),
143 #if !defined(__APPLE__) && !defined(__OpenBSD__)
144         BAUD(460800),
145 #endif
146 #endif
147 };
148
149 void (*sp_debug_handler)(const char *format, ...) = sp_default_debug_handler;
150
151 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
152 #define NUM_STD_BAUDRATES ARRAY_SIZE(std_baudrates)
153
154 /* Debug output macros. */
155 #define DEBUG(fmt, ...) do { if (sp_debug_handler) sp_debug_handler(fmt ".\n", ##__VA_ARGS__); } while (0)
156 #define DEBUG_ERROR(err, msg) DEBUG("%s returning " #err ": " msg, __func__)
157 #define DEBUG_FAIL(msg) do { \
158         char *errmsg = sp_last_error_message(); \
159         DEBUG("%s returning SP_ERR_FAIL: " msg ": %s", __func__, errmsg); \
160         sp_free_error_message(errmsg); \
161 } while (0);
162 #define RETURN() do { DEBUG("%s returning", __func__); return; } while(0)
163 #define RETURN_CODE(x) do { DEBUG("%s returning " #x, __func__); return x; } while (0)
164 #define RETURN_CODEVAL(x) do { \
165         switch (x) { \
166                 case SP_OK: RETURN_CODE(SP_OK); \
167                 case SP_ERR_ARG: RETURN_CODE(SP_ERR_ARG); \
168                 case SP_ERR_FAIL: RETURN_CODE(SP_ERR_FAIL); \
169                 case SP_ERR_MEM: RETURN_CODE(SP_ERR_MEM); \
170                 case SP_ERR_SUPP: RETURN_CODE(SP_ERR_SUPP); \
171         } \
172 } while (0)
173 #define RETURN_OK() RETURN_CODE(SP_OK);
174 #define RETURN_ERROR(err, msg) do { DEBUG_ERROR(err, msg); return err; } while (0)
175 #define RETURN_FAIL(msg) do { DEBUG_FAIL(msg); return SP_ERR_FAIL; } while (0)
176 #define RETURN_VALUE(fmt, x) do { DEBUG("%s returning " fmt, __func__, x); return x; } while (0)
177 #define SET_ERROR(val, err, msg) do { DEBUG_ERROR(err, msg); val = err; } while (0)
178 #define SET_FAIL(val, msg) do { DEBUG_FAIL(msg); val = SP_ERR_FAIL; } while (0)
179 #define TRACE(fmt, ...) DEBUG("%s(" fmt ") called", __func__, ##__VA_ARGS__)
180
181 #define TRY(x) do { int ret = x; if (ret != SP_OK) RETURN_CODEVAL(ret); } while (0)
182
183 /* Helper functions. */
184 static struct sp_port **list_append(struct sp_port **list, const char *portname);
185 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
186         struct sp_port_config *config);
187 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
188         const struct sp_port_config *config);
189
190 enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
191 {
192         struct sp_port *port;
193         int len;
194
195         TRACE("%s, %p", portname, port_ptr);
196
197         if (!port_ptr)
198                 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
199
200         *port_ptr = NULL;
201
202         if (!portname)
203                 RETURN_ERROR(SP_ERR_ARG, "Null port name");
204
205         DEBUG("Building structure for port %s", portname);
206
207         if (!(port = malloc(sizeof(struct sp_port))))
208                 RETURN_ERROR(SP_ERR_MEM, "Port structure malloc failed");
209
210         len = strlen(portname) + 1;
211
212         if (!(port->name = malloc(len))) {
213                 free(port);
214                 RETURN_ERROR(SP_ERR_MEM, "Port name malloc failed");
215         }
216
217         memcpy(port->name, portname, len);
218
219 #ifdef _WIN32
220         port->hdl = INVALID_HANDLE_VALUE;
221 #else
222         port->fd = -1;
223 #endif
224
225         *port_ptr = port;
226
227         RETURN_OK();
228 }
229
230 char *sp_get_port_name(const struct sp_port *port)
231 {
232         TRACE("%p", port);
233
234         if (!port)
235                 return NULL;
236
237         RETURN_VALUE("%s", port->name);
238 }
239
240 enum sp_return sp_get_port_handle(const struct sp_port *port, void *result_ptr)
241 {
242         TRACE("%p, %p", port, result_ptr);
243
244         if (!port)
245                 RETURN_ERROR(SP_ERR_ARG, "Null port");
246
247 #ifdef _WIN32
248         HANDLE *handle_ptr = result_ptr;
249         *handle_ptr = port->hdl;
250 #else
251         int *fd_ptr = result_ptr;
252         *fd_ptr = port->fd;
253 #endif
254
255         RETURN_OK();
256 }
257
258 enum sp_return sp_copy_port(const struct sp_port *port, struct sp_port **copy_ptr)
259 {
260         TRACE("%p, %p", port, copy_ptr);
261
262         if (!copy_ptr)
263                 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
264
265         *copy_ptr = NULL;
266
267         if (!port)
268                 RETURN_ERROR(SP_ERR_ARG, "Null port");
269
270         if (!port->name)
271                 RETURN_ERROR(SP_ERR_ARG, "Null port name");
272
273         DEBUG("Copying port structure");
274
275         RETURN_VALUE("%p", sp_get_port_by_name(port->name, copy_ptr));
276 }
277
278 void sp_free_port(struct sp_port *port)
279 {
280         TRACE("%p", port);
281
282         if (!port) {
283                 DEBUG("Null port");
284                 RETURN();
285         }
286
287         DEBUG("Freeing port structure");
288
289         if (port->name)
290                 free(port->name);
291
292         free(port);
293
294         RETURN();
295 }
296
297 static struct sp_port **list_append(struct sp_port **list, const char *portname)
298 {
299         void *tmp;
300         unsigned int count;
301
302         for (count = 0; list[count]; count++);
303         if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
304                 goto fail;
305         list = tmp;
306         if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
307                 goto fail;
308         list[count + 1] = NULL;
309         return list;
310
311 fail:
312         sp_free_port_list(list);
313         return NULL;
314 }
315
316 enum sp_return sp_list_ports(struct sp_port ***list_ptr)
317 {
318         struct sp_port **list;
319         int ret = SP_ERR_SUPP;
320
321         TRACE("%p", list_ptr);
322
323         if (!list_ptr)
324                 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
325
326         DEBUG("Enumerating ports");
327
328         if (!(list = malloc(sizeof(struct sp_port **))))
329                 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
330
331         list[0] = NULL;
332
333 #ifdef _WIN32
334         HKEY key;
335         TCHAR *value, *data;
336         DWORD max_value_len, max_data_size, max_data_len;
337         DWORD value_len, data_size, data_len;
338         DWORD type, index = 0;
339         char *name;
340         int name_len;
341
342         ret = SP_OK;
343
344         DEBUG("Opening registry key");
345         if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
346                         0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS) {
347                 SET_FAIL(ret, "RegOpenKeyEx() failed");
348                 goto out_done;
349         }
350         DEBUG("Querying registry key value and data sizes");
351         if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
352                                 &max_value_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS) {
353                 SET_FAIL(ret, "RegQueryInfoKey() failed");
354                 goto out_close;
355         }
356         max_data_len = max_data_size / sizeof(TCHAR);
357         if (!(value = malloc((max_value_len + 1) * sizeof(TCHAR)))) {
358                 SET_ERROR(ret, SP_ERR_MEM, "registry value malloc failed");
359                 goto out_close;
360         }
361         if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR)))) {
362                 SET_ERROR(ret, SP_ERR_MEM, "registry data malloc failed");
363                 goto out_free_value;
364         }
365         DEBUG("Iterating over values");
366         while (
367                 value_len = max_value_len + 1,
368                 data_size = max_data_size,
369                 RegEnumValue(key, index, value, &value_len,
370                         NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
371         {
372                 data_len = data_size / sizeof(TCHAR);
373                 data[data_len] = '\0';
374 #ifdef UNICODE
375                 name_len = WideCharToMultiByte(CP_ACP, 0, data, -1, NULL, 0, NULL, NULL)
376 #else
377                 name_len = data_len + 1;
378 #endif
379                 if (!(name = malloc(name_len))) {
380                         SET_ERROR(ret, SP_ERR_MEM, "registry port name malloc failed");
381                         goto out;
382                 }
383 #ifdef UNICODE
384                 WideCharToMultiByte(CP_ACP, 0, data, -1, name, name_len, NULL, NULL);
385 #else
386                 strcpy(name, data);
387 #endif
388                 if (type == REG_SZ) {
389                         DEBUG("Found port %s", name);
390                         if (!(list = list_append(list, name))) {
391                                 SET_ERROR(ret, SP_ERR_MEM, "list append failed");
392                                 goto out;
393                         }
394                 }
395                 index++;
396         }
397 out:
398         free(data);
399 out_free_value:
400         free(value);
401 out_close:
402         RegCloseKey(key);
403 out_done:
404 #endif
405 #ifdef __APPLE__
406         mach_port_t master;
407         CFMutableDictionaryRef classes;
408         io_iterator_t iter;
409         char *path;
410         io_object_t port;
411         CFTypeRef cf_path;
412         Boolean result;
413
414         ret = SP_OK;
415
416         DEBUG("Getting IOKit master port");
417         if (IOMasterPort(MACH_PORT_NULL, &master) != KERN_SUCCESS) {
418                 SET_FAIL(ret, "IOMasterPort() failed");
419                 goto out_done;
420         }
421
422         DEBUG("Creating matching dictionary");
423         if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue))) {
424                 SET_FAIL(ret, "IOServiceMatching() failed");
425                 goto out_done;
426         }
427
428         CFDictionarySetValue(classes,
429                         CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
430
431         DEBUG("Getting matching services");
432         if (IOServiceGetMatchingServices(master, classes, &iter) != KERN_SUCCESS) {
433                 SET_FAIL(ret, "IOServiceGetMatchingServices() failed");
434                 goto out_done;
435         }
436
437         if (!(path = malloc(PATH_MAX))) {
438                 SET_ERROR(ret, SP_ERR_MEM, "device path malloc failed");
439                 goto out_release;
440         }
441
442         DEBUG("Iterating over results");
443         while ((port = IOIteratorNext(iter))) {
444                 cf_path = IORegistryEntryCreateCFProperty(port,
445                                 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
446                 if (cf_path) {
447                         result = CFStringGetCString(cf_path,
448                                         path, PATH_MAX, kCFStringEncodingASCII);
449                         CFRelease(cf_path);
450                         if (result) {
451                                 DEBUG("Found port %s", path);
452                                 if (!(list = list_append(list, path))) {
453                                         SET_ERROR(ret, SP_ERR_MEM, "list append failed");
454                                         IOObjectRelease(port);
455                                         goto out;
456                                 }
457                         }
458                 }
459                 IOObjectRelease(port);
460         }
461 out:
462         free(path);
463 out_release:
464         IOObjectRelease(iter);
465 out_done:
466 #endif
467 #if defined(__linux__) && defined(HAVE_LIBUDEV)
468         struct udev *ud;
469         struct udev_enumerate *ud_enumerate;
470         struct udev_list_entry *ud_list;
471         struct udev_list_entry *ud_entry;
472         const char *path;
473         struct udev_device *ud_dev, *ud_parent;
474         const char *name;
475         const char *driver;
476         int fd, ioctl_result;
477         struct serial_struct serial_info;
478
479         ret = SP_OK;
480
481         DEBUG("Enumerating tty devices");
482         ud = udev_new();
483         ud_enumerate = udev_enumerate_new(ud);
484         udev_enumerate_add_match_subsystem(ud_enumerate, "tty");
485         udev_enumerate_scan_devices(ud_enumerate);
486         ud_list = udev_enumerate_get_list_entry(ud_enumerate);
487         DEBUG("Iterating over results");
488         udev_list_entry_foreach(ud_entry, ud_list) {
489                 path = udev_list_entry_get_name(ud_entry);
490                 DEBUG("Found device %s", path);
491                 ud_dev = udev_device_new_from_syspath(ud, path);
492                 /* If there is no parent device, this is a virtual tty. */
493                 ud_parent = udev_device_get_parent(ud_dev);
494                 if (ud_parent == NULL) {
495                         DEBUG("No parent device, assuming virtual tty");
496                         udev_device_unref(ud_dev);
497                         continue;
498                 }
499                 name = udev_device_get_devnode(ud_dev);
500                 /* The serial8250 driver has a hardcoded number of ports.
501                  * The only way to tell which actually exist on a given system
502                  * is to try to open them and make an ioctl call. */
503                 driver = udev_device_get_driver(ud_parent);
504                 if (driver && !strcmp(driver, "serial8250")) {
505                         DEBUG("serial8250 device, attempting to open");
506                         if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY)) < 0) {
507                                 DEBUG("open failed, skipping");
508                                 goto skip;
509                         }
510                         ioctl_result = ioctl(fd, TIOCGSERIAL, &serial_info);
511                         close(fd);
512                         if (ioctl_result != 0) {
513                                 DEBUG("ioctl failed, skipping");
514                                 goto skip;
515                         }
516                         if (serial_info.type == PORT_UNKNOWN) {
517                                 DEBUG("port type is unknown, skipping");
518                                 goto skip;
519                         }
520                 }
521                 DEBUG("Found port %s", name);
522                 list = list_append(list, name);
523 skip:
524                 udev_device_unref(ud_dev);
525                 if (!list) {
526                         SET_ERROR(ret, SP_ERR_MEM, "list append failed");
527                         goto out;
528                 }
529         }
530 out:
531         udev_enumerate_unref(ud_enumerate);
532         udev_unref(ud);
533 #endif
534
535         switch (ret) {
536         case SP_OK:
537                 *list_ptr = list;
538                 RETURN_OK();
539         case SP_ERR_SUPP:
540                 DEBUG_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform.");
541         default:
542                 if (list)
543                         sp_free_port_list(list);
544                 *list_ptr = NULL;
545                 return ret;
546         }
547 }
548
549 void sp_free_port_list(struct sp_port **list)
550 {
551         unsigned int i;
552
553         TRACE("%p", list);
554
555         if (!list) {
556                 DEBUG("Null list");
557                 RETURN();
558         }
559
560         DEBUG("Freeing port list");
561
562         for (i = 0; list[i]; i++)
563                 sp_free_port(list[i]);
564         free(list);
565
566         RETURN();
567 }
568
569 #define CHECK_PORT() do { \
570         if (port == NULL) \
571                 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
572         if (port->name == NULL) \
573                 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
574 } while (0)
575 #ifdef _WIN32
576 #define CHECK_PORT_HANDLE() do { \
577         if (port->hdl == INVALID_HANDLE_VALUE) \
578                 RETURN_ERROR(SP_ERR_ARG, "Invalid port handle"); \
579 } while (0)
580 #else
581 #define CHECK_PORT_HANDLE() do { \
582         if (port->fd < 0) \
583                 RETURN_ERROR(SP_ERR_ARG, "Invalid port fd"); \
584 } while (0)
585 #endif
586 #define CHECK_OPEN_PORT() do { \
587         CHECK_PORT(); \
588         CHECK_PORT_HANDLE(); \
589 } while (0)
590
591 enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
592 {
593         struct port_data data;
594         struct sp_port_config config;
595         enum sp_return ret;
596
597         TRACE("%p, 0x%x", port, flags);
598
599         CHECK_PORT();
600
601         if (flags > (SP_MODE_READ | SP_MODE_WRITE))
602                 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
603
604         DEBUG("Opening port %s", port->name);
605
606 #ifdef _WIN32
607         DWORD desired_access = 0, flags_and_attributes = 0;
608         char *escaped_port_name;
609
610         /* Prefix port name with '\\.\' to work with ports above COM9. */
611         if (!(escaped_port_name = malloc(strlen(port->name + 5))))
612                 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
613         sprintf(escaped_port_name, "\\\\.\\%s", port->name);
614
615         /* Map 'flags' to the OS-specific settings. */
616         flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
617         if (flags & SP_MODE_READ)
618                 desired_access |= GENERIC_READ;
619         if (flags & SP_MODE_WRITE)
620                 desired_access |= GENERIC_WRITE;
621
622         port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
623                          OPEN_EXISTING, flags_and_attributes, 0);
624
625         free(escaped_port_name);
626
627         if (port->hdl == INVALID_HANDLE_VALUE)
628                 RETURN_FAIL("port CreateFile() failed");
629
630         /* All timeouts initially disabled. */
631         port->timeouts.ReadIntervalTimeout = 0;
632         port->timeouts.ReadTotalTimeoutMultiplier = 0;
633         port->timeouts.ReadTotalTimeoutConstant = 0;
634         port->timeouts.WriteTotalTimeoutMultiplier = 0;
635         port->timeouts.WriteTotalTimeoutConstant = 0;
636
637         if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
638                 sp_close(port);
639                 RETURN_FAIL("SetCommTimeouts() failed");
640         }
641
642         /* Prepare OVERLAPPED structures. */
643         memset(&port->read_ovl, 0, sizeof(port->read_ovl));
644         memset(&port->write_ovl, 0, sizeof(port->write_ovl));
645         port->read_ovl.hEvent = INVALID_HANDLE_VALUE;
646         port->write_ovl.hEvent = INVALID_HANDLE_VALUE;
647         if ((port->read_ovl.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL)) == INVALID_HANDLE_VALUE) {
648                 sp_close(port);
649                 RETURN_FAIL("read event CreateEvent() failed");
650         }
651         if ((port->write_ovl.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL)) == INVALID_HANDLE_VALUE) {
652                 sp_close(port);
653                 RETURN_FAIL("write event CreateEvent() failed");
654         }
655
656         port->writing = FALSE;
657
658 #else
659         int flags_local = O_NONBLOCK | O_NOCTTY;
660
661         /* Map 'flags' to the OS-specific settings. */
662         if (flags & (SP_MODE_READ | SP_MODE_WRITE))
663                 flags_local |= O_RDWR;
664         else if (flags & SP_MODE_READ)
665                 flags_local |= O_RDONLY;
666         else if (flags & SP_MODE_WRITE)
667                 flags_local |= O_WRONLY;
668
669         if ((port->fd = open(port->name, flags_local)) < 0)
670                 RETURN_FAIL("open() failed");
671 #endif
672
673         ret = get_config(port, &data, &config);
674
675         if (ret < 0) {
676                 sp_close(port);
677                 RETURN_CODEVAL(ret);
678         }
679
680         /* Set sane port settings. */
681 #ifdef _WIN32
682         data.dcb.fBinary = TRUE;
683         data.dcb.fDsrSensitivity = FALSE;
684         data.dcb.fErrorChar = FALSE;
685         data.dcb.fNull = FALSE;
686         data.dcb.fAbortOnError = TRUE;
687 #else
688         /* Turn off all fancy termios tricks, give us a raw channel. */
689         data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
690 #ifdef IUCLC
691         data.term.c_iflag &= ~IUCLC;
692 #endif
693         data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
694 #ifdef OLCUC
695         data.term.c_oflag &= ~OLCUC;
696 #endif
697 #ifdef NLDLY
698         data.term.c_oflag &= ~NLDLY;
699 #endif
700 #ifdef CRDLY
701         data.term.c_oflag &= ~CRDLY;
702 #endif
703 #ifdef TABDLY
704         data.term.c_oflag &= ~TABDLY;
705 #endif
706 #ifdef BSDLY
707         data.term.c_oflag &= ~BSDLY;
708 #endif
709 #ifdef VTDLY
710         data.term.c_oflag &= ~VTDLY;
711 #endif
712 #ifdef FFDLY
713         data.term.c_oflag &= ~FFDLY;
714 #endif
715 #ifdef OFILL
716         data.term.c_oflag &= ~OFILL;
717 #endif
718         data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
719         data.term.c_cc[VMIN] = 0;
720         data.term.c_cc[VTIME] = 0;
721
722         /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
723         data.term.c_cflag |= (CLOCAL | CREAD | HUPCL);
724 #endif
725
726         ret = set_config(port, &data, &config);
727
728         if (ret < 0) {
729                 sp_close(port);
730                 RETURN_CODEVAL(ret);
731         }
732
733         RETURN_OK();
734 }
735
736 enum sp_return sp_close(struct sp_port *port)
737 {
738         TRACE("%p", port);
739
740         CHECK_OPEN_PORT();
741
742         DEBUG("Closing port %s", port->name);
743
744 #ifdef _WIN32
745         /* Returns non-zero upon success, 0 upon failure. */
746         if (CloseHandle(port->hdl) == 0)
747                 RETURN_FAIL("port CloseHandle() failed");
748         port->hdl = INVALID_HANDLE_VALUE;
749         /* Close event handle created for overlapped reads. */
750         if (port->read_ovl.hEvent != INVALID_HANDLE_VALUE && CloseHandle(port->read_ovl.hEvent) == 0)
751                 RETURN_FAIL("read event CloseHandle() failed");
752         /* Close event handle created for overlapped writes. */
753         if (port->write_ovl.hEvent != INVALID_HANDLE_VALUE && CloseHandle(port->write_ovl.hEvent) == 0)
754                 RETURN_FAIL("write event CloseHandle() failed");
755 #else
756         /* Returns 0 upon success, -1 upon failure. */
757         if (close(port->fd) == -1)
758                 RETURN_FAIL("close() failed");
759         port->fd = -1;
760 #endif
761
762         RETURN_OK();
763 }
764
765 enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
766 {
767         TRACE("%p, 0x%x", port, buffers);
768
769         CHECK_OPEN_PORT();
770
771         if (buffers > SP_BUF_BOTH)
772                 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
773
774         const char *buffer_names[] = {"no", "input", "output", "both"};
775
776         DEBUG("Flushing %s buffers on port %s", buffer_names[buffers], port->name);
777
778 #ifdef _WIN32
779         DWORD flags = 0;
780         if (buffers & SP_BUF_INPUT)
781                 flags |= PURGE_RXCLEAR;
782         if (buffers & SP_BUF_OUTPUT)
783                 flags |= PURGE_TXCLEAR;
784
785         /* Returns non-zero upon success, 0 upon failure. */
786         if (PurgeComm(port->hdl, flags) == 0)
787                 RETURN_FAIL("PurgeComm() failed");
788 #else
789         int flags = 0;
790         if (buffers & SP_BUF_BOTH)
791                 flags = TCIOFLUSH;
792         else if (buffers & SP_BUF_INPUT)
793                 flags = TCIFLUSH;
794         else if (buffers & SP_BUF_OUTPUT)
795                 flags = TCOFLUSH;
796
797         /* Returns 0 upon success, -1 upon failure. */
798         if (tcflush(port->fd, flags) < 0)
799                 RETURN_FAIL("tcflush() failed");
800 #endif
801         RETURN_OK();
802 }
803
804 enum sp_return sp_drain(struct sp_port *port)
805 {
806         TRACE("%p", port);
807
808         CHECK_OPEN_PORT();
809
810         DEBUG("Draining port %s", port->name);
811
812 #ifdef _WIN32
813         /* Returns non-zero upon success, 0 upon failure. */
814         if (FlushFileBuffers(port->hdl) == 0)
815                 RETURN_FAIL("FlushFileBuffers() failed");
816         RETURN_OK();
817 #else
818         int result;
819         while (1) {
820 #ifdef __ANDROID__
821                 int arg = 1;
822                 result = ioctl(port->fd, TCSBRK, &arg);
823 #else
824                 result = tcdrain(port->fd);
825 #endif
826                 if (result < 0) {
827                         if (errno == EINTR) {
828                                 DEBUG("tcdrain() was interrupted");
829                                 continue;
830                         } else {
831                                 RETURN_FAIL("tcdrain() failed");
832                         }
833                 } else {
834                         RETURN_OK();
835                 }
836         }
837 #endif
838 }
839
840 enum sp_return sp_blocking_write(struct sp_port *port, const void *buf, size_t count, unsigned int timeout)
841 {
842         TRACE("%p, %p, %d, %d", port, buf, count, timeout);
843
844         CHECK_OPEN_PORT();
845
846         if (!buf)
847                 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
848
849         if (timeout)
850                 DEBUG("Writing %d bytes to port %s, timeout %d ms", count, port->name, timeout);
851         else
852                 DEBUG("Writing %d bytes to port %s, no timeout", count, port->name);
853
854         if (count == 0)
855                 RETURN_VALUE("0", 0);
856
857 #ifdef _WIN32
858         DWORD bytes_written = 0;
859         BOOL result;
860
861         /* Wait for previous non-blocking write to complete, if any. */
862         if (port->writing) {
863                 DEBUG("Waiting for previous write to complete");
864                 result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
865                 port->writing = 0;
866                 if (!result)
867                         RETURN_FAIL("Previous write failed to complete");
868                 DEBUG("Previous write completed");
869         }
870
871         /* Set timeout. */
872         port->timeouts.WriteTotalTimeoutConstant = timeout;
873         if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
874                 RETURN_FAIL("SetCommTimeouts() failed");
875
876         /* Start write. */
877         if (WriteFile(port->hdl, buf, count, NULL, &port->write_ovl) == 0) {
878                 if (GetLastError() == ERROR_IO_PENDING) {
879                         DEBUG("Waiting for write to complete");
880                         GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
881                         DEBUG("Write completed, %d/%d bytes written", bytes_written, count);
882                         RETURN_VALUE("%d", bytes_written);
883                 } else {
884                         RETURN_FAIL("WriteFile() failed");
885                 }
886         } else {
887                 DEBUG("Write completed immediately");
888                 RETURN_VALUE("%d", count);
889         }
890 #else
891         size_t bytes_written = 0;
892         unsigned char *ptr = (unsigned char *) buf;
893         struct timeval start, delta, now, end = {0, 0};
894         fd_set fds;
895         int result;
896
897         if (timeout) {
898                 /* Get time at start of operation. */
899                 gettimeofday(&start, NULL);
900                 /* Define duration of timeout. */
901                 delta.tv_sec = timeout / 1000;
902                 delta.tv_usec = (timeout % 1000) * 1000;
903                 /* Calculate time at which we should give up. */
904                 timeradd(&start, &delta, &end);
905         }
906
907         /* Loop until we have written the requested number of bytes. */
908         while (bytes_written < count)
909         {
910                 /* Wait until space is available. */
911                 FD_ZERO(&fds);
912                 FD_SET(port->fd, &fds);
913                 if (timeout) {
914                         gettimeofday(&now, NULL);
915                         if (timercmp(&now, &end, >)) {
916                                 DEBUG("write timed out");
917                                 RETURN_VALUE("%d", bytes_written);
918                         }
919                         timersub(&end, &now, &delta);
920                 }
921                 result = select(port->fd + 1, NULL, &fds, NULL, timeout ? &delta : NULL);
922                 if (result < 0) {
923                         if (errno == EINTR) {
924                                 DEBUG("select() call was interrupted, repeating");
925                                 continue;
926                         } else {
927                                 RETURN_FAIL("select() failed");
928                         }
929                 } else if (result == 0) {
930                         DEBUG("write timed out");
931                         RETURN_VALUE("%d", bytes_written);
932                 }
933
934                 /* Do write. */
935                 result = write(port->fd, ptr, count - bytes_written);
936
937                 if (result < 0) {
938                         if (errno == EAGAIN)
939                                 /* This shouldn't happen because we did a select() first, but handle anyway. */
940                                 continue;
941                         else
942                                 /* This is an actual failure. */
943                                 RETURN_FAIL("write() failed");
944                 }
945
946                 bytes_written += result;
947                 ptr += result;
948         }
949
950         RETURN_VALUE("%d", bytes_written);
951 #endif
952 }
953
954 enum sp_return sp_nonblocking_write(struct sp_port *port, const void *buf, size_t count)
955 {
956         TRACE("%p, %p, %d", port, buf, count);
957
958         CHECK_OPEN_PORT();
959
960         if (!buf)
961                 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
962
963         DEBUG("Writing up to %d bytes to port %s", count, port->name);
964
965         if (count == 0)
966                 RETURN_VALUE("0", 0);
967
968 #ifdef _WIN32
969         DWORD written = 0;
970         BYTE *ptr = (BYTE *) buf;
971
972         /* Check whether previous write is complete. */
973         if (port->writing) {
974                 if (HasOverlappedIoCompleted(&port->write_ovl)) {
975                         DEBUG("Previous write completed");
976                         port->writing = 0;
977                 } else {
978                         DEBUG("Previous write not complete");
979                         /* Can't take a new write until the previous one finishes. */
980                         RETURN_VALUE("0", 0);
981                 }
982         }
983
984         /* Set timeout. */
985         port->timeouts.WriteTotalTimeoutConstant = 0;
986         if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
987                 RETURN_FAIL("SetCommTimeouts() failed");
988
989         /* Keep writing data until the OS has to actually start an async IO for it.
990          * At that point we know the buffer is full. */
991         while (written < count)
992         {
993                 /* Copy first byte of user buffer. */
994                 port->pending_byte = *ptr++;
995
996                 /* Start asynchronous write. */
997                 if (WriteFile(port->hdl, &port->pending_byte, 1, NULL, &port->write_ovl) == 0) {
998                         if (GetLastError() == ERROR_IO_PENDING) {
999                                 DEBUG("Asynchronous write started");
1000                                 port->writing = 1;
1001                                 RETURN_VALUE("%d", ++written);
1002                         } else {
1003                                 /* Actual failure of some kind. */
1004                                 RETURN_FAIL("WriteFile() failed");
1005                         }
1006                 } else {
1007                         DEBUG("Single byte written immediately.");
1008                         written++;
1009                 }
1010         }
1011
1012         DEBUG("All bytes written immediately.");
1013
1014         RETURN_VALUE("%d", written);
1015 #else
1016         /* Returns the number of bytes written, or -1 upon failure. */
1017         ssize_t written = write(port->fd, buf, count);
1018
1019         if (written < 0)
1020                 RETURN_FAIL("write() failed");
1021         else
1022                 RETURN_VALUE("%d", written);
1023 #endif
1024 }
1025
1026 enum sp_return sp_blocking_read(struct sp_port *port, void *buf, size_t count, unsigned int timeout)
1027 {
1028         TRACE("%p, %p, %d, %d", port, buf, count, timeout);
1029
1030         CHECK_OPEN_PORT();
1031
1032         if (!buf)
1033                 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1034
1035         if (timeout)
1036                 DEBUG("Reading %d bytes from port %s, timeout %d ms", count, port->name, timeout);
1037         else
1038                 DEBUG("Reading %d bytes from port %s, no timeout", count, port->name);
1039
1040         if (count == 0)
1041                 RETURN_VALUE("0", 0);
1042
1043 #ifdef _WIN32
1044         DWORD bytes_read = 0;
1045
1046         /* Set timeout. */
1047         port->timeouts.ReadIntervalTimeout = 0;
1048         port->timeouts.ReadTotalTimeoutConstant = timeout;
1049         if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1050                 RETURN_FAIL("SetCommTimeouts() failed");
1051
1052         /* Start read. */
1053         if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0) {
1054                 if (GetLastError() == ERROR_IO_PENDING) {
1055                         DEBUG("Waiting for read to complete");
1056                         GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE);
1057                         DEBUG("Read completed, %d/%d bytes read", bytes_read, count);
1058                         RETURN_VALUE("%d", bytes_read);
1059                 } else {
1060                         RETURN_FAIL("ReadFile() failed");
1061                 }
1062         } else {
1063                 DEBUG("Read completed immediately");
1064                 RETURN_VALUE("%d", count);
1065         }
1066 #else
1067         size_t bytes_read = 0;
1068         unsigned char *ptr = (unsigned char *) buf;
1069         struct timeval start, delta, now, end = {0, 0};
1070         fd_set fds;
1071         int result;
1072
1073         if (timeout) {
1074                 /* Get time at start of operation. */
1075                 gettimeofday(&start, NULL);
1076                 /* Define duration of timeout. */
1077                 delta.tv_sec = timeout / 1000;
1078                 delta.tv_usec = (timeout % 1000) * 1000;
1079                 /* Calculate time at which we should give up. */
1080                 timeradd(&start, &delta, &end);
1081         }
1082
1083         /* Loop until we have the requested number of bytes. */
1084         while (bytes_read < count)
1085         {
1086                 /* Wait until data is available. */
1087                 FD_ZERO(&fds);
1088                 FD_SET(port->fd, &fds);
1089                 if (timeout) {
1090                         gettimeofday(&now, NULL);
1091                         if (timercmp(&now, &end, >))
1092                                 /* Timeout has expired. */
1093                                 RETURN_VALUE("%d", bytes_read);
1094                         timersub(&end, &now, &delta);
1095                 }
1096                 result = select(port->fd + 1, &fds, NULL, NULL, timeout ? &delta : NULL);
1097                 if (result < 0) {
1098                         if (errno == EINTR) {
1099                                 DEBUG("select() call was interrupted, repeating");
1100                                 continue;
1101                         } else {
1102                                 RETURN_FAIL("select() failed");
1103                         }
1104                 } else if (result == 0) {
1105                         DEBUG("read timed out");
1106                         RETURN_VALUE("%d", bytes_read);
1107                 }
1108
1109                 /* Do read. */
1110                 result = read(port->fd, ptr, count - bytes_read);
1111
1112                 if (result < 0) {
1113                         if (errno == EAGAIN)
1114                                 /* This shouldn't happen because we did a select() first, but handle anyway. */
1115                                 continue;
1116                         else
1117                                 /* This is an actual failure. */
1118                                 RETURN_FAIL("read() failed");
1119                 }
1120
1121                 bytes_read += result;
1122                 ptr += result;
1123         }
1124
1125         RETURN_VALUE("%d", bytes_read);
1126 #endif
1127 }
1128
1129 enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf, size_t count)
1130 {
1131         TRACE("%p, %p, %d", port, buf, count);
1132
1133         CHECK_OPEN_PORT();
1134
1135         if (!buf)
1136                 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1137
1138         DEBUG("Reading up to %d bytes from port %s", count, port->name);
1139
1140 #ifdef _WIN32
1141         DWORD bytes_read;
1142
1143         /* Set timeout. */
1144         port->timeouts.ReadIntervalTimeout = MAXDWORD;
1145         port->timeouts.ReadTotalTimeoutConstant = 0;
1146         if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1147                 RETURN_FAIL("SetCommTimeouts() failed");
1148
1149         /* Do read. */
1150         if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0)
1151                 RETURN_FAIL("ReadFile() failed");
1152
1153         /* Get number of bytes read. */
1154         GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE);
1155
1156         RETURN_VALUE("%d", bytes_read);
1157 #else
1158         ssize_t bytes_read;
1159
1160         /* Returns the number of bytes read, or -1 upon failure. */
1161         if ((bytes_read = read(port->fd, buf, count)) < 0) {
1162                 if (errno == EAGAIN)
1163                         /* No bytes available. */
1164                         bytes_read = 0;
1165                 else
1166                         /* This is an actual failure. */
1167                         RETURN_FAIL("read() failed");
1168         }
1169         RETURN_VALUE("%d", bytes_read);
1170 #endif
1171 }
1172
1173 enum sp_return sp_input_waiting(struct sp_port *port)
1174 {
1175         TRACE("%p", port);
1176
1177         CHECK_OPEN_PORT();
1178
1179         DEBUG("Checking input bytes waiting on port %s", port->name);
1180
1181 #ifdef _WIN32
1182         DWORD errors;
1183         COMSTAT comstat;
1184
1185         if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1186                 RETURN_FAIL("ClearComError() failed");
1187         RETURN_VALUE("%d", comstat.cbInQue);
1188 #else
1189         int bytes_waiting;
1190         if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1191                 RETURN_FAIL("TIOCINQ ioctl failed");
1192         RETURN_VALUE("%d", bytes_waiting);
1193 #endif
1194 }
1195
1196 enum sp_return sp_output_waiting(struct sp_port *port)
1197 {
1198         TRACE("%p", port);
1199
1200         CHECK_OPEN_PORT();
1201
1202         DEBUG("Checking output bytes waiting on port %s", port->name);
1203
1204 #ifdef _WIN32
1205         DWORD errors;
1206         COMSTAT comstat;
1207
1208         if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1209                 RETURN_FAIL("ClearComError() failed");
1210         RETURN_VALUE("%d", comstat.cbOutQue);
1211 #else
1212         int bytes_waiting;
1213         if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1214                 RETURN_FAIL("TIOCOUTQ ioctl failed");
1215         RETURN_VALUE("%d", bytes_waiting);
1216 #endif
1217 }
1218
1219 #ifdef __linux__
1220 static enum sp_return get_baudrate(int fd, int *baudrate)
1221 {
1222         void *data;
1223
1224         TRACE("%d, %p", fd, baudrate);
1225
1226         DEBUG("Getting baud rate");
1227
1228         if (!(data = malloc(get_termios_size())))
1229                 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1230
1231         if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1232                 free(data);
1233                 RETURN_FAIL("getting termios failed");
1234         }
1235
1236         *baudrate = get_termios_speed(data);
1237
1238         free(data);
1239
1240         RETURN_OK();
1241 }
1242
1243 static enum sp_return set_baudrate(int fd, int baudrate)
1244 {
1245         void *data;
1246
1247         TRACE("%d, %d", fd, baudrate);
1248
1249         DEBUG("Getting baud rate");
1250
1251         if (!(data = malloc(get_termios_size())))
1252                 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1253
1254         if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1255                 free(data);
1256                 RETURN_FAIL("getting termios failed");
1257         }
1258
1259         DEBUG("Setting baud rate");
1260
1261         set_termios_speed(data, baudrate);
1262
1263         if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1264                 free(data);
1265                 RETURN_FAIL("setting termios failed");
1266         }
1267
1268         free(data);
1269
1270         RETURN_OK();
1271 }
1272
1273 #ifdef USE_TERMIOX
1274 static enum sp_return get_flow(int fd, int *flow)
1275 {
1276         void *data;
1277
1278         TRACE("%d, %p", fd, flow);
1279
1280         DEBUG("Getting advanced flow control");
1281
1282         if (!(data = malloc(get_termiox_size())))
1283                 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1284
1285         if (ioctl(fd, TCGETX, data) < 0) {
1286                 free(data);
1287                 RETURN_FAIL("getting termiox failed");
1288         }
1289
1290         *flow = get_termiox_flow(data);
1291
1292         free(data);
1293
1294         RETURN_OK();
1295 }
1296
1297 static enum sp_return set_flow(int fd, int flow)
1298 {
1299         void *data;
1300
1301         TRACE("%d, %d", fd, flow);
1302
1303         DEBUG("Getting advanced flow control");
1304
1305         if (!(data = malloc(get_termiox_size())))
1306                 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1307
1308         if (ioctl(fd, TCGETX, data) < 0) {
1309                 free(data);
1310                 RETURN_FAIL("getting termiox failed");
1311         }
1312
1313         DEBUG("Setting advanced flow control");
1314
1315         set_termiox_flow(data, flow);
1316
1317         if (ioctl(fd, TCSETX, data) < 0) {
1318                 free(data);
1319                 RETURN_FAIL("setting termiox failed");
1320         }
1321
1322         free(data);
1323
1324         RETURN_OK();
1325 }
1326 #endif /* USE_TERMIOX */
1327 #endif /* __linux__ */
1328
1329 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1330         struct sp_port_config *config)
1331 {
1332         unsigned int i;
1333
1334         TRACE("%p, %p, %p", port, data, config);
1335
1336         DEBUG("Getting configuration for port %s", port->name);
1337
1338 #ifdef _WIN32
1339         if (!GetCommState(port->hdl, &data->dcb))
1340                 RETURN_FAIL("GetCommState() failed");
1341
1342         for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1343                 if (data->dcb.BaudRate == std_baudrates[i].index) {
1344                         config->baudrate = std_baudrates[i].value;
1345                         break;
1346                 }
1347         }
1348
1349         if (i == NUM_STD_BAUDRATES)
1350                 /* BaudRate field can be either an index or a custom baud rate. */
1351                 config->baudrate = data->dcb.BaudRate;
1352
1353         config->bits = data->dcb.ByteSize;
1354
1355         if (data->dcb.fParity)
1356                 switch (data->dcb.Parity) {
1357                 case NOPARITY:
1358                         config->parity = SP_PARITY_NONE;
1359                         break;
1360                 case ODDPARITY:
1361                         config->parity = SP_PARITY_ODD;
1362                         break;
1363                 case EVENPARITY:
1364                         config->parity = SP_PARITY_EVEN;
1365                         break;
1366                 case MARKPARITY:
1367                         config->parity = SP_PARITY_MARK;
1368                         break;
1369                 case SPACEPARITY:
1370                         config->parity = SP_PARITY_SPACE;
1371                         break;
1372                 default:
1373                         config->parity = -1;
1374                 }
1375         else
1376                 config->parity = SP_PARITY_NONE;
1377
1378         switch (data->dcb.StopBits) {
1379         case ONESTOPBIT:
1380                 config->stopbits = 1;
1381                 break;
1382         case TWOSTOPBITS:
1383                 config->stopbits = 2;
1384                 break;
1385         default:
1386                 config->stopbits = -1;
1387         }
1388
1389         switch (data->dcb.fRtsControl) {
1390         case RTS_CONTROL_DISABLE:
1391                 config->rts = SP_RTS_OFF;
1392                 break;
1393         case RTS_CONTROL_ENABLE:
1394                 config->rts = SP_RTS_ON;
1395                 break;
1396         case RTS_CONTROL_HANDSHAKE:
1397                 config->rts = SP_RTS_FLOW_CONTROL;
1398                 break;
1399         default:
1400                 config->rts = -1;
1401         }
1402
1403         config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1404
1405         switch (data->dcb.fDtrControl) {
1406         case DTR_CONTROL_DISABLE:
1407                 config->dtr = SP_DTR_OFF;
1408                 break;
1409         case DTR_CONTROL_ENABLE:
1410                 config->dtr = SP_DTR_ON;
1411                 break;
1412         case DTR_CONTROL_HANDSHAKE:
1413                 config->dtr = SP_DTR_FLOW_CONTROL;
1414                 break;
1415         default:
1416                 config->dtr = -1;
1417         }
1418
1419         config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1420
1421         if (data->dcb.fInX) {
1422                 if (data->dcb.fOutX)
1423                         config->xon_xoff = SP_XONXOFF_INOUT;
1424                 else
1425                         config->xon_xoff = SP_XONXOFF_IN;
1426         } else {
1427                 if (data->dcb.fOutX)
1428                         config->xon_xoff = SP_XONXOFF_OUT;
1429                 else
1430                         config->xon_xoff = SP_XONXOFF_DISABLED;
1431         }
1432
1433 #else // !_WIN32
1434
1435         if (tcgetattr(port->fd, &data->term) < 0)
1436                 RETURN_FAIL("tcgetattr() failed");
1437
1438         if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
1439                 RETURN_FAIL("TIOCMGET ioctl failed");
1440
1441 #ifdef USE_TERMIOX
1442         int ret = get_flow(port->fd, &data->flow);
1443
1444         if (ret == SP_ERR_FAIL && errno == EINVAL)
1445                 data->termiox_supported = 0;
1446         else if (ret < 0)
1447                 RETURN_CODEVAL(ret);
1448         else
1449                 data->termiox_supported = 1;
1450 #else
1451         data->termiox_supported = 0;
1452 #endif
1453
1454         for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1455                 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
1456                         config->baudrate = std_baudrates[i].value;
1457                         break;
1458                 }
1459         }
1460
1461         if (i == NUM_STD_BAUDRATES) {
1462 #ifdef __APPLE__
1463                 config->baudrate = (int)data->term.c_ispeed;
1464 #elif defined(__linux__)
1465                 TRY(get_baudrate(port->fd, &config->baudrate));
1466 #else
1467                 config->baudrate = -1;
1468 #endif
1469         }
1470
1471         switch (data->term.c_cflag & CSIZE) {
1472         case CS8:
1473                 config->bits = 8;
1474                 break;
1475         case CS7:
1476                 config->bits = 7;
1477                 break;
1478         case CS6:
1479                 config->bits = 6;
1480                 break;
1481         case CS5:
1482                 config->bits = 5;
1483                 break;
1484         default:
1485                 config->bits = -1;
1486         }
1487
1488         if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1489                 config->parity = SP_PARITY_NONE;
1490         else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1491                 config->parity = -1;
1492 #ifdef CMSPAR
1493         else if (data->term.c_cflag & CMSPAR)
1494                 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
1495 #endif
1496         else
1497                 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1498
1499         config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1500
1501         if (data->term.c_cflag & CRTSCTS) {
1502                 config->rts = SP_RTS_FLOW_CONTROL;
1503                 config->cts = SP_CTS_FLOW_CONTROL;
1504         } else {
1505                 if (data->termiox_supported && data->flow & RTS_FLOW)
1506                         config->rts = SP_RTS_FLOW_CONTROL;
1507                 else
1508                         config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1509
1510                 config->cts = (data->termiox_supported && data->flow & CTS_FLOW) ?
1511                         SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1512         }
1513
1514         if (data->termiox_supported && data->flow & DTR_FLOW)
1515                 config->dtr = SP_DTR_FLOW_CONTROL;
1516         else
1517                 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1518
1519         config->dsr = (data->termiox_supported && data->flow & DSR_FLOW) ?
1520                 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1521
1522         if (data->term.c_iflag & IXOFF) {
1523                 if (data->term.c_iflag & IXON)
1524                         config->xon_xoff = SP_XONXOFF_INOUT;
1525                 else
1526                         config->xon_xoff = SP_XONXOFF_IN;
1527         } else {
1528                 if (data->term.c_iflag & IXON)
1529                         config->xon_xoff = SP_XONXOFF_OUT;
1530                 else
1531                         config->xon_xoff = SP_XONXOFF_DISABLED;
1532         }
1533 #endif
1534
1535         RETURN_OK();
1536 }
1537
1538 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1539         const struct sp_port_config *config)
1540 {
1541         unsigned int i;
1542 #ifdef __APPLE__
1543         BAUD_TYPE baud_nonstd;
1544
1545         baud_nonstd = B0;
1546 #endif
1547 #ifdef __linux__
1548         int baud_nonstd = 0;
1549 #endif
1550
1551         TRACE("%p, %p, %p", port, data, config);
1552
1553         DEBUG("Setting configuration for port %s", port->name);
1554
1555 #ifdef _WIN32
1556         if (config->baudrate >= 0) {
1557                 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1558                         if (config->baudrate == std_baudrates[i].value) {
1559                                 data->dcb.BaudRate = std_baudrates[i].index;
1560                                 break;
1561                         }
1562                 }
1563
1564                 if (i == NUM_STD_BAUDRATES)
1565                         data->dcb.BaudRate = config->baudrate;
1566         }
1567
1568         if (config->bits >= 0)
1569                 data->dcb.ByteSize = config->bits;
1570
1571         if (config->parity >= 0) {
1572                 switch (config->parity) {
1573                 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
1574                 case SP_PARITY_NONE:
1575                         data->dcb.Parity = NOPARITY;
1576                         break;
1577                 case SP_PARITY_ODD:
1578                         data->dcb.Parity = ODDPARITY;
1579                         break;
1580                 case SP_PARITY_EVEN:
1581                         data->dcb.Parity = EVENPARITY;
1582                         break;
1583                 case SP_PARITY_MARK:
1584                         data->dcb.Parity = MARKPARITY;
1585                         break;
1586                 case SP_PARITY_SPACE:
1587                         data->dcb.Parity = SPACEPARITY;
1588                         break;
1589                 default:
1590                         RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1591                 }
1592         }
1593
1594         if (config->stopbits >= 0) {
1595                 switch (config->stopbits) {
1596                 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1597                 case 1:
1598                         data->dcb.StopBits = ONESTOPBIT;
1599                         break;
1600                 case 2:
1601                         data->dcb.StopBits = TWOSTOPBITS;
1602                         break;
1603                 default:
1604                         RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
1605                 }
1606         }
1607
1608         if (config->rts >= 0) {
1609                 switch (config->rts) {
1610                 case SP_RTS_OFF:
1611                         data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
1612                         break;
1613                 case SP_RTS_ON:
1614                         data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
1615                         break;
1616                 case SP_RTS_FLOW_CONTROL:
1617                         data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
1618                         break;
1619                 default:
1620                         RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
1621                 }
1622         }
1623
1624         if (config->cts >= 0) {
1625                 switch (config->cts) {
1626                 case SP_CTS_IGNORE:
1627                         data->dcb.fOutxCtsFlow = FALSE;
1628                         break;
1629                 case SP_CTS_FLOW_CONTROL:
1630                         data->dcb.fOutxCtsFlow = TRUE;
1631                         break;
1632                 default:
1633                         RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
1634                 }
1635         }
1636
1637         if (config->dtr >= 0) {
1638                 switch (config->dtr) {
1639                 case SP_DTR_OFF:
1640                         data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
1641                         break;
1642                 case SP_DTR_ON:
1643                         data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
1644                         break;
1645                 case SP_DTR_FLOW_CONTROL:
1646                         data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
1647                         break;
1648                 default:
1649                         RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
1650                 }
1651         }
1652
1653         if (config->dsr >= 0) {
1654                 switch (config->dsr) {
1655                 case SP_DSR_IGNORE:
1656                         data->dcb.fOutxDsrFlow = FALSE;
1657                         break;
1658                 case SP_DSR_FLOW_CONTROL:
1659                         data->dcb.fOutxDsrFlow = TRUE;
1660                         break;
1661                 default:
1662                         RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
1663                 }
1664         }
1665
1666         if (config->xon_xoff >= 0) {
1667                 switch (config->xon_xoff) {
1668                 case SP_XONXOFF_DISABLED:
1669                         data->dcb.fInX = FALSE;
1670                         data->dcb.fOutX = FALSE;
1671                         break;
1672                 case SP_XONXOFF_IN:
1673                         data->dcb.fInX = TRUE;
1674                         data->dcb.fOutX = FALSE;
1675                         break;
1676                 case SP_XONXOFF_OUT:
1677                         data->dcb.fInX = FALSE;
1678                         data->dcb.fOutX = TRUE;
1679                         break;
1680                 case SP_XONXOFF_INOUT:
1681                         data->dcb.fInX = TRUE;
1682                         data->dcb.fOutX = TRUE;
1683                         break;
1684                 default:
1685                         RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
1686                 }
1687         }
1688
1689         if (!SetCommState(port->hdl, &data->dcb))
1690                 RETURN_FAIL("SetCommState() failed");
1691
1692 #else /* !_WIN32 */
1693
1694         int controlbits;
1695
1696         if (config->baudrate >= 0) {
1697                 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1698                         if (config->baudrate == std_baudrates[i].value) {
1699                                 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
1700                                         RETURN_FAIL("cfsetospeed() failed");
1701
1702                                 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
1703                                         RETURN_FAIL("cfsetispeed() failed");
1704                                 break;
1705                         }
1706                 }
1707
1708                 /* Non-standard baud rate */
1709                 if (i == NUM_STD_BAUDRATES) {
1710 #ifdef __APPLE__
1711                         /* Set "dummy" baud rate. */
1712                         if (cfsetspeed(&data->term, B9600) < 0)
1713                                 RETURN_FAIL("cfsetspeed() failed");
1714                         baud_nonstd = config->baudrate;
1715 #elif defined(__linux__)
1716                         baud_nonstd = 1;
1717 #else
1718                         RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
1719 #endif
1720                 }
1721         }
1722
1723         if (config->bits >= 0) {
1724                 data->term.c_cflag &= ~CSIZE;
1725                 switch (config->bits) {
1726                 case 8:
1727                         data->term.c_cflag |= CS8;
1728                         break;
1729                 case 7:
1730                         data->term.c_cflag |= CS7;
1731                         break;
1732                 case 6:
1733                         data->term.c_cflag |= CS6;
1734                         break;
1735                 case 5:
1736                         data->term.c_cflag |= CS5;
1737                         break;
1738                 default:
1739                         RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
1740                 }
1741         }
1742
1743         if (config->parity >= 0) {
1744                 data->term.c_iflag &= ~IGNPAR;
1745                 data->term.c_cflag &= ~(PARENB | PARODD);
1746 #ifdef CMSPAR
1747                 data->term.c_cflag &= ~CMSPAR;
1748 #endif
1749                 switch (config->parity) {
1750                 case SP_PARITY_NONE:
1751                         data->term.c_iflag |= IGNPAR;
1752                         break;
1753                 case SP_PARITY_EVEN:
1754                         data->term.c_cflag |= PARENB;
1755                         break;
1756                 case SP_PARITY_ODD:
1757                         data->term.c_cflag |= PARENB | PARODD;
1758                         break;
1759 #ifdef CMSPAR
1760                 case SP_PARITY_MARK:
1761                         data->term.c_cflag |= PARENB | PARODD;
1762                         data->term.c_cflag |= CMSPAR;
1763                         break;
1764                 case SP_PARITY_SPACE:
1765                         data->term.c_cflag |= PARENB;
1766                         data->term.c_cflag |= CMSPAR;
1767                         break;
1768 #else
1769                 case SP_PARITY_MARK:
1770                 case SP_PARITY_SPACE:
1771                         RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
1772 #endif
1773                 default:
1774                         RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1775                 }
1776         }
1777
1778         if (config->stopbits >= 0) {
1779                 data->term.c_cflag &= ~CSTOPB;
1780                 switch (config->stopbits) {
1781                 case 1:
1782                         data->term.c_cflag &= ~CSTOPB;
1783                         break;
1784                 case 2:
1785                         data->term.c_cflag |= CSTOPB;
1786                         break;
1787                 default:
1788                         RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
1789                 }
1790         }
1791
1792         if (config->rts >= 0 || config->cts >= 0) {
1793                 if (data->termiox_supported) {
1794                         data->flow &= ~(RTS_FLOW | CTS_FLOW);
1795                         switch (config->rts) {
1796                         case SP_RTS_OFF:
1797                         case SP_RTS_ON:
1798                                 controlbits = TIOCM_RTS;
1799                                 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1800                                         RETURN_FAIL("Setting RTS signal level failed");
1801                                 break;
1802                         case SP_RTS_FLOW_CONTROL:
1803                                 data->flow |= RTS_FLOW;
1804                                 break;
1805                         default:
1806                                 break;
1807                         }
1808                         if (config->cts == SP_CTS_FLOW_CONTROL)
1809                                 data->flow |= CTS_FLOW;
1810
1811                         if (data->flow & (RTS_FLOW | CTS_FLOW))
1812                                 data->term.c_iflag |= CRTSCTS;
1813                         else
1814                                 data->term.c_iflag &= ~CRTSCTS;
1815                 } else {
1816                         /* Asymmetric use of RTS/CTS not supported. */
1817                         if (data->term.c_iflag & CRTSCTS) {
1818                                 /* Flow control can only be disabled for both RTS & CTS together. */
1819                                 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
1820                                         if (config->cts != SP_CTS_IGNORE)
1821                                                 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
1822                                 }
1823                                 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
1824                                         if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
1825                                                 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
1826                                 }
1827                         } else {
1828                                 /* Flow control can only be enabled for both RTS & CTS together. */
1829                                 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
1830                                         ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
1831                                         RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
1832                         }
1833
1834                         if (config->rts >= 0) {
1835                                 if (config->rts == SP_RTS_FLOW_CONTROL) {
1836                                         data->term.c_iflag |= CRTSCTS;
1837                                 } else {
1838                                         controlbits = TIOCM_RTS;
1839                                         if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
1840                                                         &controlbits) < 0)
1841                                                 RETURN_FAIL("Setting RTS signal level failed");
1842                                 }
1843                         }
1844                 }
1845         }
1846
1847         if (config->dtr >= 0 || config->dsr >= 0) {
1848                 if (data->termiox_supported) {
1849                         data->flow &= ~(DTR_FLOW | DSR_FLOW);
1850                         switch (config->dtr) {
1851                         case SP_DTR_OFF:
1852                         case SP_DTR_ON:
1853                                 controlbits = TIOCM_DTR;
1854                                 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1855                                         RETURN_FAIL("Setting DTR signal level failed");
1856                                 break;
1857                         case SP_DTR_FLOW_CONTROL:
1858                                 data->flow |= DTR_FLOW;
1859                                 break;
1860                         default:
1861                                 break;
1862                         }
1863                         if (config->dsr == SP_DSR_FLOW_CONTROL)
1864                                 data->flow |= DSR_FLOW;
1865                 } else {
1866                         /* DTR/DSR flow control not supported. */
1867                         if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
1868                                 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
1869
1870                         if (config->dtr >= 0) {
1871                                 controlbits = TIOCM_DTR;
1872                                 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
1873                                                 &controlbits) < 0)
1874                                         RETURN_FAIL("Setting DTR signal level failed");
1875                         }
1876                 }
1877         }
1878
1879         if (config->xon_xoff >= 0) {
1880                 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
1881                 switch (config->xon_xoff) {
1882                 case SP_XONXOFF_DISABLED:
1883                         break;
1884                 case SP_XONXOFF_IN:
1885                         data->term.c_iflag |= IXOFF;
1886                         break;
1887                 case SP_XONXOFF_OUT:
1888                         data->term.c_iflag |= IXON | IXANY;
1889                         break;
1890                 case SP_XONXOFF_INOUT:
1891                         data->term.c_iflag |= IXON | IXOFF | IXANY;
1892                         break;
1893                 default:
1894                         RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
1895                 }
1896         }
1897
1898         if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
1899                 RETURN_FAIL("tcsetattr() failed");
1900
1901 #ifdef __APPLE__
1902         if (baud_nonstd != B0) {
1903                 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
1904                         RETURN_FAIL("IOSSIOSPEED ioctl failed");
1905                 /* Set baud rates in data->term to correct, but incompatible
1906                  * with tcsetattr() value, same as delivered by tcgetattr(). */
1907                 if (cfsetspeed(&data->term, baud_nonstd) < 0)
1908                         RETURN_FAIL("cfsetspeed() failed");
1909         }
1910 #elif defined(__linux__)
1911         if (baud_nonstd)
1912                 TRY(set_baudrate(port->fd, config->baudrate));
1913 #ifdef USE_TERMIOX
1914         if (data->termiox_supported)
1915                 TRY(set_flow(port->fd, data->flow));
1916 #endif
1917 #endif
1918
1919 #endif /* !_WIN32 */
1920
1921         RETURN_OK();
1922 }
1923
1924 enum sp_return sp_new_config(struct sp_port_config **config_ptr)
1925 {
1926         struct sp_port_config *config;
1927
1928         TRACE("%p", config_ptr);
1929
1930         if (!config_ptr)
1931                 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
1932
1933         *config_ptr = NULL;
1934
1935         if (!(config = malloc(sizeof(struct sp_port_config))))
1936                 RETURN_ERROR(SP_ERR_MEM, "config malloc failed");
1937
1938         config->baudrate = -1;
1939         config->bits = -1;
1940         config->parity = -1;
1941         config->stopbits = -1;
1942         config->rts = -1;
1943         config->cts = -1;
1944         config->dtr = -1;
1945         config->dsr = -1;
1946
1947         *config_ptr = config;
1948
1949         RETURN_OK();
1950 }
1951
1952 void sp_free_config(struct sp_port_config *config)
1953 {
1954         TRACE("%p", config);
1955
1956         if (!config)
1957                 DEBUG("Null config");
1958         else
1959                 free(config);
1960
1961         RETURN();
1962 }
1963
1964 enum sp_return sp_get_config(struct sp_port *port, struct sp_port_config *config)
1965 {
1966         struct port_data data;
1967
1968         TRACE("%p, %p", port, config);
1969
1970         CHECK_OPEN_PORT();
1971
1972         if (!config)
1973                 RETURN_ERROR(SP_ERR_ARG, "Null config");
1974
1975         TRY(get_config(port, &data, config));
1976
1977         RETURN_OK();
1978 }
1979
1980 enum sp_return sp_set_config(struct sp_port *port, const struct sp_port_config *config)
1981 {
1982         struct port_data data;
1983         struct sp_port_config prev_config;
1984
1985         TRACE("%p, %p", port, config);
1986
1987         CHECK_OPEN_PORT();
1988
1989         if (!config)
1990                 RETURN_ERROR(SP_ERR_ARG, "Null config");
1991
1992         TRY(get_config(port, &data, &prev_config));
1993         TRY(set_config(port, &data, config));
1994
1995         RETURN_OK();
1996 }
1997
1998 #define CREATE_ACCESSORS(x, type) \
1999 enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2000         struct port_data data; \
2001         struct sp_port_config config; \
2002         TRACE("%p, %d", port, x); \
2003         CHECK_OPEN_PORT(); \
2004         TRY(get_config(port, &data, &config)); \
2005         config.x = x; \
2006         TRY(set_config(port, &data, &config)); \
2007         RETURN_OK(); \
2008 } \
2009 enum sp_return sp_get_config_##x(const struct sp_port_config *config, type *x) { \
2010         TRACE("%p, %p", config, x); \
2011         if (!config) \
2012                 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2013         *x = config->x; \
2014         RETURN_OK(); \
2015 } \
2016 enum sp_return sp_set_config_##x(struct sp_port_config *config, type x) { \
2017         TRACE("%p, %d", config, x); \
2018         if (!config) \
2019                 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2020         config->x = x; \
2021         RETURN_OK(); \
2022 }
2023
2024 CREATE_ACCESSORS(baudrate, int)
2025 CREATE_ACCESSORS(bits, int)
2026 CREATE_ACCESSORS(parity, enum sp_parity)
2027 CREATE_ACCESSORS(stopbits, int)
2028 CREATE_ACCESSORS(rts, enum sp_rts)
2029 CREATE_ACCESSORS(cts, enum sp_cts)
2030 CREATE_ACCESSORS(dtr, enum sp_dtr)
2031 CREATE_ACCESSORS(dsr, enum sp_dsr)
2032 CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2033
2034 enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config, enum sp_flowcontrol flowcontrol)
2035 {
2036         if (!config)
2037                 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
2038
2039         if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2040                 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
2041
2042         if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
2043                 config->xon_xoff = SP_XONXOFF_INOUT;
2044         else
2045                 config->xon_xoff = SP_XONXOFF_DISABLED;
2046
2047         if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
2048                 config->rts = SP_RTS_FLOW_CONTROL;
2049                 config->cts = SP_CTS_FLOW_CONTROL;
2050         } else {
2051                 if (config->rts == SP_RTS_FLOW_CONTROL)
2052                         config->rts = SP_RTS_ON;
2053                 config->cts = SP_CTS_IGNORE;
2054         }
2055
2056         if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
2057                 config->dtr = SP_DTR_FLOW_CONTROL;
2058                 config->dsr = SP_DSR_FLOW_CONTROL;
2059         } else {
2060                 if (config->dtr == SP_DTR_FLOW_CONTROL)
2061                         config->dtr = SP_DTR_ON;
2062                 config->dsr = SP_DSR_IGNORE;
2063         }
2064
2065         RETURN_OK();
2066 }
2067
2068 enum sp_return sp_set_flowcontrol(struct sp_port *port, enum sp_flowcontrol flowcontrol)
2069 {
2070         struct port_data data;
2071         struct sp_port_config config;
2072
2073         TRACE("%p, %d", port, flowcontrol);
2074
2075         CHECK_OPEN_PORT();
2076
2077         TRY(get_config(port, &data, &config));
2078
2079         TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2080
2081         TRY(set_config(port, &data, &config));
2082
2083         RETURN_OK();
2084 }
2085
2086 enum sp_return sp_get_signals(struct sp_port *port, enum sp_signal *signals)
2087 {
2088         TRACE("%p, %p", port, signals);
2089
2090         CHECK_OPEN_PORT();
2091
2092         if (!signals)
2093                 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2094
2095         DEBUG("Getting control signals for port %s", port->name);
2096
2097         *signals = 0;
2098 #ifdef _WIN32
2099         DWORD bits;
2100         if (GetCommModemStatus(port->hdl, &bits) == 0)
2101                 RETURN_FAIL("GetCommModemStatus() failed");
2102         if (bits & MS_CTS_ON)
2103                 *signals |= SP_SIG_CTS;
2104         if (bits & MS_DSR_ON)
2105                 *signals |= SP_SIG_DSR;
2106         if (bits & MS_RLSD_ON)
2107                 *signals |= SP_SIG_DCD;
2108         if (bits & MS_RING_ON)
2109                 *signals |= SP_SIG_RI;
2110 #else
2111         int bits;
2112         if (ioctl(port->fd, TIOCMGET, &bits) < 0)
2113                 RETURN_FAIL("TIOCMGET ioctl failed");
2114         if (bits & TIOCM_CTS)
2115                 *signals |= SP_SIG_CTS;
2116         if (bits & TIOCM_DSR)
2117                 *signals |= SP_SIG_DSR;
2118         if (bits & TIOCM_CAR)
2119                 *signals |= SP_SIG_DCD;
2120         if (bits & TIOCM_RNG)
2121                 *signals |= SP_SIG_RI;
2122 #endif
2123         RETURN_OK();
2124 }
2125
2126 enum sp_return sp_start_break(struct sp_port *port)
2127 {
2128         TRACE("%p", port);
2129
2130         CHECK_OPEN_PORT();
2131 #ifdef _WIN32
2132         if (SetCommBreak(port->hdl) == 0)
2133                 RETURN_FAIL("SetCommBreak() failed");
2134 #else
2135         if (ioctl(port->fd, TIOCSBRK, 1) < 0)
2136                 RETURN_FAIL("TIOCSBRK ioctl failed");
2137 #endif
2138
2139         RETURN_OK();
2140 }
2141
2142 enum sp_return sp_end_break(struct sp_port *port)
2143 {
2144         TRACE("%p", port);
2145
2146         CHECK_OPEN_PORT();
2147 #ifdef _WIN32
2148         if (ClearCommBreak(port->hdl) == 0)
2149                 RETURN_FAIL("ClearCommBreak() failed");
2150 #else
2151         if (ioctl(port->fd, TIOCCBRK, 1) < 0)
2152                 RETURN_FAIL("TIOCCBRK ioctl failed");
2153 #endif
2154
2155         RETURN_OK();
2156 }
2157
2158 int sp_last_error_code(void)
2159 {
2160         TRACE("");
2161 #ifdef _WIN32
2162         RETURN_VALUE("%d", GetLastError());
2163 #else
2164         RETURN_VALUE("%d", errno);
2165 #endif
2166 }
2167
2168 char *sp_last_error_message(void)
2169 {
2170         TRACE("");
2171
2172 #ifdef _WIN32
2173         LPVOID message;
2174         DWORD error = GetLastError();
2175
2176         FormatMessage(
2177                 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2178                 FORMAT_MESSAGE_FROM_SYSTEM |
2179                 FORMAT_MESSAGE_IGNORE_INSERTS,
2180                 NULL,
2181                 error,
2182                 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2183                 (LPTSTR) &message,
2184                 0, NULL );
2185
2186         RETURN_VALUE("%s", message);
2187 #else
2188         RETURN_VALUE("%s", strerror(errno));
2189 #endif
2190 }
2191
2192 void sp_free_error_message(char *message)
2193 {
2194         TRACE("%s", message);
2195
2196 #ifdef _WIN32
2197         LocalFree(message);
2198 #else
2199         (void)message;
2200 #endif
2201
2202         RETURN();
2203 }
2204
2205 void sp_set_debug_handler(void (*handler)(const char *format, ...))
2206 {
2207         TRACE("%p", handler);
2208
2209         sp_debug_handler = handler;
2210
2211         RETURN();
2212 }
2213
2214 void sp_default_debug_handler(const char *format, ...)
2215 {
2216         va_list args;
2217         va_start(args, format);
2218         if (getenv("LIBSERIALPORT_DEBUG")) {
2219                 fputs("sp: ", stderr);
2220                 vfprintf(stderr, format, args);
2221         }
2222         va_end(args);
2223 }