/*
 * This file is part of DesktopBSD, see the README file.
 *
 * Author: Peter Hofer <ph@desktopbsd.net>
 *			(C) 2004-2007
 *
 * Copyright: BSD, see the COPYING file included in this distribution
 *
 */

/*
 * Copyright 2001 The Aerospace Corporation.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of The Aerospace Corporation may not be used to endorse or
 *    promote products derived from this software.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AEROSPACE CORPORATION ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AEROSPACE CORPORATION BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * $FreeBSD: src/sbin/ifconfig/ifieee80211.c,v 1.18.2.15 2007/03/10 00:48:28 sam Exp $
 */

/*-
 * Copyright (c) 1997, 1998, 2000 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
 * NASA Ames Research Center.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the NetBSD
 *	Foundation, Inc. and its contributors.
 * 4. Neither the name of The NetBSD Foundation nor the names of its
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "wirelessinterface.h"

#include <sys/param.h> /* __FreeBSD_version */

#include <net/ethernet.h>
#include <net/if_dl.h>
#include <net/if_types.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <net/if_media.h>
#include <sysctl.h>
#include <ifaddrs.h>
#include <net/route.h>
#include <net/if.h>
#if defined(__FreeBSD_version) && __FreeBSD_version >= 800038
#include <net80211/_ieee80211.h>
#endif
#include <net80211/ieee80211.h>
#include <net80211/ieee80211_crypto.h>
#include <net80211/ieee80211_ioctl.h>

#include <qstring.h>
#include <qptrlist.h>

#include <wlan.h>
#include <accesspoint.h>
#include <executor.h>

WirelessInterface::WirelessInterface(const  QString &  devName)
	: NetInterface(devName)
{
}

bool  WirelessInterface::connectTo(const  WLAN &  wlan) {
	WEPMode	wepmode = wlan.getWEPMode();

	return  (setSSID(wlan.getSSID()) &&
				setWEPMode(wepmode)  &&
				(wepmode != WEPOn || (setWEPKeyIndex(1) && setWEPKey(wlan.getWEPKey()))) &&
				NetInterface::connectTo(wlan));
}

/** Sets the device's SSID.
  * (Maximum length is 32 characters)
  */
bool  WirelessInterface::setSSID(const  QString &  ssid) {
	uint8_t  data[33];
	if(strlcpy((char *) data,  ssid.latin1(),  sizeof  data) >= sizeof data)
		return  false;

	return  (set80211(IEEE80211_IOC_SSID,  0,  ssid.length(),  data) >= 0);
}

bool  WirelessInterface::setWEPMode(WEPMode  mode) {
	int  wmode;
	switch(mode) {
	case WEPOn:
		wmode = IEEE80211_WEP_ON;
		break;

	case WEPMixed:
		wmode = IEEE80211_WEP_MIXED;
		break;

	case WEPOff:
		wmode = IEEE80211_WEP_OFF;
		break;

	default:
		return  false;
	}

	return  (set80211(IEEE80211_IOC_WEP, wmode, 0, NULL) >= 0);
}

int  WirelessInterface::hexToNumber(char  chr)  const {
	if (chr >= '0' && chr <= '9')
		chr -= '0';
	else if (chr >= 'A' && chr <= 'F')
		chr -= ('A' - 10);
	else if (chr >= 'a' && chr <= 'f')
		chr -= ('a' - 10);
	else
		chr = 0;

	return  chr;
}

/** @param key Hexadecimal key without prepended '0x'
  *				or an empty string to unset the current key.
  *
  *				This does NOT change the WEP mode (On, Off, ...)
  */
bool  WirelessInterface::setWEPKey(const QString &  key) {
	uint8_t  data[IEEE80211_KEYBUF_SIZE];
	bzero(data,  sizeof data);

	/* Convert key from hex to string */
	const char  *asc = key.latin1();
	if(asc == NULL)
		return  false;
	uint	i;
	for(i = 0;  asc[i*2] != '\0'  &&  asc[i*2+1] != '\0';  ++i) {
		if(!isxdigit(asc[i*2])  ||  !isxdigit(asc[i*2+1]))
			return  false;

		data[i] = (hexToNumber(asc[i*2]) << 4) | hexToNumber(asc[i*2+1]);
	}

	return  (set80211(IEEE80211_IOC_WEPKEY,  /* Key Index */ 0,  i,  data) >= 0);
}


/**
  * Set the default key to use for transmission. If the given
  * index is 0, the used key index is set to 'undefined'.
  *
  * @param index The key index, an integer value >= 1.
  */
bool WirelessInterface::setWEPKeyIndex(int index) {
	if(index-- == 0)
#ifdef IEEE80211_KEYIX_NONE
		index = IEEE80211_KEYIX_NONE;
#else
		index = -1;
#endif

	return (set80211(IEEE80211_IOC_WEPTXKEY, index, 0, NULL) >= 0);
}


/** Returns the current SSID of the interface
  * (can be != desired SSID)
  */
QString  WirelessInterface::getSSID()  const {
	uint8_t  data[32];
	struct ieee80211req  *ireq = getIReq(IEEE80211_IOC_SSID,  (uint8_t **) &data);
	if(ireq == NULL)
		return  "";

	QString  ssid;
	for(int i = 0;  i < ireq->i_len;  ++i)
		ssid += (char) data[i];

	return  ssid;
}

/** Returns WEPOn when WEP encryption is used,
  * WEPOff if not and WIInvalid if an error occured.
  */
WEPMode  WirelessInterface::getWEPMode()  const {
	uint8_t  data[32];
	struct ieee80211req  *ireq = getIReq(IEEE80211_IOC_WEP,  (uint8_t **) &data);
	if(ireq == NULL)
		return  WIInvalid;

	WEPMode  mode = WIInvalid;
	switch(ireq->i_val) {
		case IEEE80211_WEP_NOSUP:
			mode = WIInvalid;  break;

		case IEEE80211_WEP_OFF:
			mode = WEPOff;  break;

		case IEEE80211_WEP_ON:
			mode = WEPOn;  break;

		case IEEE80211_WEP_MIXED:
			mode = WEPMixed;  break;
	}

	delete  ireq;
	return  mode;
}

/** Scans for wireless access points.
  *
  * @return QPtrList with the found access points.
  */
QPtrList<AccessPoint>  WirelessInterface::getAPs()
{
	QPtrList<AccessPoint> list;
	
	/* Some WiFi NICs need to be in link state UP to scan for networks */
	up();

	uint8_t buffer[24 * 1024];
	struct ieee80211req *ireq = getIReq(IEEE80211_IOC_SCAN_RESULTS, (uint8_t **) buffer, sizeof buffer, 0);
	if(ireq == NULL)
		return list;

	int length = ireq->i_len;
	if (length < sizeof(struct ieee80211req_scan_result))
	{
		delete ireq;
		return list;
	}

	uint8_t *current = buffer;
	do
	{
		struct ieee80211req_scan_result *sr = (struct ieee80211req_scan_result *) current;
		list.append(new AccessPoint(*sr, copySSID((u_int8_t *) (sr + 1), (size_t) sr->isr_ssid_len)));

		current += sr->isr_len;
		length -= sr->isr_len;
	}
	while (length >= sizeof(struct ieee80211req_scan_result));
	
	delete ireq;
	return list;
}

/** Returns a list with all wireless network interfaces. */
QPtrList<WirelessInterface>  WirelessInterface::getWirelessIfs() {
	QPtrList<WirelessInterface>  lst;

	struct if_nameindex  *ifidx = if_nameindex();

	struct if_nameindex  *ifptr = ifidx;
	while(ifptr != NULL  &&  ifptr->if_name != NULL) {
		WirelessInterface  *netIf = new WirelessInterface(ifptr->if_name);

		if(netIf->isWireless() && !netIf->isLoopback())
			lst.append(netIf);
		else
			delete  netIf;

		++ifptr;
	}

	if_freenameindex(ifidx);
	return  lst;
}


int  WirelessInterface::set80211(int  type,  int  val,  int  length,  uint8_t *data)  const {
	int  s = newSocket();
	if(s < 0)
		return  -1;

	struct	ieee80211req  ireq;

	bzero(&ireq,  sizeof ireq);
	strlcpy(ireq.i_name,  getName().latin1(),  sizeof ireq.i_name);
	ireq.i_type = type;
	ireq.i_val = val;
	ireq.i_len = length;
	ireq.i_data = data;

	int  retval = ioctl(s, SIOCS80211, &ireq);
	close(s);
	return  retval;
}


/** @param data pointer to a pointer to a uint8_t array with minimum size 32 */
struct ieee80211req  *WirelessInterface::getIReq(int  type,  uint8_t  **data)  const
{
	return getIReq(type, data, 0, -1);
}


/** @param data pointer to a pointer to a uint8_t array with minimum size 32 */
struct ieee80211req  *WirelessInterface::getIReq(int type, uint8_t **data, size_t len, int16_t val)  const
{
	int  s = newSocket();
	if(s < 0)
		return  NULL;

	struct ieee80211req  *ireq = new ieee80211req;
	bzero(ireq,  sizeof *ireq);
	strlcpy(ireq->i_name,  getName(),  sizeof ireq->i_name);
	ireq->i_data = data;
	ireq->i_type = type;
	ireq->i_len = len;
	ireq->i_val = val;

	if(ioctl(s, SIOCG80211, ireq) < 0) {
		close(s);
		delete  ireq;
		return  NULL;
	}

	close(s);
	return  ireq;
}


QString WirelessInterface::copySSID(const u_int8_t *essid, const size_t essid_len) const
{
	char buf[IEEE80211_NWID_LEN + 1];
	int bufsize = sizeof(buf) - 1;
	bzero(buf, sizeof(buf));
	
	const u_int8_t *p; 
	size_t maxlen;
	int i;

	if (essid_len > bufsize)
		maxlen = bufsize;
	else
		maxlen = essid_len;
	/* determine printable or not */
	for (i = 0, p = essid; i < maxlen; i++, p++) {
		if (*p < ' ' || *p > 0x7e)
			break;
	}
	if (i != maxlen) {		/* not printable, print as hex */
		
		/* Check for hidden SSIDs (filled with zeroes) */
		for(i = 0; i < maxlen; ++i)
		{
			if(*p != 0)
				break;
		}
		if(i == maxlen)
			return QString();
		
		if (bufsize < 3)
			return "INVALID";
		strlcpy(buf, "0x", bufsize);
		bufsize -= 2;
		p = essid;
		for (i = 0; i < maxlen && bufsize >= 2; i++) {
			sprintf(&buf[2+2*i], "%02x", p[i]);
			bufsize -= 2;
		}
		if (i != essid_len)
			memcpy(&buf[2+2*i-3], "...", 3);
	} else {			/* printable, truncate as needed */
		memcpy(buf, essid, maxlen);
		if (maxlen != essid_len)
			memcpy(&buf[maxlen-3], "...", 3);
	}
	
	return QString(buf);
}
