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