I am getting invalid access to memory location when I run the following code
WIN32_FIND_DATAW FD;
WCHAR cPath[MAX_PATH], cFindPath[MAX_PATH];
if (!GetCurrentDirectoryW(MAX_PATH, cPath))
ErrorExit("GetCurrentDirectory");
else
printf("Current Path: %s\n", cPath);
StringCchCopyW(cFindPath, MAX_PATH, cPath);
StringCchCatW(cFindPath, MAX_PATH, L"\\*");
BOOL bsuccess;
HANDLE hFind = FindFirstFileW(cFindPath, &FD);
if (INVALID_HANDLE_VALUE != hFind)
{
vector<wstring> links;
do
{
WCHAR fullFileName[MAX_PATH];
StringCchPrintfW(fullFileName, MAX_PATH, L"\\\\?\\%s\\%s", cPath, FD.cFileName);
DWORD dwBufSize = MAXIMUM_REPARSE_DATA_BUFFER_SIZE;
REPARSE_DATA_BUFFER* rdata;
rdata = (REPARSE_DATA_BUFFER*)malloc(dwBufSize);
DWORD bytesReturned;
HANDLE hFile = CreateFileW(fullFileName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, NULL);
if (INVALID_HANDLE_VALUE != hFile)
{
if (DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT, NULL, 0, &rdata, dwBufSize, &bytesReturned, NULL))
{
if (IsReparseTagMicrosoft(rdata->ReparseTag))
{
if (rdata->ReparseTag == IO_REPARSE_TAG_SYMLINK)
{
printf("Symbolic-Link\n");
size_t slen = rdata->SymbolicLinkReparseBuffer.SubstituteNameLength / sizeof(WCHAR);
WCHAR *szSubName = new WCHAR[slen + 1];
wcsncpy_s(szSubName, slen + 1, &rdata->SymbolicLinkReparseBuffer.PathBuffer[rdata->SymbolicLinkReparseBuffer.SubstituteNameOffset / sizeof(WCHAR)], slen);
szSubName[slen] = 0;
printf("SubstitutionName (len: %d): '%S'\n", rdata->SymbolicLinkReparseBuffer.SubstituteNameLength, szSubName);
delete[] szSubName;
size_t plen = rdata->SymbolicLinkReparseBuffer.PrintNameLength / sizeof(WCHAR);
WCHAR *szPrintName = new WCHAR[plen + 1];
wcsncpy_s(szPrintName, plen + 1, &rdata->SymbolicLinkReparseBuffer.PathBuffer[rdata->SymbolicLinkReparseBuffer.PrintNameOffset / sizeof(WCHAR)], plen);
szPrintName[plen] = 0;
printf("PrintName (len: %d): '%S'\n", rdata->SymbolicLinkReparseBuffer.PrintNameLength, szPrintName);
delete[] szPrintName;
}
else if (rdata->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT)
{
printf("Mount-Point\n");
size_t slen = rdata->MountPointReparseBuffer.SubstituteNameLength / sizeof(WCHAR);
WCHAR *szSubName = new WCHAR[slen + 1];
wcsncpy_s(szSubName, slen + 1, &rdata->MountPointReparseBuffer.PathBuffer[rdata->MountPointReparseBuffer.SubstituteNameOffset / sizeof(WCHAR)], slen);
szSubName[slen] = 0;
printf("SubstitutionName (len: %d): '%S'\n", rdata->MountPointReparseBuffer.SubstituteNameLength, szSubName);
delete[] szSubName;
size_t plen = rdata->MountPointReparseBuffer.PrintNameLength / sizeof(WCHAR);
WCHAR *szPrintName = new WCHAR[plen + 1];
wcsncpy_s(szPrintName, plen + 1, &rdata->MountPointReparseBuffer.PathBuffer[rdata->MountPointReparseBuffer.PrintNameOffset / sizeof(WCHAR)], plen);
szPrintName[plen] = 0;
printf("PrintName (len: %d): '%S'\n", rdata->MountPointReparseBuffer.PrintNameLength, szPrintName);
delete[] szPrintName;
}
else
{
printf("No Mount-Point or Symblic-Link...\n");
}
}
else
{
printf("Not a Microsoft-reparse point - could not query data!\n");
}
free(rdata);
}
else
ErrorExit("DeviceIoControl");
}
CloseHandle(hFile);
} while (FindNextFileW(hFind, &FD));
}
else
ErrorExit("FindFirstFile");
but the following code works fine.
HANDLE hFile;
LPCTSTR szMyFile = ("C:\\Documents and Settings"); // Mount-Point (JUNCTION)
//LPCTSTR szMyFile = _T("C:\\Users\\All Users"); // Symbolic-Link (SYMLINKD)
hFile = CreateFile(szMyFile, FILE_READ_EA, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
printf(("Could not open dir '%s'; error: %d\n"), szMyFile, GetLastError());
return;
}
// Allocate the reparse data structure
DWORD dwBufSize = MAXIMUM_REPARSE_DATA_BUFFER_SIZE;
REPARSE_DATA_BUFFER* rdata;
rdata = (REPARSE_DATA_BUFFER*)malloc(dwBufSize);
// Query the reparse data
DWORD dwRetLen;
BOOL bRet = DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT, NULL, 0, rdata, dwBufSize, &dwRetLen, NULL);
if (bRet == FALSE)
{
printf(("DeviceIoControl failed with error: %d\n"), GetLastError());
CloseHandle(hFile);
return;
}
CloseHandle(hFile);
if (IsReparseTagMicrosoft(rdata->ReparseTag))
{
if (rdata->ReparseTag == IO_REPARSE_TAG_SYMLINK)
{
printf("Symbolic-Link\n");
size_t slen = rdata->SymbolicLinkReparseBuffer.SubstituteNameLength / sizeof(WCHAR);
WCHAR *szSubName = new WCHAR[slen + 1];
wcsncpy_s(szSubName, slen + 1, &rdata->SymbolicLinkReparseBuffer.PathBuffer[rdata->SymbolicLinkReparseBuffer.SubstituteNameOffset / sizeof(WCHAR)], slen);
szSubName[slen] = 0;
printf("SubstitutionName (len: %d): '%S'\n", rdata->SymbolicLinkReparseBuffer.SubstituteNameLength, szSubName);
delete[] szSubName;
size_t plen = rdata->SymbolicLinkReparseBuffer.PrintNameLength / sizeof(WCHAR);
WCHAR *szPrintName = new WCHAR[plen + 1];
wcsncpy_s(szPrintName, plen + 1, &rdata->SymbolicLinkReparseBuffer.PathBuffer[rdata->SymbolicLinkReparseBuffer.PrintNameOffset / sizeof(WCHAR)], plen);
szPrintName[plen] = 0;
printf("PrintName (len: %d): '%S'\n", rdata->SymbolicLinkReparseBuffer.PrintNameLength, szPrintName);
delete[] szPrintName;
}
else if (rdata->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT)
{
printf("Mount-Point\n");
size_t slen = rdata->MountPointReparseBuffer.SubstituteNameLength / sizeof(WCHAR);
WCHAR *szSubName = new WCHAR[slen + 1];
wcsncpy_s(szSubName, slen + 1, &rdata->MountPointReparseBuffer.PathBuffer[rdata->MountPointReparseBuffer.SubstituteNameOffset / sizeof(WCHAR)], slen);
szSubName[slen] = 0;
printf("SubstitutionName (len: %d): '%S'\n", rdata->MountPointReparseBuffer.SubstituteNameLength, szSubName);
delete[] szSubName;
size_t plen = rdata->MountPointReparseBuffer.PrintNameLength / sizeof(WCHAR);
WCHAR *szPrintName = new WCHAR[plen + 1];
wcsncpy_s(szPrintName, plen + 1, &rdata->MountPointReparseBuffer.PathBuffer[rdata->MountPointReparseBuffer.PrintNameOffset / sizeof(WCHAR)], plen);
szPrintName[plen] = 0;
printf("PrintName (len: %d): '%S'\n", rdata->MountPointReparseBuffer.PrintNameLength, szPrintName);
delete[] szPrintName;
}
else
{
printf("No Mount-Point or Symblic-Link...\n");
}
}
else
{
printf(("Not a Microsoft-reparse point - could not query data!\n"));
}
free(rdata);
I am trying to get the reparse data for the files in a given folder. This is my REPARSE_DATA_BUFFER
typedef struct _REPARSE_DATA_BUFFER {
ULONG ReparseTag;
USHORT ReparseDataLength;
USHORT Reserved;
union {
struct {
USHORT SubstituteNameOffset;
USHORT SubstituteNameLength;
USHORT PrintNameOffset;
USHORT PrintNameLength;
ULONG Flags; // it seems that the docu is missing this entry (at least 2008-03-07)
WCHAR PathBuffer[1];
} SymbolicLinkReparseBuffer;
struct {
USHORT SubstituteNameOffset;
USHORT SubstituteNameLength;
USHORT PrintNameOffset;
USHORT PrintNameLength;
WCHAR PathBuffer[1];
} MountPointReparseBuffer;
struct {
UCHAR DataBuffer[1];
} GenericReparseBuffer;
};
} REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
I Dont know where I went wrong. Please help me fix my first code.
your code containing 2 errors how minimum
you unconditionally call FSCTL_GET_REPARSE_POINT for all files, but you must do this only
if (FD.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {..}
otherwise you got ERROR_NOT_A_REPARSE_POINT in DeviceIoControl and then ErrorExit("DeviceIoControl"); executed.
and second error at this line:
DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT, NULL, 0, &rdata, dwBufSize, &bytesReturned, NULL)
&rdata - !!
when must be
DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT, NULL, 0, rdata, dwBufSize, &bytesReturned, NULL)
Related
I need help with http get. I use vsc++ 2015. I have my own code, but it seems to be wrong, so I get reply from server in a strange format.
Example : 034a0686bc29ca826dbb2f1ea4dd1879═
so the Source is:
#include "Connection.h"
CConnector g_pConnector;
CConnector::CConnector() {
}
CConnector::~CConnector() {
}
void CConnector::Connect(char* Url, char* Host) { m_Url = Url; m_Host = Host; }
void CConnector::SendPOST(const char* data, std::string &sDestBuffer) { try { char httpUseragent[512]; DWORD szhttpUserAgent = sizeof(httpUseragent); ObtainUserAgentString(0, httpUseragent, &szhttpUserAgent);
CString sMsg = ""; sMsg += /*\r\ncontent-type: application/x-www-form-urlencoded*/"\r\ncontent-type: application/x-www-form-urlencoded"; sMsg += /*\r\ncontent-lenght:
*/"\r\ncontent-lenght: "; sMsg += std::to_string(strlen(data)).c_str(); sMsg += /*\r\nuser-agent: secret_agent\r\n\r\n*/"\r\nuser-agent: secret_agent\r\n\r\n";
HINTERNET internet = InternetOpenA(httpUseragent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); if (internet != NULL) {
HINTERNET connect = InternetConnectA(internet, m_Host, INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0); if (connect != NULL) {
HINTERNET request = HttpOpenRequestA(connect, /*POST*/"POST", m_Url, /*HTTP/1.1*/"HTTP/1.1", NULL, NULL,
INTERNET_FLAG_HYPERLINK | INTERNET_FLAG_IGNORE_CERT_CN_INVALID |
INTERNET_FLAG_IGNORE_CERT_DATE_INVALID |
INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP |
INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS |
INTERNET_FLAG_NO_AUTH |
INTERNET_FLAG_NO_CACHE_WRITE |
INTERNET_FLAG_NO_UI |
INTERNET_FLAG_PRAGMA_NOCACHE |
INTERNET_FLAG_RELOAD, NULL);
if (request != NULL)
{
int datalen = 0;
if (data != NULL) datalen = strlen(data);
int headerlen = 0;
if (!sMsg.IsEmpty()) headerlen = strlen(sMsg);
HttpSendRequestA(request, sMsg, headerlen, _strdup(data), datalen);
if (request)
{
DWORD dataSize = 0;
DWORD dwBytesRead = 0;
DWORD dwBytesWritten = 0;
char* data = NULL;
do {
char buffer[2000];
InternetReadFile(request, (LPVOID)buffer, _countof(buffer), &dwBytesRead);
char *tempData = new char[dataSize + dwBytesRead];
memcpy(tempData, data, dataSize);
memcpy(tempData + dataSize, buffer, dwBytesRead);
delete[] data;
data = tempData;
dataSize += dwBytesRead;
} while (dwBytesRead);
sDestBuffer = data;
}
InternetCloseHandle(request);
} } InternetCloseHandle(connect); } InternetCloseHandle(internet); } catch (...) {} }
void CConnector::SendGET(const char* data, std::string &sDestBuffer) { try { char httpUseragent[512]; DWORD szhttpUserAgent = sizeof(httpUseragent); ObtainUserAgentString(0, httpUseragent, &szhttpUserAgent);
CString sMsg = ""; CString Url = m_Url; Url += "?"; Url += data;
HINTERNET internet = InternetOpenA(httpUseragent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); if (internet != NULL) {
HINTERNET connect = InternetConnectA(internet, m_Host, INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0); if (connect != NULL) {
HINTERNET request = HttpOpenRequestA(connect, /*GET*/"GET", Url, /*HTTP/1.1*/"HTTP/1.1", NULL, NULL,
INTERNET_FLAG_HYPERLINK | INTERNET_FLAG_IGNORE_CERT_CN_INVALID |
INTERNET_FLAG_IGNORE_CERT_DATE_INVALID |
INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP |
INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS |
INTERNET_FLAG_NO_AUTH |
INTERNET_FLAG_NO_CACHE_WRITE |
INTERNET_FLAG_NO_UI |
INTERNET_FLAG_PRAGMA_NOCACHE |
INTERNET_FLAG_RELOAD, NULL);
if (request != NULL)
{
int datalen = 0;
if (data != NULL) datalen = strlen(data);
int headerlen = 0;
if (!sMsg.IsEmpty()) headerlen = strlen(sMsg);
HttpSendRequestA(request, sMsg, headerlen, _strdup(data), datalen);
if (request)
{
DWORD dataSize = 0;
DWORD dwBytesRead = 0;
DWORD dwBytesWritten = 0;
char* data = NULL;
do {
char buffer[2000];
InternetReadFile(request, (LPVOID)buffer, _countof(buffer), &dwBytesRead);
char *tempData = new char[dataSize + dwBytesRead];
memcpy(tempData, data, dataSize);
memcpy(tempData + dataSize, buffer, dwBytesRead);
delete[] data;
data = tempData;
dataSize += dwBytesRead;
} while (dwBytesRead);
sDestBuffer = data;
}
InternetCloseHandle(request);
} } InternetCloseHandle(connect); }
InternetCloseHandle(internet); } catch (...) {} }
and I try getting reply like this
std::string request;
char key[128];
g_pConnector.Connect(script.php?something=139, "sample.com");
g_pConnector.SendGET(key, request);
I try to write dll injector with nativeApi. For this reason, i wrote this code. NtReadFile function reads something but i cant see anything except for the first value of FileReadBuffer. Also, i dont know anything about how does dll look into buffer.
(1)How can i compare buffer and dll file?
(2)How can i be sure the code runs correct.
(3)And please tell me my mistake in the code.
bool Injector::initiationDll(const std::string& dllPath)
{
if (!isDllExist(dllPath))
{
printf("Dll not found!\n");
return false;
}
else
{
printf("LibraryPath: %s\n", dllPath);
NTSTATUS status; HANDLE lFile;
OBJECT_ATTRIBUTES objAttribs = { 0 }; UNICODE_STRING unicodeString;
std::string dllPathWithprefix = "\\??\\" + dllPath;
std::wstring wString = std::wstring(dllPathWithprefix.begin(), dllPathWithprefix.end()); PCWSTR toPcwstr = wString.c_str();
RtlInitUnicodeString(&unicodeString, toPcwstr);
InitializeObjectAttributes(&objAttribs, &unicodeString, OBJ_CASE_INSENSITIVE, NULL, NULL);
objAttribs.Attributes = 0;
const int allocSize = 2048;
LARGE_INTEGER largeInteger;
largeInteger.QuadPart = allocSize;
IO_STATUS_BLOCK ioStatusBlock;
status = NtCreateFile(
&lFile,
GENERIC_READ | FILE_READ_DATA | SYNCHRONIZE,
&objAttribs,
&ioStatusBlock,
&largeInteger,
FILE_ATTRIBUTE_NORMAL,
FILE_SHARE_READ | FILE_SHARE_WRITE,
FILE_OPEN,
FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT,
NULL,
0);
if (!NT_SUCCESS(status)) {
printf("CreateFile failed..\n");
return false;
}
else {
printf("Library Handle : %p\n", lFile);
DWORD fileSize = getDllSize(dllPath);
if (fileSize == 0)
{
printf("File size is zero.\n");
return false;
}
else
{
printf("File size : %d byte.\n", fileSize);
PVOID FileReadBuffer = VirtualAlloc(NULL, fileSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if (!FileReadBuffer)
{
printf("\nError: Unable to allocate memory(%d)\n", GetLastError());
status = NtClose(lFile);
return false;
}
else {
printf("Allocate %d byte for buffer.\n", fileSize);
status = NtReadFile(
lFile,
NULL,
NULL,
NULL,
&ioStatusBlock,
FileReadBuffer,
sizeof(FileReadBuffer),
0, // ByteOffset
NULL);
if (!NT_SUCCESS(status))
{
printf("Unable to read the dll... : %d\n", GetLastError());
return false;
}
else {
status = NtClose(lFile);
for (int i = 0; i < sizeof(fileSize); i++)
{
//wprintf(L"%p : %s\n", FileReadBuffer, FileReadBuffer);
}
}
}
}
}
}
}
status = NtReadFile(
lFile,
NULL,
NULL,
NULL,
&ioStatusBlock,
FileReadBuffer,
sizeof(FileReadBuffer), // !!!!!
0, // ByteOffset
NULL);
so you read sizeof(FileReadBuffer) - 4 or 8 bytes only. i view you use my advice from here
I use setup API functions to find a USB device then use createfile to communicate with it. i.e. using SetupDiGetClassDevs, SetupDiEnumDeviceInterfaces, SetupDiGetDeviceInterfaceDetail, etc.
I would like to be able to determine if the device is connected at USB2 speeds or USB3 speeds ie. SuperSpeed or not
How can I do this through the Windows APIs?
This is what I ended up going with. It's convoluted. Cant believe there isn't an easier way:
#include "stdafx.h"
#include <Windows.h>
#include <Setupapi.h>
#include <winusb.h>
#undef LowSpeed
#include <Usbioctl.h>
#include <iostream>
#include <string>
#include <memory>
#include <vector>
class Usb_Device
{
private:
std::wstring _driverKey;
char _speed;
public:
Usb_Device(int adapterNumber, std::wstring devicePath, char speed);
virtual char GetSpeed(std::wstring driverKey);
};
class Usb_Hub : public Usb_Device
{
private:
bool _isRootHub;
std::wstring _deviceDescription;
std::wstring _devicePath;
std::vector<std::unique_ptr<Usb_Device>> _devices;
public:
Usb_Hub(std::wstring devicePath, char speed);
virtual char GetSpeed(std::wstring driverKey) override;
};
class Usb_Controller
{
private:
GUID _interfaceClassGuid;
std::wstring _devicePath;
std::wstring _deviceDescription;
std::wstring _driverKey;
std::vector<std::unique_ptr<Usb_Device>> _devices;
public:
Usb_Controller();
char GetSpeed(std::wstring driverKey);
};
static std::unique_ptr<Usb_Device> BuildDevice(int portCount, std::wstring devicePath)
{
std::unique_ptr<Usb_Device> ret;
HANDLE handle = INVALID_HANDLE_VALUE;
DWORD bytes = -1;
DWORD bytesReturned = -1;
BOOL isConnected = FALSE;
char speed;
// Open a handle to the Hub device
handle = CreateFile(devicePath.c_str(), GENERIC_WRITE, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
if (handle != INVALID_HANDLE_VALUE)
{
bytes = sizeof(USB_NODE_CONNECTION_INFORMATION_EX);
PUSB_NODE_CONNECTION_INFORMATION_EX nodeConnection = (PUSB_NODE_CONNECTION_INFORMATION_EX)(new char[bytes]);
nodeConnection->ConnectionIndex = portCount;
if (DeviceIoControl(handle, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX, nodeConnection, bytes, nodeConnection, bytes, &bytesReturned, 0))
{
isConnected = nodeConnection->ConnectionStatus == USB_CONNECTION_STATUS::DeviceConnected;
speed = nodeConnection->Speed;
}
if (isConnected)
{
if (nodeConnection->DeviceDescriptor.bDeviceClass == 0x09 /*HubDevice*/)
{
bytes = sizeof(USB_NODE_CONNECTION_NAME);
PUSB_NODE_CONNECTION_NAME nodeConnectionName = (PUSB_NODE_CONNECTION_NAME)(new char[bytes]);
nodeConnectionName->ConnectionIndex = portCount;
if (DeviceIoControl(handle, IOCTL_USB_GET_NODE_CONNECTION_NAME, nodeConnectionName, bytes, nodeConnectionName, bytes, &bytesReturned, 0))
{
bytes = nodeConnectionName->ActualLength;
delete[] nodeConnectionName;
nodeConnectionName = (PUSB_NODE_CONNECTION_NAME)(new char[bytes]);
nodeConnectionName->ConnectionIndex = portCount;
if (DeviceIoControl(handle, IOCTL_USB_GET_NODE_CONNECTION_NAME, nodeConnectionName, bytes, nodeConnectionName, bytes, &bytesReturned, 0))
{
std::wstring name = std::wstring(L"\\\\?\\") + std::wstring(nodeConnectionName->NodeName);
ret = std::unique_ptr<Usb_Device>(new Usb_Hub(name, speed));
}
}
delete[] nodeConnectionName;
}
else
{
ret = std::unique_ptr<Usb_Device>(new Usb_Device(portCount, devicePath, speed));
}
}
else
{
// Chuck this device
}
delete[] nodeConnection;
CloseHandle(handle);
}
return ret;
}
Usb_Controller::Usb_Controller()
{
BOOL success = TRUE;
for (int index = 0; success; index++)
{
GUID guid;
HRESULT hr = CLSIDFromString(L"{3abf6f2d-71c4-462a-8a92-1e6861e6af27}", (LPCLSID)&guid);
unsigned char* ptr = new unsigned char[2048]; // Should really do two calls, but that's more effort
HDEVINFO deviceInfoHandle = SetupDiGetClassDevs(&guid, 0, 0, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
// Create a device interface data structure
SP_DEVICE_INTERFACE_DATA deviceInterfaceData = { 0 };
deviceInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
// Start the enumeration.
success = SetupDiEnumDeviceInterfaces(deviceInfoHandle, 0, &guid, index, &deviceInterfaceData);
if (success)
{
_interfaceClassGuid = deviceInterfaceData.InterfaceClassGuid;
// Build a DevInfo data structure.
SP_DEVINFO_DATA deviceInfoData = { 0 };
deviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
// Now we can get some more detailed informations.
DWORD nRequiredSize = 0;
SetupDiGetDeviceInterfaceDetail(deviceInfoHandle, &deviceInterfaceData, 0, 0, &nRequiredSize, 0);
if (ERROR_INSUFFICIENT_BUFFER == GetLastError())
{
PSP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)(new char[nRequiredSize]);
memset(deviceInterfaceDetailData, 0, nRequiredSize);
deviceInterfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
if (SetupDiGetDeviceInterfaceDetail(deviceInfoHandle, &deviceInterfaceData, deviceInterfaceDetailData, nRequiredSize, &nRequiredSize, &deviceInfoData))
{
_devicePath = deviceInterfaceDetailData->DevicePath;
// Get the device description and driver key name.
DWORD requiredSize = 0;
DWORD regType = REG_SZ;
if (SetupDiGetDeviceRegistryProperty(deviceInfoHandle, &deviceInfoData, SPDRP_DEVICEDESC, ®Type, ptr, 2048, &requiredSize))
{
_deviceDescription = reinterpret_cast<wchar_t*>(ptr);
}
if (SetupDiGetDeviceRegistryProperty(deviceInfoHandle, &deviceInfoData, SPDRP_DRIVER, ®Type, ptr, 2048, &requiredSize))
{
_driverKey = reinterpret_cast<wchar_t*>(ptr);
}
}
delete[] deviceInterfaceDetailData;
}
SetupDiDestroyDeviceInfoList(deviceInfoHandle);
std::unique_ptr<Usb_Device> hub(new Usb_Hub(_devicePath, -1));
_devices.push_back(std::move(hub));
}
else
{
success = false;
}
delete[] ptr;
}
}
char Usb_Controller::GetSpeed(std::wstring driverKey)
{
char speed = -1;
for (auto it = _devices.begin(); it != _devices.end() && speed == -1; ++it)
{
if (*it != nullptr)
{
speed = (*it)->GetSpeed(driverKey);
}
}
return speed;
}
Usb_Hub::Usb_Hub(std::wstring devicePath, char speed) :
Usb_Device(-1, devicePath, speed)
{
HANDLE handle1 = INVALID_HANDLE_VALUE;
HANDLE handle2 = INVALID_HANDLE_VALUE;
_deviceDescription = L"Standard-USB-Hub";
_devicePath = devicePath;
DWORD bytesReturned = -1;
DWORD bytes = -1;
BOOL success = TRUE;
// Open a handle to the host controller.
handle1 = CreateFile(devicePath.c_str(), GENERIC_WRITE, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
if (handle1 != INVALID_HANDLE_VALUE)
{
USB_ROOT_HUB_NAME rootHubName;
memset(&rootHubName, 0, sizeof(USB_ROOT_HUB_NAME));
// Get the root hub name.
if (DeviceIoControl(handle1, IOCTL_USB_GET_ROOT_HUB_NAME, nullptr, 0, &rootHubName, sizeof(USB_ROOT_HUB_NAME), &bytesReturned, 0))
{
if (rootHubName.ActualLength > 0)
{
PUSB_ROOT_HUB_NAME actualRootHubName = (PUSB_ROOT_HUB_NAME)(new char[rootHubName.ActualLength]);
if (DeviceIoControl(handle1, IOCTL_USB_GET_ROOT_HUB_NAME, nullptr, 0, actualRootHubName, rootHubName.ActualLength, &bytesReturned, 0))
{
_isRootHub = true;
_deviceDescription = L"RootHub";
_devicePath = std::wstring(L"\\\\?\\") + std::wstring(actualRootHubName->RootHubName);
}
delete[] actualRootHubName;
}
}
// Now let's open the hub (based upon the hub name we got above).
int PortCount = 0;
handle2 = CreateFile(_devicePath.c_str(), GENERIC_WRITE, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
if (handle2 != INVALID_HANDLE_VALUE)
{
bytes = sizeof(USB_NODE_INFORMATION);
PUSB_NODE_INFORMATION nodeInfo = (PUSB_NODE_INFORMATION)(new char[bytes]);
memset(nodeInfo, 0, sizeof(USB_NODE_INFORMATION));
nodeInfo->NodeType = USB_HUB_NODE::UsbHub;
// Get the hub information.
if (DeviceIoControl(handle2, IOCTL_USB_GET_NODE_INFORMATION, nodeInfo, bytes, nodeInfo, bytes, &bytesReturned, 0))
{
DWORD d = GetLastError();
PortCount = nodeInfo->u.HubInformation.HubDescriptor.bNumberOfPorts;
}
delete[] nodeInfo;
CloseHandle(handle2);
}
CloseHandle(handle1);
for (int index = 1; index <= PortCount; index++)
{
std::unique_ptr<Usb_Device> device = BuildDevice(index, _devicePath);
_devices.push_back(std::move(device));
}
}
else
{
success = FALSE;
}
}
char Usb_Hub::GetSpeed(std::wstring driverKey)
{
char speed = Usb_Device::GetSpeed(driverKey);
if (speed == -1)
{
for (auto it = _devices.begin(); it != _devices.end() && speed == -1; ++it)
{
if (*it != nullptr)
{
speed = (*it)->GetSpeed(driverKey);
}
}
}
return speed;
}
Usb_Device::Usb_Device(int adapterNumber, std::wstring devicePath, char speed)
{
_speed = speed;
HANDLE handle = CreateFile(devicePath.c_str(), GENERIC_WRITE, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
if (handle != INVALID_HANDLE_VALUE)
{
// Get the Driver Key Name (usefull in locating a device)
DWORD bytesReturned = -1;
DWORD bytes = sizeof(USB_NODE_CONNECTION_DRIVERKEY_NAME);
PUSB_NODE_CONNECTION_DRIVERKEY_NAME driverKey = (PUSB_NODE_CONNECTION_DRIVERKEY_NAME)(new char[bytes]);
driverKey->ConnectionIndex = adapterNumber;
// Use an IOCTL call to request the Driver Key Name
if (DeviceIoControl(handle, IOCTL_USB_GET_NODE_CONNECTION_DRIVERKEY_NAME, driverKey, bytes, driverKey, bytes, &bytesReturned, 0))
{
bytes = driverKey->ActualLength;
delete[] driverKey;
driverKey = (PUSB_NODE_CONNECTION_DRIVERKEY_NAME)(new char[bytes]);
driverKey->ConnectionIndex = adapterNumber;
if (DeviceIoControl(handle, IOCTL_USB_GET_NODE_CONNECTION_DRIVERKEY_NAME, driverKey, bytes, driverKey, bytes, &bytesReturned, 0))
{
_driverKey = driverKey->DriverKeyName;
}
}
delete[] driverKey;
CloseHandle(handle);
}
}
char Usb_Device::GetSpeed(std::wstring driverKey)
{
return _speed;
}
int main()
{
Usb_Controller controller;
GUID guid;
HRESULT hr = CLSIDFromString(L"{AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA}", (LPCLSID)&guid);
HDEVINFO deviceInfoHandle = SetupDiGetClassDevs(&guid, 0, 0, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
if (deviceInfoHandle != INVALID_HANDLE_VALUE)
{
int deviceIndex = 0;
while (true)
{
SP_DEVICE_INTERFACE_DATA deviceInterface = { 0 };
deviceInterface.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
if (SetupDiEnumDeviceInterfaces(deviceInfoHandle, 0, &guid, deviceIndex, &deviceInterface))
{
DWORD cbRequired = 0;
SetupDiGetDeviceInterfaceDetail(deviceInfoHandle, &deviceInterface, 0, 0, &cbRequired, 0);
if (ERROR_INSUFFICIENT_BUFFER == GetLastError())
{
PSP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetail = (PSP_DEVICE_INTERFACE_DETAIL_DATA)(new char[cbRequired]);
memset(deviceInterfaceDetail, 0, cbRequired);
deviceInterfaceDetail->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
if (!SetupDiGetDeviceInterfaceDetail(deviceInfoHandle, &deviceInterface, deviceInterfaceDetail, cbRequired, &cbRequired, 0))
{
deviceIndex++;
continue;
}
// Initialize the structure before using it.
memset(deviceInterfaceDetail, 0, cbRequired);
deviceInterfaceDetail->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
// Call the API a second time to retrieve the actual
// device path string.
BOOL status = SetupDiGetDeviceInterfaceDetail(
deviceInfoHandle, // Handle to device information set
&deviceInterface, // Pointer to current node in devinfo set
deviceInterfaceDetail, // Pointer to buffer to receive device path
cbRequired, // Length of user-allocated buffer
&cbRequired, // Pointer to arg to receive required buffer length
NULL); // Not interested in additional data
BOOL success = TRUE;
for (int i = 0; success; i++)
{
SP_DEVINFO_DATA deviceInterfaceData = { 0 };
deviceInterfaceData.cbSize = sizeof(SP_DEVINFO_DATA);
// Start the enumeration.
success = SetupDiEnumDeviceInfo(deviceInfoHandle, i, &deviceInterfaceData);
DWORD RequiredSize = 0;
DWORD regType = REG_SZ;
unsigned char* ptr = new unsigned char[2048];
if (SetupDiGetDeviceRegistryProperty(deviceInfoHandle, &deviceInterfaceData, SPDRP_DRIVER, ®Type, ptr, 2048, &RequiredSize))
{
char speed = controller.GetSpeed(reinterpret_cast<wchar_t*>(ptr));
std::wcout << std::wstring(reinterpret_cast<wchar_t*>(ptr)) << std::endl;
std::wcout << L"Speed: " << (int)speed << std::endl;
}
delete[] ptr;
}
auto hDeviceHandle = CreateFile(
deviceInterfaceDetail->DevicePath,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
NULL);
CloseHandle(hDeviceHandle);
delete[] deviceInterfaceDetail;
}
}
else
{
break;
}
++deviceIndex;
}
SetupDiDestroyDeviceInfoList(deviceInfoHandle);
}
return 0;
}
I guess you will have to try WinUSB in the link there's a sample code of detecting the speed of USB. If you want the description of WinUSB you will find it here.
Hi guys i am trying to get dll md5 hash but it is returning same value all the time, what i did wrong?
this dll is already loaded when i am trying to getHash
i am getting hash with getHash() method and calculating it with CalcHash
thnks in advanced.
#define BUFSIZE 1024
#define MD5LEN 16
int CalcHash(HANDLE hFile, char *md5sum)
{
BOOL bResult = FALSE;
HCRYPTPROV hProv = 0;
HCRYPTHASH hHash = 0;
BYTE rgbFile[BUFSIZE];
DWORD cbRead = 0;
BYTE rgbHash[MD5LEN];
DWORD cbHash = 0;
CHAR rgbDigits[] = "0123456789abcdef";
char byt[3];
int rc, err;
rc = CryptAcquireContext(&hProv, NULL, MS_STRONG_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
if(!rc)
{
err = GetLastError();
if(err==0x80090016)
{
//first time using crypto API, need to create a new keyset
rc=CryptAcquireContext(&hProv, NULL, MS_STRONG_PROV, PROV_RSA_FULL, CRYPT_NEWKEYSET);
if(!rc)
{
err=GetLastError();
return 0;
}
}
}
CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash);
while(bResult = ReadFile(hFile, rgbFile, BUFSIZE, &cbRead, NULL))
{
if (0 == cbRead)
{
break;
}
CryptHashData(hHash, rgbFile, cbRead, 0);
}
cbHash = MD5LEN;
CryptGetHashParam(hHash, HP_HASHVAL, rgbHash, &cbHash, 0);
md5sum[0] = 0;
for (DWORD i = 0; i < cbHash; i++)
{
sprintf(byt, "%c%c", rgbDigits[rgbHash[i] >> 4], rgbDigits[rgbHash[i] & 0xf]);
strcat(md5sum, byt);
}
CryptDestroyHash(hHash);
CryptReleaseContext(hProv, 0);
return 1;
}
char *getHash()
{
CalcHash(L"dsetup.dll", md5sum);
Logger(md5sum);
return md5sum;
}
once my opencl kernel file exceeds a certain length, it is not correctly loaded anymore. The program build log (clBuildProgram) returns lots of errors, where it seems like there are cuts in the middle of a line (example int test; -> error unknown identifier 't').
Here is the function with which I load the program source:
char * load_program_source(const char *filename)
{
FILE *fh;
char* source;
long lSize;
fh = fopen(filename, "r");
if (fh == 0)
return 0;
//Get Filesize
fseek(fh,0,SEEK_END);
lSize = ftell(fh);
rewind(fh);
source = (char *) malloc(lSize);
memset(source,'\0',lSize);
fread(source, sizeof(char), lSize, fh);
return source;
}
And here is the code where the program is build:
//load program from file, compile kernels
cl_program program[1];
cl_kernel kernel[13];
const char * filename = "addKernel.c";
char *program_source = load_program_source(filename);
program[0] = clCreateProgramWithSource(context, 1, (const char**)&program_source,
NULL, &err);
if (err == CL_OUT_OF_HOST_MEMORY){
textBox1->Text += "Error: out of Host Memory!\r\n";
}
else if (err == CL_INVALID_CONTEXT){
textBox1->Text += "Error: invalid Context!\r\n";
}
else if (err == CL_INVALID_VALUE){
textBox1->Text += "Error: invalid Value!\r\n";
}
err = clBuildProgram(program[0], 0, NULL, NULL, NULL, NULL);
textBox1->Text += "Program build error: " + err + "\r\n";
cl_build_status status;
size_t logSize;
clGetProgramBuildInfo(program[0], deviceID[0], CL_PROGRAM_BUILD_STATUS, sizeof(cl_build_status), &status, NULL);
clGetProgramBuildInfo(program[0], deviceID[0], CL_PROGRAM_BUILD_LOG, 0, NULL, &logSize);
char* programLog;
programLog = (char*)calloc(logSize + 1, sizeof(char));
clGetProgramBuildInfo(program[0], deviceID[0], CL_PROGRAM_BUILD_LOG, logSize + 1, programLog, NULL);
std::string tmp = std::string(programLog);
this->textBox1->Text += "Program build info: error=" + err + ", status=" + status + ", programLog:\r\n" + gcnew System::String(tmp.c_str()) + "\r\n" + "In case of an error please make sure that openCL has been initialized\r\n";
I would be happy if you cound help me out!
Try following code. If it doesn't help, attach your kernel source
File reading:
static char* Read_Source_File(const char *filename)
{
long int
size = 0,
res = 0;
char *src = NULL;
FILE *file = fopen(filename, "rb");
if (!file) return NULL;
if (fseek(file, 0, SEEK_END))
{
fclose(file);
return NULL;
}
size = ftell(file);
if (size == 0)
{
fclose(file);
return NULL;
}
rewind(file);
src = (char *)calloc(size + 1, sizeof(char));
if (!src)
{
src = NULL;
fclose(file);
return src;
}
res = fread(src, 1, sizeof(char) * size, file);
if (res != sizeof(char) * size)
{
fclose(file);
free(src);
return src;
}
src[size] = '\0'; /* NULL terminated */
fclose(file);
return src;
}
Programm building:
cl_int ret;
program = clCreateProgramWithSource(
context, 1, (const char**)&src_file, NULL, &ret);
if(ret != CL_SUCCESS){
fprintf(stderr, "Error with code %d happened.\n", ret);
}
// Warnings will be treated like errors, this is useful for debug
char build_params[] = {"-Werror"};
ret = clBuildProgram(program, 0, NULL, build_params, NULL, NULL);
if (ret != CL_SUCCESS)
{
size_t len = 0;
char *buffer;
clGetProgramBuildInfo(program,
device_id, CL_PROGRAM_BUILD_LOG, 0, NULL, &len);
buffer = calloc(len, sizeof(char));
clGetProgramBuildInfo(program,
device_id, CL_PROGRAM_BUILD_LOG, len, buffer, NULL);
fprintf(stderr, "%s\n", buffer);
free(buffer);
}