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