Exemplo n.º 1
0
BOOL kull_m_string_args_byName(const int argc, const wchar_t * argv[], const wchar_t * name, const wchar_t ** theArgs, const wchar_t * defaultValue)
{
	BOOL result = FALSE;
	const wchar_t *pArgName, *pSeparator;
	SIZE_T argLen, nameLen = wcslen(name);
	int i;
	for(i = 0; i < argc; i++)
	{
		if((wcslen(argv[i]) > 1) && ((argv[i][0] == L'/') || (argv[i][0] == L'-')))
		{
			pArgName = argv[i] + 1;
			if(!(pSeparator = wcschr(argv[i], L':')))
				pSeparator = wcschr(argv[i], L'=');

			argLen =  (pSeparator) ? (pSeparator - pArgName) : wcslen(pArgName);
			if((argLen == nameLen) && _wcsnicmp(name, pArgName, argLen) == 0)
			{
				if(theArgs)
				{
					if(pSeparator)
					{
						*theArgs = pSeparator + 1;
						result = *theArgs[0] != L'\0';
					}
				}
				else
					result = TRUE;
				break;
			}
		}
	}

	if(!result && theArgs && defaultValue)
	{
		*theArgs = defaultValue;
		result = TRUE;
	}

	return result;
}
Exemplo n.º 2
0
//
// lpRedirectedKey is allocated and returned from this method.  Caller owns the new string and
// should release
//
HRESULT RedirectKey(REGSAM samDesired, HKEY hKey, LPCWSTR lpKey, __deref_out_z LPWSTR * lpRedirectedKey)
{
    if (hKey != kRegistryRootHive || _wcsnicmp(lpKey, kRegistryRootKey, wcslen(kRegistryRootKey)) != 0)
    {
        return ERROR_SUCCESS;
    }
    
    LPCWSTR lpRootStrippedKey = lpKey + wcslen(kRegistryRootKey);
    size_t redirectedLength = wcslen(g_registryRoot) + wcslen(lpRootStrippedKey) + 1;
    
    bool bUseWow = false;
    HRESULT hr = CheckUseWow6432Node(samDesired, &bUseWow);
    
    if (hr != ERROR_SUCCESS)
    {
        return hr;
    }
    
    if (bUseWow)
    {
        redirectedLength += wcslen(kWow6432Node);
    }
    
    *lpRedirectedKey = new (nothrow) WCHAR[redirectedLength];
    
    if (*lpRedirectedKey == NULL)
    {
        return ERROR_NOT_ENOUGH_MEMORY;
    }
    
    wcscpy_s(*lpRedirectedKey, redirectedLength, g_registryRoot);
    if (bUseWow)
    {
        StringCchCat(*lpRedirectedKey, redirectedLength, kWow6432Node);
    }
    
    StringCchCat(*lpRedirectedKey, redirectedLength, lpRootStrippedKey);
    
    return ERROR_SUCCESS;
}
Exemplo n.º 3
0
int mywcscmp(PWSTR a, int alen, PWSTR b, int blen)
{
    int len, res;

    if (-1 == alen)
        alen = (int)wcslen(a);
    if (-1 == blen)
        blen = (int)wcslen(b);

    len = alen < blen ? alen : blen;

    /* we should still be in the C locale */
    if (OptCaseInsensitiveCmp)
        res = _wcsnicmp(a, b, len);
    else
        res = wcsncmp(a, b, len);

    if (0 == res)
        res = alen - blen;

    return res;
}
Exemplo n.º 4
0
ACCESS_MASK isRestricted(RESTRICT_PARAM *list, PWCHAR key, int levs) {
  RESTRICT_PARAM *p = list;
  int cmp,i;
  WCHAR *s;
  if (!p || !key) return 0;

  while (p->obj != NULL) {
    cmp = _wcsnicmp(p->obj, key, p->len);
    if (cmp==0) {
      if (key[p->len] == L'\0') return p->mask;
      i=levs;
      s = key + p->len;
      while (i>0) {
	s = wcschr(s + 1, L'\\');
	if (s == NULL) return p->mask;
	--i;
      }
    }
    ++p;
  }
  return 0;
}
Exemplo n.º 5
0
bool CBrowseRefsDlg::SelectRef(CString refName, bool bExactMatch)
{
	if(!bExactMatch)
	{
		CString newRefName = GetFullRefName(refName);
		if(!newRefName.IsEmpty())
			refName = newRefName;
		//else refName is not a valid ref. Try to select as good as possible.
	}
	if(_wcsnicmp(refName, L"refs/", 5) != 0)
		return false; // Not a ref name

	CShadowTree& treeLeafHead=GetTreeNode(refName,NULL,false);
	if(treeLeafHead.m_hTree != NULL)
	{
		//Not a leaf. Select tree node and return
		m_RefTreeCtrl.Select(treeLeafHead.m_hTree,TVGN_CARET);
		return true;
	}

	if(treeLeafHead.m_pParent==NULL)
		return false; //Weird... should not occur.

	//This is the current head.
	m_RefTreeCtrl.Select(treeLeafHead.m_pParent->m_hTree,TVGN_CARET);

	for(int indexPos = 0; indexPos < m_ListRefLeafs.GetItemCount(); ++indexPos)
	{
		CShadowTree* pCurrShadowTree = (CShadowTree*)m_ListRefLeafs.GetItemData(indexPos);
		if(pCurrShadowTree == &treeLeafHead)
		{
			m_ListRefLeafs.SetItemState(indexPos,LVIS_SELECTED,LVIS_SELECTED);
			m_ListRefLeafs.EnsureVisible(indexPos,FALSE);
		}
	}

	return true;
}
Exemplo n.º 6
0
/**
 * DllInstall - Adds/Removes entries to the system registry per user per machine.
 */
STDAPI DllInstall(BOOL bInstall, LPCWSTR pszCmdLine)
{
    logger->debug(L"BHO::dllexports::DllInstall");
    HRESULT hr = E_FAIL;
    static const wchar_t szUserSwitch[] = L"user";

    if (pszCmdLine != NULL) {
        if (_wcsnicmp(pszCmdLine, szUserSwitch, _countof(szUserSwitch)) == 0) {
            ATL::AtlSetPerUserRegistration(true);
        }
    }

    if (bInstall) {	
        hr = DllRegisterServer();
        if (FAILED(hr)) {
            DllUnregisterServer();
        }
    } else {
        hr = DllUnregisterServer();
    }

    return hr;
}
Exemplo n.º 7
0
static
PINICACHEKEY
IniCacheFindKey(
     PINICACHESECTION Section,
     PWCHAR Name,
     ULONG NameLength)
{
    PINICACHEKEY Key;

    Key = Section->FirstKey;
    while (Key != NULL)
    {
        if (NameLength == wcslen(Key->Name))
        {
            if (_wcsnicmp(Key->Name, Name, NameLength) == 0)
                break;
        }

        Key = Key->Next;
    }

    return Key;
}
bool FirefoxAction::_getProfileLocationFromProfilesIni(wstring file, wstring &profileLocation)
{
	wifstream reader;
	wstring line;
	const int pathLen = wcslen(PATHKEY);

	reader.open(file.c_str());

	if (!reader.is_open())	
		return false;

	while(!(getline(reader, line)).eof())
	{
		if (_wcsnicmp(line.c_str(), PATHKEY, pathLen) != 0)
			continue;

		_getProfileRootDir(profileLocation);
		profileLocation += (wchar_t *)&line[pathLen];
		return true;
	}

	return false;
}
Exemplo n.º 9
0
UINT ProcessMonitor::GetPid(const WCHAR *pProcName) {
	list<ProcessEntry>::iterator iter;

	if (RefreshProcessList() == FALSE)
		return FALSE;

	WAIT_AND_SIGNAL(hProcessMutex);

	if (pList.size() == 0 || pProcName == NULL || wcslen(pProcName) == 0) {
		UNLOCK(hProcessMutex);
		return 0;
	}

	for (iter = pList.begin(); iter != pList.end(); ++iter) {
		if (_wcsnicmp(pProcName, (*iter).pe.szExeFile, MAX_PATH) == 0) {
			UNLOCK(hProcessMutex);
			return (*iter).pe.th32ProcessID;
		}
	}

	UNLOCK(hProcessMutex);
	return 0;
}
Exemplo n.º 10
0
UINT CXmlUtil::GetFieldInt(const XMLDOMElementPtr& ele,
                           const wchar_t* filename,
                           INT defValue)
{
    UINT nRet = defValue;
    std::wstring str = GetField(ele, filename);

    if (_wcsicmp(str.c_str(), L"true") == 0)
        return 1;
    if (_wcsicmp(str.c_str(), L"false") == 0)
        return 0;

    if (!str.empty())
    {
        wchar_t* endptr;
        if (_wcsnicmp(str.c_str(), L"0x", 2) == 0)
            nRet = wcstol(str.c_str(), &endptr, 16);
        else
            nRet = _wtoi(str.c_str());
    }

    return nRet;
}
Exemplo n.º 11
0
int NFOView::DetectHyperlinkEnd(const wchar_t* text, int textLength, int startOffset)
{
    for (int i = startOffset; i < textLength + 1; i++)
    {
        if (!IsCharCanInHyperlink(text[i]))
        {
            return i - 1;
        }

        if (IsHyperlinkStart(text+i, textLength-i))
        {
            if ((startOffset+1 >= wcslen(L"http://")) && 
                (0 == _wcsnicmp(text+i-wcslen(L"http://"), 
                                L"http://",
                                wcslen(L"http://")))
               )
            { continue ;}
            return i - 1;
        }
    }
    
    return textLength;
}
Exemplo n.º 12
0
Arquivo: folder.cpp Projeto: xrmb/nxtv
const NXLFSFile* NXLFSFolder::findfile(const wchar_t* path) const
{
  if(path == NULL) return NULL; // ERR
  //NXMutexLocker ml(m_mutex, "findfile", "n/a");

  while(path[0] == L'.' && (path[1] == L'/' || path[1] == L'\\')) path+=2; // note: there for nxpar2
  while(path[0] == L'/' || path[0] == L'\\') path++;

  const NXLFSFolder* fd = folders();

  const wchar_t* s = wcschr(path, L'/');
  if(s == NULL) s = wcschr(path, L'\\');
  if(s)
  {
    while(fd)
    {
      if(_wcsnicmp(fd->name(), path, s-path) == 0)
      {
        return fd->findfile(s+1);
      }
      fd = fd->next();
    }

    return NULL;
  }

  const NXLFSFile* ff = files();
  while(ff)
  {
    if(_wcsicmp(ff->name(), path) == 0)
    {
      break;
    }
    ff = ff->next();
  }
  return ff;
}
Exemplo n.º 13
0
wchar_t *edit_env(wchar_t *edit, wchar_t *oldenv){
  wchar_t **arg;
  wchar_t *value;
  wchar_t *name = wcsdup(edit);
  int i;
  wchar_t *tmp;
  arg = env_to_arg(oldenv);
  value = wcschr(name,L'=');
  if(value){
    *(value++) = L'\0';
    if(*value == L'\0')
      value = NULL;
  }
  for(i=0;arg[i] != NULL; ++i){
    tmp = wcschr(arg[i],L'=');
    if(((int) wcslen(name)) == (tmp - arg[i]) &&
       !_wcsnicmp(name,arg[i], tmp - arg[i]))
      break;
  }
  if(arg[i] != NULL){
    free(arg[i]);
    if(value){
      arg[i] = wcsdup(edit);
    } else {
      do {
	arg[i] = arg[i+1];
	++i;
      } while(arg[i] != NULL);
    }
  } else if(value){ /* add to arg, which is always allocated
		     to hold one extra environment variable*/
    arg[i] = wcsdup(edit);
    arg[i+1] = NULL;
  }
  free(name);
  return arg_to_env(arg);
}
Exemplo n.º 14
0
// Filters the settings that belong to the given language
// languages is a 00-terminated list of language names ordered by priority
void CSettingsParser::FilterLanguages( const wchar_t *languages )
{
	std::vector<const wchar_t*> lines;
	lines.swap(m_Lines);
	for (const wchar_t *lang=languages;*lang;lang+=wcslen(lang)+1)
	{
		size_t langLen=wcslen(lang);
		for (size_t i=0;i<lines.size();i++)
		{
			const wchar_t *line=lines[i];
			if (*line=='[' && _wcsnicmp(line+1,lang,langLen)==0 && line[langLen+1]==']')
			{
				for (i++;i<lines.size();i++)
				{
					line=lines[i];
					if (*line=='[') break;
					m_Lines.push_back(line);
				}
				break;
			}
		}
	}
	std::reverse(m_Lines.begin(),m_Lines.end());
}
Exemplo n.º 15
0
static int compare(const void *a, const void *b){
  wchar_t *s1 = *((wchar_t **) a);
  wchar_t *s2 = *((wchar_t **) b);
  wchar_t *e1 = wcschr(s1,L'=');
  wchar_t *e2 = wcschr(s2,L'=');
  int ret;
  int len;
  
  if(!e1)
    e1 = s1 + wcslen(s1);
  if(!e2)
    e2 = s2 + wcslen(s2);
  
  if((e1 - s1) > (e2 - s2))
    len = (e2 - s2);
  else
    len = (e1 - s1);
  
  ret = _wcsnicmp(s1,s2,len);
  if(ret == 0)
    return ((e1 - s1) - (e2 - s2));
  else
    return ret;
}
Exemplo n.º 16
0
STDAPI DllInstall(BOOL bInstall, LPCWSTR pszCmdLine)
{
	HRESULT hr = E_FAIL;
	static const wchar_t szUserSwitch[] = L"user";

	if ( pszCmdLine != NULL )
	{
#if defined(_MSC_VER) && (_MSC_VER >= 1500)	// No VS2005
		if ( _wcsnicmp(pszCmdLine, szUserSwitch, _countof(szUserSwitch)) == 0 )
			AtlSetPerUserRegistration(true);
#endif
	}

	if ( bInstall )
	{
		hr = DllRegisterServer();
		if ( FAILED(hr) )
			DllUnregisterServer();
	}
	else
		hr = DllUnregisterServer();

	return hr;
}
Exemplo n.º 17
0
static HRESULT vboxNetFltWinNotifyCheckNetAdp(IN INetCfgComponent *pComponent, OUT bool * pbShouldBind)
{
    HRESULT hr;
    LPWSTR pDevId;
    hr = pComponent->GetId(&pDevId);
    if (hr == S_OK)
    {
        if (!_wcsnicmp(pDevId, L"sun_VBoxNetAdp", sizeof(L"sun_VBoxNetAdp")/2))
        {
            *pbShouldBind = false;
        }
        else
        {
            hr = S_FALSE;
        }
        CoTaskMemFree(pDevId);
    }
    else
    {
        NonStandardAssertBreakpoint();
    }

    return hr;
}
Exemplo n.º 18
0
BOOLEAN GetKernelLdrDataTableEntry(PDRIVER_OBJECT DriverObject)  
{
	BOOLEAN bRet = FALSE;
	if (DriverObject)
	{
		PKLDR_DATA_TABLE_ENTRY Entry = NULL, FirstEntry = NULL;
		WCHAR wzNtoskrnl[] = L"ntoskrnl.exe";                                      
		int nLen = wcslen(wzNtoskrnl) * sizeof(WCHAR);
		FirstEntry = Entry = (PKLDR_DATA_TABLE_ENTRY)DriverObject->DriverSection;  

		while((PKLDR_DATA_TABLE_ENTRY)Entry->InLoadOrderLinks.Flink != FirstEntry)
		{

			if (Entry->BaseDllName.Buffer																			&& 
				nLen == Entry->BaseDllName.Length																	&&
				MmIsAddressValid((PVOID)Entry->BaseDllName.Buffer)													&&
				!_wcsnicmp(wzNtoskrnl,(WCHAR*)Entry->BaseDllName.Buffer, nLen / sizeof(WCHAR)))
			{
				Ntoskrnl_KLDR_DATA_TABLE_ENTRY = (PVOID)Entry;
				bRet = TRUE;
				break;
			}

			Entry = (PKLDR_DATA_TABLE_ENTRY)Entry->InLoadOrderLinks.Flink;
		}

		// 如果没找到ntoskrnl,那么使用自己
		if (!bRet)
		{
			Ntoskrnl_KLDR_DATA_TABLE_ENTRY = (PVOID)FirstEntry;
			bRet = TRUE;
		}
	}

	return bRet;
}
Exemplo n.º 19
0
Arquivo: CLI.cpp Projeto: gclxry/awd
void __cdecl wmain(int argc, WCHAR* argv[])
{
    if (argc>=2 && _wcsnicmp(argv[1], L"SERVER:", wcslen(L"SERVER:"))==0)
    {
            targetHost = argv[1]+wcslen(L"SERVER:");
    }
    if (targetHost)
    {
        wprintf(L"\nCurrently connected to : %s\n",targetHost);
    }else
    {
        wprintf(L"Currently connected to <local host>\nUse 08cli.exe server:<server address> \nto connect to an alternate server\n\n");
    }

    OPTIONS options[]={
        {L'0',L"To connect to a COM server from a MTA apartment",MTAClientCall},
        {L'1',L"To connect to a COM server from a STA apartment",STAClientCall},
        {L'x',L"To exit",NULL},
    }; 

    AppInfo appInfo=AppInfo(options);
    appInfo.Loop();

}
Exemplo n.º 20
0
PLDEVOBJ
NTAPI
EngLoadImageEx(
    _In_z_ LPWSTR pwszDriverName,
    _In_ ULONG ldevtype)
{
    WCHAR acwBuffer[MAX_PATH];
    PLDEVOBJ pldev;
    UNICODE_STRING strDriverName;
    SIZE_T cwcLength;
    LPWSTR pwsz;

    TRACE("EngLoadImageEx(%ls, %lu)\n", pwszDriverName, ldevtype);
    ASSERT(pwszDriverName);

    /* Initialize buffer for the the driver name */
    RtlInitEmptyUnicodeString(&strDriverName, acwBuffer, sizeof(acwBuffer));

    /* Start path with systemroot */
    RtlAppendUnicodeToString(&strDriverName, L"\\SystemRoot\\System32\\");

    /* Get Length of given string */
    cwcLength = wcslen(pwszDriverName);

    /* Check if we have a system32 path given */
    pwsz = pwszDriverName + cwcLength;
    while (pwsz > pwszDriverName)
    {
        if ((*pwsz == L'\\') && (_wcsnicmp(pwsz, L"\\system32\\", 10) == 0))
        {
            /* Driver name starts after system32 */
            pwsz += 10;
            break;
        }
        pwsz--;
    }

    /* Append the driver name */
    RtlAppendUnicodeToString(&strDriverName, pwsz);

    /* MSDN says "The driver must include this suffix in the pwszDriver string."
       But in fact it's optional. The function can also load .sys files without
       appending the .dll extension. */
    if ((cwcLength < 4) ||
        ((_wcsnicmp(pwszDriverName + cwcLength - 4, L".dll", 4) != 0) &&
         (_wcsnicmp(pwszDriverName + cwcLength - 4, L".sys", 4) != 0)) )
    {
        /* Append the .dll suffix */
        RtlAppendUnicodeToString(&strDriverName, L".dll");
    }

    /* Lock loader */
    EngAcquireSemaphore(ghsemLDEVList);

    /* Search the List of LDEVS for the driver name */
    for (pldev = gpldevHead; pldev != NULL; pldev = pldev->pldevNext)
    {
        /* Check if the ldev is associated with a file */
        if (pldev->pGdiDriverInfo)
        {
            ERR("Driver Name 1 %wZ\n", &strDriverName);
            ERR("Driver Name 2 %wZ\n", &pldev->pGdiDriverInfo->DriverName);
            /* Check for match (case insensative) */
            if (RtlEqualUnicodeString(&pldev->pGdiDriverInfo->DriverName, &strDriverName, 1))
            {
                /* Image found in LDEV list */
                break;
            }
        }
    }

    /* Did we find one? */
    if (!pldev)
    {
        /* No, allocate a new LDEVOBJ */
        pldev = LDEVOBJ_AllocLDEV(ldevtype);
        if (!pldev)
        {
            ERR("Could not allocate LDEV\n");
            goto leave;
        }

        /* Load the image */
        if (!LDEVOBJ_bLoadImage(pldev, &strDriverName))
        {
            LDEVOBJ_vFreeLDEV(pldev);
            pldev = NULL;
            ERR("LDEVOBJ_bLoadImage failed\n");
            goto leave;
        }

        /* Shall we load a driver? */
        if (ldevtype != LDEV_IMAGE)
        {
            /* Load the driver */
            if (!LDEVOBJ_bEnableDriver(pldev))
            {
                ERR("LDEVOBJ_bEnableDriver failed\n");

                /* Unload the image. */
                LDEVOBJ_vUnloadImage(pldev);
                LDEVOBJ_vFreeLDEV(pldev);
                pldev = NULL;
                goto leave;
            }
        }

        /* Insert the LDEV into the global list */
        pldev->pldevPrev = NULL;
        pldev->pldevNext = gpldevHead;
        if (gpldevHead)
            gpldevHead->pldevPrev = pldev;
        gpldevHead = pldev;
    }

    /* Increase ref count */
    pldev->cRefs++;

leave:
    /* Unlock loader */
    EngReleaseSemaphore(ghsemLDEVList);

    TRACE("EngLoadImageEx returning %p\n", pldev);
    return pldev;
}
Exemplo n.º 21
0
// Get an unsigned numeric value.  Return ERROR_INVALID_DATA if value isn't
// numeric.
NET_API_STATUS
NetpGetConfigDword(
    IN LPNET_CONFIG_HANDLE ConfigHandle,
    IN LPTSTR KeyWanted,
    IN DWORD DefaultValue,
    OUT LPDWORD ValueBuffer
    )

/*++

Routine Description:

    This function gets the keyword value from the configuration file.
    This value is converted from a string to a DWORD (unsigned).

Arguments:

    SectionPointer - Supplies the pointer to a specific section in the config
        file.

    KeyWanted - Supplies the string of the keyword within the specified
        section to look for.

    DefaultValue - Gives a default value to use if KeyWanted isn't present
        in the section or if KeyWanted exists but no value is in the config
        data.

    ValueBuffer - Returns the numeric value of the keyword.

Return Value:

    NET_API_STATUS - NERR_Success, ERROR_INVALID_DATA (if string wasn't a
    valid unsigned number), or other error code.

--*/

{
    NET_API_STATUS ApiStatus;
    DWORD CharCount;                 // Count of TCHARs, not including null.
    DWORD TempDword = DefaultValue;
    LPTSTR ValueString;

    //
    // Error check the caller somewhat.
    //
    if (ValueBuffer == NULL) {
        return (ERROR_INVALID_PARAMETER);
    }

    //
    // Check for GP fault and set default value.
    //
    *ValueBuffer = DefaultValue;

    if (ConfigHandle == NULL) {
        return (ERROR_INVALID_PARAMETER);
    }

#if defined(USE_WIN32_CONFIG)
    {
        DWORD dwType;
        LONG Error;
        NET_CONFIG_HANDLE * MyHandle = ConfigHandle;  // conv from opaque type
        DWORD ValueLength;

        // Find out what max value length is.
        ApiStatus = NetpGetConfigMaxSizes (
                MyHandle,
                NULL,  // Don't need max keyword size.
                & ValueLength);  // Get max value length.
        NetpAssert( ApiStatus == NO_ERROR );  // BUGBUG

        // Handle empty section.
        if (ValueLength == 0 ) {
            return (NO_ERROR);  // Default already set, so we're done.  Ok!
        }

        // Alloc space for the value.
        ValueString = NetpMemoryAllocate( ValueLength );
        if (ValueString == NULL) {
            return (ERROR_NOT_ENOUGH_MEMORY);
        }

        // Get the actual value.
        Error = RegQueryValueEx (
                MyHandle->WinRegKey,
                KeyWanted,
                NULL,      // reserved
                & dwType,
                (LPVOID) ValueString,    // out: value string (TCHARs).
                & ValueLength
                );
        IF_DEBUG(CONFIG) {
            NetpKdPrint(( PREFIX_NETLIB "NetpGetConfigDword: RegQueryValueEx("
                    FORMAT_LPTSTR ") returned " FORMAT_LONG ".\n",
                    KeyWanted, Error ));
        }
        if (Error == ERROR_FILE_NOT_FOUND) {
            NetpMemoryFree( ValueString );
            return (NO_ERROR);  // Default already set, so we're done.  Ok!
        } else if ( Error != ERROR_SUCCESS ) {
            NetpMemoryFree( ValueString );
            return (Error);
        }

        NetpAssert( ValueString != NULL );
        if (dwType == REG_SZ) {

            goto ParseString;   // Type is good, go parse the string.

        } else if (dwType == REG_DWORD) {

            NetpAssert( ValueLength == sizeof(DWORD) );
            TempDword = * (LPDWORD) (LPVOID) ValueString;
            goto GotValue;

        } else {
            NetpMemoryFree( ValueString );
            IF_DEBUG(CONFIG) {
                NetpKdPrint(( PREFIX_NETLIB
                        "NetpGetConfigDword: read unexpected reg type "
                        FORMAT_DWORD ".\n", dwType ));
            }
            return (ERROR_INVALID_DATA);
        }

    }

#else // ndef USE_WIN32_CONFIG

    //
    // Get a copy of the string from the config data.
    //

    ApiStatus = NetpGetConfigValue(
            ConfigHandle,
            KeyWanted,
            & ValueString );         // Must be freed by NetApiBufferFree().
    if (ApiStatus != NO_ERROR) {

        //
        // If KeyWanted isn't in config data, return default (and NO_ERROR).
        //
        if (ApiStatus == NERR_CfgParamNotFound) {
            NetpAssert( *ValueBuffer == DefaultValue );  // Already set.
            ApiStatus = NO_ERROR;
        }
        return (ApiStatus);
    }
#endif

    NetpAssert( ValueString != NULL );

ParseString:

    //
    // Do some error checking on the value string.
    //

    CharCount = STRLEN( ValueString );

    if ( CharCount == 0 ) {

        //
        // If "key=" line exists (but no value), return default and say
        // NO_ERROR.
        //
        ApiStatus = NO_ERROR;

    } else if ( _wcsnicmp( ValueString, L"0x", 2 ) == 0 ) {
        LPWSTR end;

        TempDword = wcstoul( ValueString, &end, 16 );

        if ( end - ValueString == (ptrdiff_t) CharCount ) {
            ApiStatus = NO_ERROR;
        } else {
            NetpKdPrint(( PREFIX_NETLIB
                    "NetpGetConfigDword: invalid string for keyword "
                    FORMAT_LPTSTR " is '" FORMAT_LPTSTR "'...\n",
                    KeyWanted, ValueString ));

            ApiStatus = ERROR_INVALID_DATA;
        }

    } else if ( STRSPN( ValueString, TEXT("0123456789") ) != CharCount ) {

        NetpKdPrint(( PREFIX_NETLIB
                "NetpGetConfigDword: invalid string for keyword "
                FORMAT_LPTSTR " is '" FORMAT_LPTSTR "'...\n",
                KeyWanted, ValueString ));

        ApiStatus = ERROR_INVALID_DATA;

    } else {

        //
        // Convert the string to a numeric value.
        //
        TempDword = (DWORD) ATOL( ValueString );

        ApiStatus = NO_ERROR;

    }

    IF_DEBUG(CONFIG) {
        NetpKdPrint(( PREFIX_NETLIB "NetpGetConfigDword: string for "
                FORMAT_LPTSTR " is '" FORMAT_LPTSTR "'...\n",
                KeyWanted, ValueString));
    }

GotValue:

    IF_DEBUG(CONFIG) {
        NetpKdPrint(( PREFIX_NETLIB "NetpGetConfigDword: numeric value is "
                FORMAT_DWORD ",\n", TempDword ));
        NetpKdPrint(("  returning ApiStatus " FORMAT_API_STATUS ".\n",
                ApiStatus ));
    }

    (void) NetApiBufferFree( ValueString );

    //
    // Tell caller how things went.
    //
    * ValueBuffer = TempDword;
    return (ApiStatus);
}
Exemplo n.º 22
0
/*++
Function:
  CompareStringW

See MSDN doc.
--*/
int
PALAPI
CompareStringW(
    IN LCID     Locale,
    IN DWORD    dwCmpFlags,
    IN LPCWSTR  lpString1,
    IN int      cchCount1,
    IN LPCWSTR  lpString2,
    IN int      cchCount2)
{
    INT nRetVal =0;  /*return Value*/
    INT nStrLen =0;

    ENTRY("CompareStringW(Locale=%#x, dwCmpFlags=%#x,lpString1 = %p (%S), "
          "cchCount1 =%d,lpString2 = %p (%S),cchCount2 =%d )\n",
          Locale, dwCmpFlags, lpString1, lpString1, cchCount1,lpString2,lpString2, cchCount2 );

    if ( Locale != 0x0409 )
    {
        ASSERT("Error Locale(%#x) parameter is invalid\n",Locale);
        SetLastError(ERROR_INVALID_PARAMETER);
        LOGEXIT ("CompareStringW returns int 0\n");
        return 0;
    }

    if( dwCmpFlags != ( NORM_IGNORECASE | NORM_IGNOREWIDTH ) )
    {
        ASSERT("Error dwCmpFlags(%#x) parameter is invalid\n",dwCmpFlags);
        SetLastError(ERROR_INVALID_PARAMETER);
        LOGEXIT ("CompareStringW returns int 0\n");
        return 0;
    }

    if ( !lpString1 || !lpString2 )
    {
        ERROR("One of the two params %p and %p is Invalid\n",lpString1,lpString2);
        SetLastError( ERROR_INVALID_PARAMETER );
        LOGEXIT ("CompareStringW returns 0\n" );
        return 0;
    }

    if(cchCount1 == 0 && cchCount2 == 0 )
    {
        LOGEXIT ("CompareStringW returns int %d\n", CSTR_EQUAL );
        return CSTR_EQUAL;
    }

    if ( cchCount1 == 0 )
    {
        LOGEXIT ("CompareStringW returns int %d\n", CSTR_LESS_THAN );
        return CSTR_LESS_THAN;
    }
    if ( cchCount2 == 0 )
    {
        LOGEXIT ("CompareStringW returns int %d\n", CSTR_GREATER_THAN );
        return CSTR_GREATER_THAN;
    }

    if( cchCount1 == -1)
    {
        cchCount1 = PAL_wcslen( lpString1 );
    }
    if( cchCount2 == -1 )
    {
        cchCount2 = PAL_wcslen( lpString2 );
    }

    /*take the length of the smaller of the 2 strings*/
    nStrLen = ( ( cchCount1 > cchCount2 ) ? cchCount2 : cchCount1 );
    nRetVal = _wcsnicmp( lpString1, lpString2, nStrLen );

    if(nRetVal ==0)
    {
        if(cchCount1>cchCount2)
        {
            nRetVal = 1;
        }
        else if (cchCount1 < cchCount2)
        {
            nRetVal = -1;
        }
    }

    if ( nRetVal == 0 )
    {
        LOGEXIT ("CompareStringW returns int %d\n", CSTR_EQUAL );        
        return CSTR_EQUAL;
    }
    else if ( nRetVal > 0 )
    {
        LOGEXIT ("CompareStringW returns int %d\n", CSTR_EQUAL );        
        return CSTR_GREATER_THAN;
    }
    else
    {
        LOGEXIT ("CompareStringW returns int %d\n", CSTR_LESS_THAN );
        return CSTR_LESS_THAN;
    }
}
Exemplo n.º 23
0
// Compute the offset and size for the available map area on the page
//
void MgPrintLayout::ComputeMapOffsetAndSize(double mapScale, MgEnvelope* mapBounds, double metersPerUnit,
                                            double& mapOffsetX, double& mapOffsetY, double& mapWidth, double& mapHeight, bool expandToFit)
{
    double convertUnits = 1.0;
    STRING pageUnits = m_plotSpec->GetPageSizeUnits();
    if (_wcsnicmp(pageUnits.c_str(), L"mm", 3) == 0 ||
        _wcsnicmp(pageUnits.c_str(), L"millimeters", 12) == 0 )
    {
        convertUnits = MILLIMETERS_PER_INCH;
    }

    mapOffsetX = m_plotSpec->GetMarginLeft();
    mapOffsetY = m_plotSpec->GetMarginBottom();

    if (expandToFit)
    {
        // The map is scaled to fit the available page area (aspect is not necessarily preserved)
        mapWidth = m_dPageWidth - mapOffsetX - m_plotSpec->GetMarginRight();
        mapHeight = m_dPageHeight - mapOffsetY - m_plotSpec->GetMarginTop();

        if (m_bShowLegend)
        {
            mapWidth -= (MgPrintLayout::LegendWidth + MgPrintLayout::LegendPadding)*convertUnits;
            mapOffsetX += (MgPrintLayout::LegendWidth + MgPrintLayout::LegendPadding)*convertUnits;
        }
        if (m_bShowTitle)
        {
            mapHeight -= MgPrintLayout::HeaderHeight*convertUnits;
        }
        if (m_bShowScalebar || m_bShowNorthArrow)
        {
            mapHeight -= (MgPrintLayout::ScalebarHeight + MgPrintLayout::ScalebarPadding)*convertUnits;
        }
        if (m_bShowUrl || m_bShowDateTime)
        {
            mapHeight -= MgPrintLayout::FooterHeight*convertUnits;
        }
    }

    else
    {
        // The visible extent of the map is rendered with the current aspect ratio.
        // Clipping of the extents is done as necessary.
        if (mapScale <= 0)
        {
            // The map is scaled to fit the available page area (aspect is not necessarily preserved)
            mapWidth = m_dPageWidth - mapOffsetX - m_plotSpec->GetMarginRight();
            mapHeight = m_dPageHeight - mapOffsetY - m_plotSpec->GetMarginTop();

            if (m_bShowLegend)
            {
                mapWidth -= (MgPrintLayout::LegendWidth + MgPrintLayout::LegendPadding)*convertUnits;
                mapOffsetX += (MgPrintLayout::LegendWidth + MgPrintLayout::LegendPadding)*convertUnits;
            }
            if (m_bShowTitle)
            {
                mapHeight -= MgPrintLayout::HeaderHeight;
            }
            if (m_bShowScalebar || m_bShowNorthArrow)
            {
                mapHeight -= MgPrintLayout::ScalebarHeight;
            }
            if (m_bShowUrl || m_bShowDateTime)
            {
                mapHeight -= MgPrintLayout::FooterHeight;
            }
        }
        else
        {
            // A specific scale is used for the map

            double width = mapBounds->GetWidth();
            double height = mapBounds->GetHeight();
            double mapar = width / height;

            mapHeight = height * metersPerUnit / mapScale;
            mapHeight /= METERS_PER_INCH;

            mapWidth = mapar * mapHeight;

            // mapHeight and mapWidth must be in the same units as the units specified for the page
            mapHeight *= convertUnits;
            mapWidth *= convertUnits;

            // Determine the offset in X direction such that the map is centered horizontally
            if (m_bShowLegend)
            {
                if (mapWidth > (m_dPageWidth - mapOffsetX - m_plotSpec->GetMarginRight() - (MgPrintLayout::LegendWidth + MgPrintLayout::LegendPadding)*convertUnits))
                {
                    mapWidth = m_dPageWidth - mapOffsetX - m_plotSpec->GetMarginRight() - (MgPrintLayout::LegendWidth + MgPrintLayout::LegendPadding)*convertUnits;
                    mapOffsetX += (MgPrintLayout::LegendWidth + MgPrintLayout::LegendPadding)*convertUnits;
                }
                else
                {
                    mapOffsetX += (m_dPageWidth - m_plotSpec->GetMarginLeft() - m_plotSpec->GetMarginRight()
                        - mapWidth + (MgPrintLayout::LegendWidth + MgPrintLayout::LegendPadding)*convertUnits) * 0.5;
                }
            }
            else
            {
                if (mapWidth > (m_dPageWidth - mapOffsetX - m_plotSpec->GetMarginRight() ))
                {
                    mapWidth = m_dPageWidth - mapOffsetX - m_plotSpec->GetMarginRight();
                }
                else
                {
                    //simply center the map on the page
                    mapOffsetX = (m_dPageWidth - mapWidth) * 0.5;
                }
            }

            double dMapHeightAdjustment = -(m_plotSpec->GetMarginTop() + m_plotSpec->GetMarginBottom());
            if (m_bShowTitle)
            {
                dMapHeightAdjustment -= MgPrintLayout::HeaderHeight*convertUnits;
            }
            if (m_bShowScalebar || m_bShowNorthArrow)
            {
                dMapHeightAdjustment -= MgPrintLayout::ScalebarHeight*convertUnits;
            }
            if (m_bShowUrl || m_bShowDateTime)
            {
                dMapHeightAdjustment -= MgPrintLayout::FooterHeight*convertUnits;
            }

            if (mapHeight > m_dPageHeight + dMapHeightAdjustment)
            {
                mapHeight = m_dPageHeight + dMapHeightAdjustment;
            }
        }
    }

    //finally center map vertically using updated map height
    if (m_bShowTitle)
    {
        mapOffsetY = (m_dPageHeight - MgPrintLayout::HeaderHeight*convertUnits - mapHeight) * 0.5;
    }
    if (m_bShowScalebar || m_bShowNorthArrow || m_bShowUrl || m_bShowDateTime)
    {
        mapOffsetY = (m_dPageHeight - mapHeight) * 0.5;
    }
}
Exemplo n.º 24
0
int __cdecl main(int argc, char *argv[])
{
    WCHAR str1[] = {'f','o','o',0};
    WCHAR str2[] = {'f','o','o','x',0};
    WCHAR str3[] = {'f','O','o',0};
    WCHAR str4[] = {'A','B','C','D','E',0};
    WCHAR str5[] = {'A','B','C','D',']',0};
    WCHAR str6[] = {'a','b','c','d','e',0};
    WCHAR str7[] = {'a','b','c','d',']',0};
    char cstr1[] = "foo";
    char cstr2[] = "foox";
    char cstr3[] = "fOo";
    char cstr4[] = "ABCDE";
    char cstr5[] = "ABCD]";
    char cstr6[] = "abcde";
    char cstr7[] = "abcd]";


    /*
     *  Initialize the PAL and return FAIL if this fails
     */
    if (0 != (PAL_Initialize(argc, argv)))
    {
        return FAIL;
    }

    if (_wcsnicmp(str1, str2, wcslen(str2)) >= 0)
    {
        Fail ("ERROR: wcsnicmp(\"%s\", \"%s\", %d) returned >= 0\n", cstr1,
                cstr2, wcslen(str2));
    }

    if (_wcsnicmp(str2, str1, wcslen(str2)) <= 0)
    {
        Fail ("ERROR: wcsnicmp(\"%s\", \"%s\", %d) returned <= 0\n", cstr2,
                cstr1, wcslen(str2));
    }

    if (_wcsnicmp(str1, str2, wcslen(str1)) != 0)
    {
        Fail ("ERROR: wcsnicmp(\"%s\", \"%s\", %d) returned != 0\n", cstr1,
                cstr2, wcslen(str1));
    }

    if (_wcsnicmp(str1, str3, wcslen(str1)) != 0)
    {
        Fail ("ERROR: wcsnicmp(\"%s\", \"%s\", %d) returned != 0\n", cstr1,
                cstr3, wcslen(str1));
    }

    /* new testing */
    
    /* str4 should be greater than str5 */
    if (_wcsnicmp(str4, str5, wcslen(str4)) <= 0)
    {
        Fail ("ERROR: _wcsnicmp(\"%s\", \"%s\", %d) returned >= 0\n",
                cstr4, cstr5, wcslen(str4));
    }

    /* str6 should be greater than str7 */
    if (_wcsnicmp(str6, str7, wcslen(str6)) <= 0)
    {
        Fail ("ERROR: _wcsnicmp(\"%s\", \"%s\", %d) returned <= 0\n",
                cstr6, cstr7, wcslen(str6));
    }

    PAL_Terminate();
    return PASS;
}
Exemplo n.º 25
0
nsresult
nsXREDirProvider::GetUpdateRootDir(nsIFile* *aResult)
{
  nsCOMPtr<nsIFile> updRoot;
#if defined(MOZ_WIDGET_GONK)

  nsresult rv = NS_NewNativeLocalFile(nsDependentCString("/data/local"),
                                      true,
                                      getter_AddRefs(updRoot));
  NS_ENSURE_SUCCESS(rv, rv);

#else
  nsCOMPtr<nsIFile> appFile;
  bool per = false;
  nsresult rv = GetFile(XRE_EXECUTABLE_FILE, &per, getter_AddRefs(appFile));
  NS_ENSURE_SUCCESS(rv, rv);
  rv = appFile->GetParent(getter_AddRefs(updRoot));
  NS_ENSURE_SUCCESS(rv, rv);

#ifdef XP_MACOSX
  nsCOMPtr<nsIFile> appRootDirFile;
  nsCOMPtr<nsIFile> localDir;
  nsAutoString appDirPath;
  if (NS_FAILED(appFile->GetParent(getter_AddRefs(appRootDirFile))) ||
      NS_FAILED(appRootDirFile->GetPath(appDirPath)) ||
      NS_FAILED(GetUserDataDirectoryHome(getter_AddRefs(localDir), true))) {
    return NS_ERROR_FAILURE;
  }

  int32_t dotIndex = appDirPath.RFind(".app");
  if (dotIndex == kNotFound) {
    dotIndex = appDirPath.Length();
  }
  appDirPath = Substring(appDirPath, 1, dotIndex - 1);

  bool hasVendor = gAppData->vendor && strlen(gAppData->vendor) != 0;
  if (hasVendor || gAppData->name) {
    if (NS_FAILED(localDir->AppendNative(nsDependentCString(hasVendor ?
                                           gAppData->vendor :
                                           gAppData->name)))) {
      return NS_ERROR_FAILURE;
    }
  } else if (NS_FAILED(localDir->AppendNative(NS_LITERAL_CSTRING("Mozilla")))) {
    return NS_ERROR_FAILURE;
  }

  if (NS_FAILED(localDir->Append(NS_LITERAL_STRING("updates"))) ||
      NS_FAILED(localDir->AppendRelativePath(appDirPath))) {
    return NS_ERROR_FAILURE;
  }

  localDir.forget(aResult);
  return NS_OK;

#elif XP_WIN
  nsAutoString pathHash;
  bool pathHashResult = false;
  bool hasVendor = gAppData->vendor && strlen(gAppData->vendor) != 0;

  nsAutoString appDirPath;
  if (SUCCEEDED(updRoot->GetPath(appDirPath))) {

    // Figure out where we should check for a cached hash value. If the
    // application doesn't have the nsXREAppData vendor value defined check
    // under SOFTWARE\Mozilla.
    wchar_t regPath[1024] = { L'\0' };
    swprintf_s(regPath, mozilla::ArrayLength(regPath), L"SOFTWARE\\%S\\%S\\TaskBarIDs",
               (hasVendor ? gAppData->vendor : "Mozilla"), MOZ_APP_BASENAME);

    // If we pre-computed the hash, grab it from the registry.
    pathHashResult = GetCachedHash(HKEY_LOCAL_MACHINE,
                                   nsDependentString(regPath), appDirPath,
                                   pathHash);
    if (!pathHashResult) {
      pathHashResult = GetCachedHash(HKEY_CURRENT_USER,
                                     nsDependentString(regPath), appDirPath,
                                     pathHash);
    }
  }

  // Get the local app data directory and if a vendor name exists append it.
  // If only a product name exists, append it.  If neither exist fallback to
  // old handling.  We don't use the product name on purpose because we want a
  // shared update directory for different apps run from the same path.
  nsCOMPtr<nsIFile> localDir;
  if (pathHashResult && (hasVendor || gAppData->name) &&
      NS_SUCCEEDED(GetUserDataDirectoryHome(getter_AddRefs(localDir), true)) &&
      NS_SUCCEEDED(localDir->AppendNative(nsDependentCString(hasVendor ?
                                          gAppData->vendor : gAppData->name))) &&
      NS_SUCCEEDED(localDir->Append(NS_LITERAL_STRING("updates"))) &&
      NS_SUCCEEDED(localDir->Append(pathHash))) {
    localDir.forget(aResult);
    return NS_OK;
  }

  nsAutoString appPath;
  rv = updRoot->GetPath(appPath);
  NS_ENSURE_SUCCESS(rv, rv);

  // AppDir may be a short path. Convert to long path to make sure
  // the consistency of the update folder location
  nsString longPath;
  wchar_t* buf;

  uint32_t bufLength = longPath.GetMutableData(&buf, MAXPATHLEN);
  NS_ENSURE_TRUE(bufLength >= MAXPATHLEN, NS_ERROR_OUT_OF_MEMORY);

  DWORD len = GetLongPathNameW(appPath.get(), buf, bufLength);

  // Failing GetLongPathName() is not fatal.
  if (len <= 0 || len >= bufLength)
    longPath.Assign(appPath);
  else
    longPath.SetLength(len);

  // Use <UserLocalDataDir>\updates\<relative path to app dir from
  // Program Files> if app dir is under Program Files to avoid the
  // folder virtualization mess on Windows Vista
  nsAutoString programFiles;
  rv = GetShellFolderPath(CSIDL_PROGRAM_FILES, programFiles);
  NS_ENSURE_SUCCESS(rv, rv);

  programFiles.Append('\\');
  uint32_t programFilesLen = programFiles.Length();

  nsAutoString programName;
  if (_wcsnicmp(programFiles.get(), longPath.get(), programFilesLen) == 0) {
    programName = Substring(longPath, programFilesLen);
  } else {
    // We need the update root directory to live outside of the installation
    // directory, because otherwise the updater writing the log file can cause
    // the directory to be locked, which prevents it from being replaced after
    // background updates.
    programName.AssignASCII(MOZ_APP_NAME);
  }

  rv = GetUserLocalDataDirectory(getter_AddRefs(updRoot));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = updRoot->AppendRelativePath(programName);
  NS_ENSURE_SUCCESS(rv, rv);

#endif // XP_WIN
#endif
  updRoot.forget(aResult);
  return NS_OK;
}
Exemplo n.º 26
0
NET_API_STATUS
BrCreateNetwork(
    PUNICODE_STRING TransportName,
    IN BOOLEAN Wannish,
    IN BOOLEAN Ras,
    IN PUNICODE_STRING AlternateTransportName OPTIONAL
    )
/*++

Routine Description:

    This routine allocates memory to hold a network structure, and initializes
    all of its associated data structures.

Arguments:

    TransportName - The name of the transport to add.

Return Value:

    Status of operation (mostly status of allocations).

--*/
{
    NET_API_STATUS Status;
    PNETWORK Network;
    BOOLEAN NetworkLockInitialized = FALSE;
    BOOLEAN MasterFlagsInitialized = FALSE;
    BOOLEAN BackupBrowserTimerCreated = FALSE;
    BOOLEAN MasterBrowserTimerCreated =FALSE;
    BOOLEAN AnnouncementTimerCreated = FALSE;
    BOOLEAN ResponseCacheLockInitialized = FALSE;

    //
    // Check to see if the transport already exists.
    //

    if ((Network = BrFindNetwork(TransportName)) != NULL) {

        return NERR_AlreadyExists;
    }

    //
    // If this transport is explicitly on our list of transports to unbind,
    //  simply ignore the transport.
    //

    if (BrInfo.UnboundBindings != NULL) {
        LPTSTR_ARRAY TStrArray = BrInfo.UnboundBindings;

        while (!NetpIsTStrArrayEmpty(TStrArray)) {
            LPWSTR NewTransportName;

#define NAME_PREFIX L"\\Device\\"
#define NAME_PREFIX_LENGTH 8

            //
            // The transport name in the registry is only optionally prefixed with \device\
            //

            if ( _wcsnicmp( NAME_PREFIX, TStrArray, NAME_PREFIX_LENGTH) == 0 ) {
                NewTransportName = TransportName->Buffer;
            } else {
                NewTransportName = TransportName->Buffer + NAME_PREFIX_LENGTH;
            }

            if ( _wcsicmp( TStrArray, NewTransportName ) == 0 ) {
                dprintf(INIT, ("Binding is marked as unbound: %s (Silently ignoring)\n", TransportName->Buffer ));
                return NERR_Success;
            }

            TStrArray = NetpNextTStrArrayEntry(TStrArray);

        }

    }


    //
    // If this transport isn't bound to the SMB server,
    //  don't create the transport here.
    //  we do announcments through the SMB server.
    //

    Status = I_NetServerSetServiceBits(NULL, TransportName->Buffer, 0, TRUE);

    if (Status == ERROR_PATH_NOT_FOUND ) {
        dprintf(INIT, ("SMB Server doesn't have this transport: %s (Silently unbinding)\n", TransportName->Buffer ));
        return NERR_Success;
    }


    //
    // Create the transport.
    //

    try {

        Network = MIDL_user_allocate(sizeof(NETWORK));

        if (Network == NULL) {
            try_return(Status = ERROR_NOT_ENOUGH_MEMORY);
        }

        RtlInitializeResource(&Network->Lock);

        NetworkLockInitialized = TRUE;

        Network->LockCount = 0;

        Network->ReferenceCount = 1;

        Network->Role = BrDefaultRole;

        Network->NumberOfFailedBackupTimers = 0;

        Network->NumberOfFailedPromotions = 0;

        Network->NumberOfPromotionEventsLogged = 0;

        Network->LastBackupBrowserReturned = 0;

        Network->LastDomainControllerBrowserReturned = 0;

        Network->TimeStoppedBackup = 0;

        Network->BackupServerList = NULL;
        Network->BackupDomainList = NULL;

        Network->TotalBackupServerListEntries = 0;
        Network->TotalBackupDomainListEntries = 0;

        Network->NetworkName.Buffer = MIDL_user_allocate(TransportName->MaximumLength);

        if (Network->NetworkName.Buffer == NULL) {
            try_return(Status = ERROR_NOT_ENOUGH_MEMORY);
        }

        Network->NetworkName.MaximumLength = TransportName->MaximumLength;

        RtlCopyUnicodeString(&Network->NetworkName, TransportName);

        Network->Flags = 0;

        if (ARGUMENT_PRESENT(AlternateTransportName)) {
            PNETWORK AlternateNetwork = BrFindNetwork(AlternateTransportName);

            //
            //  If we didn't find an alternate network, or if that network
            //  already has an alternate network, return an error.
            //

            if (AlternateNetwork == NULL ||
                AlternateNetwork->AlternateNetwork != NULL) {

                try_return(Status = NERR_InternalError);
            }

            Network->Flags |= NETWORK_IPX;

            //
            //  Link the two networks together.
            //

            Network->AlternateNetwork = AlternateNetwork;

            AlternateNetwork->AlternateNetwork = Network;

        } else {
            Network->AlternateNetwork = NULL;
        }

        //
        //  Null terminate the network name buffer.
        //

        Network->NetworkName.Buffer[Network->NetworkName.Length/sizeof(WCHAR)] = UNICODE_NULL;

        RtlInitUnicodeString(&Network->MasterBrowserName, NULL);

        if (Wannish) {
            Network->Flags |= NETWORK_WANNISH;
        }

        if (Ras) {
            Network->Flags |= NETWORK_RAS;
        }

        Network->LastBowserServerQueried = 0;

        RtlInitializeCriticalSection(&Network->MasterFlagsLock);

        MasterFlagsInitialized = TRUE;

        Network->MasterFlags = 0;

        InitializeInterimServerList(&Network->BrowseTable,
                                    BrBrowseTableInsertRoutine,
                                    BrBrowseTableUpdateRoutine,
                                    BrBrowseTableDeleteRoutine,
                                    BrBrowseTableAgeRoutine);

        Network->LastBowserDomainQueried = 0;

        InitializeInterimServerList(&Network->DomainList,
                                    BrDomainTableInsertRoutine,
                                    BrDomainTableUpdateRoutine,
                                    BrDomainTableDeleteRoutine,
                                    BrDomainTableAgeRoutine);

        InitializeListHead(&Network->OtherDomainsList);

        Status = BrCreateTimer(&Network->BackupBrowserTimer);

        if (Status != NERR_Success) {

            try_return(Status);
        }

        BackupBrowserTimerCreated = TRUE;

        Status = BrCreateTimer(&Network->MasterBrowserTimer);

        if (Status != NERR_Success) {
            try_return(Status);
        }

        MasterBrowserTimerCreated = TRUE;

        Status = BrCreateTimer(&Network->MasterBrowserAnnouncementTimer);

        if (Status != NERR_Success) {

            try_return(Status);
        }

        AnnouncementTimerCreated = TRUE;

        InitializeCriticalSection(&Network->ResponseCacheLock);

        ResponseCacheLockInitialized = TRUE;

        InitializeListHead(&Network->ResponseCache);

        Network->TimeCacheFlushed = 0;

        Network->NumberOfCachedResponses = 0;

        Status = RtlEnterCriticalSection(&NetworkLock);

        if (!NT_SUCCESS(Status)) {

            try_return(Status = BrMapStatus(Status));
        }

        InsertHeadList(&ServicedNetworks, &Network->NextNet);

        Status = RtlLeaveCriticalSection(&NetworkLock);

        if (!NT_SUCCESS(Status)) {
            InternalError(("Unable to release browser critical section\n"));
        }

try_exit:NOTHING;
    } finally {
        if (Status != NERR_Success) {

            if (Network != NULL) {
                if (ResponseCacheLockInitialized) {
                    DeleteCriticalSection(&Network->ResponseCacheLock);
                }

                if (MasterFlagsInitialized) {
                    RtlDeleteCriticalSection(&Network->MasterFlagsLock);
                }

                if (NetworkLockInitialized) {
                    RtlDeleteResource(&Network->Lock);
                }

                if (AnnouncementTimerCreated) {
                    BrDestroyTimer(&Network->MasterBrowserAnnouncementTimer);
                }

                if (MasterBrowserTimerCreated) {
                    BrDestroyTimer(&Network->MasterBrowserTimer);
                }

                if (BackupBrowserTimerCreated) {
                    BrDestroyTimer(&Network->BackupBrowserTimer);
                }

                if (Network->NetworkName.Buffer != NULL) {
                    MIDL_user_free(Network->NetworkName.Buffer);
                }

                MIDL_user_free(Network);

            }

        }
    }

    return Status;
}
Exemplo n.º 27
0
NTSTATUS
Ext2RegistryQueryCallback(
    IN PWSTR ValueName,
    IN ULONG ValueType,
    IN PVOID ValueData,
    IN ULONG ValueLength,
    IN PVOID Context,
    IN PVOID EntryContext
    )
{
    ULONG  i = 0;
    BYTE   *s, *t;

    if (NULL == ValueName || NULL == ValueData)
        return STATUS_SUCCESS;

    if (ValueType == REG_DWORD && wcslen(ValueName) == wcslen(WRITING_SUPPORT) &&
        _wcsnicmp(ValueName, WRITING_SUPPORT, wcslen(WRITING_SUPPORT)) == 0) {

        if (ValueData && ValueLength == sizeof(DWORD)) {
            if (*((PULONG)ValueData)) {
                SetLongFlag(Ext2Global->Flags, EXT2_SUPPORT_WRITING);
            } else {
                ClearLongFlag(Ext2Global->Flags, EXT2_SUPPORT_WRITING);
            }
        }
    } else if (ValueType == REG_DWORD && wcslen(ValueName) == wcslen(CHECKING_BITMAP) &&
        _wcsnicmp(ValueName, CHECKING_BITMAP, wcslen(CHECKING_BITMAP)) == 0) {

        if (ValueData && ValueLength == sizeof(DWORD)) {
            if (*((PULONG)ValueData)) {
                SetLongFlag(Ext2Global->Flags, EXT2_CHECKING_BITMAP);
            } else {
                ClearLongFlag(Ext2Global->Flags, EXT2_CHECKING_BITMAP);
            }
        }
    } else if (ValueType == REG_DWORD && wcslen(ValueName) == wcslen(EXT3_FORCEWRITING) &&
        _wcsnicmp(ValueName, EXT3_FORCEWRITING, wcslen(EXT3_FORCEWRITING)) == 0) {

        if (ValueData && ValueLength == sizeof(DWORD)) {
            if (*((PULONG)ValueData)) {
                SetLongFlag(Ext2Global->Flags, EXT3_FORCE_WRITING);
                SetLongFlag(Ext2Global->Flags, EXT2_SUPPORT_WRITING);
            } else {
                ClearLongFlag(Ext2Global->Flags, EXT3_FORCE_WRITING);
            }
        }
    } else if (ValueType == REG_DWORD && wcslen(ValueName) == wcslen(AUTO_MOUNT) &&
        _wcsnicmp(ValueName, AUTO_MOUNT, wcslen(AUTO_MOUNT)) == 0) {

        if (ValueData && ValueLength == sizeof(DWORD)) {
            if (*((PULONG)ValueData)) {
                SetLongFlag(Ext2Global->Flags, EXT2_AUTO_MOUNT);
            } else {
                ClearLongFlag(Ext2Global->Flags, EXT2_AUTO_MOUNT);
            }
        }
    } else if (ValueType == REG_SZ && wcslen(ValueName) == wcslen(CODEPAGE_NAME) &&
        _wcsnicmp(ValueName, CODEPAGE_NAME, wcslen(CODEPAGE_NAME)) == 0) {

        if (ValueData && ValueLength <= sizeof(WCHAR) * CODEPAGE_MAXLEN) {
            RtlCopyMemory(&Ext2Global->Codepage.PageName[0],
                          ValueData, ValueLength);
        }
    } else if (ValueType == REG_SZ && wcslen(ValueName) == wcslen(HIDING_PREFIX) &&
        _wcsnicmp(ValueName, HIDING_PREFIX, wcslen(HIDING_PREFIX)) == 0) {

        if (ValueData && ValueLength <= sizeof(WCHAR) * HIDINGPAT_LEN) {
            RtlCopyMemory(&Ext2Global->wHidingPrefix[0],
                          ValueData, ValueLength);
        }
    } else  if (ValueType == REG_SZ && wcslen(ValueName) == wcslen(HIDING_SUFFIX) &&
        _wcsnicmp(ValueName, HIDING_SUFFIX, wcslen(HIDING_SUFFIX)) == 0) {

        if (ValueData && ValueLength <= sizeof(WCHAR) * HIDINGPAT_LEN) {
            RtlCopyMemory(&Ext2Global->wHidingSuffix[0],
                          ValueData, ValueLength);
        }
    }


    return STATUS_SUCCESS;
}
Exemplo n.º 28
0
INT_PTR CDialogPackage::CTabOptions::OnCommand(WPARAM wParam, LPARAM lParam)
{
    switch (LOWORD(wParam))
    {
    case IDC_PACKAGEOPTIONS_FILEBROWSE_BUTTON:
    {
        WCHAR buffer[MAX_PATH];
        HWND item = GetDlgItem(m_Window, IDC_PACKAGEOPTIONS_FILE_EDIT);
        GetWindowText(item, buffer, _countof(buffer));

        OPENFILENAME ofn = { sizeof(OPENFILENAME) };
        ofn.lpstrFilter = L"Rainmeter skin package (.rmskin)\0*.rmskin";
        ofn.lpstrTitle = L"Select Rainmeter skin package";
        ofn.lpstrDefExt = L"dll";
        ofn.lpstrFile = buffer;
        ofn.nMaxFile = _countof(buffer);
        ofn.hwndOwner = c_Dialog->GetWindow();

        if (GetOpenFileName(&ofn))
        {
            c_Dialog->m_TargetFile = buffer;
            SetWindowText(item, buffer);
        }
    }
    break;

    case IDC_PACKAGEOPTIONS_DONOTHING_RADIO:
    {
        HWND item = GetDlgItem(m_Window, IDC_PACKAGEOPTIONS_LOADSKIN_EDIT);
        ShowWindow(item, SW_HIDE);
        item = GetDlgItem(m_Window, IDC_PACKAGEOPTIONS_LOADSKINBROWSE_BUTTON);
        ShowWindow(item, SW_HIDE);
        item = GetDlgItem(m_Window, IDC_PACKAGEOPTIONS_LOADTHEME_COMBO);
        ShowWindow(item, SW_HIDE);

        c_Dialog->m_Load.clear();
    }
    break;

    case IDC_PACKAGEOPTIONS_LOADSKIN_RADIO:
    {
        HWND item = GetDlgItem(m_Window, IDC_PACKAGEOPTIONS_LOADSKIN_EDIT);
        ShowWindow(item, SW_SHOWNORMAL);

        WCHAR buffer[MAX_PATH];
        GetWindowText(item, buffer, _countof(buffer));
        c_Dialog->m_Load = buffer;
        c_Dialog->m_LoadLayout = false;

        item = GetDlgItem(m_Window, IDC_PACKAGEOPTIONS_LOADSKINBROWSE_BUTTON);
        ShowWindow(item, SW_SHOWNORMAL);
        item = GetDlgItem(m_Window, IDC_PACKAGEOPTIONS_LOADTHEME_COMBO);
        ShowWindow(item, SW_HIDE);
    }
    break;

    case IDC_PACKAGEOPTIONS_LOADTHEME_RADIO:
    {
        HWND item = GetDlgItem(m_Window, IDC_PACKAGEOPTIONS_LOADSKIN_EDIT);
        ShowWindow(item, SW_HIDE);
        item = GetDlgItem(m_Window, IDC_PACKAGEOPTIONS_LOADSKINBROWSE_BUTTON);
        ShowWindow(item, SW_HIDE);
        item = GetDlgItem(m_Window, IDC_PACKAGEOPTIONS_LOADTHEME_COMBO);
        ShowWindow(item, SW_SHOWNORMAL);

        WCHAR buffer[MAX_PATH];
        GetWindowText(item, buffer, _countof(buffer));
        c_Dialog->m_Load = buffer;
        c_Dialog->m_LoadLayout = true;
    }
    break;

    case IDC_PACKAGEOPTIONS_LOADSKINBROWSE_BUTTON:
    {
        WCHAR buffer[MAX_PATH];
        HWND item = GetDlgItem(m_Window, IDC_PACKAGEOPTIONS_LOADSKIN_EDIT);
        GetWindowText(item, buffer, _countof(buffer));

        OPENFILENAME ofn = { sizeof(OPENFILENAME) };
        ofn.Flags = OFN_FILEMUSTEXIST;
        ofn.FlagsEx = OFN_EX_NOPLACESBAR;
        ofn.lpstrFilter = L"Rainmeter skin file (.ini)\0*.ini";
        ofn.lpstrTitle = L"Select Rainmeter skin file";
        ofn.lpstrDefExt = L"ini";
        ofn.lpstrFile = buffer;
        ofn.nMaxFile = _countof(buffer);
        ofn.lpstrInitialDir = c_Dialog->m_SkinFolder.second.c_str();
        ofn.hwndOwner = c_Dialog->GetWindow();

        if (GetOpenFileName(&ofn))
        {
            // Make sure user didn't browse to some random folder
            if (_wcsnicmp(ofn.lpstrInitialDir, buffer, c_Dialog->m_SkinFolder.second.length()) == 0)
            {
                // Skip everything before actual skin folder
                const WCHAR* folderPath = buffer + c_Dialog->m_SkinFolder.second.length() - c_Dialog->m_SkinFolder.first.length() - 1;
                SetWindowText(item, folderPath);
                c_Dialog->m_Load = folderPath;
            }
        }
    }
    break;

    case IDC_PACKAGEOPTIONS_RAINMETERVERSION_EDIT:
        if (HIWORD(wParam) == EN_CHANGE)
        {
            WCHAR buffer[32];
            GetWindowText((HWND)lParam, buffer, _countof(buffer));

            // Get caret position
            DWORD sel = Edit_GetSel((HWND)lParam);

            // Only allow numbers and period
            WCHAR* version = buffer;
            while (*version)
            {
                if (iswdigit(*version) || *version == L'.')
                {
                    ++version;
                }
                else
                {
                    *version = L'\0';
                    SetWindowText((HWND)lParam, buffer);

                    // Reset caret position
                    Edit_SetSel((HWND)lParam, LOWORD(sel), HIWORD(sel));
                    break;
                }
            }

            c_Dialog->m_MinimumRainmeter = buffer;
        }
        break;

    case IDC_PACKAGEOPTIONS_WINDOWSVERSION_COMBO:
        if (HIWORD(wParam) == CBN_SELCHANGE)
        {
            int sel = ComboBox_GetCurSel((HWND)lParam);
            c_Dialog->m_MinimumWindows = g_OsNameVersions[sel].version;
        }
        break;

    default:
        return FALSE;
    }

    return TRUE;
}
Exemplo n.º 29
0
void CZRegHelper::ParseReg(wchar_t **arg,int num)
{
	wchar_t szApplication[MAX_PATH];
	DWORD cchLength = _countof(szApplication);
	QueryFullProcessImageName(GetCurrentProcess(), 0, szApplication, &cchLength);
	CString appPath;

	appPath.Format(L"%s",szApplication);
	if(2 == num)
	{
		if(0 == _wcsnicmp(arg[1],L"/reg",4) && wcslen(arg[1]) > 4)
		{
			CString para(arg[1]);
			para = para.Right(para.GetLength()-4);
			int index = 0;
			int last = 0;
			CString tmp;

			CString icoIndex ;
			icoIndex.Format(L"%s,0",appPath);
			while(-1 != (index = para.Find('|')))
			{
				tmp = para.Left(index);
				para = para.Right(para.GetLength() - index -1);
				if(0 == tmp.CompareNoCase(L"flac"))
				{					
					RegisterFileRelation(L".FLAC",appPath,L"ZLP.FLAC",icoIndex,L"FLAC");
				}
				else if(0 == tmp.CompareNoCase(L"ape"))
				{
					RegisterFileRelation(L".APE",appPath,L"ZLP.APE",icoIndex,L"APE");
				}
				else if(0 == tmp.CompareNoCase(L"wav"))
				{
					RegisterFileRelation(L".WAV",appPath,L"ZLP.WAV",icoIndex,L"WAV");
				}
				else if(0 == tmp.CompareNoCase(L"mp3"))
				{
					RegisterFileRelation(L".MP3",appPath,L"ZLP.MP3",icoIndex,L"MP3");
				}
				else if(0 == tmp.CompareNoCase(L"cue"))
				{
					RegisterFileRelation(L".CUE",appPath,L"ZLP.CUE",icoIndex,L"CUE");
				}
				else if(0 == tmp.CompareNoCase(L"ofr"))
				{
					RegisterFileRelation(L".OFR",appPath,L"ZLP.OFR",icoIndex,L"OFR");
				}
				else if(0 == tmp.CompareNoCase(L"ogg"))
				{
					RegisterFileRelation(L".OGG",appPath,L"ZLP.OGG",icoIndex,L"OGG");
				}
				else if(0 == tmp.CompareNoCase(L"tak"))
				{
					RegisterFileRelation(L".TAK",appPath,L"ZLP.TAK",icoIndex,L"TAK");
				}
				else if(0 == tmp.CompareNoCase(L"wv"))
				{
					RegisterFileRelation(L".WV",appPath,L"ZLP.WV",icoIndex,L"WV");
				}
				else if(0 == tmp.CompareNoCase(L"aac"))
				{
					RegisterFileRelation(L".AAC",appPath,L"ZLP.AAC",icoIndex,L"AAC");
				}
				else if(0 == tmp.CompareNoCase(L"m4a"))
				{
					RegisterFileRelation(L".M4A",appPath,L"ZLP.M4A",icoIndex,L"M4A");
				}
				else if(0 == tmp.CompareNoCase(L"tta"))
				{
					RegisterFileRelation(L".TTA",appPath,L"ZLP.TTA",icoIndex,L"TTA");
				}
				tmp.Empty();
			}
			tmp.Empty();
			while(-1!=(index = para.Find(',')))
			{
				tmp = para.Left(index);
				para = para.Right(para.GetLength() - index -1);
				if(0 == tmp.CompareNoCase(L"flac"))
				{					
					UnRegisterFileRelation(L".FLAC",L"ZLP.FLAC");
				}
				else if(0 == tmp.CompareNoCase(L"ape"))
				{
					UnRegisterFileRelation(L".APE",L"ZLP.APE");
				}
				else if(0 == tmp.CompareNoCase(L"wav"))
				{
					UnRegisterFileRelation(L".WAV",L"ZLP.WAV");
				}
				else if(0 == tmp.CompareNoCase(L"mp3"))
				{
					UnRegisterFileRelation(L".MP3",L"ZLP.MP3");
				}
				else if(0 == tmp.CompareNoCase(L"cue"))
				{
					UnRegisterFileRelation(L".CUE",L"ZLP.CUE");
				}
				else if(0 == tmp.CompareNoCase(L"ofr"))
				{
					UnRegisterFileRelation(L".OFR",L"ZLP.OFR");
				}
				else if(0 == tmp.CompareNoCase(L"ogg"))
				{
					UnRegisterFileRelation(L".OGG",L"ZLP.OGG");
				}
				else if(0 == tmp.CompareNoCase(L"tak"))
				{
					UnRegisterFileRelation(L".TAK",L"ZLP.TAK");
				}
				else if(0 == tmp.CompareNoCase(L"wv"))
				{
					UnRegisterFileRelation(L".WV",L"ZLP.WV");
				}
				else if(0 == tmp.CompareNoCase(L"aac"))
				{
					UnRegisterFileRelation(L".AAC",L"ZLP.AAC");
				}
				else if(0 == tmp.CompareNoCase(L"m4a"))
				{
					UnRegisterFileRelation(L".M4A",L"ZLP.M4A");
				}
				else if(0 == tmp.CompareNoCase(L"tta"))
				{
					UnRegisterFileRelation(L".TTA",L"ZLP.TTA");
				}
				tmp.Empty();
			}
			icoIndex.Empty();
			para.Empty();
			tmp.Empty();
			SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL);
			appPath.Empty();
		}
	}
}
Exemplo n.º 30
0
NTSTATUS
NTAPI
CmpOpenHiveFiles(IN PCUNICODE_STRING BaseName,
                 IN PCWSTR Extension OPTIONAL,
                 OUT PHANDLE Primary,
                 OUT PHANDLE Log,
                 OUT PULONG PrimaryDisposition,
                 OUT PULONG LogDisposition,
                 IN BOOLEAN CreateAllowed,
                 IN BOOLEAN MarkAsSystemHive,
                 IN BOOLEAN NoBuffering,
                 OUT PULONG ClusterSize OPTIONAL)
{
    HANDLE EventHandle;
    PKEVENT Event;
    NTSTATUS Status;
    UNICODE_STRING FullName, ExtensionName;
    PWCHAR NameBuffer;
    USHORT Length;
    OBJECT_ATTRIBUTES ObjectAttributes;
    IO_STATUS_BLOCK IoStatusBlock;
    ULONG AttributeFlags, ShareMode, DesiredAccess, CreateDisposition, IoFlags;
    USHORT CompressionState;
    FILE_STANDARD_INFORMATION FileInformation;
    FILE_FS_SIZE_INFORMATION FsSizeInformation;

    /* Create event */
    Status = CmpCreateEvent(NotificationEvent, &EventHandle, &Event);
    if (!NT_SUCCESS(Status)) return Status;

    /* Initialize the full name */
    RtlInitEmptyUnicodeString(&FullName, NULL, 0);
    Length = BaseName->Length;

    /* Check if we have an extension */
    if (Extension)
    {
        /* Update the name length */
        Length += (USHORT)wcslen(Extension) * sizeof(WCHAR) + sizeof(UNICODE_NULL);

        /* Allocate the buffer for the full name */
        NameBuffer = ExAllocatePoolWithTag(PagedPool, Length, TAG_CM);
        if (!NameBuffer)
        {
            /* Fail */
            ObDereferenceObject(Event);
            ZwClose(EventHandle);
            return STATUS_NO_MEMORY;
        }

        /* Build the full name */
        FullName.Buffer = NameBuffer;
        FullName.MaximumLength = Length;
        RtlAppendUnicodeStringToString(&FullName, BaseName);
    }
    else
    {
        /* The base name is the full name */
        FullName = *BaseName;
        NameBuffer = NULL;
    }

    /* Initialize the attributes */
    InitializeObjectAttributes(&ObjectAttributes,
                               &FullName,
                               OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
                               NULL,
                               NULL);

    /* Check if we can create the hive */
    if ((CreateAllowed) && !(CmpShareSystemHives))
    {
        /* Open only or create */
        CreateDisposition = FILE_OPEN_IF;
    }
    else
    {
        /* Open only */
        CreateDisposition = FILE_OPEN;
    }

    /* Setup the flags */
    // FIXME : FILE_OPEN_FOR_BACKUP_INTENT is unimplemented and breaks 3rd stage boot
    IoFlags = //FILE_OPEN_FOR_BACKUP_INTENT |
              FILE_NO_COMPRESSION |
              FILE_RANDOM_ACCESS |
              (NoBuffering ? FILE_NO_INTERMEDIATE_BUFFERING : 0);

    /* Set share and access modes */
    if ((CmpMiniNTBoot) && (CmpShareSystemHives))
    {
        /* We're on Live CD or otherwise sharing */
        DesiredAccess = FILE_READ_DATA;
        ShareMode = FILE_SHARE_READ;
    }
    else
    {
        /* We want to write exclusively */
        ShareMode = 0;
        DesiredAccess = FILE_READ_DATA | FILE_WRITE_DATA;
    }

    /* Default attributes */
    AttributeFlags = FILE_ATTRIBUTE_NORMAL;

    /* Now create the file */
    Status = ZwCreateFile(Primary,
                          DesiredAccess | SYNCHRONIZE,
                          &ObjectAttributes,
                          &IoStatusBlock,
                          NULL,
                          AttributeFlags,
                          ShareMode,
                          CreateDisposition,
                          FILE_SYNCHRONOUS_IO_NONALERT | IoFlags,
                          NULL,
                          0);
    /* Check if anything failed until now */
    if (!NT_SUCCESS(Status))
    {
        /* Close handles and free buffers */
        if (NameBuffer) ExFreePoolWithTag(NameBuffer, TAG_CM);
        ObDereferenceObject(Event);
        ZwClose(EventHandle);
        DPRINT1("ZwCreateFile failed : %lx.\n", Status);
        *Primary = NULL;
        return Status;
    }
                          
    if (MarkAsSystemHive)
    {
        /* We opened it, mark it as a system hive */
        Status = ZwFsControlFile(*Primary,
                                 EventHandle,
                                 NULL,
                                 NULL,
                                 &IoStatusBlock,
                                 FSCTL_MARK_AS_SYSTEM_HIVE,
                                 NULL,
                                 0,
                                 NULL,
                                 0);
        if (Status == STATUS_PENDING)
        {
            /* Wait for completion */
            KeWaitForSingleObject(Event,
                                  Executive,
                                  KernelMode,
                                  FALSE,
                                  NULL);
            Status = IoStatusBlock.Status;
        }

        /* If we don't support it, ignore the failure */
        if (Status == STATUS_INVALID_DEVICE_REQUEST) Status = STATUS_SUCCESS;

        if (!NT_SUCCESS(Status))
        {
            /* Close handles and free buffers */
            if (NameBuffer) ExFreePoolWithTag(NameBuffer, TAG_CM);
            ObDereferenceObject(Event);
            ZwClose(EventHandle);
            ZwClose(*Primary);
            *Primary = NULL;
            return Status;
        }
    }

    /* Disable compression */
    CompressionState = 0;
    Status = ZwFsControlFile(*Primary,
                             EventHandle,
                             NULL,
                             NULL,
                             &IoStatusBlock,
                             FSCTL_SET_COMPRESSION,
                             &CompressionState,
                             sizeof(CompressionState),
                             NULL,
                             0);
    if (Status == STATUS_PENDING)
    {
        /* Wait for completion */
        KeWaitForSingleObject(Event,
                              Executive,
                              KernelMode,
                              FALSE,
                              NULL);
    }

    /* Get the disposition */
    *PrimaryDisposition = (ULONG)IoStatusBlock.Information;
    if (IoStatusBlock.Information != FILE_CREATED)
    {
        /* Check how large the file is */
        Status = ZwQueryInformationFile(*Primary,
                                        &IoStatusBlock,
                                        &FileInformation,
                                        sizeof(FileInformation),
                                        FileStandardInformation);
        if (NT_SUCCESS(Status))
        {
            /* Check if it's 0 bytes */
            if (!FileInformation.EndOfFile.QuadPart)
            {
                /* Assume it's a new file */
                *PrimaryDisposition = FILE_CREATED;
            }
        }
    }

    /* Check if the caller wants cluster size returned */
    if (ClusterSize)
    {
        /* Query it */
        Status = ZwQueryVolumeInformationFile(*Primary,
                                              &IoStatusBlock,
                                              &FsSizeInformation,
                                              sizeof(FsSizeInformation),
                                              FileFsSizeInformation);
        if (!NT_SUCCESS(Status))
        {
            /* Close handles and free buffers */
            if (NameBuffer) ExFreePoolWithTag(NameBuffer, TAG_CM);
            ObDereferenceObject(Event);
            ZwClose(EventHandle);
            return Status;
        }

        /* Check if the sector size is invalid */
        if (FsSizeInformation.BytesPerSector > HBLOCK_SIZE)
        {
            /* Close handles and free buffers */
            if (NameBuffer) ExFreePoolWithTag(NameBuffer, TAG_CM);
            ObDereferenceObject(Event);
            ZwClose(EventHandle);
            return STATUS_CANNOT_LOAD_REGISTRY_FILE;
        }

        /* Return cluster size */
        *ClusterSize = max(1, FsSizeInformation.BytesPerSector / HSECTOR_SIZE);
    }

    /* Check if we don't need to create a log file */
    if (!Extension)
    {
        /* We're done, close handles */
        ObDereferenceObject(Event);
        ZwClose(EventHandle);
        return STATUS_SUCCESS;
    }

    /* Check if we can create the hive */
    CreateDisposition = CmpShareSystemHives ? FILE_OPEN : FILE_OPEN_IF;
    if (*PrimaryDisposition == FILE_CREATED)
    {
        /* Over-write the existing log file, since this is a new hive */
        CreateDisposition = FILE_SUPERSEDE;
    }

    /* Setup the name */
    RtlInitUnicodeString(&ExtensionName, Extension);
    RtlAppendUnicodeStringToString(&FullName, &ExtensionName);

    /* Initialize the attributes */
    InitializeObjectAttributes(&ObjectAttributes,
                               &FullName,
                               OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
                               NULL,
                               NULL);

    /* Setup the flags */
    IoFlags = FILE_NO_COMPRESSION | FILE_NO_INTERMEDIATE_BUFFERING;

    /* Check if this is a log file */
    if (!_wcsnicmp(Extension, L".log", 4))
    {
        /* Hide log files */
        AttributeFlags |= FILE_ATTRIBUTE_HIDDEN;
    }

    /* Now create the file */
    Status = ZwCreateFile(Log,
                          DesiredAccess,
                          &ObjectAttributes,
                          &IoStatusBlock,
                          NULL,
                          AttributeFlags,
                          ShareMode,
                          CreateDisposition,
                          IoFlags,
                          NULL,
                          0);
    if ((NT_SUCCESS(Status)) && (MarkAsSystemHive))
    {
        /* We opened it, mark it as a system hive */
        Status = ZwFsControlFile(*Log,
                                 EventHandle,
                                 NULL,
                                 NULL,
                                 &IoStatusBlock,
                                 FSCTL_MARK_AS_SYSTEM_HIVE,
                                 NULL,
                                 0,
                                 NULL,
                                 0);
        if (Status == STATUS_PENDING)
        {
            /* Wait for completion */
            KeWaitForSingleObject(Event,
                                  Executive,
                                  KernelMode,
                                  FALSE,
                                  NULL);
            Status = IoStatusBlock.Status;
        }

        /* If we don't support it, ignore the failure */
        if (Status == STATUS_INVALID_DEVICE_REQUEST) Status = STATUS_SUCCESS;

        /* If we failed, close the handle */
        if (!NT_SUCCESS(Status)) ZwClose(*Log);
    }

    /* Check if anything failed until now */
    if (!NT_SUCCESS(Status))
    {
        /* Clear the handle */
        *Log = NULL;
    }
    else
    {
        /* Disable compression */
        Status = ZwFsControlFile(*Log,
                                 EventHandle,
                                 NULL,
                                 NULL,
                                 &IoStatusBlock,
                                 FSCTL_SET_COMPRESSION,
                                 &CompressionState,
                                 sizeof(CompressionState),
                                 NULL,
                                 0);
        if (Status == STATUS_PENDING)
        {
            /* Wait for completion */
            KeWaitForSingleObject(Event,
                                  Executive,
                                  KernelMode,
                                  FALSE,
                                  NULL);
        }

        /* Return the disposition */
        *LogDisposition = (ULONG)IoStatusBlock.Information;
    }

    /* We're done, close handles and free buffers */
    if (NameBuffer) ExFreePoolWithTag(NameBuffer, TAG_CM);
    ObDereferenceObject(Event);
    ZwClose(EventHandle);
    return STATUS_SUCCESS;
}