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