lowl-vcom.c 31 KB

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