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