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