Beispiel #1
0
void ChatPanel::SetBattle(IBattle* battle)
{
	if (m_battle == battle) { // battle didn't change, skip
		return;
	}

	if (m_battle != NULL) {
		OutputLine(_T("** ") + _("Left Battle."), sett().GetChatColorNotification());
	}

	if (battle == NULL) {
		SetLogFile(wxEmptyString);
		return;
	}

	OutputLine(_T("** ") + _("Joined Battle."), sett().GetChatColorNotification());

	for (unsigned int i = 0; i < battle->GetNumUsers(); ++i) {
		const wxString nick = TowxString(battle->GetUser(i).GetNick());
		textcompletiondatabase.Insert_Mapping(nick, nick);
	}

	SetLogFile(_T( "_BATTLE_" ) + TowxString(battle->GetFounder().GetNick()));
	m_battle = battle;
}
Beispiel #2
0
int InitSimSpiderEnv( struct SimSpiderEnv **ppenv , char *log_file_format , ... )
{
	int		nret = 0 ;
	
	srand( (unsigned int)time( NULL ) );
	
	if( log_file_format )
	{
		va_list         valist ;
		va_start( valist , log_file_format );
		SetLogFileV( log_file_format , valist );
		va_end( valist );
	}
	else if( getenv("SIMSPIDER_LOGFILE") )
	{
		SetLogFile( "%s" , getenv("SIMSPIDER_LOGFILE") );
	}
	else if( getenv("SIMSPIDER_LOGDIR") )
	{
		SetLogFile( "%s/simspider.log" , getenv("SIMSPIDER_LOGDIR") );
	}
	
	if( getenv("SIMSPIDER_LOGLEVEL") )
	{
		if( STRCMP( getenv("SIMSPIDER_LOGLEVEL") , == , "DEBUG" ) )
			SetLogLevel( LOGLEVEL_DEBUG );
		else if( STRCMP( getenv("SIMSPIDER_LOGLEVEL") , == , "INFO" ) )
			SetLogLevel( LOGLEVEL_INFO );
		else if( STRCMP( getenv("SIMSPIDER_LOGLEVEL") , == , "WARN" ) )
Beispiel #3
0
int ReceiveText( struct Weixin4cEnv *penv , char *post_data , int post_data_len , xml *p_req )
{
	xml	rsp ;
	char	output_buffer[ 4096 * 100 ] ;
	int	output_buflen ;
	int	output_bufsize ;
	char	rsp_buffer[ 4096 * 110 ] ;
	int	rsp_buflen ;
	
	int	nret = 0 ;
	
	TakeoffCDATA( p_req->ToUserName );
	TakeoffCDATA( p_req->FromUserName );
	TakeoffCDATA( p_req->Content );
	
	memset( output_buffer , 0x00 , sizeof(output_buffer) );
	output_buflen = 0 ;
	output_bufsize = sizeof(output_buffer) ;
	if( penv->pconf->funcs.pfuncReceiveTextProc )
	{
		SetLogFile( "%s/log/%s_ReceiveTextProc.log" , penv->pconf->home , penv->pconf->project_name );
		nret = penv->pconf->funcs.pfuncReceiveTextProc( penv->pconf->user_data , p_req , output_buffer , & output_buflen , & output_bufsize ) ;
		SetLogFile( "%s/log/%s_weixin4c.log" , penv->pconf->home , penv->pconf->project_name );
		if( nret )
		{
			ErrorLog( __FILE__ , __LINE__ , "pfuncReceiveTextProc failed[%d]" , nret );
		}
		else
		{
			InfoLog( __FILE__ , __LINE__ , "pfuncReceiveTextProc ok" );
		}
	}
	
	memset( & rsp , 0x00 , sizeof(xml) );
	snprintf( rsp.ToUserName , sizeof(rsp.ToUserName)-1 , "<![CDATA[%s]]>" , p_req->FromUserName );
	snprintf( rsp.FromUserName , sizeof(rsp.FromUserName)-1 , "<![CDATA[%s]]>" , p_req->ToUserName );
	rsp.CreateTime = (int)time(NULL) ;
	strcpy( rsp.MsgType , p_req->MsgType );
	snprintf( rsp.Content , sizeof(rsp.Content)-1 , "<![CDATA[%s]]>" , output_buffer );
	strcpy( rsp.MsgId , p_req->MsgId );
	
	memset( rsp_buffer , 0x00 , sizeof(rsp_buffer) );
	rsp_buflen = sizeof(rsp_buffer) - 1 ;
	nret = DSCSERIALIZE_XML_xml( & rsp , "GB18030" , rsp_buffer , & rsp_buflen ) ;
	if( nret )
	{
		ErrorLog( __FILE__ , __LINE__ , "DSCSERIALIZE_XML_xml failed[%d]" , nret );
	}
	else
	{
		InfoLog( __FILE__ , __LINE__ , "DSCSERIALIZE_XML_xml ok" );
		InfoLog( __FILE__ , __LINE__ , "rsp xml[%.*s]" , rsp_buflen-41 , rsp_buffer+41 );
		printf( "%.*s" , rsp_buflen-41 , rsp_buffer+41 );
	}
	
	return 0;
}
Beispiel #4
0
int wmain(int argc, CHAR* argv[])
{


	if(argc != 1){
		printf("Usage:\n \t %S \n",argv[0]);
		exit(0);
	}

	SetLogFile("PulsarCmdLine.txt");

	SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, TRUE);


	printf("Pulsar Command Line Started\n");


	pulsarCtx = PulsarInit();
	if(!pulsarCtx){
		DBGPrint("Failed to create Pulsar Context");
		goto exit;
	}

 
	WaitForMultipleObjects(pulsarCtx->handleCount, (const HANDLE*)pulsarCtx->handles, TRUE, INFINITE);	

exit:

	printf("Pulsar Command Line Done\n");

	return 0;
}
Beispiel #5
0
static int cgiinit( struct Weixin4cEnv *penv )
{
	int		nret = 0 ;
	
	chdir( "/tmp" );
	
	SetLogFile( "%s/log/%s_weixin4c.log" , penv->pconf->home , penv->pconf->project_name );
	SetLogLevel( LOGLEVEL_DEBUG );
	
	if( penv->pconf->funcs.pfuncInitEnvProc )
	{
		nret = penv->pconf->funcs.pfuncInitEnvProc( penv->pconf->user_data ) ;
		if( nret )
		{
			ErrorLog( __FILE__ , __LINE__ , "pfuncInitEnvProc failed[%d]" , nret );
			return -2;
		}
		else
		{
			InfoLog( __FILE__ , __LINE__ , "pfuncInitEnvProc ok" );
		}
	}
	
	return 0;
}
Beispiel #6
0
int xmain(int argc, char **argv)
	{
    MuscleContext *ctx = getMuscleContext();
#if	WIN32
// Multi-tasking does not work well in CPU-bound
// console apps running under Win32.
// Reducing the process priority allows GUI apps
// to run responsively in parallel.
	SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS);
#endif
	ctx->muscle.g_argc = argc;
	ctx->muscle.g_argv = argv;

	SetNewHandler();
	SetStartTime();
	ProcessArgVect(argc - 1, argv + 1);
	SetParams();
	SetLogFile();

	//extern void TestSubFams(const char *);
	//TestSubFams(g_pstrInFileName);
	//return 0;

	if (ctx->params.g_bVersion)
		{
		printf(MUSCLE_LONG_VERSION "\n");
		exit(EXIT_SUCCESS);
		}

	if (!ctx->params.g_bQuiet)
		//Credits();

	if (MissingCommand() && isatty(0))
		{
		Usage();
		exit(EXIT_SUCCESS);
		}

	if (ctx->params.g_bCatchExceptions)
		{
		try
			{
			Run();
			}
		catch (...)
			{
			OnException();
			exit(EXIT_Except);
			}
		}
	else
		Run();

#ifdef _CRTDBG_MAP_ALLOC
    delete ctx;
    _CrtDumpMemoryLeaks(); //to Output window of MSVC
#endif

	exit(EXIT_Success);
	}
Beispiel #7
0
void DoArgs(int argcount,char **arg){
    char *current;
    char *tmp;
    unsigned int i,j=1;
    current=arg[1];
    argcount--;
    //printf(current);
    //printf("\n%i\n",argcount);
    if(*arg[1]!='?'){ParseConfigFile(arg[1]);argcount--;j=2;}
    while(argcount!=0){
        tmp=current;
        if(tmp[0]!='?'){panic("Arg does not start with \'?\'");}
        for(i=0;i<strlen(current);i++){if(tmp[i]==':'){tmp[i]=0; break;}}
        if(strcmp(tmp,"?f")==0){printf("\nTTT\n");ParseConfigFile(tmp+strlen(tmp)+1);}  //debugging purposes...
        if(strcmp(tmp,"?L_com")==0){LoadComFile(tmp+strlen(tmp)+1);}  //load a .com file
        if(strcmp(tmp,"?log")==0){SetLogFile(tmp+strlen(tmp)+1);}  //use a log file
        if(strcmp(tmp,"?L_bin")==0){LoadBinFile(tmp+strlen(tmp)+1);} //load binary file
        if(strcmp(tmp,"?L_dev")==0){printf("bah");InitExLib(tmp+strlen(tmp)+1);} //load device
       // if(strcmp(tmp,"?bios")==0){LoadBios(tmp+strlen(tmp)+1);}
        j++;
        current=arg[j];
        argcount--;
        }


}
Beispiel #8
0
TDaemon::TDaemon(const char* ConfigName)
{
        // данный код уже выполняется в процессе потомка
        // разрешаем выставлять все биты прав на создаваемые файлы, 
        // иначе у нас могут быть проблемы с правами доступа
        umask(0);
        
        //Задаем путь к конфигу
        CONFIG_FILE=string(ETC_CONF_DIR)+ConfigName;
        //задаем путь к логу
        SetLogFile((string(LOG_DIR)+PROJ_NAME+".log").c_str());
        //задаем путь к PID-файлу
        PID_FILE=string(RUN_DIR)+PROJ_NAME+".pid";
        
        // создаём новый сеанс, чтобы не зависеть от родителя
        setsid();
        
        // переходим в корень диска, если мы этого не сделаем, то могут быть проблемы.
        // к примеру с размонтированием дисков
        int i=chdir("/");
        if(i<0)
        {
            WriteLog("%s [DAEMON] Failed to set default directory: %s\n", getTime(),strerror(errno));
        }
        // закрываем дискрипторы ввода/вывода/ошибок, так как нам они больше не понадобятся
        close(STDIN_FILENO);
        close(STDOUT_FILENO);
        close(STDERR_FILENO);
}
Beispiel #9
0
void ChatPanel::SetChannel(Channel* chan)
{
	ASSERT_LOGIC(this, "this==null");
	ASSERT_LOGIC(m_type == CPT_Channel, "Not of type channel");

	if ((chan == 0) && (m_channel != 0)) {
		m_channel->uidata.panel = 0;
	}
	if (m_nicklist != nullptr) {
		m_nicklist->ClearUsers();
		UpdateUserCountLabel();
	}

	if (chan != 0) {
		chan->uidata.panel = this;
		if (chan != m_channel) {
			SetLogFile(TowxString(chan->GetName()));
		}
	}
	m_channel = chan;

	//set back to false so when we rejoin this channel SetTopic doesn;t update the chan icon
	if (!m_channel)
		m_topic_set = false;
}
Beispiel #10
0
INT APIENTRY DllMain(HMODULE hDLL, DWORD Reason, LPVOID Reserved) {


	SetLogFile("C:\\pulsar\\PulsarDLL.txt");
	DBGPrint("Called\n");
 
	switch(Reason) {
		case DLL_PROCESS_ATTACH:
			DBGPrint("DLL_PROCESS_ATTACH\n");
			PULSE_INIT();
			break;
		case DLL_PROCESS_DETACH:
			DBGPrint("DLL_PROCESS_DETACH\n");
			break;
		case DLL_THREAD_ATTACH:
			DBGPrint("DLL_THREAD_ATTACH\n");
			break;
		case DLL_THREAD_DETACH:
			DBGPrint("DLL_THREAD_DETACH\n");
			break;
	}
 

return TRUE;
}
//--------------------------------------------------------------------------------
CStatus::CStatus(LPCTSTR pFilename)
	{
	AFX_MANAGE_STATE(AfxGetStaticModuleState());

	m_nRefCount++;

	SetLogFile(pFilename, (CResult*) this);
	}
Beispiel #12
0
HRESULT __stdcall DllRegisterServer(void){
	SetLogFile("C:\\debug\\PulsarDLL.txt");
	DBGPrint("Called\n");

	PULSE_INIT();

	return 0;


}
Beispiel #13
0
int CLog::SetLogFile(const string &file)
{
	FILE *pLog = fopen(file.c_str(), "a+");
	int res = SetLogFile(pLog);
	if(res == 0)
	{
		m_strLogFile = file;
	}
	return res;
}
Beispiel #14
0
ChatLog::ChatLog(const wxString& logname)
    : m_logname(logname)
    , m_active(false)
    , m_logfile()
{
	wxLogMessage(_T( "ChatLog::ChatLog( %s )" ), logname.c_str());
	if (LogEnabled()) {
		m_active = SetLogFile(logname);
	}
}
Beispiel #15
0
void mitk::LoggingBackend::Unregister()
{
  if (mitkLogBackend)
  {
    SetLogFile(nullptr);
    mbilog::UnregisterBackend(mitkLogBackend);
    delete mitkLogBackend;
    mitkLogBackend = nullptr;
  }
}
Beispiel #16
0
int main( int argc , char *argv[] )
{
	if( argc == 1 + 2 )
	{
		SetLogFile( "%s/log/%s_accesstoken.log" , getenv("HOME") , argv[1] );
		SetLogLevel( LOGLEVEL_DEBUG );
		
		return -AccessToken( argv[1] , atoi(argv[2]) );
	}
	else
	{
		usage();
		exit(9);
	}
}
Beispiel #17
0
void ChatPanel::SetServer(IServer* serv)
{
	ASSERT_LOGIC(m_type == CPT_Server, "Not of type server");
	if (m_nicklist != nullptr) {
		m_nicklist->ClearUsers();
		UpdateUserCountLabel();
	}
	if (serv != 0) {
		SetLogFile(_T("server"));
		serv->uidata.panel = this;
		if (m_server != nullptr) {
			m_server->uidata.panel = 0;
		}
		m_server = serv;
	}
}
Beispiel #18
0
void ChatPanel::Init(const wxString& panelname)
{
	m_chatpanelname = panelname;

	//Clear some controls pointer that can be used in ReadSettings
	m_say_text = nullptr;
	m_chatlog_text = nullptr;

	//Read settings
	ReadSettings();
	CreateControls();
	SetLogFile(panelname);

	GetAui().manager->AddPane(this, wxLEFT, _T("chatpanel-channel-") + panelname);
	m_chatlog_text->Connect(wxEVT_RIGHT_DOWN, wxMouseEventHandler(ChatPanel::OnMouseDown), 0, this);

	SUBSCRIBE_GLOBAL_EVENT(GlobalEventManager::OnLogin, ChatPanel::OnLogin);
	SUBSCRIBE_GLOBAL_EVENT(GlobalEventManager::ApplicationSettingsChangedEvent, ChatPanel::OnSettingsChanged);
}
Beispiel #19
0
CLogger::CLogger(void)
    :m_file_handle(NULL), m_level(0)
{
#ifdef PARAENGINE_MOBILE
    m_is_first_time_open = true;
#ifdef WIN32
    m_bForceFlush = true;
#else
    // for android client never flush, since disk is slow.
    m_bForceFlush = false;
#endif
#else
#if defined(PARAENGINE_CLIENT)
    m_bForceFlush = true;
    m_is_first_time_open = true;
#else
    m_bForceFlush = false;
    m_is_first_time_open = false;
#endif
#endif
    SetLogFile("log.txt");
}
Beispiel #20
0
ConsoleAPI::ConsoleAPI(Framework *fw) :
    QObject(fw),
    framework(fw),
    enabledLogChannels(LogLevelErrorWarnInfo),
    logFile(0),
    logFileText(0)
{
    if (!fw->IsHeadless())
        consoleWidget = new ConsoleWidget(framework);

    inputContext = framework->Input()->RegisterInputContext("Console", 100);
    inputContext->SetTakeKeyboardEventsOverQt(true);
    connect(inputContext.get(), SIGNAL(KeyEventReceived(KeyEvent *)), SLOT(HandleKeyEvent(KeyEvent *)));

    RegisterCommand("help", "Lists all registered commands.", this, SLOT(ListCommands()));
    RegisterCommand("clear", "Clears the console log.", this, SLOT(ClearLog()));
    RegisterCommand("setLogLevel", "Sets the current log level. Call with one of the parameters \"error\", \"warning\", \"info\", or \"debug\".",
        this, SLOT(SetLogLevel(const QString &)));
#ifdef WIN32
    RegisterCommand("createConsole", "Creates the native Windows console if Tundra was started without such.", this, SLOT(CreateNativeConsole()));
    RegisterCommand("removeConsole", "Removes the native Windows console if applicable.", this, SLOT(RemoveNativeConsole()));
#endif

    /// \todo Visual Leak Detector shows a memory leak originating from this allocation although the shellInputThread is released in the destructor. Perhaps a shared pointer is held elsewhere.
    shellInputThread = MAKE_SHARED(ShellInputThread);

    QStringList logLevel = fw->CommandLineParameters("--loglevel");
    if (logLevel.size() >= 1)
        SetLogLevel(logLevel[logLevel.size()-1]);
    if (logLevel.size() > 1)
        LogWarning("Ignoring multiple --loglevel command line parameters!");

    QStringList logFile = fw->CommandLineParameters("--logfile");
    if (logFile.size() >= 1)
        SetLogFile(logFile[logFile.size()-1]);
    if (logFile.size() > 1)
        LogWarning("Ignoring multiple --logfile command line parameters!");
}
Beispiel #21
0
	virtual void SetUp ()
	{
	    /* Another hack - if the server fails
	     * to start then just set another display
	     * number until it does */
	    const int MaxConnections = 255;
	    int displayNumber = 0;
	    bool serverRunningOnDisplay = true;

	    while (serverRunningOnDisplay &&
		   displayNumber < MaxConnections)
	    {
		std::stringstream ss;
		ss << ":" << displayNumber;
		Display *check = XOpenDisplay (ss.str ().c_str ());

		if (!check)
		    serverRunningOnDisplay = false;
		else
		{
		    XCloseDisplay (check);
		    ++displayNumber;
		}
	    }

	    if (displayNumber == MaxConnections)
		throw std::runtime_error ("couldn't find a socket "
					  "to launch on");

	    std::stringstream logFile;
	    logFile << "/tmp/Compiz.Xorg.GTest." << displayNumber << ".log";

	    SetDisplayNumber (displayNumber);
	    SetLogFile (logFile.str ());
	    xorg::testing::Environment::SetUp ();
	}
Beispiel #22
0
//------------------------------------------------------------------------------
void ConsoleMessageReceiver::LogMessage(const std::string &msg)
{
   std::cout << msg;
   
   if (logEnabled)
   {
      if (logFile == NULL)
      {
         SetLogFile(GetLogFileName());
      }
   }
   else if (!logFileSet)
   {
      OpenLogFile(logFileName);
   }
   
   if (logFile)
   {
      //std::string tempStr = GmatStringUtil::Replace(msg, "%", "%%");
      //fprintf(logFile, "%s", tempStr.c_str());
      fprintf(logFile, "%s", msg.c_str());
      fflush(logFile);
   }
}
Beispiel #23
0
int server( struct ServerEnv *penv )
{
	time_t			now ;
	long			epoll_timeout ;
	struct epoll_event	events[ WAIT_EVENTS_COUNT ] ;
	int			epoll_ready_count ;
	int			epoll_ready_index ;
	struct epoll_event	*pevent ;
	struct SocketSession	*psession = NULL ;
	int			accepted_session_index ;
	
	int			nret = 0 ;
	
	signal( SIGTERM , & server_signal_proc );
	
	SetLogFile( "%s/log/dc4c_rserver_1_%s:%d.log" , getenv("HOME") , penv->param.rserver_ip , penv->param.rserver_port );
	if( penv->param.loglevel_debug == 1 )
		SetLogLevel( LOGLEVEL_DEBUG );
	else
		SetLogLevel( LOGLEVEL_INFO );
	
	penv->epoll_socks = epoll_create( EPOLL_FDS_COUNT ) ;
	if( penv->epoll_socks < 0 )
	{
		ErrorLog( __FILE__ , __LINE__ , "epoll_create failed[%d]errno[%d]" , penv->epoll_socks , errno );
		return -1;
	}
	else
	{
		InfoLog( __FILE__ , __LINE__ , "epoll_create ok , sock[%d]" , penv->epoll_socks );
	}
	
	nret = InitSocketSession( & (penv->listen_session) ) ;
	if( nret )
	{
		ErrorLog( __FILE__ , __LINE__ , "InitSocketSession failed[%d]errno[%d]" , nret , errno );
		return -1;
	}
	
	nret = BindListenSocket( penv->param.rserver_ip , penv->param.rserver_port , & (penv->listen_session) ) ;
	if( nret )
	{
		ErrorLog( __FILE__ , __LINE__ , "BindListenSocket[%s:%d] failed[%d]errno[%d]" , penv->param.rserver_ip , penv->param.rserver_port , nret , errno );
		return -1;
	}
	else
	{
		InfoLog( __FILE__ , __LINE__ , "BindListenSocket[%s:%d] ok" , penv->param.rserver_ip , penv->param.rserver_port );
	}
	
	AddInputSockToEpoll( penv->epoll_socks , & (penv->listen_session) );
	
	penv->accepted_session_array = (struct SocketSession *)malloc( sizeof(struct SocketSession) * MAXCOUNT_ACCEPTED_SESSION ) ;
	if( penv->accepted_session_array == NULL )
	{
		FatalLog( __FILE__ , __LINE__ , "malloc failed[%d]errno[%d]" , nret , errno );
		return -1;
	}
	memset( penv->accepted_session_array , 0x00 , sizeof(struct SocketSession) * MAXCOUNT_ACCEPTED_SESSION );
	
	epoll_timeout = 1 ;
	while( ! g_server_exit_flag )
	{
		memset( events , 0x00 , sizeof(events) );
		if( g_server_exit_flag || getppid() == 1 )
			break;
		epoll_ready_count = epoll_wait( penv->epoll_socks , events , WAIT_EVENTS_COUNT , epoll_timeout * 1000 ) ;
		if( g_server_exit_flag || getppid() == 1 )
			break;
		
		DebugLog( __FILE__ , __LINE__ , "epoll_wait [%d]events reached" , epoll_ready_count );
		
		time( & now );
		
		for( epoll_ready_index = 0 , pevent = & (events[0]) ; epoll_ready_index < epoll_ready_count ; epoll_ready_index++ , pevent++ )
		{
			psession = pevent->data.ptr ;
			DebugLog( __FILE__ , __LINE__ , "psession[%p] pevent->events[%d]" , psession , pevent->events );
			
			if( psession == & (penv->listen_session) )
			{
				if( pevent->events & EPOLLERR )
				{
					DebugLog( __FILE__ , __LINE__ , "EPOLLERR on listen sock[%d]" , psession->sock );
					g_server_exit_flag = 1 ;
					break;
				}
				else if( pevent->events & EPOLLIN || pevent->events & EPOLLHUP )
				{
					DebugLog( __FILE__ , __LINE__ , "EPOLLIN on listen sock[%d]" , psession->sock );
					
					nret = comm_OnListenSocketInput( penv , psession ) ;
					if( nret < 0 )
						return nret;
				}
				else if( pevent->events & EPOLLOUT )
				{
					DebugLog( __FILE__ , __LINE__ , "EPOLLOUT on listen sock[%d]" , psession->sock );
					g_server_exit_flag = 1 ;
					break;
				}
			}
			else
			{
				if( pevent->events & EPOLLERR )
				{
					DebugLog( __FILE__ , __LINE__ , "EPOLLERR on accepted sock[%d]" , psession->sock );
					
					nret = comm_OnAcceptedSocketError( penv , psession ) ;
					if( nret < 0 )
						return nret;
				}
				else if( pevent->events & EPOLLIN || pevent->events & EPOLLHUP )
				{
					DebugLog( __FILE__ , __LINE__ , "EPOLLIN on accepted sock[%d]" , psession->sock );
					
					nret = comm_OnAcceptedSocketInput( penv , psession ) ;
					if( nret < 0 )
						return nret;
				}
				else if( pevent->events & EPOLLOUT )
				{
					DebugLog( __FILE__ , __LINE__ , "EPOLLOUT on accepted sock[%d]" , psession->sock );
					
					nret = comm_OnAcceptedSocketOutput( penv , psession ) ;
					if( nret < 0 )
						return nret;
				}
			}
		}
		
		app_HeartBeatRequest( penv , & now , & epoll_timeout );
	}
	
	sleep( penv->param.delay );
	
	for( accepted_session_index = 0 ; accepted_session_index < MAXCOUNT_ACCEPTED_SESSION ; accepted_session_index++ )
	{
		CleanSocketSession( penv->accepted_session_array+accepted_session_index );
	}
	free( penv->accepted_session_array );
	
	DeleteSockFromEpoll( penv->epoll_socks , & (penv->listen_session) );
	CloseSocket( & (penv->listen_session) );
	CleanSocketSession( & (penv->listen_session) );
	
	close( penv->epoll_socks );
	InfoLog( __FILE__ , __LINE__ , "close all socks and epoll_socks" );
	
	InfoLog( __FILE__ , __LINE__ , "--- rserver [%s:%d] - [1] --- end" , penv->param.rserver_ip , penv->param.rserver_port );
	
	return 0;
}
Beispiel #24
0
 LogManager::LogManager()
 {
     SetLogFile("engine.log");
 }
Beispiel #25
0
int loadSettings(const char *filename)
{
	if (!FileExists(filename)) {
		LogWarn(VB_SETTING,
			"Attempted to load settings file %s which does not exist!", filename);
		return -1;
	}

	FILE *file = fopen(filename, "r");

	if (file != NULL)
	{
		char * line = NULL;
		size_t len = 0;
		ssize_t read;
		int sIndex = 0;

		while ((read = getline(&line, &len, file)) != -1)
		{
			if (( ! line ) || ( ! read ) || ( read == 1 ))
				continue;

			char *key = NULL, *value = NULL;	// These are values we're looking for and will
												// run through trimwhitespace which means they
												// must be freed before we are done.

			char *token = strtok(line, "=");
			if ( ! token )
				continue;

			key = trimwhitespace(token);
			if ( !strlen(key) )
			{
				free(key);
				continue;
			}

			token = strtok(NULL, "=");
			if ( !token )
			{
				fprintf(stderr, "Error tokenizing value for %s setting\n", key);
				free(key);
				continue;
			}
			value = trimwhitespace(token);

			parseSetting(key, value);

            settings.keyVal[key] = strdup(value);

			if ( key )
			{
				free(key);
				key = NULL;
			}

			if ( value )
			{
				free(value);
				value = NULL;
			}
		}

		if (line)
			free(line);
	
		fclose(file);
	}
	else
	{
		LogWarn(VB_SETTING, "Warning: couldn't open settings file: '%s'!\n", filename);
		return -1;
	}

	if (getDaemonize())
		SetLogFile(getLogFile());
	else
		SetLogFile("");

	return 0;
}
Beispiel #26
0
//打开seed文件,校验,并提取所有的台站分量信息
int CSeedFile::open( const WCHAR* pFileName ,CSeedLog* lpLog)
{
	int iLeft, nRet;
	Station station;
	FIX_DATA_HEADER * lpFDH;
	FIX_DATA_HEADER* lpNext;

	//首先释放文件
	close();

	nRet = TRUE;
	//检查seed文件的合法性
	if( seed->MapFile(pFileName, 0) == NULL )
		return FALSE;

	//设置log文件
	SetLogFile(lpLog);
	//日志记录
	if(log != NULL)
	{
		SYSTEMTIME time;

		GetLocalTime(&time);
		sprintf_s(log->logString, MAX_LOG_STR_SIZE, "%04d-%02d-%02d,%02d:%02d:%02d", 
			time.wYear, time.wMonth, time.wDay, 
			time.wHour, time.wMinute, time.wSecond);
		log->FormatAndAppendLog(info_seed, info_open, log->logString);
	}

	if(! IsValidSeed(seed->m_lpBase, seed->m_iSize))//这里方式使用1000块校验,
		nRet = FALSE;
	else if(FALSE == AnalyzeSeedFile(seed->m_lpBase, seed->m_iSize, &m_swap, &m_step) )
		nRet = FALSE;

	if(nRet == FALSE)
	{
		close();
		return FALSE;
	}

	//set the file name and path
	SplitNameAndPath(pFileName, name, path);

	//日志,添加日志
	if(log != NULL)
	{
		char filenameASCII[MAX_PATH];
		WcharNameToCharName(filenameASCII, sizeof(filenameASCII), pFileName, wcslen(pFileName));
		sprintf_s(log->logString, MAX_LOG_STR_SIZE, "file name: %s. file size: %d bytes",
							filenameASCII, seed->m_iSize);
		log->FormatAndAppendLog(info_seed, info_file, log->logString);
	}


	//获取台站信息
	lpFDH = (FIX_DATA_HEADER*)GetFirstDataRecordAddr((char*)seed->m_lpBase, \
									seed->m_iSize, m_step);
	while (lpFDH != NULL)
	{
		BTIME tStart, tend;
		iLeft = seed->m_iSize - ((char*)lpFDH - (char*)(seed->m_lpBase));
		//填充信息
		charTowchar(station.station, lpFDH->szStationID, 5);
		charTowchar(station.channel, lpFDH->szChannelID, 3);

		if(AnalyzeStationInfo((char*)lpFDH, iLeft, m_step, m_swap, (char**)(&lpNext), &station.iRecordLen, 
			&tStart, &tend, &station.nSample, &station.nlost, 
			&station.freq.numerator, &station.freq.denominator) == 0)//出现重大错误,停止分析
			break;
		station.lpAddr = (char*)lpFDH;
		BTimeToSystemTime(&tStart, &station.time);
		BTimeToSystemTime(&tend, &station.tend);
		station.pData = NULL;
		station.bufitemcnt = 0;
		station.iDataCnt = 0;
		station.dataFreq.numerator = station.freq.numerator;
		station.dataFreq.denominator = station.freq.denominator;
		memcpy(&station.datatime, &station.time, sizeof(SYSTEMTIME));
		station.lpNext = NULL;
		list->AddElement(&station);


		if (log != NULL && log->IsDetailLog() )
		{
			//日志,添加台站日志信息
			char szStation[6], szChannel[4];
			float freq;
			freq = ((float)station.freq.numerator) / ((float)station.freq.denominator);
			strcpy_ULN(szStation, lpFDH->szStationID, 5);
			strcpy_ULN(szChannel, lpFDH->szChannelID, 3);
			sprintf_s(log->logString, MAX_LOG_STR_SIZE, 
				"station:%s. channel:%s. "
				"frequency:%f. total samples:%d. lost samples:%d"
				"start time:%04d-%02d-%02d,%02d:%02d:%02d"
				"end time:%04d-%02d-%02d,%02d:%02d:%02d", 
				szStation, szChannel, freq, station.nSample, station.nlost, 
				station.time.wYear, station.time.wMonth, station.time.wDay,
				station.time.wHour, station.time.wMinute, station.time.wSecond, 
				station.tend.wYear, station.tend.wMonth, station.tend.wDay, 
				station.tend.wHour, station.tend.wMinute, station.tend.wSecond);
			log->FormatAndAppendLog(info_seed, info_station, log->logString);
		}

		//准备取下一个台站分量的信息
		lpFDH = lpNext;
	}
	//强制保存
	if(log != NULL)
		log->SaveLog();
	return TRUE;
}
Beispiel #27
0
static int cgimain( struct Weixin4cEnv *penv )
{
	char		*signature = NULL ;
	char		*timestamp = NULL ;
	char		*nonce = NULL ;
	char		*echostr = NULL ;
	
	char		*post_data = NULL ;
	int		post_data_len ;
	xml		req ;
	
	int		nret = 0 ;
	
	PUBSendContentTypeHtml();
	
	PUBDupUrlParam( "signature" , & signature );
	PUBDupUrlParam( "timestamp" , & timestamp );
	PUBDupUrlParam( "nonce" , & nonce );
	PUBDupUrlParam( "echostr" , & echostr );
	
	if( signature && timestamp && nonce && echostr )
	{
		SetLogFile( "%s/log/%s_VerifyServer.log" , penv->pconf->home , penv->pconf->project_name );
		nret = VerifyServer( penv , signature , timestamp , nonce , echostr ) ;
		SetLogFile( "%s/log/%s_weixin4c.log" , penv->pconf->home , penv->pconf->project_name );
		if( nret )
		{
			ErrorLog( __FILE__ , __LINE__ , "VerifyServer failed[%d]" , nret );
		}
		else
		{
			InfoLog( __FILE__ , __LINE__ , "VerifyServer ok" );
		}
	}
	else
	{
		nret = PUBReadPostBuffer() ;
		if( nret )
		{
			ErrorLog( __FILE__ , __LINE__ , "PUBReadPostBuffer failed[%d]" , nret );
		}
		else
		{
			InfoLog( __FILE__ , __LINE__ , "PUBReadPostBuffer ok" );
			
			post_data = PUBGetPostBufferPtr() ;
			post_data_len = PUBGetPostBufferLength() ;
			
			memset( & req , 0x00 , sizeof(xml) );
			nret = DSCDESERIALIZE_XML_xml( NULL , post_data , & post_data_len , & req ) ;
			if( nret )
			{
				ErrorLog( __FILE__ , __LINE__ , "DSCDESERIALIZE_XML_xml_MsgType failed[%d] , xml[%s]" , nret , post_data );
			}
			else
			{
				InfoLog( __FILE__ , __LINE__ , "DSCDESERIALIZE_XML_xml_MsgType ok , xml[%s]" , post_data );
				
				InfoLog( __FILE__ , __LINE__ , "req.MsgType[%s]" , req.MsgType );
				if( strcmp( req.MsgType , "<![CDATA[event]]>" ) == 0 )
				{
					nret = ReceiveEvent( penv , post_data , post_data_len , & req ) ;
					if( nret )
					{
						ErrorLog( __FILE__ , __LINE__ , "ReceiveEvent failed[%d]" , nret );
					}
					else
					{
						InfoLog( __FILE__ , __LINE__ , "ReceiveEvent ok" );
					}
				}
				else if( strcmp( req.MsgType , "<![CDATA[text]]>" ) == 0 )
				{
					nret = ReceiveText( penv , post_data , post_data_len , & req ) ;
					if( nret )
					{
						ErrorLog( __FILE__ , __LINE__ , "ReceiveText failed[%d]" , nret );
					}
					else
					{
						InfoLog( __FILE__ , __LINE__ , "ReceiveText ok" );
					}
				}
				else if( strcmp( req.MsgType , "<![CDATA[image]]>" ) == 0 )
				{
					nret = ReceiveImage( penv , post_data , post_data_len , & req ) ;
					if( nret )
					{
						ErrorLog( __FILE__ , __LINE__ , "ReceiveImage failed[%d]" , nret );
					}
					else
					{
						InfoLog( __FILE__ , __LINE__ , "ReceiveImage ok" );
					}
				}
				else if( strcmp( req.MsgType , "<![CDATA[voice]]>" ) == 0 )
				{
					nret = ReceiveVoice( penv , post_data , post_data_len , & req ) ;
					if( nret )
					{
						ErrorLog( __FILE__ , __LINE__ , "ReceiveVoice failed[%d]" , nret );
					}
					else
					{
						InfoLog( __FILE__ , __LINE__ , "ReceiveVoice ok" );
					}
				}
				else if( strcmp( req.MsgType , "<![CDATA[video]]>" ) == 0 )
				{
					nret = ReceiveVideo( penv , post_data , post_data_len , & req ) ;
					if( nret )
					{
						ErrorLog( __FILE__ , __LINE__ , "ReceiveVideo failed[%d]" , nret );
					}
					else
					{
						InfoLog( __FILE__ , __LINE__ , "ReceiveVideo ok" );
					}
				}
				else if( strcmp( req.MsgType , "<![CDATA[shortvideo]]>" ) == 0 )
				{
					nret = ReceiveShortVideo( penv , post_data , post_data_len , & req ) ;
					if( nret )
					{
						ErrorLog( __FILE__ , __LINE__ , "ReceiveShortVideo failed[%d]" , nret );
					}
					else
					{
						InfoLog( __FILE__ , __LINE__ , "ReceiveShortVideo ok" );
					}
				}
				else if( strcmp( req.MsgType , "<![CDATA[location]]>" ) == 0 )
				{
					nret = ReceiveLocation( penv , post_data , post_data_len , & req ) ;
					if( nret )
					{
						ErrorLog( __FILE__ , __LINE__ , "ReceiveLocation failed[%d]" , nret );
					}
					else
					{
						InfoLog( __FILE__ , __LINE__ , "ReceiveLocation ok" );
					}
				}
				else if( strcmp( req.MsgType , "<![CDATA[link]]>" ) == 0 )
				{
					nret = ReceiveLink( penv , post_data , post_data_len , & req ) ;
					if( nret )
					{
						ErrorLog( __FILE__ , __LINE__ , "ReceiveLink failed[%d]" , nret );
					}
					else
					{
						InfoLog( __FILE__ , __LINE__ , "ReceiveLink ok" );
					}
				}
				else
				{
					ErrorLog( __FILE__ , __LINE__ , "xml.MsgType[%s] invalid" , req.MsgType );
				}
			}
		}
	}
	
	if( signature )
		free( signature );
	if( timestamp )
		free( timestamp );
	if( nonce )
		free( nonce );
	if( echostr )
		free( echostr );
	
	return nret;
}
Beispiel #28
0
BOOL CPulseDisplayDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// 이 대화 상자의 아이콘을 설정합니다. 응용 프로그램의 주 창이 대화 상자가 아닐 경우에는
	// 프레임워크가 이 작업을 자동으로 수행합니다.
	SetIcon(m_hIcon, TRUE);			// 큰 아이콘을 설정합니다.
	SetIcon(m_hIcon, FALSE);		// 작은 아이콘을 설정합니다.

	// 로그인 화면 구성 필요.
#ifdef LOGIN_DLG
	CLoginDlg	loginDlg;
	BOOL		noLogin = FALSE;
	while(loginDlg.DoModal() != IDOK)
	{
		if(AfxMessageBox(INVALID_USER, MB_OKCANCEL, NULL) == IDOK)
		{
			noLogin = TRUE;
			break;
		}
	}
	
	if(noLogin)
	{
		::PostQuitMessage(WM_QUIT);
		return FALSE;
	}
	else
		m_UserName = loginDlg.getUserName();

	// 로그인 화면 종료
#endif

#ifndef LIMIT_SCREEN_SIZE
	int cx = GetSystemMetrics(SM_CXSCREEN);
	int cy = GetSystemMetrics(SM_CYSCREEN);

	this->SetWindowPos(&CWnd::wndNoTopMost, 0, 0, cx, cy, SWP_NOMOVE);
#else
	this->SetWindowPos(&CWnd::wndNoTopMost, 0, 0, MAIN_DLG_WIDTH, MAIN_DLG_HEIGHT, SWP_NOMOVE);
#endif

	this->SetWindowText(MAIN_WINDOW_NAME);

	SetTimer(TID_TIME, 1000, NULL);

	m_ctlTabMain.InsertItem(0, _T(TAB1_DSP_NAME));
	m_ctlTabMain.InsertItem(1, _T(TAB2_DSP_NAME));
	m_ctlTabMain.InsertItem(2, _T(TAB3_DSP_NAME));
	m_ctlTabMain.InsertItem(3, _T(TAB4_DSP_NAME));
#ifndef LIMIT_SCREEN_SIZE
	m_ctlTabMain.SetItemSize(CSize(cy / 4 - 5));
#else
	m_ctlTabMain.SetItemSize(CSize(MAIN_DLG_WIDTH / 4 - 5));
#endif

	m_modelName.Empty();				// 모델이름 초기화

	SetTAB1Disp();
	SetLogFile();

	return TRUE;  // 컨트롤에 대한 포커스를 설정하지 않을 경우 TRUE를 반환합니다.
}
static void ParseOptions(
    _In_ PACE_FILTER_OPTIONS opt,
    _In_ int argc,
    _In_ TCHAR * argv[]
    ) {

    const static struct option long_options[] = {
        { _T("list-plugins"), no_argument, 0, _T('L') },
        { _T("list-importers"), no_argument, 0, _T('I') },
        { _T("list-filters"), no_argument, 0, _T('F') },
        { _T("list-writers"), no_argument, 0, _T('W') },

        { _T("importers"), required_argument, 0, _T('i') },
        { _T("filters"), required_argument, 0, _T('f') },
        { _T("writers"), required_argument, 0, _T('w') },
        { _T("invert-filters"), required_argument, 0, _T('r') },

        { _T("progression"), required_argument, 0, _T('p') },
        { _T("logfile"), required_argument, 0, _T('l') },
        { _T("dbglvl"), required_argument, 0, _T('d') },
        { _T("loglvl"), required_argument, 0, _T('d') },
        { _T("help"), no_argument, 0, _T('h') },
        { _T("usage"), no_argument, 0, _T('h') },

        { 0, 0, 0, 0 }
    };

    int curropt = 0;
    BOOL bExitAfterOpt = FALSE;
    LPTSTR filter = NULL;
    LPTSTR ctx = NULL;

    //
    // Default options
    //
    SetLogLevel(DEFAULT_OPT_DEBUGLEVEL);
    opt->misc.progression = DEFAULT_OPT_PROGRESSION;

    //
    // Parsing
    //
    while ((curropt = getopt_long_only(argc, argv, EMPTY_STR, long_options, NULL)) != -1) {
        switch (curropt) {
            //
            // List
            //
        case _T('L'):
            SetLogLevel(_T("NONE"));
            ListImporters();
            ListFilters();
            ListWriters();
            ExitProcess(EXIT_SUCCESS);
            break;

        case _T('I'):
            SetLogLevel(_T("NONE"));
            ListImporters();
            bExitAfterOpt = TRUE;
            break;

        case _T('F'):
            SetLogLevel(_T("NONE"));
            ListFilters();
            bExitAfterOpt = TRUE;
            break;

        case _T('W'):
            SetLogLevel(_T("NONE"));
            ListWriters();
            bExitAfterOpt = TRUE;
            break;

            //
            // Plugins
            //
        case _T('i'):
            opt->names.importers = optarg;
            opt->plugins.numberOfImporters = PluginLoadImporters(opt->names.importers, opt->plugins.importers, PLUGIN_MAX_IMPORTERS);
            break;

        case _T('f'):
            opt->names.filters = optarg;
            opt->plugins.numberOfFilters = PluginLoadFilters(opt->names.filters, opt->plugins.filters, PLUGIN_MAX_FILTERS);
            break;

        case _T('w'):
            opt->names.writers = optarg;
            opt->plugins.numberOfWriters = PluginLoadWriters(opt->names.writers, opt->plugins.writers, PLUGIN_MAX_WRITERS);
            break;

        case _T('r'):
            opt->names.inverted = optarg;

            DWORD i = 0;
            filter = NULL;
            ctx = NULL;

            // TODO : invert after filters (numOfF == 0)

            while (StrNextToken(opt->names.inverted, ",", &ctx, &filter)) {
                for (i = 0; i < PLUGIN_MAX_FILTERS; i++) {
                    if (PLUGIN_IS_LOADED(&opt->plugins.filters[i])) {
                        if (STR_EQ(filter, PLUGIN_GET_NAME(&opt->plugins.filters[i]))) {
                            LOG(Info, SUB_LOG(_T("Inverting filter <%s>")), filter);
                            opt->plugins.filters[i].inverted = TRUE;
                            break;
                        }
                    }
                }
                if (i == PLUGIN_MAX_FILTERS) {
                    FATAL(_T("Trying to invert a non-loaded filter : <%s>"), filter);
                }
            }
            break;

            //
            // Misc
            //
        case _T('p'):
            opt->misc.progression = _tstoi(optarg);
            LOG(Info, SUB_LOG(_T("Printing progression every <%u> ACE")), opt->misc.progression);
            break;

        case _T('l'):
            opt->misc.logfile = optarg;
            SetLogFile(opt->misc.logfile);
            break;

        case _T('d'):
            opt->misc.loglvl = optarg;
            SetLogLevel(opt->misc.loglvl);
            break;

        case _T('h'):
            opt->misc.showHelp = TRUE;
            break;

        default:
            FATAL(_T("Unknown option"));
            break;
        }
    }


    LPTSTR optname = NULL;
    LPTSTR optval = NULL;
    int i = 0;

    for (i = optind; i < argc; i++) {
        ctx = NULL;

        StrNextToken(argv[i], "=", &ctx, &optname);
        optval = ctx; //We do not use StrNextToken here because optval can contain an equal sign.

        if (!optname || !optval) {
            FATAL(_T("Cannot parse plugin option <%s> (must be in format name=value)"), argv[i]);
        }
        else {
            LOG(Dbg, _T("Adding plugin option <%s : %s>"), optname, optval);
            AddStrPair(&gs_PluginOptions.end, optname, optval);
            if (!gs_PluginOptions.head) {
                gs_PluginOptions.head = gs_PluginOptions.end;
            }
        }
    }

    if (bExitAfterOpt) {
        ExitProcess(EXIT_SUCCESS);
    }
}