Exemplo n.º 1
0
int NameToBthAddr(char *pszRemoteName, PSOCKADDR_BTH pRemoteBthAddr)
{
	INT             iResult = CXN_SUCCESS;
	BOOL            bContinueLookup = FALSE, bRemoteDeviceFound = FALSE;
	ULONG           ulFlags = 0, ulPQSSize = sizeof(WSAQUERYSET);
	HANDLE          hLookup = NULL;
	PWSAQUERYSET    pWSAQuerySet = NULL;

	ZeroMemory(pRemoteBthAddr, sizeof(*pRemoteBthAddr));

	pWSAQuerySet = (PWSAQUERYSET)HeapAlloc(GetProcessHeap(),
		HEAP_ZERO_MEMORY,
		ulPQSSize);
	if (NULL == pWSAQuerySet) {
		iResult = STATUS_NO_MEMORY;
		printf("[BTClient] Unable to allocate memory for WSAQUERYSET\n");
	}

	//
	// Search for the device with the correct name
	//
	printf("[BTClient] Looking for %s...\n", pszRemoteName);
	if (CXN_SUCCESS == iResult) {

		for (INT iRetryCount = 0;
			!bRemoteDeviceFound && (iRetryCount < CXN_MAX_INQUIRY_RETRY);
			iRetryCount++) {
			//
			// WSALookupService is used for both service search and device inquiry
			// LUP_CONTAINERS is the flag which signals that we're doing a device inquiry.
			//
			ulFlags = LUP_CONTAINERS;

			//
			// Friendly device name (if available) will be returned in lpszServiceInstanceName
			//
			ulFlags |= LUP_RETURN_NAME;

			//
			// BTH_ADDR will be returned in lpcsaBuffer member of WSAQUERYSET
			//
			ulFlags |= LUP_RETURN_ADDR;

			if (0 == iRetryCount) {
				printf("[BTClient] Inquiring device from cache...\n");
			}
			else {
				//
				// Flush the device cache for all inquiries, except for the first inquiry
				//
				// By setting LUP_FLUSHCACHE flag, we're asking the lookup service to do
				// a fresh lookup instead of pulling the information from device cache.
				//
				ulFlags |= LUP_FLUSHCACHE;

				//
				// Pause for some time before all the inquiries after the first inquiry
				//
				// Remote Name requests will arrive after device inquiry has
				// completed.  Without a window to receive IN_RANGE notifications,
				// we don't have a direct mechanism to determine when remote
				// name requests have completed.
				//
				printf("[BTClient] Unable to find device.  Waiting for %d seconds before re-inquiry...\n", CXN_DELAY_NEXT_INQUIRY);
				Sleep(CXN_DELAY_NEXT_INQUIRY * 1000);

				printf("[BTClient] Inquiring device ...\n");
			}

			//
			// Start the lookup service
			//
			iResult = CXN_SUCCESS;
			hLookup = 0;
			bContinueLookup = FALSE;
			ZeroMemory(pWSAQuerySet, ulPQSSize);
			pWSAQuerySet->dwNameSpace = NS_BTH;
			pWSAQuerySet->dwSize = sizeof(WSAQUERYSET);
			printf("[BTClient] before WSALookupServiceBegin\n");
			iResult = WSALookupServiceBegin(pWSAQuerySet, ulFlags, &hLookup);
			printf("[BTClient] after WSALookupServiceBegin\n");
			//
			// Even if we have an error, we want to continue until we
			// reach the CXN_MAX_INQUIRY_RETRY
			//
			if ((NO_ERROR == iResult) && (NULL != hLookup)) {
				bContinueLookup = TRUE;
			}
			else if (0 < iRetryCount) {
				printf("[BTClient] WSALookupServiceBegin() failed with error code %d, WSAGetLastError = %d\n", iResult, WSAGetLastError());
				break;
			}

			while (bContinueLookup) {
				//
				// Get information about next bluetooth device
				//
				// Note you may pass the same WSAQUERYSET from LookupBegin
				// as long as you don't need to modify any of the pointer
				// members of the structure, etc.
				//
				// ZeroMemory(pWSAQuerySet, ulPQSSize);
				// pWSAQuerySet->dwNameSpace = NS_BTH;
				// pWSAQuerySet->dwSize = sizeof(WSAQUERYSET);
				printf("[BTClient] Before WSALookupServiceNext\n");
				if (NO_ERROR == WSALookupServiceNext(hLookup,
					ulFlags,
					&ulPQSSize,
					pWSAQuerySet)) {

					//
					// Compare the name to see if this is the device we are looking for.
					//
					wchar_t* wcRemoteName = convertCharArrayToLPCWSTR(pszRemoteName);
					if ((pWSAQuerySet->lpszServiceInstanceName != NULL) &&
						(0 == wcscmp(pWSAQuerySet->lpszServiceInstanceName, wcRemoteName))) {
						delete wcRemoteName;
						//
						// Found a remote bluetooth device with matching name.
						// Get the address of the device and exit the lookup.
						//
						wprintf(L"[BTClient] Found %s!\n", pWSAQuerySet->lpszServiceInstanceName);
						//printf("[BTClient] lpszServiceInstanceName addr %d\n", (pWSAQuerySet->lpszServiceInstanceName));

						//printf("[BTClient] lpcsaBuffer address is %d\n", (pWSAQuerySet->lpcsaBuffer));
						//printf("[BTClient]\t pResults->...->btAddr: %012X\n", ((PSOCKADDR_BTH)pWSAQuerySet->lpcsaBuffer->RemoteAddr.lpSockaddr)->btAddr);

						//printf("[BTClient] RemoteAddr address is %d\n", (pWSAQuerySet->lpcsaBuffer->RemoteAddr));

						CopyMemory(pRemoteBthAddr,
							(PSOCKADDR_BTH)pWSAQuerySet->lpcsaBuffer->RemoteAddr.lpSockaddr,
							sizeof(*pRemoteBthAddr));
						bRemoteDeviceFound = TRUE;
						bContinueLookup = FALSE;
						printf("[BTClient] Finished copy\n");
					}
					else {
						wprintf(L"[BTClient] Found %s, still looking...\n", pWSAQuerySet->lpszServiceInstanceName);
					}
				}
				else {
					iResult = WSAGetLastError();
					if (WSA_E_NO_MORE == iResult) { //No more data
						printf("[BTClient] WSA_E_NO_MORE\n");
						//
						// No more devices found.  Exit the lookup.
						//
						bContinueLookup = FALSE;
					}
					else if (WSAEFAULT == iResult) {

						//
						// The buffer for QUERYSET was insufficient.
						// In such case 3rd parameter "ulPQSSize" of function "WSALookupServiceNext()" receives
						// the required size.  So we can use this parameter to reallocate memory for QUERYSET.
						//
						HeapFree(GetProcessHeap(), 0, pWSAQuerySet);

						pWSAQuerySet = (PWSAQUERYSET)HeapAlloc(GetProcessHeap(),
							HEAP_ZERO_MEMORY,
							ulPQSSize);
						printf("[BTClient] Got WSAEFAULT\n");
						if (NULL == pWSAQuerySet) {
							printf("[BTClient] Unable to allocate memory for WSAQERYSET\n");
							iResult = STATUS_NO_MEMORY;
							bContinueLookup = FALSE;
						}
					}
					else {
						printf("[BTClient] WSALookupServiceNext() failed with error code %d\n", iResult);
						bContinueLookup = FALSE;
					}
				}
			}

			//
			// End the lookup service
			//
			WSALookupServiceEnd(hLookup);
			if (STATUS_NO_MEMORY == iResult) {
				break;
			}
		}
	}

	if (NULL != pWSAQuerySet) {
		HeapFree(GetProcessHeap(), 0, pWSAQuerySet);
		pWSAQuerySet = NULL;
	}

	if (bRemoteDeviceFound) {
		iResult = CXN_SUCCESS;
	}
	else {
		iResult = CXN_ERROR;
	}
	return iResult;
}
Exemplo n.º 2
0
//-------------------------------------------------------------------------
// Function: PnrpResolve
//
// Purpose:  Resolve the given name within a PNRP cloud
//
// Arguments:
//   pwzName  : name to resolve in PNRP, generally the graph id
//   pwzCloud : name of cloud to resolve in, NULL = global cloud
//   pAddr    : pointer to result buffer
//
// Returns:  HRESULT
//
HRESULT PnrpResolve(PCWSTR pwzName, PCWSTR pwzCloud, __out SOCKADDR_IN6* pAddr)
{
    HRESULT         hr = S_OK;
    PNRPINFO        pnrpInfo = {0};
    BLOB            blPnrpData = {0};
    WSAQUERYSET     querySet = {0};
    WSAQUERYSET*    pResults = NULL;
    WSAQUERYSET     tempResultSet = {0};
    HANDLE          hLookup = NULL;
    BOOL            fFound = FALSE;
    DWORD           dwError;
    INT             iRet;
    ULONG           i;
    DWORD           dwSize = 0;

    //
    // fill in the WSAQUERYSET
    //
    pnrpInfo.dwSize = sizeof(pnrpInfo);
    pnrpInfo.nMaxResolve = 1;
    pnrpInfo.dwTimeout = 30;
    pnrpInfo.enResolveCriteria = PNRP_RESOLVE_CRITERIA_NON_CURRENT_PROCESS_PEER_NAME;

    blPnrpData.cbSize = sizeof(pnrpInfo);
    blPnrpData.pBlobData = (BYTE*)&pnrpInfo;

    querySet.dwSize = sizeof(querySet);
    querySet.dwNameSpace = NS_PNRPNAME;
    querySet.lpServiceClassId = (LPGUID)&SVCID_PNRPNAME;
    querySet.lpszServiceInstanceName = (PWSTR) pwzName;
    querySet.lpszContext = (PWSTR) pwzCloud;
    querySet.lpBlob = &blPnrpData;
    
    // start resolve
    iRet = WSALookupServiceBegin(
            &querySet,
            LUP_RETURN_NAME | LUP_RETURN_ADDR | LUP_RETURN_COMMENT,
            &hLookup);

    if (iRet != 0)
    {
        hr = HRESULT_FROM_WIN32(WSAGetLastError());
    }

    if (SUCCEEDED(hr))
    {
        dwSize = sizeof(tempResultSet);

        // retrieve the required size
        iRet = WSALookupServiceNext(hLookup, 0, &dwSize, &tempResultSet);
        dwError = WSAGetLastError();

        if (dwError == WSAEFAULT)
        {
            // allocate space for the results
            pResults = (WSAQUERYSET*)malloc(dwSize);
            if (pResults == NULL)
            {
                hr = HRESULT_FROM_WIN32(WSAGetLastError());
            }
        }
        else
        {        
            hr = HRESULT_FROM_WIN32(dwError);
        }
    }

    if (SUCCEEDED(hr))
    {
        // retrieve the addresses
        iRet = WSALookupServiceNext(hLookup, 0, &dwSize, pResults);
        if (iRet != 0)
        {
            hr = HRESULT_FROM_WIN32(WSAGetLastError());
        }
    }

    if (SUCCEEDED(hr))
    {
        // return the first IPv6 address found
        for (i = 0; i < pResults->dwNumberOfCsAddrs; i++)
        {
            if (pResults->lpcsaBuffer[i].iProtocol == IPPROTO_TCP &&
                pResults->lpcsaBuffer[i].RemoteAddr.iSockaddrLength == sizeof(SOCKADDR_IN6))
            {
                CopyMemory(pAddr, pResults->lpcsaBuffer[i].RemoteAddr.lpSockaddr, sizeof(SOCKADDR_IN6));
                fFound = TRUE;
                break;
            }
        }

        if (!fFound)
        {
            // unable to find an IPv6 address
            hr = HRESULT_FROM_WIN32(WSA_E_NO_MORE);
        }
    }

    if (hLookup != NULL)
    {
        WSALookupServiceEnd(hLookup);
    }
    
    free(pResults);
    return hr;
}
Exemplo n.º 3
0
int RhoBluetoothManager::DiscoverDevices() {
	LOG(INFO)  + "RhoBluetoothManager::DiscoverDevices() START";
	WSAQUERYSET		wsaq;
	HANDLE			hLookup;
	RhoDeviceList *	tempDevice;

	union {
		CHAR buf[5000];
		double __unused;	// ensure proper alignment
	};

	LPWSAQUERYSET pwsaResults = (LPWSAQUERYSET) buf;
	DWORD dwSize  = sizeof(buf);
	BOOL bHaveName;

	ZeroMemory(&wsaq, sizeof(wsaq));
	wsaq.dwSize = sizeof(wsaq);
	wsaq.dwNameSpace = NS_BTH;
	wsaq.lpcsaBuffer = NULL;

	if (ERROR_SUCCESS != WSALookupServiceBegin (&wsaq, LUP_CONTAINERS, &hLookup))
	{
		LOG(INFO)  + "RhoBluetoothManager::DiscoverDevices() return ERROR";
		return WSAGetLastError();
	}

	ZeroMemory(pwsaResults, sizeof(WSAQUERYSET));
	pwsaResults->dwSize = sizeof(WSAQUERYSET);
	pwsaResults->dwNameSpace = NS_BTH;
	pwsaResults->lpBlob = NULL;

	if(m_pStart)
	{
		for(m_pCurrentDevice=m_pStart;m_pCurrentDevice;)
		{
			RhoDeviceList *temp=m_pCurrentDevice;
			m_pCurrentDevice=m_pCurrentDevice->NextDevice;
			free(temp);
		}
	}
	m_pEnd=m_pStart=NULL;
	m_iNumDevices=0;
	while (true)
	{	
		if(WSALookupServiceNext (hLookup, LUP_RETURN_NAME | LUP_RETURN_ADDR, &dwSize, pwsaResults)!=ERROR_SUCCESS)
			break;
		ASSERT (pwsaResults->dwNumberOfCsAddrs == 1);
		//Populate the link list		
		tempDevice=(RhoDeviceList*)malloc(sizeof(RhoDeviceList));
		tempDevice->NextDevice=NULL;
		if(m_pStart==NULL)
		{
			m_pStart = tempDevice;
			m_pEnd=m_pStart;
		}
		else
		{
			m_pEnd->NextDevice =tempDevice;
			m_pEnd=tempDevice;
		}
		m_iNumDevices++;
		m_pEnd->bthAddress = ((SOCKADDR_BTH *)pwsaResults->lpcsaBuffer->RemoteAddr.lpSockaddr)->btAddr;
		bHaveName = pwsaResults->lpszServiceInstanceName && *(pwsaResults->lpszServiceInstanceName);
		//If device name is available, add to node
		StringCchPrintf(m_pEnd->bthName, ARRAYSIZE(m_pEnd->bthName),L"%s",bHaveName ? pwsaResults->lpszServiceInstanceName : L"");
		{
			char name[1024];
			WideCharToMultiByte(CP_UTF8, 0, m_pEnd->bthName, -1, name, 1024, 0, 0);
			LOG(INFO)  + "RhoBluetoothManager::DiscoverDevices() FOUND = "+name;
		}
	}

	WSALookupServiceEnd(hLookup);
	LOG(INFO)  + "RhoBluetoothManager::DiscoverDevices() FINISH";
	//	LeaveCriticalSection(&criticalSection);
	return 0;
}
Exemplo n.º 4
0
static int
bthPerformServiceLookup (
    BluetoothServiceLookupResult *result,
    ULONGLONG address, GUID *guid,
    DWORD beginFlags, DWORD nextFlags
) {
    int found = 0;

    if (bthStartSockets()) {
        SOCKADDR_BTH socketAddress = {
            .addressFamily = AF_BTH,
            .btAddr = address
        };

        char addressString[0X100];
        DWORD addressLength = sizeof(addressString);

        if (WSAAddressToString((SOCKADDR *)&socketAddress, sizeof(socketAddress),
                               NULL,
                               addressString, &addressLength) != SOCKET_ERROR) {
            HANDLE handle;

            CSADDR_INFO csa[] = {
                {
                    .RemoteAddr = {
                        .lpSockaddr = (SOCKADDR *)&socketAddress,
                        .iSockaddrLength = sizeof(socketAddress)
                    }
                }
            };

            WSAQUERYSET restrictions = {
                .dwNameSpace = NS_BTH,
                .lpszContext = addressString,
                .lpcsaBuffer = csa,
                .dwNumberOfCsAddrs = ARRAY_COUNT(csa),
                .lpServiceClassId = guid,
                .dwSize = sizeof(restrictions)
            };

            if (WSALookupServiceBegin(&restrictions, (LUP_FLUSHCACHE | beginFlags), &handle) != SOCKET_ERROR) {
                DWORD resultLength = sizeof(*result);

                if (WSALookupServiceNext(handle, nextFlags, &resultLength, &result->querySet) != SOCKET_ERROR) {
                    found = 1;
                } else {
                    static const DWORD exceptions[] = {
#ifdef WSA_E_NO_MORE
                        WSA_E_NO_MORE,
#endif /* WSA_E_NO_MORE */

#ifdef WSAENOMORE
                        WSAENOMORE,
#endif /* WSAENOMORE */

                        NO_ERROR
                    };

                    bthSocketError("WSALookupServiceNext", exceptions);
                }

                if (WSALookupServiceEnd(handle) == SOCKET_ERROR) {
                    bthSocketError("WSALookupServiceEnd", NULL);
                }
            } else {
                bthSocketError("WSALookupServiceBegin", NULL);
            }
        } else {
Exemplo n.º 5
0
    DWORD           dwResultSize;

    // Fill out information for WSA query
    CloudInfo.dwSize = sizeof(CloudInfo);
    CloudInfo.Cloud.Scope = PNRP_LINK_LOCAL_SCOPE;
    
    blPnrpData.cbSize = sizeof(CloudInfo);
    blPnrpData.pBlobData = (LPBYTE)&CloudInfo;

    querySet.dwSize = sizeof(querySet);
    querySet.dwNameSpace = NS_PNRPCLOUD;
    querySet.lpServiceClassId = (LPGUID)&SVCID_PNRPCLOUD;
    querySet.lpBlob = &blPnrpData;

    iErr = WSALookupServiceBegin(
            &querySet, 
            LUP_RETURN_NAME|LUP_RETURN_BLOB, 
            &hLookup);

    if (iErr != 0)
    {
        hr = HRESULT_FROM_WIN32(WSAGetLastError());
    }

    if (SUCCEEDED(hr))
    {
        dwResultSize = sizeof(tempResultSet);

        // Get size of results
        iErr = WSALookupServiceNext(hLookup, 0, &dwResultSize, &tempResultSet);

		if (iErr != 0)
Exemplo n.º 6
0
// =============================================================================
// BTDeviceIsNear
// =============================================================================
bool BTDeviceIsNear() {
	//Initialising winsock
	WSADATA data;
	int result;
	result = WSAStartup(MAKEWORD(2, 2), &data);
	if (result != 0){
		MsgBox("An error occured while initialising winsock, closing....");
		return false;
	}

	//Initialising query for device
	WSAQUERYSET queryset;
	memset(&queryset, 0, sizeof(WSAQUERYSET));
	queryset.dwSize = sizeof(WSAQUERYSET);
	queryset.dwNameSpace = NS_BTH;

	HANDLE hLookup;
	result = WSALookupServiceBegin(&queryset, LUP_CONTAINERS, &hLookup);
	if (result != 0){
		MsgBox("An error occured while initialising look for devices, closing....");
		return false;
	}

	//Initialisation succeed, start looking for devices
	BYTE buffer[4096];
	memset(buffer, 0, sizeof(buffer));
	DWORD bufferLength = sizeof(buffer);
	WSAQUERYSET *pResults = (WSAQUERYSET*)&buffer;
	while (result == 0) {
		result = WSALookupServiceNext(hLookup,
			LUP_RETURN_NAME | LUP_CONTAINERS | LUP_RETURN_ADDR | LUP_FLUSHCACHE |
			LUP_RETURN_TYPE | LUP_RETURN_BLOB | LUP_RES_SERVICE,
			&bufferLength, pResults);
		if (result == 0) { // A device found
			LPTSTR deviceFoundName = pResults->lpszServiceInstanceName;
			PSOCKADDR_BTH sa = PSOCKADDR_BTH(pResults->lpcsaBuffer->RemoteAddr.lpSockaddr);

			if (sa->addressFamily != AF_BTH)
			{
				// Address family is not AF_BTH  for bluetooth device discovered
				continue;
			}
			//the MAC address is available in sa->btAddr
			printf("[HookExe] Device found\n");
			if ((deviceFoundName != NULL) &&
				(0 == _wcsicmp(deviceFoundName, convertCharArrayToLPCWSTR("btdevice")))) {
				printf("[HookExe] Found the device!\n");
				printf("[HookExe] Device name is %S\t Device addr is 0x%0x\n", deviceFoundName, sa->btAddr);
				if (BluetoothIsConnectable(hLookup)) {
				//if (pResults->dwOutputFlags == BTHNS_RESULT_DEVICE_CONNECTED) {
					printf("[HookExe] Device is CONNECTED!!! 0x%0x \n", pResults->dwOutputFlags);
				}
				else {
					printf("[HookExe] Device is NOOOOOOOT CONNECTED!!! - 0x%0x\n", pResults->dwOutputFlags);
				}
				
				return true;
			} else {
				printf("[HookExe] Didn't find the device...\n");
				printf("[HookExe] Device name is %S\t Device addr is 0x%0x\n", deviceFoundName, sa->btAddr);
			}
		}
	}
	
	WSALookupServiceEnd(hLookup);
	return false;
}
Exemplo n.º 7
0
//---------------------------------------------------------------------------
//  FUNCTION: void DoRnrClient (int nServiceType, char * pszServerName, DWORD dwNameSpace)
//
//  PURPOSE: Given the service type id "nServiceType", the server instance name
//           "pszServerName" and the name space to query "dwNameSpace", 
//           perform name resolution to the server and send a message to it.
//           If "nServiceType" is some known SAP Id such as Print Queue (3),
//           File Server (4), Job Server (5), Print Server (7), Archive
//           Server (9), Remote Bridge Server (36) or Advertising Print Server
//           (71), it will not send a message to the server.
//---------------------------------------------------------------------------
void DoRnrClient (int nServiceType, char * pszServerName, DWORD dwNameSpace)
{
    static GUID guid = SVCID_NETWARE ( nServiceType );  //use this as the class id
    WSAQUERYSET qs = {0};
    AFPROTOCOLS afp[g_nMaxNumOfSocks] = {{AF_IPX,  NSPROTO_IPX}, {AF_INET, IPPROTO_UDP}, {AF_INET6, IPPROTO_UDP}};
    HANDLE hLookup = NULL;
    DWORD dwResult = 0;
    static char szName[100] = {'\0'};
    BOOL fKnownSapId = FALSE;
    DWORD dwLength = 0;
    BYTE abyBuf[sizeof(WSAQUERYSET) + OFFSET] = {0}; // provide a sufficient large 
    // buffer for returned query set
    WSAQUERYSET * pQS = (WSAQUERYSETA*) abyBuf;
    HRESULT hRet;

    if(FAILED(hRet = StringCchCopy(szName,
                                   sizeof(szName)/sizeof(szName[0]),
                                   pszServerName
                                   )))
    {
        printf("StringCchCopy failed: 0x%x\n",hRet);
        return;
    }
    
    SecureZeroMemory (&qs, sizeof (WSAQUERYSET));
    qs.dwSize = sizeof (WSAQUERYSET);
    qs.lpszServiceInstanceName = szName; 
    qs.lpServiceClassId = &guid;
    qs.dwNameSpace = dwNameSpace;
    qs.dwNumberOfProtocols = g_nMaxNumOfSocks; 
    qs.lpafpProtocols = afp; 

    SecureZeroMemory (abyBuf, sizeof (WSAQUERYSET) + OFFSET);
    dwLength = sizeof(WSAQUERYSET) + OFFSET;

    // some well known SAP name space services
    if (nServiceType == 3 || nServiceType == 4 || nServiceType == 5 ||
        nServiceType == 7 || nServiceType == 9 || nServiceType == 36 || nServiceType == 71)
        fKnownSapId = TRUE;

    if (WSALookupServiceBegin ( &qs,
                                LUP_RETURN_ADDR | LUP_RETURN_NAME,
                                &hLookup) == SOCKET_ERROR)
    {
        PrintError("WSALookupServiceBegin");
        return;
    }

    printf ("Performing Query for service (type, name) = (%d, %s) . . .\n\n", nServiceType, pszServerName);

    if (strcmp(pszServerName, "*") == 0)
    {   // enumerate all service instances
        for (;;)
        {
            dwResult = WSALookupServiceNext(hLookup,
                                            0,
                                            &dwLength,
                                            pQS);
            if (dwResult == SOCKET_ERROR)
            {
                if (WSAGetLastError() == WSAEFAULT)
                {
                    printf("WSALookupServiceNext Error: Oops, we need a larger buffer size of : %d Bytes\n", dwLength);
                }
                else
                {
                    PrintError("WSALookupServiceNext");
                }
                WSALookupServiceEnd (hLookup);
                return;
            }

            if (!dwResult)
            {
                for (DWORD i = 0; i < pQS->dwNumberOfCsAddrs; i++)
                {
                    SOCKADDR_STORAGE *mypt = (SOCKADDR_STORAGE *) pQS->lpcsaBuffer[i].RemoteAddr.lpSockaddr;
                    if (mypt)
                    {
                        // we have valid remote sockaddr
                        char temp[DEFAULT_STRING_LEN] = {'\0'};

                        printf ("Name[%d]: %30s", i, pQS->lpszServiceInstanceName);
                        GetSockAddrString (mypt, pQS->lpcsaBuffer[i].RemoteAddr.iSockaddrLength, temp, DEFAULT_STRING_LEN);
                        printf("%40s\n", temp);

                        if (! fKnownSapId)
                            ClientSend(&(pQS->lpcsaBuffer[i]));
                    }
                }

            }
        }
    }
    else
    {
        dwResult = WSALookupServiceNext(hLookup,
                                        0,
                                        &dwLength,
                                        pQS);

        if (dwResult == SOCKET_ERROR)
        {
            if (WSAGetLastError() == WSAEFAULT)
            {
                printf("WSALookupServiceNext Error: Oops, we need a larger buffer size of : %d Bytes\n", dwLength);
            }
            else
            {
                PrintError("WSALookupServiceNext");
            }
            WSALookupServiceEnd (hLookup);
            return;
        }

        if (!dwResult)
        {
            for (DWORD i = 0; i < pQS->dwNumberOfCsAddrs; i++)
            {
                SOCKADDR_STORAGE *mypt = (SOCKADDR_STORAGE *) pQS->lpcsaBuffer[i].RemoteAddr.lpSockaddr;
                if (mypt)
                {
                    // we have valid remote sockaddr
                    char temp[DEFAULT_STRING_LEN] = {'\0'};
                    printf ("Name[%d]: %30s", i, pQS->lpszServiceInstanceName);
                    GetSockAddrString (mypt, pQS->lpcsaBuffer[i].RemoteAddr.iSockaddrLength, temp, DEFAULT_STRING_LEN);
                    printf("%40s\n", temp);

                    if (! fKnownSapId)
                        ClientSend(&(pQS->lpcsaBuffer[i]));
                }
            }       
        }
        WSALookupServiceEnd (hLookup);
    }   
}
Exemplo n.º 8
0
//
// Function: main
//
// Description:
//    Initialize Winsock and set up the WSAQUERYSET structure
//    for querying DNS. We use the special GUID 
//    SVCID_INET_HOSTADDRBYNAME for name resolution and we
//    query on the UDP and TCP protocols. The information
//    is returned as a BLOB so we must specify the LUP_RETURN_BLOB
//    flag. Once the call to WSALookupServiceBegin/Next is 
//    successful then decode the BLOB data into a real HOSTENT
//    and print the results.
//
int main(int argc, char **argv)
{
    WSADATA        wsd;
    WSAQUERYSET   *qs=NULL;
    char           buff[RNR_BUFFER_SIZE];
    GUID           HostnameGuid = SVCID_INET_HOSTADDRBYNAME;
    HANDLE         hRnr;
    AFPROTOCOLS    afproto[2] = { {AF_INET, IPPROTO_UDP}, 
                                  {AF_INET, IPPROTO_TCP} };
    DWORD          dwLength=RNR_BUFFER_SIZE;
    int            ret, i;
    LPBLOB         pvRet=NULL;
    HOSTENT       *hp=NULL;
    SOCKADDR_IN    addr;

    // Check for proper usage
    //
    if (argc != 2)
    {
        printf("usage: %s hostname\n", argv[0]);
        return -1;
    }
    // Load Winsock
    //
    if (WSAStartup(MAKEWORD(2,2), &wsd) != 0)
    {
        printf("WSAStartup() failed: %d\n", GetLastError());
        return -1;
    }
    // Initalize the WSAQUERYSET structure for the query
    //
    qs = (WSAQUERYSET *)buff;

    memset(qs, 0, sizeof(*qs));
    qs->dwSize = sizeof(WSAQUERYSET);
    qs->lpszServiceInstanceName = argv[1]; // name to resolve
    qs->lpServiceClassId = &HostnameGuid;
    qs->dwNameSpace = NS_ALL;              // or ND_DNS
    qs->dwNumberOfProtocols = 2;           // TCP and UDP
    qs->lpafpProtocols = afproto;
    
    ret = WSALookupServiceBegin(qs, LUP_RETURN_BLOB | LUP_RETURN_NAME,
                &hRnr);
    if (ret == NO_ERROR)
    {
        // We only have to call WSALookupServiceNext once because
        // the BLOB HOSTENT return will contain multiple addresses
        // if there are mutliple IP addresses associated with the
        // given name
        //
        ret = WSALookupServiceNext(hRnr, 0, &dwLength, qs);
        if (ret != NO_ERROR)
        {
            if (WSAGetLastError() == WSASERVICE_NOT_FOUND)
            {
                printf("No such name found!\n");
                WSALookupServiceEnd(hRnr);
                return 0;
            }
            printf("WSALookupServiceNext() failed: %d\n",
                WSAGetLastError());
        }
        WSALookupServiceEnd(hRnr);
    }
    // Make sure we got something returned
    //
    if (qs->lpBlob == NULL)
        return -1;
    //
    // Create our own buffer to hold the blob data
    //
    hp = (HOSTENT *)LocalAlloc(LPTR, qs->lpBlob->cbSize);
    if (!hp)
    {
        printf("LocalAlloc() failed: %d\n", GetLastError());
        return -1;
    }
    memcpy(hp, qs->lpBlob->pBlobData, qs->lpBlob->cbSize);
    //
    // Unpack the BLOB data so its meaningful
    //
    UnpackHostEnt(hp);
    //
    // Print out the addresses
    //
    for(i=0; hp->h_addr_list[i] ;i++)
    {
        memcpy(&addr.sin_addr, hp->h_addr_list[i], hp->h_length);
        printf("%s IP: %s\n", argv[1], inet_ntoa(addr.sin_addr));
    }
    for(i=0; hp->h_aliases[i] ;i++)
        printf("Alias: %s\n", hp->h_aliases[i]);

    // Cleanup
    //
    LocalFree(hp);

    WSACleanup();
    return 0;
}
void bluetoothDiscovery(ConnectivityBluetooth *conn)
{
	//BOOL bHaveName;
	HANDLE hScan = INVALID_HANDLE_VALUE;
	WSAQUERYSET wsaq;
	BTHNS_INQUIRYBLOB queryBlob;
	queryBlob.LAP = BT_ADDR_GIAC;
	queryBlob.num_responses = 10;
	queryBlob.length = 12;
	BLOB blob;
	int count = 0;
	BthInquiryResult *p_inqRes;
	union {
		CHAR buf[4096];
		SOCKADDR_BTH __unused;
	};
	const BluetoothAddress *addr;

	blob.cbSize = sizeof(queryBlob);
	blob.pBlobData = (BYTE *) & queryBlob;

	ZeroMemory(&wsaq, sizeof(wsaq));
	wsaq.dwSize = sizeof(wsaq);
	wsaq.dwNameSpace = NS_BTH;
	wsaq.lpcsaBuffer = NULL;
	wsaq.lpBlob = &blob;
	
	addr = conn->rootInterface->getAddress<BluetoothAddress>();

	if (!addr)
		return;

	CM_DBG("Doing scan on device %s - %s\n", conn->rootInterface->getName(), addr->getStr());

	if (ERROR_SUCCESS != WSALookupServiceBegin(&wsaq, LUP_CONTAINERS, &hScan)) {
		CM_DBG("WSALookupServiceBegin failed\n");
		return;
	}
	// loop the results
	while (!conn->shouldExit()) {
		DWORD dwSize = sizeof(buf);
		LPWSAQUERYSET pwsaResults = (LPWSAQUERYSET) buf;
		ZeroMemory(pwsaResults, sizeof(WSAQUERYSET));
		pwsaResults->dwSize = sizeof(WSAQUERYSET);
		pwsaResults->dwNameSpace = NS_BTH;
		pwsaResults->lpBlob = NULL;
		unsigned char macaddr[BT_ALEN];
		string name = "bluetooth device";
		bool report_interface = false;
		InterfaceStatus_t status;

		if (WSALookupServiceNext(hScan, LUP_RETURN_NAME | LUP_RETURN_ADDR | LUP_RETURN_BLOB, 
			&dwSize, pwsaResults) != ERROR_SUCCESS) {
			CM_DBG("Found %d Haggle devices\n", count);
			break;
		}

		p_inqRes = (BthInquiryResult *) pwsaResults->lpBlob->pBlobData;

		BT_ADDR btAddr = ((SOCKADDR_BTH *) pwsaResults->lpcsaBuffer->RemoteAddr.lpSockaddr)->btAddr;

		if (pwsaResults->lpszServiceInstanceName && *(pwsaResults->lpszServiceInstanceName)) {
			int namelen = wcslen(pwsaResults->lpszServiceInstanceName) + 1;
			char *tmp = new char[namelen];
			wcstombs(tmp, pwsaResults->lpszServiceInstanceName, namelen);
			name.clear();
			name = tmp;
			delete[] tmp;
		}

		btAddr2Mac(btAddr, macaddr);
		BluetoothAddress addr(macaddr);

		status = conn->is_known_interface(Interface::TYPE_BLUETOOTH, macaddr);

		if (status == INTERFACE_STATUS_HAGGLE) {
			report_interface = true;
		} else if (status == INTERFACE_STATUS_UNKNOWN) {
			//int ret = DetectRFCommChannel(&btAddr);
			int ret = findHaggleService(&btAddr);
			
			if (ret > 0) {
				report_interface = true;
				conn->report_known_interface(Interface::TYPE_BLUETOOTH, macaddr, true);
			} else if (ret == 0) {
				conn->report_known_interface(Interface::TYPE_BLUETOOTH, macaddr, false);
			}
		}
		if (report_interface) {
			CM_DBG("Found Haggle Bluetooth device [%s:%s]\n", 
				addr.getStr(), name.c_str());

			BluetoothInterface foundInterface(macaddr, name, &addr, IFFLAG_UP);

			conn->report_interface(&foundInterface, 
                                               conn->rootInterface, new ConnectivityInterfacePolicyTTL(2));
			count++;
		} else {
			CM_DBG("Bluetooth device [%s] is not a Haggle device\n", 
				addr.getStr());
		}
	}

	// cleanup
	WSALookupServiceEnd(hScan);

	return;
}
/* Some code stolen from BlueCove. */
static int findHaggleService(BT_ADDR *pb)
{
	BTHNS_RESTRICTIONBLOB queryservice;
	unsigned char uuid[] = HAGGLE_BLUETOOTH_SDP_UUID;
	BLOB blob;
	WSAQUERYSET queryset;
	SOCKADDR_BTH sa;
	HANDLE hLookupSearchServices;
	int found = 0;

	memset(&queryservice, 0, sizeof(queryservice));

	queryservice.type = SDP_SERVICE_SEARCH_REQUEST;

	convertUUIDBytesToGUID((char *) uuid, &queryservice.uuids[0].u.uuid128);

	//UUID is full 128 bits
	queryservice.uuids[0].uuidType = SDP_ST_UUID128;

	// build BLOB pointing to service query

	blob.cbSize = sizeof(queryservice);
	blob.pBlobData = (BYTE *) & queryservice;

	// build query
	memset(&queryset, 0, sizeof(WSAQUERYSET));

	queryset.dwSize = sizeof(WSAQUERYSET);
	queryset.dwNameSpace = NS_BTH;
	queryset.lpBlob = &blob;


	// Build address
	memset(&sa, 0, sizeof(sa));
	sa.addressFamily = AF_BT;
	sa.btAddr = *pb;
	CSADDR_INFO csai;
	memset(&csai, 0, sizeof(csai));
	csai.RemoteAddr.lpSockaddr = (sockaddr *) &sa;
	csai.RemoteAddr.iSockaddrLength = sizeof(sa);
	queryset.lpcsaBuffer = &csai;

	// begin query

	if (WSALookupServiceBegin(&queryset, 0, &hLookupSearchServices)) {
		int last_error = WSAGetLastError();
		CM_DBG("WSALookupServiceBegin error [%s]", StrError(last_error));
		return -1;
	}
	// fetch results
	int bufSize = 0x2000;
	void *buf = malloc(bufSize);

	if (buf == NULL) {
		WSALookupServiceEnd(hLookupSearchServices);
		return NULL;
	}
	memset(buf, 0, bufSize);

	LPWSAQUERYSET pwsaResults = (LPWSAQUERYSET) buf;
	pwsaResults->dwSize = sizeof(WSAQUERYSET);
	pwsaResults->dwNameSpace = NS_BTH;
	pwsaResults->lpBlob = NULL;

	DWORD size = bufSize;

	if (WSALookupServiceNext(hLookupSearchServices, LUP_RETURN_TYPE | LUP_RETURN_BLOB | LUP_RETURN_ADDR, &size, pwsaResults)) {
		int last_error = WSAGetLastError();

		switch (last_error) {
		case WSANO_DATA:
			//HAGGLE_DBG("SDP: no data\n");
			found = -1;
			break;
		case WSA_E_NO_MORE:
			//HAGGLE_DBG("End of SDP list\n");
			break;
		case WSAENOTCONN:
			found = -1;
			HAGGLE_DBG("Could not connect to SDP service\n");
			break;
		case WSASERVICE_NOT_FOUND:
			found = 0;
			HAGGLE_DBG("SDP Service not found\n");
			break;
		default:
			CM_DBG("WSALookupServiceNext error [%s]\n", StrError(last_error));
			found = -1;
		}
	} else {
		unsigned long cChannel = 0;
		found = 1;
		HAGGLE_DBG("Found Haggle service\n");
		if (ERROR_SUCCESS == FindRFCOMMChannel(
			pwsaResults->lpBlob->pBlobData,
			pwsaResults->lpBlob->cbSize,
			&cChannel)) {
			HAGGLE_DBG("RFCOMM channel is %d\n", (int)cChannel);
			found = cChannel;
		}
	}
	WSALookupServiceEnd(hLookupSearchServices);
	free(buf);

	return found;
}
Exemplo n.º 11
0
int
DNSlookup_name(
	const char *name,
	int ai_family,
	struct hostent **Addresses
)
{
	char buffer[sizeof(WSAQUERYSET) + 2048];
	WSAQUERYSET query;
	struct hostent *addr = NULL;
	char *bufaddr = NULL;
	char ** addrlist = &bufaddr;
	int addrcnt = 0;
	WSAQUERYSET *results = (WSAQUERYSET *) buffer;
	GUID	HostnameGUID = SVCID_INET_HOSTADDRBYNAME;
	HANDLE	handle;
	DWORD dwLength;
	int err = 0;
	int retcode = 0;
	int errcode = 0;
	DWORD i;

	/*
	 * First we must create a query set
	 */
	memset(&query, 0, sizeof(query));
	query.dwSize = sizeof(query);
	query.lpszServiceInstanceName = (char *)name;
	query.dwNameSpace = NS_DNS;
	query.lpServiceClassId = &HostnameGUID;

	err = WSALookupServiceBegin(&query,
                                 LUP_RETURN_NAME | LUP_RETURN_BLOB | LUP_RETURN_ADDR,
                                 &handle);

	if(err == SOCKET_ERROR)
	{
		/*
		 * Convert the error code and return
		 */
		return (ReturnCode(WSAGetLastError()));
	}

	/*
	 * Initially none
	 * Change if we get something
	 */
	retcode = EAI_NONAME;
	dwLength = sizeof(buffer);

	while(err == 0)		/* Drop out when error */
	{
		memset(&buffer, 0, dwLength);
		err = WSALookupServiceNext(
			                handle,
			                0,
			                &dwLength,
			                results);
		errcode = WSAGetLastError();
		if (results->dwNumberOfCsAddrs > 0)
		{
			if (addr == NULL)
			{
				addr = (struct hostent *) malloc(sizeof(struct hostent));
				memset(addr, 0, sizeof(struct hostent));
				addr->h_addrtype = (short) results->lpcsaBuffer->iSocketType;
				addr->h_length = sizeof(struct in_addr); /* Only passing back the address */
				addrlist = malloc(sizeof(char *));
				*addrlist = NULL;
			}
			for (i = 0; i < results->dwNumberOfCsAddrs; i++)
			{
				AddToAddresses(addrlist, &addrcnt, &results->lpcsaBuffer[i]);
			}
		}

	}
	if (addr != NULL)
	{
		addr->h_name = (char *) name;
		addr->h_addr_list = addrlist;
		retcode = 0;
		*Addresses = addr;
	}
	else
	{
#ifdef FORCE_DNSRETRY
		/*
		 * We do this or the error would never be logged
		 */
		if (errcode == WSANO_DATA)
			msyslog(LOG_ERR, "Address not found for %s", name);
#endif
		retcode = ReturnCode(errcode);
	}
	WSALookupServiceEnd(handle);
	return (retcode);
}
Exemplo n.º 12
0
// This just redundant!!!!
//
// TODO: use inquiry timeout SDP_DEFAULT_INQUIRY_SECONDS
// NameToBthAddr converts a bluetooth device name to a bluetooth address,
// if required by performing inquiry with remote name requests.
// This function demonstrates device inquiry, with optional LUP flags.
ULONG NameToBthAddr(const char * pszRemoteName, BTH_ADDR * pRemoteBtAddr)
{
	INT          iResult = 0, iRetryCount = 0;
	BOOL         bContinueLookup = FALSE, bRemoteDeviceFound = FALSE;
	ULONG        ulFlags = 0, ulPQSSize = sizeof(WSAQUERYSET);
	HANDLE       hLookup = 0;
	PWSAQUERYSET pWSAQuerySet = NULL;

	if ((pszRemoteName == NULL) || (pRemoteBtAddr == NULL))
	{
		printf("Remote name or address is NULL!\n");
		goto CleanupAndExit;
	}

	if ((pWSAQuerySet = (PWSAQUERYSET)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, ulPQSSize)) == NULL)
	{
		printf("!ERROR! | Unable to allocate memory for WSAQUERYSET!\n");
		goto CleanupAndExit;
	}
	else
		printf("HeapAlloc() for WSAQUERYSET is OK!\n");

	// Search for the device with the correct name
	for (iRetryCount = 0; !bRemoteDeviceFound && (iRetryCount < CXN_MAX_INQUIRY_RETRY); iRetryCount++)
	{
		// WSALookupServiceXXX() is used for both service search and device inquiry
		// LUP_CONTAINERS is the flag which signals that we're doing a device inquiry. 
		ulFlags = LUP_CONTAINERS;
		// Friendly device name (if available) will be returned in lpszServiceInstanceName
		ulFlags |= LUP_RETURN_NAME;
		// BTH_ADDR will be returned in lpcsaBuffer member of WSAQUERYSET
		ulFlags |= LUP_RETURN_ADDR;
		// Similar to:
		// ulFlags = LUP_CONTAINERS | LUP_RETURN_NAME | LUP_RETURN_ADDR;

		if (iRetryCount == 0)
		{
			printf("*INFO* | Inquiring device from cache...\n");
		}
		else
		{
			// Flush the device cache for all inquiries, except for the first inquiry
			//
			// By setting LUP_FLUSHCACHE flag, we're asking the lookup service to do
			// a fresh lookup instead of pulling the information from device cache.
			ulFlags |= LUP_FLUSHCACHE;

			// Pause for some time before all the inquiries after the first inquiry
			//
			// Remote Name requests will arrive after device inquiry has
			// completed.  Without a window to receive IN_RANGE notifications,
			// we don't have a direct mechanism to determine when remote
			// name requests have completed.
			printf("*INFO* | Unable to find device.  Waiting for %d seconds before re-inquiry...\n", CXN_DELAY_NEXT_INQUIRY);
			printf("I am sleeping for a while...\n");
			Sleep(CXN_DELAY_NEXT_INQUIRY * 1000);

			printf("*INFO* | Inquiring device ...\n");
		}

		// Start the lookup service
		iResult = 0;
		hLookup = 0;
		bContinueLookup = FALSE;
		ZeroMemory(pWSAQuerySet, ulPQSSize);
		pWSAQuerySet->dwNameSpace = NS_BTH;
		pWSAQuerySet->dwSize = sizeof(WSAQUERYSET);

		iResult = WSALookupServiceBegin(pWSAQuerySet, ulFlags, &hLookup);

		if ((iResult == NO_ERROR) && (hLookup != NULL))
		{
			printf("WSALookupServiceBegin() is fine!\n");
			bContinueLookup = TRUE;
		}
		else if (0 < iRetryCount)
		{
			printf("=CRITICAL= | WSALookupServiceBegin() failed with error code %d, Error = %d\n", iResult, WSAGetLastError());
			goto CleanupAndExit;
		}

		while (bContinueLookup)
		{
			// Get information about next bluetooth device
			//
			// Note you may pass the same WSAQUERYSET from LookupBegin
			// as long as you don't need to modify any of the pointer
			// members of the structure, etc.
			//
			// ZeroMemory(pWSAQuerySet, ulPQSSize);
			// pWSAQuerySet->dwNameSpace = NS_BTH;
			// pWSAQuerySet->dwSize = sizeof(WSAQUERYSET);
			if (WSALookupServiceNext(hLookup, ulFlags, &ulPQSSize, pWSAQuerySet) == NO_ERROR)
			{
				printf("WSALookupServiceNext() is OK lol!\n");

				if ((pWSAQuerySet->lpszServiceInstanceName != NULL))
				{
					// Found a remote bluetooth device with matching name.
					// Get the address of the device and exit the lookup.
					printf("Again, remote name: %S\n", pWSAQuerySet->lpszServiceInstanceName);
					// Need to convert to the 'standard' address format
					printf("Local address: %012X\n", pWSAQuerySet->lpcsaBuffer->LocalAddr);
					printf("Remote address: %012X\n", pWSAQuerySet->lpcsaBuffer->RemoteAddr);
					CopyMemory(pRemoteBtAddr, &((PSOCKADDR_BTH)pWSAQuerySet->lpcsaBuffer->RemoteAddr.lpSockaddr)->btAddr,
						sizeof(*pRemoteBtAddr));
					bRemoteDeviceFound = TRUE;
					bContinueLookup = FALSE;
				}
			}
			else
			{
				if ((iResult = WSAGetLastError()) == WSA_E_NO_MORE) //No more data
				{
					// No more devices found.  Exit the lookup.
					printf("No more device found...\n");
					bContinueLookup = FALSE;
				}
				else if (iResult == WSAEFAULT)
				{
					// The buffer for QUERYSET was insufficient.
					// In such case 3rd parameter "ulPQSSize" of function "WSALookupServiceNext()" receives
					// the required size.  So we can use this parameter to reallocate memory for QUERYSET.
					HeapFree(GetProcessHeap(), 0, pWSAQuerySet);
					pWSAQuerySet = NULL;
					if (NULL == (pWSAQuerySet = (PWSAQUERYSET)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, ulPQSSize)))
					{
						printf("!ERROR! | Unable to allocate memory for WSAQERYSET...\n");
						bContinueLookup = FALSE;
					}
					else
						printf("HeapAlloc() for WSAQERYSET is OK!\n");
				}
				else
				{
					printf("=CRITICAL= | WSALookupServiceNext() failed with error code %d\n", iResult);
					bContinueLookup = FALSE;
				}
			}
		}
		// End the lookup service
		WSALookupServiceEnd(hLookup);
	}

CleanupAndExit:
	if (NULL != pWSAQuerySet)
	{
		HeapFree(GetProcessHeap(), 0, pWSAQuerySet);
		pWSAQuerySet = NULL;
	}

	if (bRemoteDeviceFound)
	{
		return(0);
	}
	else
	{
		return(1);
	}
}