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