lowl-vcom.c 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217
  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. 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. bfg_probe_result_flags = BPR_WRONG_DEVTYPE;
  592. return false;
  593. }
  594. detectone_meta_info = (struct detectone_meta_info_t){
  595. .manufacturer = info->manufacturer,
  596. .product = info->product,
  597. .serial = info->serial,
  598. };
  599. const bool rv = detectone(info->path);
  600. clear_detectone_meta_info();
  601. return rv;
  602. }
  603. bool _serial_autodetect_found_cb(struct lowlevel_device_info * const devinfo, void *userp)
  604. {
  605. detectone_func_t detectone = userp;
  606. if (bfg_claim_any(NULL, devinfo->path, devinfo->devid))
  607. {
  608. applog(LOG_DEBUG, "%s (%s) is already claimed, skipping probe", devinfo->path, devinfo->devid);
  609. return false;
  610. }
  611. if (devinfo->lowl != &lowl_vcom)
  612. {
  613. #ifdef HAVE_LIBUSB
  614. if (devinfo->lowl == &lowl_usb)
  615. {
  616. if (lowl_usb_attach_kernel_driver(devinfo))
  617. bfg_need_detect_rescan = true;
  618. }
  619. else
  620. #endif
  621. applog(LOG_WARNING, "Non-VCOM %s (%s) matched", devinfo->path, devinfo->devid);
  622. return false;
  623. }
  624. detectone_meta_info = (struct detectone_meta_info_t){
  625. .manufacturer = devinfo->manufacturer,
  626. .product = devinfo->product,
  627. .serial = devinfo->serial,
  628. };
  629. const bool rv = detectone(devinfo->path);
  630. clear_detectone_meta_info();
  631. return rv;
  632. }
  633. int _serial_autodetect(detectone_func_t detectone, ...)
  634. {
  635. va_list needles;
  636. char *needles_array[0x10];
  637. int needlecount = 0;
  638. va_start(needles, detectone);
  639. while ( (needles_array[needlecount++] = va_arg(needles, void *)) )
  640. {}
  641. va_end(needles);
  642. return _lowlevel_detect(_serial_autodetect_found_cb, NULL, (const char **)needles_array, detectone);
  643. }
  644. static
  645. struct lowlevel_device_info *vcom_devinfo_scan()
  646. {
  647. struct lowlevel_device_info *devinfo_hash = NULL;
  648. struct lowlevel_device_info *devinfo_list = NULL;
  649. struct lowlevel_device_info *devinfo, *tmp;
  650. // All 3 USB Strings available:
  651. #ifndef WIN32
  652. _vcom_devinfo_scan_sysfs(&devinfo_hash);
  653. #endif
  654. #ifdef HAVE_WIN_DDKUSB
  655. _vcom_devinfo_scan_windows(&devinfo_hash);
  656. #endif
  657. #ifdef HAVE_LIBUDEV
  658. _vcom_devinfo_scan_udev(&devinfo_hash);
  659. #endif
  660. // Missing Manufacturer:
  661. #ifdef WIN32
  662. _vcom_devinfo_scan_ftdi(&devinfo_hash);
  663. #endif
  664. // All blobbed together:
  665. #ifndef WIN32
  666. _vcom_devinfo_scan_devserial(&devinfo_hash);
  667. #endif
  668. // No info:
  669. #ifdef WIN32
  670. _vcom_devinfo_scan_querydosdevice(&devinfo_hash);
  671. #else
  672. _vcom_devinfo_scan_lsdev(&devinfo_hash);
  673. #endif
  674. _vcom_devinfo_scan_user(&devinfo_hash);
  675. // Convert hash to simple list
  676. HASH_ITER(hh, devinfo_hash, devinfo, tmp)
  677. {
  678. LL_PREPEND(devinfo_list, devinfo);
  679. }
  680. HASH_CLEAR(hh, devinfo_hash);
  681. return devinfo_list;
  682. }
  683. struct device_drv *bfg_claim_serial(struct device_drv * const api, const bool verbose, const char * const devpath)
  684. {
  685. char * const devs = _vcom_unique_id(devpath);
  686. if (!devs)
  687. return false;
  688. struct device_drv * const rv = bfg_claim_any(api, (verbose ? devpath : NULL), devs);
  689. free(devs);
  690. return rv;
  691. }
  692. // This code is purely for debugging but is very useful for that
  693. // It also took quite a bit of effort so I left it in
  694. // #define TERMIOS_DEBUG 1
  695. // Here to include it at compile time
  696. // It's off by default
  697. #ifndef WIN32
  698. #ifdef TERMIOS_DEBUG
  699. #define BITSSET "Y"
  700. #define BITSNOTSET "N"
  701. int tiospeed(speed_t speed)
  702. {
  703. switch (speed) {
  704. #define IOSPEED(baud) \
  705. case B ## baud: \
  706. return baud; \
  707. // END
  708. #include "iospeeds_local.h"
  709. #undef IOSPEED
  710. default:
  711. return -1;
  712. }
  713. }
  714. void termios_debug(const char *devpath, struct termios *my_termios, const char *msg)
  715. {
  716. applog(LOG_DEBUG, "TIOS: Open %s attributes %s: ispeed=%d ospeed=%d",
  717. devpath, msg, tiospeed(cfgetispeed(my_termios)), tiospeed(cfgetispeed(my_termios)));
  718. #define ISSETI(b) ((my_termios->c_iflag | (b)) ? BITSSET : BITSNOTSET)
  719. 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",
  720. ISSETI(IGNBRK), ISSETI(BRKINT), ISSETI(IGNPAR), ISSETI(PARMRK),
  721. ISSETI(INPCK), ISSETI(ISTRIP), ISSETI(INLCR), ISSETI(IGNCR),
  722. ISSETI(ICRNL), ISSETI(IUCLC), ISSETI(IXON), ISSETI(IXANY),
  723. ISSETI(IXOFF), ISSETI(IMAXBEL), ISSETI(IUTF8));
  724. #define ISSETO(b) ((my_termios->c_oflag | (b)) ? BITSSET : BITSNOTSET)
  725. #define VALO(b) (my_termios->c_oflag | (b))
  726. 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",
  727. ISSETO(OPOST), ISSETO(OLCUC), ISSETO(ONLCR), ISSETO(OCRNL),
  728. ISSETO(ONOCR), ISSETO(ONLRET), ISSETO(OFILL), ISSETO(OFDEL),
  729. VALO(NLDLY), VALO(CRDLY), VALO(TABDLY), VALO(BSDLY),
  730. VALO(VTDLY), VALO(FFDLY));
  731. #define ISSETC(b) ((my_termios->c_cflag | (b)) ? BITSSET : BITSNOTSET)
  732. #define VALC(b) (my_termios->c_cflag | (b))
  733. applog(LOG_DEBUG, "TIOS: c_cflag: CBAUDEX=%s CSIZE=%d CSTOPB=%s CREAD=%s PARENB=%s PARODD=%s HUPCL=%s CLOCAL=%s"
  734. #ifdef LOBLK
  735. " LOBLK=%s"
  736. #endif
  737. " CMSPAR=%s CRTSCTS=%s",
  738. ISSETC(CBAUDEX), VALC(CSIZE), ISSETC(CSTOPB), ISSETC(CREAD),
  739. ISSETC(PARENB), ISSETC(PARODD), ISSETC(HUPCL), ISSETC(CLOCAL),
  740. #ifdef LOBLK
  741. ISSETC(LOBLK),
  742. #endif
  743. ISSETC(CMSPAR), ISSETC(CRTSCTS));
  744. #define ISSETL(b) ((my_termios->c_lflag | (b)) ? BITSSET : BITSNOTSET)
  745. 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"
  746. #ifdef DEFECHO
  747. " DEFECHO=%s"
  748. #endif
  749. " FLUSHO=%s NOFLSH=%s TOSTOP=%s PENDIN=%s IEXTEN=%s",
  750. ISSETL(ISIG), ISSETL(ICANON), ISSETL(XCASE), ISSETL(ECHO),
  751. ISSETL(ECHOE), ISSETL(ECHOK), ISSETL(ECHONL), ISSETL(ECHOCTL),
  752. ISSETL(ECHOPRT), ISSETL(ECHOKE),
  753. #ifdef DEFECHO
  754. ISSETL(DEFECHO),
  755. #endif
  756. ISSETL(FLUSHO), ISSETL(NOFLSH), ISSETL(TOSTOP), ISSETL(PENDIN),
  757. ISSETL(IEXTEN));
  758. #define VALCC(b) (my_termios->c_cc[b])
  759. 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"
  760. #ifdef VSWTCH
  761. " VSWTCH=0x%02x"
  762. #endif
  763. " VSTART=0x%02x VSTOP=0x%02x VSUSP=0x%02x"
  764. #ifdef VDSUSP
  765. " VDSUSP=0x%02x"
  766. #endif
  767. " VLNEXT=0x%02x VWERASE=0x%02x VREPRINT=0x%02x VDISCARD=0x%02x"
  768. #ifdef VSTATUS
  769. " VSTATUS=0x%02x"
  770. #endif
  771. ,
  772. VALCC(VINTR), VALCC(VQUIT), VALCC(VERASE), VALCC(VKILL),
  773. VALCC(VEOF), VALCC(VMIN), VALCC(VEOL), VALCC(VTIME),
  774. VALCC(VEOL2),
  775. #ifdef VSWTCH
  776. VALCC(VSWTCH),
  777. #endif
  778. VALCC(VSTART), VALCC(VSTOP), VALCC(VSUSP),
  779. #ifdef VDSUSP
  780. VALCC(VDSUSP),
  781. #endif
  782. VALCC(VLNEXT), VALCC(VWERASE),
  783. VALCC(VREPRINT), VALCC(VDISCARD)
  784. #ifdef VSTATUS
  785. ,VALCC(VSTATUS)
  786. #endif
  787. );
  788. }
  789. #endif /* TERMIOS_DEBUG */
  790. speed_t tiospeed_t(int baud)
  791. {
  792. switch (baud) {
  793. #define IOSPEED(baud) \
  794. case baud: \
  795. return B ## baud; \
  796. // END
  797. #include "iospeeds_local.h"
  798. #undef IOSPEED
  799. default:
  800. return B0;
  801. }
  802. }
  803. #endif /* WIN32 */
  804. bool valid_baud(int baud)
  805. {
  806. switch (baud) {
  807. #define IOSPEED(baud) \
  808. case baud: \
  809. return true; \
  810. // END
  811. #include "iospeeds_local.h"
  812. #undef IOSPEED
  813. default:
  814. return false;
  815. }
  816. }
  817. bool vcom_set_timeout(const int fdDev, const uint8_t timeout)
  818. {
  819. #ifdef WIN32
  820. const HANDLE hSerial = (HANDLE)_get_osfhandle(fdDev);
  821. // Code must specify a valid timeout value (0 means don't timeout)
  822. const DWORD ctoms = ((DWORD)timeout * 100);
  823. COMMTIMEOUTS cto = {ctoms, 0, ctoms, 0, ctoms};
  824. return (SetCommTimeouts(hSerial, &cto) != 0);
  825. #else
  826. struct termios my_termios;
  827. tcgetattr(fdDev, &my_termios);
  828. my_termios.c_cc[VTIME] = (cc_t)timeout;
  829. return (tcsetattr(fdDev, TCSANOW, &my_termios) == 0);
  830. #endif
  831. }
  832. /* NOTE: Linux only supports uint8_t (decisecond) timeouts; limiting it in
  833. * this interface buys us warnings when bad constants are passed in.
  834. */
  835. int serial_open(const char *devpath, unsigned long baud, uint8_t timeout, bool purge)
  836. {
  837. #ifdef WIN32
  838. HANDLE hSerial = CreateFile(devpath, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
  839. if (unlikely(hSerial == INVALID_HANDLE_VALUE))
  840. {
  841. DWORD e = GetLastError();
  842. switch (e) {
  843. case ERROR_ACCESS_DENIED:
  844. applog(LOG_ERR, "Do not have user privileges required to open %s", devpath);
  845. break;
  846. case ERROR_SHARING_VIOLATION:
  847. applog(LOG_ERR, "%s is already in use by another process", devpath);
  848. break;
  849. default:
  850. applog(LOG_DEBUG, "Open %s failed, GetLastError:%u", devpath, (unsigned)e);
  851. break;
  852. }
  853. return -1;
  854. }
  855. if (baud)
  856. {
  857. COMMCONFIG comCfg = {0};
  858. comCfg.dwSize = sizeof(COMMCONFIG);
  859. comCfg.wVersion = 1;
  860. comCfg.dcb.DCBlength = sizeof(DCB);
  861. comCfg.dcb.BaudRate = baud;
  862. comCfg.dcb.fBinary = 1;
  863. comCfg.dcb.fDtrControl = DTR_CONTROL_ENABLE;
  864. comCfg.dcb.fRtsControl = RTS_CONTROL_ENABLE;
  865. comCfg.dcb.ByteSize = 8;
  866. SetCommConfig(hSerial, &comCfg, sizeof(comCfg));
  867. }
  868. // Code must specify a valid timeout value (0 means don't timeout)
  869. const DWORD ctoms = ((DWORD)timeout * 100);
  870. COMMTIMEOUTS cto = {ctoms, 0, ctoms, 0, ctoms};
  871. SetCommTimeouts(hSerial, &cto);
  872. if (purge) {
  873. PurgeComm(hSerial, PURGE_RXABORT);
  874. PurgeComm(hSerial, PURGE_TXABORT);
  875. PurgeComm(hSerial, PURGE_RXCLEAR);
  876. PurgeComm(hSerial, PURGE_TXCLEAR);
  877. }
  878. return _open_osfhandle((intptr_t)hSerial, 0);
  879. #else
  880. int fdDev = open(devpath, O_RDWR | O_CLOEXEC | O_NOCTTY);
  881. if (unlikely(fdDev == -1))
  882. {
  883. if (errno == EACCES)
  884. applog(LOG_ERR, "Do not have user privileges required to open %s", devpath);
  885. else
  886. applog(LOG_DEBUG, "Open %s failed: %s", devpath, bfg_strerror(errno, BST_ERRNO));
  887. return -1;
  888. }
  889. #if defined(LOCK_EX) && defined(LOCK_NB)
  890. if (likely(!flock(fdDev, LOCK_EX | LOCK_NB)))
  891. applog(LOG_DEBUG, "Acquired exclusive advisory lock on %s", devpath);
  892. else
  893. if (errno == EWOULDBLOCK)
  894. {
  895. applog(LOG_ERR, "%s is already in use by another process", devpath);
  896. close(fdDev);
  897. return -1;
  898. }
  899. else
  900. applog(LOG_WARNING, "Failed to acquire exclusive lock on %s: %s (ignoring)", devpath, bfg_strerror(errno, BST_ERRNO));
  901. #endif
  902. struct termios my_termios;
  903. tcgetattr(fdDev, &my_termios);
  904. #ifdef TERMIOS_DEBUG
  905. termios_debug(devpath, &my_termios, "before");
  906. #endif
  907. if (baud)
  908. {
  909. speed_t speed = tiospeed_t(baud);
  910. if (speed == B0)
  911. applog(LOG_WARNING, "Unrecognized baud rate: %lu", baud);
  912. else
  913. {
  914. cfsetispeed(&my_termios, speed);
  915. cfsetospeed(&my_termios, speed);
  916. }
  917. }
  918. my_termios.c_cflag &= ~(CSIZE | PARENB);
  919. my_termios.c_cflag |= CS8;
  920. my_termios.c_cflag |= CREAD;
  921. #ifdef USE_AVALON
  922. // my_termios.c_cflag |= CRTSCTS;
  923. #endif
  924. my_termios.c_cflag |= CLOCAL;
  925. my_termios.c_iflag &= ~(IGNBRK | BRKINT | PARMRK |
  926. ISTRIP | INLCR | IGNCR | ICRNL | IXON);
  927. my_termios.c_oflag &= ~OPOST;
  928. my_termios.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
  929. // Code must specify a valid timeout value (0 means don't timeout)
  930. my_termios.c_cc[VTIME] = (cc_t)timeout;
  931. my_termios.c_cc[VMIN] = 0;
  932. #ifdef TERMIOS_DEBUG
  933. termios_debug(devpath, &my_termios, "settings");
  934. #endif
  935. tcsetattr(fdDev, TCSANOW, &my_termios);
  936. #ifdef TERMIOS_DEBUG
  937. tcgetattr(fdDev, &my_termios);
  938. termios_debug(devpath, &my_termios, "after");
  939. #endif
  940. if (purge)
  941. tcflush(fdDev, TCIOFLUSH);
  942. return fdDev;
  943. #endif
  944. }
  945. int serial_close(const int fd)
  946. {
  947. #if defined(LOCK_EX) && defined(LOCK_NB) && defined(LOCK_UN)
  948. flock(fd, LOCK_UN);
  949. #endif
  950. return close(fd);
  951. }
  952. ssize_t _serial_read(int fd, char *buf, size_t bufsiz, char *eol)
  953. {
  954. ssize_t len, tlen = 0;
  955. while (bufsiz) {
  956. len = read(fd, buf, eol ? 1 : bufsiz);
  957. if (len < 1)
  958. break;
  959. tlen += len;
  960. if (eol && *eol == buf[0])
  961. break;
  962. buf += len;
  963. bufsiz -= len;
  964. }
  965. return tlen;
  966. }
  967. #ifndef WIN32
  968. enum bfg_gpio_value get_serial_cts(int fd)
  969. {
  970. int flags;
  971. if (fd == -1)
  972. return BGV_ERROR;
  973. ioctl(fd, TIOCMGET, &flags);
  974. return (flags & TIOCM_CTS) ? BGV_HIGH : BGV_LOW;
  975. }
  976. static
  977. enum bfg_gpio_value _set_serial_cmflag(int fd, int flag, bool val)
  978. {
  979. int flags;
  980. if (fd == -1)
  981. return BGV_ERROR;
  982. ioctl(fd, TIOCMGET, &flags);
  983. if (val)
  984. flags |= flag;
  985. else
  986. flags &= ~flag;
  987. ioctl(fd, TIOCMSET, &flags);
  988. return val ? BGV_HIGH : BGV_LOW;
  989. }
  990. enum bfg_gpio_value set_serial_dtr(int fd, enum bfg_gpio_value dtr)
  991. {
  992. return _set_serial_cmflag(fd, TIOCM_DTR, dtr);
  993. }
  994. enum bfg_gpio_value set_serial_rts(int fd, enum bfg_gpio_value rts)
  995. {
  996. return _set_serial_cmflag(fd, TIOCM_RTS, rts);
  997. }
  998. #else
  999. enum bfg_gpio_value get_serial_cts(const int fd)
  1000. {
  1001. if (fd == -1)
  1002. return BGV_ERROR;
  1003. const HANDLE fh = (HANDLE)_get_osfhandle(fd);
  1004. if (fh == INVALID_HANDLE_VALUE)
  1005. return BGV_ERROR;
  1006. DWORD flags;
  1007. if (!GetCommModemStatus(fh, &flags))
  1008. return BGV_ERROR;
  1009. return (flags & MS_CTS_ON) ? BGV_HIGH : BGV_LOW;
  1010. }
  1011. static
  1012. enum bfg_gpio_value _set_serial_cmflag(int fd, void (*setfunc)(DCB*, bool), bool val, const char * const fname)
  1013. {
  1014. if (fd == -1)
  1015. return BGV_ERROR;
  1016. const HANDLE fh = (HANDLE)_get_osfhandle(fd);
  1017. if (fh == INVALID_HANDLE_VALUE)
  1018. return BGV_ERROR;
  1019. DCB dcb;
  1020. if (!GetCommState(fh, &dcb))
  1021. applogr(BGV_ERROR, LOG_DEBUG, "Failed to %s"IN_FMT_FFL": %s",
  1022. "GetCommState", __FILE__, fname, __LINE__,
  1023. bfg_strerror(GetLastError(), BST_SYSTEM));
  1024. setfunc(&dcb, val);
  1025. if (!SetCommState(fh, &dcb))
  1026. applogr(BGV_ERROR, LOG_DEBUG, "Failed to %s"IN_FMT_FFL": %s",
  1027. "GetCommState", __FILE__, fname, __LINE__,
  1028. bfg_strerror(GetLastError(), BST_SYSTEM));
  1029. return val ? BGV_HIGH : BGV_LOW;
  1030. }
  1031. #define _set_serial_cmflag2(name, field, trueval, falseval) \
  1032. static \
  1033. void _set_serial_cmflag_ ## name(DCB *dcb, bool val) \
  1034. { \
  1035. dcb->field = val ? (trueval) : (falseval); \
  1036. } \
  1037. \
  1038. enum bfg_gpio_value set_serial_ ## name(int fd, enum bfg_gpio_value val) \
  1039. { \
  1040. return _set_serial_cmflag(fd, _set_serial_cmflag_ ## name, val, "set_serial_" #name); \
  1041. } \
  1042. // END _set_serial_cmflag2
  1043. _set_serial_cmflag2(dtr, fDtrControl, DTR_CONTROL_ENABLE, DTR_CONTROL_DISABLE)
  1044. _set_serial_cmflag2(rts, fRtsControl, RTS_CONTROL_ENABLE, RTS_CONTROL_DISABLE)
  1045. #endif // ! WIN32
  1046. struct lowlevel_driver lowl_vcom = {
  1047. .dname = "vcom",
  1048. .devinfo_scan = vcom_devinfo_scan,
  1049. };