bool Wlan::IsNetAvailable( const char * ssid ) { bool result = false; if (OpenHandle()) { PWLAN_INTERFACE_INFO_LIST wlanInterfaces; if (WlanEnumInterfaces( m_handle, NULL, &wlanInterfaces ) == ERROR_SUCCESS) { for (int i = 0; i < wlanInterfaces->dwNumberOfItems; i++) { if (wlanInterfaces->InterfaceInfo[i].isState == wlan_interface_state_connected) { PWLAN_AVAILABLE_NETWORK_LIST wlanNetworks; if (WlanGetAvailableNetworkList( m_handle, &wlanInterfaces->InterfaceInfo[i].InterfaceGuid, 0, NULL, &wlanNetworks ) == ERROR_SUCCESS) { for (int j = 0; j < wlanNetworks->dwNumberOfItems; j++) { if (_strnicmp( (const char *) wlanNetworks->Network[j].dot11Ssid.ucSSID, ssid, strlen(ssid) ) == 0) { result = true; break; } } WlanFreeMemory( wlanNetworks ); } } } WlanFreeMemory( wlanInterfaces ); } } return result; }
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; } }
void WiFiInfo::Impl::GetApnsAndNotifyClient() { vector<WiFiInfo::AccessPoint> apns; PWLAN_INTERFACE_INFO_LIST pIfList = NULL; DWORD dwResult = WlanEnumInterfaces(m_hClient, NULL, &pIfList); if (dwResult == ERROR_SUCCESS) { for (int ifIndex = 0; ifIndex < static_cast<int>(pIfList->dwNumberOfItems); ++ifIndex) { PWLAN_INTERFACE_INFO pIfInfo = (PWLAN_INTERFACE_INFO)&pIfList->InterfaceInfo[ifIndex]; PWLAN_BSS_LIST pWlanBssList = NULL; if (pWlanGetNetworkBssList) { // on WinXP we don't have this function :( dwResult = pWlanGetNetworkBssList(m_hClient, &pIfInfo->InterfaceGuid, 0, dot11_BSS_type_any, FALSE, NULL, &pWlanBssList); if (dwResult == ERROR_SUCCESS) { for (int wlanIndex = 0; wlanIndex < static_cast<int>(pWlanBssList->dwNumberOfItems); ++wlanIndex) { PWLAN_BSS_ENTRY pBssEntry = &pWlanBssList->wlanBssEntries[wlanIndex]; WiFiInfo::AccessPoint apn; apn.m_ssid.assign(&pBssEntry->dot11Ssid.ucSSID[0], &pBssEntry->dot11Ssid.ucSSID[pBssEntry->dot11Ssid.uSSIDLength]); char buff[20] = {}; sprintf(buff, "%02X-%02X-%02X-%02X-%02X-%02X", pBssEntry->dot11Bssid[0], pBssEntry->dot11Bssid[1], pBssEntry->dot11Bssid[2], pBssEntry->dot11Bssid[3], pBssEntry->dot11Bssid[4], pBssEntry->dot11Bssid[5]); apn.m_bssid = buff; sprintf(buff, "%ld", pBssEntry->lRssi); apn.m_signalStrength = buff; apns.push_back(apn); } WlanFreeMemory(pWlanBssList); } } } WlanFreeMemory(pIfList); } m_callback(apns); // on WinXP, clean up timer if it was used if (m_timer) { DeleteTimerQueueTimer(NULL, m_timer, NULL); m_timer = NULL; } }
HRESULT CWlanManager::GetHostedNetworkInterfaceGuid( GUID& InterfaceGuid ) { HRESULT hr = S_OK; DWORD dwError = ERROR_SUCCESS; PWLAN_HOSTED_NETWORK_STATUS pAPStatus = NULL; // hosted network status // // get the hosted network status // dwError = WlanHostedNetworkQueryStatus( m_WlanHandle, &pAPStatus, NULL // reserved ); BAIL_ON_WIN32_ERROR(dwError, hr); InterfaceGuid = pAPStatus->IPDeviceID; error: if (pAPStatus != NULL) { WlanFreeMemory(pAPStatus); pAPStatus = NULL; } return hr; }
/* * 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; }
/* * Get SSID from Profile XML * Really quick and dirty */ DWORD GetProfileSSID (HANDLE h, const GUID *iface, const wchar_t *name, wchar_t *ssid){ wchar_t *_ssid, *_ssidend; wchar_t *xml = NULL; DWORD status; DWORD flags = 0; DWORD granted = 0; status = WlanGetProfile(h, iface, name, NULL, &xml, &flags, &granted); if (status == ERROR_SUCCESS){ status = ERROR_INVALID_DATA; _ssid = wcsstr(xml, L"<SSID>"); if (_ssid){ _ssid = wcsstr(_ssid, L"<name>"); if (_ssid){ _ssid = _ssid + wcslen(L"<name>"); _ssidend = wcsstr(_ssid, L"</name>"); if (_ssidend){ *_ssidend = 0; wcscpy (ssid, _ssid); status = ERROR_SUCCESS; } } } WlanFreeMemory(xml); xml = NULL; } return status; }
// Get a list of Wifi Networks from the last scan std::vector<NetworkInfo> getWifiNetworks(HANDLE hClient, GUID ifGuid) { // Return variable std::vector<NetworkInfo> ns; // Result variable DWORD dwResult; // List of interfaces PWLAN_INTERFACE_INFO_LIST ifList = NULL; // Interface info PWLAN_INTERFACE_INFO ifInfo = NULL; // Service list PWLAN_BSS_LIST bssList = NULL; // Network service PWLAN_BSS_ENTRY bssEntry = NULL; // Retrieve a list of available networks dwResult = WlanGetNetworkBssList(hClient, &ifGuid, NULL, dot11_BSS_type_any, 0, NULL, &bssList); if (dwResult != ERROR_SUCCESS) { } else { // For each network for (unsigned int j = 0; j < bssList->dwNumberOfItems; j++) { // Grab the network bssEntry = (WLAN_BSS_ENTRY *)&bssList->wlanBssEntries[j]; // Network info struct NetworkInfo ni; // SSID for (int k = 0, l = bssEntry->dot11Ssid.uSSIDLength; k < 32; k++) { if (k < l) ni.ssid[k] = (int)bssEntry->dot11Ssid.ucSSID[k]; else ni.ssid[k] = 0; } // Hardware MAC Address for (int k = 0, l = 6; k < 32; k++) { if (k < l) ni.bssid[k] = (int)bssEntry->dot11Bssid[k]; else ni.bssid[k] = 0; } // Channel Frequency ni.frequency = bssEntry->ulChCenterFrequency; // Rssi ni.rssi = bssEntry->lRssi; // Signal quality ni.quality = bssEntry->uLinkQuality; // Add to the list ns.push_back(ni); } } // Clean up if (bssList != NULL) { WlanFreeMemory(bssList); bssList = NULL; } // Finish return ns; }
/* * Get the index of the first available network in the list on an interface */ DWORD GetIfaceAvailableSSID (HANDLE h, const GUID *iface, const wchar_t *ifname, WLANKEY *keys, int *index, WLAN_REASON_CODE *reason){ WLAN_AVAILABLE_NETWORK_LIST *netlist = NULL; DWORD status; int i; int j; int k; wchar_t det_ssid[65]; fwprintf (stderr, L"Getting available networks on interface \"%s\"\n", ifname); status = WlanGetAvailableNetworkList(h, iface, 0, NULL, &netlist); if (netlist != NULL){ fwprintf (stderr, L"%d networks in NetList\n", netlist->dwNumberOfItems); for (j = 0; j < netlist->dwNumberOfItems; j++){ for (k = 0; k < netlist->Network[j].dot11Ssid.uSSIDLength; k++){ det_ssid[k] = netlist->Network[j].dot11Ssid.ucSSID[k]; } det_ssid[k] = 0; fwprintf (stderr, L"Network %d: SSID=%ls\n", j, det_ssid); } for (i = 0; keys[i].ssid[0] != 0; i++){ for (j = 0; j < netlist->dwNumberOfItems; j++){ for (k = 0; k < netlist->Network[j].dot11Ssid.uSSIDLength; k++){ det_ssid[k] = netlist->Network[j].dot11Ssid.ucSSID[k]; } det_ssid[k] = 0; if (wcscmp(keys[i].ssid, det_ssid) == 0){ fwprintf (stderr, L"Network %d is in the profile list\n", j); *index = i; WlanFreeMemory(netlist); return status; } } } fwprintf (stderr, L"No detected networks are in the profile list\n"); WlanFreeMemory(netlist); } else { fwprintf (stderr, L"NetList is NULL\n"); } return status; }
/* * Remove all profiles on an interface */ DWORD RemoveIfaceProfiles (HANDLE h, const GUID *iface, const WLANKEY *profiles, const WLANKEY *keep){ WLAN_PROFILE_INFO_LIST *profile_list = NULL; DWORD status; int i; int j; int k; status = WlanGetProfileList(h, iface, NULL, &profile_list); if (status == ERROR_SUCCESS && profile_list != NULL){ for (i = 0; status == ERROR_SUCCESS && i < profile_list->dwNumberOfItems; i++){ WLAN_PROFILE_INFO *profile = (WLAN_PROFILE_INFO *)(profile_list->ProfileInfo + i); if (profile != NULL){ wchar_t ssid[256]; GetProfileSSID(h, iface, profile->strProfileName, ssid); if (keep != NULL){ int keep_profile = 0; for (j = 0; keep[j].ssid[0] != 0; j++){ const wchar_t *profilename; if ((GetVersion() & 0xFF) >= 0x06){ // Windows Vista and above profilename = keep[j].displayname; } else { profilename = keep[j].ssid; } if (!wcscmp(profile->strProfileName, profilename)){ keep_profile = 1; break; } } if (keep_profile){ continue; } } j = 0; do { if (profiles == NULL || !wcscmp(ssid, profiles[j].ssid)){ status = WlanDeleteProfile(h, iface, profile->strProfileName, NULL); fwprintf (stderr, L" Removing profile \"%ls\"\n", profile->strProfileName); break; } } while (profiles != NULL && profiles[++j].ssid[0] != 0); } } WlanFreeMemory(profile_list); } return status; }
/*! * \fn DWORD PMD::cleanup() * \ingroup win32backend * \private * \brief Cleans up the allocated memory before exiting a function. */ VOID PMD::cleanup() { if (hClientHandle != NULL) { printf ("\thClientHandle not null\n"); WlanCloseHandle( hClientHandle, NULL // reserved ); } if (pInterfaceList != NULL) { printf ("\tpInterfaceList not null \n"); WlanFreeMemory(pInterfaceList); } if (pCurrentConnInfo != NULL) { printf ("\tpCurrentConnInfo not null\n"); WlanFreeMemory(pCurrentConnInfo); }/* */ }
void FinalizeHandle() { g_pInterface = nullptr; if (g_pIntfList != nullptr) { WlanFreeMemory(g_pIntfList); g_pIntfList = nullptr; } if (g_hClient != nullptr) { WlanCloseHandle(g_hClient, nullptr); g_hClient = nullptr; } }
void WiFiInfo::Impl::RequestWiFiBSSIDs(WifiRequestCallbackT callback) { m_callback = callback; // if it's XP without necessary api... use gateway instead if (!pWlanGetNetworkBssList) { vector<WiFiInfo::AccessPoint> apns; GatewaysInfo(apns); callback(apns); return; } if (!m_isNotificationSupported) { // request timer after 4 seconds, when scanning completes CreateTimerQueueTimer(&m_timer, NULL, &WaitOrTimerCallback, this, 4100, 0, WT_EXECUTEONLYONCE); } else { // subscribe to notification when scanning is completed WlanRegisterNotification(m_hClient, WLAN_NOTIFICATION_SOURCE_ACM, TRUE, &OnWlanScanCompleted, this, NULL, NULL); } // start scanning PWLAN_INTERFACE_INFO_LIST pIfList = NULL; DWORD dwResult = WlanEnumInterfaces(m_hClient, NULL, &pIfList); if (dwResult == ERROR_SUCCESS) { for (int ifIndex = 0; ifIndex < static_cast<int>(pIfList->dwNumberOfItems); ++ifIndex) { PWLAN_INTERFACE_INFO pIfInfo = (PWLAN_INTERFACE_INFO)&pIfList->InterfaceInfo[ifIndex]; WlanScan(m_hClient, &pIfInfo->InterfaceGuid, NULL, NULL, NULL); } WlanFreeMemory(pIfList); } }
/* * 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; }
BOOL GetWlanOperationMode(tstring strGUID, tstring &strMode) { strGUID = _T("{") + strGUID + _T("}"); GUID ChoiceGUID; if (myGUIDFromString(strGUID.c_str(), &ChoiceGUID) != TRUE) { _tprintf(_T("Error: GetWlanOperationMode::myGUIDFromString error\n")); return FALSE; } ULONG ulOperationMode = -1; PULONG pOperationMode; DWORD dwResult = GetInterface(wlan_intf_opcode_current_operation_mode, (PVOID*)&pOperationMode, &ChoiceGUID); if (dwResult != ERROR_SUCCESS) { LPTSTR strErrorText = NULL; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwResult, 0, (PTSTR)&strErrorText, 0, NULL); if (strErrorText[_tcslen(strErrorText) - 2] == _T('\r') && strErrorText[_tcslen(strErrorText) - 1] == _T('\n')) { strErrorText[_tcslen(strErrorText) - 2] = 0x0; strErrorText[_tcslen(strErrorText) - 1] = 0x0; } _tprintf(_T("Error: GetWlanOperationMode::GetInterface error, error code = %d (%s)\n"), dwResult, strErrorText); return FALSE; } else { ulOperationMode = *pOperationMode; WlanFreeMemory(pOperationMode); } strMode = OperationMode2String(ulOperationMode); return TRUE; }
/* * 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; }
// enumerate wireless interfaces UINT EnumInterface( HANDLE hClient, WLAN_INTERFACE_INFO sInfo[64] ) { DWORD dwError = ERROR_SUCCESS; PWLAN_INTERFACE_INFO_LIST pIntfList = NULL; UINT i = 0; __try { // enumerate wireless interfaces if ((dwError = WlanEnumInterfaces( hClient, NULL, // reserved &pIntfList )) != ERROR_SUCCESS) { __leave; } // print out interface information for (i = 0; i < pIntfList->dwNumberOfItems; i++) { memcpy( &sInfo[i], &pIntfList->InterfaceInfo[i], sizeof(WLAN_INTERFACE_INFO) ); } return pIntfList->dwNumberOfItems; } __finally { // clean up if (pIntfList != NULL) { WlanFreeMemory(pIntfList); } } return 0; }
//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; }
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; }
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; }
// Main program int main(int argc, char** argv) { // Parse arguments int task = 0; if (argc < 2) { usage(argv[0]); return 2; } // Interface number DWORD ifSelect = 0; // Task if (argc >= 2) { if (strncmp(argv[1], "if", 2) == 0) { task = TASK_LIST_INTERFACES; } else if (strncmp(argv[1], "scan", 4) == 0) { task = TASK_SCAN_NETWORKS; } else if (strncmp(argv[1], "list", 4) == 0) { task = TASK_LIST_NETWORKS; } else if (strncmp(argv[1], "query", 5) == 0) { task = TASK_SCAN_NETWORKS | TASK_LIST_NETWORKS; } } // Interface if (argc >= 3) { sscanf(argv[2], "%d", &ifSelect); } // Setup HANDLE whandle = getWlanHandle(); std::string input; if (whandle == NULL) { printf("Error: Failed to open wlan handle.\n"); return 1; } // Print usage and exit if (task == TASK_USAGE) { usage(argv[0]); return 2; } // Get interfaces PWLAN_INTERFACE_INFO_LIST ifList = NULL; ifList = getWlanInterfaces(whandle); if (ifList == NULL) { printf("Error: Failed to find wlan interfaces.\n"); return 1; } // Print interfaces and exit if (bitCheck(task, TASK_LIST_INTERFACES)) { for (DWORD i = 0; i < ifList->dwNumberOfItems; i++) { PWLAN_INTERFACE_INFO info = (WLAN_INTERFACE_INFO *)&ifList->InterfaceInfo[i]; printf("% 2d ", i); for (int j = 0; j < 256 && info->strInterfaceDescription[j] != 0; j++) { printf("%c", (unsigned char) info->strInterfaceDescription[j]); } printf("\n"); } WlanFreeMemory(ifList); return 0; } // Select the wlan interface GUID ifGuid; if (ifList->dwNumberOfItems == 0) { printf("Error: No wlan interfaces exist.\n"); return 1; } else { if (ifSelect >= ifList->dwNumberOfItems) { //printf("Warning: Interface %d does not exist. Defaulting to interface 0.\n", ifSelect); ifSelect = 0; } ifGuid = ((WLAN_INTERFACE_INFO *)&ifList->InterfaceInfo[ifSelect])->InterfaceGuid; } WlanFreeMemory(ifList); if (bitCheck(task, TASK_LIST_NETWORKS)) { // List available networks std::vector<NetworkInfo> networks = getWifiNetworks(whandle, ifGuid); for (auto itr = networks.begin(); itr != networks.end(); itr++) { // Rssi printf("% 4d ", (*itr).rssi); // Quality printf("% 4d ", (*itr).quality); // Bssid for (int i = 0; i < 6; i++) printf("%02x", (*itr).bssid[i]) && (i<5) && printf(":"); printf(" "); // Ssid for (int i = 0; i < 32; i++) printf("%c", (*itr).ssid[i]); printf("\n"); } } if (bitCheck(task, TASK_SCAN_NETWORKS)) { // Scan for network scanWifiNetworks(whandle, ifGuid); } 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; }
HRESULT CWlanManager::GetHostedNetworkKey( CAtlString& strKey ) { HRESULT hr = S_OK; DWORD dwError = ERROR_SUCCESS; BOOL bIsPassPhrase = FALSE; BOOL bPersistent = FALSE; PUCHAR pucSecondaryKey = NULL; DWORD dwSecondaryKeyLength = 0; WCHAR strSecondaryKey[WLAN_MAX_NAME_LENGTH]; // get the user security key dwError = WlanHostedNetworkQuerySecondaryKey( m_WlanHandle, &dwSecondaryKeyLength, &pucSecondaryKey, &bIsPassPhrase, &bPersistent, NULL, NULL ); BAIL_ON_WIN32_ERROR(dwError, hr); int cchKey = 0; if (dwSecondaryKeyLength > 0) { // Must be passphrase _ASSERT(bIsPassPhrase); // convert the key if (bIsPassPhrase) { #pragma prefast(suppress:26035, "If the key is a pass phrase, it is guaranteed to be null-terminated.") cchKey = MultiByteToWideChar( CP_ACP, MB_ERR_INVALID_CHARS, (LPCSTR)pucSecondaryKey, dwSecondaryKeyLength, strSecondaryKey, sizeof(strSecondaryKey) / sizeof(strSecondaryKey[0]) -1 ); } } if(cchKey == 0) { // secondary key is not set or not passphrase // set a temporary one CAtlString strTmpKey = L"HostedNetwork12345"; hr = SetHostedNetworkKey(strTmpKey); BAIL_ON_FAILURE(hr); strKey = strTmpKey; } else { // got the key strKey = strSecondaryKey; } error: if (pucSecondaryKey != NULL) { WlanFreeMemory(pucSecondaryKey); pucSecondaryKey = NULL; } return hr; }
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; }
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; }
PLUGIN_EXPORT double Update(void* data) { if (g_pInterface == nullptr) return 0; MeasureData* measure = (MeasureData*)data; double value = 0; if (measure->type != UNKNOWN) { if (measure->type == LIST) { PWLAN_AVAILABLE_NETWORK_LIST pwnl = nullptr; DWORD dwErr = WlanGetAvailableNetworkList(g_hClient, &g_pInterface->InterfaceGuid, 0, nullptr, &pwnl); if (ERROR_SUCCESS != dwErr) { measure->statusString = L"Error"; } else { // Size of network name can be up to 64 chars, set to 80 to add room for delimiters measure->statusString.clear(); measure->statusString.reserve(80 * measure->listMax); UINT printed = 0; // count of how many networks have been printed already // Check all items in WLAN NETWORK LIST for (size_t i = 0; i < pwnl->dwNumberOfItems ; ++i) { if (printed == measure->listMax) break; // SSID is in UCHAR, convert to WCHAR std::wstring ssid = ConvertToWide((LPCSTR)pwnl->Network[i].dot11Ssid.ucSSID, (int)pwnl->Network[i].dot11Ssid.uSSIDLength); // Prevent duplicates that result from profiles, check using SSID if (!ssid.empty() && ssid[0] && wcsstr(measure->statusString.c_str(), ssid.c_str()) == nullptr) { ++printed; measure->statusString += ssid; if (measure->listStyle > 0) { if (measure->listStyle == 1 || measure->listStyle == 3) { // ADD PHY type measure->statusString += L" @"; measure->statusString += ToString(pwnl->Network[i].dot11PhyTypes[0]); } if (measure->listStyle == 2 || measure->listStyle == 3) { // ADD cipher and authentication measure->statusString += L" ("; measure->statusString += ToString(pwnl->Network[i].dot11DefaultCipherAlgorithm); measure->statusString += L':'; measure->statusString += ToString(pwnl->Network[i].dot11DefaultAuthAlgorithm); measure->statusString += L')'; } } measure->statusString += L'\n'; } } WlanFreeMemory(pwnl); } } else if (measure->type == TXRATE) { DWORD dwErr = getAdapterAddresses(&g_pAddresses); if (NO_ERROR != dwErr) { measure->statusString = L"Error"; value = (double)-1; } else { PIP_ADAPTER_ADDRESSES pCurrAddresses = g_pAddresses; value = (double)-1; while(pCurrAddresses) { // Doesn't work - not sure how to compare the 2 GUIDs // if (pCurrAddresses->NetworkGuid != g_pInterface->InterfaceGuid) // Ignores the interface index parameter - whoops. if (IF_TYPE_IEEE80211 != pCurrAddresses->IfType) { pCurrAddresses = pCurrAddresses->Next; continue; } value = (double)pCurrAddresses->TransmitLinkSpeed; break; } } if (g_pAddresses != nullptr) { FREE(g_pAddresses); } } else { ULONG outsize = 0; PWLAN_CONNECTION_ATTRIBUTES wlan_cattr = nullptr; DWORD dwErr = WlanQueryInterface(g_hClient, &g_pInterface->InterfaceGuid, wlan_intf_opcode_current_connection, nullptr, &outsize, (PVOID*)&wlan_cattr, nullptr); if (ERROR_SUCCESS != dwErr) { switch (measure->type) { case SSID: case PHY: case ENCRYPTION: case AUTH: measure->statusString = L"-1"; break; } } else { switch (measure->type) { // This rate is currently bogus, sadly :-( // case TXRATE: // value = (double)wlan_cattr->wlanAssociationAttributes.ulTxRate; // break; case QUALITY: value = (double)wlan_cattr->wlanAssociationAttributes.wlanSignalQuality; break; case SSID: // Need to convert ucSSID to wchar from uchar measure->statusString = ConvertToWide((LPCSTR)wlan_cattr->wlanAssociationAttributes.dot11Ssid.ucSSID, (int)wlan_cattr->wlanAssociationAttributes.dot11Ssid.uSSIDLength); // If not connected yet add current status measure->statusString += ToString(wlan_cattr->isState); break; case PHY: measure->statusString = ToString(wlan_cattr->wlanAssociationAttributes.dot11PhyType); break; case ENCRYPTION: measure->statusString = ToString(wlan_cattr->wlanSecurityAttributes.dot11CipherAlgorithm); break; case AUTH: measure->statusString = ToString(wlan_cattr->wlanSecurityAttributes.dot11AuthAlgorithm); break; default: // Invalid type measure->statusString.clear(); break; } WlanFreeMemory(wlan_cattr); } } } return value; }
int MainInteractive() { HANDLE hClient = NULL; WLAN_INTERFACE_INFO sInfo[64]; RPC_TSTR strGuid = NULL; TCHAR szBuffer[256]; DWORD dwRead; if (OpenHandleAndCheckVersion(&hClient) != ERROR_SUCCESS) { _tsystem(_T("PAUSE")); return -1; } UINT nCount = EnumInterface(hClient, sInfo); for (UINT i = 0; i < nCount; ++i) { if (UuidToString(&sInfo[i].InterfaceGuid, &strGuid) == RPC_S_OK) { ULONG ulOperationMode = -1; PULONG pOperationMode; DWORD dwResult = GetInterface(wlan_intf_opcode_current_operation_mode, (PVOID*)&pOperationMode, &sInfo[i].InterfaceGuid); if (dwResult != ERROR_SUCCESS) { _tprintf(_T("GetInterface error, error code = %d\n"), dwResult); _tsystem(_T("PAUSE")); } else { ulOperationMode = *pOperationMode; WlanFreeMemory(pOperationMode); } _tprintf(_T("%d. %s\n\tName: %s\n\tDescription: %s\n\tState: %s\n\tOperation Mode: %s\n"), i, strGuid, getAdapterNameFromGuid((TCHAR*) strGuid).c_str(), sInfo[i].strInterfaceDescription, GetInterfaceStateString(sInfo[i].isState), GetInterfaceOperationModeString(ulOperationMode)); RpcStringFree(&strGuid); } } UINT nChoice = 0; GUID ChoiceGUID; LPGUID pChoiceGUID = NULL; _tprintf(_T("Enter the choice (0, 1,..) of the wireless card you want to operate on:\n")); if (ReadConsole(GetStdHandle(STD_INPUT_HANDLE), szBuffer, _countof(szBuffer), &dwRead, NULL) == FALSE) { _putts(_T("Error input.")); _tsystem(_T("PAUSE")); return -1; } szBuffer[dwRead] = 0; // TCHAR *aaa = _T("42dfd47a-2764-43ac-b58e-3df569c447da"); // dwRead = sizeof(aaa); TCHAR buf[256]; _stprintf_s(buf, 256, _T("{%s}"), szBuffer); if (dwRead > 32) { if (myGUIDFromString(buf, &ChoiceGUID) != TRUE) { _tprintf(_T("UuidFromString error, error code = %d\n"), -1); _tsystem(_T("PAUSE")); } else { pChoiceGUID = &ChoiceGUID; } } else { nChoice = _ttoi(szBuffer); if (nChoice > nCount) { _putts(_T("No such index.")); _tsystem(_T("PAUSE")); return -1; } pChoiceGUID = &sInfo[nChoice].InterfaceGuid; } UINT nSTate = 0; ULONG ulOperationMode = -1; _tprintf(_T("Enter the operation mode (0, 1 or 2) you want to switch to for the chosen wireless card:\n")); _tprintf(_T("0: Extensible Station (ExtSTA)\n1: Network Monitor (NetMon)\n2: Extensible Access Point (ExtAP)\n")); if (ReadConsole(GetStdHandle(STD_INPUT_HANDLE), szBuffer, _countof(szBuffer), &dwRead, NULL) == FALSE) { _putts(_T("Error input.")); _tsystem(_T("PAUSE")); return -1; } szBuffer[dwRead] = 0; nSTate = _ttoi(szBuffer); if (nSTate != 0 && nSTate != 1 && nSTate != 2) { _putts(_T("Only 0, 1 and 2 are valid inputs.")); _tsystem(_T("PAUSE")); return -1; } if (nSTate == 0) { ulOperationMode = DOT11_OPERATION_MODE_EXTENSIBLE_STATION; } else if (nSTate == 1) { ulOperationMode = DOT11_OPERATION_MODE_NETWORK_MONITOR; } else // nSTate == 2 { ulOperationMode = DOT11_OPERATION_MODE_EXTENSIBLE_AP; } DWORD dwResult = SetInterface(wlan_intf_opcode_current_operation_mode, (PVOID*)&ulOperationMode, pChoiceGUID); if (dwResult != ERROR_SUCCESS) { _tprintf(_T("SetInterface error, error code = %d\n"), dwResult); _tsystem(_T("PAUSE")); } else { _tprintf(_T("SetInterface success!\n")); } return 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; }
//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; } }