]> sigrok.org Git - libserialport.git/blob - freebsd.c
Implement FreeBSD OS-specific serial port detection and query
[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 <unistd.h>
80 #include <stdint.h>
81 #include <stdlib.h>
82 #include <limits.h>
83 #include <stdio.h>
84 #include <string.h>
85 #include <sys/types.h>
86 #include <sys/sysctl.h>
87 #include <dirent.h>
88 #include <libusb20.h>
89 #include <libusb20_desc.h>
90 #include "libserialport.h"
91 #include "libserialport_internal.h"
92
93 #define DEV_CUA_PATH "/dev/cua"
94
95 //#define DBG(...) printf(__VA_ARGS__)
96 #define DBG(...)
97
98 static char *strrspn(const char *s, const char *charset)
99 {
100         char *t = (char *)s + strlen(s);
101         while (t != (char *)s)
102                 if (!strchr(charset, *(--t)))
103                         return ++t;
104         return t;
105 }
106
107 static int strend(const char *str, const char *pattern)
108 {
109         size_t slen = strlen(str);
110         size_t plen = strlen(pattern);
111         if (slen >= plen)
112                 return (!memcmp(pattern, (str + slen - plen), plen));
113         return 0;
114 }
115
116 static int libusb_query_port(struct libusb20_device *dev, int idx,
117                              char **drv_name_str, char **drv_inst_str)
118 {
119         int rc;
120         char *j;
121         char sbuf[FILENAME_MAX];
122
123         if (!drv_name_str || !drv_inst_str)
124                 return -1;
125
126         rc = libusb20_dev_kernel_driver_active(dev, idx);
127         if (rc < 0)
128                 return rc;
129
130         sbuf[0] = 0;
131         libusb20_dev_get_iface_desc(dev, idx, (char *)&sbuf,
132                                     (uint8_t)sizeof(sbuf) - 1);
133         if (sbuf[0] == 0)
134                 return rc;
135
136         DBG("device interface descriptor: idx=%003d '%s'\n", idx, sbuf);
137         j = strchr(sbuf, ':');
138         if (j > sbuf) {
139                 sbuf[j - sbuf] = 0;
140                 /*
141                  * The device driver name may contain digits that
142                  * is not a part of the device instance number - like "u3g".
143                  */
144                 j = strrspn(sbuf, "0123456789");
145                 if (j > sbuf) {
146                         *drv_name_str = strndup(sbuf, j - sbuf);
147                         *drv_inst_str = strdup((j));
148                 }
149         }
150
151         return rc;
152 }
153
154 static int sysctl_query_dev_drv(const char *drv_name_str,
155         const char *drv_inst_str, char **ttyname, int *const ttyport_cnt)
156 {
157         int rc;
158         char sbuf[FILENAME_MAX];
159         char tbuf[FILENAME_MAX];
160         size_t tbuf_len;
161
162         if (!ttyname || !ttyport_cnt)
163                 return -1;
164
165         snprintf(sbuf, sizeof(sbuf) - 1, "dev.%s.%s.ttyname", drv_name_str,
166                  drv_inst_str);
167         tbuf_len = sizeof(tbuf) - 1;
168         if ((rc = sysctlbyname(sbuf, tbuf, &tbuf_len, NULL, 0)) != 0)
169                 return rc;
170
171         tbuf[tbuf_len] = 0;
172         *ttyname = strndup(tbuf, tbuf_len);
173         DBG("sysctl: '%s' (%d) (%d): '%.*s'\n", sbuf, rc, (int)tbuf_len,
174             (int)tbuf_len, tbuf);
175
176         snprintf(sbuf, sizeof(sbuf) - 1, "dev.%s.%s.ttyports",
177                  drv_name_str, drv_inst_str);
178         tbuf_len = sizeof(tbuf) - 1;
179         rc = sysctlbyname(sbuf, tbuf, &tbuf_len, NULL, 0);
180         if (rc == 0) {
181                 *ttyport_cnt = *(uint32_t *)tbuf;
182                 DBG("sysctl: '%s' (%d) (%d): '%d'\n", sbuf, rc,
183                     (int)tbuf_len, (int)ttyport_cnt);
184         } else {
185                 *ttyport_cnt = 0;
186         }
187
188         return rc;
189 }
190
191 static int populate_port_struct_from_libusb_desc(struct sp_port *const port,
192                                                  struct libusb20_device *dev)
193 {
194         char tbuf[FILENAME_MAX];
195
196         /* Populate port structure from libusb description. */
197         struct LIBUSB20_DEVICE_DESC_DECODED *dev_desc =
198                 libusb20_dev_get_device_desc(dev);
199
200         if (!dev_desc)
201                 return -1;
202
203         port->transport = SP_TRANSPORT_USB;
204         port->usb_vid = dev_desc->idVendor;
205         port->usb_pid = dev_desc->idProduct;
206         port->usb_bus = libusb20_dev_get_bus_number(dev);
207         port->usb_address = libusb20_dev_get_address(dev);
208         if (libusb20_dev_req_string_simple_sync
209             (dev, dev_desc->iManufacturer, tbuf, sizeof(tbuf)) == 0) {
210                 port->usb_manufacturer = strdup(tbuf);
211         }
212         if (libusb20_dev_req_string_simple_sync
213             (dev, dev_desc->iProduct, tbuf, sizeof(tbuf)) == 0) {
214                 port->usb_product = strdup(tbuf);
215         }
216         if (libusb20_dev_req_string_simple_sync
217             (dev, dev_desc->iSerialNumber, tbuf, sizeof(tbuf)) == 0) {
218                 port->usb_serial = strdup(tbuf);
219         }
220         /* If present, add serial to description for better identification. */
221         tbuf[0] = '\0';
222         if (port->usb_product && port->usb_product[0])
223                 strncat(tbuf, port->usb_product, sizeof(tbuf) - 1);
224         else
225                 strncat(tbuf, libusb20_dev_get_desc(dev), sizeof(tbuf) - 1);
226         if (port->usb_serial && port->usb_serial[0]) {
227                 strncat(tbuf, " ", sizeof(tbuf) - 1);
228                 strncat(tbuf, port->usb_serial, sizeof(tbuf) - 1);
229         }
230         port->description = strdup(tbuf);
231         port->bluetooth_address = NULL;
232
233         return 0;
234 }
235
236 SP_PRIV enum sp_return get_port_details(struct sp_port *port)
237 {
238         int rc;
239         struct libusb20_backend *be;
240         struct libusb20_device *dev, *dev_last;
241         char tbuf[FILENAME_MAX];
242         char *cua_sfx;
243         int cua_dev_found;
244         uint8_t idx;
245         int sub_inst;
246
247         DBG("portname: '%s'\n", port->name);
248
249         if (!strncmp(port->name, DEV_CUA_PATH, strlen(DEV_CUA_PATH))) {
250                 cua_sfx = port->name + strlen(DEV_CUA_PATH);
251                 DBG("'%s': '%s'\n", DEV_CUA_PATH, cua_sfx);
252         } else {
253                 RETURN_ERROR(SP_ERR_ARG, "Device name not recognized.");
254         }
255
256         dev = dev_last = NULL;
257         be = libusb20_be_alloc_default();
258         cua_dev_found = 0;
259         while (cua_dev_found == 0) {
260                 dev = libusb20_be_device_foreach(be, dev_last);
261                 if (!dev)
262                         break;
263
264                 libusb20_dev_open(dev, 0);
265                 DBG("device descriptor: '%s'\n", libusb20_dev_get_desc(dev));
266
267                 for (idx = 0; idx <= UINT8_MAX - 1; idx++) {
268                         char *drv_name_str = NULL;
269                         char *drv_inst_str = NULL;
270                         char *ttyname = NULL;
271                         int ttyport_cnt;
272
273                         rc = libusb_query_port(dev, idx, &drv_name_str, &drv_inst_str);
274                         if (rc == 0) {
275                                 rc = sysctl_query_dev_drv(drv_name_str,
276                                           drv_inst_str, &ttyname, &ttyport_cnt);
277                                 if (rc == 0) {
278                                         /* Handle multiple subinstances of serial ports in the same driver instance. */
279                                         for (sub_inst = 0; sub_inst < ttyport_cnt; sub_inst++) {
280                                                 if (ttyport_cnt == 1)
281                                                         snprintf(tbuf, sizeof(tbuf) - 1, "%s", ttyname);
282                                                 else
283                                                         snprintf(tbuf, sizeof(tbuf) - 1, "%s.%d", ttyname, sub_inst);
284                                                 if (!strcmp(cua_sfx, tbuf)) {
285                                                         DBG("MATCH: '%s' == '%s'\n", cua_sfx, tbuf);
286                                                         cua_dev_found = 1;
287                                                         populate_port_struct_from_libusb_desc(port, dev);
288                                                         break; /* Break out of sub instance loop. */
289                                                 }
290                                         }
291                                 }
292                         }
293
294                         /* Clean up. */
295                         if (ttyname)
296                                 free(ttyname);
297                         if (drv_name_str)
298                                 free(drv_name_str);
299                         if (drv_inst_str)
300                                 free(drv_inst_str);
301                         if (cua_dev_found)
302                                 break; /* Break out of USB device port idx loop. */
303                 }
304                 libusb20_dev_close(dev);
305                 dev_last = dev;
306         }
307         libusb20_be_free(be);
308
309         if (cua_dev_found == 0)
310                 DBG("WARN: found no match '%s' %s'\n", port->name, cua_sfx);
311
312         RETURN_OK();
313 }
314
315 SP_PRIV enum sp_return list_ports(struct sp_port ***list)
316 {
317         DIR *dir;
318         struct dirent entry;
319         struct dirent *result;
320         struct termios tios;
321         char name[PATH_MAX];
322         int fd, ret;
323
324         DEBUG("Enumerating tty devices");
325         if (!(dir = opendir("/dev")))
326                 RETURN_FAIL("could not open dir /dev");
327
328         DEBUG("Iterating over results");
329         while (!readdir_r(dir, &entry, &result) && result) {
330                 ret = SP_OK;
331                 if (entry.d_type != DT_CHR)
332                         continue;
333                 if (strncmp(entry.d_name, "cuaU", 4) != 0)
334                         if (strncmp(entry.d_name, "cuau", 4) != 0)
335                                 if (strncmp(entry.d_name, "cuad", 4) != 0)
336                                         continue;
337                 if (strend(entry.d_name, ".init"))
338                         continue;
339                 if (strend(entry.d_name, ".lock"))
340                         continue;
341
342                 DEBUG_FMT("Found device %s", name);
343                 snprintf(name, sizeof(name), "/dev/%s", entry.d_name);
344
345                 /* Check that we can open tty/cua device in rw mode - we need that. */
346                 if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY | O_TTY_INIT | O_CLOEXEC)) < 0) {
347                         DEBUG("open failed, skipping");
348                         continue;
349                 }
350
351                 /* Sanity check if we got a real tty. */
352                 if (!isatty(fd)) {
353                         close(fd);
354                         continue;
355                 }
356
357                 ret = tcgetattr(fd, &tios);
358                 close(fd);
359                 if (ret < 0 || cfgetospeed(&tios) <= 0 || cfgetispeed(&tios) <= 0)
360                         continue;
361
362                 DEBUG_FMT("Found port %s", name);
363                 DBG("%s: %s\n", __func__, entry.d_name);
364
365                 *list = list_append(*list, name);
366                 if (!list) {
367                         SET_ERROR(ret, SP_ERR_MEM, "list append failed");
368                         break;
369                 }
370         }
371         closedir(dir);
372
373         return ret;
374 }