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