Ejemplo n.º 1
0
static void WlanOpenHandle_test(void)
{
    DWORD ret;
    DWORD dwNegotiatedVersion;
    HANDLE hClientHandle;

    /* correct call to determine if WlanSvc is running */
    ret = WlanOpenHandle(1, NULL, &dwNegotiatedVersion, &hClientHandle);
    if (ret == ERROR_SERVICE_EXISTS)
    {
        skip("Skipping wlanapi tests, WlanSvc is not running\n");
        return;
    }
    ok(ret == ERROR_SUCCESS, "WlanOpenHandle failed, error %ld\n", ret);
    WlanCloseHandle(hClientHandle, NULL);

    /* invalid pdwNegotiatedVersion */
    ret = WlanOpenHandle(1, NULL, NULL, &hClientHandle);
    ok(ret == ERROR_INVALID_PARAMETER, "expected ERROR_INVALID_PARAMETER, got %ld\n", GetLastError());

    /* invalid hClientHandle */
    ret = WlanOpenHandle(1, NULL, &dwNegotiatedVersion, NULL);
    ok(ret == ERROR_INVALID_PARAMETER, "expected ERROR_INVALID_PARAMETER, got %ld\n", GetLastError());

    /* invalid pReserved */
    ret = WlanOpenHandle(1, (PVOID) 1, &dwNegotiatedVersion, &hClientHandle);
    ok(ret == ERROR_INVALID_PARAMETER, "expected ERROR_INVALID_PARAMETER, got %ld\n", GetLastError());
}
Ejemplo n.º 2
0
/*
 * Get the index of the first available network in the list
 */
DWORD GetWlanAvailableSSID (WLANKEY *keys,
                            int *index,
                            WLAN_REASON_CODE *reason){
	DWORD apiver;
	DWORD status;
	HANDLE h;
	WLAN_INTERFACE_INFO_LIST *iflist;
	GUID *iface;
	wchar_t *ifname;
	unsigned int i;
	status = WlanOpenHandle (1, NULL, &apiver, &h);
	if (status != ERROR_SUCCESS){
		return status;
	}
	status = WlanEnumInterfaces (h, NULL, &iflist);
	*index = -1;
	for (i=0; *index == -1 && i < iflist->dwNumberOfItems; i++){
		iface = &(iflist->InterfaceInfo[i].InterfaceGuid);
		ifname = iflist->InterfaceInfo[i].strInterfaceDescription;
		status = GetIfaceAvailableSSID (h, iface, ifname, keys, index, reason);
	}
	WlanFreeMemory (iflist);
	WlanCloseHandle (h, NULL);
	return status;
}
Ejemplo n.º 3
0
void KPR_system_getWifiInfo(xsMachine* the)
{
    DWORD dwResult = 0;
    HANDLE hClient = NULL;
    DWORD dwMaxClient = 2; 
    DWORD dwCurVersion = 0;
    PWLAN_INTERFACE_INFO_LIST pIfList = NULL;
    int i;
    PWLAN_INTERFACE_INFO pIfInfo = NULL;
    DWORD connectInfoSize = sizeof(WLAN_CONNECTION_ATTRIBUTES);
    PWLAN_CONNECTION_ATTRIBUTES pConnectInfo = NULL;
    WLAN_OPCODE_VALUE_TYPE opCode = wlan_opcode_value_type_invalid;
    ULONG length;
	xsVars(1);
    dwResult = WlanOpenHandle(dwMaxClient, NULL, &dwCurVersion, &hClient); 
    if (dwResult != ERROR_SUCCESS) 
    	goto bail;
	dwResult = WlanEnumInterfaces(hClient, NULL, &pIfList); 
    if (dwResult != ERROR_SUCCESS)
    	goto bail;
    for (i = 0; i < (int) pIfList->dwNumberOfItems; i++) {
		pIfInfo = (WLAN_INTERFACE_INFO *) &pIfList->InterfaceInfo[i];
   		if (pIfInfo->isState == wlan_interface_state_connected) {
			dwResult = WlanQueryInterface(hClient, &pIfInfo->InterfaceGuid,
										  wlan_intf_opcode_current_connection,
										  NULL,
										  &connectInfoSize,
										  (PVOID *) &pConnectInfo, 
										  &opCode);
			if (dwResult != ERROR_SUCCESS)
				goto bail;
			length = pConnectInfo->wlanAssociationAttributes.dot11Ssid.uSSIDLength;
			if (length > 0) {
				xsResult = xsNewInstanceOf(xsObjectPrototype);
				xsVar(0) = xsStringBuffer(NULL, length + 1);
				FskMemCopy(xsToString(xsVar(0)), pConnectInfo->wlanAssociationAttributes.dot11Ssid.ucSSID, length);
				xsSet(xsResult, xsID("SSID"), xsVar(0));
			}
   			break;
   		}
   	}
bail:
    if (pConnectInfo != NULL) {
        WlanFreeMemory(pConnectInfo);
        pConnectInfo = NULL;
    }
    if (pIfList != NULL) {
        WlanFreeMemory(pIfList);
        pIfList = NULL;
    }
    if (hClient != NULL) {
        WlanCloseHandle(hClient, NULL);
        hClient = NULL;
    }
}
Ejemplo n.º 4
0
WiFiInfo::Impl::Impl() : m_hClient(NULL), m_timer(NULL)
{
  DWORD dwMaxClient = 2;  // 1 for WinXP, 2 for Vista and above
  DWORD dwCurVersion = 0;
  DWORD dwResult = WlanOpenHandle(dwMaxClient, NULL, &dwCurVersion, &m_hClient);
  if (dwResult != ERROR_SUCCESS)
  {
    LOG(LWARNING, ("Error while opening WLAN handle", dwResult));
  }
  m_isNotificationSupported = (dwCurVersion > 1);
  pWlanGetNetworkBssList = (PWLANGETNETWORKBSSLIST)GetProcAddress(GetModuleHandleA("wlanapi.dll"),
                "WlanGetNetworkBssList");
}
Ejemplo n.º 5
0
t_wifi		wififriend_create_handle(void)
{
	t_wifi	Connect;
	DWORD	SetHandle = ERROR_SUCCESS;
	HANDLE	Handle = NULL;
	DWORD	Version = 0;

	if ((SetHandle = WlanOpenHandle(WLAN_API_VERSION, NULL, &Version, &Handle)) != ERROR_SUCCESS)
		error_invalid_handle(1);
	else
		Connect.MyHandle = Handle;
	return (Connect);
}
Ejemplo n.º 6
0
DWORD SetInterface(WLAN_INTF_OPCODE opcode, PVOID* pData, GUID* InterfaceGuid)
{
	DWORD dwResult = 0;
	HANDLE hClient = NULL;
	DWORD dwCurVersion = 0;
	DWORD outsize = 0;

	// Open Handle for the set operation
	dwResult = WlanOpenHandle(WLAN_CLIENT_VERSION_VISTA, NULL, &dwCurVersion, &hClient);
	dwResult = WlanSetInterface(hClient, InterfaceGuid, opcode, sizeof(ULONG), pData, NULL);
	WlanCloseHandle(hClient, NULL);

	return dwResult;
}
Ejemplo n.º 7
0
// open a WLAN client handle and check version
DWORD
OpenHandleAndCheckVersion(
						  PHANDLE phClient
						  )
{
	DWORD dwError = ERROR_SUCCESS;
	DWORD dwServiceVersion;
	HANDLE hClient = NULL;

	__try
	{
		*phClient = NULL;

		// open a handle to the service
		if ((dwError = WlanOpenHandle(
			WLAN_API_VERSION,
			NULL,               // reserved
			&dwServiceVersion,
			&hClient
			)) != ERROR_SUCCESS)
		{
			__leave;
		}

		// check service version
		if (WLAN_API_VERSION_MAJOR(dwServiceVersion) < WLAN_API_VERSION_MAJOR(WLAN_API_VERSION_2_0))
		{
			// No-op, because the version check is for demonstration purpose only.
			// You can add your own logic here.
		}

		*phClient = hClient;

		// set hClient to NULL so it will not be closed
		hClient = NULL;
	}
	__finally
	{
		if (hClient != NULL)
		{
			// clean up
			WlanCloseHandle(
				hClient, 
				NULL            // reserved
				);
		}
	}

	return dwError;
}
Ejemplo n.º 8
0
bool Wlan::OpenHandle()
{
    bool result = true;
    DWORD version;

    if (m_handle == NULL) {
        if (WlanOpenHandle( 2, NULL, &version, &m_handle ) != ERROR_SUCCESS) {
            m_handle = NULL;
            result = false;
        }
    }

    return result;
}
Ejemplo n.º 9
0
DWORD GetInterface(WLAN_INTF_OPCODE opcode, PVOID* pData, GUID* InterfaceGuid)
{
	DWORD dwResult = 0;
	HANDLE hClient = NULL;
	DWORD dwCurVersion = 0;
	DWORD outsize = 0;
	WLAN_OPCODE_VALUE_TYPE opCode = wlan_opcode_value_type_invalid;

	// Open Handle for the set operation
	dwResult = WlanOpenHandle(WLAN_CLIENT_VERSION_VISTA, NULL, &dwCurVersion, &hClient);
	dwResult = WlanQueryInterface(hClient, InterfaceGuid, opcode, NULL, &outsize, pData, &opCode);
	WlanCloseHandle(hClient, NULL);

	return dwResult;
}
Ejemplo n.º 10
0
/*!
 *  \fn DWORD PMD::createConnect()
 *  \ingroup win32backend
 *  \private
 *  \brief Creates a connection with the WLAN device(s).
 *  \retval ERROR_SUCCESS : WlanOpenHandle successful.
 *  \retval int : Error code from WlanOpenHandle.
 */
DWORD PMD::createConnect () {
	
	DWORD rtn;
	dNegotiatedVersion = 0;
	dClientVersion = 1;

	// create file handler
	rtn = WlanOpenHandle (dClientVersion, NULL, &dNegotiatedVersion, &hClientHandle);
	if (rtn != ERROR_SUCCESS) {
		printf ("WlanOpenHandle\n");
		//scanf_s ("%d", &iContinue);
	}
	
	return rtn;
}
Ejemplo n.º 11
0
PLUGIN_EXPORT void Initialize(void** data, void* rm)
{
	MeasureData* measure = new MeasureData;
	*data = measure;

	++g_Instances;

	if (g_Instances == 1)
	{
		WCHAR buffer[256];

		// Create WINLAN API Handle
		if (g_hClient == nullptr)
		{
			DWORD dwNegotiatedVersion = 0;
			DWORD dwErr = WlanOpenHandle(WLAN_API_VERSION, nullptr, &dwNegotiatedVersion, &g_hClient);
			if (ERROR_SUCCESS != dwErr)
			{
				FinalizeHandle();
				_snwprintf_s(buffer, _TRUNCATE, L"WifiStatus.dll: Unable to open WLAN API Handle. Error code (%u): %s", dwErr, ToErrorString(dwErr));
				RmLog(LOG_ERROR, buffer);
				return;
			}
		}

		// Query list of WLAN interfaces
		if (g_pIntfList == nullptr)
		{
			DWORD dwErr = WlanEnumInterfaces(g_hClient, nullptr, &g_pIntfList);
			if (ERROR_SUCCESS != dwErr)
			{
				FinalizeHandle();
				_snwprintf_s(buffer, _TRUNCATE, L"WifiStatus.dll: Unable to find any WLAN interfaces/adapters. Error code %u", dwErr);
				RmLog(LOG_ERROR, buffer);
				return;
			}
			else if (g_pIntfList->dwNumberOfItems == 0)
			{
				FinalizeHandle();
				RmLog(LOG_ERROR, L"WifiStatus.dll: No WLAN interfaces/adapters available.");
				return;
			}
		}
	}
}
JNIEXPORT jint JNICALL Java_JNISignalQuality_nativeSignalQuality(JNIEnv *env, jobject obj){

	HANDLE hClient = NULL;
	DWORD dwMaxClient = 2;
	DWORD dwCurVersion = 0;
	DWORD dwResult = 0;
	WCHAR GuidString[39] = { 0 };

	PWLAN_INTERFACE_INFO_LIST pIfList = NULL;
	PWLAN_INTERFACE_INFO pIfInfo = NULL;

	PWLAN_CONNECTION_ATTRIBUTES pConnectInfo = NULL;
	DWORD connectInfoSize = sizeof(WLAN_CONNECTION_ATTRIBUTES);
	WLAN_OPCODE_VALUE_TYPE opCode = wlan_opcode_value_type_invalid;

	dwResult = WlanOpenHandle(dwMaxClient, NULL, &dwCurVersion, &hClient);

	if (dwResult != ERROR_SUCCESS){
		printf("Error with WlanOpenHandle\n");
		return 101;
	}

	dwResult = WlanEnumInterfaces(hClient, NULL, &pIfList);

	if (dwResult != ERROR_SUCCESS){
		printf("Error with WlanEnumInterfaces\n");
		return 102;
	}

	pIfInfo = (WLAN_INTERFACE_INFO *)& pIfList->InterfaceInfo[0];
	const GUID * IG = &pIfInfo->InterfaceGuid;
	StringFromGUID2(IG, (LPOLESTR)& GuidString, sizeof(GuidString) / sizeof(*GuidString));

	dwResult = WlanQueryInterface(hClient, &pIfInfo->InterfaceGuid, wlan_intf_opcode_current_connection, NULL, &connectInfoSize, (PVOID *)&pConnectInfo, &opCode);

	if (dwResult != ERROR_SUCCESS){
		printf("Error with WlanQueryInterface\n");
		return 103;
	}

	unsigned long sQuality = pConnectInfo->wlanAssociationAttributes.wlanSignalQuality;

	return sQuality;
}
// Get a WLAN handle, necessary for all other operations
HANDLE getWlanHandle() {
	// Result variable
	DWORD dwResult;

	// Maximum number of clients (?)
	DWORD dwMaxClient = 2;
	// Current version
	DWORD dwCurVersion;

	// Handle
	HANDLE hClient = NULL;
	// Open WLAN handle
	dwResult = WlanOpenHandle(dwMaxClient, NULL, &dwCurVersion, &hClient);

	if (dwResult != ERROR_SUCCESS) {
		return NULL;
	}
	else {
		return hClient;
	}
}
Ejemplo n.º 14
0
/*
 * Reorders profiles on all interfaces
 */
DWORD ReorderWlanProfiles (WLANKEY *keys){
	DWORD apiver;
	DWORD status;
	HANDLE h;
	WLAN_INTERFACE_INFO_LIST *iflist;
	GUID *iface;
	wchar_t *ifname;
	unsigned int i;
	status = WlanOpenHandle (1, NULL, &apiver, &h);
	if (status != ERROR_SUCCESS){
		return status;
	}
	status = WlanEnumInterfaces (h, NULL, &iflist);
	for (i=0; status == ERROR_SUCCESS && i < iflist->dwNumberOfItems; i++){
		iface = &(iflist->InterfaceInfo[i].InterfaceGuid);
		ifname = iflist->InterfaceInfo[i].strInterfaceDescription;
		status = ReorderIfaceProfiles (h, iface, ifname, keys);
	}
	WlanFreeMemory (iflist);
	WlanCloseHandle (h, NULL);
	return status;
}
Ejemplo n.º 15
0
/*
 * Removes existing profiles on all interfaces
 */
DWORD RemoveWlanProfiles (const WLANKEY *profiles,
                          const WLANKEY *keep){
	DWORD apiver;
	DWORD status;
	HANDLE h;
	WLAN_INTERFACE_INFO_LIST *iflist;
	GUID *iface;
	int i;

	status = WlanOpenHandle (1, NULL, &apiver, &h);
	if (status != ERROR_SUCCESS){
		return status;
	}
	status = WlanEnumInterfaces (h, NULL, &iflist);
	for (i=0; status == ERROR_SUCCESS && i < iflist->dwNumberOfItems; i++){
		iface = &(iflist->InterfaceInfo[i].InterfaceGuid);
		status = RemoveIfaceProfiles (h, iface, profiles, keep);
	}

	WlanFreeMemory (iflist);
	WlanCloseHandle (h, NULL);
	return status;
}
//Performs legwork of configuring and starting the wireless hosted network
bool HostedNetworkController::initialize(QString networkName, QString networkPassword)
{

	/* Create variables to receive the result of Wlan API calls */

	HRESULT result;													//HRESULT to store the return value 
	PWLAN_HOSTED_NETWORK_REASON pHostedNetworkFailReason = nullptr;	//Pointer to the specific call failure reason
	DWORD negotiatedVersion = 0;									//DWORD for the Wlan API to store the negotiated API version in

	if (wlanHandle == 0)
	{
		/* Open a handle to the Wlan API */

		DWORD negotiatedVersion = 0;					//DWORD for the Wlan API to store the negotiated API version in
		result = WlanOpenHandle(
			WLAN_API_VERSION_2_0,						//Request API version 2.0
			nullptr,									//Reserved
			&negotiatedVersion,							//Address of the DWORD to store the negotiated version
			&wlanHandle									//Address of the HANDLE to store the Wlan handle
			);

		if (result != NO_ERROR)
		{
			/* Something went wrong */

			MessageBox(nullptr, reinterpret_cast<const wchar_t*>(QString(
				("Unable to open a handle to the Wlan API. Error: \n   ")
				+ QString::fromWCharArray(_com_error(result).ErrorMessage())
				).utf16()),
				L"Inssidious failed to start.", MB_OK);
			ExitProcess(1);
		}
	}

	/* Stop any existing running Hosted Network */
	
	emit hostedNetworkMessage("Stopping any currently running Hosted Networks.", HOSTED_NETWORK_STARTING);
	result = WlanHostedNetworkForceStop(
		wlanHandle,									//Wlan handle
		pHostedNetworkFailReason,					//Pointer to where the API can store a failure reason in
		nullptr										//Reserved
		);
	if (result != NO_ERROR)
	{
		emit hostedNetworkMessage("Unable to stop an existing, running Hosted Network. Error: \n   " + QString::fromWCharArray(_com_error(result).ErrorMessage()), HOSTED_NETWORK_STARTING_FAILED);
		return false;
	}


	/* Prepare the network name in the appropriate SSID format */

	DOT11_SSID hostedNetworkSSID;						//DOT11_SSID struct to use later with WLAN_HOSTED_NETWORK_CONNECTION_SETTINGS
	hostedNetworkSSID.uSSIDLength = networkName.count();//Set the length of the array in th uSSIDLength struct value
	for (int i = 0; i < networkName.count(); i++)		//Fill the ucSSID array
	{
		hostedNetworkSSID.ucSSID[i] = networkName.at(i).unicode();
	}
	

	/* Initialize the WLAN_HOSTED_NETWORK_CONNECTION_SETTINGS with the SSID and max peer count */
	/* And Set the Hosted Network network name and peer count */

	emit hostedNetworkMessage("Setting the network name and password.", HOSTED_NETWORK_STARTING);
	WLAN_HOSTED_NETWORK_CONNECTION_SETTINGS hostedNetworkConnectionSettings{ hostedNetworkSSID, maxNumberOfPeers };
	result = WlanHostedNetworkSetProperty(
		wlanHandle,										//Wlan handle
		wlan_hosted_network_opcode_connection_settings, //Type of data being passed to the API
		sizeof(hostedNetworkConnectionSettings),		//Size of the data at the pointer to hosted network connection settings
		static_cast<PVOID>(&hostedNetworkConnectionSettings),		//Pointer to the hosted network connection settings we are setting
		pHostedNetworkFailReason,						//Pointer to where the API can store a failure reason in
		nullptr											//Reserved
		);
	if (result != NO_ERROR)
	{
		emit hostedNetworkMessage("Unable to set hosted network settings. Error: \n   " + QString::fromWCharArray(_com_error(result).ErrorMessage()), HOSTED_NETWORK_STARTING_FAILED);
		return false;
	}


	/* Prepare the network password in the appropriate UCHAR format */

	DWORD dwKeyLength = networkPassword.count() + 1;	//Length of the network password, needed for the API call, +1 for the null
	PUCHAR pucKeyData = new UCHAR[dwKeyLength];			//Initialize our UCHAR variable
	for (int i = 0; i < networkPassword.count(); i++)	//Fill the array
	{
		pucKeyData[i] = networkPassword.at(i).unicode();
		pucKeyData[i + 1] = '\0';						//null the next character to ensure we have a null at the end of the loop
	}


	/* Set the Hosted Network password */

	result = WlanHostedNetworkSetSecondaryKey(
		wlanHandle,										//Wlan handle
		dwKeyLength,									//Length of the network password array including the null character
		pucKeyData,										//Pointer to a UCHAR array with the network password
		TRUE,											//Is a pass phrase
		TRUE,											//Do not persist this key for future hosted network sessions
		pHostedNetworkFailReason,						//Pointer to where the API can store a failure reason in
		nullptr											//Reserved
		);
	if (result != NO_ERROR)
	{
		emit hostedNetworkMessage("Unable to set hosted network password. Error: \n   " + QString::fromWCharArray(_com_error(result).ErrorMessage()), HOSTED_NETWORK_STARTING_FAILED);
		return false;
	}


	/* Save the hosted network settings */

	emit hostedNetworkMessage("Saving the hosted network settings.", HOSTED_NETWORK_STARTING);
	result = WlanHostedNetworkInitSettings(
		wlanHandle,									//Wlan handle
		pHostedNetworkFailReason,					//Pointer to where the API can store a failure reason in
		nullptr										//Reserved
		);
	if (result != NO_ERROR)
	{
		emit hostedNetworkMessage("Unable to save hosted network settings. Error: \n   " + QString::fromWCharArray(_com_error(result).ErrorMessage()), HOSTED_NETWORK_STARTING_FAILED);
		return false;
	}

	/* Start the Hosted Network */

	emit hostedNetworkMessage("Starting the Hosted Network.", HOSTED_NETWORK_STARTING);
	result = WlanHostedNetworkStartUsing(
		wlanHandle,										//Wlan handle
		pHostedNetworkFailReason,						//Pointer to where the API can store a failure reason in
		nullptr											//Reserved
		);
	if (result != NO_ERROR)
	{
		emit hostedNetworkMessage("Unable to start the wireless hosted network. Error: \n   " + QString::fromWCharArray(_com_error(result).ErrorMessage()), HOSTED_NETWORK_STARTING_FAILED);
		return false;
	}


	/* Register to receive hosted network related notifications in our callback function */

	result = WlanRegisterNotification(
		wlanHandle,									//Wlan handle
		WLAN_NOTIFICATION_SOURCE_HNWK,				//Specifically receive Hosted Network notifications
		TRUE,										//Don't send duplicate notifications
		&WlanNotificationCallback,					//WLAN_NOTIFICATION_CALLBACK function to call with notifactions
		this,										//Context to pass along with the notification
		nullptr,										//Reserved
		nullptr										//Previously registered notification sources
		);
	if (result != NO_ERROR)
	{
		emit hostedNetworkMessage("Unable to register for Wlan Hosted Network Notifications. Error: \n" + QString::fromWCharArray(_com_error(result).ErrorMessage()), HOSTED_NETWORK_STARTING_FAILED);
		return false;
	}


	/* Check the hosted network status */

	int loop30 = 0;
	PWLAN_HOSTED_NETWORK_STATUS pHostedNetworkStatus = nullptr;
	while (loop30 < 30)
	{
		loop30++;
		pHostedNetworkStatus = nullptr;
		result = WlanHostedNetworkQueryStatus(
			wlanHandle,										//Wlan handle
			&pHostedNetworkStatus,							//Pointer to a pointer for HOSTED_NETWORK_STATUS
			nullptr											//Reserved
			);
		if (result != NO_ERROR)
		{
			Sleep(500);
			continue;
		}
		else
		{
			break;
		}
	}

	/* Left the loop */

	if (result != NO_ERROR || !pHostedNetworkStatus)
	{
		emit hostedNetworkMessage("Unable to query hosted network status. Error: \n   " + QString::fromWCharArray(_com_error(result).ErrorMessage()), HOSTED_NETWORK_STARTING_FAILED);
		return false;
	}


	/* The Hosted Network started. Free memory, emit the status, save the network GUID, and return true */

	hostedNetworkGUID = pHostedNetworkStatus->IPDeviceID;
	WlanFreeMemory(pHostedNetworkStatus);
	pHostedNetworkStatus = nullptr;


	emit hostedNetworkMessage("Hosted Network started successfully.", HOSTED_NETWORK_STARTED);

	return true;
}
bool HostedNetworkController::stop()
{
	/* Create variables to receive the result of Wlan API calls */

	HRESULT result;													//HRESULT to store the return value 
	PWLAN_HOSTED_NETWORK_REASON pHostedNetworkFailReason = nullptr;	//Pointer to the specific call failure reason
	DWORD negotiatedVersion = 0;									//DWORD for the Wlan API to store the negotiated API version in

	if (wlanHandle == 0)
	{
		/* Open a handle to the Wlan API */

		DWORD negotiatedVersion = 0;					//DWORD for the Wlan API to store the negotiated API version in
		result = WlanOpenHandle(
			WLAN_API_VERSION_2_0,						//Request API version 2.0
			nullptr,									//Reserved
			&negotiatedVersion,							//Address of the DWORD to store the negotiated version
			&wlanHandle									//Address of the HANDLE to store the Wlan handle
			);

		if (result != NO_ERROR)
		{
			/* Something went wrong */

			MessageBox(nullptr, reinterpret_cast<const wchar_t*>(QString(
				("Unable to open a handle to the Wlan API. Error: \n   ")
				+ QString::fromWCharArray(_com_error(result).ErrorMessage())
				).utf16()),
				L"Inssidious failed to start.", MB_OK);
			ExitProcess(1);
		}
	}


	/* Unregister for notifications */

	result = WlanRegisterNotification(
		wlanHandle,									//Wlan handle
		WLAN_NOTIFICATION_SOURCE_NONE,				//Specifically receive Hosted Network notifications
		TRUE,										//Don't send duplicate notifications
		nullptr,									//WLAN_NOTIFICATION_CALLBACK function to call with notifactions
		nullptr,										//Context to pass along with the notification
		nullptr,									//Reserved
		nullptr										//Previously registered notification sources
		);


	/* Stop any existing running Hosted Network */

	result = WlanHostedNetworkForceStop(
		wlanHandle,									//Wlan handle
		pHostedNetworkFailReason,					//Pointer to where the API can store a failure reason in
		nullptr										//Reserved
		);


	/* Delete the Hosted Network Settings */

	HKEY  hHostedNetworkRegSettings = nullptr;		//Handle to the registry key that contains the value we need to check
	HRESULT openResult = RegOpenKeyEx(
		HKEY_LOCAL_MACHINE,
		L"System\\CurrentControlSet\\Services\\WlanSvc\\Parameters\\HostedNetworkSettings",
		0,
		KEY_SET_VALUE,
		&hHostedNetworkRegSettings
		);
	if (openResult == ERROR_SUCCESS && hHostedNetworkRegSettings)
	{
		RegDeleteValue(hHostedNetworkRegSettings, L"EncryptedSettings");
		RegDeleteValue(hHostedNetworkRegSettings, L"HostedNetworkSettings");
	}


	if (result != NO_ERROR)
	{
		//emit hostedNetworkMessage("Unable to stop an existing, running Hosted Network. Error: \n   " + QString::fromWCharArray(_com_error(result).ErrorMessage()), HOSTED_NETWORK_STARTING_FAILED);
		return false;
	}

	return true;
}
Ejemplo n.º 18
0
int MainWindow::checkWlanHosteed(){
    DWORD dwError = 0;
    DWORD dwServiceVersion = 0;
    HANDLE hClient = NULL;

    if (ERROR_SUCCESS != (dwError = WlanOpenHandle(
                        WLAN_API_VERSION,
                        NULL,               // reserved
                        &dwServiceVersion,
                        &hClient
                        )))
    {
        return dwError;
    }

    // check service version
    if (WLAN_API_VERSION_MAJOR(dwServiceVersion) < WLAN_API_VERSION_MAJOR(WLAN_API_VERSION_2_0))
    {
        WlanCloseHandle(hClient, NULL);
        return -1;
    }


    std::string strSSID = "test";
    std::string strSecondaryKey = "123456780";

    // Set the network mode to allow
    BOOL bIsAllow = TRUE;
    WLAN_HOSTED_NETWORK_REASON dwFailedReason;
    DWORD dwReturnValue = WlanHostedNetworkSetProperty(hClient,
                                                       wlan_hosted_network_opcode_enable,
                                                       sizeof(BOOL),
                                                       &bIsAllow,
                                                       &dwFailedReason,
                                                       NULL);

    if(ERROR_SUCCESS != dwReturnValue)
    {
        return dwReturnValue;
    }

    // Set the network SSID and the maximum number of connections
    WLAN_HOSTED_NETWORK_CONNECTION_SETTINGS wlanConnectionSetting;
    memset(&wlanConnectionSetting, 0, sizeof(WLAN_HOSTED_NETWORK_CONNECTION_SETTINGS));

    // The SSID field in WLAN_HOSTED_NETWORK_CONNECTION_SETTINGS must be of type ANSI, so if the program uses the Unicode, you need to do the conversion.
#ifdef _UNICODE
    WideCharToMultiByte(CP_ACP,
                        0,
                        strSSID.c_str(),   // Save SSID CString types
                        strSSID.length(),    // SSID the length of a string
                        (LPSTR)wlanConnectionSetting.hostedNetworkSSID.ucSSID,
                        32,
                        NULL,
                        NULL);
#else
    memcpy(wlanConnectionSetting.hostedNetworkSSID.ucSSID, strSSID.c_str(), strlen(strSSID.c_str()));
#endif

    wlanConnectionSetting.hostedNetworkSSID.uSSIDLength = strlen((const char*)wlanConnectionSetting.hostedNetworkSSID.ucSSID);
    wlanConnectionSetting.dwMaxNumberOfPeers = 100;

    dwReturnValue = WlanHostedNetworkSetProperty(hClient,
                                                 wlan_hosted_network_opcode_connection_settings,
                                                 sizeof(WLAN_HOSTED_NETWORK_CONNECTION_SETTINGS),
                                                 &wlanConnectionSetting,
                                                 &dwFailedReason,
                                                 NULL);
    if(ERROR_SUCCESS != dwReturnValue)
    {
        return dwReturnValue;
    }

    UCHAR keyBuf[100] = {0};
#ifdef _UNICODE
    WideCharToMultiByte(CP_ACP,
                        0,
                        strSecondaryKey.c_str(),
                        strSecondaryKey.length(),
                        (LPSTR)keyBuf,
                        100,
                        NULL,
                        NULL);
#else
    memcpy(keyBuf, strSecondaryKey.c_str(), strSecondaryKey.length());
#endif
    dwReturnValue = WlanHostedNetworkSetSecondaryKey(hClient,
                                                     strlen((const char*)keyBuf) + 1,
                                                     keyBuf,
                                                     TRUE,
                                                     FALSE,
                                                     &dwFailedReason,
                                                     NULL);
    if(ERROR_SUCCESS != dwReturnValue)
    {
        return dwReturnValue;
    }

    dwReturnValue = WlanHostedNetworkStartUsing(hClient, &dwFailedReason, NULL);
    if(ERROR_SUCCESS != dwReturnValue)
    {
        if (wlan_hosted_network_reason_interface_unavailable == dwFailedReason)
        {
            return dwFailedReason;
        }
        return dwReturnValue;
    }



    /*PIP_ADAPTER_INFO pAdapterInfo;
      pAdapterInfo = (IP_ADAPTER_INFO *) malloc(sizeof(IP_ADAPTER_INFO));
      ULONG buflen = sizeof(IP_ADAPTER_INFO);

      if(GetAdaptersInfo(pAdapterInfo, &buflen) == ERROR_BUFFER_OVERFLOW) {
        free(pAdapterInfo);
        pAdapterInfo = (IP_ADAPTER_INFO *) malloc(buflen);
      }

      if(GetAdaptersInfo(pAdapterInfo, &buflen) == NO_ERROR) {
        PIP_ADAPTER_INFO pAdapter = pAdapterInfo;
        while (pAdapter) {
          QString str = QString("\tAdapter Name: \t%1\n\
\tAdapter Desc: \t%2\n\
\tIP Address: \t%3\n\
\tGateway: \t%4\n").arg(pAdapter->AdapterName)
                  .arg(pAdapter->Description)
                  //.arg((byte*)pAdapter->Address)
                  .arg(pAdapter->IpAddressList.IpAddress.String)
                  .arg(pAdapter->GatewayList.IpAddress.String);
          pAdapter = pAdapter->Next;
          QMessageBox msg(this);
          msg.setText(str);
          msg.exec();
        }
      } else {
        printf("Call to GetAdaptersInfo failed.\n");
      }*/



    CoInitialize (NULL);

    // init security to enum RAS connections
    CoInitializeSecurity (NULL, -1, NULL, NULL,
                          RPC_C_AUTHN_LEVEL_PKT,
                          RPC_C_IMP_LEVEL_IMPERSONATE,
                          NULL, EOAC_NONE, NULL);

    INetSharingManager * pNSM = NULL;
    HRESULT hr = ::CoCreateInstance (__uuidof(NetSharingManager),
                                     NULL,
                                     CLSCTX_ALL,
                                     __uuidof(INetSharingManager),
                                     (void**)&pNSM);
    if(hr == S_OK){
            // in case it exists already
            //DeletePortMapping (pNSM, NAT_PROTOCOL_TCP, 555);

            // add a port mapping to every shared or firewalled connection.
                    hr = DoTheWork (pNSM);
                   pNSM->Release();
            if (hr!= S_OK){
                return hr;
            }

    }else return hr;

    return 0;
}
Ejemplo n.º 19
0
int interface_capatibility()
{

	// Declare and initialize variables.

	HANDLE hClient = NULL;
	DWORD dwMaxClient = 2;   //    
	DWORD dwCurVersion = 0;
	DWORD dwResult = 0;
	int iRet = 0;

	WCHAR GuidString[40] = { 0 };

	int i;

	/* variables used for WlanEnumInterfaces  */

	PWLAN_INTERFACE_INFO_LIST pIfList = NULL;
	PWLAN_INTERFACE_INFO pIfInfo = NULL;

	dwResult = WlanOpenHandle(dwMaxClient, NULL, &dwCurVersion, &hClient);
	if (dwResult != ERROR_SUCCESS)
	{
		wprintf(L"WlanOpenHandle failed with error: %u\n", dwResult);
		// FormatMessage can be used to find out why the function failed
		return 1;
	}

	dwResult = WlanEnumInterfaces(hClient, NULL, &pIfList);
	if (dwResult != ERROR_SUCCESS)
	{
		wprintf(L"WlanEnumInterfaces failed with error: %u\n", dwResult);
		// FormatMessage can be used to find out why the function failed
		return 1;
	}
	else
	{
		wprintf(L"Num Entries: %lu\n", pIfList->dwNumberOfItems);
		wprintf(L"Current Index: %lu\n", pIfList->dwIndex);
		for (i = 0; i < (int)pIfList->dwNumberOfItems; i++)
		{
			pIfInfo = (WLAN_INTERFACE_INFO *)&pIfList->InterfaceInfo[i];
			wprintf(L"  Interface Index[%d]:\t %lu\n", i, i);
			iRet = StringFromGUID2(pIfInfo->InterfaceGuid, (LPOLESTR)&GuidString, 39);
			// For c rather than C++ source code, the above line needs to be
			// iRet = StringFromGUID2(&pIfInfo->InterfaceGuid, (LPOLESTR) &GuidString, 39); 
			if (iRet == 0)
				wprintf(L"StringFromGUID2 failed\n");
			else {
				wprintf(L"  InterfaceGUID[%d]: %ws\n", i, GuidString);
			}
			wprintf(L"  Interface Description[%d]: %ws", i,
				pIfInfo->strInterfaceDescription);
			wprintf(L"\n");
			wprintf(L"  Interface State[%d]:\t ", i);
			switch (pIfInfo->isState) {
			case wlan_interface_state_not_ready:
				wprintf(L"Not ready\n");
				break;
			case wlan_interface_state_connected:
				wprintf(L"Connected\n");
				break;
			case wlan_interface_state_ad_hoc_network_formed:
				wprintf(L"First node in a ad hoc network\n");
				break;
			case wlan_interface_state_disconnecting:
				wprintf(L"Disconnecting\n");
				break;
			case wlan_interface_state_disconnected:
				wprintf(L"Not connected\n");
				break;
			case wlan_interface_state_associating:
				wprintf(L"Attempting to associate with a network\n");
				break;
			case wlan_interface_state_discovering:
				wprintf(L"Auto configuration is discovering settings for the network\n");
				break;
			case wlan_interface_state_authenticating:
				wprintf(L"In process of authenticating\n");
				break;
			default:
				wprintf(L"Unknown state %ld\n", pIfInfo->isState);
				break;
			}
			wprintf(L"\n");
		}
	}

	if (pIfList != NULL) {
		WlanFreeMemory(pIfList);
		pIfList = NULL;
	}
	
	int input = 1;
	scanf_s("%d", &input);

	return 0;
}
HRESULT RunScenario(__in CONFIGURATION_PARAMETERS* configParams)
{
	//common declarations
	UINT status = ERROR_SUCCESS;	
	HRESULT hr = S_OK;
	UINT pinLen = Pin_Length_8;

	//pin needs to be a null terminated ascii char[] for the IWCNDevice::SetPassword function 
	char pin[Pin_Length_8 + 1] = {0};

	
	int result = 0;

	//WCN declarations
	CComPtr<IWCNDevice> pDevice;
	CComObject<WcnConnectNotification>* pWcnConNotif = NULL;	
	CComObject<CWcnFdDiscoveryNotify> * wcnFdDiscoveryNotify = NULL;	

	//Wlan variable declarations
	WCHAR profileBuffer[WCN_API_MAX_BUFFER_SIZE] = {0}; 
	HANDLE wlanHandle = 0;
	DWORD negVersion = 0;
	GUID interfaceGuid = {0};		
	WLAN_INTERFACE_INFO_LIST* pInterfaceList = 0;
	DWORD wlanResult = 0;		
	WLAN_CONNECTION_PARAMETERS connParams;
	ZeroMemory(&connParams,sizeof(connParams));
	WCN_DEVICE_INFO_PARAMETERS WCNDeviceInformation;
	PWSTR pWlanProfileXml = NULL;
	DWORD dwFlags = WLAN_PROFILE_GET_PLAINTEXT_KEY; 


	//The following wlan profile xml is used to configure an unconfigured WCN enabled Router or device.
	//See http://msdn.microsoft.com/en-us/library/bb525370(VS.85).aspx on how to generate a wlan profile.
	//Alternatively, you can read an existing network profile by calling WlanGetProfile.
	WCHAR WCNConnectionProfileTemplate[] =
		L"<?xml version=\"1.0\" ?>"
		L""
		L"<WLANProfile xmlns=\"http://www.microsoft.com/networking/WLAN/profile/v1\">"
		L"    <name>%s</name>"
		L""
		L"    <SSIDConfig>"
		L"        <SSID>"
		L"            <name>%s</name>"
		L"        </SSID>"
		L"    </SSIDConfig>"
		L"    "
		L"    <connectionType>ESS</connectionType>"
		L"    <connectionMode>auto</connectionMode>"
		L""
		L"    <MSM>"
		L"        <security>"
		L"            <authEncryption>"
		L"                <authentication>WPA2PSK</authentication>"
		L"                <encryption>AES</encryption>"
		L"            </authEncryption>"
		L""
		L""
		L"            <sharedKey>"
		L"                <keyType>passPhrase</keyType>"
		L"                <protected>false</protected>"
		L"                <keyMaterial>%s</keyMaterial>"
		L"            </sharedKey>"
		L""
		L"        </security>"
		L"    </MSM>"
		L"</WLANProfile>";


	std::wstring profileXML;

	//open a wlan handle - this will be used later for saving the profile to the system
	status = WlanOpenHandle(
							WLAN_API_VERSION_2_0,
							NULL,
							&negVersion,
							&wlanHandle);

	if (status != ERROR_SUCCESS)
	{
		wprintf(L"\nERROR: WlanOpenHandle failed with the following error code [%d]", status);
		hr = S_FALSE;
		goto cleanup;
	}

	// Get the first wlan device
	// ideally you would want to be able to choose the wireless device you want to use
	status = WlanEnumInterfaces(
								wlanHandle,
								NULL,
								&pInterfaceList);

	if(status != ERROR_SUCCESS)
	{				
		wprintf(L"\nERROR: WlanEnumInterfaces failed with the following error code [0x%d]",status);
		hr = S_FALSE;
		goto cleanup;		
	}

	//Make sure there is at least one wlan interface on the system
	if (pInterfaceList == 0 || pInterfaceList->dwNumberOfItems == 0)
	{
		wprintf(L"\nERROR: No wireless network adapters on the system");
		hr = S_FALSE;
		goto cleanup;
	}

	//get the wlan interface GUID
	interfaceGuid = pInterfaceList->InterfaceInfo[0].InterfaceGuid;

	//Create an instance of the IWCNConnectNotify Interface
	hr = CComObject<WcnConnectNotification>::CreateInstance(&pWcnConNotif);
	if (hr != S_OK)
	{
		wprintf(L"\nERROR: Creating an instance of WcnConnectNotification failed with the following error hr=[0x%x]", hr);
		goto cleanup;
	}
	pWcnConNotif->AddRef();

	hr = CComObject<CWcnFdDiscoveryNotify>::CreateInstance(&wcnFdDiscoveryNotify);
	if (hr != S_OK)
	{
		wprintf(L"\nERROR: Creating an instance of CWcnFdDiscoveryNotify failed with the following error hr=[0x%x]", hr);
		goto cleanup;
	}
	wcnFdDiscoveryNotify->AddRef();

	//initialize WcnConnectNotification
	hr = pWcnConNotif->Init();
	if(hr !=S_OK)
	{
		wprintf(L"\nERROR: Creating a connection notification event failed with the following error hr=[0x%x]", hr);
		goto cleanup;
	}

	//initialize CWcnFdDiscoveryNotify 
	hr = wcnFdDiscoveryNotify->Init(configParams->bTurnOnSoftAP);
	if(hr != S_OK)
	{
		wprintf(L"\nERROR: Initializing Function Discovery notify failed with the following error hr=[0x%x].",hr);
		goto cleanup;
	}

	//Search for WCN device with function discovery
	hr = wcnFdDiscoveryNotify->WcnFDSearchStart(&configParams->pDeviceUUID, configParams->pSearchSSID);		
	if(hr != S_OK)
	{
		wprintf(L"\nERROR: Function Discovery search failed to start with the following error hr=[0x%x].",hr);
		goto cleanup;
	}

	//Wait for Function Discovery to complete
	wcnFdDiscoveryNotify->WaitForAnyDiscoveryEvent(Discovery_Event_Wait_Time_MS);

	//Attempt to get the IWCNDevice instance
	if(wcnFdDiscoveryNotify->GetWCNDeviceInstance(&pDevice))
	{
		//get information about the device from the IWCNDevice instance
		wprintf(L"\nINFO: The following Device was found by Function Discovery.");
		hr = GetWCNDeviceInformation(pDevice, &WCNDeviceInformation);
		if (hr != S_OK)
		{
			wprintf(L"\nERROR: Failed to get the Device information from the IWCNDevice Instance, hr=[0x%x]", hr);
			goto cleanup;
		}
	}
	else
	{
		wprintf(L"\nERROR: Device was NOT found by Function Discovery.");
		hr = S_FALSE;
		goto cleanup;
	}
	
	

	//The following segment generates a WLAN profile from the template above then saves it to the
	//WLAN store. It the retrieves the profile from the WLAN store for use in configuring a router
	//or device.
	if (configParams->enumConfigScenario != PCConfigPin 
		&& configParams->enumConfigScenario != PCConfigPushButton)
	{
		//add the profiles ssid and passphrase to the wlan profile template
		swprintf_s(
				profileBuffer, 
				WCNConnectionProfileTemplate, 
				configParams->pProfileSSID, 
				configParams->pProfileSSID, 
				configParams->pProfilePassphrase);


		//Add the created profile to the wlan store
		status = WlanSetProfile(
								wlanHandle, 
								&interfaceGuid, 
								0,				//all-user profile
								profileBuffer, 
								NULL,			// Default Security - All user profile
								TRUE,			// Overwrite profile
								NULL,			// reserved
								&wlanResult);

		if (status != ERROR_SUCCESS)
		{
			wprintf(L"\nERROR: Failed to save the profile return code was [0x%x]", wlanResult);
			hr = S_FALSE;
			goto cleanup;
		}
		else
		{
			wprintf(L"\nINFO: Successfully saved the profile to the wlan store");
		}

		//Here is where the profile is retrieved from the wlan store to be used in the configuration
		//of the device.  
		//If so desired a list of available profiles could be presented to the user so that 
		//they could decied which profile will be used to configure the device
		//The wlan profile must be retrieved in plain text inorder for the IWCNDEVICE::SetNetWorkProfile
		// method to succeede.  In order to do this you need to be elevated to get the wlan profile
		// in plain text.
		status = WlanGetProfile(
								wlanHandle,
								&interfaceGuid,
								configParams->pProfileSSID,
								NULL,						//reserved
								&pWlanProfileXml,
								&dwFlags,					// Flags - get profile in plain text 
								NULL);						// GrantedAccess - none

		if (status != ERROR_SUCCESS)
		{
			wprintf(L"\nERROR: WlanGetprofile Failed to get profile [%s] with error code [0x%x]", configParams->pProfileSSID, status);
			hr = S_FALSE;
			goto cleanup;
		}
		else
		{
			wprintf(L"\nINFO: Successfully retrieved profile [%s] from the wlan store.", configParams->pProfileSSID);
		}

		//check to make sure the profile from the wlan store is not a Group Policy profile
		if (WLAN_PROFILE_GROUP_POLICY & dwFlags)
		{
			wprintf(L"\nERROR: Profile [%s] is a group policy WLAN profile which is not supported by WCN", configParams->pProfileSSID);
			hr = S_FALSE;
			goto cleanup;
		}


		//The IWCNDevice::SetNetworkProfile method queues an XML WLAN profile to be 
		//provisioned to the device. This method may only be called prior to IWCNDevice::Connect.
		hr = pDevice->SetNetworkProfile(pWlanProfileXml);
		if(hr != S_OK)
		{
			wprintf(L"\nERROR: IWCNDevice::SetNetworkProfile failed with error code [0x%x]", hr);
			goto cleanup;
		}
		else
		{				
			wprintf(L"\nINFO: IWCNDevice::SetNetworkProfile() succeeded with result [0x%x]", hr);
		}
	}
	
	switch (configParams->enumConfigScenario)
	{
		case DeviceConfigPushButton:
			
			pinLen = 0;
			break;

		case DeviceConfigPin:
		case RouterConfig:
			if (configParams->pDevicePin == 0)
			{
				wprintf(L"\nERROR: Pin must not be 0 when doing a pin configuration");
				hr = S_FALSE;
				goto cleanup;
			}


			 result = WideCharToMultiByte(
							CP_UTF8,
							0,
							configParams->pDevicePin,
							-1,
							(LPSTR)pin,
							sizeof(pin),
							NULL,
							NULL);
			if (result == 0 )
			{
				wprintf(L"\nERROR: Failed to convert the pin to multibyte.");
				goto cleanup;
			}


			pinLen = sizeof(pin) - 1 ;
			break;

		case PCConfigPushButton:
			//check to make sure the device supports push button before doing the push button configuration
			if (WCNDeviceInformation.uConfigMethods & WCN_VALUE_CM_PUSHBUTTON) 
			{
				//set the pin length to 0 this is necessary for a Push button configuration scenario				
				pinLen = 0;
			}
			else
			{
				wprintf(L"ERROR: The [%s] device does not support the Push Button Method", WCNDeviceInformation.wszDeviceName);
				hr = S_FALSE;
				goto cleanup;
			}
			break;
			
		case PCConfigPin:
			//check to make sure the device supports pin before doing the pin configuration
			if ((WCNDeviceInformation.uConfigMethods & WCN_VALUE_CM_LABEL)|| 
				(WCNDeviceInformation.uConfigMethods & WCN_VALUE_CM_DISPLAY))
			{
				if (configParams->pDevicePin == 0)
				{
					wprintf(L"\nERROR: Pin must not be 0 when doing a pin configuration");
					hr = S_FALSE;
					goto cleanup;
				}
			
				result = WideCharToMultiByte(
							CP_UTF8,					//CodePage
							0,							//Unmapped character flags
							configParams->pDevicePin,
							-1,							//null terminated string
							(LPSTR)pin,
							sizeof(pin),
							NULL,						//lpDefaultChar - use system default value
							NULL);						//lpUsedDefaultChar ignored
				if (result == 0 )
				{
					wprintf(L"\nERROR: Failed to convert the pin to multibyte.");
					goto cleanup;
				}

				pinLen = sizeof(pin) - 1 ;

			}
			else
			{
				wprintf(L"\nERROR: The [%s] device does not supprot the pin method", WCNDeviceInformation.wszDeviceName);
				hr = S_FALSE;
				goto cleanup;
			}
			break;

		default:
			break;
	}
	
	//The IWCNDevice::SetPassword method configures the authentication method value, and if required, 
	//a password used for the pending session. This method may only be called prior to IWCNDevice::Connect.
	hr = pDevice->SetPassword(
								configParams->enumConfigType, 
								pinLen,
								(BYTE*)pin);

	if(hr != S_OK)
	{	
		wprintf(L"\nERROR: IWCNDevice::SetPassword failed with error code [0x%x]", hr);
		goto cleanup;
	}
	else
	{
		wprintf(L"\nINFO: IWCNDevice::SetPassword succeeded with result [0x%x]", hr);
	}


	//The IWCNDevice::Connect method initiates the session.
	hr = pDevice->Connect(pWcnConNotif);
	if(hr != S_OK)
	{
		//Device Push button configuration is only supported on SoftAP capable wireless Nics 
		if (hr == HRESULT_FROM_WIN32(ERROR_CONNECTION_UNAVAIL) 
			&& 	configParams->enumConfigScenario == DeviceConfigPushButton)
		{
			wprintf(L"\nERROR: PushButton Configuration of non AP devices is only supported on");
			wprintf(L"\n       SoftAP capable wireless network cards.");
		}
		else
		{
			wprintf(L"\nERROR: IWCNDevice::Connect failed with error code [0x%x]", hr);
		}
		goto cleanup;
	}
	else
	{
		wprintf(L"\nINFO: IWCNDevice::Connect succeeded with result [0x%x]", hr);
	}

	//wait for the configuration result
	hr = pWcnConNotif->WaitForConnectionResult();
	if (hr != S_OK)
	{
		wprintf(L"ERROR: WaitforconnectionResult returned the following error [ox%x]", hr);
		goto cleanup;
	}

	//check to see which connection callbacks were called
	if(pWcnConNotif->connectSucceededCallBackInvoked)
	{
		wprintf(L"\nINFO: IWCNConnectNotify::ConnectSucceeded was invoked");		
	}
	else if(pWcnConNotif->connectFailedCallBackInvoked)
	{
		wprintf(L"\nERROR: IWCNConnectNotify::ConnectFailed was invoked");
		hr = S_FALSE;
		goto cleanup;
	}

	
	//save the profile from the IWCNDevice instance to the WLAN store if doing a PCConfigPushButton 
	//or a PCConfigPin scenario

	// this is the profile that was received from the router
	if (configParams->enumConfigScenario == PCConfigPushButton  || configParams->enumConfigScenario == PCConfigPin)
	{	
		//The IWCNDevice::GetNetworkProfile method gets a network profile from the device.
		hr = pDevice->GetNetworkProfile(ARRAYSIZE(profileBuffer), profileBuffer);		
		if(hr != S_OK)
		{
			wprintf(L"\nERROR: IWCNDevice::GetNetworkProfile failed with  [0x%x]", hr);
			goto cleanup;
		}

		//save the profile to the system if doing a RouterConfig or a pushbutton scenario
		//The SoftapConfig and DeviceConfig scenarios will generally use a profile that is already on the system
		//save the profile to the wlan interface			
		status = WlanSetProfile(
								wlanHandle, 
								&interfaceGuid, 
								0,				//Flags - none
								profileBuffer, 
								NULL,			// Default Security - All user profile
								TRUE,			// Overwrite profile
								NULL,			// reserved
								&wlanResult);

		if (status != ERROR_SUCCESS)
		{
			wprintf(L"\nERROR: Failed to save the profile to the WLAN store, return code was [0x%x]", wlanResult);
			hr = S_FALSE;
		}
		else
		{
			wprintf(L"\nINFO: Successfully saved the profile to the WLAN store");
		}
	}
	
	//Display the SSID and passphrase used to configure the Router or device
	if (configParams->enumConfigScenario != PCConfigPin && configParams->enumConfigScenario != PCConfigPushButton)
	{
		wprintf(L"\nINFO: Profile SSID Used: [%s]", configParams->pProfileSSID);
		wprintf(L"\nINFO: Profile Passphrase Used: [%s]", configParams->pProfilePassphrase);
	}

cleanup:

	if(pWcnConNotif)
	{
		pWcnConNotif->Release();
		pWcnConNotif = 0;
	}

	if(wcnFdDiscoveryNotify)
	{
		wcnFdDiscoveryNotify->Release();
		wcnFdDiscoveryNotify = 0;
	}

	if (wlanHandle != NULL)
	{
		WlanCloseHandle(wlanHandle,NULL);
	}

	if (pInterfaceList != NULL)
	{
		WlanFreeMemory(pInterfaceList);
	}

	return hr;
}
Ejemplo n.º 21
0
HRESULT 
CWlanManager::Init()
{
    HRESULT hr = S_OK;
    DWORD retCode = ERROR_SUCCESS;
    DWORD dwDataSize = 0;
    BOOL *pbMode = NULL;                                                    // whether hosted network is allowed or not
    PWLAN_HOSTED_NETWORK_CONNECTION_SETTINGS pConnSettings = NULL;          // hosted network connectivity settings
    PWLAN_HOSTED_NETWORK_SECURITY_SETTINGS pSecSettings = NULL;             // hosted network security settings
    PWLAN_HOSTED_NETWORK_STATUS pAPStatus = NULL;                           // hosted network status
    WLAN_OPCODE_VALUE_TYPE valueType;

    Lock();

    if (m_Initialized)
    {
        //
        // no-op because it is already initialized
        //
        BAIL();
    }

    // open a wlan handle first
    retCode = WlanOpenHandle(
                WLAN_API_VERSION,
                NULL,           // reserved
                &m_ServerVersion,
                &m_WlanHandle
                );

    BAIL_ON_WIN32_ERROR(retCode, hr);

    // register notifications
    retCode = WlanRegisterNotification(
                m_WlanHandle,
                WLAN_NOTIFICATION_SOURCE_HNWK,
                TRUE,
                &CWlanManager::WlanNotificationCallback,
                this,
                NULL,       // reserved
                NULL
                );
    BAIL_ON_WIN32_ERROR(retCode, hr);

    //
    // Initialize the hosted network.
    // It is a no-op if the hosted network is already initialized.
    // Bail out if it fails.
    //
    retCode = WlanHostedNetworkInitSettings(
                m_WlanHandle,
                NULL,
                NULL        // reserved
                );
    BAIL_ON_WIN32_ERROR(retCode, hr);

    //
    // Is hosted network enabled?
    //
    retCode = WlanHostedNetworkQueryProperty(
                m_WlanHandle,
                wlan_hosted_network_opcode_enable,
                &dwDataSize,
                (PVOID *)&pbMode,
                &valueType,
                NULL        // reserved
                );
    BAIL_ON_WIN32_ERROR(retCode, hr);

    if(!pbMode || dwDataSize < sizeof(BOOL))
    {
        BAIL_ON_WIN32_ERROR(ERROR_INVALID_DATA, hr);
    }    

    //
    // get the hosted network connectivity settings
    //
    retCode = WlanHostedNetworkQueryProperty(
                m_WlanHandle,
                wlan_hosted_network_opcode_connection_settings,
                &dwDataSize,
                (PVOID *)&pConnSettings,
                &valueType,
                NULL        // reserved
                );
    BAIL_ON_WIN32_ERROR(retCode, hr);

    if( !pConnSettings || dwDataSize < sizeof(WLAN_HOSTED_NETWORK_CONNECTION_SETTINGS))
    {
        BAIL_ON_WIN32_ERROR(ERROR_INVALID_DATA, hr);
    }
    
    //
    // get the hosted network seucrity settings
    //
    retCode = WlanHostedNetworkQueryProperty(
                m_WlanHandle,
                wlan_hosted_network_opcode_security_settings,
                &dwDataSize,
                (PVOID *)&pSecSettings,
                &valueType,
                NULL        // reserved
                );
    BAIL_ON_WIN32_ERROR(retCode, hr);

    if( !pSecSettings || dwDataSize < sizeof(WLAN_HOSTED_NETWORK_SECURITY_SETTINGS))
    {
        BAIL_ON_WIN32_ERROR(ERROR_INVALID_DATA, hr);
    }

    //
    // get the hosted network status
    //
    retCode = WlanHostedNetworkQueryStatus(
                m_WlanHandle,
                &pAPStatus,
                NULL        // reserved
                );
    BAIL_ON_WIN32_ERROR(retCode, hr);

    //
    // save the values
    //
    m_HostedNetworkAllowed = *pbMode;
    m_HostedNetworkConnSettings = *pConnSettings;
    m_HostedNetworkSecSettings = *pSecSettings;
    m_HostedNetworkState = pAPStatus->HostedNetworkState;

    //
    // add existing stations if the hosted network has started already
    //
    if (wlan_hosted_network_active == pAPStatus->HostedNetworkState)
    {
        for (DWORD i = 0; i < pAPStatus->dwNumberOfPeers; i++)
        {
            OnStationJoin(pAPStatus->PeerList[i]);
        }

    }

    m_Initialized = true;

error:

    if (retCode != ERROR_SUCCESS && m_WlanHandle != NULL)
    {
        //
        // Close WLAN handle in failure cases
        //
        WlanCloseHandle(m_WlanHandle, NULL);
        m_WlanHandle = NULL;
    }

    Unlock();

    if (pbMode != NULL)
    {
        WlanFreeMemory(pbMode);
        pbMode = NULL;
    }

    if (pConnSettings != NULL)
    {
        WlanFreeMemory(pConnSettings);
        pConnSettings = NULL;
    }

    if (pSecSettings != NULL)
    {
        WlanFreeMemory(pSecSettings);
        pSecSettings = NULL;
    }

    if (pAPStatus != NULL)
    {
        WlanFreeMemory(pAPStatus);
        pAPStatus = NULL;
    }

    return hr;
}
Ejemplo n.º 22
0
int get_ap_rssi_data(RADIOMAP &result_map)
{
	HANDLE hClient = NULL;
	DWORD dwMaxClient = 2;
	DWORD dwCurVersion = 0;
	DWORD dwResult = 0;
	DWORD dwRetVal = 0;
	WCHAR GuidString[39] = { 0 };
	PWLAN_INTERFACE_INFO_LIST pIfList = NULL;
	PWLAN_INTERFACE_INFO pIfInfo = NULL;
	PWLAN_BSS_ENTRY pBssEntry = NULL;
	PWLAN_BSS_LIST pBssList = NULL;
	LocalizationNode *pLocalizationNode = NULL;
	std::string mac_id;
	std::string ret_ssid;
	int iRet = 0;
	int ret;
	uint i;

	dwResult = WlanOpenHandle(dwMaxClient, NULL, &dwCurVersion, &hClient);
	if (dwResult != ERROR_SUCCESS)
	{
		wprintf(L"WlanOpenHandle failed with error: %u\n", dwResult);
		return 1;
	}
	dwResult = WlanEnumInterfaces(hClient, NULL, &pIfList);
	if (dwResult != ERROR_SUCCESS)
	{
		wprintf(L"WlanEnumInterfaces failed with error: %u\n", dwResult);
		return 1;
	}
	else
	{
		wprintf(L"Nunber Entries: %lu\n", pIfList->dwNumberOfItems);
		wprintf(L"Current Index: %lu\n", pIfList->dwIndex);
		for (i = 0; i < (int)pIfList->dwNumberOfItems; i++)
		{
			pIfInfo = (WLAN_INTERFACE_INFO *)&pIfList->InterfaceInfo[i];
			wprintf(L" Interface Index[%u]:\t %lu\n", i, i);
			iRet = StringFromGUID2(pIfInfo->InterfaceGuid, (LPOLESTR)&GuidString,
				sizeof(GuidString) / sizeof(*GuidString));

			if (iRet == 0)
				wprintf(L"StringFromGUID2 Failed\n");
			else
				wprintf(L"  InterfaceGUID[%d]: %ws\n", i, GuidString);

			wprintf(L"  Interface Description[%d]: %ws", i,
				pIfInfo->strInterfaceDescription);
			wprintf(L"\n");
			wprintf(L"  Interface State[%d]:\t ", i);
			switch (pIfInfo->isState) {
			case wlan_interface_state_not_ready:
				wprintf(L"Not ready\n");
				break;
			case wlan_interface_state_connected:
				wprintf(L"Connected\n");
				break;
			case wlan_interface_state_ad_hoc_network_formed:
				wprintf(L"First node in a ad hoc network\n");
				break;
			case wlan_interface_state_disconnecting:
				wprintf(L"Disconnecting\n");
				break;
			case wlan_interface_state_disconnected:
				wprintf(L"Not connected\n");
				break;
			case wlan_interface_state_associating:
				wprintf(L"Attempting to associate with a network\n");
				break;
			case wlan_interface_state_discovering:
				wprintf(L"Auto configuration is discovering settings for the network\n");
				break;
			case wlan_interface_state_authenticating:
				wprintf(L"In process of authenticating\n");
				break;
			default:
				wprintf(L"Unknown state %ld\n", pIfInfo->isState);
				break;
			}
			wprintf(L"\n");

			const GUID * pGUID = &pIfInfo->InterfaceGuid;
			dwResult = WlanGetNetworkBssList(hClient, pGUID, NULL, dot11_BSS_type_any, 0, NULL, &pBssList);
			if (dwResult != ERROR_SUCCESS)
			{
				wprintf(L"Wlan get network bss list error: %lu\n", dwResult);
				return 1;
			}
			else
			{
				for (uint i = 0; i < pBssList->dwNumberOfItems; i++)
				{
					pBssEntry = &pBssList->wlanBssEntries[i];
					get_mac_id(pBssEntry->dot11Bssid, mac_id);
					if (find_at_radiomap(mac_id, result_map, pLocalizationNode) == 0)
					{
						pLocalizationNode->add_recoder(pBssEntry->lRssi);
					}
					else if (get_ssid(pBssEntry->dot11Ssid, ret_ssid) == 0)
					{
						LocalizationNode new_ap(mac_id, ret_ssid, pBssEntry->lRssi);
						ret = add_to_radiomap(new_ap, result_map);
						if (ret != 0)
						{
							printf("ERROR: add_to_radiomap error");
							exit(1);
						}
					}
				}
			}
		}
	}
	if (pBssList != NULL)
	{
		WlanFreeMemory(pBssList);
		pBssList = NULL;
	}
	if (pIfList != NULL)
	{
		WlanFreeMemory(pIfList);
		pIfList = NULL;
	}
	WlanCloseHandle(hClient, 0);
	return 0;
}
Ejemplo n.º 23
0
int main(int argc, char *argv[])
{
HANDLE hWlan = NULL;

	DWORD dwError = 0;
	DWORD dwSupportedVersion = 0;
	DWORD dwClientVersion = (IsVistaOrHigher() ? 2 : 1);

	GUID guidInterface; ZeroMemory(&guidInterface, sizeof(GUID));

	WLAN_INTERFACE_INFO_LIST *wlanInterfaceList = (WLAN_INTERFACE_INFO_LIST*)WlanAllocateMemory(sizeof(WLAN_INTERFACE_INFO_LIST));
	ZeroMemory(wlanInterfaceList, sizeof(WLAN_INTERFACE_INFO_LIST));

	WLAN_AVAILABLE_NETWORK_LIST *wlanNetworkList = (WLAN_AVAILABLE_NETWORK_LIST*)WlanAllocateMemory(sizeof(WLAN_AVAILABLE_NETWORK_LIST));
	ZeroMemory(wlanNetworkList, sizeof(WLAN_AVAILABLE_NETWORK_LIST));

	try
	{
		if(dwError = WlanOpenHandle(dwClientVersion, NULL, &dwSupportedVersion, &hWlan) != ERROR_SUCCESS)
			throw("[x] Unable access wireless interface");

		if(dwError = WlanEnumInterfaces(hWlan, NULL, &wlanInterfaceList) != ERROR_SUCCESS)
			throw("[x] Unable to enum wireless interfaces");

		wprintf(L"[!] Found adapter %s\n", wlanInterfaceList->InterfaceInfo[0].strInterfaceDescription);

		if(dwError = wlanInterfaceList->InterfaceInfo[0].isState != wlan_interface_state_not_ready)
		{
				if(wlanInterfaceList->dwNumberOfItems > 1)
				{
					// TODO: Add processing for multiple wireless cards here
					printf("[!] Detected multiple wireless adapters, using default\n");
					guidInterface = wlanInterfaceList->InterfaceInfo[0].InterfaceGuid;
				}
				else
				{
					guidInterface = wlanInterfaceList->InterfaceInfo[0].InterfaceGuid;
				}
		}
		else
			throw("[x] Default wireless adapter disabled");

		DWORD dwPrevNotif = 0;

		// Scan takes awhile so we need to register a callback
		if(dwError = WlanRegisterNotification(hWlan, WLAN_NOTIFICATION_SOURCE_ACM, TRUE,
		  (WLAN_NOTIFICATION_CALLBACK)WlanNotification, NULL, NULL, &dwPrevNotif) != ERROR_SUCCESS)
			throw("[x] Unable to register for notifications");

		printf("[i] Scanning for nearby networks...\n");
		if(dwError = WlanScan(hWlan, &guidInterface, NULL, NULL, NULL) != ERROR_SUCCESS)
			throw("[x] Scan failed, check adapter is enabled");

		// Yawn...
		while(bWait)
			Sleep(100);

		// Unregister callback, don't care if it succeeds or not
		WlanRegisterNotification(hWlan, WLAN_NOTIFICATION_SOURCE_NONE, TRUE, NULL, NULL, NULL, &dwPrevNotif);

		if(dwError = WlanGetAvailableNetworkList(hWlan, &guidInterface, NULL, NULL, &wlanNetworkList) != ERROR_SUCCESS)
			throw("[x] Unable to obtain network list");

		for(unsigned int i = 0; i < wlanNetworkList->dwNumberOfItems; i++)
		{
				printf("\nSSID:\t\t\t%s\nSIGNAL:\t\t\t%d%%\n",
						wlanNetworkList->Network[i].dot11Ssid.ucSSID,
						wlanNetworkList->Network[i].wlanSignalQuality);

				printf("SECURITY:\t\t");
				switch(wlanNetworkList->Network[i].dot11DefaultAuthAlgorithm)
				{
						case DOT11_AUTH_ALGO_80211_OPEN:
						case DOT11_AUTH_ALGO_80211_SHARED_KEY:
							printf("WEP");
						break;

						case DOT11_AUTH_ALGO_WPA:
						case DOT11_AUTH_ALGO_WPA_PSK:
						case DOT11_AUTH_ALGO_WPA_NONE:
							printf("WPA");
						break;

						case DOT11_AUTH_ALGO_RSNA:
						case DOT11_AUTH_ALGO_RSNA_PSK:
							printf("WPA2");
						break;

						default:
							printf("UNKNOWN");
						break;
				}
				printf("\n");
		}
	}
	catch(char *szError)
	{
		printf("%s (0x%X)\nQuitting...\n", szError);
	}

	if(wlanNetworkList)
		WlanFreeMemory(wlanNetworkList);
	if(wlanInterfaceList)
		WlanFreeMemory(wlanInterfaceList);
	if(hWlan)
		WlanCloseHandle(hWlan, NULL);

	return dwError;
}
Ejemplo n.º 24
0
int foo() {

  WindowsNdisApi* w = WindowsNdisApi::Create();
  std::vector<AccessPoint> apData;
  w->GetAccessPointData(apData);


  ///////////////////////////////////////////////////////////
	HANDLE hClient;
	PWLAN_INTERFACE_INFO_LIST pIfList = NULL;
	PWLAN_INTERFACE_INFO pIfConnInfo = NULL;
	PWLAN_CONNECTION_ATTRIBUTES pConnectInfo = NULL;

	PWLAN_BSS_LIST pBssList=NULL;
	PWLAN_BSS_ENTRY  pBssEntry=NULL;
	WLAN_OPCODE_VALUE_TYPE opCode = wlan_opcode_value_type_invalid;

	DWORD dwResult = 0;
	DWORD dwMaxClient = 2;         
	DWORD dwCurVersion = 0;
	DWORD connectInfoSize = sizeof(WLAN_CONNECTION_ATTRIBUTES);

	int i;

	// Initialise the Handle
	dwResult = WlanOpenHandle(dwMaxClient, NULL, &dwCurVersion, &hClient);
	if (dwResult != ERROR_SUCCESS) 
	{    
		return 0;
	}

	// Get the Interface List
	dwResult = WlanEnumInterfaces(hClient, NULL, &pIfList);
	if (dwResult != ERROR_SUCCESS) 
	{    
		return 0;
	}

	//Loop through the List to find the connected Interface
	PWLAN_INTERFACE_INFO pIfInfo = NULL;
	for (i = 0; i < (int) pIfList->dwNumberOfItems; i++) 
	{
		pIfInfo = (WLAN_INTERFACE_INFO *) & pIfList->InterfaceInfo[i];    
		if (pIfInfo->isState == wlan_interface_state_connected) 
		{
			pIfConnInfo = pIfInfo;
			break;
		}
	}

	if ( pIfConnInfo == NULL )
		return 0;

	// Query the Interface
	dwResult = WlanQueryInterface(hClient,&pIfConnInfo->InterfaceGuid,wlan_intf_opcode_current_connection,NULL,&connectInfoSize,(PVOID *) &pConnectInfo,&opCode);
	if (dwResult != ERROR_SUCCESS) 
	{    
		return 0;
	}

	// Scan the connected SSID
	dwResult = WlanScan(hClient, &pIfConnInfo->InterfaceGuid,
		                NULL/*&pConnectInfo->wlanAssociationAttributes.dot11Ssid*/,
						NULL, NULL);
	if (dwResult != ERROR_SUCCESS) 
	{    
		return 0;
	}

	// Get the BSS Entry
	dwResult = WlanGetNetworkBssList(hClient, &pIfConnInfo->InterfaceGuid,
		NULL /*&pConnectInfo->wlanAssociationAttributes.dot11Ssid */,
		dot11_BSS_type_any,
		TRUE, NULL, &pBssList);

	if (dwResult != ERROR_SUCCESS) 
	{    
		return 0;
	}

	// Get the RSSI value
	pBssEntry=&pBssList->wlanBssEntries[0];
	return pBssEntry->lRssi;
}
Ejemplo n.º 25
0
int _tmain(int argc, _TCHAR* argv[])
{
	bool first_run=true;
	DWORD dwRetVal = 0;
	while(1)
	{
	/*Test per funzione di errore*/
	std::map<std::string, int> lMacAddress_TEST;
	
	// Declare and initialize variables.

    HANDLE hClient = NULL;		//Handle del client utilizzato nella sessione corrente
    DWORD dwMaxClient = 2;      //E' una costante che va inserita in WlanOpenHandle (1->Win XP SP2/3 | 2->Win Vista/Server 2008)    
    DWORD dwCurVersion = 0;		//Versione della WLAN API attualmente utilizzata da inserire nella WlanOpenHandle
    DWORD dwResult = 0;
    
    int iRet = 0;
    
    WCHAR GuidString[39] = {0};		//Conterrà un GUID sottoforma di stringa di caratteri

    unsigned int i, j, k;

    /* variables used for WlanEnumInterfaces  */

    PWLAN_INTERFACE_INFO_LIST pIfList = NULL;	//Contiene un array di NIC con relative informazioni
    PWLAN_INTERFACE_INFO pIfInfo = NULL;		//Contiene le informazioni relative ad una NIC (ID, Descrizione, Stato)

    PWLAN_AVAILABLE_NETWORK_LIST pBssList = NULL;	//Contiene un array di reti con relative informazioni
    PWLAN_AVAILABLE_NETWORK pBssEntry = NULL;		//Contiene info relative ad una rete raggiungibile (es. SSID, qualità segnale, algoritmo cifratura)
    
    int iRSSI = 0;

    dwResult = WlanOpenHandle(dwMaxClient, NULL, &dwCurVersion, &hClient); //Apre una connessione con il server
    if (dwResult != ERROR_SUCCESS)
		{
        wprintf(L"WlanOpenHandle failed with error: %u\n", dwResult);
        return 1;
        // You can use FormatMessage here to find out why the function failed
		}

    dwResult = WlanEnumInterfaces(hClient, NULL, &pIfList); //Inserisce in pIfList l'elenco delle NIC abilitate sul pc
    if (dwResult != ERROR_SUCCESS) 
		{
        wprintf(L"WlanEnumInterfaces failed with error: %u\n", dwResult);
        return 1;
        // You can use FormatMessage here to find out why the function failed
		} 
	else 
		{
        wprintf(L"Num Entries: %lu\n", pIfList->dwNumberOfItems); //Numero NIC trovate
        wprintf(L"Current Index: %lu\n", pIfList->dwIndex);	//Indice NIC corrente
        for (i = 0; i < (int) pIfList->dwNumberOfItems; i++) 
			{
            pIfInfo = (WLAN_INTERFACE_INFO *) &pIfList->InterfaceInfo[i]; //pIfInfo punta alla struttura con le informazioni relative alla NIC corrente
            wprintf(L"  Interface Index[%u]:\t %lu\n", i, i);
            iRet = StringFromGUID2(pIfInfo->InterfaceGuid, (LPOLESTR) &GuidString,	//Trasforma un GUID in stringa di caratteri 
                sizeof(GuidString)/sizeof(*GuidString));  //Numero di caratteri massimo per la stringa finale
            // For c rather than C++ source code, the above line needs to be
            // iRet = StringFromGUID2(&pIfInfo->InterfaceGuid, (LPOLESTR) &GuidString, 
            //     sizeof(GuidString)/sizeof(*GuidString)); 
            if (iRet == 0)	//Se StringFromGUID2 fallisce ritorna 0
                wprintf(L"StringFromGUID2 failed\n");
            else 
				{		//Altrimenti il numero di caratteri della stringa 
                wprintf(L"  InterfaceGUID[%d]: %ws\n",i, GuidString);
				}    
            wprintf(L"  Interface Description[%d]: %ws", i, pIfInfo->strInterfaceDescription);
            wprintf(L"\n");
            wprintf(L"  Interface State[%d]:\t ", i);
            switch (pIfInfo->isState) 
				{
				case wlan_interface_state_not_ready:
					wprintf(L"Not ready\n");
					break;
				case wlan_interface_state_connected:
					wprintf(L"Connected\n");
					break;
				case wlan_interface_state_ad_hoc_network_formed:
					wprintf(L"First node in a ad hoc network\n");
					break;
				case wlan_interface_state_disconnecting:
					wprintf(L"Disconnecting\n");
					break;
				case wlan_interface_state_disconnected:
					wprintf(L"Not connected\n");
					break;
				case wlan_interface_state_associating:
					wprintf(L"Attempting to associate with a network\n");
					break;
				case wlan_interface_state_discovering:
					wprintf(L"Auto configuration is discovering settings for the network\n");
					break;
				case wlan_interface_state_authenticating:
					wprintf(L"In process of authenticating\n");
					break;
				default:
					wprintf(L"Unknown state %ld\n", pIfInfo->isState);
					break;
				}
            wprintf(L"\n");

			//Inserisce in pBssList i dati delle reti disponibili
            dwResult = WlanGetAvailableNetworkList(hClient,		//Client handle ottenuto all'inizio
                                             &pIfInfo->InterfaceGuid,	//Interface GUID
                                             0, 
                                             NULL, 
                                             &pBssList);	//Puntatore alla lista delle entry trovate

            if (dwResult != ERROR_SUCCESS) 
				{
                wprintf(L"WlanGetAvailableNetworkList failed with error: %u\n", dwResult);
                dwRetVal = 1;
                // You can use FormatMessage to find out why the function failed
				} 
			else 
				{
                wprintf(L"WLAN_AVAILABLE_NETWORK_LIST for this interface\n");

                wprintf(L"  Num Entries: %lu\n\n", pBssList->dwNumberOfItems);

                for (j = 0; j < pBssList->dwNumberOfItems; j++) 
					{
                    pBssEntry = (WLAN_AVAILABLE_NETWORK *) & pBssList->Network[j]; //pBssEntry punta alla struttura di informazioni relative alla rete corrente
                    wprintf(L"  Profile Name[%u]:  %ws\n", j, pBssEntry->strProfileName);
                    wprintf(L"  SSID[%u]:\t\t ", j);
                    if (pBssEntry->dot11Ssid.uSSIDLength == 0) //Se l'SSID ha lunghezza nulla va a capo
                        wprintf(L"\n");
                    else 
						{   
                        for (k = 0; k < pBssEntry->dot11Ssid.uSSIDLength; k++) 
							{
                            wprintf(L"%c", (int) pBssEntry->dot11Ssid.ucSSID[k]); //Scrittura a video dell SSID
							}
                        wprintf(L"\n");
						}
					
					//Prova per ottenere il MAC Address-----------------------------------------------
					//--------------------------------------------------------------------------------
					PWLAN_BSS_LIST pWlanBssList=NULL;
					DWORD uscita=0;
					DOT11_SSID Dot11Ssid=pBssEntry->dot11Ssid;
					
					WlanGetNetworkBssList(
						hClient,		//Client inizializzato precedentemente
						&(pIfInfo->InterfaceGuid),	//Interfaccia sul quale si fanno le misurazioni
						&(pBssEntry->dot11Ssid),	//Struttura del SSID correntemente analizzato
						dot11_BSS_type_infrastructure, //Cerca tra le interfacce di infrastruttura
						pBssEntry->bSecurityEnabled,	//Security policy dell'interfaccia corrente
						NULL,	//DEVE ESSERE NULL
						&pWlanBssList	//Struttura che sarà riempita con info opportune
						);
					if(uscita==ERROR_SUCCESS)
					wprintf(L"\n  GOOD Exit status Bss\n");
					wprintf(L"\n  Number of Bss entries: %u\n", pWlanBssList->dwNumberOfItems);
					//for(int z=0; z<(int)pWlanBssList->dwNumberOfItems;z++)
					//{
						PWLAN_BSS_ENTRY px = (WLAN_BSS_ENTRY *) & pWlanBssList->wlanBssEntries;
						std::string sMACAddress = PrintMACaddress(px->dot11Bssid);
					//}
					//std::cout << sMACAddress;

					/*----------------------------------------------------------------------------------*/
					/*----------------------------------------------------------------------------------*/
                    wprintf(L"  BSS Network type[%u]:\t ", j);
                    switch (pBssEntry->dot11BssType) 
						{
						case dot11_BSS_type_infrastructure   :
							wprintf(L"Infrastructure (%u)\n", pBssEntry->dot11BssType);
							break;
						case dot11_BSS_type_independent:
							wprintf(L"Infrastructure (%u)\n", pBssEntry->dot11BssType);
							break;
						default:
							wprintf(L"Other (%lu)\n", pBssEntry->dot11BssType);
							break;
						}
                                
                    wprintf(L"  Number of BSSIDs[%u]:\t %u\n", j, pBssEntry->uNumberOfBssids);	
                    wprintf(L"  Connectable[%u]:\t ", j);
                    if (pBssEntry->bNetworkConnectable)
                        wprintf(L"Yes\n");
                    else 
						{
                        wprintf(L"No\n");
                        wprintf(L"  Not connectable WLAN_REASON_CODE value[%u]:\t %u\n", j, pBssEntry->wlanNotConnectableReason);
						}        
                    wprintf(L"  Number of PHY types supported[%u]:\t %u\n", j, pBssEntry->uNumberOfPhyTypes);

                    if (pBssEntry->wlanSignalQuality == 0)
                        iRSSI = -100;
                    else if (pBssEntry->wlanSignalQuality == 100)   
                        iRSSI = -50;
                    else
                        iRSSI = -100 + (pBssEntry->wlanSignalQuality/2);    
                        
                    wprintf(L"  Signal Quality[%u]:\t %u (RSSI: %i dBm)\n", j, pBssEntry->wlanSignalQuality, iRSSI);
					//Prova con memorizzazione dei MAC
					lMacAddress_TEST.insert(std::make_pair(sMACAddress,iRSSI));
                    if (first_run==true)
					{
						luogo.InsertElement(sMACAddress,iRSSI);
					}
					wprintf(L"  Security Enabled[%u]:\t ", j);
                    if (pBssEntry->bSecurityEnabled)
                        wprintf(L"Yes\n");
                    else
                        wprintf(L"No\n");
         
                    wprintf(L"  Default AuthAlgorithm[%u]: ", j);
                    switch (pBssEntry->dot11DefaultAuthAlgorithm) 
						{
						case DOT11_AUTH_ALGO_80211_OPEN:
							wprintf(L"802.11 Open (%u)\n", pBssEntry->dot11DefaultAuthAlgorithm);
							break;
						case DOT11_AUTH_ALGO_80211_SHARED_KEY:
							wprintf(L"802.11 Shared (%u)\n", pBssEntry->dot11DefaultAuthAlgorithm);
							break;
						case DOT11_AUTH_ALGO_WPA:
							wprintf(L"WPA (%u)\n", pBssEntry->dot11DefaultAuthAlgorithm);
							break;
						case DOT11_AUTH_ALGO_WPA_PSK:
							wprintf(L"WPA-PSK (%u)\n", pBssEntry->dot11DefaultAuthAlgorithm);
							break;
						case DOT11_AUTH_ALGO_WPA_NONE:
							wprintf(L"WPA-None (%u)\n", pBssEntry->dot11DefaultAuthAlgorithm);
							break;
						case DOT11_AUTH_ALGO_RSNA:
							wprintf(L"RSNA (%u)\n", pBssEntry->dot11DefaultAuthAlgorithm);
							break;
						case DOT11_AUTH_ALGO_RSNA_PSK:
							wprintf(L"RSNA with PSK(%u)\n", pBssEntry->dot11DefaultAuthAlgorithm);
							break;
						default:
							wprintf(L"Other (%lu)\n", pBssEntry->dot11DefaultAuthAlgorithm);
							break;
						}
                        
                    wprintf(L"  Default CipherAlgorithm[%u]: ", j);
                    switch (pBssEntry->dot11DefaultCipherAlgorithm) 
						{
						case DOT11_CIPHER_ALGO_NONE:
							wprintf(L"None (0x%x)\n", pBssEntry->dot11DefaultCipherAlgorithm);
							break;
						case DOT11_CIPHER_ALGO_WEP40:
							wprintf(L"WEP-40 (0x%x)\n", pBssEntry->dot11DefaultCipherAlgorithm);
							break;
						case DOT11_CIPHER_ALGO_TKIP:
							wprintf(L"TKIP (0x%x)\n", pBssEntry->dot11DefaultCipherAlgorithm);
							break;
						case DOT11_CIPHER_ALGO_CCMP:
							wprintf(L"CCMP (0x%x)\n", pBssEntry->dot11DefaultCipherAlgorithm);
							break;
						case DOT11_CIPHER_ALGO_WEP104:
							wprintf(L"WEP-104 (0x%x)\n", pBssEntry->dot11DefaultCipherAlgorithm);
							break;
						case DOT11_CIPHER_ALGO_WEP:
							wprintf(L"WEP (0x%x)\n", pBssEntry->dot11DefaultCipherAlgorithm);
							break;
						default:
							wprintf(L"Other (0x%x)\n", pBssEntry->dot11DefaultCipherAlgorithm);
							break;
						}

                    wprintf(L"  Flags[%u]:\t 0x%x", j, pBssEntry->dwFlags);
                    if (pBssEntry->dwFlags) 
						{
                        if (pBssEntry->dwFlags & WLAN_AVAILABLE_NETWORK_CONNECTED)
                            wprintf(L" - Currently connected");
                        if (pBssEntry->dwFlags & WLAN_AVAILABLE_NETWORK_HAS_PROFILE)
                            wprintf(L" - Has profile");
						}   
                    wprintf(L"\n");
                    
                    wprintf(L"\n");
					if (pWlanBssList!=NULL)
					{
        WlanFreeMemory(pWlanBssList);	//Libera la zona di memoria preposta alla lista di reti disponibili appena utilizzata
        pWlanBssList = NULL;
		}
                }
            }
        }

    }
    if (pBssList != NULL) 
		{
        WlanFreeMemory(pBssList);	//Libera la zona di memoria preposta alla lista di reti disponibili appena utilizzata
        pBssList = NULL;
		}
	

    if (pIfList != NULL) 
		{
        WlanFreeMemory(pIfList);	//Libera la zona di memoria preposta alla lista di NIC appena utilizzata
        pIfList = NULL;
		}
	
		if (first_run==true)
		{
			first_run=false;
		}
		else
		{
			float error;
			error=luogo.ErrorValue(lMacAddress_TEST);
			wprintf(L"Errore con i dati memorizzati: %f\n\n", error);
		}
		WlanCloseHandle(hClient, NULL);
	system("pause");
	}
	return dwRetVal;
}
//Called on HostedNetwork instantiation, message boxes if hosted network is not enabled
void HostedNetworkController::isHostedNetworkCapable()
{
	HRESULT result;									//HRESULT to store the return value from IP Helper API calls
	bool atLeastOneHostedNetworkSupport = false;	//Inssidious requires at least one wireless adapter with hosted network support


	if (wlanHandle == 0)
	{
		/* Open a handle to the Wlan API */

		DWORD negotiatedVersion = 0;					//DWORD for the Wlan API to store the negotiated API version in
		result = WlanOpenHandle(
			WLAN_API_VERSION_2_0,						//Request API version 2.0
			nullptr,									//Reserved
			&negotiatedVersion,							//Address of the DWORD to store the negotiated version
			&wlanHandle									//Address of the HANDLE to store the Wlan handle
			);

		if (result != NO_ERROR)
		{
			/* Something went wrong */

			MessageBox(nullptr, reinterpret_cast<const wchar_t*>(QString(
				("Unable to open a handle to the Wlan API. Error: \n   ")
				+ QString::fromWCharArray(_com_error(result).ErrorMessage())
				).utf16()),
				L"Inssidious failed to start.", MB_OK);
			ExitProcess(1);
		}
	}



	/* Get a list of all network adapters on the system */

	PIP_ADAPTER_ADDRESSES pAddresses = nullptr;		//Pointer to store information from GetAdaptersAddresses in
	ULONG ulOutBufLen = 0;							//Buffer for PIP_ADAPTER_ADDRESSES information
	int remainingRetries = 20;						//Number of times to try increasing buffer to accomodate data
	while (remainingRetries > 0)						//Loop to repeatedly try to populate PIP_ADAPTER_ADDRESSES buffer
	{
		remainingRetries--;


		/* Allocate memory */

		pAddresses = static_cast<IP_ADAPTER_ADDRESSES *>(HeapAlloc(GetProcessHeap(), 0, (ulOutBufLen)));

		if (pAddresses == nullptr)
		{
			/* Something went wrong */

			MessageBox(nullptr, L"Unable to allocate memory needed to call GetAdapterInfo.\nPlease restart Inssidious and try again.",
											L"Inssidious failed to start.", MB_OK);
			ExitProcess(1);
		}


		/* Try to get network adapter information */

		result = GetAdaptersAddresses(AF_INET, GAA_FLAG_INCLUDE_ALL_INTERFACES, nullptr, pAddresses, &ulOutBufLen);

		if (result == ERROR_BUFFER_OVERFLOW)
		{
			/* We need more memory. ulOutBufLen now has the size needed */
			/* Free what we allocated, nullptr pAddresses, and continue. */

			HeapFree(GetProcessHeap(), 0, (pAddresses));
			pAddresses = nullptr;
			continue;
		}
		else if (result == ERROR_NO_DATA)
		{
			/* The system has no network adapters. */

			MessageBox(nullptr, L"No network adapters found. Please enable or connect network \n adapters to the system and restart Inssidious.",
											L"Inssidious failed to start.", MB_OK);
			ExitProcess(1);
		}
		else if (result != NO_ERROR || remainingRetries == 0)
		{
			/* Something went wrong */

			MessageBox(nullptr, reinterpret_cast<const wchar_t*>(QString(
				           ("Unable to get network adapter information. Error: \n   ")
				           + QString::fromWCharArray(_com_error(result).ErrorMessage())
			           ).utf16()),
				L"Inssidious failed to start.", MB_OK);
			ExitProcess(1);
		}
		else
		{
			/* We successfully retreived the network adapter list. Leave the loop */

			break;
		}
	}


	/* Traverse the list of network adapters to identify hosted network capable wireless adapters */

	PIP_ADAPTER_ADDRESSES pCurrAddresses = pAddresses;					//Pointer to travse entries in the linked list
	while (pCurrAddresses)
	{
		if ((pCurrAddresses->IfType == IF_TYPE_IEEE80211))
		{

			/* Check whether the adapter supports running a wireless hosted network */
			/* Support for this is required by all wireless cards certified for Windows 7 or newer */

			GUID adapterAsGuid = QUuid(pCurrAddresses->AdapterName);
			DWORD responseSize = 0;										//DWORD for the Wlan API to store the size of its reply in
			PBOOL pHostedNetworkCapable = nullptr;						//Pointer to a bool for hosted network capabilities
			result = WlanQueryInterface(
				wlanHandle,												//Handle to the WLAN API opened earlier
				&adapterAsGuid,											//Char Array to Qt Uuid to GUID of the adapter ID
				wlan_intf_opcode_hosted_network_capable,				//Asking specifically on hosted network support
				nullptr,												//Reserved
				&responseSize,											//Size of the response received
				reinterpret_cast<PVOID *>(&pHostedNetworkCapable),		//Bool for whether adapter supports hosted network
				nullptr													//Optional return data type value
				);

			if (result == S_OK && *pHostedNetworkCapable)
			{
				/* This adapter supports wireless hosted networks. */
				/* Flag that we met the requirement of at least one wireless adapter on the system supporting hosted networks */

				atLeastOneHostedNetworkSupport = true;
			}


			/* Free the memory the Wlan API allocated for us */

			if (pHostedNetworkCapable != nullptr)
			{
				WlanFreeMemory(pHostedNetworkCapable);
				pHostedNetworkCapable = nullptr;
			}
		}

		/* Continue moving through the the linked list of adapters */

		pCurrAddresses = pCurrAddresses->Next;
	}


	/* All adapters have been processed. Free the memory allocated for the adapter list. */

	HeapFree(GetProcessHeap(), 0, (pAddresses));


	/* Check if any adapters supported Wireless Hosted Networks. */
	/* Inssidious requires at least one wireless adapter with Hosted Network support */

	if (!atLeastOneHostedNetworkSupport)
	{
		MessageBox(nullptr, L"No wireless network adapters with Hosted Network Support were found.\nPlease insert or enable another wireless adapter and restart Inssidious.",
									L"Inssidious failed to start.", MB_OK);
		ExitProcess(1);
	}
	else
	{
		return;
	}
}