lowl-vcom.c 36 KB

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