]> sigrok.org Git - libserialport.git/blob - serialport.c
Always return an empty port list unless allocation fails.
[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  *
8  * This program is free software: you can redistribute it and/or modify
9  * it under the terms of the GNU Lesser General Public License as
10  * published by the Free Software Foundation, either version 3 of the
11  * License, or (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public License
19  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
20  */
21
22 #include <string.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <fcntl.h>
26 #include <unistd.h>
27 #include <stdlib.h>
28 #include <errno.h>
29 #ifdef _WIN32
30 #include <windows.h>
31 #include <tchar.h>
32 #else
33 #include <termios.h>
34 #include <sys/ioctl.h>
35 #endif
36 #ifdef __APPLE__
37 #include <IOKit/IOKitLib.h>
38 #include <IOKit/serial/IOSerialKeys.h>
39 #include <sys/syslimits.h>
40 #endif
41 #ifdef __linux__
42 #include "libudev.h"
43 #include "linux/serial.h"
44 #endif
45
46 #include "serialport.h"
47
48 static char **sp_list_append(char **list, void *data, size_t len)
49 {
50         void *tmp;
51         unsigned int count;
52         for (count = 0; list[count]; count++);
53         if (!(tmp = realloc(list, sizeof(char *) * (count + 2))))
54                 goto fail;
55         list = tmp;
56         if (!(list[count] = malloc(len)))
57                 goto fail;
58         memcpy(list[count], data, len);
59         list[count + 1] = NULL;
60         return list;
61 fail:
62         sp_free_port_list(list);
63         return NULL;
64 }
65
66 /**
67  * List the serial ports available on the system.
68  *
69  * @return A null-terminated array of port name strings.
70  */
71 char **sp_list_ports(void)
72 {
73         char **list;
74
75         if (!(list = malloc(sizeof(char *))))
76                 return NULL;
77
78         list[0] = NULL;
79
80 #ifdef _WIN32
81         HKEY key;
82         TCHAR *value, *data;
83         DWORD max_value_len, max_data_size, max_data_len;
84         DWORD value_len, data_size, data_len;
85         DWORD type, index = 0;
86
87         if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
88                         0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS)
89                 return NULL;
90         if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
91                                 &max_value_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS)
92                 goto out_close;
93         max_data_len = max_data_size / sizeof(TCHAR);
94         if (!(value = malloc((max_value_len + 1) * sizeof(TCHAR))))
95                 goto out_close;
96         if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR))))
97                 goto out_free_value;
98         while (
99                 value_len = max_value_len,
100                 data_size = max_data_size,
101                 RegEnumValue(key, index, value, &value_len,
102                         NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
103         {
104                 data_len = data_size / sizeof(TCHAR);
105                 data[data_len] = '\0';
106                 if (type == REG_SZ)
107                         if (!(list = sp_list_append(list,
108                                         data, (data_len + 1) * sizeof(TCHAR))))
109                                 goto out;
110                 index++;
111         }
112 out:
113         free(data);
114 out_free_value:
115         free(value);
116 out_close:
117         RegCloseKey(key);
118         return list;
119 #endif
120 #ifdef __APPLE__
121         mach_port_t master;
122         CFMutableDictionaryRef classes;
123         io_iterator_t iter;
124         char *path;
125         io_object_t port;
126         CFTypeRef cf_path;
127         Boolean result;
128
129         if (IOMasterPort(MACH_PORT_NULL, &master) != KERN_SUCCESS)
130                 return NULL;
131
132         if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue)))
133                 return NULL;
134
135         CFDictionarySetValue(classes,
136                         CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
137
138         if (!(IOServiceGetMatchingServices(master, classes, &iter)))
139                 return NULL;
140
141         if (!(path = malloc(PATH_MAX)))
142                 goto out_release;
143
144         while ((port = IOIteratorNext(iter))) {
145                 cf_path = IORegistryEntryCreateCFProperty(port,
146                                 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
147                 if (cf_path) {
148                         result = CFStringGetCString(cf_path,
149                                         path, PATH_MAX, kCFStringEncodingASCII);
150                         CFRelease(cf_path);
151                         if (result)
152                                 if (!(list = sp_list_append(list, path, strlen(path) + 1)))
153                                 {
154                                         IOObjectRelease(port);
155                                         goto out;
156                                 }
157                 }
158                 IOObjectRelease(port);
159         }
160
161 out:
162         free(path);
163 out_release:
164         IOObjectRelease(iter);
165         return list;
166 #endif
167 #ifdef __linux__
168         struct udev *ud;
169         struct udev_enumerate *ud_enumerate;
170         struct udev_list_entry *ud_list;
171         struct udev_list_entry *ud_entry;
172         const char *path;
173         struct udev_device *ud_dev, *ud_parent;
174         const char *name;
175         const char *driver;
176         int fd, ioctl_result;
177         struct serial_struct serial_info;
178
179         ud = udev_new();
180         ud_enumerate = udev_enumerate_new(ud);
181         udev_enumerate_add_match_subsystem(ud_enumerate, "tty");
182         udev_enumerate_scan_devices(ud_enumerate);
183         ud_list = udev_enumerate_get_list_entry(ud_enumerate);
184         udev_list_entry_foreach(ud_entry, ud_list)
185         {
186                 path = udev_list_entry_get_name(ud_entry);
187                 ud_dev = udev_device_new_from_syspath(ud, path);
188                 /* If there is no parent device, this is a virtual tty. */
189                 ud_parent = udev_device_get_parent(ud_dev);
190                 if (ud_parent == NULL)
191                 {
192                         udev_device_unref(ud_dev);
193                         continue;
194                 }
195                 name = udev_device_get_devnode(ud_dev);
196                 /* The serial8250 driver has a hardcoded number of ports.
197                  * The only way to tell which actually exist on a given system
198                  * is to try to open them and make an ioctl call. */
199                 driver = udev_device_get_driver(ud_parent);
200                 if (driver && !strcmp(driver, "serial8250"))
201                 {
202                         if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY)) < 0)
203                                 goto skip;
204                         ioctl_result = ioctl(fd, TIOCGSERIAL, &serial_info);
205                         close(fd);
206                         if (ioctl_result != 0)
207                                 goto skip;
208                         if (serial_info.type == PORT_UNKNOWN)
209                                 goto skip;
210                 }
211                 list = sp_list_append(list, (void *)name, strlen(name) + 1);
212 skip:
213                 udev_device_unref(ud_dev);
214                 if (!list)
215                         goto out;
216         }
217 out:
218         udev_enumerate_unref(ud_enumerate);
219         udev_unref(ud);
220         return list;
221 #endif
222 }
223
224 /**
225  * Free a port list returned by sp_list_ports.
226  */
227 void sp_free_port_list(char **list)
228 {
229         unsigned int i;
230         for (i = 0; list[i]; i++)
231                 free(list[i]);
232         free(list);
233 }
234
235 static int sp_validate_port(struct sp_port *port)
236 {
237         if (port == NULL)
238                 return 0;
239 #ifdef _WIN32
240         if (port->hdl == INVALID_HANDLE_VALUE)
241                 return 0;
242 #else
243         if (port->fd < 0)
244                 return 0;
245 #endif
246         return 1;
247 }
248
249 #define CHECK_PORT() do { if (!sp_validate_port(port)) return SP_ERR_ARG; } while (0)
250
251 /**
252  * Open the specified serial port.
253  *
254  * @param port Pointer to empty port structure allocated by caller.
255  * @param portname Name of port to open.
256  * @param flags Flags to use when opening the serial port. Possible flags
257  *              are: SP_MODE_RDWR, SP_MODE_RDONLY, SP_MODE_NONBLOCK.
258  *
259  * @return SP_OK on success, SP_ERR_FAIL on failure,
260  *         or SP_ERR_ARG if an invalid port or name is passed.
261  */
262 int sp_open(struct sp_port *port, char *portname, int flags)
263 {
264         if (!port)
265                 return SP_ERR_ARG;
266
267         if (!portname)
268                 return SP_ERR_ARG;
269
270         port->name = portname;
271
272 #ifdef _WIN32
273         DWORD desired_access = 0, flags_and_attributes = 0;
274         /* Map 'flags' to the OS-specific settings. */
275         desired_access |= GENERIC_READ;
276         flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
277         if (flags & SP_MODE_RDWR)
278                 desired_access |= GENERIC_WRITE;
279         if (flags & SP_MODE_NONBLOCK)
280                 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
281
282         port->hdl = CreateFile(port->name, desired_access, 0, 0,
283                          OPEN_EXISTING, flags_and_attributes, 0);
284         if (port->hdl == INVALID_HANDLE_VALUE)
285                 return SP_ERR_FAIL;
286 #else
287         int flags_local = 0;
288         /* Map 'flags' to the OS-specific settings. */
289         if (flags & SP_MODE_RDWR)
290                 flags_local |= O_RDWR;
291         if (flags & SP_MODE_RDONLY)
292                 flags_local |= O_RDONLY;
293         if (flags & SP_MODE_NONBLOCK)
294                 flags_local |= O_NONBLOCK;
295
296         if ((port->fd = open(port->name, flags_local)) < 0)
297                 return SP_ERR_FAIL;
298 #endif
299
300         return SP_OK;
301 }
302
303 /**
304  * Close the specified serial port.
305  *
306  * @param port Pointer to port structure.
307  *
308  * @return SP_OK on success, SP_ERR_FAIL on failure,
309  *         or SP_ERR_ARG if an invalid port is passed.
310  */
311 int sp_close(struct sp_port *port)
312 {
313         CHECK_PORT();
314
315 #ifdef _WIN32
316         /* Returns non-zero upon success, 0 upon failure. */
317         if (CloseHandle(port->hdl) == 0)
318                 return SP_ERR_FAIL;
319 #else
320         /* Returns 0 upon success, -1 upon failure. */
321         if (close(port->fd) == -1)
322                 return SP_ERR_FAIL;
323 #endif
324
325         return SP_OK;
326 }
327
328 /**
329  * Flush serial port buffers.
330  *
331  * @param port Pointer to port structure.
332  *
333  * @return SP_OK on success, SP_ERR_FAIL on failure,
334  *         or SP_ERR_ARG if an invalid port is passed.
335  */
336 int sp_flush(struct sp_port *port)
337 {
338         CHECK_PORT();
339
340 #ifdef _WIN32
341         /* Returns non-zero upon success, 0 upon failure. */
342         if (PurgeComm(port->hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0)
343                 return SP_ERR_FAIL;
344 #else
345         /* Returns 0 upon success, -1 upon failure. */
346         if (tcflush(port->fd, TCIOFLUSH) < 0)
347                 return SP_ERR_FAIL;
348 #endif
349         return SP_OK;
350 }
351
352 /**
353  * Write a number of bytes to the specified serial port.
354  *
355  * @param port Pointer to port structure.
356  * @param buf Buffer containing the bytes to write.
357  * @param count Number of bytes to write.
358  *
359  * @return The number of bytes written, SP_ERR_FAIL on failure,
360  *         or SP_ERR_ARG if an invalid port is passed.
361  */
362 int sp_write(struct sp_port *port, const void *buf, size_t count)
363 {
364         CHECK_PORT();
365
366         if (!buf)
367                 return SP_ERR_ARG;
368
369 #ifdef _WIN32
370         DWORD written = 0;
371         /* Returns non-zero upon success, 0 upon failure. */
372         if (WriteFile(port->hdl, buf, count, &written, NULL) == 0)
373                 return SP_ERR_FAIL;
374         return written;
375 #else
376         /* Returns the number of bytes written, or -1 upon failure. */
377         ssize_t written = write(port->fd, buf, count);
378         if (written < 0)
379                 return SP_ERR_FAIL;
380         else
381                 return written;;
382 #endif
383 }
384
385 /**
386  * Read a number of bytes from the specified serial port.
387  *
388  * @param port Pointer to port structure.
389  * @param buf Buffer where to store the bytes that are read.
390  * @param count The number of bytes to read.
391  *
392  * @return The number of bytes read, SP_ERR_FAIL on failure,
393  *         or SP_ERR_ARG if an invalid port is passed.
394  */
395 int sp_read(struct sp_port *port, void *buf, size_t count)
396 {
397         CHECK_PORT();
398
399         if (!buf)
400                 return SP_ERR_ARG;
401
402 #ifdef _WIN32
403         DWORD bytes_read = 0;
404         /* Returns non-zero upon success, 0 upon failure. */
405         if (ReadFile(port->hdl, buf, count, &bytes_read, NULL) == 0)
406                 return SP_ERR_FAIL;
407         return bytes_read;
408 #else
409         ssize_t bytes_read;
410         /* Returns the number of bytes read, or -1 upon failure. */
411         if ((bytes_read = read(port->fd, buf, count)) < 0)
412                 return SP_ERR_FAIL;
413         return bytes_read;
414 #endif
415 }
416
417 /**
418  * Set serial parameters for the specified serial port.
419  *
420  * @param port Pointer to port structure.
421  * @param baudrate The baudrate to set.
422  * @param bits The number of data bits to use.
423  * @param parity The parity setting to use (0 = none, 1 = even, 2 = odd).
424  * @param stopbits The number of stop bits to use (1 or 2).
425  * @param flowcontrol The flow control settings to use (0 = none, 1 = RTS/CTS,
426  *                    2 = XON/XOFF).
427  *
428  * @return The number of bytes read, SP_ERR_FAIL on failure,
429  *         or SP_ERR_ARG if an invalid argument is passed.
430  */
431 int sp_set_params(struct sp_port *port, int baudrate,
432                               int bits, int parity, int stopbits,
433                               int flowcontrol, int rts, int dtr)
434 {
435         CHECK_PORT();
436
437 #ifdef _WIN32
438         DCB dcb;
439
440         if (!GetCommState(port->hdl, &dcb))
441                 return SP_ERR_FAIL;
442
443         switch (baudrate) {
444         /*
445          * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
446          * have documented CBR_* macros.
447          */
448         case 110:
449                 dcb.BaudRate = CBR_110;
450                 break;
451         case 300:
452                 dcb.BaudRate = CBR_300;
453                 break;
454         case 600:
455                 dcb.BaudRate = CBR_600;
456                 break;
457         case 1200:
458                 dcb.BaudRate = CBR_1200;
459                 break;
460         case 2400:
461                 dcb.BaudRate = CBR_2400;
462                 break;
463         case 4800:
464                 dcb.BaudRate = CBR_4800;
465                 break;
466         case 9600:
467                 dcb.BaudRate = CBR_9600;
468                 break;
469         case 14400:
470                 dcb.BaudRate = CBR_14400; /* Not available on Unix? */
471                 break;
472         case 19200:
473                 dcb.BaudRate = CBR_19200;
474                 break;
475         case 38400:
476                 dcb.BaudRate = CBR_38400;
477                 break;
478         case 57600:
479                 dcb.BaudRate = CBR_57600;
480                 break;
481         case 115200:
482                 dcb.BaudRate = CBR_115200;
483                 break;
484         case 128000:
485                 dcb.BaudRate = CBR_128000; /* Not available on Unix? */
486                 break;
487         case 256000:
488                 dcb.BaudRate = CBR_256000; /* Not available on Unix? */
489                 break;
490         default:
491                 return SP_ERR_ARG;
492         }
493
494         switch (stopbits) {
495         /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
496         case 1:
497                 dcb.StopBits = ONESTOPBIT;
498                 break;
499         case 2:
500                 dcb.StopBits = TWOSTOPBITS;
501                 break;
502         default:
503                 return SP_ERR_ARG;
504         }
505
506         switch (parity) {
507         /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
508         case SP_PARITY_NONE:
509                 dcb.Parity = NOPARITY;
510                 break;
511         case SP_PARITY_EVEN:
512                 dcb.Parity = EVENPARITY;
513                 break;
514         case SP_PARITY_ODD:
515                 dcb.Parity = ODDPARITY;
516                 break;
517         default:
518                 return SP_ERR_ARG;
519         }
520
521         if (rts != -1) {
522                 if (rts)
523                         dcb.fRtsControl = RTS_CONTROL_ENABLE;
524                 else
525                         dcb.fRtsControl = RTS_CONTROL_DISABLE;
526         }
527
528         if (dtr != -1) {
529                 if (dtr)
530                         dcb.fDtrControl = DTR_CONTROL_ENABLE;
531                 else
532                         dcb.fDtrControl = DTR_CONTROL_DISABLE;
533         }
534
535         if (!SetCommState(port->hdl, &dcb))
536                 return SP_ERR_FAIL;
537 #else
538         struct termios term;
539         speed_t baud;
540         int controlbits;
541
542         if (tcgetattr(port->fd, &term) < 0)
543                 return SP_ERR_FAIL;
544
545         switch (baudrate) {
546         case 50:
547                 baud = B50;
548                 break;
549         case 75:
550                 baud = B75;
551                 break;
552         case 110:
553                 baud = B110;
554                 break;
555         case 134:
556                 baud = B134;
557                 break;
558         case 150:
559                 baud = B150;
560                 break;
561         case 200:
562                 baud = B200;
563                 break;
564         case 300:
565                 baud = B300;
566                 break;
567         case 600:
568                 baud = B600;
569                 break;
570         case 1200:
571                 baud = B1200;
572                 break;
573         case 1800:
574                 baud = B1800;
575                 break;
576         case 2400:
577                 baud = B2400;
578                 break;
579         case 4800:
580                 baud = B4800;
581                 break;
582         case 9600:
583                 baud = B9600;
584                 break;
585         case 19200:
586                 baud = B19200;
587                 break;
588         case 38400:
589                 baud = B38400;
590                 break;
591         case 57600:
592                 baud = B57600;
593                 break;
594         case 115200:
595                 baud = B115200;
596                 break;
597         case 230400:
598                 baud = B230400;
599                 break;
600 #if !defined(__APPLE__) && !defined(__OpenBSD__)
601         case 460800:
602                 baud = B460800;
603                 break;
604 #endif
605         default:
606                 return SP_ERR_ARG;
607         }
608
609         if (cfsetospeed(&term, baud) < 0)
610                 return SP_ERR_FAIL;
611
612         if (cfsetispeed(&term, baud) < 0)
613                 return SP_ERR_FAIL;
614
615         term.c_cflag &= ~CSIZE;
616         switch (bits) {
617         case 8:
618                 term.c_cflag |= CS8;
619                 break;
620         case 7:
621                 term.c_cflag |= CS7;
622                 break;
623         default:
624                 return SP_ERR_ARG;
625         }
626
627         term.c_cflag &= ~CSTOPB;
628         switch (stopbits) {
629         case 1:
630                 term.c_cflag &= ~CSTOPB;
631                 break;
632         case 2:
633                 term.c_cflag |= CSTOPB;
634                 break;
635         default:
636                 return SP_ERR_ARG;
637         }
638
639         term.c_iflag &= ~(IXON | IXOFF | IXANY);
640         term.c_cflag &= ~CRTSCTS;
641         switch (flowcontrol) {
642         case 0:
643                 /* No flow control. */
644                 break;
645         case 1:
646                 term.c_cflag |= CRTSCTS;
647                 break;
648         case 2:
649                 term.c_iflag |= IXON | IXOFF | IXANY;
650                 break;
651         default:
652                 return SP_ERR_ARG;
653         }
654
655         term.c_iflag &= ~IGNPAR;
656         term.c_cflag &= ~(PARENB | PARODD);
657         switch (parity) {
658         case SP_PARITY_NONE:
659                 term.c_iflag |= IGNPAR;
660                 break;
661         case SP_PARITY_EVEN:
662                 term.c_cflag |= PARENB;
663                 break;
664         case SP_PARITY_ODD:
665                 term.c_cflag |= PARENB | PARODD;
666                 break;
667         default:
668                 return SP_ERR_ARG;
669         }
670
671         /* Turn off all serial port cooking. */
672         term.c_iflag &= ~(ISTRIP | INLCR | ICRNL);
673         term.c_oflag &= ~(ONLCR | OCRNL | ONOCR);
674 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
675         term.c_oflag &= ~OFILL;
676 #endif
677
678         /* Disable canonical mode, and don't echo input characters. */
679         term.c_lflag &= ~(ICANON | ECHO);
680
681         /* Ignore modem status lines; enable receiver */
682         term.c_cflag |= (CLOCAL | CREAD);
683
684         /* Write the configured settings. */
685         if (tcsetattr(port->fd, TCSADRAIN, &term) < 0)
686                 return SP_ERR_FAIL;
687
688         if (rts != -1) {
689                 controlbits = TIOCM_RTS;
690                 if (ioctl(port->fd, rts ? TIOCMBIS : TIOCMBIC,
691                                 &controlbits) < 0)
692                         return SP_ERR_FAIL;
693         }
694
695         if (dtr != -1) {
696                 controlbits = TIOCM_DTR;
697                 if (ioctl(port->fd, dtr ? TIOCMBIS : TIOCMBIC,
698                                 &controlbits) < 0)
699                         return SP_ERR_FAIL;
700         }
701 #endif
702
703         return SP_OK;
704 }
705
706 /**
707  * Get error code for failed operation.
708  *
709  * In order to obtain the correct result, this function should be called
710  * straight after the failure, before executing any other system operations.
711  *
712  * @return The system's numeric code for the error that caused the last
713  *         operation to fail.
714  */
715 int sp_last_error_code(void)
716 {
717 #ifdef _WIN32
718         return GetLastError();
719 #else
720         return errno;
721 #endif
722 }
723
724 /**
725  * Get error message for failed operation.
726  *
727  * In order to obtain the correct result, this function should be called
728  * straight after the failure, before executing other system operations.
729  *
730  * @return The system's message for the error that caused the last
731  *         operation to fail. This string may be allocated by the function,
732  *         and can be freed after use by calling sp_free_error_message.
733  */
734 char *sp_last_error_message(void)
735 {
736 #ifdef _WIN32
737         LPVOID message;
738         DWORD error = GetLastError();
739
740         FormatMessage(
741                 FORMAT_MESSAGE_ALLOCATE_BUFFER |
742                 FORMAT_MESSAGE_FROM_SYSTEM |
743                 FORMAT_MESSAGE_IGNORE_INSERTS,
744                 NULL,
745                 error,
746                 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
747                 (LPTSTR) &message,
748                 0, NULL );
749
750         return message;
751 #else
752         return strerror(errno);
753 #endif
754 }
755
756 /**
757  * Free error message.
758  *
759  * This function can be used to free a string returned by the
760  * sp_last_error_message function.
761  */
762 void sp_free_error_message(char *message)
763 {
764 #ifdef _WIN32
765         LocalFree(message);
766 #else
767         (void)message;
768 #endif
769 }