lowl-vcom.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137
  1. /*
  2. * Copyright 2012-2013 Luke Dashjr
  3. * Copyright 2013 Con Kolivas
  4. * Copyright 2012 Andrew Smith
  5. * Copyright 2013 Xiangfu
  6. *
  7. * This program is free software; you can redistribute it and/or modify it
  8. * under the terms of the GNU General Public License as published by the Free
  9. * Software Foundation; either version 3 of the License, or (at your option)
  10. * any later version. See COPYING for more details.
  11. */
  12. #include "config.h"
  13. #include <ctype.h>
  14. #include <stdarg.h>
  15. #include <stdbool.h>
  16. #include <stdint.h>
  17. #include <stdlib.h>
  18. #include <sys/types.h>
  19. #include <dirent.h>
  20. #include <string.h>
  21. #ifdef HAVE_SYS_FILE_H
  22. #include <sys/file.h>
  23. #endif
  24. #ifdef HAVE_LIBUSB
  25. #include <libusb.h>
  26. #endif
  27. #include "miner.h"
  28. #ifndef WIN32
  29. #include <errno.h>
  30. #include <termios.h>
  31. #include <sys/ioctl.h>
  32. #include <sys/stat.h>
  33. #include <unistd.h>
  34. #include <fcntl.h>
  35. #ifndef O_CLOEXEC
  36. #define O_CLOEXEC 0
  37. #endif
  38. #else /* WIN32 */
  39. #include <windows.h>
  40. #ifdef HAVE_WIN_DDKUSB
  41. #include <setupapi.h>
  42. #include <usbioctl.h>
  43. #include <usbiodef.h>
  44. #endif
  45. #include <io.h>
  46. #include <utlist.h>
  47. #define dlsym (void*)GetProcAddress
  48. #define dlclose FreeLibrary
  49. typedef unsigned long FT_STATUS;
  50. typedef PVOID FT_HANDLE;
  51. __stdcall FT_STATUS (*FT_ListDevices)(PVOID pArg1, PVOID pArg2, DWORD Flags);
  52. __stdcall FT_STATUS (*FT_Open)(int idx, FT_HANDLE*);
  53. __stdcall FT_STATUS (*FT_GetComPortNumber)(FT_HANDLE, LPLONG lplComPortNumber);
  54. __stdcall FT_STATUS (*FT_Close)(FT_HANDLE);
  55. const uint32_t FT_OPEN_BY_SERIAL_NUMBER = 1;
  56. const uint32_t FT_OPEN_BY_DESCRIPTION = 2;
  57. const uint32_t FT_LIST_ALL = 0x20000000;
  58. const uint32_t FT_LIST_BY_INDEX = 0x40000000;
  59. const uint32_t FT_LIST_NUMBER_ONLY = 0x80000000;
  60. enum {
  61. FT_OK,
  62. };
  63. #endif /* WIN32 */
  64. #ifdef HAVE_LIBUDEV
  65. #include <libudev.h>
  66. #include <sys/ioctl.h>
  67. #endif
  68. #include "logging.h"
  69. #include "lowlevel.h"
  70. #include "miner.h"
  71. #include "util.h"
  72. #include "lowl-vcom.h"
  73. struct lowlevel_driver lowl_vcom;
  74. struct detectone_meta_info_t detectone_meta_info;
  75. void clear_detectone_meta_info(void)
  76. {
  77. detectone_meta_info = (struct detectone_meta_info_t){
  78. .manufacturer = NULL,
  79. };
  80. }
  81. #define _vcom_unique_id(devpath) devpath_to_devid(devpath)
  82. struct lowlevel_device_info *_vcom_devinfo_findorcreate(struct lowlevel_device_info ** const devinfo_list, const char * const devpath)
  83. {
  84. struct lowlevel_device_info *devinfo;
  85. char * const devid = _vcom_unique_id(devpath);
  86. HASH_FIND_STR(*devinfo_list, devid, devinfo);
  87. if (!devinfo)
  88. {
  89. devinfo = malloc(sizeof(*devinfo));
  90. *devinfo = (struct lowlevel_device_info){
  91. .lowl = &lowl_vcom,
  92. .path = strdup(devpath),
  93. .devid = devid,
  94. };
  95. HASH_ADD_KEYPTR(hh, *devinfo_list, devinfo->devid, strlen(devid), devinfo);
  96. }
  97. else
  98. free(devid);
  99. return devinfo;
  100. }
  101. #ifdef HAVE_LIBUDEV
  102. static
  103. void _decode_udev_enc(char *o, const char *s)
  104. {
  105. while(s[0])
  106. {
  107. if (s[0] == '\\' && s[1] == 'x' && s[2] && s[3])
  108. {
  109. hex2bin((void*)(o++), &s[2], 1);
  110. s += 4;
  111. }
  112. else
  113. (o++)[0] = (s++)[0];
  114. }
  115. o[0] = '\0';
  116. }
  117. static
  118. char *_decode_udev_enc_dup(const char *s)
  119. {
  120. if (!s)
  121. return NULL;
  122. char *o = malloc(strlen(s) + 1);
  123. if (!o)
  124. {
  125. applog(LOG_ERR, "Failed to malloc in _decode_udev_enc_dup");
  126. return NULL;
  127. }
  128. _decode_udev_enc(o, s);
  129. return o;
  130. }
  131. static
  132. void _vcom_devinfo_scan_udev(struct lowlevel_device_info ** const devinfo_list)
  133. {
  134. struct udev *udev = udev_new();
  135. struct udev_enumerate *enumerate = udev_enumerate_new(udev);
  136. struct udev_list_entry *list_entry;
  137. struct lowlevel_device_info *devinfo;
  138. udev_enumerate_add_match_subsystem(enumerate, "tty");
  139. udev_enumerate_add_match_property(enumerate, "ID_SERIAL", "*");
  140. udev_enumerate_scan_devices(enumerate);
  141. udev_list_entry_foreach(list_entry, udev_enumerate_get_list_entry(enumerate)) {
  142. struct udev_device *device = udev_device_new_from_syspath(
  143. udev_enumerate_get_udev(enumerate),
  144. udev_list_entry_get_name(list_entry)
  145. );
  146. if (!device)
  147. continue;
  148. const char * const devpath = udev_device_get_devnode(device);
  149. devinfo = _vcom_devinfo_findorcreate(devinfo_list, devpath);
  150. BFGINIT(devinfo->manufacturer, _decode_udev_enc_dup(udev_device_get_property_value(device, "ID_VENDOR_ENC")));
  151. BFGINIT(devinfo->product, _decode_udev_enc_dup(udev_device_get_property_value(device, "ID_MODEL_ENC")));
  152. BFGINIT(devinfo->serial, _decode_udev_enc_dup(udev_device_get_property_value(device, "ID_SERIAL_SHORT")));
  153. udev_device_unref(device);
  154. }
  155. udev_enumerate_unref(enumerate);
  156. udev_unref(udev);
  157. }
  158. #endif
  159. #ifndef WIN32
  160. static
  161. void _vcom_devinfo_scan_devserial(struct lowlevel_device_info ** const devinfo_list)
  162. {
  163. DIR *D;
  164. struct dirent *de;
  165. const char udevdir[] = "/dev/serial/by-id";
  166. char devpath[sizeof(udevdir) + 1 + NAME_MAX];
  167. char *devfile = devpath + sizeof(udevdir);
  168. struct lowlevel_device_info *devinfo;
  169. D = opendir(udevdir);
  170. if (!D)
  171. return;
  172. memcpy(devpath, udevdir, sizeof(udevdir) - 1);
  173. devpath[sizeof(udevdir) - 1] = '/';
  174. while ( (de = readdir(D)) ) {
  175. if (strncmp(de->d_name, "usb-", 4))
  176. continue;
  177. strcpy(devfile, de->d_name);
  178. devinfo = _vcom_devinfo_findorcreate(devinfo_list, devpath);
  179. if (!(devinfo->manufacturer || devinfo->product || devinfo->serial))
  180. devinfo->product = strdup(devfile);
  181. }
  182. closedir(D);
  183. }
  184. #endif
  185. #ifndef WIN32
  186. static
  187. char *_sysfs_do_read(const char *devpath, char *devfile, const char *append)
  188. {
  189. char buf[0x40];
  190. FILE *F;
  191. strcpy(devfile, append);
  192. F = fopen(devpath, "r");
  193. if (F)
  194. {
  195. if (fgets(buf, sizeof(buf), F))
  196. {
  197. size_t L = strlen(buf);
  198. while (isCspace(buf[--L]))
  199. buf[L] = '\0';
  200. }
  201. else
  202. buf[0] = '\0';
  203. fclose(F);
  204. }
  205. else
  206. buf[0] = '\0';
  207. return buf[0] ? strdup(buf) : NULL;
  208. }
  209. static
  210. void _sysfs_find_tty(char *devpath, char *devfile, struct lowlevel_device_info ** const devinfo_list)
  211. {
  212. struct lowlevel_device_info *devinfo;
  213. DIR *DT;
  214. struct dirent *de;
  215. char ttybuf[0x10] = "/dev/";
  216. char *mydevfile = strdup(devfile);
  217. DT = opendir(devpath);
  218. if (!DT)
  219. goto out;
  220. while ( (de = readdir(DT)) )
  221. {
  222. if (strncmp(de->d_name, "tty", 3))
  223. continue;
  224. if (!de->d_name[3])
  225. {
  226. // "tty" directory: recurse (needed for ttyACM)
  227. sprintf(devfile, "%s/tty", mydevfile);
  228. _sysfs_find_tty(devpath, devfile, devinfo_list);
  229. continue;
  230. }
  231. if (strncmp(&de->d_name[3], "USB", 3) && strncmp(&de->d_name[3], "ACM", 3))
  232. continue;
  233. strcpy(&ttybuf[5], de->d_name);
  234. devinfo = _vcom_devinfo_findorcreate(devinfo_list, ttybuf);
  235. BFGINIT(devinfo->manufacturer, _sysfs_do_read(devpath, devfile, "/manufacturer"));
  236. BFGINIT(devinfo->product, _sysfs_do_read(devpath, devfile, "/product"));
  237. BFGINIT(devinfo->serial, _sysfs_do_read(devpath, devfile, "/serial"));
  238. }
  239. closedir(DT);
  240. out:
  241. free(mydevfile);
  242. }
  243. static
  244. void _vcom_devinfo_scan_sysfs(struct lowlevel_device_info ** const devinfo_list)
  245. {
  246. DIR *D, *DS;
  247. struct dirent *de;
  248. const char devroot[] = "/sys/bus/usb/devices";
  249. const size_t devrootlen = sizeof(devroot) - 1;
  250. char devpath[sizeof(devroot) + (NAME_MAX * 3)];
  251. char *devfile, *upfile;
  252. size_t len, len2;
  253. D = opendir(devroot);
  254. if (!D)
  255. return;
  256. memcpy(devpath, devroot, devrootlen);
  257. devpath[devrootlen] = '/';
  258. while ( (de = readdir(D)) )
  259. {
  260. len = strlen(de->d_name);
  261. upfile = &devpath[devrootlen + 1];
  262. memcpy(upfile, de->d_name, len);
  263. devfile = upfile + len;
  264. devfile[0] = '\0';
  265. DS = opendir(devpath);
  266. if (!DS)
  267. continue;
  268. devfile[0] = '/';
  269. ++devfile;
  270. while ( (de = readdir(DS)) )
  271. {
  272. if (strncmp(de->d_name, upfile, len))
  273. continue;
  274. len2 = strlen(de->d_name);
  275. memcpy(devfile, de->d_name, len2 + 1);
  276. _sysfs_find_tty(devpath, devfile, devinfo_list);
  277. }
  278. closedir(DS);
  279. }
  280. closedir(D);
  281. }
  282. #endif
  283. #ifdef HAVE_WIN_DDKUSB
  284. static const GUID WIN_GUID_DEVINTERFACE_USB_HOST_CONTROLLER = { 0x3ABF6F2D, 0x71C4, 0x462A, {0x8A, 0x92, 0x1E, 0x68, 0x61, 0xE6, 0xAF, 0x27} };
  285. static
  286. char *windows_usb_get_port_path(HANDLE hubh, const int portno)
  287. {
  288. size_t namesz;
  289. ULONG rsz;
  290. {
  291. USB_NODE_CONNECTION_NAME pathinfo = {
  292. .ConnectionIndex = portno,
  293. };
  294. if (!(DeviceIoControl(hubh, IOCTL_USB_GET_NODE_CONNECTION_NAME, &pathinfo, sizeof(pathinfo), &pathinfo, sizeof(pathinfo), &rsz, NULL) && rsz >= sizeof(pathinfo)))
  295. applogfailinfor(NULL, LOG_ERR, "ioctl (1)", "%s", bfg_strerror(GetLastError(), BST_SYSTEM));
  296. namesz = pathinfo.ActualLength;
  297. }
  298. const size_t bufsz = sizeof(USB_NODE_CONNECTION_NAME) + namesz;
  299. uint8_t buf[bufsz];
  300. USB_NODE_CONNECTION_NAME *path = (USB_NODE_CONNECTION_NAME *)buf;
  301. *path = (USB_NODE_CONNECTION_NAME){
  302. .ConnectionIndex = portno,
  303. };
  304. if (!(DeviceIoControl(hubh, IOCTL_USB_GET_NODE_CONNECTION_NAME, path, bufsz, path, bufsz, &rsz, NULL) && rsz >= sizeof(*path)))
  305. applogfailinfor(NULL, LOG_ERR, "ioctl (2)", "%s", bfg_strerror(GetLastError(), BST_SYSTEM));
  306. return ucs2_to_utf8_dup(path->NodeName, path->ActualLength);
  307. }
  308. static
  309. char *windows_usb_get_string(HANDLE hubh, const int portno, const uint8_t descid)
  310. {
  311. if (!descid)
  312. return NULL;
  313. const size_t descsz_max = sizeof(USB_STRING_DESCRIPTOR) + MAXIMUM_USB_STRING_LENGTH;
  314. const size_t reqsz = sizeof(USB_DESCRIPTOR_REQUEST) + descsz_max;
  315. uint8_t buf[reqsz];
  316. USB_DESCRIPTOR_REQUEST * const req = (USB_DESCRIPTOR_REQUEST *)buf;
  317. USB_STRING_DESCRIPTOR * const desc = (USB_STRING_DESCRIPTOR *)&req[1];
  318. *req = (USB_DESCRIPTOR_REQUEST){
  319. .ConnectionIndex = portno,
  320. .SetupPacket = {
  321. .wValue = (USB_STRING_DESCRIPTOR_TYPE << 8) | descid,
  322. .wIndex = 0,
  323. .wLength = descsz_max,
  324. },
  325. };
  326. // Need to explicitly zero the output memory
  327. memset(desc, '\0', descsz_max);
  328. ULONG descsz;
  329. if (!DeviceIoControl(hubh, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, req, reqsz, req, reqsz, &descsz, NULL))
  330. applogfailinfor(NULL, LOG_DEBUG, "ioctl", "%s", bfg_strerror(GetLastError(), BST_SYSTEM));
  331. if (descsz < 2 || desc->bDescriptorType != USB_STRING_DESCRIPTOR_TYPE || desc->bLength > descsz - sizeof(USB_DESCRIPTOR_REQUEST) || desc->bLength % 2)
  332. applogfailr(NULL, LOG_ERR, "sanity check");
  333. return ucs2_to_utf8_dup(desc->bString, desc->bLength);
  334. }
  335. static void _vcom_devinfo_scan_windows__hub(struct lowlevel_device_info **, const char *);
  336. static
  337. void _vcom_devinfo_scan_windows__hubport(struct lowlevel_device_info ** const devinfo_list, HANDLE hubh, const int portno)
  338. {
  339. struct lowlevel_device_info *devinfo;
  340. const size_t conninfosz = sizeof(USB_NODE_CONNECTION_INFORMATION) + (sizeof(USB_PIPE_INFO) * 30);
  341. uint8_t buf[conninfosz];
  342. USB_NODE_CONNECTION_INFORMATION * const conninfo = (USB_NODE_CONNECTION_INFORMATION *)buf;
  343. conninfo->ConnectionIndex = portno;
  344. ULONG respsz;
  345. if (!DeviceIoControl(hubh, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION, conninfo, conninfosz, conninfo, conninfosz, &respsz, NULL))
  346. applogfailinfor(, LOG_ERR, "ioctl", "%s", bfg_strerror(GetLastError(), BST_SYSTEM));
  347. if (conninfo->ConnectionStatus != DeviceConnected)
  348. return;
  349. if (conninfo->DeviceIsHub)
  350. {
  351. const char * const hubpath = windows_usb_get_port_path(hubh, portno);
  352. if (hubpath)
  353. _vcom_devinfo_scan_windows__hub(devinfo_list, hubpath);
  354. return;
  355. }
  356. const USB_DEVICE_DESCRIPTOR * const devdesc = &conninfo->DeviceDescriptor;
  357. char * const serial = windows_usb_get_string(hubh, portno, devdesc->iSerialNumber);
  358. if (!serial)
  359. {
  360. out:
  361. free(serial);
  362. return;
  363. }
  364. const size_t slen = strlen(serial);
  365. char subkey[52 + slen + 18 + 1];
  366. sprintf(subkey, "SYSTEM\\CurrentControlSet\\Enum\\USB\\VID_%04x&PID_%04x\\%s\\Device Parameters",
  367. (unsigned)devdesc->idVendor, (unsigned)devdesc->idProduct, serial);
  368. HKEY hkey;
  369. int e;
  370. if (ERROR_SUCCESS != (e = RegOpenKey(HKEY_LOCAL_MACHINE, subkey, &hkey)))
  371. {
  372. applogfailinfo(LOG_ERR, "open Device Parameters registry key", "%s", bfg_strerror(e, BST_SYSTEM));
  373. goto out;
  374. }
  375. char devpath[0x10] = "\\\\.\\";
  376. DWORD type, sz = sizeof(devpath) - 4;
  377. if (ERROR_SUCCESS != (e = RegQueryValueExA(hkey, "PortName", NULL, &type, (LPBYTE)&devpath[4], &sz)))
  378. {
  379. applogfailinfo(LOG_DEBUG, "get PortName registry key value", "%s", bfg_strerror(e, BST_SYSTEM));
  380. RegCloseKey(hkey);
  381. goto out;
  382. }
  383. RegCloseKey(hkey);
  384. if (type != REG_SZ)
  385. {
  386. applogfailinfor(, LOG_ERR, "get expected type for PortName registry key value", "%ld", (long)type);
  387. goto out;
  388. }
  389. devinfo = _vcom_devinfo_findorcreate(devinfo_list, devpath);
  390. BFGINIT(devinfo->manufacturer, windows_usb_get_string(hubh, portno, devdesc->iManufacturer));
  391. BFGINIT(devinfo->product, windows_usb_get_string(hubh, portno, devdesc->iProduct));
  392. if (devinfo->serial)
  393. free(serial);
  394. else
  395. devinfo->serial = serial;
  396. }
  397. static
  398. void _vcom_devinfo_scan_windows__hub(struct lowlevel_device_info ** const devinfo_list, const char * const hubpath)
  399. {
  400. HANDLE hubh;
  401. USB_NODE_INFORMATION nodeinfo;
  402. {
  403. char deviceName[4 + strlen(hubpath) + 1];
  404. sprintf(deviceName, "\\\\.\\%s", hubpath);
  405. hubh = CreateFile(deviceName, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
  406. if (hubh == INVALID_HANDLE_VALUE)
  407. applogr(, LOG_ERR, "Error opening USB hub device %s for autodetect: %s", deviceName, bfg_strerror(GetLastError(), BST_SYSTEM));
  408. }
  409. ULONG nBytes;
  410. if (!DeviceIoControl(hubh, IOCTL_USB_GET_NODE_INFORMATION, &nodeinfo, sizeof(nodeinfo), &nodeinfo, sizeof(nodeinfo), &nBytes, NULL))
  411. applogfailinfor(, LOG_ERR, "ioctl", "%s", bfg_strerror(GetLastError(), BST_SYSTEM));
  412. const int portcount = nodeinfo.u.HubInformation.HubDescriptor.bNumberOfPorts;
  413. for (int i = 1; i <= portcount; ++i)
  414. _vcom_devinfo_scan_windows__hubport(devinfo_list, hubh, i);
  415. CloseHandle(hubh);
  416. }
  417. static
  418. char *windows_usb_get_root_hub_path(HANDLE hcntlrh)
  419. {
  420. size_t namesz;
  421. ULONG rsz;
  422. {
  423. USB_ROOT_HUB_NAME pathinfo;
  424. if (!DeviceIoControl(hcntlrh, IOCTL_USB_GET_ROOT_HUB_NAME, 0, 0, &pathinfo, sizeof(pathinfo), &rsz, NULL))
  425. applogfailinfor(NULL, LOG_ERR, "ioctl (1)", "%s", bfg_strerror(GetLastError(), BST_SYSTEM));
  426. if (rsz < sizeof(pathinfo))
  427. applogfailinfor(NULL, LOG_ERR, "ioctl (1)", "Size too small (%d < %d)", (int)rsz, (int)sizeof(pathinfo));
  428. namesz = pathinfo.ActualLength;
  429. }
  430. const size_t bufsz = sizeof(USB_ROOT_HUB_NAME) + namesz;
  431. uint8_t buf[bufsz];
  432. USB_ROOT_HUB_NAME *hubpath = (USB_ROOT_HUB_NAME *)buf;
  433. if (!(DeviceIoControl(hcntlrh, IOCTL_USB_GET_ROOT_HUB_NAME, NULL, 0, hubpath, bufsz, &rsz, NULL) && rsz >= sizeof(*hubpath)))
  434. applogfailinfor(NULL, LOG_ERR, "ioctl (2)", "%s", bfg_strerror(GetLastError(), BST_SYSTEM));
  435. return ucs2_to_utf8_dup(hubpath->RootHubName, hubpath->ActualLength);
  436. }
  437. static
  438. void _vcom_devinfo_scan_windows__hcntlr(struct lowlevel_device_info ** const devinfo_list, HDEVINFO *devinfo, const int i)
  439. {
  440. SP_DEVICE_INTERFACE_DATA devifacedata = {
  441. .cbSize = sizeof(devifacedata),
  442. };
  443. if (!SetupDiEnumDeviceInterfaces(*devinfo, 0, (LPGUID)&WIN_GUID_DEVINTERFACE_USB_HOST_CONTROLLER, i, &devifacedata))
  444. applogfailinfor(, LOG_ERR, "SetupDiEnumDeviceInterfaces", "%s", bfg_strerror(GetLastError(), BST_SYSTEM));
  445. DWORD detailsz;
  446. if (!(!SetupDiGetDeviceInterfaceDetail(*devinfo, &devifacedata, NULL, 0, &detailsz, NULL) && GetLastError() == ERROR_INSUFFICIENT_BUFFER))
  447. applogfailinfor(, LOG_ERR, "SetupDiEnumDeviceInterfaceDetail (1)", "%s", bfg_strerror(GetLastError(), BST_SYSTEM));
  448. PSP_DEVICE_INTERFACE_DETAIL_DATA detail = alloca(detailsz);
  449. detail->cbSize = sizeof(*detail);
  450. if (!SetupDiGetDeviceInterfaceDetail(*devinfo, &devifacedata, detail, detailsz, &detailsz, NULL))
  451. applogfailinfor(, LOG_ERR, "SetupDiEnumDeviceInterfaceDetail (2)", "%s", bfg_strerror(GetLastError(), BST_SYSTEM));
  452. HANDLE hcntlrh = CreateFile(detail->DevicePath, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
  453. if (hcntlrh == INVALID_HANDLE_VALUE)
  454. applogfailinfor(, LOG_DEBUG, "open USB host controller device", "%s", bfg_strerror(GetLastError(), BST_SYSTEM));
  455. char * const hubpath = windows_usb_get_root_hub_path(hcntlrh);
  456. CloseHandle(hcntlrh);
  457. if (unlikely(!hubpath))
  458. return;
  459. _vcom_devinfo_scan_windows__hub(devinfo_list, hubpath);
  460. free(hubpath);
  461. }
  462. static
  463. void _vcom_devinfo_scan_windows(struct lowlevel_device_info ** const devinfo_list)
  464. {
  465. HDEVINFO devinfo;
  466. devinfo = SetupDiGetClassDevs(&WIN_GUID_DEVINTERFACE_USB_HOST_CONTROLLER, NULL, NULL, (DIGCF_PRESENT | DIGCF_DEVICEINTERFACE));
  467. SP_DEVINFO_DATA devinfodata = {
  468. .cbSize = sizeof(devinfodata),
  469. };
  470. for (int i = 0; SetupDiEnumDeviceInfo(devinfo, i, &devinfodata); ++i)
  471. _vcom_devinfo_scan_windows__hcntlr(devinfo_list, &devinfo, i);
  472. SetupDiDestroyDeviceInfoList(devinfo);
  473. }
  474. #endif
  475. #ifdef WIN32
  476. #define LOAD_SYM(sym) do { \
  477. if (!(sym = dlsym(dll, #sym))) { \
  478. applog(LOG_DEBUG, "Failed to load " #sym ", not using FTDI autodetect"); \
  479. goto out; \
  480. } \
  481. } while(0)
  482. static
  483. char *_ftdi_get_string(char *buf, intptr_t i, DWORD flags)
  484. {
  485. if (FT_OK != FT_ListDevices((PVOID)i, buf, FT_LIST_BY_INDEX | flags))
  486. return NULL;
  487. return buf[0] ? buf : NULL;
  488. }
  489. static
  490. void _vcom_devinfo_scan_ftdi(struct lowlevel_device_info ** const devinfo_list)
  491. {
  492. char devpath[] = "\\\\.\\COMnnnnn";
  493. char *devpathnum = &devpath[7];
  494. char **bufptrs;
  495. char *buf;
  496. char serial[64];
  497. struct lowlevel_device_info *devinfo;
  498. DWORD i;
  499. FT_STATUS ftStatus;
  500. DWORD numDevs;
  501. HMODULE dll = LoadLibrary("FTD2XX.DLL");
  502. if (!dll) {
  503. applog(LOG_DEBUG, "FTD2XX.DLL failed to load, not using FTDI autodetect");
  504. return;
  505. }
  506. LOAD_SYM(FT_ListDevices);
  507. LOAD_SYM(FT_Open);
  508. LOAD_SYM(FT_GetComPortNumber);
  509. LOAD_SYM(FT_Close);
  510. ftStatus = FT_ListDevices(&numDevs, NULL, FT_LIST_NUMBER_ONLY);
  511. if (ftStatus != FT_OK) {
  512. applog(LOG_DEBUG, "FTDI device count failed, not using FTDI autodetect");
  513. goto out;
  514. }
  515. applog(LOG_DEBUG, "FTDI reports %u devices", (unsigned)numDevs);
  516. buf = alloca(65 * numDevs);
  517. bufptrs = alloca(sizeof(*bufptrs) * (numDevs + 1));
  518. for (i = 0; i < numDevs; ++i)
  519. bufptrs[i] = &buf[i * 65];
  520. bufptrs[numDevs] = NULL;
  521. ftStatus = FT_ListDevices(bufptrs, &numDevs, FT_LIST_ALL | FT_OPEN_BY_DESCRIPTION);
  522. if (ftStatus != FT_OK) {
  523. applog(LOG_DEBUG, "FTDI device list failed, not using FTDI autodetect");
  524. goto out;
  525. }
  526. for (i = numDevs; i > 0; ) {
  527. --i;
  528. bufptrs[i][64] = '\0';
  529. FT_HANDLE ftHandle;
  530. if (FT_OK != FT_Open(i, &ftHandle))
  531. continue;
  532. LONG lComPortNumber;
  533. ftStatus = FT_GetComPortNumber(ftHandle, &lComPortNumber);
  534. FT_Close(ftHandle);
  535. if (FT_OK != ftStatus || lComPortNumber < 0)
  536. continue;
  537. applog(LOG_ERR, "FT_GetComPortNumber(%p (%ld), %ld)", ftHandle, (long)i, (long)lComPortNumber);
  538. sprintf(devpathnum, "%d", (int)lComPortNumber);
  539. devinfo = _vcom_devinfo_findorcreate(devinfo_list, devpath);
  540. BFGINIT(devinfo->product, (bufptrs[i] && bufptrs[i][0]) ? strdup(bufptrs[i]) : NULL);
  541. BFGINIT(devinfo->serial, maybe_strdup(_ftdi_get_string(serial, i, FT_OPEN_BY_SERIAL_NUMBER)));
  542. }
  543. out:
  544. dlclose(dll);
  545. }
  546. #endif
  547. #ifdef WIN32
  548. extern void _vcom_devinfo_scan_querydosdevice(struct lowlevel_device_info **);
  549. #else
  550. extern void _vcom_devinfo_scan_lsdev(struct lowlevel_device_info **);
  551. #endif
  552. void _vcom_devinfo_scan_user(struct lowlevel_device_info ** const devinfo_list)
  553. {
  554. struct string_elist *sd_iter, *sd_tmp;
  555. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  556. {
  557. const char * const dname = sd_iter->string;
  558. const char * const colon = strpbrk(dname, ":@");
  559. const char *dev;
  560. if (!(colon && colon != dname))
  561. dev = dname;
  562. else
  563. dev = &colon[1];
  564. if (!access(dev, F_OK))
  565. _vcom_devinfo_findorcreate(devinfo_list, dev);
  566. }
  567. }
  568. extern bool lowl_usb_attach_kernel_driver(const struct lowlevel_device_info *);
  569. bool vcom_lowl_probe_wrapper(const struct lowlevel_device_info * const info, detectone_func_t detectone)
  570. {
  571. if (info->lowl != &lowl_vcom)
  572. {
  573. #ifdef HAVE_LIBUSB
  574. if (info->lowl == &lowl_usb)
  575. {
  576. if (lowl_usb_attach_kernel_driver(info))
  577. bfg_need_detect_rescan = true;
  578. }
  579. #endif
  580. return false;
  581. }
  582. detectone_meta_info = (struct detectone_meta_info_t){
  583. .manufacturer = info->manufacturer,
  584. .product = info->product,
  585. .serial = info->serial,
  586. };
  587. const bool rv = detectone(info->path);
  588. clear_detectone_meta_info();
  589. return rv;
  590. }
  591. bool _serial_autodetect_found_cb(struct lowlevel_device_info * const devinfo, void *userp)
  592. {
  593. detectone_func_t detectone = userp;
  594. if (bfg_claim_any(NULL, devinfo->path, devinfo->devid))
  595. {
  596. applog(LOG_DEBUG, "%s (%s) is already claimed, skipping probe", devinfo->path, devinfo->devid);
  597. return false;
  598. }
  599. if (devinfo->lowl != &lowl_vcom)
  600. {
  601. #ifdef HAVE_LIBUSB
  602. if (devinfo->lowl == &lowl_usb)
  603. {
  604. if (lowl_usb_attach_kernel_driver(devinfo))
  605. bfg_need_detect_rescan = true;
  606. }
  607. else
  608. #endif
  609. applog(LOG_WARNING, "Non-VCOM %s (%s) matched", devinfo->path, devinfo->devid);
  610. return false;
  611. }
  612. detectone_meta_info = (struct detectone_meta_info_t){
  613. .manufacturer = devinfo->manufacturer,
  614. .product = devinfo->product,
  615. .serial = devinfo->serial,
  616. };
  617. const bool rv = detectone(devinfo->path);
  618. clear_detectone_meta_info();
  619. return rv;
  620. }
  621. int _serial_autodetect(detectone_func_t detectone, ...)
  622. {
  623. va_list needles;
  624. char *needles_array[0x10];
  625. int needlecount = 0;
  626. va_start(needles, detectone);
  627. while ( (needles_array[needlecount++] = va_arg(needles, void *)) )
  628. {}
  629. va_end(needles);
  630. return _lowlevel_detect(_serial_autodetect_found_cb, NULL, (const char **)needles_array, detectone);
  631. }
  632. static
  633. struct lowlevel_device_info *vcom_devinfo_scan()
  634. {
  635. struct lowlevel_device_info *devinfo_hash = NULL;
  636. struct lowlevel_device_info *devinfo_list = NULL;
  637. struct lowlevel_device_info *devinfo, *tmp;
  638. // All 3 USB Strings available:
  639. #ifndef WIN32
  640. _vcom_devinfo_scan_sysfs(&devinfo_hash);
  641. #endif
  642. #ifdef HAVE_WIN_DDKUSB
  643. _vcom_devinfo_scan_windows(&devinfo_hash);
  644. #endif
  645. #ifdef HAVE_LIBUDEV
  646. _vcom_devinfo_scan_udev(&devinfo_hash);
  647. #endif
  648. // Missing Manufacturer:
  649. #ifdef WIN32
  650. _vcom_devinfo_scan_ftdi(&devinfo_hash);
  651. #endif
  652. // All blobbed together:
  653. #ifndef WIN32
  654. _vcom_devinfo_scan_devserial(&devinfo_hash);
  655. #endif
  656. // No info:
  657. #ifdef WIN32
  658. _vcom_devinfo_scan_querydosdevice(&devinfo_hash);
  659. #else
  660. _vcom_devinfo_scan_lsdev(&devinfo_hash);
  661. #endif
  662. _vcom_devinfo_scan_user(&devinfo_hash);
  663. // Convert hash to simple list
  664. HASH_ITER(hh, devinfo_hash, devinfo, tmp)
  665. {
  666. LL_PREPEND(devinfo_list, devinfo);
  667. }
  668. HASH_CLEAR(hh, devinfo_hash);
  669. return devinfo_list;
  670. }
  671. struct device_drv *bfg_claim_serial(struct device_drv * const api, const bool verbose, const char * const devpath)
  672. {
  673. char * const devs = _vcom_unique_id(devpath);
  674. if (!devs)
  675. return false;
  676. struct device_drv * const rv = bfg_claim_any(api, (verbose ? devpath : NULL), devs);
  677. free(devs);
  678. return rv;
  679. }
  680. // This code is purely for debugging but is very useful for that
  681. // It also took quite a bit of effort so I left it in
  682. // #define TERMIOS_DEBUG 1
  683. // Here to include it at compile time
  684. // It's off by default
  685. #ifndef WIN32
  686. #ifdef TERMIOS_DEBUG
  687. #define BITSSET "Y"
  688. #define BITSNOTSET "N"
  689. int tiospeed(speed_t speed)
  690. {
  691. switch (speed) {
  692. #define IOSPEED(baud) \
  693. case B ## baud: \
  694. return baud; \
  695. // END
  696. #include "iospeeds_local.h"
  697. #undef IOSPEED
  698. default:
  699. return -1;
  700. }
  701. }
  702. void termios_debug(const char *devpath, struct termios *my_termios, const char *msg)
  703. {
  704. applog(LOG_DEBUG, "TIOS: Open %s attributes %s: ispeed=%d ospeed=%d",
  705. devpath, msg, tiospeed(cfgetispeed(my_termios)), tiospeed(cfgetispeed(my_termios)));
  706. #define ISSETI(b) ((my_termios->c_iflag | (b)) ? BITSSET : BITSNOTSET)
  707. applog(LOG_DEBUG, "TIOS: c_iflag: IGNBRK=%s BRKINT=%s IGNPAR=%s PARMRK=%s INPCK=%s ISTRIP=%s INLCR=%s IGNCR=%s ICRNL=%s IUCLC=%s IXON=%s IXANY=%s IOFF=%s IMAXBEL=%s IUTF8=%s",
  708. ISSETI(IGNBRK), ISSETI(BRKINT), ISSETI(IGNPAR), ISSETI(PARMRK),
  709. ISSETI(INPCK), ISSETI(ISTRIP), ISSETI(INLCR), ISSETI(IGNCR),
  710. ISSETI(ICRNL), ISSETI(IUCLC), ISSETI(IXON), ISSETI(IXANY),
  711. ISSETI(IXOFF), ISSETI(IMAXBEL), ISSETI(IUTF8));
  712. #define ISSETO(b) ((my_termios->c_oflag | (b)) ? BITSSET : BITSNOTSET)
  713. #define VALO(b) (my_termios->c_oflag | (b))
  714. applog(LOG_DEBUG, "TIOS: c_oflag: OPOST=%s OLCUC=%s ONLCR=%s OCRNL=%s ONOCR=%s ONLRET=%s OFILL=%s OFDEL=%s NLDLY=%d CRDLY=%d TABDLY=%d BSDLY=%d VTDLY=%d FFDLY=%d",
  715. ISSETO(OPOST), ISSETO(OLCUC), ISSETO(ONLCR), ISSETO(OCRNL),
  716. ISSETO(ONOCR), ISSETO(ONLRET), ISSETO(OFILL), ISSETO(OFDEL),
  717. VALO(NLDLY), VALO(CRDLY), VALO(TABDLY), VALO(BSDLY),
  718. VALO(VTDLY), VALO(FFDLY));
  719. #define ISSETC(b) ((my_termios->c_cflag | (b)) ? BITSSET : BITSNOTSET)
  720. #define VALC(b) (my_termios->c_cflag | (b))
  721. applog(LOG_DEBUG, "TIOS: c_cflag: CBAUDEX=%s CSIZE=%d CSTOPB=%s CREAD=%s PARENB=%s PARODD=%s HUPCL=%s CLOCAL=%s"
  722. #ifdef LOBLK
  723. " LOBLK=%s"
  724. #endif
  725. " CMSPAR=%s CRTSCTS=%s",
  726. ISSETC(CBAUDEX), VALC(CSIZE), ISSETC(CSTOPB), ISSETC(CREAD),
  727. ISSETC(PARENB), ISSETC(PARODD), ISSETC(HUPCL), ISSETC(CLOCAL),
  728. #ifdef LOBLK
  729. ISSETC(LOBLK),
  730. #endif
  731. ISSETC(CMSPAR), ISSETC(CRTSCTS));
  732. #define ISSETL(b) ((my_termios->c_lflag | (b)) ? BITSSET : BITSNOTSET)
  733. applog(LOG_DEBUG, "TIOS: c_lflag: ISIG=%s ICANON=%s XCASE=%s ECHO=%s ECHOE=%s ECHOK=%s ECHONL=%s ECHOCTL=%s ECHOPRT=%s ECHOKE=%s"
  734. #ifdef DEFECHO
  735. " DEFECHO=%s"
  736. #endif
  737. " FLUSHO=%s NOFLSH=%s TOSTOP=%s PENDIN=%s IEXTEN=%s",
  738. ISSETL(ISIG), ISSETL(ICANON), ISSETL(XCASE), ISSETL(ECHO),
  739. ISSETL(ECHOE), ISSETL(ECHOK), ISSETL(ECHONL), ISSETL(ECHOCTL),
  740. ISSETL(ECHOPRT), ISSETL(ECHOKE),
  741. #ifdef DEFECHO
  742. ISSETL(DEFECHO),
  743. #endif
  744. ISSETL(FLUSHO), ISSETL(NOFLSH), ISSETL(TOSTOP), ISSETL(PENDIN),
  745. ISSETL(IEXTEN));
  746. #define VALCC(b) (my_termios->c_cc[b])
  747. applog(LOG_DEBUG, "TIOS: c_cc: VINTR=0x%02x VQUIT=0x%02x VERASE=0x%02x VKILL=0x%02x VEOF=0x%02x VMIN=%u VEOL=0x%02x VTIME=%u VEOL2=0x%02x"
  748. #ifdef VSWTCH
  749. " VSWTCH=0x%02x"
  750. #endif
  751. " VSTART=0x%02x VSTOP=0x%02x VSUSP=0x%02x"
  752. #ifdef VDSUSP
  753. " VDSUSP=0x%02x"
  754. #endif
  755. " VLNEXT=0x%02x VWERASE=0x%02x VREPRINT=0x%02x VDISCARD=0x%02x"
  756. #ifdef VSTATUS
  757. " VSTATUS=0x%02x"
  758. #endif
  759. ,
  760. VALCC(VINTR), VALCC(VQUIT), VALCC(VERASE), VALCC(VKILL),
  761. VALCC(VEOF), VALCC(VMIN), VALCC(VEOL), VALCC(VTIME),
  762. VALCC(VEOL2),
  763. #ifdef VSWTCH
  764. VALCC(VSWTCH),
  765. #endif
  766. VALCC(VSTART), VALCC(VSTOP), VALCC(VSUSP),
  767. #ifdef VDSUSP
  768. VALCC(VDSUSP),
  769. #endif
  770. VALCC(VLNEXT), VALCC(VWERASE),
  771. VALCC(VREPRINT), VALCC(VDISCARD)
  772. #ifdef VSTATUS
  773. ,VALCC(VSTATUS)
  774. #endif
  775. );
  776. }
  777. #endif /* TERMIOS_DEBUG */
  778. speed_t tiospeed_t(int baud)
  779. {
  780. switch (baud) {
  781. #define IOSPEED(baud) \
  782. case baud: \
  783. return B ## baud; \
  784. // END
  785. #include "iospeeds_local.h"
  786. #undef IOSPEED
  787. default:
  788. return B0;
  789. }
  790. }
  791. #endif /* WIN32 */
  792. bool valid_baud(int baud)
  793. {
  794. switch (baud) {
  795. #define IOSPEED(baud) \
  796. case baud: \
  797. return true; \
  798. // END
  799. #include "iospeeds_local.h"
  800. #undef IOSPEED
  801. default:
  802. return false;
  803. }
  804. }
  805. /* NOTE: Linux only supports uint8_t (decisecond) timeouts; limiting it in
  806. * this interface buys us warnings when bad constants are passed in.
  807. */
  808. int serial_open(const char *devpath, unsigned long baud, uint8_t timeout, bool purge)
  809. {
  810. #ifdef WIN32
  811. HANDLE hSerial = CreateFile(devpath, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
  812. if (unlikely(hSerial == INVALID_HANDLE_VALUE))
  813. {
  814. DWORD e = GetLastError();
  815. switch (e) {
  816. case ERROR_ACCESS_DENIED:
  817. applog(LOG_ERR, "Do not have user privileges required to open %s", devpath);
  818. break;
  819. case ERROR_SHARING_VIOLATION:
  820. applog(LOG_ERR, "%s is already in use by another process", devpath);
  821. break;
  822. default:
  823. applog(LOG_DEBUG, "Open %s failed, GetLastError:%u", devpath, (unsigned)e);
  824. break;
  825. }
  826. return -1;
  827. }
  828. if (baud)
  829. {
  830. COMMCONFIG comCfg = {0};
  831. comCfg.dwSize = sizeof(COMMCONFIG);
  832. comCfg.wVersion = 1;
  833. comCfg.dcb.DCBlength = sizeof(DCB);
  834. comCfg.dcb.BaudRate = baud;
  835. comCfg.dcb.fBinary = 1;
  836. comCfg.dcb.fDtrControl = DTR_CONTROL_ENABLE;
  837. comCfg.dcb.fRtsControl = RTS_CONTROL_ENABLE;
  838. comCfg.dcb.ByteSize = 8;
  839. SetCommConfig(hSerial, &comCfg, sizeof(comCfg));
  840. }
  841. // Code must specify a valid timeout value (0 means don't timeout)
  842. const DWORD ctoms = ((DWORD)timeout * 100);
  843. COMMTIMEOUTS cto = {ctoms, 0, ctoms, 0, ctoms};
  844. SetCommTimeouts(hSerial, &cto);
  845. if (purge) {
  846. PurgeComm(hSerial, PURGE_RXABORT);
  847. PurgeComm(hSerial, PURGE_TXABORT);
  848. PurgeComm(hSerial, PURGE_RXCLEAR);
  849. PurgeComm(hSerial, PURGE_TXCLEAR);
  850. }
  851. return _open_osfhandle((intptr_t)hSerial, 0);
  852. #else
  853. int fdDev = open(devpath, O_RDWR | O_CLOEXEC | O_NOCTTY);
  854. if (unlikely(fdDev == -1))
  855. {
  856. if (errno == EACCES)
  857. applog(LOG_ERR, "Do not have user privileges required to open %s", devpath);
  858. else
  859. applog(LOG_DEBUG, "Open %s failed: %s", devpath, bfg_strerror(errno, BST_ERRNO));
  860. return -1;
  861. }
  862. #if defined(LOCK_EX) && defined(LOCK_NB)
  863. if (likely(!flock(fdDev, LOCK_EX | LOCK_NB)))
  864. applog(LOG_DEBUG, "Acquired exclusive advisory lock on %s", devpath);
  865. else
  866. if (errno == EWOULDBLOCK)
  867. {
  868. applog(LOG_ERR, "%s is already in use by another process", devpath);
  869. close(fdDev);
  870. return -1;
  871. }
  872. else
  873. applog(LOG_WARNING, "Failed to acquire exclusive lock on %s: %s (ignoring)", devpath, bfg_strerror(errno, BST_ERRNO));
  874. #endif
  875. struct termios my_termios;
  876. tcgetattr(fdDev, &my_termios);
  877. #ifdef TERMIOS_DEBUG
  878. termios_debug(devpath, &my_termios, "before");
  879. #endif
  880. if (baud)
  881. {
  882. speed_t speed = tiospeed_t(baud);
  883. if (speed == B0)
  884. applog(LOG_WARNING, "Unrecognized baud rate: %lu", baud);
  885. else
  886. {
  887. cfsetispeed(&my_termios, speed);
  888. cfsetospeed(&my_termios, speed);
  889. }
  890. }
  891. my_termios.c_cflag &= ~(CSIZE | PARENB);
  892. my_termios.c_cflag |= CS8;
  893. my_termios.c_cflag |= CREAD;
  894. #ifdef USE_AVALON
  895. // my_termios.c_cflag |= CRTSCTS;
  896. #endif
  897. my_termios.c_cflag |= CLOCAL;
  898. my_termios.c_iflag &= ~(IGNBRK | BRKINT | PARMRK |
  899. ISTRIP | INLCR | IGNCR | ICRNL | IXON);
  900. my_termios.c_oflag &= ~OPOST;
  901. my_termios.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
  902. // Code must specify a valid timeout value (0 means don't timeout)
  903. my_termios.c_cc[VTIME] = (cc_t)timeout;
  904. my_termios.c_cc[VMIN] = 0;
  905. #ifdef TERMIOS_DEBUG
  906. termios_debug(devpath, &my_termios, "settings");
  907. #endif
  908. tcsetattr(fdDev, TCSANOW, &my_termios);
  909. #ifdef TERMIOS_DEBUG
  910. tcgetattr(fdDev, &my_termios);
  911. termios_debug(devpath, &my_termios, "after");
  912. #endif
  913. if (purge)
  914. tcflush(fdDev, TCIOFLUSH);
  915. return fdDev;
  916. #endif
  917. }
  918. int serial_close(const int fd)
  919. {
  920. #if defined(LOCK_EX) && defined(LOCK_NB) && defined(LOCK_UN)
  921. flock(fd, LOCK_UN);
  922. #endif
  923. return close(fd);
  924. }
  925. ssize_t _serial_read(int fd, char *buf, size_t bufsiz, char *eol)
  926. {
  927. ssize_t len, tlen = 0;
  928. while (bufsiz) {
  929. len = read(fd, buf, eol ? 1 : bufsiz);
  930. if (len < 1)
  931. break;
  932. tlen += len;
  933. if (eol && *eol == buf[0])
  934. break;
  935. buf += len;
  936. bufsiz -= len;
  937. }
  938. return tlen;
  939. }
  940. #ifndef WIN32
  941. int get_serial_cts(int fd)
  942. {
  943. int flags;
  944. if (!fd)
  945. return -1;
  946. ioctl(fd, TIOCMGET, &flags);
  947. return (flags & TIOCM_CTS) ? 1 : 0;
  948. }
  949. int set_serial_rts(int fd, int rts)
  950. {
  951. int flags;
  952. if (!fd)
  953. return -1;
  954. ioctl(fd, TIOCMGET, &flags);
  955. if (rts)
  956. flags |= TIOCM_RTS;
  957. else
  958. flags &= ~TIOCM_RTS;
  959. ioctl(fd, TIOCMSET, &flags);
  960. return flags & TIOCM_CTS;
  961. }
  962. #else
  963. int get_serial_cts(const int fd)
  964. {
  965. if (!fd)
  966. return -1;
  967. const HANDLE fh = (HANDLE)_get_osfhandle(fd);
  968. if (!fh)
  969. return -1;
  970. DWORD flags;
  971. if (!GetCommModemStatus(fh, &flags))
  972. return -1;
  973. return (flags & MS_CTS_ON) ? 1 : 0;
  974. }
  975. #endif // ! WIN32
  976. struct lowlevel_driver lowl_vcom = {
  977. .dname = "vcom",
  978. .devinfo_scan = vcom_devinfo_scan,
  979. };