12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472 |
- /**
- * nmrpflash - Netgear Unbrick Utility
- * Copyright (C) 2016 Joseph Lehner <joseph.c.lehner@gmail.com>
- *
- * nmrpflash is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * nmrpflash is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with nmrpflash. If not, see <http://www.gnu.org/licenses/>.
- *
- */
- #include <sys/types.h>
- #include <stdbool.h>
- #include <stdarg.h>
- #include <string.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <fcntl.h>
- #include "nmrpd.h"
- #if defined(NMRPFLASH_WINDOWS)
- # include <iphlpapi.h>
- # define NMRPFLASH_PRETTY_FMT "%ls"
- # ifndef ERROR_NDIS_MEDIA_DISCONNECTED
- # define ERROR_NDIS_MEDIA_DISCONNECTED 0x8034001f
- # endif
- # define WPCAP
- # include <pcap.h>
- #else
- # include <sys/ioctl.h>
- # include <ifaddrs.h>
- # include <unistd.h>
- # include <net/if.h>
- # include <pcap.h>
- # if defined(NMRPFLASH_LINUX)
- # define NMRPFLASH_AF_PACKET AF_PACKET
- # include <linux/if_packet.h>
- # include <netlink/route/addr.h>
- # include <netlink/route/neighbour.h>
- # else
- # define NMRPFLASH_AF_PACKET AF_LINK
- # include <net/if_types.h>
- # include <net/if_media.h>
- # endif
- #endif
- #ifdef NMRPFLASH_OSX
- #include <CoreFoundation/CoreFoundation.h>
- #define NMRPFLASH_PRETTY_FMT "%s"
- #endif
- struct ethsock
- {
- const char *intf;
- pcap_t *pcap;
- #ifndef NMRPFLASH_WINDOWS
- int fd;
- #ifdef NMRPFLASH_LINUX
- bool stp;
- // managed by NetworkManager
- bool nm_managed;
- #endif
- #else
- HANDLE handle;
- DWORD index;
- #endif
- unsigned timeout;
- uint8_t hwaddr[6];
- };
- struct ethsock_arp_undo
- {
- uint32_t ipaddr;
- uint8_t hwaddr[6];
- };
- struct ethsock_ip_undo
- {
- uint32_t ip[2];
- };
- static int x_pcap_findalldevs(pcap_if_t **devs)
- {
- char errbuf[PCAP_ERRBUF_SIZE];
- if (pcap_findalldevs(devs, errbuf) != 0) {
- fprintf(stderr, "%s.\n", errbuf);
- return -1;
- }
- return 0;
- }
- static bool intf_get_pcap_flags(const char *intf, bpf_u_int32 *flags)
- {
- pcap_if_t *devs, *dev;
- if (x_pcap_findalldevs(&devs) == 0) {
- for (dev = devs; dev; dev = dev->next) {
- if (!strcmp(intf, dev->name)) {
- *flags = dev->flags;
- break;
- }
- }
- pcap_freealldevs(devs);
- return dev != NULL;
- }
- return false;
- }
- #ifndef NMRPFLASH_WINDOWS
- static int systemf(const char *fmt, ...)
- {
- char cmd[1024];
- int ret;
- va_list va;
- va_start(va, fmt);
- ret = vsnprintf(cmd, sizeof(cmd) - 1, fmt, va);
- if (ret >= sizeof(cmd) - 1) {
- return -1;
- }
- ret = system(cmd);
- va_end(va);
- return ret;
- }
- #endif
- #ifndef NMRPFLASH_WINDOWS
- static inline bool sockaddr_get_hwaddr(struct sockaddr *sa, uint8_t *hwaddr)
- {
- void *src;
- if (!sa || sa->sa_family != NMRPFLASH_AF_PACKET) {
- return false;
- }
- #ifndef NMRPFLASH_LINUX
- if (((struct sockaddr_dl*)sa)->sdl_type != IFT_ETHER) {
- return false;
- }
- src = LLADDR((struct sockaddr_dl*)sa);
- #else
- src = ((struct sockaddr_ll*)sa)->sll_addr;
- #endif
- memcpy(hwaddr, src, 6);
- return true;
- }
- #ifdef NMRPFLASH_LINUX
- static int intf_sys_open(const char* intf, const char* file)
- {
- char name[256];
- snprintf(name, sizeof(name), "/sys/class/net/%s/%s", intf, file);
- return open(name, O_RDWR, 0644);
- }
- static bool intf_sys_read(const char* intf, const char* file, bool def)
- {
- char c;
- int fd;
- fd = intf_sys_open(intf, file);
- if (fd == -1) {
- return def;
- }
- c = 0;
- read(fd, &c, 1);
- close(fd);
- return c ? (c == '1') : def;
- }
- static bool intf_stp_enable(const char *intf, bool enabled)
- {
- int fd;
- ssize_t n;
- fd = intf_sys_open(intf, "bridge/stp_state");
- if (fd == -1) {
- return false;
- }
- n = write(fd, enabled ? "1\n" : "0\n", 2);
- close(fd);
- return n == 2;
- }
- static struct nl_addr *build_ip(uint32_t ip)
- {
- struct nl_addr *na = nl_addr_build(AF_INET, &ip, 4);
- if (!na) {
- xperror("nl_addr_build");
- }
- return na;
- }
- static struct nl_sock *xnl_socket_route()
- {
- int err;
- struct nl_sock *sk = nl_socket_alloc();
- if (sk) {
- if (!(err = nl_connect(sk, NETLINK_ROUTE))) {
- return sk;
- }
- nl_socket_free(sk);
- nl_perror(err, "nl_connect");
- } else {
- xperror("nl_socket_alloc");
- }
- return NULL;
- }
- static bool intf_add_del_ip(const char *intf, uint32_t ipaddr, uint32_t ipmask, bool add)
- {
- struct rtnl_addr *ra = NULL;
- struct nl_sock *sk = NULL;
- struct nl_addr *laddr = NULL;
- struct nl_addr *bcast = NULL;
- int err = 1;
- if (!(sk = xnl_socket_route())) {
- return false;
- }
- if (!(laddr = build_ip(ipaddr))) {
- goto out;
- }
- nl_addr_set_prefixlen(laddr, bitcount(ipmask));
- if (!(bcast = build_ip((ipaddr & ipmask) | ~ipmask))) {
- goto out;
- }
- if (!(ra = rtnl_addr_alloc())) {
- xperror("rtnl_addr_alloc");
- goto out;
- }
- rtnl_addr_set_ifindex(ra, if_nametoindex(intf));
- rtnl_addr_set_local(ra, laddr);
- rtnl_addr_set_broadcast(ra, bcast);
- if ((err = (add ? rtnl_addr_add(sk, ra, 0) : rtnl_addr_delete(sk, ra, 0))) < 0) {
- if (add && err == -NLE_EXIST) {
- err = 0;
- } else if (add || verbosity > 1) {
- nl_perror(err, add ? "rtnl_addr_add" : "rtnl_addr_delete");
- }
- }
- out:
- rtnl_addr_put(ra);
- nl_addr_put(laddr);
- nl_addr_put(bcast);
- nl_socket_free(sk);
- return !err;
- }
- static bool intf_add_del_arp(const char *intf, uint32_t ipaddr, uint8_t *hwaddr, bool add)
- {
- #if 0
- struct arpreq arp;
- memset(&arp, 0, sizeof(arp));
- arp.arp_ha.sa_family = ARPHRD_ETHER;
- memcpy(&arp.arp_ha.sa_data, hwaddr, 6);
- arp.arp_flags = ATF_PERM | ATF_COM;
- struct sockaddr_in *in = (struct sockaddr_in*)&req.arp_pa;
- in->sin_addr.s_addr = htonl(ipaddr);
- in->sin_family = AF_INET;
- int fd = socket(AF_INET, SOCK_DGRAM, 0);
- if (fd < 0) {
- perror("socket");
- return false;
- }
- bool ret = true;
- if (ioctl(fd, add ? SIOCSARP : SIOCDARP, &req) < 0) {
- perror(add ? "ioctl(SIOCSARP)" : "ioctl(SIOCDARP");
- ret = false;
- }
- close(fd);
- return ret;
- #else
- struct nl_sock *sk;
- struct rtnl_neigh *neigh;
- struct nl_addr *mac, *ip;
- int err = 1;
- sk = NULL;
- neigh = NULL;
- mac = ip = NULL;
- if (!(sk = xnl_socket_route())) {
- goto out;
- }
- if (!(neigh = rtnl_neigh_alloc())) {
- xperror("rtnl_neigh_alloc");
- goto out;
- }
- if (!(mac = nl_addr_build(AF_PACKET, hwaddr, 6))) {
- xperror("nl_addr_build");
- goto out;
- }
- if (!(ip = nl_addr_build(AF_INET, &ipaddr, 4))) {
- xperror("nl_addr_build");
- goto out;
- }
- rtnl_neigh_set_ifindex(neigh, if_nametoindex(intf));
- rtnl_neigh_set_dst(neigh, ip);
- err = rtnl_neigh_delete(sk, neigh, 0);
- if (add) {
- rtnl_neigh_set_lladdr(neigh, mac);
- rtnl_neigh_set_state(neigh, NUD_PERMANENT);
- err = rtnl_neigh_add(sk, neigh, NLM_F_CREATE);
- }
- if (err && add) {
- nl_perror(err, "rtnl_neigh_add");
- }
- out:
- nl_addr_put(ip);
- nl_addr_put(mac);
- rtnl_neigh_put(neigh);
- nl_socket_free(sk);
- return !err;
- #endif
- }
- #endif
- static bool intf_get_hwaddr_and_bridge(const char *intf, uint8_t *hwaddr, bool *bridge)
- {
- struct ifaddrs *ifas, *ifa;
- bool found;
- if (getifaddrs(&ifas) != 0) {
- xperror("getifaddrs");
- return false;
- }
- found = false;
- if (bridge) {
- *bridge = false;
- }
- for (ifa = ifas; ifa; ifa = ifa->ifa_next) {
- if (!strcmp(ifa->ifa_name, intf)) {
- if (sockaddr_get_hwaddr(ifa->ifa_addr, hwaddr)) {
- #ifdef NMRPFLASH_BSD
- if (bridge) {
- *bridge = ((struct if_data*) ifa->ifa_data)->ifi_type == IFT_BRIDGE;
- }
- #endif
- found = true;
- break;
- }
- }
- }
- freeifaddrs(ifas);
- return found;
- }
- #else
- void win_perror2(const char *msg, DWORD err)
- {
- char *buf = NULL;
- FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
- FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
- NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
- (LPTSTR)&buf, 0, NULL);
- if (buf) {
- /* FormatMessageA terminates buf with CRLF! */
- fprintf(stderr, "%s: %s", msg, buf);
- LocalFree(buf);
- } else {
- fprintf(stderr, "%s: error %d\n", msg, (int)err);
- }
- }
- static bool intf_get_if_row(NET_IFINDEX index, MIB_IF_ROW2* row)
- {
- DWORD err;
- memset(row, 0, sizeof(*row));
- row->InterfaceIndex = index;
- err = GetIfEntry2(row);
- if (err != NO_ERROR) {
- if (verbosity > 1) {
- win_perror2("GetIfEntry2", err);
- }
- return false;
- }
- return true;
- }
- static bool intf_get_hwaddr_and_index(const char *intf, uint8_t *hwaddr, DWORD *index)
- {
- PIP_ADAPTER_ADDRESSES adapters, adapter;
- ULONG ret, flags, bufLen;
- bool found = false;
- flags = GAA_FLAG_INCLUDE_ALL_INTERFACES;
- bufLen = 0;
- ret = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, NULL, &bufLen);
- if (ret != ERROR_BUFFER_OVERFLOW) {
- win_perror2("GetAdaptersAddresses", ret);
- return false;
- }
- bufLen *= 2;
- adapters = malloc(bufLen);
- if (!adapters) {
- xperror("malloc");
- return false;
- }
- ret = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, adapters, &bufLen);
- if (ret == NO_ERROR) {
- for (adapter = adapters; adapter; adapter = adapter->Next) {
- if (verbosity > 2) {
- printf(" %s: Type=%lu, Name=%ls\n", adapter->AdapterName, adapter->IfType, adapter->FriendlyName);
- }
- if (adapter->IfType != IF_TYPE_ETHERNET_CSMACD && adapter->IfType != IF_TYPE_IEEE80211) {
- continue;
- }
- /* Interface names from WinPcap are "\Device\NPF_{GUID}", while
- * AdapterName from GetAdaptersAddresses is just "{GUID}".*/
- if (strstr(intf, adapter->AdapterName)) {
- if (adapter->PhysicalAddressLength == 6) {
- memcpy(hwaddr, adapter->PhysicalAddress, 6);
- if (index) {
- *index = adapter->IfIndex;
- }
- found = true;
- break;
- }
- }
- }
- } else {
- win_perror2("GetAdaptersAddresses", ret);
- }
- free(adapters);
- return found;
- }
- static const char *intf_name_to_wpcap(const char *intf)
- {
- static char buf[128];
- if (intf[0] == '\\') {
- return intf;
- }
- do {
- NET_IFINDEX index;
- DWORD err;
- NET_LUID luid;
- GUID guid;
- if (sscanf(intf, "net%lu", &index) != 1) {
- index = if_nametoindex(intf);
- if (!index) {
- break;
- }
- }
- err = ConvertInterfaceIndexToLuid(index, &luid);
- if (err != NO_ERROR) {
- if (verbosity) {
- win_perror2("ConvertInterfaceIndexToLuid", err);
- }
- break;
- }
- err = ConvertInterfaceLuidToGuid(&luid, &guid);
- if (err != NO_ERROR) {
- if (verbosity) {
- win_perror2("ConvertInterfaceLuidToGuid", err);
- }
- break;
- }
- snprintf(buf, sizeof(buf),
- "\\Device\\NPF_{%08lX-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}",
- guid.Data1, guid.Data2, guid.Data3,
- guid.Data4[0], guid.Data4[1], guid.Data4[2],
- guid.Data4[3], guid.Data4[4], guid.Data4[5],
- guid.Data4[6], guid.Data4[7]);
- return buf;
- } while (false);
- fprintf(stderr, "Invalid interface name.\n");
- return NULL;
- }
- NET_IFINDEX intf_get_index(const char* intf)
- {
- const char* p;
- GUID guid;
- NET_LUID luid;
- DWORD err;
- NET_IFINDEX ret;
- int n;
- p = strstr(intf, "NPF_{");
- if (!p) {
- return 0;
- }
- sscanf(p + 5,
- "%08lX-%04hX-%04hX-%02hhX%02hhX-%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX%n",
- &guid.Data1, &guid.Data2, &guid.Data3,
- &guid.Data4[0], &guid.Data4[1], &guid.Data4[2],
- &guid.Data4[3], &guid.Data4[4], &guid.Data4[5],
- &guid.Data4[6], &guid.Data4[7], &n);
- if (n != 36) {
- return 0;
- }
- err = ConvertInterfaceGuidToLuid(&guid, &luid);
- if (err) {
- win_perror2("ConvertInterfaceGuidToLuid", err);
- return 0;
- }
- err = ConvertInterfaceLuidToIndex(&luid, &ret);
- if (err) {
- win_perror2("ConvertInterfaceLuidToIndex", err);
- return 0;
- }
- return ret;
- }
- #endif
- #ifdef NMRPFLASH_OSX
- void cf_perror(const char* function)
- {
- if (verbosity > 1) {
- fprintf(stderr, "Warning: %s failed\n", function);
- }
- }
- CFStringRef to_cfstring(const char* str)
- {
- CFStringRef ret = CFStringCreateWithFileSystemRepresentation(
- kCFAllocatorDefault, str);
- if (!ret) {
- cf_perror("CFStringCreateWithFileSystemRepresentation");
- }
- return ret;
- }
- CFPropertyListRef plist_open(const char* filename)
- {
- CFURLRef url = NULL;
- CFReadStreamRef stream = NULL;
- CFPropertyListRef plist = NULL;
- do {
- url = CFURLCreateFromFileSystemRepresentation(
- kCFAllocatorDefault, (const UInt8*)filename,
- strlen(filename), false);
- if (!url) {
- cf_perror("CFURLCreateFromFileSystemRepresentation");
- break;
- }
- stream = CFReadStreamCreateWithFile(kCFAllocatorDefault, url);
- if (!stream) {
- cf_perror("CFReadStreamCreateWithFile");
- break;
- }
- if (!CFReadStreamOpen(stream)) {
- cf_perror("CFReadStreamOpen");
- break;
- }
- plist = CFPropertyListCreateWithStream(
- kCFAllocatorDefault, stream, 0,
- kCFPropertyListImmutable, NULL, NULL);
- if (!plist) {
- cf_perror("CFPropertyListCreateWithStream");
- break;
- }
- } while (false);
- if (url) {
- CFRelease(url);
- }
- if (stream) {
- CFReadStreamClose(stream);
- CFRelease(stream);
- }
- return plist;
- }
- bool dict_get_value(CFDictionaryRef dict, const char* key, const void** value)
- {
- CFStringRef cfkey = to_cfstring(key);
- if (!cfkey) {
- return false;
- }
- Boolean status = CFDictionaryGetValueIfPresent(dict, cfkey, value);
- CFRelease(cfkey);
- return status;
- }
- char* dict_get_string(CFDictionaryRef dict, const char* key)
- {
- CFStringRef str;
- if (!dict_get_value(dict, key, (const void**)&str)) {
- return NULL;
- }
- CFIndex len = CFStringGetLength(str) + 1;
- char* buf = (char*)malloc(len);
- if (!buf) {
- perror("malloc");
- return NULL;
- }
- Boolean status = CFStringGetFileSystemRepresentation(
- str, buf, len);
- if (!status) {
- cf_perror("CFStringGetFileSystemRepresentation");
- free(buf);
- return NULL;
- }
- return buf;
- }
- typedef struct {
- const char* device;
- char* pretty;
- } find_pretty_name_ctx;
- void find_pretty_name(const void* key, const void* value, void* context)
- {
- find_pretty_name_ctx* ctx = (find_pretty_name_ctx*)context;
- if (ctx->pretty) {
- return;
- }
- CFDictionaryRef dict;
- if (!dict_get_value((CFDictionaryRef)value, "Interface", (const void**)&dict)) {
- return;
- }
- char* device = dict_get_string(dict, "DeviceName");
- if (!device) {
- return;
- }
- if (!strcmp(ctx->device, device)) {
- // there are two instances of UserDefinedName. The one in the "Interface" dict
- // defines a base name, such as "Wi-Fi", whereas the one in the root dict
- // might contain a trailing number (e.g. "Wi-Fi 2") to identify multiple
- // interfaces with the same base name.
- ctx->pretty = dict_get_string((CFDictionaryRef)value, "UserDefinedName");
- if (!ctx->pretty) {
- ctx->pretty = dict_get_string(dict, "UserDefinedName");
- }
- }
- free(device);
- }
- char* get_pretty_name(const char* interface)
- {
- CFPropertyListRef plist = plist_open("/Library/Preferences/SystemConfiguration/preferences.plist");
- if (!plist) {
- return NULL;
- }
- // what we're after is a CFDictionary element with the path
- // /NetworkServices/<UUID>/Interface. The keys we're interested
- // in are DeviceName (the network interface name), and UserDefinedName
- // (the pretty name). Since we don't know the interface's UUID,
- // we have to loop through all of them.
- CFDictionaryRef dict;
- find_pretty_name_ctx ctx = { interface, NULL };
- if (dict_get_value((CFDictionaryRef)plist, "NetworkServices", (const void**)&dict)) {
- CFDictionaryApplyFunction(dict, find_pretty_name, &ctx);
- }
- CFRelease(plist);
- return ctx.pretty;
- }
- #endif
- inline uint8_t *ethsock_get_hwaddr(struct ethsock *sock)
- {
- return sock->hwaddr;
- }
- bool ethsock_is_wifi(struct ethsock *sock)
- {
- #ifdef PCAP_IF_WIRELESS
- bpf_u_int32 flags;
- if (!intf_get_pcap_flags(sock->intf, &flags)) {
- return false;
- }
- return flags & PCAP_IF_WIRELESS;
- #else
- #warning "libpcap version is < 1.9.0"
- return false;
- #endif
- }
- bool ethsock_is_unplugged(struct ethsock *sock)
- {
- #ifdef PCAP_IF_CONNECTION_STATUS
- bpf_u_int32 flags;
- if (!intf_get_pcap_flags(sock->intf, &flags)) {
- return false;
- }
- return (flags & PCAP_IF_CONNECTION_STATUS)
- == PCAP_IF_CONNECTION_STATUS_DISCONNECTED;
- #else
- #warning "libpcap version is < 1.9.0"
- return false;
- #endif
- }
- struct ethsock *ethsock_create(const char *intf, uint16_t protocol)
- {
- char buf[PCAP_ERRBUF_SIZE];
- struct bpf_program fp;
- struct ethsock *sock;
- bool is_bridge = false;
- int err;
- #ifdef NMRPFLASH_WINDOWS
- intf = intf_name_to_wpcap(intf);
- if (!intf) {
- return NULL;
- }
- #endif
- sock = malloc(sizeof(struct ethsock));
- if (!sock) {
- xperror("malloc");
- return NULL;
- }
- buf[0] = '\0';
- sock->intf = intf;
- sock->pcap = pcap_create(sock->intf, buf);
- if (!sock->pcap) {
- fprintf(stderr, "pcap_create: %s\n", buf);
- }
- if (*buf) {
- fprintf(stderr, "Warning: %s.\n", buf);
- }
- err = pcap_set_snaplen(sock->pcap, BUFSIZ);
- if (err) {
- pcap_perror(sock->pcap, "pcap_set_snaplen");
- goto cleanup;
- }
- err = pcap_set_promisc(sock->pcap, 1);
- if (err) {
- pcap_perror(sock->pcap, "pcap_set_promisc");
- goto cleanup;
- }
- err = pcap_set_timeout(sock->pcap, 200);
- if (err) {
- pcap_perror(sock->pcap, "pcap_set_timeout");
- goto cleanup;
- }
- err = pcap_set_immediate_mode(sock->pcap, 1);
- if (err) {
- pcap_perror(sock->pcap, "pcap_set_immediate_mode");
- goto cleanup;
- }
- err = pcap_activate(sock->pcap);
- if (err < 0) {
- pcap_perror(sock->pcap, "pcap_activate");
- goto cleanup;
- } else if (err > 0) {
- fprintf(stderr, "Warning: %s.\n", pcap_geterr(sock->pcap));
- }
- if (pcap_datalink(sock->pcap) != DLT_EN10MB) {
- fprintf(stderr, "%s is not an ethernet interface.\n",
- intf);
- goto cleanup;
- }
- #ifndef NMRPFLASH_WINDOWS
- err = !intf_get_hwaddr_and_bridge(intf, sock->hwaddr, &is_bridge);
- #else
- err = !intf_get_hwaddr_and_index(intf, sock->hwaddr, &sock->index);
- #endif
- if (err) {
- fprintf(stderr, "Failed to get interface info.\n");
- goto cleanup;
- }
- #ifdef NMRPFLASH_WINDOWS
- err = pcap_setmintocopy(sock->pcap, 0);
- if (err) {
- pcap_perror(sock->pcap, "pcap_setmintocopy");
- goto cleanup;
- }
- sock->handle = pcap_getevent(sock->pcap);
- if (!sock->handle) {
- pcap_perror(sock->pcap, "pcap_getevent");
- goto cleanup;
- }
- #else
- sock->fd = pcap_get_selectable_fd(sock->pcap);
- if (sock->fd == -1) {
- pcap_perror(sock->pcap, "pcap_get_selectable_fd");
- goto cleanup;
- }
- #endif
- snprintf(buf, sizeof(buf), "ether proto 0x%04x and not ether src %s",
- protocol, mac_to_str(sock->hwaddr));
- err = pcap_compile(sock->pcap, &fp, buf, 0, 0);
- if (err) {
- pcap_perror(sock->pcap, "pcap_compile");
- goto cleanup;
- }
- err = pcap_setfilter(sock->pcap, &fp);
- pcap_freecode(&fp);
- if (err) {
- pcap_perror(sock->pcap, "pcap_setfilter");
- goto cleanup;
- }
- #ifdef NMRPFLASH_LINUX
- // nmrpflash does not work on bridge interfaces with STP enabled
- if ((sock->stp = intf_sys_read(intf, "bridge/stp_state", false))) {
- if (!intf_stp_enable(intf, false)) {
- fprintf(stderr, "Warning: failed to disable STP on %s.\n", intf);
- }
- }
- err = system("nmcli -v > /dev/null");
- if (!err) {
- err = systemf("nmcli -f GENERAL.STATE device show %s | grep -q unmanaged", sock->intf);
- if (!err) {
- sock->nm_managed = false;
- } else {
- sock->nm_managed = true;
- err = systemf("nmcli device set ifname %s managed no", sock->intf);
- if (err) {
- printf("Warning: failed to temporarily disable NetworkManager\n");
- } else if (verbosity > 1) {
- printf("Temporarily disabling NetworkManager on interface.\n");
- }
- }
- } else {
- sock->nm_managed = false;
- }
- #else
- if (is_bridge) {
- fprintf(stderr, "Warning: bridge interfaces are not fully "
- "supported on this platform.\n");
- }
- #endif
- return sock;
- cleanup:
- ethsock_close(sock);
- return NULL;
- }
- ssize_t ethsock_recv(struct ethsock *sock, void *buf, size_t len)
- {
- struct pcap_pkthdr* hdr;
- const u_char *capbuf;
- int status;
- #ifdef NMRPFLASH_WINDOWS
- DWORD ret;
- if (sock->timeout) {
- ret = WaitForSingleObject(sock->handle, sock->timeout);
- if (ret == WAIT_TIMEOUT) {
- return 0;
- } else if (ret != WAIT_OBJECT_0) {
- win_perror2("WaitForSingleObject", ret);
- return -1;
- }
- }
- #else
- if (sock->timeout) {
- status = select_fd(sock->fd, sock->timeout);
- if (status < 0) {
- return -1;
- } else if (status == 0) {
- return 0;
- }
- }
- #endif
- status = pcap_next_ex(sock->pcap, &hdr, &capbuf);
- switch (status) {
- case 1:
- memcpy(buf, capbuf, MIN(len, hdr->caplen));
- return hdr->caplen;
- case 0:
- return 0;
- case -1:
- pcap_perror(sock->pcap, "pcap_next_ex");
- return -1;
- default:
- fprintf(stderr, "pcap_next_ex: returned %d.\n", status);
- return -1;
- }
- }
- int ethsock_send(struct ethsock *sock, void *buf, size_t len)
- {
- if (pcap_inject(sock->pcap, buf, len) != len) {
- #ifdef NMRPFLASH_WINDOWS
- // Npcap's pcap_inject fails in many cases where neither
- // Linux or macOS report an error. For now, we simply
- // ignore errors if unplugged (and let all other through
- // as well, just printing a debug line).
- if (!ethsock_is_unplugged(sock) && verbosity > 1) {
- pcap_perror(sock->pcap, "pcap_inject");
- }
- return 0;
- #endif
- pcap_perror(sock->pcap, "pcap_inject");
- return -1;
- }
- return 0;
- }
- int ethsock_close(struct ethsock *sock)
- {
- if (!sock) {
- return 0;
- }
- #ifdef NMRPFLASH_LINUX
- if (sock->stp) {
- intf_stp_enable(sock->intf, true);
- }
- if (sock->nm_managed) {
- systemf("nmcli device set ifname %s managed yes", sock->intf);
- }
- #endif
- if (sock->pcap) {
- pcap_close(sock->pcap);
- }
- free(sock);
- return 0;
- }
- inline int ethsock_set_timeout(struct ethsock *sock, unsigned msec)
- {
- sock->timeout = msec;
- return 0;
- }
- unsigned ethsock_get_timeout(struct ethsock *sock)
- {
- return sock->timeout;
- }
- static int ethsock_arp(struct ethsock *sock, uint8_t *hwaddr, uint32_t ipaddr, struct ethsock_arp_undo **undo)
- {
- #if defined(NMRPFLASH_UNIX) && !defined(NMRPFLASH_LINUX)
- struct in_addr addr = { .s_addr = ipaddr };
- #elif defined(NMRPFLASH_WINDOWS)
- DWORD err;
- MIB_IPNETROW arp = {
- .dwIndex = sock->index,
- .dwPhysAddrLen = 6,
- .dwAddr = ipaddr,
- .dwType = MIB_IPNET_TYPE_STATIC
- };
- memcpy(arp.bPhysAddr, hwaddr, 6);
- #endif
- if (undo) {
- #if defined(NMRPFLASH_LINUX)
- if (!intf_add_del_arp(sock->intf, ipaddr, hwaddr, true)) {
- return -1;
- }
- #elif defined(NMRPFLASH_WINDOWS)
- err = CreateIpNetEntry(&arp);
- if (err != NO_ERROR) {
- win_perror2("CreateIpNetEntry", err);
- return -1;
- }
- #else
- if (systemf("arp -s %s %s", inet_ntoa(addr), mac_to_str(hwaddr)) != 0) {
- return -1;
- }
- #endif
- *undo = malloc(sizeof(struct ethsock_arp_undo));
- if (!*undo) {
- xperror("malloc");
- return -1;
- }
- (*undo)->ipaddr = ipaddr;
- memcpy((*undo)->hwaddr, hwaddr, 6);
- } else {
- #if defined(NMRPFLASH_LINUX)
- if (!intf_add_del_arp(sock->intf, ipaddr, hwaddr, false)) {
- return -1;
- }
- #elif defined(NMRPFLASH_WINDOWS)
- return DeleteIpNetEntry(&arp) ? 0 : -1;
- #else
- return systemf("arp -d %s &> /dev/null", inet_ntoa(addr));
- #endif
- }
- return 0;
- }
- int ethsock_arp_add(struct ethsock *sock, uint8_t *hwaddr, uint32_t ipaddr, struct ethsock_arp_undo **undo)
- {
- // remove any previous ARP entry
- ethsock_arp(sock, hwaddr, ipaddr, NULL);
- // add the new ARP entry
- return undo ? ethsock_arp(sock, hwaddr, ipaddr, undo) : -1;
- }
- int ethsock_arp_del(struct ethsock *sock, struct ethsock_arp_undo **undo)
- {
- if (!*undo) {
- return 0;
- }
- int ret = ethsock_arp(sock, (*undo)->hwaddr, (*undo)->ipaddr, NULL);
- free(*undo);
- *undo = NULL;
- return ret;
- }
- static bool get_hwaddr_from_pcap(const pcap_if_t *dev, uint8_t *hwaddr)
- {
- #ifndef NMRPFLASH_WINDOWS
- pcap_addr_t *addr;
- int i;
- for (addr = dev->addresses; addr; addr = addr->next) {
- if (verbosity > 1) {
- printf("%s: sa_family=%d, sa_data={ ", dev->name,
- addr->addr->sa_family);
- for (i = 0; i != sizeof(addr->addr->sa_data); ++i) {
- printf("%02x ", addr->addr->sa_data[i] & 0xff);
- }
- printf("}\n");
- }
- if (sockaddr_get_hwaddr(addr->addr, hwaddr)) {
- return true;
- }
- }
- return intf_get_hwaddr_and_bridge(dev->name, hwaddr, NULL);
- #else
- return intf_get_hwaddr_and_index(dev->name, hwaddr, NULL);
- #endif
- }
- int ethsock_list_all(void)
- {
- pcap_if_t *devs, *dev;
- pcap_addr_t *addr;
- uint8_t hwaddr[6];
- unsigned dev_num = 0, dev_ok = 0;
- #if defined(NMRPFLASH_WINDOWS)
- wchar_t *pretty = NULL;
- NET_IFINDEX index;
- MIB_IF_ROW2 row;
- #elif defined(NMRPFLASH_OSX)
- char *pretty = NULL;
- #endif
- if (x_pcap_findalldevs(&devs) != 0) {
- return -1;
- }
- memset(hwaddr, 0, 6);
- for (dev = devs; dev; dev = dev->next, ++dev_num) {
- if (dev->flags & PCAP_IF_LOOPBACK) {
- if (verbosity) {
- printf("%-15s (loopback device)\n", dev->name);
- }
- continue;
- }
- if (!get_hwaddr_from_pcap(dev, hwaddr)) {
- if (verbosity) {
- printf("%-15s (not an ethernet device)\n",
- dev->name);
- }
- continue;
- }
- #ifndef NMRPFLASH_WINDOWS
- printf("%-15s", dev->name);
- # ifdef NMRPFLASH_OSX
- pretty = get_pretty_name(dev->name);
- # endif
- #else
- index = intf_get_index(dev->name);
- if (intf_get_if_row(index, &row)) {
- if (!row.InterfaceAndOperStatusFlags.HardwareInterface) {
- if (verbosity) {
- printf("%-15s (virtual interface)\n", dev->name);
- }
- continue;
- }
- if (row.Alias[0]) {
- pretty = row.Alias;
- }
- }
- if (!verbosity && index) {
- printf("net%-2lu", index);
- } else {
- printf("%-15s", dev->name);
- }
- #endif
- for (addr = dev->addresses; addr; addr = addr->next) {
- if (addr->addr->sa_family == AF_INET) {
- printf(" %-15s",
- inet_ntoa(((struct sockaddr_in*)addr->addr)->sin_addr));
- break;
- }
- }
- if (!addr) {
- printf(" %-15s", "0.0.0.0");
- }
- printf(" %s", mac_to_str(hwaddr));
- #if defined(NMRPFLASH_WINDOWS) || defined(NMRPFLASH_OSX)
- if (pretty) {
- printf(" (" NMRPFLASH_PRETTY_FMT ")", pretty);
- } else if (dev->description) {
- printf(" (%s)", dev->description);
- }
- #endif
- #ifdef NMRPFLASH_OSX
- free(pretty);
- #endif
- printf("\n");
- ++dev_ok;
- }
- if (!dev_ok) {
- printf("No suitable network interfaces found.\n");
- }
- return 0;
- }
- int ethsock_for_each_ip(struct ethsock *sock, ethsock_ip_callback_t callback,
- void *arg)
- {
- struct ethsock_ip_callback_args args;
- pcap_if_t *devs, *dev;
- pcap_addr_t *addr;
- int status = 0;
- if (x_pcap_findalldevs(&devs) != 0) {
- return -1;
- }
- args.arg = arg;
- for (dev = devs; dev; dev = dev->next) {
- if (strcmp(sock->intf, dev->name)) {
- continue;
- }
- for (addr = dev->addresses; addr; addr = addr->next) {
- if (addr->addr->sa_family == AF_INET) {
- args.ipaddr = &((struct sockaddr_in*)addr->addr)->sin_addr;
- args.ipmask = &((struct sockaddr_in*)addr->netmask)->sin_addr;
- status = callback(&args);
- if (status <= 0) {
- break;
- }
- }
- }
- break;
- }
- pcap_freealldevs(devs);
- return status <= 0 ? status : 0;
- }
- static inline void set_addr(void *p, uint32_t addr)
- {
- struct sockaddr_in* sin = p;
- sin->sin_family = AF_INET;
- sin->sin_addr.s_addr = addr;
- #ifdef NMRPFLASH_BSD
- ((struct sockaddr*)p)->sa_len = sizeof(struct sockaddr_in);
- #endif
- }
- #if !defined(NMRPFLASH_WINDOWS) && !defined(NMRPFLASH_LINUX)
- static bool intf_up(int fd, const char *intf, bool up)
- {
- struct ifreq ifr;
- strncpy(ifr.ifr_name, intf, IFNAMSIZ);
- if (ioctl(fd, SIOCGIFFLAGS, &ifr) != 0) {
- if (up) {
- xperror("ioctl(SIOCGIFFLAGS)");
- }
- return false;
- }
- if (!up) {
- ifr.ifr_flags &= ~(IFF_UP | IFF_RUNNING);
- } else {
- ifr.ifr_flags |= IFF_UP | IFF_RUNNING;
- }
- if (ioctl(fd, SIOCSIFFLAGS, &ifr) != 0) {
- if (up) {
- xperror("ioctl(SIOCSIFFLAGS)");
- }
- return false;
- }
- return true;
- }
- #endif
- static int ethsock_ip_add_del(struct ethsock *sock, uint32_t ipaddr, uint32_t ipmask, struct ethsock_ip_undo **undo, bool add)
- {
- int ret, fd;
- if (add && undo) {
- if (!(*undo = malloc(sizeof(struct ethsock_ip_undo)))) {
- xperror("malloc");
- return -1;
- }
- (*undo)->ip[0] = ipaddr;
- (*undo)->ip[1] = ipmask;
- } else if (!add && (!undo || !*undo)) {
- return 0;
- }
- ret = -1;
- fd = socket(AF_INET, SOCK_DGRAM, 0);
- if (fd < 0) {
- sock_perror("socket");
- goto out;
- }
- #ifndef NMRPFLASH_WINDOWS
- #ifdef NMRPFLASH_LINUX
- if (!intf_add_del_ip(sock->intf, (*undo)->ip[0], (*undo)->ip[1], add)) {
- goto out;
- }
- #else // NMRPFLASH_OSX (or any other BSD)
- struct ifaliasreq ifra;
- memset(&ifra, 0, sizeof(ifra));
- strncpy(ifra.ifra_name, sock->intf, IFNAMSIZ);
- set_addr(&ifra.ifra_addr, ipaddr);
- set_addr(&ifra.ifra_mask, ipmask);
- //set_addr(&ifra.ifra_broadaddr, (ipaddr & ipmask) | ~ipmask);
- if (ioctl(fd, add ? SIOCAIFADDR : SIOCDIFADDR, &ifra) != 0) {
- if (add) {
- xperror("ioctl(SIOCAIFADDR");
- }
- goto out;
- }
- if (add) {
- (*undo)->ip[0] = ipaddr;
- (*undo)->ip[1] = ipmask;
- intf_up(fd, ifra.ifra_name, true);
- }
- #endif
- #else // NMRPFLASH_WINDOWS
- MIB_UNICASTIPADDRESS_ROW row;
- DWORD err;
- int i;
- memset(&row, 0, sizeof(row));
- row.InterfaceIndex = sock->index;
- set_addr(&row.Address.Ipv4, ipaddr);
- row.Address.si_family = AF_INET;
- if (add) {
- row.PrefixOrigin = IpPrefixOriginManual;
- row.SuffixOrigin = IpPrefixOriginManual;
- row.OnLinkPrefixLength = bitcount(ipmask);
- row.SkipAsSource = false;
- row.PreferredLifetime = 0xffffffff;
- row.ValidLifetime = 0xffffffff;
- }
- if (add) {
- err = CreateUnicastIpAddressEntry(&row);
- if (err != NO_ERROR && err != ERROR_OBJECT_ALREADY_EXISTS) {
- win_perror2("CreateUnicastIpAddressEntry", err);
- goto out;
- }
- if (err != ERROR_OBJECT_ALREADY_EXISTS) {
- /* Wait until the new IP has actually been added */
- for (i = 0; i < 20; ++i) {
- err = GetUnicastIpAddressEntry(&row);
- if (err != NO_ERROR) {
- win_perror2("GetUnicastIpAddressEntry", err);
- goto out;
- }
- if (row.DadState == IpDadStateTentative) {
- Sleep(500);
- } else {
- break;
- }
- }
- if (row.DadState == IpDadStateDeprecated) {
- fprintf(stderr, "Warning: IP address marked as deprecated.\n");
- } else if (row.DadState == IpDadStateTentative) {
- fprintf(stderr, "Warning: IP address marked as tentative.\n");
- } else if (row.DadState != IpDadStatePreferred) {
- fprintf(stderr, "Failed to add IP address (state=%d).\n", row.DadState);
- goto out;
- }
- }
- } else {
- err = DeleteUnicastIpAddressEntry(&row);
- if (err != NO_ERROR) {
- win_perror2("DeleteUnicastIpAddressEntry", err);
- goto out;
- }
- }
- #endif
- ret = 0;
- out:
- #ifndef NMRPFLASH_WINDOWS
- close(fd);
- #else
- closesocket(fd);
- #endif
- if (ret != 0 && undo) {
- free(*undo);
- *undo = NULL;
- }
- return ret;
- }
- int ethsock_ip_add(struct ethsock *sock, uint32_t ipaddr, uint32_t ipmask, struct ethsock_ip_undo **undo)
- {
- return ethsock_ip_add_del(sock, ipaddr, ipmask, undo, true);
- }
- int ethsock_ip_del(struct ethsock *sock, struct ethsock_ip_undo **undo)
- {
- if (!undo || !*undo) {
- return 0;
- }
- int ret;
- if ((*undo)->ip[0] != INADDR_NONE) {
- ret = ethsock_ip_add_del(sock, (*undo)->ip[0], (*undo)->ip[1], undo, false);
- } else {
- ret = 0;
- }
- free(*undo);
- *undo = NULL;
- return ret;
- }
|