void RemoveUser( IRState* pThis, int pUser, BOOL pExpired ) { int lGame; int lPlayer; int lNbLeft; pThis->mUser[pUser].mExpiration = 0; pThis->mUser[pUser].mTimeStamp = pThis->mTimeStamp; /* Log this user entry */ if( InitLogFile() ) { fprintf( gLogFile, "%s %d %c %d %d %d ^%s^(%d-%d) %s %s\n", GetTime( pThis->mUser[pUser].mLogingTime ), time( NULL )-pThis->mUser[pUser].mLogingTime, pExpired? 'o':'t', pThis->mUser[pUser].mGameCode, pThis->mUser[pUser].mNbRefresh, pThis->mUser[pUser].mNbChat, pThis->mUser[pUser].mName, pThis->mUser[pUser].mKeyID.mMajor, pThis->mUser[pUser].mKeyID.mMinor, pThis->mUser[pUser].mIP, pThis->mUser[pUser].mDomain ); } /* Verify the games that the user take parts to */ for( lGame = 0; lGame < IR_MAX_GAME; lGame++ ) { if( pThis->mGame[ lGame ].mUsed ) { if( pThis->mGame[ lGame ].mPlayers[0] == pUser ) { pThis->mGame[ lGame ].mUsed = FALSE; pThis->mGame[ lGame ].mTimeStamp = pThis->mTimeStamp; } else { for( lPlayer = 1; lPlayer < pThis->mGame[ lGame ].mNbPlayer; lPlayer++ ) { if( pThis->mGame[ lGame ].mPlayers[lPlayer] == pUser ) { pThis->mGame[ lGame ].mNbPlayer--; pThis->mGame[ lGame ].mTimeStamp = pThis->mTimeStamp; lNbLeft = lPlayer-pThis->mGame[ lGame ].mNbPlayer; if( lNbLeft > 0 ) { memmove( &( pThis->mGame[ lGame ].mPlayers[lPlayer]), &(pThis->mGame[ lGame ].mPlayers[lPlayer+1]), sizeof( (pThis->mGame[ lGame ].mPlayers[lPlayer]) )*lNbLeft ); } } } } } } pThis->mTimeStamp++; }
LogMessage::~LogMessage() { if (severity_ == LogSeverity::LOG_FATAL) { stream_ << "\n"; StackWalker walker; walker.DumpCallStack(stream_); } stream_ << std::endl; std::string msg = stream_.str(); if (g_logging_dest & LoggingDestination::LOG_TO_SYSTEM_DEBUG_LOG) { OutputDebugStringA(msg.c_str()); // Also writes to standard error stream. fwrite(msg.data(), sizeof(char), msg.length(), stderr); fflush(stderr); } else if (severity_ >= kAlwaysPrintErrorMinLevel) { fwrite(msg.data(), sizeof(char), msg.length(), stderr); fflush(stderr); } // If `InitLogFile` wasn't called at the start of the program, do it on the spot. // However, if we unfortunately failed to initialize the log file, just skip the writting. // Note that, if more than one thread in here try to call `InitLogFile`, there will be a // race condition. This is why you should call `ConfigureLoggingSettings` at start. if ((g_logging_dest & LoggingDestination::LOG_TO_FILE) && InitLogFile()) { DWORD bytes_written = 0; WriteFile(g_log_file, msg.data(), static_cast<DWORD>(msg.length() * sizeof(char)), &bytes_written, nullptr); } }
void LogText(std::string text) { InitLogFile(); int currentTime = clock() - g_startTime; g_file << currentTime << '\t' << text.c_str() << std::endl; }
CRecordManServerMonitor::CRecordManServerMonitor(void) { bzero(m_chLogpath, sizeof(m_chLogpath)); sprintf(m_chLogpath, "%s", MANAGER_BOARD_DEFAULT_ROOT_LOG); m_nLogLevel = CLogFile::trace; m_nLogDays = MONITOR_LOG_SAVE_DEFAULT_DAYS; InitLogFile(); }
void CLogging::LogMessage(wxString SourceFile, int nSourceLine, void *pInstance, MessageType nMessageType, const wxChar *msgFormat, ...) const { InitLogFile(); const int debugLevel = m_pEngine->GetOptions()->GetOptionVal(OPTION_LOGGING_DEBUGLEVEL); switch (nMessageType) { case Debug_Warning: if (!debugLevel) return; break; case Debug_Info: if (debugLevel < 2) return; break; case Debug_Verbose: if (debugLevel < 3) return; break; case Debug_Debug: if (debugLevel != 4) return; break; default: break; } int pos = SourceFile.Find('\\', true); if (pos != -1) SourceFile = SourceFile.Mid(pos+1); pos = SourceFile.Find('/', true); if (pos != -1) SourceFile = SourceFile.Mid(pos+1); va_list ap; va_start(ap, msgFormat); wxString text = wxString::FormatV(msgFormat, ap); va_end(ap); wxString msg = wxString::Format(_T("%s(%d): %s caller=%p"), SourceFile.c_str(), nSourceLine, text.c_str(), this); LogToFile(nMessageType, msg); CLogmsgNotification *notification = new CLogmsgNotification; notification->msgType = nMessageType; notification->msg = msg; m_pEngine->AddNotification(notification); }
void CProProcess::InitProProcess(CString sProcess) { InitLogFile(); g_Log.WriteLine(_T("\nInitProProcess")); m_bIsProtect = false; m_hEvent = NULL; m_hMemMap = NULL; m_pMemPointer = NULL; m_thTimeThread = NULL; m_sProcess = sProcess; if (!m_hEvent) { TCHAR pAppEventName[256]={0}; lstrcpy(pAppEventName,FASTRUN_APP_EVENT_NAME); lstrcat(pAppEventName,sProcess); m_hEvent = ::CreateEvent (NULL,FALSE,FALSE,pAppEventName); } if (!m_hMemMap) { TCHAR pAppNotifyName[256]={0}; lstrcpy(pAppNotifyName,FASTRUN_NOTIFY_EVENT_NAME); lstrcat(pAppNotifyName,sProcess); m_hMemMap = ::CreateFileMapping (INVALID_HANDLE_VALUE,NULL, PAGE_READWRITE,0,sizeof(int),pAppNotifyName); } m_pMemPointer = ::MapViewOfFile (m_hMemMap,FILE_MAP_WRITE,0,0,0); *((int*)m_pMemPointer) = 0; MyRegister(TRUE); InitModulePath(); if (!m_thTimeThread) { m_thTimeThread= ::AfxBeginThread (TimeCheckingThreadFunc, NULL, THREAD_PRIORITY_BELOW_NORMAL); } //默认不是保护 就必须通过配置文件记录保护属性 //得到配置文件的属性 if (GetProfileSetting()) StartProtect(); else StopProtect(); }
void ConfigureLoggingSettings(const LoggingSettings& settings) { g_min_severity_level = settings.min_severity_level; g_log_item_options = settings.log_item_options; g_logging_dest = settings.logging_destination; g_old_file_option = settings.old_file_disposal_option; if (!(g_logging_dest & LoggingDestination::LOG_TO_FILE)) { return; } if (!settings.log_file_path.empty()) { g_log_file_path = settings.log_file_path; } auto rv = InitLogFile(); ENSURE(CHECK, rv)(LastError()).Require(); }
void CLogging::LogMessage(MessageType nMessageType, const wxChar *msgFormat, ...) const { InitLogFile(); const int debugLevel = m_pEngine->GetOptions()->GetOptionVal(OPTION_LOGGING_DEBUGLEVEL); switch (nMessageType) { case Debug_Warning: if (!debugLevel) return; break; case Debug_Info: if (debugLevel < 2) return; break; case Debug_Verbose: if (debugLevel < 3) return; break; case Debug_Debug: if (debugLevel != 4) return; break; case RawList: if (!m_pEngine->GetOptions()->GetOptionVal(OPTION_LOGGING_RAWLISTING)) return; break; default: break; } va_list ap; va_start(ap, msgFormat); wxString text = wxString::FormatV(msgFormat, ap); va_end(ap); LogToFile(nMessageType, text); CLogmsgNotification *notification = new CLogmsgNotification; notification->msgType = nMessageType; notification->msg = text; m_pEngine->AddNotification(notification); }
void CLogging::LogMessageRaw(MessageType nMessageType, const wxChar *msg) const { InitLogFile(); const int debugLevel = m_pEngine->GetOptions()->GetOptionVal(OPTION_LOGGING_DEBUGLEVEL); switch (nMessageType) { case Debug_Warning: if (!debugLevel) return; break; case Debug_Info: if (debugLevel < 2) return; break; case Debug_Verbose: if (debugLevel < 3) return; break; case Debug_Debug: if (debugLevel != 4) return; break; case RawList: if (!m_pEngine->GetOptions()->GetOptionVal(OPTION_LOGGING_RAWLISTING)) return; break; default: break; } LogToFile(nMessageType, msg); CLogmsgNotification *notification = new CLogmsgNotification; notification->msgType = nMessageType; notification->msg = msg; m_pEngine->AddNotification(notification); }
void CLogging::LogToFile(MessageType nMessageType, const wxString& msg) const { fz::scoped_lock l(mutex_); if (!m_logfile_initialized) { if (!InitLogFile(l)) { return; } } #ifdef __WXMSW__ if (m_log_fd == INVALID_HANDLE_VALUE) return; #else if (m_log_fd == -1) return; #endif fz::datetime now = fz::datetime::now(); wxString out(wxString::Format(_T("%s %u %d %s %s") #ifdef __WXMSW__ _T("\r\n"), #else _T("\n"), #endif now.format(_T("%Y-%m-%d %H:%M:%S"), fz::datetime::local), m_pid, engine_.GetEngineId(), m_prefixes[static_cast<int>(nMessageType)], msg)); const wxWX2MBbuf utf8 = out.mb_str(wxConvUTF8); if (utf8) { #ifdef __WXMSW__ if (m_max_size) { LARGE_INTEGER size; if (!GetFileSizeEx(m_log_fd, &size) || size.QuadPart > m_max_size) { CloseHandle(m_log_fd); m_log_fd = INVALID_HANDLE_VALUE; // m_log_fd might no longer be the original file. // Recheck on a new handle. Proteced with a mutex against other processes HANDLE hMutex = ::CreateMutex(0, true, _T("FileZilla 3 Logrotate Mutex")); if (!hMutex) { wxString error = wxSysErrorMsg(); l.unlock(); LogMessage(MessageType::Error, _("Could not create logging mutex: %s"), error); return; } HANDLE hFile = CreateFile(m_file.wc_str(), FILE_APPEND_DATA, FILE_SHARE_DELETE | FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); if (hFile == INVALID_HANDLE_VALUE) { wxString error = wxSysErrorMsg(); // Oh dear.. ReleaseMutex(hMutex); CloseHandle(hMutex); l.unlock(); // Avoid recursion LogMessage(MessageType::Error, _("Could not open log file: %s"), error); return; } wxString error; if (GetFileSizeEx(hFile, &size) && size.QuadPart > m_max_size) { CloseHandle(hFile); // MoveFileEx can fail if trying to access a deleted file for which another process still has // a handle. Move it far away first. // Todo: Handle the case in which logdir and tmpdir are on different volumes. // (Why is everthing so needlessly complex on MSW?) wxString tmp = wxFileName::CreateTempFileName(_T("fz3")); MoveFileEx((m_file + _T(".1")).wc_str(), tmp.wc_str(), MOVEFILE_REPLACE_EXISTING); DeleteFile(tmp.wc_str()); MoveFileEx(m_file.wc_str(), (m_file + _T(".1")).wc_str(), MOVEFILE_REPLACE_EXISTING); m_log_fd = CreateFile(m_file.wc_str(), FILE_APPEND_DATA, FILE_SHARE_DELETE | FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); if (m_log_fd == INVALID_HANDLE_VALUE) { // If this function would return bool, I'd return FILE_NOT_FOUND here. error = wxSysErrorMsg(); } } else m_log_fd = hFile; if (hMutex) { ReleaseMutex(hMutex); CloseHandle(hMutex); } if (!error.empty()) { l.unlock(); // Avoid recursion LogMessage(MessageType::Error, _("Could not open log file: %s"), error); return; } } } DWORD len = (DWORD)strlen((const char*)utf8); DWORD written; BOOL res = WriteFile(m_log_fd, (const char*)utf8, len, &written, 0); if (!res || written != len) { CloseHandle(m_log_fd); m_log_fd = INVALID_HANDLE_VALUE; l.unlock(); // Avoid recursion LogMessage(MessageType::Error, _("Could not write to log file: %s"), wxSysErrorMsg()); } #else if (m_max_size) { struct stat buf; int rc = fstat(m_log_fd, &buf); while (!rc && buf.st_size > m_max_size) { struct flock lock = {}; lock.l_type = F_WRLCK; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 1; int rc; // Retry through signals while ((rc = fcntl(m_log_fd, F_SETLKW, &lock)) == -1 && errno == EINTR); // Ignore any other failures int fd = open(m_file.fn_str(), O_WRONLY | O_APPEND | O_CREAT | O_CLOEXEC, 0644); if (fd == -1) { wxString error = wxSysErrorMsg(); close(m_log_fd); m_log_fd = -1; l.unlock(); // Avoid recursion LogMessage(MessageType::Error, error); return; } struct stat buf2; rc = fstat(fd, &buf2); // Different files if (!rc && buf.st_ino != buf2.st_ino) { close(m_log_fd); // Releases the lock m_log_fd = fd; buf = buf2; continue; } // The file is indeed the log file and we are holding a lock on it. // Rename it rc = rename(m_file.fn_str(), (m_file + _T(".1")).fn_str()); close(m_log_fd); close(fd); // Get the new file m_log_fd = open(m_file.fn_str(), O_WRONLY | O_APPEND | O_CREAT | O_CLOEXEC, 0644); if (m_log_fd == -1) { l.unlock(); // Avoid recursion LogMessage(MessageType::Error, wxSysErrorMsg()); return; } if (!rc) // Rename didn't fail rc = fstat(m_log_fd, &buf); } } size_t len = strlen((const char*)utf8); size_t written = write(m_log_fd, (const char*)utf8, len); if (written != len) { close(m_log_fd); m_log_fd = -1; l.unlock(); // Avoid recursion LogMessage(MessageType::Error, _("Could not write to log file: %s"), wxSysErrorMsg()); } #endif } }
//void deroulement_du_jeu() int main(int argc, char *argv[] ) { // if( !InitGUI() ){ return 0; } if( !CheckCommand(argc,argv) ){ return 0; } if( !InitLogFile() ){ printf("Fail init logFile\n"); } PrintHeaderMatch(); //Il faut nbMaxCps pour chaques joueurs, donc on multiplie par 2 nbMaxCps *= 2; if( !PrintLibInitHeader() ){ printf("Fail print libHeader\n"); } if( !LoadLibraries() ){ return(0); } PrintTLine(); SGameState* gameState = CreateBoard(); //Srand pour obtenir des nombres aléatoires srand(time(NULL)); //Initialisation des joueurs j1InitLibrary(j1Name); j2InitLibrary(j2Name); if( strlen(pathIA1) && !strlen(pathIA2) ){ PrintPhysicalPlayers(NULL,j2Name); } else if( !strlen(pathIA1) && strlen(pathIA2) ){ PrintPhysicalPlayers(j1Name,NULL); } else if( !strlen(pathIA1) && !strlen(pathIA2) ){ PrintPhysicalPlayers(j1Name,j2Name); } else { PrintPhysicalPlayers(NULL,NULL); } PrintIAPlayers(pathIA1,pathIA2); PrintMaxCps(nbMaxCps/2); j1StartMatch(); j2StartMatch(); int nbMatch = 3; int j1Win = 0; int j2Win = 0; while( nbMatch>0 && j1Win<2 && j2Win<2){ PrintMatch(4-nbMatch); // InitBoard //On initialise le nombre de coups maximums int cptCps = nbMaxCps; j1NbPenalty = 0; j2NbPenalty = 0; InitGameState(gameState); EPiece j1BoardInit[4][10]; EPiece j2BoardInit[4][10]; SetPlayerColors(); j1StartGame(j1Color,j1BoardInit); j2StartGame(j2Color,j2BoardInit); if( j1Color == ECblue ){ PrintColors(j2Name, j1Name); } else{ PrintColors(j1Name, j2Name); } //Initialisation des pions sur le plateau if( j1Color == ECblue ){ if( !InitBlueBoard(gameState,j1BoardInit) ){PrintBoardInitError(ECblue);return 0;} if( !InitRedBoard(gameState,j2BoardInit) ){PrintBoardInitError(ECred);return 0;} } else{ if( !InitRedBoard(gameState,j1BoardInit) ){PrintBoardInitError(ECred);return 0;} if( !InitBlueBoard(gameState,j2BoardInit) ){PrintBoardInitError(ECblue);return 0;} } //Le premier joueur est le rouge EColor player = ECred; EColor winner = 0; PrintLine(); PrintGameState(gameState); while( !winner && cptCps>0 ){ SMove move; //Duplication du plateau SGameState *gameStateCpy = (SGameState*) malloc(sizeof(SGameState)); GameStateCpy(gameState,gameStateCpy); //Si c'est le tour du joueur rouge, on inverse son plateau if( player == ECred ){ RevertGame(gameStateCpy); } //On cache les pions du joueur ennemi HideColor(gameStateCpy,abs((player+1)%2)+2); if( player == j1Color ){ move = j1NextMove(gameStateCpy); } else{ move = j2NextMove(gameStateCpy); } if( player == ECred ){ move.start.line = 9-move.start.line; move.end.line = 9-move.end.line; } int moveType = CorrectMove(gameState,move,player); PrintMove(player,move); //Mouvement incorrecte if( moveType == 0 ){ if( player == j1Color ){ j1NbPenalty++; j1Penalty(); PrintInvalidMove(player,j1NbPenalty); if( j1NbPenalty == 3 ){ PrintPenalty(j1Name,j1Color); winner = abs((j1Color+1)%2)+2; break; } } else{ j2NbPenalty++; j2Penalty(); PrintInvalidMove(player,j2NbPenalty); if( j2NbPenalty == 3 ){ PrintPenalty(j2Name,j2Color); winner = abs((j2Color+1)%2)+2; break; } } } else{ //Attaque if( moveType == 1 ){ EPiece army = gameState->board[move.start.line][move.start.col].piece; EPiece enemy = gameState->board[move.end.line][move.end.col].piece; if( player == j1Color ){ j1AttackResult(move.start,army,move.end,enemy); j2AttackResult(move.end,enemy,move.start,army); } else{ j1AttackResult(move.end,enemy,move.start,army); j2AttackResult(move.start,army,move.end,enemy); } PrintAttackResult(player,move.start,army,move.end,enemy); } ExecuteMove(gameState,move,player); } PrintGameState(gameState); free(gameStateCpy); if( player == ECred ){ player = ECblue; } else{ player = ECred; } winner = Finished(gameState); cptCps--; } if( cptCps == 0){ PrintMaxMoveReached(); } else{ if( j1Color == winner ){ PrintMatchWinner(j1Name, winner, 4-nbMatch);j1Win++; } else{ PrintMatchWinner(j2Name, winner, 4-nbMatch);j2Win++; } } nbMatch--; j1EndGame(); j2EndGame(); printf("j1Win : %d\nj2Win : %d\n",j1Win,j2Win); } if( j1Win >= 2 ){ PrintGameWinner(j1Name, j1Color); } else{ PrintGameWinner(j2Name, j2Color); } j1EndMatch(); j2EndMatch(); free(gameState); return(0); }
// Application init function (override) bool CQ2RTApplication::AppInit(void) { if(QFileSystemInit() != Q_NO_ERROR) QMonitor.WarningMessage("Can not initialize file system"); #ifdef OS_VXWORKS else { // Set starting work directory if(QChangeDirectory(APPLICATION_FILE_PATH) != Q_NO_ERROR) QMonitor.WarningMessage("Can not change directory to application directory"); } AppFilePath.Value() = APPLICATION_FILE_PATH; #endif // Set high priority for this process (windows only) #ifdef OS_WINDOWS SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS); #endif // Init application parameters manager if(! CAppParams::Init(AppFilePath.Value() + LOAD_STRING(IDS_CONFIGS_DIRNAME))) return false; // Initialize the global error handler CErrorHandler::Init(); // Initialize the log file InitLogFile(); // Create a mini-sequencer object m_MiniSequencer = new CMiniSequencer("AppMiniSequencer"); // Initilize the modes manager CModesManager::Init(CAppParams::Instance(), AppFilePath.Value(), m_MiniSequencer); CAppParams::Instance()->EnableDisableSaveEvents(true); InitFrontEnd(); CModesManager::Instance()->EnterMode(DEFAULT_MODE, DEFAULT_MODES_DIR); CModesManager::Instance()->EnterMode(OPERATION_MODE_NAME(CAppParams::Instance()->PipesOperationMode), GENERAL_MODES_DIR); // Initilize the maintenance counters system CMaintenanceCounters::Init(NUM_OF_MAINTENANCE_COUNTERS, AppFilePath.Value() + LOAD_STRING(IDS_CONFIGS_DIRNAME) + "Maintenance.dat"); SetMaintenanceCountersDefaultWarnings(); CMaintenanceCounters::GetInstance()->LoadFromFile(); SetMachineSinceDateParam(); //OBJET_MACHINE ApplyParametersChange(); // Initialize the data card if(CHECK_NOT_EMULATION(CAppParams::Instance()->DataCard_Emulation)) { DWORD dwStatus = EdenPCISystem_Init(); if(dwStatus != WD_STATUS_SUCCESS) { m_IsPciCardInitialized = false; CQLog::Write(LOG_TAG_PRINT, QFormatStr("Data PCI card problem, dwStatus: %s", Stat2Str(dwStatus))); QMonitor.WarningMessage(QFormatStr("Data PCI card problem: %s", Stat2Str(dwStatus))); } else { m_IsPciCardInitialized = true; SetFIFOUnderrunErrorCallback(FIFOUnderrunErrorCallback, NULL); } } // Initialize communication related components InitCommComponents(); m_LayerProcess = new CLayerProcess; m_HostComm = new CHostComm; // Create a mini-sequencer object // Create other system objects m_MachineManager = new CMachineManager; m_Tester = new CTester; // Initialize BIT system m_BITManager = new CBITManager; AppBIT::Init(); RefreshBIT(); #ifdef OBJET_MACHINE CActionsHistoryTable::GetInstance()->Init(); #endif // Protect "Show incoming slices" menu // ------------------------------------------------------------------------ Chasp hasp(ChaspFeature::fromFeature(INT_FROM_RESOURCE(IDN_HASP_INCOMING_SLICES_PROTECTION_FEATURE))); try { haspStatus status = hasp.login(HASP_OBJET_VENDOR_CODE, HASP_LOCAL_SCOPE); bool show = false; if(HASP_SUCCEEDED(status)) { show = true; } else { show = false; } m_MachineManager->GetMachineSequencer()->HandleIncomingSlicesProtection(show); } __finally { hasp.logout(); } // ------------------------------------------------------------------------ // Enable m_SolubleSupportAllowed flag // ------------------------------------------------------------------------ TLicensedMaterialsList MaterialsList = CBackEndInterface::Instance()->GetLicensedMaterialsList(); for(TLicensedMaterialsList::iterator it = MaterialsList.begin() ; it != MaterialsList.end() ; it++) { if( it->MaterialName == "SUP707" || it->MaterialName == "SUP706" ) { SetSupportReplacementAllowed(true); break; } } // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // Enable m_QATestsAllowed flag // ------------------------------------------------------------------------ Chasp hasp1(ChaspFeature::fromFeature(INT_FROM_RESOURCE(IDN_HASP_QA_TESTS_ALLOWED_FEATURE))); try { haspStatus status = hasp1.login(HASP_OBJET_VENDOR_CODE, HASP_LOCAL_SCOPE); bool enable = false; if(HASP_SUCCEEDED(status)) { enable = true; } else { enable = false; } SetQATestsAllowed(enable); } __finally { hasp1.logout(); } // ------------------------------------------------------------------------ #ifndef EMULATION_ONLY //HASP feature number is generated from application version, for example Connex500 ver 57.1 - HASP feature: 571 ChaspFeature feature = ChaspFeature::fromFeature(GetHaspFeatureNum()); CHaspInterfaceWrapper::Init(feature, LOG_TAG_HASP, m_MachineManager->GetMachineSequencer()->HandleHaspStatus); #else CHaspInterfaceWrapper::Init(); #endif LogThreadsProperties(); try { m_timeoutTimer = new TTimer(NULL); //bug 5950 } catch(std::bad_alloc& ba) { m_timeoutTimer = NULL; CQLog::Write(LOG_TAG_GENERAL, "m_timeoutTimer - Memory allocation failed: %s", ba.what()); } QMonitor.SetServiceCallsCheckingMsgSafety( CFrontEndInterface::IsWizardRunning, CFrontEndInterface::CancelWizard); return true; }
void AddUser( IRState* pThis, const char* pUserName, int pVersion, int pMajorID, int pMinorID, unsigned int pKey2, unsigned int pKey3 ) { BOOL lBanned; BOOL lExpired; BOOL lDoubleLog; BOOL lNotReg; int lIPIndex; int lCounter; int lCounter2; /* First verify the version */ if( (pVersion<IR_VERSION_MIN)||(pVersion>IR_VERSION_MAX)) { printf( "ERROR 103\n" ); } else { /* find an empty entry for the new user */ for( lCounter = 0; lCounter < IR_MAX_CLIENT; lCounter++ ) { if( pThis->mUser[ lCounter ].mExpiration == 0 ) { break; } } if( lCounter == IR_MAX_CLIENT ) { printf( "ERROR 102\n" ); } else { lBanned = FALSE; lExpired = FALSE; lDoubleLog = FALSE; lNotReg = FALSE; lIPIndex = 0; if( pMajorID == -1 ) { while( !lBanned && (gBannedISP_IP[ lIPIndex ] != NULL) ) { if( !strncmp( gBannedISP_IP[lIPIndex], chk(getenv( "REMOTE_ADDR" )), strlen(gBannedISP_IP[lIPIndex])) ) { lBanned = TRUE; } lIPIndex++; } } #ifdef _REG_ONLY_ if( pMajorID == -1 ) { lNotReg = TRUE; } #endif /* Verify if the user is not already logued */ if( pMajorID != -1 ) { /* Go thru user list */ for( lCounter2 = 0; lCounter2 < IR_MAX_CLIENT; lCounter2++ ) { if( (pThis->mUser[lCounter2].mTimeStamp != 0)&&(pThis->mUser[ lCounter2 ].mExpiration != 0) ) { if( (pThis->mUser[lCounter2].mKeyID.mMajor == pMajorID) && (pThis->mUser[lCounter2].mKeyID.mMinor == pMinorID) ) { lDoubleLog = TRUE; } } } } #ifdef _EXPIRED_ lExpired = TRUE; #endif if( !lBanned && !lExpired && !lDoubleLog && !lNotReg ) { pThis->mUser[ lCounter ].mTimeStamp = pThis->mTimeStamp; pThis->mUser[ lCounter ].mExpiration = time( NULL )+IR_EXPIRATION_DELAY; pThis->mUser[ lCounter ].mId = pThis->mNextUserId++; pThis->mUser[lCounter].mKeyID.mMajor = pMajorID; pThis->mUser[lCounter].mKeyID.mMinor = pMinorID; StrMaxCopy( pThis->mUser[ lCounter ].mName, pUserName, IR_USER_NAME_LEN ); pThis->mTimeStamp++; /* Fill loging fields */ pThis->mUser[ lCounter ].mLogingTime = time( NULL ); pThis->mUser[ lCounter ].mGameCode = 0; pThis->mUser[ lCounter ].mNbRefresh = 0; pThis->mUser[ lCounter ].mNbChat = 0; StrMaxCopy( pThis->mUser[ lCounter ].mIP, chk(getenv( "REMOTE_ADDR" )), IR_MAX_USER_IP ); StrMaxCopy( pThis->mUser[ lCounter ].mDomain, chk(getenv( "REMOTE_HOST" )) ,IR_MAX_USER_DOM ); printf( "SUCCESS\n", lCounter ); printf( "USER_ID %d-%u\n", lCounter, pThis->mUser[ lCounter ].mId ); PrintState( pThis ); } else { /* We got one */ printf( "SUCCESS\n", lCounter ); printf( "USER_ID %d-%u\n", IR_BANNEDSLOT, 0 ); if( lExpired ) { printf( "CHAT\n--\n" ); printf( "CHAT\nThis version of HoverRace is expired\n" ); printf( "CHAT\nPlease download the new version from www.grokksoft.com\n" ); printf( "CHAT\n--\n" ); /* Write this to the LOG */ if( InitLogFile() ) { fprintf( gLogFile, "EXPIRED ^%s^ %d-%d %s\n", pUserName, pMajorID, pMinorID, chk(getenv( "REMOTE_ADDR" )) ); } } else if( lBanned ) { printf( "CHAT\nYour ISP have been temporary banned from this gameroom because one of there customer was causing troubles\n" ); printf( "CHAT\nWe have informed your ISP and we will reenable your access as soon as they will have corrected the situation\n" ); printf( "CHAT\nYou can communicate with them to accelerate the process. Sorry for the inconvenients\n" ); printf( "CHAT\nYou can also communicate with us [email protected] to get a special code that will let you access the game\n" ); printf( "CHAT\nAlso, If you register the game you will be able to play since we can track registred users\n" ); /* Write this to the LOG */ if( InitLogFile() ) { fprintf( gLogFile, "BANNED ^%s^ %s\n", pUserName, chk(getenv( "REMOTE_ADDR" )) ); } } else if( lDoubleLog ) { printf( "CHAT\nYour can not login because our database indicates that you are already logued in\n" ); printf( "CHAT\nThis error may due to an error network. Retry to connect in a minute.\n" ); printf( "CHAT\nIf it still dont works please contact [email protected]\n" ); /* Write this to the LOG */ if( InitLogFile() ) { fprintf( gLogFile, "DOUBLELOG ^%s^ %d-%d %s\n", pUserName, pMajorID, pMinorID, chk(getenv( "REMOTE_ADDR" )) ); } } else if( lNotReg ) { printf( "CHAT\nYou must registrer to have access to this room\n" ); printf( "CHAT\nSorry\n" ); /* Write this to the LOG */ if( InitLogFile() ) { fprintf( gLogFile, "UNREG ^%s^ %s\n", pUserName, chk(getenv( "REMOTE_ADDR" )) ); } } } } } }
void AddChatMessage( IRState* pThis, int pUserIndex, int pUserId, const char* pMessage ) { int lSUIndex; BOOL lOK; int lCounter; int lLen; if( !ValidUserId( pThis, pUserIndex, pUserId ) ) { printf( "ERROR 301" ); } else { printf( "SUCCESS\n" ); if( pMessage[0] == '/' ) { /* verify if the user have super user rights */ if( ( pThis->mUser[ pUserIndex ].mExpiration != 0) &&( pThis->mUser[ pUserIndex ].mKeyID.mMajor != -1) ) { lSUIndex = 0; lOK = FALSE; while( !lOK && (gSUList[ lSUIndex ].mMajor != -1) ) { if( ( gSUList[ lSUIndex ].mMajor == pThis->mUser[ pUserIndex ].mKeyID.mMajor ) &&( gSUList[ lSUIndex ].mMinor == pThis->mUser[ pUserIndex ].mKeyID.mMinor ) ) { lOK = TRUE; } lSUIndex++; } if( !strncmp( pMessage, "/kick ", 5 )) { if( lOK ) { /* find the user to kick (start from the end this way there is more chance to catch the good one */ for( lCounter = IR_MAX_CLIENT-1; lCounter >= 0; lCounter-- ) { if( ( pThis->mUser[lCounter].mTimeStamp != 0)&&(pThis->mUser[ lCounter ].mExpiration != 0) ) { if( !strcmp( pThis->mUser[ lCounter ].mName, pMessage+6 )) { /* Kick and quit */ if( InitLogFile() ) { fprintf( gLogFile, "KICK %s(%d-%d) by %s(%d-%d)\n", pThis->mUser[ lCounter ].mName, pThis->mUser[ lCounter ].mKeyID.mMajor, pThis->mUser[ lCounter ].mKeyID.mMinor, pThis->mUser[ pUserIndex ].mName, pThis->mUser[ pUserIndex ].mKeyID.mMajor, pThis->mUser[ pUserIndex ].mKeyID.mMinor ); } RemoveUser( pThis, lCounter, TRUE ); break; } } } } else { } } } } else { lLen = 0; pThis->mChatFifo[ pThis->mChatTail ].mTimeStamp = pThis->mTimeStamp; if( pThis->mUser[ pUserIndex ].mExpiration != 0 ) { lLen += StrMaxCopy( pThis->mChatFifo[ pThis->mChatTail ].mData, pThis->mUser[ pUserIndex ].mName , IR_CHAT_MESSAGE_LEN/4 ); pThis->mChatFifo[ pThis->mChatTail ].mData[ lLen++ ] = '>'; pThis->mChatFifo[ pThis->mChatTail ].mData[ lLen++ ] = ' '; } StrMaxCopy( pThis->mChatFifo[ pThis->mChatTail ].mData+lLen, pMessage, IR_CHAT_MESSAGE_LEN-lLen ); pThis->mChatTail = (pThis->mChatTail+1)%IR_MAX_CHAT_MESSAGE; pThis->mTimeStamp++; pThis->mUser[ pUserIndex ].mNbChat++; } } }
int main( int pArgc, const char** pArgs ) { const char* lQueryPtr; int lLock; int lMemId; char lQuery[4096]; char lOp[12]; BOOL lPrintTitle; #ifndef _NO_IPC_ union semun lNULL; #endif #ifdef _NO_IPC_ gGlobalState.Clear(); if( InitLogFile() ) { fprintf( gLogFile, "IMR Init version 0.13.13b %s\n", GetTime( time(NULL)) ); } #endif #ifdef _FAST_CGI_ while( FCGI_Accept() >= 0 ) { #endif lPrintTitle = TRUE; /* Send the header required by the server */ printf("Content-type: text/plain%c%c", 10, 10); lQueryPtr = getenv( "QUERY_STRING" ); if( lQueryPtr == NULL ) { printf( "No parameters\n" ); } else { StrMaxCopy( lQuery, lQueryPtr, 4096 ); UnpadQuery( lQuery ); if( sscanf( lQuery, "=%11s", lOp ) == 1 ) { #ifndef _FAST_CGI_ /* Change the local directory */ char* lPathEnd = strrchr( pArgs[0], '/' ); if( lPathEnd != NULL ) { *lPathEnd = 0; chdir( pArgs[0] ); } #endif if( !strcmp( lOp, "RESET" ) ) { printf( "RESET OK\n\n" ); #ifdef _NO_IPC_ /* // gGlobalState.Clear(); // sleep( 2 ); // return 0; // break; */ #else lLock = semget( IR_SEM_KEY, 1, 0777 ); lMemId = shmget( IR_SHMEM_KEY, sizeof( IRState ), 0666 ); if( lLock != -1 ) { semctl( lLock, 0, IPC_RMID, lNULL ); } if( lMemId != -1 ) { shmctl( lMemId, IPC_RMID, NULL ); } #endif if( InitLogFile() ) { fprintf( gLogFile, "IMR Reset %s\n", GetTime( time(NULL)) ); } #ifdef _FAST_CGI_ break; #endif } else if( !strcmp( lOp, "SET_MESSAGE" ) ) { } /* else if( !strcmp( lOp, "STICK" ) ) { // Fork and leave a child running for 1 hour int lCode = fork(); if( lCode == 0 ) { if( InitLogFile() ) { fprintf( gLogFile, "STICK Start %s\n", GetTime( time(NULL)) ); CloseLogFile(); } close( 0 ); close( 1 ); close( 2 ); sleep( 3600 ); if( InitLogFile() ) { fprintf( gLogFile, "STICK End %s\n", GetTime( time(NULL)) ); CloseLogFile(); } } else if( lCode == -1 ) { printf( "ERROR\n" ); } else { printf( "SUCCESS\n" ); } } */ else { IRState* lState = NULL; #ifdef _NO_IPC_ lState = &gGlobalState; #else int lLock; /* Semaphore */ int lMemId; /* Shared memory */ struct sembuf lSemOp; lSemOp.sem_flg = 0; /*Avoid corruption but must not core-dump SEM_UNDO; // Risky but prevents dead-lock */ lSemOp.sem_num = 0; /* First try to create the structure for the first time */ /* Lock the data struct */ lLock = semget( IR_SEM_KEY, 1, 0777|IPC_CREAT|IPC_EXCL ); if( lLock != -1 ) { union semun lArg; /* Initialize the newly created semaphore */ lArg.val = 1; semctl( lLock, 0, SETVAL, lArg ); } else { lLock = semget( IR_SEM_KEY, 1, 0777 ); } if( lLock == -1 ) { printf( "Unable to get semaphore\n" ); } else { lSemOp.sem_op = -1; if( semop( lLock, &lSemOp, 1 ) == -1 ) { printf( "Unable to decrement semaphore\n" ); lLock = -1; } else { /* From here we can work safely */ lMemId = shmget( IR_SHMEM_KEY, sizeof( IRState ), 0666|IPC_CREAT|IPC_EXCL ); if( lMemId != -1 ) { lState = (IRState*)shmat( lMemId, NULL, 0 ); if( (int)lState == -1 ) { lState = NULL; } if( lState == NULL ) { printf( "Unable to attach shmem\n" ); } else { Clear( lState ); if( InitLogFile() ) { fprintf( gLogFile, "IMR Init %s\n", GetTime( time(NULL)) ); } } } else { lMemId = shmget( IR_SHMEM_KEY, sizeof( IRState ), 0666 ); if( lMemId == -1 ) { printf( "Unable to get shmem\n" ); } else { lState = (IRState*)shmat( lMemId, NULL, 0 ); if( (int)lState == -1 ) { lState = NULL; } if( lState == NULL ) { printf( "Unable to attach shmem\n" ); } } } } } #endif if( lState != NULL ) { lPrintTitle = FALSE; VerifyExpirations( lState ); if( !strcmp( lOp, "REFRESH" ) ) { int lUserIndex; int lUserId; int lTimeStamp; if( sscanf( lQuery, "%*s %d-%u %d", &lUserIndex, &lUserId, &lTimeStamp )==3 ) { PrintStateChange( lState, lUserIndex, lUserId, lTimeStamp ); } } else if( !strcmp( lOp, "ADD_CHAT" ) ) { int lUserIndex; int lUserId; char lChatMessage[200]; if( sscanf( lQuery, "%*s %d-%u %200s", &lUserIndex, &lUserId, lChatMessage )==3 ) { Unpad( lChatMessage ); AddChatMessage( lState, lUserIndex, lUserId, lChatMessage ); } } /* URL?=ADD_USER MAJOR-MINORID VERSION KEY2 KEY3 ALIAS */ else if( !strcmp( lOp, "ADD_USER" ) ) { int lMajorID; int lMinorID; int lVersion; unsigned int lKey2; unsigned int lKey3; char lUserName[40]; #ifdef _EXPIRED_ AddUser( lState, "User", 1,-1, -1, 0, 0 ); #else if( sscanf( lQuery, "%*s %d-%d %d %d %d %40s", &lMajorID, &lMinorID, &lVersion, &lKey2, &lKey3, lUserName )==6 ) { Unpad( lUserName ); AddUser( lState, lUserName, lVersion,lMajorID, lMinorID, lKey2, lKey3 ); } #endif } /* URL?=ADD_GAME USER_ID GAME_NAME TRACK_NAME NBLAP WEAPON PORT */ else if( !strcmp( lOp, "ADD_GAME" ) ) { int lUserIndex; int lUserId; int lNbLap; char lGameName[40]; char lTrackName[40]; int lWeapon; unsigned lPort; if( sscanf( lQuery, "%*s %d-%u %40s %40s %d %d %u", &lUserIndex, &lUserId, lGameName, lTrackName, &lNbLap, &lWeapon, &lPort )==7 ) { const char* lRemoteAddr = getenv( "REMOTE_ADDR" ); if( (lRemoteAddr != NULL)&&(strlen(lRemoteAddr) != 0) ) { Unpad( lTrackName ); Unpad( lGameName ); AddGame( lState, lGameName, lTrackName, lNbLap, lUserIndex, lUserId, lRemoteAddr, lPort, lWeapon ); } } } else if( !strcmp( lOp, "JOIN_GAME" ) ) { int lUserIndex; int lUserId; int lGameIndex; int lGameId; if( sscanf( lQuery, "%*s %d-%u %d-%u", &lGameIndex, &lGameId, &lUserIndex, &lUserId )==4 ) { JoinGame( lState, lGameIndex, lGameId, lUserIndex, lUserId ); } } else if( !strcmp( lOp, "DEL_GAME" ) ) { int lUserIndex; int lUserId; int lGameIndex; int lGameId; if( sscanf( lQuery, "%*s %d-%u %d-%u", &lGameIndex, &lGameId, &lUserIndex, &lUserId )==4 ) { DeleteGame( lState, lGameIndex, lGameId, lUserIndex, lUserId ); } } else if( !strcmp( lOp, "LEAVE_GAME" ) ) { int lUserIndex; int lUserId; int lGameIndex; int lGameId; if( sscanf( lQuery, "%*s %d-%u %d-%u", &lGameIndex, &lGameId, &lUserIndex, &lUserId )==4 ) { LeaveGame( lState, lGameIndex, lGameId, lUserIndex, lUserId ); } } else if( !strcmp( lOp, "DEL_USER" ) ) { int lUserIndex; int lUserId; if( sscanf( lQuery, "%*s %d-%u", &lUserIndex, &lUserId )==2 ) { DeleteUser( lState, lUserIndex, lUserId ); } } else if( !strcmp( lOp, "START_GAME" ) ) { int lUserIndex; int lUserId; int lGameIndex; int lGameId; if( sscanf( lQuery, "%*s %d-%u %d-%u", &lGameIndex, &lGameId, &lUserIndex, &lUserId )==4 ) { StartGame( lState, lGameIndex, lGameId, lUserIndex, lUserId ); } } else { lPrintTitle = TRUE; } } #ifdef _NO_IPC_ lState = NULL; #else /* Release lock */ if( lLock != -1 ) { lSemOp.sem_op = 1; semop( lLock, &lSemOp, 1 ); /* Release memory */ if( lState != NULL ) { shmdt( (char*)lState ); } } #endif } } } CloseLogFile(); if( lPrintTitle ) { printf( "Internet Meeting Room (c)1996,97 GrokkSoft inc.\n" ); } #ifdef _FAST_CGI_ } #endif return 0; }