CMarkdown::HSTR CMarkdown::_HSTR::Resolve(const EntityMap &map) { HSTR H = this; BSTR p, q = H->B; while ((p = StrChrW(q, '&')) != NULL && (q = StrChrW(p, ';')) != NULL) { *q = '\0'; OLECHAR *key = p + 1; std::wstring value; if (*key == '#') { int ordinal = '?'; *key = '0'; if (StrToIntExW(key, STIF_SUPPORT_HEX, &ordinal)) value.assign(1, (OLECHAR)ordinal); *key = '#'; } else { EntityMap::const_iterator p = map.find(key); if (p != map.end()) value = p->second; } *q = ';'; ++q; if (int cchValue = value.length()) { int i = p - H->B; int j = q - H->B; int cchKey = q - p; if (int cchGrow = cchValue - cchKey) { BSTR B = H->B; int b = SysStringLen(B); size_t cbMove = (b - j) * sizeof(OLECHAR); if (cchGrow < 0) { memmove(q + cchGrow, q, cbMove); } if (!SysReAllocStringLen(&B, B, b + cchGrow)) { continue; } H = (HSTR)B; p = H->B + i; q = H->B + j; if (cchGrow > 0) { memmove(q + cchGrow, q, cbMove); } } memcpy(p, value.c_str(), cchValue * sizeof(OLECHAR)); q = p + cchValue; } } return H; }
HRESULT WINAPI CExeDropHandler::Drop(IDataObject *pDataObject, DWORD dwKeyState, POINTL pt, DWORD *pdwEffect) { TRACE ("(%p)\n", this); FORMATETC fmt; STGMEDIUM medium; LPWSTR pszSrcList; InitFormatEtc (fmt, CF_HDROP, TYMED_HGLOBAL); WCHAR wszBuf[MAX_PATH * 2 + 8], *pszEnd = wszBuf; size_t cchRemaining = _countof(wszBuf); if (SUCCEEDED(pDataObject->GetData(&fmt, &medium)) /* && SUCCEEDED(pDataObject->GetData(&fmt2, &medium))*/) { LPDROPFILES lpdf = (LPDROPFILES) GlobalLock(medium.hGlobal); if (!lpdf) { ERR("Error locking global\n"); return E_FAIL; } pszSrcList = (LPWSTR) (((byte*) lpdf) + lpdf->pFiles); while (*pszSrcList) { if (StrChrW(pszSrcList, L' ') && cchRemaining > 3) StringCchPrintfExW(pszEnd, cchRemaining, &pszEnd, &cchRemaining, 0, L"\"%ls\" ", pszSrcList); else StringCchPrintfExW(pszEnd, cchRemaining, &pszEnd, &cchRemaining, 0, L"%ls ", pszSrcList); pszSrcList += wcslen(pszSrcList) + 1; } } ShellExecuteW(NULL, L"open", sPathTarget, wszBuf, NULL,SW_SHOWNORMAL); return S_OK; }
bool Cx_StringTable::GetValue(std::wstring& value, const std::wstring& name, std::wstring& module, std::wstring& id) { if (name.size() > 1 && '@' == name[0] && StrChrW(name.c_str(), ':') != NULL) { LPCWSTR p = StrChrW(name.c_str(), ':'); module = std::wstring(name.c_str() + 1, (size_t)(p - name.c_str() - 1)); id = p + 1; return GetValue(value, module, id); } return false; }
static LPITEMIDLIST _ILReadFromSharedMemory(PCWSTR strField) { LPITEMIDLIST ret = NULL; // Ensure it really is an IDLIST-formatted parameter // Format for IDLIST params: ":pid:shared" if (*strField != L':') return NULL; HANDLE hData = (HANDLE) StrToIntW(strField + 1); PWSTR strSecond = StrChrW(strField + 1, L':'); if (strSecond) { int pid = StrToIntW(strSecond + 1); void* pvShared = SHLockShared(hData, pid); if (pvShared) { ret = ILClone((LPCITEMIDLIST) pvShared); SHUnlockShared(pvShared); SHFreeShared(hData, pid); } } return ret; }
int WINAPI get_parameters(LPWSTR wdir, LPWSTR lpstrCmd, DWORD len) { int ret = -1; LPWSTR lp = NULL; WCHAR temp[VALUE_LEN+1] = {0}; WCHAR m_para[VALUE_LEN+1] = {0}; if ( read_appkey(L"attach",L"ExPath",temp,sizeof(temp)) ) { wdir[0] = L'\0'; lp = StrChrW(temp,L','); if (isdigit(temp[wcslen(temp)-1])&&lp) { ret = temp[wcslen(temp)-1] - L'0'; temp[lp-temp] = L'\0'; lp = StrChrW(temp,L' '); /* 如果第三方进程存在参数,工作目录设为浏览器主进程所在目录 */ if ( lp ) { temp[lp-temp] = L'\0'; _snwprintf(m_para,VALUE_LEN,L" "L"%ls",lp+1); if ( !GetCurrentWorkDir(wdir,len) ) { wdir[0] = L'\0'; } } _snwprintf(lpstrCmd,len,L"%ls",temp); if ( lpstrCmd[0] == L'.' || lpstrCmd[0] == L'%' ) { PathToCombineW(lpstrCmd,VALUE_LEN); } wcsncat(lpstrCmd,m_para,len); if ( wcslen(wdir) == 0 ) { _snwprintf(wdir,len,L"%ls",lpstrCmd); if ( !PathRemoveFileSpecW(wdir) ) { wdir[0] = L'\0'; } } } } return ret; }
static WCHAR *GetCookieParamValuePtr(WCHAR *lpPtr) { lpPtr=StrChrW(lpPtr,L'='); if (lpPtr) { lpPtr++; while ((*lpPtr) && (*lpPtr == L' ')) lpPtr++; } return lpPtr; }
BOOL WINAPI is_specialdll(UINT_PTR callerAddress,LPCWSTR dll_file) { BOOL ret = FALSE; HMODULE hCallerModule = NULL; if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCWSTR)callerAddress, &hCallerModule)) { WCHAR szModuleName[VALUE_LEN+1] = {0}; if ( GetModuleFileNameW(hCallerModule, szModuleName, VALUE_LEN) ) { if ( StrChrW(dll_file,L'*') || StrChrW(dll_file,L'?') ) { if ( PathMatchSpecW(szModuleName, dll_file) ) { ret = TRUE; } } else if ( stristrW(szModuleName, dll_file) ) { ret = TRUE; } } } return ret; }
static void test_StrChrW(void) { WCHAR string[16385]; WORD count; /* this test crashes on win2k SP4 */ /*ok(!StrChrW(NULL,'\0'), "found a character in a NULL string!\n");*/ for (count = 32; count < 16384; count++) string[count] = count; string[16384] = '\0'; for (count = 32; count < 16384; count++) { LPWSTR result = StrChrW(string+32, count); ok((result - string) == count, "found char %d in wrong place\n", count); } for (count = 32; count < 16384; count++) { LPWSTR result = StrChrW(string+count+1, count); ok(!result, "found char not in the string\n"); } }
void WINAPI charTochar(LPWSTR path) { LPWSTR lp = NULL; INT_PTR pos; do { lp = StrChrW(path,L'/'); if (lp) { pos = lp-path; path[pos] = L'\\'; } } while (lp!=NULL); return; }
static inline bool IsSpaceChar(WCHAR cChar, LPCWSTR targets = NULL) { return targets ? (StrChrW(targets, cChar) != NULL) : (0x0020 == cChar || 0x3000 == cChar || '\t' == cChar); }
void InetProcessCookies(HTTP_REQUEST_HANDLE *lpReq) { if ((lpReq) && (lpReq->dwType == HTTP_REQUEST)) { EnterSafeCriticalSection(&lpReq->lpUrl->lpSession->csSession); { WCHAR *lpUrl=NULL, *lpPath=NULL, *lpHost=NULL; do { DWORD dwLen=INTERNET_MAX_URL_LENGTH*sizeof(WCHAR); lpUrl=(WCHAR*)MemQuickAlloc(dwLen); if (!lpUrl) break; if (!InternetQueryOptionW(lpReq->hReq,INTERNET_OPTION_URL,lpUrl,&dwLen)) break; lpPath=WCHAR_QuickAlloc(INTERNET_MAX_PATH_LENGTH); if (!lpPath) break; lpHost=WCHAR_QuickAlloc(INTERNET_MAX_HOST_NAME_LENGTH); if (!lpHost) break; URL_COMPONENTSW url={0}; url.dwStructSize=sizeof(url); url.lpszHostName=lpHost; url.dwHostNameLength=INTERNET_MAX_HOST_NAME_LENGTH; url.lpszUrlPath=lpPath; url.dwUrlPathLength=INTERNET_MAX_PATH_LENGTH; if (!InternetCrackUrlW(lpUrl,NULL,0,&url)) break; DWORD i=0; while (true) { WCHAR *lpCookie=NULL,szTmp[1]; DWORD dwSize=0; if ((HttpQueryInfoW(lpReq->hReq,HTTP_QUERY_SET_COOKIE,szTmp,&dwSize,&i)) || (GetLastError() != ERROR_INSUFFICIENT_BUFFER)) break; dwSize+=2; lpCookie=(WCHAR*)MemQuickAlloc(dwSize); if (!lpCookie) break; if (HttpQueryInfoW(lpReq->hReq,HTTP_QUERY_SET_COOKIE,lpCookie,&dwSize,&i)) { WCHAR *lpData=StrChrW(lpCookie,L'='); if (lpData) { *lpData++=0; Cookie_Parse(lpReq->lpUrl->lpSession,lpHost,lpPath,lpCookie,lpData); } } MemFree(lpCookie); } } while (false); MemFree(lpUrl); MemFree(lpPath); MemFree(lpHost); } LeaveSafeCriticalSection(&lpReq->lpUrl->lpSession->csSession); } return; }
static void Cookie_Parse(HTTP_SESSION_HANDLE *lpSession,WCHAR *lpCookieDomain,WCHAR *lpCookiePath,WCHAR *lpCookieName,WCHAR *lpData) { WCHAR *lpPtr=lpData, *lpPorts=NULL; DWORD dwCookieFlags=0, dwFlags=0, dwPortsCount=0; FILETIME ftExpiry={0}; while (true) { if (!(lpPtr=StrChrW(lpPtr,L';'))) break; *lpPtr++=0; while ((*lpPtr) && (*lpPtr == L' ')) lpPtr++; if (IsKnownParam(dcrW_c7ed8bb1("domain"),6)) { lpPtr=GetCookieParamValuePtr(lpPtr); lpCookieDomain=lpPtr; } else if (IsKnownParam(dcrW_1ab74e01("path"),4)) { lpPtr=GetCookieParamValuePtr(lpPtr); lpCookiePath=lpPtr; } else if (IsKnownParam(dcrW_a3df71ef("expires"),7)) { lpPtr=GetCookieParamValuePtr(lpPtr); if ((!(dwCookieFlags & COOKIE_FLAG_EXPIRES_SET)) && (!(dwFlags & COOKIE_HANDLER_MAXAGE_SET))) { SYSTEMTIME st; if (InternetTimeToSystemTimeW(lpPtr,&st,0)) { dwCookieFlags|=COOKIE_FLAG_EXPIRES_SET; SystemTimeToFileTime(&st,&ftExpiry); FILETIME tm; GetSystemTimeAsFileTime(&tm); if (CompareFileTime(&tm,&ftExpiry) > 0) dwFlags|=COOKIE_HANDLER_EXPIRED; } } } else if (IsKnownParam(dcrW_77b02e79("secure"),6)) { lpPtr=GetCookieParamValuePtr(lpPtr); dwCookieFlags|=COOKIE_FLAG_SECURE; } else if (IsKnownParam(dcrW_60249e06("discard"),7)) { lpPtr=GetCookieParamValuePtr(lpPtr); dwCookieFlags|=COOKIE_FLAG_DISCARD; } else if (IsKnownParam(dcrW_53e691c9("max-age"),7)) { lpPtr=GetCookieParamValuePtr(lpPtr); GetSystemTimeAsFileTime(&ftExpiry); /** MSDN: It is not recommended that you add and subtract values from the FILETIME structure to obtain relative times. Instead, you should copy the low- and high-order parts of the file time to a LARGE_INTEGER structure, perform 64-bit arithmetic on the QuadPart member, and copy the LowPart and HighPart members into the FILETIME structure. Do not cast a pointer to a FILETIME structure to either a LARGE_INTEGER* or __int64* value because it can cause alignment faults on 64-bit Windows. **/ LARGE_INTEGER liTime={ftExpiry.dwLowDateTime,ftExpiry.dwHighDateTime}; liTime.QuadPart+=StrToIntW(lpPtr)*_100NS_IN_SEC; ftExpiry.dwLowDateTime=liTime.LowPart; ftExpiry.dwHighDateTime=liTime.HighPart; dwFlags|=COOKIE_HANDLER_MAXAGE_SET; dwCookieFlags|=COOKIE_FLAG_EXPIRES_SET; } else if (IsKnownParam(dcrW_f98fd7e9("port"),4)) { lpPtr=GetCookieParamValuePtr(lpPtr); do { if (dwCookieFlags & COOKIE_FLAG_PORT_SET) break; if (*lpPtr != L'"') break; WCHAR *lpPortsStart=lpPtr+1, *lpPortsEnd=StrChrW(lpPortsStart,L'"'); if (!lpPortsEnd) break; dwPortsCount=1; WCHAR *lpCurPort=lpPortsStart; while (true) { lpCurPort=StrChrW(lpCurPort,L','); if (!lpCurPort) break; if (lpCurPort > lpPortsEnd) break; dwPortsCount++; lpCurPort++; } lpPorts=lpPortsStart; dwCookieFlags|=COOKIE_FLAG_PORT_SET; } while (false); } } do { COOKIE_DOMAIN *lpDomain=Cookie_FindDomain(lpSession,lpCookieDomain,lpCookiePath,false,NULL); if ((!lpDomain) && (!(dwFlags & COOKIE_HANDLER_EXPIRED))) lpDomain=Cookie_AddDomain(lpSession,lpCookieDomain,lpCookiePath); if (!lpDomain) break; COOKIE *lpCookie=Cookie_Find(lpDomain,lpCookieName); if (lpCookie) Cookie_Delete(lpCookie,(!(dwFlags & COOKIE_HANDLER_EXPIRED))); if (!(dwFlags & COOKIE_HANDLER_EXPIRED)) { COOKIE *lpCookie=Cookie_Add(lpDomain,lpCookieName,lpData); if (!lpCookie) break; lpCookie->ftExpiry=ftExpiry; lpCookie->dwCookieFlags=dwCookieFlags; if (dwCookieFlags & COOKIE_FLAG_PORT_SET) { lpCookie->lpPortsList=(WORD*)MemQuickAlloc(dwPortsCount*sizeof(WORD)); if (lpCookie->lpPortsList) { lpCookie->dwPortsCount&=~COOKIE_FLAG_PORT_SET; break; } lpCookie->dwPortsCount=dwPortsCount; WCHAR *lpCurPort=lpPorts; for (DWORD i=0; i < dwPortsCount; i++) { lpCookie->lpPortsList[i]=StrToIntW(lpCurPort); lpCurPort=StrChrW(lpCurPort,L','); lpCurPort++; } } } } while (false); return; }
BOOL WINAPI in_whitelist(LPCWSTR lpfile) { WCHAR *moz_processes[] = {L"", L"plugin-container.exe", L"plugin-hang-ui.exe", L"webapprt-stub.exe", L"webapp-uninstaller.exe",L"WSEnable.exe",L"uninstall\\helper.exe", L"crashreporter.exe",L"CommandExecuteHandler.exe",L"maintenanceservice.exe", L"maintenanceservice_installer.exe",L"updater.exe" }; static WCHAR white_list[EXCLUDE_NUM][VALUE_LEN+1]; int i = sizeof(moz_processes)/sizeof(moz_processes[0]); LPCWSTR pname = lpfile; BOOL ret = FALSE; if (lpfile[0] == L'"') { pname = &lpfile[1]; } /* 遍历白名单一次,只需遍历一次 */ ret = stristrW(white_list[1],L"plugin-container.exe") != NULL; if ( !ret ) { /* firefox目录下进程的路径 */ int num; WCHAR temp[VALUE_LEN+1]; GetModuleFileNameW(NULL,temp,VALUE_LEN); wcsncpy(white_list[0],(LPCWSTR)temp,VALUE_LEN); PathRemoveFileSpecW(temp); for(num=1; num<i; ++num) { _snwprintf(white_list[num],VALUE_LEN,L"%ls\\%ls", temp, moz_processes[num]); } ret = foreach_section(L"whitelist", &white_list[num], EXCLUDE_NUM-num); } if ( (ret = !ret) == FALSE ) { /* 核对白名单 */ for ( i=0; i<EXCLUDE_NUM ; i++ ) { if (wcslen(white_list[i]) == 0) { continue; } if ( StrChrW(white_list[i],L'*') || StrChrW(white_list[i],L'?') ) { if ( PathMatchSpecW(pname,white_list[i]) ) { ret = TRUE; break; } } else if (white_list[i][1] != L':') { PathToCombineW(white_list[i],VALUE_LEN); } if (_wcsnicmp(white_list[i],pname,wcslen(white_list[i]))==0) { ret = TRUE; break; } } } return ret; }
static DWORD Dde_OnExecute(HCONV hconv, HSZ hszTopic, HDDEDATA hdata) { WCHAR szTopic[MAX_PATH]; WCHAR szCommand[MAX_PATH]; WCHAR *pszCommand; DdeQueryStringW(dwDDEInst, hszTopic, szTopic, _countof(szTopic), CP_WINUNICODE); pszCommand = (WCHAR*) DdeAccessData(hdata, NULL); if (!pszCommand) return DDE_FNOTPROCESSED; StringCchCopyW(szCommand, _countof(szCommand), pszCommand); DdeUnaccessData(hdata); TRACE("Dde_OnExecute: hconv=%p, topic=%S, command=%S\n", hconv, szTopic, pszCommand); /* [ViewFolder("%l", %I, %S)] -- Open a folder in standard mode [ExploreFolder("%l", %I, %S)] -- Open a folder in "explore" mode (file tree is shown to the left by default) [FindFolder("%l", %I)] -- Open a folder in "find" mode (search panel is shown to the left by default) [ShellFile("%1","%1",%S)] -- Execute the contents of the specified .SCF file Approximate grammar (Upper names define rules, <lower> names define terminals, single-quotes are literals): Rules Command = ('[' Function ']') | Function Function = <identifier> '(' Parameters ')' Parameters = (<quoted-string> (',' <idlist> (',' <number>)?)?)? Terminals <identifier> = [a-zA-Z]+ <quoted-string> = \"([^\"]|\\.)\" <idlist> = \:[0-9]+\:[0-9]+ <number> = [0-9]+ */ WCHAR Command[MAX_PATH] = L""; WCHAR Path[MAX_PATH] = L""; LPITEMIDLIST IdList = NULL; INT UnknownParameter = 0; // Simplified parsing (assumes the command will not be TOO broken): PWSTR cmd = szCommand; // 1. if starts with [, skip first char if (*cmd == L'[') cmd++; if (*cmd == L']') { ERR("Empty command. Nothing to run.\n"); return DDE_FNOTPROCESSED; } // Read until first (, and take text before ( as command name { PWSTR cmdEnd = StrChrW(cmd, L'('); if (!cmdEnd) { ERR("Could not find '('. Invalid command.\n"); return DDE_FNOTPROCESSED; } *cmdEnd = 0; StringCchCopy(Command, _countof(Command), cmd); cmd = cmdEnd + 1; } // Read first param after (, expecting quoted string if (*cmd != L')') { // Copy unescaped string PWSTR dst = Path; BOOL isQuote = FALSE; PWSTR arg = cmd; while (*arg && (isQuote || *arg != L',')) { if (*arg == L'"') { isQuote = !isQuote; if (isQuote && arg != cmd) // do not copy the " at the beginning of the string { *(dst++) = L'"'; } } else { *(dst++) = *arg; } arg++; } cmd = arg + 1; while (*cmd == L' ') cmd++; } // Read second param, expecting an idlist in shared memory if (*cmd != L')') { if (*cmd != ':') { ERR("Expected ':'. Invalid command.\n"); return DDE_FNOTPROCESSED; } PWSTR idlistEnd = StrChrW(cmd, L','); if (!idlistEnd) idlistEnd = StrChrW(cmd, L')'); if (!idlistEnd) { ERR("Expected ',' or ')'. Invalid command.\n"); return DDE_FNOTPROCESSED; } IdList = _ILReadFromSharedMemory(cmd); cmd = idlistEnd + 1; } // Read third param, expecting an integer if (*cmd != L')') { UnknownParameter = StrToIntW(cmd); } TRACE("Parse end: cmd=%S, S=%d, pidl=%p, path=%S\n", Command, UnknownParameter, IdList, Path); // Find handler in list for (int i = 0; i < HandlerListLength; i++) { DDECommandHandler & handler = HandlerList[i]; if (StrCmpW(handler.Command, Command) == 0) { return handler.Handler(Command, Path, IdList, UnknownParameter); } } // No handler found ERR("Unknown command %S\n", Command); return DDE_FNOTPROCESSED; }
int BLBS_ReadSetting() { // Init and declare variables HANDLE hFile; uint8_t make_ini = FALSE; // If this is true, use default option wchar_t* file_buf = NULL; wchar_t path_buf[MAX_PATH] = {0}; uint32_t file_size = 0; BLBS_GetIniFullPath(path_buf, sizeof(path_buf)); #ifdef _DEBUG_CONSOLE printf("[IniFile]\n%S\n\n", path_buf); #endif // _DEBUG_CONSOLE // File IO // https://msdn.microsoft.com/en-us/library/windows/desktop/bb540534%28v=vs.85%29.aspx // Open File hFile = CreateFileW(path_buf, // lpFileName GENERIC_READ | GENERIC_WRITE, // dwDesiredAccess FILE_SHARE_READ, // dwShareMode NULL, // lpSecurityAttributes OPEN_EXISTING, // dwCreationDisposition FILE_ATTRIBUTE_NORMAL, // dwFlagsAndAttributes NULL); // hTemplateFile // Cannot open! Error Handling if (hFile == INVALID_HANDLE_VALUE) { // No ini file, use default opntion! if (GetLastError() == ERROR_FILE_NOT_FOUND) make_ini = TRUE; else JV_ErrorHandle(JVERR_CreateFile, TRUE); } if (make_ini) { // no BatteryLine.ini, so generate BatteryLine.ini. Note : hFile is invalid at this point uint32_t written_byte = 0; // Write default setting to file hFile = CreateFileW(path_buf, // lpFileName GENERIC_READ | GENERIC_WRITE, // dwDesiredAccess 0, // dwShareMode NULL, // lpSecurityAttributes CREATE_ALWAYS, // dwCreationDisposition FILE_ATTRIBUTE_NORMAL, // dwFlagsAndAttributes NULL); // hTemplateFile // Is handle is opened without problem? if (hFile == INVALID_HANDLE_VALUE) JV_ErrorHandle(JVERR_CreateFile, TRUE); // Write BOM to File if (!WriteFile(hFile, &BOM, sizeof(uint16_t), (DWORD*)&written_byte, NULL)) JV_ErrorHandle(JVERR_WriteFile, TRUE); // Is BOM written to file fully? if (written_byte != sizeof(uint16_t)) JV_ErrorHandle(JVERR_FILEIO_WRITTEN_BYTES, FALSE); // Write default setting string to File if (!WriteFile(hFile, (void*) BL_DefaultSettingStr, wcslen(BL_DefaultSettingStr) * sizeof(wchar_t), (DWORD*)&written_byte, NULL)) JV_ErrorHandle(JVERR_WriteFile, TRUE); // Is string writeen to file fully? if (written_byte != wcslen(BL_DefaultSettingStr) * sizeof(wchar_t)) JV_ErrorHandle(JVERR_FILEIO_WRITTEN_BYTES, FALSE); // Close Handle CloseHandle(hFile); // point file_buf to BL_DefaultSettingStr, no dyn alloc file_buf = BL_DefaultSettingStr; } else { // file is successfully open, read setting from file. Note : hFile is alive at this point uint32_t read_byte = 0; size_t sztmp = 0; // Get file size, and dyn allocate file_buf file_size = GetFileSize(hFile, NULL); file_buf = (wchar_t*) malloc(file_size+16); memset((void*) file_buf, 0, file_size+16); // Read from file if (!ReadFile(hFile, // hFile file_buf, // lpBuffer file_size, // nNumberOfBytesToRead (DWORD*) &read_byte, // lpNumberOfBytesRead NULL)) // lpOverlapped JV_ErrorHandle(JVERR_ReadFile, TRUE); // Is all bytes successfully read? if (read_byte != file_size) JV_ErrorHandle(JVERR_FILEIO_READ_BYTES, FALSE); // Close Handle CloseHandle(hFile); // Add \r\n at EOF sztmp = wcslen(file_buf); file_buf[sztmp] = L'\r'; file_buf[sztmp+1] = L'\n'; file_buf[sztmp+2] = L'\0'; } // Parse ini File - Too complex... wchar_t* str_cursor = NULL, *str_next = NULL; wchar_t line_token[BS_TOKEN_BUF_SIZE]; // Unicode LineFeed : \r\n (00d0 00a0) wchar_t line_rawbuf[BS_LINE_BUF_SIZE], line_buf[BS_LINE_BUF_SIZE]; size_t line_len = 0; wchar_t* equal_pos = NULL; wchar_t equal_left[BS_LINE_BUF_SIZE], equal_right[BS_LINE_BUF_SIZE]; uint8_t state_section = BS_SECTION_OFF; uint8_t color_idx = 0; BL_OPTION valid; // 01 using \r\n as token, traverse all lines in BL_SettingFile line_token[0] = L'\r'; line_token[1] = L'\n'; line_token[2] = L'\0'; // str_cursor will serve as cursor for each line str_cursor = file_buf; // 'valid' will be used to check wether these option is already set - FALSE for not set, TRUE for set ZeroMemory(&valid, sizeof(BL_OPTION)); // Parsing loop. Escape when meet EOF while (1) { // 02 Copy one line to line_rawbuf. // 02 Note that line_rawbuf contains 'raw' strings, which has tab, space, \r, \n. str_next = StrStrW(str_cursor, line_token); // Start of next line if (str_next == NULL) // No more line, EOF break; line_len = str_next - str_cursor; // Get this line's length StringCchCopyNW(line_rawbuf, BS_LINE_BUF_SIZE, str_cursor+1, line_len-1); // Copy one line to line_buf, +1 for remove first \r\n, -1 for remove last \r str_cursor = str_next + 1; // Fot next iteration, move cursor to next line // For debugging, there is too many segfaults in parsing alg! #ifdef _DEBUG_PARSING printf("line_rawbuf : %S\n", line_rawbuf); printf("state : %u\n", state_section); #endif // Finite State Machine Model // 03 line_rawbuf has [] -> start a section, represent as 'state' if (StrChrW(line_rawbuf, L'[') != NULL && StrChrW(line_rawbuf, L']') != NULL) { // Contains [ ] switch (state_section) { case BS_SECTION_OFF: if (StrStrIW(line_rawbuf, L"[General]") != NULL) state_section = BS_SECTION_GENERAL; else if (StrStrIW(line_rawbuf, L"[Color]") != NULL) state_section = BS_SECTION_COLOR; break; case BS_SECTION_GENERAL: if (StrStrIW(line_rawbuf, L"[General]") != NULL) state_section = BS_SECTION_GENERAL; else if (StrStrIW(line_rawbuf, L"[Color]") != NULL) state_section = BS_SECTION_COLOR; else state_section = BS_SECTION_OFF; break; case BS_SECTION_COLOR: if (StrStrIW(line_rawbuf, L"[General]") != NULL) state_section = BS_SECTION_GENERAL; else if (StrStrIW(line_rawbuf, L"[Color]") != NULL) state_section = BS_SECTION_COLOR; else state_section = BS_SECTION_OFF; break; } } // 04 line_rawbuf does not have [] -> remove Tab, Space, \r, \n and put into line_buf else if (line_rawbuf[0] != L'#') // This line is not comment and do not contain [] { int32_t dword = 0; uint8_t lowedge8 = 0, highedge8 = 0, r8 = 0, g8 = 0, b8 = 0; wchar_t quote_tmp[BS_TOKEN_BUF_SIZE] = {0}; wchar_t* quote_pos = NULL, *quote_next = NULL; uint32_t x = 0; // 04 Remove Tab, Space, \r, \n from line_rawbuf and put into line_buf for (uint32_t i = 0; i < line_len; i++) { if (line_rawbuf[i] == L'#') // if we meet # in the middle, ignore remnant characters break; if (line_rawbuf[i] != L'\t' && line_rawbuf[i] != L' ' && line_rawbuf[i] != L'\r' && line_rawbuf[i] != L'\n') { line_buf[x] = line_rawbuf[i]; x++; } } line_buf[x] = L'\0'; line_len = x; #ifdef _DEBUG_PARSING printf("line_buf : %S\n", line_buf); #endif switch (state_section) { case BS_SECTION_OFF: break; case BS_SECTION_GENERAL: // 05 using = as basis, cut left sting and right string. // 06 left string : which option to set? // 06 right string : how to parse right string? equal_pos = StrChrW(line_buf, L'='); if (equal_pos == NULL) // no '=' { state_section = BS_SECTION_OFF; // invalid option, think this as end of section. continue; // so ignore this line and go to next line } StringCchCopyNW(equal_left, BS_LINE_BUF_SIZE, line_buf, equal_pos-line_buf); // Copy left part StringCchCopyW(equal_right, BS_LINE_BUF_SIZE, line_buf+(equal_pos-line_buf+1)); // Copy right part if (StrCmpIW(equal_left, L"showcharge") == 0) { // {true, false} if (StrCmpIW(equal_right, L"true") == 0) option.showcharge = TRUE; else if (StrCmpIW(equal_right, L"false") == 0) option.showcharge = FALSE; else JV_ErrorHandle(JVERR_OPT_INI_INVALID_SHOWCHARGE, FALSE); valid.showcharge = TRUE; } else if (StrCmpIW(equal_left, L"monitor") == 0) { // {primary, 1, 2, ... , 32} if (StrCmpIW(equal_right, L"primary") == 0) option.monitor = BL_MON_PRIMARY; else { int32_t dword = _wtoi(equal_right); // Count Monitor's number and write to g_nMon g_nMon = 0; g_nPriMon = 0; ZeroMemory(&g_monInfo, sizeof(MONITORINFO) * BL_MAX_MONITOR); EnumDisplayMonitors(NULL, NULL, BLCB_MonEnumProc_GetFullInfo, 0); #ifdef _DEBUG_MONITOR printf("[Monitor]\nThis system has %d monitors.\n\n", g_nMon); #endif if (!(1 <= dword && dword <= BL_MAX_MONITOR)) JV_ErrorHandle(JVERR_OPT_INI_INVALID_MONITOR, FALSE); if (!(dword <= g_nMon)) // JV_ErrorHandle(JVERR_OPT_INI_NOT_EXIST_MONITOR, FALSE); option.monitor = (uint8_t) dword; } valid.monitor = TRUE; } else if (StrCmpIW(equal_left, L"position") == 0) { // {top, bottom, left, right} if (StrCmpIW(equal_right, L"top") == 0) option.position = BL_POS_TOP; else if (StrCmpIW(equal_right, L"bottom") == 0) option.position = BL_POS_BOTTOM; else if (StrCmpIW(equal_right, L"left") == 0) option.position = BL_POS_LEFT; else if (StrCmpIW(equal_right, L"right") == 0) option.position = BL_POS_RIGHT; else JV_ErrorHandle(JVERR_OPT_INI_INVALID_POSITION, FALSE); valid.position = TRUE; } else if (StrCmpIW(equal_left, L"taskbar") == 0) { // {ignore, evade} if (StrCmpIW(equal_right, L"ignore") == 0) option.taskbar = BL_TASKBAR_IGNORE; else if (StrCmpIW(equal_right, L"evade") == 0) option.taskbar = BL_TASKBAR_EVADE; else JV_ErrorHandle(JVERR_OPT_INI_INVALID_TASKBAR, FALSE); valid.taskbar = TRUE; } else if (StrCmpIW(equal_left, L"transparency") == 0) { // {0 <= number <= 255} int32_t dword = _wtoi(equal_right); if (!(0 <= dword && dword <= 255)) JV_ErrorHandle(JVERR_OPT_INI_INVALID_TRANSPARENCY, FALSE); option.transparency = (uint8_t) dword; valid.transparency = TRUE; } else if (StrCmpIW(equal_left, L"height") == 0) { // {1 <= number <= 255} int32_t dword = _wtoi(equal_right); if (!(1 <= dword && dword <= 255)) JV_ErrorHandle(JVERR_OPT_INI_INVALID_HEIGHT, FALSE); option.height = (uint8_t) dword; valid.height = TRUE; } break; case BS_SECTION_COLOR: // 05 using = as basis, cut left sting and right string. // 06 left string : which option to set? // 06 right string : how to parse right string? equal_pos = StrChrW(line_buf, L'='); if (equal_pos == NULL) // no '=' { state_section = BS_SECTION_OFF; // invalid option, think this as end of section. continue; // so ignore this line and go to next line } StringCchCopyNW(equal_left, BS_LINE_BUF_SIZE, line_buf, equal_pos-line_buf); // Copy left part StringCchCopyW(equal_right, BS_LINE_BUF_SIZE, line_buf+(equal_pos-line_buf+1)); // Copy right part if (!StrCmpIW(equal_left, L"defaultcolor")) { // Format : {R, G, B} quote_pos = equal_right; for (uint32_t i = 0; i < 3; i++) // R, G, B { quote_next = StrChrW(quote_pos, L','); if (quote_next != NULL) // , still exists { StringCchCopyNW(quote_tmp, BS_TOKEN_BUF_SIZE, quote_pos, quote_next-quote_pos); // Copy a number quote_pos = quote_next+1; // +1 for , } else // NULL, no ','! StringCchCopyW(quote_tmp, BS_TOKEN_BUF_SIZE, quote_pos); // Copy last number dword = _wtoi(quote_tmp); if (!(0 <= dword && dword <= 255)) JV_ErrorHandle(JVERR_OPT_INI_INVALID_DEFAULTCOLOR, FALSE); switch (i) { case 0: r8 = dword; break; case 1: g8 = dword; break; case 2: b8 = dword; break; } } option.defaultcolor = RGB(r8, g8, b8); valid.defaultcolor = TRUE; } else if (!StrCmpIW(equal_left, L"chargecolor")) { // Format : {R, G, B} quote_pos = equal_right; for (uint32_t i = 0; i < 3; i++) // R, G, B { quote_next = StrChrW(quote_pos, L','); if (quote_next != NULL) // , still exists { StringCchCopyNW(quote_tmp, BS_TOKEN_BUF_SIZE, quote_pos, quote_next-quote_pos); // Copy a number quote_pos = quote_next+1; // +1 for , } else // NULL, no ','! StringCchCopyW(quote_tmp, BS_TOKEN_BUF_SIZE, quote_pos); // Copy last number dword = _wtoi(quote_tmp); if (!(0 <= dword && dword <= 255)) JV_ErrorHandle(JVERR_OPT_INI_INVALID_CHARGECOLOR, FALSE); switch (i) { case 0: r8 = dword; break; case 1: g8 = dword; break; case 2: b8 = dword; break; } } option.chargecolor = RGB(r8, g8, b8); valid.chargecolor = TRUE; } else if (!StrCmpIW(equal_left, L"fullcolor")) { // Format : {R, G, B} quote_pos = equal_right; for (uint32_t i = 0; i < 3; i++) // R, G, B { quote_next = StrChrW(quote_pos, L','); if (quote_next != NULL) // , still exists { StringCchCopyNW(quote_tmp, BS_TOKEN_BUF_SIZE, quote_pos, quote_next-quote_pos); // Copy a number quote_pos = quote_next+1; // +1 for , } else // NULL, no ','! StringCchCopyW(quote_tmp, BS_TOKEN_BUF_SIZE, quote_pos); // Copy last number dword = _wtoi(quote_tmp); if (!(0 <= dword && dword <= 255)) JV_ErrorHandle(JVERR_OPT_INI_INVALID_FULLCOLOR, FALSE); switch (i) { case 0: r8 = dword; break; case 1: g8 = dword; break; case 2: b8 = dword; break; } } option.fullcolor = RGB(r8, g8, b8); valid.fullcolor = TRUE; } else if (StrCmpIW(equal_left, L"color") == 0) { // {LowEdge, HighEdge, R, G, B}, Support up to 16 thresholds quote_pos = equal_right; for (uint32_t i = 0; i < 5; i++) // R, G, B { quote_next = StrChrW(quote_pos, L','); if (quote_next != NULL) // , still exists { StringCchCopyNW(quote_tmp, BS_TOKEN_BUF_SIZE, quote_pos, quote_next-quote_pos); // Copy a number quote_pos = quote_next+1; // +1 for , } else // NULL, no ','! StringCchCopyW(quote_tmp, BS_TOKEN_BUF_SIZE, quote_pos); // Copy last number dword = _wtoi(quote_tmp); if (!(0 <= dword && dword <= 255)) JV_ErrorHandle(JVERR_OPT_INI_INVALID_COLOR, FALSE); switch (i) { case 0: lowedge8 = dword; break; case 1: highedge8 = dword; break; case 2: r8 = dword; break; case 3: g8 = dword; break; case 4: b8 = dword; break; } } if (BL_COLOR_LEVEL <= color_idx) JV_ErrorHandle(JVERR_OPT_INI_TOO_MUCH_COLOR, FALSE); option.threshold[color_idx*2+0] = lowedge8; option.threshold[color_idx*2+1] = highedge8; option.color[color_idx] = RGB(r8, g8, b8); color_idx++; } break; } } } for (uint32_t i = color_idx; i < BL_COLOR_LEVEL; i++) { option.color[i] = 0; option.threshold[2*i] = 0; option.threshold[2*i+1] = 0; } // Free allocated byte in file_buf if (file_buf != BL_DefaultSettingStr) { free(file_buf); file_buf = NULL; } // Debug print #ifdef _DEBUG_CONSOLE puts("[Setting]"); printf("showcharge = %u\n", option.showcharge); printf("monitor = %u\n", option.monitor); printf("position = %u\n", option.position); printf("taskbar = %u\n", option.taskbar); printf("transparency = %u\n", option.transparency); printf("height = %u\n", option.height); putchar('\n'); puts("[Color]"); printf("defaultcolor = %lu,%lu,%lu\n", BLU_RGB_R(option.defaultcolor), BLU_RGB_G(option.defaultcolor), BLU_RGB_B(option.defaultcolor)); printf("chargecolor = %lu,%lu,%lu\n", BLU_RGB_R(option.chargecolor), BLU_RGB_G(option.chargecolor), BLU_RGB_B(option.chargecolor)); for (uint32_t i = 0; i < BL_COLOR_LEVEL; i++) { printf("color[%02d] = %lu,%lu,%lu\n", i, BLU_RGB_R(option.color[i]), BLU_RGB_G(option.color[i]), BLU_RGB_B(option.color[i])); printf("threshold[%02d] = %u\n", 2*i, option.threshold[2*i]); printf("threshold[%02d] = %u\n", 2*i+1, option.threshold[2*i+1]); } putchar('\n'); puts("[Event]"); // For WndProcedure Debug Message #endif // Check necessary options are read successfully if (!(valid.showcharge && valid.monitor && valid.position && valid.taskbar && valid.transparency && valid.height // Section [General] && valid.defaultcolor && valid.chargecolor && valid.fullcolor)) // Section [Color] { JV_ErrorHandle(JVERR_OPT_INI_MISSING_OPTIONS, FALSE); } return 0; }
/********************************************************************* * add_zone_to_listview [internal] * */ static void add_zone_to_listview(secdlg_data *sd, DWORD *pindex, DWORD zone) { DWORD lv_index = *pindex; ZONEATTRIBUTES *za = &sd->zone_attr[lv_index]; LVITEMW lvitem; HRESULT hr; INT iconid = 0; HMODULE hdll = NULL; WCHAR * ptr; HICON icon; TRACE("item %d (zone %d)\n", lv_index, zone); sd->zones[lv_index] = zone; memset(&lvitem, 0, sizeof(LVITEMW)); memset(za, 0, sizeof(ZONEATTRIBUTES)); za->cbSize = sizeof(ZONEATTRIBUTES); hr = IInternetZoneManager_GetZoneAttributes(sd->zone_mgr, zone, za); if (SUCCEEDED(hr)) { TRACE("displayname: %s\n", debugstr_w(za->szDisplayName)); TRACE("description: %s\n", debugstr_w(za->szDescription)); TRACE("minlevel: 0x%x, recommended: 0x%x, current: 0x%x (flags: 0x%x)\n", za->dwTemplateMinLevel, za->dwTemplateRecommended, za->dwTemplateCurrentLevel, za->dwFlags); if (za->dwFlags & ZAFLAGS_NO_UI ) { TRACE("item %d (zone %d): UI disabled for %s\n", lv_index, zone, debugstr_w(za->szDisplayName)); return; } sd->levels[lv_index] = za->dwTemplateCurrentLevel; lvitem.mask = LVIF_TEXT | LVIF_IMAGE | LVIF_PARAM; lvitem.iItem = lv_index; lvitem.iSubItem = 0; lvitem.pszText = za->szDisplayName; lvitem.lParam = (LPARAM) zone; /* format is "filename.ext#iconid" */ ptr = StrChrW(za->szIconPath, '#'); if (ptr) { *ptr = 0; ptr++; iconid = StrToIntW(ptr); hdll = LoadLibraryExW(za->szIconPath, NULL, LOAD_LIBRARY_AS_DATAFILE); TRACE("%p: icon #%d from %s\n", hdll, iconid, debugstr_w(za->szIconPath)); icon = LoadImageW(hdll, MAKEINTRESOURCEW(iconid), IMAGE_ICON, GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON), LR_SHARED); if (!icon) { FIXME("item %d (zone %d): missing icon #%d in %s\n", lv_index, zone, iconid, debugstr_w(za->szIconPath)); } /* the failure result (NULL) from LoadImageW let ImageList_AddIcon fail with -1, which is reused in ListView_InsertItemW to disable the image */ lvitem.iImage = ImageList_AddIcon(sd->himages, icon); } else FIXME("item %d (zone %d): malformed szIconPath %s\n", lv_index, zone, debugstr_w(za->szIconPath)); if (ListView_InsertItemW(sd->hlv, &lvitem) >= 0) { /* activate first item in the listview */ if (! lv_index) { lvitem.state = LVIS_FOCUSED | LVIS_SELECTED; lvitem.stateMask = LVIS_FOCUSED | LVIS_SELECTED; SendMessageW(sd->hlv, LVM_SETITEMSTATE, 0, (LPARAM) &lvitem); sd->last_level = ~0; update_zone_info(sd, lv_index); } (*pindex)++; } FreeLibrary(hdll); } else FIXME("item %d (zone %d): GetZoneAttributes failed with 0x%x\n", lv_index, zone, hr); }
HRESULT ParseAsmDir(LPWSTR pszAsmDir, CTransCache *pTC) { HRESULT hr=S_OK; TRANSCACHEINFO *pTCInfo = pTC->_pInfo; WCHAR wzDirName[MAX_PATH+1]; LPWSTR pwzTemp=NULL, pwzStringLeft=NULL,pwzCulture=NULL ; DWORD dwLen =0; WORD wVerA, wVerB, wVerC, wVerD; PBYTE lpByte=NULL; ASSERT(pTC); pTCInfo = pTC->_pInfo; StrCpy(wzDirName, pszAsmDir); pwzStringLeft = wzDirName; pwzTemp = StrChrW(pwzStringLeft, ATTR_SEPARATOR_CHAR); if(!pwzTemp) { hr = E_UNEXPECTED; goto exit; } *pwzTemp = '\0'; hr = VersionFromString(pwzStringLeft, &wVerA, &wVerB, &wVerC, &wVerD); if(FAILED(hr)) goto exit; pTCInfo->dwVerHigh = MAKELONG(wVerB, wVerA); pTCInfo->dwVerLow = MAKELONG(wVerD, wVerC); pwzStringLeft = ++pwzTemp; pwzTemp = StrChrW(pwzStringLeft, ATTR_SEPARATOR_CHAR); if(!pwzTemp) { hr = E_UNEXPECTED; goto exit; } *pwzTemp = '\0'; dwLen = lstrlenW(pwzStringLeft)+1; pwzCulture = NEW(WCHAR[dwLen]); if(!pwzCulture) { hr = E_OUTOFMEMORY; goto exit; } StrCpy(pwzCulture, pwzStringLeft); pwzStringLeft = ++pwzTemp; pwzTemp = StrChrW(pwzStringLeft, ATTR_SEPARATOR_CHAR); if(pwzTemp) { *pwzTemp = '\0'; // we don't parse beyond this point. } dwLen = lstrlenW(pwzStringLeft)/2; if(dwLen) { lpByte = NEW(BYTE[dwLen]); if(!lpByte) { hr = E_OUTOFMEMORY; goto exit; } CParseUtils::UnicodeHexToBin(pwzStringLeft, lstrlenW(pwzStringLeft), lpByte ); } pTCInfo->blobPKT.pBlobData = lpByte; lpByte = NULL; pTCInfo->blobPKT.cbSize = dwLen ; pTCInfo->pwzCulture = pwzCulture; pwzCulture = NULL; exit: SAFEDELETEARRAY(lpByte); SAFEDELETEARRAY(pwzCulture); return hr; }