]> sigrok.org Git - libserialport.git/blob - serialport.c
Make sp_flush take an option for what to flush.
[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  *
9  * This program is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU Lesser General Public License as
11  * published by the Free Software Foundation, either version 3 of the
12  * License, or (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  */
22
23 #include <string.h>
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #include <fcntl.h>
27 #include <unistd.h>
28 #include <stdlib.h>
29 #include <errno.h>
30 #ifdef _WIN32
31 #include <windows.h>
32 #include <tchar.h>
33 #include <stdio.h>
34 #else
35 #include <termios.h>
36 #include <sys/ioctl.h>
37 #endif
38 #ifdef __APPLE__
39 #include <IOKit/IOKitLib.h>
40 #include <IOKit/serial/IOSerialKeys.h>
41 #include <IOKit/serial/ioss.h>
42 #include <sys/syslimits.h>
43 #endif
44 #ifdef __linux__
45 #include "libudev.h"
46 #include "linux/serial.h"
47 #include "linux_termios.h"
48 #if defined(TCGETX) && defined(TCSETX) && defined(HAVE_TERMIOX)
49 #define USE_TERMIOX
50 #endif
51 #endif
52
53 #include "libserialport.h"
54
55 struct port_data {
56 #ifdef _WIN32
57         DCB dcb;
58 #else
59         struct termios term;
60         int controlbits;
61 #ifdef USE_TERMIOX
62         int flow;
63 #endif
64 #endif
65 };
66
67 /* Standard baud rates. */
68 #ifdef _WIN32
69 #define BAUD_TYPE DWORD
70 #define BAUD(n) {CBR_##n, n}
71 #else
72 #define BAUD_TYPE speed_t
73 #define BAUD(n) {B##n, n}
74 #endif
75
76 struct std_baudrate {
77         BAUD_TYPE index;
78         int value;
79 };
80
81 const struct std_baudrate std_baudrates[] = {
82 #ifdef _WIN32
83         /*
84          * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
85          * have documented CBR_* macros.
86          */
87         BAUD(110), BAUD(300), BAUD(600), BAUD(1200), BAUD(2400), BAUD(4800),
88         BAUD(9600), BAUD(14400), BAUD(19200), BAUD(38400), BAUD(57600),
89         BAUD(115200), BAUD(128000), BAUD(256000),
90 #else
91         BAUD(50), BAUD(75), BAUD(110), BAUD(134), BAUD(150), BAUD(200),
92         BAUD(300), BAUD(600), BAUD(1200), BAUD(1800), BAUD(2400), BAUD(4800),
93         BAUD(9600), BAUD(19200), BAUD(38400), BAUD(57600), BAUD(115200),
94         BAUD(230400),
95 #if !defined(__APPLE__) && !defined(__OpenBSD__)
96         BAUD(460800),
97 #endif
98 #endif
99 };
100
101 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
102 #define NUM_STD_BAUDRATES ARRAY_SIZE(std_baudrates)
103
104 #define TRY(x) do { int ret = x; if (ret != SP_OK) return ret; } while (0)
105
106 /* Helper functions. */
107 static enum sp_return validate_port(struct sp_port *port);
108 static struct sp_port **list_append(struct sp_port **list, const char *portname);
109 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
110         struct sp_port_config *config);
111 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
112         const struct sp_port_config *config);
113
114 enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
115 {
116         struct sp_port *port;
117         int len;
118
119         if (!port_ptr)
120                 return SP_ERR_ARG;
121
122         *port_ptr = NULL;
123
124         if (!portname)
125                 return SP_ERR_ARG;
126
127         if (!(port = malloc(sizeof(struct sp_port))))
128                 return SP_ERR_MEM;
129
130         len = strlen(portname) + 1;
131
132         if (!(port->name = malloc(len))) {
133                 free(port);
134                 return SP_ERR_MEM;
135         }
136
137         memcpy(port->name, portname, len);
138
139 #ifdef _WIN32
140         port->hdl = INVALID_HANDLE_VALUE;
141 #else
142         port->fd = -1;
143 #endif
144
145         *port_ptr = port;
146
147         return SP_OK;
148 }
149
150 enum sp_return sp_copy_port(const struct sp_port *port, struct sp_port **copy_ptr)
151 {
152         if (!copy_ptr)
153                 return SP_ERR_ARG;
154
155         *copy_ptr = NULL;
156
157         if (!port || !port->name)
158                 return SP_ERR_ARG;
159
160         return sp_get_port_by_name(port->name, copy_ptr);
161 }
162
163 void sp_free_port(struct sp_port *port)
164 {
165         if (!port)
166                 return;
167
168         if (port->name)
169                 free(port->name);
170
171         free(port);
172 }
173
174 static struct sp_port **list_append(struct sp_port **list, const char *portname)
175 {
176         void *tmp;
177         unsigned int count;
178
179         for (count = 0; list[count]; count++);
180         if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
181                 goto fail;
182         list = tmp;
183         if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
184                 goto fail;
185         list[count + 1] = NULL;
186         return list;
187
188 fail:
189         sp_free_port_list(list);
190         return NULL;
191 }
192
193 enum sp_return sp_list_ports(struct sp_port ***list_ptr)
194 {
195         struct sp_port **list;
196         int ret = SP_OK;
197
198         if (!(list = malloc(sizeof(struct sp_port **))))
199                 return SP_ERR_MEM;
200
201         list[0] = NULL;
202
203 #ifdef _WIN32
204         HKEY key;
205         TCHAR *value, *data;
206         DWORD max_value_len, max_data_size, max_data_len;
207         DWORD value_len, data_size, data_len;
208         DWORD type, index = 0;
209         char *name;
210         int name_len;
211
212         if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
213                         0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS) {
214                 ret = SP_ERR_FAIL;
215                 goto out_done;
216         }
217         if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
218                                 &max_value_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS) {
219                 ret = SP_ERR_FAIL;
220                 goto out_close;
221         }
222         max_data_len = max_data_size / sizeof(TCHAR);
223         if (!(value = malloc((max_value_len + 1) * sizeof(TCHAR)))) {
224                 ret = SP_ERR_MEM;
225                 goto out_close;
226         }
227         if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR)))) {
228                 ret = SP_ERR_MEM;
229                 goto out_free_value;
230         }
231         while (
232                 value_len = max_value_len + 1,
233                 data_size = max_data_size,
234                 RegEnumValue(key, index, value, &value_len,
235                         NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
236         {
237                 data_len = data_size / sizeof(TCHAR);
238                 data[data_len] = '\0';
239 #ifdef UNICODE
240                 name_len = WideCharToMultiByte(CP_ACP, 0, data, -1, NULL, 0, NULL, NULL)
241 #else
242                 name_len = data_len + 1;
243 #endif
244                 if (!(name = malloc(name_len))) {
245                         ret = SP_ERR_MEM;
246                         goto out;
247                 }
248 #ifdef UNICODE
249                 WideCharToMultiByte(CP_ACP, 0, data, -1, name, name_len, NULL, NULL);
250 #else
251                 strcpy(name, data);
252 #endif
253                 if (type == REG_SZ && !(list = list_append(list, name))) {
254                         ret = SP_ERR_MEM;
255                         goto out;
256                 }
257                 index++;
258         }
259 out:
260         free(data);
261 out_free_value:
262         free(value);
263 out_close:
264         RegCloseKey(key);
265 out_done:
266 #endif
267 #ifdef __APPLE__
268         mach_port_t master;
269         CFMutableDictionaryRef classes;
270         io_iterator_t iter;
271         char *path;
272         io_object_t port;
273         CFTypeRef cf_path;
274         Boolean result;
275
276         if (IOMasterPort(MACH_PORT_NULL, &master) != KERN_SUCCESS) {
277                 ret = SP_ERR_FAIL;
278                 goto out_done;
279         }
280
281         if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue))) {
282                 ret = SP_ERR_FAIL;
283                 goto out_done;
284         }
285
286         CFDictionarySetValue(classes,
287                         CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
288
289         if (IOServiceGetMatchingServices(master, classes, &iter) != KERN_SUCCESS) {
290                 ret = SP_ERR_FAIL;
291                 goto out_done;
292         }
293
294         if (!(path = malloc(PATH_MAX))) {
295                 ret = SP_ERR_MEM;
296                 goto out_release;
297         }
298
299         while ((port = IOIteratorNext(iter))) {
300                 cf_path = IORegistryEntryCreateCFProperty(port,
301                                 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
302                 if (cf_path) {
303                         result = CFStringGetCString(cf_path,
304                                         path, PATH_MAX, kCFStringEncodingASCII);
305                         CFRelease(cf_path);
306                         if (result && !(list = list_append(list, path))) {
307                                 ret = SP_ERR_MEM;
308                                 IOObjectRelease(port);
309                                 goto out;
310                         }
311                 }
312                 IOObjectRelease(port);
313         }
314 out:
315         free(path);
316 out_release:
317         IOObjectRelease(iter);
318 out_done:
319 #endif
320 #ifdef __linux__
321         struct udev *ud;
322         struct udev_enumerate *ud_enumerate;
323         struct udev_list_entry *ud_list;
324         struct udev_list_entry *ud_entry;
325         const char *path;
326         struct udev_device *ud_dev, *ud_parent;
327         const char *name;
328         const char *driver;
329         int fd, ioctl_result;
330         struct serial_struct serial_info;
331
332         ud = udev_new();
333         ud_enumerate = udev_enumerate_new(ud);
334         udev_enumerate_add_match_subsystem(ud_enumerate, "tty");
335         udev_enumerate_scan_devices(ud_enumerate);
336         ud_list = udev_enumerate_get_list_entry(ud_enumerate);
337         udev_list_entry_foreach(ud_entry, ud_list) {
338                 path = udev_list_entry_get_name(ud_entry);
339                 ud_dev = udev_device_new_from_syspath(ud, path);
340                 /* If there is no parent device, this is a virtual tty. */
341                 ud_parent = udev_device_get_parent(ud_dev);
342                 if (ud_parent == NULL) {
343                         udev_device_unref(ud_dev);
344                         continue;
345                 }
346                 name = udev_device_get_devnode(ud_dev);
347                 /* The serial8250 driver has a hardcoded number of ports.
348                  * The only way to tell which actually exist on a given system
349                  * is to try to open them and make an ioctl call. */
350                 driver = udev_device_get_driver(ud_parent);
351                 if (driver && !strcmp(driver, "serial8250")) {
352                         if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY)) < 0)
353                                 goto skip;
354                         ioctl_result = ioctl(fd, TIOCGSERIAL, &serial_info);
355                         close(fd);
356                         if (ioctl_result != 0)
357                                 goto skip;
358                         if (serial_info.type == PORT_UNKNOWN)
359                                 goto skip;
360                 }
361                 list = list_append(list, name);
362 skip:
363                 udev_device_unref(ud_dev);
364                 if (!list) {
365                         ret = SP_ERR_MEM;
366                         goto out;
367                 }
368         }
369 out:
370         udev_enumerate_unref(ud_enumerate);
371         udev_unref(ud);
372 #endif
373
374         if (ret == SP_OK) {
375                 *list_ptr = list;
376         } else {
377                 if (list)
378                         sp_free_port_list(list);
379                 *list_ptr = NULL;
380         }
381
382         return ret;
383 }
384
385 void sp_free_port_list(struct sp_port **list)
386 {
387         unsigned int i;
388
389         for (i = 0; list[i]; i++)
390                 sp_free_port(list[i]);
391         free(list);
392 }
393
394 static enum sp_return validate_port(struct sp_port *port)
395 {
396         if (port == NULL)
397                 return 0;
398 #ifdef _WIN32
399         if (port->hdl == INVALID_HANDLE_VALUE)
400                 return 0;
401 #else
402         if (port->fd < 0)
403                 return 0;
404 #endif
405         return 1;
406 }
407
408 #define CHECK_PORT() do { if (!validate_port(port)) return SP_ERR_ARG; } while (0)
409
410 enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
411 {
412         if (!port)
413                 return SP_ERR_ARG;
414
415 #ifdef _WIN32
416         DWORD desired_access = 0, flags_and_attributes = 0;
417         char *escaped_port_name;
418
419         /* Prefix port name with '\\.\' to work with ports above COM9. */
420         if (!(escaped_port_name = malloc(strlen(port->name + 5))))
421                 return SP_ERR_MEM;
422         sprintf(escaped_port_name, "\\\\.\\%s", port->name);
423
424         /* Map 'flags' to the OS-specific settings. */
425         flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
426         if (flags & SP_MODE_READ)
427                 desired_access |= GENERIC_READ;
428         if (flags & SP_MODE_WRITE)
429                 desired_access |= GENERIC_WRITE;
430         if (flags & SP_MODE_NONBLOCK)
431                 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
432
433         port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
434                          OPEN_EXISTING, flags_and_attributes, 0);
435
436         free(escaped_port_name);
437
438         if (port->hdl == INVALID_HANDLE_VALUE)
439                 return SP_ERR_FAIL;
440 #else
441         int flags_local = 0;
442         struct port_data data;
443         struct sp_port_config config;
444         int ret;
445
446         /* Map 'flags' to the OS-specific settings. */
447         if (flags & (SP_MODE_READ | SP_MODE_WRITE))
448                 flags_local |= O_RDWR;
449         else if (flags & SP_MODE_READ)
450                 flags_local |= O_RDONLY;
451         else if (flags & SP_MODE_WRITE)
452                 flags_local |= O_WRONLY;
453         if (flags & SP_MODE_NONBLOCK)
454                 flags_local |= O_NONBLOCK;
455
456         if ((port->fd = open(port->name, flags_local)) < 0)
457                 return SP_ERR_FAIL;
458
459         ret = get_config(port, &data, &config);
460
461         if (ret < 0) {
462                 sp_close(port);
463                 return ret;
464         }
465
466         /* Turn off all serial port cooking. */
467         data.term.c_iflag &= ~(ISTRIP | INLCR | ICRNL);
468         data.term.c_oflag &= ~(ONLCR | OCRNL | ONOCR);
469 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
470         data.term.c_oflag &= ~OFILL;
471 #endif
472         /* Disable canonical mode, and don't echo input characters. */
473         data.term.c_lflag &= ~(ICANON | ECHO);
474
475         /* Ignore modem status lines; enable receiver */
476         data.term.c_cflag |= (CLOCAL | CREAD);
477
478         ret = set_config(port, &data, &config);
479
480         if (ret < 0) {
481                 sp_close(port);
482                 return ret;
483         }
484 #endif
485
486         return SP_OK;
487 }
488
489 enum sp_return sp_close(struct sp_port *port)
490 {
491         CHECK_PORT();
492
493 #ifdef _WIN32
494         /* Returns non-zero upon success, 0 upon failure. */
495         if (CloseHandle(port->hdl) == 0)
496                 return SP_ERR_FAIL;
497         port->hdl = INVALID_HANDLE_VALUE;
498 #else
499         /* Returns 0 upon success, -1 upon failure. */
500         if (close(port->fd) == -1)
501                 return SP_ERR_FAIL;
502         port->fd = -1;
503 #endif
504
505         return SP_OK;
506 }
507
508 enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
509 {
510         CHECK_PORT();
511
512 #ifdef _WIN32
513         DWORD flags = 0;
514         if (buffers & SP_BUF_INPUT)
515                 flags |= PURGE_RXCLEAR;
516         if (buffers & SP_BUF_OUTPUT)
517                 flags |= PURGE_TXCLEAR;
518
519         /* Returns non-zero upon success, 0 upon failure. */
520         if (PurgeComm(port->hdl, flags) == 0)
521                 return SP_ERR_FAIL;
522 #else
523         int flags = 0;
524         if (buffers & SP_BUF_BOTH)
525                 flags = TCIOFLUSH;
526         else if (buffers & SP_BUF_INPUT)
527                 flags = TCIFLUSH;
528         if (buffers & SP_BUF_OUTPUT)
529                 flags = TCOFLUSH;
530
531         /* Returns 0 upon success, -1 upon failure. */
532         if (tcflush(port->fd, flags) < 0)
533                 return SP_ERR_FAIL;
534 #endif
535         return SP_OK;
536 }
537
538 enum sp_return sp_write(struct sp_port *port, const void *buf, size_t count)
539 {
540         CHECK_PORT();
541
542         if (!buf)
543                 return SP_ERR_ARG;
544
545 #ifdef _WIN32
546         DWORD written = 0;
547
548         /* Returns non-zero upon success, 0 upon failure. */
549         if (WriteFile(port->hdl, buf, count, &written, NULL) == 0)
550                 return SP_ERR_FAIL;
551         return written;
552 #else
553         /* Returns the number of bytes written, or -1 upon failure. */
554         ssize_t written = write(port->fd, buf, count);
555
556         if (written < 0)
557                 return SP_ERR_FAIL;
558         else
559                 return written;
560 #endif
561 }
562
563 enum sp_return sp_read(struct sp_port *port, void *buf, size_t count)
564 {
565         CHECK_PORT();
566
567         if (!buf)
568                 return SP_ERR_ARG;
569
570 #ifdef _WIN32
571         DWORD bytes_read = 0;
572
573         /* Returns non-zero upon success, 0 upon failure. */
574         if (ReadFile(port->hdl, buf, count, &bytes_read, NULL) == 0)
575                 return SP_ERR_FAIL;
576         return bytes_read;
577 #else
578         ssize_t bytes_read;
579
580         /* Returns the number of bytes read, or -1 upon failure. */
581         if ((bytes_read = read(port->fd, buf, count)) < 0)
582                 return SP_ERR_FAIL;
583         return bytes_read;
584 #endif
585 }
586
587 #ifdef __linux__
588 static enum sp_return get_baudrate(int fd, int *baudrate)
589 {
590         void *data;
591
592         if (!(data = malloc(get_termios_size())))
593                 return SP_ERR_MEM;
594
595         if (ioctl(fd, get_termios_get_ioctl(), data) < 0)
596                 return SP_ERR_FAIL;
597
598         *baudrate = get_termios_speed(data);
599
600         return SP_OK;
601 }
602
603 static enum sp_return set_baudrate(int fd, int baudrate)
604 {
605         void *data;
606
607         if (!(data = malloc(get_termios_size())))
608                 return SP_ERR_MEM;
609
610         if (ioctl(fd, get_termios_get_ioctl(), data) < 0)
611                 return SP_ERR_FAIL;
612
613         set_termios_speed(data, baudrate);
614
615         if (ioctl(fd, get_termios_set_ioctl(), data) < 0)
616                 return SP_ERR_FAIL;
617
618         return SP_OK;
619 }
620
621 #ifdef USE_TERMIOX
622 static enum sp_return get_flow(int fd, int *flow)
623 {
624         void *data;
625
626         if (!(data = malloc(get_termiox_size())))
627                 return SP_ERR_MEM;
628
629         if (ioctl(fd, TCGETX, data) < 0)
630                 return SP_ERR_FAIL;
631
632         *flow = get_termiox_flow(data);
633
634         return SP_OK;
635 }
636
637 static enum sp_return set_flow(int fd, int flow)
638 {
639         void *data;
640
641         if (!(data = malloc(get_termiox_size())))
642                 return SP_ERR_MEM;
643
644         if (ioctl(fd, TCGETX, data) < 0)
645                 return SP_ERR_FAIL;
646
647         set_termiox_flow(data, flow);
648
649         if (ioctl(fd, TCSETX, data) < 0)
650                 return SP_ERR_FAIL;
651
652         return SP_OK;
653 }
654 #endif /* USE_TERMIOX */
655 #endif /* __linux__ */
656
657 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
658         struct sp_port_config *config)
659 {
660         unsigned int i;
661
662 #ifdef _WIN32
663         if (!GetCommState(port->hdl, &data->dcb))
664                 return SP_ERR_FAIL;
665
666         for (i = 0; i < NUM_STD_BAUDRATES; i++) {
667                 if (data->dcb.BaudRate == std_baudrates[i].index) {
668                         config->baudrate = std_baudrates[i].value;
669                         break;
670                 }
671         }
672
673         if (i == NUM_STD_BAUDRATES)
674                 /* BaudRate field can be either an index or a custom baud rate. */
675                 config->baudrate = data->dcb.BaudRate;
676
677         config->bits = data->dcb.ByteSize;
678
679         if (data->dcb.fParity)
680                 switch (data->dcb.Parity) {
681                 case NOPARITY:
682                         config->parity = SP_PARITY_NONE;
683                         break;
684                 case EVENPARITY:
685                         config->parity = SP_PARITY_EVEN;
686                         break;
687                 case ODDPARITY:
688                         config->parity = SP_PARITY_ODD;
689                         break;
690                 default:
691                         config->parity = -1;
692                 }
693         else
694                 config->parity = SP_PARITY_NONE;
695
696         switch (data->dcb.StopBits) {
697         case ONESTOPBIT:
698                 config->stopbits = 1;
699                 break;
700         case TWOSTOPBITS:
701                 config->stopbits = 2;
702                 break;
703         default:
704                 config->stopbits = -1;
705         }
706
707         switch (data->dcb.fRtsControl) {
708         case RTS_CONTROL_DISABLE:
709                 config->rts = SP_RTS_OFF;
710                 break;
711         case RTS_CONTROL_ENABLE:
712                 config->rts = SP_RTS_ON;
713                 break;
714         case RTS_CONTROL_HANDSHAKE:
715                 config->rts = SP_RTS_FLOW_CONTROL;
716                 break;
717         default:
718                 config->rts = -1;
719         }
720
721         config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
722
723         switch (data->dcb.fDtrControl) {
724         case DTR_CONTROL_DISABLE:
725                 config->dtr = SP_DTR_OFF;
726                 break;
727         case DTR_CONTROL_ENABLE:
728                 config->dtr = SP_DTR_ON;
729                 break;
730         case DTR_CONTROL_HANDSHAKE:
731                 config->dtr = SP_DTR_FLOW_CONTROL;
732                 break;
733         default:
734                 config->dtr = -1;
735         }
736
737         config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
738
739         if (data->dcb.fInX) {
740                 if (data->dcb.fOutX)
741                         config->xon_xoff = SP_XONXOFF_INOUT;
742                 else
743                         config->xon_xoff = SP_XONXOFF_IN;
744         } else {
745                 if (data->dcb.fOutX)
746                         config->xon_xoff = SP_XONXOFF_OUT;
747                 else
748                         config->xon_xoff = SP_XONXOFF_DISABLED;
749         }
750
751 #else // !_WIN32
752
753         if (tcgetattr(port->fd, &data->term) < 0)
754                 return SP_ERR_FAIL;
755
756         if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
757                 return SP_ERR_FAIL;
758
759 #ifdef USE_TERMIOX
760         TRY(get_flow(port->fd, &data->flow));
761 #endif
762
763         for (i = 0; i < NUM_STD_BAUDRATES; i++) {
764                 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
765                         config->baudrate = std_baudrates[i].value;
766                         break;
767                 }
768         }
769
770         if (i == NUM_STD_BAUDRATES) {
771 #ifdef __APPLE__
772                 config->baudrate = (int)data->term.c_ispeed;
773 #elif defined(__linux__)
774                 TRY(get_baudrate(port->fd, &config->baudrate));
775 #else
776                 config->baudrate = -1;
777 #endif
778         }
779
780         switch (data->term.c_cflag & CSIZE) {
781         case CS8:
782                 config->bits = 8;
783                 break;
784         case CS7:
785                 config->bits = 7;
786                 break;
787         case CS6:
788                 config->bits = 6;
789                 break;
790         case CS5:
791                 config->bits = 5;
792                 break;
793         default:
794                 config->bits = -1;
795         }
796
797         if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
798                 config->parity = SP_PARITY_NONE;
799         else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
800                 config->parity = -1;
801         else
802                 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
803
804         config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
805
806         if (data->term.c_cflag & CRTSCTS) {
807                 config->rts = SP_RTS_FLOW_CONTROL;
808                 config->cts = SP_CTS_FLOW_CONTROL;
809         } else {
810 #ifdef USE_TERMIOX
811                 if (data->flow & RTS_FLOW)
812                         config->rts = SP_RTS_FLOW_CONTROL;
813                 else
814                         config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
815
816                 config->cts = (data->flow & CTS_FLOW) ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
817 #else
818                 config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
819                 config->cts = SP_CTS_IGNORE;
820 #endif
821         }
822
823 #ifdef USE_TERMIOX
824         if (data->flow & DTR_FLOW)
825                 config->dtr = SP_DTR_FLOW_CONTROL;
826         else
827                 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
828
829         config->dsr = (data->flow & DSR_FLOW) ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
830 #else
831         config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
832         config->dsr = SP_DSR_IGNORE;
833 #endif
834
835         if (data->term.c_iflag & IXOFF) {
836                 if (data->term.c_iflag & IXON)
837                         config->xon_xoff = SP_XONXOFF_INOUT;
838                 else
839                         config->xon_xoff = SP_XONXOFF_IN;
840         } else {
841                 if (data->term.c_iflag & IXON)
842                         config->xon_xoff = SP_XONXOFF_OUT;
843                 else
844                         config->xon_xoff = SP_XONXOFF_DISABLED;
845         }
846 #endif
847
848         return SP_OK;
849 }
850
851 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
852         const struct sp_port_config *config)
853 {
854         unsigned int i;
855 #ifdef __APPLE__
856         BAUD_TYPE baud_nonstd;
857
858         baud_nonstd = B0;
859 #endif
860 #ifdef __linux__
861         int baud_nonstd = 0;
862 #endif
863
864 #ifdef _WIN32
865         if (config->baudrate >= 0) {
866                 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
867                         if (config->baudrate == std_baudrates[i].value) {
868                                 data->dcb.BaudRate = std_baudrates[i].index;
869                                 break;
870                         }
871                 }
872
873                 if (i == NUM_STD_BAUDRATES)
874                         data->dcb.BaudRate = config->baudrate;
875         }
876
877         if (config->bits >= 0)
878                 data->dcb.ByteSize = config->bits;
879
880         if (config->parity >= 0) {
881                 switch (config->parity) {
882                 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
883                 case SP_PARITY_NONE:
884                         data->dcb.Parity = NOPARITY;
885                         break;
886                 case SP_PARITY_EVEN:
887                         data->dcb.Parity = EVENPARITY;
888                         break;
889                 case SP_PARITY_ODD:
890                         data->dcb.Parity = ODDPARITY;
891                         break;
892                 default:
893                         return SP_ERR_ARG;
894                 }
895         }
896
897         if (config->stopbits >= 0) {
898                 switch (config->stopbits) {
899                 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
900                 case 1:
901                         data->dcb.StopBits = ONESTOPBIT;
902                         break;
903                 case 2:
904                         data->dcb.StopBits = TWOSTOPBITS;
905                         break;
906                 default:
907                         return SP_ERR_ARG;
908                 }
909         }
910
911         if (config->rts >= 0) {
912                 switch (config->rts) {
913                 case SP_RTS_OFF:
914                         data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
915                         break;
916                 case SP_RTS_ON:
917                         data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
918                         break;
919                 case SP_RTS_FLOW_CONTROL:
920                         data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
921                         break;
922                 default:
923                         return SP_ERR_ARG;
924                 }
925         }
926
927         if (config->cts >= 0) {
928                 switch (config->cts) {
929                 case SP_CTS_IGNORE:
930                         data->dcb.fOutxCtsFlow = FALSE;
931                         break;
932                 case SP_CTS_FLOW_CONTROL:
933                         data->dcb.fOutxCtsFlow = TRUE;
934                         break;
935                 default:
936                         return SP_ERR_ARG;
937                 }
938         }
939
940         if (config->dtr >= 0) {
941                 switch (config->dtr) {
942                 case SP_DTR_OFF:
943                         data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
944                         break;
945                 case SP_DTR_ON:
946                         data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
947                         break;
948                 case SP_DTR_FLOW_CONTROL:
949                         data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
950                         break;
951                 default:
952                         return SP_ERR_ARG;
953                 }
954         }
955
956         if (config->dsr >= 0) {
957                 switch (config->dsr) {
958                 case SP_DSR_IGNORE:
959                         data->dcb.fOutxDsrFlow = FALSE;
960                         break;
961                 case SP_DSR_FLOW_CONTROL:
962                         data->dcb.fOutxDsrFlow = TRUE;
963                         break;
964                 default:
965                         return SP_ERR_ARG;
966                 }
967         }
968
969         if (config->xon_xoff >= 0) {
970                 switch (config->xon_xoff) {
971                 case SP_XONXOFF_DISABLED:
972                         data->dcb.fInX = FALSE;
973                         data->dcb.fOutX = FALSE;
974                         break;
975                 case SP_XONXOFF_IN:
976                         data->dcb.fInX = TRUE;
977                         data->dcb.fOutX = FALSE;
978                         break;
979                 case SP_XONXOFF_OUT:
980                         data->dcb.fInX = FALSE;
981                         data->dcb.fOutX = TRUE;
982                         break;
983                 case SP_XONXOFF_INOUT:
984                         data->dcb.fInX = TRUE;
985                         data->dcb.fOutX = TRUE;
986                         break;
987                 default:
988                         return SP_ERR_ARG;
989                 }
990         }
991
992         if (!SetCommState(port->hdl, &data->dcb))
993                 return SP_ERR_FAIL;
994
995 #else /* !_WIN32 */
996
997         int controlbits;
998
999         if (config->baudrate >= 0) {
1000                 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1001                         if (config->baudrate == std_baudrates[i].value) {
1002                                 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
1003                                         return SP_ERR_FAIL;
1004
1005                                 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
1006                                         return SP_ERR_FAIL;
1007                                 break;
1008                         }
1009                 }
1010
1011                 /* Non-standard baud rate */
1012                 if (i == NUM_STD_BAUDRATES) {
1013 #ifdef __APPLE__
1014                         /* Set "dummy" baud rate */
1015                         if (cfsetspeed(&data->term, B9600) < 0)
1016                                 return SP_ERR_FAIL;
1017                         baud_nonstd = config->baudrate;
1018 #elif defined(__linux__)
1019                         baud_nonstd = 1;
1020 #else
1021                         return SP_ERR_ARG;
1022 #endif
1023                 }
1024         }
1025
1026         if (config->bits >= 0) {
1027                 data->term.c_cflag &= ~CSIZE;
1028                 switch (config->bits) {
1029                 case 8:
1030                         data->term.c_cflag |= CS8;
1031                         break;
1032                 case 7:
1033                         data->term.c_cflag |= CS7;
1034                         break;
1035                 case 6:
1036                         data->term.c_cflag |= CS6;
1037                         break;
1038                 case 5:
1039                         data->term.c_cflag |= CS5;
1040                         break;
1041                 default:
1042                         return SP_ERR_ARG;
1043                 }
1044         }
1045
1046         if (config->parity >= 0) {
1047                 data->term.c_iflag &= ~IGNPAR;
1048                 data->term.c_cflag &= ~(PARENB | PARODD);
1049                 switch (config->parity) {
1050                 case SP_PARITY_NONE:
1051                         data->term.c_iflag |= IGNPAR;
1052                         break;
1053                 case SP_PARITY_EVEN:
1054                         data->term.c_cflag |= PARENB;
1055                         break;
1056                 case SP_PARITY_ODD:
1057                         data->term.c_cflag |= PARENB | PARODD;
1058                         break;
1059                 default:
1060                         return SP_ERR_ARG;
1061                 }
1062         }
1063
1064         if (config->stopbits >= 0) {
1065                 data->term.c_cflag &= ~CSTOPB;
1066                 switch (config->stopbits) {
1067                 case 1:
1068                         data->term.c_cflag &= ~CSTOPB;
1069                         break;
1070                 case 2:
1071                         data->term.c_cflag |= CSTOPB;
1072                         break;
1073                 default:
1074                         return SP_ERR_ARG;
1075                 }
1076         }
1077
1078         if (config->rts >= 0 || config->cts >= 0) {
1079 #ifdef USE_TERMIOX
1080                 data->flow &= ~(RTS_FLOW | CTS_FLOW);
1081                 switch (config->rts) {
1082                         case SP_RTS_OFF:
1083                         case SP_RTS_ON:
1084                                 controlbits = TIOCM_RTS;
1085                                 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
1086                                                 &controlbits) < 0)
1087                                         return SP_ERR_FAIL;
1088                                 break;
1089                         case SP_RTS_FLOW_CONTROL:
1090                                 data->flow |= RTS_FLOW;
1091                                 break;
1092                         default:
1093                                 break;
1094                 }
1095                 if (config->cts == SP_CTS_FLOW_CONTROL)
1096                         data->flow |= CTS_FLOW;
1097
1098                 if (data->flow & (RTS_FLOW | CTS_FLOW))
1099                         data->term.c_iflag |= CRTSCTS;
1100                 else
1101                         data->term.c_iflag &= ~CRTSCTS;
1102 #else
1103                 /* Asymmetric use of RTS/CTS not supported. */
1104                 if (data->term.c_iflag & CRTSCTS) {
1105                         /* Flow control can only be disabled for both RTS & CTS together. */
1106                         if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
1107                                 if (config->cts != SP_CTS_IGNORE)
1108                                         return SP_ERR_ARG;
1109                         }
1110                         if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
1111                                 if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
1112                                         return SP_ERR_ARG;
1113                         }
1114                 } else {
1115                         /* Flow control can only be enabled for both RTS & CTS together. */
1116                         if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
1117                                 ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
1118                                 return SP_ERR_ARG;
1119                 }
1120
1121                 if (config->rts >= 0) {
1122                         if (config->rts == SP_RTS_FLOW_CONTROL) {
1123                                 data->term.c_iflag |= CRTSCTS;
1124                         } else {
1125                                 controlbits = TIOCM_RTS;
1126                                 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
1127                                                 &controlbits) < 0)
1128                                         return SP_ERR_FAIL;
1129                         }
1130                 }
1131 #endif
1132         }
1133
1134         if (config->dtr >= 0 || config->dsr >= 0) {
1135 #ifdef USE_TERMIOX
1136                 data->flow &= ~(DTR_FLOW | DSR_FLOW);
1137                 switch (config->dtr) {
1138                         case SP_DTR_OFF:
1139                         case SP_DTR_ON:
1140                                 controlbits = TIOCM_DTR;
1141                                 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
1142                                                 &controlbits) < 0)
1143                                         return SP_ERR_FAIL;
1144                                 break;
1145                         case SP_DTR_FLOW_CONTROL:
1146                                 data->flow |= DTR_FLOW;
1147                                 break;
1148                         default:
1149                                 break;
1150                 }
1151                 if (config->dsr == SP_DSR_FLOW_CONTROL)
1152                         data->flow |= DSR_FLOW;
1153 #else
1154                 /* DTR/DSR flow control not supported. */
1155                 if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
1156                         return SP_ERR_ARG;
1157
1158                 if (config->dtr >= 0) {
1159                         controlbits = TIOCM_DTR;
1160                         if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
1161                                         &controlbits) < 0)
1162                                 return SP_ERR_FAIL;
1163                 }
1164 #endif
1165         }
1166
1167         if (config->xon_xoff >= 0) {
1168                 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
1169                 switch (config->xon_xoff) {
1170                 case SP_XONXOFF_DISABLED:
1171                         break;
1172                 case SP_XONXOFF_IN:
1173                         data->term.c_iflag |= IXOFF;
1174                         break;
1175                 case SP_XONXOFF_OUT:
1176                         data->term.c_iflag |= IXON | IXANY;
1177                         break;
1178                 case SP_XONXOFF_INOUT:
1179                         data->term.c_iflag |= IXON | IXOFF | IXANY;
1180                         break;
1181                 default:
1182                         return SP_ERR_ARG;
1183                 }
1184         }
1185
1186         if (tcsetattr(port->fd, TCSADRAIN, &data->term) < 0)
1187                 return SP_ERR_FAIL;
1188
1189 #ifdef __APPLE__
1190         if (baud_nonstd != B0) {
1191                 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
1192                         return SP_ERR_FAIL;
1193                 /* Set baud rates in data->term to correct, but incompatible
1194                  * with tcsetattr() value, same as delivered by tcgetattr(). */
1195                 if (cfsetspeed(&data->term, baud_nonstd) < 0)
1196                         return SP_ERR_FAIL;
1197         }
1198 #elif defined(__linux__)
1199         if (baud_nonstd)
1200                 TRY(set_baudrate(port->fd, config->baudrate));
1201 #ifdef USE_TERMIOX
1202         TRY(set_flow(port->fd, data->flow));
1203 #endif
1204 #endif
1205
1206 #endif /* !_WIN32 */
1207
1208         return SP_OK;
1209 }
1210
1211 enum sp_return sp_set_config(struct sp_port *port, const struct sp_port_config *config)
1212 {
1213         struct port_data data;
1214         struct sp_port_config prev_config;
1215
1216         CHECK_PORT();
1217
1218         if (!config)
1219                 return SP_ERR_ARG;
1220
1221         TRY(get_config(port, &data, &prev_config));
1222         TRY(set_config(port, &data, config));
1223
1224         return SP_OK;
1225 }
1226
1227 #define CREATE_SETTER(x, type) int sp_set_##x(struct sp_port *port, type x) { \
1228         struct port_data data; \
1229         struct sp_port_config config; \
1230         CHECK_PORT(); \
1231         TRY(get_config(port, &data, &config)); \
1232         config.x = x; \
1233         TRY(set_config(port, &data, &config)); \
1234         return SP_OK; \
1235 }
1236
1237 CREATE_SETTER(baudrate, int)
1238 CREATE_SETTER(bits, int)
1239 CREATE_SETTER(parity, enum sp_parity)
1240 CREATE_SETTER(stopbits, int)
1241 CREATE_SETTER(rts, enum sp_rts)
1242 CREATE_SETTER(cts, enum sp_cts)
1243 CREATE_SETTER(dtr, enum sp_dtr)
1244 CREATE_SETTER(dsr, enum sp_dsr)
1245 CREATE_SETTER(xon_xoff, enum sp_xonxoff)
1246
1247 enum sp_return sp_set_flowcontrol(struct sp_port *port, enum sp_flowcontrol flowcontrol)
1248 {
1249         struct port_data data;
1250         struct sp_port_config config;
1251
1252         CHECK_PORT();
1253
1254         TRY(get_config(port, &data, &config));
1255
1256         if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
1257                 config.xon_xoff = SP_XONXOFF_INOUT;
1258         else
1259                 config.xon_xoff = SP_XONXOFF_DISABLED;
1260
1261         if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
1262                 config.rts = SP_RTS_FLOW_CONTROL;
1263                 config.cts = SP_CTS_FLOW_CONTROL;
1264         } else {
1265                 if (config.rts == SP_RTS_FLOW_CONTROL)
1266                         config.rts = SP_RTS_ON;
1267                 config.cts = SP_CTS_IGNORE;
1268         }
1269
1270         if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
1271                 config.dtr = SP_DTR_FLOW_CONTROL;
1272                 config.dsr = SP_DSR_FLOW_CONTROL;
1273         } else {
1274                 if (config.dtr == SP_DTR_FLOW_CONTROL)
1275                         config.dtr = SP_DTR_ON;
1276                 config.dsr = SP_DSR_IGNORE;
1277         }
1278
1279         TRY(set_config(port, &data, &config));
1280
1281         return SP_OK;
1282 }
1283
1284 int sp_last_error_code(void)
1285 {
1286 #ifdef _WIN32
1287         return GetLastError();
1288 #else
1289         return errno;
1290 #endif
1291 }
1292
1293 char *sp_last_error_message(void)
1294 {
1295 #ifdef _WIN32
1296         LPVOID message;
1297         DWORD error = GetLastError();
1298
1299         FormatMessage(
1300                 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1301                 FORMAT_MESSAGE_FROM_SYSTEM |
1302                 FORMAT_MESSAGE_IGNORE_INSERTS,
1303                 NULL,
1304                 error,
1305                 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1306                 (LPTSTR) &message,
1307                 0, NULL );
1308
1309         return message;
1310 #else
1311         return strerror(errno);
1312 #endif
1313 }
1314
1315 void sp_free_error_message(char *message)
1316 {
1317 #ifdef _WIN32
1318         LocalFree(message);
1319 #else
1320         (void)message;
1321 #endif
1322 }