/*
    zifaces.c - Network interfaces detection
    Copyright (C) 2002-2020  Ladislav Vaiz <ok1zia@nagano.cz>
    and authors of samba www.samba.org

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    version 2 as published by the Free Software Foundation.

*/


/* 
   Unix SMB/Netbios implementation.
   Version 2.0
   return a list of network interfaces
   Copyright (C) Andrew Tridgell 1998
   
   This program 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 2 of the License, or
   (at your option) any later version.
   
   This program 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 this program; if not, write to the Free Software
   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/


/* working out the interfaces for a OS is an incredibly non-portable
   thing. We have several possible implementations below, and autoconf
   tries each of them to see what works

   Note that this file does _not_ include includes.h. That is so this code
   can be called directly from the autoconf tests. That also means
   this code cannot use any of the normal Samba debug stuff or defines.
   This is standalone code.

*/

#include <libziaint.h>
#include <zstr.h>

#define MAX_INTERFACES 128

#ifndef Z_MSC_MINGW


#include <errno.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#ifndef Z_HAVE_LINUX_WIRELESS_H /* avoid redefinition errors */
#include <net/if.h> // after sys/socket.h and sys/types.h
#endif
#ifdef Z_HAVE_IFADDRS_H
#include <ifaddrs.h>  // after net/if.h
#endif
#ifdef Z_HAVE_LINUX_WIRELESS_H
#include <linux/wireless.h>
#endif
#include <glib.h>

#include <zifaces.h>

#include <zdebug.h>


/* this works for Linux 2.2, Solaris 2.5, SunOS4, HPUX 10.20, OSF1
   V4.0, Ultrix 4.4, SCO Unix 3.2, IRIX 6.4, FreeBSD 3.2. and cygwin

   It probably also works on any BSD style system.  */

#ifndef Z_HAVE_IFADDRS_H
static int _interfaces_get(struct ziface_struct *ifaces, int max_interfaces, int up_only)
{  
    struct ifconf ifc;
    char buff[8192];
    int fd, i, n;
    struct ifreq *ifr=NULL;
    int total = 0;
    struct in_addr ipaddr;
    struct in_addr nmask;
    char *iname;

    if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
        return -1;
    }
  
    ifc.ifc_len = sizeof(buff);
    ifc.ifc_buf = buff;

    if (ioctl(fd, SIOCGIFCONF, &ifc) != 0) {
        close(fd);
        return -1;
    } 

    ifr = ifc.ifc_req;
  
    n = ifc.ifc_len / sizeof(struct ifreq);

    /* Loop through interfaces, looking for given IP address */
    for (i=n-1;i>=0 && total < max_interfaces;i--) {
        if (ioctl(fd, SIOCGIFADDR, &ifr[i]) != 0) {
            continue;
        }

        iname = ifr[i].ifr_name;
        ipaddr = (*(struct sockaddr_in *)&ifr[i].ifr_addr).sin_addr;

#ifdef SIOCGIFHWADDR
        memset(ifaces[total].mac, 0, 6);
        if (ioctl(fd, SIOCGIFHWADDR, &ifr[i]) == 0) {
            memcpy(ifaces[total].mac, ifr[i].ifr_hwaddr.sa_data, 6);
        }
#endif

        if (ioctl(fd, SIOCGIFFLAGS, &ifr[i]) != 0) {
            continue;
        }  

        if (!(ifr[i].ifr_flags & IFF_UP)) {
            continue;
        }

        if (ioctl(fd, SIOCGIFNETMASK, &ifr[i]) != 0) {
            continue;
        }        

        nmask = ((struct sockaddr_in *)&ifr[i].ifr_addr)->sin_addr;

        strncpy(ifaces[total].name, iname, sizeof(ifaces[total].name)-1);
        ifaces[total].name[sizeof(ifaces[total].name)-1] = 0;
        ifaces[total].ip = ipaddr;
        ifaces[total].netmask = nmask;
        total++;
    }

    close(fd);

    return total;
} 
#endif 

#ifdef Z_HAVE_IFADDRS_H
static int _interfaces_get_ifaddrs(struct ziface_struct *ifaces, int max_interfaces, int up_only)
{
      struct ifaddrs *interfaceArray = NULL;
      int total = 0;

      if (getifaddrs(&interfaceArray) != 0) {
          dbg("getifaddrs() failed with errno =  %d %s \n", errno, strerror(errno));
          return -1;
      }

      for (struct ifaddrs *tempIfAddr = interfaceArray;
           tempIfAddr != NULL && total < max_interfaces;
           tempIfAddr = tempIfAddr->ifa_next) {
          if (tempIfAddr->ifa_addr == NULL || tempIfAddr->ifa_addr->sa_family != AF_INET)
              continue;

          if (up_only && !(tempIfAddr->ifa_flags & IFF_UP))
              continue;

          if (tempIfAddr->ifa_netmask == NULL ||
              tempIfAddr->ifa_netmask->sa_family != AF_INET)
              continue;

          strncpy(ifaces[total].name, tempIfAddr->ifa_name,
                  sizeof(ifaces[total].name) - 1);
          ifaces[total].name[sizeof(ifaces[total].name) - 1] = 0;
          memcpy(&ifaces[total].ip,
                 &((struct sockaddr_in *)tempIfAddr->ifa_addr)->sin_addr,
                 sizeof(struct in_addr));
          memcpy(&ifaces[total].netmask,
                 &((struct sockaddr_in *)tempIfAddr->ifa_netmask)->sin_addr,
                 sizeof(struct in_addr));
          total++;
      }

      freeifaddrs(interfaceArray); /* free the dynamic memory */
      interfaceArray = NULL;       /* prevent use after free  */

      return total;
}
#endif

int ziface_wifi_stats(struct zwifi_stat *stat, char *devname, int clear){
#ifdef Z_HAVE_LINUX_WIRELESS_H
	int sockfd;
	struct iw_statistics stats;
	struct ziface_struct ifaces[MAX_INTERFACES];

	int total = zifaces_get(ifaces, MAX_INTERFACES, 1);
	int i;

	if (total <= 0) return -1;

	for (i = 0; i < total; i++){
		//int b;
		//struct in_addr iaddr;

		if (devname != NULL){
			if (strcmp(devname, ifaces[i].name) != 0) continue;
		}


		struct iwreq req = {
			.u.data = {
				.pointer = &stats,
				.length = sizeof(struct iw_statistics),
				.flags = clear
			}
		};
		//printf("%-10s ", ifaces[i].name);
		g_strlcpy(req.ifr_name, ifaces[i].name, IFNAMSIZ);

		/* Any old socket will do, and a datagram socket is pretty cheap */
		if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
			continue;
		}

		/* Perform the ioctl */
		if (ioctl(sockfd, SIOCGIWSTATS, &req) == -1) {
			close(sockfd);
			continue;
		}

		stat->raw_level = stats.qual.level;
		stat->raw_noise = stats.qual.noise;
		stat->raw_qual = stats.qual.qual;
		stat->raw_updated = stats.qual.updated & IW_QUAL_LEVEL_UPDATED;



		struct iw_range range;

		req.u.data.pointer = (caddr_t)&range;
		req.u.data.length = sizeof(struct iw_range);
		req.u.data.flags = 0;

		if (ioctl(sockfd, SIOCGIWRANGE, &req) < 0){
			close(sockfd);
			continue;
		}

		stat->raw_max_qual = range.max_qual.qual;

		close(sockfd);

		stat->quality_percent = (stat->raw_qual * 100) / stat->raw_max_qual;
		stat->level_dbm = range.sensitivity - 256 + (unsigned char)stats.qual.level;

		return 0;
	}
#endif
	return -1;
}


#else

#include <zifaces.h>
#include <stdio.h>
#include <glib.h>
#include <windows.h>
#include <iphlpapi.h>

#pragma warning(disable : 4996)


typedef DWORD (CALLBACK *T_GetAdaptersInfo)(PIP_ADAPTER_INFO pAdapterInfo, PULONG pOutBufLen);


/* GetAdaptersInfo is since Win2k */
int _interfaces_get(struct ziface_struct *ifaces, int max_interfaces, int up_only/*under win32 only up are returned*/){
    PIP_ADAPTER_INFO pAdapterInfo;
	PIP_ADAPTER_INFO pAdapter;
	int i;
	T_GetAdaptersInfo p_GetAdaptersInfo = NULL;
	HMODULE iphlpapi = NULL;
	ULONG ulOutBufLen = sizeof (IP_ADAPTER_INFO);
	

	iphlpapi = LoadLibrary("iphlpapi.dll");
	if (!iphlpapi) return 0;
	
	p_GetAdaptersInfo = (T_GetAdaptersInfo) GetProcAddress(iphlpapi, "GetAdaptersInfo");
	if (!p_GetAdaptersInfo){
		FreeLibrary(iphlpapi);
		return 0;
	}

	pAdapterInfo = (IP_ADAPTER_INFO *) g_malloc(sizeof (IP_ADAPTER_INFO));
	if (pAdapterInfo == NULL) {
		FreeLibrary(iphlpapi);
		return 0;
	}

	if (p_GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW) {
		g_free(pAdapterInfo);
		pAdapterInfo = (IP_ADAPTER_INFO *) g_malloc(ulOutBufLen);
		if (pAdapterInfo == NULL) {
			FreeLibrary(iphlpapi);
			return 0;
		}
	}

	if (p_GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) != NO_ERROR) {
		g_free(pAdapterInfo);
		FreeLibrary(iphlpapi);
		return 0;
	}

	FreeLibrary(iphlpapi);
	
	for (pAdapter = pAdapterInfo, i = 0; 
		pAdapter != NULL && i < max_interfaces; 
		pAdapter = pAdapter->Next) {

		if (up_only && z_strcasestr(pAdapter->Description, "VirtualBox") != NULL)
		{
			continue;
		}

		ifaces[i].ip.S_un.S_addr = inet_addr(pAdapter->IpAddressList.IpAddress.String);
		if (ifaces[i].ip.S_un.S_addr == 0L) continue;
		ifaces[i].netmask.S_un.S_addr = inet_addr(pAdapter->IpAddressList.IpMask.String);
		switch (pAdapter->Type){
			case MIB_IF_TYPE_OTHER:      g_snprintf(ifaces[i].name, ZIFACE_NAME_SIZE, "oth%d", i);  break;
			case MIB_IF_TYPE_ETHERNET:	 g_snprintf(ifaces[i].name, ZIFACE_NAME_SIZE, "eth%d", i); break;
			case MIB_IF_TYPE_TOKENRING:  g_snprintf(ifaces[i].name, ZIFACE_NAME_SIZE, "tr%d", i); break;
			case MIB_IF_TYPE_FDDI:       g_snprintf(ifaces[i].name, ZIFACE_NAME_SIZE, "fddi%d", i); break;
			case MIB_IF_TYPE_PPP:        g_snprintf(ifaces[i].name, ZIFACE_NAME_SIZE, "ppp%d", i); break;
			case MIB_IF_TYPE_LOOPBACK:   g_snprintf(ifaces[i].name, ZIFACE_NAME_SIZE, "lo"); break;
			case MIB_IF_TYPE_SLIP:       g_snprintf(ifaces[i].name, ZIFACE_NAME_SIZE, "sl%d", i); break;
			case IF_TYPE_IEEE80211:		 g_snprintf(ifaces[i].name, ZIFACE_NAME_SIZE, "wlan%d", i); break;
			default: 			 	 	 g_snprintf(ifaces[i].name, ZIFACE_NAME_SIZE, "unk%d", i); break;
		}
		memcpy(ifaces[i].mac, pAdapter->Address, 6);
		i++;
	}

	return i;
}

int ziface_wifi_stats(struct zwifi_stat *stat, char *devname, int clear){
	static int i = 0;

	stat->level_dbm = i - 100;
	stat->quality_percent = i;

	i += 10;
	if (i > 100) i = 0;


	return 0;
}

#endif


static int iface_comp(struct ziface_struct *i1, struct ziface_struct *i2)
{
	int r;
	r = strcmp(i1->name, i2->name);
	if (r) return r;
	r = ntohl(i1->ip.s_addr) - ntohl(i2->ip.s_addr);
	if (r) return r;
	r = ntohl(i1->netmask.s_addr) - ntohl(i2->netmask.s_addr);
	return r;
}

/* this wrapper is used to remove duplicates from the interface list generated
above */
int zifaces_get(struct ziface_struct *ifaces, int max_interfaces, int up_only)
{
	int total, i, j;

#ifndef Z_HAVE_IFADDRS_H
	total = _interfaces_get(ifaces, max_interfaces, up_only);
#else
	total = _interfaces_get_ifaddrs(ifaces, max_interfaces, up_only);
#endif
	if (total <= 0) return total;

	/* now we need to remove duplicates */	
	qsort(ifaces, total, sizeof(ifaces[0]), (int (*)(const void *, const void *))iface_comp);

	for (i=1;i<total;) {
		if (iface_comp(&ifaces[i-1], &ifaces[i]) == 0) {
			for (j=i-1;j<total-1;j++) {
				ifaces[j] = ifaces[j+1];
			}
			total--;
		} else {
			i++;
		}
	}

	return total;
}




#ifdef AUTOCONF_TEST
/* this is the autoconf driver to test get_interfaces() */


int main()
{
    struct ziface_struct ifaces[MAX_INTERFACES];
    int total = zifaces_get(ifaces, MAX_INTERFACES);
    int i;

    printf("got %d interfaces:\n", total);
    if (total <= 0) exit(1);

    for (i=0;i<total;i++) {
        int b;
        struct in_addr iaddr;
        
        printf("%-10s ", ifaces[i].name);
        printf("IP=%-15s ", inet_ntoa(ifaces[i].ip));
        printf("NETMASK=%-15s", inet_ntoa(ifaces[i].netmask));
        b = ifaces[i].ip.s_addr | ~(ifaces[i].netmask.s_addr);
        iaddr.s_addr  = b;
        printf("BCAST=%-15s\n", inet_ntoa(iaddr));
        printf("MAC=");
        for (b = 0; b < 6; b++) printf("%02X ", ifaces[i].mac[b]);
        printf("\n");
        
    }
    return 0;
}
#endif

#define ZMAX_INTERFACES 100

int ziface_is_local(struct in_addr ia){
    struct ziface_struct ifaces[ZMAX_INTERFACES];
	int i, ret;

	if ((ntohl(ia.s_addr) & 0xff000000) == 0x7f000000) return 1;

	ret = zifaces_get(ifaces, ZMAX_INTERFACES, 1);
	for (i = 0; i < ret; i++){
		unsigned long mynet = ifaces[i].ip.s_addr & ifaces[i].netmask.s_addr;
		unsigned long peernet = ia.s_addr & ifaces[i].netmask.s_addr;
		if (mynet == peernet) return 1;
	}
	return 0;
}


char *ziface_macid(const char *namestarts){
#if defined(Z_MSC) || defined(SIOCGIFHWADDR)
	static char macid[32];
    int total, i, up_only;

    struct ziface_struct ifaces[MAX_INTERFACES];

    for (up_only = 1; up_only >= 0; up_only--){
		total = zifaces_get(ifaces, MAX_INTERFACES, up_only);
        if (total <= 0) return NULL;

        for (i=0;i<total;i++) {

            if (namestarts != NULL){
                char *c = strstr(ifaces[i].name, namestarts);
                if (c == NULL) continue;
            }
            
            g_snprintf(macid, 32, "%02X%02X", ifaces[i].mac[4], ifaces[i].mac[5]);
            return macid;
        }
    }											 
#endif
    return NULL;
}
