]> sigrok.org Git - libserialport.git/blob - freebsd.c
change type of result variables to ssize_t
[libserialport.git] / freebsd.c
1 /*
2  * This file is part of the libserialport project.
3  *
4  * Copyright (C) 2015 Uffe Jakobsen <uffe@uffe.org>
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Lesser General Public License as
8  * published by the Free Software Foundation, either version 3 of the
9  * License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 /*
21  * FreeBSD platform specific serial port information:
22  *
23  * FreeBSD has two device nodes for each serial port:
24  *
25  *  1) a call-in port
26  *  2) a call-out port
27  *
28  * Quoting FreeBSD Handbook section 26.2.1
29  * (https://www.freebsd.org/doc/handbook/serial.html)
30  *
31  * In FreeBSD, each serial port is accessed through an entry in /dev.
32  * There are two different kinds of entries:
33  *
34  * 1) Call-in ports are named /dev/ttyuN where N is the port number,
35  *    starting from zero. If a terminal is connected to the first serial port
36  *    (COM1), use /dev/ttyu0 to refer to the terminal. If the terminal is on
37  *    the second serial port (COM2), use /dev/ttyu1, and so forth.
38  *    Generally, the call-in port is used for terminals. Call-in ports require
39  *    that the serial line assert the "Data Carrier Detect" signal to work
40  *    correctly.
41  *
42  * 2) Call-out ports are named /dev/cuauN on FreeBSD versions 10.x and higher
43  *    and /dev/cuadN on FreeBSD versions 9.x and lower. Call-out ports are
44  *    usually not used for terminals, but are used for modems. The call-out
45  *    port can be used if the serial cable or the terminal does not support
46  *    the "Data Carrier Detect" signal.
47  *
48  * FreeBSD also provides initialization devices (/dev/ttyuN.init and
49  * /dev/cuauN.init or /dev/cuadN.init) and locking devices (/dev/ttyuN.lock
50  * and /dev/cuauN.lock or /dev/cuadN.lock). The initialization devices are
51  * used to initialize communications port parameters each time a port is
52  * opened, such as crtscts for modems which use RTS/CTS signaling for flow
53  * control. The locking devices are used to lock flags on ports to prevent
54  * users or programs changing certain parameters.
55  *
56  * In line with the above device naming USB-serial devices have
57  * the following naming:
58  *
59  * 1) call-in ports: /dev/ttyUN where N is the port number
60  * 2) call-out ports: /dev/cuaUN where N is the port number
61  *
62  * See also: ucom(4), https://www.freebsd.org/cgi/man.cgi?query=ucom
63  *
64  * Getting USB serial port device description:
65  *
66  * In order to query USB serial ports for device description - the mapping
67  * between the kernel device driver instances must be correlated with the
68  * above mentioned device nodes.
69  *
70  * 1) For each USB-serial port (/dev/cuaUN) use libusb to lookup the device
71  *    description and the name of the kernel device driver instance.
72  * 2) Query sysctl for the kernel device driver instance info.
73  * 3) Derive the ttyname and (serial) port count for the kernel device
74  *    driver instance.
75  * 4) If sysctl ttyname and port matches /dev/cuaUN apply the libusb
76  *    device description.
77  */
78
79 #include <config.h>
80 #include <unistd.h>
81 #include <stdint.h>
82 #include <stdlib.h>
83 #include <limits.h>
84 #include <stdio.h>
85 #include <string.h>
86 #include <sys/types.h>
87 #include <sys/sysctl.h>
88 #include <dirent.h>
89 #include <libusb20.h>
90 #include <libusb20_desc.h>
91 #include "libserialport.h"
92 #include "libserialport_internal.h"
93
94 #define DEV_CUA_PATH "/dev/cua"
95
96 //#define DBG(...) printf(__VA_ARGS__)
97 #define DBG(...)
98
99 static char *strrspn(const char *s, const char *charset)
100 {
101         char *t = (char *)s + strlen(s);
102         while (t != (char *)s)
103                 if (!strchr(charset, *(--t)))
104                         return ++t;
105         return t;
106 }
107
108 static int strend(const char *str, const char *pattern)
109 {
110         size_t slen = strlen(str);
111         size_t plen = strlen(pattern);
112         if (slen >= plen)
113                 return (!memcmp(pattern, (str + slen - plen), plen));
114         return 0;
115 }
116
117 static int libusb_query_port(struct libusb20_device *dev, int idx,
118                              char **drv_name_str, char **drv_inst_str)
119 {
120         int rc;
121         char *j;
122         char sbuf[FILENAME_MAX];
123
124         if (!drv_name_str || !drv_inst_str)
125                 return -1;
126
127         rc = libusb20_dev_kernel_driver_active(dev, idx);
128         if (rc < 0)
129                 return rc;
130
131         sbuf[0] = 0;
132         libusb20_dev_get_iface_desc(dev, idx, (char *)&sbuf,
133                                     (uint8_t)sizeof(sbuf) - 1);
134         if (sbuf[0] == 0)
135                 return rc;
136
137         DBG("Device interface descriptor: idx=%003d '%s'\n", idx, sbuf);
138         j = strchr(sbuf, ':');
139         if (j > sbuf) {
140                 sbuf[j - sbuf] = 0;
141                 /*
142                  * The device driver name may contain digits that
143                  * is not a part of the device instance number - like "u3g".
144                  */
145                 j = strrspn(sbuf, "0123456789");
146                 if (j > sbuf) {
147                         *drv_name_str = strndup(sbuf, j - sbuf);
148                         *drv_inst_str = strdup((j));
149                 }
150         }
151
152         return rc;
153 }
154
155 static int sysctl_query_dev_drv(const char *drv_name_str,
156         const char *drv_inst_str, char **ttyname, int *const ttyport_cnt)
157 {
158         int rc;
159         char sbuf[FILENAME_MAX];
160         char tbuf[FILENAME_MAX];
161         size_t tbuf_len;
162
163         if (!ttyname || !ttyport_cnt)
164                 return -1;
165
166         snprintf(sbuf, sizeof(sbuf), "dev.%s.%s.ttyname", drv_name_str,
167                  drv_inst_str);
168         tbuf_len = sizeof(tbuf) - 1;
169         if ((rc = sysctlbyname(sbuf, tbuf, &tbuf_len, NULL, 0)) != 0)
170                 return rc;
171
172         tbuf[tbuf_len] = 0;
173         *ttyname = strndup(tbuf, tbuf_len);
174         DBG("sysctl: '%s' (%d) (%d): '%.*s'\n", sbuf, rc, (int)tbuf_len,
175             (int)tbuf_len, tbuf);
176
177         snprintf(sbuf, sizeof(sbuf), "dev.%s.%s.ttyports",
178                  drv_name_str, drv_inst_str);
179         tbuf_len = sizeof(tbuf) - 1;
180         rc = sysctlbyname(sbuf, tbuf, &tbuf_len, NULL, 0);
181         if (rc == 0) {
182                 *ttyport_cnt = *(uint32_t *)tbuf;
183                 DBG("sysctl: '%s' (%d) (%d): '%d'\n", sbuf, rc,
184                     (int)tbuf_len, (int)ttyport_cnt);
185         } else {
186                 *ttyport_cnt = 0;
187         }
188
189         return rc;
190 }
191
192 static int populate_port_struct_from_libusb_desc(struct sp_port *const port,
193                                                  struct libusb20_device *dev)
194 {
195         char tbuf[FILENAME_MAX];
196
197         /* Populate port structure from libusb description. */
198         struct LIBUSB20_DEVICE_DESC_DECODED *dev_desc =
199                 libusb20_dev_get_device_desc(dev);
200
201         if (!dev_desc)
202                 return -1;
203
204         port->transport = SP_TRANSPORT_USB;
205         port->usb_vid = dev_desc->idVendor;
206         port->usb_pid = dev_desc->idProduct;
207         port->usb_bus = libusb20_dev_get_bus_number(dev);
208         port->usb_address = libusb20_dev_get_address(dev);
209         if (libusb20_dev_req_string_simple_sync
210             (dev, dev_desc->iManufacturer, tbuf, sizeof(tbuf)) == 0) {
211                 port->usb_manufacturer = strdup(tbuf);
212         }
213         if (libusb20_dev_req_string_simple_sync
214             (dev, dev_desc->iProduct, tbuf, sizeof(tbuf)) == 0) {
215                 port->usb_product = strdup(tbuf);
216         }
217         if (libusb20_dev_req_string_simple_sync
218             (dev, dev_desc->iSerialNumber, tbuf, sizeof(tbuf)) == 0) {
219                 port->usb_serial = strdup(tbuf);
220         }
221         /* If present, add serial to description for better identification. */
222         tbuf[0] = '\0';
223         if (port->usb_product && port->usb_product[0])
224                 strncat(tbuf, port->usb_product, sizeof(tbuf) - 1);
225         else
226                 strncat(tbuf, libusb20_dev_get_desc(dev), sizeof(tbuf) - 1);
227         if (port->usb_serial && port->usb_serial[0]) {
228                 strncat(tbuf, " ", sizeof(tbuf) - 1);
229                 strncat(tbuf, port->usb_serial, sizeof(tbuf) - 1);
230         }
231         port->description = strdup(tbuf);
232         port->bluetooth_address = NULL;
233
234         return 0;
235 }
236
237 SP_PRIV enum sp_return get_port_details(struct sp_port *port)
238 {
239         int rc;
240         struct libusb20_backend *be;
241         struct libusb20_device *dev, *dev_last;
242         char tbuf[FILENAME_MAX];
243         char *cua_sfx;
244         int cua_dev_found;
245         uint8_t idx;
246         int sub_inst;
247
248         DBG("Portname: '%s'\n", port->name);
249
250         if (!strncmp(port->name, DEV_CUA_PATH, strlen(DEV_CUA_PATH))) {
251                 cua_sfx = port->name + strlen(DEV_CUA_PATH);
252                 DBG("'%s': '%s'\n", DEV_CUA_PATH, cua_sfx);
253         } else {
254                 RETURN_ERROR(SP_ERR_ARG, "Device name not recognized");
255         }
256
257         /* Native UART enumeration. */
258         if ((cua_sfx[0] == 'u') || (cua_sfx[0] == 'd')) {
259                 port->transport = SP_TRANSPORT_NATIVE;
260                 snprintf(tbuf, sizeof(tbuf), "cua%s", cua_sfx);
261                 port->description = strdup(tbuf);
262                 RETURN_OK();
263         }
264
265         /* USB device enumeration. */
266         dev = dev_last = NULL;
267         be = libusb20_be_alloc_default();
268         cua_dev_found = 0;
269         while (cua_dev_found == 0) {
270                 dev = libusb20_be_device_foreach(be, dev_last);
271                 if (!dev)
272                         break;
273
274                 libusb20_dev_open(dev, 0);
275                 DBG("Device descriptor: '%s'\n", libusb20_dev_get_desc(dev));
276
277                 for (idx = 0; idx <= UINT8_MAX - 1; idx++) {
278                         char *drv_name_str = NULL;
279                         char *drv_inst_str = NULL;
280                         char *ttyname = NULL;
281                         int ttyport_cnt;
282
283                         rc = libusb_query_port(dev, idx, &drv_name_str, &drv_inst_str);
284                         if (rc == 0) {
285                                 rc = sysctl_query_dev_drv(drv_name_str,
286                                           drv_inst_str, &ttyname, &ttyport_cnt);
287                                 if (rc == 0) {
288                                         /* Handle multiple subinstances of serial ports in the same driver instance. */
289                                         for (sub_inst = 0; sub_inst < ttyport_cnt; sub_inst++) {
290                                                 if (ttyport_cnt == 1)
291                                                         snprintf(tbuf, sizeof(tbuf), "%s", ttyname);
292                                                 else
293                                                         snprintf(tbuf, sizeof(tbuf), "%s.%d", ttyname, sub_inst);
294                                                 if (!strcmp(cua_sfx, tbuf)) {
295                                                         DBG("MATCH: '%s' == '%s'\n", cua_sfx, tbuf);
296                                                         cua_dev_found = 1;
297                                                         populate_port_struct_from_libusb_desc(port, dev);
298                                                         break; /* Break out of sub instance loop. */
299                                                 }
300                                         }
301                                 }
302                         }
303
304                         /* Clean up. */
305                         if (ttyname)
306                                 free(ttyname);
307                         if (drv_name_str)
308                                 free(drv_name_str);
309                         if (drv_inst_str)
310                                 free(drv_inst_str);
311                         if (cua_dev_found)
312                                 break; /* Break out of USB device port idx loop. */
313                 }
314                 libusb20_dev_close(dev);
315                 dev_last = dev;
316         }
317         libusb20_be_free(be);
318
319         if (cua_dev_found == 0)
320                 DBG("WARN: Found no match '%s' %s'\n", port->name, cua_sfx);
321
322         RETURN_OK();
323 }
324
325 SP_PRIV enum sp_return list_ports(struct sp_port ***list)
326 {
327         DIR *dir;
328         struct dirent *entry;
329         struct termios tios;
330         char name[PATH_MAX];
331         int fd, ret;
332
333         DEBUG("Enumerating tty devices");
334         if (!(dir = opendir("/dev")))
335                 RETURN_FAIL("Could not open dir /dev");
336
337         DEBUG("Iterating over results");
338         while ((entry = readdir(dir))) {
339                 ret = SP_OK;
340                 if (entry->d_type != DT_CHR)
341                         continue;
342                 if (strncmp(entry->d_name, "cuaU", 4) != 0)
343                         if (strncmp(entry->d_name, "cuau", 4) != 0)
344                                 if (strncmp(entry->d_name, "cuad", 4) != 0)
345                                         continue;
346                 if (strend(entry->d_name, ".init"))
347                         continue;
348                 if (strend(entry->d_name, ".lock"))
349                         continue;
350
351                 snprintf(name, sizeof(name), "/dev/%s", entry->d_name);
352                 DEBUG_FMT("Found device %s", name);
353
354                 /* Check that we can open tty/cua device in rw mode - we need that. */
355                 if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY | O_TTY_INIT | O_CLOEXEC)) < 0) {
356                         DEBUG("Open failed, skipping");
357                         continue;
358                 }
359
360                 /* Sanity check if we got a real tty. */
361                 if (!isatty(fd)) {
362                         close(fd);
363                         continue;
364                 }
365
366                 ret = tcgetattr(fd, &tios);
367                 close(fd);
368                 if (ret < 0 || cfgetospeed(&tios) <= 0 || cfgetispeed(&tios) <= 0)
369                         continue;
370
371                 DEBUG_FMT("Found port %s", name);
372                 DBG("%s: %s\n", __func__, entry->d_name);
373
374                 *list = list_append(*list, name);
375                 if (!*list) {
376                         SET_ERROR(ret, SP_ERR_MEM, "List append failed");
377                         break;
378                 }
379         }
380         closedir(dir);
381
382         return ret;
383 }