/* goodG2B() uses the GoodSource with the BadSink */ static void goodG2B() { wchar_t * data; wchar_t * *dataPtr1 = &data; wchar_t * *dataPtr2 = &data; wchar_t dataBuffer[256] = L""; data = dataBuffer; { wchar_t * data = *dataPtr1; /* FIX: Use a fixed file name */ wcscat(data, L"Doe, XXXXX"); *dataPtr1 = data; } { wchar_t * data = *dataPtr2; { LDAP* pLdapConnection = NULL; ULONG connectSuccess = 0L; ULONG searchSuccess = 0L; LDAPMessage *pMessage = NULL; wchar_t filter[256]; /* POTENTIAL FLAW: data concatenated into LDAP search, which could result in LDAP Injection*/ _snwprintf(filter, 256-1, L"(cn=%s)", data); pLdapConnection = ldap_initW(L"localhost", LDAP_PORT); if (pLdapConnection == NULL) { printLine("Initialization failed"); exit(1); } connectSuccess = ldap_connect(pLdapConnection, NULL); if (connectSuccess != LDAP_SUCCESS) { printLine("Connection failed"); exit(1); } searchSuccess = ldap_search_ext_sW( pLdapConnection, L"base", LDAP_SCOPE_SUBTREE, filter, NULL, 0, NULL, NULL, LDAP_NO_LIMIT, LDAP_NO_LIMIT, &pMessage); if (searchSuccess != LDAP_SUCCESS) { printLine("Search failed"); if (pMessage != NULL) { ldap_msgfree(pMessage); } exit(1); } /* Typically you would do something with the search results, but this is a test case and we can ignore them */ /* Free the results to avoid incidentals */ if (pMessage != NULL) { ldap_msgfree(pMessage); } /* Close the connection */ ldap_unbind(pLdapConnection); } } }
void DisassembleToken(IMetaDataImport *i, DWORD token, __inout_z WCHAR *buffer) { HRESULT hr; switch (TypeFromToken(token)) { default: _snwprintf(buffer, INT_MAX/sizeof(WCHAR), L"<unknown token type %08x>", TypeFromToken(token)); break; case mdtTypeDef: { ULONG cLen; WCHAR szName[50]; hr = i->GetTypeDefProps(token, szName, 49, &cLen, NULL, NULL); if (FAILED(hr)) wcscpy(szName, L"<unknown type def>"); _snwprintf(buffer, INT_MAX/sizeof(WCHAR), L"%s", szName); } break; case mdtTypeRef: { ULONG cLen; WCHAR szName[50]; hr = i->GetTypeRefProps(token, NULL, szName, 49, &cLen); if (FAILED(hr)) wcscpy(szName, L"<unknown type ref>"); _snwprintf(buffer, INT_MAX/sizeof(WCHAR), L"%s", szName); } break; case mdtFieldDef: { ULONG cLen; WCHAR szFieldName[50]; WCHAR szClassName[50]; mdTypeDef mdClass; hr = i->GetFieldProps(token, &mdClass, szFieldName, 49, &cLen, NULL, NULL, NULL, NULL, NULL, NULL); if (FAILED(hr)) wcscpy(szFieldName, L"<unknown field def>"); hr = i->GetTypeDefProps(mdClass, szClassName, 49, &cLen, NULL, NULL); if (FAILED(hr)) wcscpy(szClassName, L"<unknown type def>"); _snwprintf(buffer, INT_MAX/sizeof(WCHAR), L"%s::%s", szClassName, szFieldName); } break; case mdtMethodDef: { ULONG cLen; WCHAR szFieldName[50]; WCHAR szClassName[50]; mdTypeDef mdClass; hr = i->GetMethodProps(token, &mdClass, szFieldName, 49, &cLen, NULL, NULL, NULL, NULL, NULL); if (FAILED(hr)) wcscpy(szFieldName, L"<unknown method def>"); hr = i->GetTypeDefProps(mdClass, szClassName, 49, &cLen, NULL, NULL); if (FAILED(hr)) wcscpy(szClassName, L"<unknown type def>"); _snwprintf(buffer, INT_MAX/sizeof(WCHAR), L"%s::%s", szClassName, szFieldName); } break; case mdtMemberRef: { mdTypeRef cr = mdTypeRefNil; LPWSTR pMemberName; WCHAR memberName[50]; ULONG memberNameLen; hr = i->GetMemberRefProps(token, &cr, memberName, 49, &memberNameLen, NULL, NULL); if (FAILED(hr)) { pMemberName = L"<unknown member ref>"; } else pMemberName = memberName; ULONG cLen; WCHAR szName[50]; if(TypeFromToken(cr) == mdtTypeRef) { if (FAILED(i->GetTypeRefProps(cr, NULL, szName, 50, &cLen))) { wcscpy(szName, L"<unknown type ref>"); } } else if(TypeFromToken(cr) == mdtTypeDef) { if (FAILED(i->GetTypeDefProps(cr, szName, 49, &cLen, NULL, NULL))) { wcscpy(szName, L"<unknown type def>"); } } _snwprintf(buffer, INT_MAX/sizeof(WCHAR), L"%s::%s ", szName, pMemberName); buffer += wcslen(buffer); } break; } }
/*static*/ SIZE_T DebuggerFunction::Disassemble(BOOL native, SIZE_T offset, BYTE *codeStart, BYTE *codeEnd, __inout_z WCHAR *buffer, BOOL noAddress, DebuggerModule *module, BYTE *ilCode) { SIZE_T ret; if (!native) { // // Write the address // _snwprintf(buffer, INT_MAX/sizeof(WCHAR), L"[IL:%.4x] ", offset); buffer += wcslen(buffer); // // Read next opcode // BYTE *ip = codeStart + offset; DWORD opcode; BYTE *prevIP = ip; ip = (BYTE *) ReadNextOpcode(ip, &opcode); // // Get the end of the instruction // BYTE *nextIP = (BYTE *) SkipIP(ip, opcode); BYTE *bytes = prevIP; // // Dump the raw value of the stream // while (bytes < ip) { _snwprintf(buffer, INT_MAX/sizeof(WCHAR), L"%.2x", *bytes++); buffer += wcslen(buffer); } *buffer++ = ':'; while (bytes < nextIP) { _snwprintf(buffer, INT_MAX/sizeof(WCHAR), L"%.2x", *bytes++); buffer += wcslen(buffer); } while (bytes++ - prevIP < 8) { *buffer++ = L' '; *buffer++ = L' '; } // // Print the opcode // _snwprintf(buffer, INT_MAX/sizeof(WCHAR), L"%s\t", opcodeName[opcode]); buffer += wcslen(buffer); int tokenType = operandDescription[opcode]; if (tokenType == InlineSwitch) { *buffer++ = L'\n'; DWORD caseCount = GET_UNALIGNED_VAL32(ip); ip += 4; DWORD index = 0; while (index < caseCount) { _snwprintf(buffer, INT_MAX/sizeof(WCHAR), L"\t\t\t%.5d:[%.4x]\n", index, GET_UNALIGNED_VAL16(ip)); buffer += wcslen(buffer); index++; ip += 4; } } else if (tokenType == InlinePhi) { *buffer++ = L'\n'; DWORD caseCount = *(unsigned char*)ip; ip += 1; DWORD index = 0; while (index < caseCount) { _snwprintf(buffer, INT_MAX/sizeof(WCHAR), L"\t\t\t%.5d: [%.4x]\n", index, GET_UNALIGNED_VAL16(ip)); buffer += wcslen(buffer); index++; ip += 2; } } else if (tokenType == InlineTok || tokenType == InlineType || tokenType == InlineField || tokenType == InlineMethod) { DisassembleToken(module->GetMetaData(), GET_UNALIGNED_VAL32(ip), buffer); buffer += wcslen(buffer); } else { DisassembleArgument(ip, ip - ilCode, tokenType, buffer); buffer += wcslen(buffer); } ret = nextIP - ilCode; } else { // Write the address if (!noAddress) { _snwprintf(buffer, INT_MAX/sizeof(WCHAR), L"[%.4x] ", offset); buffer += wcslen(buffer); } ret = 0xffff; goto Done; } Done: // If there's a failure, mark something. if (ret == 0xffff) { _snwprintf(buffer, INT_MAX/sizeof(WCHAR), L"????"); buffer += wcslen(buffer); } *buffer++ = L'\n'; *buffer = L'\0'; return (ret); }
int uv_cpu_info(uv_cpu_info_t** cpu_infos_ptr, int* cpu_count_ptr) { uv_cpu_info_t* cpu_infos; SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION* sppi; DWORD sppi_size; SYSTEM_INFO system_info; DWORD cpu_count, r, i; NTSTATUS status; ULONG result_size; int err; uv_cpu_info_t* cpu_info; cpu_infos = NULL; cpu_count = 0; sppi = NULL; uv__once_init(); GetSystemInfo(&system_info); cpu_count = system_info.dwNumberOfProcessors; cpu_infos = uv__calloc(cpu_count, sizeof *cpu_infos); if (cpu_infos == NULL) { err = ERROR_OUTOFMEMORY; goto error; } sppi_size = cpu_count * sizeof(*sppi); sppi = uv__malloc(sppi_size); if (sppi == NULL) { err = ERROR_OUTOFMEMORY; goto error; } status = pNtQuerySystemInformation(SystemProcessorPerformanceInformation, sppi, sppi_size, &result_size); if (!NT_SUCCESS(status)) { err = pRtlNtStatusToDosError(status); goto error; } assert(result_size == sppi_size); for (i = 0; i < cpu_count; i++) { WCHAR key_name[128]; HKEY processor_key; DWORD cpu_speed; DWORD cpu_speed_size = sizeof(cpu_speed); WCHAR cpu_brand[256]; DWORD cpu_brand_size = sizeof(cpu_brand); size_t len; len = _snwprintf(key_name, ARRAY_SIZE(key_name), L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\%d", i); assert(len > 0 && len < ARRAY_SIZE(key_name)); r = RegOpenKeyExW(HKEY_LOCAL_MACHINE, key_name, 0, KEY_QUERY_VALUE, &processor_key); if (r != ERROR_SUCCESS) { err = GetLastError(); goto error; } if (RegQueryValueExW(processor_key, L"~MHz", NULL, NULL, (BYTE*) &cpu_speed, &cpu_speed_size) != ERROR_SUCCESS) { err = GetLastError(); RegCloseKey(processor_key); goto error; } if (RegQueryValueExW(processor_key, L"ProcessorNameString", NULL, NULL, (BYTE*) &cpu_brand, &cpu_brand_size) != ERROR_SUCCESS) { err = GetLastError(); RegCloseKey(processor_key); goto error; } RegCloseKey(processor_key); cpu_info = &cpu_infos[i]; cpu_info->speed = cpu_speed; cpu_info->cpu_times.user = sppi[i].UserTime.QuadPart / 10000; cpu_info->cpu_times.sys = (sppi[i].KernelTime.QuadPart - sppi[i].IdleTime.QuadPart) / 10000; cpu_info->cpu_times.idle = sppi[i].IdleTime.QuadPart / 10000; cpu_info->cpu_times.irq = sppi[i].InterruptTime.QuadPart / 10000; cpu_info->cpu_times.nice = 0; len = WideCharToMultiByte(CP_UTF8, 0, cpu_brand, cpu_brand_size / sizeof(WCHAR), NULL, 0, NULL, NULL); if (len == 0) { err = GetLastError(); goto error; } assert(len > 0); /* Allocate 1 extra byte for the null terminator. */ cpu_info->model = uv__malloc(len + 1); if (cpu_info->model == NULL) { err = ERROR_OUTOFMEMORY; goto error; } if (WideCharToMultiByte(CP_UTF8, 0, cpu_brand, cpu_brand_size / sizeof(WCHAR), cpu_info->model, len, NULL, NULL) == 0) { err = GetLastError(); goto error; } /* Ensure that cpu_info->model is null terminated. */ cpu_info->model[len] = '\0'; } uv__free(sppi); *cpu_count_ptr = cpu_count; *cpu_infos_ptr = cpu_infos; return 0; error: /* This is safe because the cpu_infos array is zeroed on allocation. */ for (i = 0; i < cpu_count; i++) uv__free(cpu_infos[i].model); uv__free(cpu_infos); uv__free(sppi); return uv_translate_sys_error(err); }
void uv_process_fs_event_req(uv_loop_t* loop, uv_req_t* req, uv_fs_event_t* handle) { FILE_NOTIFY_INFORMATION* file_info; int sizew, size, result; char* filename = NULL; wchar_t* filenamew, *long_filenamew = NULL; DWORD offset = 0; assert(req->type == UV_FS_EVENT_REQ); assert(handle->req_pending); handle->req_pending = 0; /* If we're closing, don't report any callbacks, and just push the handle */ /* onto the endgame queue. */ if (handle->flags & UV_HANDLE_CLOSING) { uv_want_endgame(loop, (uv_handle_t*) handle); return; }; file_info = (FILE_NOTIFY_INFORMATION*)(handle->buffer + offset); if (REQ_SUCCESS(req)) { if (req->overlapped.InternalHigh > 0) { do { file_info = (FILE_NOTIFY_INFORMATION*)((char*)file_info + offset); assert(!filename); assert(!long_filenamew); /* * Fire the event only if we were asked to watch a directory, * or if the filename filter matches. */ if (handle->dirw || _wcsnicmp(handle->filew, file_info->FileName, file_info->FileNameLength / sizeof(wchar_t)) == 0 || _wcsnicmp(handle->short_filew, file_info->FileName, file_info->FileNameLength / sizeof(wchar_t)) == 0) { if (handle->dirw) { /* * We attempt to convert the file name to its long form for * events that still point to valid files on disk. * For removed and renamed events, we do not provide the file name. */ if (file_info->Action != FILE_ACTION_REMOVED && file_info->Action != FILE_ACTION_RENAMED_OLD_NAME) { /* Construct a full path to the file. */ size = wcslen(handle->dirw) + file_info->FileNameLength / sizeof(wchar_t) + 2; filenamew = (wchar_t*)malloc(size * sizeof(wchar_t)); if (!filenamew) { uv_fatal_error(ERROR_OUTOFMEMORY, "malloc"); } _snwprintf(filenamew, size, L"%s\\%s", handle->dirw, file_info->FileName); filenamew[size - 1] = L'\0'; /* Convert to long name. */ size = GetLongPathNameW(filenamew, NULL, 0); if (size) { long_filenamew = (wchar_t*)malloc(size * sizeof(wchar_t)); if (!long_filenamew) { uv_fatal_error(ERROR_OUTOFMEMORY, "malloc"); } size = GetLongPathNameW(filenamew, long_filenamew, size); if (size) { long_filenamew[size] = '\0'; } else { free(long_filenamew); long_filenamew = NULL; } } free(filenamew); if (long_filenamew) { /* Get the file name out of the long path. */ result = uv_split_path(long_filenamew, NULL, &filenamew); free(long_filenamew); if (result == 0) { long_filenamew = filenamew; sizew = -1; } else { long_filenamew = NULL; } } /* * If we couldn't get the long name - just use the name * provided by ReadDirectoryChangesW. */ if (!long_filenamew) { filenamew = file_info->FileName; sizew = file_info->FileNameLength / sizeof(wchar_t); } } else { /* Removed or renamed callbacks don't provide filename. */ filenamew = NULL; } } else { /* We already have the long name of the file, so just use it. */ filenamew = handle->filew; sizew = -1; } if (filenamew) { /* Convert the filename to utf8. */ size = uv_utf16_to_utf8(filenamew, sizew, NULL, 0); if (size) { filename = (char*)malloc(size + 1); if (!filename) { uv_fatal_error(ERROR_OUTOFMEMORY, "malloc"); } size = uv_utf16_to_utf8(filenamew, sizew, filename, size); if (size) { filename[size] = '\0'; } else { free(filename); filename = NULL; } } } switch (file_info->Action) { case FILE_ACTION_ADDED: case FILE_ACTION_REMOVED: case FILE_ACTION_RENAMED_OLD_NAME: case FILE_ACTION_RENAMED_NEW_NAME: handle->cb(handle, filename, UV_RENAME, 0); break; case FILE_ACTION_MODIFIED: handle->cb(handle, filename, UV_CHANGE, 0); break; } free(filename); filename = NULL; free(long_filenamew); long_filenamew = NULL; } offset = file_info->NextEntryOffset; } while (offset && !(handle->flags & UV_HANDLE_CLOSING)); } else { handle->cb(handle, NULL, UV_CHANGE, 0); } } else { uv__set_sys_error(loop, GET_REQ_ERROR(req)); handle->cb(handle, NULL, 0, -1); } if (!(handle->flags & UV_HANDLE_CLOSING)) { uv_fs_event_queue_readdirchanges(loop, handle); } else { uv_want_endgame(loop, (uv_handle_t*)handle); } }
static void OxtUpdateScreens(BOOL bClearScreens) { DWORD dwDevNum; int iCount = 0; DISPLAY_DEVICE DisplayDevice; BOOL bRet; IOxtGuestServices *piOxtSvcs = NULL; HRESULT hr; int iWidth, iHeight; WCHAR wszData[MAX_LOADSTRING]; CComBSTR bstrPath, bstrValue; hr = ::CoCreateInstance(CLSID_OxtGuestServices, NULL, CLSCTX_LOCAL_SERVER, IID_IOxtGuestServices, (LPVOID*)&piOxtSvcs); if (FAILED(hr)) { // Not much we can do... return; } if (bClearScreens) { bstrPath = L"display/activeAdapter"; bstrValue = L"0"; piOxtSvcs->XenStoreWrite(bstrPath, bstrValue); return; } ::memset(&DisplayDevice, 0, sizeof(DISPLAY_DEVICE)); DisplayDevice.cb = sizeof(DISPLAY_DEVICE); for (dwDevNum = 0; ; dwDevNum++) { bRet = ::EnumDisplayDevices(NULL, dwDevNum, &DisplayDevice, 0); if (!bRet) { // We are done, error returned when there are no more break; } if (((DisplayDevice.StateFlags & DISPLAY_DEVICE_ACTIVE) == 0) || (DisplayDevice.StateFlags & DISPLAY_DEVICE_REMOTE)) { continue; } _snwprintf(wszData, MAX_LOADSTRING, L"display/activeAdapter/%d", iCount); bstrPath = wszData; bstrValue = DisplayDevice.DeviceString; piOxtSvcs->XenStoreWrite(bstrPath, bstrValue); iCount++; } // First the active adapter count (not sure if it is used though). bstrPath = L"display/activeAdapter"; _snwprintf(wszData, MAX_LOADSTRING, L"%d", iCount); bstrValue = wszData; piOxtSvcs->XenStoreWrite(bstrPath, bstrValue); iWidth = ::GetSystemMetrics(SM_CXVIRTUALSCREEN); iHeight = ::GetSystemMetrics(SM_CYVIRTUALSCREEN); bstrPath = L"attr/desktopDimensions"; _snwprintf(wszData, MAX_LOADSTRING, L"%d %d", iWidth, iHeight); bstrValue = wszData; piOxtSvcs->XenStoreWrite(bstrPath, bstrValue); piOxtSvcs->Release(); }
// Ritorna FALSE se la esplora ed e' vuota oppure se non e' valida BOOL Explorer::ExploreDirectory(WCHAR *wStartPath, DWORD dwDepth) { WIN32_FIND_DATAW wfd; HANDLE hFind = INVALID_HANDLE_VALUE; BOOL bFull = FALSE; FilesystemData fsData; WCHAR wFilePath[MAX_PATH], wRecursePath[MAX_PATH]; WCHAR wHiddenPath[MAX_PATH]; wstring strPath = L"\\*"; if (wStartPath == NULL) { DBG_TRACE(L"Debug - Explorer.cpp - ExploreDirectory() [wStartPath == NULL] ", 5, TRUE); return FALSE; } if (dwDepth == 0) return TRUE; // Evita il browsing della dir nascosta _snwprintf(wHiddenPath, MAX_PATH, L"%s", LOG_DIR_NAME); // Bisogna partire dalla lista dei drive if (!wcscmp(wStartPath, L"/")) { // Nel caso speciale impostiamo la depth a 2, il primo run // trova solo la root "\", il secondo i file nella root. dwDepth = 2; // Creiamo una root-entry artificiale ZeroMemory(&fsData, sizeof(FilesystemData)); fsData.dwVersion = LOG_FILESYSTEM_VERSION; fsData.dwFlags = FILESYSTEM_IS_DIRECTORY; strPath = L"\\"; DBG_TRACE_STR(L"Debug - Explorer.cpp - Logging path: ", strPath.c_str(), 4, FALSE); fsData.dwPathLen = strPath.size() * sizeof(WCHAR); log.WriteLog((BYTE *)&fsData, sizeof(fsData)); log.WriteLog((BYTE *)strPath.c_str(), fsData.dwPathLen); // Iniziamo la ricerca reale ZeroMemory(&wfd, sizeof(wfd)); hFind = _FindFirstFile(strPath.c_str(), &wfd); if (hFind == INVALID_HANDLE_VALUE) { DWORD dwErr = GetLastError(); if (dwErr != ERROR_NO_MORE_FILES) { DBG_TRACE_INT(L"Debug - Explorer.cpp - ExploreDirectory() [FindFirstFileW() (1) Failed] Err: ", 5, FALSE, dwErr); } return FALSE; } do { if (wcsstr(wfd.cFileName, wHiddenPath)) continue; ZeroMemory(&fsData, sizeof(FilesystemData)); fsData.dwVersion = LOG_FILESYSTEM_VERSION; fsData.dwFileSizeHi = wfd.nFileSizeHigh; fsData.dwFileSizeLo = wfd.nFileSizeLow; fsData.ftTime = wfd.ftLastWriteTime; if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) fsData.dwFlags |= FILESYSTEM_IS_DIRECTORY; strPath = L"\\"; strPath += wfd.cFileName; DBG_TRACE_STR(L"Debug - Explorer.cpp - Logging path: ", strPath.c_str(), 4, FALSE); fsData.dwPathLen = strPath.size() * sizeof(WCHAR); log.WriteLog((BYTE *)&fsData, sizeof(fsData)); log.WriteLog((BYTE *)strPath.c_str(), fsData.dwPathLen); if (!ExploreDirectory(RecurseDirectory(wfd.cFileName, wRecursePath), dwDepth - 1)) fsData.dwFlags |= FILESYSTEM_IS_EMPTY; } while (FindNextFile(hFind, &wfd)); FindClose(hFind); return TRUE; } ZeroMemory(&wfd, sizeof(wfd)); hFind = _FindFirstFile(wStartPath, &wfd); if (hFind == INVALID_HANDLE_VALUE) { DWORD dwErr = GetLastError(); if (dwErr != ERROR_NO_MORE_FILES) { DBG_TRACE_INT(L"Debug - Explorer.cpp - ExploreDirectory() [FindFirstFileW() (2) Failed] Err: ", 5, FALSE, dwErr); } } do { if (wcsstr(wfd.cFileName, wHiddenPath)) continue; bFull = TRUE; ZeroMemory(&fsData, sizeof(FilesystemData)); fsData.dwVersion = LOG_FILESYSTEM_VERSION; fsData.dwFileSizeHi = wfd.nFileSizeHigh; fsData.dwFileSizeLo = wfd.nFileSizeLow; fsData.ftTime = wfd.ftLastWriteTime; if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) fsData.dwFlags |= FILESYSTEM_IS_DIRECTORY; CompleteDirectoryPath(wStartPath, wfd.cFileName, wFilePath); fsData.dwPathLen = WideLen(wFilePath); if (fsData.dwFlags & FILESYSTEM_IS_DIRECTORY) if (!ExploreDirectory(RecurseDirectory(wFilePath, wRecursePath), dwDepth - 1)) fsData.dwFlags |= FILESYSTEM_IS_EMPTY; DBG_TRACE_STR(L"Debug - Explorer.cpp - Logging path: ", wFilePath, 4, FALSE); log.WriteLog((BYTE *)&fsData, sizeof(fsData)); log.WriteLog((BYTE *)&wFilePath, fsData.dwPathLen); } while (FindNextFileW(hFind, &wfd)); FindClose(hFind); return bFull; }
/* 必须使用进程依赖crt的wputenv函数追加环境变量 */ unsigned WINAPI SetPluginPath(void * pParam) { typedef int (__cdecl *_pwrite_env)(LPCWSTR envstring); int ret = 0; HMODULE hCrt =NULL; _pwrite_env write_env = NULL; char msvc_crt[CRT_LEN+1] = {0}; LPWSTR lpstring; if ( !find_msvcrt(msvc_crt,CRT_LEN) ) { return ((unsigned)ret); } if ( (hCrt = GetModuleHandleA(msvc_crt)) == NULL ) { return ((unsigned)ret); } if ( profile_path[1] != L':' ) { if (!ini_ready(profile_path,MAX_PATH)) { return ((unsigned)ret); } } write_env = (_pwrite_env)GetProcAddress(hCrt,"_wputenv"); if ( write_env ) { if ( (lpstring = (LPWSTR)SYS_MALLOC(MAX_ENV_SIZE)) != NULL ) { if ( (ret = GetPrivateProfileSectionW(L"Env", lpstring, MAX_ENV_SIZE-1, profile_path)) > 0 ) { LPWSTR strKey = lpstring; while(*strKey != L'\0') { if ( stristrW(strKey, L"NpluginPath") ) { WCHAR lpfile[VALUE_LEN+1]; if ( read_appkey(L"Env",L"NpluginPath",lpfile,sizeof(lpfile)) ) { WCHAR env_string[VALUE_LEN+1] = {0}; PathToCombineW(lpfile, VALUE_LEN); if ( _snwprintf(env_string,VALUE_LEN,L"%ls%ls",L"MOZ_PLUGIN_PATH=",lpfile) > 0) { ret = write_env( (LPCWSTR)env_string ); } } } else if (stristrW(strKey, L"TmpDataPath")) { ; } else { ret = write_env( (LPCWSTR)strKey ); } strKey += wcslen(strKey)+1; } } SYS_FREE(lpstring); } } return ( (unsigned)ret ); }
LRESULT CDlgTimingScoring::DlgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { static int tmStartRace, tmEndRace; // Variables for setting up receive time / live car position HL_hWnd = GetDlgItem(hWnd,IDC_TIMINGSCORING); // Hot Laps listview TS_hWnd = GetDlgItem(hWnd,IDC_RACESCORING); // Race Timing listview switch(uMsg) { case WM_INITDIALOG: { // Initialize the results array for (int i=0;i<50;i++) { swprintf(m_ScoringData[i].db_strRaceName, NUMCHARS(m_ScoringData[i].db_strRaceName),L""); swprintf(m_ScoringData[i].db_szTotTime, NUMCHARS(m_ScoringData[i].db_szTotTime),L""); } // tmStartRace = NULL; // tmEndRace = NULL; // Set the initial End Race time to NULL // Set up the Hot Lap timing list box vector<wstring> lstCols; vector<int> lstWidths; lstCols.push_back(L"Pos"); lstCols.push_back(L"Name"); lstCols.push_back(L"Comment"); lstCols.push_back(L"Laptime"); lstWidths.push_back(40); lstWidths.push_back(210); lstWidths.push_back(85); lstWidths.push_back(85); // HL_hWnd = GetDlgItem(hWnd,IDC_TIMINGSCORING); // Hot Laps listview sfListBox.Init(HL_hWnd,lstCols,lstWidths); // Now set up the Scoring list box vector<wstring> scoringLstCols; vector<int> scoringLstWidths; scoringLstCols.push_back(L"Pos"); scoringLstCols.push_back(L"Name"); scoringLstCols.push_back(L"Lap/Time Ahead"); scoringLstWidths.push_back(30); scoringLstWidths.push_back(145); scoringLstWidths.push_back(95); sfListBox.Init(TS_hWnd,scoringLstCols,scoringLstWidths); HWND hWnd_Comment = GetDlgItem(hWnd, IDC_RACE_COMMENT); SetDlgItemText(hWnd, IDC_RACE_COMMENT, szTitle); TimingScoringProc((LPVOID)&m_szPath, hWnd); break; } case WM_NOTIFY: { // check for column click notification and sort the list view accordingly if ( ( ((LPNMHDR)lParam)->idFrom == IDC_RACESCORING) && ( ((LPNMHDR)lParam)->code == LVN_COLUMNCLICK) ) { // TS_hWnd = GetDlgItem(hWnd,IDC_RACESCORING); OnColumnClick((LPNMLISTVIEW)lParam, TS_hWnd ); } else if ( ( ((LPNMHDR)lParam)->idFrom == IDC_TIMINGSCORING) && ( ((LPNMHDR)lParam)->code == LVN_COLUMNCLICK) ) { // HL_hWnd = GetDlgItem(hWnd,IDC_TIMINGSCORING); OnColumnClick((LPNMLISTVIEW)lParam, HL_hWnd ); } return TRUE; } case WM_COMMAND: { switch(LOWORD(wParam)) { case IDRESCAN: { TimingScoringProc((LPVOID)&m_szPath, hWnd); if (tmStartRace) { CRaceScoring((LPVOID) &m_szPath, hWnd, tmStartRace, tmEndRace); } m_pResults->fCancelled = false; return TRUE; } case IDCANCEL: { m_pResults->fCancelled = true; for (int i=0;i<50;i++) { m_sfResult->m_RaceId[i] = -1; } EndDialog(hWnd,0); return TRUE; } case IDSTARTRACE: { TCHAR szText[MAX_PATH] = {NULL}; TCHAR szTemp[MAX_PATH] = {NULL}; if (tmEndRace == NULL && tmStartRace != NULL) { MessageBox(hWnd, L"Race already in progress!\n\nYou must end that race before starting a new one", L"***ERROR***", MB_OK); } else { if (tmStartRace > 0) // There is already a time marker stored, verify user wants to change this { DWORD dRet = MessageBox(hWnd, L"You already have a race stored!\n\nAre you sure you want to start a new race?\n\nPrevious race results will be lost if you haven't saved them", L"WARNING", MB_YESNO); if(dRet == IDNO) { // Do nothing m_pResults->fCancelled = true; return TRUE; } } tmEndRace = NULL; // Remove any end of race marker when new race begins. INT format tmStartRace = GetSecondsSince1970(); // Set the start time for this race session. Unixtime in INT format // tmStartRace = 1376100527; // Used for the TestRaces database only // swprintf(szText, NUMCHARS(szText), L"Race Started\n\nTime = %i", tmStartRace); // MessageBox(hWnd, szText, L"Started", MB_OK); MessageBox(hWnd, L"Race started", L"Started", MB_OK); HWND prog_hWnd = GetDlgItem(hWnd, IDC_RACE_PROGRESS); swprintf(szText, NUMCHARS(szText), L"<<<< Race In Progress >>>>"); SendMessage(prog_hWnd, WM_SETTEXT, 0, (LPARAM)szText); } m_pResults->fCancelled = false; return TRUE; } case IDENDRACE: { if (tmStartRace != NULL) { TCHAR szText[MAX_PATH] = {NULL}; TCHAR szTemp[MAX_PATH] = {NULL}; if (tmEndRace > 0) // There is already a time marker stored, verify user wants to change this { DWORD dRet = MessageBox(hWnd, L"You already have a race stored!\n\nAre you sure you want to change the end time for this race?\n\nPrevious race results will be lost if you haven't saved them", L"WARNING", MB_YESNO); if(dRet == IDNO) { // Do nothing m_pResults->fCancelled = true; return TRUE; } } tmEndRace = GetSecondsSince1970(); // Set the end time for this race session. Unixtime in INT format // tmEndRace = 1376100699; // Used for the TestRaces database only // swprintf(szText, NUMCHARS(szText), L"Race End = %i", tmEndRace); // MessageBox(hWnd, szText, L"Ended", MB_OK); HWND prog_hWnd = GetDlgItem(hWnd, IDC_RACE_PROGRESS); swprintf(szText, NUMCHARS(szText), L">>>> Race Ended <<<<"); SendMessage(prog_hWnd, WM_SETTEXT, 0, (LPARAM)szText); ::FormatTimeMinutesSecondsMs((tmEndRace - tmStartRace), szText, NUMCHARS(szText) ); TimingScoringProc((LPVOID)&m_szPath, hWnd); // Refresh the results one last time if (tmStartRace) { CRaceScoring((LPVOID) &m_szPath, hWnd, tmStartRace, tmEndRace); } swprintf(szTemp, NUMCHARS(szTemp), szText); _snwprintf(szText, NUMCHARS(szText), L"Race has ended\n\nRace duration: %s", szTemp); MessageBox(hWnd, szText, L"Ended", MB_OK); } else { MessageBox(hWnd, L"Race scoring has not been started", L"***ERROR***", MB_OK); } m_pResults->fCancelled = false; return TRUE; } case IDC_RACE_RERUN: { // Let's set up for displaying the T&S page int m_RaceId[50] = {NULL}; // Show the race-selection dialog and let the User pick which ones to use on T&S page RACERERUN_RESULT sfResult; if (sfResult.iStart <= 0 || tmStartRace > 0) sfResult.iStart = tmStartRace; if (sfResult.iEnd <= 0 || tmEndRace > 0) sfResult.iEnd = tmEndRace; CRaceRerunDlg dlgRace(&sfResult); ArtShowDialog<IDD_RACE_RERUN>(&dlgRace); if(!sfResult.fCancelled) { // Get the Start and End race markers and store them for race scoring tmStartRace = sfResult.iStart; tmEndRace = sfResult.iEnd; TimingScoringProc((LPVOID)&m_szPath, hWnd); // Refresh the results one last time if (tmStartRace) { CRaceScoring((LPVOID) &m_szPath, hWnd, tmStartRace, tmEndRace); } } return TRUE; } case IDC_RACE_SAVE: { if (tmEndRace == NULL && tmStartRace != NULL) { MessageBox(hWnd, L"Race in progress!\n\nYou must end the race before saving your results", L"***ERROR***", MB_OK); } else if (tmEndRace == NULL && tmStartRace == NULL) { MessageBox(hWnd, L"No race data to save", L"***ERROR***", MB_OK); } else { TCHAR szText[MAX_PATH] = {NULL}; TCHAR szTemp[MAX_PATH] = {NULL}; // Save the results into a text file if(tmEndRace > 0) { // swprintf(szText, NUMCHARS(szText), L"Race Start = %i\n\nRace End = %i", tmStartRace, tmEndRace); // MessageBox(hWnd, szText, L"Saving", MB_OK); TCHAR szFilename[MAX_PATH] = {NULL}; wcscat(szFilename,L"TimingScoring.txt"); while (true) { if(ArtGetSaveFileName(hWnd, L"Choose Output file", szFilename, NUMCHARS(szFilename),L"TXT Files (*.txt)\0*.TXT\0\0")) { // let's make sure there's a .txt suffix on that bugger. if(!str_ends_with(szFilename,L".txt") && !str_ends_with(szFilename,L".TXT") ) { wcsncat(szFilename,L".txt", NUMCHARS(szFilename)); } const bool fFileIsNew = !DoesFileExist(szFilename); if(fFileIsNew) { break; // Exit loop, as file name is valid and new } else { DWORD dwRet = MessageBox(NULL,L"A file already exists with that name.\n\nAre you sure you want to overwrite it?",L"WARNING", MB_APPLMODAL | MB_ICONWARNING | MB_YESNO | MB_TOPMOST | MB_DEFBUTTON2); if (dwRet == IDYES) { break; // User wants to overwrite file, so exit loop and proceed } } } else { return 0; // User cancelled the save operation, so leave subroutine } } // Open up the file and write the information to it wofstream out; out.open(szFilename); // First the race title information HWND hWnd_Comment = GetDlgItem(hWnd, IDC_RACE_COMMENT); int len; len = GetWindowTextLength(hWnd_Comment); GetDlgItemText(hWnd, IDC_RACE_COMMENT, szTitle, len+1); out<<szTitle<<endl<<endl; out<<L"File Name: "<<m_szPath<<endl; // Let's save the start/end markers so the race can be recreated if needed _snwprintf(szText, NUMCHARS(szText), L"Race start marker:\t%i", tmStartRace); out<<szText<<endl; _snwprintf(szText, NUMCHARS(szText), L"Race ending marker:\t%i", tmEndRace); out<<szText<<endl; // Now the race duration ::FormatTimeMinutesSecondsMs((tmEndRace - tmStartRace), szText, NUMCHARS(szText) ); // swprintf(szText, _tcslen(szText) - 2, L"%s", szText); // Remove the fractional time swprintf(szTemp, NUMCHARS(szTemp), szText); _snwprintf(szText, NUMCHARS(szText), L"Race duration:\t%s", szTemp); out<<szText<<endl<<endl; out<<L"ID\tName\t\t\t\t\tLap/Time Ahead"<<endl; out<<L"====================================================================="<<endl; for(int i = 0; i < 25; i++) { if (m_ScoringData[i].db_iRaceId <= 0 || m_ScoringData[i].db_iUnixFirstTime == 0) break; int Temp = m_ScoringData[i].db_iUnixFirstTime + m_ScoringData[i].db_iUnixLastTime; ::FormatTimeMinutesSecondsMs(Temp, szTemp, NUMCHARS(szTemp) ); out << m_ScoringData[i].db_iRaceId << L"\t"; out << m_ScoringData[i].db_strRaceName << L"\t"; out << m_ScoringData[i].db_szTotTime << endl; } out<<endl; // Now let's push out all of the Top 40 Hot Laps to the file out<<endl<<endl; out<<L"\t\tTop 40 Hot Laps"<<endl; out<<L"Pos\tName\t\t\t\t\tComment\tLap Time"<<endl; out<<L"====================================================================="<<endl; for(int i = 0; i < 40; i++) { if (_wtoi(m_ScoringData[i].lstPos) <= 0) break; out << m_ScoringData[i].lstPos << L"\t"; out << m_ScoringData[i].lstRaceName << L"\t"; out << m_ScoringData[i].lstComment << L"\t\t"; out << m_ScoringData[i].lstLapTimes << endl; } out<<endl; out.close(); // Close the file MessageBox(hWnd, L"Race Results Saved", L"Saved", MB_OK); m_pResults->fCancelled = false; return TRUE; } else { swprintf(szText, NUMCHARS(szText), L"Race Start = %i\n\nRace End = %i", tmStartRace, tmEndRace); MessageBox(hWnd, szText, MB_OK, NULL); } } } } break; } // end WM_COMMAND case WM_CLOSE: { m_pResults->fCancelled = true; for (int i=0;i<50;i++) { m_sfResult->m_RaceId[i] = -1; } EndDialog(hWnd,0); break; } } return FALSE; }
BOOL DeleteDirectory(const WCHAR* sPathToDelete) { BOOL bResult = TRUE; HANDLE hFile; WCHAR sFilePath[MAX_PATH]; WCHAR sPattern[MAX_PATH]; WIN32_FIND_DATA findData; wcscpy(sPattern, sPathToDelete); wcscat(sPattern, L"\\*.*"); hFile = FindFirstFile(sPattern, &findData); if (hFile != INVALID_HANDLE_VALUE) { do { if (findData.cFileName[0] != L'.') { _snwprintf(sFilePath, MAX_PATH, L"%s\\%s", sPathToDelete, findData.cFileName); if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { // Delete subdirectory if (!DeleteDirectory(sFilePath)) bResult = FALSE; } else { // Set file attributes if (SetFileAttributes(sFilePath, FILE_ATTRIBUTE_NORMAL)) { // Delete file if (!DeleteFile(sFilePath) && nTotalRetries < c_nMaxTotalRetries) { BOOL bDeleted = FALSE; nTotalRetries++; for (int nRetry = 0; nRetry < c_nMaxOneFileRetries; nRetry++) { Sleep(c_nRetryDelay); if (DeleteFile(sFilePath)) { bDeleted = TRUE; break; } } if (!bDeleted) bResult = FALSE; } } } } } while (FindNextFile(hFile, &findData)); // Close handle FindClose(hFile); } // Set directory attributes if (SetFileAttributes(sPathToDelete, FILE_ATTRIBUTE_NORMAL)) { g_nDirsDeleted++; UpdateProgress(); // Delete directory if (!RemoveDirectory(sPathToDelete) && nTotalRetries < c_nMaxTotalRetries) { BOOL bDeleted = FALSE; nTotalRetries++; for (int nRetry = 0; nRetry < c_nMaxOneFileRetries; nRetry++) { Sleep(c_nRetryDelay); if (RemoveDirectory(sPathToDelete)) { bDeleted = TRUE; break; } } if (!bDeleted) bResult = FALSE; } } return bResult; }
void uv_process_fs_event_req(uv_loop_t* loop, uv_req_t* req, uv_fs_event_t* handle) { FILE_NOTIFY_INFORMATION* file_info; int err, sizew, size; char* filename = NULL; WCHAR* filenamew = NULL; WCHAR* long_filenamew = NULL; DWORD offset = 0; assert(req->type == UV_FS_EVENT_REQ); assert(handle->req_pending); handle->req_pending = 0; /* Don't report any callbacks if: * - We're closing, just push the handle onto the endgame queue * - We are not active, just ignore the callback */ if (!uv__is_active(handle)) { if (handle->flags & UV_HANDLE_CLOSING) { uv_want_endgame(loop, (uv_handle_t*) handle); } return; } file_info = (FILE_NOTIFY_INFORMATION*)(handle->buffer + offset); if (REQ_SUCCESS(req)) { if (req->u.io.overlapped.InternalHigh > 0) { do { file_info = (FILE_NOTIFY_INFORMATION*)((char*)file_info + offset); assert(!filename); assert(!filenamew); assert(!long_filenamew); /* * Fire the event only if we were asked to watch a directory, * or if the filename filter matches. */ if (handle->dirw || file_info_cmp(handle->filew, file_info->FileName, file_info->FileNameLength) == 0 || file_info_cmp(handle->short_filew, file_info->FileName, file_info->FileNameLength) == 0) { if (handle->dirw) { /* * We attempt to resolve the long form of the file name explicitly. * We only do this for file names that might still exist on disk. * If this fails, we use the name given by ReadDirectoryChangesW. * This may be the long form or the 8.3 short name in some cases. */ if (file_info->Action != FILE_ACTION_REMOVED && file_info->Action != FILE_ACTION_RENAMED_OLD_NAME) { /* Construct a full path to the file. */ size = wcslen(handle->dirw) + file_info->FileNameLength / sizeof(WCHAR) + 2; filenamew = (WCHAR*)uv__malloc(size * sizeof(WCHAR)); if (!filenamew) { uv_fatal_error(ERROR_OUTOFMEMORY, "uv__malloc"); } _snwprintf(filenamew, size, L"%s\\%.*s", handle->dirw, file_info->FileNameLength / (DWORD)sizeof(WCHAR), file_info->FileName); filenamew[size - 1] = L'\0'; /* Convert to long name. */ size = GetLongPathNameW(filenamew, NULL, 0); if (size) { long_filenamew = (WCHAR*)uv__malloc(size * sizeof(WCHAR)); if (!long_filenamew) { uv_fatal_error(ERROR_OUTOFMEMORY, "uv__malloc"); } size = GetLongPathNameW(filenamew, long_filenamew, size); if (size) { long_filenamew[size] = '\0'; } else { uv__free(long_filenamew); long_filenamew = NULL; } } uv__free(filenamew); if (long_filenamew) { /* Get the file name out of the long path. */ uv_relative_path(long_filenamew, handle->dirw, &filenamew); uv__free(long_filenamew); long_filenamew = filenamew; sizew = -1; } else { /* We couldn't get the long filename, use the one reported. */ filenamew = file_info->FileName; sizew = file_info->FileNameLength / sizeof(WCHAR); } } else { /* * Removed or renamed events cannot be resolved to the long form. * We therefore use the name given by ReadDirectoryChangesW. * This may be the long form or the 8.3 short name in some cases. */ filenamew = file_info->FileName; sizew = file_info->FileNameLength / sizeof(WCHAR); } } else { /* We already have the long name of the file, so just use it. */ filenamew = handle->filew; sizew = -1; } /* Convert the filename to utf8. */ uv__convert_utf16_to_utf8(filenamew, sizew, &filename); switch (file_info->Action) { case FILE_ACTION_ADDED: case FILE_ACTION_REMOVED: case FILE_ACTION_RENAMED_OLD_NAME: case FILE_ACTION_RENAMED_NEW_NAME: handle->cb(handle, filename, UV_RENAME, 0); break; case FILE_ACTION_MODIFIED: handle->cb(handle, filename, UV_CHANGE, 0); break; } uv__free(filename); filename = NULL; uv__free(long_filenamew); long_filenamew = NULL; filenamew = NULL; } offset = file_info->NextEntryOffset; } while (offset && !(handle->flags & UV_HANDLE_CLOSING)); } else { handle->cb(handle, NULL, UV_CHANGE, 0); } } else { err = GET_REQ_ERROR(req); handle->cb(handle, NULL, 0, uv_translate_sys_error(err)); } if (!(handle->flags & UV_HANDLE_CLOSING)) { uv_fs_event_queue_readdirchanges(loop, handle); } else { uv_want_endgame(loop, (uv_handle_t*)handle); } }
int zmq::make_fdpair (fd_t *r_, fd_t *w_) { #if defined ZMQ_HAVE_EVENTFD int flags = 0; #if defined ZMQ_HAVE_EVENTFD_CLOEXEC // Setting this option result in sane behaviour when exec() functions // are used. Old sockets are closed and don't block TCP ports, avoid // leaks, etc. flags |= EFD_CLOEXEC; #endif fd_t fd = eventfd (0, flags); if (fd == -1) { errno_assert (errno == ENFILE || errno == EMFILE); *w_ = *r_ = -1; return -1; } else { *w_ = *r_ = fd; return 0; } #elif defined ZMQ_HAVE_WINDOWS #if !defined _WIN32_WCE && !defined ZMQ_HAVE_WINDOWS_UWP // Windows CE does not manage security attributes SECURITY_DESCRIPTOR sd; SECURITY_ATTRIBUTES sa; memset (&sd, 0, sizeof sd); memset (&sa, 0, sizeof sa); InitializeSecurityDescriptor (&sd, SECURITY_DESCRIPTOR_REVISION); SetSecurityDescriptorDacl (&sd, TRUE, 0, FALSE); sa.nLength = sizeof (SECURITY_ATTRIBUTES); sa.lpSecurityDescriptor = &sd; #endif // This function has to be in a system-wide critical section so that // two instances of the library don't accidentally create signaler // crossing the process boundary. // We'll use named event object to implement the critical section. // Note that if the event object already exists, the CreateEvent requests // EVENT_ALL_ACCESS access right. If this fails, we try to open // the event object asking for SYNCHRONIZE access only. HANDLE sync = NULL; // Create critical section only if using fixed signaler port // Use problematic Event implementation for compatibility if using old port 5905. // Otherwise use Mutex implementation. int event_signaler_port = 5905; if (signaler_port == event_signaler_port) { #if !defined _WIN32_WCE && !defined ZMQ_HAVE_WINDOWS_UWP sync = CreateEventW (&sa, FALSE, TRUE, L"Global\\zmq-signaler-port-sync"); #else sync = CreateEventW (NULL, FALSE, TRUE, L"Global\\zmq-signaler-port-sync"); #endif if (sync == NULL && GetLastError () == ERROR_ACCESS_DENIED) sync = OpenEventW (SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE, L"Global\\zmq-signaler-port-sync"); win_assert (sync != NULL); } else if (signaler_port != 0) { wchar_t mutex_name[MAX_PATH]; #ifdef __MINGW32__ _snwprintf (mutex_name, MAX_PATH, L"Global\\zmq-signaler-port-%d", signaler_port); #else swprintf (mutex_name, MAX_PATH, L"Global\\zmq-signaler-port-%d", signaler_port); #endif #if !defined _WIN32_WCE && !defined ZMQ_HAVE_WINDOWS_UWP sync = CreateMutexW (&sa, FALSE, mutex_name); #else sync = CreateMutexW (NULL, FALSE, mutex_name); #endif if (sync == NULL && GetLastError () == ERROR_ACCESS_DENIED) sync = OpenMutexW (SYNCHRONIZE, FALSE, mutex_name); win_assert (sync != NULL); } // Windows has no 'socketpair' function. CreatePipe is no good as pipe // handles cannot be polled on. Here we create the socketpair by hand. *w_ = INVALID_SOCKET; *r_ = INVALID_SOCKET; // Create listening socket. SOCKET listener; listener = open_socket (AF_INET, SOCK_STREAM, 0); wsa_assert (listener != INVALID_SOCKET); // Set SO_REUSEADDR and TCP_NODELAY on listening socket. BOOL so_reuseaddr = 1; int rc = setsockopt (listener, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char *> (&so_reuseaddr), sizeof so_reuseaddr); wsa_assert (rc != SOCKET_ERROR); tune_socket (listener); // Init sockaddr to signaler port. struct sockaddr_in addr; memset (&addr, 0, sizeof addr); addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK); addr.sin_port = htons (signaler_port); // Create the writer socket. *w_ = open_socket (AF_INET, SOCK_STREAM, 0); wsa_assert (*w_ != INVALID_SOCKET); // Set TCP_NODELAY on writer socket. tune_socket (*w_); if (sync != NULL) { // Enter the critical section. DWORD dwrc = WaitForSingleObject (sync, INFINITE); zmq_assert (dwrc == WAIT_OBJECT_0 || dwrc == WAIT_ABANDONED); } // Bind listening socket to signaler port. rc = bind (listener, reinterpret_cast<const struct sockaddr *> (&addr), sizeof addr); if (rc != SOCKET_ERROR && signaler_port == 0) { // Retrieve ephemeral port number int addrlen = sizeof addr; rc = getsockname (listener, reinterpret_cast<struct sockaddr *> (&addr), &addrlen); } // Listen for incoming connections. if (rc != SOCKET_ERROR) rc = listen (listener, 1); // Connect writer to the listener. if (rc != SOCKET_ERROR) rc = connect (*w_, reinterpret_cast<struct sockaddr *> (&addr), sizeof addr); // Accept connection from writer. if (rc != SOCKET_ERROR) *r_ = accept (listener, NULL, NULL); // Send/receive large chunk to work around TCP slow start // This code is a workaround for #1608 if (*r_ != INVALID_SOCKET) { size_t dummy_size = 1024 * 1024; // 1M to overload default receive buffer unsigned char *dummy = static_cast<unsigned char *> (malloc (dummy_size)); wsa_assert (dummy); int still_to_send = static_cast<int> (dummy_size); int still_to_recv = static_cast<int> (dummy_size); while (still_to_send || still_to_recv) { int nbytes; if (still_to_send > 0) { nbytes = ::send ( *w_, reinterpret_cast<char *> (dummy + dummy_size - still_to_send), still_to_send, 0); wsa_assert (nbytes != SOCKET_ERROR); still_to_send -= nbytes; } nbytes = ::recv ( *r_, reinterpret_cast<char *> (dummy + dummy_size - still_to_recv), still_to_recv, 0); wsa_assert (nbytes != SOCKET_ERROR); still_to_recv -= nbytes; } free (dummy); } // Save errno if error occurred in bind/listen/connect/accept. int saved_errno = 0; if (*r_ == INVALID_SOCKET) saved_errno = WSAGetLastError (); // We don't need the listening socket anymore. Close it. rc = closesocket (listener); wsa_assert (rc != SOCKET_ERROR); if (sync != NULL) { // Exit the critical section. BOOL brc; if (signaler_port == event_signaler_port) brc = SetEvent (sync); else brc = ReleaseMutex (sync); win_assert (brc != 0); // Release the kernel object brc = CloseHandle (sync); win_assert (brc != 0); } if (*r_ != INVALID_SOCKET) { make_socket_noninheritable (*r_); return 0; } // Cleanup writer if connection failed if (*w_ != INVALID_SOCKET) { rc = closesocket (*w_); wsa_assert (rc != SOCKET_ERROR); *w_ = INVALID_SOCKET; } // Set errno from saved value errno = wsa_error_to_errno (saved_errno); return -1; #elif defined ZMQ_HAVE_OPENVMS // Whilst OpenVMS supports socketpair - it maps to AF_INET only. Further, // it does not set the socket options TCP_NODELAY and TCP_NODELACK which // can lead to performance problems. // // The bug will be fixed in V5.6 ECO4 and beyond. In the meantime, we'll // create the socket pair manually. struct sockaddr_in lcladdr; memset (&lcladdr, 0, sizeof lcladdr); lcladdr.sin_family = AF_INET; lcladdr.sin_addr.s_addr = htonl (INADDR_LOOPBACK); lcladdr.sin_port = 0; int listener = open_socket (AF_INET, SOCK_STREAM, 0); errno_assert (listener != -1); int on = 1; int rc = setsockopt (listener, IPPROTO_TCP, TCP_NODELAY, &on, sizeof on); errno_assert (rc != -1); rc = setsockopt (listener, IPPROTO_TCP, TCP_NODELACK, &on, sizeof on); errno_assert (rc != -1); rc = bind (listener, (struct sockaddr *) &lcladdr, sizeof lcladdr); errno_assert (rc != -1); socklen_t lcladdr_len = sizeof lcladdr; rc = getsockname (listener, (struct sockaddr *) &lcladdr, &lcladdr_len); errno_assert (rc != -1); rc = listen (listener, 1); errno_assert (rc != -1); *w_ = open_socket (AF_INET, SOCK_STREAM, 0); errno_assert (*w_ != -1); rc = setsockopt (*w_, IPPROTO_TCP, TCP_NODELAY, &on, sizeof on); errno_assert (rc != -1); rc = setsockopt (*w_, IPPROTO_TCP, TCP_NODELACK, &on, sizeof on); errno_assert (rc != -1); rc = connect (*w_, (struct sockaddr *) &lcladdr, sizeof lcladdr); errno_assert (rc != -1); *r_ = accept (listener, NULL, NULL); errno_assert (*r_ != -1); close (listener); return 0; #elif defined ZMQ_HAVE_VXWORKS struct sockaddr_in lcladdr; memset (&lcladdr, 0, sizeof lcladdr); lcladdr.sin_family = AF_INET; lcladdr.sin_addr.s_addr = htonl (INADDR_LOOPBACK); lcladdr.sin_port = 0; int listener = open_socket (AF_INET, SOCK_STREAM, 0); errno_assert (listener != -1); int on = 1; int rc = setsockopt (listener, IPPROTO_TCP, TCP_NODELAY, (char *) &on, sizeof on); errno_assert (rc != -1); rc = bind (listener, (struct sockaddr *) &lcladdr, sizeof lcladdr); errno_assert (rc != -1); socklen_t lcladdr_len = sizeof lcladdr; rc = getsockname (listener, (struct sockaddr *) &lcladdr, (int *) &lcladdr_len); errno_assert (rc != -1); rc = listen (listener, 1); errno_assert (rc != -1); *w_ = open_socket (AF_INET, SOCK_STREAM, 0); errno_assert (*w_ != -1); rc = setsockopt (*w_, IPPROTO_TCP, TCP_NODELAY, (char *) &on, sizeof on); errno_assert (rc != -1); rc = connect (*w_, (struct sockaddr *) &lcladdr, sizeof lcladdr); errno_assert (rc != -1); *r_ = accept (listener, NULL, NULL); errno_assert (*r_ != -1); close (listener); return 0; #else // All other implementations support socketpair() int sv[2]; int type = SOCK_STREAM; // Setting this option result in sane behaviour when exec() functions // are used. Old sockets are closed and don't block TCP ports, avoid // leaks, etc. #if defined ZMQ_HAVE_SOCK_CLOEXEC type |= SOCK_CLOEXEC; #endif int rc = socketpair (AF_UNIX, type, 0, sv); if (rc == -1) { errno_assert (errno == ENFILE || errno == EMFILE); *w_ = *r_ = -1; return -1; } else { make_socket_noninheritable (sv[0]); make_socket_noninheritable (sv[1]); *w_ = sv[0]; *r_ = sv[1]; return 0; } #endif }
// // FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM) // // PURPOSE: Processes messages for the main window. // // WM_COMMAND - process the application menu // WM_PAINT - Paint the main window // WM_DESTROY - post a quit message and return // // LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; switch (message) { case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // Parse the menu selections: switch (wmId) { case IDM_ABOUT: DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_PAINT: hdc = BeginPaint(hWnd, &ps); ::TextOut(hdc, 10, 10, L"Arrow keys to turn.", 19); ::SetTextColor(hdc, RGB(200,0,0)); ::TextOut(hdc, 10, 25, L"Red = Original;", 15); ::SetTextColor(hdc, RGB(0,0,255)); ::TextOut(hdc, 120, 25, L"Blue = Extrapolated", 19); ::SetTextColor(hdc, RGB(0,0,0)); { wchar_t buf[100]; _snwprintf(buf, 100, L"Latency %d ms Jitter %d ms Droprate %d%%", (int)(LATENCY*1000), (int)(JITTER*1000), (int)(DROPRATE*100)); buf[99] = 0; ::TextOut(hdc, 10, 40, buf, (INT)wcslen(buf)); } ::TextOut(hdc, 10, 55, L"F2: change draw mode", 20); ::TextOut(hdc, 10, 70, L"F3: pause/go", 12); ::TextOut(hdc, 10, 85, L"F4: single step", 15); if (gPaused) { ::SetTextColor(hdc, RGB(255,0,0)); ::TextOut(hdc, 300, 10, L"PAUSED", 6); ::SetTextColor(hdc, RGB(0,0,0)); } if (gPointDisplay) { ::TextOut(hdc, 300, 25, L"POINTS", 6); } else { ::TextOut(hdc, 300, 25, L"LINES", 5); } DrawWindow(hWnd, hdc); EndPaint(hWnd, &ps); break; case WM_DESTROY: PostQuitMessage(0); gRunning = false; break; case WM_SYSKEYDOWN: case WM_KEYDOWN: keyDown[wParam&0xff] = true; break; case WM_SYSKEYUP: case WM_KEYUP: keyDown[wParam&0xff] = false; break; case WM_ACTIVATEAPP: gActive = (wParam != 0); memset(keyDown, 0, sizeof(keyDown)); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; }
void CWE90_LDAP_Injection__w32_wchar_t_environment_32_bad() { wchar_t * data; wchar_t * *dataPtr1 = &data; wchar_t * *dataPtr2 = &data; wchar_t dataBuffer[256] = L""; data = dataBuffer; { wchar_t * data = *dataPtr1; { /* Append input from an environment variable to data */ size_t dataLen = wcslen(data); wchar_t * environment = GETENV(ENV_VARIABLE); /* If there is data in the environment variable */ if (environment != NULL) { /* POTENTIAL FLAW: Read data from an environment variable */ wcsncat(data+dataLen, environment, 256-dataLen-1); } } *dataPtr1 = data; } { wchar_t * data = *dataPtr2; { LDAP* pLdapConnection = NULL; ULONG connectSuccess = 0L; ULONG searchSuccess = 0L; LDAPMessage *pMessage = NULL; wchar_t filter[256]; /* POTENTIAL FLAW: data concatenated into LDAP search, which could result in LDAP Injection*/ _snwprintf(filter, 256-1, L"(cn=%s)", data); pLdapConnection = ldap_initW(L"localhost", LDAP_PORT); if (pLdapConnection == NULL) { printLine("Initialization failed"); exit(1); } connectSuccess = ldap_connect(pLdapConnection, NULL); if (connectSuccess != LDAP_SUCCESS) { printLine("Connection failed"); exit(1); } searchSuccess = ldap_search_ext_sW( pLdapConnection, L"base", LDAP_SCOPE_SUBTREE, filter, NULL, 0, NULL, NULL, LDAP_NO_LIMIT, LDAP_NO_LIMIT, &pMessage); if (searchSuccess != LDAP_SUCCESS) { printLine("Search failed"); if (pMessage != NULL) { ldap_msgfree(pMessage); } exit(1); } /* Typically you would do something with the search results, but this is a test case and we can ignore them */ /* Free the results to avoid incidentals */ if (pMessage != NULL) { ldap_msgfree(pMessage); } /* Close the connection */ ldap_unbind(pLdapConnection); } } }
BOOL WINAPI DllMain(HANDLE hDll, DWORD dwReason, LPVOID lpReserved) { NTSTATUS Status; BASESRV_API_CONNECTINFO ConnectInfo; ULONG ConnectInfoSize = sizeof(ConnectInfo); WCHAR SessionDir[256]; DPRINT("DllMain(hInst %p, dwReason %lu)\n", hDll, dwReason); Basep8BitStringToUnicodeString = RtlAnsiStringToUnicodeString; /* Cache the PEB and Session ID */ Peb = NtCurrentPeb(); SessionId = Peb->SessionId; switch (dwReason) { case DLL_PROCESS_ATTACH: { /* Set no filter initially */ GlobalTopLevelExceptionFilter = RtlEncodePointer(NULL); /* Enable the Rtl thread pool and timer queue to use proper Win32 thread */ RtlSetThreadPoolStartFunc(BaseCreateThreadPoolThread, BaseExitThreadPoolThread); /* Register the manifest prober routine */ LdrSetDllManifestProber(BasepProbeForDllManifest); /* Don't bother us for each thread */ LdrDisableThreadCalloutsForDll((PVOID)hDll); /* Initialize default path to NULL */ RtlInitUnicodeString(&BaseDefaultPath, NULL); /* Setup the Object Directory path */ if (!SessionId) { /* Use the raw path */ wcscpy(SessionDir, WIN_OBJ_DIR); } else { /* Use the session path */ swprintf(SessionDir, L"%ws\\%ld%ws", SESSION_DIR, SessionId, WIN_OBJ_DIR); } /* Connect to the Base Server */ Status = CsrClientConnectToServer(SessionDir, BASESRV_SERVERDLL_INDEX, &ConnectInfo, &ConnectInfoSize, &BaseRunningInServerProcess); if (!NT_SUCCESS(Status)) { DPRINT1("Failed to connect to CSR (Status %lx)\n", Status); NtTerminateProcess(NtCurrentProcess(), Status); return FALSE; } /* Get the server data */ ASSERT(Peb->ReadOnlyStaticServerData); BaseStaticServerData = Peb->ReadOnlyStaticServerData[BASESRV_SERVERDLL_INDEX]; ASSERT(BaseStaticServerData); /* Check if we are running a CSR Server */ if (!BaseRunningInServerProcess) { /* Set the termination port for the thread */ DPRINT("Creating new thread for CSR\n"); CsrNewThread(); } /* Initialize heap handle table */ BaseDllInitializeMemoryManager(); /* Set HMODULE for our DLL */ kernel32_handle = hCurrentModule = hDll; /* Set the directories */ BaseWindowsDirectory = BaseStaticServerData->WindowsDirectory; BaseWindowsSystemDirectory = BaseStaticServerData->WindowsSystemDirectory; /* Construct the default path (using the static buffer) */ _snwprintf(BaseDefaultPathBuffer, sizeof(BaseDefaultPathBuffer) / sizeof(WCHAR), L".;%wZ;%wZ\\system;%wZ;", &BaseWindowsSystemDirectory, &BaseWindowsDirectory, &BaseWindowsDirectory); BaseDefaultPath.Buffer = BaseDefaultPathBuffer; BaseDefaultPath.Length = wcslen(BaseDefaultPathBuffer) * sizeof(WCHAR); BaseDefaultPath.MaximumLength = sizeof(BaseDefaultPathBuffer); /* Use remaining part of the default path buffer for the append path */ BaseDefaultPathAppend.Buffer = (PWSTR)((ULONG_PTR)BaseDefaultPathBuffer + BaseDefaultPath.Length); BaseDefaultPathAppend.Length = 0; BaseDefaultPathAppend.MaximumLength = BaseDefaultPath.MaximumLength - BaseDefaultPath.Length; /* Initialize command line */ InitCommandLines(); /* Initialize the DLL critical section */ RtlInitializeCriticalSection(&BaseDllDirectoryLock); /* Initialize the National Language Support routines */ if (!NlsInit()) { DPRINT1("NLS Init failed\n"); return FALSE; } /* Initialize Console Support */ if (!ConDllInitialize(dwReason, SessionDir)) { DPRINT1("Failed to set up console\n"); return FALSE; } /* Initialize application certification globals */ InitializeListHead(&BasepAppCertDllsList); RtlInitializeCriticalSection(&gcsAppCert); /* Insert more dll attach stuff here! */ DllInitialized = TRUE; break; } case DLL_PROCESS_DETACH: { if (DllInitialized == TRUE) { /* Uninitialize console support */ ConDllInitialize(dwReason, NULL); /* Insert more dll detach stuff here! */ NlsUninit(); /* Delete DLL critical section */ RtlDeleteCriticalSection(&BaseDllDirectoryLock); } break; } case DLL_THREAD_ATTACH: { /* ConDllInitialize sets the current console locale for the new thread */ return ConDllInitialize(dwReason, NULL); } default: break; } return TRUE; }
// Function calculates the current laps and elapsed time since the race started DWORD* CDlgTimingScoring::CRaceScoring(LPVOID pv, HWND hWnd, int tmStartRace, int tmEndRace) { LPCTSTR lpszPath = (LPCTSTR)pv; CSfArtSQLiteDB sfDB; vector<wstring> lstTables; // HWND DlgScoring_hWnd = GetDlgItem(hWnd, IDC_RACESCORING); // TS_hWnd = GetDlgItem(hWnd, IDC_RACESCORING); if(SUCCEEDED(sfDB.Open(lpszPath, lstTables, true))) { // Race ID's are stored in the sfResult.m_RaceId structure int z = 0; while (m_sfResult->m_RaceId[z] >= 0 && z < 50) { m_ScoringData[z].db_iRaceId = m_sfResult->m_RaceId[z]; z++; } // First query for the total number of laps for each car TCHAR szTmStartRace[MAX_PATH] = {NULL}; TCHAR szTmEndRace[MAX_PATH] = {NULL}; // First let's make the strings for Start and End times long long iTmStartRace = 0; long long iTmEndRace = 0; iTmStartRace = tmStartRace; swprintf(szTmStartRace, NUMCHARS(szTmEndRace), L"%d", iTmStartRace); iTmEndRace = tmEndRace; if (iTmEndRace <= 0) { swprintf(szTmEndRace, NUMCHARS(szTmEndRace), L"5555555555"); } else { swprintf(szTmEndRace, NUMCHARS(szTmEndRace), L"%d", iTmEndRace); } // Now cycle through all selected RaceId's and get the number of laps completed CSfArtSQLiteQuery sfQuery(sfDB); TCHAR szTmp[2080] = {NULL}; TCHAR szTemp[1080] = L"select count(laps._id) from laps,races where laps.raceid=races._id and races._id = "; //? and laps.unixtime > ? and laps.unixtime < ?"; for (int y = 0; y < z; y++) { _snwprintf(szTmp, NUMCHARS(szTmp), L"%s%i and laps.unixtime > %s and laps.unixtime < %s", szTemp, m_ScoringData[y].db_iRaceId, szTmStartRace, szTmEndRace); if(sfQuery.Init(szTmp)) { while(sfQuery.Next()) { // sfQuery.BindValue(m_ScoringData[y].db_iRaceId); // sfQuery.BindValue((int)iTmStartRace); // sfQuery.BindValue((int)iTmEndRace); int cLaps = 0; if(sfQuery.GetCol(0,&cLaps)) { m_ScoringData[y].db_iTotLaps = cLaps; // Store the lap count value in the data structure } } } } // Now let's get their lap time information, so that we can figure out between-lap time differences // Right now we are just getting the time difference between EndRace time and the last lap time // First, cycle through all selected RaceId's and get all of their laptimes and sort them by race name and then by time collected in the given timespan _snwprintf(szTmp, NUMCHARS(szTmp), L""); _snwprintf(szTemp, NUMCHARS(szTemp), L"select races.name,laps.unixtime,laps._id from laps,races where laps.raceid=races._id and ("); for (int y = 0; y < z; y++) { int s_RaceId = m_ScoringData[y].db_iRaceId; if (s_RaceId != 0) { _snwprintf(szTemp, NUMCHARS(szTemp), L"%sraces._id = %i or ", szTemp, s_RaceId); } } swprintf(szTmp, wcslen(szTemp) - 3, L"%s", szTemp); _snwprintf(szTemp, NUMCHARS(szTemp), L"%s) and laps.unixtime > %s and laps.unixtime < %s order by name and unixtime", szTmp, szTmStartRace, szTmEndRace); int rec = 0, recFlag = 0; if(sfQuery.Init(szTemp)) { int db_iUnixFirstTimeStart = -1; int db_iUnixLastTimeStart = -1; TCHAR szLapsIdStart[MAX_PATH] = {NULL}; TCHAR szRaceNameStart[300] = {NULL}; long long flStartLapTime = -1; long long flFinishLapTime = -1; TCHAR szPos[MAX_PATH] = {NULL}; TCHAR szRaceName[300] = {NULL}; TCHAR szLap[300] = {NULL}; long long flLapTime = 0, flLapTemp = 0; while(sfQuery.Next()) { if (sfQuery.GetCol(0,szRaceName,NUMCHARS(szRaceName))) { if (recFlag == 0) swprintf(szRaceNameStart, NUMCHARS(szRaceNameStart), szRaceName); } if (sfQuery.GetCol(1,&flLapTemp)) { int flTemp = _wtoi(szTmStartRace); flLapTime = flLapTemp - (long long)flTemp; if (recFlag == 0) { // Initialize times for first data point flStartLapTime = flLapTime; flFinishLapTime = flLapTime; recFlag = 1; } else if (flLapTemp > flFinishLapTime && wcscmp(szRaceNameStart, szRaceName) == 0) { flFinishLapTime = flLapTemp; } else { // We have gone past the last lap for this Race_Id // Store the results in the data structure and reset the indicies m_ScoringData[rec].db_iUnixFirstTime = (int)flStartLapTime; swprintf(m_ScoringData[rec].db_strRaceName, NUMCHARS(m_ScoringData[rec].db_strRaceName), szRaceNameStart); flFinishLapTime = iTmEndRace - flFinishLapTime; m_ScoringData[rec].db_iUnixLastTime = (int)flFinishLapTime; int iTotTime = m_ScoringData[rec].db_iUnixFirstTime + m_ScoringData[rec].db_iUnixLastTime; TCHAR szText[MAX_PATH] = {NULL}; ::FormatTimeMinutesSecondsMs((float)iTotTime,szText,NUMCHARS(szText)); if (iTmEndRace > 0) { _snwprintf(m_ScoringData[rec].db_szTotTime, NUMCHARS(m_ScoringData[rec].db_szTotTime), L"%i / %s", m_ScoringData[rec].db_iTotLaps, szText); } else { _snwprintf(m_ScoringData[rec].db_szTotTime, NUMCHARS(m_ScoringData[rec].db_szTotTime), L"%i / TBD", m_ScoringData[rec].db_iTotLaps); } swprintf(szRaceNameStart, NUMCHARS(szRaceNameStart), szRaceName); flStartLapTime = flLapTime; flFinishLapTime = flLapTime; rec++; // Go to the next summary record and continue } } } // We have gone to the last lap data record // Put the final time difference into the data structure m_ScoringData[rec].db_iUnixFirstTime = (int)flStartLapTime; swprintf(m_ScoringData[rec].db_strRaceName, NUMCHARS(m_ScoringData[rec].db_strRaceName), szRaceNameStart); flFinishLapTime = iTmEndRace - flFinishLapTime; m_ScoringData[rec].db_iUnixLastTime = (int)flFinishLapTime; int iTotTime = m_ScoringData[rec].db_iUnixFirstTime + m_ScoringData[rec].db_iUnixLastTime; TCHAR szText[MAX_PATH] = {NULL}; ::FormatTimeMinutesSecondsMs((float)iTotTime,szText,NUMCHARS(szText)); if (iTmEndRace > 0) { _snwprintf(m_ScoringData[rec].db_szTotTime, NUMCHARS(m_ScoringData[rec].db_szTotTime), L"%i / %s", m_ScoringData[rec].db_iTotLaps, szText); } else { _snwprintf(m_ScoringData[rec].db_szTotTime, NUMCHARS(m_ScoringData[rec].db_szTotTime), L"%i / TBD", m_ScoringData[rec].db_iTotLaps); } rec++; // Keep the counter correct } sfDB.Close(); // Close the file // set up List view items ListView_DeleteAllItems(TS_hWnd); // Clear the list before displaying the update TCHAR szText[MAX_PATH] = {NULL}; int nItem; // LVITEM lvi; LPWSTR result; for (nItem = 0; nItem < rec; ++nItem) { p_TSlvi.mask = LVIF_TEXT | LVIF_PARAM; p_TSlvi.iItem = nItem; p_TSlvi.iSubItem = 0; p_TSlvi.lParam = nItem; swprintf(szTemp, NUMCHARS(szTemp), L"%i", m_ScoringData[nItem].db_iRaceId); std::wstring strTemp(szTemp); result = (LPWSTR)strTemp.c_str(); p_TSlvi.pszText = result; p_TSlvi.cchTextMax = wcslen(result); ListView_InsertItem(TS_hWnd, &p_TSlvi); // set up subitems p_TSlvi.mask = LVIF_TEXT; p_TSlvi.iItem = nItem; p_TSlvi.iSubItem = 1; std::wstring strRace(m_ScoringData[nItem].db_strRaceName); result = (LPWSTR)strRace.c_str(); // p_TSlvi.lParam = (LPARAM) result; // Try this for LPARAM p_TSlvi.lParam = nItem; p_TSlvi.pszText = result; p_TSlvi.cchTextMax = wcslen(result); ListView_SetItem(TS_hWnd, &p_TSlvi); p_TSlvi.iSubItem = 2; std::wstring strTotTimes(m_ScoringData[nItem].db_szTotTime); result = (LPWSTR)strTotTimes.c_str(); // p_TSlvi.lParam = (LPARAM) result; // Try this for LPARAM p_TSlvi.lParam = nItem; p_TSlvi.pszText = result; p_TSlvi.cchTextMax = wcslen(result); ListView_SetItem(TS_hWnd, &p_TSlvi); } } return 0; }
BOOL wf_post_connect(freerdp* instance) { rdpGdi* gdi; DWORD dwStyle; rdpCache* cache; wfContext* wfc; rdpContext* context; WCHAR lpWindowName[64]; rdpSettings* settings; EmbedWindowEventArgs e; settings = instance->settings; context = instance->context; wfc = (wfContext*) instance->context; cache = instance->context->cache; wfc->dstBpp = 32; wfc->width = settings->DesktopWidth; wfc->height = settings->DesktopHeight; if (wfc->sw_gdi) { gdi_init(instance, CLRCONV_ALPHA | CLRCONV_INVERT | CLRBUF_32BPP, NULL); gdi = instance->context->gdi; wfc->hdc = gdi->primary->hdc; wfc->primary = wf_image_new(wfc, wfc->width, wfc->height, wfc->dstBpp, gdi->primary_buffer); } else { wf_gdi_register_update_callbacks(instance->update); wfc->srcBpp = instance->settings->ColorDepth; wfc->primary = wf_image_new(wfc, wfc->width, wfc->height, wfc->dstBpp, NULL); wfc->hdc = gdi_GetDC(); wfc->hdc->bitsPerPixel = wfc->dstBpp; wfc->hdc->bytesPerPixel = wfc->dstBpp / 8; wfc->hdc->alpha = wfc->clrconv->alpha; wfc->hdc->invert = wfc->clrconv->invert; wfc->hdc->hwnd = (HGDI_WND) malloc(sizeof(GDI_WND)); wfc->hdc->hwnd->invalid = gdi_CreateRectRgn(0, 0, 0, 0); wfc->hdc->hwnd->invalid->null = 1; wfc->hdc->hwnd->count = 32; wfc->hdc->hwnd->cinvalid = (HGDI_RGN) malloc(sizeof(GDI_RGN) * wfc->hdc->hwnd->count); wfc->hdc->hwnd->ninvalid = 0; if (settings->RemoteFxCodec) { wfc->tile = wf_image_new(wfc, 64, 64, 32, NULL); wfc->rfx_context = rfx_context_new(FALSE); } if (settings->NSCodec) { wfc->nsc_context = nsc_context_new(); } } if (settings->WindowTitle != NULL) _snwprintf(lpWindowName, ARRAYSIZE(lpWindowName), L"%S", settings->WindowTitle); else if (settings->ServerPort == 3389) _snwprintf(lpWindowName, ARRAYSIZE(lpWindowName), L"FreeRDP: %S", settings->ServerHostname); else _snwprintf(lpWindowName, ARRAYSIZE(lpWindowName), L"FreeRDP: %S:%d", settings->ServerHostname, settings->ServerPort); if (settings->EmbeddedWindow) settings->Decorations = FALSE; if (!settings->Decorations) dwStyle = WS_CHILD | WS_BORDER; else dwStyle = 0; if (!wfc->hwnd) { wfc->hwnd = CreateWindowEx((DWORD) NULL, wfc->wndClassName, lpWindowName, dwStyle, 0, 0, 0, 0, wfc->hWndParent, NULL, wfc->hInstance, NULL); SetWindowLongPtr(wfc->hwnd, GWLP_USERDATA, (LONG_PTR) wfc); } wf_resize_window(wfc); wf_add_system_menu(wfc); BitBlt(wfc->primary->hdc, 0, 0, wfc->width, wfc->height, NULL, 0, 0, BLACKNESS); wfc->drawing = wfc->primary; EventArgsInit(&e, "wfreerdp"); e.embed = FALSE; e.handle = (void*) wfc->hwnd; PubSub_OnEmbedWindow(context->pubSub, context, &e); ShowWindow(wfc->hwnd, SW_SHOWNORMAL); UpdateWindow(wfc->hwnd); if (wfc->sw_gdi) { instance->update->BeginPaint = (pBeginPaint) wf_sw_begin_paint; instance->update->EndPaint = (pEndPaint) wf_sw_end_paint; instance->update->DesktopResize = (pDesktopResize) wf_sw_desktop_resize; } else { instance->update->BeginPaint = (pBeginPaint) wf_hw_begin_paint; instance->update->EndPaint = (pEndPaint) wf_hw_end_paint; instance->update->DesktopResize = (pDesktopResize) wf_hw_desktop_resize; } pointer_cache_register_callbacks(instance->update); if (wfc->sw_gdi != TRUE) { brush_cache_register_callbacks(instance->update); bitmap_cache_register_callbacks(instance->update); offscreen_cache_register_callbacks(instance->update); } wf_register_graphics(instance->context->graphics); freerdp_channels_post_connect(instance->context->channels, instance); wf_cliprdr_init(wfc, instance->context->channels); floatbar_window_create(wfc); return TRUE; }
// Function updates the HotLap screen for HPDE's and track days, based upon user choices for Race Sessions selected DWORD* CDlgTimingScoring::TimingScoringProc(LPVOID pv, HWND hWnd) { LPCTSTR lpszPath = (LPCTSTR)pv; CSfArtSQLiteDB sfDB; vector<wstring> lstTables; // HL_hWnd = GetDlgItem(hWnd, IDC_TIMINGSCORING); if(SUCCEEDED(sfDB.Open(lpszPath, lstTables, true))) { // Race ID's are stored in the sfResult.m_RaceId structure int z = 0; int z_RaceId[50] = {-1}; while (m_sfResult->m_RaceId[z] >= 0 && z < 50) { z_RaceId[z] = m_sfResult->m_RaceId[z]; z++; } vector<wstring> lstPos; vector<wstring> lstRaceName; vector<wstring> lstComment; vector<wstring> lstLapTimes; CSfArtSQLiteQuery sfQuery(sfDB); TCHAR szTmp[1080] = {NULL}; // Now cycle through all selected RaceId's and get their laptimes and sort them TCHAR szTemp[1080] = L"select races.name,laps.laptime,extras.comment from laps,races left join extras on extras.lapid = laps._id where laps.raceid=races._id and ("; for (int y = 0; y < z; y++) { int s_RaceId = z_RaceId[y]; if (s_RaceId != 0) { _snwprintf(szTemp, NUMCHARS(szTemp), L"%sraces._id = %i or ", szTemp, s_RaceId); } } swprintf(szTmp, wcslen(szTemp) - 3, L"%s", szTemp); _snwprintf(szTemp, NUMCHARS(szTemp), L"%s) order by laptime asc limit 40", szTmp); if(sfQuery.Init(szTemp)) { SYSTEMTIME st; GetSystemTime(&st); int z = 1; TCHAR szPos[MAX_PATH] = {NULL}; TCHAR szRaceName[300] = {NULL}; TCHAR szComment[300] = {NULL}; TCHAR szLap[300] = {NULL}; // Load up all of the HL vectors with data from the database while(sfQuery.Next()) { float flLapTime = 0; sfQuery.GetCol(0,szRaceName,NUMCHARS(szRaceName)); sfQuery.GetCol(1,&flLapTime); sfQuery.GetCol(2,szComment,NUMCHARS(szComment)); ::FormatTimeMinutesSecondsMs(flLapTime,szLap,NUMCHARS(szLap)); _snwprintf(szPos,NUMCHARS(szPos),L"%i",z); lstPos.push_back(szPos); lstRaceName.push_back(szRaceName); lstComment.push_back(szComment); lstLapTimes.push_back(szLap); z++; } // HWND HL_hWnd = GetDlgItem(hWnd, IDC_TIMINGSCORING); ListView_DeleteAllItems(HL_hWnd); // Clear the list before displaying the update ClearHotLaps(); // Clear the Top 40 Hot Laps list before updating TCHAR szText[MAX_PATH] = {NULL}; // set up list view items int nItem; // LVITEM p_HLlvi; LPWSTR result; for (nItem = 0; nItem < z - 1; ++nItem) { p_HLlvi.mask = LVIF_TEXT | LVIF_PARAM; p_HLlvi.iItem = nItem; p_HLlvi.iSubItem = 0; p_HLlvi.lParam = nItem; std::wstring strPos(lstPos[nItem]); result = (LPWSTR)strPos.c_str(); p_HLlvi.pszText = result; p_HLlvi.cchTextMax = wcslen(result); ListView_InsertItem(HL_hWnd, &p_HLlvi); // set up subitems p_HLlvi.mask = LVIF_TEXT; p_HLlvi.iItem = nItem; p_HLlvi.iSubItem = 1; std::wstring strRace(lstRaceName[nItem]); result = (LPWSTR)strRace.c_str(); //From TCHAR to DWORD. // DWORD dwSomeNum; // dwSomeNum = wcstod(result, _T('\0')); // p_HLlvi.lParam = (LPARAM) dwSomeNum; // Try this for LPARAM p_HLlvi.lParam = nItem; p_HLlvi.pszText = result; p_HLlvi.cchTextMax = wcslen(result); ListView_SetItem(HL_hWnd, &p_HLlvi); p_HLlvi.iSubItem = 2; std::wstring strComment(lstComment[nItem]); result = (LPWSTR)strComment.c_str(); //From TCHAR to DWORD. // dwSomeNum = wcstod(result, _T('\0')); // p_HLlvi.lParam = (LPARAM) dwSomeNum; // Try this for LPARAM p_HLlvi.lParam = nItem; p_HLlvi.pszText = result; p_HLlvi.cchTextMax = wcslen(result); ListView_SetItem(HL_hWnd, &p_HLlvi); p_HLlvi.iSubItem = 3; p_HLlvi.pszText = (LPWSTR)&lstLapTimes[nItem]; std::wstring strLapTimes(lstLapTimes[nItem]); result = (LPWSTR)strLapTimes.c_str(); //From TCHAR to DWORD. // dwSomeNum = wcstod(result, _T('\0')); // p_HLlvi.lParam = (LPARAM) dwSomeNum; // Try this for LPARAM p_HLlvi.lParam = nItem; p_HLlvi.pszText = result; p_HLlvi.cchTextMax = wcslen(result); ListView_SetItem(HL_hWnd, &p_HLlvi); } // Now load the RACERESULTS vectors with the Top 40 Hot Laps for saving to a text file for (int y = 0; y < z -1; y++) { std::wstring strPos(lstPos[y]); result = (LPWSTR)strPos.c_str(); _snwprintf(m_ScoringData[y].lstPos, NUMCHARS(m_ScoringData[y].lstPos), result); std::wstring strRace(lstRaceName[y]); result = (LPWSTR)strRace.c_str(); _snwprintf(m_ScoringData[y].lstRaceName, NUMCHARS(m_ScoringData[y].lstRaceName), result); std::wstring strComment(lstComment[y]); result = (LPWSTR)strComment.c_str(); _snwprintf(m_ScoringData[y].lstComment, NUMCHARS(m_ScoringData[y].lstComment), result); std::wstring strLapTimes(lstLapTimes[y]); result = (LPWSTR)strLapTimes.c_str(); _snwprintf(m_ScoringData[y].lstLapTimes, NUMCHARS(m_ScoringData[y].lstLapTimes), result); } } lstPos.clear(); lstRaceName.clear(); lstComment.clear(); lstLapTimes.clear(); sfDB.Close(); } return 0; }
WCHAR* Explorer::RecurseDirectory(WCHAR *wStartPath, WCHAR *wRecursePath) { _snwprintf(wRecursePath, MAX_PATH, L"%s\\*", wStartPath); return wRecursePath; }
DWORD WINAPI eventLogMonitorThreadProc(LPVOID elm_info_param) { EVENTLOGRECORD *pevlr; BYTE bBuffer[BUFFER_SIZE] = { 0 }; DWORD dwRead, dwNeeded, res; DWORD reported_next_record, num_records; BOOL skip_first = FALSE; HANDLE log = NULL, event = NULL; WCHAR msgbuf[BUFFER_SIZE]; eventlogmon_info *elm_info = (eventlogmon_info *) elm_info_param; control = 0; log = OpenEventLog(NULL, L_COMPANY_NAME); if (log == NULL) { (*elm_info->cb_err)(ELM_ERR_FATAL, L"Could not open the " L_COMPANY_NAME L" event log."); goto exit_elm_thread_error; } event = CreateEvent(NULL, FALSE, FALSE, NULL); NotifyChangeEventLog(log, event); pevlr = (EVENTLOGRECORD *) &bBuffer; if (!GetNumberOfEventLogRecords(log, &num_records) || !GetOldestEventLogRecord(log, &reported_next_record)) { _snwprintf(msgbuf, BUFFER_SIZE_ELEMENTS(msgbuf), L"error %d getting eventlog info", GetLastError()); (*elm_info->cb_err)(ELM_ERR_FATAL, msgbuf); goto exit_elm_thread_error; } /* FIXME: we don't handle the situation when the eventlog was cleared, * but our pointer is less than the number of new records. for this * we'll probably have to store a timestamp, and compare against the * event record at next_record. */ if (((int)elm_info->next_record) < 0) { elm_info->next_record = reported_next_record; } else if (elm_info->next_record > (reported_next_record + num_records + 1)) { /* looks like the eventlog was cleared since we last checked * it. issue a warning and reset */ elm_info->next_record = reported_next_record; (*elm_info->cb_err)(ELM_ERR_CLEARED, L"Eventlog was cleared!\n"); } else { /* we need to ensure we SEEK to a valid record; but since * it's already been reported, don't report it again. */ elm_info->next_record--; skip_first = TRUE; } /* first seek to the last record * EVENTLOG_FORWARDS_READ indicates we will get messages in * chronological order. * FIXME: test to make sure that this works properly on * overwrite-wrapped logs */ if (!ReadEventLog(log, EVENTLOG_FORWARDS_READ | EVENTLOG_SEEK_READ, elm_info->next_record, pevlr, BUFFER_SIZE, &dwRead, &dwNeeded)) { dwRead = 0; dwNeeded = 0; } for(;;) { do { /* case 5813: if pevlr->Length is 0, we'll have an infinite * loop. this could possibly happen if drive is full? * just abort if we detect it. */ while (dwRead > 0 && pevlr->Length > 0) { if (format_messages && !skip_first) { res = get_formatted_message(pevlr, msgbuf, BUFFER_SIZE); if (res != ERROR_SUCCESS) { _snwprintf(msgbuf, BUFFER_SIZE_ELEMENTS(msgbuf), L"FormatMessage error %d\n", res); (*elm_info->cb_err)(ELM_ERR_WARN, msgbuf); } else { /* invoke the callback */ (*elm_info->cb_format)(pevlr->RecordNumber, pevlr->EventType, msgbuf, pevlr->TimeGenerated); } } else if(!skip_first) { /* xref case 3065: insurance */ if (pevlr->RecordNumber != 0 || pevlr->TimeGenerated != 0) { /* raw callback */ (*elm_info->cb_raw)(pevlr); } } else { skip_first = FALSE; } dwRead -= pevlr->Length; pevlr = (EVENTLOGRECORD *) ((LPBYTE) pevlr + pevlr->Length); } pevlr = (EVENTLOGRECORD *) &bBuffer; } while (ReadEventLog(log, EVENTLOG_FORWARDS_READ | EVENTLOG_SEQUENTIAL_READ, 0, pevlr, BUFFER_SIZE, &dwRead, &dwNeeded)); if((res = GetLastError()) != ERROR_HANDLE_EOF) { //FIXME: assert GetLastError() is appropriate _snwprintf(msgbuf, BUFFER_SIZE_ELEMENTS(msgbuf), L"Unexpected error %d reading event log\n", res); (*elm_info->cb_err)(ELM_ERR_WARN, msgbuf); } if (do_once) break; /* the event is auto-reset. timeout because NotifyChangeEventLog is not reliable. */ WaitForSingleObject(event, MINIPULSE); if(control) break; } exit_elm_thread_error: if (log != NULL) CloseEventLog(log); if (event != NULL) CloseHandle(event); free(elm_info); /* FIXME: need ExitThread()? */ return 0; }
void CreateMinidump(void* pInfo, tchar* pszDirectory) { #ifndef _DEBUG time_t currTime = ::time( NULL ); struct tm * pTime = ::localtime( &currTime ); wchar_t szModule[MAX_PATH]; ::GetModuleFileName( NULL, szModule, sizeof(szModule) / sizeof(tchar) ); wchar_t *pModule = wcsrchr( szModule, '.' ); if ( pModule ) *pModule = 0; pModule = wcsrchr( szModule, '\\' ); if ( pModule ) pModule++; else pModule = L"unknown"; wchar_t szFileName[MAX_PATH]; _snwprintf( szFileName, sizeof(szFileName) / sizeof(tchar), L"%s_%d.%.2d.%2d.%.2d.%.2d.%.2d_%d.mdmp", pModule, pTime->tm_year + 1900, pTime->tm_mon + 1, pTime->tm_mday, pTime->tm_hour, pTime->tm_min, pTime->tm_sec, g_iMinidumpsWritten++ ); HANDLE hFile = CreateFile( convert_to_wstring(GetAppDataDirectory(pszDirectory, convert_from_wstring(szFileName))).c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); if( ( hFile != NULL ) && ( hFile != INVALID_HANDLE_VALUE ) ) { MINIDUMP_EXCEPTION_INFORMATION mdei; mdei.ThreadId = GetCurrentThreadId(); mdei.ExceptionPointers = (EXCEPTION_POINTERS*)pInfo; mdei.ClientPointers = FALSE; MINIDUMP_CALLBACK_INFORMATION mci; mci.CallbackRoutine = NULL; mci.CallbackParam = 0; MINIDUMP_TYPE mdt = (MINIDUMP_TYPE)(MiniDumpWithIndirectlyReferencedMemory | MiniDumpScanMemory); BOOL rv = MiniDumpWriteDump( GetCurrentProcess(), GetCurrentProcessId(), hFile, mdt, (pInfo != 0) ? &mdei : 0, 0, &mci ); if( rv ) { // Success... message to user? } CloseHandle( hFile ); } #endif }
LRESULT CALLBACK view_context_proc(HWND hwnd,UINT msg,WPARAM wparam,LPARAM lparam) { static HWND grippy=0; int lines,dir,do_scroll=FALSE,update_scroll_pos=TRUE; static int divider_drag=FALSE,org_row_width=90,row_width=90,last_pos=0; #ifdef _DEBUG if(FALSE) // if(message!=0x200&&message!=0x84&&message!=0x20&&message!=WM_ENTERIDLE) // if(msg!=WM_MOUSEFIRST&&msg!=WM_NCHITTEST&&msg!=WM_SETCURSOR&&msg!=WM_ENTERIDLE&&msg!=WM_DRAWITEM // &&msg!=WM_CTLCOLORBTN&&msg!=WM_CTLCOLOREDIT&&msg!=WM_CTLCOLORSCROLLBAR) if(msg!=WM_NCHITTEST&&msg!=WM_SETCURSOR&&msg!=WM_ENTERIDLE) { static DWORD tick=0; if((GetTickCount()-tick)>500) printf("--\n"); printf("v"); print_msg(msg,lparam,wparam); tick=GetTickCount(); } #endif switch(msg) { case WM_INITDIALOG: grippy=create_grippy(hwnd); init_context_win_anchor(hwnd); get_ini_value("CONTEXT_WINDOW","row_width",&row_width); set_context_divider(hwnd,row_width); restore_context_rel_pos(hwnd); SendDlgItemMessage(hwnd,IDC_CONTEXT_SCROLLBAR,SBM_SETRANGE,0,10000); { int tabstop=21; //4 fixed chars SendDlgItemMessage(hwnd,IDC_CONTEXT,EM_SETTABSTOPS,1,&tabstop); } set_context_font(hwnd); open_file(&gfh); if(gfh==0){ WCHAR str[MAX_PATH*2]; _snwprintf(str,sizeof(str)/sizeof(WCHAR),L"cant open %s",fname); str[sizeof(str)/sizeof(WCHAR)-1]=0; MessageBoxW(hwnd,str,L"error",MB_OK); EndDialog(hwnd,0); return 0; } get_file_size(gfh,&fsize); _fseeki64(gfh,start_offset,SEEK_SET); set_scroll_pos(hwnd,IDC_CONTEXT_SCROLLBAR,gfh); SetFocus(GetDlgItem(hwnd,IDC_CONTEXT_SCROLLBAR)); line_count=get_number_of_lines(hwnd,IDC_CONTEXT); fill_context(hwnd,IDC_CONTEXT,gfh); close_file(&gfh); last_pos=-1; orig_edit=SetWindowLong(GetDlgItem(hwnd,IDC_CONTEXT),GWL_WNDPROC,subclass_edit); orig_scroll=SetWindowLong(GetDlgItem(hwnd,IDC_CONTEXT_SCROLLBAR),GWL_WNDPROC,subclass_scroll); SetWindowTextW(hwnd,fname); return 0; case WM_DESTROY: save_context_rel_pos(hwnd); break; case WM_HELP: context_help(hwnd); return TRUE; break; case WM_SIZE: grippy_move(hwnd,grippy); set_context_divider(hwnd,row_width); line_count=get_number_of_lines(hwnd,IDC_CONTEXT); open_file(&gfh); fill_context(hwnd,IDC_CONTEXT,gfh); set_scroll_pos(hwnd,IDC_CONTEXT_SCROLLBAR,gfh); close_file(&gfh); break; case WM_RBUTTONDOWN: case WM_LBUTTONUP: ReleaseCapture(); if(divider_drag){ write_ini_value("CONTEXT_WINDOW","row_width",row_width); divider_drag=FALSE; } break; case WM_LBUTTONDOWN: SetCapture(hwnd); SetCursor(LoadCursor(NULL,IDC_SIZEWE)); divider_drag=TRUE; org_row_width=row_width; break; case WM_MOUSEFIRST: { int x=LOWORD(lparam); SetCursor(LoadCursor(NULL,IDC_SIZEWE)); if(divider_drag){ RECT rect; GetClientRect(hwnd,&rect); if((rect.right-x)>25 && x>5){ row_width=x; set_context_divider(hwnd,row_width); } } } break; case WM_MOUSEWHEEL: { short wheel=HIWORD(wparam); int flags=LOWORD(wparam); if(wheel>0){ dir=-1; if(flags&MK_RBUTTON) lines=line_count-2; else lines=3+1; } else{ dir=1; if(flags&MK_RBUTTON) lines=line_count-2-1; else lines=3; } do_scroll=TRUE; } break; case WM_VSCROLL: { int pos=HIWORD(wparam); switch(LOWORD(wparam)){ case SB_TOP: if(GetKeyState(VK_CONTROL)&0x8000){ last_offset=0; current_line=1; } else{ last_offset=start_offset; //_fseeki64(f,start_offset,SEEK_SET); current_line=start_line; } lines=dir=0; do_scroll=TRUE; break; case SB_PAGEUP: dir=-1; lines=line_count-2; if(lines<=0) lines=1; do_scroll=TRUE; break; case SB_PAGEDOWN: dir=1; lines=line_count-2-1; if(lines<=0) lines=1; do_scroll=TRUE; break; case SB_LINEUP: dir=-1; lines=2; do_scroll=TRUE; break; case SB_LINEDOWN: dir=1; lines=1; do_scroll=TRUE; break; case SB_THUMBTRACK: //printf("pos=%i last_pos=%i scroll_pos=%i line_count=%i\n",HIWORD(wparam),last_pos,scroll_pos,line_count); if(pos<last_pos){ dir=-1; lines=line_count/4; if(lines<=1) lines=2; do_scroll=TRUE; } else if(pos>last_pos){ dir=1; lines=line_count/4; if(lines==0) lines=1; do_scroll=TRUE; } if(last_pos==-1) do_scroll=FALSE; last_pos=pos; update_scroll_pos=FALSE; break; case SB_THUMBPOSITION: //dragged and released dir=lines=0; do_scroll=TRUE; break; case SB_ENDSCROLL: last_pos=-1; break; } } break; case WM_COMMAND: switch(LOWORD(wparam)){ case IDCANCEL: if(divider_drag){ divider_drag=FALSE; ReleaseCapture(); set_context_divider(hwnd,org_row_width); row_width=org_row_width; return 0; } if(gfh!=0) fclose(gfh); gfh=0; if(orig_edit!=0)SetWindowLong(GetDlgItem(hwnd,IDC_CONTEXT),GWL_WNDPROC,orig_edit); EndDialog(hwnd,0); return 0; } break; } if(do_scroll) do_scroll_proc(hwnd,lines,dir,update_scroll_pos); return 0; }
BOOL WINAPI in_whitelist(LPCWSTR lpfile) { WCHAR *moz_processes[] = {L"", L"plugin-container.exe", L"plugin-hang-ui.exe", L"webapprt-stub.exe", L"webapp-uninstaller.exe",L"WSEnable.exe",L"uninstall\\helper.exe", L"crashreporter.exe",L"CommandExecuteHandler.exe",L"maintenanceservice.exe", L"maintenanceservice_installer.exe",L"updater.exe" }; static WCHAR white_list[EXCLUDE_NUM][VALUE_LEN+1]; int i = sizeof(moz_processes)/sizeof(moz_processes[0]); LPCWSTR pname = lpfile; BOOL ret = FALSE; if (lpfile[0] == L'"') { pname = &lpfile[1]; } /* 遍历白名单一次,只需遍历一次 */ ret = stristrW(white_list[1],L"plugin-container.exe") != NULL; if ( !ret ) { /* firefox目录下进程的路径 */ int num; WCHAR temp[VALUE_LEN+1]; GetModuleFileNameW(NULL,temp,VALUE_LEN); wcsncpy(white_list[0],(LPCWSTR)temp,VALUE_LEN); PathRemoveFileSpecW(temp); for(num=1; num<i; ++num) { _snwprintf(white_list[num],VALUE_LEN,L"%ls\\%ls", temp, moz_processes[num]); } ret = foreach_section(L"whitelist", &white_list[num], EXCLUDE_NUM-num); } if ( (ret = !ret) == FALSE ) { /* 核对白名单 */ for ( i=0; i<EXCLUDE_NUM ; i++ ) { if (wcslen(white_list[i]) == 0) { continue; } if ( StrChrW(white_list[i],L'*') || StrChrW(white_list[i],L'?') ) { if ( PathMatchSpecW(pname,white_list[i]) ) { ret = TRUE; break; } } else if (white_list[i][1] != L':') { PathToCombineW(white_list[i],VALUE_LEN); } if (_wcsnicmp(white_list[i],pname,wcslen(white_list[i]))==0) { ret = TRUE; break; } } } return ret; }
PW32CP wchar_t *php_win32_cp_conv_ascii_to_w(const char* in, size_t in_len, size_t *out_len) {/*{{{*/ wchar_t *ret = NULL; const char *idx = in, *end; assert(in && in_len ? in[in_len] == '\0' : 1); if (!in) { SET_ERRNO_FROM_WIN32_CODE(ERROR_INVALID_PARAMETER); return NULL; } else if (0 == in_len) { /* Not binary safe. */ in_len = strlen(in); if (in_len > (size_t)INT_MAX) { SET_ERRNO_FROM_WIN32_CODE(ERROR_INVALID_PARAMETER); return NULL; } } end = in + in_len; while (idx != end) { if (!__isascii(*idx) && '\0' != *idx) { break; } idx++; } if (idx == end) { size_t i = 0; int k = 0; wchar_t *ret_idx; ret = malloc((in_len+1)*sizeof(wchar_t)); if (!ret) { SET_ERRNO_FROM_WIN32_CODE(ERROR_OUTOFMEMORY); return NULL; } ret_idx = ret; do { k = _snwprintf(ret_idx, in_len - i, L"%.*hs", (int)(in_len - i), in); if (-1 == k) { free(ret); SET_ERRNO_FROM_WIN32_CODE(ERROR_INVALID_PARAMETER); return NULL; } i += k + 1; if (i < in_len) { /* Advance as this seems to be a string with \0 in it. */ in += k + 1; ret_idx += k + 1; } } while (i < in_len); ret[in_len] = L'\0'; assert(ret ? wcslen(ret) == in_len : 1); if (PHP_WIN32_CP_IGNORE_LEN_P != out_len) { *out_len = in_len; } } else { if (PHP_WIN32_CP_IGNORE_LEN_P != out_len) { *out_len = 0; } } return ret; }/*}}}*/
// ========================================================================= BOOL CALLBACK dlgAbout_HandleMsg_WM_INITDIALOG(HWND hDlg) { LPWSTR strVersion; SHINITDLGINFO shidi; WCHAR betaNumber[5]; // Needs to be long enough to hold the beta number DWORD driverVersion; WCHAR driverVersionStr[256]; // 256 pretty arbitary; just needs to be big // enough to store the formatted version // string SDUI18N_LANGUAGEW translationDetails; DEBUGOUTGUI(DEBUGLEV_ENTER, (TEXT("dlgAbout_HandleMsg_WM_INITDIALOG\n"))); shidi.dwMask = SHIDIM_FLAGS; shidi.dwFlags = ( SHIDIF_DONEBUTTON | SHIDIF_SIPDOWN | SHIDIF_SIZEDLGFULLSCREEN ); shidi.hDlg = hDlg; SHInitDialog(&shidi); G_dlgAbout_MenuBar = SetupMenu_Simple(hDlg, IDR_MENU_NULL); G_URLBrush = CreateSolidBrush(RGB(255, 0, 255)); SDUi18n_TranslateWindow(hDlg); SDUi18n_TranslateCommandBar(G_dlgAbout_MenuBar); // App title... SDUTextSetBold(hDlg, IDC_APP_TITLE, TRUE); SetStaticText(hDlg, IDC_APP_TITLE, APP_TITLE); // Meeeee! SetStaticText(hDlg, IDC_APP_AUTHORCREDIT, APP_AUTHOR_CREDIT); // Translator credit... SetControlVisible(hDlg, IDC_APP_TRANSLATORCREDIT, FALSE); if (!(SDUi18nIsLanguageCodeEnglishW(G_Options->LanguageCode))) { if (SDUi18n_GetTranslationDetailsW( G_Options->LanguageCode, &translationDetails )) { SetStaticText( hDlg, IDC_APP_TRANSLATORCREDIT, SDUParamSubstituteW( _("%1 translation by %2"), TEXT("%s"), translationDetails.LanguageName, TEXT("%s"), translationDetails.TranslatorName, NULL ) ); SetControlVisible(hDlg, IDC_APP_TRANSLATORCREDIT, TRUE); } } // App version... if (SDUGetVersionInfoShortFmtAlloc( NULL, &strVersion )) { SetStaticText(hDlg, IDC_APP_VERSION, strVersion); free(strVersion); } if (APP_BETA_BUILD > 0) { _itow(APP_BETA_BUILD, betaNumber, 10); AppendStaticText_ResizeToText(hDlg, IDC_APP_VERSION, TEXT(" ")); AppendStaticText_ResizeToText(hDlg, IDC_APP_VERSION, _("BETA")); AppendStaticText_ResizeToText(hDlg, IDC_APP_VERSION, TEXT(" ")); AppendStaticText_ResizeToText(hDlg, IDC_APP_VERSION, betaNumber); } // Driver version... SetStaticText( hDlg, IDC_DRIVER_VERSION, _("<unknown>") ); if (driver_VersionID(&driverVersion)) { if (_snwprintf( driverVersionStr, //(sizeof(driverVersionStr) * sizeof(driverVersionStr[0])), (sizeof(driverVersionStr) / sizeof(driverVersionStr[0])), TEXT("v%d.%0.2d.%0.4d"), (driverVersion & 0xFF000000) / 0x00FF0000, (driverVersion & 0x00FF0000) / 0x0000FF00, (driverVersion & 0x0000FFFF) ) >= 0) { SetStaticText(hDlg, IDC_DRIVER_VERSION, driverVersionStr); } } _dlgAbout_AlignControls(hDlg); // Tappable URL... SetStaticText(hDlg, IDC_STATIC_URL, APP_URL); SDUTextSetUnderline(hDlg, IDC_STATIC_URL, TRUE); DEBUGOUTGUI(DEBUGLEV_EXIT, (TEXT("dlgAbout_HandleMsg_WM_INITDIALOG\n"))); return TRUE; }
/* * Set the key for an SSID on an interface */ DWORD SetIfaceProfile (HANDLE h, const GUID *iface, WLANKEY *key, BOOL replace, WLAN_REASON_CODE *reason){ static wchar_t profilexml[65536]; static wchar_t securityxml[65536]; static wchar_t onexconfigxml[65536]; static wchar_t rootcaxml[65536]; static wchar_t tmp[65]; static wchar_t ssid[512]; static wchar_t name[512]; static wchar_t auth[512]; static wchar_t enc[512]; static wchar_t psk[512]; static unsigned char zeroca[20] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; int i, j; DWORD status; fwprintf (stderr, L" Creating profile for %s\n", key->displayname); XMLEntities (ssid, key->ssid, 512); XMLEntities (auth, key->auth, 512); XMLEntities (enc, key->enc, 512); XMLEntities (name, key->displayname, 512); securityxml[0] = securityxml[65535] = 0; profilexml[0] = profilexml[65535] = 0; onexconfigxml[0] = onexconfigxml[65535] = 0; rootcaxml[0] = rootcaxml[65535] = 0; if (wcscmp (auth, L"WPAPSK") == 0 || wcscmp(auth, L"WPA2PSK") == 0){ wcsncpy (tmp, key->wpa.psk, 64); tmp[64] = 0; XMLEntities (psk, tmp, 512); if (wcslen(psk) == 64){ _snwprintf (securityxml, 65535, securityxmlpskkey, psk); } else { _snwprintf (securityxml, 65535, securityxmlpskpass, psk); } } else if (key->useonex){ memset (rootcaxml, 0, 65536); for (i = 0; i < 4; i++){ if (memcmp(key->wpa.onex.rootca[i].hash, zeroca, 20) != 0){ wcscat (rootcaxml, L" "); wcscat (rootcaxml, L"<TrustedRootCA>"); for (j = 0; j < 20; j++){ _snwprintf (tmp, 64, L"%02x ", key->wpa.onex.rootca[i].hash[j]); wcscat (rootcaxml, tmp); } wcscat (rootcaxml, L"</TrustedRootCA>\n"); } } if (key->wpa.onex.eaptype == 13){ /* EAP-TLS */ _snwprintf (onexconfigxml, 65536, securityxmleaptls, rootcaxml, key->wpa.onex.eap.tls.diffuser ? L"true" : L"false"); } else if (key->wpa.onex.eaptype == 25){ /* PEAP-MSCHAPv2 */ _snwprintf (onexconfigxml, 65536, securityxmlpeapmschap, rootcaxml, key->wpa.onex.eap.mschap.usecred ? L"true" : L"false"); } _snwprintf (securityxml, 65536, securityxmlonex, key->wpa.onex.sso ? securityxmlsso : L"", key->wpa.onex.eaptype, key->wpa.onex.eaptype, onexconfigxml); } _snwprintf (profilexml, 65535, profilexmltpl, name, ssid, key->autoconnect ? L"auto" : L"manual", key->preferred ? L"false" : L"true", auth, enc, key->useonex ? L"true" : L"false", securityxml); status = WlanSetProfile (h, iface, 0, profilexml, NULL, replace, NULL, reason); if (status == ERROR_ALREADY_EXISTS){ fwprintf (stderr, L" Profile %s already exists\n", key->displayname); return ERROR_SUCCESS; } else { return status; } }
void DisassembleArgument(BYTE *ip, DWORD address, int type, __inout_z WCHAR *buffer) { /* * !!! this code isn't processor portable. */ switch (type) { case InlineNone: *buffer = L'\0'; break; case ShortInlineI: _snwprintf(buffer, INT_MAX/sizeof(WCHAR), L"%d", *(char *)ip); break; case ShortInlineVar: _snwprintf(buffer, INT_MAX/sizeof(WCHAR), L"%u", *(unsigned char *)ip); break; case InlineVar: _snwprintf(buffer, INT_MAX/sizeof(WCHAR), L"%u", GET_UNALIGNED_VAL16(ip)); break; case InlineI: _snwprintf(buffer, INT_MAX/sizeof(WCHAR), L"%d", GET_UNALIGNED_VAL32(ip)); break; case InlineI8: _snwprintf(buffer, INT_MAX/sizeof(WCHAR), L"%I64d", GET_UNALIGNED_VAL64(ip)); break; case ShortInlineR: { __int32 Value = GET_UNALIGNED_VAL32(ip); _snwprintf(buffer, INT_MAX/sizeof(WCHAR), L"%g", (float &)Value); } break; case InlineR: { __int64 Value = GET_UNALIGNED_VAL64(ip); _snwprintf(buffer, INT_MAX/sizeof(WCHAR), L"%g", (double &) Value); } break; case ShortInlineBrTarget: _snwprintf(buffer, INT_MAX/sizeof(WCHAR), L"[%.4x]", address + 1 + *(char *)ip); break; case InlineBrTarget: _snwprintf(buffer, INT_MAX/sizeof(WCHAR), L"[%.4x]", address + 4 + GET_UNALIGNED_VAL32(ip)); break; case InlineSwitch: { DWORD caseCount = GET_UNALIGNED_VAL32(ip); ip += 4; address += caseCount*4 + 4; DWORD index = 0; while (index < caseCount) { int offset = GET_UNALIGNED_VAL32(ip); buffer += wcslen(buffer); _snwprintf(buffer, INT_MAX/sizeof(WCHAR), L"%d:[%.4x] ", index, address + offset); index++; ip += 4; } } break; case InlinePhi: { DWORD caseCount = *(unsigned char*)ip; ip += 1; DWORD index = 0; while (index < caseCount) { buffer += wcslen(buffer); _snwprintf(buffer, INT_MAX/sizeof(WCHAR), L"%d:[%.4x] ", index, GET_UNALIGNED_VAL16(ip)); index++; ip += 2; } } break; case InlineTok: case InlineMethod: case InlineField: case InlineType: case InlineSig: _snwprintf(buffer, INT_MAX/sizeof(WCHAR), L"%d", GET_UNALIGNED_VAL32(ip)); break; case InlineString: _snwprintf(buffer, INT_MAX/sizeof(WCHAR), L"%08x", GET_UNALIGNED_VAL32(ip)); break; default: _snwprintf(buffer, INT_MAX/sizeof(WCHAR), L"<unknown type %d>", type); } }
BOOL UpdateProgressBarProc (__int64 byteOffset) { wchar_t text[100]; wchar_t speed[100]; HWND hProgressBar = GetDlgItem (hCurPage, nPbar); int time = GetTickCount (); int elapsed = (time - startTime) / 1000; uint64 bytesDone = (bProgressBarReverse ? (TotalSize - byteOffset) : byteOffset); uint64 bytesPerSec = (bProgressBarReverse ? (resumedPointBytesDone - byteOffset) : (bytesDone - resumedPointBytesDone)) / (elapsed + 1); if (bPercentMode) { double perc = (double) (100.0 * (bProgressBarReverse ? ((double) (TotalSize - byteOffset)) : ((double) byteOffset)) / (TotalSize == 0 ? 0.0001 : ((double) TotalSize))); if (perc > 99.999999999) wcscpy (text, GetString ("PROCESSED_PORTION_100_PERCENT")); else _snwprintf (text, sizeof text/2, GetString ("PROCESSED_PORTION_X_PERCENT"), perc); wcscat (speed, L" "); } else { GetSizeString (bytesDone, text); if (bytesDone < (unsigned __int64) BYTES_PER_MB * 1000000) swprintf(text, L"%I64d %s ", bytesDone / BYTES_PER_MB, GetString ("MB")); else if (bytesDone < (unsigned __int64) BYTES_PER_GB * 1000000) swprintf(text, L"%I64d %s ", bytesDone / BYTES_PER_GB, GetString ("GB")); else if (bytesDone < (unsigned __int64) BYTES_PER_TB * 1000000) swprintf(text, L"%I64d %s ", bytesDone / BYTES_PER_TB, GetString ("TB")); else swprintf(text, L"%I64d %s ", bytesDone / BYTES_PER_PB, GetString ("PB")); } SetWindowTextW (GetDlgItem (hCurPage, IDC_BYTESWRITTEN), text); if (!bShowStatus) { GetSpeedString (bRWThroughput ? bytesPerSec*2 : bytesPerSec, speed); wcscat (speed, L" "); SetWindowTextW (GetDlgItem (hCurPage, IDC_WRITESPEED), speed); } if (byteOffset < TotalSize) { int64 sec = (int64) ((bProgressBarReverse ? byteOffset : (TotalSize - byteOffset)) / (bytesPerSec == 0 ? 0.001 : bytesPerSec)); if (bytesPerSec == 0 || sec > 60 * 60 * 24 * 999) swprintf (text, L"%s ", GetString ("NOT_APPLICABLE_OR_NOT_AVAILABLE")); else if (sec >= 60 * 60 * 24 * 2) swprintf (text, L"%I64d %s ", sec / (60 * 24 * 60), days); else if (sec >= 120 * 60) swprintf (text, L"%I64d %s ", sec / (60 * 60), hours); else if (sec >= 120) swprintf (text, L"%I64d %s ", sec / 60, minutes); else swprintf (text, L"%I64d %s ", sec, seconds); SetWindowTextW (GetDlgItem (hCurPage, IDC_TIMEREMAIN), text); } prevTime = time; SendMessage (hProgressBar, PBM_SETPOS, (int) (10000.0 * (bProgressBarReverse ? (TotalSize - byteOffset) : byteOffset) / (TotalSize == 0 ? 1 : TotalSize)), 0); return bVolTransformThreadCancel; }
//------------------------------------------------------------------------------ static void display_matches(char** matches, int match_count, int longest) { int i; char** new_matches; CONSOLE_SCREEN_BUFFER_INFO csbi; WORD text_attrib; HANDLE std_out_handle; wchar_t buffer[512]; int show_matches = 2; int match_colour; // Process matches and recalculate the longest match length. new_matches = match_display_filter(matches, match_count); longest = 0; for (i = 0; i < (match_count + 1); ++i) { int len = (int)strlen(new_matches[i]); longest = (len > longest) ? len : longest; } std_out_handle = GetStdHandle(STD_OUTPUT_HANDLE); GetConsoleScreenBufferInfo(std_out_handle, &csbi); // Get the console's current colour settings match_colour = get_clink_setting_int("match_colour"); if (match_colour == -1) { // Pick a suitable foreground colour, check fg isn't the same as bg, and set. text_attrib = csbi.wAttributes; text_attrib ^= 0x08; if ((text_attrib & 0xf0) == (text_attrib & 0x0f)) { text_attrib ^= FOREGROUND_INTENSITY; } } else { text_attrib = csbi.wAttributes & 0xf0; text_attrib |= (match_colour & 0x0f); } SetConsoleTextAttribute(std_out_handle, text_attrib); // If there's lots of matches, check with the user before displaying them // This matches readline's behaviour, which will get skipped (annoyingly) if ((rl_completion_query_items > 0) && (match_count >= rl_completion_query_items)) { DWORD written; _snwprintf( buffer, sizeof_array(buffer), L"\nDisplay all %d possibilities? (y or n)", match_count ); WriteConsoleW(std_out_handle, buffer, wcslen(buffer), &written, NULL); while (show_matches > 1) { int c = rl_read_key(); switch (c) { case 'y': case 'Y': case ' ': show_matches = 1; break; case 'n': case 'N': case 0x03: // handling Ctrl+C case 0x7f: show_matches = 0; break; } } } // Get readline to display the matches. if (show_matches > 0) { // Turn of '/' suffix for directories. RL assumes '/', which isn't the // case, plus clink uses colours instead. int j = _rl_complete_mark_directories; _rl_complete_mark_directories = 0; rl_display_match_list(new_matches, match_count, longest); _rl_complete_mark_directories = j; } else { rl_crlf(); } // Reset console colour back to normal. SetConsoleTextAttribute(std_out_handle, csbi.wAttributes); rl_forced_update_display(); rl_display_fixed = 1; // Tidy up. for (i = 0; i < match_count; ++i) { free(new_matches[i]); } free(new_matches); }
LPWSTR FormatError(DWORD dwError, LPWSTR wszBuffer, LPDWORD lpBufferSize) { INT iValue; DWORD dwReturn; switch (dwError) { case ERROR_DEV_NOT_EXIST: case ERROR_PATH_NOT_FOUND: case ERROR_FILE_NOT_FOUND: case ERROR_INVALID_DRIVE: case IO_NO_ACCESS_PRIVATE: WERROR(wszBuffer, dwReturn, L"No such file or directory"); break; case IO_VIRTUAL_DIR: WERROR(wszBuffer, dwReturn, L"Modifying virtual directories is not allowed"); break; case ERROR_DIRECTORY: WERROR(wszBuffer, dwReturn, L"Not a directory"); break; case ERROR_NOT_EMPTY: WERROR(wszBuffer, dwReturn, L"Directory not empty"); break; case ERROR_WRITE_PROTECT: WERROR(wszBuffer, dwReturn, L"Permission denied"); break; case ERROR_ALREADY_EXISTS: WERROR(wszBuffer, dwReturn, L"Directory/File already exists"); break; case ERROR_HANDLE_DISK_FULL: WERROR(wszBuffer, dwReturn, L"Device full, contact system administrator"); break; case ERROR_INVALID_NAME: WERROR(wszBuffer, dwReturn, L"Invalid filename"); break; case IO_APPEND_SCRIPT: case IO_STORE_SCRIPT: case IO_NEWDIR_SCRIPT: WERROR(wszBuffer, dwReturn, L"Action blocked by external script"); break; case WSAEWOULDBLOCK: case WSAEINPROGRESS: case WSAETIMEDOUT: WERROR(wszBuffer, dwReturn, L"Connection timed out"); break; case WSAENOTSOCK: WERROR(wszBuffer, dwReturn, L"Data socket not connected"); break; case IO_NO_ACCESS: WERROR(wszBuffer, dwReturn, L"Permission denied"); break; case IO_NO_ACCESS_VFS: WERROR(wszBuffer, dwReturn, L"Permission denied (directory mode)"); break; case IO_NO_ACCESS_INI: WERROR(wszBuffer, dwReturn, L"Permission denied (config file)"); break; case IO_INVALID_FILENAME: WERROR(wszBuffer, dwReturn, L"Invalid filename"); break; case IO_NO_ACCESS_FXP_IN: WERROR(wszBuffer, dwReturn, L"FXP to path is not allowed"); break; case IO_NO_ACCESS_FXP_OUT: WERROR(wszBuffer, dwReturn, L"FXP from path is not allowed"); break; case IO_BAD_FXP_ADDR: WERROR(wszBuffer, dwReturn, L"Transfer to specified network address is not allowed"); break; case IO_NO_CREDITS: WERROR(wszBuffer, dwReturn, L"Insufficient credits left to perform requested action"); break; case IO_SSL_FAIL: WERROR(wszBuffer, dwReturn, L"SSL library returned a failure code"); break; case IO_SSL_FAIL2: WERROR(wszBuffer, dwReturn, L"SSL failure"); break; case IO_MAX_DOWNLOADS: WERROR(wszBuffer, dwReturn, L"Maximum concurrent downloads for account reached"); break; case IO_MAX_UPLOADS: WERROR(wszBuffer, dwReturn, L"Maximum concurrent uploads for account reached"); break; case IO_ENCRYPTION_REQUIRED: WERROR(wszBuffer, dwReturn, L"Your user class requires you to use secure connections"); break; case IO_TRANSFER_ABORTED: WERROR(wszBuffer, dwReturn, L"Transfer aborted"); break; case IO_INVALID_ARGUMENTS: WERROR(wszBuffer, dwReturn, L"Invalid arguments"); break; case IO_GADMIN_EMPTY: WERROR(wszBuffer, dwReturn, L"No group admin rights found"); break; case IO_NOT_GADMIN: WERROR(wszBuffer, dwReturn, L"User is not in your admin groups"); break; case IO_NO_SLOTS: WERROR(wszBuffer, dwReturn, L"Group's limit has been reached"); break; case ERROR_GROUP_NOT_EMPTY: WERROR(wszBuffer, dwReturn, L"Group is not empty"); break; case ERROR_NO_MATCH: WERROR(wszBuffer, dwReturn, L"No results for search term"); break; case ERROR_GROUPNAME: WERROR(wszBuffer, dwReturn, L"Invalid name for group"); break; case ERROR_USERNAME: WERROR(wszBuffer, dwReturn, L"Invalid name for user"); break; case ERROR_MODULE_CONFLICT: WERROR(wszBuffer, dwReturn, L"Module ownership conflict"); break; case ERROR_SERVICE_NAME_NOT_FOUND: WERROR(wszBuffer, dwReturn, L"Service name does not exist"); break; case ERROR_DEVICE_NAME_NOT_FOUND: WERROR(wszBuffer, dwReturn, L"Device name does not exist"); break; case ERROR_MODULE_NOT_FOUND: WERROR(wszBuffer, dwReturn, L"Required module is not loaded"); break; case ERROR_USER_NOT_FOUND: WERROR(wszBuffer, dwReturn, L"User does not exist"); break; case ERROR_GROUP_NOT_FOUND: WERROR(wszBuffer, dwReturn, L"Group does not exist"); break; case ERROR_GROUP_EXISTS: WERROR(wszBuffer, dwReturn, L"Group already exists"); break; case ERROR_USER_EXISTS: WERROR(wszBuffer, dwReturn, L"User already exists"); break; case ERROR_USER_LOCK_FAILED: WERROR(wszBuffer, dwReturn, L"User locking failed"); break; case ERROR_GROUP_LOCK_FAILED: WERROR(wszBuffer, dwReturn, L"Group locking failed"); break; case ERROR_LOCK_FAILED: WERROR(wszBuffer, dwReturn, L"File locking failed"); break; case ERROR_INVALID_ARGUMENTS: WERROR(wszBuffer, dwReturn, L"Syntax error in parameters or arguments"); break; case ERROR_MISSING_ARGUMENT: WERROR(wszBuffer, dwReturn, L"Not enough parameters"); break; case ERROR_NO_ACTIVE_DEVICE: WERROR(wszBuffer, dwReturn, L"Service has no active devices"); break; case ERROR_USER_NOT_ONLINE: WERROR(wszBuffer, dwReturn, L"User is not online"); break; case ERROR_PASSWORD: WERROR(wszBuffer, dwReturn, L"Invalid password"); break; case ERROR_SERVICE_LOGINS: WERROR(wszBuffer, dwReturn, L"Service is full, try again later"); break; case ERROR_CLASS_LOGINS: WERROR(wszBuffer, dwReturn, L"Maximum concurrent connections for ip-class reached, try again later"); break; case ERROR_IP_LOGINS: WERROR(wszBuffer, dwReturn, L"Maximum concurrent connections for single host reached"); break; case ERROR_USER_IP_LOGINS: WERROR(wszBuffer, dwReturn, L"Maximum concurrent connections for account from a single host reached"); break; case ERROR_USER_LOGINS: WERROR(wszBuffer, dwReturn, L"Maximum concurrent connections for account reached, try again later"); break; case ERROR_MASTER: WERROR(wszBuffer, dwReturn, L"Cannot target Master account"); break; case ERROR_SITEOP: WERROR(wszBuffer, dwReturn, L"Cannot target Master or SiteOp account"); break; case ERROR_FILESEEK: WERROR(wszBuffer, dwReturn, L"Seek offset exceeds end of file"); break; case ERROR_INVALID_FILEMODE: WERROR(wszBuffer, dwReturn, L"Invalid filemode"); break; case ERROR_USER_EXPIRED: WERROR(wszBuffer, dwReturn, L"Account has expired"); break; case ERROR_USER_BANNED: WERROR(wszBuffer, dwReturn, L"Account has been temporarily banned"); break; case ERROR_USER_DELETED: WERROR(wszBuffer, dwReturn, L"Account has been deleted"); break; case ERROR_USER_NOT_DELETED: WERROR(wszBuffer, dwReturn, L"User not marked for deletion or account hasn't expired"); break; case ERROR_HOME_DIR: WERROR(wszBuffer, dwReturn, L"Error with home directory"); break; case ERROR_VFS_FILE: WERROR(wszBuffer, dwReturn, L"Error with VFS file"); break; case ERROR_ALREADY_CLOSED: WERROR(wszBuffer, dwReturn, L"Server already closed"); break; case ERROR_ALREADY_OPEN: WERROR(wszBuffer, dwReturn, L"Server already open"); break; case ERROR_SERVER_CLOSED: case ERROR_SERVER_SINGLE: WERROR(wszBuffer, dwReturn, L"Server is closed"); break; case ERROR_SHUTTING_DOWN: WERROR(wszBuffer, dwReturn, L"Server is shutting down"); break; case ERROR_STARTING_UP: WERROR(wszBuffer, dwReturn, L"Server is starting up"); break; case ERROR_COMMAND_FAILED: WERROR(wszBuffer, dwReturn, L"Command failed"); break; case ERROR_CLIENT_HOST: WERROR(wszBuffer, dwReturn, L"Your IP/hostname is not authorized"); break; case ERROR_IDENT_FAILURE: WERROR(wszBuffer, dwReturn, L"Your user ident response did not match"); break; case ERROR_BAD_THEME: WERROR(wszBuffer, dwReturn, L"Invalid/Missing theme"); break; case ERROR_NOT_MODIFIED: WERROR(wszBuffer, dwReturn, L"Not modified"); break; case ERROR_DIRECTORY_LOCKED: WERROR(wszBuffer, dwReturn, L"Directory being moved or deleted"); break; case IO_SCRIPT_FAILURE: WERROR(wszBuffer, dwReturn, L"Fatal script error"); break; case ERROR_FILE_MISSING: WERROR(wszBuffer, dwReturn, L"File missing"); break; case ERROR_NO_HELP: WERROR(wszBuffer, dwReturn, L"No help found"); break; case ERROR_NOGROUP: WERROR(wszBuffer, dwReturn, L"Cannot delete default group (GID #1)"); break; case ERROR_SCRIPT_MISSING: WERROR(wszBuffer, dwReturn, L"Cannot find script"); break; case ERROR_CLOSED_SOCKET: WERROR(wszBuffer, dwReturn, L"Failed send/recv on already closed socket"); break; case ERROR_MATCH_LIST: WERROR(wszBuffer, dwReturn, L"No previously saved user matches"); break; case ERROR_TCL_VERSION: WERROR(wszBuffer, dwReturn, L"Error with TCL, .dll or /lib version mismatch"); break; case ERROR_TRANSFER_TIMEOUT: WERROR(wszBuffer, dwReturn, L"Data transfer timeout"); break; case ERROR_INVALID_FS_TARGET: WERROR(wszBuffer, dwReturn, L"Invalid filesystem target"); break; default: // Default error handler dwReturn = FormatMessageW(FORMAT_MESSAGE_IGNORE_INSERTS|FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwError, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), wszBuffer, lpBufferSize[0]-1, NULL); // Check result if (dwReturn) { // Remove carriage feed if (wszBuffer[dwReturn - 1] == L'\n') dwReturn--; if (wszBuffer[dwReturn - 1] == L'\r') dwReturn--; if (wszBuffer[dwReturn - 1] == L'.') dwReturn--; // Add zero padding wszBuffer[dwReturn] = L'\0'; break; } // ok, no english for the above error, try local language but append (#) to end... dwReturn = FormatMessageW(FORMAT_MESSAGE_IGNORE_INSERTS|FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwError, 0, wszBuffer, lpBufferSize[0]-1, NULL); if (dwReturn) { // Remove carriage feed if (wszBuffer[dwReturn - 1] == L'\n') dwReturn--; if (wszBuffer[dwReturn - 1] == L'\r') dwReturn--; if (wszBuffer[dwReturn - 1] == L'.') dwReturn--; // Add zero padding wszBuffer[dwReturn] = L'\0'; iValue = _snwprintf(&wszBuffer[dwReturn], lpBufferSize[0]-dwReturn-1, L" (#%u)", dwError); if (iValue > 0) { dwReturn += iValue; } wszBuffer[dwReturn] = L'\0'; break; } dwReturn = 0; iValue = _snwprintf(wszBuffer, lpBufferSize[0], L"Unknown error (%u)", dwError); if (iValue > 0) { dwReturn = iValue; } wszBuffer[dwReturn] = L'\0'; } lpBufferSize[0] = dwReturn; return wszBuffer; }