]> sigrok.org Git - libserialport.git/blob - freebsd.c
a1305b6ebdcfde05e6a25d9414395ba91256e0bc
[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), "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), "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         /* Native UART enumeration. */
257         if ((cua_sfx[0] == 'u') || (cua_sfx[0] == 'd')) {
258                 port->transport = SP_TRANSPORT_NATIVE;
259                 snprintf(tbuf, sizeof(tbuf), "cua%s", cua_sfx);
260                 port->description = strdup(tbuf);
261                 RETURN_OK();
262         }
263
264         /* USB device enumeration. */
265         dev = dev_last = NULL;
266         be = libusb20_be_alloc_default();
267         cua_dev_found = 0;
268         while (cua_dev_found == 0) {
269                 dev = libusb20_be_device_foreach(be, dev_last);
270                 if (!dev)
271                         break;
272
273                 libusb20_dev_open(dev, 0);
274                 DBG("Device descriptor: '%s'\n", libusb20_dev_get_desc(dev));
275
276                 for (idx = 0; idx <= UINT8_MAX - 1; idx++) {
277                         char *drv_name_str = NULL;
278                         char *drv_inst_str = NULL;
279                         char *ttyname = NULL;
280                         int ttyport_cnt;
281
282                         rc = libusb_query_port(dev, idx, &drv_name_str, &drv_inst_str);
283                         if (rc == 0) {
284                                 rc = sysctl_query_dev_drv(drv_name_str,
285                                           drv_inst_str, &ttyname, &ttyport_cnt);
286                                 if (rc == 0) {
287                                         /* Handle multiple subinstances of serial ports in the same driver instance. */
288                                         for (sub_inst = 0; sub_inst < ttyport_cnt; sub_inst++) {
289                                                 if (ttyport_cnt == 1)
290                                                         snprintf(tbuf, sizeof(tbuf), "%s", ttyname);
291                                                 else
292                                                         snprintf(tbuf, sizeof(tbuf), "%s.%d", ttyname, sub_inst);
293                                                 if (!strcmp(cua_sfx, tbuf)) {
294                                                         DBG("MATCH: '%s' == '%s'\n", cua_sfx, tbuf);
295                                                         cua_dev_found = 1;
296                                                         populate_port_struct_from_libusb_desc(port, dev);
297                                                         break; /* Break out of sub instance loop. */
298                                                 }
299                                         }
300                                 }
301                         }
302
303                         /* Clean up. */
304                         if (ttyname)
305                                 free(ttyname);
306                         if (drv_name_str)
307                                 free(drv_name_str);
308                         if (drv_inst_str)
309                                 free(drv_inst_str);
310                         if (cua_dev_found)
311                                 break; /* Break out of USB device port idx loop. */
312                 }
313                 libusb20_dev_close(dev);
314                 dev_last = dev;
315         }
316         libusb20_be_free(be);
317
318         if (cua_dev_found == 0)
319                 DBG("WARN: Found no match '%s' %s'\n", port->name, cua_sfx);
320
321         RETURN_OK();
322 }
323
324 SP_PRIV enum sp_return list_ports(struct sp_port ***list)
325 {
326         DIR *dir;
327         struct dirent entry;
328         struct dirent *result;
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 (!readdir_r(dir, &entry, &result) && result) {
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 }