Пример #1
2
int usb_install_needs_restart_np(void)
{
  HDEVINFO dev_info;
  SP_DEVINFO_DATA dev_info_data;
  int dev_index = 0;
  SP_DEVINSTALL_PARAMS install_params;
  int ret = FALSE;

  dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
  dev_info = SetupDiGetClassDevs(NULL, NULL, NULL,
                                 DIGCF_ALLCLASSES | DIGCF_PRESENT);
  
  SetEnvironmentVariable("LIBUSB_NEEDS_REBOOT", "1");

  if(dev_info == INVALID_HANDLE_VALUE)
    {
      usb_error("usb_install_needs_restart_np(): getting "
                "device info set failed");
      return ret;
    }
  
  while(SetupDiEnumDeviceInfo(dev_info, dev_index, &dev_info_data))
    {
      memset(&install_params, 0, sizeof(SP_PROPCHANGE_PARAMS));
      install_params.cbSize = sizeof(SP_DEVINSTALL_PARAMS);

      if(SetupDiGetDeviceInstallParams(dev_info, &dev_info_data, 
                                       &install_params))
        {
          if(install_params.Flags & (DI_NEEDRESTART | DI_NEEDREBOOT))
            {
              usb_message("usb_install_needs_restart_np(): restart needed");
              ret = TRUE;
            }
        }
      
      dev_index++;
    }
  
  SetupDiDestroyDeviceInfoList(dev_info);

  return ret;
}
Пример #2
0
void
InformDriverOfChanges(BOOL NeedReboot,
                      IN PLPT_PROP_PARAMS LptPropParams)
{
    SP_DEVINSTALL_PARAMS spDevInstall;

    //
    // Now broadcast this change to the device manager
    //
    ZeroMemory(&spDevInstall, sizeof(SP_DEVINSTALL_PARAMS));
    spDevInstall.cbSize = sizeof(SP_DEVINSTALL_PARAMS);

    if (SetupDiGetDeviceInstallParams(LptPropParams->DeviceInfoSet,
                                      LptPropParams->DeviceInfoData,
                                      &spDevInstall)) {
        if (NeedReboot) {
            spDevInstall.Flags |= DI_PROPERTIES_CHANGE | DI_NEEDREBOOT;
        } else {
            spDevInstall.FlagsEx |= DI_FLAGSEX_PROPCHANGE_PENDING;
        }
        SetupDiSetDeviceInstallParams(LptPropParams->DeviceInfoSet,
                                      LptPropParams->DeviceInfoData,
                                      &spDevInstall);
    }
}
Пример #3
0
DWORD
__stdcall CoRequireReboot (
               IN     DI_FUNCTION               InstallFunction,
               IN     HDEVINFO                  DeviceInfoSet,
               IN     PSP_DEVINFO_DATA          DeviceInfoData,
               IN OUT PCOINSTALLER_CONTEXT_DATA Context
               )
{
	UNREFERENCED_PARAMETER(Context);

	OutputDebugString(TEXT("CoRequireReboot"));

	if (InstallFunction == DIF_INSTALLDEVICE)
	{
		SP_DEVINSTALL_PARAMS DevInstallParams;
		OutputDebugString(TEXT("  CoRequireReboot: DIF_INSTALLDEVICE"));
		DevInstallParams.cbSize = sizeof(SP_DEVINSTALL_PARAMS);
		
		if (SetupDiGetDeviceInstallParams(DeviceInfoSet, DeviceInfoData, &DevInstallParams))
		{
			OutputDebugString(TEXT("  CoRequireReboot: SetupDiGetDeviceInstallParams"));
			DevInstallParams.Flags |= DI_DONOTCALLCONFIGMG;
			DevInstallParams.Flags |= DI_NEEDREBOOT;
			if (SetupDiSetDeviceInstallParams(DeviceInfoSet, DeviceInfoData, &DevInstallParams))
			{
				OutputDebugString(TEXT("  CoRequireReboot: SetupDiSetDeviceInstallParams"));
			}
		}
	}

    return NO_ERROR;
}
Пример #4
0
static DECLSPEC_NOINLINE HRESULT
DifRemove(
    IN  HDEVINFO                    DeviceInfoSet,
    IN  PSP_DEVINFO_DATA            DeviceInfoData,
    IN  PCOINSTALLER_CONTEXT_DATA   Context
    )
{
    SP_DEVINSTALL_PARAMS            DeviceInstallParams;
    HRESULT                         Error;

    DeviceInstallParams.cbSize = sizeof (DeviceInstallParams);

    if (!SetupDiGetDeviceInstallParams(DeviceInfoSet,
                                       DeviceInfoData,
                                       &DeviceInstallParams))
        goto fail1;

    Log("Flags = %08x", DeviceInstallParams.Flags);

    if (!Context->PostProcessing) {
        Error = DifRemovePreProcess(DeviceInfoSet, DeviceInfoData, Context);

        if (Error == NO_ERROR)
            Error = ERROR_DI_POSTPROCESSING_REQUIRED; 
    } else {
        Error = Context->InstallResult;
        
        if (Error == NO_ERROR) {
            (VOID) DifRemovePostProcess(DeviceInfoSet, DeviceInfoData, Context);
        } else {
            PTCHAR  Message;

            Message = GetErrorMessage(Error);
            Log("NOT RUNNING (DifRemovePreProcess Error: %s)", Message);
            LocalFree(Message);
        }

        Error = NO_ERROR; 
    }

    return Error;

fail1:
    Error = GetLastError();

    {
        PTCHAR  Message;

        Message = GetErrorMessage(Error);
        Log("fail1 (%s)", Message);
        LocalFree(Message);
    }

    return Error;
}
Пример #5
0
static bool UpdateRebootRequired(HDEVINFO hDevInfo, PSP_DEVINFO_DATA pDevInfoData, BOOL *pRebootRequired)
{
  if (!pRebootRequired)
    return TRUE;

  if (*pRebootRequired)
    return TRUE;

  ULONG status = 0;
  ULONG problem = 0;

  *pRebootRequired =
      CM_Get_DevNode_Status(&status, &problem, pDevInfoData->DevInst, 0) == CR_SUCCESS &&
      (status & DN_NEED_RESTART) != 0;

  //if (*pRebootRequired)
  //  Trace("Enumerated status=0x%lX problem=0x%lX\n", status, problem);

  if (*pRebootRequired)
    return TRUE;

  SP_DEVINSTALL_PARAMS installParams;

  memset(&installParams, 0, sizeof(installParams));
  installParams.cbSize = sizeof(SP_DEVINSTALL_PARAMS);

  if (!SetupDiGetDeviceInstallParams(hDevInfo, pDevInfoData, &installParams)) {
    ShowLastError(MB_OK|MB_ICONSTOP, "SetupDiGetDeviceInstallParams()");
    return FALSE;
  }

  *pRebootRequired = (installParams.Flags & (DI_NEEDREBOOT|DI_NEEDRESTART)) ? TRUE : FALSE;

  //if (*pRebootRequired)
  //  Trace("Enumerated Flags=0x%lX\n", installParams.Flags);

  return TRUE;
}
Пример #6
0
static DECLSPEC_NOINLINE HRESULT
DifRemove(
    IN  HDEVINFO                    DeviceInfoSet,
    IN  PSP_DEVINFO_DATA            DeviceInfoData,
    IN  PCOINSTALLER_CONTEXT_DATA   Context
    )
{
    SP_DEVINSTALL_PARAMS            DeviceInstallParams;
    HRESULT                         Error;

    DeviceInstallParams.cbSize = sizeof (DeviceInstallParams);

    if (!SetupDiGetDeviceInstallParams(DeviceInfoSet,
                                       DeviceInfoData,
                                       &DeviceInstallParams))
        goto fail1;

    Log("Flags = %08x", DeviceInstallParams.Flags);

    Error = (!Context->PostProcessing) ?
            __DifRemovePreProcess(DeviceInfoSet, DeviceInfoData, Context) :
            __DifRemovePostProcess(DeviceInfoSet, DeviceInfoData, Context);

    return Error;

fail1:
    Error = GetLastError();

    {
        PTCHAR  Message;

        Message = GetErrorMessage(Error);
        Log("fail1 (%s)", Message);
        LocalFree(Message);
    }

    return Error;
}
Пример #7
0
NDASDI_API BOOL WINAPI 
NdasDiRemoveLegacyDevice(
	IN HWND hwndParent,
	IN LPCTSTR ServiceName,
	IN BOOL PresentOnly,
	OUT LPDWORD pdwRemovedDeviceCount OPTIONAL,
	OUT LPBOOL pbRebootRequired OPTIONAL,
	IN NDASDIREMOVEDEVICEERRCALLBACKPROC ErrorCallbackProc OPTIONAL,
	IN LPVOID Context OPTIONAL)
{
	_ASSERTE(!IsBadStringPtr(ServiceName, LINE_LEN));
	_ASSERTE(NULL == pbRebootRequired || !IsBadWritePtr(pbRebootRequired, sizeof(BOOL)));
	_ASSERTE(NULL == ErrorCallbackProc || !IsBadCodePtr((FARPROC)ErrorCallbackProc));

	BOOL fReturn = FALSE;
	BOOL fSuccess = FALSE;

    HDEVINFO DeviceInfoSet = INVALID_HANDLE_VALUE;
    SP_DEVINFO_DATA DeviceInfoData = {0};
	DWORD Flags = DIGCF_ALLCLASSES;
	
	if (PresentOnly) {
		Flags |= DIGCF_PRESENT;
	}
	
    //
    // Create a Device Information Set with all present devices.
    //
    DeviceInfoSet = SetupDiGetClassDevs(
		NULL, // All Classes
        0,
        hwndParent, 
        Flags); // All devices present on system

    if (INVALID_HANDLE_VALUE == DeviceInfoSet) {
		goto cleanup;
    }
    
	if (NULL != pbRebootRequired) {
		*pbRebootRequired = FALSE;
	}

	//
    //  Enumerate through all Devices.
    //
    DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);

	if (NULL != pdwRemovedDeviceCount) {
		*pdwRemovedDeviceCount = 0;
	}

	for (DWORD i = 0;
		SetupDiEnumDeviceInfo(DeviceInfoSet,i,&DeviceInfoData);
		++i)
    {
        DWORD DataT;
        LPTSTR buffer = NULL;
        DWORD buffersize = 0;
        
        //
        // We won't know the size of the HardwareID buffer until we call
        // this function. So call it with a null to begin with, and then 
        // use the required buffer size to Alloc the nessicary space.
        // Keep calling we have success or an unknown failure.
        //
        while (TRUE) {

			fSuccess = SetupDiGetDeviceRegistryProperty(
				DeviceInfoSet,
				&DeviceInfoData,
				SPDRP_SERVICE,
				&DataT,
				(PBYTE)buffer,
				buffersize,
				&buffersize);
			
			if (fSuccess) {
				break;
			}

            if (ERROR_INVALID_DATA == GetLastError()) {
                //
                // May be a Legacy Device with no HardwareID. Continue.
                //
                break;
            } else if (ERROR_INSUFFICIENT_BUFFER == GetLastError()) {
                //
                // We need to change the buffer size.
                //
                if (buffer) {
                    LocalFree(buffer);
				}
                buffer = (LPTSTR) LocalAlloc(LPTR,buffersize);

			} else {
                //
                // Unknown Failure.
                //
				if (ErrorCallbackProc) {
					BOOL fCont = ErrorCallbackProc(
						NDIRD_ERROR_GetDeviceRegistryProperty,
						DeviceInfoSet,
						&DeviceInfoData,
						GetLastError(),
						Context);
					if (fCont) {
					}
					fReturn = FALSE;
					goto cleanup;
				}
            }            
        }

		//
		// May be a Legacy Device with no HardwareID. Continue.
		//
        if (GetLastError() == ERROR_INVALID_DATA) {
            continue;
		}
        
        //
        // Service Name is REG_SZ (Not MultiSZ)
        //
		LPCTSTR p = buffer;
		DPNoise(_T("%s\n"), p);

		if (0 == lstrcmpi(ServiceName,p)) {

			DPNoise(_T("\n>>> %s <<<\n"), p);

			//
            // Worker function to remove device.
            //
				fSuccess = SetupDiCallClassInstaller(
				DIF_REMOVE, 
				DeviceInfoSet, 
				&DeviceInfoData);

			if (!fSuccess && ErrorCallbackProc) {
				BOOL fCont = ErrorCallbackProc(
					NDIRD_ERROR_CallRemoveToClassInstaller,
					DeviceInfoSet, 
					&DeviceInfoData, 
					GetLastError(), 
					Context);

				if (buffer) {
					LocalFree(buffer);
				}
				fReturn = FALSE;
				goto cleanup;
			}

			//
			// Get the installation param
			//
			if (NULL != pbRebootRequired) {

				SP_DEVINSTALL_PARAMS diParams = {0};
				diParams.cbSize = sizeof(SP_DEVINSTALL_PARAMS);

				fSuccess = SetupDiGetDeviceInstallParams(
					DeviceInfoSet,
					&DeviceInfoData,
					&diParams);

				_ASSERTE(fSuccess);

				*pbRebootRequired |= 
					(diParams.Flags & DI_NEEDREBOOT) ||
					(diParams.Flags & DI_NEEDRESTART);

			}

			if (NULL != pdwRemovedDeviceCount) {
				++(*pdwRemovedDeviceCount);
			}

            break;

		}

        if (buffer) {
			LocalFree(buffer);
		}
    }

    if ((NO_ERROR != GetLastError()) && 
		(ERROR_NO_MORE_ITEMS != GetLastError())) 
	{
		fReturn = FALSE;
	} else {
		fReturn = TRUE;
	}
    
    //
    //  Cleanup.
    //    
cleanup:

    DWORD err = GetLastError();

	if (INVALID_HANDLE_VALUE != DeviceInfoSet) {
		SetupDiDestroyDeviceInfoList(DeviceInfoSet);
	}
	
	SetLastError(err);

	return fReturn;
}
Пример #8
0
extern "C" DWORD InstallLoopBack(LPCTSTR pConnectionName, LPCTSTR ip, LPCTSTR mask)
{
    BOOL ok;
    DWORD ret = 0;
    GUID netGuid;
    HDEVINFO hDeviceInfo = INVALID_HANDLE_VALUE;
    SP_DEVINFO_DATA DeviceInfoData;
    SP_DRVINFO_DATA DriverInfoData;
    SP_DEVINSTALL_PARAMS  DeviceInstallParams;
    TCHAR className[MAX_PATH];
    TCHAR temp[MAX_PATH];
    DWORD index = 0;
    BOOL found = FALSE;
    BOOL registered = FALSE;
    BOOL destroyList = FALSE;
    PSP_DRVINFO_DETAIL_DATA pDriverInfoDetail;
    DWORD detailBuf[2048];    // for our purposes, 8k buffer is more
			      // than enough to obtain the hardware ID
			      // of the loopback driver.

    HKEY hkey = NULL;
    DWORD cbSize;
    DWORD dwValueType;
    TCHAR pCfgGuidString[40];

    // initialize the structure size
    DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
    DriverInfoData.cbSize = sizeof(SP_DRVINFO_DATA);

    // copy the net class GUID
    memcpy(&netGuid, &GUID_DEVCLASS_NET, sizeof(GUID_DEVCLASS_NET));

    // create an empty device info set associated with the net class GUID
    hDeviceInfo = SetupDiCreateDeviceInfoList(&netGuid, NULL);
    if (hDeviceInfo == INVALID_HANDLE_VALUE)
        return GetLastError();

    // get the class name from GUID
    ok = SetupDiClassNameFromGuid(&netGuid, className, MAX_PATH, NULL);
    if (!ok)
    {
        ret = GetLastError();
        goto cleanup;
    }

    // create a device info element and add the new device instance
    // key to registry
    ok = SetupDiCreateDeviceInfo(hDeviceInfo, className, &netGuid, NULL, NULL,
                                 DICD_GENERATE_ID, &DeviceInfoData);
    if (!ok)
    {
        ret = GetLastError();
        goto cleanup;
    }

    // select the newly created device info to be the currently
    // selected member
    ok = SetupDiSetSelectedDevice(hDeviceInfo, &DeviceInfoData);
    if (!ok)
    {
        ret = GetLastError();
        goto cleanup;
    }

    // build a list of class drivers
    ok = SetupDiBuildDriverInfoList(hDeviceInfo, &DeviceInfoData,
                                    SPDIT_CLASSDRIVER);
    if (!ok)
    {
        ret = GetLastError();
        goto cleanup;
    }

    destroyList = TRUE;

    // enumerate the driver info list
    while (TRUE)
    {
        BOOL ret;

	ret = SetupDiEnumDriverInfo(hDeviceInfo, &DeviceInfoData,
				  SPDIT_CLASSDRIVER, index, &DriverInfoData);

	// if the function failed and GetLastError() returned
	// ERROR_NO_MORE_ITEMS, then we have reached the end of the
	// list.  Othewise there was something wrong with this
	// particular driver.
	if(!ret) {
	  if(GetLastError() == ERROR_NO_MORE_ITEMS)
	    break;
	  else {
	    index++;
	    continue;
	  }
	}

	pDriverInfoDetail = (PSP_DRVINFO_DETAIL_DATA) detailBuf;
	pDriverInfoDetail->cbSize = sizeof(SP_DRVINFO_DETAIL_DATA);

	// if we successfully find the hardware ID and it turns out to
	// be the one for the loopback driver, then we are done.
	if (SetupDiGetDriverInfoDetail(hDeviceInfo,
				      &DeviceInfoData,
				      &DriverInfoData,
				      pDriverInfoDetail,
				      sizeof(detailBuf),
				      NULL)) {
            TCHAR * t;

	    // pDriverInfoDetail->HardwareID is a MULTISZ string.  Go through the
	    // whole list and see if there is a match somewhere.
	    t = pDriverInfoDetail->HardwareID;
	    while (t && *t && t < (TCHAR *) &detailBuf[sizeof(detailBuf)/sizeof(detailBuf[0])]) {
	      if (!_tcsicmp(t, DRIVERHWID))
		break;

	      t += _tcslen(t) + 1;
	    }

	    if (t && *t && t < (TCHAR *) &detailBuf[sizeof(detailBuf)/sizeof(detailBuf[0])]) {
	      found = TRUE;
	      break;
	    }
	}

        index++;
    }

    if (!found)
    {
        ret = GetLastError();
        ReportMessage(0,"Could not find the driver to install", DRIVER_DESC, NULL, 0);
        goto cleanup;
    }

    // set the loopback driver to be the currently selected
    ok = SetupDiSetSelectedDriver(hDeviceInfo, &DeviceInfoData,
                                  &DriverInfoData);
    if (!ok)
    {
        ret = GetLastError();
        goto cleanup;
    }

    // register the phantom device to repare for install
    ok = SetupDiCallClassInstaller(DIF_REGISTERDEVICE, hDeviceInfo,
                                   &DeviceInfoData);
    if (!ok)
    {
        ret = GetLastError();
        goto cleanup;
    }

    // registered, but remove if errors occur in the following code
    registered = TRUE;

    // ask the installer if we can install the device
    ok = SetupDiCallClassInstaller(DIF_ALLOW_INSTALL, hDeviceInfo,
                                   &DeviceInfoData);
    if (!ok)
    {
        ret = GetLastError();
        if (ret != ERROR_DI_DO_DEFAULT)
        {
            goto cleanup;
        }
        else
            ret = 0;
    }

    // install the files first
    ok = SetupDiCallClassInstaller(DIF_INSTALLDEVICEFILES, hDeviceInfo,
                                   &DeviceInfoData);
    if (!ok)
    {
        ret = GetLastError();
        goto cleanup;
    }

    // get the device install parameters and disable filecopy
    DeviceInstallParams.cbSize = sizeof(SP_DEVINSTALL_PARAMS);
    ok = SetupDiGetDeviceInstallParams(hDeviceInfo, &DeviceInfoData,
                                       &DeviceInstallParams);
    if (ok)
    {
        DeviceInstallParams.Flags |= DI_NOFILECOPY;
        ok = SetupDiSetDeviceInstallParams(hDeviceInfo, &DeviceInfoData,
                                           &DeviceInstallParams);
        if (!ok)
        {
            ret = GetLastError();
            goto cleanup;
        }
    }

    //
    // Register any device-specific co-installers for this device,
    //

    ok = SetupDiCallClassInstaller(DIF_REGISTER_COINSTALLERS,
                                   hDeviceInfo,
                                   &DeviceInfoData);
    if (!ok)
    {
        ret = GetLastError();
        goto cleanup;
    }

    //
    // install any  installer-specified interfaces.
    // and then do the real install
    //
    ok = SetupDiCallClassInstaller(DIF_INSTALLINTERFACES,
                                   hDeviceInfo,
                                   &DeviceInfoData);
    if (!ok)
    {
        ret = GetLastError();
        goto cleanup;
    }
    PAUSE;
    ok = SetupDiCallClassInstaller(DIF_INSTALLDEVICE,
                                   hDeviceInfo,
                                   &DeviceInfoData);
    if (!ok)
    {
        ret = GetLastError();
        PAUSE;
        goto cleanup;
    }

    /* Skip to the end if we aren't setting the name */
    if (!pConnectionName) goto cleanup;

    // Figure out NetCfgInstanceId
    hkey = SetupDiOpenDevRegKey(hDeviceInfo,
                                &DeviceInfoData,
                                DICS_FLAG_GLOBAL,
                                0,
                                DIREG_DRV,
                                KEY_READ);
    if (hkey == INVALID_HANDLE_VALUE)
    {
        ret = GetLastError();
        goto cleanup;
    }

    cbSize = sizeof(pCfgGuidString);
    ret = RegQueryValueEx(hkey, _T("NetCfgInstanceId"), NULL,
                          &dwValueType, (LPBYTE)pCfgGuidString, &cbSize);
    RegCloseKey(hkey);

    ret = RenameConnection(pCfgGuidString, pConnectionName);
    if (ret)
    {
        ReportMessage(0,"Could not set the connection name", NULL, pConnectionName, 0);
        goto cleanup;
    }

    if (!ip) goto cleanup;
    ret = SetIpAddress(pCfgGuidString, ip, mask);
    if (ret)
    {
        ReportMessage(0,"Could not set the ip address and network mask",NULL,NULL,ret);
        goto cleanup;
    }
    ret = LoopbackBindings(pCfgGuidString);
    if (ret)
    {
        ReportMessage(0,"Could not properly set the bindings",NULL,NULL,0);
        goto cleanup;
    }
    ret = !UpdateHostsFile( pConnectionName, ip, "hosts", FALSE );
    if (ret)
    {
        ReportMessage(0,"Could not update hosts file",NULL,NULL,0);
        goto cleanup;
    }
    ret = !UpdateHostsFile( pConnectionName, ip, "lmhosts", TRUE );
    if (ret)
    {
        ReportMessage(0,"Could not update lmhosts file",NULL,NULL,0);
        goto cleanup;
    }


cleanup:
    // an error has occured, but the device is registered, we must remove it
    if (ret != 0 && registered)
        SetupDiCallClassInstaller(DIF_REMOVE, hDeviceInfo, &DeviceInfoData);

    found = SetupDiDeleteDeviceInfo(hDeviceInfo, &DeviceInfoData);

    // destroy the driver info list
    if (destroyList)
        SetupDiDestroyDriverInfoList(hDeviceInfo, &DeviceInfoData,
                                     SPDIT_CLASSDRIVER);
    // clean up the device info set
    if (hDeviceInfo != INVALID_HANDLE_VALUE)
        SetupDiDestroyDeviceInfoList(hDeviceInfo);

    return ret;
};
Пример #9
0
bool remove(const std::wstring& hardware_id, bool& reboot_required)
{
	bool result = false;

	HDEVINFO devices = SetupDiGetClassDevsEx(NULL, NULL, NULL, DIGCF_ALLCLASSES | DIGCF_PRESENT, NULL, NULL, NULL);

	if (devices != INVALID_HANDLE_VALUE)
	{
		std::wcerr << "Got device information set." << std::endl;

		SP_DEVINFO_LIST_DETAIL_DATA device_info_list_detail;
		memset(&device_info_list_detail, 0x00, sizeof(device_info_list_detail));
		device_info_list_detail.cbSize = sizeof(device_info_list_detail);

		if (SetupDiGetDeviceInfoListDetail(devices, &device_info_list_detail))
		{
			std::wcerr << "Got device information list details." << std::endl;

			SP_DEVINFO_DATA device_info;
			device_info.cbSize = sizeof(device_info);

			for (DWORD index = 0; SetupDiEnumDeviceInfo(devices, index, &device_info); ++index)
			{
				TCHAR device_id[MAX_DEVICE_ID_LEN];

				if (CM_Get_Device_ID_Ex(device_info.DevInst, device_id, MAX_DEVICE_ID_LEN, 0, device_info_list_detail.RemoteMachineHandle) == CR_SUCCESS)
				{
					std::list<std::wstring> device_hardware_id_list;

					if (getDeviceProperty(devices, device_info, SPDRP_HARDWAREID, device_hardware_id_list))
					{
						bool match = false;

						for (std::list<std::wstring>::const_iterator device_hardware_id = device_hardware_id_list.begin(); device_hardware_id != device_hardware_id_list.end(); ++device_hardware_id)
						{
							if (*device_hardware_id == hardware_id)
							{
								match = true;

								break;
							}
						}

						if (match)
						{
							std::wstring friendly_name;

							if (getDeviceProperty(devices, device_info, SPDRP_FRIENDLYNAME, friendly_name) && (friendly_name.length() > 0))
							{
								std::wcerr << "Removing device: " << friendly_name << " (" << device_id << ")" << std::endl;
							} else
							{
								std::wcerr << "Removing device: " << device_id << std::endl;
							}

							SP_REMOVEDEVICE_PARAMS remove_device_params;
							remove_device_params.ClassInstallHeader.cbSize = sizeof(SP_CLASSINSTALL_HEADER);
							remove_device_params.ClassInstallHeader.InstallFunction = DIF_REMOVE;
							remove_device_params.Scope = DI_REMOVEDEVICE_GLOBAL;
							remove_device_params.HwProfile = 0;

							result = true;

							if (!SetupDiSetClassInstallParams(devices, &device_info, &remove_device_params.ClassInstallHeader, sizeof(remove_device_params)) || 
									!SetupDiCallClassInstaller(DIF_REMOVE, devices, &device_info))
							{
								std::wcerr << "Failed to set the class installer." << std::endl;

								result = false;
							}

							if (result)
							{
								reboot_required = false;

								SP_DEVINSTALL_PARAMS device_params;

								if (SetupDiGetDeviceInstallParams(devices, &device_info, &device_params))
								{
									if (device_params.Flags & (DI_NEEDRESTART | DI_NEEDREBOOT))
									{
										reboot_required = true;
									}
								}
							}
						}
					}
				}
			}
		}

		SetupDiDestroyDeviceInfoList(devices);
	}

	return result;
}
Пример #10
0
/*
* @implemented
*/
BOOL WINAPI
DevInstallW(
    IN HWND hWndParent,
    IN HINSTANCE hInstance,
    IN LPCWSTR InstanceId,
    IN INT Show)
{
    PDEVINSTDATA DevInstData = NULL;
    BOOL ret;
    DWORD config_flags;
    BOOL retval = FALSE;

    TRACE("(%p, %p, %s, %d)\n", hWndParent, hInstance, debugstr_w(InstanceId), Show);

    if (!IsUserAdmin())
    {
        /* XP kills the process... */
        ExitProcess(ERROR_ACCESS_DENIED);
    }

    DevInstData = HeapAlloc(GetProcessHeap(), 0, sizeof(DEVINSTDATA));
    if (!DevInstData)
    {
        TRACE("HeapAlloc() failed\n");
        SetLastError(ERROR_NOT_ENOUGH_MEMORY);
        goto cleanup;
    }

    /* Clear devinst data */
    ZeroMemory(DevInstData, sizeof(DEVINSTDATA));
    DevInstData->devInfoData.cbSize = 0; /* Tell if the devInfoData is valid */

    /* Fill devinst data */
    DevInstData->hDevInfo = SetupDiCreateDeviceInfoListExW(NULL, NULL, NULL, NULL);
    if (DevInstData->hDevInfo == INVALID_HANDLE_VALUE)
    {
        TRACE("SetupDiCreateDeviceInfoListExW() failed with error 0x%x\n", GetLastError());
        goto cleanup;
    }

    DevInstData->devInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
    ret = SetupDiOpenDeviceInfoW(
        DevInstData->hDevInfo,
        InstanceId,
        NULL,
        0, /* Open flags */
        &DevInstData->devInfoData);
    if (!ret)
    {
        TRACE("SetupDiOpenDeviceInfoW() failed with error 0x%x (InstanceId %s)\n",
            GetLastError(), debugstr_w(InstanceId));
        DevInstData->devInfoData.cbSize = 0;
        goto cleanup;
    }

    SetLastError(ERROR_GEN_FAILURE);
    ret = SetupDiGetDeviceRegistryProperty(
        DevInstData->hDevInfo,
        &DevInstData->devInfoData,
        SPDRP_DEVICEDESC,
        &DevInstData->regDataType,
        NULL, 0,
        &DevInstData->requiredSize);

    if (!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER && DevInstData->regDataType == REG_SZ)
    {
        DevInstData->buffer = HeapAlloc(GetProcessHeap(), 0, DevInstData->requiredSize);
        if (!DevInstData->buffer)
        {
            TRACE("HeapAlloc() failed\n");
            SetLastError(ERROR_NOT_ENOUGH_MEMORY);
        }
        else
        {
            ret = SetupDiGetDeviceRegistryPropertyW(
                DevInstData->hDevInfo,
                &DevInstData->devInfoData,
                SPDRP_DEVICEDESC,
                &DevInstData->regDataType,
                DevInstData->buffer, DevInstData->requiredSize,
                &DevInstData->requiredSize);
        }
    }
    if (!ret)
    {
        TRACE("SetupDiGetDeviceRegistryProperty() failed with error 0x%x (InstanceId %s)\n",
            GetLastError(), debugstr_w(InstanceId));
        goto cleanup;
    }

    if (SetupDiGetDeviceRegistryPropertyW(
        DevInstData->hDevInfo,
        &DevInstData->devInfoData,
        SPDRP_CONFIGFLAGS,
        NULL,
        (BYTE *)&config_flags,
        sizeof(config_flags),
        NULL))
    {
        if (config_flags & CONFIGFLAG_FAILEDINSTALL)
        {
            /* The device is disabled */
            TRACE("Device is disabled\n");
            retval = TRUE;
            goto cleanup;
        }
    }

    TRACE("Installing %s (%s)\n", debugstr_w((PCWSTR)DevInstData->buffer), debugstr_w(InstanceId));

    /* Search driver in default location and removable devices */
    if (!PrepareFoldersToScan(DevInstData, FALSE, FALSE, NULL))
    {
        TRACE("PrepareFoldersToScan() failed with error 0x%lx\n", GetLastError());
        goto cleanup;
    }
    if (ScanFoldersForDriver(DevInstData))
    {
        /* Driver found ; install it */
        retval = InstallCurrentDriver(DevInstData);
        TRACE("InstallCurrentDriver() returned %d\n", retval);
        if (retval && Show != SW_HIDE)
        {
            /* Should we display the 'Need to reboot' page? */
            SP_DEVINSTALL_PARAMS installParams;
            installParams.cbSize = sizeof(SP_DEVINSTALL_PARAMS);
            if (SetupDiGetDeviceInstallParams(
                DevInstData->hDevInfo,
                &DevInstData->devInfoData,
                &installParams))
            {
                if (installParams.Flags & (DI_NEEDRESTART | DI_NEEDREBOOT))
                {
                    TRACE("Displaying 'Reboot' wizard page\n");
                    retval = DisplayWizard(DevInstData, hWndParent, IDD_NEEDREBOOT);
                }
            }
        }
        goto cleanup;
    }
    else if (Show == SW_HIDE)
    {
        /* We can't show the wizard. Fail the install */
        TRACE("No wizard\n");
        goto cleanup;
    }

    /* Prepare the wizard, and display it */
    TRACE("Need to show install wizard\n");
    retval = DisplayWizard(DevInstData, hWndParent, IDD_WELCOMEPAGE);

cleanup:
    if (DevInstData)
    {
        if (DevInstData->devInfoData.cbSize != 0)
        {
            if (!SetupDiDestroyDriverInfoList(DevInstData->hDevInfo, &DevInstData->devInfoData, SPDIT_COMPATDRIVER))
                TRACE("SetupDiDestroyDriverInfoList() failed with error 0x%lx\n", GetLastError());
        }
        if (DevInstData->hDevInfo != INVALID_HANDLE_VALUE)
        {
            if (!SetupDiDestroyDeviceInfoList(DevInstData->hDevInfo))
                TRACE("SetupDiDestroyDeviceInfoList() failed with error 0x%lx\n", GetLastError());
        }
        HeapFree(GetProcessHeap(), 0, DevInstData->buffer);
        HeapFree(GetProcessHeap(), 0, DevInstData);
    }

    return retval;
}
Пример #11
0
BOOL DumpDeviceDriverFiles(_In_ HDEVINFO Devs, _In_ PSP_DEVINFO_DATA DevInfo)
/*++

Routine Description:

    Dump information about what files were installed for driver package
    <tab>Installed using OEM123.INF section [abc.NT]
    <tab><tab>file...

Arguments:

    Devs    )_ uniquely identify device
    DevInfo )

Return Value:

    none

--*/
{
    //
    // do this by 'searching' for the current driver
    // mimmicing a copy-only install to our own file queue
    // and then parsing that file queue
    //
    SP_DEVINSTALL_PARAMS deviceInstallParams;
    SP_DRVINFO_DATA driverInfoData;
    SP_DRVINFO_DETAIL_DATA driverInfoDetail;
    HSPFILEQ queueHandle = INVALID_HANDLE_VALUE;
    DWORD count;
    DWORD scanResult;
    BOOL success = FALSE;

    ZeroMemory(&driverInfoData,sizeof(driverInfoData));
    driverInfoData.cbSize = sizeof(driverInfoData);

    if(!FindCurrentDriver(Devs,DevInfo,&driverInfoData)) {
        Padding(1);
        FormatToStream(stdout, MSG_DUMP_NO_DRIVER);
        return FALSE;
    }

    //
    // get useful driver information
    //
    driverInfoDetail.cbSize = sizeof(SP_DRVINFO_DETAIL_DATA);
    if(!SetupDiGetDriverInfoDetail(Devs,DevInfo,&driverInfoData,&driverInfoDetail,sizeof(SP_DRVINFO_DETAIL_DATA),NULL) &&
       GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
        //
        // no information about driver or section
        //
        goto final;
    }
    if(!driverInfoDetail.InfFileName[0] || !driverInfoDetail.SectionName[0]) {
        goto final;
    }

    //
    // pretend to do the file-copy part of a driver install
    // to determine what files are used
    // the specified driver must be selected as the active driver
    //
    if(!SetupDiSetSelectedDriver(Devs, DevInfo, &driverInfoData)) {
        goto final;
    }

    //
    // create a file queue so we can look at this queue later
    //
    queueHandle = SetupOpenFileQueue();

    if ( queueHandle == (HSPFILEQ)INVALID_HANDLE_VALUE ) {
        goto final;
    }

    //
    // modify flags to indicate we're providing our own queue
    //
    ZeroMemory(&deviceInstallParams, sizeof(deviceInstallParams));
    deviceInstallParams.cbSize = sizeof(SP_DEVINSTALL_PARAMS);
    if ( !SetupDiGetDeviceInstallParams(Devs, DevInfo, &deviceInstallParams) ) {
        goto final;
    }

    //
    // we want to add the files to the file queue, not install them!
    //
    deviceInstallParams.FileQueue = queueHandle;
    deviceInstallParams.Flags |= DI_NOVCP;

    if ( !SetupDiSetDeviceInstallParams(Devs, DevInfo, &deviceInstallParams) ) {
        goto final;
    }

    //
    // now fill queue with files that are to be installed
    // this involves all class/co-installers
    //
    if ( !SetupDiCallClassInstaller(DIF_INSTALLDEVICEFILES, Devs, DevInfo) ) {
        goto final;
    }

    //
    // we now have a list of delete/rename/copy files
    // iterate the copy queue twice - 1st time to get # of files
    // 2nd time to get files
    // (WinXP has API to get # of files, but we want this to work
    // on Win2k too)
    //

    count = 0;
    scanResult = 0;
    //
    // call once to count
    //
    SetupScanFileQueue(queueHandle,SPQ_SCAN_USE_CALLBACK,NULL,DumpDeviceDriversCallback,&count,&scanResult);
    Padding(1);
    FormatToStream(stdout, count ? MSG_DUMP_DRIVER_FILES : MSG_DUMP_NO_DRIVER_FILES, count, driverInfoDetail.InfFileName, driverInfoDetail.SectionName);
    //
    // call again to dump the files
    //
    SetupScanFileQueue(queueHandle,SPQ_SCAN_USE_CALLBACK,NULL,DumpDeviceDriversCallback,NULL,&scanResult);

    success = TRUE;

final:
Пример #12
0
static BOOL ChangeStatus( DWORD dwNewStatus, DWORD dwSelectedItem, HDEVINFO hDevInfo )
{
    BOOL bRet = TRUE;

    TRY
    {
        SP_DEVINFO_DATA DeviceInfoData;
        ZeroMemory( &DeviceInfoData, sizeof( SP_DEVINFO_DATA ) );
        DeviceInfoData.cbSize = sizeof( SP_DEVINFO_DATA );

        // Get a handle to the Selected Item
        if ( !SetupDiEnumDeviceInfo( hDevInfo, dwSelectedItem, &DeviceInfoData ) )
        {
            bRet = FALSE;
        }
        else
        {
            SP_PROPCHANGE_PARAMS PropChangeParams;
            ZeroMemory( &PropChangeParams, sizeof( SP_PROPCHANGE_PARAMS ) );
            PropChangeParams.ClassInstallHeader.cbSize = sizeof( SP_CLASSINSTALL_HEADER );

            // Set the PropChangeParams structure
            PropChangeParams.ClassInstallHeader.InstallFunction = DIF_PROPERTYCHANGE;
            PropChangeParams.Scope = DICS_FLAG_GLOBAL;
            PropChangeParams.StateChange = dwNewStatus;

            if ( !SetupDiSetClassInstallParams( hDevInfo, &DeviceInfoData, ( SP_CLASSINSTALL_HEADER* )&PropChangeParams, sizeof( PropChangeParams ) ) )
            {
                bRet = FALSE;
            }
            else
            {
                // Call the ClassInstaller and perform the change
                if ( !SetupDiCallClassInstaller( DIF_PROPERTYCHANGE, hDevInfo, &DeviceInfoData ) )
                {
                    bRet = FALSE;
                }
                else
                {
                    //
                    // Is Need to restart computer
                    //
                    SP_DEVINSTALL_PARAMS devParams;
                    ZeroMemory( &devParams, sizeof( SP_DEVINSTALL_PARAMS ) );
                    devParams.cbSize = sizeof( SP_DEVINSTALL_PARAMS );

                    if ( !SetupDiGetDeviceInstallParams( hDevInfo, &DeviceInfoData, &devParams ) )
                    {
                        bRet = FALSE;
                    }
                    else
                    {
                        if ( devParams.Flags & ( DI_NEEDRESTART | DI_NEEDREBOOT ) )
                        {
                            TRACE( _T("\nNeed Restart Computer\n") );
                        }
                    }
                }
            }
        }
    }
    CATCH_ALL( e )
    {
        e->ReportError();
        bRet = FALSE;
    }
    END_CATCH_ALL

    return bRet;
}
Пример #13
0
//////////////////////////// 
// FETCH    USB     DRIVER      VERSION
void windozeHelpers::FetchUsbDriverVersion( const uint16_t DeviceNum, std::string & version )
{
    HDEVINFO deviceInfo = 0;
    SP_DEVICE_INTERFACE_DATA interfaceData;

     std::string msg;

    if( !EnumerateDevice( DeviceNum, deviceInfo, interfaceData, msg ) )
    {
        apgHelper::throwRuntimeException( __FILE__, msg, __LINE__, Apg::ErrorType_Connection );
    }

    
    SP_DEVINFO_DATA deviceData;
    deviceData.cbSize = sizeof(SP_DEVINFO_DATA);
    if( !SetupDiEnumDeviceInfo( deviceInfo, DeviceNum, &deviceData ) )
    {
        //getting the windows error message b4 the next winapi calls
        //nukes it out.  then throw the error
        std::string errMsg = "SetupDiEnumDeviceInfo failed "
            + windozeHelpers::GetLastWinError();

        SetupDiDestroyDeviceInfoList(deviceInfo);

        apgHelper::throwRuntimeException( __FILE__, 
           errMsg , __LINE__,Apg::ErrorType_Connection );
    }
  
    //from BOOL DumpDeviceDriverNodes in dump.cpp in 
    //C:\WinDDK\6001.18002\src\setup\devcon
    SP_DEVINSTALL_PARAMS deviceInstallParams;
    SP_DRVINFO_DATA driverInfoData;

    ZeroMemory(&deviceInstallParams, sizeof(deviceInstallParams));
    ZeroMemory(&driverInfoData, sizeof(driverInfoData));

    driverInfoData.cbSize = sizeof(SP_DRVINFO_DATA);
    deviceInstallParams.cbSize = sizeof(SP_DEVINSTALL_PARAMS);

    if( !SetupDiGetDeviceInstallParams(deviceInfo, &deviceData, 
        &deviceInstallParams) )
    {
       std::string errMsg = "SetupDiGetDeviceInstallParams failed "
            + windozeHelpers::GetLastWinError();

        SetupDiDestroyDeviceInfoList(deviceInfo);

        apgHelper::throwRuntimeException( __FILE__, 
           errMsg , __LINE__,Apg::ErrorType_Connection );
    }

    //
    // Set the flags that tell SetupDiBuildDriverInfoList to allow excluded drivers.
    //
    deviceInstallParams.FlagsEx |= (DI_FLAGSEX_INSTALLEDDRIVER | DI_FLAGSEX_ALLOWEXCLUDEDDRVS);

    if( !SetupDiSetDeviceInstallParams(deviceInfo, &deviceData, 
        &deviceInstallParams) )
    {
         std::string errMsg = "SetupDiGetDeviceInstallParams failed "
            + windozeHelpers::GetLastWinError();

        SetupDiDestroyDeviceInfoList(deviceInfo);

        apgHelper::throwRuntimeException( __FILE__, 
           errMsg , __LINE__,Apg::ErrorType_Connection );
    }

    if( !SetupDiBuildDriverInfoList(deviceInfo, &deviceData, 
        SPDIT_COMPATDRIVER) )
    {
         std::string errMsg = "SetupDiBuildDriverInfoList failed "
            + windozeHelpers::GetLastWinError();

        SetupDiDestroyDeviceInfoList(deviceInfo);

        apgHelper::throwRuntimeException( __FILE__, 
           errMsg , __LINE__,Apg::ErrorType_Connection );
    }

  
    // believe the member index should be set to 0 for all
    // devices...not 100% sure what this parameter is referring
    // to, the number of devices, the number of driver interfaces,
    // number of device interfaces????
    // http://msdn.microsoft.com/en-us/library/windows/hardware/ff551018(v=vs.85).aspx
    if( !SetupDiEnumDriverInfo(deviceInfo, &deviceData, 
        SPDIT_COMPATDRIVER, 0, &driverInfoData) )
    {
        std::string errMsg = "SetupDiEnumDriverInfo failed "
            + windozeHelpers::GetLastWinError();

        SetupDiDestroyDriverInfoList(deviceInfo, &deviceData,
        SPDIT_COMPATDRIVER);
        SetupDiDestroyDeviceInfoList(deviceInfo);

        apgHelper::throwRuntimeException( __FILE__, 
           errMsg , __LINE__,Apg::ErrorType_Connection );
    }
 
    ULARGE_INTEGER Version;
    Version.QuadPart = driverInfoData.DriverVersion;
    
    std::stringstream ss;
    ss << HIWORD(Version.HighPart) << ".";
    ss << LOWORD(Version.HighPart) << ".";
    ss << HIWORD(Version.LowPart) << ".";
    ss << LOWORD(Version.LowPart);
                       
    version = ss.str();

    SetupDiDestroyDriverInfoList(deviceInfo, &deviceData,
        SPDIT_COMPATDRIVER);
    SetupDiDestroyDeviceInfoList(deviceInfo);

}
Пример #14
0
BOOL
OnNotify(
    HWND    ParentHwnd,
    LPNMHDR NmHdr,
    PTOASTER_PROP_PARAMS Params
    )
{
    SP_DEVINSTALL_PARAMS spDevInstall = {0};
    TCHAR                friendlyName[LINE_LEN] ={0};
    BOOL    fSuccess;
    
    switch (NmHdr->code) {
    case PSN_APPLY:
        //
        // Sent when the user clicks on Apply OR OK !!
        //

        GetDlgItemText(ParentHwnd, IDC_FRIENDLYNAME, friendlyName,
                                        LINE_LEN-1 );
        friendlyName[LINE_LEN-1] = UNICODE_NULL;
        if(friendlyName[0]) {

            fSuccess = SetupDiSetDeviceRegistryProperty(Params->DeviceInfoSet, 
                         Params->DeviceInfoData,
                         SPDRP_FRIENDLYNAME,
                         (BYTE *)friendlyName,
                         (lstrlen(friendlyName)+1) * sizeof(TCHAR)
                         );
            if(!fSuccess) {
                DbgOut("SetupDiSetDeviceRegistryProperty failed!");                   
                break;
            }

            //
            // Inform setup about property change so that it can
            // restart the device.
            //

            spDevInstall.cbSize = sizeof(SP_DEVINSTALL_PARAMS);
     
            if (Params && SetupDiGetDeviceInstallParams(Params->DeviceInfoSet,
                                              Params->DeviceInfoData,
                                              &spDevInstall)) {
                //
                // If your device requires a reboot to restart, you can
                // specify that by setting DI_NEEDREBOOT as shown below
                //
                // if(NeedReboot) {
                //    spDevInstall.Flags |= DI_PROPERTIES_CHANGE | DI_NEEDREBOOT;
                // }
                //
                spDevInstall.FlagsEx |= DI_FLAGSEX_PROPCHANGE_PENDING;
                
                SetupDiSetDeviceInstallParams(Params->DeviceInfoSet,
                                              Params->DeviceInfoData,
                                              &spDevInstall);
            }
        
        }
        return TRUE;

    default:
        return FALSE;
    }
    return FALSE;   
} 
Пример #15
0
BOOL ExitPropertyPageAdvanced(_In_ HWND hwndDlg, _Inout_ PCOISANE_Data privateData)
{
	SP_DEVINSTALL_PARAMS devInstallParams;
	PWINSANE_Session oSession;
	PWINSANE_Device oDevice;
	LPTSTR lpName;
	LPTSTR lpUsername;
	LPTSTR lpPassword;
	BOOL res;

	lpName = (LPTSTR) HeapAlloc(privateData->hHeap, HEAP_ZERO_MEMORY, sizeof(TCHAR) * MAX_PATH);
	if (lpName) {
		res = GetDlgItemText(hwndDlg, IDC_PROPERTIES_COMBO_SCANNER, lpName, MAX_PATH);
		if (res) {
			if (privateData->lpName) {
				HeapFree(privateData->hHeap, 0, privateData->lpName);
			}
			privateData->lpName = lpName;
		} else {
			HeapFree(privateData->hHeap, 0, lpName);
		}
	} else {
		res = FALSE;
	}

	if (res) {
		lpUsername = (LPTSTR) HeapAlloc(privateData->hHeap, HEAP_ZERO_MEMORY, sizeof(TCHAR) * MAX_PATH);
		if (lpUsername) {
			if (GetDlgItemText(hwndDlg, IDC_PROPERTIES_EDIT_USERNAME, lpUsername, MAX_PATH)) {
				if (privateData->lpUsername) {
					HeapFree(privateData->hHeap, 0, privateData->lpUsername);
				}
				privateData->lpUsername = lpUsername;
			} else {
				HeapFree(privateData->hHeap, 0, lpUsername);
			}
		}

		lpPassword = (LPTSTR) HeapAlloc(privateData->hHeap, HEAP_ZERO_MEMORY, sizeof(TCHAR) * MAX_PATH);
		if (lpPassword) {
			if (GetDlgItemText(hwndDlg, IDC_PROPERTIES_EDIT_PASSWORD, lpPassword, MAX_PATH)) {
				if (privateData->lpPassword) {
					HeapFree(privateData->hHeap, 0, privateData->lpPassword);
				}
				privateData->lpPassword = lpPassword;
			} else {
				HeapFree(privateData->hHeap, 0, lpPassword);
			}
		}

		oSession = WINSANE_Session::Remote(privateData->lpHost, privateData->usPort);
		if (oSession) {
			if (oSession->Init(NULL, NULL) == SANE_STATUS_GOOD) {
				if (oSession->GetDevices() > 0) {
					oDevice = oSession->GetDevice(privateData->lpName);
					if (oDevice) {
						UpdateDeviceInfo(privateData, oDevice);
						UpdateDeviceData(privateData, oDevice);

						ZeroMemory(&devInstallParams, sizeof(SP_DEVINSTALL_PARAMS));
						devInstallParams.cbSize = sizeof(SP_DEVINSTALL_PARAMS);
						res = SetupDiGetDeviceInstallParams(privateData->hDeviceInfoSet, privateData->pDeviceInfoData, &devInstallParams);
						if (res) {
							devInstallParams.FlagsEx |= DI_FLAGSEX_PROPCHANGE_PENDING;
							res = SetupDiSetDeviceInstallParams(privateData->hDeviceInfoSet, privateData->pDeviceInfoData, &devInstallParams);
						}
					} else {
						res = FALSE;
					}
				} else {
					res = FALSE;
				}
				if (oSession->Exit() != SANE_STATUS_GOOD) {
					res = FALSE;
				}
			} else {
				res = FALSE;
			}
			delete oSession;
		} else {
			res = FALSE;
		}
	}

	return res;
}
Пример #16
0
/**
 * Install the VBox video driver.
 *
 * @returns TRUE on success.
 * @returns FALSE on failure.
 * @param   szDriverDir     The base directory where we find the INF.
 */
BOOL installVideoDriver(TCHAR* szDriverDir)
{
  HDEVINFO hDevInfo;
  SP_DEVINSTALL_PARAMS DeviceInstallParams={0};
  SP_DRVINFO_DATA drvInfoData={0};
  SP_DRVINFO_DETAIL_DATA DriverInfoDetailData={0};

  DWORD cbReqSize;

  /* Vars used for reading the INF */
  HINF hInf;
  TCHAR szServiceSection[LINE_LEN];
  INFCONTEXT serviceContext;
  TCHAR szServiceData[LINE_LEN];
  TCHAR deviceRegStr[1000];//I'm lazy here. 1000 ought to be enough for everybody...

  SP_DEVINFO_DATA deviceInfoData;
  DWORD configFlags;

  HKEY hkey;
  DWORD disp;
  TCHAR regKeyName[LINE_LEN];

  BOOL rc;

  /* Create an empty list */
  hDevInfo = SetupDiCreateDeviceInfoList((LPGUID) &GUID_DEVCLASS_DISPLAY,
                                         NULL);

  if (hDevInfo == INVALID_HANDLE_VALUE)
    return FALSE;

  memset(&DeviceInstallParams, 0, sizeof(SP_DEVINSTALL_PARAMS));
  DeviceInstallParams.cbSize = sizeof(SP_DEVINSTALL_PARAMS);

  rc=SetupDiGetDeviceInstallParams(hDevInfo,
                                   NULL,
                                   &DeviceInstallParams);

  if(!rc)
    return FALSE;

  DeviceInstallParams.cbSize = sizeof(SP_DEVINSTALL_PARAMS);
  DeviceInstallParams.Flags |= DI_NOFILECOPY | /* We did our own file copying */
    DI_DONOTCALLCONFIGMG |
    DI_ENUMSINGLEINF; /* .DriverPath specifies an inf file */


  /* Path to inf file */
  wsprintf(DeviceInstallParams.DriverPath,
           TEXT("%ws\\%ws"),
           szDriverDir, TEXT(VBOXGUEST_VIDEO_INF_NAME));

  rc=SetupDiSetDeviceInstallParams(hDevInfo,
                                   NULL,
                                   &DeviceInstallParams);
  if(!rc)
    return FALSE;

  /* Read the drivers from the inf file */
  if (!SetupDiBuildDriverInfoList(hDevInfo, NULL, SPDIT_CLASSDRIVER))
    {
      SetupDiDestroyDeviceInfoList(hDevInfo);
      return FALSE;
    }

  /* Get the first found driver.
     Our Inf file only contains one so this is fine  */
  drvInfoData.cbSize = sizeof(SP_DRVINFO_DATA);
  if(FALSE==SetupDiEnumDriverInfo(hDevInfo, NULL, SPDIT_CLASSDRIVER,
                                  0, &drvInfoData)){
    SetupDiDestroyDeviceInfoList(hDevInfo);
    return FALSE;
  }

  /* Get necessary driver details */
  DriverInfoDetailData.cbSize = sizeof(SP_DRVINFO_DETAIL_DATA);
  if (!(!SetupDiGetDriverInfoDetail(hDevInfo,
                                    NULL,
                                    &drvInfoData,
                                    &DriverInfoDetailData,
                                    DriverInfoDetailData.cbSize,
                                    &cbReqSize)
        &&GetLastError()== ERROR_INSUFFICIENT_BUFFER) )
    {
      SetupDiDestroyDriverInfoList(hDevInfo, NULL, SPDIT_CLASSDRIVER);
      SetupDiDestroyDeviceInfoList(hDevInfo);
      return FALSE;
    }

  hInf = SetupOpenInfFile(DriverInfoDetailData.InfFileName,
                          NULL, INF_STYLE_WIN4, NULL);

  if (hInf == INVALID_HANDLE_VALUE)
    {
      SetupDiDestroyDriverInfoList(hDevInfo, NULL, SPDIT_CLASSDRIVER);
      SetupDiDestroyDeviceInfoList(hDevInfo);
      return FALSE;
    }

  /* First install the service */
  wsprintf(szServiceSection, TEXT("%ws.Services"),
           DriverInfoDetailData.SectionName);

  if(!SetupFindFirstLine(hInf, szServiceSection, NULL, &serviceContext))
    {
      /* No service line?? Can't be... */
      closeAndDestroy(hDevInfo, hInf);
      return FALSE;
    }

  /* Get the name */
  SetupGetStringField(&serviceContext,
                      1,
                      szServiceData,
                      sizeof(szServiceData),
                      NULL);

  wsprintf(deviceRegStr, TEXT("Root\\LEGACY_%ws\\0000"), szServiceData);

  memset(&deviceInfoData, 0, sizeof(SP_DEVINFO_DATA));
  deviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);

  if (SetupDiOpenDeviceInfo(hDevInfo, deviceRegStr, NULL, 0, &deviceInfoData) //Check for existing
      ||(SetupDiCreateDeviceInfo(hDevInfo, deviceRegStr,                      //Create new
                                 (LPGUID) &GUID_DEVCLASS_DISPLAY,
                                 NULL, //Do we need a description here?
                                 NULL, //No user interface
                                 0,
                                 &deviceInfoData) &&
         SetupDiRegisterDeviceInfo(hDevInfo,
                                   &deviceInfoData,
                                   0,
                                   NULL,
                                   NULL,
                                   NULL)) )
    {
      /* We created a new key in the registry */

      memset(&DeviceInstallParams, 0,sizeof(SP_DEVINSTALL_PARAMS));
      DeviceInstallParams.cbSize = sizeof(SP_DEVINSTALL_PARAMS);

      SetupDiGetDeviceInstallParams(hDevInfo,
                                    &deviceInfoData,
                                    &DeviceInstallParams);

      DeviceInstallParams.Flags |= DI_NOFILECOPY | //We already copied the files
        DI_DONOTCALLCONFIGMG |
        DI_ENUMSINGLEINF; //Use our INF file only

      /* Path to inf file */
      wsprintf(DeviceInstallParams.DriverPath,
               TEXT("%ws\\%ws"),
               szDriverDir, TEXT(VBOXGUEST_VIDEO_INF_NAME));

      SetupDiSetDeviceInstallParams(hDevInfo,
                                    &deviceInfoData,
                                    &DeviceInstallParams);


      if(!SetupDiBuildDriverInfoList(hDevInfo,
                                     &deviceInfoData,
                                     SPDIT_CLASSDRIVER))
        {
          closeAndDestroy(hDevInfo, hInf);
          return FALSE;
        }

      drvInfoData.cbSize = sizeof(SP_DRVINFO_DATA);
      if (!SetupDiEnumDriverInfo(hDevInfo,
                                 &deviceInfoData,
                                 SPDIT_CLASSDRIVER,
                                 0,
                                 &drvInfoData))
        {
          closeAndDestroy(hDevInfo, hInf);
          return FALSE;
        }

      if(!SetupDiSetSelectedDriver(hDevInfo,
                                   &deviceInfoData,
                                   &drvInfoData))
        {
          closeAndDestroy(hDevInfo, hInf);
          return FALSE;
        }

      if(!SetupDiInstallDevice(hDevInfo,
                               &deviceInfoData))
        {
          closeAndDestroy(hDevInfo, hInf);
          return FALSE;
        }
    }

  /* Make sure the device is enabled */
  if (SetupDiGetDeviceRegistryProperty(hDevInfo,
                                       &deviceInfoData, SPDRP_CONFIGFLAGS,
                                       NULL, (LPBYTE) &configFlags,
                                       sizeof(DWORD),
                                       NULL)
      && (configFlags & CONFIGFLAG_DISABLED))
    {
      configFlags &= ~CONFIGFLAG_DISABLED;

      SetupDiSetDeviceRegistryProperty(hDevInfo,
                                       &deviceInfoData,
                                       SPDRP_CONFIGFLAGS,
                                       (LPBYTE) &configFlags,
                                       sizeof(DWORD));
    }

  wsprintf(regKeyName,
           TEXT("System\\CurrentControlSet\\Services\\%ws\\Device%d"),
           szServiceData, 0); //We only have one device

  if (RegCreateKeyEx(HKEY_LOCAL_MACHINE,
                     regKeyName,
                     0,
                     NULL,
                     REG_OPTION_NON_VOLATILE,
                     KEY_READ | KEY_WRITE,
                     NULL,
                     &hkey,
                     &disp) == ERROR_SUCCESS)
    {
      /* Insert description */
      RegSetValueEx(hkey,
                    TEXT("Device Description"),
                    0,
                    REG_SZ,
                    (LPBYTE) DriverInfoDetailData.DrvDescription,
                    (lstrlen(DriverInfoDetailData.DrvDescription) + 1) *
                    sizeof(TCHAR) );

      TCHAR szSoftwareSection[LINE_LEN];

      wsprintf(szSoftwareSection,
               TEXT("%ws.SoftwareSettings"),
               szServiceData);

      if (!SetupInstallFromInfSection(NULL,
                                      hInf,
                                      szSoftwareSection,
                                      SPINST_REGISTRY,
                                      hkey,
                                      NULL,
                                      0,
                                      NULL,
                                      NULL,
                                      NULL,
                                      NULL))
        {
          RegCloseKey(hkey);
          closeAndDestroy(hDevInfo, hInf);
          return FALSE;
        }

      RegCloseKey(hkey);
    }

  /* Install OpenGL stuff */
  if (RegCreateKeyEx(HKEY_LOCAL_MACHINE,
                     TEXT("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\OpenGLDrivers"),
                     0,
                     NULL,
                     REG_OPTION_NON_VOLATILE,
                     KEY_READ | KEY_WRITE,
                     NULL,
                     &hkey,
                     &disp) == ERROR_SUCCESS)
    {
      /* Do installation here if ever necessary. Currently there is no OpenGL stuff */

      RegCloseKey(hkey);
    }


  /* Cleanup */
  closeAndDestroy(hDevInfo, hInf);

#if 0
  /* If this key is inserted into the registry, windows will show the desktop
     applet on next boot. We decide in the installer if we want that so the code
     is disabled here. */
  /* Set registry keys so windows picks up the changes */
  if (RegCreateKeyEx(HKEY_LOCAL_MACHINE,
                     TEXT("SYSTEM\\CurrentControlSet\\Control\\GraphicsDrivers\\NewDisplay"),
                     0,
                     NULL,
                     REG_OPTION_NON_VOLATILE,
                     KEY_READ | KEY_WRITE,
                     NULL,
                     &hkey,
                     &disp) == ERROR_SUCCESS)
    {
      RegCloseKey(hkey);
    }
#endif

  /* We must reboot at some point */
  if (RegCreateKeyEx(HKEY_LOCAL_MACHINE,
                     TEXT("SYSTEM\\CurrentControlSet\\Control\\GraphicsDrivers\\RebootNecessary"),
                     0,
                     NULL,
                     REG_OPTION_NON_VOLATILE,
                     KEY_READ | KEY_WRITE,
                     NULL,
                     &hkey,
                     &disp) == ERROR_SUCCESS)
    {
      RegCloseKey(hkey);
    }

  return TRUE;
}
Пример #17
0
DWORD
InstallInfOnDevice(
    IN HWND hWnd,
    HDEVINFO DeviceInfoSet,
    PSP_DEVINFO_DATA DeviceInfoData,
    PTSTR Inf,
    BOOL DelayInstall
    )
{
    DWORD Err = NO_ERROR;
    SP_DEVINSTALL_PARAMS DeviceInstallParams;
    BOOL Reboot = FALSE;

    if (!SetupDiSetSelectedDevice(DeviceInfoSet, DeviceInfoData)) {
        Err = GetLastError();
        goto exit;
    }

    DeviceInstallParams.cbSize = sizeof(DeviceInstallParams);
    if (!SetupDiGetDeviceInstallParams(DeviceInfoSet,
                                       DeviceInfoData,
                                       &DeviceInstallParams)) {
        Err = GetLastError();
        goto exit;
    }

    //
    // Set DriverPath to the path of the INF that we want to install from.
    // Set the DI_ENUMSINGLEINFO so setupapi builds up a driver list just from
    //   this specific INF.
    // Set DI_DONOTCALLCONFIGMG so that we won't call kernel PnP when installing
    //   the driver.  This will do all the install actions except stop/start the 
    //   device so it won't start using the new driver until a reboot.
    //
    StringCchCopy(DeviceInstallParams.DriverPath, 
                  SIZECHARS(DeviceInstallParams.DriverPath),
                  Inf);
    DeviceInstallParams.hwndParent = hWnd;
    DeviceInstallParams.Flags |= (DI_ENUMSINGLEINF | DI_QUIETINSTALL);
    if (DelayInstall) {
        DeviceInstallParams.Flags |= DI_DONOTCALLCONFIGMG;
    }
    DeviceInstallParams.FlagsEx |= DI_FLAGSEX_ALLOWEXCLUDEDDRVS;
    if (!SetupDiSetDeviceInstallParams(DeviceInfoSet,
                                       DeviceInfoData,
                                       &DeviceInstallParams)) {
        Err = GetLastError();
        goto exit;
    }

    //
    // Build up a list of drivers from the specified INFs
    //
    if (!SetupDiBuildDriverInfoList(DeviceInfoSet, DeviceInfoData, SPDIT_COMPATDRIVER)) {
        Err = GetLastError();
        goto exit;
    }

    //
    // Tell setupapi and the class installers to select the best driver from the 
    // list built from the specified INF.
    //
    if (!SetupDiCallClassInstaller(DIF_SELECTBESTCOMPATDRV,
                                   DeviceInfoSet,
                                   DeviceInfoData)) {
        Err = GetLastError();
        goto exit;
    }

    //
    // Install the selected driver on the selected device without calling kernel mode
    //
    if (!InstallSelectedDriver(hWnd,
                               DeviceInfoSet,
                               NULL,
                               FALSE,
                               &Reboot)) {
        Err = GetLastError();
        goto exit;
    }

exit:
    return Err;
}
Пример #18
0
BOOL FindCurrentDriver(_In_ HDEVINFO Devs, _In_ PSP_DEVINFO_DATA DevInfo, _In_ PSP_DRVINFO_DATA DriverInfoData)
/*++

Routine Description:

    Find the driver that is associated with the current device
    We can do this either the quick way (available in WinXP)
    or the long way that works in Win2k.

Arguments:

    Devs    )_ uniquely identify device
    DevInfo )

Return Value:

    TRUE if we managed to determine and select current driver

--*/
{
    SP_DEVINSTALL_PARAMS deviceInstallParams;
    WCHAR SectionName[LINE_LEN];
    WCHAR DrvDescription[LINE_LEN];
    WCHAR MfgName[LINE_LEN];
    WCHAR ProviderName[LINE_LEN];
    HKEY hKey = NULL;
    DWORD RegDataLength;
    DWORD RegDataType;
    DWORD c;
    BOOL match = FALSE;
    long regerr;

    ZeroMemory(&deviceInstallParams, sizeof(deviceInstallParams));
    deviceInstallParams.cbSize = sizeof(SP_DEVINSTALL_PARAMS);

    if(!SetupDiGetDeviceInstallParams(Devs, DevInfo, &deviceInstallParams)) {
        return FALSE;
    }

#ifdef DI_FLAGSEX_INSTALLEDDRIVER
    //
    // Set the flags that tell SetupDiBuildDriverInfoList to just put the
    // currently installed driver node in the list, and that it should allow
    // excluded drivers. This flag introduced in WinXP.
    //
    deviceInstallParams.FlagsEx |= (DI_FLAGSEX_INSTALLEDDRIVER | DI_FLAGSEX_ALLOWEXCLUDEDDRVS);

    if(SetupDiSetDeviceInstallParams(Devs, DevInfo, &deviceInstallParams)) {
        //
        // we were able to specify this flag, so proceed the easy way
        // we should get a list of no more than 1 driver
        //
        if(!SetupDiBuildDriverInfoList(Devs, DevInfo, SPDIT_CLASSDRIVER)) {
            return FALSE;
        }
        if (!SetupDiEnumDriverInfo(Devs, DevInfo, SPDIT_CLASSDRIVER,
                                   0, DriverInfoData)) {
            return FALSE;
        }
        //
        // we've selected the current driver
        //
        return TRUE;
    }
    deviceInstallParams.FlagsEx &= ~(DI_FLAGSEX_INSTALLEDDRIVER | DI_FLAGSEX_ALLOWEXCLUDEDDRVS);
#endif
    //
    // The following method works in Win2k, but it's slow and painful.
    //
    // First, get driver key - if it doesn't exist, no driver
    //
    hKey = SetupDiOpenDevRegKey(Devs,
                                DevInfo,
                                DICS_FLAG_GLOBAL,
                                0,
                                DIREG_DRV,
                                KEY_READ
                               );

    if(hKey == INVALID_HANDLE_VALUE) {
        //
        // no such value exists, so there can't be an associated driver
        //
        RegCloseKey(hKey);
        return FALSE;
    }

    //
    // obtain path of INF - we'll do a search on this specific INF
    //
    RegDataLength = sizeof(deviceInstallParams.DriverPath); // bytes!!!
    regerr = RegQueryValueEx(hKey,
                             REGSTR_VAL_INFPATH,
                             NULL,
                             &RegDataType,
                             (PBYTE)deviceInstallParams.DriverPath,
                             &RegDataLength
                             );

    if((regerr != ERROR_SUCCESS) || (RegDataType != REG_SZ)) {
        //
        // no such value exists, so no associated driver
        //
        RegCloseKey(hKey);
        return FALSE;
    }

    //
    // obtain name of Provider to fill into DriverInfoData
    //
    RegDataLength = sizeof(ProviderName); // bytes!!!
    regerr = RegQueryValueEx(hKey,
                             REGSTR_VAL_PROVIDER_NAME,
                             NULL,
                             &RegDataType,
                             (PBYTE)ProviderName,
                             &RegDataLength
                             );

    if((regerr != ERROR_SUCCESS) || (RegDataType != REG_SZ)) {
        //
        // no such value exists, so we don't have a valid associated driver
        //
        RegCloseKey(hKey);
        return FALSE;
    }

    //
    // obtain name of section - for final verification
    //
    RegDataLength = sizeof(SectionName); // bytes!!!
    regerr = RegQueryValueEx(hKey,
                             REGSTR_VAL_INFSECTION,
                             NULL,
                             &RegDataType,
                             (PBYTE)SectionName,
                             &RegDataLength
                             );

    if((regerr != ERROR_SUCCESS) || (RegDataType != REG_SZ)) {
        //
        // no such value exists, so we don't have a valid associated driver
        //
        RegCloseKey(hKey);
        return FALSE;
    }

    //
    // driver description (need not be same as device description)
    // - for final verification
    //
    RegDataLength = sizeof(DrvDescription); // bytes!!!
    regerr = RegQueryValueEx(hKey,
                             REGSTR_VAL_DRVDESC,
                             NULL,
                             &RegDataType,
                             (PBYTE)DrvDescription,
                             &RegDataLength
                             );

    RegCloseKey(hKey);

    if((regerr != ERROR_SUCCESS) || (RegDataType != REG_SZ)) {
        //
        // no such value exists, so we don't have a valid associated driver
        //
        return FALSE;
    }

    //
    // Manufacturer (via SPDRP_MFG, don't access registry directly!)
    //

    if(!SetupDiGetDeviceRegistryProperty(Devs,
                                        DevInfo,
                                        SPDRP_MFG,
                                        NULL,      // datatype is guaranteed to always be REG_SZ.
                                        (PBYTE)MfgName,
                                        sizeof(MfgName), // bytes!!!
                                        NULL)) {
        //
        // no such value exists, so we don't have a valid associated driver
        //
        return FALSE;
    }

    //
    // now search for drivers listed in the INF
    //
    //
    deviceInstallParams.Flags |= DI_ENUMSINGLEINF;
    deviceInstallParams.FlagsEx |= DI_FLAGSEX_ALLOWEXCLUDEDDRVS;

    if(!SetupDiSetDeviceInstallParams(Devs, DevInfo, &deviceInstallParams)) {
        return FALSE;
    }
    if(!SetupDiBuildDriverInfoList(Devs, DevInfo, SPDIT_CLASSDRIVER)) {
        return FALSE;
    }

    //
    // find the entry in the INF that was used to install the driver for
    // this device
    //
    for(c=0;SetupDiEnumDriverInfo(Devs,DevInfo,SPDIT_CLASSDRIVER,c,DriverInfoData);c++) {
        if((_tcscmp(DriverInfoData->MfgName,MfgName)==0)
            &&(_tcscmp(DriverInfoData->ProviderName,ProviderName)==0)) {
            //
            // these two fields match, try more detailed info
            // to ensure we have the exact driver entry used
            //
            SP_DRVINFO_DETAIL_DATA detail;
            detail.cbSize = sizeof(SP_DRVINFO_DETAIL_DATA);
            if(!SetupDiGetDriverInfoDetail(Devs,DevInfo,DriverInfoData,&detail,sizeof(detail),NULL)
                    && (GetLastError() != ERROR_INSUFFICIENT_BUFFER)) {
                continue;
            }
            if((_tcscmp(detail.SectionName,SectionName)==0) &&
                (_tcscmp(detail.DrvDescription,DrvDescription)==0)) {
                match = TRUE;
                break;
            }
        }
    }
    if(!match) {
        SetupDiDestroyDriverInfoList(Devs,DevInfo,SPDIT_CLASSDRIVER);
    }
    return match;
}