]> sigrok.org Git - libserialport.git/blob - serialport.c
windows: Avoid unnecessary calls to SetCommTimeouts().
[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) == 0) {
762                 if (GetLastError() == ERROR_IO_PENDING) {
763                         DEBUG("Waiting for write to complete");
764                         GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
765                         DEBUG_FMT("Write completed, %d/%d bytes written", bytes_written, count);
766                         RETURN_INT(bytes_written);
767                 } else {
768                         RETURN_FAIL("WriteFile() failed");
769                 }
770         } else {
771                 DEBUG("Write completed immediately");
772                 RETURN_INT(count);
773         }
774 #else
775         size_t bytes_written = 0;
776         unsigned char *ptr = (unsigned char *) buf;
777         struct timeval start, delta, now, end = {0, 0};
778         fd_set fds;
779         int result;
780
781         if (timeout_ms) {
782                 /* Get time at start of operation. */
783                 gettimeofday(&start, NULL);
784                 /* Define duration of timeout. */
785                 delta.tv_sec = timeout_ms / 1000;
786                 delta.tv_usec = (timeout_ms % 1000) * 1000;
787                 /* Calculate time at which we should give up. */
788                 timeradd(&start, &delta, &end);
789         }
790
791         /* Loop until we have written the requested number of bytes. */
792         while (bytes_written < count) {
793                 /* Wait until space is available. */
794                 FD_ZERO(&fds);
795                 FD_SET(port->fd, &fds);
796                 if (timeout_ms) {
797                         gettimeofday(&now, NULL);
798                         if (timercmp(&now, &end, >)) {
799                                 DEBUG("Write timed out");
800                                 RETURN_INT(bytes_written);
801                         }
802                         timersub(&end, &now, &delta);
803                 }
804                 result = select(port->fd + 1, NULL, &fds, NULL, timeout_ms ? &delta : NULL);
805                 if (result < 0) {
806                         if (errno == EINTR) {
807                                 DEBUG("select() call was interrupted, repeating");
808                                 continue;
809                         } else {
810                                 RETURN_FAIL("select() failed");
811                         }
812                 } else if (result == 0) {
813                         DEBUG("Write timed out");
814                         RETURN_INT(bytes_written);
815                 }
816
817                 /* Do write. */
818                 result = write(port->fd, ptr, count - bytes_written);
819
820                 if (result < 0) {
821                         if (errno == EAGAIN)
822                                 /* This shouldn't happen because we did a select() first, but handle anyway. */
823                                 continue;
824                         else
825                                 /* This is an actual failure. */
826                                 RETURN_FAIL("write() failed");
827                 }
828
829                 bytes_written += result;
830                 ptr += result;
831         }
832
833         RETURN_INT(bytes_written);
834 #endif
835 }
836
837 SP_API enum sp_return sp_nonblocking_write(struct sp_port *port,
838                                            const void *buf, size_t count)
839 {
840         TRACE("%p, %p, %d", port, buf, count);
841
842         CHECK_OPEN_PORT();
843
844         if (!buf)
845                 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
846
847         DEBUG_FMT("Writing up to %d bytes to port %s", count, port->name);
848
849         if (count == 0)
850                 RETURN_INT(0);
851
852 #ifdef _WIN32
853         DWORD written = 0;
854         BYTE *ptr = (BYTE *) buf;
855
856         /* Check whether previous write is complete. */
857         if (port->writing) {
858                 if (HasOverlappedIoCompleted(&port->write_ovl)) {
859                         DEBUG("Previous write completed");
860                         port->writing = 0;
861                 } else {
862                         DEBUG("Previous write not complete");
863                         /* Can't take a new write until the previous one finishes. */
864                         RETURN_INT(0);
865                 }
866         }
867
868         /* Set timeout. */
869         if (port->timeouts.WriteTotalTimeoutConstant != 0) {
870                 port->timeouts.WriteTotalTimeoutConstant = 0;
871                 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
872                         RETURN_FAIL("SetCommTimeouts() failed");
873         }
874
875         /*
876          * Keep writing data until the OS has to actually start an async IO
877          * for it. At that point we know the buffer is full.
878          */
879         while (written < count) {
880                 /* Copy first byte of user buffer. */
881                 port->pending_byte = *ptr++;
882
883                 /* Start asynchronous write. */
884                 if (WriteFile(port->hdl, &port->pending_byte, 1, NULL, &port->write_ovl) == 0) {
885                         if (GetLastError() == ERROR_IO_PENDING) {
886                                 if (HasOverlappedIoCompleted(&port->write_ovl)) {
887                                         DEBUG("Asynchronous write completed immediately");
888                                         port->writing = 0;
889                                         written++;
890                                         continue;
891                                 } else {
892                                         DEBUG("Asynchronous write running");
893                                         port->writing = 1;
894                                         RETURN_INT(++written);
895                                 }
896                         } else {
897                                 /* Actual failure of some kind. */
898                                 RETURN_FAIL("WriteFile() failed");
899                         }
900                 } else {
901                         DEBUG("Single byte written immediately");
902                         written++;
903                 }
904         }
905
906         DEBUG("All bytes written immediately");
907
908         RETURN_INT(written);
909 #else
910         /* Returns the number of bytes written, or -1 upon failure. */
911         ssize_t written = write(port->fd, buf, count);
912
913         if (written < 0)
914                 RETURN_FAIL("write() failed");
915         else
916                 RETURN_INT(written);
917 #endif
918 }
919
920 SP_API enum sp_return sp_blocking_read(struct sp_port *port, void *buf,
921                                        size_t count, unsigned int timeout_ms)
922 {
923         TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
924
925         CHECK_OPEN_PORT();
926
927         if (!buf)
928                 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
929
930         if (timeout_ms)
931                 DEBUG_FMT("Reading %d bytes from port %s, timeout %d ms",
932                         count, port->name, timeout_ms);
933         else
934                 DEBUG_FMT("Reading %d bytes from port %s, no timeout",
935                         count, port->name);
936
937         if (count == 0)
938                 RETURN_INT(0);
939
940 #ifdef _WIN32
941         DWORD bytes_read = 0;
942         DWORD bytes_remaining;
943         int ret;
944
945         /* Set timeout. */
946         if (port->timeouts.ReadIntervalTimeout != 0 ||
947                         port->timeouts.ReadTotalTimeoutConstant != timeout_ms) {
948                 port->timeouts.ReadIntervalTimeout = 0;
949                 port->timeouts.ReadTotalTimeoutConstant = timeout_ms;
950                 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
951                         RETURN_FAIL("SetCommTimeouts() failed");
952         }
953
954         /* Start read. */
955         if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0) {
956                 if (GetLastError() == ERROR_IO_PENDING) {
957                         DEBUG("Waiting for read to complete");
958                         GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE);
959                         DEBUG_FMT("Read completed, %d/%d bytes read", bytes_read, count);
960                 } else {
961                         RETURN_FAIL("ReadFile() failed");
962                 }
963         } else {
964                 DEBUG("Read completed immediately");
965                 bytes_read = count;
966         }
967
968         ret = sp_input_waiting(port);
969
970         if (ret < 0)
971                 RETURN_CODEVAL(ret);
972
973         bytes_remaining = ret;
974
975         /* Restart wait operation if buffer was emptied. */
976         if (bytes_read > 0 && bytes_remaining == 0)
977                 TRY(restart_wait(port));
978
979         RETURN_INT(bytes_read);
980
981 #else
982         size_t bytes_read = 0;
983         unsigned char *ptr = (unsigned char *) buf;
984         struct timeval start, delta, now, end = {0, 0};
985         fd_set fds;
986         int result;
987
988         if (timeout_ms) {
989                 /* Get time at start of operation. */
990                 gettimeofday(&start, NULL);
991                 /* Define duration of timeout. */
992                 delta.tv_sec = timeout_ms / 1000;
993                 delta.tv_usec = (timeout_ms % 1000) * 1000;
994                 /* Calculate time at which we should give up. */
995                 timeradd(&start, &delta, &end);
996         }
997
998         /* Loop until we have the requested number of bytes. */
999         while (bytes_read < count) {
1000                 /* Wait until data is available. */
1001                 FD_ZERO(&fds);
1002                 FD_SET(port->fd, &fds);
1003                 if (timeout_ms) {
1004                         gettimeofday(&now, NULL);
1005                         if (timercmp(&now, &end, >))
1006                                 /* Timeout has expired. */
1007                                 RETURN_INT(bytes_read);
1008                         timersub(&end, &now, &delta);
1009                 }
1010                 result = select(port->fd + 1, &fds, NULL, NULL, timeout_ms ? &delta : NULL);
1011                 if (result < 0) {
1012                         if (errno == EINTR) {
1013                                 DEBUG("select() call was interrupted, repeating");
1014                                 continue;
1015                         } else {
1016                                 RETURN_FAIL("select() failed");
1017                         }
1018                 } else if (result == 0) {
1019                         DEBUG("Read timed out");
1020                         RETURN_INT(bytes_read);
1021                 }
1022
1023                 /* Do read. */
1024                 result = read(port->fd, ptr, count - bytes_read);
1025
1026                 if (result < 0) {
1027                         if (errno == EAGAIN)
1028                                 /* This shouldn't happen because we did a select() first, but handle anyway. */
1029                                 continue;
1030                         else
1031                                 /* This is an actual failure. */
1032                                 RETURN_FAIL("read() failed");
1033                 }
1034
1035                 bytes_read += result;
1036                 ptr += result;
1037         }
1038
1039         RETURN_INT(bytes_read);
1040 #endif
1041 }
1042
1043 SP_API enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf,
1044                                           size_t count)
1045 {
1046         TRACE("%p, %p, %d", port, buf, count);
1047
1048         CHECK_OPEN_PORT();
1049
1050         if (!buf)
1051                 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1052
1053         DEBUG_FMT("Reading up to %d bytes from port %s", count, port->name);
1054
1055 #ifdef _WIN32
1056         DWORD bytes_read;
1057         DWORD bytes_remaining;
1058         int ret;
1059
1060         /* Set timeout. */
1061         if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1062                         port->timeouts.ReadTotalTimeoutConstant != 0) {
1063                 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1064                 port->timeouts.ReadTotalTimeoutConstant = 0;
1065                 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1066                         RETURN_FAIL("SetCommTimeouts() failed");
1067         }
1068
1069         /* Do read. */
1070         if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0)
1071                 RETURN_FAIL("ReadFile() failed");
1072
1073         /* Get number of bytes read. */
1074         if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1075                 RETURN_FAIL("GetOverlappedResult() failed");
1076
1077         ret = sp_input_waiting(port);
1078
1079         if (ret < 0)
1080                 RETURN_CODEVAL(ret);
1081
1082         bytes_remaining = ret;
1083
1084         /* Restart wait operation if buffer was emptied. */
1085         if (bytes_read > 0 && bytes_remaining == 0)
1086                 TRY(restart_wait(port));
1087
1088         RETURN_INT(bytes_read);
1089 #else
1090         ssize_t bytes_read;
1091
1092         /* Returns the number of bytes read, or -1 upon failure. */
1093         if ((bytes_read = read(port->fd, buf, count)) < 0) {
1094                 if (errno == EAGAIN)
1095                         /* No bytes available. */
1096                         bytes_read = 0;
1097                 else
1098                         /* This is an actual failure. */
1099                         RETURN_FAIL("read() failed");
1100         }
1101         RETURN_INT(bytes_read);
1102 #endif
1103 }
1104
1105 SP_API enum sp_return sp_input_waiting(struct sp_port *port)
1106 {
1107         TRACE("%p", port);
1108
1109         CHECK_OPEN_PORT();
1110
1111         DEBUG_FMT("Checking input bytes waiting on port %s", port->name);
1112
1113 #ifdef _WIN32
1114         DWORD errors;
1115         COMSTAT comstat;
1116
1117         if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1118                 RETURN_FAIL("ClearCommError() failed");
1119         RETURN_INT(comstat.cbInQue);
1120 #else
1121         int bytes_waiting;
1122         if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1123                 RETURN_FAIL("TIOCINQ ioctl failed");
1124         RETURN_INT(bytes_waiting);
1125 #endif
1126 }
1127
1128 SP_API enum sp_return sp_output_waiting(struct sp_port *port)
1129 {
1130         TRACE("%p", port);
1131
1132         CHECK_OPEN_PORT();
1133
1134         DEBUG_FMT("Checking output bytes waiting on port %s", port->name);
1135
1136 #ifdef _WIN32
1137         DWORD errors;
1138         COMSTAT comstat;
1139
1140         if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1141                 RETURN_FAIL("ClearCommError() failed");
1142         RETURN_INT(comstat.cbOutQue);
1143 #else
1144         int bytes_waiting;
1145         if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1146                 RETURN_FAIL("TIOCOUTQ ioctl failed");
1147         RETURN_INT(bytes_waiting);
1148 #endif
1149 }
1150
1151 SP_API enum sp_return sp_new_event_set(struct sp_event_set **result_ptr)
1152 {
1153         struct sp_event_set *result;
1154
1155         TRACE("%p", result_ptr);
1156
1157         if (!result_ptr)
1158                 RETURN_ERROR(SP_ERR_ARG, "Null result");
1159
1160         *result_ptr = NULL;
1161
1162         if (!(result = malloc(sizeof(struct sp_event_set))))
1163                 RETURN_ERROR(SP_ERR_MEM, "sp_event_set malloc() failed");
1164
1165         memset(result, 0, sizeof(struct sp_event_set));
1166
1167         *result_ptr = result;
1168
1169         RETURN_OK();
1170 }
1171
1172 static enum sp_return add_handle(struct sp_event_set *event_set,
1173                 event_handle handle, enum sp_event mask)
1174 {
1175         void *new_handles;
1176         enum sp_event *new_masks;
1177
1178         TRACE("%p, %d, %d", event_set, handle, mask);
1179
1180         if (!(new_handles = realloc(event_set->handles,
1181                         sizeof(event_handle) * (event_set->count + 1))))
1182                 RETURN_ERROR(SP_ERR_MEM, "Handle array realloc() failed");
1183
1184         event_set->handles = new_handles;
1185
1186         if (!(new_masks = realloc(event_set->masks,
1187                         sizeof(enum sp_event) * (event_set->count + 1))))
1188                 RETURN_ERROR(SP_ERR_MEM, "Mask array realloc() failed");
1189
1190         event_set->masks = new_masks;
1191
1192         ((event_handle *) event_set->handles)[event_set->count] = handle;
1193         event_set->masks[event_set->count] = mask;
1194
1195         event_set->count++;
1196
1197         RETURN_OK();
1198 }
1199
1200 SP_API enum sp_return sp_add_port_events(struct sp_event_set *event_set,
1201         const struct sp_port *port, enum sp_event mask)
1202 {
1203         TRACE("%p, %p, %d", event_set, port, mask);
1204
1205         if (!event_set)
1206                 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1207
1208         if (!port)
1209                 RETURN_ERROR(SP_ERR_ARG, "Null port");
1210
1211         if (mask > (SP_EVENT_RX_READY | SP_EVENT_TX_READY | SP_EVENT_ERROR))
1212                 RETURN_ERROR(SP_ERR_ARG, "Invalid event mask");
1213
1214         if (!mask)
1215                 RETURN_OK();
1216
1217 #ifdef _WIN32
1218         enum sp_event handle_mask;
1219         if ((handle_mask = mask & SP_EVENT_TX_READY))
1220                 TRY(add_handle(event_set, port->write_ovl.hEvent, handle_mask));
1221         if ((handle_mask = mask & (SP_EVENT_RX_READY | SP_EVENT_ERROR)))
1222                 TRY(add_handle(event_set, port->wait_ovl.hEvent, handle_mask));
1223 #else
1224         TRY(add_handle(event_set, port->fd, mask));
1225 #endif
1226
1227         RETURN_OK();
1228 }
1229
1230 SP_API void sp_free_event_set(struct sp_event_set *event_set)
1231 {
1232         TRACE("%p", event_set);
1233
1234         if (!event_set) {
1235                 DEBUG("Null event set");
1236                 RETURN();
1237         }
1238
1239         DEBUG("Freeing event set");
1240
1241         if (event_set->handles)
1242                 free(event_set->handles);
1243         if (event_set->masks)
1244                 free(event_set->masks);
1245
1246         free(event_set);
1247
1248         RETURN();
1249 }
1250
1251 SP_API enum sp_return sp_wait(struct sp_event_set *event_set,
1252                               unsigned int timeout_ms)
1253 {
1254         TRACE("%p, %d", event_set, timeout_ms);
1255
1256         if (!event_set)
1257                 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1258
1259 #ifdef _WIN32
1260         if (WaitForMultipleObjects(event_set->count, event_set->handles, FALSE,
1261                         timeout_ms ? timeout_ms : INFINITE) == WAIT_FAILED)
1262                 RETURN_FAIL("WaitForMultipleObjects() failed");
1263
1264         RETURN_OK();
1265 #else
1266         struct timeval start, delta, now, end = {0, 0};
1267         int result, timeout_remaining_ms;
1268         struct pollfd *pollfds;
1269         unsigned int i;
1270
1271         if (!(pollfds = malloc(sizeof(struct pollfd) * event_set->count)))
1272                 RETURN_ERROR(SP_ERR_MEM, "pollfds malloc() failed");
1273
1274         for (i = 0; i < event_set->count; i++) {
1275                 pollfds[i].fd = ((int *) event_set->handles)[i];
1276                 pollfds[i].events = 0;
1277                 pollfds[i].revents = 0;
1278                 if (event_set->masks[i] & SP_EVENT_RX_READY)
1279                         pollfds[i].events |= POLLIN;
1280                 if (event_set->masks[i] & SP_EVENT_TX_READY)
1281                         pollfds[i].events |= POLLOUT;
1282                 if (event_set->masks[i] & SP_EVENT_ERROR)
1283                         pollfds[i].events |= POLLERR;
1284         }
1285
1286         if (timeout_ms) {
1287                 /* Get time at start of operation. */
1288                 gettimeofday(&start, NULL);
1289                 /* Define duration of timeout. */
1290                 delta.tv_sec = timeout_ms / 1000;
1291                 delta.tv_usec = (timeout_ms % 1000) * 1000;
1292                 /* Calculate time at which we should give up. */
1293                 timeradd(&start, &delta, &end);
1294         }
1295
1296         /* Loop until an event occurs. */
1297         while (1) {
1298                 if (timeout_ms) {
1299                         gettimeofday(&now, NULL);
1300                         if (timercmp(&now, &end, >)) {
1301                                 DEBUG("Wait timed out");
1302                                 break;
1303                         }
1304                         timersub(&end, &now, &delta);
1305                         timeout_remaining_ms = delta.tv_sec * 1000 + delta.tv_usec / 1000;
1306                 }
1307
1308                 result = poll(pollfds, event_set->count, timeout_ms ? timeout_remaining_ms : -1);
1309
1310                 if (result < 0) {
1311                         if (errno == EINTR) {
1312                                 DEBUG("poll() call was interrupted, repeating");
1313                                 continue;
1314                         } else {
1315                                 free(pollfds);
1316                                 RETURN_FAIL("poll() failed");
1317                         }
1318                 } else if (result == 0) {
1319                         DEBUG("poll() timed out");
1320                         break;
1321                 } else {
1322                         DEBUG("poll() completed");
1323                         break;
1324                 }
1325         }
1326
1327         free(pollfds);
1328         RETURN_OK();
1329 #endif
1330 }
1331
1332 #ifdef USE_TERMIOS_SPEED
1333 static enum sp_return get_baudrate(int fd, int *baudrate)
1334 {
1335         void *data;
1336
1337         TRACE("%d, %p", fd, baudrate);
1338
1339         DEBUG("Getting baud rate");
1340
1341         if (!(data = malloc(get_termios_size())))
1342                 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1343
1344         if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1345                 free(data);
1346                 RETURN_FAIL("Getting termios failed");
1347         }
1348
1349         *baudrate = get_termios_speed(data);
1350
1351         free(data);
1352
1353         RETURN_OK();
1354 }
1355
1356 static enum sp_return set_baudrate(int fd, int baudrate)
1357 {
1358         void *data;
1359
1360         TRACE("%d, %d", fd, baudrate);
1361
1362         DEBUG("Getting baud rate");
1363
1364         if (!(data = malloc(get_termios_size())))
1365                 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1366
1367         if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1368                 free(data);
1369                 RETURN_FAIL("Getting termios failed");
1370         }
1371
1372         DEBUG("Setting baud rate");
1373
1374         set_termios_speed(data, baudrate);
1375
1376         if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1377                 free(data);
1378                 RETURN_FAIL("Setting termios failed");
1379         }
1380
1381         free(data);
1382
1383         RETURN_OK();
1384 }
1385 #endif /* USE_TERMIOS_SPEED */
1386
1387 #ifdef USE_TERMIOX
1388 static enum sp_return get_flow(int fd, struct port_data *data)
1389 {
1390         void *termx;
1391
1392         TRACE("%d, %p", fd, data);
1393
1394         DEBUG("Getting advanced flow control");
1395
1396         if (!(termx = malloc(get_termiox_size())))
1397                 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1398
1399         if (ioctl(fd, TCGETX, termx) < 0) {
1400                 free(termx);
1401                 RETURN_FAIL("Getting termiox failed");
1402         }
1403
1404         get_termiox_flow(termx, &data->rts_flow, &data->cts_flow,
1405                         &data->dtr_flow, &data->dsr_flow);
1406
1407         free(termx);
1408
1409         RETURN_OK();
1410 }
1411
1412 static enum sp_return set_flow(int fd, struct port_data *data)
1413 {
1414         void *termx;
1415
1416         TRACE("%d, %p", fd, data);
1417
1418         DEBUG("Getting advanced flow control");
1419
1420         if (!(termx = malloc(get_termiox_size())))
1421                 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1422
1423         if (ioctl(fd, TCGETX, termx) < 0) {
1424                 free(termx);
1425                 RETURN_FAIL("Getting termiox failed");
1426         }
1427
1428         DEBUG("Setting advanced flow control");
1429
1430         set_termiox_flow(termx, data->rts_flow, data->cts_flow,
1431                         data->dtr_flow, data->dsr_flow);
1432
1433         if (ioctl(fd, TCSETX, termx) < 0) {
1434                 free(termx);
1435                 RETURN_FAIL("Setting termiox failed");
1436         }
1437
1438         free(termx);
1439
1440         RETURN_OK();
1441 }
1442 #endif /* USE_TERMIOX */
1443
1444 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1445         struct sp_port_config *config)
1446 {
1447         unsigned int i;
1448
1449         TRACE("%p, %p, %p", port, data, config);
1450
1451         DEBUG_FMT("Getting configuration for port %s", port->name);
1452
1453 #ifdef _WIN32
1454         if (!GetCommState(port->hdl, &data->dcb))
1455                 RETURN_FAIL("GetCommState() failed");
1456
1457         for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1458                 if (data->dcb.BaudRate == std_baudrates[i].index) {
1459                         config->baudrate = std_baudrates[i].value;
1460                         break;
1461                 }
1462         }
1463
1464         if (i == NUM_STD_BAUDRATES)
1465                 /* BaudRate field can be either an index or a custom baud rate. */
1466                 config->baudrate = data->dcb.BaudRate;
1467
1468         config->bits = data->dcb.ByteSize;
1469
1470         if (data->dcb.fParity)
1471                 switch (data->dcb.Parity) {
1472                 case NOPARITY:
1473                         config->parity = SP_PARITY_NONE;
1474                         break;
1475                 case ODDPARITY:
1476                         config->parity = SP_PARITY_ODD;
1477                         break;
1478                 case EVENPARITY:
1479                         config->parity = SP_PARITY_EVEN;
1480                         break;
1481                 case MARKPARITY:
1482                         config->parity = SP_PARITY_MARK;
1483                         break;
1484                 case SPACEPARITY:
1485                         config->parity = SP_PARITY_SPACE;
1486                         break;
1487                 default:
1488                         config->parity = -1;
1489                 }
1490         else
1491                 config->parity = SP_PARITY_NONE;
1492
1493         switch (data->dcb.StopBits) {
1494         case ONESTOPBIT:
1495                 config->stopbits = 1;
1496                 break;
1497         case TWOSTOPBITS:
1498                 config->stopbits = 2;
1499                 break;
1500         default:
1501                 config->stopbits = -1;
1502         }
1503
1504         switch (data->dcb.fRtsControl) {
1505         case RTS_CONTROL_DISABLE:
1506                 config->rts = SP_RTS_OFF;
1507                 break;
1508         case RTS_CONTROL_ENABLE:
1509                 config->rts = SP_RTS_ON;
1510                 break;
1511         case RTS_CONTROL_HANDSHAKE:
1512                 config->rts = SP_RTS_FLOW_CONTROL;
1513                 break;
1514         default:
1515                 config->rts = -1;
1516         }
1517
1518         config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1519
1520         switch (data->dcb.fDtrControl) {
1521         case DTR_CONTROL_DISABLE:
1522                 config->dtr = SP_DTR_OFF;
1523                 break;
1524         case DTR_CONTROL_ENABLE:
1525                 config->dtr = SP_DTR_ON;
1526                 break;
1527         case DTR_CONTROL_HANDSHAKE:
1528                 config->dtr = SP_DTR_FLOW_CONTROL;
1529                 break;
1530         default:
1531                 config->dtr = -1;
1532         }
1533
1534         config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1535
1536         if (data->dcb.fInX) {
1537                 if (data->dcb.fOutX)
1538                         config->xon_xoff = SP_XONXOFF_INOUT;
1539                 else
1540                         config->xon_xoff = SP_XONXOFF_IN;
1541         } else {
1542                 if (data->dcb.fOutX)
1543                         config->xon_xoff = SP_XONXOFF_OUT;
1544                 else
1545                         config->xon_xoff = SP_XONXOFF_DISABLED;
1546         }
1547
1548 #else // !_WIN32
1549
1550         if (tcgetattr(port->fd, &data->term) < 0)
1551                 RETURN_FAIL("tcgetattr() failed");
1552
1553         if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
1554                 RETURN_FAIL("TIOCMGET ioctl failed");
1555
1556 #ifdef USE_TERMIOX
1557         int ret = get_flow(port->fd, data);
1558
1559         if (ret == SP_ERR_FAIL && errno == EINVAL)
1560                 data->termiox_supported = 0;
1561         else if (ret < 0)
1562                 RETURN_CODEVAL(ret);
1563         else
1564                 data->termiox_supported = 1;
1565 #else
1566         data->termiox_supported = 0;
1567 #endif
1568
1569         for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1570                 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
1571                         config->baudrate = std_baudrates[i].value;
1572                         break;
1573                 }
1574         }
1575
1576         if (i == NUM_STD_BAUDRATES) {
1577 #ifdef __APPLE__
1578                 config->baudrate = (int)data->term.c_ispeed;
1579 #elif defined(USE_TERMIOS_SPEED)
1580                 TRY(get_baudrate(port->fd, &config->baudrate));
1581 #else
1582                 config->baudrate = -1;
1583 #endif
1584         }
1585
1586         switch (data->term.c_cflag & CSIZE) {
1587         case CS8:
1588                 config->bits = 8;
1589                 break;
1590         case CS7:
1591                 config->bits = 7;
1592                 break;
1593         case CS6:
1594                 config->bits = 6;
1595                 break;
1596         case CS5:
1597                 config->bits = 5;
1598                 break;
1599         default:
1600                 config->bits = -1;
1601         }
1602
1603         if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1604                 config->parity = SP_PARITY_NONE;
1605         else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1606                 config->parity = -1;
1607 #ifdef CMSPAR
1608         else if (data->term.c_cflag & CMSPAR)
1609                 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
1610 #endif
1611         else
1612                 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1613
1614         config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1615
1616         if (data->term.c_cflag & CRTSCTS) {
1617                 config->rts = SP_RTS_FLOW_CONTROL;
1618                 config->cts = SP_CTS_FLOW_CONTROL;
1619         } else {
1620                 if (data->termiox_supported && data->rts_flow)
1621                         config->rts = SP_RTS_FLOW_CONTROL;
1622                 else
1623                         config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1624
1625                 config->cts = (data->termiox_supported && data->cts_flow) ?
1626                         SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1627         }
1628
1629         if (data->termiox_supported && data->dtr_flow)
1630                 config->dtr = SP_DTR_FLOW_CONTROL;
1631         else
1632                 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1633
1634         config->dsr = (data->termiox_supported && data->dsr_flow) ?
1635                 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1636
1637         if (data->term.c_iflag & IXOFF) {
1638                 if (data->term.c_iflag & IXON)
1639                         config->xon_xoff = SP_XONXOFF_INOUT;
1640                 else
1641                         config->xon_xoff = SP_XONXOFF_IN;
1642         } else {
1643                 if (data->term.c_iflag & IXON)
1644                         config->xon_xoff = SP_XONXOFF_OUT;
1645                 else
1646                         config->xon_xoff = SP_XONXOFF_DISABLED;
1647         }
1648 #endif
1649
1650         RETURN_OK();
1651 }
1652
1653 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1654         const struct sp_port_config *config)
1655 {
1656         unsigned int i;
1657 #ifdef __APPLE__
1658         BAUD_TYPE baud_nonstd;
1659
1660         baud_nonstd = B0;
1661 #endif
1662 #ifdef USE_TERMIOS_SPEED
1663         int baud_nonstd = 0;
1664 #endif
1665
1666         TRACE("%p, %p, %p", port, data, config);
1667
1668         DEBUG_FMT("Setting configuration for port %s", port->name);
1669
1670 #ifdef _WIN32
1671         if (config->baudrate >= 0) {
1672                 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1673                         if (config->baudrate == std_baudrates[i].value) {
1674                                 data->dcb.BaudRate = std_baudrates[i].index;
1675                                 break;
1676                         }
1677                 }
1678
1679                 if (i == NUM_STD_BAUDRATES)
1680                         data->dcb.BaudRate = config->baudrate;
1681         }
1682
1683         if (config->bits >= 0)
1684                 data->dcb.ByteSize = config->bits;
1685
1686         if (config->parity >= 0) {
1687                 switch (config->parity) {
1688                 case SP_PARITY_NONE:
1689                         data->dcb.Parity = NOPARITY;
1690                         break;
1691                 case SP_PARITY_ODD:
1692                         data->dcb.Parity = ODDPARITY;
1693                         break;
1694                 case SP_PARITY_EVEN:
1695                         data->dcb.Parity = EVENPARITY;
1696                         break;
1697                 case SP_PARITY_MARK:
1698                         data->dcb.Parity = MARKPARITY;
1699                         break;
1700                 case SP_PARITY_SPACE:
1701                         data->dcb.Parity = SPACEPARITY;
1702                         break;
1703                 default:
1704                         RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1705                 }
1706         }
1707
1708         if (config->stopbits >= 0) {
1709                 switch (config->stopbits) {
1710                 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1711                 case 1:
1712                         data->dcb.StopBits = ONESTOPBIT;
1713                         break;
1714                 case 2:
1715                         data->dcb.StopBits = TWOSTOPBITS;
1716                         break;
1717                 default:
1718                         RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
1719                 }
1720         }
1721
1722         if (config->rts >= 0) {
1723                 switch (config->rts) {
1724                 case SP_RTS_OFF:
1725                         data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
1726                         break;
1727                 case SP_RTS_ON:
1728                         data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
1729                         break;
1730                 case SP_RTS_FLOW_CONTROL:
1731                         data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
1732                         break;
1733                 default:
1734                         RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
1735                 }
1736         }
1737
1738         if (config->cts >= 0) {
1739                 switch (config->cts) {
1740                 case SP_CTS_IGNORE:
1741                         data->dcb.fOutxCtsFlow = FALSE;
1742                         break;
1743                 case SP_CTS_FLOW_CONTROL:
1744                         data->dcb.fOutxCtsFlow = TRUE;
1745                         break;
1746                 default:
1747                         RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
1748                 }
1749         }
1750
1751         if (config->dtr >= 0) {
1752                 switch (config->dtr) {
1753                 case SP_DTR_OFF:
1754                         data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
1755                         break;
1756                 case SP_DTR_ON:
1757                         data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
1758                         break;
1759                 case SP_DTR_FLOW_CONTROL:
1760                         data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
1761                         break;
1762                 default:
1763                         RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
1764                 }
1765         }
1766
1767         if (config->dsr >= 0) {
1768                 switch (config->dsr) {
1769                 case SP_DSR_IGNORE:
1770                         data->dcb.fOutxDsrFlow = FALSE;
1771                         break;
1772                 case SP_DSR_FLOW_CONTROL:
1773                         data->dcb.fOutxDsrFlow = TRUE;
1774                         break;
1775                 default:
1776                         RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
1777                 }
1778         }
1779
1780         if (config->xon_xoff >= 0) {
1781                 switch (config->xon_xoff) {
1782                 case SP_XONXOFF_DISABLED:
1783                         data->dcb.fInX = FALSE;
1784                         data->dcb.fOutX = FALSE;
1785                         break;
1786                 case SP_XONXOFF_IN:
1787                         data->dcb.fInX = TRUE;
1788                         data->dcb.fOutX = FALSE;
1789                         break;
1790                 case SP_XONXOFF_OUT:
1791                         data->dcb.fInX = FALSE;
1792                         data->dcb.fOutX = TRUE;
1793                         break;
1794                 case SP_XONXOFF_INOUT:
1795                         data->dcb.fInX = TRUE;
1796                         data->dcb.fOutX = TRUE;
1797                         break;
1798                 default:
1799                         RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
1800                 }
1801         }
1802
1803         if (!SetCommState(port->hdl, &data->dcb))
1804                 RETURN_FAIL("SetCommState() failed");
1805
1806 #else /* !_WIN32 */
1807
1808         int controlbits;
1809
1810         if (config->baudrate >= 0) {
1811                 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1812                         if (config->baudrate == std_baudrates[i].value) {
1813                                 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
1814                                         RETURN_FAIL("cfsetospeed() failed");
1815
1816                                 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
1817                                         RETURN_FAIL("cfsetispeed() failed");
1818                                 break;
1819                         }
1820                 }
1821
1822                 /* Non-standard baud rate */
1823                 if (i == NUM_STD_BAUDRATES) {
1824 #ifdef __APPLE__
1825                         /* Set "dummy" baud rate. */
1826                         if (cfsetspeed(&data->term, B9600) < 0)
1827                                 RETURN_FAIL("cfsetspeed() failed");
1828                         baud_nonstd = config->baudrate;
1829 #elif defined(USE_TERMIOS_SPEED)
1830                         baud_nonstd = 1;
1831 #else
1832                         RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
1833 #endif
1834                 }
1835         }
1836
1837         if (config->bits >= 0) {
1838                 data->term.c_cflag &= ~CSIZE;
1839                 switch (config->bits) {
1840                 case 8:
1841                         data->term.c_cflag |= CS8;
1842                         break;
1843                 case 7:
1844                         data->term.c_cflag |= CS7;
1845                         break;
1846                 case 6:
1847                         data->term.c_cflag |= CS6;
1848                         break;
1849                 case 5:
1850                         data->term.c_cflag |= CS5;
1851                         break;
1852                 default:
1853                         RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
1854                 }
1855         }
1856
1857         if (config->parity >= 0) {
1858                 data->term.c_iflag &= ~IGNPAR;
1859                 data->term.c_cflag &= ~(PARENB | PARODD);
1860 #ifdef CMSPAR
1861                 data->term.c_cflag &= ~CMSPAR;
1862 #endif
1863                 switch (config->parity) {
1864                 case SP_PARITY_NONE:
1865                         data->term.c_iflag |= IGNPAR;
1866                         break;
1867                 case SP_PARITY_EVEN:
1868                         data->term.c_cflag |= PARENB;
1869                         break;
1870                 case SP_PARITY_ODD:
1871                         data->term.c_cflag |= PARENB | PARODD;
1872                         break;
1873 #ifdef CMSPAR
1874                 case SP_PARITY_MARK:
1875                         data->term.c_cflag |= PARENB | PARODD;
1876                         data->term.c_cflag |= CMSPAR;
1877                         break;
1878                 case SP_PARITY_SPACE:
1879                         data->term.c_cflag |= PARENB;
1880                         data->term.c_cflag |= CMSPAR;
1881                         break;
1882 #else
1883                 case SP_PARITY_MARK:
1884                 case SP_PARITY_SPACE:
1885                         RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
1886 #endif
1887                 default:
1888                         RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1889                 }
1890         }
1891
1892         if (config->stopbits >= 0) {
1893                 data->term.c_cflag &= ~CSTOPB;
1894                 switch (config->stopbits) {
1895                 case 1:
1896                         data->term.c_cflag &= ~CSTOPB;
1897                         break;
1898                 case 2:
1899                         data->term.c_cflag |= CSTOPB;
1900                         break;
1901                 default:
1902                         RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
1903                 }
1904         }
1905
1906         if (config->rts >= 0 || config->cts >= 0) {
1907                 if (data->termiox_supported) {
1908                         data->rts_flow = data->cts_flow = 0;
1909                         switch (config->rts) {
1910                         case SP_RTS_OFF:
1911                         case SP_RTS_ON:
1912                                 controlbits = TIOCM_RTS;
1913                                 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1914                                         RETURN_FAIL("Setting RTS signal level failed");
1915                                 break;
1916                         case SP_RTS_FLOW_CONTROL:
1917                                 data->rts_flow = 1;
1918                                 break;
1919                         default:
1920                                 break;
1921                         }
1922                         if (config->cts == SP_CTS_FLOW_CONTROL)
1923                                 data->cts_flow = 1;
1924
1925                         if (data->rts_flow && data->cts_flow)
1926                                 data->term.c_iflag |= CRTSCTS;
1927                         else
1928                                 data->term.c_iflag &= ~CRTSCTS;
1929                 } else {
1930                         /* Asymmetric use of RTS/CTS not supported. */
1931                         if (data->term.c_iflag & CRTSCTS) {
1932                                 /* Flow control can only be disabled for both RTS & CTS together. */
1933                                 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
1934                                         if (config->cts != SP_CTS_IGNORE)
1935                                                 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
1936                                 }
1937                                 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
1938                                         if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
1939                                                 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
1940                                 }
1941                         } else {
1942                                 /* Flow control can only be enabled for both RTS & CTS together. */
1943                                 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
1944                                         ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
1945                                         RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
1946                         }
1947
1948                         if (config->rts >= 0) {
1949                                 if (config->rts == SP_RTS_FLOW_CONTROL) {
1950                                         data->term.c_iflag |= CRTSCTS;
1951                                 } else {
1952                                         controlbits = TIOCM_RTS;
1953                                         if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
1954                                                         &controlbits) < 0)
1955                                                 RETURN_FAIL("Setting RTS signal level failed");
1956                                 }
1957                         }
1958                 }
1959         }
1960
1961         if (config->dtr >= 0 || config->dsr >= 0) {
1962                 if (data->termiox_supported) {
1963                         data->dtr_flow = data->dsr_flow = 0;
1964                         switch (config->dtr) {
1965                         case SP_DTR_OFF:
1966                         case SP_DTR_ON:
1967                                 controlbits = TIOCM_DTR;
1968                                 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1969                                         RETURN_FAIL("Setting DTR signal level failed");
1970                                 break;
1971                         case SP_DTR_FLOW_CONTROL:
1972                                 data->dtr_flow = 1;
1973                                 break;
1974                         default:
1975                                 break;
1976                         }
1977                         if (config->dsr == SP_DSR_FLOW_CONTROL)
1978                                 data->dsr_flow = 1;
1979                 } else {
1980                         /* DTR/DSR flow control not supported. */
1981                         if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
1982                                 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
1983
1984                         if (config->dtr >= 0) {
1985                                 controlbits = TIOCM_DTR;
1986                                 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
1987                                                 &controlbits) < 0)
1988                                         RETURN_FAIL("Setting DTR signal level failed");
1989                         }
1990                 }
1991         }
1992
1993         if (config->xon_xoff >= 0) {
1994                 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
1995                 switch (config->xon_xoff) {
1996                 case SP_XONXOFF_DISABLED:
1997                         break;
1998                 case SP_XONXOFF_IN:
1999                         data->term.c_iflag |= IXOFF;
2000                         break;
2001                 case SP_XONXOFF_OUT:
2002                         data->term.c_iflag |= IXON | IXANY;
2003                         break;
2004                 case SP_XONXOFF_INOUT:
2005                         data->term.c_iflag |= IXON | IXOFF | IXANY;
2006                         break;
2007                 default:
2008                         RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2009                 }
2010         }
2011
2012         if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
2013                 RETURN_FAIL("tcsetattr() failed");
2014
2015 #ifdef __APPLE__
2016         if (baud_nonstd != B0) {
2017                 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
2018                         RETURN_FAIL("IOSSIOSPEED ioctl failed");
2019                 /*
2020                  * Set baud rates in data->term to correct, but incompatible
2021                  * with tcsetattr() value, same as delivered by tcgetattr().
2022                  */
2023                 if (cfsetspeed(&data->term, baud_nonstd) < 0)
2024                         RETURN_FAIL("cfsetspeed() failed");
2025         }
2026 #elif defined(__linux__)
2027 #ifdef USE_TERMIOS_SPEED
2028         if (baud_nonstd)
2029                 TRY(set_baudrate(port->fd, config->baudrate));
2030 #endif
2031 #ifdef USE_TERMIOX
2032         if (data->termiox_supported)
2033                 TRY(set_flow(port->fd, data));
2034 #endif
2035 #endif
2036
2037 #endif /* !_WIN32 */
2038
2039         RETURN_OK();
2040 }
2041
2042 SP_API enum sp_return sp_new_config(struct sp_port_config **config_ptr)
2043 {
2044         struct sp_port_config *config;
2045
2046         TRACE("%p", config_ptr);
2047
2048         if (!config_ptr)
2049                 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2050
2051         *config_ptr = NULL;
2052
2053         if (!(config = malloc(sizeof(struct sp_port_config))))
2054                 RETURN_ERROR(SP_ERR_MEM, "Config malloc failed");
2055
2056         config->baudrate = -1;
2057         config->bits = -1;
2058         config->parity = -1;
2059         config->stopbits = -1;
2060         config->rts = -1;
2061         config->cts = -1;
2062         config->dtr = -1;
2063         config->dsr = -1;
2064
2065         *config_ptr = config;
2066
2067         RETURN_OK();
2068 }
2069
2070 SP_API void sp_free_config(struct sp_port_config *config)
2071 {
2072         TRACE("%p", config);
2073
2074         if (!config)
2075                 DEBUG("Null config");
2076         else
2077                 free(config);
2078
2079         RETURN();
2080 }
2081
2082 SP_API enum sp_return sp_get_config(struct sp_port *port,
2083                                     struct sp_port_config *config)
2084 {
2085         struct port_data data;
2086
2087         TRACE("%p, %p", port, config);
2088
2089         CHECK_OPEN_PORT();
2090
2091         if (!config)
2092                 RETURN_ERROR(SP_ERR_ARG, "Null config");
2093
2094         TRY(get_config(port, &data, config));
2095
2096         RETURN_OK();
2097 }
2098
2099 SP_API enum sp_return sp_set_config(struct sp_port *port,
2100                                     const struct sp_port_config *config)
2101 {
2102         struct port_data data;
2103         struct sp_port_config prev_config;
2104
2105         TRACE("%p, %p", port, config);
2106
2107         CHECK_OPEN_PORT();
2108
2109         if (!config)
2110                 RETURN_ERROR(SP_ERR_ARG, "Null config");
2111
2112         TRY(get_config(port, &data, &prev_config));
2113         TRY(set_config(port, &data, config));
2114
2115         RETURN_OK();
2116 }
2117
2118 #define CREATE_ACCESSORS(x, type) \
2119 SP_API enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2120         struct port_data data; \
2121         struct sp_port_config config; \
2122         TRACE("%p, %d", port, x); \
2123         CHECK_OPEN_PORT(); \
2124         TRY(get_config(port, &data, &config)); \
2125         config.x = x; \
2126         TRY(set_config(port, &data, &config)); \
2127         RETURN_OK(); \
2128 } \
2129 SP_API enum sp_return sp_get_config_##x(const struct sp_port_config *config, \
2130                                         type *x) { \
2131         TRACE("%p, %p", config, x); \
2132         if (!x) \
2133                 RETURN_ERROR(SP_ERR_ARG, "Null result pointer"); \
2134         if (!config) \
2135                 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2136         *x = config->x; \
2137         RETURN_OK(); \
2138 } \
2139 SP_API enum sp_return sp_set_config_##x(struct sp_port_config *config, \
2140                                         type x) { \
2141         TRACE("%p, %d", config, x); \
2142         if (!config) \
2143                 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2144         config->x = x; \
2145         RETURN_OK(); \
2146 }
2147
2148 CREATE_ACCESSORS(baudrate, int)
2149 CREATE_ACCESSORS(bits, int)
2150 CREATE_ACCESSORS(parity, enum sp_parity)
2151 CREATE_ACCESSORS(stopbits, int)
2152 CREATE_ACCESSORS(rts, enum sp_rts)
2153 CREATE_ACCESSORS(cts, enum sp_cts)
2154 CREATE_ACCESSORS(dtr, enum sp_dtr)
2155 CREATE_ACCESSORS(dsr, enum sp_dsr)
2156 CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2157
2158 SP_API enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config,
2159                                                 enum sp_flowcontrol flowcontrol)
2160 {
2161         if (!config)
2162                 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
2163
2164         if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2165                 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
2166
2167         if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
2168                 config->xon_xoff = SP_XONXOFF_INOUT;
2169         else
2170                 config->xon_xoff = SP_XONXOFF_DISABLED;
2171
2172         if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
2173                 config->rts = SP_RTS_FLOW_CONTROL;
2174                 config->cts = SP_CTS_FLOW_CONTROL;
2175         } else {
2176                 if (config->rts == SP_RTS_FLOW_CONTROL)
2177                         config->rts = SP_RTS_ON;
2178                 config->cts = SP_CTS_IGNORE;
2179         }
2180
2181         if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
2182                 config->dtr = SP_DTR_FLOW_CONTROL;
2183                 config->dsr = SP_DSR_FLOW_CONTROL;
2184         } else {
2185                 if (config->dtr == SP_DTR_FLOW_CONTROL)
2186                         config->dtr = SP_DTR_ON;
2187                 config->dsr = SP_DSR_IGNORE;
2188         }
2189
2190         RETURN_OK();
2191 }
2192
2193 SP_API enum sp_return sp_set_flowcontrol(struct sp_port *port,
2194                                          enum sp_flowcontrol flowcontrol)
2195 {
2196         struct port_data data;
2197         struct sp_port_config config;
2198
2199         TRACE("%p, %d", port, flowcontrol);
2200
2201         CHECK_OPEN_PORT();
2202
2203         TRY(get_config(port, &data, &config));
2204
2205         TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2206
2207         TRY(set_config(port, &data, &config));
2208
2209         RETURN_OK();
2210 }
2211
2212 SP_API enum sp_return sp_get_signals(struct sp_port *port,
2213                                      enum sp_signal *signals)
2214 {
2215         TRACE("%p, %p", port, signals);
2216
2217         CHECK_OPEN_PORT();
2218
2219         if (!signals)
2220                 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2221
2222         DEBUG_FMT("Getting control signals for port %s", port->name);
2223
2224         *signals = 0;
2225 #ifdef _WIN32
2226         DWORD bits;
2227         if (GetCommModemStatus(port->hdl, &bits) == 0)
2228                 RETURN_FAIL("GetCommModemStatus() failed");
2229         if (bits & MS_CTS_ON)
2230                 *signals |= SP_SIG_CTS;
2231         if (bits & MS_DSR_ON)
2232                 *signals |= SP_SIG_DSR;
2233         if (bits & MS_RLSD_ON)
2234                 *signals |= SP_SIG_DCD;
2235         if (bits & MS_RING_ON)
2236                 *signals |= SP_SIG_RI;
2237 #else
2238         int bits;
2239         if (ioctl(port->fd, TIOCMGET, &bits) < 0)
2240                 RETURN_FAIL("TIOCMGET ioctl failed");
2241         if (bits & TIOCM_CTS)
2242                 *signals |= SP_SIG_CTS;
2243         if (bits & TIOCM_DSR)
2244                 *signals |= SP_SIG_DSR;
2245         if (bits & TIOCM_CAR)
2246                 *signals |= SP_SIG_DCD;
2247         if (bits & TIOCM_RNG)
2248                 *signals |= SP_SIG_RI;
2249 #endif
2250         RETURN_OK();
2251 }
2252
2253 SP_API enum sp_return sp_start_break(struct sp_port *port)
2254 {
2255         TRACE("%p", port);
2256
2257         CHECK_OPEN_PORT();
2258 #ifdef _WIN32
2259         if (SetCommBreak(port->hdl) == 0)
2260                 RETURN_FAIL("SetCommBreak() failed");
2261 #else
2262         if (ioctl(port->fd, TIOCSBRK, 1) < 0)
2263                 RETURN_FAIL("TIOCSBRK ioctl failed");
2264 #endif
2265
2266         RETURN_OK();
2267 }
2268
2269 SP_API enum sp_return sp_end_break(struct sp_port *port)
2270 {
2271         TRACE("%p", port);
2272
2273         CHECK_OPEN_PORT();
2274 #ifdef _WIN32
2275         if (ClearCommBreak(port->hdl) == 0)
2276                 RETURN_FAIL("ClearCommBreak() failed");
2277 #else
2278         if (ioctl(port->fd, TIOCCBRK, 1) < 0)
2279                 RETURN_FAIL("TIOCCBRK ioctl failed");
2280 #endif
2281
2282         RETURN_OK();
2283 }
2284
2285 SP_API int sp_last_error_code(void)
2286 {
2287         TRACE_VOID();
2288 #ifdef _WIN32
2289         RETURN_INT(GetLastError());
2290 #else
2291         RETURN_INT(errno);
2292 #endif
2293 }
2294
2295 SP_API char *sp_last_error_message(void)
2296 {
2297         TRACE_VOID();
2298
2299 #ifdef _WIN32
2300         TCHAR *message;
2301         DWORD error = GetLastError();
2302
2303         DWORD length = FormatMessage(
2304                 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2305                 FORMAT_MESSAGE_FROM_SYSTEM |
2306                 FORMAT_MESSAGE_IGNORE_INSERTS,
2307                 NULL,
2308                 error,
2309                 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2310                 (LPTSTR) &message,
2311                 0, NULL );
2312
2313         if (length >= 2 && message[length - 2] == '\r')
2314                 message[length - 2] = '\0';
2315
2316         RETURN_STRING(message);
2317 #else
2318         RETURN_STRING(strerror(errno));
2319 #endif
2320 }
2321
2322 SP_API void sp_free_error_message(char *message)
2323 {
2324         TRACE("%s", message);
2325
2326 #ifdef _WIN32
2327         LocalFree(message);
2328 #else
2329         (void)message;
2330 #endif
2331
2332         RETURN();
2333 }
2334
2335 SP_API void sp_set_debug_handler(void (*handler)(const char *format, ...))
2336 {
2337         TRACE("%p", handler);
2338
2339         sp_debug_handler = handler;
2340
2341         RETURN();
2342 }
2343
2344 SP_API void sp_default_debug_handler(const char *format, ...)
2345 {
2346         va_list args;
2347         va_start(args, format);
2348         if (getenv("LIBSERIALPORT_DEBUG")) {
2349                 fputs("sp: ", stderr);
2350                 vfprintf(stderr, format, args);
2351         }
2352         va_end(args);
2353 }
2354
2355 SP_API int sp_get_major_package_version(void)
2356 {
2357         return SP_PACKAGE_VERSION_MAJOR;
2358 }
2359
2360 SP_API int sp_get_minor_package_version(void)
2361 {
2362         return SP_PACKAGE_VERSION_MINOR;
2363 }
2364
2365 SP_API int sp_get_micro_package_version(void)
2366 {
2367         return SP_PACKAGE_VERSION_MICRO;
2368 }
2369
2370 SP_API const char *sp_get_package_version_string(void)
2371 {
2372         return SP_PACKAGE_VERSION_STRING;
2373 }
2374
2375 SP_API int sp_get_current_lib_version(void)
2376 {
2377         return SP_LIB_VERSION_CURRENT;
2378 }
2379
2380 SP_API int sp_get_revision_lib_version(void)
2381 {
2382         return SP_LIB_VERSION_REVISION;
2383 }
2384
2385 SP_API int sp_get_age_lib_version(void)
2386 {
2387         return SP_LIB_VERSION_AGE;
2388 }
2389
2390 SP_API const char *sp_get_lib_version_string(void)
2391 {
2392         return SP_LIB_VERSION_STRING;
2393 }
2394
2395 /** @} */