BOOL operator!=(const CStrW& s_String) { return (wcsicmp(mu16_Buf, s_String) != 0); }
static BOOL CALLBACK MiniDumpCallback( PVOID CallbackParam, const PMINIDUMP_CALLBACK_INPUT CallbackInput, PMINIDUMP_CALLBACK_OUTPUT CallbackOutput ) { const dumpCbParams_t *params = (dumpCbParams_t*)CallbackParam; switch( CallbackInput->CallbackType ) { case IncludeThreadCallback: { int i; for( i = 0; i < params->p->numIgnoreThreads; i++ ) { if( CallbackInput->IncludeThread.ThreadId == params->p->ignoreThreadIds[i] ) { return FALSE; } } } return TRUE; case IncludeModuleCallback: { int i; for( i = 0; i < params->p->numIgnoreModules; i++ ) { if( (HMODULE)CallbackInput->IncludeModule.BaseOfImage == params->p->ignoreModules[i] ) { return FALSE; } } } return TRUE; case ModuleCallback: if( params->hModulesFile ) { #if !defined (_WIN32) PWCHAR packIncludeMods[] = { L"/OpenWolf.exe", L"rendererGL3x86.dll", L"rendererGLx86.dll", L"rendererGL3x86.dll", L"rendererD3Dx86.dll", L"snd_openal.dll", L"qagame_mp_x86.dll", L"cgame_mp_x86.dll", L"ui_mp_x86.dll" }; #else PWCHAR packIncludeMods[] = { L"/OpenWolf.exe", L"rendererGL3x86_64.dll", L"rendererGLx86_64.dll", L"rendererD3Dx86_64.dll", L"snd_openal.dll", L"qagame_mp_x86_64.dll", L"cgame_mp_x86_64.dll", L"ui_mp_x86_64.dll" }; #endif wchar_t *path = CallbackInput->Module.FullPath; size_t len = wcslen( path ); size_t i, c; //path is fully qualified - this won't trash for( i = len; i--; ) { if( path[i] == L'\\' ) { break; } } c = i + 1; for( i = 0; i < lengthof( packIncludeMods ); i++ ) if( wcsicmp( path + c, packIncludeMods[i] ) == 0 ) { DWORD dummy; WriteFile( params->hModulesFile, path, sizeof( wchar_t ) * len, &dummy, NULL ); WriteFile( params->hModulesFile, L"\n", sizeof( wchar_t ), &dummy, NULL ); break; } } return TRUE; default: return TRUE; } }
BOOL InitializeGlobalJobList() { const WCHAR wszPath[] = L"\\PRINTERS\\?????.SHD"; const DWORD cchPath = _countof(wszPath) - 1; DWORD dwErrorCode; DWORD dwJobID; HANDLE hFind; PLOCAL_JOB pJob = NULL; PWSTR p; WCHAR wszFullPath[MAX_PATH]; WIN32_FIND_DATAW FindData; // This one is incremented in _GetNextJobID. _dwLastJobID = 0; // Initialize an empty list for all jobs of all local printers. // We will search it by Job ID (supply a pointer to a DWORD in LookupElementSkiplist). InitializeSkiplist(&GlobalJobList, DllAllocSplMem, _GlobalJobListCompareRoutine, (PSKIPLIST_FREE_ROUTINE)DllFreeSplMem); // Construct the full path search pattern. CopyMemory(wszFullPath, wszSpoolDirectory, cchSpoolDirectory * sizeof(WCHAR)); CopyMemory(&wszFullPath[cchSpoolDirectory], wszPath, (cchPath + 1) * sizeof(WCHAR)); // Use the search pattern to look for unfinished jobs serialized in shadow files (.SHD) hFind = FindFirstFileW(wszFullPath, &FindData); if (hFind == INVALID_HANDLE_VALUE) { // No unfinished jobs found. dwErrorCode = ERROR_SUCCESS; goto Cleanup; } do { // Skip possible subdirectories. if (FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue; // Extract the Job ID and verify the file name format at the same time. // This includes all valid names (like "00005.SHD") and excludes invalid ones (like "10ABC.SHD"). dwJobID = wcstoul(FindData.cFileName, &p, 10); if (!IS_VALID_JOB_ID(dwJobID)) continue; if (wcsicmp(p, L".SHD") != 0) continue; // This shadow file has a valid name. Construct the full path and try to load it. GetJobFilePath(L"SHD", dwJobID, wszFullPath); pJob = ReadJobShadowFile(wszFullPath); if (!pJob) continue; // Add it to the Global Job List. if (!InsertElementSkiplist(&GlobalJobList, pJob)) { dwErrorCode = ERROR_NOT_ENOUGH_MEMORY; ERR("InsertElementSkiplist failed for job %lu for the GlobalJobList!\n", pJob->dwJobID); goto Cleanup; } // Add it to the Printer's Job List. if (!InsertElementSkiplist(&pJob->pPrinter->JobList, pJob)) { dwErrorCode = ERROR_NOT_ENOUGH_MEMORY; ERR("InsertElementSkiplist failed for job %lu for the Printer's Job List!\n", pJob->dwJobID); goto Cleanup; } } while (FindNextFileW(hFind, &FindData)); dwErrorCode = ERROR_SUCCESS; Cleanup: // Outside the loop if (hFind) FindClose(hFind); SetLastError(dwErrorCode); return (dwErrorCode == ERROR_SUCCESS); }
int iStrCmp(ILconst_string src1, ILconst_string src2) { return wcsicmp(src1, src2); }
BOOL pw_callback(process_info_t *pi, void **param) { char *resstr; char reschar; int res; WCHAR buf[MAX_CMDLINE]; DWORD version; BOOL under_dr; WCHAR qual_name[MAX_CMDLINE]; if (exe) generate_process_name(pi, qual_name, BUFFER_SIZE_ELEMENTS(qual_name)); if ( (pid && pi->ProcessID == pid) || (exe && (!wcsicmp(wexe, pi->ProcessName) || !wcsicmp(wexe, qual_name))) || listall || listdr) { version = -1; res = under_dynamorio_ex(pi->ProcessID, &version); switch (res) { case DLL_PROFILE : resstr=NAME" profile"; reschar='P'; break; case DLL_RELEASE : resstr=NAME" release"; reschar='R'; break; case DLL_DEBUG : resstr=NAME" debug"; reschar='D'; break; case DLL_CUSTOM : resstr=NAME" custom"; reschar='C'; break; case DLL_NONE : resstr="native"; reschar='N'; break; case DLL_UNKNOWN : default : resstr="<error>"; reschar='?'; } under_dr = !(res == DLL_NONE || res == DLL_UNKNOWN); if (!listdr || under_dr) { if (!nopid && !showmem) { if (onlypid) fprintf(fp, "%d\n", (DWORD) pi->ProcessID); else fprintf(fp, "PID %d, ", (DWORD) pi->ProcessID); } if (!showmem && !onlypid) { WCHAR qual_name[MAX_CMDLINE]; WCHAR *name_to_use = pi->ProcessName; #ifdef X64 HANDLE hproc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, (DWORD) pi->ProcessID); if (is_wow64(hproc)) { if (!no32) fprintf(fp, "32-bit, "); /* FIXME: currently x64 process can't see 32-bit * drmarker */ resstr="<unknown>"; } CloseHandle(hproc); #endif if (!noqnames) { generate_process_name(pi, qual_name, BUFFER_SIZE_ELEMENTS(qual_name)); name_to_use = qual_name; } fprintf(fp, "Process %S, ", name_to_use); if (version == -1 || !showbuild) fprintf(fp, "running %s\n", resstr); else fprintf(fp, "running %s (build %d)\n", resstr, version); } if (cmdline) { res = get_process_cmdline(pi->ProcessID, buf, BUFFER_SIZE_ELEMENTS(buf)); NULL_TERMINATE_BUFFER(buf); if (res == ERROR_SUCCESS) { fprintf(fp, "\tCmdline: %S\n", buf); } else fprintf(fp, "\t<Cmdline err %d>\n", res); } if (qname) { WCHAR cmdline[MAX_CMDLINE]; res = get_process_cmdline(pi->ProcessID, cmdline, BUFFER_SIZE_ELEMENTS(cmdline)); NULL_TERMINATE_BUFFER(cmdline); if (res == ERROR_SUCCESS) { if (!get_commandline_qualifier(cmdline, buf, BUFFER_SIZE_ELEMENTS(buf), !strip)) buf[0] = L'\0'; /* no args */ NULL_TERMINATE_BUFFER(buf); } if (res == ERROR_SUCCESS) fprintf(fp, "\tQname: %S%s%S\n", pi->ProcessName, buf[0] == L'\0' ? "" : "-", buf); else fprintf(fp, "\t<Qname err %d>\n", res); } if (under_dr && hotp) { hotp_policy_status_table_t *status_tbl = NULL; res = get_hotp_status(pi->ProcessID, &status_tbl); if (res == ERROR_SUCCESS) { uint j; hotp_policy_status_t *cur; fprintf(fp, "\tHotpatching:\n", res); for (j = 0; j < status_tbl->num_policies; j++) { char status_buf[MAX_PATH]; cur = &(status_tbl->policy_status_array[j]); if (get_status_string(status_buf, MAX_PATH, cur->inject_status, cur->mode)) fprintf(fp, "\t Patch %s: %s\n", cur->policy_id, status_buf); } } else if (res == ERROR_DRMARKER_ERROR) { fprintf(fp, "\tHot Patching Not Enabled\n", res); } else { fprintf(fp, "\t<Hotpatch Query Error %d>\n", res); } } if (under_dr && showstats) { dr_statistics_t *stats = get_dynamorio_stats(pi->ProcessID); if (stats != NULL) { uint i; fprintf(fp, "\t%.*s\n", BUFFER_SIZE_ELEMENTS(stats->process_name), stats->process_name); for (i = 0; i < stats->num_stats; i++) { fprintf(fp, "\t%*.*s :%9d\n", BUFFER_SIZE_ELEMENTS(stats->stats[i].name), BUFFER_SIZE_ELEMENTS(stats->stats[i].name), stats->stats[i].name, stats->stats[i].value); } } free_dynamorio_stats(stats); } if (showmem) { print_mem_stats(pi, reschar, version); } count++; } } return TRUE; }
static CURLcode verify_certificate(struct connectdata *conn, int sockindex) { SECURITY_STATUS status; struct SessionHandle *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; CURLcode result = CURLE_OK; CERT_CONTEXT *pCertContextServer = NULL; const CERT_CHAIN_CONTEXT *pChainContext = NULL; status = s_pSecFn->QueryContextAttributes(&connssl->ctxt->ctxt_handle, SECPKG_ATTR_REMOTE_CERT_CONTEXT, &pCertContextServer); if((status != SEC_E_OK) || (pCertContextServer == NULL)) { failf(data, "schannel: Failed to read remote certificate context: %s", Curl_sspi_strerror(conn, status)); result = CURLE_PEER_FAILED_VERIFICATION; } if(result == CURLE_OK) { CERT_CHAIN_PARA ChainPara; memset(&ChainPara, 0, sizeof(ChainPara)); ChainPara.cbSize = sizeof(ChainPara); if(!CertGetCertificateChain(NULL, pCertContextServer, NULL, pCertContextServer->hCertStore, &ChainPara, 0, NULL, &pChainContext)) { failf(data, "schannel: CertGetCertificateChain failed: %s", Curl_sspi_strerror(conn, GetLastError())); pChainContext = NULL; result = CURLE_PEER_FAILED_VERIFICATION; } if(result == CURLE_OK) { CERT_SIMPLE_CHAIN *pSimpleChain = pChainContext->rgpChain[0]; DWORD dwTrustErrorMask = ~(CERT_TRUST_IS_NOT_TIME_NESTED| CERT_TRUST_REVOCATION_STATUS_UNKNOWN); dwTrustErrorMask &= pSimpleChain->TrustStatus.dwErrorStatus; if(dwTrustErrorMask) { if(dwTrustErrorMask & CERT_TRUST_IS_PARTIAL_CHAIN) failf(data, "schannel: CertGetCertificateChain trust error" " CERT_TRUST_IS_PARTIAL_CHAIN"); if(dwTrustErrorMask & CERT_TRUST_IS_UNTRUSTED_ROOT) failf(data, "schannel: CertGetCertificateChain trust error" " CERT_TRUST_IS_UNTRUSTED_ROOT"); if(dwTrustErrorMask & CERT_TRUST_IS_NOT_TIME_VALID) failf(data, "schannel: CertGetCertificateChain trust error" " CERT_TRUST_IS_NOT_TIME_VALID"); failf(data, "schannel: CertGetCertificateChain error mask: 0x%08x", dwTrustErrorMask); result = CURLE_PEER_FAILED_VERIFICATION; } } } if(result == CURLE_OK) { if(data->set.ssl.verifyhost == 1) { infof(data, "warning: ignoring unsupported value (1) ssl.verifyhost\n"); } else if(data->set.ssl.verifyhost == 2) { WCHAR cert_hostname[128]; WCHAR *hostname = Curl_convert_UTF8_to_wchar(conn->host.name); DWORD len; len = CertGetNameStringW(pCertContextServer, CERT_NAME_DNS_TYPE, 0, NULL, cert_hostname, 128); if(len > 0 && cert_hostname[0] == '*') { /* this is a wildcard cert. try matching the last len - 1 chars */ int hostname_len = strlen(conn->host.name); if(wcsicmp(cert_hostname + 1, hostname + hostname_len - len + 2) != 0) result = CURLE_PEER_FAILED_VERIFICATION; } else if(len == 0 || wcsicmp(hostname, cert_hostname) != 0) { result = CURLE_PEER_FAILED_VERIFICATION; } if(result == CURLE_PEER_FAILED_VERIFICATION) { const char *_cert_hostname; _cert_hostname = Curl_convert_wchar_to_UTF8(cert_hostname); failf(data, "schannel: CertGetNameString() certificate hostname " "(%s) did not match connection (%s)", _cert_hostname, conn->host.name); free((void *)_cert_hostname); } free(hostname); } } if(pChainContext) CertFreeCertificateChain(pChainContext); if(pCertContextServer) CertFreeCertificateContext(pCertContextServer); return result; }
//---------------------------------------------------------------------- // // ParseCommandLine // // Get the switches. // //---------------------------------------------------------------------- static int ParseCommandLine(int argc, WCHAR *argv[]) { int i, j; BOOLEAN gotFormat = FALSE; BOOLEAN gotQuick = FALSE; BOOLEAN gotSize = FALSE; BOOLEAN gotLabel = FALSE; BOOLEAN gotCompressed = FALSE; for (i = 1; i < argc; i++) { switch (argv[i][0]) { case L'-': case L'/': if (!_wcsnicmp(&argv[i][1], L"FS:", 3)) { if (gotFormat) return -1; FileSystem = &argv[i][4]; gotFormat = TRUE; } else if (!_wcsnicmp(&argv[i][1], L"A:", 2)) { if (gotSize) return -1; j = 0; while (LegalSizes[j].ClusterSize && wcsicmp(LegalSizes[j].SizeString, &argv[i][3])) { j++; } if (!LegalSizes[j].ClusterSize) return i; ClusterSize = LegalSizes[j].ClusterSize; gotSize = TRUE; } else if (!_wcsnicmp(&argv[i][1], L"V:", 2)) { if (gotLabel) return -1; Label = &argv[i][3]; gotLabel = TRUE; GotALabel = TRUE; } else if (!wcsicmp(&argv[i][1], L"Q")) { if (gotQuick) return -1; QuickFormat = TRUE; gotQuick = TRUE; } else if (!wcsicmp(&argv[i][1], L"C")) { if (gotCompressed) return -1; CompressDrive = TRUE; gotCompressed = TRUE; } else { return i; } break; default: { if (Drive) return i; if (argv[i][1] != L':') return i; Drive = argv[i]; break; } } } return 0; }
bool WString::EndsWithI ( const WString& strOther ) const { return wcsicmp ( Right ( (int)strOther.length () ), strOther ) == 0; }
bool WString::BeginsWithI ( const WString& strOther ) const { return wcsicmp ( Left ( (int)strOther.length () ), strOther ) == 0; }
BOOL HandleClickButton(const wchar_t* buttontext, BEHAVIOR_EVENT_PARAMS& params) { MDIWindow* wnd = GetActiveWin(); wyInt32 tabicon = 0; htmlayout::dom::element src = params.heTarget; htmlayout::dom::element temp; #ifndef COMMUNITY TabObject* ptabinfo = NULL; SchemaOptimizer* sopt = NULL; RedundantIndexFinder* redindfinder = NULL; TabDbSearch* tabsearch; TabEditor* ptabeditor = wnd->m_pctabmodule->GetActiveTabEditor(); #endif tabicon = wnd->m_pctabmodule->GetActiveTabImage(); if(!wnd || !wnd->m_pctabmodule || !buttontext || !wcslen(buttontext)) { return FALSE; } #ifndef COMMUNITY if(tabicon == IDI_DATASEARCH) { if(!(tabsearch = (TabDbSearch*)wnd->m_pctabmodule->GetActiveTabType())) { return FALSE; } tabsearch->OnSearchButton(); return FALSE; } else if(tabicon == IDI_TABLEINDEX) { ptabinfo = (TabObject*)wnd->m_pctabmodule->GetActiveTabType(); if(!ptabinfo || !ptabinfo->m_pobjinfo->m_schemaoptimize || !ptabinfo->m_pobjinfo->m_redindexfinder) { return FALSE; } sopt = ptabinfo->m_pobjinfo->m_schemaoptimize; redindfinder = ptabinfo->m_pobjinfo->m_redindexfinder; } else if(ptabeditor && ptabeditor->m_pctabmgmt->GetActiveTabIcon() == IDI_TABLEINDEX) { sopt = ptabeditor->m_pctabmgmt->m_pqueryobj->m_pobjectinfo->m_schemaoptimize; redindfinder = ptabeditor->m_pctabmgmt->m_pqueryobj->m_pobjectinfo->m_redindexfinder; } else { return FALSE; } if(!sopt->m_tabinfo || !redindfinder->m_tabinfo) { return FALSE; } #endif if(wcsicmp(buttontext, OPTIMIZER_CALCULATE) == 0 || wcsicmp(buttontext, REDUNDANT_INDEX_FIND) == 0) { #ifndef COMMUNITY if(pGlobals->m_pcmainwin->m_connection->m_enttype != ENT_PRO && pGlobals->m_pcmainwin->m_connection->m_enttype != ENT_NORMAL) { if(wcsicmp(buttontext, OPTIMIZER_CALCULATE) == 0) { sopt->ProcessTableAnalyse(); } else { if(redindfinder->ProcessFind() == wyTrue) { //scroll the element into view temp = htmlayout::dom::element::root_element(ptabinfo->m_pobjinfo->m_hwndhtmleditor); temp = temp.get_element_by_id(L"indexinfo"); temp.scroll_to_view(true, false); } } } #else pGlobals->m_pcmainwin->m_connection->GetSQLyogUltimateDialog(); return TRUE; #endif } #ifndef COMMUNITY else if(wcsicmp(buttontext, OPTIMIZER_STOP) == 0) { sopt->StopExecution(wnd); //Resetting the Button text if(sopt->m_ismysqlerror == wyTrue) { src.set_text(_(L"Calculate Optimal Datatypes")); } } else if(wcsicmp(buttontext, OPTIMIZER_HIDE) == 0) { if(ptabinfo && ptabinfo->m_pobjinfo) { ptabinfo->m_pobjinfo->m_istableanalyse = wyFalse; ptabinfo->m_pobjinfo->m_istohideoptimizecolumn = wyTrue; ptabinfo->OnSelectInfoTab(sopt->m_con); ptabinfo->m_pobjinfo->m_istohideoptimizecolumn = wyFalse; } else if(ptabeditor && ptabeditor->m_pctabmgmt->m_pqueryobj) { ptabeditor->m_pctabmgmt->m_pqueryobj->m_pobjectinfo->m_istableanalyse = wyFalse; ptabeditor->m_pctabmgmt->m_pqueryobj->m_pobjectinfo->m_istohideoptimizecolumn = wyTrue; ptabeditor->m_pctabmgmt->m_pqueryobj->Refresh(wyTrue); ptabeditor->m_pctabmgmt->m_pqueryobj->m_pobjectinfo->m_istohideoptimizecolumn = wyFalse; } } else if(wcsicmp(buttontext, REDUNDANT_INDEX_HIDE)== 0) { //hide the redundant indexes info redindfinder->HideColumns(); //scroll the element into view temp = htmlayout::dom::element::root_element(ptabinfo->m_pobjinfo->m_hwndhtmleditor); temp = temp.get_element_by_id(L"indexinfo"); temp.scroll_to_view(true, false); } #endif return FALSE; }
// // Case insensitive compate. // bool WString::CompareI ( const WString& strOther ) const { return wcsicmp ( *this, strOther ) == 0; }
BOOL HandleClickEventOnLink(HWND hwndLayout, HELEMENT helem, const wchar_t *url) { wyInt32 tabicon; MDIWindow *wnd = GetActiveWin(); if(url) { tabicon = wnd->m_pctabmodule->GetActiveTabImage(); if(tabicon == IDI_DATASEARCH) { #ifndef COMMUNITY TabDbSearch *tabsearch; tabsearch = dynamic_cast<TabDbSearch*>(wnd->m_pctabmodule->GetActiveTabType()); if(!tabsearch) { return FALSE; } tabsearch->OnHyperLink(helem, url); #endif return true; } if(!wcsicmp(url, L"optimizer_help ")) { ShowHelp("Schema%20Optimizer%20SQLyog%20MySQL%20GUI.htm"); } else if(!wcsicmp(url, L"redundantindexes_help ")) { ShowHelp("Redundant%20Indexes%20for%20SQLyog%20MySQL%20Client.htm"); } else if(!wcsicmp(url, L"pref_others ")) { PreferenceBase *pref = CreatePreferences(); if(pref) { if(pGlobals->m_entlicense.CompareI("Professional")) { pref->Create(4); } else { pref->Create(3); } delete pref; } } else if(!wcsicmp(url, L"http://www.webyog.com/shop/?ref=community.queryprofiler")) { ::ShellExecuteW(hwndLayout,L"open", url, NULL,NULL,SW_SHOWNORMAL); } else { HandleClickTableURL(url); PostMessage(hwndLayout, UM_FOCUS, 0, 0); } } return true; }
int main(void) { int r = 1, wait = 1, prefix_args_len = -1, needs_env_setup = 1, is_git_command = 1, full_path = 1, skip_arguments = 0, allocate_console = 0, show_console = 0; WCHAR exepath[MAX_PATH], exe[MAX_PATH], top_level_path[MAX_PATH]; LPWSTR cmd = NULL, exep = exe, prefix_args = NULL, basename; LPWSTR working_directory = NULL; /* Determine MSys2-based Git path. */ swprintf(msystem_bin, sizeof(msystem_bin), L"mingw%d\\bin", (int) sizeof(void *) * 8); *top_level_path = L'\0'; /* get the installation location */ GetModuleFileName(NULL, exepath, MAX_PATH); if (!PathRemoveFileSpec(exepath)) { fwprintf(stderr, L"Invalid executable path: %s\n", exepath); ExitProcess(1); } basename = exepath + wcslen(exepath) + 1; if (configure_via_resource(basename, exepath, exep, &prefix_args, &prefix_args_len, &is_git_command, &working_directory, &full_path, &skip_arguments, &allocate_console, &show_console)) { /* do nothing */ } else if (!wcsicmp(basename, L"git-gui.exe")) { static WCHAR buffer[BUFSIZE]; wait = 0; allocate_console = 1; initialize_top_level_path(top_level_path, exepath, NULL, 1); /* set the default exe module */ wcscpy(exe, top_level_path); PathAppend(exe, msystem_bin); PathAppend(exe, L"wish.exe"); if (_waccess(exe, 0) != -1) swprintf(buffer, BUFSIZE, L"\"%s\\%.*s\\libexec\\git-core\"", exepath, wcslen(msystem_bin) - 4, msystem_bin); else { wcscpy(exe, top_level_path); PathAppend(exe, L"mingw\\bin\\wish.exe"); swprintf(buffer, BUFSIZE, L"\"%s\\mingw\\libexec\\git-core\"", top_level_path); } PathAppend(buffer, L"git-gui"); prefix_args = buffer; prefix_args_len = wcslen(buffer); } else if (!wcsnicmp(basename, L"git-", 4)) { needs_env_setup = 0; /* Call a builtin */ prefix_args = basename + 4; prefix_args_len = wcslen(prefix_args); if (!wcsicmp(prefix_args + prefix_args_len - 4, L".exe")) prefix_args_len -= 4; /* set the default exe module */ wcscpy(exe, exepath); PathAppend(exe, L"git.exe"); } else if (!wcsicmp(basename, L"git.exe")) { initialize_top_level_path(top_level_path, exepath, NULL, 1); /* set the default exe module */ wcscpy(exe, top_level_path); PathAppend(exe, msystem_bin); PathAppend(exe, L"git.exe"); if (_waccess(exe, 0) == -1) { wcscpy(exe, top_level_path); PathAppend(exe, L"bin\\git.exe"); } } else if (!wcsicmp(basename, L"gitk.exe")) { static WCHAR buffer[BUFSIZE]; allocate_console = 1; initialize_top_level_path(top_level_path, exepath, NULL, 1); /* set the default exe module */ wcscpy(exe, top_level_path); swprintf(buffer, BUFSIZE, L"\"%s\"", top_level_path); PathAppend(exe, msystem_bin); PathAppend(exe, L"wish.exe"); if (_waccess(exe, 0) != -1) PathAppend(buffer, msystem_bin); else { wcscpy(exe, top_level_path); PathAppend(exe, L"mingw\\bin\\wish.exe"); PathAppend(buffer, L"mingw\\bin"); } PathAppend(buffer, L"gitk"); prefix_args = buffer; prefix_args_len = wcslen(buffer); } if (needs_env_setup) { if (!top_level_path[0]) initialize_top_level_path(top_level_path, exepath, msystem_bin, -4); setup_environment(top_level_path, full_path); } cmd = fixup_commandline(exepath, &exep, &wait, prefix_args, prefix_args_len, is_git_command, skip_arguments); if (working_directory == (LPWSTR)1) { int len = GetEnvironmentVariable(L"HOME", NULL, 0); if (len) { working_directory = malloc(sizeof(WCHAR) * len); GetEnvironmentVariable(L"HOME", working_directory, len); } } { STARTUPINFO si; PROCESS_INFORMATION pi; DWORD creation_flags = CREATE_UNICODE_ENVIRONMENT; HANDLE console_handle; BOOL br = FALSE; ZeroMemory(&pi, sizeof(PROCESS_INFORMATION)); ZeroMemory(&si, sizeof(STARTUPINFO)); si.cb = sizeof(STARTUPINFO); if (allocate_console | show_console) creation_flags |= CREATE_NEW_CONSOLE; else if ((console_handle = CreateFile(L"CONOUT$", GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) != INVALID_HANDLE_VALUE) CloseHandle(console_handle); else { #define STD_HANDLE(field, id) si.hStd##field = GetStdHandle(STD_##id); if (!si.hStd##field) si.hStd##field = INVALID_HANDLE_VALUE STD_HANDLE(Input, INPUT_HANDLE); STD_HANDLE(Output, OUTPUT_HANDLE); STD_HANDLE(Error, ERROR_HANDLE); si.dwFlags = STARTF_USESTDHANDLES; creation_flags |= CREATE_NO_WINDOW; } if (show_console) { si.dwFlags |= STARTF_USESHOWWINDOW; si.wShowWindow = SW_SHOW; } br = CreateProcess(/* module: null means use command line */ exep, cmd, /* modified command line */ NULL, /* process handle inheritance */ NULL, /* thread handle inheritance */ /* handles inheritable? */ allocate_console ? FALSE : TRUE, creation_flags, NULL, /* environment: use parent */ working_directory, /* use parent's */ &si, &pi); if (br) { if (wait) WaitForSingleObject(pi.hProcess, INFINITE); if (!GetExitCodeProcess(pi.hProcess, (DWORD *)&r)) print_error(L"error reading exit code", GetLastError()); CloseHandle(pi.hProcess); } else { print_error(L"error launching git", GetLastError()); r = 1; } } free(cmd); ExitProcess(r); }
/************************************************ * Return PID using ZwQuerySystemInformation(). * ************************************************/ DWORD GetPIDFromNameZwQuerySystemInformation(char *szProcessName) { // Some definitions from NTDDK and other sources typedef LONG NTSTATUS; typedef LONG KPRIORITY; #define NT_SUCCESS(Status) ((NTSTATUS)(Status) >= 0) #define STATUS_INFO_LENGTH_MISMATCH ((NTSTATUS)0xC0000004L) #define SystemProcessesAndThreadsInformation 5 typedef struct _CLIENT_ID { DWORD UniqueProcess; DWORD UniqueThread; } CLIENT_ID; typedef struct _UNICODE_STRING { USHORT Length; USHORT MaximumLength; PWSTR Buffer; } UNICODE_STRING; typedef struct _VM_COUNTERS { SIZE_T PeakVirtualSize; SIZE_T VirtualSize; ULONG PageFaultCount; SIZE_T PeakWorkingSetSize; SIZE_T WorkingSetSize; SIZE_T QuotaPeakPagedPoolUsage; SIZE_T QuotaPagedPoolUsage; SIZE_T QuotaPeakNonPagedPoolUsage; SIZE_T QuotaNonPagedPoolUsage; SIZE_T PagefileUsage; SIZE_T PeakPagefileUsage; } VM_COUNTERS; typedef struct _SYSTEM_THREADS { LARGE_INTEGER KernelTime; LARGE_INTEGER UserTime; LARGE_INTEGER CreateTime; ULONG WaitTime; PVOID StartAddress; CLIENT_ID ClientId; KPRIORITY Priority; KPRIORITY BasePriority; ULONG ContextSwitchCount; LONG State; LONG WaitReason; } SYSTEM_THREADS, * PSYSTEM_THREADS; // NOTE: SYSTEM_PROCESSES structure is different on NT 4 and Win2K typedef struct _SYSTEM_PROCESSES { ULONG NextEntryDelta; ULONG ThreadCount; ULONG Reserved1[6]; LARGE_INTEGER CreateTime; LARGE_INTEGER UserTime; LARGE_INTEGER KernelTime; UNICODE_STRING ProcessName; KPRIORITY BasePriority; ULONG ProcessId; ULONG InheritedFromProcessId; ULONG HandleCount; ULONG Reserved2[2]; VM_COUNTERS VmCounters; #if _WIN32_WINNT >= 0x500 IO_COUNTERS IoCounters; #endif SYSTEM_THREADS Threads[1]; } SYSTEM_PROCESSES, * PSYSTEM_PROCESSES; typedef LONG (WINAPI *ZWQUERYSYSTEMINFORMATION)(UINT SystemInformationClass, PVOID SystemInformation, ULONG SystemInformationLength, PULONG ReturnLength); ZWQUERYSYSTEMINFORMATION ZwQuerySystemInformation; PSYSTEM_PROCESSES pInfo; HINSTANCE hNTDll; WCHAR wcProcessName[MAX_PATH+2]; PCWSTR pszProcessName; DWORD dwPID; ULONG BufferLen = 0x8000; LPVOID pBuffer = NULL; LONG Status; // Check szProcessName if (!szProcessName) return -1; // Convert szProcessName to Unicode if (!MultiByteToWideChar(CP_ACP, 0, szProcessName, -1, wcProcessName, sizeof(wcProcessName) / sizeof(WCHAR))) return -1; // Get NTDLL handle if (!(hNTDll = LoadLibrary("NTDLL.DLL"))) return -1; // Load ZwQuerySystemInformation() dynamically if (!(ZwQuerySystemInformation = (ZWQUERYSYSTEMINFORMATION)GetProcAddress(hNTDll, "ZwQuerySystemInformation"))) { FreeLibrary(hNTDll); SetLastError(ERROR_PROC_NOT_FOUND); return -1; } // Find needed buffer length do { if (!(pBuffer = malloc(BufferLen))) { FreeLibrary(hNTDll); SetLastError(ERROR_NOT_ENOUGH_MEMORY); return -1; } Status = ZwQuerySystemInformation(SystemProcessesAndThreadsInformation, pBuffer, BufferLen, NULL); if (Status == STATUS_INFO_LENGTH_MISMATCH) { free(pBuffer); BufferLen *= 2; } else if (!NT_SUCCESS(Status)) { free(pBuffer); FreeLibrary(hNTDll); return -1; } } while (Status == STATUS_INFO_LENGTH_MISMATCH); pInfo = (PSYSTEM_PROCESSES)pBuffer; for (;;) { pszProcessName = pInfo->ProcessName.Buffer; if (pszProcessName == NULL) pszProcessName = L"Idle"; // Process found ? if (wcsicmp(pszProcessName, wcProcessName) == 0) { dwPID = pInfo->ProcessId; free(pBuffer); FreeLibrary(hNTDll); return dwPID; } if (pInfo->NextEntryDelta == 0) break; // Find the address of the next process structure pInfo = (PSYSTEM_PROCESSES)(((PUCHAR)pInfo) + pInfo->NextEntryDelta); } free(pBuffer); FreeLibrary(hNTDll); return -1; }
static VOID TestCommandLine( _In_ INT ExpectedRet, _In_ INT ExpectedCsidl, _In_ DWORD ExpectedFlags, _In_ PCWSTR ExpectedFileName, _In_ PCWSTR PidlPath, _Out_opt_ PUINT PWriteEnd) { EXPLORER_INFO Info; UINT Ret; ULONG i; PDWORD InfoWords = (PDWORD) &Info; FillMemory(&Info, sizeof(Info), 0x55); Info.dwFlags = 0x00000000; Ret = SHExplorerParseCmdLine(&Info); // Special case for empty cmdline: Ret is the PIDL for the selected folder. if (ExpectedRet == -1) ok((LPITEMIDLIST) Ret == Info.pidl, "Ret = %x, expected %p\n", Ret, Info.pidl); else ok(Ret == ExpectedRet, "Ret = %x, expected %p\n", Ret, (PVOID) ExpectedRet); if (ExpectedFileName == NULL) ok(Info.FileName == InvalidPointer, "FileName = %p\n", Info.FileName); else { ok(Info.FileName != NULL && Info.FileName != InvalidPointer, "FileName = %p\n", Info.FileName); if (Info.FileName != NULL && Info.FileName != InvalidPointer) { ok(!wcscmp(Info.FileName, ExpectedFileName), "FileName = %ls, expected %ls\n", Info.FileName, ExpectedFileName); LocalFree(Info.FileName); } } ok(Info.dwFlags == ExpectedFlags, "dwFlags = %08lx, expected %08lx\n", Info.dwFlags, ExpectedFlags); if (ExpectedCsidl == PIDL_IS_UNTOUCHED) ok(Info.pidl == InvalidPointer, "pidl = %p\n", Info.pidl); else if (ExpectedCsidl == PIDL_IS_NULL) ok(Info.pidl == NULL, "pidl = %p\n", Info.pidl); else { PIDLIST_ABSOLUTE ExpectedPidl; HRESULT hr; ok(Info.pidl != NULL, "pidl = %p\n", Info.pidl); if (Info.pidl != NULL && Info.pidl != InvalidPointer) { WCHAR pidlPathName[MAX_PATH] = L""; if (Info.pidl != NULL && Info.pidl != (LPITEMIDLIST) 0x55555555) { SHGetPathFromIDListW(Info.pidl, pidlPathName); } if (ExpectedCsidl == PIDL_PATH_EQUALS_PATH) { ok(wcsicmp(pidlPathName, PidlPath) == 0, "Path from pidl does not match; pidlPathName=%S\n", pidlPathName); } else if (ExpectedCsidl == PIDL_IS_EMPTY) { ok(wcslen(pidlPathName) == 0, "Unexpected non-empty path from pidl; pidlPathName=%S\n", pidlPathName); } else { if (ExpectedCsidl == PIDL_IS_PATH) { ExpectedPidl = SHSimpleIDListFromPath(PidlPath); hr = ExpectedPidl == NULL ? E_FAIL : S_OK; ok(ExpectedPidl != NULL, "SHSimpleIDListFromPath(%S) failed. pidlPathName=%S\n", PidlPath, pidlPathName); if (SUCCEEDED(hr)) { ok(ILIsEqual(Info.pidl, ExpectedPidl), "Unexpected pidl value %p; pidlPathName=%S PidlPath=%S\n", Info.pidl, pidlPathName, PidlPath); ILFree(ExpectedPidl); } } else { hr = SHGetFolderLocation(NULL, ExpectedCsidl, NULL, 0, &ExpectedPidl); ok(hr == S_OK, "SHGetFolderLocation returned %08lx\n", hr); if (SUCCEEDED(hr)) { BOOL eq = ILIsEqual(Info.pidl, ExpectedPidl); ILFree(ExpectedPidl); ok(eq, "Unexpected pidl value %p; pidlPathName=%S CSIDL=%d\n", Info.pidl, pidlPathName, ExpectedCsidl); } } } if (Info.pidl != NULL && Info.pidl != (LPITEMIDLIST) 0x55555555) ILFree(Info.pidl); } } for (i = 0; i < sizeof(Info) / sizeof(DWORD); i++) { switch (i*4) { case 0x00: // FileName case 0x04: // pidl case 0x08: // dwFlags case 0x20: // pidlRoot case 0x34: // guidInproc (1/4) case 0x38: // guidInproc (2/4) case 0x3C: // guidInproc (3/4) case 0x40: // guidInproc (4/4) break; default: ok(InfoWords[i] == 0x55555555, "Word 0x%02lx has been set to 0x%08lx\n", i * 4, InfoWords[i]); } } if (PWriteEnd) { PBYTE data = (PBYTE)&Info; *PWriteEnd = 0; for (i = sizeof(Info); i > 0; i--) { if (data[i - 1] != 0x55) { *PWriteEnd = i; break; } } } }
/* * @implemented */ int CHString::CompareNoCase(LPCWSTR lpsz) const { // Just call the deprecated function here - no matter we are null terminated // Did you read my statement about how safe is this implementation? return wcsicmp(m_pchData, lpsz); }
int sci_light(scilabEnv env, int nin, scilabVar* in, int nopt, scilabOpt opt, int nout, scilabVar* out) { int light = 0; if (nin > 1) { Scierror(77, _("%s: Wrong number of input argument(s): %d to %d expected.\n"), fname, 0, 1); return 1; } if (nin + nopt == 0) { light = ConstructLight(fname, 0, -1, TRUE, NULL, NULL, NULL, NULL, NULL); } else { int type = -1; BOOL visible = 1; double* position = NULL; double* direction = NULL; double* ambient_color = NULL; double* diffuse_color = NULL; double* specular_color = NULL; int axes = 0; scilabVar var = NULL; if (nin > 0 && scilab_isHandle(env, in[0])) { long long axesHandle = 0; if (scilab_isScalar(env, in[0])) { if (scilab_getHandle(env, in[0], &axesHandle)) { Scierror(999, _("%s: Wrong type for input argument #%d: A graphic handle expected.\n"), fname, 1); return 1; } } else { Scierror(999, _("%s: Wrong type for input argument #%d: A graphic handle expected.\n"), fname, 1); return 1; } axes = getObjectFromHandle((long)axesHandle); } //optionals var = scilab_getOptional(env, opt, L"visible"); if (var && scilab_isString(env, var) && scilab_isScalar(env, var)) { wchar_t* wstr = NULL; if (scilab_getString(env, var, &wstr)) { Scierror(999, _("%s: Wrong type for input argument #%d: string expected.\n"), fname, 7); return 0; } if (wcsicmp(wstr, L"on") == 0) { visible = 1; } else if (wcsicmp(wstr, L"off") == 0) { visible = 0; } } var = scilab_getOptional(env, opt, L"type"); if (var && scilab_isString(env, var) && scilab_isScalar(env, var)) { wchar_t* wstr = NULL; if (scilab_getString(env, var, &wstr)) { Scierror(999, _("%s: Wrong type for input argument #%d: string expected.\n"), fname, 7); return 0; } if (wcsicmp(wstr, L"directional") == 0) { type = 0; } else if (wcsicmp(wstr, L"point") == 0) { type = 1; } } var = scilab_getOptional(env, opt, L"position"); if (var && scilab_isDouble(env, var) && scilab_getSize(env, var) == 3) { scilab_getDoubleArray(env, var, &position); } var = scilab_getOptional(env, opt, L"direction"); if (var && scilab_isDouble(env, var) && scilab_getSize(env, var) == 3) { scilab_getDoubleArray(env, var, &direction); } var = scilab_getOptional(env, opt, L"ambient_color"); if (var && scilab_isDouble(env, var) && scilab_getSize(env, var) == 3) { scilab_getDoubleArray(env, var, &ambient_color); } var = scilab_getOptional(env, opt, L"diffuse_color"); if (var && scilab_isDouble(env, var) && scilab_getSize(env, var) == 3) { scilab_getDoubleArray(env, var, &diffuse_color); } var = scilab_getOptional(env, opt, L"specular_color"); if (var && scilab_isDouble(env, var) && scilab_getSize(env, var) == 3) { scilab_getDoubleArray(env, var, &specular_color); } light = ConstructLight(fname, axes, type, visible, position, direction, ambient_color, diffuse_color, specular_color); } //error occurs in ConstructLight if (light == 0) { //error is manage in ConstructLight return 1; } out[0] = scilab_createHandle(env); if (out[0] == NULL) { Scierror(999, _("%s: Memory allocation error.\n"), fname); return 0; } scilab_setHandle(env, out[0], getHandle(light)); return 0; }
int CUnicodeString::CompareNoCase(LPCWSTR lpsz) { ASSERT(IsValidString(lpsz)); return wcsicmp(m_Buffer, lpsz); }
void CPLUGIN::exec_before(const CSAORIInput& in,CSAORIOutput& out) { //----------変数群初期化---------- script.erase(); script_option.erase(); event.erase(); event_option.erase(); target.erase(); marker.erase(); security_level.erase(); language.erase(); map_strpair::const_iterator itr = in.opts.find(L"Language"); if ( itr != in.opts.end() ) { language = itr->second; } sender.erase(); itr = in.opts.find(L"Sender"); if ( itr != in.opts.end() ) { sender = itr->second; } //----------ゴーストリスト更新---------- if ( in.args.size() >= 5 ) { if ( wcsicmp(in.id.c_str(),L"OnGhostBoot") == 0 || wcsicmp(in.id.c_str(),L"OnGhostInfoUpdate") == 0 ) { string_t path = in.args[4]; ghost_map_type::iterator itr = ghost_map.find(path); SAORI_FUNC::CCriticalSectionLock lock(sstp_thread_lock); CGhostInfo *pGI; if ( itr != ghost_map.end() ) { pGI = &(itr->second); } else { pGI = &(ghost_map[path]); } pGI->hwnd = reinterpret_cast<void*>(wcstoul(in.args[0].c_str(),NULL,10)); pGI->name = in.args[1]; pGI->shell_name = in.args[2]; pGI->id = in.args[3]; pGI->path = path; if ( in.args.size() >= 6 ) { pGI->shell_path = in.args[5]; } else { pGI->shell_path.erase(); } } else if ( wcsicmp(in.id.c_str(),L"OnGhostExit") == 0 ) { string_t path = in.args[4]; SAORI_FUNC::CCriticalSectionLock lock(sstp_thread_lock); ghost_map_type::iterator itr = ghost_map.find(path); if ( itr != ghost_map.end() ) { ghost_map.erase(itr); } } } }
static void AddService(SC_HANDLE hSCManager, LPENUM_SERVICE_STATUS_PROCESS Service, BOOL bHideOSVendorServices) { // // Retrieve a handle to the service. // SC_HANDLE hService = OpenServiceW(hSCManager, Service->lpServiceName, SERVICE_QUERY_CONFIG); if (hService == NULL) return; DWORD dwBytesNeeded = 0; QueryServiceConfigW(hService, NULL, 0, &dwBytesNeeded); // if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) LPQUERY_SERVICE_CONFIG lpServiceConfig = (LPQUERY_SERVICE_CONFIG)MemAlloc(0, dwBytesNeeded); if (!lpServiceConfig) { CloseServiceHandle(hService); return; } QueryServiceConfigW(hService, lpServiceConfig, dwBytesNeeded, &dwBytesNeeded); // // Get the service's vendor... // LPWSTR lpszVendor = NULL; { // Isolate only the executable path, without any arguments. // TODO: Correct at the level of CmdLineToArgv the potential bug when lpszFilename == NULL. #if 0 // Disabled until CmdLineToArgv is included unsigned int argc = 0; LPWSTR* argv = NULL; CmdLineToArgv(lpServiceConfig->lpBinaryPathName, &argc, &argv, L" \t"); if (argc >= 1 && argv[0]) lpszVendor = GetExecutableVendor(argv[0]); #else // Hackish solution taken from the original srvpage.c. // Will be removed after CmdLineToArgv is introduced. WCHAR FileName[MAX_PATH]; memset(&FileName, 0, sizeof(FileName)); if (wcscspn(lpServiceConfig->lpBinaryPathName, L"\"")) { wcsncpy(FileName, lpServiceConfig->lpBinaryPathName, wcscspn(lpServiceConfig->lpBinaryPathName, L" ") ); } else { wcscpy(FileName, lpServiceConfig->lpBinaryPathName); } lpszVendor = GetExecutableVendor(FileName); #endif if (!lpszVendor) lpszVendor = LoadResourceString(hInst, IDS_UNKNOWN); #if 0 MemFree(argv); #endif } // ...and display or not the Microsoft / ReactOS services. BOOL bContinue = TRUE; if (bHideOSVendorServices) { if (FindSubStrI(lpszVendor, bIsWindows ? IDS_MICROSOFT : IDS_REACTOS)) bContinue = FALSE; } if (bContinue) { BOOL bIsServiceEnabled = (lpServiceConfig->dwStartType != SERVICE_DISABLED); BOOL bAddServiceToList = FALSE; BOOL bIsModifiedService = FALSE; RegistryDisabledServiceItemParams params = {}; // // Try to look into the user modifications list... // POSITION it = userModificationsList.Find(Service->lpServiceName); if (it) { bAddServiceToList = TRUE; bIsModifiedService = TRUE; } // // ...if not found, try to find if the disabled service is in the registry. // if (!bAddServiceToList) { if (!bIsServiceEnabled) { QUERY_REGISTRY_KEYS_TABLE KeysQueryTable[2] = {}; KeysQueryTable[0].QueryRoutine = GetRegistryKeyedDisabledServicesQueryRoutine; KeysQueryTable[0].EntryContext = ¶ms; RegQueryRegistryKeys(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Shared Tools\\MSConfig\\services", KeysQueryTable, Service->lpServiceName); bAddServiceToList = params.bIsPresent; if (bIsWindows && bIsPreVistaOSVersion && !bAddServiceToList) { QUERY_REGISTRY_VALUES_TABLE ValuesQueryTable[2] = {}; ValuesQueryTable[0].QueryRoutine = GetRegistryValuedDisabledServicesQueryRoutine; ValuesQueryTable[0].EntryContext = ¶ms; RegQueryRegistryValues(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Shared Tools\\MSConfig\\services", ValuesQueryTable, Service->lpServiceName); bAddServiceToList = params.bIsPresent; } } else { bAddServiceToList = TRUE; } } if (bAddServiceToList) { // // Check if service is required by the system. // BOOL bIsRequired = FALSE; dwBytesNeeded = 0; QueryServiceConfig2(hService, SERVICE_CONFIG_FAILURE_ACTIONS, NULL, 0, &dwBytesNeeded); // if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) LPSERVICE_FAILURE_ACTIONS lpServiceFailureActions = (LPSERVICE_FAILURE_ACTIONS)MemAlloc(0, dwBytesNeeded); if (!lpServiceFailureActions) { MemFree(lpszVendor); MemFree(lpServiceConfig); CloseServiceHandle(hService); return; } QueryServiceConfig2(hService, SERVICE_CONFIG_FAILURE_ACTIONS, (LPBYTE)lpServiceFailureActions, dwBytesNeeded, &dwBytesNeeded); // In Microsoft's MSConfig, things are done just like that!! (extracted string values from msconfig.exe) if ( ( wcsicmp(Service->lpServiceName, L"rpcss" ) == 0 || wcsicmp(Service->lpServiceName, L"rpclocator") == 0 || wcsicmp(Service->lpServiceName, L"dcomlaunch") == 0 ) || ( lpServiceFailureActions && (lpServiceFailureActions->cActions >= 1) && (lpServiceFailureActions->lpsaActions[0].Type == SC_ACTION_REBOOT) ) ) // We add also this test, which corresponds to real life. { bIsRequired = TRUE; } MemFree(lpServiceFailureActions); // // Add the service into the list. // LVITEM item = {}; item.mask = LVIF_TEXT | LVIF_PARAM; item.pszText = Service->lpDisplayName; item.lParam = reinterpret_cast<LPARAM>(new ServiceItem(Service->lpServiceName, bIsServiceEnabled, bIsRequired)); item.iItem = ListView_InsertItem(hServicesListCtrl, &item); if (bIsRequired) { LPWSTR lpszYes = LoadResourceString(hInst, IDS_YES); ListView_SetItemText(hServicesListCtrl, item.iItem, 1, lpszYes); MemFree(lpszYes); } ListView_SetItemText(hServicesListCtrl, item.iItem, 2, lpszVendor); LPWSTR lpszStatus = LoadResourceString(hInst, ((Service->ServiceStatusProcess.dwCurrentState == SERVICE_STOPPED) ? IDS_SERVICES_STATUS_STOPPED : IDS_SERVICES_STATUS_RUNNING)); ListView_SetItemText(hServicesListCtrl, item.iItem, 3, lpszStatus); MemFree(lpszStatus); if (!bIsServiceEnabled) { LPWSTR lpszUnknown = LoadResourceString(hInst, IDS_UNKNOWN); LPWSTR lpszDisableDate = FormatDateTime(¶ms.time); ListView_SetItemText(hServicesListCtrl, item.iItem, 4, (lpszDisableDate ? lpszDisableDate : lpszUnknown)); FreeDateTime(lpszDisableDate); MemFree(lpszUnknown); } ListView_SetCheckState(hServicesListCtrl, item.iItem, (!bIsModifiedService ? bIsServiceEnabled : !bIsServiceEnabled)); } } MemFree(lpszVendor); MemFree(lpServiceConfig); CloseServiceHandle(hService); return; }
//---------------------------------------------------------------------- // // WMain // // Engine. Just get command line switches and fire off a format. This // could also be done in a GUI like Explorer does when you select a // drive and run a check on it. // // We do this in UNICODE because the chkdsk command expects PWCHAR // arguments. // //---------------------------------------------------------------------- int wmain(int argc, WCHAR *argv[]) { int badArg; DWORD media = FMIFS_HARDDISK; DWORD driveType; WCHAR fileSystem[1024]; WCHAR volumeName[1024]; WCHAR input[1024]; DWORD serialNumber; DWORD flags, maxComponent; ULARGE_INTEGER freeBytesAvailableToCaller, totalNumberOfBytes, totalNumberOfFreeBytes; WCHAR szMsg[RC_STRING_MAX_SIZE]; wprintf(L"\n" L"Formatx v1.0 by Mark Russinovich\n" L"Systems Internals - http://www.sysinternals.com\n" L"ReactOS adaptation 1999 by Emanuele Aliberti\n\n"); #ifndef FMIFS_IMPORT_DLL // // Get function pointers // if (!LoadFMIFSEntryPoints()) { PrintResourceString(STRING_FMIFS_FAIL); return -1; } #endif // // Parse command line // badArg = ParseCommandLine(argc, argv); if (badArg) { PrintResourceString(STRING_UNKNOW_ARG, argv[badArg]); Usage(argv[0]); return -1; } // // Get the drive's format // if (!Drive) { PrintResourceString(STRING_DRIVE_PARM); Usage(argv[0]); return -1; } else { wcscpy(RootDirectory, Drive); } RootDirectory[2] = L'\\'; RootDirectory[3] = L'\0'; // // See if the drive is removable or not // driveType = GetDriveTypeW(RootDirectory); switch (driveType) { case DRIVE_UNKNOWN : LoadStringW(GetModuleHandle(NULL), STRING_ERROR_DRIVE_TYPE, szMsg, ARRAYSIZE(szMsg)); PrintWin32Error(szMsg, GetLastError()); return -1; case DRIVE_REMOTE: case DRIVE_CDROM: PrintResourceString(STRING_NO_SUPPORT); return -1; case DRIVE_NO_ROOT_DIR: LoadStringW(GetModuleHandle(NULL), STRING_NO_VOLUME, szMsg, ARRAYSIZE(szMsg)); PrintWin32Error(szMsg, GetLastError()); return -1; case DRIVE_REMOVABLE: PrintResourceString(STRING_INSERT_DISK, RootDirectory[0]); fgetws(input, ARRAYSIZE(input), stdin); media = FMIFS_FLOPPY; break; case DRIVE_FIXED: case DRIVE_RAMDISK: media = FMIFS_HARDDISK; break; } // Reject attempts to format the system drive { WCHAR path[MAX_PATH + 1]; UINT rc; rc = GetWindowsDirectoryW(path, MAX_PATH); if (rc == 0 || rc > MAX_PATH) // todo: Report "Unable to query system directory" return -1; if (towlower(path[0]) == towlower(Drive[0])) { // todo: report "Cannot format system drive" PrintResourceString(STRING_NO_SUPPORT); return -1; } } // // Determine the drive's file system format // if (!GetVolumeInformationW(RootDirectory, volumeName, ARRAYSIZE(volumeName), &serialNumber, &maxComponent, &flags, fileSystem, ARRAYSIZE(fileSystem))) { LoadStringW(GetModuleHandle(NULL), STRING_NO_VOLUME, szMsg, ARRAYSIZE(szMsg)); PrintWin32Error(szMsg, GetLastError()); return -1; } if (!GetDiskFreeSpaceExW(RootDirectory, &freeBytesAvailableToCaller, &totalNumberOfBytes, &totalNumberOfFreeBytes)) { LoadStringW(GetModuleHandle(NULL), STRING_NO_VOLUME_SIZE, szMsg, ARRAYSIZE(szMsg)); PrintWin32Error(szMsg, GetLastError()); return -1; } PrintResourceString(STRING_FILESYSTEM, fileSystem); // // Make sure they want to do this // if (driveType == DRIVE_FIXED) { if (volumeName[0]) { while (TRUE) { PrintResourceString(STRING_LABEL_NAME_EDIT, RootDirectory[0]); fgetws(input, ARRAYSIZE(input), stdin); input[wcslen(input) - 1] = 0; if (!wcsicmp(input, volumeName)) break; PrintResourceString(STRING_ERROR_LABEL); } } PrintResourceString(STRING_YN_FORMAT, RootDirectory[0]); LoadStringW(GetModuleHandle(NULL), STRING_YES_NO_FAQ, szMsg, ARRAYSIZE(szMsg)); while (TRUE) { fgetws(input, ARRAYSIZE(input), stdin); if (_wcsnicmp(&input[0], &szMsg[0], 1) == 0) break; if (_wcsnicmp(&input[0], &szMsg[1], 1) == 0) { wprintf(L"\n"); return 0; } } } // // Tell the user we're doing a long format if appropriate // if (!QuickFormat) { LoadStringW(GetModuleHandle(NULL), STRING_VERIFYING, szMsg, ARRAYSIZE(szMsg)); if (totalNumberOfBytes.QuadPart > 1024*1024*10) { PrintString(L"%s %luM\n", szMsg, (DWORD)(totalNumberOfBytes.QuadPart/(1024*1024))); } else { PrintString(L"%s %.1fM\n", szMsg, ((float)(LONGLONG)totalNumberOfBytes.QuadPart)/(float)(1024.0*1024.0)); } } else { LoadStringW(GetModuleHandle(NULL), STRING_FAST_FMT, szMsg, ARRAYSIZE(szMsg)); if (totalNumberOfBytes.QuadPart > 1024*1024*10) { PrintString(L"%s %luM\n", szMsg, (DWORD)(totalNumberOfBytes.QuadPart/(1024*1024))); } else { PrintString(L"%s %.2fM\n", szMsg, ((float)(LONGLONG)totalNumberOfBytes.QuadPart)/(float)(1024.0*1024.0)); } PrintResourceString(STRING_CREATE_FSYS); } // // Format away! // FormatEx(RootDirectory, media, FileSystem, Label, QuickFormat, ClusterSize, FormatExCallback); if (Error) return -1; PrintResourceString(STRING_FMT_COMPLETE); // // Enable compression if desired // if (CompressDrive) { if (!EnableVolumeCompression(RootDirectory, TRUE)) PrintResourceString(STRING_VOL_COMPRESS); } // // Get the label if we don't have it // if (!GotALabel) { PrintResourceString(STRING_ENTER_LABEL); fgetws(input, ARRAYSIZE(LabelString), stdin); input[wcslen(input) - 1] = 0; if (!SetVolumeLabelW(RootDirectory, input)) { LoadStringW(GetModuleHandle(NULL), STRING_NO_LABEL, szMsg, ARRAYSIZE(szMsg)); PrintWin32Error(szMsg, GetLastError()); return -1; } } if (!GetVolumeInformationW(RootDirectory, volumeName, ARRAYSIZE(volumeName), &serialNumber, &maxComponent, &flags, fileSystem, ARRAYSIZE(fileSystem))) { LoadStringW(GetModuleHandle(NULL), STRING_NO_VOLUME, szMsg, ARRAYSIZE(szMsg)); PrintWin32Error(szMsg, GetLastError()); return -1; } // // Print out some stuff including the formatted size // if (!GetDiskFreeSpaceExW(RootDirectory, &freeBytesAvailableToCaller, &totalNumberOfBytes, &totalNumberOfFreeBytes)) { LoadStringW(GetModuleHandle(NULL), STRING_NO_VOLUME_SIZE, szMsg, ARRAYSIZE(szMsg)); PrintWin32Error(szMsg, GetLastError()); return -1; } PrintResourceString(STRING_FREE_SPACE, totalNumberOfBytes.QuadPart, totalNumberOfFreeBytes.QuadPart); // // Get the drive's serial number // if (!GetVolumeInformationW(RootDirectory, volumeName, ARRAYSIZE(volumeName), &serialNumber, &maxComponent, &flags, fileSystem, ARRAYSIZE(fileSystem))) { LoadStringW(GetModuleHandle(NULL), STRING_NO_VOLUME, szMsg, ARRAYSIZE(szMsg)); PrintWin32Error(szMsg, GetLastError()); return -1; } PrintResourceString(STRING_SERIAL_NUMBER, (unsigned int)(serialNumber >> 16), (unsigned int)(serialNumber & 0xFFFF)); return 0; }
CNetRequestImpl::CNetRequestImpl(CNetRequest* pParent, const char* method, const String& strUrl, IRhoSession* oSession, Hashtable<String,String>* pHeaders) { m_pParent = pParent; m_pParent->m_pCurNetRequestImpl = this; m_pHeaders = pHeaders; m_bCancel = false; m_pSession = oSession; pszErrFunction = NULL; hInet = NULL, hConnection = NULL, hRequest = NULL; memset(&uri, 0, sizeof(uri) ); m_strUrl = strUrl; CAtlStringW strUrlW(strUrl.c_str()); LOG(INFO) + "Method: " + method + ";Url: " + strUrl; do { if ( !URI::isLocalHost(strUrl.c_str()) && !SetupInternetConnection(strUrlW) ) { pszErrFunction = L"SetupInternetConnection"; break; } hInet = InternetOpen(_T("rhodes-wm"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, NULL ); if ( !hInet ) { pszErrFunction = L"InternetOpen"; break; } DWORD dwUrlLength = 1024; CAtlStringW strCanonicalUrlW; if ( !InternetCanonicalizeUrl( strUrlW, strCanonicalUrlW.GetBuffer(dwUrlLength), &dwUrlLength, 0) ) { pszErrFunction = _T("InternetCanonicalizeUrl"); break; } strCanonicalUrlW.ReleaseBuffer(); alloc_url_components( &uri, strCanonicalUrlW ); if( !InternetCrackUrl( strCanonicalUrlW, strCanonicalUrlW.GetLength(), 0, &uri ) ) { pszErrFunction = L"InternetCrackUrl"; break; } hConnection = InternetConnect( hInet, uri.lpszHostName, uri.nPort, _T("anonymous"), NULL, INTERNET_SERVICE_HTTP, 0, 0 ); if ( !hConnection ) { pszErrFunction = L"InternetConnect"; break; } strReqUrlW = uri.lpszUrlPath; strReqUrlW += uri.lpszExtraInfo; DWORD dwFlags = INTERNET_FLAG_KEEP_CONNECTION|INTERNET_FLAG_NO_CACHE_WRITE|INTERNET_FLAG_NO_COOKIES; if ( uri.lpszScheme && wcsicmp(uri.lpszScheme,L"https")==0) dwFlags |= INTERNET_FLAG_SECURE; hRequest = HttpOpenRequest( hConnection, CAtlStringW(method), strReqUrlW, NULL, NULL, NULL, dwFlags, NULL ); if ( !hRequest ) { pszErrFunction = L"HttpOpenRequest"; break; } if (oSession!=null) { String strSession = oSession->getSession(); LOG(INFO) + "Cookie : " + strSession; if ( strSession.length() > 0 ) { String strHeader = "Cookie: " + strSession + "\r\n"; if ( !HttpAddRequestHeaders( hRequest, common::convertToStringW(strHeader).c_str(), -1, HTTP_ADDREQ_FLAG_ADD|HTTP_ADDREQ_FLAG_REPLACE ) ) pszErrFunction = L"HttpAddRequestHeaders"; } } }while(0); }
BOOL SaveBinaryDataToFile( PWSTR pFilename, PMPD pmpd ) /*++ Routine Description: Save binary PCL-XL printer description data to a file Arguments: pFilename - Specifies the original printer description filename pmpd - Points to binary printer description data Return Value: TRUE if successful, FALSE if there is an error --*/ #define XLD_EXTENSION L"xld" #define MPD_EXTENSION L"mpd" { WCHAR mpdFilename[MAX_PATH]; PWSTR pExtension, p; HANDLE hFile; DWORD cbWritten; // // Generate a binary file name based the original filename // pExtension = NULL; p = mpdFilename; while ((*p = *pFilename++) != NUL) { if (*p++ == L'.') pExtension = p; } if (pExtension == NULL || wcsicmp(pExtension, XLD_EXTENSION) != EQUAL_STRING) { Warning(("Printer description filename should have extension .%ws\n", XLD_EXTENSION)); *p++ = L'.'; pExtension = p; } wcscpy(pExtension, MPD_EXTENSION); // // Create a file and write data to it // Verbose(("Writing to binary printer description data to: %ws\n", mpdFilename)); hFile = CreateFile(mpdFilename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { Error(("Failed to create file: %ws\n", mpdFilename)); return FALSE; } if (!WriteFile(hFile, pmpd, pmpd->fileSize, &cbWritten, NULL) || pmpd->fileSize != cbWritten) { Error(("WriteFile failed\n")); CloseHandle(hFile); return FALSE; } CloseHandle(hFile); #if DBG // // Read the binary data back and verify it // if (! (pmpd = MpdCreate(mpdFilename))) { Error(("Binary printer description data is corrupted.\n")); return FALSE; } MpdDelete(pmpd); #endif return TRUE; }
DWORD APIENTRY NPLogonNotify( PLUID lpLogonId, LPCWSTR lpAuthentInfoType, LPVOID lpAuthentInfo, LPCWSTR lpPreviousAuthentInfoType, LPVOID lpPreviousAuthentInfo, LPWSTR lpStationName, LPVOID StationHandle, LPWSTR *lpLogonScript) { char uname[MAX_USERNAME_LENGTH]=""; char password[MAX_PASSWORD_LENGTH]=""; char logonDomain[MAX_DOMAIN_LENGTH]=""; char cell[256]="<non-integrated logon>"; char homePath[MAX_PATH]=""; char szLogonId[128] = ""; MSV1_0_INTERACTIVE_LOGON *IL; DWORD code = 0, code2; int pw_exp; char *reason; char *ctemp; BOOLEAN interactive; BOOLEAN flag; DWORD LSPtype, LSPsize; HKEY NPKey; HWND hwndOwner = (HWND)StationHandle; BOOLEAN afsWillAutoStart; BOOLEAN lowercased_name = TRUE; LogonOptions_t opt; /* domain specific logon options */ int retryInterval; int sleepInterval; /* Are we interactive? */ interactive = (wcsicmp(lpStationName, L"WinSta0") == 0); #ifdef DISABLE_NON_INTERACTIVE /* Do not do anything if the logon session is not interactive. */ if (!interactive) return 0; #endif (void) RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY, 0, KEY_QUERY_VALUE, &NPKey); LSPsize=sizeof(TraceOption); RegQueryValueEx(NPKey, REG_CLIENT_TRACE_OPTION_PARM, NULL, &LSPtype, (LPBYTE)&TraceOption, &LSPsize); RegCloseKey (NPKey); DebugEvent("NPLogonNotify - LoginId(%d,%d)", lpLogonId->HighPart, lpLogonId->LowPart); /* Make sure the AFS Libraries are initialized */ AfsLogonInit(); /* Initialize Logon Script to none */ *lpLogonScript=NULL; /* MSV1_0_INTERACTIVE_LOGON and KERB_INTERACTIVE_LOGON are equivalent for * our purposes */ if ( wcsicmp(lpAuthentInfoType,L"MSV1_0:Interactive") && wcsicmp(lpAuthentInfoType,L"Kerberos:Interactive") ) { DebugEvent("Unsupported Authentication Info Type: %S", lpAuthentInfoType); return 0; } IL = (MSV1_0_INTERACTIVE_LOGON *) lpAuthentInfo; /* Convert from Unicode to ANSI */ /*TODO: Use SecureZeroMemory to erase passwords */ if (!UnicodeStringToANSI(IL->UserName, uname, MAX_USERNAME_LENGTH) || !UnicodeStringToANSI(IL->Password, password, MAX_PASSWORD_LENGTH) || !UnicodeStringToANSI(IL->LogonDomainName, logonDomain, MAX_DOMAIN_LENGTH)) return 0; /* Make sure AD-DOMANS sent from login that is sent to us is striped */ ctemp = strchr(uname, '@'); if (ctemp) *ctemp = 0; /* is the name all lowercase? */ for ( ctemp = uname; *ctemp ; ctemp++) { if ( !islower(*ctemp) ) { lowercased_name = FALSE; break; } } /* * Get Logon options */ GetDomainLogonOptions( lpLogonId, uname, logonDomain, &opt ); retryInterval = opt.retryInterval; sleepInterval = opt.sleepInterval; *lpLogonScript = opt.logonScript; if (retryInterval < sleepInterval) sleepInterval = retryInterval; DebugEvent("Got logon script: %S",opt.logonScript); afsWillAutoStart = AFSWillAutoStart(); DebugEvent("LogonOption[%x], Service AutoStart[%d]", opt.LogonOption,afsWillAutoStart); /* Check for zero length password if integrated logon*/ if ( ISLOGONINTEGRATED(opt.LogonOption) ) { if ( password[0] == 0 ) { DebugEvent0("Password is the empty string"); code = GT_PW_NULL; reason = "zero length password is illegal"; code=0; } /* Get cell name if doing integrated logon. We might overwrite this if we are logging into an AD realm and we find out that the user's home dir is in some other cell. */ DebugEvent("About to call cm_GetRootCellName(%s)",cell); code = cm_GetRootCellName(cell); if (code < 0) { DebugEvent0("Unable to obtain Root Cell"); code = KTC_NOCELL; reason = "unknown cell"; code=0; } else { DebugEvent("Cell is %s",cell); } /* We get the user's home directory path, if applicable, though we can't lookup the cell right away because the client service may not have started yet. This call also sets the AD_REALM flag in opt.flags if applicable. */ if (ISREMOTE(opt.flags)) { DebugEvent0("Is Remote"); GetAdHomePath(homePath,MAX_PATH,lpLogonId,&opt); } } /* loop until AFS is started. */ if (afsWillAutoStart) { while (IsServiceRunning() || IsServiceStartPending()) { DebugEvent("while(autostart) LogonOption[%x], Service AutoStart[%d]", opt.LogonOption,afsWillAutoStart); if (ISADREALM(opt.flags)) { code = GetFileCellName(homePath,cell,256); if (!code) { DebugEvent("profile path [%s] is in cell [%s]",homePath,cell); } /* Don't bail out if GetFileCellName failed. * The home dir may not be in AFS after all. */ } else code=0; /* if Integrated Logon */ if (ISLOGONINTEGRATED(opt.LogonOption)) { if ( KFW_is_available() ) { SetEnvironmentVariable(DO_NOT_REGISTER_VARNAME, ""); if (opt.realm) { char * principal, *p; size_t len, tlen; StringCchLength(opt.realm, MAX_DOMAIN_LENGTH, &tlen); len = tlen; StringCchLength(uname, MAX_USERNAME_LENGTH, &tlen); len += tlen + 2; /* tlen is now the length of uname in characters */ principal = (char *)malloc(len * sizeof(char)); if ( principal ) { StringCchCopy(principal, len, uname); p = principal + tlen; *p++ = '@'; StringCchCopy(p, len - tlen -1, opt.realm); code = KFW_AFS_get_cred(principal, cell, password, 0, opt.smbName, &reason); DebugEvent("KFW_AFS_get_cred uname=[%s] smbname=[%s] cell=[%s] code=[%d]", principal,opt.smbName,cell,code); free(principal); } } else { code = KFW_AFS_get_cred(uname, cell, password, 0, opt.smbName, &reason); DebugEvent("KFW_AFS_get_cred uname=[%s] smbname=[%s] cell=[%s] code=[%d]", uname,opt.smbName,cell,code); } SetEnvironmentVariable(DO_NOT_REGISTER_VARNAME, NULL); if (code == 0 && opt.theseCells) { char * principal, *p; size_t len, tlen; StringCchLength(opt.realm ? opt.realm : cell, MAX_DOMAIN_LENGTH, &tlen); len = tlen; StringCchLength(uname, MAX_USERNAME_LENGTH, &tlen); len += tlen + 2; /* tlen is now the length of uname in characters */ principal = (char *)malloc(len * sizeof(char)); if ( principal ) { StringCchCopy(principal, len, uname); p = principal + tlen; *p++ = '@'; if (opt.realm) { StringCchCopy(p, len - tlen -1, opt.realm); } else { StringCchCopy(p, len - tlen - 1, cell); for ( ;*p; p++) { *p = toupper(*p); } } p = opt.theseCells; while ( *p ) { if ( cm_stricmp_utf8(p, cell) ) { SetEnvironmentVariable(DO_NOT_REGISTER_VARNAME, ""); code2 = KFW_AFS_get_cred(principal, p, 0, 0, opt.smbName, &reason); SetEnvironmentVariable(DO_NOT_REGISTER_VARNAME, NULL); DebugEvent("KFW_AFS_get_cred uname=[%s] smbname=[%s] cell=[%s] code=[%d]", principal,opt.smbName,p,code2); } p += strlen(p) + 1; } free(principal); } } } else { code = ka_UserAuthenticateGeneral2(KA_USERAUTH_VERSION+KA_USERAUTH_AUTHENT_LOGON, uname, "", cell, password, opt.smbName, 0, &pw_exp, 0, &reason); DebugEvent("AFS AfsLogon - (INTEGRATED only)ka_UserAuthenticateGeneral2 Code[%x] uname[%s] smbname=[%s] Cell[%s] PwExp=[%d] Reason=[%s]", code,uname,opt.smbName,cell,pw_exp,reason?reason:""); } if ( code && code != KTC_NOCM && code != KTC_NOCMRPC && !lowercased_name ) { for ( ctemp = uname; *ctemp ; ctemp++) { *ctemp = tolower(*ctemp); } lowercased_name = TRUE; goto sleeping; } /* is service started yet?*/ /* If we've failed because the client isn't running yet and the * client is set to autostart (and therefore it makes sense for * us to wait for it to start) then sleep a while and try again. * If the error was something else, then give up. */ if (code != KTC_NOCM && code != KTC_NOCMRPC) break; } else { /*JUST check to see if its running*/ if (IsServiceRunning()) break; if (!IsServiceStartPending()) { code = KTC_NOCMRPC; reason = "AFS Service start failed"; break; } } /* If the retry interval has expired and we still aren't * logged in, then just give up if we are not in interactive * mode or the failSilently flag is set, otherwise let the * user know we failed and give them a chance to try again. */ if (retryInterval <= 0) { reason = "AFS not running"; if (!interactive || opt.failSilently) break; flag = MessageBox(hwndOwner, "AFS is still starting. Retry?", "AFS Logon", MB_ICONQUESTION | MB_RETRYCANCEL); if (flag == IDCANCEL) break; /* Wait just a little while and try again */ retryInterval = opt.retryInterval; } sleeping: Sleep(sleepInterval * 1000); retryInterval -= sleepInterval; } } DebugEvent0("while loop exited"); /* remove any kerberos 5 tickets currently held by the SYSTEM account * for this user */ if (ISLOGONINTEGRATED(opt.LogonOption) && KFW_is_available()) { #ifdef KFW_LOGON sprintf(szLogonId,"%d.%d",lpLogonId->HighPart, lpLogonId->LowPart); KFW_AFS_copy_cache_to_system_file(uname, szLogonId); #endif KFW_AFS_destroy_tickets_for_principal(uname); } if (code) { char msg[128]; HANDLE h; char *ptbuf[1]; StringCbPrintf(msg, sizeof(msg), "Integrated login failed: %s", reason); if (ISLOGONINTEGRATED(opt.LogonOption) && interactive && !opt.failSilently) MessageBox(hwndOwner, msg, "AFS Logon", MB_OK); h = RegisterEventSource(NULL, AFS_LOGON_EVENT_NAME); ptbuf[0] = msg; ReportEvent(h, EVENTLOG_WARNING_TYPE, 0, 1008, NULL, 1, 0, ptbuf, NULL); DeregisterEventSource(h); code = MapAuthError(code); SetLastError(code); if (ISLOGONINTEGRATED(opt.LogonOption) && (code!=0)) { if (*lpLogonScript) LocalFree(*lpLogonScript); *lpLogonScript = NULL; if (!afsWillAutoStart) // its not running, so if not autostart or integrated logon then just skip code = 0; } } if (opt.theseCells) free(opt.theseCells); if (opt.smbName) free(opt.smbName); if (opt.realm) free(opt.realm); DebugEvent("AFS AfsLogon - Exit","Return Code[%x]",code); return code; }
int winAccessW(const wchar_t *path, int mode) { DWORD attr = GetFileAttributesW(path); if(attr == 0xffffffff) return -1; if(mode == F_OK) return 0; if(mode & X_OK) if(!(attr & FILE_ATTRIBUTE_DIRECTORY)) { /* Directory, so OK */ /* Look at extension for executables */ wchar_t *p = wcsrchr(path, '.'); if(p == NULL || !((wcsicmp(p, L".exe") == 0) || (wcsicmp(p, L".com") == 0) || (wcsicmp(p, L".bat") == 0) || (wcsicmp(p, L".cmd") == 0)) ) return -1; } { /* Now look for file security info */ SECURITY_DESCRIPTOR *sdPtr = NULL; DWORD size = 0; GENERIC_MAPPING genMap; HANDLE hToken = NULL; DWORD desiredAccess = 0; DWORD grantedAccess = 0; BOOL accessYesNo = FALSE; PRIVILEGE_SET privSet; DWORD privSetSize = sizeof(PRIVILEGE_SET); int error; /* get size */ GetFileSecurityW(path, OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, 0, 0, &size); error = GetLastError(); if (error != ERROR_INSUFFICIENT_BUFFER) return -1; sdPtr = (SECURITY_DESCRIPTOR *) alloca(size); if(!GetFileSecurityW(path, OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, sdPtr, size, &size)) return -1; /* * Perform security impersonation of the user and open the * resulting thread token. */ if(!ImpersonateSelf(SecurityImpersonation)) return -1; if(!OpenThreadToken(GetCurrentThread (), TOKEN_DUPLICATE | TOKEN_QUERY, FALSE, &hToken)) return -1; if (mode & R_OK) desiredAccess |= FILE_GENERIC_READ; if (mode & W_OK) desiredAccess |= FILE_GENERIC_WRITE; if (mode & X_OK) desiredAccess |= FILE_GENERIC_EXECUTE; memset(&genMap, 0x0, sizeof (GENERIC_MAPPING)); genMap.GenericRead = FILE_GENERIC_READ; genMap.GenericWrite = FILE_GENERIC_WRITE; genMap.GenericExecute = FILE_GENERIC_EXECUTE; genMap.GenericAll = FILE_ALL_ACCESS; if(!AccessCheck(sdPtr, hToken, desiredAccess, &genMap, &privSet, &privSetSize, &grantedAccess, &accessYesNo)) { CloseHandle(hToken); return -1; } CloseHandle(hToken); if (!accessYesNo) return -1; if ((mode & W_OK) && !(attr & FILE_ATTRIBUTE_DIRECTORY) && (attr & FILE_ATTRIBUTE_READONLY)) return -1; } return 0; }
BOOL CMainFrameDropTarget::IsSupportedDropData(COleDataObject* pDataObject) { BOOL bResult; //************************************************************************ //*** THIS FUNCTION HAS TO BE AS FAST AS POSSIBLE!!! //************************************************************************ if (m_cfHTML && pDataObject->IsDataAvailable(m_cfHTML)) { // If the data is in 'HTML Format', there is no need to check the contents. bResult = TRUE; } else if (m_cfShellURL && pDataObject->IsDataAvailable(m_cfShellURL)) { // If the data is in 'UniformResourceLocator', there is no need to check the contents. bResult = TRUE; } else if (pDataObject->IsDataAvailable(CF_TEXT)) { // // Check text data // bResult = FALSE; HANDLE hMem; if ((hMem = pDataObject->GetGlobalData(CF_TEXT)) != NULL) { LPCSTR lpszUrl; if ((lpszUrl = (LPCSTR)GlobalLock(hMem)) != NULL) { // skip white space while (isspace(*lpszUrl)) lpszUrl++; bResult = IsUrlSchemeSupportedA(lpszUrl); GlobalUnlock(hMem); } GlobalFree(hMem); } } else if (pDataObject->IsDataAvailable(CF_HDROP)) { // // Check HDROP data // bResult = FALSE; HANDLE hMem; if ((hMem = pDataObject->GetGlobalData(CF_HDROP)) != NULL) { LPDROPFILES lpDrop; if ((lpDrop = (LPDROPFILES)GlobalLock(hMem)) != NULL) { // Just check, if there's at least one file we can import if (lpDrop->fWide) { LPCWSTR pszFileW = (LPCWSTR)((LPBYTE)lpDrop + lpDrop->pFiles); while (*pszFileW != L'\0') { int iLen = wcslen(pszFileW); LPCWSTR pszExtW = GetFileExtW(pszFileW, iLen); if (pszExtW != NULL && wcsicmp(pszExtW, FILEEXTDOT_INETSHRTCUTW) == 0) { bResult = TRUE; break; } pszFileW += iLen + 1; } } else { LPCSTR pszFileA = (LPCSTR)((LPBYTE)lpDrop + lpDrop->pFiles); while (*pszFileA != '\0') { int iLen = strlen(pszFileA); LPCSTR pszExtA = GetFileExtA(pszFileA, iLen); if (pszExtA != NULL && stricmp(pszExtA, FILEEXTDOT_INETSHRTCUTA) == 0) { bResult = TRUE; break; } pszFileA += iLen + 1; } } GlobalUnlock(hMem); } GlobalFree(hMem); } } else { // Unknown data format bResult = FALSE; } return bResult; }
int AddFile(wchar_t *fileName, wchar_t *path, int &index) { index = 0; if (!fileName || !fileName[0]) return -2; wchar_t *name2 = wcsdup(fileName); if (!name2) return -2; int l = (int)wcslen(name2); /*int pos = 0; while (fileName[pos]) { if (fileName[pos] == '/') fileName[pos] = '\\' l++; pos++; }//*/ if (fileName[0] == '<') { if (fileName[l-1] != '>') { return -2; } int l2 = 0; if (path) l2 = (int)wcslen(path); memcpy(name2, fileName+1, l * 2 - 4); name2[l-2] = 0; wchar_t *name = (wchar_t*) malloc(sizeof(wchar_t) * (l + 30)); if (name) { wsprintf(name, L"Override\\%s", name2); if (GetFileAttributes(name) == INVALID_FILE_ATTRIBUTES) { wsprintf(name, L"Include\\%s", name2); } free(name2); name2=name; l = (int)wcslen(name2); } //wchar_t *test = ResolvePath(path, name2); } else { if (fileName[0] == '\"') { if (l<=3 || fileName[l-1] != '\"') { free(name2); return -2; } l-=2; fileName++; memcpy(name2, fileName, l * 2); name2[l] = 0; } if (name2[1] != ':' && name2[0] != '\\') { wchar_t *w = wcsrchr(path, '\\'); int l2 = 1+(int)(w - path); if (!srealloc(name2, 2*(l2 + l + 2))) { free(name2); return -2; } memmove(name2 + l2, name2, 2*l+2); memcpy(name2, path, 2*l2); l+=l2+2; } } int q = GetFullPathName(name2, 0, 0, 0); wchar_t *nnew; if (q<=0 || !(nnew = (wchar_t*) malloc(q*sizeof(wchar_t)))) { free(name2); return -2; } int q2 = GetFullPathName(name2, q, nnew, 0); free(name2); if (q2 <= 0 || q2 >= q) { free(nnew); return -2; } name2 = nnew; q2 = GetLongPathName(nnew, 0, 0); if (q2 > 0 && (nnew = (wchar_t*)malloc(q2*sizeof(wchar_t)))) { if ((q = GetLongPathName(name2, nnew, q2)) >0 && q<q2) { free(name2); name2 = nnew; } else { free(nnew); } } /* //name2 = ResolvePathSteal(name2); if (name2[2] == '?') { l = (int) wcslen(name2); if (l < MAX_PATH+4) memmove(name2, name2 + 4, 2*(l - 3)); } int i = GetLongPathName(name2, 0, 0); if (i <= 0 || !(fileName = (wchar_t*) malloc(i*2+2))) { free(name2); return -2; } int w = i; i = GetLongPathName(name2, fileName, w); free(name2); if (i+1 != w) { free(fileName); return -2; } //*/ int i; for (i=0; i<numFiles; i++) { if (!wcsicmp(files[i].name, name2)) break; } if (i != numFiles) { free(name2); index = i; return files[i].loaded; } if (srealloc(files, sizeof(FileInfo)*(numFiles+1))) { index = numFiles; files[numFiles].name = name2; files[numFiles++].loaded = -1; return -1; } free(name2); return -2; }
HICON GetApplicationIcon(WCHAR* szFilteredPath, bool bSmall, WCHAR* wzExeFile, WCHAR* wzWndText, WCHAR* wzClassName) { WCHAR szEXEPath[MAX_PATH]; HICON hIcon = NULL; if (wzExeFile && wzClassName) { WCHAR wzRegPath[MAX_PATH]; HKEY hKey; wcscpy(wzRegPath, L"Software\\HTC\\TaskManager\\NoIconProcess"); if (ERROR_SUCCESS == RegOpenKeyEx(HKEY_CURRENT_USER, wzRegPath, 0,KEY_READ,&hKey)) { HKEY hKeyProc; if (ERROR_SUCCESS == RegOpenKeyEx(hKey, wzExeFile, 0,KEY_READ,&hKeyProc)) { HKEY hKeyClass; if (ERROR_SUCCESS == RegOpenKeyEx(hKeyProc, L"NoClass", 0,KEY_READ,&hKeyClass)) { RegCloseKey(hKeyClass); } else { if (ERROR_SUCCESS == RegOpenKeyEx(hKeyProc, wzClassName, 0,KEY_READ,&hKeyClass)) { WCHAR wzRegValue[MAX_PATH]; DWORD dwRegPath = MAX_PATH; DWORD dwRegValue = MAX_PATH * sizeof(WCHAR); if (ERROR_SUCCESS == RegEnumValue(hKeyClass, 0, wzRegPath, &dwRegPath, NULL, NULL, (LPBYTE)wzRegValue, &dwRegValue)) { ExtractIconEx(wzRegPath, _wtoi(wzRegValue), NULL, &hIcon, 1); if (hIcon) { return hIcon; } } RegCloseKey(hKeyClass); } } RegCloseKey(hKeyProc); } RegCloseKey(hKey); } } if (wzWndText) { if (SHGetSpecialFolderPath(NULL, szEXEPath, CSIDL_PROGRAMS, FALSE)) { TrimEndSpaces(wzWndText); wcscat(szEXEPath, L"\\"); if (FindLnkIcon(szFilteredPath, szEXEPath, wzWndText)) { Sleep(0); } } } WCHAR* wzExt = wcsrchr(szFilteredPath, L'.'); if (wzExt && 0 == wcsicmp(wzExt, L".lnk")) { SHGetShortcutTarget(szFilteredPath, szEXEPath, MAX_PATH); WCHAR* szEXEPath2 = szEXEPath; szEXEPath2 = TrimSpaces(szEXEPath2); int iIndex = 0; if (!hIcon) { FILE* hFile = _wfopen(szFilteredPath, L"r"); if (hFile) { char szLnkData[500]; memset(szLnkData, 0, sizeof(szLnkData)); fread(szLnkData, sizeof(char), sizeof(szLnkData), hFile); fclose(hFile); char* szQuestion = strchr(szLnkData, '?'); if (szQuestion) { szQuestion++; char* szComma = strchr(szLnkData, ','); if (szComma) { szComma[0] = '\0'; szComma++; int cCharacters = strlen(szQuestion)+1; int iIcon = atoi(szComma); WCHAR* pszW = (LPOLESTR)CoTaskMemAlloc(cCharacters*2); MultiByteToWideChar(CP_ACP, 0, szQuestion, cCharacters, pszW, cCharacters); ExtractIconEx(pszW, iIcon, (bSmall) ? NULL : &hIcon, (!bSmall) ? NULL : &hIcon, 1); CoTaskMemFree(pszW); } } else { char* szColon = strstr(szLnkData, "#:"); if (szColon) { szColon++; char* szNewLine = strchr(szLnkData, '\r'); if (szNewLine) { szNewLine[0] = '\0'; } szNewLine = strchr(szLnkData, '\n'); if (szNewLine) { szNewLine[0] = '\0'; } WCHAR wzRegPath[MAX_PATH]; int cCharacters = strlen(szColon)+1; WCHAR* pszW = (LPOLESTR)CoTaskMemAlloc(cCharacters*2); MultiByteToWideChar(CP_ACP, 0, szColon, cCharacters, pszW, cCharacters); wcscpy(wzRegPath, L"Software\\Microsoft\\Shell\\Rai\\"); wcscat(wzRegPath, pszW); CoTaskMemFree(pszW); HKEY hKey; if (ERROR_SUCCESS == RegOpenKeyEx(HKEY_LOCAL_MACHINE, wzRegPath, 0,KEY_READ,&hKey)) { DWORD dwSize; DWORD dwType; dwSize = sizeof(wzRegPath); dwType = REG_SZ; RegQueryValueEx(hKey, L"1",0,&dwType,(LPBYTE)wzRegPath,&dwSize); WCHAR* wzRegPath2 = TrimSpaces(wzRegPath); ExtractIconEx(wzRegPath2, 0, (bSmall) ? NULL : &hIcon, (!bSmall) ? NULL : &hIcon, 1); } } } } } if (!hIcon) { ExtractIconEx(szEXEPath2, 0, (bSmall) ? NULL : &hIcon, (!bSmall) ? NULL : &hIcon, 1); } } else { ExtractIconEx(szFilteredPath, 0, (bSmall) ? NULL : &hIcon, (!bSmall) ? NULL : &hIcon, 1); } return hIcon; }
/** * CStringW::operator> * @date Modified Mar 02, 2006 */ bool CStringW::operator>(const CStringW& str) const { return wcsicmp(m_strTheString.c_str(), str.m_strTheString.c_str()) > 0; }
BOOL operator!=(const WCHAR* u16_String) { return (wcsicmp(mu16_Buf, u16_String) != 0); }