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