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