示例#1
0
文件: error.c 项目: Kakama/denice
// Print formatted error and if error is fatal, terminate
void error(int fatal, char* format, ...){
	char str[256];
	va_list args;
	va_start(args, format);
	// put the error msg in local array
	vsnprintf(str, 256, format, args);
	va_end(args);
	// print it out
	fprintf(stderr, "%s", str);
	
	if(fatal){
		fprintf(stderr,"Fatal error... Exiting.\n");
		exit(1);
	}
	else if(I && irc_is_connected(I)){
		// generate ERROR event to handle in scripts
		const char** strp = malloc(sizeof(char*));
		strp[0] = str;
		fprintf(stderr,"Generating ERROR event...\n");
		if(str[strlen(str)-1] == '\n')
			str[strlen(str)-1] = '\0';
		event_generic(I, "ERROR", "(core)", strp, 1);
		free(strp);
	}
	
}
示例#2
0
int irc_run(irc_session_t * session) {
    if (session->state != LIBIRC_STATE_CONNECTING) {
        session->lasterror = LIBIRC_ERR_STATE;
        return 1;
    }

    while (irc_is_connected(session)) {
        const long timeout_ms = 750;

        fdwatch_zero();
        fdwatch_add_fd(session->sock);

        irc_add_select_descriptors(session);

        if (fdwatch(timeout_ms) < 0) {
            if (socket_error() == EINTR)
                continue;

            session->lasterror = LIBIRC_ERR_TERMINATED;
            return 1;
        }
        
        if (session->callbacks.keep_alive_callback) {
            session->callbacks.keep_alive_callback(session);
        }

        if (irc_process_select_descriptors(session))
            return 1;
    }

    return 0;
}
示例#3
0
void ServerState::prepareConnecting(Server &server, fd_set &setinput, fd_set &setoutput, int &maxfd)
{
	/*
	 * The connect function will either fail if the hostname wasn't resolved
	 * or if any of the internal functions fail.
	 *
	 * It returns success if the connection was successful but it does not
	 * mean that connection is established.
	 *
	 * Because this function will be called repeatidly from the
	 * ServerManager, if the connection was started and we're still not
	 * connected in the specified timeout time, we mark the server
	 * as disconnected.
	 *
	 * Otherwise, the libircclient event_connect will change the state.
	 */
	const ServerInfo &info = server.info();

	if (m_started) {
		const ServerSettings &settings = server.settings();

		if (m_timer.elapsed() > static_cast<unsigned>(settings.recotimeout * 1000)) {
			Logger::warning() << "server " << info.name << ": timeout while connecting" << std::endl;
			server.next(ServerState::Disconnected);
		} else if (!irc_is_connected(server.session())) {
			Logger::warning() << "server " << info.name << ": error while connecting: "
					  << irc_strerror(irc_errno(server.session())) << std::endl;

			if (settings.recotimeout > 0) {
				Logger::warning() << "server " << info.name << ": retrying in " << settings.recotimeout << " seconds" << std::endl;
			}

			server.next(ServerState::Disconnected);
		} else {
			irc_add_select_descriptors(server.session(), &setinput, &setoutput, &maxfd);
		}
	} else {
		/*
		 * This is needed if irccd is started before DHCP or if
		 * DNS cache is outdated.
		 *
		 * For more information see bug #190.
		 */
#if !defined(_WIN32)
		(void)res_init();
#endif
		Logger::info() << "server " << info.name << ": trying to connect to " << info.host << ", port " << info.port << std::endl;

		if (!connect(server)) {
			Logger::warning() << "server " << info.name << ": disconnected while connecting: "
					  << irc_strerror(irc_errno(server.session())) << std::endl;
			server.next(ServerState::Disconnected);
		} else {
			m_started = true;
		}
	}
}
示例#4
0
void ServerState::prepareConnected(Server &server, fd_set &setinput, fd_set &setoutput, int &maxfd)
{
	if (!irc_is_connected(server.session())) {
		const ServerSettings &settings = server.settings();

		Logger::warning() << "server " << server.info().name << ": disconnected" << std::endl;

		if (settings.recotimeout > 0) {
			Logger::warning() << "server " << server.info().name << ": retrying in "
					  << settings.recotimeout << " seconds" << std::endl;
		}

		server.next(ServerState::Disconnected);
	} else {
		irc_add_select_descriptors(server.session(), &setinput, &setoutput, &maxfd);
	}
}
int irc_run (irc_session_t * session)
{
	if ( session->state != LIBIRC_STATE_CONNECTING )
	{
		session->lasterror = LIBIRC_ERR_STATE;
		return 1;
	}

	while ( irc_is_connected(session) )
	{
		struct timeval tv;
		fd_set in_set, out_set;
		int maxfd = 0;

		tv.tv_usec = 250000;
		tv.tv_sec = 0;

		// Init sets
		FD_ZERO (&in_set);
		FD_ZERO (&out_set);

		irc_add_select_descriptors (session, &in_set, &out_set, &maxfd);

		if ( select (maxfd + 1, &in_set, &out_set, 0, &tv) < 0 )
		{
			if ( socket_error() == EINTR )
				continue;

			session->lasterror = LIBIRC_ERR_TERMINATED;
			return 1;
		}

		if ( irc_process_select_descriptors (session, &in_set, &out_set) )
			return 1;
	}

	return 0;
}
示例#6
0
void IRCSelect() {

// Make sure that all the IRC sessions are connected
if( !irc_is_connected( sysconfig.irc_session ) ) {
	return;
}

// Create the structures for select()
struct timeval tv;
fd_set in_set, out_set;
int maxfd = 0;

// Wait 0.25 sec for the events
tv.tv_usec = 250000;
tv.tv_sec = 0;

// Initialize the sets
FD_ZERO (&in_set);
FD_ZERO (&out_set);

// Add the IRC session descriptors - call irc_add_select_descriptors() for each active session
irc_add_select_descriptors( sysconfig.irc_session, &in_set, &out_set, &maxfd );

// Call select()
if( ( select(maxfd + 1, &in_set, &out_set, 0, &tv) < 0 ) && ( sysconfig.shutdown == false ) ) {
	error("IRC Select error");
	return;
}

// Call irc_process_select_descriptors() for each session with the descriptor set
if ( irc_process_select_descriptors(sysconfig.irc_session, &in_set, &out_set) && ( sysconfig.shutdown == false ) ) {
		error("IRC Session Error");
}


return;
}
示例#7
0
/*
====================
IRC_SessionIsConnected

Returns true if the session handle is currently connected to an IRC server.
====================
*/
qboolean IRC_SessionIsConnected(int handle) {
    return IS_VALID_IRC_SESSION(handle) && irc_is_connected(irc_sessions[handle].session);
}
wxThread::ExitCode CslIrcThread::Entry()
{
    int maxfd,error;
    struct timeval timeout;
    fd_set readSet,writeSet;
    CslIrcContext *context=NULL;
    wxInt32 pos=0,count=0,termcount=10;

    m_mutex.Lock();

    while (termcount)
    {
        if (m_terminate)
            termcount--;

        m_section.Enter();
        count=m_contexts.GetCount();
        if (count)
            context=m_contexts.Item((pos=pos+1>=count ? 0:pos+1));
        else
            context=NULL;
        m_section.Leave();

        if (!context)
        {
            if (!m_terminate)
                m_condition->Wait();
            continue;
        }

        if (!context->Disconnecting && !irc_is_connected(context->Session))
        {
            if (irc_connect(context->Session,U2A(context->Server->Address),
                            context->Server->Port,NULL,U2A(context->Server->Network->Nick),
                            U2A(CSL_NAME_SHORT_STR),NULL))
            {
                LibIrcError(context,irc_errno(context->Session));
                continue;
            }
        }

        FD_ZERO(&readSet);
        FD_ZERO(&writeSet);
        timeout.tv_sec=0;
        timeout.tv_usec=max(50000,200000/count);
        maxfd=0;

        irc_add_select_descriptors(context->Session,&readSet,&writeSet,&maxfd);

        if (select(maxfd+1,&readSet,&writeSet,NULL,&timeout)<0)
        {
            LOG_DEBUG("select failed: %s\n",strerror(errno));
            if (errno==EINTR)
                continue;
        }

        if (irc_process_select_descriptors(context->Session,&readSet,&writeSet))
            if ((error=irc_errno(context->Session)))
                LibIrcError(context,error);
    }

    m_mutex.Unlock();

    return 0;
}
示例#9
0
////////////////////////////////////////////////////////////////////////////////
// update
eSysStateReturn GaMatchmakingState::main()
{
	BcScopedLock< BcMutex > Lock( Lock_ );
	BcReal Delta = SysKernel::pImpl()->getFrameTime();

	switch( HandshakeState_ )
	{
	case HSS_STUN:
		{
			// Only do once.
			if( MappedHandshakeAddr_ == 0 )
			{
				if( doSTUN() )
				{
					SysID_ = static_cast< BcU32 >( BcHash( (BcU8*)&MappedHandshakeAddr_, sizeof( MappedHandshakeAddr_ ) ) ); // Hash the mapped address to we don't broadcast it.
					if( MappedHandshakeAddr_ != 0 )
					{
						HandshakeState_ = HSS_IDLE;
					}
				}
				else
				{
					HandshakeState_ = HSS_STUN;
				}
			}
			else
			{
				HandshakeState_ = HSS_IDLE;
			}
		}
		break;
	case HSS_IDLE:
		{
			ConnectTimer_ -= Delta;

			if( ConnectTimer_ < 0.0f )
			{
				if( pSession_ == NULL )
				{
					pSession_ = irc_create_session( &Callbacks_ );
				}

				if( pSession_ != NULL && !irc_is_connected( pSession_ ) )
				{
					irc_set_ctx( pSession_, this );

					std::string Channel = "#testchannel";
					BcFile File;
					if( File.open( "config.json" ) )
					{
						char* pData = new char[ File.size() ];
						File.read( pData, File.size() );
						Json::Reader Reader;
		
						Json::Value Root;
						if( Reader.parse( pData, pData + File.size(), Root ) )
						{
							Channel = Root["channel"].asCString();
						}
						delete [] pData;
					}

					BcSPrintf( ScreenName_, "%s_%x", "PSY", BcRandom::Global.rand() );
					BcSPrintf( Channel_, Channel.c_str() );

					// Connect to the server.
					int RetVal = irc_connect( pSession_, "www.neilo.gd", 8000, NULL, ScreenName_, ScreenName_, ScreenName_ );

					if( RetVal == 0 )
					{
						// Start the thread to tick the client.
						BcThread::start( "EvtBridgeIRC" );

						ClientID_ = BcErrorCode;
						RemoteHandshakeAddr_ = 0;
						RemoteHandshakePort_ = 0;
						//LocalHandshakeAddr_ = 0;
						//LocalHandshakePort_ = 0;
						//MappedHandshakeAddr_ = 0;
						//MappedHandshakePort_ = 0;
						HandshakeState_ = HSS_WAIT_INVITE;
					}
					else
					{
						BcThread::join();

						irc_destroy_session( pSession_ );
						pSession_ = NULL;
					}
				}
			}
		}
		break;

	case HSS_WAIT_INVITE:
		{
			InviteTimer_ -= Delta;

			if( InviteTimer_ < 0.0f )
			{
				InviteTimer_ = BcAbs( BcRandom::Global.randReal() ) * 5.0f + 5.0f;

				// Send play with me message to channel.

				BcChar PlayBuffer[256];
				BcSPrintf( PlayBuffer, "REQ:%u", SysID_ );
				irc_cmd_msg( pSession_, Channel_, PlayBuffer );
			}
		}
		break;

	case HSS_WAIT_ADDR:
		{
			HandshakeTimer_ -= Delta;

			if( HandshakeTimer_ < 0.0f )
			{
				HandshakeState_ = HSS_WAIT_INVITE;
			}
		}
		break;

	case HSS_COMPLETE:
		{
			BcPrintf("GaMatchmakingState: Complete! ClientID of ours is %u\n", ClientID_);
			return sysSR_FINISHED;
		}
		break;
	}

	if( HandshakeState_ != HSS_STUN )
	{
		if( HandshakeState_ != HSS_IDLE && ( pSession_ == NULL || !irc_is_connected( pSession_ ) ) )
		{
			BcSleep( 0.1f );
			BcThread::join();
			BcSleep( 0.1f );
			if( pSession_ != NULL )
			{
				irc_destroy_session( pSession_ );
				pSession_ = NULL;
			}
			HandshakeState_ = HSS_IDLE;
			ConnectTimer_ = 10.0f;
		}
	}

	return sysSR_CONTINUE;
}
示例#10
0
//Ok, so here goes nothing...
void iohtmlFunc_ajax( ReplyDataPtr cnt ) {
	#if IRCBOT_SUPPORT
	ConfigArrayPtr settings[2];
	#endif
	int a, c, id, numbuild;
	int64_t b;
	int64_t bsums[CMD_BLDG_NUMUSED+1];
	int64_t usums[CMD_UNIT_NUMUSED];
	const char *typestring, *idstring, *refer;
	char CHECKER[256];
	char timebuf[512];
	dbMainEmpireDef empired;
	dbBuildPtr build;
	dbUserMainDef maind;
	proginfoDef pinfod;
	urlinfoPtr urlp;
	cpuInfo cpuinfo;
	time_t tint;
	struct sysinfo sysinfod;

refer = idstring = typestring = NULL;
cpuGetInfo( &cpuinfo );
getsys_infos( &pinfod );
if( sysinfo(&sysinfod) != 0 ) {
	critical( "Failure getting system infomation... Critical failure." );
	sysconfig.shutdown = true; return;
}

idstring = iohtmlVarsFind( cnt, "id" );
typestring = iohtmlVarsFind( cnt, "typ" );

refer = iohtmlHeaderFind(cnt, "Referer");

if( ( id = iohtmlIdentify( cnt, 2 ) ) >= 0 ) {
	if( dbUserMainRetrieve( id, &maind ) < 0 )
		goto BAILAJAX;
	else if( dbEmpireGetInfo( maind.empire, &empired ) < 0 )
		goto BAILAJAX;

}

if( ( typestring ) && ( refer ) ) {
	urlp = parse_url(refer);
	refer = urlp->path;
	httpString( cnt, "<?xml version=\"1.0\"?>" );
	httpPrintf( cnt, "<xml>" );
	//Begin XML generation, we only make one request now... so we have to structure carefully!
	if( !strcmp(typestring,"ticker") ) {
		//Send basic tick info, and check if user is loged in.
		httpPrintf( cnt, "<pass>%d</pass>", ( id != -1 ) ? ( ( bitflag( ((cnt->session)->dbuser)->flags, CMD_USER_FLAGS_ACTIVATED ) ) ? true : false ) : false );
		if( refer )
			httpPrintf( cnt, "<page>%s</page>", refer );
		httpPrintf( cnt, "<u_online>%d</u_online><u_activated>%d</u_activated>", dbRegisteredInfo[DB_TOTALS_USERS_ONLINE], dbRegisteredInfo[DB_TOTALS_USERS_ACTIVATED] );
		httpPrintf( cnt, "<time><next>%d</next><week>%d</week><year>%d</year></time>", (int)fmax( 0.0, ( ticks.next - time(0) ) ), ticks.number % 52, ticks.number / 52 );
		if( !strcmp(refer,"status") ) {
			snprintf( CHECKER, sizeof(CHECKER), "%lu bytes ( %5.1f mb )", pinfod.stvsize, pinfod.stvsize  / megabyte );
			httpString( cnt, "<general>" );
			httpPrintf( cnt, "<servpriority>%ld</servpriority>", pinfod.stpriority );
			httpPrintf( cnt, "<servthreads>%ld</servthreads>", pinfod.threads );
			httpString( cnt, "</general>" );
			httpString( cnt, "<memory>" );
			httpPrintf( cnt, "<memused>%s</memused>", CHECKER );
			httpPrintf( cnt, "<memavbytes>%ld bytes</memavbytes>", sysinfod.freeram );
			httpPrintf( cnt, "<memavmeg>( %4.1f mb )</memavmeg>", (sysinfod.freeram  / megabyte ) );


			httpPrintf( cnt, "<totalswapbytes>%ld bytes</totalswapbytes>", sysinfod.totalswap );
			httpPrintf( cnt, "<totalswapmeg>( %5.1f mb )</totalswapmeg>", (sysinfod.totalswap / megabyte ) );

			httpPrintf( cnt, "<freeswapbytes>%ld bytes</freeswapbytes>", sysinfod.freeswap );
			httpPrintf( cnt, "<freeswapmeg>( %5.1f mb )</freeswapmeg>", (sysinfod.freeswap  / megabyte ) );

			httpPrintf( cnt, "<bufferbytes>%ld bytes</bufferbytes>", sysinfod.bufferram );
			httpPrintf( cnt, "<bufermeg>( %5.1f mb )</bufermeg>", (sysinfod.bufferram  / megabyte ) );

			httpPrintf( cnt, "<sharedbytes>%ld bytes</sharedbytes>", sysinfod.sharedram );
			httpPrintf( cnt, "<sharedmeg>( %5.1f mb )</sharedmeg>", (sysinfod.sharedram  / megabyte ) );

			time( &tint );
			strftime(timebuf,512,"%a, %d %b %G %T %Z", localtime( &tint ) );
			httpPrintf( cnt, "<timeserver>%s</timeserver>", timebuf );
			strftime(timebuf,512,"%a, %d %b %G %T %Z", gmtime( &tint ) );
			httpPrintf( cnt, "<timegmt>%s</timegmt>", timebuf );
			
			httpPrintf( cnt, "<strss>%lu pages</strss>", pinfod.strss );
			httpPrintf( cnt, "</memory>" );
			httpString( cnt, "<cpu>" );
			httpPrintf( cnt, "<cpuprocs>%d</cpuprocs>", sysinfod.procs );
			httpPrintf( cnt, "<cpuloads>%f (1 min) - %f (5 mins) - %f (15 mins)</cpuloads>",pinfod.loadavg[0],pinfod.loadavg[1],pinfod.loadavg[2]);
			httpPrintf( cnt, "<cputotal>%.3f %%</cputotal>", pinfod.userload + pinfod.kernelload );
			httpPrintf( cnt, "<cpukernel>%.3f %%</cpukernel>", pinfod.kernelload );
			httpPrintf( cnt, "<cpuuser>%.3f %%</cpuuser>", pinfod.userload );
			httpString( cnt, "</cpu>" );
			
			#if IRCBOT_SUPPORT
			if( sysconfig.irc_enabled ) {
				if( irc_is_connected(sysconfig.irc_session) ) {
					settings[0] = GetSetting( "IRC Host" );
					settings[1] = GetSetting( "IRC Channel" );
					snprintf( CHECKER, sizeof(CHECKER), "Enabled (Host:%s, Channel:%s)", settings[0]->string_value, settings[1]->string_value );
				} else {
					snprintf( CHECKER, sizeof(CHECKER), "%s", "Enabled but not connected" );
				}
			} else {
				snprintf( CHECKER, sizeof(CHECKER), "%s", "Disabled");
			}
			httpPrintf( cnt, "<botstatus>%s</botstatus>", CHECKER );
			#endif

		//End Status block -- Start user block
		}
		if( id < 0 )
			goto ENDXML;
		a = dbUserNewsGetFlags( id );
		//OK, so they are loged in... time to send some info. Lets start with the header. =)
		httpString( cnt, "<header>" );
		httpPrintf( cnt, "<networth>%lld</networth>", (long long)maind.networth );
		httpString( cnt, "<notification>" );
		httpPrintf( cnt, "<mail>%d</mail>",  ( a & CMD_NEWS_FLAGS_MAIL ) ? true : false );
		httpPrintf( cnt, "<build>%d</build>",  ( a & CMD_NEWS_FLAGS_BUILD ) ? true : false );
		httpPrintf( cnt, "<aid>%d</aid>", ( a & CMD_NEWS_FLAGS_AID ) ? true : false );
		httpPrintf( cnt, "<fleet>%d</fleet>", ( a & CMD_NEWS_FLAGS_ATTACK ) ? 1 : ( ( a & CMD_NEWS_FLAGS_FLEET ) ? 2 : false ) );
		httpString( cnt, "</notification>" );
		httpString( cnt, "<ressources>" );
		for( a = 0 ; a < CMD_RESSOURCE_NUMUSED ; a++ ) {
			snprintf( CHECKER, sizeof(CHECKER),"%s",cmdRessourceName[a]);
			for(b = 0; CHECKER[b]; b++){
				CHECKER[b] = tolower(CHECKER[b]);
			}
			httpPrintf( cnt, "<%s>%lld</%s>", CHECKER, (long long)maind.ressource[a], CHECKER );
		}
		httpPrintf( cnt, "<population>%lld</population>", (long long)maind.ressource[CMD_RESSOURCE_POPULATION] );
		httpString( cnt, "</ressources>" );
		httpString( cnt, "</header>" );
		httpPrintf( cnt, "<%s>", refer );
		//End Header block -- Start HQ block
		if( !strcmp(refer,"hq") ) {
			httpString( cnt, "<readiness>" );
			for( a = 0 ; a < CMD_READY_NUMUSED ; a++ ) {
				httpPrintf( cnt, "<%sready>%d</%sready>", cmdReadyName[a], maind.readiness[a] >> 16, cmdReadyName[a] );
			}
			httpString( cnt, "</readiness>" );
		httpPrintf( cnt, "<planets>%d</planets>", maind.planets );
		//End HQ block -- Start Council block
		} else if( !strcmp(refer,"council") ) {