ethsock.c 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472
  1. /**
  2. * nmrpflash - Netgear Unbrick Utility
  3. * Copyright (C) 2016 Joseph Lehner <joseph.c.lehner@gmail.com>
  4. *
  5. * nmrpflash is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * nmrpflash is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with nmrpflash. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. #include <sys/types.h>
  20. #include <stdbool.h>
  21. #include <stdarg.h>
  22. #include <string.h>
  23. #include <stdlib.h>
  24. #include <stdio.h>
  25. #include <fcntl.h>
  26. #include "nmrpd.h"
  27. #if defined(NMRPFLASH_WINDOWS)
  28. # include <iphlpapi.h>
  29. # define NMRPFLASH_PRETTY_FMT "%ls"
  30. # ifndef ERROR_NDIS_MEDIA_DISCONNECTED
  31. # define ERROR_NDIS_MEDIA_DISCONNECTED 0x8034001f
  32. # endif
  33. # define WPCAP
  34. # include <pcap.h>
  35. #else
  36. # include <sys/ioctl.h>
  37. # include <ifaddrs.h>
  38. # include <unistd.h>
  39. # include <net/if.h>
  40. # include <pcap.h>
  41. # if defined(NMRPFLASH_LINUX)
  42. # define NMRPFLASH_AF_PACKET AF_PACKET
  43. # include <linux/if_packet.h>
  44. # include <netlink/route/addr.h>
  45. # include <netlink/route/neighbour.h>
  46. # else
  47. # define NMRPFLASH_AF_PACKET AF_LINK
  48. # include <net/if_types.h>
  49. # include <net/if_media.h>
  50. # endif
  51. #endif
  52. #ifdef NMRPFLASH_OSX
  53. #include <CoreFoundation/CoreFoundation.h>
  54. #define NMRPFLASH_PRETTY_FMT "%s"
  55. #endif
  56. struct ethsock
  57. {
  58. const char *intf;
  59. pcap_t *pcap;
  60. #ifndef NMRPFLASH_WINDOWS
  61. int fd;
  62. #ifdef NMRPFLASH_LINUX
  63. bool stp;
  64. // managed by NetworkManager
  65. bool nm_managed;
  66. #endif
  67. #else
  68. HANDLE handle;
  69. DWORD index;
  70. #endif
  71. unsigned timeout;
  72. uint8_t hwaddr[6];
  73. };
  74. struct ethsock_arp_undo
  75. {
  76. uint32_t ipaddr;
  77. uint8_t hwaddr[6];
  78. };
  79. struct ethsock_ip_undo
  80. {
  81. uint32_t ip[2];
  82. };
  83. static int x_pcap_findalldevs(pcap_if_t **devs)
  84. {
  85. char errbuf[PCAP_ERRBUF_SIZE];
  86. if (pcap_findalldevs(devs, errbuf) != 0) {
  87. fprintf(stderr, "%s.\n", errbuf);
  88. return -1;
  89. }
  90. return 0;
  91. }
  92. static bool intf_get_pcap_flags(const char *intf, bpf_u_int32 *flags)
  93. {
  94. pcap_if_t *devs, *dev;
  95. if (x_pcap_findalldevs(&devs) == 0) {
  96. for (dev = devs; dev; dev = dev->next) {
  97. if (!strcmp(intf, dev->name)) {
  98. *flags = dev->flags;
  99. break;
  100. }
  101. }
  102. pcap_freealldevs(devs);
  103. return dev != NULL;
  104. }
  105. return false;
  106. }
  107. #ifndef NMRPFLASH_WINDOWS
  108. static int systemf(const char *fmt, ...)
  109. {
  110. char cmd[1024];
  111. int ret;
  112. va_list va;
  113. va_start(va, fmt);
  114. ret = vsnprintf(cmd, sizeof(cmd) - 1, fmt, va);
  115. if (ret >= sizeof(cmd) - 1) {
  116. return -1;
  117. }
  118. ret = system(cmd);
  119. va_end(va);
  120. return ret;
  121. }
  122. #endif
  123. #ifndef NMRPFLASH_WINDOWS
  124. static inline bool sockaddr_get_hwaddr(struct sockaddr *sa, uint8_t *hwaddr)
  125. {
  126. void *src;
  127. if (!sa || sa->sa_family != NMRPFLASH_AF_PACKET) {
  128. return false;
  129. }
  130. #ifndef NMRPFLASH_LINUX
  131. if (((struct sockaddr_dl*)sa)->sdl_type != IFT_ETHER) {
  132. return false;
  133. }
  134. src = LLADDR((struct sockaddr_dl*)sa);
  135. #else
  136. src = ((struct sockaddr_ll*)sa)->sll_addr;
  137. #endif
  138. memcpy(hwaddr, src, 6);
  139. return true;
  140. }
  141. #ifdef NMRPFLASH_LINUX
  142. static int intf_sys_open(const char* intf, const char* file)
  143. {
  144. char name[256];
  145. snprintf(name, sizeof(name), "/sys/class/net/%s/%s", intf, file);
  146. return open(name, O_RDWR, 0644);
  147. }
  148. static bool intf_sys_read(const char* intf, const char* file, bool def)
  149. {
  150. char c;
  151. int fd;
  152. fd = intf_sys_open(intf, file);
  153. if (fd == -1) {
  154. return def;
  155. }
  156. c = 0;
  157. read(fd, &c, 1);
  158. close(fd);
  159. return c ? (c == '1') : def;
  160. }
  161. static bool intf_stp_enable(const char *intf, bool enabled)
  162. {
  163. int fd;
  164. ssize_t n;
  165. fd = intf_sys_open(intf, "bridge/stp_state");
  166. if (fd == -1) {
  167. return false;
  168. }
  169. n = write(fd, enabled ? "1\n" : "0\n", 2);
  170. close(fd);
  171. return n == 2;
  172. }
  173. static struct nl_addr *build_ip(uint32_t ip)
  174. {
  175. struct nl_addr *na = nl_addr_build(AF_INET, &ip, 4);
  176. if (!na) {
  177. xperror("nl_addr_build");
  178. }
  179. return na;
  180. }
  181. static struct nl_sock *xnl_socket_route()
  182. {
  183. int err;
  184. struct nl_sock *sk = nl_socket_alloc();
  185. if (sk) {
  186. if (!(err = nl_connect(sk, NETLINK_ROUTE))) {
  187. return sk;
  188. }
  189. nl_socket_free(sk);
  190. nl_perror(err, "nl_connect");
  191. } else {
  192. xperror("nl_socket_alloc");
  193. }
  194. return NULL;
  195. }
  196. static bool intf_add_del_ip(const char *intf, uint32_t ipaddr, uint32_t ipmask, bool add)
  197. {
  198. struct rtnl_addr *ra = NULL;
  199. struct nl_sock *sk = NULL;
  200. struct nl_addr *laddr = NULL;
  201. struct nl_addr *bcast = NULL;
  202. int err = 1;
  203. if (!(sk = xnl_socket_route())) {
  204. return false;
  205. }
  206. if (!(laddr = build_ip(ipaddr))) {
  207. goto out;
  208. }
  209. nl_addr_set_prefixlen(laddr, bitcount(ipmask));
  210. if (!(bcast = build_ip((ipaddr & ipmask) | ~ipmask))) {
  211. goto out;
  212. }
  213. if (!(ra = rtnl_addr_alloc())) {
  214. xperror("rtnl_addr_alloc");
  215. goto out;
  216. }
  217. rtnl_addr_set_ifindex(ra, if_nametoindex(intf));
  218. rtnl_addr_set_local(ra, laddr);
  219. rtnl_addr_set_broadcast(ra, bcast);
  220. if ((err = (add ? rtnl_addr_add(sk, ra, 0) : rtnl_addr_delete(sk, ra, 0))) < 0) {
  221. if (add && err == -NLE_EXIST) {
  222. err = 0;
  223. } else if (add || verbosity > 1) {
  224. nl_perror(err, add ? "rtnl_addr_add" : "rtnl_addr_delete");
  225. }
  226. }
  227. out:
  228. rtnl_addr_put(ra);
  229. nl_addr_put(laddr);
  230. nl_addr_put(bcast);
  231. nl_socket_free(sk);
  232. return !err;
  233. }
  234. static bool intf_add_del_arp(const char *intf, uint32_t ipaddr, uint8_t *hwaddr, bool add)
  235. {
  236. #if 0
  237. struct arpreq arp;
  238. memset(&arp, 0, sizeof(arp));
  239. arp.arp_ha.sa_family = ARPHRD_ETHER;
  240. memcpy(&arp.arp_ha.sa_data, hwaddr, 6);
  241. arp.arp_flags = ATF_PERM | ATF_COM;
  242. struct sockaddr_in *in = (struct sockaddr_in*)&req.arp_pa;
  243. in->sin_addr.s_addr = htonl(ipaddr);
  244. in->sin_family = AF_INET;
  245. int fd = socket(AF_INET, SOCK_DGRAM, 0);
  246. if (fd < 0) {
  247. perror("socket");
  248. return false;
  249. }
  250. bool ret = true;
  251. if (ioctl(fd, add ? SIOCSARP : SIOCDARP, &req) < 0) {
  252. perror(add ? "ioctl(SIOCSARP)" : "ioctl(SIOCDARP");
  253. ret = false;
  254. }
  255. close(fd);
  256. return ret;
  257. #else
  258. struct nl_sock *sk;
  259. struct rtnl_neigh *neigh;
  260. struct nl_addr *mac, *ip;
  261. int err = 1;
  262. sk = NULL;
  263. neigh = NULL;
  264. mac = ip = NULL;
  265. if (!(sk = xnl_socket_route())) {
  266. goto out;
  267. }
  268. if (!(neigh = rtnl_neigh_alloc())) {
  269. xperror("rtnl_neigh_alloc");
  270. goto out;
  271. }
  272. if (!(mac = nl_addr_build(AF_PACKET, hwaddr, 6))) {
  273. xperror("nl_addr_build");
  274. goto out;
  275. }
  276. if (!(ip = nl_addr_build(AF_INET, &ipaddr, 4))) {
  277. xperror("nl_addr_build");
  278. goto out;
  279. }
  280. rtnl_neigh_set_ifindex(neigh, if_nametoindex(intf));
  281. rtnl_neigh_set_dst(neigh, ip);
  282. err = rtnl_neigh_delete(sk, neigh, 0);
  283. if (add) {
  284. rtnl_neigh_set_lladdr(neigh, mac);
  285. rtnl_neigh_set_state(neigh, NUD_PERMANENT);
  286. err = rtnl_neigh_add(sk, neigh, NLM_F_CREATE);
  287. }
  288. if (err && add) {
  289. nl_perror(err, "rtnl_neigh_add");
  290. }
  291. out:
  292. nl_addr_put(ip);
  293. nl_addr_put(mac);
  294. rtnl_neigh_put(neigh);
  295. nl_socket_free(sk);
  296. return !err;
  297. #endif
  298. }
  299. #endif
  300. static bool intf_get_hwaddr_and_bridge(const char *intf, uint8_t *hwaddr, bool *bridge)
  301. {
  302. struct ifaddrs *ifas, *ifa;
  303. bool found;
  304. if (getifaddrs(&ifas) != 0) {
  305. xperror("getifaddrs");
  306. return false;
  307. }
  308. found = false;
  309. if (bridge) {
  310. *bridge = false;
  311. }
  312. for (ifa = ifas; ifa; ifa = ifa->ifa_next) {
  313. if (!strcmp(ifa->ifa_name, intf)) {
  314. if (sockaddr_get_hwaddr(ifa->ifa_addr, hwaddr)) {
  315. #ifdef NMRPFLASH_BSD
  316. if (bridge) {
  317. *bridge = ((struct if_data*) ifa->ifa_data)->ifi_type == IFT_BRIDGE;
  318. }
  319. #endif
  320. found = true;
  321. break;
  322. }
  323. }
  324. }
  325. freeifaddrs(ifas);
  326. return found;
  327. }
  328. #else
  329. void win_perror2(const char *msg, DWORD err)
  330. {
  331. char *buf = NULL;
  332. FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  333. FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  334. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  335. (LPTSTR)&buf, 0, NULL);
  336. if (buf) {
  337. /* FormatMessageA terminates buf with CRLF! */
  338. fprintf(stderr, "%s: %s", msg, buf);
  339. LocalFree(buf);
  340. } else {
  341. fprintf(stderr, "%s: error %d\n", msg, (int)err);
  342. }
  343. }
  344. static bool intf_get_if_row(NET_IFINDEX index, MIB_IF_ROW2* row)
  345. {
  346. DWORD err;
  347. memset(row, 0, sizeof(*row));
  348. row->InterfaceIndex = index;
  349. err = GetIfEntry2(row);
  350. if (err != NO_ERROR) {
  351. if (verbosity > 1) {
  352. win_perror2("GetIfEntry2", err);
  353. }
  354. return false;
  355. }
  356. return true;
  357. }
  358. static bool intf_get_hwaddr_and_index(const char *intf, uint8_t *hwaddr, DWORD *index)
  359. {
  360. PIP_ADAPTER_ADDRESSES adapters, adapter;
  361. ULONG ret, flags, bufLen;
  362. bool found = false;
  363. flags = GAA_FLAG_INCLUDE_ALL_INTERFACES;
  364. bufLen = 0;
  365. ret = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, NULL, &bufLen);
  366. if (ret != ERROR_BUFFER_OVERFLOW) {
  367. win_perror2("GetAdaptersAddresses", ret);
  368. return false;
  369. }
  370. bufLen *= 2;
  371. adapters = malloc(bufLen);
  372. if (!adapters) {
  373. xperror("malloc");
  374. return false;
  375. }
  376. ret = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, adapters, &bufLen);
  377. if (ret == NO_ERROR) {
  378. for (adapter = adapters; adapter; adapter = adapter->Next) {
  379. if (verbosity > 2) {
  380. printf(" %s: Type=%lu, Name=%ls\n", adapter->AdapterName, adapter->IfType, adapter->FriendlyName);
  381. }
  382. if (adapter->IfType != IF_TYPE_ETHERNET_CSMACD && adapter->IfType != IF_TYPE_IEEE80211) {
  383. continue;
  384. }
  385. /* Interface names from WinPcap are "\Device\NPF_{GUID}", while
  386. * AdapterName from GetAdaptersAddresses is just "{GUID}".*/
  387. if (strstr(intf, adapter->AdapterName)) {
  388. if (adapter->PhysicalAddressLength == 6) {
  389. memcpy(hwaddr, adapter->PhysicalAddress, 6);
  390. if (index) {
  391. *index = adapter->IfIndex;
  392. }
  393. found = true;
  394. break;
  395. }
  396. }
  397. }
  398. } else {
  399. win_perror2("GetAdaptersAddresses", ret);
  400. }
  401. free(adapters);
  402. return found;
  403. }
  404. static const char *intf_name_to_wpcap(const char *intf)
  405. {
  406. static char buf[128];
  407. if (intf[0] == '\\') {
  408. return intf;
  409. }
  410. do {
  411. NET_IFINDEX index;
  412. DWORD err;
  413. NET_LUID luid;
  414. GUID guid;
  415. if (sscanf(intf, "net%lu", &index) != 1) {
  416. index = if_nametoindex(intf);
  417. if (!index) {
  418. break;
  419. }
  420. }
  421. err = ConvertInterfaceIndexToLuid(index, &luid);
  422. if (err != NO_ERROR) {
  423. if (verbosity) {
  424. win_perror2("ConvertInterfaceIndexToLuid", err);
  425. }
  426. break;
  427. }
  428. err = ConvertInterfaceLuidToGuid(&luid, &guid);
  429. if (err != NO_ERROR) {
  430. if (verbosity) {
  431. win_perror2("ConvertInterfaceLuidToGuid", err);
  432. }
  433. break;
  434. }
  435. snprintf(buf, sizeof(buf),
  436. "\\Device\\NPF_{%08lX-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}",
  437. guid.Data1, guid.Data2, guid.Data3,
  438. guid.Data4[0], guid.Data4[1], guid.Data4[2],
  439. guid.Data4[3], guid.Data4[4], guid.Data4[5],
  440. guid.Data4[6], guid.Data4[7]);
  441. return buf;
  442. } while (false);
  443. fprintf(stderr, "Invalid interface name.\n");
  444. return NULL;
  445. }
  446. NET_IFINDEX intf_get_index(const char* intf)
  447. {
  448. const char* p;
  449. GUID guid;
  450. NET_LUID luid;
  451. DWORD err;
  452. NET_IFINDEX ret;
  453. int n;
  454. p = strstr(intf, "NPF_{");
  455. if (!p) {
  456. return 0;
  457. }
  458. sscanf(p + 5,
  459. "%08lX-%04hX-%04hX-%02hhX%02hhX-%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX%n",
  460. &guid.Data1, &guid.Data2, &guid.Data3,
  461. &guid.Data4[0], &guid.Data4[1], &guid.Data4[2],
  462. &guid.Data4[3], &guid.Data4[4], &guid.Data4[5],
  463. &guid.Data4[6], &guid.Data4[7], &n);
  464. if (n != 36) {
  465. return 0;
  466. }
  467. err = ConvertInterfaceGuidToLuid(&guid, &luid);
  468. if (err) {
  469. win_perror2("ConvertInterfaceGuidToLuid", err);
  470. return 0;
  471. }
  472. err = ConvertInterfaceLuidToIndex(&luid, &ret);
  473. if (err) {
  474. win_perror2("ConvertInterfaceLuidToIndex", err);
  475. return 0;
  476. }
  477. return ret;
  478. }
  479. #endif
  480. #ifdef NMRPFLASH_OSX
  481. void cf_perror(const char* function)
  482. {
  483. if (verbosity > 1) {
  484. fprintf(stderr, "Warning: %s failed\n", function);
  485. }
  486. }
  487. CFStringRef to_cfstring(const char* str)
  488. {
  489. CFStringRef ret = CFStringCreateWithFileSystemRepresentation(
  490. kCFAllocatorDefault, str);
  491. if (!ret) {
  492. cf_perror("CFStringCreateWithFileSystemRepresentation");
  493. }
  494. return ret;
  495. }
  496. CFPropertyListRef plist_open(const char* filename)
  497. {
  498. CFURLRef url = NULL;
  499. CFReadStreamRef stream = NULL;
  500. CFPropertyListRef plist = NULL;
  501. do {
  502. url = CFURLCreateFromFileSystemRepresentation(
  503. kCFAllocatorDefault, (const UInt8*)filename,
  504. strlen(filename), false);
  505. if (!url) {
  506. cf_perror("CFURLCreateFromFileSystemRepresentation");
  507. break;
  508. }
  509. stream = CFReadStreamCreateWithFile(kCFAllocatorDefault, url);
  510. if (!stream) {
  511. cf_perror("CFReadStreamCreateWithFile");
  512. break;
  513. }
  514. if (!CFReadStreamOpen(stream)) {
  515. cf_perror("CFReadStreamOpen");
  516. break;
  517. }
  518. plist = CFPropertyListCreateWithStream(
  519. kCFAllocatorDefault, stream, 0,
  520. kCFPropertyListImmutable, NULL, NULL);
  521. if (!plist) {
  522. cf_perror("CFPropertyListCreateWithStream");
  523. break;
  524. }
  525. } while (false);
  526. if (url) {
  527. CFRelease(url);
  528. }
  529. if (stream) {
  530. CFReadStreamClose(stream);
  531. CFRelease(stream);
  532. }
  533. return plist;
  534. }
  535. bool dict_get_value(CFDictionaryRef dict, const char* key, const void** value)
  536. {
  537. CFStringRef cfkey = to_cfstring(key);
  538. if (!cfkey) {
  539. return false;
  540. }
  541. Boolean status = CFDictionaryGetValueIfPresent(dict, cfkey, value);
  542. CFRelease(cfkey);
  543. return status;
  544. }
  545. char* dict_get_string(CFDictionaryRef dict, const char* key)
  546. {
  547. CFStringRef str;
  548. if (!dict_get_value(dict, key, (const void**)&str)) {
  549. return NULL;
  550. }
  551. CFIndex len = CFStringGetLength(str) + 1;
  552. char* buf = (char*)malloc(len);
  553. if (!buf) {
  554. perror("malloc");
  555. return NULL;
  556. }
  557. Boolean status = CFStringGetFileSystemRepresentation(
  558. str, buf, len);
  559. if (!status) {
  560. cf_perror("CFStringGetFileSystemRepresentation");
  561. free(buf);
  562. return NULL;
  563. }
  564. return buf;
  565. }
  566. typedef struct {
  567. const char* device;
  568. char* pretty;
  569. } find_pretty_name_ctx;
  570. void find_pretty_name(const void* key, const void* value, void* context)
  571. {
  572. find_pretty_name_ctx* ctx = (find_pretty_name_ctx*)context;
  573. if (ctx->pretty) {
  574. return;
  575. }
  576. CFDictionaryRef dict;
  577. if (!dict_get_value((CFDictionaryRef)value, "Interface", (const void**)&dict)) {
  578. return;
  579. }
  580. char* device = dict_get_string(dict, "DeviceName");
  581. if (!device) {
  582. return;
  583. }
  584. if (!strcmp(ctx->device, device)) {
  585. // there are two instances of UserDefinedName. The one in the "Interface" dict
  586. // defines a base name, such as "Wi-Fi", whereas the one in the root dict
  587. // might contain a trailing number (e.g. "Wi-Fi 2") to identify multiple
  588. // interfaces with the same base name.
  589. ctx->pretty = dict_get_string((CFDictionaryRef)value, "UserDefinedName");
  590. if (!ctx->pretty) {
  591. ctx->pretty = dict_get_string(dict, "UserDefinedName");
  592. }
  593. }
  594. free(device);
  595. }
  596. char* get_pretty_name(const char* interface)
  597. {
  598. CFPropertyListRef plist = plist_open("/Library/Preferences/SystemConfiguration/preferences.plist");
  599. if (!plist) {
  600. return NULL;
  601. }
  602. // what we're after is a CFDictionary element with the path
  603. // /NetworkServices/<UUID>/Interface. The keys we're interested
  604. // in are DeviceName (the network interface name), and UserDefinedName
  605. // (the pretty name). Since we don't know the interface's UUID,
  606. // we have to loop through all of them.
  607. CFDictionaryRef dict;
  608. find_pretty_name_ctx ctx = { interface, NULL };
  609. if (dict_get_value((CFDictionaryRef)plist, "NetworkServices", (const void**)&dict)) {
  610. CFDictionaryApplyFunction(dict, find_pretty_name, &ctx);
  611. }
  612. CFRelease(plist);
  613. return ctx.pretty;
  614. }
  615. #endif
  616. inline uint8_t *ethsock_get_hwaddr(struct ethsock *sock)
  617. {
  618. return sock->hwaddr;
  619. }
  620. bool ethsock_is_wifi(struct ethsock *sock)
  621. {
  622. #ifdef PCAP_IF_WIRELESS
  623. bpf_u_int32 flags;
  624. if (!intf_get_pcap_flags(sock->intf, &flags)) {
  625. return false;
  626. }
  627. return flags & PCAP_IF_WIRELESS;
  628. #else
  629. #warning "libpcap version is < 1.9.0"
  630. return false;
  631. #endif
  632. }
  633. bool ethsock_is_unplugged(struct ethsock *sock)
  634. {
  635. #ifdef PCAP_IF_CONNECTION_STATUS
  636. bpf_u_int32 flags;
  637. if (!intf_get_pcap_flags(sock->intf, &flags)) {
  638. return false;
  639. }
  640. return (flags & PCAP_IF_CONNECTION_STATUS)
  641. == PCAP_IF_CONNECTION_STATUS_DISCONNECTED;
  642. #else
  643. #warning "libpcap version is < 1.9.0"
  644. return false;
  645. #endif
  646. }
  647. struct ethsock *ethsock_create(const char *intf, uint16_t protocol)
  648. {
  649. char buf[PCAP_ERRBUF_SIZE];
  650. struct bpf_program fp;
  651. struct ethsock *sock;
  652. bool is_bridge = false;
  653. int err;
  654. #ifdef NMRPFLASH_WINDOWS
  655. intf = intf_name_to_wpcap(intf);
  656. if (!intf) {
  657. return NULL;
  658. }
  659. #endif
  660. sock = malloc(sizeof(struct ethsock));
  661. if (!sock) {
  662. xperror("malloc");
  663. return NULL;
  664. }
  665. buf[0] = '\0';
  666. sock->intf = intf;
  667. sock->pcap = pcap_create(sock->intf, buf);
  668. if (!sock->pcap) {
  669. fprintf(stderr, "pcap_create: %s\n", buf);
  670. }
  671. if (*buf) {
  672. fprintf(stderr, "Warning: %s.\n", buf);
  673. }
  674. err = pcap_set_snaplen(sock->pcap, BUFSIZ);
  675. if (err) {
  676. pcap_perror(sock->pcap, "pcap_set_snaplen");
  677. goto cleanup;
  678. }
  679. err = pcap_set_promisc(sock->pcap, 1);
  680. if (err) {
  681. pcap_perror(sock->pcap, "pcap_set_promisc");
  682. goto cleanup;
  683. }
  684. err = pcap_set_timeout(sock->pcap, 200);
  685. if (err) {
  686. pcap_perror(sock->pcap, "pcap_set_timeout");
  687. goto cleanup;
  688. }
  689. err = pcap_set_immediate_mode(sock->pcap, 1);
  690. if (err) {
  691. pcap_perror(sock->pcap, "pcap_set_immediate_mode");
  692. goto cleanup;
  693. }
  694. err = pcap_activate(sock->pcap);
  695. if (err < 0) {
  696. pcap_perror(sock->pcap, "pcap_activate");
  697. goto cleanup;
  698. } else if (err > 0) {
  699. fprintf(stderr, "Warning: %s.\n", pcap_geterr(sock->pcap));
  700. }
  701. if (pcap_datalink(sock->pcap) != DLT_EN10MB) {
  702. fprintf(stderr, "%s is not an ethernet interface.\n",
  703. intf);
  704. goto cleanup;
  705. }
  706. #ifndef NMRPFLASH_WINDOWS
  707. err = !intf_get_hwaddr_and_bridge(intf, sock->hwaddr, &is_bridge);
  708. #else
  709. err = !intf_get_hwaddr_and_index(intf, sock->hwaddr, &sock->index);
  710. #endif
  711. if (err) {
  712. fprintf(stderr, "Failed to get interface info.\n");
  713. goto cleanup;
  714. }
  715. #ifdef NMRPFLASH_WINDOWS
  716. err = pcap_setmintocopy(sock->pcap, 0);
  717. if (err) {
  718. pcap_perror(sock->pcap, "pcap_setmintocopy");
  719. goto cleanup;
  720. }
  721. sock->handle = pcap_getevent(sock->pcap);
  722. if (!sock->handle) {
  723. pcap_perror(sock->pcap, "pcap_getevent");
  724. goto cleanup;
  725. }
  726. #else
  727. sock->fd = pcap_get_selectable_fd(sock->pcap);
  728. if (sock->fd == -1) {
  729. pcap_perror(sock->pcap, "pcap_get_selectable_fd");
  730. goto cleanup;
  731. }
  732. #endif
  733. snprintf(buf, sizeof(buf), "ether proto 0x%04x and not ether src %s",
  734. protocol, mac_to_str(sock->hwaddr));
  735. err = pcap_compile(sock->pcap, &fp, buf, 0, 0);
  736. if (err) {
  737. pcap_perror(sock->pcap, "pcap_compile");
  738. goto cleanup;
  739. }
  740. err = pcap_setfilter(sock->pcap, &fp);
  741. pcap_freecode(&fp);
  742. if (err) {
  743. pcap_perror(sock->pcap, "pcap_setfilter");
  744. goto cleanup;
  745. }
  746. #ifdef NMRPFLASH_LINUX
  747. // nmrpflash does not work on bridge interfaces with STP enabled
  748. if ((sock->stp = intf_sys_read(intf, "bridge/stp_state", false))) {
  749. if (!intf_stp_enable(intf, false)) {
  750. fprintf(stderr, "Warning: failed to disable STP on %s.\n", intf);
  751. }
  752. }
  753. err = system("nmcli -v > /dev/null");
  754. if (!err) {
  755. err = systemf("nmcli -f GENERAL.STATE device show %s | grep -q unmanaged", sock->intf);
  756. if (!err) {
  757. sock->nm_managed = false;
  758. } else {
  759. sock->nm_managed = true;
  760. err = systemf("nmcli device set ifname %s managed no", sock->intf);
  761. if (err) {
  762. printf("Warning: failed to temporarily disable NetworkManager\n");
  763. } else if (verbosity > 1) {
  764. printf("Temporarily disabling NetworkManager on interface.\n");
  765. }
  766. }
  767. } else {
  768. sock->nm_managed = false;
  769. }
  770. #else
  771. if (is_bridge) {
  772. fprintf(stderr, "Warning: bridge interfaces are not fully "
  773. "supported on this platform.\n");
  774. }
  775. #endif
  776. return sock;
  777. cleanup:
  778. ethsock_close(sock);
  779. return NULL;
  780. }
  781. ssize_t ethsock_recv(struct ethsock *sock, void *buf, size_t len)
  782. {
  783. struct pcap_pkthdr* hdr;
  784. const u_char *capbuf;
  785. int status;
  786. #ifdef NMRPFLASH_WINDOWS
  787. DWORD ret;
  788. if (sock->timeout) {
  789. ret = WaitForSingleObject(sock->handle, sock->timeout);
  790. if (ret == WAIT_TIMEOUT) {
  791. return 0;
  792. } else if (ret != WAIT_OBJECT_0) {
  793. win_perror2("WaitForSingleObject", ret);
  794. return -1;
  795. }
  796. }
  797. #else
  798. if (sock->timeout) {
  799. status = select_fd(sock->fd, sock->timeout);
  800. if (status < 0) {
  801. return -1;
  802. } else if (status == 0) {
  803. return 0;
  804. }
  805. }
  806. #endif
  807. status = pcap_next_ex(sock->pcap, &hdr, &capbuf);
  808. switch (status) {
  809. case 1:
  810. memcpy(buf, capbuf, MIN(len, hdr->caplen));
  811. return hdr->caplen;
  812. case 0:
  813. return 0;
  814. case -1:
  815. pcap_perror(sock->pcap, "pcap_next_ex");
  816. return -1;
  817. default:
  818. fprintf(stderr, "pcap_next_ex: returned %d.\n", status);
  819. return -1;
  820. }
  821. }
  822. int ethsock_send(struct ethsock *sock, void *buf, size_t len)
  823. {
  824. if (pcap_inject(sock->pcap, buf, len) != len) {
  825. #ifdef NMRPFLASH_WINDOWS
  826. // Npcap's pcap_inject fails in many cases where neither
  827. // Linux or macOS report an error. For now, we simply
  828. // ignore errors if unplugged (and let all other through
  829. // as well, just printing a debug line).
  830. if (!ethsock_is_unplugged(sock) && verbosity > 1) {
  831. pcap_perror(sock->pcap, "pcap_inject");
  832. }
  833. return 0;
  834. #endif
  835. pcap_perror(sock->pcap, "pcap_inject");
  836. return -1;
  837. }
  838. return 0;
  839. }
  840. int ethsock_close(struct ethsock *sock)
  841. {
  842. if (!sock) {
  843. return 0;
  844. }
  845. #ifdef NMRPFLASH_LINUX
  846. if (sock->stp) {
  847. intf_stp_enable(sock->intf, true);
  848. }
  849. if (sock->nm_managed) {
  850. systemf("nmcli device set ifname %s managed yes", sock->intf);
  851. }
  852. #endif
  853. if (sock->pcap) {
  854. pcap_close(sock->pcap);
  855. }
  856. free(sock);
  857. return 0;
  858. }
  859. inline int ethsock_set_timeout(struct ethsock *sock, unsigned msec)
  860. {
  861. sock->timeout = msec;
  862. return 0;
  863. }
  864. unsigned ethsock_get_timeout(struct ethsock *sock)
  865. {
  866. return sock->timeout;
  867. }
  868. static int ethsock_arp(struct ethsock *sock, uint8_t *hwaddr, uint32_t ipaddr, struct ethsock_arp_undo **undo)
  869. {
  870. #if defined(NMRPFLASH_UNIX) && !defined(NMRPFLASH_LINUX)
  871. struct in_addr addr = { .s_addr = ipaddr };
  872. #elif defined(NMRPFLASH_WINDOWS)
  873. DWORD err;
  874. MIB_IPNETROW arp = {
  875. .dwIndex = sock->index,
  876. .dwPhysAddrLen = 6,
  877. .dwAddr = ipaddr,
  878. .dwType = MIB_IPNET_TYPE_STATIC
  879. };
  880. memcpy(arp.bPhysAddr, hwaddr, 6);
  881. #endif
  882. if (undo) {
  883. #if defined(NMRPFLASH_LINUX)
  884. if (!intf_add_del_arp(sock->intf, ipaddr, hwaddr, true)) {
  885. return -1;
  886. }
  887. #elif defined(NMRPFLASH_WINDOWS)
  888. err = CreateIpNetEntry(&arp);
  889. if (err != NO_ERROR) {
  890. win_perror2("CreateIpNetEntry", err);
  891. return -1;
  892. }
  893. #else
  894. if (systemf("arp -s %s %s", inet_ntoa(addr), mac_to_str(hwaddr)) != 0) {
  895. return -1;
  896. }
  897. #endif
  898. *undo = malloc(sizeof(struct ethsock_arp_undo));
  899. if (!*undo) {
  900. xperror("malloc");
  901. return -1;
  902. }
  903. (*undo)->ipaddr = ipaddr;
  904. memcpy((*undo)->hwaddr, hwaddr, 6);
  905. } else {
  906. #if defined(NMRPFLASH_LINUX)
  907. if (!intf_add_del_arp(sock->intf, ipaddr, hwaddr, false)) {
  908. return -1;
  909. }
  910. #elif defined(NMRPFLASH_WINDOWS)
  911. return DeleteIpNetEntry(&arp) ? 0 : -1;
  912. #else
  913. return systemf("arp -d %s &> /dev/null", inet_ntoa(addr));
  914. #endif
  915. }
  916. return 0;
  917. }
  918. int ethsock_arp_add(struct ethsock *sock, uint8_t *hwaddr, uint32_t ipaddr, struct ethsock_arp_undo **undo)
  919. {
  920. // remove any previous ARP entry
  921. ethsock_arp(sock, hwaddr, ipaddr, NULL);
  922. // add the new ARP entry
  923. return undo ? ethsock_arp(sock, hwaddr, ipaddr, undo) : -1;
  924. }
  925. int ethsock_arp_del(struct ethsock *sock, struct ethsock_arp_undo **undo)
  926. {
  927. if (!*undo) {
  928. return 0;
  929. }
  930. int ret = ethsock_arp(sock, (*undo)->hwaddr, (*undo)->ipaddr, NULL);
  931. free(*undo);
  932. *undo = NULL;
  933. return ret;
  934. }
  935. static bool get_hwaddr_from_pcap(const pcap_if_t *dev, uint8_t *hwaddr)
  936. {
  937. #ifndef NMRPFLASH_WINDOWS
  938. pcap_addr_t *addr;
  939. int i;
  940. for (addr = dev->addresses; addr; addr = addr->next) {
  941. if (verbosity > 1) {
  942. printf("%s: sa_family=%d, sa_data={ ", dev->name,
  943. addr->addr->sa_family);
  944. for (i = 0; i != sizeof(addr->addr->sa_data); ++i) {
  945. printf("%02x ", addr->addr->sa_data[i] & 0xff);
  946. }
  947. printf("}\n");
  948. }
  949. if (sockaddr_get_hwaddr(addr->addr, hwaddr)) {
  950. return true;
  951. }
  952. }
  953. return intf_get_hwaddr_and_bridge(dev->name, hwaddr, NULL);
  954. #else
  955. return intf_get_hwaddr_and_index(dev->name, hwaddr, NULL);
  956. #endif
  957. }
  958. int ethsock_list_all(void)
  959. {
  960. pcap_if_t *devs, *dev;
  961. pcap_addr_t *addr;
  962. uint8_t hwaddr[6];
  963. unsigned dev_num = 0, dev_ok = 0;
  964. #if defined(NMRPFLASH_WINDOWS)
  965. wchar_t *pretty = NULL;
  966. NET_IFINDEX index;
  967. MIB_IF_ROW2 row;
  968. #elif defined(NMRPFLASH_OSX)
  969. char *pretty = NULL;
  970. #endif
  971. if (x_pcap_findalldevs(&devs) != 0) {
  972. return -1;
  973. }
  974. memset(hwaddr, 0, 6);
  975. for (dev = devs; dev; dev = dev->next, ++dev_num) {
  976. if (dev->flags & PCAP_IF_LOOPBACK) {
  977. if (verbosity) {
  978. printf("%-15s (loopback device)\n", dev->name);
  979. }
  980. continue;
  981. }
  982. if (!get_hwaddr_from_pcap(dev, hwaddr)) {
  983. if (verbosity) {
  984. printf("%-15s (not an ethernet device)\n",
  985. dev->name);
  986. }
  987. continue;
  988. }
  989. #ifndef NMRPFLASH_WINDOWS
  990. printf("%-15s", dev->name);
  991. # ifdef NMRPFLASH_OSX
  992. pretty = get_pretty_name(dev->name);
  993. # endif
  994. #else
  995. index = intf_get_index(dev->name);
  996. if (intf_get_if_row(index, &row)) {
  997. if (!row.InterfaceAndOperStatusFlags.HardwareInterface) {
  998. if (verbosity) {
  999. printf("%-15s (virtual interface)\n", dev->name);
  1000. }
  1001. continue;
  1002. }
  1003. if (row.Alias[0]) {
  1004. pretty = row.Alias;
  1005. }
  1006. }
  1007. if (!verbosity && index) {
  1008. printf("net%-2lu", index);
  1009. } else {
  1010. printf("%-15s", dev->name);
  1011. }
  1012. #endif
  1013. for (addr = dev->addresses; addr; addr = addr->next) {
  1014. if (addr->addr->sa_family == AF_INET) {
  1015. printf(" %-15s",
  1016. inet_ntoa(((struct sockaddr_in*)addr->addr)->sin_addr));
  1017. break;
  1018. }
  1019. }
  1020. if (!addr) {
  1021. printf(" %-15s", "0.0.0.0");
  1022. }
  1023. printf(" %s", mac_to_str(hwaddr));
  1024. #if defined(NMRPFLASH_WINDOWS) || defined(NMRPFLASH_OSX)
  1025. if (pretty) {
  1026. printf(" (" NMRPFLASH_PRETTY_FMT ")", pretty);
  1027. } else if (dev->description) {
  1028. printf(" (%s)", dev->description);
  1029. }
  1030. #endif
  1031. #ifdef NMRPFLASH_OSX
  1032. free(pretty);
  1033. #endif
  1034. printf("\n");
  1035. ++dev_ok;
  1036. }
  1037. if (!dev_ok) {
  1038. printf("No suitable network interfaces found.\n");
  1039. }
  1040. return 0;
  1041. }
  1042. int ethsock_for_each_ip(struct ethsock *sock, ethsock_ip_callback_t callback,
  1043. void *arg)
  1044. {
  1045. struct ethsock_ip_callback_args args;
  1046. pcap_if_t *devs, *dev;
  1047. pcap_addr_t *addr;
  1048. int status = 0;
  1049. if (x_pcap_findalldevs(&devs) != 0) {
  1050. return -1;
  1051. }
  1052. args.arg = arg;
  1053. for (dev = devs; dev; dev = dev->next) {
  1054. if (strcmp(sock->intf, dev->name)) {
  1055. continue;
  1056. }
  1057. for (addr = dev->addresses; addr; addr = addr->next) {
  1058. if (addr->addr->sa_family == AF_INET) {
  1059. args.ipaddr = &((struct sockaddr_in*)addr->addr)->sin_addr;
  1060. args.ipmask = &((struct sockaddr_in*)addr->netmask)->sin_addr;
  1061. status = callback(&args);
  1062. if (status <= 0) {
  1063. break;
  1064. }
  1065. }
  1066. }
  1067. break;
  1068. }
  1069. pcap_freealldevs(devs);
  1070. return status <= 0 ? status : 0;
  1071. }
  1072. static inline void set_addr(void *p, uint32_t addr)
  1073. {
  1074. struct sockaddr_in* sin = p;
  1075. sin->sin_family = AF_INET;
  1076. sin->sin_addr.s_addr = addr;
  1077. #ifdef NMRPFLASH_BSD
  1078. ((struct sockaddr*)p)->sa_len = sizeof(struct sockaddr_in);
  1079. #endif
  1080. }
  1081. #if !defined(NMRPFLASH_WINDOWS) && !defined(NMRPFLASH_LINUX)
  1082. static bool intf_up(int fd, const char *intf, bool up)
  1083. {
  1084. struct ifreq ifr;
  1085. strncpy(ifr.ifr_name, intf, IFNAMSIZ);
  1086. if (ioctl(fd, SIOCGIFFLAGS, &ifr) != 0) {
  1087. if (up) {
  1088. xperror("ioctl(SIOCGIFFLAGS)");
  1089. }
  1090. return false;
  1091. }
  1092. if (!up) {
  1093. ifr.ifr_flags &= ~(IFF_UP | IFF_RUNNING);
  1094. } else {
  1095. ifr.ifr_flags |= IFF_UP | IFF_RUNNING;
  1096. }
  1097. if (ioctl(fd, SIOCSIFFLAGS, &ifr) != 0) {
  1098. if (up) {
  1099. xperror("ioctl(SIOCSIFFLAGS)");
  1100. }
  1101. return false;
  1102. }
  1103. return true;
  1104. }
  1105. #endif
  1106. static int ethsock_ip_add_del(struct ethsock *sock, uint32_t ipaddr, uint32_t ipmask, struct ethsock_ip_undo **undo, bool add)
  1107. {
  1108. int ret, fd;
  1109. if (add && undo) {
  1110. if (!(*undo = malloc(sizeof(struct ethsock_ip_undo)))) {
  1111. xperror("malloc");
  1112. return -1;
  1113. }
  1114. (*undo)->ip[0] = ipaddr;
  1115. (*undo)->ip[1] = ipmask;
  1116. } else if (!add && (!undo || !*undo)) {
  1117. return 0;
  1118. }
  1119. ret = -1;
  1120. fd = socket(AF_INET, SOCK_DGRAM, 0);
  1121. if (fd < 0) {
  1122. sock_perror("socket");
  1123. goto out;
  1124. }
  1125. #ifndef NMRPFLASH_WINDOWS
  1126. #ifdef NMRPFLASH_LINUX
  1127. if (!intf_add_del_ip(sock->intf, (*undo)->ip[0], (*undo)->ip[1], add)) {
  1128. goto out;
  1129. }
  1130. #else // NMRPFLASH_OSX (or any other BSD)
  1131. struct ifaliasreq ifra;
  1132. memset(&ifra, 0, sizeof(ifra));
  1133. strncpy(ifra.ifra_name, sock->intf, IFNAMSIZ);
  1134. set_addr(&ifra.ifra_addr, ipaddr);
  1135. set_addr(&ifra.ifra_mask, ipmask);
  1136. //set_addr(&ifra.ifra_broadaddr, (ipaddr & ipmask) | ~ipmask);
  1137. if (ioctl(fd, add ? SIOCAIFADDR : SIOCDIFADDR, &ifra) != 0) {
  1138. if (add) {
  1139. xperror("ioctl(SIOCAIFADDR");
  1140. }
  1141. goto out;
  1142. }
  1143. if (add) {
  1144. (*undo)->ip[0] = ipaddr;
  1145. (*undo)->ip[1] = ipmask;
  1146. intf_up(fd, ifra.ifra_name, true);
  1147. }
  1148. #endif
  1149. #else // NMRPFLASH_WINDOWS
  1150. MIB_UNICASTIPADDRESS_ROW row;
  1151. DWORD err;
  1152. int i;
  1153. memset(&row, 0, sizeof(row));
  1154. row.InterfaceIndex = sock->index;
  1155. set_addr(&row.Address.Ipv4, ipaddr);
  1156. row.Address.si_family = AF_INET;
  1157. if (add) {
  1158. row.PrefixOrigin = IpPrefixOriginManual;
  1159. row.SuffixOrigin = IpPrefixOriginManual;
  1160. row.OnLinkPrefixLength = bitcount(ipmask);
  1161. row.SkipAsSource = false;
  1162. row.PreferredLifetime = 0xffffffff;
  1163. row.ValidLifetime = 0xffffffff;
  1164. }
  1165. if (add) {
  1166. err = CreateUnicastIpAddressEntry(&row);
  1167. if (err != NO_ERROR && err != ERROR_OBJECT_ALREADY_EXISTS) {
  1168. win_perror2("CreateUnicastIpAddressEntry", err);
  1169. goto out;
  1170. }
  1171. if (err != ERROR_OBJECT_ALREADY_EXISTS) {
  1172. /* Wait until the new IP has actually been added */
  1173. for (i = 0; i < 20; ++i) {
  1174. err = GetUnicastIpAddressEntry(&row);
  1175. if (err != NO_ERROR) {
  1176. win_perror2("GetUnicastIpAddressEntry", err);
  1177. goto out;
  1178. }
  1179. if (row.DadState == IpDadStateTentative) {
  1180. Sleep(500);
  1181. } else {
  1182. break;
  1183. }
  1184. }
  1185. if (row.DadState == IpDadStateDeprecated) {
  1186. fprintf(stderr, "Warning: IP address marked as deprecated.\n");
  1187. } else if (row.DadState == IpDadStateTentative) {
  1188. fprintf(stderr, "Warning: IP address marked as tentative.\n");
  1189. } else if (row.DadState != IpDadStatePreferred) {
  1190. fprintf(stderr, "Failed to add IP address (state=%d).\n", row.DadState);
  1191. goto out;
  1192. }
  1193. }
  1194. } else {
  1195. err = DeleteUnicastIpAddressEntry(&row);
  1196. if (err != NO_ERROR) {
  1197. win_perror2("DeleteUnicastIpAddressEntry", err);
  1198. goto out;
  1199. }
  1200. }
  1201. #endif
  1202. ret = 0;
  1203. out:
  1204. #ifndef NMRPFLASH_WINDOWS
  1205. close(fd);
  1206. #else
  1207. closesocket(fd);
  1208. #endif
  1209. if (ret != 0 && undo) {
  1210. free(*undo);
  1211. *undo = NULL;
  1212. }
  1213. return ret;
  1214. }
  1215. int ethsock_ip_add(struct ethsock *sock, uint32_t ipaddr, uint32_t ipmask, struct ethsock_ip_undo **undo)
  1216. {
  1217. return ethsock_ip_add_del(sock, ipaddr, ipmask, undo, true);
  1218. }
  1219. int ethsock_ip_del(struct ethsock *sock, struct ethsock_ip_undo **undo)
  1220. {
  1221. if (!undo || !*undo) {
  1222. return 0;
  1223. }
  1224. int ret;
  1225. if ((*undo)->ip[0] != INADDR_NONE) {
  1226. ret = ethsock_ip_add_del(sock, (*undo)->ip[0], (*undo)->ip[1], undo, false);
  1227. } else {
  1228. ret = 0;
  1229. }
  1230. free(*undo);
  1231. *undo = NULL;
  1232. return ret;
  1233. }