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