Skip to main content

HDD enumeration and info retreive - another way

In this part I tried to enumerate all physical hard disk drive (HDD) attached to the system and tried to query to those attached physical drive to get the disk information like Vendor ID, Product ID, Product Revision, Serial number etc.

In my last blog, I've tried to get physical hard disk drive count through volume map, but in this post, I tried get it through "SetupDiGetClassDevs" API. All the SetupDiXXX APIs are very powerful APIs. These APIs along with DeviceIoControl API helps to retrieve very useful information regarding devices. So, I'm not going to talk much on this rather let MSDN to speak about this APIs.

Let's see what are other information that we can get on HDD attached to the system through the usage of this API:

void printStorageDeviceProperty(UCHAR *outBuf, const DWORD returnedLength)
{
    PSTORAGE_DEVICE_DESCRIPTOR            devDesc;
    PUCHAR                              pUbuffer;

    devDesc = (PSTORAGE_DEVICE_DESCRIPTOR) outBuf;
           
    pUbuffer = (PUCHAR) outBuf;
    if ( devDesc->VendorIdOffset && pUbuffer[devDesc->VendorIdOffset] )
    {
        wprintf(L"Vendor ID       : " );
        for ( DWORD i = devDesc->VendorIdOffset; pUbuffer[i] != (UCHAR) NULL && i < returnedLength; i++ )
        {
            wprintf( L"%c", pUbuffer[i] );
        }
        wprintf(L"\n");
    }

    if ( devDesc->ProductIdOffset && pUbuffer[devDesc->ProductIdOffset] )
    {
        wprintf(L"Product ID       : " );
        for ( DWORD i = devDesc->ProductIdOffset; pUbuffer[i] != (UCHAR) NULL && i < returnedLength; i++ )
        {
            wprintf( L"%c", pUbuffer[i] );
        }
        wprintf(L"\n");
    }

    if ( devDesc->ProductRevisionOffset && pUbuffer[devDesc->ProductRevisionOffset] )
    {
        wprintf(L"Product Revision       : " );
        for ( DWORD i = devDesc->ProductRevisionOffset; pUbuffer[i] != (UCHAR) NULL && i < returnedLength; i++ )
        {
            wprintf( L"%c", pUbuffer[i] );
        }
        wprintf(L"\n");
    }

    if ( devDesc->SerialNumberOffset && pUbuffer[devDesc->SerialNumberOffset] )
    {
        wprintf(L"Serial Number       : " );
        for ( DWORD i = devDesc->SerialNumberOffset; pUbuffer[i] != (UCHAR) NULL && i < returnedLength; i++ )
        {
            wprintf( L"%c", pUbuffer[i] );
        }
        wprintf(L"\n");
    }
   
    wprintf(L"Removable Media : %s\n", ((devDesc->RemovableMedia) ? L"Yes..." : L"No..."));
}

void printMediaType(HANDLE hDevice)
{
    PGET_MEDIA_TYPES MediaTypes = {0};
    BOOL    status = FALSE;
    UCHAR   buffer[2048];
    ULONG    returnedLength;

    status = DeviceIoControl(hDevice, IOCTL_STORAGE_GET_MEDIA_TYPES_EX, NULL, 0, buffer, sizeof(buffer), &returnedLength, FALSE);

    if (!status)
    {
        wprintf(L"IOCTL_STORAGE_GET_MEDIA_TYPES_EX failed with error code%d.\n\n", GetLastError());
        return;
    }

    MediaTypes = (PGET_MEDIA_TYPES) buffer;
    switch(MediaTypes->DeviceType)
    {
        case FILE_DEVICE_DISK:
            wprintf(L"Media Type: Device Disk\n");
            break;
        case FILE_DEVICE_DISK_FILE_SYSTEM:
            wprintf(L"Media Type: Device Disk File System\n");
            break;
        case FILE_DEVICE_FILE_SYSTEM:
            wprintf(L"Media Type: File Device File System\n");
            break;
        default:
            wprintf(L"Media Type: Unknown");
            break;
    }

    // Device Media Info
    for (DWORD i = 0; i < MediaTypes->MediaInfoCount; i++)
    {
        wprintf(L"Bytes/Sector:        %ld\n", MediaTypes->MediaInfo[i].DeviceSpecific.DiskInfo.BytesPerSector);
        wprintf(L"No. of Cylinders: %I64d\n", MediaTypes->MediaInfo[i].DeviceSpecific.DiskInfo.Cylinders);
        // wprintf(L"Media Characteristics: %ld\n", MediaTypes->MediaInfo[i].DeviceSpecific.DiskInfo.MediaCharacteristics);
        switch(MediaTypes->MediaInfo[i].DeviceSpecific.DiskInfo.MediaType)
        {
        case FixedMedia:
            wprintf(L"Media Type:    FixedMedia\n");
            break;
        default:
            wprintf(L"Media Type:    Unknown...\n");
            break;
        }
        wprintf(L"No. of sides:        %ld\n", MediaTypes->MediaInfo[i].DeviceSpecific.DiskInfo.NumberMediaSides);
        wprintf(L"Sectors/track:    %ld\n", MediaTypes->MediaInfo[i].DeviceSpecific.DiskInfo.SectorsPerTrack);
        wprintf(L"Tracks/Cylinder:    %ld\n", MediaTypes->MediaInfo[i].DeviceSpecific.DiskInfo.TracksPerCylinder);
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    HDEVINFO hDevInfo;
    SP_DEVINFO_DATA DeviceInfoData;
    DWORD i;

    // Create a HDEVINFO with all HDD present in system.
    hDevInfo = SetupDiGetClassDevs((LPGUID)&GUID_DEVINTERFACE_DISK,
       0, // Enumerator
       0, DIGCF_PRESENT | DIGCF_INTERFACEDEVICE );

    if (hDevInfo == INVALID_HANDLE_VALUE)
    {
       return 1;
    }
   
    // Enumerate through all physical drive in Set.
    DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
    for(i=0; SetupDiEnumDeviceInfo(hDevInfo, i, &DeviceInfoData); i++)
    {
        LPTSTR buffer = NULL;
        DWORD buffersize = 0;

        SP_DEVICE_INTERFACE_DATA                interfaceData;
        PSP_DEVICE_INTERFACE_DETAIL_DATA        interfaceDetailData = NULL;
        HANDLE                                    hDevice;
        BOOL                                    status;
        DWORD                                    interfaceDetailDataSize;
        DWORD                                    reqBufSize;
        DWORD                                    errorCode;

        interfaceData.cbSize = sizeof (SP_INTERFACE_DEVICE_DATA);

        status = SetupDiEnumDeviceInterfaces (
            hDevInfo,                    // Interface Device Info handle
            0,                            // Device Info data
            (LPGUID)&DiskClassGuid,        // Interface registered by driver
            i,                            // Member
            &interfaceData                // Device Interface Data
        );

        status = SetupDiGetDeviceInterfaceDetail(hDevInfo, &interfaceData, NULL, 0, &reqBufSize, NULL);
        if(status == FALSE)
        {
            errorCode = GetLastError();
            if(errorCode != ERROR_INSUFFICIENT_BUFFER)
            {
                wprintf( L"SetupDiGetDeviceInterfaceDetail failed with error: %d\n", errorCode   );
                return FALSE;
            }
        }

        interfaceDetailDataSize = reqBufSize;
        interfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)LocalAlloc(LPTR, reqBufSize);

        interfaceDetailData->cbSize = sizeof (SP_INTERFACE_DEVICE_DETAIL_DATA);

        status = SetupDiGetDeviceInterfaceDetail(hDevInfo, &interfaceData, interfaceDetailData,
            interfaceDetailDataSize, &reqBufSize, NULL);

        if ( status == FALSE )
        {
            wprintf(L"Error in SetupDiGetDeviceInterfaceDetail failed with error: %d\n", GetLastError());
            return FALSE;
        }

        wprintf( L"Interface: %s\n", interfaceDetailData->DevicePath);

        hDevice = CreateFile(
                interfaceDetailData->DevicePath,    // device interface name
                GENERIC_READ | GENERIC_WRITE,       // dwDesiredAccess
                FILE_SHARE_READ | FILE_SHARE_WRITE, // dwShareMode
                NULL,                               // lpSecurityAttributes
                OPEN_EXISTING,                      // dwCreationDistribution
                0,                                  // dwFlagsAndAttributes
                NULL                                // hTemplateFile
                );

        if (interfaceDetailData)
            LocalFree(interfaceDetailData);

        if (hDevice == INVALID_HANDLE_VALUE)
        {
            wprintf(L"CreateFile failed with error: %d\n", GetLastError());
            return TRUE;
        }

        STORAGE_PROPERTY_QUERY                query;
        UCHAR                                outBuf[512];
        DWORD                                returnedLength;

       query.PropertyId = StorageDeviceProperty;
       query.QueryType = PropertyStandardQuery;
      
       status = DeviceIoControl( hDevice,               
                        IOCTL_STORAGE_QUERY_PROPERTY,
                        &query, sizeof( STORAGE_PROPERTY_QUERY ),
                        &outBuf, 512, &returnedLength, NULL
                        );

        if ( !status )
        {
            wprintf(L"IOCTL failed with error code: %d.\n\n", GetLastError() );
        }
        else
        {
            printStorageDeviceProperty(outBuf, returnedLength);
            printMediaType(hDevice);

            wprintf(L"\n\n");
        }

        if ( !CloseHandle(hDevice) )    
        {
            wprintf( L"Failed to close device.\n");
        }
    }    // End of for loop...

    if ( GetLastError() != NO_ERROR && GetLastError() != ERROR_NO_MORE_ITEMS )
    {
       return 1;
    }

    //  Cleanup
    SetupDiDestroyDeviceInfoList(hDevInfo);

    return 0;
}


The output looks like below:




Comments

Popular posts from this blog

Reversing char array without splitting the array to tokens

 I was reading about strdup, a C++ function and suddenly an idea came to my mind if this can be leveraged to aid in reversing a character array without splitting the array into words and reconstructing it again by placing spaces and removing trailing spaces. Again, I wanted an array to be passed as a function argument and an array size to be passed implicitly with the array to the function. Assumed, a well-formed char array has been passed into the function. No malformed array checking is done inside the function. So, the function signature and definition are like below: Below is the call from the client code to reverse the array without splitting tokens and reconstructing it. Finally, copy the reversed array to the destination.  For GNU C++, we should use strdup instead _strdup . On run, we get the following output: Demo code

A simple approach to generate Fibonacci series via multi-threading

T his is a very simple approach taken to generate the Fibonacci series through multithreading. Here instead of a function, used a function object. The code is very simple and self-explanatory.  #include <iostream> #include <mutex> #include <thread> class Fib { public:     Fib() : _num0(1), _num1(1) {}     unsigned long operator()(); private:     unsigned long _num0, _num1;     std::mutex mu; }; unsigned long Fib::operator()() {     mu.lock(); // critical section, exclusive access to the below code by locking the mutex     unsigned long  temp = _num0;     _num0 = _num1;     _num1 = temp + _num0;     mu.unlock();     return temp; } int main() {     Fib f;          int i = 0;     unsigned long res = 0, res2= 0, res3 = 0;     std::cout << "Fibonacci series: ";     while (i <= 15) {         std::thread t1([&] { res = f(); }); // Capturing result to respective variable via lambda         std::thread t2([&] { res2 = f(); });         std::thread t3(

Close a Window Application from another application.

 This is just a demo application code to show how the WM_CLOSE message can be sent to the target process which has a titled window to close the application. To achieve this, either we can use SendMessage or PostMessage APIs to send required Windows messages to the target application. Though both the APIs are dispatching WM_XXXXX message to target application two APIs has some differences, these are as below: 1. SendMessage () call is a blocking call but PostMessage is a non-blocking call(Asynchronous) 2. SendMessage() APIs return type is LRESULT (LONG_PTR) but PostMessage() APIs return type is BOOL(typedef int). In Short, SendMessage () APIs return type depends on what message has been sent to the Windowed target process. For the other one, it's always a non-zero value, which indicates the message has been successfully placed on the target process message queue. Now let's see how can I close a target windowed application "Solitaire & Casual Games" from my custom-