]> sigrok.org Git - libserialport.git/blob - serialport.c
add_handle(): Fix a realloc() related issue.
[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         event_set->handles = new_handles;
1169
1170         if (!(new_masks = realloc(event_set->masks,
1171                         sizeof(enum sp_event) * (event_set->count + 1))))
1172                 RETURN_ERROR(SP_ERR_MEM, "Mask array realloc() failed");
1173
1174         event_set->masks = new_masks;
1175
1176         ((event_handle *) event_set->handles)[event_set->count] = handle;
1177         event_set->masks[event_set->count] = mask;
1178
1179         event_set->count++;
1180
1181         RETURN_OK();
1182 }
1183
1184 SP_API enum sp_return sp_add_port_events(struct sp_event_set *event_set,
1185         const struct sp_port *port, enum sp_event mask)
1186 {
1187         TRACE("%p, %p, %d", event_set, port, mask);
1188
1189         if (!event_set)
1190                 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1191
1192         if (!port)
1193                 RETURN_ERROR(SP_ERR_ARG, "Null port");
1194
1195         if (mask > (SP_EVENT_RX_READY | SP_EVENT_TX_READY | SP_EVENT_ERROR))
1196                 RETURN_ERROR(SP_ERR_ARG, "Invalid event mask");
1197
1198         if (!mask)
1199                 RETURN_OK();
1200
1201 #ifdef _WIN32
1202         enum sp_event handle_mask;
1203         if ((handle_mask = mask & SP_EVENT_TX_READY))
1204                 TRY(add_handle(event_set, port->write_ovl.hEvent, handle_mask));
1205         if ((handle_mask = mask & (SP_EVENT_RX_READY | SP_EVENT_ERROR)))
1206                 TRY(add_handle(event_set, port->wait_ovl.hEvent, handle_mask));
1207 #else
1208         TRY(add_handle(event_set, port->fd, mask));
1209 #endif
1210
1211         RETURN_OK();
1212 }
1213
1214 SP_API void sp_free_event_set(struct sp_event_set *event_set)
1215 {
1216         TRACE("%p", event_set);
1217
1218         if (!event_set) {
1219                 DEBUG("Null event set");
1220                 RETURN();
1221         }
1222
1223         DEBUG("Freeing event set");
1224
1225         if (event_set->handles)
1226                 free(event_set->handles);
1227         if (event_set->masks)
1228                 free(event_set->masks);
1229
1230         free(event_set);
1231
1232         RETURN();
1233 }
1234
1235 SP_API enum sp_return sp_wait(struct sp_event_set *event_set,
1236                               unsigned int timeout)
1237 {
1238         TRACE("%p, %d", event_set, timeout);
1239
1240         if (!event_set)
1241                 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1242
1243 #ifdef _WIN32
1244         if (WaitForMultipleObjects(event_set->count, event_set->handles, FALSE,
1245                         timeout ? timeout : INFINITE) == WAIT_FAILED)
1246                 RETURN_FAIL("WaitForMultipleObjects() failed");
1247
1248         RETURN_OK();
1249 #else
1250         struct timeval start, delta, now, end = {0, 0};
1251         int result, timeout_remaining;
1252         struct pollfd *pollfds;
1253         unsigned int i;
1254
1255         if (!(pollfds = malloc(sizeof(struct pollfd) * event_set->count)))
1256                 RETURN_ERROR(SP_ERR_MEM, "pollfds malloc() failed");
1257
1258         for (i = 0; i < event_set->count; i++) {
1259                 pollfds[i].fd = ((int *) event_set->handles)[i];
1260                 pollfds[i].events = 0;
1261                 pollfds[i].revents = 0;
1262                 if (event_set->masks[i] & SP_EVENT_RX_READY)
1263                         pollfds[i].events |= POLLIN;
1264                 if (event_set->masks[i] & SP_EVENT_TX_READY)
1265                         pollfds[i].events |= POLLOUT;
1266                 if (event_set->masks[i] & SP_EVENT_ERROR)
1267                         pollfds[i].events |= POLLERR;
1268         }
1269
1270         if (timeout) {
1271                 /* Get time at start of operation. */
1272                 gettimeofday(&start, NULL);
1273                 /* Define duration of timeout. */
1274                 delta.tv_sec = timeout / 1000;
1275                 delta.tv_usec = (timeout % 1000) * 1000;
1276                 /* Calculate time at which we should give up. */
1277                 timeradd(&start, &delta, &end);
1278         }
1279
1280         /* Loop until an event occurs. */
1281         while (1) {
1282                 if (timeout) {
1283                         gettimeofday(&now, NULL);
1284                         if (timercmp(&now, &end, >)) {
1285                                 DEBUG("Wait timed out");
1286                                 break;
1287                         }
1288                         timersub(&end, &now, &delta);
1289                         timeout_remaining = delta.tv_sec * 1000 + delta.tv_usec / 1000;
1290                 }
1291
1292                 result = poll(pollfds, event_set->count, timeout ? timeout_remaining : -1);
1293
1294                 if (result < 0) {
1295                         if (errno == EINTR) {
1296                                 DEBUG("poll() call was interrupted, repeating");
1297                                 continue;
1298                         } else {
1299                                 free(pollfds);
1300                                 RETURN_FAIL("poll() failed");
1301                         }
1302                 } else if (result == 0) {
1303                         DEBUG("poll() timed out");
1304                         break;
1305                 } else {
1306                         DEBUG("poll() completed");
1307                         break;
1308                 }
1309         }
1310
1311         free(pollfds);
1312         RETURN_OK();
1313 #endif
1314 }
1315
1316 #ifdef USE_TERMIOS_SPEED
1317 static enum sp_return get_baudrate(int fd, int *baudrate)
1318 {
1319         void *data;
1320
1321         TRACE("%d, %p", fd, baudrate);
1322
1323         DEBUG("Getting baud rate");
1324
1325         if (!(data = malloc(get_termios_size())))
1326                 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1327
1328         if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1329                 free(data);
1330                 RETURN_FAIL("Getting termios failed");
1331         }
1332
1333         *baudrate = get_termios_speed(data);
1334
1335         free(data);
1336
1337         RETURN_OK();
1338 }
1339
1340 static enum sp_return set_baudrate(int fd, int baudrate)
1341 {
1342         void *data;
1343
1344         TRACE("%d, %d", fd, baudrate);
1345
1346         DEBUG("Getting baud rate");
1347
1348         if (!(data = malloc(get_termios_size())))
1349                 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1350
1351         if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1352                 free(data);
1353                 RETURN_FAIL("Getting termios failed");
1354         }
1355
1356         DEBUG("Setting baud rate");
1357
1358         set_termios_speed(data, baudrate);
1359
1360         if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1361                 free(data);
1362                 RETURN_FAIL("Setting termios failed");
1363         }
1364
1365         free(data);
1366
1367         RETURN_OK();
1368 }
1369 #endif /* USE_TERMIOS_SPEED */
1370
1371 #ifdef USE_TERMIOX
1372 static enum sp_return get_flow(int fd, struct port_data *data)
1373 {
1374         void *termx;
1375
1376         TRACE("%d, %p", fd, data);
1377
1378         DEBUG("Getting advanced flow control");
1379
1380         if (!(termx = malloc(get_termiox_size())))
1381                 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1382
1383         if (ioctl(fd, TCGETX, termx) < 0) {
1384                 free(termx);
1385                 RETURN_FAIL("Getting termiox failed");
1386         }
1387
1388         get_termiox_flow(termx, &data->rts_flow, &data->cts_flow,
1389                         &data->dtr_flow, &data->dsr_flow);
1390
1391         free(termx);
1392
1393         RETURN_OK();
1394 }
1395
1396 static enum sp_return set_flow(int fd, struct port_data *data)
1397 {
1398         void *termx;
1399
1400         TRACE("%d, %p", fd, data);
1401
1402         DEBUG("Getting advanced flow control");
1403
1404         if (!(termx = malloc(get_termiox_size())))
1405                 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1406
1407         if (ioctl(fd, TCGETX, termx) < 0) {
1408                 free(termx);
1409                 RETURN_FAIL("Getting termiox failed");
1410         }
1411
1412         DEBUG("Setting advanced flow control");
1413
1414         set_termiox_flow(termx, data->rts_flow, data->cts_flow,
1415                         data->dtr_flow, data->dsr_flow);
1416
1417         if (ioctl(fd, TCSETX, termx) < 0) {
1418                 free(termx);
1419                 RETURN_FAIL("Setting termiox failed");
1420         }
1421
1422         free(termx);
1423
1424         RETURN_OK();
1425 }
1426 #endif /* USE_TERMIOX */
1427
1428 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1429         struct sp_port_config *config)
1430 {
1431         unsigned int i;
1432
1433         TRACE("%p, %p, %p", port, data, config);
1434
1435         DEBUG_FMT("Getting configuration for port %s", port->name);
1436
1437 #ifdef _WIN32
1438         if (!GetCommState(port->hdl, &data->dcb))
1439                 RETURN_FAIL("GetCommState() failed");
1440
1441         for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1442                 if (data->dcb.BaudRate == std_baudrates[i].index) {
1443                         config->baudrate = std_baudrates[i].value;
1444                         break;
1445                 }
1446         }
1447
1448         if (i == NUM_STD_BAUDRATES)
1449                 /* BaudRate field can be either an index or a custom baud rate. */
1450                 config->baudrate = data->dcb.BaudRate;
1451
1452         config->bits = data->dcb.ByteSize;
1453
1454         if (data->dcb.fParity)
1455                 switch (data->dcb.Parity) {
1456                 case NOPARITY:
1457                         config->parity = SP_PARITY_NONE;
1458                         break;
1459                 case ODDPARITY:
1460                         config->parity = SP_PARITY_ODD;
1461                         break;
1462                 case EVENPARITY:
1463                         config->parity = SP_PARITY_EVEN;
1464                         break;
1465                 case MARKPARITY:
1466                         config->parity = SP_PARITY_MARK;
1467                         break;
1468                 case SPACEPARITY:
1469                         config->parity = SP_PARITY_SPACE;
1470                         break;
1471                 default:
1472                         config->parity = -1;
1473                 }
1474         else
1475                 config->parity = SP_PARITY_NONE;
1476
1477         switch (data->dcb.StopBits) {
1478         case ONESTOPBIT:
1479                 config->stopbits = 1;
1480                 break;
1481         case TWOSTOPBITS:
1482                 config->stopbits = 2;
1483                 break;
1484         default:
1485                 config->stopbits = -1;
1486         }
1487
1488         switch (data->dcb.fRtsControl) {
1489         case RTS_CONTROL_DISABLE:
1490                 config->rts = SP_RTS_OFF;
1491                 break;
1492         case RTS_CONTROL_ENABLE:
1493                 config->rts = SP_RTS_ON;
1494                 break;
1495         case RTS_CONTROL_HANDSHAKE:
1496                 config->rts = SP_RTS_FLOW_CONTROL;
1497                 break;
1498         default:
1499                 config->rts = -1;
1500         }
1501
1502         config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1503
1504         switch (data->dcb.fDtrControl) {
1505         case DTR_CONTROL_DISABLE:
1506                 config->dtr = SP_DTR_OFF;
1507                 break;
1508         case DTR_CONTROL_ENABLE:
1509                 config->dtr = SP_DTR_ON;
1510                 break;
1511         case DTR_CONTROL_HANDSHAKE:
1512                 config->dtr = SP_DTR_FLOW_CONTROL;
1513                 break;
1514         default:
1515                 config->dtr = -1;
1516         }
1517
1518         config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1519
1520         if (data->dcb.fInX) {
1521                 if (data->dcb.fOutX)
1522                         config->xon_xoff = SP_XONXOFF_INOUT;
1523                 else
1524                         config->xon_xoff = SP_XONXOFF_IN;
1525         } else {
1526                 if (data->dcb.fOutX)
1527                         config->xon_xoff = SP_XONXOFF_OUT;
1528                 else
1529                         config->xon_xoff = SP_XONXOFF_DISABLED;
1530         }
1531
1532 #else // !_WIN32
1533
1534         if (tcgetattr(port->fd, &data->term) < 0)
1535                 RETURN_FAIL("tcgetattr() failed");
1536
1537         if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
1538                 RETURN_FAIL("TIOCMGET ioctl failed");
1539
1540 #ifdef USE_TERMIOX
1541         int ret = get_flow(port->fd, data);
1542
1543         if (ret == SP_ERR_FAIL && errno == EINVAL)
1544                 data->termiox_supported = 0;
1545         else if (ret < 0)
1546                 RETURN_CODEVAL(ret);
1547         else
1548                 data->termiox_supported = 1;
1549 #else
1550         data->termiox_supported = 0;
1551 #endif
1552
1553         for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1554                 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
1555                         config->baudrate = std_baudrates[i].value;
1556                         break;
1557                 }
1558         }
1559
1560         if (i == NUM_STD_BAUDRATES) {
1561 #ifdef __APPLE__
1562                 config->baudrate = (int)data->term.c_ispeed;
1563 #elif defined(USE_TERMIOS_SPEED)
1564                 TRY(get_baudrate(port->fd, &config->baudrate));
1565 #else
1566                 config->baudrate = -1;
1567 #endif
1568         }
1569
1570         switch (data->term.c_cflag & CSIZE) {
1571         case CS8:
1572                 config->bits = 8;
1573                 break;
1574         case CS7:
1575                 config->bits = 7;
1576                 break;
1577         case CS6:
1578                 config->bits = 6;
1579                 break;
1580         case CS5:
1581                 config->bits = 5;
1582                 break;
1583         default:
1584                 config->bits = -1;
1585         }
1586
1587         if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1588                 config->parity = SP_PARITY_NONE;
1589         else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1590                 config->parity = -1;
1591 #ifdef CMSPAR
1592         else if (data->term.c_cflag & CMSPAR)
1593                 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
1594 #endif
1595         else
1596                 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1597
1598         config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1599
1600         if (data->term.c_cflag & CRTSCTS) {
1601                 config->rts = SP_RTS_FLOW_CONTROL;
1602                 config->cts = SP_CTS_FLOW_CONTROL;
1603         } else {
1604                 if (data->termiox_supported && data->rts_flow)
1605                         config->rts = SP_RTS_FLOW_CONTROL;
1606                 else
1607                         config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1608
1609                 config->cts = (data->termiox_supported && data->cts_flow) ?
1610                         SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1611         }
1612
1613         if (data->termiox_supported && data->dtr_flow)
1614                 config->dtr = SP_DTR_FLOW_CONTROL;
1615         else
1616                 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1617
1618         config->dsr = (data->termiox_supported && data->dsr_flow) ?
1619                 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1620
1621         if (data->term.c_iflag & IXOFF) {
1622                 if (data->term.c_iflag & IXON)
1623                         config->xon_xoff = SP_XONXOFF_INOUT;
1624                 else
1625                         config->xon_xoff = SP_XONXOFF_IN;
1626         } else {
1627                 if (data->term.c_iflag & IXON)
1628                         config->xon_xoff = SP_XONXOFF_OUT;
1629                 else
1630                         config->xon_xoff = SP_XONXOFF_DISABLED;
1631         }
1632 #endif
1633
1634         RETURN_OK();
1635 }
1636
1637 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1638         const struct sp_port_config *config)
1639 {
1640         unsigned int i;
1641 #ifdef __APPLE__
1642         BAUD_TYPE baud_nonstd;
1643
1644         baud_nonstd = B0;
1645 #endif
1646 #ifdef USE_TERMIOS_SPEED
1647         int baud_nonstd = 0;
1648 #endif
1649
1650         TRACE("%p, %p, %p", port, data, config);
1651
1652         DEBUG_FMT("Setting configuration for port %s", port->name);
1653
1654 #ifdef _WIN32
1655         if (config->baudrate >= 0) {
1656                 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1657                         if (config->baudrate == std_baudrates[i].value) {
1658                                 data->dcb.BaudRate = std_baudrates[i].index;
1659                                 break;
1660                         }
1661                 }
1662
1663                 if (i == NUM_STD_BAUDRATES)
1664                         data->dcb.BaudRate = config->baudrate;
1665         }
1666
1667         if (config->bits >= 0)
1668                 data->dcb.ByteSize = config->bits;
1669
1670         if (config->parity >= 0) {
1671                 switch (config->parity) {
1672                 case SP_PARITY_NONE:
1673                         data->dcb.Parity = NOPARITY;
1674                         break;
1675                 case SP_PARITY_ODD:
1676                         data->dcb.Parity = ODDPARITY;
1677                         break;
1678                 case SP_PARITY_EVEN:
1679                         data->dcb.Parity = EVENPARITY;
1680                         break;
1681                 case SP_PARITY_MARK:
1682                         data->dcb.Parity = MARKPARITY;
1683                         break;
1684                 case SP_PARITY_SPACE:
1685                         data->dcb.Parity = SPACEPARITY;
1686                         break;
1687                 default:
1688                         RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1689                 }
1690         }
1691
1692         if (config->stopbits >= 0) {
1693                 switch (config->stopbits) {
1694                 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1695                 case 1:
1696                         data->dcb.StopBits = ONESTOPBIT;
1697                         break;
1698                 case 2:
1699                         data->dcb.StopBits = TWOSTOPBITS;
1700                         break;
1701                 default:
1702                         RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
1703                 }
1704         }
1705
1706         if (config->rts >= 0) {
1707                 switch (config->rts) {
1708                 case SP_RTS_OFF:
1709                         data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
1710                         break;
1711                 case SP_RTS_ON:
1712                         data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
1713                         break;
1714                 case SP_RTS_FLOW_CONTROL:
1715                         data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
1716                         break;
1717                 default:
1718                         RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
1719                 }
1720         }
1721
1722         if (config->cts >= 0) {
1723                 switch (config->cts) {
1724                 case SP_CTS_IGNORE:
1725                         data->dcb.fOutxCtsFlow = FALSE;
1726                         break;
1727                 case SP_CTS_FLOW_CONTROL:
1728                         data->dcb.fOutxCtsFlow = TRUE;
1729                         break;
1730                 default:
1731                         RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
1732                 }
1733         }
1734
1735         if (config->dtr >= 0) {
1736                 switch (config->dtr) {
1737                 case SP_DTR_OFF:
1738                         data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
1739                         break;
1740                 case SP_DTR_ON:
1741                         data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
1742                         break;
1743                 case SP_DTR_FLOW_CONTROL:
1744                         data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
1745                         break;
1746                 default:
1747                         RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
1748                 }
1749         }
1750
1751         if (config->dsr >= 0) {
1752                 switch (config->dsr) {
1753                 case SP_DSR_IGNORE:
1754                         data->dcb.fOutxDsrFlow = FALSE;
1755                         break;
1756                 case SP_DSR_FLOW_CONTROL:
1757                         data->dcb.fOutxDsrFlow = TRUE;
1758                         break;
1759                 default:
1760                         RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
1761                 }
1762         }
1763
1764         if (config->xon_xoff >= 0) {
1765                 switch (config->xon_xoff) {
1766                 case SP_XONXOFF_DISABLED:
1767                         data->dcb.fInX = FALSE;
1768                         data->dcb.fOutX = FALSE;
1769                         break;
1770                 case SP_XONXOFF_IN:
1771                         data->dcb.fInX = TRUE;
1772                         data->dcb.fOutX = FALSE;
1773                         break;
1774                 case SP_XONXOFF_OUT:
1775                         data->dcb.fInX = FALSE;
1776                         data->dcb.fOutX = TRUE;
1777                         break;
1778                 case SP_XONXOFF_INOUT:
1779                         data->dcb.fInX = TRUE;
1780                         data->dcb.fOutX = TRUE;
1781                         break;
1782                 default:
1783                         RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
1784                 }
1785         }
1786
1787         if (!SetCommState(port->hdl, &data->dcb))
1788                 RETURN_FAIL("SetCommState() failed");
1789
1790 #else /* !_WIN32 */
1791
1792         int controlbits;
1793
1794         if (config->baudrate >= 0) {
1795                 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1796                         if (config->baudrate == std_baudrates[i].value) {
1797                                 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
1798                                         RETURN_FAIL("cfsetospeed() failed");
1799
1800                                 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
1801                                         RETURN_FAIL("cfsetispeed() failed");
1802                                 break;
1803                         }
1804                 }
1805
1806                 /* Non-standard baud rate */
1807                 if (i == NUM_STD_BAUDRATES) {
1808 #ifdef __APPLE__
1809                         /* Set "dummy" baud rate. */
1810                         if (cfsetspeed(&data->term, B9600) < 0)
1811                                 RETURN_FAIL("cfsetspeed() failed");
1812                         baud_nonstd = config->baudrate;
1813 #elif defined(USE_TERMIOS_SPEED)
1814                         baud_nonstd = 1;
1815 #else
1816                         RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
1817 #endif
1818                 }
1819         }
1820
1821         if (config->bits >= 0) {
1822                 data->term.c_cflag &= ~CSIZE;
1823                 switch (config->bits) {
1824                 case 8:
1825                         data->term.c_cflag |= CS8;
1826                         break;
1827                 case 7:
1828                         data->term.c_cflag |= CS7;
1829                         break;
1830                 case 6:
1831                         data->term.c_cflag |= CS6;
1832                         break;
1833                 case 5:
1834                         data->term.c_cflag |= CS5;
1835                         break;
1836                 default:
1837                         RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
1838                 }
1839         }
1840
1841         if (config->parity >= 0) {
1842                 data->term.c_iflag &= ~IGNPAR;
1843                 data->term.c_cflag &= ~(PARENB | PARODD);
1844 #ifdef CMSPAR
1845                 data->term.c_cflag &= ~CMSPAR;
1846 #endif
1847                 switch (config->parity) {
1848                 case SP_PARITY_NONE:
1849                         data->term.c_iflag |= IGNPAR;
1850                         break;
1851                 case SP_PARITY_EVEN:
1852                         data->term.c_cflag |= PARENB;
1853                         break;
1854                 case SP_PARITY_ODD:
1855                         data->term.c_cflag |= PARENB | PARODD;
1856                         break;
1857 #ifdef CMSPAR
1858                 case SP_PARITY_MARK:
1859                         data->term.c_cflag |= PARENB | PARODD;
1860                         data->term.c_cflag |= CMSPAR;
1861                         break;
1862                 case SP_PARITY_SPACE:
1863                         data->term.c_cflag |= PARENB;
1864                         data->term.c_cflag |= CMSPAR;
1865                         break;
1866 #else
1867                 case SP_PARITY_MARK:
1868                 case SP_PARITY_SPACE:
1869                         RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
1870 #endif
1871                 default:
1872                         RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1873                 }
1874         }
1875
1876         if (config->stopbits >= 0) {
1877                 data->term.c_cflag &= ~CSTOPB;
1878                 switch (config->stopbits) {
1879                 case 1:
1880                         data->term.c_cflag &= ~CSTOPB;
1881                         break;
1882                 case 2:
1883                         data->term.c_cflag |= CSTOPB;
1884                         break;
1885                 default:
1886                         RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
1887                 }
1888         }
1889
1890         if (config->rts >= 0 || config->cts >= 0) {
1891                 if (data->termiox_supported) {
1892                         data->rts_flow = data->cts_flow = 0;
1893                         switch (config->rts) {
1894                         case SP_RTS_OFF:
1895                         case SP_RTS_ON:
1896                                 controlbits = TIOCM_RTS;
1897                                 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1898                                         RETURN_FAIL("Setting RTS signal level failed");
1899                                 break;
1900                         case SP_RTS_FLOW_CONTROL:
1901                                 data->rts_flow = 1;
1902                                 break;
1903                         default:
1904                                 break;
1905                         }
1906                         if (config->cts == SP_CTS_FLOW_CONTROL)
1907                                 data->cts_flow = 1;
1908
1909                         if (data->rts_flow && data->cts_flow)
1910                                 data->term.c_iflag |= CRTSCTS;
1911                         else
1912                                 data->term.c_iflag &= ~CRTSCTS;
1913                 } else {
1914                         /* Asymmetric use of RTS/CTS not supported. */
1915                         if (data->term.c_iflag & CRTSCTS) {
1916                                 /* Flow control can only be disabled for both RTS & CTS together. */
1917                                 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
1918                                         if (config->cts != SP_CTS_IGNORE)
1919                                                 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
1920                                 }
1921                                 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
1922                                         if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
1923                                                 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
1924                                 }
1925                         } else {
1926                                 /* Flow control can only be enabled for both RTS & CTS together. */
1927                                 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
1928                                         ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
1929                                         RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
1930                         }
1931
1932                         if (config->rts >= 0) {
1933                                 if (config->rts == SP_RTS_FLOW_CONTROL) {
1934                                         data->term.c_iflag |= CRTSCTS;
1935                                 } else {
1936                                         controlbits = TIOCM_RTS;
1937                                         if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
1938                                                         &controlbits) < 0)
1939                                                 RETURN_FAIL("Setting RTS signal level failed");
1940                                 }
1941                         }
1942                 }
1943         }
1944
1945         if (config->dtr >= 0 || config->dsr >= 0) {
1946                 if (data->termiox_supported) {
1947                         data->dtr_flow = data->dsr_flow = 0;
1948                         switch (config->dtr) {
1949                         case SP_DTR_OFF:
1950                         case SP_DTR_ON:
1951                                 controlbits = TIOCM_DTR;
1952                                 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1953                                         RETURN_FAIL("Setting DTR signal level failed");
1954                                 break;
1955                         case SP_DTR_FLOW_CONTROL:
1956                                 data->dtr_flow = 1;
1957                                 break;
1958                         default:
1959                                 break;
1960                         }
1961                         if (config->dsr == SP_DSR_FLOW_CONTROL)
1962                                 data->dsr_flow = 1;
1963                 } else {
1964                         /* DTR/DSR flow control not supported. */
1965                         if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
1966                                 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
1967
1968                         if (config->dtr >= 0) {
1969                                 controlbits = TIOCM_DTR;
1970                                 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
1971                                                 &controlbits) < 0)
1972                                         RETURN_FAIL("Setting DTR signal level failed");
1973                         }
1974                 }
1975         }
1976
1977         if (config->xon_xoff >= 0) {
1978                 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
1979                 switch (config->xon_xoff) {
1980                 case SP_XONXOFF_DISABLED:
1981                         break;
1982                 case SP_XONXOFF_IN:
1983                         data->term.c_iflag |= IXOFF;
1984                         break;
1985                 case SP_XONXOFF_OUT:
1986                         data->term.c_iflag |= IXON | IXANY;
1987                         break;
1988                 case SP_XONXOFF_INOUT:
1989                         data->term.c_iflag |= IXON | IXOFF | IXANY;
1990                         break;
1991                 default:
1992                         RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
1993                 }
1994         }
1995
1996         if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
1997                 RETURN_FAIL("tcsetattr() failed");
1998
1999 #ifdef __APPLE__
2000         if (baud_nonstd != B0) {
2001                 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
2002                         RETURN_FAIL("IOSSIOSPEED ioctl failed");
2003                 /*
2004                  * Set baud rates in data->term to correct, but incompatible
2005                  * with tcsetattr() value, same as delivered by tcgetattr().
2006                  */
2007                 if (cfsetspeed(&data->term, baud_nonstd) < 0)
2008                         RETURN_FAIL("cfsetspeed() failed");
2009         }
2010 #elif defined(__linux__)
2011 #ifdef USE_TERMIOS_SPEED
2012         if (baud_nonstd)
2013                 TRY(set_baudrate(port->fd, config->baudrate));
2014 #endif
2015 #ifdef USE_TERMIOX
2016         if (data->termiox_supported)
2017                 TRY(set_flow(port->fd, data));
2018 #endif
2019 #endif
2020
2021 #endif /* !_WIN32 */
2022
2023         RETURN_OK();
2024 }
2025
2026 SP_API enum sp_return sp_new_config(struct sp_port_config **config_ptr)
2027 {
2028         struct sp_port_config *config;
2029
2030         TRACE("%p", config_ptr);
2031
2032         if (!config_ptr)
2033                 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2034
2035         *config_ptr = NULL;
2036
2037         if (!(config = malloc(sizeof(struct sp_port_config))))
2038                 RETURN_ERROR(SP_ERR_MEM, "Config malloc failed");
2039
2040         config->baudrate = -1;
2041         config->bits = -1;
2042         config->parity = -1;
2043         config->stopbits = -1;
2044         config->rts = -1;
2045         config->cts = -1;
2046         config->dtr = -1;
2047         config->dsr = -1;
2048
2049         *config_ptr = config;
2050
2051         RETURN_OK();
2052 }
2053
2054 SP_API void sp_free_config(struct sp_port_config *config)
2055 {
2056         TRACE("%p", config);
2057
2058         if (!config)
2059                 DEBUG("Null config");
2060         else
2061                 free(config);
2062
2063         RETURN();
2064 }
2065
2066 SP_API enum sp_return sp_get_config(struct sp_port *port,
2067                                     struct sp_port_config *config)
2068 {
2069         struct port_data data;
2070
2071         TRACE("%p, %p", port, config);
2072
2073         CHECK_OPEN_PORT();
2074
2075         if (!config)
2076                 RETURN_ERROR(SP_ERR_ARG, "Null config");
2077
2078         TRY(get_config(port, &data, config));
2079
2080         RETURN_OK();
2081 }
2082
2083 SP_API enum sp_return sp_set_config(struct sp_port *port,
2084                                     const struct sp_port_config *config)
2085 {
2086         struct port_data data;
2087         struct sp_port_config prev_config;
2088
2089         TRACE("%p, %p", port, config);
2090
2091         CHECK_OPEN_PORT();
2092
2093         if (!config)
2094                 RETURN_ERROR(SP_ERR_ARG, "Null config");
2095
2096         TRY(get_config(port, &data, &prev_config));
2097         TRY(set_config(port, &data, config));
2098
2099         RETURN_OK();
2100 }
2101
2102 #define CREATE_ACCESSORS(x, type) \
2103 SP_API enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2104         struct port_data data; \
2105         struct sp_port_config config; \
2106         TRACE("%p, %d", port, x); \
2107         CHECK_OPEN_PORT(); \
2108         TRY(get_config(port, &data, &config)); \
2109         config.x = x; \
2110         TRY(set_config(port, &data, &config)); \
2111         RETURN_OK(); \
2112 } \
2113 SP_API enum sp_return sp_get_config_##x(const struct sp_port_config *config, \
2114                                         type *x) { \
2115         TRACE("%p, %p", config, x); \
2116         if (!config) \
2117                 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2118         *x = config->x; \
2119         RETURN_OK(); \
2120 } \
2121 SP_API enum sp_return sp_set_config_##x(struct sp_port_config *config, \
2122                                         type x) { \
2123         TRACE("%p, %d", config, x); \
2124         if (!config) \
2125                 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2126         config->x = x; \
2127         RETURN_OK(); \
2128 }
2129
2130 CREATE_ACCESSORS(baudrate, int)
2131 CREATE_ACCESSORS(bits, int)
2132 CREATE_ACCESSORS(parity, enum sp_parity)
2133 CREATE_ACCESSORS(stopbits, int)
2134 CREATE_ACCESSORS(rts, enum sp_rts)
2135 CREATE_ACCESSORS(cts, enum sp_cts)
2136 CREATE_ACCESSORS(dtr, enum sp_dtr)
2137 CREATE_ACCESSORS(dsr, enum sp_dsr)
2138 CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2139
2140 SP_API enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config,
2141                                                 enum sp_flowcontrol flowcontrol)
2142 {
2143         if (!config)
2144                 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
2145
2146         if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2147                 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
2148
2149         if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
2150                 config->xon_xoff = SP_XONXOFF_INOUT;
2151         else
2152                 config->xon_xoff = SP_XONXOFF_DISABLED;
2153
2154         if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
2155                 config->rts = SP_RTS_FLOW_CONTROL;
2156                 config->cts = SP_CTS_FLOW_CONTROL;
2157         } else {
2158                 if (config->rts == SP_RTS_FLOW_CONTROL)
2159                         config->rts = SP_RTS_ON;
2160                 config->cts = SP_CTS_IGNORE;
2161         }
2162
2163         if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
2164                 config->dtr = SP_DTR_FLOW_CONTROL;
2165                 config->dsr = SP_DSR_FLOW_CONTROL;
2166         } else {
2167                 if (config->dtr == SP_DTR_FLOW_CONTROL)
2168                         config->dtr = SP_DTR_ON;
2169                 config->dsr = SP_DSR_IGNORE;
2170         }
2171
2172         RETURN_OK();
2173 }
2174
2175 SP_API enum sp_return sp_set_flowcontrol(struct sp_port *port,
2176                                          enum sp_flowcontrol flowcontrol)
2177 {
2178         struct port_data data;
2179         struct sp_port_config config;
2180
2181         TRACE("%p, %d", port, flowcontrol);
2182
2183         CHECK_OPEN_PORT();
2184
2185         TRY(get_config(port, &data, &config));
2186
2187         TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2188
2189         TRY(set_config(port, &data, &config));
2190
2191         RETURN_OK();
2192 }
2193
2194 SP_API enum sp_return sp_get_signals(struct sp_port *port,
2195                                      enum sp_signal *signals)
2196 {
2197         TRACE("%p, %p", port, signals);
2198
2199         CHECK_OPEN_PORT();
2200
2201         if (!signals)
2202                 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2203
2204         DEBUG_FMT("Getting control signals for port %s", port->name);
2205
2206         *signals = 0;
2207 #ifdef _WIN32
2208         DWORD bits;
2209         if (GetCommModemStatus(port->hdl, &bits) == 0)
2210                 RETURN_FAIL("GetCommModemStatus() failed");
2211         if (bits & MS_CTS_ON)
2212                 *signals |= SP_SIG_CTS;
2213         if (bits & MS_DSR_ON)
2214                 *signals |= SP_SIG_DSR;
2215         if (bits & MS_RLSD_ON)
2216                 *signals |= SP_SIG_DCD;
2217         if (bits & MS_RING_ON)
2218                 *signals |= SP_SIG_RI;
2219 #else
2220         int bits;
2221         if (ioctl(port->fd, TIOCMGET, &bits) < 0)
2222                 RETURN_FAIL("TIOCMGET ioctl failed");
2223         if (bits & TIOCM_CTS)
2224                 *signals |= SP_SIG_CTS;
2225         if (bits & TIOCM_DSR)
2226                 *signals |= SP_SIG_DSR;
2227         if (bits & TIOCM_CAR)
2228                 *signals |= SP_SIG_DCD;
2229         if (bits & TIOCM_RNG)
2230                 *signals |= SP_SIG_RI;
2231 #endif
2232         RETURN_OK();
2233 }
2234
2235 SP_API enum sp_return sp_start_break(struct sp_port *port)
2236 {
2237         TRACE("%p", port);
2238
2239         CHECK_OPEN_PORT();
2240 #ifdef _WIN32
2241         if (SetCommBreak(port->hdl) == 0)
2242                 RETURN_FAIL("SetCommBreak() failed");
2243 #else
2244         if (ioctl(port->fd, TIOCSBRK, 1) < 0)
2245                 RETURN_FAIL("TIOCSBRK ioctl failed");
2246 #endif
2247
2248         RETURN_OK();
2249 }
2250
2251 SP_API enum sp_return sp_end_break(struct sp_port *port)
2252 {
2253         TRACE("%p", port);
2254
2255         CHECK_OPEN_PORT();
2256 #ifdef _WIN32
2257         if (ClearCommBreak(port->hdl) == 0)
2258                 RETURN_FAIL("ClearCommBreak() failed");
2259 #else
2260         if (ioctl(port->fd, TIOCCBRK, 1) < 0)
2261                 RETURN_FAIL("TIOCCBRK ioctl failed");
2262 #endif
2263
2264         RETURN_OK();
2265 }
2266
2267 SP_API int sp_last_error_code(void)
2268 {
2269         TRACE_VOID();
2270 #ifdef _WIN32
2271         RETURN_INT(GetLastError());
2272 #else
2273         RETURN_INT(errno);
2274 #endif
2275 }
2276
2277 SP_API char *sp_last_error_message(void)
2278 {
2279         TRACE_VOID();
2280
2281 #ifdef _WIN32
2282         LPVOID message;
2283         DWORD error = GetLastError();
2284
2285         FormatMessage(
2286                 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2287                 FORMAT_MESSAGE_FROM_SYSTEM |
2288                 FORMAT_MESSAGE_IGNORE_INSERTS,
2289                 NULL,
2290                 error,
2291                 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2292                 (LPTSTR) &message,
2293                 0, NULL );
2294
2295         RETURN_STRING(message);
2296 #else
2297         RETURN_STRING(strerror(errno));
2298 #endif
2299 }
2300
2301 SP_API void sp_free_error_message(char *message)
2302 {
2303         TRACE("%s", message);
2304
2305 #ifdef _WIN32
2306         LocalFree(message);
2307 #else
2308         (void)message;
2309 #endif
2310
2311         RETURN();
2312 }
2313
2314 SP_API void sp_set_debug_handler(void (*handler)(const char *format, ...))
2315 {
2316         TRACE("%p", handler);
2317
2318         sp_debug_handler = handler;
2319
2320         RETURN();
2321 }
2322
2323 SP_API void sp_default_debug_handler(const char *format, ...)
2324 {
2325         va_list args;
2326         va_start(args, format);
2327         if (getenv("LIBSERIALPORT_DEBUG")) {
2328                 fputs("sp: ", stderr);
2329                 vfprintf(stderr, format, args);
2330         }
2331         va_end(args);
2332 }
2333
2334 SP_API int sp_get_major_package_version(void)
2335 {
2336         return SP_PACKAGE_VERSION_MAJOR;
2337 }
2338
2339 SP_API int sp_get_minor_package_version(void)
2340 {
2341         return SP_PACKAGE_VERSION_MINOR;
2342 }
2343
2344 SP_API int sp_get_micro_package_version(void)
2345 {
2346         return SP_PACKAGE_VERSION_MICRO;
2347 }
2348
2349 SP_API const char *sp_get_package_version_string(void)
2350 {
2351         return SP_PACKAGE_VERSION_STRING;
2352 }
2353
2354 SP_API int sp_get_current_lib_version(void)
2355 {
2356         return SP_LIB_VERSION_CURRENT;
2357 }
2358
2359 SP_API int sp_get_revision_lib_version(void)
2360 {
2361         return SP_LIB_VERSION_REVISION;
2362 }
2363
2364 SP_API int sp_get_age_lib_version(void)
2365 {
2366         return SP_LIB_VERSION_AGE;
2367 }
2368
2369 SP_API const char *sp_get_lib_version_string(void)
2370 {
2371         return SP_LIB_VERSION_STRING;
2372 }
2373
2374 /** @} */