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