Example #1
0
BOOL CFile::CreateFile(_In_ PCWSTR pFileName, DWORD desiredAccess,
    DWORD creationDisposition,
    DWORD sharedMode, _Inout_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD flagsAndAttributes, _Inout_opt_ HANDLE templateFileHandle)
{
    size_t fullPathLen = wcslen(pFileName);
    if (!_pFileName)
    {
        _pFileName = new (std::nothrow) WCHAR[ fullPathLen + 1 ];
    }
    if (!_pFileName)
    {
        return FALSE;
    }

    StringCchCopyN(_pFileName, fullPathLen + 1, pFileName, fullPathLen);

    _fileHandle = ::CreateFile(pFileName, desiredAccess, sharedMode,
        lpSecurityAttributes, creationDisposition, flagsAndAttributes, templateFileHandle);

    if (_fileHandle == INVALID_HANDLE_VALUE)
    {
        return FALSE;
    }

    _fileSize = ::GetFileSize(_fileHandle, NULL);

    return TRUE;
}
Example #2
0
/*****************************************************************************
static DWORD CreateChecksumFiles_OneFile(CONST HWND arrHwnd[ID_NUM_WINDOWS], CONST UINT uiMode, list<FILEINFO*> *finalList)
	arrHwnd			: (IN) array with window handles
	uiMode			: (IN) create MD5 or SFV files
	finalList		: (IN) pointer to list of fileinfo pointers on which the action is to be performed

Return Value:
returns NOERROR or GetLastError()

Notes:
- handles the situation if the user want one sfv/md5 file for whole directory tree
*****************************************************************************/
static DWORD CreateChecksumFiles_OneFile(CONST HWND arrHwnd[ID_NUM_WINDOWS], CONST UINT uiMode, list<FILEINFO*> *finalList, BOOL askForFilename)
{
	HANDLE hFile;
    TCHAR szFileOut[MAX_PATH_EX];
    TCHAR szDefaultDir[MAX_PATH_EX];
    UINT uiSameCharCount;
	DWORD dwResult;

    uiSameCharCount = FindCommonPrefix(finalList);
    StringCchCopyN(szDefaultDir, MAX_PATH_EX, finalList->front()->szFilename, uiSameCharCount);

    if(!GenerateFilename_OneFile(arrHwnd[ID_MAIN_WND], szDefaultDir, uiMode, szFileOut, askForFilename))
        return NOERROR;

	hFile = CreateFile(szFileOut, GENERIC_WRITE, 0, 0, CREATE_ALWAYS, 0, NULL);

	if(hFile == INVALID_HANDLE_VALUE)
		return GetLastError();

#ifdef UNICODE
    // we need a BOM if we are writing unicode
    if(!WriteCurrentBOM(hFile))
		return GetLastError();
#endif

	if( (uiMode == MODE_SFV) && g_program_options.bWinsfvComp){
		dwResult = WriteSfvHeader(hFile);
		if(dwResult != NOERROR){
			CloseHandle(hFile);
			return dwResult;
		}
	}

    if(g_program_options.bIncludeFileComments) {
        for(list<FILEINFO*>::iterator it=finalList->begin();it!=finalList->end();it++) {
            dwResult = WriteFileComment(hFile, (*it), uiSameCharCount);

		    if(dwResult != NOERROR){
			    CloseHandle(hFile);
			    return dwResult;
		    }
	    }
    }

	for(list<FILEINFO*>::iterator it=finalList->begin();it!=finalList->end();it++) {
        dwResult = WriteHashLine(hFile, (*it)->szFilename.GetString() + uiSameCharCount, (*it)->hashInfo[uiMode].szResult, uiMode == MODE_SFV);
		
		if(dwResult != NOERROR){
			CloseHandle(hFile);
			return dwResult;
		}
	}

	CloseHandle(hFile);

	return NOERROR;
}
Example #3
0
int GetSelectionText(HWND hWnd, LPTSTR lpString, int nMaxCount)
{
    DWORD dwStart = 0;
    DWORD dwEnd = 0;
    DWORD dwSize;
    HRESULT hResult;
    LPTSTR lpTemp;

    if (!lpString)
    {
        return 0;
    }

    SendMessage(hWnd, EM_GETSEL, (WPARAM)&dwStart, (LPARAM)&dwEnd);

    if (dwStart == dwEnd)
    {
        return 0;
    }

    dwSize = GetWindowTextLength(hWnd) + 1;
    lpTemp = HeapAlloc(GetProcessHeap(), 0, dwSize * sizeof(TCHAR));
    if (!lpTemp)
    {
        return 0;
    }

    dwSize = GetWindowText(hWnd, lpTemp, dwSize);

    if (!dwSize)
    {
        HeapFree(GetProcessHeap(), 0, lpTemp);
        return 0;
    }

    hResult = StringCchCopyN(lpString, nMaxCount, lpTemp + dwStart, dwEnd - dwStart);
    HeapFree(GetProcessHeap(), 0, lpTemp);

    switch (hResult)
    {
        case S_OK:
        {
            return dwEnd - dwStart;
        }

        case STRSAFE_E_INSUFFICIENT_BUFFER:
        {
            return nMaxCount - 1;
        }

        default:
        {
            return 0;
        }
    }
}
Example #4
0
/*!
	ASTなユニコード文字列を受け取って分解しつつページに入れる
	@param[in]	ptStr		分解対象文字列へのポインター
	@param[in]	cchSize		その文字列の文字数
	@param[in]	pfPageLoad	内容を入れるコールバック函数のアレ
	@return		UINT		作成した頁数
*/
UINT DocStringSplitAST( LPTSTR ptStr, INT cchSize, PAGELOAD pfPageLoad )
{
	LPTSTR	ptCaret;	//	読込開始・現在位置
	LPTSTR	ptStart;	//	セパレータの直前
	LPTSTR	ptEnd;
	UINT	iNumber;	//	通し番号カウント
	UINT	cchItem;
	BOOLEAN	bLast;
	TCHAR	atName[MAX_PATH];

	ptCaret = ptStr;	//	まずは最初から

	iNumber = 0;	//	通し番号0インデックス

	bLast = FALSE;



	do	//	とりあえず一番最初はptCaretは[AA]になってる
	{
		ptStart = NextLineW( ptCaret );	//	次の行からが本番

		ptCaret += 5;	//	[AA][
		cchItem = ptStart - ptCaret;	//	名前部分の文字数
		cchItem -= 3;	//	]rn

		ZeroMemory( atName, sizeof(atName) );	//	名前確保
		if( 0 < cchItem )	StringCchCopyN( atName, MAX_PATH, ptCaret, cchItem );

		ptCaret = ptStart;	//	本体部分

		ptEnd = StrStr( ptCaret, AST_SEPARATERW );	//	セパレータを探す
		//	この時点でptEndは次の[AA]をさしてる・もしくはNULL(最後のコマ)
		if( !ptEnd )	//	見つからなかったら=これが最後なら=NULL
		{
			ptEnd = ptStr + cchSize;	//	WCHARサイズで計算おk?
			bLast = TRUE;
		}
		cchItem = ptEnd - ptCaret;	//	WCHAR単位なので計算結果は文字数のようだ

		if( !(bLast) && 0 < cchItem )	//	最終頁でない場合は末端の改行分引く
		{
			cchItem -= CH_CRLF_CCH;
			ptCaret[cchItem] = 0;
		}

		pfPageLoad( atName, ptCaret, cchItem );

		iNumber++;

		ptCaret = ptEnd;

	}while( *ptCaret );	//	データ有る限りループで探す

	return iNumber;
}
Example #5
0
		//ms-help://MS.VSCC.v90/MS.MSDNQTR.v90.chs/memory/base/obtaining_a_file_name_from_a_file_handle.htm
		BOOL TinyFile::GetFileNameFromHandle(HANDLE hFile, LPTSTR pszFilename)
		{
			BOOL bSuccess = FALSE;
			HANDLE hFileMap;
			DWORD dwFileSizeHi = 0;
			DWORD dwFileSizeLo = ::GetFileSize(hFile, &dwFileSizeHi);
			if (dwFileSizeLo == 0 && dwFileSizeHi == 0) return FALSE;
			hFileMap = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, MAX_PATH, NULL);
			if (hFileMap)
			{
				void* pMapView = MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, 1);
				if (pMapView)
				{
					if (GetMappedFileName(GetCurrentProcess(), pMapView, pszFilename, MAX_PATH))
					{
						TCHAR szTemp[1024];
						szTemp[0] = '\0';
						if (GetLogicalDriveStrings(1024 - 1, szTemp))
						{
							TCHAR szName[MAX_PATH];
							TCHAR szDrive[3] = TEXT(" :");
							BOOL bFound = FALSE;
							TCHAR* p = szTemp;
							do
							{
								*szDrive = *p;
								if (QueryDosDevice(szDrive, szName, 1024))
								{
									UINT iNameSize = _tcslen(szName);
									if (iNameSize < MAX_PATH)
									{
										bFound = _tcsnicmp(pszFilename, szName, iNameSize) == 0;
										if (bFound)
										{
											TCHAR szTempFile[MAX_PATH];
											StringCchPrintf(szTempFile,
												MAX_PATH,
												TEXT("%s%s"),
												szDrive,
												pszFilename + iNameSize);
											StringCchCopyN(pszFilename, MAX_PATH + 1, szTempFile, _tcslen(szTempFile));
										}
									}
								}
								while (*p++);
							} while (!bFound && *p);
						}
					}
					bSuccess = TRUE;
					UnmapViewOfFile(pMapView);
				}
				CloseHandle(hFileMap);
			}
			return(bSuccess);
		}
void CDirectoryMonitor::CopyDirectoryChangeFileName(FILE_NOTIFY_INFORMATION *pfni,
TCHAR *szFileName,size_t iBufLen)
{
	#ifndef UNICODE
	nConverted = WideCharToMultiByte(CP_ACP,0,pfni->FileName,
		(pfni->FileNameLength / sizeof(pfni->FileName[0])) + 1,
		szFileName,iBufLen,NULL,NULL);

	szFileName[nConverted - 1] = '\0';
	#else
	/* FileNameLength is size in bytes NOT characters. */
	StringCchCopyN(szFileName,iBufLen,
		pfni->FileName,pfni->FileNameLength / sizeof(TCHAR));
	#endif
}
Example #7
0
/*****************************************************************************
BOOL GetCrcFromFilename(TCHAR szFilename[MAX_PATH], DWORD * pdwFoundCrc)
	szFilename		: (IN) string; assumed to be the szFilenameShort member of the
						   FILEINFO struct
	pdwFoundCrc		: (OUT) return value is TRUE this parameter is set to the found
							CRC32 as a DWORD

Return Value:
	returns TRUE if a CRC was found in the filename. Otherwise FALSE

Notes:
	- walks through a filename from the rear to the front.
	- if a ']' or ')' is found we check if 9 chars before is an '[' or '(' and if
	  there are 8 legal Hex characters in between (via IsLegalHexSymbol)
*****************************************************************************/
BOOL GetCrcFromFilename(CONST TCHAR szFilename[MAX_PATH], DWORD * pdwFoundCrc)
{
	size_t StringSize;
	INT iIndex;
	BOOL bFound;
	TCHAR szCrc[9];
	TCHAR szFileWithoutPath[MAX_PATH];

	StringCchCopy(szFileWithoutPath, MAX_PATH, GetFilenameWithoutPathPointer(szFilename));

	if(FAILED(StringCchLength(szFileWithoutPath, MAX_PATH, &StringSize)))
		return FALSE;

	if(StringSize == 0)
		return FALSE;
	
	iIndex = (int)StringSize;
	bFound = FALSE;
	do{
		--iIndex;
		if((szFileWithoutPath[iIndex] == TEXT(']')) || (szFileWithoutPath[iIndex] == TEXT(')')) )
		{
			if ((iIndex - 9) < 0)
				break;
			else{
				bFound = TRUE;
				if (! ((szFileWithoutPath[iIndex-9] == TEXT('[')) || (szFileWithoutPath[iIndex-9] == TEXT('(')) ) )
					bFound = FALSE;
				for(int i=1; i <= 8; ++i)
					if(! IsLegalHexSymbol(szFileWithoutPath[iIndex-i]))
						bFound = FALSE;
				if(bFound)
					iIndex -= 8;
			}
		}
	}
	while((iIndex > 0) && (!bFound));

	if(!bFound)
		return FALSE;
	
	StringCchCopyN(szCrc, 9, szFileWithoutPath + iIndex, 8);
	(*pdwFoundCrc) = HexToDword(szCrc, 8);

	return TRUE;
}
Example #8
0
//
// Description:
//  Given the service execution string, returns the portion of the string that
//  only contains the path to the YoNTMA executables (no arguments).
//
// Parameters:
//  pszServiceExecutionString - Contains the string used by the service to
//      execute the YoNTMA binary (includes binary path + command-line
//      arguments).
//
//  pszInstalledPath - On success, contains the path to where the YoNTMA binary
//      is installed on the system.
//
//  cchInstalledPath - The size of the pszInstalledPath buffer (in characters).
//
HRESULT ServiceExecutionStringToInstalledPath(__in PTSTR pszServiceExecutionString, __out PTSTR pszInstalledPath, __in size_t cchInstalledPath)
{
    HRESULT hr;
    PTSTR pszInstalledPathEnd;
    size_t cchToCopy;

    //
    // The path to the YoNTMA binary appears first in the service execution
    // string and is enclosed in quotes. Retrieve the string between the
    // two quotation marks.
    //

    if(pszServiceExecutionString[0] != '\"') {
        hr = E_INVALIDARG;
        goto cleanexit;
    }

    pszInstalledPathEnd = _tcschr(pszServiceExecutionString + 1, '\"');
    if(!pszInstalledPathEnd) {
        hr = E_INVALIDARG;
        goto cleanexit;
    }

    cchToCopy = (pszInstalledPathEnd - (pszServiceExecutionString + 1));
    
    hr = StringCchCopyN(pszInstalledPath,
                        cchInstalledPath,
                        pszServiceExecutionString + 1,
                        cchToCopy);
    if(HB_FAILED(hr)) {
        goto cleanexit;
    }

    hr = S_OK;

cleanexit:

    return hr;
}
Example #9
0
HRESULT  DbgUniqueProcessName(LPCTSTR inName, LPTSTR outName)
{
    HRESULT hr = S_OK;
    const TCHAR *pIn = inName;
    int dotPos = -1;

    //scan the input and record the last '.' position
    while (*pIn && (pIn - inName) < MAX_PATH)
    {
        if ( TEXT('.') == *pIn )
            dotPos = (int)(pIn-inName);
        ++pIn;
    }

    if (*pIn) //input should be zero-terminated within MAX_PATH
        return E_INVALIDARG;

    DWORD dwProcessId = GetCurrentProcessId();

    if (dotPos < 0) 
    {
        //no extension in the input, appending process id to the input
        hr = StringCchPrintf(outName, MAX_PATH, TEXT("%s_%d"), inName, dwProcessId);
    }
    else
    {
        TCHAR pathAndBasename[MAX_PATH] = {0};
        
        //there's an extension  - zero-terminate the path and basename first by copying
        hr = StringCchCopyN(pathAndBasename, MAX_PATH, inName, (size_t)dotPos);

        //re-combine path, basename and extension with processId appended to a basename
        if (SUCCEEDED(hr))
            hr = StringCchPrintf(outName, MAX_PATH, TEXT("%s_%d%s"), pathAndBasename, dwProcessId, inName + dotPos);
    }

    return hr;
}
Example #10
0
void k4_handle_wmnc_notify(k4_dlg_data * d,
                           WPARAM wParam,
                           LPARAM lParam) {
    switch(HIWORD(wParam)) {

    case WMNC_IDENTITY_CHANGE:
        k4_read_identity_data(d);
        k4_update_display(d, TRUE);
        break;

    case WMNC_CREDTEXT_LINK:
        {
            wchar_t wid[KHUI_MAXCCH_HTLINK_FIELD];
            wchar_t * wids;
            khui_htwnd_link * l;

            l = (khui_htwnd_link *) lParam;

            StringCchCopyN(wid, ARRAYLENGTH(wid), l->id, l->id_len);
            wids = wcschr(wid, L':');

            if (!wids)
                break;
            else
                wids++;

            if (!wcscmp(wids, L"Enable")) {
                d->k4_enabled = TRUE;

                k4_update_display(d, TRUE);
                khui_cw_enable_type(d->nc, credtype_id_krb4, TRUE);
            }
        }
        break;
    }
}
Example #11
0
HRESULT GetPathParentDirectory(__in PTSTR pszPath, __out PTSTR pszParentDirectory, __in size_t cchParentDirectory)
{
    HRESULT hr;
    size_t cchPath;
    PTSTR pszDirectoryEnd;
    size_t cchToCopy;

    cchPath = _tcsclen(pszPath);
    if(cchPath < 2) {
        hr = E_INVALIDARG;
        goto cleanexit;
    }

    //
    // Walk backwards in the string until we encounter a path separator
    // character. We start from cchPath - 2 to skip the NULL terminaor and to
    // ignore a possible trailing slash.
    //

    pszDirectoryEnd = &pszPath[cchPath - 2];
    while(pszDirectoryEnd > pszPath)  {
        if(*pszDirectoryEnd == '\\') {
            break;
        }
        pszDirectoryEnd--;
    }

    cchToCopy = pszDirectoryEnd - pszPath + 1;
    hr = StringCchCopyN(pszParentDirectory, cchParentDirectory, pszPath, cchToCopy);
    if(HB_FAILED(hr)) {
        goto cleanexit;
    }

cleanexit:
    return hr;
}
/* This function takes a handle, and provides the associated filename back */
BOOL GetFileNameFromHandle(HANDLE hFile, WCHAR* fName)
{
	BOOL bSuccess = FALSE; // Was this function successful?
	TCHAR pszFilename[MAX_PATH + 1]; // Holds filename once retrieved
	HANDLE hFileMap; // Handle used for the CreateFileMapping();

	/* Create file mapping */
	hFileMap = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL);

	if (hFileMap)
	{
		/* Map view of file */
		void* pMem = MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, 1);

		if (pMem)
		{
			/* At this point, we are able to retrieve the filename */
			if (GetMappedFileName(GetCurrentProcess(), pMem, pszFilename, MAX_PATH))
			{

				/* Now we want to make it into the friendly format with drive lettes etc */
				TCHAR szTemp[BUFSIZE];
				szTemp[0] = '\0';

				if (GetLogicalDriveStrings(BUFSIZE - 1, szTemp))
				{
					TCHAR szName[MAX_PATH];
					TCHAR szDrive[3] = TEXT(" :");
					BOOL bFound = FALSE;
					TCHAR* p = szTemp;

					do
					{
						// Copy the drive letter to the template string
						*szDrive = *p;

						// Look up each device name
						if (QueryDosDevice(szDrive, szName, MAX_PATH))
						{
							size_t uNameLen = _tcslen(szName);

							if (uNameLen < MAX_PATH)
							{
								bFound = _tcsnicmp(pszFilename, szName, uNameLen) == 0
									&& *(pszFilename + uNameLen) == _T('\\');

								if (bFound)
								{
									// Reconstruct pszFilename using szTempFile
									// Replace device path with DOS path
									TCHAR szTempFile[MAX_PATH];
									StringCchPrintf(szTempFile, MAX_PATH, TEXT("%s%s"), szDrive, pszFilename + uNameLen);
									StringCchCopyN(pszFilename, MAX_PATH + 1, szTempFile, _tcslen(szTempFile));
								}
							}
						}

						// Go to the next NULL character.
						while (*p++);
					} while (!bFound && *p); // end of string
				}
			}
			/* Function completed successfully */
			bSuccess = TRUE;
			UnmapViewOfFile(pMem);
		}

		CloseHandle(hFileMap);
	}
	else {
		CloseHandle(hFileMap);
		return bSuccess;
	}
	/* Copy the filename string into our _OUT_ variable */
	wcscpy_s(fName, MAX_PATH, pszFilename);
	return bSuccess;
}
Example #13
0
void RecursiveTraverseFindStd(__in LPSEARCH_PROGRRESS_INFO lpProgressInfo)
{
	if (lpProgressInfo == NULL)		return;
	
	WIN32_FIND_DATA FindFileData = { 0 };
	HANDLE hListFile = INVALID_HANDLE_VALUE;
	TCHAR szFilePath[MAX_PATH] = { 0 }, szFilePathNotMatch[MAX_PATH] = { 0 };
	//构造代表子目录和文件夹路径的字符串,使用通配符“*”
	StringCchCopy(szFilePath, MAX_PATH - 1, lpProgressInfo->m_szStartLocation);
	//注释的代码可以用于查找所有以“.txt结尾”的文件。
	//StringCchCat(szFilePath, "\\*.txt");
	StringCchCopyN(szFilePathNotMatch, MAX_PATH - 1, lpProgressInfo->m_szStartLocation, _tcslen(szFilePath));
	StringCchCat(szFilePath, MAX_PATH - _tcslen(szFilePath) - 1, _T("\\*"));
	
	// 如果收到了中断信号,立即返回
	if (WaitForSingleObject(g_hBrokenEvent, 10) == WAIT_OBJECT_0)
		return;

	//查找第一个文件/目录,获得查找句柄
	hListFile = FindFirstFile(szFilePath, &FindFileData);
	//判断句柄
	if (hListFile == INVALID_HANDLE_VALUE)
		return ;

	static TCHAR szMsg[nMSG_SIZE] = { 0 };		// 预置为静态的,不必每次递归都初始化和处理,提高效率
	do
	{
		// 不需要代表本级目录和上级目录的“.”和“..”
		if ((FindFileData.cFileName[0] == _T('.') && FindFileData.cFileName[1] == _T('\0')) ||
			(FindFileData.cFileName[0] == _T('.') && FindFileData.cFileName[1] == _T('.') && FindFileData.cFileName[2] == _T('\0')))
			continue;

		// 不管是目录还是文件,先按指定规则进行匹配
		g_clsMutex.Lock();
		g_nTotalView++;
		lpProgressInfo->m_nViewCount++;
		g_clsMutex.Unlock();
		for (std::vector<STRING>::iterator it = lpProgressInfo->m_vecSearchStrings.begin(); it != lpProgressInfo->m_vecSearchStrings.end(); it++)
		{
			if (_StrStrI(FindFileData.cFileName, it->c_str()))
			{
				FIND_DATA fd = { 0 };
				StringCchCopy(fd.m_szFilename, MAX_PATH - 1, FindFileData.cFileName);
				StringCchCopy(fd.m_szLocation, MAX_PATH - 1, lpProgressInfo->m_szStartLocation);
				FileTimeToSystemTime(&FindFileData.ftLastWriteTime, &fd.m_stFileDateAndTime);
				fd.m_dwFileSize = FindFileData.nFileSizeLow;
				g_clsMutex.Lock();
				g_vecCurrentFindData.push_back(fd);
				g_nTotalFound++;
				lpProgressInfo->m_nFoundCount++;
				StringCchPrintf(
					szMsg,
					nMSG_SIZE - 1,
					_T("正在搜索[%d/%d]%s"),
					g_nTotalFound,
					g_nTotalView,
					lpProgressInfo->m_szStartLocation);
				lpProgressInfo->m_Update(lpProgressInfo->m_lpDlg, &fd, NULL);
				g_clsMutex.Unlock();
				break;
			}
		}

		if (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
		{
			// 若是目录则递归调用此方法
			StringCchCopy(lpProgressInfo->m_szStartLocation, MAX_PATH - 1, szFilePathNotMatch);
			StringCchCat(lpProgressInfo->m_szStartLocation, MAX_PATH - 1, _T("\\"));
			StringCchCat(lpProgressInfo->m_szStartLocation, MAX_PATH - 1, FindFileData.cFileName);
			g_clsMutex.Lock();
			StringCchPrintf(
				szMsg,
				nMSG_SIZE - 1,
				_T("正在搜索[%d/%d]%s"),
				g_nTotalFound,
				g_nTotalView,
				lpProgressInfo->m_szStartLocation);
			lpProgressInfo->m_Update(lpProgressInfo->m_lpDlg, NULL, szMsg);
			g_clsMutex.Unlock();
			RecursiveTraverseFindStd(lpProgressInfo);
		}

		if (WaitForSingleObject(g_hBrokenEvent, 10) == WAIT_OBJECT_0)
			break;
	} while (FindNextFile(hListFile, &FindFileData));
	
	FindClose(hListFile);
	return;
}
Example #14
0
HRESULT CDIME::_HandleCandidateWorker(TfEditCookie ec, _In_ ITfContext *pContext)
{

	debugPrint(L"CDIME::_HandleCandidateWorker() \n");
    HRESULT hr = S_OK;
	CStringRange commitString, convertedString;
	CDIMEArray<CCandidateListItem> candidatePhraseList;	
	CStringRange lastChar;
	CStringRange notify;
	
    if (nullptr == _pUIPresenter)
    {
        goto Exit; //should not happen
    }
	
	const WCHAR* pCandidateString = nullptr;
	DWORD_PTR candidateLen = 0;
	BOOL arrayUsingSPCode =FALSE;

	if (!_IsComposing())
		_StartComposition(pContext);

	if (Global::imeMode == IME_MODE_ARRAY)// check if the _strokebuffer is array special code
	{
		candidateLen = _pCompositionProcessorEngine->CollectWordFromArraySpeicalCode(&pCandidateString);
		if(candidateLen) arrayUsingSPCode = TRUE;
	}
	candidateLen = 0;
	candidateLen = _pUIPresenter->_GetSelectedCandidateString(&pCandidateString);
	if (candidateLen == 0)
    {
		if(_candidateMode == CANDIDATE_WITH_NEXT_COMPOSITION || _candidateMode == CANDIDATE_PHRASE)
		{
			_HandleCancel(ec, pContext);
			goto Exit;
		}
		else
		{
			hr = S_FALSE;
			_HandleCancel(ec, pContext);
			DoBeep(BEEP_COMPOSITION_ERROR); //beep for no valid mapping found
			goto Exit;
		}
    }
	if (_pCompositionProcessorEngine->IsArrayShortCode() && candidateLen == 1 && *pCandidateString == 0x2394) // empty position in arry short code table.
	{
		hr = S_FALSE;
		if (Global::imeMode == IME_MODE_PHONETIC)
			DoBeep(BEEP_WARNING);
		else
		{
			if (CConfig::GetClearOnBeep()) _HandleCancel(ec, pContext);
			DoBeep(BEEP_COMPOSITION_ERROR); //beep for no valid mapping found
		}
		goto Exit;
	}
	
	
	StringCchCopy(_commitString, 1, L"\0");
	StringCchCatN(_commitString, MAX_COMMIT_LENGTH, pCandidateString, candidateLen);
	commitString.Set(_commitString, candidateLen);
	//_commitString = commitString;
	
	PWCHAR pwch = new (std::nothrow) WCHAR[2];  // pCandidateString will be destroyed after _detelteCanddiateList was called.
	if(candidateLen > 1)
	{	
		StringCchCopyN(pwch, 2, pCandidateString + candidateLen -1, 1); 
	}else // cnadidateLen ==1
	{
		StringCchCopyN(pwch, 2, pCandidateString, 1); 	
	}
	lastChar.Set(pwch, 1 );
	//-----------------do reverse conversion notify. We should not show notify in UI-less mode, thus cancel reverse conversion notify in UILess Mode
	if (!_IsUILessMode())
	{
		if (_pITfReverseConversion[Global::imeMode])
		{
			_AsyncReverseConversion(pContext); //asynchronized the reverse conversion with editsession for better perfomance
		}
		//-----------------or complete real key code when input with wildcard
		else if (_isCandidateWithWildcard)
		{
			const WCHAR* pCandidateKeyCode = nullptr;
			DWORD_PTR keyCodeLen = _pUIPresenter->_GetSelectedCandidateKeyCode(&pCandidateKeyCode);
			StringCchCopy(_commitKeyCode, 1, L"\0");
			StringCchCatN(_commitKeyCode, MAX_KEY_LENGTH, pCandidateKeyCode, keyCodeLen);
			CStringRange commitKeyCode, convertedKeyCode;
			_pCompositionProcessorEngine->GetReadingString(&convertedKeyCode, NULL, &commitKeyCode.Set(_commitKeyCode, wcslen(_commitKeyCode)));
			_pUIPresenter->ShowNotifyText(&convertedKeyCode);
		}

	}
	//-----------------do  array spcial code notify. We should not show notify in UI-less mode, thus cancel forceSP mode in UILess Mode---
	BOOL ArraySPFound = FALSE;            
	if(Global::imeMode == IME_MODE_ARRAY && !_IsUILessMode()  && !arrayUsingSPCode && (CConfig::GetArrayForceSP() || CConfig::GetArrayNotifySP()))
	{
		CStringRange specialCode;
		CStringRange notifyText;
		ArraySPFound = _pCompositionProcessorEngine->GetArraySpeicalCodeFromConvertedText(&commitString, &specialCode); 
		if(specialCode.Get())
			_pUIPresenter->ShowNotifyText(&specialCode);
	}
	convertedString = commitString;
	//----------------- do TC to SC covert if required----------------------------------------------------------------------------------
	if(CConfig::GetDoHanConvert())
	{
		_pCompositionProcessorEngine->GetSCFromTC(&commitString, &convertedString);
	}
	//----------------- commit the selected string  ------------------------------------------------------------------------------------ 
	if(Global::imeMode == IME_MODE_ARRAY && !_IsUILessMode()  && !arrayUsingSPCode && CConfig::GetArrayForceSP() &&  ArraySPFound )
	{
		_HandleCancel(ec, pContext);
		DoBeep(BEEP_WARNING);
		return hr;
	}
	else
	{
		hr = _AddComposingAndChar(ec, pContext, &convertedString);
		if (FAILED(hr))	return hr;
		// Do not send _endcandidatelist (or handleComplete) here to avoid cand dissapear in win8 metro
		_HandleComplete(ec,pContext);
	}
	//-----------------do accociated phrase (make phrase)--------------------------------------------------------------------------------
	if (CConfig::GetMakePhrase())
	{
		_pCompositionProcessorEngine->GetCandidateStringInConverted(lastChar, &candidatePhraseList);


		// We have a candidate list if candidatePhraseList.Cnt is not 0
		// If we are showing reverse conversion, use UIPresenter

		if (candidatePhraseList.Count())
		{
			CStringRange emptyComposition;
			if (!_IsComposing())
				_StartComposition(pContext);  //StartCandidateList require a valid selection from a valid pComposition to determine the location to show the candidate window
			_AddComposingAndChar(ec, pContext, &emptyComposition.Set(L" ",1)); 

			_pUIPresenter->_ClearCandidateList();
			_pUIPresenter->_SetCandidateTextColor(CConfig::GetPhraseColor(), CConfig::GetItemBGColor());    // Text color is green
			_pUIPresenter->_SetCandidateSelectedTextColor(CConfig::GetSelectedColor(), CConfig::GetSelectedBGColor());    
			_pUIPresenter->_SetCandidateNumberColor(CConfig::GetNumberColor(), CConfig::GetItemBGColor());    
			_pUIPresenter->_SetCandidateFillColor(CConfig::GetItemBGColor());//(HBRUSH)(COLOR_WINDOW+1));    // Background color is window
			_pUIPresenter->_SetCandidateText(&candidatePhraseList, _pCompositionProcessorEngine->GetCandidateListIndexRange(),
				TRUE, _pCompositionProcessorEngine->GetCandidateWindowWidth());
			_pUIPresenter->_SetCandidateSelection(-1, FALSE); // set selected index to -1 if showing phrase candidates
			_candidateMode = CANDIDATE_PHRASE;
			_isCandidateWithWildcard = FALSE;	
			
		}
		else
		{   //cancel the composition if the phrase lookup return 0 results
			_HandleCancel(ec,pContext);
		}


	}
	else
		_DeleteCandidateList(TRUE, pContext); // endCanddiateUI if not doing associated phrase.
		
Exit:
    return hr;
}
Example #15
0
/// Function name  : findNextXMLToken
// Description     : Retrieve the next XML token from an XML string using an XML tokeniser
// 
// XML_TOKENISER*  pOutput : [in/out] XML Tokeniser containing the input string. On output this will contain the next token.
// ERROR_STACK*    &pError : [out]    New Error message, if any
// 
// Return Value   : FALSE if there are no more tokens. 
///           NOTE: This function does not return FALSE if there is an error, you must check 'pError' for that.
// 
BOOL  findNextXMLToken(XML_TOKENISER*  pOutput, ERROR_STACK*  &pError)
{
   CONST TCHAR  *szTokenEnd,     // Marks the end of the token
                *szTokenStart;   // Marks the beginning of the token

   TRY
   {
      // Prepare
      szTokenStart = pOutput->szNextToken;
      pError       = NULL;

      /// [NO MORE TOKENS] Return FALSE
      if (!szTokenStart OR !szTokenStart[0])
      {
         pOutput->szText[0] = NULL;
         pOutput->iCount = NULL;
         return FALSE;
      }

      // Determine whether token is a tag or not
      pOutput->eType = (szTokenStart[0] == '<' ? XTT_OPENING_TAG : XTT_TEXT);

      // [CHECK] Is this a comment tag?
      if (utilCompareStringN(szTokenStart, "<!--", 4))
      {
         /// [COMMENT] Search for the closing comment brace
         if (szTokenEnd = utilFindSubString(&szTokenStart[3], "-->"))
         {
            pOutput->eType = XTT_COMMENT_TAG;
            szTokenEnd += 2;  // Position 'TokenEnd' at the '>' character
         }
         else
            // [ERROR] "An unclosed <%s> tag was detected in the attached XML snippet from line %d of '%s'"
            pError = generateDualError(HERE(IDS_XML_UNCLOSED_OPENING_TAG), TEXT("comment"), pOutput->iLineNumber, pOutput->szFileName);
      }
      // [CHECK] Is this a character-data block?
      else if (utilCompareStringN(szTokenStart, "<![CDATA[", 9))
      {
         /// [CHARACTER DATA] Search for the closing character data brace
         if (szTokenEnd = utilFindSubString(&szTokenStart[3], "]]>"))
         {
            pOutput->eType = XTT_COMMENT_TAG;
            szTokenEnd += 2;  // Position 'TokenEnd' at the '>' character
         }
         else
            // [ERROR] "An unclosed <%s> tag was detected in the attached XML snippet from line %d of '%s'"
            pError = generateDualError(HERE(IDS_XML_UNCLOSED_OPENING_TAG), TEXT("!CDATA"), pOutput->iLineNumber, pOutput->szFileName);
      }
      else
         /// [NON-COMMENT] Search for closing tag (or an illegal opening tag)
         szTokenEnd = utilFindCharacterInSet(&szTokenStart[1], "<>");
      
      // [NON-FINAL TOKEN]
      if (!pError AND szTokenEnd)
      {
         // Examine token type
         switch (pOutput->eType)
         {
         /// [TAG] Determine tag type and extract without the angle brackets
         case XTT_OPENING_TAG:
            // [CHECK] Ensure tags finish with '>'
            if (szTokenEnd[0] == '<')
            {  
               // [ERROR] "An unexpected opening tag '<' character was detected in the attached XML snippet from line %d of '%s'"
               pError = generateDualError(HERE(IDS_XML_UNEXPECTED_OPENING_BRACKET), pOutput->iLineNumber, pOutput->szFileName);
               break;
            }
            
            /// Identify tag type
            // [CLOSING] Indicated by the tag starting with '</'
            if (szTokenStart[1] == '/')
               pOutput->eType = XTT_CLOSING_TAG;
            // [SELF CLOSING] Indicated by the tag ending with '/>'
            else if (szTokenEnd[-1] == '/')
               pOutput->eType = XTT_SELF_CLOSING_TAG;
            // [COMMENT] Indicated by the tag starting with '<!'
            else if (szTokenStart[1] == '!')
               pOutput->eType = XTT_COMMENT_TAG;
            // [SCHEMA] Indicated by the tag starting with '<?'
            else if (szTokenStart[1] == '?')
               pOutput->eType = XTT_SCHEMA_TAG;

            // Fall through...

         /// [COMMENT TAG] Already identified, just copy the text
         case XTT_COMMENT_TAG:
            /// Copy and measure tag (without the special characters)
            switch (pOutput->eType)
            {
            /// [OPENING TAG] Copy without < and >
            case XTT_OPENING_TAG:
               pOutput->iCount = max(0, szTokenEnd - szTokenStart - 1);
               StringCchCopyN(pOutput->szText, MAX_STRING, &szTokenStart[1], pOutput->iCount);
               break;
            /// [CLOSING TAG] Copy without </ and >
            case XTT_CLOSING_TAG:
               pOutput->iCount = max(0, szTokenEnd - szTokenStart - 2);
               StringCchCopyN(pOutput->szText, MAX_STRING, &szTokenStart[2], pOutput->iCount);
               break;
            /// [SELF CLOSING TAG] Copy with < and />
            case XTT_SELF_CLOSING_TAG:
               pOutput->iCount = max(0, szTokenEnd - szTokenStart - 2);
               StringCchCopyN(pOutput->szText, MAX_STRING, &szTokenStart[1], pOutput->iCount);
               break;
            /// [COMMENT TAG] Copy without <!-- and -->
            case XTT_COMMENT_TAG:
               pOutput->iCount = max(0, szTokenEnd - szTokenStart - 6);
               StringCchCopyN(pOutput->szText, MAX_STRING, &szTokenStart[4], pOutput->iCount);
               break;
            /// [SCHEMA TAG] Copy without <? and ?>
            case XTT_SCHEMA_TAG:
               pOutput->iCount = max(0, szTokenEnd - szTokenStart - 3);
               StringCchCopyN(pOutput->szText, MAX_STRING, &szTokenStart[2], pOutput->iCount);
               break;
            }

            // Set 'next token' as the character beyond the end of the tag
            pOutput->szNextToken = &szTokenEnd[1];
            break;

         /// [TEXT] Extract tag and identify whitespace 
         case XTT_TEXT:
   #ifdef BUG_FIX
            // [CHECK] Ensure text finishes with '<'
            if (szTokenEnd[0] == '>')
            {  
               // [ERROR] "An unexpected closing tag '>' character was detected in the attached XML snippet from line %d of '%s'"
               pError = generateDualError(HERE(IDS_XML_UNEXPECTED_CLOSING_BRACKET), pOutput->iLineNumber, pOutput->szFileName);
               attachXMLToError(pError, szTokenStart);
               break;
            }
   #endif
            // [CHECK] Ensure text finishes with '<'
            if (szTokenEnd[0] == '>')                    /// [FIX] BUG:002 'You receieve multiple 'an unexpected close tag was detected' errors when loading scripts created by eXscriptor for the first time'
            {  
               //// [ERROR] "An unexpected closing tag '>' character was detected in the attached XML snippet from line %d of '%s'"
               //pError = generateDualWarning(HERE(IDS_XML_UNEXPECTED_CLOSING_BRACKET), pOutput->iLineNumber, pOutput->szFileName);

               // Search for next opening character
               szTokenEnd = utilFindCharacter(&szTokenEnd[1], '<');
               ASSERT(szTokenEnd);            
            }

            // Measure text
            pOutput->iCount = (szTokenEnd - szTokenStart);

            /// [CHECK] Attempt to copy string
            if (pOutput->iCount >= MAX_STRING OR StringCchCopyN(pOutput->szText, MAX_STRING, szTokenStart, pOutput->iCount) != S_OK)
               // [ERROR] "A string exceeding 32,768 characters was detected on line %d of '%s', this is not supported by X-Studio"
               pError = generateDualError(HERE(IDS_XML_TEXT_EXCEEDS_BUFFER), pOutput->iLineNumber, pOutput->szFileName);

            // [CHECK] Check for character entities
            else if (utilFindSubString(pOutput->szText, "&#"))
               // [FOUND] Replace entities
               pOutput->iCount = performXMLCharacterEntityReplacement(pOutput->szText, pOutput->iCount);
            
            // Set 'next token' as the start of the next tag
            pOutput->szNextToken = szTokenEnd;
            break;
         }
      }
      // [FINAL TOKEN] Set the next token to NULL
      else
      {
         // Set next token to NULL
         pOutput->szNextToken = NULL;

         /// Extract final token text
         StringCchCopy(pOutput->szText, MAX_STRING, szTokenStart);
         pOutput->iCount = lstrlen(pOutput->szText);
      }

      /// [WHITESPACE] Determine whether text is whitespace
      if (pOutput->eType == XTT_TEXT AND isStringWhitespace(pOutput->szText))
         pOutput->eType = XTT_WHITESPACE;
      
      /// [LINE NUMBER] Calculate the new line number
      pOutput->iLineNumber += calculateCharacterCountInString(pOutput->szText, '\n');     // [FIX] BUG:1018 'Errors produced by findNextXMLToken() don't have a Line number in any of the messages'

      /// [NEW TAG] Create node from token
      if (!pOutput->bBlocking AND (pOutput->eType == XTT_OPENING_TAG OR pOutput->eType == XTT_SELF_CLOSING_TAG))
         pOutput->pNode = createXMLTreeNode(pOutput);

      // [ERROR] Append XML snippets to all errors
      if (pError)
      {
         // Append XML snippet
         generateOutputTextFromError(pError);
         attachXMLToError(pError, szTokenStart, (szTokenStart - pOutput->szSource));

         // Skip beyond token
         pOutput->szNextToken = &szTokenEnd[1];
         // Zero any existing token
         pOutput->szText[0] = NULL;
         pOutput->iCount    = 0;
      }

      // Return TRUE to indicate there are more tokens, even if an error occurred
      return TRUE;
   }
   CATCH0("Unable to retrieve next token");
   return FALSE;
}
HRESULT STDMETHODCALLTYPE TextAreaTextRange::GetText(_In_ int maxLength, _Out_ BSTR * retVal)
{
    if (!IsWindow(_hwnd))
    {
        return UIA_E_ELEMENTNOTAVAILABLE;
    }

    HRESULT hr = S_OK;
    int builderSize;
    PWSTR textBuilder;
    if (maxLength >= 0)
    {
        builderSize = maxLength + 1;
    }
    else
    {
        builderSize = 0;
        EndPoint current = _range.begin;
        while (QuickCompareEndpoints(current, _range.end) < 0)
        {
            if (current.line < _range.end.line)
            {
                int length = _control->GetLineLength(current.line);
                // Add 1 for the implied newline
                builderSize += length - current.character + 1;
                current.line++;
                current.character = 0;
            }
            else
            {
                builderSize += _range.end.character - current.character;
                current.character = _range.end.character;
            }
        }

        // Always allow space for the final string terminator.
        builderSize++;
    }

    textBuilder = new WCHAR[builderSize];
    if (textBuilder != NULL)
    {
        int writePos = 0;
        EndPoint current = _range.begin;
        while (QuickCompareEndpoints(current, _range.end) < 0 && writePos < (builderSize - 1))
        {
            int copyLength = 0;
            EndPoint next;
            bool trailingNewline = false;
            if (current.line < _range.end.line)
            {
                int length = _control->GetLineLength(current.line);
                // Add 1 for the implied newline
                copyLength = length - current.character;
                trailingNewline = true;
                next.line = current.line + 1;
                next.character = 0;
            }
            else
            {
                copyLength = _range.end.character - current.character;
                next.line = current.line;
                next.character = _range.end.character;
            }

            if (writePos + copyLength >= (builderSize - 1))
            {
                copyLength = (builderSize - 1) - writePos;
            }

            TextLine *textLine = _control->GetLine(current.line);
            StringCchCopyN(&textBuilder[writePos], copyLength + 1, &textLine->text[current.character], copyLength);
            writePos += copyLength;
            current = next;

            if (trailingNewline && writePos < (builderSize - 1))
            {
                textBuilder[writePos++] = '\n';
            }
        }
        // Ensure the string is null-terminated
        textBuilder[writePos] = '\0';

        *retVal = SysAllocString(textBuilder);
        if (*retVal == NULL)
        {
            hr = E_OUTOFMEMORY;
        }

        delete [] textBuilder;
    }
    else
    {
        hr = E_OUTOFMEMORY;
    }
        
    return hr;
}
Example #17
0
void k4_handle_wmnc_notify(k4_dlg_data * d,
                           WPARAM wParam,
                           LPARAM lParam) {
    switch(HIWORD(wParam)) {
    case WMNC_UPDATE_CREDTEXT:
        {
            if (d->nct->credtext) {
                PFREE(d->nct->credtext);
                d->nct->credtext = NULL;
            }

            if (d->nc->n_identities > 0 &&
                d->nc->identities[0]) {

                khm_int32 flags = 0;
                wchar_t idname[KCDB_IDENT_MAXCCH_NAME];
                wchar_t * atsign;
                wchar_t * realm;
                khm_size cb;

                kcdb_identity_get_flags(d->nc->identities[0], &flags);

                if (!(flags & KCDB_IDENT_FLAG_VALID)) {
                    break;
                }

                cb = sizeof(idname);
                kcdb_identity_get_name(d->nc->identities[0], idname,
                                       &cb);

                atsign = wcsrchr(idname, L'@');

                if (atsign == NULL || !atsign[1])
                    break;

                realm = ++atsign;

                if (d->k4_enabled) {
                    wchar_t wmethod[128];
                    wchar_t wfmt[128];
                    wchar_t wct[512];

                    LoadString(hResModule, IDS_CT_TGTFOR,
                               wfmt, ARRAYLENGTH(wfmt));

                    if (d->method == K4_METHOD_AUTO)
                        LoadString(hResModule, IDS_METHOD_AUTO, wmethod,
                                   ARRAYLENGTH(wmethod));
                    else if (d->method == K4_METHOD_PASSWORD)
                        LoadString(hResModule, IDS_METHOD_PWD, wmethod,
                                   ARRAYLENGTH(wmethod));
                    else if (d->method == K4_METHOD_K524)
                        LoadString(hResModule, IDS_METHOD_K524, wmethod,
                                   ARRAYLENGTH(wmethod));
                    else {
                        assert(FALSE);
                    }

                    StringCbPrintf(wct, sizeof(wct), wfmt, realm, wmethod);

                    StringCbLength(wct, sizeof(wct), &cb);
                    cb += sizeof(wchar_t);

                    d->nct->credtext = PMALLOC(cb);

                    StringCbCopy(d->nct->credtext, cb, wct);
                } else {
                    wchar_t wct[256];

                    LoadString(hResModule, IDS_CT_DISABLED,
                               wct, ARRAYLENGTH(wct));

                    StringCbLength(wct, sizeof(wct), &cb);
                    cb += sizeof(wchar_t);

                    d->nct->credtext = PMALLOC(cb);

                    StringCbCopy(d->nct->credtext, cb, wct);
                }
            }
            /* no identities were selected.  it is not the
               responsibility of krb4 to complain about this. */
        }
        break;

    case WMNC_IDENTITY_CHANGE:
        k4_read_identity_data(d);
        k4_update_display(d, TRUE);
        break;

    case WMNC_CREDTEXT_LINK:
        {
            wchar_t wid[KHUI_MAXCCH_HTLINK_FIELD];
            wchar_t * wids;
            khui_htwnd_link * l;

            l = (khui_htwnd_link *) lParam;

            StringCchCopyN(wid, ARRAYLENGTH(wid), l->id, l->id_len);
            wids = wcschr(wid, L':');

            if (!wids)
                break;
            else
                wids++;

            if (!wcscmp(wids, L"Enable")) {
                d->k4_enabled = TRUE;

                k4_update_display(d, TRUE);
                khui_cw_enable_type(d->nc, credtype_id_krb4, TRUE);
            }
        }
        break;
    }
}
Example #18
0
k5_kinit_task *
k5_kinit_task_create(khui_new_creds * nc)
{
    k5_kinit_task * kt;
    k5_dlg_data   * d;

    wchar_t idname[KCDB_IDENT_MAXCCH_NAME];
    khm_size cbbuf;

    LPNETID_DLGINFO pdlginfo;
    khui_action_context * pctx = NULL;

    khm_handle hsub = NULL;

    khui_cw_find_type(nc, credtype_id_krb5, (khui_new_creds_by_type **) &d);
    if (!d)
	return NULL;

    kt = (k5_kinit_task *) PMALLOC(sizeof(*kt));
    memset(kt, 0, sizeof(*kt));
    kt->magic = K5_KINIT_TASK_MAGIC;
    kt->nc = nc;
    kt->dlg_data = d;
    kt->nct = &d->nct;
    kt->context = 0;

    khui_cw_get_primary_id(nc, &kt->identity);
    cbbuf = sizeof(idname);
    kcdb_identity_get_name(kt->identity, idname, &cbbuf);
    cbbuf = (cbbuf * sizeof(char)) / sizeof(wchar_t);

    kt->principal = PMALLOC(cbbuf);
    UnicodeStrToAnsi(kt->principal, cbbuf, idname);
    kt->password = NULL;
    kt->params = d->params;
    kt->params.lifetime = (krb5_deltat) d->tc_lifetime.current;
    kt->params.renew_life = (krb5_deltat) d->tc_renew.current;

    /* if we have external parameters, we should use them as well */
    pctx = khui_cw_get_ctx(nc);
    if (pctx && pctx->cb_vparam == sizeof(NETID_DLGINFO) &&
        (pdlginfo = pctx->vparam) != NULL &&
        pdlginfo->size == NETID_DLGINFO_V1_SZ) {

        wchar_t * t;
        size_t size;

        if (pdlginfo->in.ccache[0] &&
            SUCCEEDED(StringCchLength(pdlginfo->in.ccache,
                                      NETID_CCACHE_NAME_SZ,
                                      &size))) {
            kt->ccache = PMALLOC(sizeof(char) * (size + 1));
            UnicodeStrToAnsi(kt->ccache, size + 1,
                             pdlginfo->in.ccache);

            /* this is the same as the output cache */

            StringCbCopy(pdlginfo->out.ccache, sizeof(pdlginfo->out.ccache),
                         pdlginfo->in.ccache);
        } else {
            wchar_t ccache[KRB5_MAXCCH_CCNAME];

            size = sizeof(ccache);

            khm_krb5_get_identity_default_ccache(kt->identity, ccache, &size);

            StringCbCopy(pdlginfo->out.ccache, sizeof(pdlginfo->out.ccache),
                         ccache);
        }

        t = khm_get_realm_from_princ(idname);

        if (t) {
            StringCbCopy(pdlginfo->out.realm,
                         sizeof(pdlginfo->out.realm),
                         t);

            if ((t - idname) > 1) {
                StringCchCopyN(pdlginfo->out.username,
                               ARRAYLENGTH(pdlginfo->out.username),
                               idname,
                               (t - idname) - 1);
            } else {
                StringCbCopy(pdlginfo->out.username,
                             sizeof(pdlginfo->out.username),
                             L"");
            }
        } else {
            StringCbCopy(pdlginfo->out.username,
                         sizeof(pdlginfo->out.username),
                         idname);
            StringCbCopy(pdlginfo->out.realm,
                         sizeof(pdlginfo->out.realm),
                         L"");
        }
    }

    kt->state = K5_KINIT_STATE_PREP;
    InitializeCriticalSection(&kt->cs);
    kt->h_task_wait = CreateEvent(NULL, FALSE, FALSE, NULL);
    kt->h_parent_wait = CreateEvent(NULL, FALSE, FALSE, NULL);

    kt->refcount = 2;           /* One hold for the caller, one hold
                                   for the thread */

    kmq_create_subscription(k5_msg_callback, &hsub);

    kt->task = task_create(NULL, 32 * 4096, kinit_task_proc, kt, hsub, 0);

    return kt;
}
Example #19
0
HRESULT IsNetworkSecure(__in __opt LPCTSTR pszSSID, BOOL fUse8021x,
        DWORD dwAuthentication, DWORD dwEncryption,
        __out __opt LPTSTR *ppszSSIDDisplay, DWORD cxpExtent, BOOL fEscapeHtml)
{
    HRESULT hr = S_FALSE;
    BOOL fSecure;
    HDC hdcScreen = NULL;

    // if 802.1x or NOT open and unencrypted then it's secure
    fSecure = fUse8021x || !( (Ndis802_11AuthModeOpen == dwAuthentication) &&
        !CWZCManagerWireless::IsEncrypted(dwEncryption) );
    
    hr = fSecure ? S_OK : S_FALSE;

    if (NULL != ppszSSIDDisplay)
    {
        TCHAR szSSIDEllipsized[MAX_SSID_LEN + ARRAYSIZE(c_szEllipsis)];
        LPVOID rgpvArgs[] = {szSSIDEllipsized};
        int cchTry, cchSSID, cchFit;
        SIZE  size;

        CPREx(pszSSID, E_INVALIDARG);

        // caller wants the string

        *ppszSSIDDisplay = NULL;
        hdcScreen = GetDC(NULL);
        cchSSID = lstrlen(pszSSID);

        // work backwards from the full string less one char
        for (cchTry = cchSSID; cchTry >= 0; cchTry--)
        {
            hr = StringCchCopyN(szSSIDEllipsized,
                ARRAYSIZE(szSSIDEllipsized), pszSSID, cchTry);
            CHR(hr);
            if (cchTry < cchSSID)
            {
                // second and successive times, ellipsize
                hr = StringCchCat(szSSIDEllipsized,
                    ARRAYSIZE(szSSIDEllipsized), c_szEllipsis);
                VHR(hr);
            }
            LocalFree(*ppszSSIDDisplay);

            CWR(FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
                FORMAT_MESSAGE_FROM_STRING | FORMAT_MESSAGE_ARGUMENT_ARRAY,
                (LPTSTR)LoadString(HINST_RESDLL,
                fSecure ? IDS_WZC_NETSEL_FORMAT_SECURE_NETWORK :
                IDS_WZC_NETSEL_FORMAT_OPEN_NETWORK, NULL, 0), 0, 0,
                (LPTSTR)ppszSSIDDisplay, 0, (va_list *)rgpvArgs));
            VBR(GetTextExtentExPoint(hdcScreen, *ppszSSIDDisplay,
                lstrlen(*ppszSSIDDisplay), cxpExtent, &cchFit, NULL,
                &size));
            // need to continue lopping?
            if (size.cx <= (int)cxpExtent)
            {
                if (fEscapeHtml)
                {
                    // Create the escaped version of the SSID
                    hr = EscapeHtmlString(szSSIDEllipsized, ARRAYSIZE(szSSIDEllipsized));
                    CHR(hr);

                    CWR(FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
                        FORMAT_MESSAGE_FROM_STRING | FORMAT_MESSAGE_ARGUMENT_ARRAY,
                        (LPTSTR)LoadString(HINST_RESDLL,
                        fSecure ? IDS_WZC_NETSEL_FORMAT_SECURE_NETWORK :
                        IDS_WZC_NETSEL_FORMAT_OPEN_NETWORK, NULL, 0), 0, 0,
                        (LPTSTR)ppszSSIDDisplay, 0, (va_list *)rgpvArgs));
                }
                break;
            }
            
        }
        ASSERT(cchTry >= 0);

    }

Error:
    if (FAILED(hr) && (NULL != ppszSSIDDisplay) && (NULL != *ppszSSIDDisplay))
    {
        LocalFree(*ppszSSIDDisplay);
        *ppszSSIDDisplay = NULL;
    }

    if (NULL != hdcScreen)
    {
        ReleaseDC(NULL, hdcScreen);
    }

    return hr;
}
Example #20
0
/// Function name  : findNextSubStringSimple
// Description     : Searches for the next SubString in a GameString without resolving sub-strings
// 
// CONST GAME_STRING*  pGameString    : [in]     GameString currently being resolved
// SUBSTRING*          pSubString     : [in/out] Contains the resolved SubString on return, if successful
// 
// Return Value   : TRUE if substring was found, FALSE if there were no more substrings
// 
BearScriptAPI
BOOL   findNextSubStringSimple(CONST GAME_STRING*  pGameString, SUBSTRING*  pSubString)
{
   CONST TCHAR*  szEndMarker;    // Marks the position of a matching closing bracket

   // Prepare
   pSubString->szText[0] = NULL;

   // [CHECK] Is there no more string?
   if (!pSubString->szMarker OR !pSubString->szMarker[0])
      return FALSE;

   // Determine sub-string type from first character
   switch (pSubString->szMarker[0])
   {
   /// [TEXT or NORMAL BRACKET] - Indicates TEXT or COMMENT substring
   default: 
      // [COMMENT] Search for a matching closing bracket (or EOF)
      if (pSubString->szMarker[0] == '(')
      {
         // Calculate the size. (Include closing bracket, if any)
         if (szEndMarker = findNextNonEscapedCharacter(pSubString->szMarker, ')'))
            pSubString->iCount = (szEndMarker - pSubString->szMarker) + 1;
         // Set type
         pSubString->eType = SST_COMMENT;
      }
      // [TEXT] Search for any opening brackets (or EOF)
      else
      {
         // Calculate the size.  (Exclude opening bracket)
         if (szEndMarker = findNextNonEscapedCharacters(pSubString->szMarker, TEXT("({")))
            pSubString->iCount = (szEndMarker - pSubString->szMarker);
         // Set type
         pSubString->eType = SST_TEXT;
      }

      // Determine the sub-string length (if no matching bracket was found)
      if (szEndMarker == NULL)
         pSubString->iCount = lstrlen(pSubString->szMarker);

      /// Extract string to the output buffer and update the marker
      StringCchCopyN(pSubString->szText, MAX_STRING, pSubString->szMarker, pSubString->iCount);
      pSubString->szMarker += pSubString->iCount;
      break;

   /// [CURLY BRACKET] - Indicates LOOKUP or MISSION
   case '{':
      // Identify the *matching* closing curly bracket (sub-strings may be nested)
      if (szEndMarker = findSubStringEndMarker(pSubString->szMarker))
      {
         // Extend 'end' marker to cover the closing curly bracket
         szEndMarker += 1;

         /// [MISSION] Copy verbatim
         pSubString->iCount = (szEndMarker - pSubString->szMarker);
         StringCchCopyN(pSubString->szText, MAX_STRING, pSubString->szMarker, pSubString->iCount);
         // Set the type
         pSubString->eType = SST_MISSION;
         
         // Position the marker beyond the closing bracket
         pSubString->szMarker = szEndMarker;
      }
      else
      {
         /// [VALIDATION_FIX] Copy string verbatim. They're often used as characters in the MARS scripts without escapes.
         StringCchCopy(pSubString->szText, MAX_STRING, pSubString->szMarker);
         pSubString->iCount = lstrlen(pSubString->szText);

         // Return 'TEXT' and ensure further calls return FALSE
         pSubString->eType    = SST_TEXT;
         pSubString->szMarker = NULL;
      }
      break;
   }

   // [FOUND] Return TRUE
   return TRUE;
}
Example #21
0
/// Function name  : findNextSubString
// Description     : Searches for the next SubString in a GameString
// 
// CONST GAME_STRING*  pGameString    : [in]     GameString currently being resolved
// SUBSTRING*          pSubString     : [in/out] Contains the resolved SubString on return, if successful
// STACK*              pHistoryStack  : [in/out] Represents the 'chain' of GameStrings being resolved
// ERROR_QUEUE*        pErrorQueue    : [in/out] ErrorQueue, may already contain errors
// 
// Return Value   : TRUE if substring was found, FALSE if there were no more substrings
// 
BOOL   findNextSubString(CONST GAME_STRING*  pGameString, SUBSTRING*  pSubString, UINT&  iMissingCount, STACK*  pHistoryStack, ERROR_QUEUE*  pErrorQueue)
{
   CONST TCHAR*  szEndMarker;    // Marks the position of a matching closing bracket
   GAME_STRING*  pLookupString;  // Sub-string lookup string
   TCHAR*        szPreview;      // GameString preview text, for error reporting

   // Prepare
   pSubString->szText[0] = NULL;

   // [CHECK] Is there no more string?
   if (!pSubString->szMarker OR !pSubString->szMarker[0])
      return FALSE;

   // Determine sub-string type from first character
   switch (pSubString->szMarker[0])
   {
   /// [TEXT or NORMAL BRACKET] - Indicates TEXT or COMMENT substring
   default: 
      // [COMMENT] Search for a matching closing bracket (or EOF)
      if (pSubString->szMarker[0] == '(')
      {
         // Calculate the size. (Include closing bracket, if any)
         if (szEndMarker = findNextNonEscapedCharacter(pSubString->szMarker, ')'))
            pSubString->iCount = (szEndMarker - pSubString->szMarker) + 1;
         // Set type
         pSubString->eType = SST_COMMENT;
      }
      // [TEXT] Search for any opening brackets (or EOF)
      else
      {
         // Calculate the size.  (Exclude opening bracket)
         if (szEndMarker = findNextNonEscapedCharacters(pSubString->szMarker, TEXT("({")))
            pSubString->iCount = (szEndMarker - pSubString->szMarker);
         // Set type
         pSubString->eType = SST_TEXT;
      }

      // Determine the sub-string length (if no matching bracket was found)
      if (szEndMarker == NULL)
         pSubString->iCount = lstrlen(pSubString->szMarker);

      /// Extract string to the output buffer and update the marker
      StringCchCopyN(pSubString->szText, MAX_STRING, pSubString->szMarker, pSubString->iCount);
      pSubString->szMarker += pSubString->iCount;
      break;

   /// [CURLY BRACKET] - Indicates LOOKUP or MISSION
   case '{':
      // Identify the *matching* closing curly bracket (sub-strings may be nested)
      if (szEndMarker = findSubStringEndMarker(pSubString->szMarker))
      {
         // Extend 'end' marker to cover the closing curly bracket
         szEndMarker += 1;

         // [CHECK] Is this a lookup or a MD variable?
         if (isSubStringLookup(pSubString->szMarker, szEndMarker - pSubString->szMarker))
         {
            /// [LOOKUP] Lookup the GameString 
            if (findGameStringBySubString(pSubString->szMarker, szEndMarker - pSubString->szMarker, pGameString->iPageID, pLookupString))
            {
               // [CHECK] Are substrings within GameString resolved?
               if (pLookupString->bResolved)
               {
                  // [RESOLVED] Insert verbatim
                  StringCchCopy(pSubString->szText, MAX_STRING, pLookupString->szText);
                  pSubString->iCount = pLookupString->iCount;
               }
               else
               {
                  // [UNRESOLVED] Recursively resolve sub-strings
                  resolveGameStringSubStrings(pLookupString, pSubString->szText, MAX_STRING, pHistoryStack, pErrorQueue);
                  pSubString->iCount = lstrlen(pSubString->szText);
               }
            }
            else
            {  
               /// [NOT FOUND] GameString lookup not found (return the sub-string tag)
               pSubString->iCount = (szEndMarker - pSubString->szMarker);
               StringCchCopyN(pSubString->szText, MAX_STRING, pSubString->szMarker, pSubString->iCount);

               // Report number of missing strings
               iMissingCount++;

               // [WARNING] "Page:%d  String:%d : Missing sub-string %s in '%s'"
               generateQueuedWarning(pErrorQueue, HERE(IDS_GAME_STRING_SUBSTRING_NOT_FOUND), pGameString->iPageID, pGameString->iID, pSubString->szText, szPreview = generateGameStringPreview(pGameString, 96));
               utilDeleteString(szPreview);
            }
            // Set the type
            pSubString->eType  = SST_LOOKUP;
         }
         else
         {
            /// [MISSION] Copy verbatim
            pSubString->iCount = (szEndMarker - pSubString->szMarker);
            StringCchCopyN(pSubString->szText, MAX_STRING, pSubString->szMarker, pSubString->iCount);
            // Set the type
            pSubString->eType = SST_MISSION;
         }
         // Position the marker beyond the closing bracket
         pSubString->szMarker = szEndMarker;
      }
      else
      {
         /// [ERROR] No matching curly bracket
         //StringCchCopy(pSubString->szText, MAX_STRING, TEXT("{Error, no matching bracket}"));
         //pSubString->iCount = lstrlen(pSubString->szText);

         //// [ERROR] "Unclosed sub-string marker detected in page %u, string %u : '%s'"
         //pushErrorQueue(pErrorQueue, generateDualWarning(HERE(IDS_GAME_STRING_SUBSTRING_CORRUPT), pGameString->iPageID, pGameString->iID, szPreview = generateGameStringPreview(pGameString, 96)));
         //utilDeleteString(szPreview);

         /// [VALIDATION_FIX] Copy string verbatim. They're often used as characters in the MARS scripts without escapes.
         StringCchCopy(pSubString->szText, MAX_STRING, pSubString->szMarker);
         pSubString->iCount = lstrlen(pSubString->szText);

         // Return 'TEXT' and ensure further calls return FALSE
         pSubString->eType    = SST_TEXT;
         pSubString->szMarker = NULL;
      }
      break;
   }

   // [FOUND] Return TRUE
   return TRUE;
}
	BOOL GetFileNameFromHandle(HANDLE hFile) 
	{
	  BOOL bSuccess = FALSE;
	  TCHAR pszFilename[MAX_PATH+1];
	  HANDLE hFileMap;

	  // Get the file size.
	  DWORD dwFileSizeHi = 0;
	  DWORD dwFileSizeLo = GetFileSize(hFile, &dwFileSizeHi); 

	  if( dwFileSizeLo == 0 && dwFileSizeHi == 0 )
	  {
		 _tprintf(TEXT("Cannot map a file with a length of zero.\n"));
		 return FALSE;
	  }

	  // Create a file mapping object.
	  hFileMap = CreateFileMapping(hFile, 
						NULL, 
						PAGE_READONLY,
						0, 
						1,
						NULL);

	  if (hFileMap) 
	  {
		// Create a file mapping to get the file name.
		void* pMem = MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, 1);

		if (pMem) 
		{
		  if (GetMappedFileName (GetCurrentProcess(), 
								 pMem, 
								 pszFilename,
								 MAX_PATH)) 
		  {

			// Translate path with device name to drive letters.
			TCHAR szTemp[BUFSIZE];
			szTemp[0] = '\0';

			if (GetLogicalDriveStrings(BUFSIZE-1, szTemp)) 
			{
			  TCHAR szName[MAX_PATH];
			  TCHAR szDrive[3] = TEXT(" :");
			  BOOL bFound = FALSE;
			  TCHAR* p = szTemp;

			  do 
			  {
				// Copy the drive letter to the template string
				*szDrive = *p;

				// Look up each device name
				if (QueryDosDevice(szDrive, szName, MAX_PATH))
				{
				  size_t uNameLen = _tcslen(szName);

				  if (uNameLen < MAX_PATH) 
				  {
					bFound = _tcsnicmp(pszFilename, szName, uNameLen) == 0
							 && *(pszFilename + uNameLen) == _T('\\');

					if (bFound) 
					{
					  // Reconstruct pszFilename using szTempFile
					  // Replace device path with DOS path
					  TCHAR szTempFile[MAX_PATH];
					  StringCchPrintf(szTempFile,
								MAX_PATH,
								TEXT("%s%s"),
								szDrive,
								pszFilename+uNameLen);
					  StringCchCopyN(pszFilename, MAX_PATH+1, szTempFile, _tcslen(szTempFile));
					}
				  }
				}

				// Go to the next NULL character.
				while (*p++);
			  } while (!bFound && *p); // end of string
			}
		  }
		  bSuccess = TRUE;
		  UnmapViewOfFile(pMem);
		} 

		CloseHandle(hFileMap);
	  }
	  _tprintf(TEXT("File name is %s\n"), pszFilename);
	  return(bSuccess);
	}
/* Presumably Windows, pulled from MSDN sample code */
int
GetFileNameFromHandle(HANDLE hFile, char filepath[])
{
    int bSuccess = 0;
    TCHAR pszFilename[MAXPATHLEN+1];
    char filename[MAXPATHLEN+1];
    HANDLE hFileMap;

    /* Get the file size. */
    DWORD dwFileSizeHi = 0;
    DWORD dwFileSizeLo = GetFileSize(hFile, &dwFileSizeHi);

    if (dwFileSizeLo == 0 && dwFileSizeHi == 0) {
	_tprintf(TEXT("Cannot map a file with a length of zero.\n"));
	return FALSE;
    }

    /* Create a file mapping object. */
    hFileMap = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 1, NULL);

    if (hFileMap) {
	/* Create a file mapping to get the file name. */
	void* pMem = MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, 1);

	if (pMem) {
	    if (GetMappedFileName (GetCurrentProcess(), pMem, pszFilename, MAXPATHLEN)) {

		/* Translate path with device name to drive letters. */
		TCHAR szTemp[MAXPATHLEN+1];
		szTemp[0] = '\0';

		if (GetLogicalDriveStrings(MAXPATHLEN, szTemp)) {
		    TCHAR szName[MAXPATHLEN];
		    TCHAR szDrive[3] = TEXT(" :");
		    int bFound = 0;
		    TCHAR* p = szTemp;

		    do {
			/* Copy the drive letter to the template string */
			*szDrive = *p;

			/* Look up each device name */
			if (QueryDosDevice(szDrive, szName, MAXPATHLEN)) {
			    size_t uNameLen = _tcslen(szName);

			    if (uNameLen < MAXPATHLEN) {
				bFound = _tcsnicmp(pszFilename, szName, uNameLen) == 0;

				if (bFound && *(pszFilename + uNameLen) == _T('\\')) {
				    /* Reconstruct pszFilename using szTempFile */
				    /* Replace device path with DOS path */
				    TCHAR szTempFile[MAXPATHLEN];
				    StringCchPrintf(szTempFile, MAXPATHLEN, TEXT("%s%s"), szDrive, pszFilename+uNameLen);
				    StringCchCopyN(pszFilename, MAXPATHLEN+1, szTempFile, _tcslen(szTempFile));
				}
			    }
			}

			/* Go to the next NULL character. */
			while (*p++);
		    } while (!bFound && *p)
			; /* end of string */
		}
	    }
	    bSuccess = TRUE;
	    UnmapViewOfFile(pMem);
	}

	CloseHandle(hFileMap);
    }
    if (sizeof(TCHAR) == sizeof(wchar_t)) {
	wcstombs(filename, (const wchar_t *)pszFilename, MAXPATHLEN);
	bu_strlcpy(filepath, filename, MAXPATHLEN);
    } else {
	bu_strlcpy(filepath, pszFilename, MAXPATHLEN);
    }
    return (bSuccess);
}