Exemplo n.º 1
0
NTSTATUS
NTAPI
UserEnumDisplayDevices(
    PUNICODE_STRING pustrDevice,
    DWORD iDevNum,
    PDISPLAY_DEVICEW pdispdev,
    DWORD dwFlags)
{
    PGRAPHICS_DEVICE pGraphicsDevice;
    ULONG cbSize;
    HKEY hkey;
    NTSTATUS Status;

    /* Ask gdi for the GRAPHICS_DEVICE */
    pGraphicsDevice = EngpFindGraphicsDevice(pustrDevice, iDevNum, 0);
    if (!pGraphicsDevice)
    {
        /* No device found */
        ERR("No GRAPHICS_DEVICE found\n");
        return STATUS_UNSUCCESSFUL;
    }

    /* Open thhe device map registry key */
    Status = RegOpenKey(KEY_VIDEO, &hkey);
    if (!NT_SUCCESS(Status))
    {
        /* No device found */
        ERR("Could not open reg key\n");
        return STATUS_UNSUCCESSFUL;
    }

    /* Query the registry path */
    cbSize = sizeof(pdispdev->DeviceKey);
    RegQueryValue(hkey,
                  pGraphicsDevice->szNtDeviceName,
                  REG_SZ,
                  pdispdev->DeviceKey,
                  &cbSize);

    /* Close registry key */
    ZwClose(hkey);

    /* Copy device name, device string and StateFlags */
    RtlStringCbCopyW(pdispdev->DeviceName, sizeof(pdispdev->DeviceName), pGraphicsDevice->szWinDeviceName);
    RtlStringCbCopyW(pdispdev->DeviceString, sizeof(pdispdev->DeviceString), pGraphicsDevice->pwszDescription);
    pdispdev->StateFlags = pGraphicsDevice->StateFlags;
    // FIXME: fill in DEVICE ID
    pdispdev->DeviceID[0] = UNICODE_NULL;

    return STATUS_SUCCESS;
}
Exemplo n.º 2
0
void CMainFrame::OnViewViewxml()
{
	CGumpEditorDoc* pDoc = GetGumpDocument();
	if (!pDoc || pDoc->GetPathName().IsEmpty()) return;

	char szPath[MAX_PATH+1]={0,};
	LONG cbValue=sizeof(szPath);
	RegQueryValue(HKEY_LOCAL_MACHINE,"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\IEXPLORE.EXE", szPath, &cbValue);

	
	CString strExec;
	strExec.Format("%s %s", szPath, pDoc->GetPathName());
	WinExec(strExec,SW_SHOW);
}
Exemplo n.º 3
0
LONG CHyperLink::GetRegKey(HKEY key, LPCTSTR subkey, LPTSTR retdata)
{
    HKEY hkey;
    LONG retval = RegOpenKeyEx(key, subkey, 0, KEY_QUERY_VALUE, &hkey);

    if (retval == ERROR_SUCCESS) {
        long datasize = MAX_PATH;
        TCHAR data[MAX_PATH];
        RegQueryValue(hkey, NULL, data, &datasize);
        lstrcpy(retdata,data);
        RegCloseKey(hkey);
    }

    return retval;
}
Exemplo n.º 4
0
LONG CHyperLink::GetRegKey(HKEY key, LPCTSTR szSubkey, LPTSTR szRetData, int retStrLen)
{
    HKEY hKey;
    LONG lRetVal = RegOpenKeyEx(key, szSubkey, 0, KEY_QUERY_VALUE, &hKey);

    if (szRetData == ERROR_SUCCESS) {
        long nDataSize = MAX_PATH;
        TCHAR szData[MAX_PATH];
        RegQueryValue(hKey, NULL, szData, &nDataSize);
        CopyString(szRetData, szData, retStrLen);
        RegCloseKey(hKey);
    }

    return lRetVal;
}
Exemplo n.º 5
0
/* This is called from the crash handler; don't use RegistryAccess, since it's
 * not crash-conditions safe. */
static LONG GetRegKey( HKEY key, RString subkey, LPTSTR retdata )
{
	HKEY hKey;
    LONG iRet = RegOpenKeyEx( key, subkey, 0, KEY_QUERY_VALUE, &hKey );

    if( iRet != ERROR_SUCCESS )
		return iRet;

	long iDataSize = MAX_PATH;
	char data[MAX_PATH];
	RegQueryValue( hKey, "emulation", data, &iDataSize );
	strcpy( retdata, data );
	RegCloseKey( hKey );

    return ERROR_SUCCESS;
}
Exemplo n.º 6
0
static long GetRegKey(HKEY hKey, LPCTSTR subkey, LPTSTR retdata)
{
	HKEY hSubKey;
	long retval = RegOpenKeyEx(hKey, subkey, 0, KEY_QUERY_VALUE, &hSubKey);
	
	if (retval == ERROR_SUCCESS) 
	{
		long datasize = MAX_PATH;
		TCHAR data[MAX_PATH];
		RegQueryValue(hSubKey, NULL, data, &datasize);
		_tcscpy(retdata,data);
		RegCloseKey(hSubKey);
	}
	
	return retval;
}
Exemplo n.º 7
0
LONG
CHyperLink::GetRegKey( HKEY hKey, zCPCHAR cpcSubkey, zPCHAR pchReturnData )
{
   zLONG lRC = RegOpenKeyEx( hKey, cpcSubkey, 0, KEY_QUERY_VALUE, &hKey );

   if ( lRC == ERROR_SUCCESS )
   {
      zLONG lDataSize = MAX_PATH;
      zCHAR szData[ MAX_PATH ];
      RegQueryValue( hKey, 0, szData, &lDataSize );
      strcpy_s( pchReturnData, MAX_PATH, szData );
      RegCloseKey( hKey );
   }

   return( lRC );
}
Exemplo n.º 8
0
/* RegCopyClassName() - Returns the ASCII class id from the listbox.
 */
BOOL FAR RegCopyClassName(HWND hwndList, LPSTR lpstrClassName) {
    BOOL    fSuccess = FALSE;
    DWORD   dwSize = 0L;
    HKEY    hkeyTemp;
    char    szClass[KEYNAMESIZE];
    char    szExec[KEYNAMESIZE];
    char    szKey[KEYNAMESIZE];
    char    szName[KEYNAMESIZE];
    int     i;
    int     iWhich;

    iWhich = (int)SendMessage(hwndList, LB_GETCURSEL, 0, 0L);
    SendMessage(hwndList, LB_GETTEXT, iWhich, (DWORD)(LPSTR)szKey);

    RegOpenKey(HKEY_CLASSES_ROOT,NULL,&hkeyRoot);
    for (i = 0; !fSuccess && !RegEnumKey(HKEY_CLASSES_ROOT, i++, szClass, KEYNAMESIZE); )
        if (*szClass != '.') {          /* Not default extension... */

            /* See if this class really refers to a server */
            dwSize = 0;
            hkeyTemp = NULL;
            lstrcpy(szExec, szClass);
            lstrcat(szExec, "\\protocol\\StdFileEditing\\server");

            if (!RegOpenKey(HKEY_CLASSES_ROOT, szExec, &hkeyTemp)) {
                /* ... get the class name string */
                dwSize = KEYNAMESIZE;
                if (!RegQueryValue(HKEY_CLASSES_ROOT, szClass, szName, &dwSize)
                    && !lstrcmp(szName, szKey))
                    fSuccess = TRUE;

                RegCloseKey(hkeyTemp);
            }
        }

    if (fSuccess)
        lstrcpy(lpstrClassName, szClass);

    if (hkeyRoot)
    {
        RegCloseKey(hkeyRoot);
        hkeyRoot = NULL;
    }

    return fSuccess;
}
Exemplo n.º 9
0
BOOL CMIKeysExist()
{
	HKEY key;
	unsigned int i;
	BOOL result = FALSE;
	LONG size;

	if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"), NULL, KEY_SET_VALUE, &key) != ERROR_SUCCESS) {
		PrintLastError("RegOpenKeyEx()");
		return FALSE;
	}
	for (i=0;i<NumberOfCMIKeys;i++) {
		result |= (RegQueryValue(key, CMIKeys[i], NULL, &size) == ERROR_SUCCESS);
	}
	RegCloseKey(key);

	return result;
}
Exemplo n.º 10
0
static long get_reg_key (HKEY key, char *subkey, char *retdata)
{
    long err;
    HKEY hkey;

    err = RegOpenKeyEx(key, subkey, 0, KEY_QUERY_VALUE, &hkey);

    if (err == ERROR_SUCCESS) {
	long datasize = MAX_PATH;
	char data[MAX_PATH];

	RegQueryValue(hkey, NULL, (LPSTR) data, &datasize);

	lstrcpy(retdata, data);
	RegCloseKey(hkey);
    }

    return err;
}
Exemplo n.º 11
0
BOOL CWinApp::Unregister()
{
	HKEY    hKey = 0;
	TCHAR   szBuf[MAX_PATH+1];
	LONG    cSize;
	BOOL    bRet = TRUE;

	POSITION pos = GetFirstDocTemplatePosition();
	while (pos != NULL)
	{
		CDocTemplate* pTempl = GetNextDocTemplate(pos);
		if (pTempl != NULL)
			pTempl->OnCmdMsg(0, CN_OLE_UNREGISTER, NULL, NULL);
	}

	// Remove profile information -- the registry entries exist if
	// SetRegistryKey() was used.

	if (m_pszRegistryKey)
	{
		ASSERT(m_pszProfileName);

		CString strKey = _T("Software\\");
		strKey += m_pszRegistryKey;
		CString strSubKey = strKey + _T("\\") + m_pszProfileName;

		DelRegTree(HKEY_CURRENT_USER, strSubKey);

		// If registry key is empty then remove it

		DWORD   dwResult;
		if ((dwResult = ::RegOpenKey(HKEY_CURRENT_USER, strKey, &hKey)) ==
			ERROR_SUCCESS)
		{
			if (::RegEnumKey(hKey, 0, szBuf, _MAX_PATH) == ERROR_NO_MORE_ITEMS)
				DelRegTree(HKEY_CURRENT_USER, strKey);
			::RegCloseKey(hKey);
		}
		if (RegQueryValue(HKEY_CURRENT_USER, strSubKey, szBuf, &cSize) == ERROR_SUCCESS)
			bRet = TRUE;
	}
	return bRet;
}
Exemplo n.º 12
0
BOOL CBatchRunBtn::OnSetLCID(DWORD dwLCID, HMODULE hInstance)
{
	TCHAR szLCID[20];
	wsprintf(szLCID, TEXT("%d"), dwLCID);
	BOOL ret = CTlbButton::OnSetLCID(dwLCID, hInstance);

	TCHAR langPath[MAX_PATH];
	LONG cbData = sizeof(langPath);
	RegQueryValue(HKEY_CLASSES_ROOT, TEXT("CLSID\\{FC712CA0-A945-11D4-A594-956F6349FC18}\\InprocServer32"), langPath, &cbData);
	PathRemoveFileSpec(langPath);
	PathAddBackslash(langPath);
	lstrcat(langPath, TEXT("langs\\"));
	lstrcat(langPath, szLCID);
	lstrcat(langPath, TEXT("\\batchrun.xml"));
	m_xui.clearStrings();
	m_xui.loadStrings(langPath);

	return ret;
}
Exemplo n.º 13
0
static void lcRegisterShellFileTypes()
{
	TCHAR modulePath[_MAX_PATH], longModulePath[_MAX_PATH];
	TCHAR temp[2*_MAX_PATH];

	GetModuleFileName(NULL, longModulePath, _MAX_PATH);
	if (GetShortPathName(longModulePath, modulePath, _MAX_PATH) == 0)
		lstrcpy(modulePath, longModulePath);

	if (RegSetValue(HKEY_CLASSES_ROOT, TEXT("LeoCAD.Project"), REG_SZ, TEXT("LeoCAD Project"), lstrlen(TEXT("LeoCAD Project")) * sizeof(TCHAR)) != ERROR_SUCCESS)
		return;

	lstrcpy(temp, modulePath);
	lstrcat(temp, TEXT(",0"));
	if (RegSetValue(HKEY_CLASSES_ROOT, TEXT("LeoCAD.Project\\DefaultIcon"), REG_SZ, temp, lstrlen(temp) * sizeof(TCHAR)) != ERROR_SUCCESS)
		return;

	lstrcpy(temp, modulePath);
	lstrcat(temp, TEXT(" \"%1\""));
	if (RegSetValue(HKEY_CLASSES_ROOT, TEXT("LeoCAD.Project\\shell\\open\\command"), REG_SZ, temp, lstrlen(temp) * sizeof(TCHAR)) != ERROR_SUCCESS)
		return;

	LONG size = 2 * _MAX_PATH;
	LONG result = RegQueryValue(HKEY_CLASSES_ROOT, TEXT(".lcd"), temp, &size);

	if (result != ERROR_SUCCESS || !lstrlen(temp) || lstrcmp(temp, TEXT("LeoCAD.Project")))
	{
		if (RegSetValue(HKEY_CLASSES_ROOT, TEXT(".lcd"), REG_SZ, TEXT("LeoCAD.Project"), lstrlen(TEXT("LeoCAD.Project")) * sizeof(TCHAR)) != ERROR_SUCCESS)
			return;

		HKEY key;
		DWORD disposition = 0;

		if (RegCreateKeyEx(HKEY_CLASSES_ROOT, TEXT(".lcd\\ShellNew"), 0, REG_NONE, REG_OPTION_NON_VOLATILE, KEY_WRITE | KEY_READ, NULL, &key, &disposition) != ERROR_SUCCESS)
			return;

		LONG result = RegSetValueEx(key, TEXT("NullFile"), 0, REG_SZ, (CONST BYTE*)TEXT(""), (lstrlen(TEXT("")) + 1) * sizeof(TCHAR));

		if (RegCloseKey(key) != ERROR_SUCCESS || result != ERROR_SUCCESS)
			return;
	}
}
Exemplo n.º 14
0
//===========================================================================
int WINAPI DllEntryPoint(HINSTANCE hinst, unsigned long reason, void* lpReserved)
{
   if(reason==DLL_PROCESS_ATTACH) {
	   HKEY   pOpenKey;
	   char*  cResult="";    // Узнаём как перекл. раскладка
	   long   lSize=2;
		  KEYBLAY=3;

           if(RegOpenKey(HKEY_USERS,".Default\\keyboard layout\\toggle", &pOpenKey)==ERROR_SUCCESS) {
                 RegQueryValue(pOpenKey,"",cResult,&lSize);
                 if (strcmp(cResult,"1") == 0) KEYBLAY=1;    // Alt+Shift
                 if (strcmp(cResult,"2") == 0) KEYBLAY=2;    // Ctrl+Shift
                 RegCloseKey(pOpenKey);
           } else { MessageBox(0,"Не могу получить данные о способе переключения раскладки клавиатуры", "Внимание!", MB_ICONERROR); }

           if(!SystemParametersInfo(SPI_GETSCREENSAVEACTIVE,0, &bSCRSAVEACTIVE,0))
                 MessageBox(0,"Не могу получить данные об установленном хранителе экрана", "Внимание!",MB_ICONERROR);
   }
   return 1;
}
Exemplo n.º 15
0
FILE *PyWin_FindRegisteredModule( const char *moduleName, struct filedescr **ppFileDesc, char *pathBuf, int pathLen)
{
	char *moduleKey;
	const char keyPrefix[] = "Software\\Python\\PythonCore\\";
	const char keySuffix[] = "\\Modules\\";
#ifdef _DEBUG
	// In debugging builds, we _must_ have the debug version registered.
	const char debugString[] = "\\Debug";
#else
	const char debugString[] = "";
#endif
	struct filedescr *fdp = NULL;
	FILE *fp;
	HKEY keyBase = PyWin_IsWin32s() ? HKEY_CLASSES_ROOT : HKEY_LOCAL_MACHINE;
	int modNameSize;
	long regStat;

	// Calculate the size for the sprintf buffer.
	// Get the size of the chars only, plus 1 NULL.
	int bufSize = sizeof(keyPrefix)-1 + strlen(PyWin_DLLVersionString) + sizeof(keySuffix) + strlen(moduleName) + sizeof(debugString) - 1;
	// alloca == no free required, but memory only local to fn, also no heap fragmentation!
	moduleKey = alloca(bufSize); 
	sprintf(moduleKey, "Software\\Python\\PythonCore\\%s\\Modules\\%s%s", PyWin_DLLVersionString, moduleName, debugString);

	modNameSize = pathLen;
	regStat = RegQueryValue(keyBase, moduleKey, pathBuf, &modNameSize);
	if (regStat!=ERROR_SUCCESS)
		return NULL;
	// use the file extension to locate the type entry.
	for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
		int extLen=strlen(fdp->suffix);
		if (modNameSize>extLen && strnicmp(pathBuf+(modNameSize-extLen-1),fdp->suffix,extLen)==0)
			break;
	}
	if (fdp->suffix==NULL)
		return NULL;
	fp = fopen(pathBuf, fdp->mode);
	if (fp != NULL)
		*ppFileDesc = fdp;
	return fp;
}
Exemplo n.º 16
0
/* RegGetClassNames() - Fills the list box with possible server names.
 */
BOOL FAR RegGetClassNames(HWND hwndList) {
    BOOL    fSuccess = FALSE;
    DWORD   dwSize = 0L;
    HKEY    hkeyTemp;
    char    szClass[KEYNAMESIZE];
    char    szExec[KEYNAMESIZE];
    char    szName[KEYNAMESIZE];
    int     i;

    SendMessage(hwndList, LB_RESETCONTENT, 0, 0L);

    RegOpenKey(HKEY_CLASSES_ROOT,NULL,&hkeyRoot);
    for (i = 0; !RegEnumKey(HKEY_CLASSES_ROOT, i++, szClass, KEYNAMESIZE); )
        if (*szClass != '.') {          /* Not default extension... */

            /* See if this class really refers to a server */
            dwSize = 0;
            hkeyTemp = NULL;
            lstrcpy(szExec, szClass);
            lstrcat(szExec, "\\protocol\\StdFileEditing\\server");

            if (!RegOpenKey(HKEY_CLASSES_ROOT, szExec, &hkeyTemp)) {
                /* ... get the class name string */
                dwSize = KEYNAMESIZE;
                if (!RegQueryValue(HKEY_CLASSES_ROOT, szClass, szName, &dwSize)) {
                    SendMessage(hwndList, LB_ADDSTRING, 0, (DWORD)(LPSTR)szName);
                    fSuccess = TRUE;
                }
                RegCloseKey(hkeyTemp);
            }
        }

    if (hkeyRoot)
    {
        RegCloseKey(hkeyRoot);
        hkeyRoot = NULL;
    }
    return fSuccess;
}
Exemplo n.º 17
0
void loSearchIID(IUnknown *punk)
{
 DWORD indx;
 HKEY key;
 char buf[256], *tbuf;

 UL_TRACE((LOGID, "Iface: %p", punk));

 if (ERROR_SUCCESS != RegOpenKey(HKEY_CLASSES_ROOT, "Interface", &key))
   {
    UL_ERROR((LOGID, "%!L RegOpenKey(Interface)"));
    return;
   }
 strcpy(buf, "Interface\\");
 tbuf = buf + strlen(buf);
 for(indx = 0; ERROR_SUCCESS == RegEnumKey(
               key, indx, tbuf, buf + sizeof(buf) - tbuf); indx++)
   {
    GUID iid;
    HRESULT hr;
    IUnknown *qi;
    LONG cb;
    char name[256]; name[0] = 0;
    cb = sizeof(name);
    RegQueryValue(key, tbuf, name, &cb);
    StrToIID(&iid, tbuf);
    if (S_OK == (hr = punk->QueryInterface(iid, (LPVOID*)&qi)))
      {
       UL_TRACE((LOGID, "Ok %s %p", name, qi));
       qi->Release();
      }
/*    else if (hr != E_NOINTERFACE)
      {
       UL_DEBUG((LOGID, "%!l %s -> %s", hr, name, tbuf));
      }    */
   }
 RegCloseKey(key);
}
Exemplo n.º 18
0
int fileassociation_selected(const string ext)
{
    letter         apext[255];
    letter         apcls[255];
    letter         rvalue[260];
    unsigned long  rvsize = sizeof(rvalue);
    const string   cls_name = uni("fennec.player.file.");

    apext[0] = uni('.');
    str_cpy(apext + 1, ext);

    str_cpy(apcls, cls_name);
    str_cat(apcls, ext); /* i.e. "fennec.player.file.ogg" */

    memset(rvalue, 0, sizeof(rvalue));

    RegQueryValue(HKEY_CLASSES_ROOT, apext, rvalue, (PLONG)&rvsize);

    if(rvsize)
    {
        if(str_icmp(apcls, rvalue))return 0;
    }
    return 1;
}
Exemplo n.º 19
0
BOOL ShareDLL_Init(void)
{
    TCHAR szPath[MAX_PATH];
    LONG cb;

    //BUGBUG!!! what if share.dll is gone?

    // See if we have already tried to load this in this context
    if (s_fShareLoaded)
        return(TRUE);

    s_fShareLoaded = TRUE;
    szPath[0] = 0;
    cb = SIZEOF(szPath);
    RegQueryValue(HKEY_CLASSES_ROOT, c_szNetworkSharingHandler, szPath, &cb);
    if (szPath[0]) {
        s_hmodShare = LoadLibrary(szPath);
        if (ISVALIDHINSTANCE(s_hmodShare)) {
            g_pfnIsPathShared = (PFNISPATHSHARED)GetProcAddress(s_hmodShare, c_szPathIsShared);
        }
    }

    return TRUE;
}
Exemplo n.º 20
0
// Queries registry for those three file names
BOOLEAN WinLdrGetNLSNames(LPSTR AnsiName,
                          LPSTR OemName,
                          LPSTR LangName)
{
	LONG rc = ERROR_SUCCESS;
	FRLDRHKEY hKey;
	WCHAR szIdBuffer[80];
	WCHAR NameBuffer[80];
	ULONG BufferSize;

	/* open the codepage key */
	rc = RegOpenKey(NULL,
		L"\\Registry\\Machine\\SYSTEM\\CurrentControlSet\\Control\\NLS\\CodePage",
		&hKey);
	if (rc != ERROR_SUCCESS)
	{
		//strcpy(szErrorOut, "Couldn't open CodePage registry key");
		return FALSE;
	}

	/* get ANSI codepage */
	BufferSize = sizeof(szIdBuffer);
	rc = RegQueryValue(hKey, L"ACP", NULL, (PUCHAR)szIdBuffer, &BufferSize);
	if (rc != ERROR_SUCCESS)
	{
		//strcpy(szErrorOut, "Couldn't get ACP NLS setting");
		return FALSE;
	}

	BufferSize = sizeof(NameBuffer);
	rc = RegQueryValue(hKey, szIdBuffer, NULL, (PUCHAR)NameBuffer, &BufferSize);
	if (rc != ERROR_SUCCESS)
	{
		//strcpy(szErrorOut, "ACP NLS Setting exists, but isn't readable");
		return FALSE;
	}
	sprintf(AnsiName, "%S", NameBuffer);

	/* get OEM codepage */
	BufferSize = sizeof(szIdBuffer);
	rc = RegQueryValue(hKey, L"OEMCP", NULL, (PUCHAR)szIdBuffer, &BufferSize);
	if (rc != ERROR_SUCCESS)
	{
		//strcpy(szErrorOut, "Couldn't get OEMCP NLS setting");
		return FALSE;
	}

	BufferSize = sizeof(NameBuffer);
	rc = RegQueryValue(hKey, szIdBuffer, NULL, (PUCHAR)NameBuffer, &BufferSize);
	if (rc != ERROR_SUCCESS)
	{
		//strcpy(szErrorOut, "OEMCP NLS setting exists, but isn't readable");
		return FALSE;
	}
	sprintf(OemName, "%S", NameBuffer);

	/* open the language key */
	rc = RegOpenKey(NULL,
		L"\\Registry\\Machine\\SYSTEM\\CurrentControlSet\\Control\\NLS\\Language",
		&hKey);
	if (rc != ERROR_SUCCESS)
	{
		//strcpy(szErrorOut, "Couldn't open Language registry key");
		return FALSE;
	}

	/* get the Unicode case table */
	BufferSize = sizeof(szIdBuffer);
	rc = RegQueryValue(hKey, L"Default", NULL, (PUCHAR)szIdBuffer, &BufferSize);
	if (rc != ERROR_SUCCESS)
	{
		//strcpy(szErrorOut, "Couldn't get Language Default setting");
		return FALSE;
	}

	BufferSize = sizeof(NameBuffer);
	rc = RegQueryValue(hKey, szIdBuffer, NULL, (PUCHAR)NameBuffer, &BufferSize);
	if (rc != ERROR_SUCCESS)
	{
		//strcpy(szErrorOut, "Language Default setting exists, but isn't readable");
		return FALSE;
	}
	sprintf(LangName, "%S", NameBuffer);

	return TRUE;
}
Exemplo n.º 21
0
VOID
WinLdrScanRegistry(IN OUT PLOADER_PARAMETER_BLOCK LoaderBlock,
                   IN LPCSTR DirectoryPath)
{
	LONG rc = 0;
	FRLDRHKEY hGroupKey, hOrderKey, hServiceKey, hDriverKey;
	LPWSTR GroupNameBuffer;
	WCHAR ServiceName[256];
	ULONG OrderList[128];
	ULONG BufferSize;
	ULONG Index;
	ULONG TagIndex;
	LPWSTR GroupName;

	ULONG ValueSize;
	ULONG ValueType;
	ULONG StartValue;
	ULONG TagValue;
	WCHAR DriverGroup[256];
	ULONG DriverGroupSize;

	CHAR ImagePath[256];
	WCHAR TempImagePath[256];

	BOOLEAN Status;

	/* get 'service group order' key */
	rc = RegOpenKey(NULL,
		L"\\Registry\\Machine\\SYSTEM\\CurrentControlSet\\Control\\ServiceGroupOrder",
		&hGroupKey);
	if (rc != ERROR_SUCCESS) {

		TRACE_CH(ODYSSEY, "Failed to open the 'ServiceGroupOrder' key (rc %d)\n", (int)rc);
		return;
	}

	/* get 'group order list' key */
	rc = RegOpenKey(NULL,
		L"\\Registry\\Machine\\SYSTEM\\CurrentControlSet\\Control\\GroupOrderList",
		&hOrderKey);
	if (rc != ERROR_SUCCESS) {

		TRACE_CH(ODYSSEY, "Failed to open the 'GroupOrderList' key (rc %d)\n", (int)rc);
		return;
	}

	/* enumerate drivers */
	rc = RegOpenKey(NULL,
		L"\\Registry\\Machine\\SYSTEM\\CurrentControlSet\\Services",
		&hServiceKey);
	if (rc != ERROR_SUCCESS)  {

		TRACE_CH(ODYSSEY, "Failed to open the 'Services' key (rc %d)\n", (int)rc);
		return;
	}

	/* Get the Name Group */
	BufferSize = 4096;
	GroupNameBuffer = MmHeapAlloc(BufferSize);
	rc = RegQueryValue(hGroupKey, L"List", NULL, (PUCHAR)GroupNameBuffer, &BufferSize);
	TRACE_CH(ODYSSEY, "RegQueryValue(): rc %d\n", (int)rc);
	if (rc != ERROR_SUCCESS)
		return;
	TRACE_CH(ODYSSEY, "BufferSize: %d \n", (int)BufferSize);
	TRACE_CH(ODYSSEY, "GroupNameBuffer: '%S' \n", GroupNameBuffer);

	/* Loop through each group */
	GroupName = GroupNameBuffer;
	while (*GroupName)
	{
		TRACE("Driver group: '%S'\n", GroupName);

		/* Query the Order */
		BufferSize = sizeof(OrderList);
		rc = RegQueryValue(hOrderKey, GroupName, NULL, (PUCHAR)OrderList, &BufferSize);
		if (rc != ERROR_SUCCESS) OrderList[0] = 0;

		/* enumerate all drivers */
		for (TagIndex = 1; TagIndex <= OrderList[0]; TagIndex++)
		{
			Index = 0;

			while (TRUE)
			{
				/* Get the Driver's Name */
				ValueSize = sizeof(ServiceName);
				rc = RegEnumKey(hServiceKey, Index, ServiceName, &ValueSize);
				//TRACE_CH(ODYSSEY, "RegEnumKey(): rc %d\n", (int)rc);

				/* Makre sure it's valid, and check if we're done */
				if (rc == ERROR_NO_MORE_ITEMS)
					break;
				if (rc != ERROR_SUCCESS)
				{
					MmHeapFree(GroupNameBuffer);
					return;
				}
				//TRACE_CH(ODYSSEY, "Service %d: '%S'\n", (int)Index, ServiceName);

				/* open driver Key */
				rc = RegOpenKey(hServiceKey, ServiceName, &hDriverKey);
				if (rc == ERROR_SUCCESS)
				{
					/* Read the Start Value */
					ValueSize = sizeof(ULONG);
					rc = RegQueryValue(hDriverKey, L"Start", &ValueType, (PUCHAR)&StartValue, &ValueSize);
					if (rc != ERROR_SUCCESS) StartValue = (ULONG)-1;
					//TRACE_CH(ODYSSEY, "  Start: %x  \n", (int)StartValue);

					/* Read the Tag */
					ValueSize = sizeof(ULONG);
					rc = RegQueryValue(hDriverKey, L"Tag", &ValueType, (PUCHAR)&TagValue, &ValueSize);
					if (rc != ERROR_SUCCESS) TagValue = (ULONG)-1;
					//TRACE_CH(ODYSSEY, "  Tag:   %x  \n", (int)TagValue);

					/* Read the driver's group */
					DriverGroupSize = sizeof(DriverGroup);
					rc = RegQueryValue(hDriverKey, L"Group", NULL, (PUCHAR)DriverGroup, &DriverGroupSize);
					//TRACE_CH(ODYSSEY, "  Group: '%S'  \n", DriverGroup);

					/* Make sure it should be started */
					if ((StartValue == 0) &&
						(TagValue == OrderList[TagIndex]) &&
						(_wcsicmp(DriverGroup, GroupName) == 0)) {

							/* Get the Driver's Location */
							ValueSize = sizeof(TempImagePath);
							rc = RegQueryValue(hDriverKey, L"ImagePath", NULL, (PUCHAR)TempImagePath, &ValueSize);

							/* Write the whole path if it suceeded, else prepare to fail */
							if (rc != ERROR_SUCCESS) {
								TRACE_CH(ODYSSEY, "ImagePath: not found\n");
								TempImagePath[0] = 0;
								sprintf(ImagePath, "%s\\system32\\drivers\\%S.sys", DirectoryPath, ServiceName);
							} else if (TempImagePath[0] != L'\\') {
								sprintf(ImagePath, "%s%S", DirectoryPath, TempImagePath);
							} else {
								sprintf(ImagePath, "%S", TempImagePath);
								TRACE_CH(ODYSSEY, "ImagePath: '%s'\n", ImagePath);
							}

							TRACE("Adding boot driver: '%s'\n", ImagePath);

							Status = WinLdrAddDriverToList(&LoaderBlock->BootDriverListHead,
								L"\\Registry\\Machine\\System\\CurrentControlSet\\Services\\",
								TempImagePath,
								ServiceName);

							if (!Status)
								ERR("Failed to add boot driver\n");
					} else
					{
						//TRACE("  Skipping driver '%S' with Start %d, Tag %d and Group '%S' (Current Tag %d, current group '%S')\n",
						//	ServiceName, StartValue, TagValue, DriverGroup, OrderList[TagIndex], GroupName);
					}
				}

				Index++;
			}
		}

		Index = 0;
		while (TRUE)
		{
			/* Get the Driver's Name */
			ValueSize = sizeof(ServiceName);
			rc = RegEnumKey(hServiceKey, Index, ServiceName, &ValueSize);

			//TRACE_CH(ODYSSEY, "RegEnumKey(): rc %d\n", (int)rc);
			if (rc == ERROR_NO_MORE_ITEMS)
				break;
			if (rc != ERROR_SUCCESS)
			{
				MmHeapFree(GroupNameBuffer);
				return;
			}
			//TRACE_CH(ODYSSEY, "Service %d: '%S'\n", (int)Index, ServiceName);

			/* open driver Key */
			rc = RegOpenKey(hServiceKey, ServiceName, &hDriverKey);
			if (rc == ERROR_SUCCESS)
			{
				/* Read the Start Value */
				ValueSize = sizeof(ULONG);
				rc = RegQueryValue(hDriverKey, L"Start", &ValueType, (PUCHAR)&StartValue, &ValueSize);
				if (rc != ERROR_SUCCESS) StartValue = (ULONG)-1;
				//TRACE_CH(ODYSSEY, "  Start: %x  \n", (int)StartValue);

				/* Read the Tag */
				ValueSize = sizeof(ULONG);
				rc = RegQueryValue(hDriverKey, L"Tag", &ValueType, (PUCHAR)&TagValue, &ValueSize);
				if (rc != ERROR_SUCCESS) TagValue = (ULONG)-1;
				//TRACE_CH(ODYSSEY, "  Tag:   %x  \n", (int)TagValue);

				/* Read the driver's group */
				DriverGroupSize = sizeof(DriverGroup);
				rc = RegQueryValue(hDriverKey, L"Group", NULL, (PUCHAR)DriverGroup, &DriverGroupSize);
				//TRACE_CH(ODYSSEY, "  Group: '%S'  \n", DriverGroup);

				for (TagIndex = 1; TagIndex <= OrderList[0]; TagIndex++) {
					if (TagValue == OrderList[TagIndex]) break;
				}

				if ((StartValue == 0) &&
					(TagIndex > OrderList[0]) &&
					(_wcsicmp(DriverGroup, GroupName) == 0)) {

						ValueSize = sizeof(TempImagePath);
						rc = RegQueryValue(hDriverKey, L"ImagePath", NULL, (PUCHAR)TempImagePath, &ValueSize);
						if (rc != ERROR_SUCCESS) {
							TRACE_CH(ODYSSEY, "ImagePath: not found\n");
							TempImagePath[0] = 0;
							sprintf(ImagePath, "%ssystem32\\drivers\\%S.sys", DirectoryPath, ServiceName);
						} else if (TempImagePath[0] != L'\\') {
							sprintf(ImagePath, "%s%S", DirectoryPath, TempImagePath);
						} else {
							sprintf(ImagePath, "%S", TempImagePath);
							TRACE_CH(ODYSSEY, "ImagePath: '%s'\n", ImagePath);
						}
						TRACE("  Adding boot driver: '%s'\n", ImagePath);

						Status = WinLdrAddDriverToList(&LoaderBlock->BootDriverListHead,
							L"\\Registry\\Machine\\System\\CurrentControlSet\\Services\\",
							TempImagePath,
							ServiceName);

						if (!Status)
							ERR(" Failed to add boot driver\n");
				} else
				{
					//TRACE("  Skipping driver '%S' with Start %d, Tag %d and Group '%S' (Current group '%S')\n",
					//	ServiceName, StartValue, TagValue, DriverGroup, GroupName);
				}
			}

			Index++;
		}

		/* Move to the next group name */
		GroupName = GroupName + wcslen(GroupName) + 1;
	}

	/* Free allocated memory */
	MmHeapFree(GroupNameBuffer);
}
Exemplo n.º 22
0
int fileassociation_set(const string ext,    /* extension (w\o leading period) */
                        const string acname, /* action name */
                        const string lacname,/* long action name */
                        const string icpath, /* icon path */
                        const string accmd,  /* action command */
                        const string dsc,    /* type description */
                        int          icidx)  /* icon index */
{

    letter        apext [256];
    letter        apcls [256];
    letter        kval  [256];
    letter        icdat [256];
    letter        tmpbuf[128];
    HKEY          rkey, extkey, clskey, tmpkey, tmpkey2, tmpkey3;
    long          vsize;
    const string  cls_name = uni("fennec.player.file.");
    const string  bkp_name = uni("fennec.player.backup");

    if(!ext)return 0;
    if(!acname)return 0;
    if(!str_len(ext))return 0;
    if(!str_len(acname))return 0;

    if(icidx == -1)icidx = get_default_file_icon(ext);

    apext[0] = uni('.');
    str_cpy(apext + 1, ext);

    /* create class name */

    str_cpy(apcls, cls_name);
    str_cat(apcls, ext); /* i.e. "fennec.player.file.ogg" */

    /* try opening keys */

    if(RegOpenKey(HKEY_CLASSES_ROOT, 0, &rkey) != ERROR_SUCCESS)return 0;


    RegCreateKey(rkey, apext, &extkey);

    /* get current value */

    memset(kval, 0, sizeof(kval));
    vsize = sizeof(kval);
    RegQueryValue(extkey, 0 /* (default) */, kval, &vsize);

    if(str_icmp(apcls, kval))
    {
        /* create a backup */
        RegSetValueEx(extkey, bkp_name, 0, REG_SZ, (CONST BYTE*)kval, (unsigned long)str_size(kval));
    }

    RegSetValue(extkey, 0, REG_SZ, apcls, (unsigned long)str_size(apcls));

    RegCloseKey(extkey);

    /* create the class */

    if(RegCreateKey(rkey, apcls, &clskey) != ERROR_SUCCESS)
    {
        RegCloseKey(rkey);
        return 0;
    }

    RegSetValue(clskey, 0, REG_SZ, dsc, (unsigned long)str_size(dsc));

    /* <icon creation> */

    RegCreateKey(clskey, uni("DefaultIcon"), &tmpkey);

    memset(tmpbuf, 0, sizeof(tmpbuf));
    str_itos(icidx, tmpbuf, 10);
    str_cpy(icdat, icpath);
    str_cat(icdat, uni(","));
    str_cat(icdat, tmpbuf);

    RegSetValue(tmpkey, 0, REG_SZ, icdat, (unsigned long)str_size(icdat));

    RegCloseKey(tmpkey);

    /* </icon creation> */

    /* <shell> */

    RegCreateKey(clskey, uni("shell"), &tmpkey);

    RegSetValue(tmpkey, 0, REG_SZ, acname, (unsigned long)str_size(acname));

    RegCreateKey(tmpkey, acname, &tmpkey2);

    RegSetValue(tmpkey2, 0, REG_SZ, lacname, (unsigned long)str_size(lacname));

    RegCreateKey(tmpkey2, uni("command"), &tmpkey3);

    memset(kval, 0, sizeof(kval));
    str_cpy(kval, uni("\""));
    str_cat(kval, accmd);
    str_cat(kval, uni("\" \"%1\"")); /* "%1" */

    RegSetValue(tmpkey3, 0, REG_SZ, kval, (unsigned long)str_size(kval));

    RegCloseKey(tmpkey3);
    RegCloseKey(tmpkey2);
    RegCloseKey(tmpkey);
    RegCloseKey(clskey);
    RegCloseKey(rkey);

    str_cpy(apcls, uni("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\"));
    str_cat(apcls, apext);

    RegOpenKey(HKEY_CURRENT_USER, apcls, &rkey);
    RegDeleteValue(rkey, uni("Application"));
    RegDeleteValue(rkey, uni("ProgID"));
    RegCloseKey(rkey);

    /* </shell> */
    return 1;
}
Exemplo n.º 23
0
extern "C" void __declspec(dllexport) GetRegistrationInfo(RegistrationInfo* info)
{
	long size = 0;
	LONG ret = 0;
	time_t ltime = 0;
	time_t currTime = 0;

	memset(info, 0, sizeof(*info));

	// get name
	size = sizeof(info->name);
	info->name[0] = 0;
	ret = RegQueryValue(HKEY_CLASSES_ROOT,
							 RegKeyValues[3][0],
							 (char*)&(info->name),
							 &size);

	// get organization
	size = sizeof(info->organization);
	info->organization[0] = 0;
	ret = RegQueryValue(HKEY_CLASSES_ROOT,
							 RegKeyValues[4][0],
							 (char*)&(info->organization),
							 &size);

	// get registration code
	static char regbuf[16];
	size = sizeof(regbuf);
	regbuf[0] = 0;
	ret = RegQueryValue(HKEY_CLASSES_ROOT,
							 RegKeyValues[5][0],
							 (char*)&regbuf,
							 &size);
	if (regbuf[0])
		info->registrationCode = atoi(regbuf);

	// get timeout
	static char timeoutbuf[128];
	size = sizeof(timeoutbuf);
	timeoutbuf[0] = 0;
	ret = RegQueryValue(HKEY_CLASSES_ROOT,
							 TimeoutRegKeyValues[3][0],
							 timeoutbuf,
							 &size);
	if (ret != ERROR_SUCCESS)
	{
		// install 30 day evaluation time
		InstallTimeout(30);
		timeoutbuf[0] = 0;
		ret = RegQueryValue(HKEY_CLASSES_ROOT,
								TimeoutRegKeyValues[3][0],
								timeoutbuf,
								&size);
	}

	if (ret != ERROR_SUCCESS)
	{
		info->timeout = -1;
		info->daysRemaining = 0;
	}
	else
	if (timeoutbuf[0])
	{
		currTime = time(&ltime);
		info->timeout = atoi(timeoutbuf);
		info->daysRemaining =
			static_cast<int>(((time_t)(info->timeout) - currTime))
				/ (60 * 60 * 24);
	}
	info->version = CheckRegistration(info->name, info->organization, regbuf);
	info->isRegistered = (info->version >= 25);
}
Exemplo n.º 24
0
/* The search string can be either:
 * a) a file name
 * b) a CLSID, major, minor e.g. "{00000200-0000-0010-8000-00AA006D2EA4},2,0"
 * c) a Type Library name e.g. "Microsoft OLE DB ActiveX Data Objects 1.0 Library"
 */
PHP_COM_DOTNET_API ITypeLib *php_com_load_typelib(char *search_string, int codepage TSRMLS_DC)
{
	ITypeLib *TL = NULL;
	char *strtok_buf, *major, *minor;
	CLSID clsid;
	OLECHAR *p;
	HRESULT hr;

	search_string = php_strtok_r(search_string, ",", &strtok_buf);

	if (search_string == NULL) {
		return NULL;
	}

	major = php_strtok_r(NULL, ",", &strtok_buf);
	minor = php_strtok_r(NULL, ",", &strtok_buf);

	p = php_com_string_to_olestring(search_string, strlen(search_string), codepage TSRMLS_CC);

	if (SUCCEEDED(CLSIDFromString(p, &clsid))) {
		WORD major_i = 1, minor_i = 0;

		/* pick up the major/minor numbers; if none specified, default to 1,0 */
		if (major && minor) {
			major_i = (WORD)atoi(major);
			minor_i = (WORD)atoi(minor);
		}

		/* Load the TypeLib by GUID */
		hr = LoadRegTypeLib((REFGUID)&clsid, major_i, minor_i, LANG_NEUTRAL, &TL);

		/* if that failed, assumed that the GUID is actually a CLSID and
		 * attemp to get the library via an instance of that class */
		if (FAILED(hr) && (major == NULL || minor == NULL)) {
			IDispatch *disp = NULL;
			ITypeInfo *info = NULL;
			int idx;

			if (SUCCEEDED(hr = CoCreateInstance(&clsid, NULL, CLSCTX_SERVER, &IID_IDispatch, (LPVOID*)&disp)) &&
					SUCCEEDED(hr = IDispatch_GetTypeInfo(disp, 0, LANG_NEUTRAL, &info))) {
				hr = ITypeInfo_GetContainingTypeLib(info, &TL, &idx);
			}

			if (info) {
				ITypeInfo_Release(info);
			}
			if (disp) {
				IDispatch_Release(disp);
			}
		}
	} else {
		/* Try to load it from a file; if it fails, do a really painful search of
		 * the registry */
		if (FAILED(LoadTypeLib(p, &TL))) {
			HKEY hkey, hsubkey;
			DWORD SubKeys, MaxSubKeyLength;
			char *keyname;
			unsigned int i, j;
			DWORD VersionCount;
			char version[20];
			char *libname;
			DWORD libnamelen;

			if (ERROR_SUCCESS == RegOpenKeyEx(HKEY_CLASSES_ROOT, "TypeLib", 0, KEY_READ, &hkey) &&
					ERROR_SUCCESS == RegQueryInfoKey(hkey, NULL, NULL, NULL, &SubKeys,
					&MaxSubKeyLength, NULL, NULL, NULL, NULL, NULL, NULL)) {

				MaxSubKeyLength++; /* make room for NUL */
				keyname = emalloc(MaxSubKeyLength);
				libname = emalloc(strlen(search_string) + 1);

				for (i = 0; i < SubKeys && TL == NULL; i++) {
					if (ERROR_SUCCESS == RegEnumKey(hkey, i, keyname, MaxSubKeyLength) &&
							ERROR_SUCCESS == RegOpenKeyEx(hkey, keyname, 0, KEY_READ, &hsubkey)) {
						if (ERROR_SUCCESS == RegQueryInfoKey(hsubkey, NULL, NULL, NULL, &VersionCount,
								NULL, NULL, NULL, NULL, NULL, NULL, NULL)) {
							for (j = 0; j < VersionCount; j++) {
								if (ERROR_SUCCESS != RegEnumKey(hsubkey, j, version, sizeof(version))) {
									continue;
								}
								/* get the default value for this key and compare */
								libnamelen = strlen(search_string)+1;
								if (ERROR_SUCCESS == RegQueryValue(hsubkey, version, libname, &libnamelen)) {
									if (0 == stricmp(libname, search_string)) {
										char *str = NULL;
										int major_tmp, minor_tmp;

										/* fetch the GUID and add the version numbers */
										if (2 != sscanf(version, "%d.%d", &major_tmp, &minor_tmp)) {
											major_tmp = 1;
											minor_tmp = 0;
										}
										spprintf(&str, 0, "%s,%d,%d", keyname, major_tmp, minor_tmp);
										/* recurse */
										TL = php_com_load_typelib(str, codepage TSRMLS_CC);

										efree(str);
										break;
									}
								}
							}
						}
						RegCloseKey(hsubkey);
					}
				}
				RegCloseKey(hkey);
				efree(keyname);
				efree(libname);
			}
		}
	}
	
	efree(p);

	return TL;
}
Exemplo n.º 25
0
//
//	Close the current image and open the new image
//
void CommandLine()
{
	ULONG			target		= '0';
	PSTR			file_name	= NULL;
	VFD_DISKTYPE	disk_type	= VFD_DISKTYPE_FILE;
	VFD_MEDIA		media_type	= VFD_MEDIA_NONE;
	VFD_FLAGS		image_flags	= 0;
	VFD_FILETYPE	file_type;
	BOOL			five_inch	= FALSE;
	CHAR			protect		= 0;
	BOOL			open_folder	= TRUE;
	BOOL			close_only	= FALSE;
	HANDLE			hDevice;
	CHAR			letter;
	DWORD			driver_state;
	DWORD			ret;

	//
	//	process command line parameters
	//
	while (*(++__argv)) {

		//	Open switch
		if (_stricmp(*__argv, VFD_OPEN_SWITCH) == 0) {
			close_only = FALSE;
		}

		//	Close switch
		else if (_stricmp(*__argv, "/close") == 0) {
			close_only = TRUE;
		}

		//	Quiet mode switch
		else if (stricmp(*__argv, "/q") == 0) {
			open_folder = FALSE;
		}

		//	Disk type options
		else if (_stricmp(*__argv, "/ram") == 0) {
			disk_type = VFD_DISKTYPE_RAM;
		}

		//	Protect options
		else if (_stricmp(*__argv, "/p") == 0 ||
			_stricmp(*__argv, "/w") == 0) {

			protect = (CHAR)toupper(*(*__argv + 1));
		}

		//	media type options
		/*else if (strcmp(*__argv, "/160") == 0) {
			media_type = VFD_MEDIA_F5_160;
		}
		else if (strcmp(*__argv, "/180") == 0) {
			media_type = VFD_MEDIA_F5_180;
		}
		else if (strcmp(*__argv, "/320") == 0) {
			media_type = VFD_MEDIA_F5_320;
		}
		else if (strcmp(*__argv, "/360") == 0) {
			media_type = VFD_MEDIA_F5_360;
		}
		else if (strcmp(*__argv, "/640") == 0) {
			media_type = VFD_MEDIA_F3_640;
		}*/
		else if (strcmp(*__argv, "/720") == 0) {
			media_type = VFD_MEDIA_F3_720;
		}
		/*else if (strcmp(*__argv, "/820") == 0) {
			media_type = VFD_MEDIA_F3_820;
		}
		else if (strcmp(*__argv, "/120") == 0 ||
			strcmp(*__argv, "/1.20") == 0) {
			media_type = VFD_MEDIA_F3_1P2;
		}*/
		else if (strcmp(*__argv, "/144") == 0 ||
			strcmp(*__argv, "/1.44") == 0) {
			media_type = VFD_MEDIA_F3_1P4;
		}
		/*else if (strcmp(*__argv, "/168") == 0 ||
			strcmp(*__argv, "/1.68") == 0) {
			media_type = VFD_MEDIA_F3_1P6;
		}
		else if (strcmp(*__argv, "/172") == 0 ||
			strcmp(*__argv, "/1.72") == 0) {
			media_type = VFD_MEDIA_F3_1P7;
		}
		else if (strcmp(*__argv, "/288") == 0 ||
			strcmp(*__argv, "/2.88") == 0) {
			media_type = VFD_MEDIA_F3_2P8;
		}*/

		//	5.25 inch
		else if (strcmp(*__argv, "/5") == 0 ||
			strcmp(*__argv, "/525") == 0 ||
			strcmp(*__argv, "/5.25") == 0) {
			five_inch = TRUE;
		}

		//	target drive
		else if (isalnum(**__argv) &&
			*(*__argv + 1) == ':' &&
			*(*__argv + 2) == '\0') {

			target = toupper(**__argv);
		}
		else if (**__argv == '*' &&
			*(*__argv + 1) == ':' &&
			*(*__argv + 2) == '\0') {

			target = (ULONG)-1;
		}

		//	image filename
		else if (**__argv != '/') {
			file_name = *__argv;

			if (*file_name == '\"' && *(file_name + strlen(file_name) - 1) == '\"') {

				// remove quote characters if the path is quoted

				*(file_name + strlen(file_name) - 1) = '\0';
				file_name++;
			}
		}

		//	unknown options
		else {
			ShowErrorMessage(0, MSG_ERR_INVALID_PARAM, *__argv);
			return;
		}
	}

	//	check parameter consistency

	if (target == (ULONG)-1 && !close_only) {
		ShowErrorMessage(0, MSG_ERR_INVALID_PARAM, "*:");
		return;
	}

	//	Get the current driver state

	ret = VfdGetDriverState(&driver_state);

	if (ret != ERROR_SUCCESS) {
		ShowErrorMessage(ret, MSG_ERR_APP_INTERNAL);
		return;
	}

	if (close_only && driver_state != SERVICE_RUNNING) {
		//	nothing to do...
		return;
	}

	//	ensure that the driver is running

	if (driver_state == VFD_NOT_INSTALLED) {
		ret = VfdInstallDriver(NULL, SERVICE_DEMAND_START);

		if (ret != ERROR_SUCCESS) {
			ShowErrorMessage(ret, MSG_ERR_DRIVER_INSTALL);
			return;
		}
	}

	//	ensure that the driver is started

	if (driver_state != SERVICE_RUNNING) {
		ret = VfdStartDriver(&driver_state);

		if (ret != ERROR_SUCCESS ||
			driver_state != SERVICE_RUNNING) {
			ShowErrorMessage(ret, MSG_ERR_DRIVER_START);
			return;
		}
	}

	//
	//	close the current image (if any)
	//
	if (target == (ULONG)-1) {
		int i;
		for (i = 0; i < VFD_MAXIMUM_DEVICES; i++) {
			ret = VfdGuiClose(NULL, i);

			if (ret != ERROR_SUCCESS && ret != ERROR_NOT_READY) {
				ShowErrorMessage(ret, MSG_ERR_IMAGE_CLOSE, i + '0');
			}
		}
		return;
	}

	ret = VfdGuiClose(NULL, target);

	if (ret != ERROR_SUCCESS && ret != ERROR_NOT_READY) {
		ShowErrorMessage(ret, MSG_ERR_IMAGE_CLOSE, target);
		return;
	}

	if (close_only) {
		return;
	}

	//
	//	check target image file
	//
	if (file_name) {
		DWORD			file_attr;
		ULONG			image_size;

		ret = VfdCheckImageFile(
			file_name, &file_attr, &file_type, &image_size);

		if (ret == ERROR_FILE_NOT_FOUND) {

			//	If file does not exist, create a new image file

			if (media_type == VFD_MEDIA_NONE) {
				media_type = VFD_MEDIA_F3_1P4;
			}

			ret = VfdCreateImageFile(
				file_name, media_type, VFD_FILETYPE_RAW, FALSE);

			if (ret != ERROR_SUCCESS) {
				ShowErrorMessage(ret, MSG_ERR_FILE_CREATE, file_name);
				return;
			}

			ret = VfdCheckImageFile(
				file_name, &file_attr, &file_type, &image_size);

			if (ret != ERROR_SUCCESS) {
				ShowErrorMessage(ret, MSG_ERR_FILE_OPEN, file_name);
				return;
			}
		}
		else if (ret == ERROR_SUCCESS) {

			//	check file size / media size

			ULONG		media_size;
			VFD_MEDIA	def_media;

			media_size = VfdGetMediaSize(media_type);

			if (media_size > image_size) {

				ShowErrorMessage(0, MSG_ERR_IMAGE_TOO_SMALL);
				return;
			}

			def_media = VfdLookupMedia(image_size);

			if (def_media == VFD_MEDIA_NONE) {

				ShowErrorMessage(0, MSG_ERR_IMAGE_TOO_SMALL);
				return;
			}

			if (media_type == VFD_MEDIA_NONE) {
				media_type = def_media;
			}

			//	check file type

			if (file_type == VFD_FILETYPE_ZIP ||
				(file_attr & (FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_COMPRESSED | FILE_ATTRIBUTE_ENCRYPTED))) {
				disk_type = VFD_DISKTYPE_RAM;
			}
		}
		else {
			ShowErrorMessage(ret, MSG_ERR_FILE_OPEN, file_name);
			return;
		}

		if (disk_type != VFD_DISKTYPE_FILE) {
			if (protect != 'W') {
				protect = 'P';
			}
		}
	}
	else {
		disk_type = VFD_DISKTYPE_RAM;

		if (media_type == VFD_MEDIA_NONE) {
			media_type = VFD_MEDIA_F3_1P4;
		}
	}

	if (protect == 'P') {
		image_flags |= VFD_FLAG_WRITE_PROTECTED;
	}

	if (five_inch &&
		VfdGetMediaSize(media_type) == VfdGetMediaSize((VFD_MEDIA)(media_type + 1))) {
		media_type = (VFD_MEDIA)(media_type + 1);
	}

	//	Open the target device

	hDevice = VfdOpenDevice(target);

	if (hDevice == INVALID_HANDLE_VALUE) {
		ShowErrorMessage(GetLastError(), MSG_ERR_DEVICE_OPEN, target);
		return;
	}

	//	assign a drive letter if the drive has none

	VfdGetGlobalLink(hDevice, &letter);

	if (!isalpha(letter)) {
		VfdGetLocalLink(hDevice, &letter);
	}

	if (!isalpha(letter)) {
		letter = VfdChooseLetter();
		VfdSetLocalLink(hDevice, letter);
	}

	//	Open the image file

	ret = VfdOpenImage(hDevice, file_name,
		disk_type, media_type, image_flags);

	CloseHandle(hDevice);

	if (ret != ERROR_SUCCESS) {
		ShowErrorMessage(ret, MSG_ERR_FILE_OPEN,
			file_name ? file_name : "<RAM>");
		return;
	}

	//
	//	Unless otherwise specified, open the drive
	//
	if (open_folder && isalpha(letter)) {
		CHAR drive[] = "A:\\";
		CHAR verb[20] = {0};
		LONG size = sizeof(verb);

		drive[0] = (CHAR)toupper(letter);

		//	get the default verb for folder object from the registry
		RegQueryValue(HKEY_CLASSES_ROOT, "Folder\\shell", verb, &size);

		ret = (DWORD)ShellExecute(
			NULL, verb[0] ? verb : NULL, drive, NULL, NULL, SW_SHOWNORMAL);

		if (ret <= 32) {
			VFDTRACE(0, ("OpenImage : ShellExecute - %s",
				GetSystemMessage(GetLastError())));
		}
	}

	return;
}
Exemplo n.º 26
0
void WINAPI TimeServiceMain(DWORD dwArgc, LPTSTR *lpszArgv) 
{
#ifdef _WIN64
   unsigned __int64 dwCompKey  = CK_SERVICECONTROL;
#else
   DWORD dwCompKey  = CK_SERVICECONTROL;
#endif
   DWORD fdwControl = SERVICE_CONTROL_RUN;
   DWORD dwBytesTransferred;
   OVERLAPPED *po;
   SERVICE_STATUS ss;
   SERVICE_STATUS_HANDLE hSS;
   BOOL bPasswordCompileEmbedded = 0;

// We must get the private password for connecting to this machine.
// The password can be compiled into the server any of the following ways......


//  1 way - the easiest way, just uncomment and put any value between the quotes
//  then remove the code between --Load External Password Begin & End-- below
//  ***** example of very simple integrated password ********
//  GString strPassword("Password");
//	GString strPort("80");
//	GString strRoot;
//	bPasswordCompileEmbedded = 1;


//  Another way - a most secure way to embed the password.
//  ***** example of integrated password ********
//  GString strPassword;
//	MakePassword(strPassword);    // Go read the MakePassword() routine above.
//	GString strPort("80");
//	GString strRoot;
//	bPasswordCompileEmbedded = 1;


//              OR

// The password can be retrieved from an external disk location.
// Passwords can be obtained from disk in two different ways.
// Either in a registry key matching the (probably renamed) 
// executable file that is this server, OR by loading a 
// predefined file name at a predefined location. 
// This file must be present while starting the server, but can be
// removed once this process has fully started.


//  --Load External Password Begin--
GString strPassword;
GString strPort;
GString strRoot;

if (!bPasswordCompileEmbedded)
{
	GString strThisEXEName(GetThisEXEName());
	GString strStartupKey;

	// use our runtime image name as the registry key
	char buf[512];
	long lSize = sizeof(buf);
	if (RegQueryValue(HKEY_CLASSES_ROOT,(const char *)strThisEXEName,buf,&lSize) == ERROR_SUCCESS)
	{
		// uudecode the startup key
		BUFFER b;
		BufferInit(&b);
		unsigned int nDecoded;
		uudecode(buf, &b, &nDecoded, false);
		strStartupKey.write((const char *)b.pBuf,nDecoded);
		BufferTerminate(&b);
	}

	GString strStartupData;
	if (strStartupKey.Length())
	{
		// look for a file in the root of the file system (c:\)
		// with the same name as this .exe
		GString strFile("c:\\");
		strFile += strThisEXEName;


		// load the crypted disk file into clear text memory
		char *pDest;
		int nDestLen;
		GString strErrorOut;
		if (FileDecryptToMemory(strStartupKey, strFile, &pDest, &nDestLen, strErrorOut))
		{
			// parse into the profile data structures
			pDest[7 + nDestLen] = 0; // null terminate it
			strStartupData.write(&pDest[7], nDestLen + 1); // and cap the GString 
		}
		else
		{
			// if the file was not in the root of the file system
			// see if there is an environment setting directing
			// this server to look for the file in another location
			// The variable name is dynamic, matching this .exe name
			// and the environment variable value must be a fully
			// qualified path and file name to the startup file.
			if (getenv(strThisEXEName))
			{
				if (FileDecryptToMemory(strStartupKey, getenv(strThisEXEName), &pDest, &nDestLen, strErrorOut))
				{
					// parse into the profile data structures
					strStartupData.write(&pDest[7], nDestLen-7);
				}
			}
		}

		// parse stored settings in startup file to startup variables
		if (strStartupData.Length())
		{
			GStringList lstOptions("&&",strStartupData);
			GStringIterator it(&lstOptions);

			if (it()) strPassword = it++;
			if (it()) strRoot = it++; // currently not used
			if (it()) strPort = it++;
		}
	}
}

//  --Load External Password End--

	GString strFile;
	GString strConfigFileDefault;
	GString strErrorOut;
	int bSetStartupFile = 0;

#ifdef _WIN32
	SetPriorityClass(GetCurrentProcess(),HIGH_PRIORITY_CLASS); // = 1 point above normal
#endif


   // Create the completion port and save its handle in a global
   // variable so that the Handler function can access it.
   g_hIOCP = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, CK_PIPE, 0);

   // Give SCM the address of this service's Handler
   // NOTE: hSS does not have to be closed.
   hSS = RegisterServiceCtrlHandler((const char *)strServerName, TimeServiceHandler);

   // Do what the service should do.
   // Initialize the members that never change
   ss.dwServiceType = SERVICE_WIN32_OWN_PROCESS; 
   ss.dwControlsAccepted = SERVICE_ACCEPT_STOP | 
      SERVICE_ACCEPT_PAUSE_CONTINUE | SERVICE_ACCEPT_SHUTDOWN;

   do {
      switch (dwCompKey) {
      case CK_SERVICECONTROL:
         // We got a new control code
         ss.dwWin32ExitCode = NO_ERROR; 
         ss.dwServiceSpecificExitCode = 0; 
         ss.dwCheckPoint = 0; 
         ss.dwWaitHint = 0;

         if (fdwControl == SERVICE_CONTROL_INTERROGATE) {
            SetServiceStatus(hSS, &ss);
            break;
         }

         // Determine which PENDING state to return
         if (dwSrvCtrlToPend[fdwControl] != 0) {
            ss.dwCurrentState = dwSrvCtrlToPend[fdwControl]; 
            ss.dwCheckPoint = 0;
            ss.dwWaitHint = 500;   // half a second
            SetServiceStatus(hSS, &ss);
         }

         switch (fdwControl) {
            case SERVICE_CONTROL_RUN:
            case SERVICE_CONTROL_CONTINUE:
				try
				{
					if (strRoot.Length() && strPort.Length())
					{
						GString strCfgData;
						strCfgData.Format(pzBoundStartupConfig,(const char *)strRoot,(const char *)strPort);
						SetProfile(new GProfile((const char *)strCfgData, (int)strCfgData.Length(), 0));

						if (!server_start())
						{
							ss.dwCurrentState = SERVICE_STOPPED; 
							ss.dwCheckPoint = ss.dwWaitHint = 0;
							SetServiceStatus(hSS, &ss);
							break;
						}
					}
					else
					{
						// No password compiled in - and no valid startup file found
						for(int i=0; i<3;i++)
						{
							// three beeps
							MessageBeep(0);
							Sleep(1000);
						}
						ss.dwCurrentState = SERVICE_STOPPED; 
						ss.dwCheckPoint = ss.dwWaitHint = 0;
						SetServiceStatus(hSS, &ss);
						break;
					}
				}
				catch ( GException &)
				{
					ss.dwCurrentState = SERVICE_STOPPED; 
					ss.dwCheckPoint = ss.dwWaitHint = 0;
					SetServiceStatus(hSS, &ss);
					break;
				}



				if (dwSrvPendToState[ss.dwCurrentState] != 0) 
				{
					ss.dwCurrentState = dwSrvPendToState[ss.dwCurrentState]; 
					ss.dwCheckPoint = ss.dwWaitHint = 0;
					SetServiceStatus(hSS, &ss);
				}
				break;

            case SERVICE_CONTROL_PAUSE:
            case SERVICE_CONTROL_STOP:
            case SERVICE_CONTROL_SHUTDOWN:
                server_stop();
				if (dwSrvPendToState[ss.dwCurrentState] != 0) 
				{
					ss.dwCurrentState = dwSrvPendToState[ss.dwCurrentState]; 
					ss.dwCheckPoint = ss.dwWaitHint = 0;
					SetServiceStatus(hSS, &ss);
				}
				break;
         }

         // Determine which complete state to return
         break;

      }

      if (ss.dwCurrentState != SERVICE_STOPPED) {
         // Sleep until a control code comes in or a client connects
         GetQueuedCompletionStatus(g_hIOCP, &dwBytesTransferred,
            &dwCompKey, &po, INFINITE);
         fdwControl = dwBytesTransferred;
      }
   } while (ss.dwCurrentState != SERVICE_STOPPED);

   // Cleanup and stop this service
   CloseHandle(g_hIOCP);   
}
Exemplo n.º 27
0
VOID 
REINITIALIZE_ADAPTER( 
	PVOID 
	)

/*++

Routine Description

	This routine re-initializes display driver
	 to obtains its DrvCoptBits pointer.
	This routine executed as a separate thread in the context of CSRSS.EXE

Arguments

	PVOID

		Thread context, always NULL

Return Value

	None, thread terminates by call PsTerminateSystemThread

Environment

	Separate thread of CSRSS process

--*/

{
	//
	// This routine runs in the context of csrss.exe
	//
	
	KdPrint(("REINITIALIZE_ADAPTER enter\n"));

	HANDLE hDrv = EngLoadImage (L"vid_copy.dll");
	KdPrint(("vid_copy is %X\n", hDrv));
	if (hDrv)
	{
		BOOLEAN (NTAPI *pOriginalDrvEnableDriver)(
			ULONG iEngineVersion,
			ULONG cj,
			PDRVENABLEDATA pded
			);

		*(PVOID*)&pOriginalDrvEnableDriver = EngFindImageProcAddress (hDrv, "DrvEnableDriver");

		KdPrint(("pOriginalDrvEnableDriver = %X\n", pOriginalDrvEnableDriver));

		if (pOriginalDrvEnableDriver)
		{
			BOOLEAN Ret;
			DRVENABLEDATA DrvEnableData = {0};
		
			Ret = pOriginalDrvEnableDriver (DDI_DRIVER_VERSION_NT5_01_SP1,
				sizeof(DrvEnableData),
				&DrvEnableData);

			KdPrint(("pOriginalDrvEnableDriver returned %X\n", Ret));

			if (Ret)
			{
				for (ULONG i = 0; i<DrvEnableData.c; i++)
				{
					if (DrvEnableData.pdrvfn[i].iFunc == INDEX_DrvCopyBits)
					{
						KdPrint(("Found DrvCopyBits: %X\n", DrvEnableData.pdrvfn[i].pfn));

						HANDLE hKey;
						wchar_t value[512];

						hKey = RegOpenKey (L"\\Registry\\Machine\\Software\\NGdbg", KEY_QUERY_VALUE);
						if (hKey)
						{
							ULONG Len = sizeof(value);

							if (RegQueryValue (hKey, L"DisplayDriver", REG_SZ, value, &Len))
							{
								KdPrint(("Display driver: %S\n", value));

								wcscat (value, L".dll");

								PVOID OrigBase = FindImage (value);
								PVOID VidBase = FindImage (L"vid_copy.dll");

								if (OrigBase && VidBase)
								{
									ULONG Offset = (ULONG)DrvEnableData.pdrvfn[i].pfn - (ULONG)VidBase;

									KdPrint(("Offset %X\n", Offset));

									pDrvCopyBits = (PUCHAR)OrigBase + Offset;

									KdPrint(("DrvCopyBits %X\n", pDrvCopyBits));
								}
								else
								{
									KdPrint(("FindImage failed: OrigBase %X, VidBase %X\n", OrigBase, VidBase));
								}
							}
							else
							{
								KdPrint(("RegQueryValue failed\n"));
							}

							ZwClose (hKey);
						}
						else
						{
							KdPrint(("RegOpenKey failed\n"));
						}
					}
				}
			}
		}

		EngUnloadImage (hDrv);
	}

	KdPrint(("REINITIALIZE_ADAPTER exit\n"));

	PsTerminateSystemThread (0);
}
Exemplo n.º 28
0
/** Finds the executable and parameter list associated with the
    provided extension. */
BOOL 
GetExecutableAndArgumentTemplateByExtention (
	LPCSTR extension, 
	LPSTR  executable,
	LPSTR  arguments ) {

	DWORD			last_error			= ERROR_SUCCESS;
	LONG			result,
					length;
    CHAR			value[MAX_PATH+1],
					key[MAX_PATH+1],
                    name[MAX_PATH+1],
                    uppercase[MAX_PATH+1],
                    default_verb[]      = "Open";
    LPSTR           verb                = NULL;
	HANDLE			found				= INVALID_HANDLE_VALUE;
	WIN32_FIND_DATA find_data;
	LPSTR			tmp, 
					start				= NULL;					
	BOOL			quoted				= FALSE,
					expanded			= FALSE,
					ok					= FALSE;

	__try {

        /* make sure the output buffers not contain any misleading 
        information, if we are to fail */
        executable[0] = '\0';
        if ( arguments ) {
            arguments[0] = '\0';
        }

		/* using the extension, find the script type (or program ID) */
		length = MAX_PATH;
		result = RegQueryValue (
			HKEY_CLASSES_ROOT,
			extension,
			(LPSTR) value, 
			&length );

		if ( ERROR_SUCCESS != result ) {

			last_error = result;

			dprintf (
                D_ALWAYS,
				"GetExecutableAndArgumentsByExtention: failed to find "
				"extension *%s in the registry (last-error = %d).\n",
				extension, 
				last_error );

			__leave;

		}

        /* Because some file types have /n/ verb handlers, there is
        no intelligent way we can choose which one to use.  The verb
        'Open' is the most common, but we allow the user define one
		if they want. */
        strcpy (
            uppercase, 
            extension + 1 );

        sprintf ( 
            name, 
            "OPEN_VERB_FOR_%s_FILES", 
            strupr ( uppercase ) );

        verb = param ( name );

        sprintf ( 
            key, 
            "%s\\Shell\\%s\\Command", 
            value, 
            verb ? verb : default_verb );

        if ( verb ) {
            free ( verb );
        }

        length = MAX_PATH;
	    result = RegQueryValue (
		    HKEY_CLASSES_ROOT,
		    key,
		    (LPSTR) value, 
		    &length );

        if ( ERROR_SUCCESS != result ) {

			last_error = result;

			dprintf (
                D_ALWAYS,
				"GetExecutableAndArgumentsByExtention: failed to "
				"find a suitable handler for files with extension "
				"'*%s'. (last-error = %d)\n",
				extension, 
				last_error );

			__leave;

		}

        /* we now have the command-line.  First, let's trim all the
		leading whitespace. */
		tmp = (LPSTR) value;

		/* strip leading spaces */
        while ( *tmp && isspace ( *tmp ) ) {
            tmp++;
        }

        /* we are now at the start of the executable's path */
		start = tmp;

        /* if the executable is surrounded by quotes, then we want to 
		ignore all whitespace until we see another quote--after that
		we will stop. */
		quoted = ( '"' == *start );

		/* step through the executable's path until we reach either
		the closing quote, a whitespace character or NULL. */
		if ( quoted ) {
			
			/* skip first quote because FindFirstFile() does not
			work if there are quotes surrounding a script name. */
			start = ++tmp;
			while ( *tmp && ( '"' != *tmp ) ) {
				tmp++;
			}			

        } else {

			start = tmp;
            while ( *tmp && !isspace ( *tmp ) ) {
                tmp++;
            }

        }

		/* null terminate at the closing quote, the first 
		whitespace character or at the end of the buffer. */
		*tmp = '\0';

        /* validate the executable's existence */
		found = FindFirstFile ( 
			start,
			&find_data );

		if ( INVALID_HANDLE_VALUE == found ) {

			last_error = GetLastError ();

			dprintf (
                D_ALWAYS,
				"GetExecutableAndArgumentsByExtention: failed to "
                "locate the executable, %s, to handle files "
                "with extension '*%s'. (last-error = %d)\n",
				start, 
				extension, 
				last_error );

			__leave;

		}

		/* clean-up after the script search */
		FindClose ( found );
		
		/* finally, copy the executable path */
		strcpy ( executable, start );

		/* if we have not already consumed the entire buffer, then
		copy the rest as the arguments to the executable */
		start = ++tmp;
		if ( arguments && value - start < length - 1 ) {
			
			/* strip leading space until we are at the start of the
			executable's arguments */
            while ( *start && isspace ( *start ) ) {
                start++;
            }

			/* make a copy of the arguments */
            strcpy ( arguments, start );

		}
		
		/* if we made it here, then we're all going to be ok */
		ok = TRUE;

	}
	__finally {

		/* propagate the last error to our caller */
		SetLastError ( ok ? ERROR_SUCCESS : last_error );

	};
	
	return ok;

}
Exemplo n.º 29
0
NTSTATUS
NTAPI
InitVideo()
{
    ULONG iDevNum, iVGACompatible = -1, ulMaxObjectNumber = 0;
    WCHAR awcDeviceName[20];
    WCHAR awcBuffer[256];
    NTSTATUS Status;
    PGRAPHICS_DEVICE pGraphicsDevice;
    ULONG cbValue;
    HKEY hkey;

    TRACE("----------------------------- InitVideo() -------------------------------\n");

    /* Open the key for the boot command line */
    Status = RegOpenKey(L"\\REGISTRY\\MACHINE\\SYSTEM\\CurrentControlSet\\Control", &hkey);
    if (NT_SUCCESS(Status))
    {
        cbValue = 256;
        Status = RegQueryValue(hkey, L"SystemStartOptions", REG_SZ, awcBuffer, &cbValue);
        if (NT_SUCCESS(Status))
        {
            /* Check if VGA mode is requested. */
            if (wcsstr(awcBuffer, L"BASEVIDEO") != 0)
            {
                ERR("VGA mode requested.\n");
                gbBaseVideo = TRUE;
            }
        }

        ZwClose(hkey);
    }

    /* Open the key for the adapters */
    Status = RegOpenKey(KEY_VIDEO, &hkey);
    if (!NT_SUCCESS(Status))
    {
        ERR("Could not open HARDWARE\\DEVICEMAP\\VIDEO registry key:0x%lx\n", Status);
        return Status;
    }

    /* Read the name of the VGA adapter */
    cbValue = 20;
    Status = RegQueryValue(hkey, L"VgaCompatible", REG_SZ, awcDeviceName, &cbValue);
    if (NT_SUCCESS(Status))
    {
        iVGACompatible = _wtoi(&awcDeviceName[13]);
        ERR("VGA adapter = %ld\n", iVGACompatible);
    }

    /* Get the maximum mumber of adapters */
    if (!RegReadDWORD(hkey, L"MaxObjectNumber", &ulMaxObjectNumber))
    {
        ERR("Could not read MaxObjectNumber, defaulting to 0.\n");
    }

    TRACE("Found %ld devices\n", ulMaxObjectNumber + 1);

    /* Loop through all adapters */
    for (iDevNum = 0; iDevNum <= ulMaxObjectNumber; iDevNum++)
    {
        /* Create the adapter's key name */
        swprintf(awcDeviceName, L"\\Device\\Video%lu", iDevNum);

        /* Read the reg key name */
        cbValue = sizeof(awcBuffer);
        Status = RegQueryValue(hkey, awcDeviceName, REG_SZ, awcBuffer, &cbValue);
        if (!NT_SUCCESS(Status))
        {
            ERR("failed to query the registry path:0x%lx\n", Status);
            continue;
        }

        /* Initialize the driver for this device */
        pGraphicsDevice = InitDisplayDriver(awcDeviceName, awcBuffer);
        if (!pGraphicsDevice) continue;

        /* Check if this is a VGA compatible adapter */
        if (pGraphicsDevice->StateFlags & DISPLAY_DEVICE_VGA_COMPATIBLE)
        {
            /* Save this as the VGA adapter */
            if (!gpVgaGraphicsDevice)
                gpVgaGraphicsDevice = pGraphicsDevice;
            TRACE("gpVgaGraphicsDevice = %p\n", gpVgaGraphicsDevice);
        }
        else
        {
            /* Set the first one as primary device */
            if (!gpPrimaryGraphicsDevice)
                gpPrimaryGraphicsDevice = pGraphicsDevice;
            TRACE("gpPrimaryGraphicsDevice = %p\n", gpPrimaryGraphicsDevice);
        }
    }

    /* Close the device map registry key */
    ZwClose(hkey);

    /* Was VGA mode requested? */
    if (gbBaseVideo)
    {
        /* Check if we found a VGA compatible device */
        if (gpVgaGraphicsDevice)
        {
            /* Set the VgaAdapter as primary */
            gpPrimaryGraphicsDevice = gpVgaGraphicsDevice;
            // FIXME: DEVMODE
        }
        else
        {
            ERR("Could not find VGA compatible driver. Trying normal.\n");
        }
    }

    /* Check if we had any success */
    if (!gpPrimaryGraphicsDevice)
    {
        /* Check if there is a VGA device we skipped */
        if (gpVgaGraphicsDevice)
        {
            /* There is, use the VGA device */
            gpPrimaryGraphicsDevice = gpVgaGraphicsDevice;
        }
        else
        {
            ERR("No usable display driver was found.\n");
            return STATUS_UNSUCCESSFUL;
        }
    }

    InitSysParams();

    return 1;
}
Exemplo n.º 30
0
PGRAPHICS_DEVICE
NTAPI
InitDisplayDriver(
    IN PWSTR pwszDeviceName,
    IN PWSTR pwszRegKey)
{
    PGRAPHICS_DEVICE pGraphicsDevice;
    UNICODE_STRING ustrDeviceName, ustrDisplayDrivers, ustrDescription;
    NTSTATUS Status;
    WCHAR awcBuffer[128];
    ULONG cbSize;
    HKEY hkey;
    DEVMODEW dmDefault;
    DWORD dwVga;

    ERR("InitDisplayDriver(%S, %S);\n",
            pwszDeviceName, pwszRegKey);

    /* Open the driver's registry key */
    Status = RegOpenKey(pwszRegKey, &hkey);
    if (!NT_SUCCESS(Status))
    {
        ERR("Failed to open registry key: %ls\n", pwszRegKey);
        return NULL;
    }

    /* Query the diplay drivers */
    cbSize = sizeof(awcBuffer) - 10;
    Status = RegQueryValue(hkey,
                           L"InstalledDisplayDrivers",
                           REG_MULTI_SZ,
                           awcBuffer,
                           &cbSize);
    if (!NT_SUCCESS(Status))
    {
        ERR("Didn't find 'InstalledDisplayDrivers', status = 0x%lx\n", Status);
        ZwClose(hkey);
        return NULL;
    }

    /* Initialize the UNICODE_STRING */
    ustrDisplayDrivers.Buffer = awcBuffer;
    ustrDisplayDrivers.MaximumLength = (USHORT)cbSize;
    ustrDisplayDrivers.Length = (USHORT)cbSize;

    /* Set Buffer for description and size of remaining buffer */
    ustrDescription.Buffer = awcBuffer + (cbSize / sizeof(WCHAR));
    cbSize = sizeof(awcBuffer) - cbSize;

    /* Query the device string */
    Status = RegQueryValue(hkey,
                           L"Device Description",
                           REG_SZ,
                           ustrDescription.Buffer,
                           &cbSize);
    if (NT_SUCCESS(Status))
    {
        ustrDescription.MaximumLength = (USHORT)cbSize;
        ustrDescription.Length = (USHORT)cbSize;
    }
    else
    {
        RtlInitUnicodeString(&ustrDescription, L"<unknown>");
    }

    /* Query the default settings */
    RegReadDisplaySettings(hkey, &dmDefault);

    /* Query if this is a VGA compatible driver */
    cbSize = sizeof(DWORD);
    Status = RegQueryValue(hkey, L"VgaCompatible", REG_DWORD, &dwVga, &cbSize);
    if (!NT_SUCCESS(Status)) dwVga = 0;

    /* Close the registry key */
    ZwClose(hkey);

    /* Register the device with GDI */
    RtlInitUnicodeString(&ustrDeviceName, pwszDeviceName);
    pGraphicsDevice = EngpRegisterGraphicsDevice(&ustrDeviceName,
                                                 &ustrDisplayDrivers,
                                                 &ustrDescription,
                                                 &dmDefault);
    if (pGraphicsDevice && dwVga)
    {
        pGraphicsDevice->StateFlags |= DISPLAY_DEVICE_VGA_COMPATIBLE;
    }

    return pGraphicsDevice;
}