int mywcscmp(PWSTR a, int alen, PWSTR b, int blen) { int len, res; if (-1 == alen) alen = (int)wcslen(a); if (-1 == blen) blen = (int)wcslen(b); len = alen < blen ? alen : blen; /* we should still be in the C locale */ if (OptCaseInsensitiveCmp) res = _wcsnicmp(a, b, len); else res = wcsncmp(a, b, len); if (0 == res) res = alen - blen; return res; }
bool IsRelativeSymlinkSafe(CommandData *Cmd,const wchar *SrcName,const wchar *PrepSrcName,const wchar *TargetName) { // Catch root dir based /path/file paths also as stuff like \\?\. // Do not check PrepSrcName here, it can be root based if destination path // is a root based. if (IsFullRootPath(SrcName) || IsFullRootPath(TargetName)) return false; // We could check just prepared src name, but for extra safety // we check both original (as from archive header) and prepared // (after applying the destination path and -ep switches) names. int AllowedDepth=CalcAllowedDepth(SrcName); // Original name depth. // Remove the destination path from prepared name if any. We should not // count the destination path depth, because the link target must point // inside of this path, not outside of it. size_t ExtrPathLength=wcslen(Cmd->ExtrPath); if (ExtrPathLength>0 && wcsncmp(PrepSrcName,Cmd->ExtrPath,ExtrPathLength)==0) { PrepSrcName+=ExtrPathLength; while (IsPathDiv(*PrepSrcName)) PrepSrcName++; } int PrepAllowedDepth=CalcAllowedDepth(PrepSrcName); // Number of ".." in link target. int UpLevels=0; for (int Pos=0;*TargetName!=0;Pos++) { bool Dot2=TargetName[0]=='.' && TargetName[1]=='.' && (IsPathDiv(TargetName[2]) || TargetName[2]==0) && (Pos==0 || IsPathDiv(*(TargetName-1))); if (Dot2) UpLevels++; TargetName++; } return AllowedDepth>=UpLevels && PrepAllowedDepth>=UpLevels; }
FRR_TYPE ReplaceFunctionW(const wchar_t *dllName, const char *funcName, FUNCPTR newFunc, UINT opcodesNumber, FUNCPTR* origFunc) { // Cache the results of the last search for the module // Assume that there was no DLL unload between static wchar_t cachedName[MAX_PATH+1]; static HMODULE cachedHM = 0; if (!dllName || !*dllName) return FRR_NODLL; if (!cachedHM || wcsncmp(dllName, cachedName, MAX_PATH) != 0) { // Find the module handle for the input dll HMODULE hModule = GetModuleHandleW(dllName); if (hModule == 0) { // Couldn't find the module with the input name cachedHM = 0; return FRR_NODLL; } cachedHM = hModule; wcsncpy(cachedName, dllName, MAX_PATH); } FARPROC inpFunc = GetProcAddress(cachedHM, funcName); if (inpFunc == 0) { // Function was not found return FRR_NOFUNC; } if (!InsertTrampoline((void*)inpFunc, (void*)newFunc, opcodesNumber, origFunc)){ // Failed to insert the trampoline to the target address return FRR_FAILED; } return FRR_OK; }
/** * w32u_check_UTF8(): Check if UTF-8 is supported. * @return 0 if UTF-8 is supported; non-zero if it isn't. */ static int WINAPI w32u_check_UTF8(void) { static const char s_utf8_test[] = { 0xC2, 0xA5, 0xC3, 0xB3, 0xC3, 0xB9, 0x20, 0x6A, 0xC3, 0xBC, 0xC5, 0x9F, 0x74, 0x20, 0xC2, 0xA3, 0xC3, 0xB5, 0xC5, 0x9F, 0xE2, 0x94, 0xBC, 0x20, 0x54, 0xE1, 0xB8, 0xA9, 0xE1, 0xBA, 0xBD, 0x20, 0xC4, 0xA2, 0xC3, 0xA2, 0x6D, 0xC4, 0x95, 0x2E, 0x20, 0xE2, 0x8C, 0x98, 0x00 }; static const wchar_t s_utf16_test[] = { 0x00A5, 0x00F3, 0x00F9, 0x0020, 0x006A, 0x00FC, 0x015F, 0x0074, 0x0020, 0x00A3, 0x00F5, 0x015F, 0x253C, 0x0020, 0x0054, 0x1E29, 0x1EBD, 0x0020, 0x0122, 0x00E2, 0x006D, 0x0115, 0x002E, 0x0020, 0x2318, 0x0000 }; int s_len = MultiByteToWideChar(CP_UTF8, 0, s_utf8_test, -1, NULL, 0); if (s_len != (sizeof(s_utf16_test)/sizeof(s_utf16_test[0]))) { // Required length is incorrect. // This usually means it's 0, in which case // the OS doesn't support UTF-8. return -1; } // Convert the test string from UTF-8 to UTF-16. wchar_t s_utf16_result[sizeof(s_utf16_test)/sizeof(s_utf16_test[0])]; s_utf16_result[0] = 0x00; MultiByteToWideChar(CP_UTF8, 0, s_utf8_test, -1, s_utf16_result, sizeof(s_utf16_result)/sizeof(s_utf16_result[0])); // Verify that the string matches. if (wcsncmp(s_utf16_test, s_utf16_result, sizeof(s_utf16_test)/sizeof(s_utf16_test[0])) != 0) { // String doesn't match. return -2; } // UTF-8 is supported. return 0; }
VOID ScanApplyObjectsRules() { HANDLE hObjDir; OBJECT_ATTRIBUTES ObjAttrib; UNICODE_STRING uniGlobalDir; uniGlobalDir.Buffer = L"\\GLOBAL??"; uniGlobalDir.Length = (USHORT)(wcslen(uniGlobalDir.Buffer) * sizeof(WCHAR)); uniGlobalDir.MaximumLength = (USHORT)(uniGlobalDir.Length + sizeof(WCHAR)); InitializeObjectAttributes(&ObjAttrib, &uniGlobalDir, OBJ_CASE_INSENSITIVE, NULL, NULL); NTSTATUS status = ntdll_ZwOpenDirectoryObject(&hObjDir, DIRECTORY_QUERY, &ObjAttrib); if (status != STATUS_SUCCESS) { DebugOut("Failed to open directory object! (status = %x)\n", status); return; } SIZE_T len = 0x1000; PVOID pBuffer = NULL; do { if (pBuffer) { free(pBuffer); len *= 2; } DWORD context = 0, dwRet; pBuffer = malloc(len); status = ntdll_ZwQueryDirectoryObject(hObjDir, pBuffer, (ULONG)len, FALSE, TRUE, &context, &dwRet); } while (status == STATUS_MORE_ENTRIES || status == STATUS_BUFFER_TOO_SMALL); if (status == STATUS_SUCCESS) { PDIRECTORY_BASIC_INFORMATION pObject = (PDIRECTORY_BASIC_INFORMATION)pBuffer; while (pObject->ObjectName.Length != 0) { if (pObject->ObjectName.Length > ObjectPrefixLength * sizeof(WCHAR)) { if (wcsncmp(pObject->ObjectName.Buffer, ObjectPrefix, ObjectPrefixLength) == 0) { DebugOut("Found matching object: \"%S\"\n", pObject->ObjectName.Buffer); AddAllowSidForDevice(pObject->ObjectName.Buffer, gpSid, gSidLength); } } pObject++; } } else DebugOut("Failed to query directory object! (status = %x)\n", status); free(pBuffer); }
static wchar_t *find_erlexec_dir(wchar_t *erlpath) { /* Assume that the path to erl is absolute and * that it is not a symbolic link*/ wchar_t *dir =_wcsdup(erlpath); wchar_t *p; wchar_t *p2; /* Chop of base name*/ for (p = dir+wcslen(dir)-1 ;p >= dir && *p != L'\\'; --p) ; *p =L'\0'; p--; /* Check if dir path is like ...\install_dir\erts-vsn\bin */ for (;p >= dir && *p != L'\\'; --p) ; p--; for (p2 = p;p2 >= dir && *p2 != '\\'; --p2) ; p2++; if (wcsncmp(p2, L"erts-", wcslen(L"erts-")) == 0) { p = _wcsdup(dir); free(dir); return p; } /* Assume that dir path is like ...\install_dir\bin */ *++p =L'\0'; /* chop off bin dir */ p = find_erlexec_dir2(dir); free(dir); if (p == NULL) { error("Cannot find erlexec.exe"); } else { return p; } }
// One trailing (or middle) asterisk allowed bool CompareFileMask(const wchar_t* asFileName, const wchar_t* asMask) { if (!asFileName || !*asFileName || !asMask || !*asMask) return false; // Any file? if (*asMask == L'*' && *(asMask+1) == 0) return true; int iCmp = -1; wchar_t sz1[MAX_PATH+1], sz2[MAX_PATH+1]; lstrcpyn(sz1, asFileName, countof(sz1)); size_t nLen1 = lstrlen(sz1); CharUpperBuffW(sz1, (DWORD)nLen1); lstrcpyn(sz2, asMask, countof(sz2)); size_t nLen2 = lstrlen(sz2); CharUpperBuffW(sz2, (DWORD)nLen2); wchar_t* pszAst = wcschr(sz2, L'*'); if (!pszAst) { iCmp = lstrcmp(sz1, sz2); } else { *pszAst = 0; size_t nLen = pszAst - sz2; size_t nRight = lstrlen(pszAst+1); if (wcsncmp(sz1, sz2, nLen) == 0) { if (!nRight) iCmp = 0; else if (nLen1 >= (nRight + nLen)) iCmp = lstrcmp(sz1+nLen1-nRight, pszAst+1); } } return (iCmp == 0); }
int git_win32_path__cwd(wchar_t *out, size_t len) { int cwd_len; if ((cwd_len = path__cwd(out, len)) < 0) return -1; /* UNC paths */ if (wcsncmp(L"\\\\", out, 2) == 0) { /* Our buffer must be at least 5 characters larger than the * current working directory: we swallow one of the leading * '\'s, but we we add a 'UNC' specifier to the path, plus * a trailing directory separator, plus a NUL. */ if (cwd_len > MAX_PATH - 4) { errno = ENAMETOOLONG; return -1; } memmove(out+2, out, sizeof(wchar_t) * cwd_len); out[0] = L'U'; out[1] = L'N'; out[2] = L'C'; cwd_len += 2; } /* Our buffer must be at least 2 characters larger than the current * working directory. (One character for the directory separator, * one for the null. */ else if (cwd_len > MAX_PATH - 2) { errno = ENAMETOOLONG; return -1; } return cwd_len; }
/* * Check workdir\fname is inside config_dir * The logic here is simple: we may reject some valid paths if ..\ is in any of the strings */ static BOOL CheckConfigPath(const WCHAR *workdir, const WCHAR *fname, const settings_t *s) { WCHAR tmp[MAX_PATH]; const WCHAR *config_file = NULL; const WCHAR *config_dir = NULL; /* convert fname to full path */ if (PathIsRelativeW(fname) ) { snwprintf(tmp, _countof(tmp), L"%s\\%s", workdir, fname); tmp[_countof(tmp)-1] = L'\0'; config_file = tmp; } else { config_file = fname; } #ifdef UNICODE config_dir = s->config_dir; #else if (MultiByteToWideChar(CP_UTF8, 0, s->config_dir, -1, widepath, MAX_PATH) == 0) { MsgToEventLog(M_SYSERR, TEXT("Failed to convert config_dir name to WideChar")); return FALSE; } config_dir = widepath; #endif if (wcsncmp(config_dir, config_file, wcslen(config_dir)) == 0 && wcsstr(config_file + wcslen(config_dir), L"..") == NULL) { return TRUE; } return FALSE; }
HANDLE MakeSISOpenFile(LPCWSTR pszFilename, DWORD dwAccessMode, DWORD dwCreateFlags) // Open file with Unicode filename correctly under Win95 and WinNT { HANDLE hFile; char pszMultiByte[MAX_PATH] = "\0"; LPWSTR p=(LPWSTR)pszFilename; if (!wcsncmp(pszFilename,L"./",2)) p+=2; ::WideCharToMultiByte(CP_OEMCP, // code page 0, // performance and mapping flags p, // address of wide-character string -1, // number of characters in string pszMultiByte, // address of buffer for new string MAX_PATH, // size of buffer NULL, // address of default for unmappable characters NULL); // address of flag set when default char. used hFile = ::CreateFileA(pszMultiByte, dwAccessMode, 0, NULL, dwCreateFlags, FILE_ATTRIBUTE_NORMAL, NULL); return hFile; }
BOOL IOemPS::isTSPrinter(HANDLE hPrinter){ DWORD dwBytesReturned, dwBytesNeeded; GetPrinter(hPrinter, 2, NULL, NULL, &dwBytesNeeded); PRINTER_INFO_2* p2 = (PRINTER_INFO_2*)GlobalAlloc(GPTR, dwBytesNeeded); if ( ! ::GetPrinter(hPrinter, 2, (LPBYTE)p2, dwBytesNeeded, &dwBytesReturned)){ GlobalFree(p2); return FALSE; } if (p2->Attributes & PRINTER_ATTRIBUTE_TS){ GlobalFree(p2); return TRUE; } /* on Windows XP, no support for PRINTER_ATTRIBUTE_TS attribute*/ if ( wcsncmp(p2->pPortName, L"TS", 2) == 0){ GlobalFree(p2); return TRUE; } GlobalFree(p2); return FALSE; }
GIT_INLINE(int) path__cwd(wchar_t *path, int size) { int len; if ((len = GetCurrentDirectoryW(size, path)) == 0) { errno = GetLastError() == ERROR_ACCESS_DENIED ? EACCES : ENOENT; return -1; } else if (len > size) { errno = ENAMETOOLONG; return -1; } /* The Win32 APIs may return "\\?\" once you've used it first. * But it may not. What a gloriously predictible API! */ if (wcsncmp(path, PATH__NT_NAMESPACE, PATH__NT_NAMESPACE_LEN)) return len; len -= PATH__NT_NAMESPACE_LEN; memmove(path, path + PATH__NT_NAMESPACE_LEN, sizeof(wchar_t) * len); return len; }
int delete_name(wchar_t name[]) { int found = 0; PersonFeatureList *tmp = g_feature_list, *before; while(tmp != NULL) { if (wcsncmp(name, tmp->feature.name, wcslen(name)) == 0) { found = 1; break; } before = tmp; tmp = tmp->next; } if (found) { if(tmp == g_feature_list) g_feature_list = g_feature_list->next; else before->next = tmp->next; free(tmp); save_list(); } return found; }
int ensure_absolute_path(wchar_t *out, const wchar_t *in, int length) { if(!wcsncmp(in, L"\\??\\", 4)) { length -= 4, in += 4; wcsncpy(out, in, length < MAX_PATH ? length : MAX_PATH); return out[length] = 0, length; } else if(in[1] != ':' || (in[2] != '\\' && in[2] != '/')) { wchar_t cur_dir[MAX_PATH], fname[MAX_PATH]; GetCurrentDirectoryW(ARRAYSIZE(cur_dir), cur_dir); // ensure the filename is zero-terminated wcsncpy(fname, in, length < MAX_PATH ? length : MAX_PATH); fname[length] = 0; PathCombineW(out, cur_dir, fname); return lstrlenW(out); } else { wcsncpy(out, in, length < MAX_PATH ? length : MAX_PATH); return out[length] = 0, length; } }
void STDMETHODCALLTYPE IECrossfireBHO::OnNavigateComplete2(IDispatch *pDisp, VARIANT *pvarURL) { if (m_contextCreated || m_serverState != STATE_CONNECTED) { return; } CComPtr<IUnknown> webBrowserIUnknown = NULL; HRESULT hr = m_webBrowser->QueryInterface(IID_IUnknown, (void**)&webBrowserIUnknown); if (FAILED(hr)) { Logger::error("IECrossfireBHO.OnNavigateComplete2(): QI(IUnknown)[1] failed", hr); } else { CComPtr<IUnknown> pDispIUnknown = NULL; hr = pDisp->QueryInterface(IID_IUnknown, (void**)&pDispIUnknown); if (FAILED(hr)) { Logger::error("IECrossfireBHO.OnNavigateComplete2(): QI(IUnknown)[2] failed", hr); } else { if (webBrowserIUnknown == pDispIUnknown) { /* this is the top-level page frame */ wchar_t* url = pvarURL->bstrVal; wchar_t* hash = wcschr(url, wchar_t('#')); if (!hash || !m_lastUrl || wcsncmp(url, m_lastUrl, hash - url) != 0) { DWORD processId = GetCurrentProcessId(); DWORD threadId = GetCurrentThreadId(); HRESULT hr = m_server->contextCreated(processId, threadId, url); if (FAILED(hr)) { Logger::error("IECrossfireBHO.OnNavigateComplete2(): contextCreated() failed", hr); } else { m_contextCreated = true; } } if (m_lastUrl) { free(m_lastUrl); } m_lastUrl = _wcsdup(url); } } } }
int regReadString(PWCHAR key, PWCHAR val, PUNICODE_STRING result) { WCHAR *path; RTL_QUERY_REGISTRY_TABLE qtbl[2]; NTSTATUS status; path = ExAllocatePoolWithTag ( PagedPool, (wcslen(key)+20)*sizeof(WCHAR), CRASH_TAG); if (!path) return -1; result->Buffer[0] = L'\0'; result->Length = 0; wcscpy(path, L"\\Registry\\Machine\\"); if (wcsncmp(key, path, wcslen(path))==0) wcscpy(path, key); else wcscat(path, key); qtbl[0].QueryRoutine = regReadStringCB; qtbl[0].Flags = RTL_QUERY_REGISTRY_NOEXPAND; qtbl[0].Name = val; qtbl[0].EntryContext = NULL; qtbl[0].DefaultType = REG_NONE; qtbl[0].DefaultData = NULL; qtbl[0].DefaultLength = 0; memset(&(qtbl[1]), 0, sizeof(qtbl[1])); status = RtlQueryRegistryValues(RTL_REGISTRY_ABSOLUTE, path, qtbl, result, NULL); ExFreePool(path); if (status == STATUS_SUCCESS) return 0; return -1; }
void GenericPlayer::NewData(const WCHAR *data, size_t len) { // m_log(_T("NewData"), _T("Processing")); if (data[0] == L'\0') { // m_log(_T("NewData"), _T("ERROR: Text is empty")); return; } EnterCriticalSection(&cs); len = min(len, 1023); if (wcsncmp(received, data, len) != 0) { // m_log(_T("NewData"), _T("Got new text, scheduling update")); wcsncpy(received, data, len); received[len] = L'\0'; //#ifdef UNICODE // m_log(_T("NewData"), _T("Text: %s"), received); //#else // m_log(_T("NewData"), _T("Text: %S"), received); //#endif KILLTIMER(hSendTimer); hSendTimer = SetTimer(NULL, NULL, 300, (TIMERPROC)SendTimerProc); // Do the processing after we return true } // else // { // m_log(_T("NewData"), _T("END: Text is the same as last time")); // } LeaveCriticalSection(&cs); }
// IsEqual static bool IsEqual(COpcText& cToken, LPCWSTR szValue1, LPCWSTR szValue2, UINT uSize = -1) { if (szValue1 == NULL || szValue2 == NULL) { return (szValue1 == szValue2); } else if (uSize == -1 && cToken.GetIgnoreCase()) { return (wcsicmp(szValue1, szValue2) == 0); } else if (uSize == -1) { return (wcscmp(szValue1, szValue2) == 0); } else if (cToken.GetIgnoreCase()) { return (wcsnicmp(szValue1, szValue2, uSize) == 0); } return (wcsncmp(szValue1, szValue2, uSize) == 0); }
bool terminal_try_attach(void) { // mpv.exe is a flagged as a GUI application, but it acts as a console // application when started from the console wrapper (see // osdep/win32-console-wrapper.c). The console wrapper sets // _started_from_console=yes, so check that variable before trying to // attach to the console. wchar_t console_env[4] = { 0 }; if (!GetEnvironmentVariableW(L"_started_from_console", console_env, 4)) return false; if (wcsncmp(console_env, L"yes", 4)) return false; SetEnvironmentVariableW(L"_started_from_console", NULL); if (!AttachConsole(ATTACH_PARENT_PROCESS)) return false; // We have a console window. Redirect output streams to that console's // low-level handles, so things that use printf directly work later on. reopen_console_handle(STD_OUTPUT_HANDLE, STDOUT_FILENO, stdout); reopen_console_handle(STD_ERROR_HANDLE, STDERR_FILENO, stderr); return true; }
bool ParseCommandLine(LPCTSTR lpCmdLine, HRESULT* pnRetCode ) throw( ) { m_nRestarting = 1; TCHAR szTokens[] = _T("-/"); LPCTSTR lpszToken = FindOneOf(lpCmdLine, szTokens); while (lpszToken != NULL) { if (WordCmpI(lpszToken, _T("Restarting"))==0) { m_nRestarting = 10; } #if defined(OS_WINDOWS) else if (wcsncmp(lpszToken, _T("approot"),7)==0) { char* token = wce_wctomb(lpszToken); //parseToken will allocate extra byte at the end of the returned token value char* path = parseToken( token, strlen(token) ); if (path) { int len = strlen(path); if (!(path[len]=='\\' || path[len]=='/')) { path[len] = '\\'; path[len+1] = 0; } __setRootPath(path); free(path); } free(token); } #endif lpszToken = FindOneOf(lpszToken, szTokens); } // rho_logconf_Init(RhoGetRootPath()); // runAllLogTests(); return __super::ParseCommandLine(lpCmdLine, pnRetCode); }
uint O2IPFilter:: filtering(ulong ip, const wstrarray &hostnames) { uint ret = DefaultFlag; Lock(); for (uint i = 0; i < records.size(); i++) { if (records[i].host.empty()) { if ((ip & records[i].mask) == records[i].ip) ret = records[i].flag; } else if (!hostnames.empty()) { for (uint j = 0; j < hostnames.size(); j++) { int offset = hostnames[j].size() - records[i].host.size(); if (offset >= 0 && wcsncmp(&hostnames[j][offset], records[i].host.c_str(), records[i].host.size()) == 0) ret = records[i].flag; } } } Unlock(); return (ret); }
static IXMLDOMElement *FindFirstElement(IXMLDOMElement *parent, LPCTSTR name, int length) { if (parent == NULL) { return NULL; } if (length == -1) { length = _tcslen(name); } CComPtr<IXMLDOMNode> child; parent->get_firstChild(&child); while (child != NULL) { CComQIPtr<IXMLDOMElement> e(child); if (e != NULL) { CComBSTR tagName; e->get_tagName(&tagName); if (tagName.Length() == length && wcsncmp(tagName, name, length) == 0) { return e.Detach(); } } CComPtr<IXMLDOMNode> next; child->get_nextSibling(&next); child = next; } return NULL; }
wchar_t* wcswcs(const wchar_t* ws1, const wchar_t* ws2) { wchar_t* wcspos; if (ws1 == 0) return 0; if (wcslen(ws2)==0) return (wchar_t*)ws1; wcspos = (wchar_t*)ws1; while (*wcspos != 0) { if (wcsncmp(wcspos, ws2, wcslen(ws2)) == 0) { return wcspos; } wcspos++; } return NULL; }
void UL::setValueFromURN(const wchar_t* str, UInt32 strLen) { // Check if the length is correct if (strLen != 45) { return; } // Check if the prefix is correct if (wcsncmp(str, L"urn:x-ul:", 9) != 0) { return; } // OK, lets crunch those hex digits str += 9; UInt32 pos = 0; UInt32 byte = 1; UInt8 sixteens; UInt8 units; while ((pos < strLen - 1) && (byte <= 16)) { sixteens = 16 * hexCharToVal(str[pos]); units = hexCharToVal(str[pos + 1]); setByte(byte, sixteens + units); if (pos == 6 || pos == 11 || pos == 16 || pos == 25) { pos += 3; } else { pos += 2; } ++byte; } }
static wchar_t *uncpathw(const wchar_t *path) { DWORD len = 0; unsigned int pathlen; wchar_t *stripme, *strip_from, *dest = malloc((PATH_MAX + 1) * sizeof(wchar_t)); if(!dest) return NULL; pathlen = wcslen(path); if(wcsncmp(path, L"\\\\", 2)) { /* NOT already UNC */ memcpy(dest, L"\\\\?\\", 8); if(pathlen < 2 || path[1] != L':' || *path < L'A' || *path > L'z' || (*path > L'Z' && *path < L'a')) { /* Relative path */ len = GetCurrentDirectoryW(PATH_MAX - 5, &dest[4]); if(!len || len > PATH_MAX - 5) { free(dest); return NULL; } if(*path == L'\\') len = 6; /* Current drive root */ else { len += 4; /* A 'really' relative path */ dest[len] = L'\\'; len++; } } else { /* C:\ and friends */ len = 4; } } else { /* UNC already */ len = 0; } if(pathlen >= PATH_MAX - len) { free(dest); return NULL; } wcscpy(&dest[len], path); len = wcslen(dest); strip_from = &dest[3]; /* append a backslash to naked drives and get rid of . and .. */ if(!wcsncmp(dest, L"\\\\?\\", 4) && (dest[5] == L':') && ((dest[4] >= L'A' && dest[4] <= L'Z') || (dest[4] >= L'a' && dest[4] <= L'z'))) { if(len == 6) { dest[6] = L'\\'; dest[7] = L'\0'; } strip_from = &dest[6]; } while((stripme = wcsstr(strip_from, L"\\."))) { wchar_t *copy_from, *copy_to; if(!stripme[2] || stripme[2] == L'\\') { copy_from = &stripme[2]; copy_to = stripme; } else if (stripme[2] == L'.' && (!stripme[3] || stripme[3] == L'\\')) { *stripme = L'\0'; copy_from = &stripme[3]; copy_to = wcsrchr(strip_from, L'\\'); if(!copy_to) copy_to = stripme; } else { strip_from = &stripme[1]; continue; } while(1) { *copy_to = *copy_from; if(!*copy_from) break; copy_to++; copy_from++; } } /* strip double slashes */ if((stripme = wcsstr(&dest[4], L"\\\\"))) { strip_from = stripme; while(1) { wchar_t c = *strip_from; strip_from++; if(c == L'\\' && *strip_from == L'\\') continue; *stripme = c; stripme++; if(!c) break; } } if(wcslen(dest) == 6 && !wcsncmp(dest, L"\\\\?\\", 4) && (dest[5] == L':') && ((dest[4] >= L'A' && dest[4] <= L'Z') || (dest[4] >= L'a' && dest[4] <= L'z'))) { dest[6] = L'\\'; dest[7] = L'\0'; } return dest; }
int _getopt_internal_r_w ( int argc, wchar_t *const *argv, const wchar_t *optstring, const struct option_w *longopts, int *longind, int long_only, struct _getopt_data_w *d, int posixly_correct ) { int print_errors = d->opterr; if ( argc < 1 ) { return -1; } d->optarg = NULL; if ( d->optind == 0 || !d->__initialized ) { if ( d->optind == 0 ) { d->optind = 1; } optstring = _getopt_initialize_w ( optstring, d, posixly_correct ); d->__initialized = 1; } else if ( optstring[0] == L'-' || optstring[0] == L'+' ) { optstring++; } if ( optstring[0] == L':' ) { print_errors = 0; } if ( d->__nextchar == NULL || *d->__nextchar == L'\0' ) { if ( d->__last_nonopt > d->optind ) { d->__last_nonopt = d->optind; } if ( d->__first_nonopt > d->optind ) { d->__first_nonopt = d->optind; } if ( d->__ordering == PERMUTE ) { if ( d->__first_nonopt != d->__last_nonopt && d->__last_nonopt != d->optind ) { exchange_w ( ( wchar_t ** ) argv, d ); } else if ( d->__last_nonopt != d->optind ) { d->__first_nonopt = d->optind; } while ( d->optind < argc && ( argv[d->optind][0] != L'-' || argv[d->optind][1] == L'\0' ) ) { d->optind++; } d->__last_nonopt = d->optind; } if ( d->optind != argc && !wcscmp ( argv[d->optind], L"--" ) ) { d->optind++; if ( d->__first_nonopt != d->__last_nonopt && d->__last_nonopt != d->optind ) { exchange_w ( ( wchar_t ** ) argv, d ); } else if ( d->__first_nonopt == d->__last_nonopt ) { d->__first_nonopt = d->optind; } d->__last_nonopt = argc; d->optind = argc; } if ( d->optind == argc ) { if ( d->__first_nonopt != d->__last_nonopt ) { d->optind = d->__first_nonopt; } return -1; } if ( ( argv[d->optind][0] != L'-' || argv[d->optind][1] == L'\0' ) ) { if ( d->__ordering == REQUIRE_ORDER ) { return -1; } d->optarg = argv[d->optind++]; return 1; } d->__nextchar = ( argv[d->optind] + 1 + ( longopts != NULL && argv[d->optind][1] == L'-' ) ); } if ( longopts != NULL && ( argv[d->optind][1] == L'-' || ( long_only && ( argv[d->optind][2] || !wcschr ( optstring, argv[d->optind][1] ) ) ) ) ) { wchar_t *nameend; unsigned int namelen; const struct option_w *p; const struct option_w *pfound = NULL; struct option_list { const struct option_w *p; struct option_list *next; } *ambig_list = NULL; int exact = 0; int indfound = -1; int option_index; for ( nameend = d->__nextchar; *nameend && *nameend != L'='; nameend++ ); namelen = ( unsigned int ) ( nameend - d->__nextchar ); for ( p = longopts, option_index = 0; p->name; p++, option_index++ ) if ( !wcsncmp ( p->name, d->__nextchar, namelen ) ) { if ( namelen == ( unsigned int ) wcslen ( p->name ) ) { pfound = p; indfound = option_index; exact = 1; break; } else if ( pfound == NULL ) { pfound = p; indfound = option_index; } else if ( long_only || pfound->has_arg != p->has_arg || pfound->flag != p->flag || pfound->val != p->val ) { struct option_list *newp = ( struct option_list * ) alloca ( sizeof ( *newp ) ); newp->p = p; newp->next = ambig_list; ambig_list = newp; } } if ( ambig_list != NULL && !exact ) { if ( print_errors ) { struct option_list first; first.p = pfound; first.next = ambig_list; ambig_list = &first; fwprintf ( stderr, L"%s: option '%s' is ambiguous; possibilities:", argv[0], argv[d->optind] ); do { fwprintf ( stderr, L" '--%s'", ambig_list->p->name ); ambig_list = ambig_list->next; } while ( ambig_list != NULL ); fputwc ( L'\n', stderr ); } d->__nextchar += wcslen ( d->__nextchar ); d->optind++; d->optopt = 0; return L'?'; } if ( pfound != NULL ) { option_index = indfound; d->optind++; if ( *nameend ) { if ( pfound->has_arg ) { d->optarg = nameend + 1; } else { if ( print_errors ) { if ( argv[d->optind - 1][1] == L'-' ) { fwprintf ( stderr, L"%s: option '--%s' doesn't allow an argument\n", argv[0], pfound->name ); } else { fwprintf ( stderr, L"%s: option '%c%s' doesn't allow an argument\n", argv[0], argv[d->optind - 1][0], pfound->name ); } } d->__nextchar += wcslen ( d->__nextchar ); d->optopt = pfound->val; return L'?'; } } else if ( pfound->has_arg == 1 ) { if ( d->optind < argc ) { d->optarg = argv[d->optind++]; } else { if ( print_errors ) { fwprintf ( stderr, L"%s: option '--%s' requires an argument\n", argv[0], pfound->name ); } d->__nextchar += wcslen ( d->__nextchar ); d->optopt = pfound->val; return optstring[0] == L':' ? L':' : L'?'; } } d->__nextchar += wcslen ( d->__nextchar ); if ( longind != NULL ) { *longind = option_index; } if ( pfound->flag ) { * ( pfound->flag ) = pfound->val; return 0; } return pfound->val; } if ( !long_only || argv[d->optind][1] == L'-' || wcschr ( optstring, *d->__nextchar ) == NULL ) { if ( print_errors ) { if ( argv[d->optind][1] == L'-' ) { fwprintf ( stderr, L"%s: unrecognized option '--%s'\n", argv[0], d->__nextchar ); } else { fwprintf ( stderr, L"%s: unrecognized option '%c%s'\n", argv[0], argv[d->optind][0], d->__nextchar ); } } d->__nextchar = ( wchar_t * ) L""; d->optind++; d->optopt = 0; return L'?'; } } { wchar_t c = *d->__nextchar++; wchar_t *temp = ( wchar_t * ) wcschr ( optstring, c ); if ( *d->__nextchar == L'\0' ) { ++d->optind; } if ( temp == NULL || c == L':' || c == L';' ) { if ( print_errors ) { fwprintf ( stderr, L"%s: invalid option -- '%c'\n", argv[0], c ); } d->optopt = c; return L'?'; } if ( temp[0] == L'W' && temp[1] == L';' ) { wchar_t *nameend; const struct option_w *p; const struct option_w *pfound = NULL; int exact = 0; int ambig = 0; int indfound = 0; int option_index; if ( longopts == NULL ) { goto no_longs; } if ( *d->__nextchar != L'\0' ) { d->optarg = d->__nextchar; d->optind++; } else if ( d->optind == argc ) { if ( print_errors ) { fwprintf ( stderr, L"%s: option requires an argument -- '%c'\n", argv[0], c ); } d->optopt = c; if ( optstring[0] == L':' ) { c = L':'; } else { c = L'?'; } return c; } else { d->optarg = argv[d->optind++]; } for ( d->__nextchar = nameend = d->optarg; *nameend && *nameend != L'='; nameend++ ); for ( p = longopts, option_index = 0; p->name; p++, option_index++ ) if ( !wcsncmp ( p->name, d->__nextchar, nameend - d->__nextchar ) ) { if ( ( unsigned int ) ( nameend - d->__nextchar ) == wcslen ( p->name ) ) { pfound = p; indfound = option_index; exact = 1; break; } else if ( pfound == NULL ) { pfound = p; indfound = option_index; } else if ( long_only || pfound->has_arg != p->has_arg || pfound->flag != p->flag || pfound->val != p->val ) { ambig = 1; } } if ( ambig && !exact ) { if ( print_errors ) { fwprintf ( stderr, L"%s: option '-W %s' is ambiguous\n", argv[0], d->optarg ); } d->__nextchar += wcslen ( d->__nextchar ); d->optind++; return L'?'; } if ( pfound != NULL ) { option_index = indfound; if ( *nameend ) { if ( pfound->has_arg ) { d->optarg = nameend + 1; } else { if ( print_errors ) { fwprintf ( stderr, L"%s: option '-W %s' doesn't allow an argument\n", argv[0], pfound->name ); } d->__nextchar += wcslen ( d->__nextchar ); return L'?'; } } else if ( pfound->has_arg == 1 ) { if ( d->optind < argc ) { d->optarg = argv[d->optind++]; } else { if ( print_errors ) { fwprintf ( stderr, L"%s: option '-W %s' requires an argument\n", argv[0], pfound->name ); } d->__nextchar += wcslen ( d->__nextchar ); return optstring[0] == L':' ? L':' : L'?'; } } else { d->optarg = NULL; } d->__nextchar += wcslen ( d->__nextchar ); if ( longind != NULL ) { *longind = option_index; } if ( pfound->flag ) { * ( pfound->flag ) = pfound->val; return 0; } return pfound->val; } no_longs: d->__nextchar = NULL; return L'W'; } if ( temp[1] == L':' ) { if ( temp[2] == L':' ) { if ( *d->__nextchar != L'\0' ) { d->optarg = d->__nextchar; d->optind++; } else { d->optarg = NULL; } d->__nextchar = NULL; } else { if ( *d->__nextchar != L'\0' ) { d->optarg = d->__nextchar; d->optind++; } else if ( d->optind == argc ) { if ( print_errors ) { fwprintf ( stderr, L"%s: option requires an argument -- '%c'\n", argv[0], c ); } d->optopt = c; if ( optstring[0] == L':' ) { c = L':'; } else { c = L'?'; } } else { d->optarg = argv[d->optind++]; } d->__nextchar = NULL; } } return c; } }
/// /// Get any register aliases for the register passed in. This is heavily used in the x86/x64 meta-disassembly, to map ah, al, ax, eax, and rax together, for example const OPERAND * GetRegisterAliases( ULONG dwProcessor, PCWSTR pwzRegister, size_t cchRegister, TAINT_TRACKING_MODE eMode ) { OPERAND *pRegisterAliases = NULL; switch( dwProcessor ) { case IMAGE_FILE_MACHINE_I386: if( eMode == SET_TAINT ) { pRegisterAliases = X86_REGISTER_TAINT_ALIASES; } else if( eMode == CLEAR_TAINT ) { pRegisterAliases = X86_REGISTER_CLEAR_ALIASES; } else { return( NULL ); } break; case IMAGE_FILE_MACHINE_ARM: case IMAGE_FILE_MACHINE_THUMB: case IMAGE_FILE_MACHINE_ARMNT: return( NULL ); case IMAGE_FILE_MACHINE_AMD64: if( eMode == SET_TAINT ) { pRegisterAliases = X64_REGISTER_TAINT_ALIASES; } else if( eMode == CLEAR_TAINT ) { pRegisterAliases = X64_REGISTER_CLEAR_ALIASES; } else { return( NULL ); } break; default: return( NULL ); } // Search through the alias list while( pRegisterAliases->pwzOperand != NULL ) { OPERAND *pComparison = pRegisterAliases; while( pComparison->pwzOperand != NULL ) { if( (cchRegister == pComparison->cchOperand) && (wcsncmp( pwzRegister, pComparison->pwzOperand, cchRegister ) == 0) ) { return( pRegisterAliases ); } else { // Skip to the end of this list, because we only compare the first registers in each list while( pComparison->pwzOperand != NULL ) { pComparison++; } } } pRegisterAliases = pComparison + 1; } return( NULL ); }
int TkGetInterpNames( Tcl_Interp *interp, /* Interpreter for returning a result. */ Tk_Window tkwin) /* Window whose display is to be used for the * lookup. */ { #ifndef TK_SEND_ENABLED_ON_WINDOWS /* * Temporarily disabled for bug #858822 */ return TCL_OK; #else /* TK_SEND_ENABLED_ON_WINDOWS */ LPRUNNINGOBJECTTABLE pROT = NULL; LPCOLESTR oleszStub = TKWINSEND_REGISTRATION_BASE; HRESULT hr = S_OK; Tcl_Obj *objList = NULL; int result = TCL_OK; hr = GetRunningObjectTable(0, &pROT); if (SUCCEEDED(hr)) { IBindCtx* pBindCtx = NULL; objList = Tcl_NewListObj(0, NULL); hr = CreateBindCtx(0, &pBindCtx); if (SUCCEEDED(hr)) { IEnumMoniker* pEnum; hr = pROT->lpVtbl->EnumRunning(pROT, &pEnum); if (SUCCEEDED(hr)) { IMoniker* pmk = NULL; while (pEnum->lpVtbl->Next(pEnum, 1, &pmk, NULL) == S_OK) { LPOLESTR olestr; hr = pmk->lpVtbl->GetDisplayName(pmk, pBindCtx, NULL, &olestr); if (SUCCEEDED(hr)) { IMalloc *pMalloc = NULL; if (wcsncmp(olestr, oleszStub, wcslen(oleszStub)) == 0) { LPOLESTR p = olestr + wcslen(oleszStub); if (*p) { result = Tcl_ListObjAppendElement(interp, objList, Tcl_NewUnicodeObj(p + 1, -1)); } } hr = CoGetMalloc(1, &pMalloc); if (SUCCEEDED(hr)) { pMalloc->lpVtbl->Free(pMalloc, (void*)olestr); pMalloc->lpVtbl->Release(pMalloc); } } pmk->lpVtbl->Release(pmk); } pEnum->lpVtbl->Release(pEnum); } pBindCtx->lpVtbl->Release(pBindCtx); } pROT->lpVtbl->Release(pROT); } if (FAILED(hr)) { /* * Expire the list if set. */ if (objList != NULL) { Tcl_DecrRefCount(objList); } Tcl_SetObjResult(interp, Win32ErrorObj(hr)); result = TCL_ERROR; } if (result == TCL_OK) { Tcl_SetObjResult(interp, objList); } return result; #endif /* TK_SEND_ENABLED_ON_WINDOWS */ }
/*! * @brief Configure the named pipe connnection. If it doesn't exist, go ahead and estbalish it. * @param transport Pointer to the transport instance. * @return Indication of success or failure. */ static BOOL configure_named_pipe_connection(Transport* transport) { DWORD result = ERROR_SUCCESS; wchar_t tempUrl[512]; NamedPipeTransportContext* ctx = (NamedPipeTransportContext*)transport->ctx; if (ctx->pipe_name == NULL) { dprintf("[NP CONFIGURE] Url: %S", transport->url); wcscpy_s(tempUrl, 512, transport->url); dprintf("[NP CONFIGURE] Copied: %S", tempUrl); transport->comms_last_packet = current_unix_timestamp(); dprintf("[NP CONFIGURE] Making sure it's a pipe ..."); if (wcsncmp(tempUrl, L"pipe", 4) == 0) { dprintf("[NP CONFIGURE] Yup, it is, parsing"); wchar_t* pServer = wcsstr(tempUrl, L"//") + 2; dprintf("[NP CONFIGURE] pServer is %p", pServer); dprintf("[NP CONFIGURE] pServer is %S", pServer); wchar_t* pName = wcschr(pServer, L'/') + 1; dprintf("[NP CONFIGURE] pName is %p", pName); dprintf("[NP CONFIGURE] pName is %S", pName); wchar_t* pSlash = wcschr(pName, L'/'); dprintf("[NP CONFIGURE] pName is %p", pName); // Kill off a trailing slash if there is one if (pSlash != NULL) { *pSlash = '\0'; } *(pName - 1) = '\0'; dprintf("[NP CONFIGURE] Server: %S", pServer); dprintf("[NP CONFIGURE] Name: %S", pName); size_t requiredSize = wcslen(pServer) + wcslen(pName) + 9; ctx->pipe_name = (STRTYPE)calloc(requiredSize, sizeof(CHARTYPE)); _snwprintf_s(ctx->pipe_name, requiredSize, requiredSize - 1, L"\\\\%s\\pipe\\%s", pServer, pName); dprintf("[NP CONFIGURE] Full pipe name: %S", ctx->pipe_name); } } // check if comms is already open via a staged payload if (ctx->pipe != NULL && ctx->pipe != INVALID_HANDLE_VALUE) { // Configure PIPE_WAIT. Stager doesn't do this because ConnectNamedPipe may never return. DWORD mode = 0; SetNamedPipeHandleState((HANDLE)ctx->pipe, &mode, NULL, NULL); dprintf("[NP] Connection already running on %u", ctx->pipe); } else { dprintf("[NP CONFIGURE] pipe name is %p", ctx->pipe_name); if (ctx->pipe_name != NULL) { if (wcsncmp(ctx->pipe_name, L"\\\\.\\", 4) == 0) { ctx->pipe = bind_named_pipe(ctx->pipe_name, &transport->timeouts); } else { ctx->pipe = reverse_named_pipe(ctx->pipe_name, &transport->timeouts); } } else { dprintf("[NP] we might have had an invalid URL"); result = ERROR_INVALID_PARAMETER; } } if (ctx->pipe == INVALID_HANDLE_VALUE) { dprintf("[SERVER] Something went wrong"); return FALSE; } dprintf("[SERVER] Looking good, FORWARD!"); // Do not allow the file descriptor to be inherited by child processes SetHandleInformation((HANDLE)ctx->pipe, HANDLE_FLAG_INHERIT, 0); transport->comms_last_packet = current_unix_timestamp(); return TRUE; }
// ----------------------------------------------------------------------------------------- PDEVICE_OBJECT Disk_GetDeviceObjectByLetter(WCHAR DriveLetter) { PDEVICE_OBJECT pDevice = NULL; NTSTATUS ntStatus; HANDLE hDir; UNICODE_STRING us; OBJECT_ATTRIBUTES ObjAttr; HANDLE hLink; WCHAR targetNameBuffer[260]; UNICODE_STRING targetNameUnicodeString; PFILE_OBJECT fileObject; IO_STATUS_BLOCK ioStatus; WCHAR cDrive[3] = L"A:"; RtlInitUnicodeString(&us, (PWCHAR)L"\\??"); InitializeObjectAttributes(&ObjAttr, &us, OBJ_CASE_INSENSITIVE, NULL, NULL); ntStatus = ZwOpenDirectoryObject(&hDir, DIRECTORY_QUERY,&ObjAttr); if(!NT_SUCCESS(ntStatus)) { DbPrint(DC_LLDISKIO, DL_ERROR, ("ZwOpenDirectoryObject %S failed, status %x\n",us.Buffer, ntStatus)); return NULL; } cDrive[0] = DriveLetter; RtlInitUnicodeString(&us,cDrive); InitializeObjectAttributes(&ObjAttr, &us, OBJ_CASE_INSENSITIVE, hDir, NULL); ntStatus = ZwOpenSymbolicLinkObject(&hLink, SYMBOLIC_LINK_QUERY, &ObjAttr); if(NT_SUCCESS(ntStatus)) { RtlZeroMemory(targetNameBuffer, sizeof(targetNameBuffer)); targetNameUnicodeString.Buffer = targetNameBuffer; targetNameUnicodeString.MaximumLength = sizeof(targetNameBuffer); ntStatus = ZwQuerySymbolicLinkObject(hLink, &targetNameUnicodeString, NULL); if(NT_SUCCESS(ntStatus)) { if(!wcsncmp(targetNameBuffer,L"\\Device",7)) { HANDLE hFile; ntStatus = ZwCreateFile(&hFile, SYNCHRONIZE | FILE_ANY_ACCESS, &ObjAttr, &ioStatus, NULL, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, FILE_OPEN, FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0); if(NT_SUCCESS(ntStatus)) { //!FILE_DEVICE_MASS_STORAGE or FILE_DEVICE_TAPE ntStatus = ObReferenceObjectByHandle(hFile, FILE_READ_DATA, NULL, KernelMode, (PVOID*) &fileObject, NULL); if(NT_SUCCESS(ntStatus)) { pDevice = fileObject->DeviceObject; if (pDevice->Vpb != NULL) { if (pDevice->Vpb->RealDevice != NULL) pDevice = pDevice->Vpb->RealDevice; } if(pDevice->DeviceType == FILE_DEVICE_DISK || pDevice->DeviceType == FILE_DEVICE_CD_ROM || pDevice->DeviceType == FILE_DEVICE_DVD) { if(!NT_SUCCESS(ObReferenceObjectByPointer(pDevice, STANDARD_RIGHTS_REQUIRED, *IoDeviceObjectType, KernelMode))) //dereference will be in caller proc pDevice = NULL; } else pDevice = NULL; ObDereferenceObject(fileObject); } ZwClose(hFile); } } } ZwClose(hLink); } ZwClose(hDir); return pDevice; }