Example #1
0
bool Master::Run(int argc, char ** argv)
{
	char * config_file = (char*)default_config_file;
	char * realm_config_file = (char*)default_realm_config_file;

	int file_log_level = DEF_VALUE_NOT_SET;
	int screen_log_level = DEF_VALUE_NOT_SET;
	int do_check_conf = 0;
	int do_version = 0;
	int do_cheater_check = 0;
	int do_database_clean = 0;
	time_t curTime;

	struct arctic_option longopts[] =
	{
		{ "checkconf",			arctic_no_argument,			&do_check_conf,			1		},
		{ "screenloglevel",		arctic_required_argument,		&screen_log_level,	1		},
		{ "fileloglevel",		arctic_required_argument,		&file_log_level,	-1		},
		{ "version",			arctic_no_argument,			&do_version,			1		},
		{ "conf",				arctic_required_argument,		NULL,				'c'		},
		{ "realmconf",			arctic_required_argument,		NULL,				'r'		},
		{ 0, 0, 0, 0 }
	};

	char c;
	while ((c = arctic_getopt_long_only(argc, argv, ":f:", longopts, NULL)) != -1)
	{
		switch (c)
		{
		case 'c':
			config_file = new char[strlen(arctic_optarg)];
			strcpy(config_file, arctic_optarg);
			break;

		case 'r':
			realm_config_file = new char[strlen(arctic_optarg)];
			strcpy(realm_config_file, arctic_optarg);
			break;

		case 0:
			break;
		default:
			sLog.m_fileLogLevel = -1;
			sLog.m_screenLogLevel = 3;
			printf("Usage: %s [--checkconf] [--conf <filename>] [--realmconf <filename>] [--version]\n", argv[0]);
			return true;
		}
	}
	/* set new log levels if used as argument*/
	if( screen_log_level != (int)DEF_VALUE_NOT_SET )
		sLog.SetScreenLoggingLevel(screen_log_level);

	if( file_log_level != (int)DEF_VALUE_NOT_SET )
		sLog.SetFileLoggingLevel(file_log_level);

	// Startup banner
	UNIXTIME = time(NULL);
	g_localTime = *localtime(&UNIXTIME);

	sLog.outString("===============================================================================");
	printf(BANNER, BUILD_REVISION, CONFIG, PLATFORM_TEXT, ARCH);
	sLog.outString("===============================================================================");
	sLog.outString("");
	sLog.outString("The key combination <Ctrl-C> will safely shut down the server at any time.");
	Log.Line();
	if( do_check_conf )
	{
		Log.Notice( "Config", "Checking config file: %s", config_file );
		if( Config.MainConfig.SetSource(config_file, true ) )
			Log.Success( "Config", "Passed without errors." );
		else
			Log.Warning( "Config", "Encountered one or more errors." );

		Log.Notice( "Config", "Checking config file: %s\n", realm_config_file );
		if( Config.RealmConfig.SetSource( realm_config_file, true ) )
			Log.Success( "Config", "Passed without errors.\n" );
		else
			Log.Warning( "Config", "Encountered one or more errors.\n" );

		/* test for die variables */
		string die;
		if( Config.MainConfig.GetString( "die", "msg", &die) || Config.MainConfig.GetString("die2", "msg", &die ) )
			Log.Warning( "Config", "Die directive received: %s", die.c_str() );

		return true;
	}

	// use these log_level until we are fully started up.
	sLog.Init(-1, 3);
#ifndef WIN32
	if(geteuid() == 0 || getegid() == 0)
		Log.LargeErrorMessage( LARGERRORMESSAGE_WARNING, "You are running ArcTic as root.", "This is not needed, and may be a possible security risk.", "It is advised to hit CTRL+C now and", "start as a non-privileged user.", NULL);
#endif

	InitRandomNumberGenerators();
	Log.Success( "Rnd", "Initialized Random Number Generators." );

	ThreadPool.Startup();
	uint32 LoadingTime = getMSTime();

	Log.Notice( "Config", "Loading Config Files...\n" );
	if( Config.MainConfig.SetSource( config_file ) )
		Log.Success( "Config", ">> WorldServer.conf" );
	else
	{
		Log.Error( "Config", ">> WorldServer.conf" );
		return false;
	}

	string die;
	if( Config.MainConfig.GetString( "die", "msg", &die) || Config.MainConfig.GetString( "die2", "msg", &die ) )
	{
		Log.Warning( "Config", "Die directive received: %s", die.c_str() );
		return false;
	}	

	if(Config.RealmConfig.SetSource(realm_config_file))
		Log.Success( "Config", ">> Realms.conf" );
	else
	{
		Log.Error( "Config", ">> Realms.conf" );
		return false;
	}

	if( !_StartDB() )
	{
		Database::CleanupLibs();
		return false;
	}

	Log.Line();
	sLog.outString( "" );

	new EventMgr;
	new World;

	// open cheat log file
	Anticheat_Log = new SessionLogWriter(FormatOutputString( "logs", "cheaters", false).c_str(), false );
	GMCommand_Log = new SessionLogWriter(FormatOutputString( "logs", "gmcommand", false).c_str(), false );
	Player_Log = new SessionLogWriter(FormatOutputString( "logs", "players", false).c_str(), false );

	/* load the config file */
	sWorld.Rehash(false);

	// Initialize Opcode Table
	WorldSession::InitPacketHandlerTable();

	string host = Config.MainConfig.GetStringDefault( "Listen", "Host", DEFAULT_HOST );
	int wsport = Config.MainConfig.GetIntDefault( "Listen", "WorldServerPort", DEFAULT_WORLDSERVER_PORT );

	new ScriptMgr;

	if( !sWorld.SetInitialWorldSettings() )
	{
		Log.Error( "Server", "SetInitialWorldSettings() failed. Something went wrong? Exiting." );
		return false;
	}

	g_bufferPool.Init();
	sWorld.SetStartTime(uint32(UNIXTIME));

	WorldRunnable * wr = new WorldRunnable();
	ThreadPool.ExecuteTask(wr);

	_HookSignals();

	ConsoleThread * console = new ConsoleThread();
	ThreadPool.ExecuteTask(console);

	uint32 realCurrTime, realPrevTime;
	realCurrTime = realPrevTime = getMSTime();

	// Socket loop!
	uint32 start;
	uint32 diff;
	uint32 last_time = now();
	uint32 etime;

	// Start Network Subsystem
	DEBUG_LOG("Server","Starting network subsystem..." );
	new SocketMgr;
	new SocketGarbageCollector;
	sSocketMgr.SpawnWorkerThreads();

	if( StartConsoleListener() )
	{
#ifdef WIN32
		ThreadPool.ExecuteTask( GetConsoleListener() );
#endif
		Log.Success("RemoteConsole", "Started and listening on port %i",Config.MainConfig.GetIntDefault("RemoteConsole", "Port", 8092));
	}
	else
		DEBUG_LOG("RemoteConsole", "Not enabled or failed listen.");

	LoadingTime = getMSTime() - LoadingTime;
	Log.Success("Server","Ready for connections. Startup time: %ums\n", LoadingTime );

	//Update sLog to obey config setting
	sLog.Init(Config.MainConfig.GetIntDefault("LogLevel", "File", -1),Config.MainConfig.GetIntDefault("LogLevel", "Screen", 1));

	/* write pid file */
	FILE * fPid = fopen( "conf/WorldServer.pid", "w" );
	if( fPid )
	{
		uint32 pid;
#ifdef WIN32
		pid = GetCurrentProcessId();
#else
		pid = getpid();
#endif
		fprintf( fPid, "%u", (unsigned int)pid );
		fclose( fPid );
	}
#ifdef WIN32
	HANDLE hThread = GetCurrentThread();
#endif

	uint32 loopcounter = 0;
	//ThreadPool.Gobble();

#ifndef CLUSTERING
	/* Connect to realmlist servers / logon servers */
	new LogonCommHandler();
	sLogonCommHandler.Startup();

	// Create listener
	ListenSocket<WorldSocket> * ls = new ListenSocket<WorldSocket>(host.c_str(), wsport);
    bool listnersockcreate = ls->IsOpen();
#ifdef WIN32
	if( listnersockcreate )
		ThreadPool.ExecuteTask(ls);
#endif
	while( !m_stopEvent && listnersockcreate )
#else
	new ClusterInterface;
	sClusterInterface.ConnectToRealmServer();
	while(!m_stopEvent)
#endif
	{
		start = now();
		diff = start - last_time;
		if(! ((++loopcounter) % 10000) )		// 5mins
		{
			ThreadPool.ShowStats();
			ThreadPool.IntegrityCheck(); // Checks if THREAD_RESERVE is met
			g_bufferPool.Optimize();
		}

		/* since time() is an expensive system call, we only update it once per server loop */
		curTime = time(NULL);
		if( UNIXTIME != curTime )
		{
			UNIXTIME = time(NULL);
			g_localTime = *localtime(&curTime);
		}

		sSocketGarbageCollector.Update();

		/* UPDATE */
		last_time = now();
		etime = last_time - start;
		if( 50 > etime )
		{
#ifdef WIN32
			WaitForSingleObject(hThread, 50 - etime);
#else
			Sleep(50 - etime);
#endif
		}
	};

	// begin server shutdown
	Log.Notice("Shutdown", "Initiated at %s", ConvertTimeStampToDataTime( uint32(UNIXTIME)).c_str());
	bServerShutdown = true;

	_UnhookSignals();

    wr->Terminate();

	/* Shut down console system */
	CloseConsoleListener();
	console->terminate();
	delete console;

	if( lootmgr.is_loading )
	{
		Log.Notice("Shutdown", "Waiting for loot to finish loading...");
		while( lootmgr.is_loading )
			Sleep( 100 );
	}

	Log.Notice("CharacterLoaderThread", "Exiting...");
	sCLT.Terminate();

	sWorld.LogoutPlayers(); //(Also saves players).
	CharacterDatabase.Execute("UPDATE characters SET online = 0");

	// send a query to wake it up if its inactive
	Log.Notice("Database", "Clearing all pending queries...");

	// kill the database thread first so we don't lose any queries/data
	CharacterDatabase.EndThreads();
	WorldDatabase.EndThreads();

	Log.Notice("Server", "Shutting down random generator.");
	CleanupRandomNumberGenerators();

	Log.Notice( "WintergraspInternal", "Exiting..." );
	sWintergraspI.terminate();

	Log.Notice( "DayWatcherThread", "Exiting..." );
	sDayWatcher.terminate();

#ifndef CLUSTERING
	ls->Close();
#endif

	Log.Notice( "Network", "Shutting down network subsystem." );
#ifdef WIN32
	sSocketMgr.ShutdownThreads();
#endif
	sSocketMgr.CloseAll();

	sAddonMgr.SaveToDB();
	Log.Notice("AddonMgr", "~AddonMgr()");
	delete AddonMgr::getSingletonPtr();

	Log.Notice("AuctionMgr", "~AuctionMgr()");
	delete AuctionMgr::getSingletonPtr();

	Log.Notice("LootMgr", "~LootMgr()");
	delete LootMgr::getSingletonPtr();

	Log.Notice("MailSystem", "~MailSystem()");
	delete MailSystem::getSingletonPtr();

	ThreadPool.Shutdown();

#ifndef CLUSTERING
	delete ls;
#endif

	sLog.outString( "" );

	delete LogonCommHandler::getSingletonPtr();

	Log.Notice("World", "~World()");
	delete World::getSingletonPtr();

	sScriptMgr.UnloadScripts();
	delete ScriptMgr::getSingletonPtr();

	Log.Notice("EventMgr", "~EventMgr()");
	delete EventMgr::getSingletonPtr();

	Log.Notice("Database", "Closing Connections...");
	_StopDB();

	Log.Notice("Network", "Deleting Network Subsystem...");
	delete SocketMgr::getSingletonPtr();
	delete SocketGarbageCollector::getSingletonPtr();

#ifdef ENABLE_LUA_SCRIPTING
	sLog.outString("Deleting Script Engine...");
	LuaEngineMgr::getSingleton().Unload();
#endif
	// delete ScriptSystem;

	delete GMCommand_Log;
	delete Anticheat_Log;
	delete Player_Log;

	// remove pid
	remove("conf/WorldServer.pid");
	g_bufferPool.Destroy();

	Log.Notice("Shutdown", "Shutdown complete.");

#ifdef WIN32
	WSACleanup();
#endif
	return true;
}
Example #2
0
int main(int argc, char* argv[])
{
	// Program parameters
	unsigned long bit_size = DEFAULT_BITSIZE;
	unsigned long num_attribs = 0;
	unsigned long counter = 0;
	time_t expiry = std::time(NULL);
	std::string pub_key_filename;
	std::string priv_key_filename;
	std::string base_URI = DEFAULT_BASE_URI;
	int c = 0;
	
	// Add a year to expiry and round it down to 1 day
	struct tm* now = localtime(&expiry);
	now->tm_year = now->tm_year + 1;
	now->tm_hour = 0;
	now->tm_min = 0;
	now->tm_sec = 0;
	expiry = mktime(now);

	while ((c = getopt(argc, argv, "a:n:c:d:p:P:u:hv")) != -1)
	{
		switch (c)
		{
		case 'h':
			usage();
			return 0;
		case 'v':
			version();
			return 0;
		case 'a':
			num_attribs = strtoul(optarg, NULL, 10);
			break;
		case 'n':
			bit_size = strtoul(optarg, NULL, 10);
			break;
		case 'c':
			counter = strtoul(optarg, NULL, 10);
			break;
		case 'd':
			expiry = strtoul(optarg, NULL, 10);
			break;
		case 'p':
			pub_key_filename = std::string(optarg);
			break;
		case 'P':
			priv_key_filename = std::string(optarg);
			break;
		case 'u':
			base_URI = std::string(optarg);
			break;
		}
	}
	
	if (num_attribs <= 0)
	{
		fprintf(stderr, "Missing argument -a; please specify a number of attributes\n");
		
		return -1;
	}
	
	FILE* pub_key_file = stdout;
	FILE* priv_key_file = stdout;
	
	if (!pub_key_filename.empty())
	{
		pub_key_file = fopen(pub_key_filename.c_str(), "w");
		
		if (pub_key_file == NULL)
		{
			fprintf(stderr, "Failed to open %s for writing\n", pub_key_filename.c_str());
			
			return -1;
		}
		
		printf("Writing public key to %s\n", pub_key_filename.c_str());
	}
	
	if (!priv_key_filename.empty())
	{
		priv_key_file = fopen(priv_key_filename.c_str(), "w");
		
		if (priv_key_file == NULL)
		{
			fprintf(stderr, "Failed to open %s for writing\n", priv_key_filename.c_str());
			
			return -1;
		}
		
		printf("Writing private key to %s\n", priv_key_filename.c_str());
	}
	
	generate_key_pair(pub_key_file, priv_key_file, base_URI, num_attribs, bit_size, counter, expiry);
	
	if (!pub_key_filename.empty()) fclose(pub_key_file);
	if (!priv_key_filename.empty()) fclose(priv_key_file);
	
	return 0;
}
Example #3
0
void rspfLocalTm::now()
{
   time_t t = time(0);
   *this = *localtime(&t);
}
Example #4
0
/// Calculate the new weather
bool Weather::ReGenerate()
{
    if (!m_weatherChances)
    {
        m_type = WEATHER_TYPE_FINE;
        m_grade = 0.0f;
        return false;
    }

    /// Weather statistics:
    ///- 30% - no change
    ///- 30% - weather gets better (if not fine) or change weather type
    ///- 30% - weather worsens (if not fine)
    ///- 10% - radical change (if not fine)
    uint32 u = urand(0, 99);

    if (u < 30)
        return false;

    // remember old values
    WeatherType old_type = m_type;
    float old_grade = m_grade;

    //78 days between January 1st and March 20nd; 365/4=91 days by season
    // season source http://aa.usno.navy.mil/data/docs/EarthSeasons.html
    time_t gtime = sWorld->GetGameTime();
    struct tm * ltime = localtime(&gtime);
    uint32 season = ((ltime->tm_yday - 78 + 365)/91)%4;

    static char const* seasonName[WEATHER_SEASONS] = { "spring", "summer", "fall", "winter" };

    TC_LOG_INFO(LOG_FILTER_GENERAL, "Generating a change in %s weather for zone %u.", seasonName[season], m_zone);

    if ((u < 60) && (m_grade < 0.33333334f))                // Get fair
    {
        m_type = WEATHER_TYPE_FINE;
        m_grade = 0.0f;
    }

    if ((u < 60) && (m_type != WEATHER_TYPE_FINE))          // Get better
    {
        m_grade -= 0.33333334f;
        return true;
    }

    if ((u < 90) && (m_type != WEATHER_TYPE_FINE))          // Get worse
    {
        m_grade += 0.33333334f;
        return true;
    }

    if (m_type != WEATHER_TYPE_FINE)
    {
        /// Radical change:
        ///- if light -> heavy
        ///- if medium -> change weather type
        ///- if heavy -> 50% light, 50% change weather type

        if (m_grade < 0.33333334f)
        {
            m_grade = 0.9999f;                              // go nuts
            return true;
        }
        else
        {
            if (m_grade > 0.6666667f)
            {
                                                            // Severe change, but how severe?
                uint32 rnd = urand(0, 99);
                if (rnd < 50)
                {
                    m_grade -= 0.6666667f;
                    return true;
                }
            }
            m_type = WEATHER_TYPE_FINE;                     // clear up
            m_grade = 0;
        }
    }

    // At this point, only weather that isn't doing anything remains but that have weather data
    uint32 chance1 = m_weatherChances->data[season].rainChance;
    uint32 chance2 = chance1+ m_weatherChances->data[season].snowChance;
    uint32 chance3 = chance2+ m_weatherChances->data[season].stormChance;

    uint32 rnd = urand(0, 99);
    if (rnd <= chance1)
        m_type = WEATHER_TYPE_RAIN;
    else if (rnd <= chance2)
        m_type = WEATHER_TYPE_SNOW;
    else if (rnd <= chance3)
        m_type = WEATHER_TYPE_STORM;
    else
        m_type = WEATHER_TYPE_FINE;

    /// New weather statistics (if not fine):
    ///- 85% light
    ///- 7% medium
    ///- 7% heavy
    /// If fine 100% sun (no fog)

    if (m_type == WEATHER_TYPE_FINE)
    {
        m_grade = 0.0f;
    }
    else if (u < 90)
    {
        m_grade = (float)rand_norm() * 0.3333f;
    }
    else
    {
        // Severe change, but how severe?
        rnd = urand(0, 99);
        if (rnd < 50)
            m_grade = (float)rand_norm() * 0.3333f + 0.3334f;
        else
            m_grade = (float)rand_norm() * 0.3333f + 0.6667f;
    }

    // return true only in case weather changes
    return m_type != old_type || m_grade != old_grade;
}
Example #5
0
void
setthetime(char *p)
{
    struct tm *lt;
    struct timeval tv;
    char *dot, *t;
    int yearset = 0;

    for (t = p, dot = NULL; *t; ++t) {
        if (isdigit(*t))
            continue;
        if (*t == '.' && dot == NULL) {
            dot = t;
            continue;
        }
        badformat();
    }

    lt = localtime(&tval);

    lt->tm_isdst = -1;			/* correct for DST */

    if (dot != NULL) {			/* .SS */
        *dot++ = '\0';
        if (strlen(dot) != 2)
            badformat();
        lt->tm_sec = ATOI2(dot);
        if (lt->tm_sec > 61)
            badformat();
    } else
        lt->tm_sec = 0;

    switch (strlen(p)) {
    case 12:				/* cc */
        lt->tm_year = ATOI2(p) * 100 - TM_YEAR_BASE;
        yearset = 1;
    /* FALLTHROUGH */
    case 10:				/* yy */
        if (!yearset) {
            /* mask out current year, leaving only century */
            lt->tm_year = ((lt->tm_year / 100) * 100);
        }
        lt->tm_year += ATOI2(p);
    /* FALLTHROUGH */
    case 8:					/* mm */
        lt->tm_mon = ATOI2(p);
        if ((lt->tm_mon > 12) || !lt->tm_mon)
            badformat();
        --lt->tm_mon;			/* time struct is 0 - 11 */
    /* FALLTHROUGH */
    case 6:					/* dd */
        lt->tm_mday = ATOI2(p);
        if ((lt->tm_mday > 31) || !lt->tm_mday)
            badformat();
    /* FALLTHROUGH */
    case 4:					/* HH */
        lt->tm_hour = ATOI2(p);
        if (lt->tm_hour > 23)
            badformat();
    /* FALLTHROUGH */
    case 2:					/* MM */
        lt->tm_min = ATOI2(p);
        if (lt->tm_min > 59)
            badformat();
        break;
    default:
        badformat();
    }

    /* convert broken-down time to UTC clock time */
    if ((tval = mktime(lt)) < 0)
        errx(1, "specified date is outside allowed range");

    if (jflag)
        return;

    /* set the time */
    if (slidetime) {
        struct timeval tv_current;

        if (gettimeofday(&tv_current, NULL) == -1)
            err(1, "Could not get local time of day");

        tv.tv_sec = tval - tv_current.tv_sec;
        tv.tv_usec = 0;
        if (adjtime(&tv, NULL) == -1)
            errx(1, "adjtime");
    } else {
#ifndef SMALL
        logwtmp("|", "date", "");
#endif
        tv.tv_sec = tval;
        tv.tv_usec = 0;
        if (settimeofday(&tv, NULL))
            err(1, "settimeofday");
#ifndef SMALL
        logwtmp("{", "date", "");
#endif
    }

    if ((p = getlogin()) == NULL)
        p = "???";
    syslog(LOG_AUTH | LOG_NOTICE, "date set by %s", p);
}
Example #6
0
int main( int argc, char* argv[] ) {

  char mat_fn[MAX_FN_LEN+1];
  char maln_fn[MAX_FN_LEN+1];
  char fastq_out_fn[MAX_FN_LEN+1];
  char maln_root[MAX_FN_LEN+1];
  char ref_fn[MAX_FN_LEN+1];
  char frag_fn[MAX_FN_LEN+1];
  char adapter_code[2]; // place to keep the argument for -a (which adapter to trim)
  char* c_time; // place to keep asctime string
  char* test_id;

  int ich;
  int any_arg = 0;
  int Hard_cut = 0; // If 0 => use dynamic score cutoff, if > 0 use this instead
  int circular = 0; // Boolean, TRUE if reference sequence is circular
  int make_fastq = 0; // Boolean, TRUE if we should also output fastq database of seqs in assembly
  int seq_code = 0; // code to indicate sequence input format; 0 => fasta; 1 => fastq
  int do_adapter_trimming = 0; // Boolean, TRUE if we should try to trim
                               // adapter from input sequences
  int iterate = 0; //Boolean, TRUE means interate the assembly until convergence
  // on an assembled sequence
  int FINAL_ONLY = 0; //Boolean, TRUE means only write out the final assembly maln file
                      //         FALSE (default) means write out each one
  int ids_rest = 0; // Boolean, TRUE means restrict analysis to IDs in input file
  int repeat_filt = 0; //Boolean, TRUE means remove sequences that are repeats, 
                       // keeping best-scoring representative
  int repeat_qual_filt = 0; //Boolean, TRUE means remove sequences that are repeats,
                            // keeping best quality score sum representative
  int just_outer_coords = 1; // Boolean, TRUE means just use strand, start, and end to
                             // determine if sequences are redundant
  int SCORE_CUT_SET = 0; //Boolean, TRUE means user has set a length/score cutoff line
  int seen_seqs = 0;
  int hp_special = 0; // Boolean, TRUE means user wants hp gap special discount
  int distant_ref = 0; // Boolean, TRUE means the initial reference sequence is
                       // known to be distantly related so keep trying to align all
                       // sequences each round
  int kmer_filt_len = -1; // length of kmer filtering, if user wants it; otherwise
                          // special value of -1 indicates this is unset
  int soft_mask = 0; //Boolean; TRUE => do not use kmers that are all lower-case
                     //        FALSE => DO use all kmers, regardless of case
  int iter_num; // Number of iterations of assembly done
  int collapse = 0; // Boolean; TRUE => collapse input sequences in FSDB to improve
                    //                  sequence quality
                    //          FALSE => (default) keep all sequences
  double slope     = DEF_S; // Set these to default unless, until user changes
  double intercept = DEF_N; // them 
  MapAlignmentP maln, // Contains all fragments initially better
                      // than FIRST_ROUND_SCORE_CUTOFF
    culled_maln;      // Contains all fragments with scores
                      // better than SCORE_CUTOFF
  AlignmentP fw_align, rc_align, adapt_align;
  
  PSSMP ancsubmat   = init_flatsubmat();
  PSSMP rcancsubmat = revcom_submat(ancsubmat);
  const PSSMP flatsubmat  = init_flatsubmat();

  KPL* fkpa; // Place to keep forward kmer array if user requested kmer 
  KPL* rkpa; // Place to keep reverse kmer array if user requested kmer 
  IDsListP good_ids;
  FragSeqP frag_seq;
  PWAlnFragP front_pwaln, back_pwaln;
  FSDB fsdb; // Database to hold sequences to iterate over
  FILE* FF;
  time_t curr_time;


  char maln_root_def[] = "assembly.maln.iter";
  extern int optind;
  extern char* optarg;
  char neand_adapt[] = "GTCAGACACGCAACAGGGGATAGGCAAGGCACACAGGGGATAGG";
  char stand_adapt[] = "CTGAGACACGCAACAGGGGATAGGCAAGGCACACAGGGGATAGG";
  char user_def_adapt[128];
  char* adapter; // set to either neand_adapt or stand_adapt based on user preference
  adapter = neand_adapt; // Default is Neandertal
  char* assembly_cons;
  char* last_assembly_cons;
  int cc = 1; // consensus code for calling consensus base
  int i;

  /* Set the default output filename until the user overrides it */
  strcpy( maln_root, maln_root_def );


  /* Process command line arguments */
  while( (ich=getopt( argc, argv, "s:r:f:m:a:p:H:I:S:N:k:q:FTciuhDMUAC" )) != -1 ) {
    switch(ich) {
    case 'c' :
      circular = 1;
      break;
    case 'q' :
      make_fastq = 1;
      strcpy( fastq_out_fn, optarg );
    case 'C' :
      collapse = 1;
      break;
    case 'i' :
      iterate = 1;
      break;
    case 'h' :
      hp_special = 1;
      break;
    case 'u' :
      repeat_filt = 1;
      break;
    case 'A' :
      just_outer_coords = 0;
      break;
    case 'U' :
      repeat_qual_filt = 1;
      break;
    case 'D' :
      distant_ref = 1;
      break;
    case 'p' :
      cc = atoi( optarg );
      any_arg = 1;
      break;
    case 'I' :
      good_ids = parse_ids( optarg );
      ids_rest = 1;
      break;
    case 'H' :
      Hard_cut = atoi( optarg );
      if ( Hard_cut <= 0 ) {
	fprintf( stderr, "Hard cutoff (-H) must be positive\n" );
	help();
	exit( 0 );
      }
      any_arg = 1;
      break;
    case 'M' :
      soft_mask = 1;
      break;
    case 's' :
      strcpy( mat_fn, optarg );
      free( ancsubmat ); // trash the flat submat we initialized with
      ancsubmat   = read_pssm( mat_fn );
      free( rcancsubmat ); // trash the init rcsubmat, too
      rcancsubmat = revcom_submat( ancsubmat );
      any_arg = 1;
      break;
    case 'r' :
      strcpy( ref_fn, optarg );
      any_arg = 1;
      break;
    case 'k' :
      kmer_filt_len = atoi( optarg );
      any_arg = 1;
      break;
    case 'f' :
      strcpy( frag_fn, optarg );
      any_arg = 1;
      break;
    case 'm' :
      strcpy( maln_root, optarg );
      any_arg = 1;
      break;
    case 'T' :
      do_adapter_trimming = 1;
      break;
    case 'a' :
      if ( strlen( optarg ) > 127 ) {
	  fprintf( stderr, "That adapter is too big!\nMIA will use the standard adapter.\n" );
	  adapter = stand_adapt;
      }
      else {
	strcpy( user_def_adapt, optarg );
	  if ( strlen( user_def_adapt ) > 1 ) {
	    adapter = user_def_adapt;
	  }
	  else {
	    if ( !( (user_def_adapt[0] == 'n') ||
		    (user_def_adapt[0] == 'N') ) ) {
	      adapter = stand_adapt;
	    }
	    else {
	      adapter = neand_adapt;
	    }
	  }
      }
      break;
    case 'S' :
      slope = atof( optarg );
      SCORE_CUT_SET = 1;
      break;
    case 'N' :
      intercept = atof( optarg );
      SCORE_CUT_SET = 1;
      break;
    case 'F' :
      FINAL_ONLY = 1;
      break;
    default :
      help();
      exit( 0 );
    }
  }

  if ( !any_arg ) {
    help();
    exit( 0 );
  }

  if ( optind != argc ) {
    fprintf( stderr, "There seems to be some extra cruff on the command line that mia does not understand.\n" );
  }

  /* Start the clock... */
  curr_time = time(NULL);
  //  c_time = (char*)save_malloc(64*sizeof(char));
  //  c_time = asctime(localtime(&curr_time));

  /* Announce that we're starting */
  fprintf( stderr, 
	   "Starting assembly of %s\nusing %s\nas reference at %s\n", 
	   frag_fn, ref_fn, 
	   asctime(localtime(&curr_time)) );


  /* Set up the maln structure */
  maln = (MapAlignmentP)init_map_alignment();
  maln->cons_code = cc; 
  if ( maln == NULL ) {
    fprintf( stderr, "Not enough memories for this\n" );
    exit( 1 );
  }

  /* Set the distant_ref flag */
  maln->distant_ref = distant_ref;

  /* Set up the FSDB for keeping good-scoring sequence in memory */
  fsdb = init_FSDB();
  if ( fsdb == NULL ) {
    fprintf( stderr, "Not enough memories for holding sequences\n" );
    exit( 1 );
  }

  /* Read in the reference sequence and make reverse complement, too*/
  if ( read_fasta_ref( maln->ref, ref_fn ) != 1 ) {
    fprintf( stderr, "Problem reading reference sequence file %s\n", ref_fn );
    exit( 1 );
  }

  /* Add wrap-around sequence (rc, too) and set maln->ref->circular
     if it's circular */
  if ( circular ) {
    add_ref_wrap( maln->ref );
  }
  else {
    maln->ref->wrap_seq_len = maln->ref->seq_len;
  }
  /* Add space for the gaps array */
  maln->ref->gaps = (int*)save_malloc((maln->ref->wrap_seq_len+1) *
				      sizeof(int));
  for( i = 0; i <= maln->ref->wrap_seq_len; i++ ) {
    maln->ref->gaps[i] = 0;
  }

  /* Set up fkpa and rkpa for list of kmers in the reference (forward and
     revcom strand) if user wants kmer filtering */
  if ( kmer_filt_len > 0 ) {
    fprintf( stderr, "Making kmer list for k-mer filtering...\n" );
    fkpa = init_kpa(kmer_filt_len);
    rkpa = init_kpa(kmer_filt_len);
    /* 
    kmer_list = (KmersP)pop_kmers( maln->ref, kmer_filt_len );
    */
    populate_kpa( fkpa, maln->ref->seq, 
		  maln->ref->wrap_seq_len, kmer_filt_len, 
		  soft_mask );
    populate_kpa( rkpa, maln->ref->rcseq, 
		  maln->ref->wrap_seq_len, kmer_filt_len,
		  soft_mask );
  }

  /* Now kmer arrays have been made if requested. We can upper case
     the reference sequences. */
  make_ref_upper( maln->ref );

  /* Set up FragSeqP to point to a FragSeq */
  frag_seq = (FragSeqP)save_malloc(sizeof(FragSeq));

  /* Set up the alignment structures for forward and reverse
     complement alignments */
  fw_align = (AlignmentP)init_alignment( INIT_ALN_SEQ_LEN,
					 (maln->ref->wrap_seq_len + 
					  (2*INIT_ALN_SEQ_LEN)),
					 0, hp_special );
  rc_align = (AlignmentP)init_alignment( INIT_ALN_SEQ_LEN,
					 (maln->ref->wrap_seq_len + 
					  (2*INIT_ALN_SEQ_LEN)),
					 1, hp_special );

  /* Set up the alignment structure for adapter trimming, if user
     wants that */
  if ( do_adapter_trimming ) {
    adapt_align = (AlignmentP)init_alignment( INIT_ALN_SEQ_LEN,
					      INIT_ALN_SEQ_LEN,
					      0, hp_special );
    /* Setup the flatsubmat */
    //flatsubmat = init_flatsubmat();
    adapt_align->submat = flatsubmat;

    adapt_align->seq2   = adapter;
    adapt_align->len2   = strlen( adapt_align->seq2 );
    pop_s2c_in_a( adapt_align );
    if ( hp_special ) {
      pop_hpl_and_hps( adapt_align->seq2, adapt_align->len2,
		       adapt_align->hprl, adapt_align->hprs );
    }
    /* Set for a semi-global that pays a penalty for unaligning the
       beginning of the adapter, but not for the end of the adapter.
       This is because if the sequence read (align->seq1) ends, then
       we won't see any more of the adapter. When we search for the
       best alignment, we'll only look in the last column, requiring that
       all of align->seq1 is accounted for */
    adapt_align->sg5    = 1;
    adapt_align->sg3    = 0;
  }

  fw_align->seq1 = maln->ref->seq;
  rc_align->seq1 = maln->ref->rcseq;
  if ( circular ) {
    fw_align->len1 = maln->ref->wrap_seq_len;
    rc_align->len1 = maln->ref->wrap_seq_len;
  }
  else {
    fw_align->len1 = maln->ref->seq_len;
    rc_align->len1 = maln->ref->seq_len;
  }

  /* Now the reference sequence and its reverse complement are
     prepared, put the s1c lookup codes in */
  pop_s1c_in_a( fw_align );
  pop_s1c_in_a( rc_align );

  if ( hp_special ) {
    pop_hpl_and_hps( fw_align->seq1, fw_align->len1,
		     fw_align->hpcl, fw_align->hpcs );
    pop_hpl_and_hps( rc_align->seq1, rc_align->len1,
		     rc_align->hpcl, rc_align->hpcs );
  }

  /* One by one, go through the input file of fragments to be aligned.
     Align them to the reference. For each fragment generating an
     alignment score better than the cutoff, merge it into the maln
     alignment. Keep track of those that don't, too. */
  FF = fileOpen( frag_fn, "r" );
  seq_code = find_input_type( FF );

  //LOG = fileOpen( log_fn, "w" );
  front_pwaln = (PWAlnFragP)save_malloc( sizeof(PWAlnFrag));
  back_pwaln  = (PWAlnFragP)save_malloc( sizeof(PWAlnFrag));

  /* Give some space to remember the IDs as we see them */
  test_id = (char*)save_malloc(MAX_ID_LEN * sizeof(char));

  /* Announce we're strarting alignment of fragments */
  fprintf( stderr, "Starting to align sequences to the reference...\n" );

  while( read_next_seq( FF, frag_seq, seq_code ) ) {
    seen_seqs++;
    strcpy( test_id, frag_seq->id );
    if ( DEBUG ) {
      fprintf( stderr, "%s\n", frag_seq->id );
    }
    if ( !ids_rest ||
	 ( bsearch( &test_id, good_ids->ids, 
		    good_ids->num_ids,
		    sizeof(char*), idCmp ) 
	   != NULL ) ) {

      if ( do_adapter_trimming ) {
	/* Trim sequence (set frag_seg->trimmed and 
	   frag_seg->trim_point field) */
	trim_frag( frag_seq, adapter, adapt_align );
      }
      else {
	frag_seq->trimmed = 0;
      }

      /* Check if kmer filtering. If so, filter */
      if ( new_kmer_filter( frag_seq, fkpa, rkpa, kmer_filt_len,
			    fw_align, rc_align ) ) {
	/* Align this fragment to the reference and write 
	   the result into pwaln; use the ancsubmat, not the reverse
	   complemented rcsancsubmat during this first iteration because
	   all sequence is forward strand
	*/
	fw_align->submat = ancsubmat;
	rc_align->submat = ancsubmat;
	
	if ( sg_align( maln, frag_seq, fsdb, 
		       fw_align, rc_align,
		       front_pwaln, 
		       back_pwaln ) == 0 ) {
	  fprintf( stderr, "Problem handling %s\n", frag_seq->id );
	}
      }  
    }
    if ( seen_seqs % 1000 == 0 ) {
      fprintf( stderr, "." );
    }
    if ( seen_seqs % 80000 == 0 ) {
      fprintf( stderr, "\n" );
    }
  }

  /* Now, fsdb is complete and points to all the things in maln.
     So we can fill in the AlnSeqP->smp array for everything in the 
     maln->AlnSeqArray to know which matrices to use for *CALLING* 
     a consensus; Conveniently, there are pointers to all of these
     in the fss->fss[X]->front|back_asp */
  pop_smp_from_FSDB( fsdb, PSSM_DEPTH );

  //fprintf( LOG, "__Finished with initial alignments__" );
  //fflush( LOG );
  fprintf( stderr, "\n" );
  iter_num = 1;

  /* Now, we need a new MapAlignment, culled_maln, that is big
     enough to hold all the unique guys from maln */
  culled_maln = init_culled_map_alignment( maln );

  /* Filtering repeats announcement */
  fprintf( stderr, "Repeat and score filtering\n" );

  /* If user wants to filter against repeats by alignment score, do it */
  if ( repeat_filt ) {  
    /* Sort fsdb by fsdb->as */
    sort_fsdb( fsdb );
    
    /* Now, everything is sorted in fsdb, so I can easily see
       which guys are unique by as, ae, and rc fields */
    set_uniq_in_fsdb( fsdb, just_outer_coords );
  }

  /* If user wants to filter against repeats by q-score sum, do it */
  if ( repeat_qual_filt ) {  
    /* Sort fsdb by fsdb->as */
    sort_fsdb_qscore( fsdb );
    
    /* Now, everything is sorted in fsdb, so I can easily see
       which guys are unique by as, ae, and rc fields */
    set_uniq_in_fsdb( fsdb, just_outer_coords );
  }

  /* Now, we know which sequences are unique, so make a
     culled_maln with just the unique guys */
  cull_maln_from_fsdb( culled_maln, fsdb, Hard_cut, 
		       SCORE_CUT_SET, slope, intercept );

  fclose(FF);

  /* Tell the culled_maln which matrices to use for assembly */
  culled_maln->fpsm = ancsubmat;
  culled_maln->rpsm = rcancsubmat;

  sort_aln_frags( culled_maln ); //invalidates fsdb->front|back_asp fields!

  fw_align->submat = ancsubmat;
  fw_align->sg5 = 1;
  fw_align->sg3 = 1;

  last_assembly_cons = (char*)save_malloc((maln->ref->seq_len +1) * 
				     sizeof(char));
  strncpy( last_assembly_cons, maln->ref->seq, 
	   maln->ref->seq_len );
  last_assembly_cons[maln->ref->seq_len] = '\0';

  /* Re-align everything with revcomped
     sequence and substitution matrices, but first
     unmask all alignment positions and collapse sequences
     if requested
  */
  memset(fw_align->align_mask, 1, fw_align->len1);
  if ( collapse ) {
    collapse_FSDB( fsdb, Hard_cut, SCORE_CUT_SET, 
		   slope, intercept );
  }
  reiterate_assembly( last_assembly_cons, iter_num, maln, fsdb,
		      fw_align, front_pwaln, back_pwaln, 
		      ancsubmat, rcancsubmat );
  pop_smp_from_FSDB( fsdb, PSSM_DEPTH );
  fprintf( stderr, "Repeat and score filtering\n" );
  if ( repeat_filt ) {
    sort_fsdb( fsdb );
    set_uniq_in_fsdb( fsdb, just_outer_coords );
  }
  if ( repeat_qual_filt ) {  
    sort_fsdb_qscore( fsdb );
    set_uniq_in_fsdb( fsdb, just_outer_coords );
  }
  cull_maln_from_fsdb( culled_maln, fsdb, Hard_cut,
		       SCORE_CUT_SET, slope, intercept );
  
  
  /* Tell the culled_maln which matrices to use for assembly */
  culled_maln->fpsm = ancsubmat;
  culled_maln->rpsm = rcancsubmat;
  
  //invalidates fsdb->front|back_asp fields!
  sort_aln_frags( culled_maln );
  sprintf( maln_fn, "%s.%d", maln_root, iter_num );
  if ( !iterate || !FINAL_ONLY ) {
    write_ma( maln_fn, culled_maln );
    if ( make_fastq ) {
      write_fastq( fastq_out_fn, fsdb );
    }
  }

  /* Are we iterating (re-aligning to the a new consensus? */
  if (iterate) {
    /* New assembly consensus announcement */
    fprintf( stderr, "Generating new assembly consensus\n" );
    assembly_cons = consensus_assembly_string( culled_maln );

    while( ( strcmp( assembly_cons, last_assembly_cons ) != 0) &&
	   (iter_num < MAX_ITER) ) {
      /* Another round...*/
      iter_num++;
      free( last_assembly_cons );
      last_assembly_cons = assembly_cons;

      fprintf( stderr, "Starting assembly iteration %d\n", 
	       iter_num );

      /* If the user wants collapsed sequences, now is the time */
      if ( collapse ) {
	collapse_FSDB( fsdb, Hard_cut, SCORE_CUT_SET, 
		       slope, intercept );
      }

      reiterate_assembly( assembly_cons, iter_num, maln, fsdb, 
			  fw_align, front_pwaln, back_pwaln,
			  ancsubmat, rcancsubmat );

      pop_smp_from_FSDB( fsdb, PSSM_DEPTH );

      fprintf( stderr, "Repeat and score filtering\n" );
      if ( repeat_filt ) {
	sort_fsdb( fsdb );
	set_uniq_in_fsdb( fsdb, just_outer_coords );
      }
      if ( repeat_qual_filt ) {
	sort_fsdb_qscore( fsdb );
	set_uniq_in_fsdb( fsdb, just_outer_coords );
      }
      cull_maln_from_fsdb( culled_maln, fsdb, Hard_cut,
			   SCORE_CUT_SET, slope, intercept );

      
      /* Tell the culled_maln which matrices to use for assembly */
      culled_maln->fpsm = ancsubmat;
      culled_maln->rpsm = rcancsubmat;

      //invalidates fsdb->front|back_asp fields!
      sort_aln_frags( culled_maln );

      sprintf( maln_fn, "%s.%d", maln_root, iter_num );
      if ( !FINAL_ONLY ) {
	fprintf( stderr, "Writing maln file for iteration %d\n", 
		 iter_num );
	write_ma( maln_fn, culled_maln );
      }
      assembly_cons = consensus_assembly_string( culled_maln );
    }
  
    /* Convergence? */
    if ( strcmp( assembly_cons, last_assembly_cons ) == 0 ) {
      fprintf( stderr, "Assembly convergence - writing final maln\n" );
      write_ma( maln_fn, culled_maln );
    }
    else {
      fprintf( stderr, "Assembly did not converge after % rounds, quitting\n" );
      write_ma( maln_fn, culled_maln );
    }
    if ( make_fastq ) {
      write_fastq( fastq_out_fn, fsdb );
    }
  }

  /* No iteration, but we must still re-align everything with revcomped
     sequence and substitution matrices to keep scores comparable to what
     they would have been had we iterated */

  /* Announce we're finished */
  curr_time = time(NULL);
  //  c_time    = asctime(localtime(&curr_time));
  fprintf( stderr, "Assembly finished at %s\n",
	   asctime(localtime(&curr_time)) );

  exit( 0 );
}
Example #7
0
tm *TimeUtil::get_current_tm()
{
	const time_t timeTmp = get_current_time();
	return localtime( &timeTmp );
}
Example #8
0
/********** MAIN PROGRAM ************************************************
 *
 * This program reads current weather data from a WS2300
 * and writes the data to a log file.
 *
 * Log file format:
 * Timestamp Date Time Ti To DP RHi RHo Wind Dir-degree Dir-text WC
 *              Rain1h Rain24h Rain-tot Rel-Press Tendency Forecast
 *
 * Just run the program without parameters for usage.
 *
 * It takes two parameters. The first is the log filename with path
 * The second is the config file name with path
 * If this parameter is omitted the program will look at the default paths
 * See the open2300.conf-dist file for info
 *
 ***********************************************************************/
int main(int argc, char *argv[])
{
	WEATHERSTATION ws2300;
	FILE *fileptr;
	char tempstring[1000] = "";
	char logline[1000] = "";
    char urlline[3000] = "";
	char pachubeline[2000] = "";
	char datestring[50];        //used to hold the date stamp for the log file
	const char *directions[]= {"N","NNE","NE","ENE","E","ESE","SE","SSE",
	                           "S","SSW","SW","WSW","W","WNW","NW","NNW"};
	double winddir[6];
	int tempint;
	char tendency[15];
	char forecast[15];
	struct config_type config;
	time_t basictime;
	int dataFlag = 1;

	get_configuration(&config, argv[2]);

	ws2300 = open_weatherstation(config.serial_device_name);
	
	/* START WITH URL, ID AND PASSWORD */

	sprintf(urlline, "GET %s?ID=%s&PASSWORD=%s", WEATHER_UNDERGROUND_PATH,
	        config.weather_underground_id,config.weather_underground_password);

			
	/* GET DATE AND TIME FOR URL */
	
	time(&basictime);
	basictime = basictime - atof(config.timezone) * 60 * 60;
	strftime(datestring,sizeof(datestring),"&dateutc=%Y-%m-%d+%H%%3A%M%%3A%S",
	         localtime(&basictime));
	strcat(urlline, datestring);
	
	/* Get log filename. */

	if (argc < 2 || argc > 3)
	{
		print_usage();
	}

	fileptr = fopen(argv[1], "a+");
	if (fileptr == NULL)
	{
		printf("Cannot open file %s\n",argv[1]);
		exit(-1);
	}


	/* READ TEMPERATURE INDOOR */

	//sprintf(logline,"%.1f ", temperature_indoor(ws2300, config.temperature_conv));
	sprintf(tempstring,"%.1f", temperature_indoor(ws2300, config.temperature_conv)); 
	strcat(logline, tempstring);
	
	strcat(pachubeline,"2,");
	strcat(pachubeline,tempstring);
	
	double outdoor = humidity_outdoor(ws2300);
	double dew = dewpoint(ws2300, config.temperature_conv);

    if ( outdoor > 100) dataFlag = 0;
	if (dew < -10.0) dataFlag = 0;
	if (dew > 100.0) dataFlag = 0;
	
	/* READ TEMPERATURE OUTDOOR */

		//sprintf(tempstring,"%.1f ", temperature_outdoor(ws2300, config.temperature_conv));
		sprintf(tempstring,"%.1f", outdoor);
		strcat(logline, " ");
		strcat(logline, tempstring);
		
		if (dataFlag) {
			strcat(pachubeline,"\r\n4,");
			strcat(pachubeline,tempstring);
		
			strcat(urlline,"&tempf=");
			strcat(urlline, tempstring);
		}

		/* READ DEWPOINT */

		//sprintf(tempstring,"%.1f ", dewpoint(ws2300, config.temperature_conv));
		sprintf(tempstring,"%.1f", dew);
		strcat(logline, " ");
		strcat(logline, tempstring);
		if (dataFlag) {
			strcat(pachubeline,"\r\n5,");
			strcat(pachubeline,tempstring);
			
			strcat(urlline,"&dewptf=");
			strcat(urlline, tempstring);
		}
	
	/* READ RELATIVE HUMIDITY INDOOR */

	sprintf(tempstring,"%d", humidity_indoor(ws2300));	
	strcat(logline, " ");
	strcat(logline, tempstring);
	
	strcat(pachubeline,"\r\n3,");
	strcat(pachubeline,tempstring);

	/* READ RELATIVE HUMIDITY OUTDOOR */

	sprintf(tempstring,"%d", humidity_outdoor(ws2300));	 
	strcat(logline, " ");
	strcat(logline, tempstring);
	if (dataFlag) {
		strcat(pachubeline,"\r\n6,");
		strcat(pachubeline,tempstring);
			
		strcat(urlline,"&humidity=");
		strcat(urlline, tempstring);
	}
		
	/* READ WIND SPEED AND DIRECTION */

	sprintf(tempstring,"%.1f",
	       wind_all(ws2300, config.wind_speed_conv_factor, &tempint, winddir));
	
	strcat(logline, " ");
	strcat(logline, tempstring);
	if (dataFlag) {
		strcat(pachubeline,"\r\n7,");
		strcat(pachubeline,tempstring);
			
		strcat(urlline,"&windspeedmph=");
		strcat(urlline, tempstring);
	}
	
	sprintf(tempstring,"%.1f %s ", winddir[0], directions[tempint]);
	strcat(logline, tempstring);

	sprintf(tempstring,"%.1f", winddir[0]);
	strcat(pachubeline,"\r\n8,");
	strcat(pachubeline,tempstring);
			
	/* READ WIND GUST - miles/hour for Weather Underground */

	if (GUST)
	{
		tmpvalue = wind_minmax(ws2300, config.wind_speed_conv_factor, NULL, NULL, NULL, NULL);
		if (tmpvalue>100.0) tmpvalue=0.0;
		sprintf(tempstring, "%.1f",tmpvalue);
		strcat(logline, " ");
		strcat(logline, tempstring);
		
		strcat(pachubeline,"\r\n9,");
		strcat(pachubeline,tempstring);
	
		strcat(urlline,"&windgustmph=");
		strcat(urlline, tempstring);
		
		wind_reset(ws2300, RESET_MIN + RESET_MAX);
	}
	
	/* READ WINDCHILL */

	sprintf(tempstring,"%.1f ", windchill(ws2300, config.temperature_conv));
	strcat(logline, tempstring);

	/* READ RAIN 1H */

	sprintf(tempstring,"%.2f", rain_1h(ws2300, config.rain_conv_factor));
	strcat(logline, " ");
	strcat(logline, tempstring);
	
	strcat(pachubeline,"\r\n10,");
	strcat(pachubeline,tempstring);
	
	strcat(urlline,"&rainin=");
	strcat(urlline, tempstring);	

	/* READ RAIN 24H */

	sprintf(tempstring,"%.2f", rain_24h(ws2300, config.rain_conv_factor));
	strcat(logline, " ");
	strcat(logline, tempstring);
	
	strcat(pachubeline,"\r\n11,");
	strcat(pachubeline,tempstring);
	
	strcat(urlline,"&dailyrainin=");
	strcat(urlline, tempstring);	

	/* READ RAIN TOTAL */

	sprintf(tempstring,"%.2f ", rain_total(ws2300, config.rain_conv_factor));
	strcat(logline, tempstring);


	/* READ RELATIVE PRESSURE */

	sprintf(tempstring,"%.3f", rel_pressure(ws2300, config.pressure_conv_factor));
	strcat(logline, " ");
	strcat(logline, tempstring);
	
	strcat(pachubeline,"\r\n12,");
	strcat(pachubeline,tempstring);
	
	
	sprintf(tempstring, "%.3f", rel_pressure(ws2300, INCHES_HG) );
	strcat(urlline,"&baromin=");
	strcat(urlline, tempstring);

	/* READ TENDENCY AND FORECAST */

	tendency_forecast(ws2300, tendency, forecast);
	sprintf(tempstring,"%s %s ", tendency, forecast);
	strcat(logline, tempstring);

	/* GET DATE AND TIME FOR LOG FILE, PLACE BEFORE ALL DATA IN LOG LINE */

	//time(&basictime);
	strftime(datestring, sizeof(datestring), "%Y%m%d%H%M%S %Y-%b-%d %H:%M:%S",
	         localtime(&basictime));

	// Print out and leave

	// printf("%s %s\n",datestring, logline); //disabled to be used in cron job
	fprintf(fileptr, "%s %s\n", datestring, logline);
	
	fclose(fileptr);
	
	/* ADD SOFTWARE TYPE AND ACTION */
	sprintf(tempstring, "&softwaretype=open2300-%s&action=updateraw", VERSION);
	strcat(urlline, tempstring);
	
	sprintf(tempstring, " HTTP/1.0\r\nUser-Agent: open2300/%s\r\nAccept: */*\r\n"
	                   "Host: %s\r\nConnection: Keep-Alive\r\n\r\n",
	        VERSION, WEATHER_UNDERGROUND_BASEURL);
	strcat(urlline, tempstring);

	
	close_weatherstation(ws2300);
	
	if (DEBUG)
	{
		printf("%s\n",logline);
		printf("%s\n",urlline);
		printf("%s\n",pachubeline);
	}
	else
	{
	 	if (dataFlag) 
		{
			http_request_url(urlline);
		}
	}
	
	return(0);
}
Example #9
0
void parseifinfo(int newdb)
{
    uint64_t rxchange=0, txchange=0, btime, cc;   /* rxchange = rx change in MB */
    uint64_t krxchange=0, ktxchange=0, maxtransfer;   /* krxchange = rx change in kB */
    time_t current, interval;
    struct tm *d;
    int day, month, year, hour, min, shift, maxbw;
    int rxkchange=0, txkchange=0;			          /* changes in the kB counters */

    ifinfo.rxp = ifinfo.txp = 0;
    current=time(NULL);
    interval=current-data.lastupdated;
    btime=getbtime();

    /* count traffic only if previous update wasn't too long ago */
    if ( interval < (60*MAXUPDATEINTERVAL) ) {

        /* btime in /proc/stat seems to vary ±1 second so we use btime-BVAR just to be safe */
        /* the variation is also slightly different between various kernels... */
        if (data.btime < (btime-cfg.bvar)) {
            data.currx=0;
            data.curtx=0;
            if (debug)
                printf("System has been booted.\n");
        }

        /* process rx & tx */
        if (newdb!=1) {
            cc = countercalc(&data.currx, &ifinfo.rx);
            rxchange = cc/1048576;      /* 1024/1024 */
            rxkchange = (cc/1024)%1024;
            krxchange = cc/1024;
            ifinfo.rxp = cc%1024;

            cc = countercalc(&data.curtx, &ifinfo.tx);
            txchange = cc/1048576;      /* 1024/1024 */
            txkchange = (cc/1024)%1024;
            ktxchange = cc/1024;
            ifinfo.txp = cc%1024;
        }

        /* get bandwidth limit for current interface */
        maxbw = ibwget(data.interface);

        if (maxbw > 0) {

            /* calculate maximum possible transfer since last update based on set maximum rate */
            /* and add 10% in order to be on the safe side */
            maxtransfer = ceil((maxbw/(float)8)*interval*(float)1.1);

            if (debug)
                printf("interval: %"PRIu64"  maxbw: %d  maxrate: %"PRIu64"  rxc: %"PRIu64"  txc: %"PRIu64"\n", (uint64_t)interval, maxbw, maxtransfer, rxchange, txchange);

            /* sync counters if traffic is greater than set maximum */
            if ( (rxchange > maxtransfer) || (txchange > maxtransfer) ) {
                snprintf(errorstring, 512, "Traffic rate for \"%s\" higher than set maximum %d Mbit (%"PRIu64"->%"PRIu64", r%"PRIu64" t%"PRIu64"), syncing.", data.interface, maxbw, (uint64_t)interval, maxtransfer, rxchange, txchange);
                printe(PT_Info);
                rxchange = krxchange = rxkchange = txchange = ktxchange = txkchange = 0;
                ifinfo.rxp = ifinfo.txp = 0;
            }
        }

    } else {
        if (debug)
            printf("Too much time passed since previous update, syncing. (%"PRIu64" < %d)\n", (uint64_t)interval, 60*MAXUPDATEINTERVAL);
    }


    /* keep btime updated in case it drifts slowly */
    data.btime = btime;

    data.currx = ifinfo.rx - ifinfo.rxp;
    data.curtx = ifinfo.tx - ifinfo.txp;
    addtraffic(&data.totalrx, &data.totalrxk, rxchange, rxkchange);
    addtraffic(&data.totaltx, &data.totaltxk, txchange, txkchange);

    /* update days and months */
    addtraffic(&data.day[0].rx, &data.day[0].rxk, rxchange, rxkchange);
    addtraffic(&data.day[0].tx, &data.day[0].txk, txchange, txkchange);
    addtraffic(&data.month[0].rx, &data.month[0].rxk, rxchange, rxkchange);
    addtraffic(&data.month[0].tx, &data.month[0].txk, txchange, txkchange);

    /* fill some variables from current date & time */
    d=localtime(&current);
    if (d==NULL) {
        panicexit(__FILE__, __LINE__);
    }
    day=d->tm_mday;
    month=d->tm_mon;
    year=d->tm_year;
    hour=d->tm_hour;
    min=d->tm_min;
    shift=hour;

    /* add traffic to previous hour when update happens at X:00 */
    /* and previous update was during previous hour */
    d=localtime(&data.lastupdated);
    if (d==NULL) {
        panicexit(__FILE__, __LINE__);
    }
    if ((min==0) && (d->tm_hour!=hour) && ((current-data.lastupdated)<=3600)) {
        hour--;
        if (hour<0) {
            hour=23;
        }
    }

    /* clean and update hourly */
    cleanhours();
    data.hour[shift].date=current;   /* avoid shifting timestamp */
    data.hour[hour].rx+=krxchange;
    data.hour[hour].tx+=ktxchange;

    /* rotate days in database if needed */
    d=localtime(&data.day[0].date);
    if (d==NULL) {
        panicexit(__FILE__, __LINE__);
    }
    if ((d->tm_mday!=day) || (d->tm_mon!=month) || (d->tm_year!=year)) {

        /* make a new entry only if there's something to remember (configuration dependent) */
        if ( (data.day[0].rx==0) && (data.day[0].tx==0) && (data.day[0].rxk==0) && (data.day[0].txk==0) && (cfg.traflessday==0) ) {
            data.day[0].date=current;
        } else {
            rotatedays();
        }
    }

    /* rotate months in database if needed */
    d=localtime(&data.month[0].month);
    if (d==NULL) {
        panicexit(__FILE__, __LINE__);
    }
    if ((d->tm_mon!=month) && (day>=cfg.monthrotate)) {
        rotatemonths();
    }
}
Example #10
0
//*****************************************************************************
//
void MAIN_Print( char *pszString )
{
	char	szBuffer[SERVERCONSOLE_TEXTLENGTH];
	char	szInputString[SERVERCONSOLE_TEXTLENGTH];
	char	*psz;
	char	c;
	bool	bScroll = false;
	bool	bRecycled = false;

	// Prefix the line with a timestamp (unless it's a newline).
	if ( strlen( pszString ) && pszString[0] != '\n' )
	{
		time_t			CurrentTime;
		struct	tm		*pTimeInfo;

		time( &CurrentTime );
		pTimeInfo = localtime( &CurrentTime );

		// It's AM if the hour in the day is less than 12.
		if ( pTimeInfo->tm_hour < 12 )
			sprintf( szInputString, "[%02d:%02d:%02d am] ", ( pTimeInfo->tm_hour == 0 ) ? 12 : pTimeInfo->tm_hour, pTimeInfo->tm_min, pTimeInfo->tm_sec );
		else
			sprintf( szInputString, "[%02d:%02d:%02d pm] ", ( pTimeInfo->tm_hour == 12 ) ? 12 : pTimeInfo->tm_hour % 12, pTimeInfo->tm_min, pTimeInfo->tm_sec );

		psz = szInputString + strlen( szInputString );
	}
	else
		psz = szInputString;

	// Check where the scrollbars are.
	LONG	lVisibleLine;
	LONG	lTotalLines;
	LONG	lLineDiff;

	while ( 1 )
	{
		c = *pszString++;
		if ( c == '\0' )
		{
			*psz = c;
			break;
		}

		if ( c == '\n' )
		{
			*psz++ = '\r';
		}

		*psz++ = c;
	}

	lVisibleLine = SendDlgItemMessage( g_hDlg_Overview, IDC_CONSOLEBOX, EM_GETFIRSTVISIBLELINE, 0, 0 );
	lTotalLines = SendDlgItemMessage( g_hDlg_Overview, IDC_CONSOLEBOX, EM_GETLINECOUNT, 0, 0 );
	lLineDiff = lTotalLines - lVisibleLine;
	bScroll = ( lLineDiff <= 9 );

	if ( GetDlgItemText( g_hDlg_Overview, IDC_CONSOLEBOX, szBuffer, sizeof( szBuffer )))
	{
		LONG	lDifference;
		char	szConsoleBuffer[SERVERCONSOLE_TEXTLENGTH];

		// If the amount of text added to the buffer will cause a buffer overflow, shuffle the text upwards.
		psz = szBuffer;
		if (( lDifference = ( (LONG)strlen( szBuffer ) + (LONG)strlen( szInputString ) - SERVERCONSOLE_TEXTLENGTH )) >= 0 )
		{
			bRecycled = true;
			while ( 1 )
			{
				psz++;
				lDifference--;
				if ( *psz == 0 )
					break;
				if ( lDifference < 0 )
				{
					while ( 1 )
					{
						if ( *psz == 0 )
						{
							psz++;
							break;
						}
						else if ( *psz == '\r' )
						{
							psz += 2;
							break;
						}
						psz++;
					}
					break;
				}
			}
		}

		sprintf( szConsoleBuffer, "%s%s", psz, szInputString );
		SetDlgItemText( g_hDlg_Overview, IDC_CONSOLEBOX, szConsoleBuffer );

		// If the user has scrolled all the way down, autoscroll.
		if ( bScroll )
			SendDlgItemMessage( g_hDlg_Overview, IDC_CONSOLEBOX, EM_LINESCROLL, 0, lTotalLines );

		// If they've scrolled up but we've trimmed the text, don't autoscroll and compensate. 
		else if( bRecycled && ( lVisibleLine > 0 ) )
			SendDlgItemMessage( g_hDlg_Overview, IDC_CONSOLEBOX, EM_LINESCROLL, 0, lVisibleLine - 1 );

		// If they've scrolled up, don't autoscroll.
		else
			SendDlgItemMessage( g_hDlg_Overview, IDC_CONSOLEBOX, EM_LINESCROLL, 0, lVisibleLine );
	}
}
Example #11
0
/*
 * Timer handling. Includes a hold off for a period of time if there is resource contention
 */
void handle_calendar_timer(void *cookie) {
	
  // Show the alert and let the world know
  if ((int)cookie >= ALERT_EVENT && (int)cookie <= ALERT_EVENT + MAX_EVENTS) {
	  int num = (int)cookie - ALERT_EVENT;
	  if (timer_rec[num].active == false)
		  return; // Already had the data for this event deleted - cannot show it.
	  timer_rec[num].active = false;
	  for (int i = num + 1; i < max_entries; i++) {
		  if (timer_rec[i].active == true) {
			  handle_calendar_timer((void *)100 + i);
			  vibes_short_pulse();
			  light_enable_interaction();
			  return;
		  }
	  }
	  //draw_date();
	  return;
  }

  if ((int)cookie >= 100 && (int)cookie <= 100 + MAX_EVENTS) {
	  int num = (int)cookie - 100;
	  if (timer_rec[num].active == false)
		  return; // Already had the data for this event
	  Event event = events[num];
	  // Compute the event start time as a figure in ms
	  int time_position = 9;
	  if (event.start_date[5] != '/')
		time_position = 6;

	  int hour = a_to_i(&event.start_date[time_position],2);
	  int minute_position = time_position + 3;
	  if (event.start_date[time_position + 1] == ':')
		  minute_position = time_position + 2;
	  int minute = a_to_i(&event.start_date[minute_position],2);

	  uint32_t event_in_ms = (hour * 3600 + minute * 60) * 1000;

	  // Get now as ms
	  time_t rawtime;
	  time(&rawtime);
	  struct tm *time = localtime(&rawtime);
	  uint32_t now_in_ms = (time->tm_hour * 3600 + time->tm_min * 60 + time->tm_sec) * 1000;

	  // Work out the alert interval  
	  int32_t alert_event = event_in_ms - now_in_ms;

	  // If this is negative then we are after the alert period
	  if (alert_event >= 0) {
		  set_relative_desc(num, alert_event);
		  display_event_text(timer_rec[num].event_desc, timer_rec[num].relative_desc);

		  if (alert_event == 0) {
			  timer_rec[num].handle = app_timer_register(30000, handle_calendar_timer, (void *)ALERT_EVENT + num);
			  vibes_double_pulse();
			  light_enable_interaction();
		  } else if (alert_event > 0) {
			  timer_rec[num].handle = app_timer_register(60000 - time->tm_sec * 1000, handle_calendar_timer, (void *)100 + num);
		  }
	  }

	  return;
  }

  // Server requests	  
  if ((int)cookie != REQUEST_CALENDAR_KEY)
	  return;

  // If we're going to make a call to the phone, then a dictionary is a good idea.
  DictionaryIterator *iter;
  app_message_outbox_begin(&iter);

  // We didn't get a dictionary - so go away and wait until resources are available
  if (!iter) {
	// Can't get an dictionary then come back in a second
    app_timer_register(1000, handle_calendar_timer, (void *)cookie);
    return;
  }

  // Make the appropriate call to the server
  if ((int)cookie == REQUEST_CALENDAR_KEY) {
	calendar_request(iter);
    app_timer_register(REQUEST_CALENDAR_INTERVAL_MS, handle_calendar_timer, (void *)cookie);
  } 
}
Example #12
0
int main(int argc,char **args)
{	
	char configfilename[MAXLENGTH];
	char logfilename[MAXLENGTH];
	FILE* logfile;
	int skipHeader = 0;
	char tuplename[MAXLENGTH];
	int isRunning;
	int element_ready;
	PeisTuple* mytuple;	
	int i;
	int ID, len;
	char* value;
	time_t now;
    struct tm ts;
  	char date[MAXLENGTH];
	float kernel_time;
  
	// handlers
  	PeisSubscriberHandle subHandler[MAXKEYS];
	PeisCallbackHandle callHandler[MAXKEYS];
	  	
	// init isRunning
	isRunning = 1;
	// init the semaphore
	pthread_mutex_init(&tuple_processing, NULL);
	// init the tuple list
	initializeList(&tuples);
	
	// initial check for arguments
  	memcpy(configfilename, CONFIGFILE, strlen(CONFIGFILE)+1);
  	memcpy(logfilename, LOGFILE, strlen(CONFIGFILE)+1);

	for ( i = 0; i < argc; i++ )
    {
		if (strcmp(args[i],"--help") == 0) { printUsage(stderr,argc,args); }
		if (strcmp(args[i],"--conf") == 0) { memcpy(configfilename, args[i+1], strlen(args[i+1])+1); }
		if (strcmp(args[i],"--log") == 0)  { memcpy(logfilename, args[i+1], strlen(args[i+1])+1); }
		if (strcmp(args[i],"--skip") == 0) { skipHeader = 1; }
	}

  	// instantiate & initialize the PEIS component
	peiskmt_initialize(&argc, args);

	// prepare the header of the log file
  	// time: "ddd yyyy-mm-dd hh:mm:ss zzz"
 	time(&now);
  	ts = *localtime(&now);
  	strftime(date, sizeof(date), "%a %Y-%m-%d %H:%M:%S %Z", &ts);
  	kernel_time = peiskmt_gettimef();

  	// Printing the header for the log file
  	if (skipHeader == 0)
	{
        if( !(logfile = fopen(logfilename, "w") ) )
        {
            printf("Error opening the log file %s \n", logfilename);
            isRunning = 0;
        }
        ID = peiskmt_peisid();
        PeisTuple* kernelTuple = peiskmt_getTuple(ID,"kernel.version",PEISK_KEEP_OLD|PEISK_NON_BLOCKING);
        fprintf(logfile, "; Kernel version %s\n", kernelTuple->data);
        fprintf(logfile, "; peislogger version 1.0\n");
        fprintf(logfile, "; starting at %f kernel time, %s\n", kernel_time, date);
        fprintf(logfile, "%f\n", kernel_time);
        fprintf(logfile, "; structure of recorded data:\n");
        fprintf(logfile, "; kernel_ts,write_ts,user_ts,expire_ts,owner,creator,keyDepth,keys,datalenght,data\n");
        fclose(logfile);
	}

  	// Reading the keys of the tuples to subscribe
  	if (!readConfiguration(configfilename))
    {
		printf("Problem reading from configuration file %s \n", configfilename);
		isRunning = 0;
	}
	
  	// Subscribe to all the keys specified in the configuration file and attach a callback
  	for( i = 0 ; i < keyscounter ; i++)
    {
        printf("Subscribing to tuple: \"%s\" ", keys[i]);
        printf("...");
        subHandler[i] = peiskmt_subscribe(-1, keys[i]);
        callHandler[i] = peiskmt_registerTupleCallback(-1, keys[i], NULL, (void*)eventCallback);
        printf("DONE \n");
  	}
 	
  	while( isRunning && peiskmt_isRunning() )
    { 
        // get the tuple to write
  		// not very elegant, but this way I can use the semaphores
		pthread_mutex_lock(&tuple_processing);
  		element_ready = isNotEmpty(&tuples);
		pthread_mutex_unlock(&tuple_processing);

		if(element_ready)
        {
			pthread_mutex_lock(&tuple_processing);
			mytuple = getAndDeleteFirstElement(&tuples);
			pthread_mutex_unlock(&tuple_processing);
			
			peiskmt_printTuple(mytuple);
			printf("\n");
            if ( !(logfile = fopen(logfilename, "a") ) )
            {
				printf("Error appending to logfile file %s \n", logfilename);
				exit(0);
			}
            peiskmt_getTupleName(mytuple, tuplename, sizeof(tuplename));
            fprintf(logfile, "%f %d.%d %d.%d %d.%d %d %d %d %d %d %s %d %s\n", 
			peiskmt_gettimef(), mytuple->ts_write[0], mytuple->ts_write[1], 
			mytuple->ts_user[0], mytuple->ts_user[1], mytuple->ts_expire[0], mytuple->ts_expire[1],
			mytuple->owner, mytuple->creator, mytuple->alloclen, mytuple->isNew, mytuple->keyDepth, 
			tuplename, strlen(mytuple->data)+1, (char*)mytuple->data);
    		fclose(logfile);
		}		
	    usleep(10000);
  	}

	// unsubscribe
	for( i = 0 ; i < keyscounter ; i++)
    {
        peiskmt_unsubscribe(subHandler[i]);
		peiskmt_unregisterTupleCallback(callHandler[i]);
	}

	// free the memory of both the queue and the variables
	peiskmt_freeTuple(mytuple);
	emptyQueue(&tuples);
	pthread_mutex_destroy(&tuple_processing);
  	
	peiskmt_shutdown();
}
Example #13
0
static void init() {
  s_main_window = window_create();
  #ifdef PBL_COLOR
		window_set_background_color(s_main_window, GColorDarkCandyAppleRed);
	#else
  	window_set_background_color(s_main_window, GColorBlack);
	#endif
  window_set_window_handlers(s_main_window, (WindowHandlers) {
    .load = main_window_load,
    .unload = main_window_unload,
  });
  window_stack_push(s_main_window, true);
  tick_timer_service_subscribe(MINUTE_UNIT, &handle_minute_tick);
  
  // Prevent starting blank
  time_t now = time(NULL);
  struct tm *t = localtime(&now);
  handle_minute_tick(t, MINUTE_UNIT);
}

static void deinit() {
  window_destroy(s_main_window);
  tick_timer_service_unsubscribe();
}

int main() {
  init();
  app_event_loop();
  deinit();
}
Example #14
0
AbstractCommand::PostAction
BanList::doExecute( Context& txt )
{
    // bail if nothing to display
    if (userDB.mapBANTIME.empty()) {
        txt._ebuf << "There are no banned users.";
        return PA_ERROR;
    }

    struct Filter {
        string auth;  
        string ip;
        int    level;
        string name;  
        int    since; 
    };
    Filter filter = { "", "", -1, "", 0 };

    // parse filter options    
    {
        const vector<string>::size_type max = txt._args.size();
        for ( vector<string>::size_type i = 1; i < max; i++ ) {
            // pairs of args are expected
            if ((max - i) < 2)
                return PA_USAGE;

            string s = txt._args[i];
            str::toLower( s );

            if (s == "-auth" ) {
                filter.auth = txt._args[++i];
                str::toLower( filter.auth );
            }
            else if (s == "-ip" ) {
                filter.ip = txt._args[++i];
            }
            else if (s == "-level") {
                const string& s = txt._args[++i];
                string err;
                Level& lev = lookupLEVEL( s, txt );
                if (lev == Level::BAD)
                    return PA_ERROR;
                filter.level = lev.level;
            }
            else if (s == "-name") {
                filter.name = txt._args[++i];
                str::toLower( filter.name );
            }
            else if (s == "-since") {
                filter.since = str::toSeconds( txt._args[++i] );
            }
            else {
                return PA_USAGE;
            }
        }
    }

    InlineText cID      = xheader;
    InlineText cWhen    = xheader;
    InlineText cSubject = xheader;
    InlineText cRemain  = xheader;
    InlineText cAuth    = xheader;

    cID.flags      |= ios::left;
    cWhen.flags    |= ios::left;
    cSubject.flags |= ios::left;

    cID.width      = 8;
    cWhen.width    = 24;
    cSubject.width = 25;
    cRemain.width  = 13;

    cWhen.prefixOutside    = ' ';
    cSubject.prefixOutside = ' ';
    cRemain.prefixOutside  = ' ';
    cAuth.prefixOutside    = ' ';

    Buffer buf;
    buf << cID      ( "ID" )
        << cWhen    ( "WHEN" )
        << cSubject ( "SUBJECT" )
        << cRemain  ( "REMAINING" )
        << cAuth    ( "AUTHORITY" );

    cID.color      = xcnone;
    cWhen.color    = xcnone;
    cSubject.color = xcnone;
    cRemain.color  = xcnone;
    cAuth.color    = xcnone;

    const time_t now = time( NULL );
    string tmp;

    uint32 numExpired = 0;
    uint32 num = 0;
    const UserDB::mapBANTIME_t::const_reverse_iterator max = userDB.mapBANTIME.rend();
    for ( UserDB::mapBANTIME_t::const_reverse_iterator it = userDB.mapBANTIME.rbegin(); it != max; it++ ) {
        const User& user = *it->second;
        const string id = (user.guid.length() == 32) ? user.guid.substr( 24 ) : "";

        const time_t deltaTime = user.banExpiry - now;

        // skip if ban has expired
        if (user.banExpiry && deltaTime < 0) {
            numExpired++;
            continue;
        }

        if (!filter.auth.empty()) {
            tmp = user.banAuthority;
            str::toLower( tmp );
            if (tmp.find( filter.auth ) == string::npos)
                continue;
        }

        if (!filter.ip.empty() && (user.ip.find( filter.ip ) == string::npos))
            continue;

        if (filter.level != -1 && user.authLevel != filter.level)
            continue;

        if (!filter.name.empty()) {
            tmp = user.name;
            str::toLower( tmp );
            if (tmp.find( filter.name ) == string::npos)
                continue;
        }

        if (filter.since > 0 && ((now - user.timestamp) > filter.since))
            continue;

        if (++num > (Page::maxLines * Page::maxPages))
            break;

        // format ban time
        char ftime[32];
        strftime( ftime, sizeof(ftime), "%c", localtime( &user.banTime ));

        buf << '\n'
            << cID      ( id )
            << cWhen    ( ftime )
            << cSubject ( str::etAlignLeft( user.namex, cSubject.width, tmp ));

        ostringstream remain;
        if (!user.banExpiry) {
            remain << "permanent";
        }
        else {
            int secs = (user.banExpiry - now);

            int days = secs / (60*60*24);
            secs -= (days * (60*60*24));

            int hours = secs / (60*60);
            secs -= (hours * (60*60));

            int mins = secs / 60;
            secs -= (mins * 60);

            if (days > 999)
                remain << "999d-";
            else if (days > 0)
                remain << days << "d-";

            remain << setw(2) << setfill('0') << hours
                   << ':' << setw(2) << setfill('0') << mins
                   << ':' << setw(2) << setfill('0') << secs;
        }

        buf << cRemain ( remain.str() )
            << cAuth   ( user.banAuthorityx );
    }

    Page::report( txt._client, buf );

    if (numExpired) {
        buf.reset();
        buf << xcheader << "--there were " << xvalue( numExpired ) << " expired-bans not listed.";
        print( txt._client, buf );
    }

    return PA_NONE;
}
Example #15
0
string get_time_iso_string(time_t time)
{
  char time_buffer[1024];
  strftime(time_buffer, 1024, "%Y-%m-%dT%H:%M:%S", localtime(&time));
  return string(time_buffer);
}
Example #16
0
//保存打包文件信息
bool KPackFilePartner::Save(const char* pFileName, unsigned int uPackTime, unsigned int uPackCRC)
{
	int nResult  = false;

    m_uPackTime = uPackTime;
	m_uCRC = uPackCRC;

	KSmartFile	file;
	file = g_CreateFile(pFileName);
	if (!file)
		return false;

#define	MAX_BUFF_SIZE	10240
	int			nElemIndex;
	struct tm*	pFormatTime = NULL;
	struct tm	t = { 0 };
	char		line[MAX_BUFF_SIZE + 512];
	int			nPos = 0;

	pFormatTime = localtime((time_t *)&uPackTime);
	if (pFormatTime == NULL)
		pFormatTime = &t;

	nPos += sprintf((line + nPos), LINE_FORMAT_FIRST, m_nElemCount,
		pFormatTime->tm_year + 1900, pFormatTime->tm_mon + 1,	pFormatTime->tm_mday,
		pFormatTime->tm_hour, pFormatTime->tm_min, pFormatTime->tm_sec,
		m_uPackTime, m_uCRC);
	nPos += sprintf((line + nPos), LINE_FORMAT_SECOND);

	bool bResult = true;

	for (nElemIndex = 0; nElemIndex < m_nElemCount; ++nElemIndex)
	{
		PACKPARTNER_ELEM_INFO& info = m_pElemInfoList[nElemIndex];
        pFormatTime = localtime((time_t *)(&info.uTime));
		if (pFormatTime == NULL)
			pFormatTime = &t;
		nPos += sprintf((line + nPos), LINE_FORMAT_OTHERS,
			info.nElemIndex, info.uId, 
			pFormatTime->tm_year + 1900, pFormatTime->tm_mon + 1,	pFormatTime->tm_mday,
			pFormatTime->tm_hour, pFormatTime->tm_min, pFormatTime->tm_sec,
			info.szFileName,
			info.uSize, (info.uStoreSizeAndCompressFlag & XPACK_COMPRESS_SIZE_FILTER),
			(info.uStoreSizeAndCompressFlag >> XPACK_COMPRESS_SIZE_BIT), info.uCRC);
		if (nPos >= MAX_BUFF_SIZE)
		{
			if (file->Write(line, nPos) != nPos)
			{
				nPos = 0;
				bResult = false;
				break;
			}
			nPos = 0;
		}
	}

	if (nPos > 0)
	{
		if (file->Write(line, nPos) != nPos)
			bResult = false;
	}

	file->Close();
	return bResult;
}
Example #17
0
/**
 * check the departure time
 * return True if the train should go
 */
Boolean checkScheduleTime( iILcDriverInt inst, const char* scheduleID, int scheduleIdx ) {
  iOLcDriverData data = Data(inst);
  Boolean go = False;
  iONode schedule = data->model->getSchedule( data->model, scheduleID );

  if( schedule != NULL ) {
    int idx = 0;
    int timeprocessing = wSchedule.gettimeprocessing(schedule);
    int timeframe      = wSchedule.gettimeframe(schedule);
    int fromhour       = wSchedule.getfromhour(schedule);
    int tohour         = wSchedule.gettohour(schedule);
    int maxdelay       = wSchedule.getmaxdelay(schedule);

    iONode entry = wSchedule.getscentry( schedule );

    /* check if the schedule index is correct: */
    while( entry != NULL ) {
      if( idx == scheduleIdx ) {
        long modeltime = data->model->getTime( data->model );
        struct tm* ltm;
        int modelminutes    = 0;
        int scheduleminutes = 0;
        int mins  = 0;
        int hours = 0;

        if( timeprocessing == wSchedule.time_relative ) {
          modeltime = modeltime - data->scheduletime;
          modelminutes = modeltime / 60;
          mins  = modelminutes % 60;
          hours = modelminutes / 60;
          TraceOp.trc( name, TRCLEVEL_USER1, __LINE__, 4203, "using relative time: modeltime=%d", modeltime );
        }
        else {
          ltm = localtime( &modeltime );
          hours = ltm->tm_hour;
          mins  = ltm->tm_min;
          TraceOp.trc( name, TRCLEVEL_USER1, __LINE__, 4203, "using real time: modeltime=%d", modeltime );
        }

        TraceOp.trc( name, TRCLEVEL_USER1, __LINE__, 4203, "modeltime %02d:%02d (%ld)",
            hours, mins, modeltime );

        scheduleminutes = wScheduleEntry.gethour(entry) * 60 + wScheduleEntry.getminute(entry);

        if(timeprocessing == wSchedule.time_hourly ) {
          TraceOp.trc( name, TRCLEVEL_USER1, __LINE__, 4203, "using hourly timing" );
          /* processing hourly timing */
          modelminutes = mins;
          if( hours < fromhour || tohour < hours ) {
            TraceOp.trc( name, TRCLEVEL_USER1, __LINE__, 4203,
                "current hour, %d, is not in the hourly range from %d to %d",
                hours, fromhour, tohour );
            scheduleminutes += 60;
          }
          else if( modelminutes > scheduleminutes && modelminutes - scheduleminutes > timeframe ) {
            TraceOp.trc( name, TRCLEVEL_USER1, __LINE__, 4203,
                "diff between schedule[%d] and model[%d] time is bigger then the allowed frame of %d; force wait for next hour...",
                scheduleminutes, modelminutes, timeframe );
            scheduleminutes += 60;
          }
        }
        else {
          modelminutes = hours * 60 + mins;
        }


        TraceOp.trc( name, TRCLEVEL_USER1, __LINE__, 4203,
            "check departure time schedule=%d model=%d index=%d",
            scheduleminutes, modelminutes, scheduleIdx );

        /* compare clock with departure time */
        if( scheduleminutes <= modelminutes ) {
          if( (modelminutes - scheduleminutes) <= maxdelay ) {
            TraceOp.trc( name, TRCLEVEL_USER1, __LINE__, 4203,
                "train must leave now %d <= %d and is delayed by %d minutes", scheduleminutes, modelminutes, modelminutes - scheduleminutes );
            go = True;
          }
          else {
            TraceOp.trc( name, TRCLEVEL_USER1, __LINE__, 4203,
                "train exceeded the max.(%d) delay time: %d", maxdelay, modelminutes - scheduleminutes );
          }
        }
        else {
          TraceOp.trc( name, TRCLEVEL_USER1, __LINE__, 4203,
              "train must wait %d > %d", scheduleminutes, modelminutes );
        }

        break;
      }
      idx++;
      entry = wSchedule.nextscentry( schedule, entry );
    };

  }
  else
    go = True;

  return go;
}
Example #18
0
void getTime(struct tm *current_time)
{
	time_t sec = 0;
	time(&sec);
	*current_time = *(localtime(&sec)); 
}
Example #19
0
int datetime_( char* sDate, char* sTime, char* zone, integer* values, 

				ftnlen dateLen, ftnlen timeLen, ftnlen zoneLen )

{

	time_t 		t1;

	struct tm 	*now;

	struct tm 	localNow;

	struct tm 	utcNow;

	integer 	zoneTime;

	char		temp[11];		/* allow room for terminating null */

	int			maxLen;

	int			i;

	

	time( &t1 );				/* System time */

	now = gmtime( &t1 );		/* format as struct in utc time */

	utcNow = *now;

	now = localtime( &t1 ); 	/* format as struct in local time */

	localNow = *now;



	/* Set up the values array */

	values[0] = localNow.tm_year + 1900;

	values[1] = localNow.tm_mon + 1;

	values[2] = localNow.tm_mday;

	

	/* Handle non-whole hour timezones correctly; produce value in minutes */

	values[3] = (localNow.tm_hour - utcNow.tm_hour) * 60;

	values[3] += localNow.tm_min - utcNow.tm_min;				

	

	values[4] = localNow.tm_hour;

	values[5] = localNow.tm_min;

	values[6] = localNow.tm_sec;

	values[7] = 0;

	

	

	/* Fill in the date string */

	strftime( temp, 11, "%Y%y%m%d", now ); 	/* use ANSI strftime to format */	

	/* Copy over at most the first 8 characters */

	maxLen = (dateLen < 8) ? dateLen : 8;

	for ( i = 0; i < maxLen; i++ )

		sDate[i] = temp[i];

	

	/* Fill in the time string, zeroing out the milliseconds */

	strftime( temp, 11, "%H%M%S", now );

	temp[6] = '.';

	temp[7] = temp[8] = temp[9] = '0';

	/* Copy over at most the first 11 characters */

	maxLen = (timeLen < 11) ? timeLen : 11;

	for ( i = 0; i < maxLen; i++ )

		sTime[i] = temp[i];

	

	/* Fill in the zone string */

	/* ...Get sign */

	if ( values[3] < 0 )

	{

		temp[0] = '-';

		zoneTime = -values[3];				// Force positive for following computations

	}

	else

	{

		temp[0] = '+';

		zoneTime = values[3];	

	}	

	/* ...Get hours */

	sprintf( temp+1, "%2d", zoneTime/60 );

	/* ...Get the minutes */

	sprintf( temp+3, "%2d", zoneTime % 60 );

	/* Copy over at most the first 5 characters */

	maxLen = (zoneLen < 5) ? zoneLen : 5;

	for ( i = 0; i < maxLen; i++ )

		zone[i] = temp[i];

	

	

	return 1;

}
Example #20
0
void MySkype::OnConversationListChange(const ConversationRef &conversation, const Conversation::LIST_TYPE &type, const bool &added){

  if (type == Conversation::LIVE_CONVERSATIONS)
  {
    Conversation::LOCAL_LIVESTATUS liveStatus;
    if (!conversation->GetPropLocalLivestatus(liveStatus)) throw SkypeException("Can't obtain contact status.\n");
    SEString liveStatusAsString = tostring(liveStatus);
    printf("[SKYPE]: OnConversationListChange : %s\n", (const char*)liveStatusAsString);

    if (liveStatus == Conversation::RINGING_FOR_ME || liveStatus == Conversation::NONE)
    {
        printf("[SKYPE]: RING RING..\n");
        printf("[SKYPE]: Picking up call from MySkype::OnConversationListChange\n");
        // Saving the currently live conversation reference..
        liveSession = conversation->ref();
        liveSession.fetch();

  // -----------------------------------------------

        if (!liveSession->GetParticipants(liveSession->callerList, Conversation::OTHER_CONSUMERS)) throw SkypeException("Can't obtain participants.\n");
        SEString peopleCalling[liveSession->callerList.size()];

        for (uint i = 0; i < liveSession->callerList.size(); i++)
        {
            //Añadir conversaciones a la tabla. Luego cuando se quiera aceptar uno, obtener la conversacion por ID y hacerle un JoinLiveSession
            peopleCalling[i] = (const char*)liveSession->callerList[i]->GetProp(Participant::P_IDENTITY);

            wxString aux(std::string(peopleCalling[i]).c_str(), wxConvUTF8);

            std::string s_aux = (liveStatus == Conversation::RINGING_FOR_ME)?"Calling":"Call finished";
            wxString aux2(s_aux.c_str(), wxConvUTF8);

            time_t mytime = time(0);
            wxString aux3(std::string(asctime(localtime(&mytime))).c_str(), wxConvUTF8);
            /*
            incoming_calls->ClearAll();
            long itemIndex = incoming_calls->InsertItem(0, aux);

            incoming_calls->SetItem(itemIndex, 1, aux2);
            incoming_calls->SetItem(itemIndex, 2, aux3);

            */

            //TODO: NINONI
            std::string auxiliar;
            auxiliar = "";
            auxiliar.append(std::string(peopleCalling[i]).c_str());
            auxiliar.append(" - ");
            auxiliar.append(s_aux.c_str());
            auxiliar.append(" - ");
            auxiliar.append(std::string(asctime(localtime(&mytime))).c_str());

            incomingCall_event = true;
            incomingCall_message = auxiliar;//std::string(peopleCalling[i]).c_str();


        };

        if (!liveSession->GetParticipants(liveSession->callerList, Conversation::ALL)) throw SkypeException("Can't obtain participants.\n");
        fetch(liveSession->callerList);
  // -----------------------------------------------
    };
  };
};
Example #21
0
int dc_read_switch_config(CmdData *cmd_data)
{
	u32 i;
	int src_number;
	char start_time[4096], end_time[4096];

	time_t now_t = time(NULL);
	struct tm start_tm = *localtime(&now_t);
	struct tm end_tm = *localtime(&now_t);

	GF_Config *conf = cmd_data->switch_conf;
	u32 sec_count = gf_cfg_get_section_count(conf);

	dc_task_init(&cmd_data->task_list);

	if (sec_count == 0) {
		return 0;
	}

	for (i = 0; i < sec_count; i++) {
		const char *section_name = gf_cfg_get_section_name(conf, i);
		const char *section_type = gf_cfg_get_key(conf, section_name, "type");

		if (strcmp(section_type, "video") == 0) {
			VideoDataConf *video_data_conf = gf_malloc(sizeof(VideoDataConf));

			strcpy(video_data_conf->source_id, section_name);
			strcpy(video_data_conf->filename, gf_cfg_get_key(conf, section_name, "source"));

			strcpy(start_time, gf_cfg_get_key(conf, section_name, "start"));
			parse_time(start_time, &start_tm);
			video_data_conf->start_time = mktime(&start_tm);
			strcpy(end_time, gf_cfg_get_key(conf, section_name, "end"));
			parse_time(end_time, &end_tm);
			video_data_conf->end_time = mktime(&end_tm);

			gf_list_add(cmd_data->vsrc, (void *) video_data_conf);

			src_number = gf_list_count(cmd_data->vsrc);

			dc_task_add(&cmd_data->task_list, src_number, video_data_conf->source_id, video_data_conf->start_time, video_data_conf->end_time);
		}
		else if (strcmp(section_type, "audio") == 0)
		{
			AudioDataConf *audio_data_conf = gf_malloc(sizeof(AudioDataConf));
			strcpy(audio_data_conf->source_id, section_name);
			strcpy(audio_data_conf->filename, gf_cfg_get_key(conf, section_name, "source"));

			strcpy(start_time, gf_cfg_get_key(conf, section_name, "start"));
			parse_time(start_time, &start_tm);
			audio_data_conf->start_time = mktime(&start_tm);

			strcpy(end_time, gf_cfg_get_key(conf, section_name, "end"));
			parse_time(end_time, &end_tm);
			audio_data_conf->end_time = mktime(&end_tm);

			gf_list_add(cmd_data->asrc, (void *) audio_data_conf);
		} else {
			fprintf(stdout, "Switch source configuration file: type %s is not supported.\n", section_type);
		}
	}

	fprintf(stdout, "\33[34m\33[1m");
	fprintf(stdout, "Sources:\n");
	for (i=0; i<gf_list_count(cmd_data->vsrc); i++) {
		VideoDataConf *video_data_conf = gf_list_get(cmd_data->vsrc, i);
		strftime(start_time, 20, "%Y-%m-%d %H:%M:%S", localtime(&video_data_conf->start_time));
		strftime(end_time, 20, "%Y-%m-%d %H:%M:%S", localtime(&video_data_conf->end_time));
		fprintf(stdout, "    id:%s\tsource:%s\tstart:%s\tend:%s\n", video_data_conf->source_id, video_data_conf->filename, start_time, end_time);
	}

	for (i=0; i<gf_list_count(cmd_data->asrc); i++) {
		AudioDataConf *audio_data_conf = gf_list_get(cmd_data->asrc, i);
		strftime(start_time, 20, "%Y-%m-%d %H:%M:%S", localtime(&audio_data_conf->start_time));
		strftime(end_time, 20, "%Y-%m-%d %H:%M:%S", localtime(&audio_data_conf->end_time));
		fprintf(stdout, "    id:%s\tsource:%s\tstart:%s\tend:%s\n", audio_data_conf->source_id, audio_data_conf->filename, start_time, end_time);
	}
	fprintf(stdout, "\33[0m");
	fflush(stdout);

	return 0;
}
Example #22
0
bool Master::Run(int argc, char** argv)
{
	char* config_file = (char*)default_config_file;
	char* optional_config_file = (char*)default_optional_config_file;
	char* realm_config_file = (char*)default_realm_config_file;

	int file_log_level = DEF_VALUE_NOT_SET;
	int screen_log_level = DEF_VALUE_NOT_SET;
	int do_check_conf = 0;
	int do_version = 0;
	int do_cheater_check = 0;
	int do_database_clean = 0;
	time_t curTime;

	struct arcpro_option longopts[] =
	{
		{ "checkconf",			arcpro_no_argument,				&do_check_conf,			1		},
		{ "screenloglevel",		arcpro_required_argument,		&screen_log_level,		1		},
		{ "fileloglevel",		arcpro_required_argument,		&file_log_level,		1		},
		{ "version",			arcpro_no_argument,				&do_version,			1		},
		{ "conf",				arcpro_required_argument,		NULL,					'c'		},
		{ "realmconf",			arcpro_required_argument,		NULL,					'r'		},
		{ "databasecleanup",	arcpro_no_argument,				&do_database_clean,		1		},
		{ "cheatercheck",		arcpro_no_argument,				&do_cheater_check,		1		},
		{ 0, 0, 0, 0 }
	};

	char c;
	while((c = static_cast<char>(arcpro_getopt_long_only(argc, argv, ":f:", longopts, NULL))) != -1)
	{
		switch(c)
		{
			case 'c':
				config_file = new char[strlen(arcpro_optarg)];
				strcpy(config_file, arcpro_optarg);
				break;

			case 'r':
				realm_config_file = new char[strlen(arcpro_optarg)];
				strcpy(realm_config_file, arcpro_optarg);
				break;

			case 0:
				break;
			default:
				sLog.Init(0, WORLD_LOG);
				printf("Usage: %s [--checkconf] [--fileloglevel <level>] [--conf <filename>] [--realmconf <filename>] [--version] [--databasecleanup] [--cheatercheck]\n", argv[0]);
				sLog.Close();
				return true;
		}
	}

	// Startup banner
	UNIXTIME = time(NULL);
	g_localTime = *localtime(&UNIXTIME);

	sLog.Init(0, WORLD_LOG);
	
	sLog.outBasic(BANNER, BUILD_TAG, BUILD_HASH_STR, CONFIG, PLATFORM_TEXT, ARCH);
	sLog.outErrorSilent(BANNER, BUILD_TAG, BUILD_HASH_STR, CONFIG, PLATFORM_TEXT, ARCH); // Echo off.

	if(do_version)
	{
		sLog.Close();
		return true;
	}

	if(do_check_conf)
	{
		Log.Notice("Config", "Checking config file: %s", config_file);
		if(Config.MainConfig.SetSource(config_file, true))
			Log.Success("Config", "Passed without errors.");
		else
			Log.Error("Config", "Encountered one or more errors.");

		Log.Notice("Config", "Checking config file: %s", realm_config_file);
		if(Config.RealmConfig.SetSource(realm_config_file, true))
			Log.Success("Config", "Passed without errors.");
		else
			Log.Error("Config", "Encountered one or more errors.");

		Log.Notice("Config", "Checking config file:: %s", optional_config_file);
		if(Config.OptionalConfig.SetSource(optional_config_file, true))
			Log.Success("Config", "Passed without errors.");
		else
			Log.Error("Config", "Encountered one or more errors.");

		sLog.Close();
		return true;
	}

	printf("The key combination <Ctrl-C> will safely shut down the server at any time.\n");

#ifndef WIN32
	if(geteuid() == 0 || getegid() == 0)
		Log.LargeErrorMessage("You are running ArcPro as root.", "This is not needed, and may be a possible security risk.", "It is advised to hit CTRL+C now and", "start as a non-privileged user.", NULL);
#endif

	InitImplicitTargetFlags();
	InitRandomNumberGenerators();
	Log.Notice("Rnd", "Initialized Random Number Generators.");

	ThreadPool.Startup();
	uint32 LoadingTime = getMSTime();

	Log.Success("Config", "Loading Config Files...");
	if(Config.MainConfig.SetSource(config_file))
		Log.Notice("Config", ">> " CONFDIR "/world.conf loaded");
	else
	{
		sLog.Error("Config", ">> error occurred loading " CONFDIR "/world.conf");
		sLog.Close();
		return false;
	}

	if(Config.OptionalConfig.SetSource(optional_config_file))
		Log.Notice("Config", ">> " CONFDIR "/optional.conf loaded");
	else
	{
		sLog.Error("Config", ">> error occurred loading " CONFDIR "/optional.conf");
		sLog.Close();
		return false;
	}

	if(Config.RealmConfig.SetSource(realm_config_file))
		Log.Notice("Config", ">> " CONFDIR "/realms.conf loaded");
	else
	{
		sLog.Error("Config", ">> error occurred loading " CONFDIR "/realms.conf");
		sLog.Close();
		return false;
	}

#if !defined(WIN32) && defined(__DEBUG__)
	if(Config.MainConfig.GetIntDefault("LogLevel", "DisableCrashdumpReport", 0) == 0)
	{
		char cmd[1024];
		char banner[1024];
		snprintf(banner, 1024, BANNER, BUILD_TAG, BUILD_REVISION, CONFIG, PLATFORM_TEXT, ARCH);
		snprintf(cmd, 1024, "./arcpro-crashreport -r %d -d \'%s\'", BUILD_REVISION, banner);
		system(cmd);
	}
	unlink("arcpro.uptime");
#endif

	if(!_StartDB())
	{
		Database::CleanupLibs();
		sLog.Close();
		return false;
	}

	// Checking the DB version. If it's wrong or can't be validated we exit.
	if(!CheckDBVersion())
	{
		sLog.Close();
		return false;
	}

	if(do_database_clean)
	{
		sLog.outDebug("Entering database maintenance mode.");
		new DatabaseCleaner;
		DatabaseCleaner::getSingleton().Run();
		delete DatabaseCleaner::getSingletonPtr();
		sLog.outDebug("Maintenance finished.");
	}

	new EventMgr;
	new World;

	// optional time stamp in logs
	bool useTimeStamp = Config.MainConfig.GetBoolDefault("log", "TimeStamp", false);

	// open cheat log file
	Anticheat_Log = new SessionLogWriter(FormatOutputString("logs", "cheaters", useTimeStamp).c_str(), false);
	GMCommand_Log = new SessionLogWriter(FormatOutputString("logs", "gmcommand", useTimeStamp).c_str(), false);
	Player_Log = new SessionLogWriter(FormatOutputString("logs", "players", useTimeStamp).c_str(), false);

	/* load the config file */
	sWorld.Rehash(false);

	/* set new log levels */
	if(file_log_level != (int)DEF_VALUE_NOT_SET)
		sLog.SetFileLoggingLevel(file_log_level);

	// Initialize Opcode Table
	WorldSession::InitPacketHandlerTable();

	string host = Config.MainConfig.GetStringDefault("Listen", "Host", DEFAULT_HOST);
	int wsport = Config.MainConfig.GetIntDefault("Listen", "WorldServerPort", DEFAULT_WORLDSERVER_PORT);

	new ScriptMgr;

	if(!sWorld.SetInitialWorldSettings())
	{
		Log.Error("Server", "SetInitialWorldSettings() failed. Something went wrong? Exiting.");
		sLog.Close();
		return false;
	}

	if(do_cheater_check)
		sWorld.CleanupCheaters();

	sWorld.SetStartTime((uint32)UNIXTIME);

	WorldRunnable* wr = new WorldRunnable();
	ThreadPool.ExecuteTask(wr);

	_HookSignals();

	ConsoleThread* console = new ConsoleThread();
	ThreadPool.ExecuteTask(console);

	uint32 realCurrTime, realPrevTime;
	realCurrTime = realPrevTime = getMSTime();

	// Socket loop!
	uint32 start;
	uint32 diff;
	uint32 last_time = now();
	uint32 etime;
	uint32 next_printout = getMSTime(), next_send = getMSTime();

	// Start Network Subsystem
	Log.Success("Network", "Starting subsystem...");
	new SocketMgr;
	new SocketGarbageCollector;
	sSocketMgr.SpawnWorkerThreads();

	sScriptMgr.LoadScripts();

	if(Config.MainConfig.GetBoolDefault("Startup", "EnableSpellIDDump", false))
		sScriptMgr.DumpUnimplementedSpells();

	LoadingTime = getMSTime() - LoadingTime;
	Log.Success("Server", "Ready for connections. Startup time: %ums", LoadingTime);

	Log.Notice("RemoteConsole", "Starting...");
	if(StartConsoleListener())
	{
#ifdef WIN32
		ThreadPool.ExecuteTask(GetConsoleListener());
#endif
		Log.Notice("RemoteConsole", "Now open.");
	}
	else
	{
		Log.Warning("RemoteConsole", "Not enabled or failed listen.");
	}


	/* write pid file */
	FILE* fPid = fopen("ArcPro.pid", "w");
	if(fPid)
	{
		uint32 pid;
#ifdef WIN32
		pid = GetCurrentProcessId();
#else
		pid = getpid();
#endif
		fprintf(fPid, "%u", (unsigned int)pid);
		fclose(fPid);
	}

	uint32 loopcounter = 0;
	//ThreadPool.Gobble();

	/* Connect to realmlist servers / logon servers */
	new LogonCommHandler();
	sLogonCommHandler.Startup();

	// Create listener
	ListenSocket<WorldSocket> * ls = new ListenSocket<WorldSocket>(host.c_str(), wsport);
	bool listnersockcreate = ls->IsOpen();
#ifdef WIN32
	if(listnersockcreate)
		ThreadPool.ExecuteTask(ls);
#endif

	while(!m_stopEvent && listnersockcreate)
	{
		start = now();
		diff = start - last_time;
		if(!((++loopcounter) % 10000))		// 5mins
		{
			ThreadPool.ShowStats();
			ThreadPool.IntegrityCheck();
#if !defined(WIN32) && defined(__DEBUG__)
			FILE* f = fopen("arcpro.uptime", "w");
			if(f)
			{
				fprintf(f, "%u %u %u %u", sWorld.GetUptime(), sWorld.GetSessionCount(), sWorld.PeakSessionCount, sWorld.mAcceptedConnections);
				fclose(f);
			}
#endif
		}

		/* since time() is an expensive system call, we only update it once per server loop */
		curTime = time(NULL);
		if(UNIXTIME != curTime)
		{
			UNIXTIME = time(NULL);
			g_localTime = *localtime(&curTime);
		}

		sSocketGarbageCollector.Update();

		/* UPDATE */
		last_time = now();
		etime = last_time - start;
		if(m_ShutdownEvent)
		{
			if(getMSTime() >= next_printout)
			{
				if(m_ShutdownTimer > 60000.0f)
				{
					if(!((int)(m_ShutdownTimer) % 60000))
						Log.Notice("Server", "Shutdown in %i minutes.", (int)(m_ShutdownTimer / 60000.0f));
				}
				else
					Log.Notice("Server", "Shutdown in %i seconds.", (int)(m_ShutdownTimer / 1000.0f));

				next_printout = getMSTime() + 500;
			}

			if(getMSTime() >= next_send)
			{
				int time = m_ShutdownTimer / 1000;
				if((time % 30 == 0) || time < 10)
				{
					// broadcast packet.
					WorldPacket data(20);
					data.SetOpcode(SMSG_SERVER_MESSAGE);
					if(m_restartEvent)
						data << uint32(SERVER_MSG_RESTART_TIME);
					else
						data << uint32(SERVER_MSG_SHUTDOWN_TIME);

					if(time > 0)
					{
						int mins = 0, secs = 0;
						if(time > 60)
							mins = time / 60;
						if(mins)
							time -= (mins * 60);
						secs = time;
						char str[20];
						snprintf(str, 20, "%02u:%02u", mins, secs);
						data << str;
						sWorld.SendGlobalMessage(&data, NULL);
					}
				}
				next_send = getMSTime() + 1000;
			}
			if(diff >= m_ShutdownTimer)
				break;
			else
				m_ShutdownTimer -= diff;
		}

		if(50 > etime)
		{

			arcpro::Sleep(50 - etime);

		}
	}
	_UnhookSignals();

	wr->SetThreadState(THREADSTATE_TERMINATE);
	ThreadPool.ShowStats();
	/* Shut down console system */
	console->terminate();
	delete console;

	// begin server shutdown
	Log.Success("Shutdown", "Initiated at %s", ConvertTimeStampToDataTime((uint32)UNIXTIME).c_str());

	if(lootmgr.is_loading)
	{
		Log.Notice("Shutdown", "Waiting for loot to finish loading...");
		while(lootmgr.is_loading)
			arcpro::Sleep(100);
	}

	// send a query to wake it up if its inactive
	Log.Notice("Database", "Clearing all pending queries...");

	// kill the database thread first so we don't lose any queries/data
	CharacterDatabase.EndThreads();
	WorldDatabase.EndThreads();

	Log.Notice("DayWatcherThread", "Exiting...");
	dw->terminate();
	dw = NULL;

	Log.Notice("CommonScheduleThread", "Exiting...");
	cs->terminate();
	cs = NULL;

	ls->Close();

	CloseConsoleListener();
	sWorld.SaveAllPlayers();

	Log.Notice("Network", "Shutting down network subsystem.");
#ifdef WIN32
	sSocketMgr.ShutdownThreads();
#endif
	sSocketMgr.CloseAll();

	bServerShutdown = true;
	ThreadPool.Shutdown();

	delete ls;

	sWorld.LogoutPlayers();

	delete LogonCommHandler::getSingletonPtr();

	sWorld.ShutdownClasses();
	Log.Notice("World", "~World()");
	delete World::getSingletonPtr();

	sScriptMgr.UnloadScripts();
	delete ScriptMgr::getSingletonPtr();

	Log.Notice("ChatHandler", "~ChatHandler()");
	delete ChatHandler::getSingletonPtr();

	Log.Notice("EventMgr", "~EventMgr()");
	delete EventMgr::getSingletonPtr();

	Log.Notice("Database", "Closing Connections...");
	_StopDB();

	Log.Notice("Network", "Deleting Network Subsystem...");
	delete SocketMgr::getSingletonPtr();
	delete SocketGarbageCollector::getSingletonPtr();

	delete GMCommand_Log;
	delete Anticheat_Log;
	delete Player_Log;

	// remove pid
	remove("ArcPro.pid");

	Log.Success("Shutdown", "Shutdown complete.");
	Log.Close();

#ifdef WIN32
	WSACleanup();

	// Terminate Entire Application
	//HANDLE pH = OpenProcess(PROCESS_TERMINATE, TRUE, GetCurrentProcessId());
	//TerminateProcess(pH, 0);
	//CloseHandle(pH);

#endif

	return true;
}
Example #23
0
/* Re-randomize the state of one strip.
 */
static void
reset_strip (ModeInfo *mi, strip *s)
{
  matrix_configuration *mp = &mps[MI_SCREEN(mi)];
  int i;
  Bool time_displayed_p = False;  /* never display time twice in one strip */

  memset (s, 0, sizeof(*s));
  s->x = (GLfloat) (frand(GRID_SIZE) - (GRID_SIZE/2));
  s->y = (GLfloat) (GRID_SIZE/2 + BELLRAND(0.5));      /* shift top slightly */
  s->z = (GLfloat) (GRID_DEPTH * 0.2) - frand (GRID_DEPTH * 0.7);
  s->spinner_y = 0;

  s->dx = 0;
/*  s->dx = ((BELLRAND(0.01) - 0.005) * speed); */
  s->dy = 0;
  s->dz = (BELLRAND(0.02) * speed);

  s->spinner_speed = (BELLRAND(0.3) * speed);

  s->spin_speed = (int) BELLRAND(2.0 / speed) + 1;
  s->spin_tick  = 0;

  s->wave_position = 0;
  s->wave_speed = (int) BELLRAND(3.0 / speed) + 1;
  s->wave_tick  = 0;

  for (i = 0; i < GRID_SIZE; i++)
    if (do_clock &&
        !time_displayed_p &&
        (i < GRID_SIZE-5) &&   /* display approx. once per 5 strips */
	!(random() % (GRID_SIZE-5)*5))
      {
	int j;
	char text[80], *p;
        time_t now = time ((time_t *) 0);
        struct tm *tm = localtime (&now);
#if 1	// hacked by katahiromz
	for(p = timefmt; *p; p++)
	  if (p[0] == '%' && p[1] == 'l') p[1] = 'I';
#endif
	strftime (text, sizeof(text)-1, timefmt, tm);

	/* render time into the strip */
	for (j = 0; j < strlen(text) && i < GRID_SIZE; j++, i++)
	  {
	    s->glyphs[i] = char_map [((unsigned char *) text)[j]] + 1;
	    s->highlight[i] = True;
	  }

        time_displayed_p = True;	
      }
    else
      {
	int draw_p = (random() % 7);
	int spin_p = (draw_p && !(random() % 20));
	int g = (draw_p
		 ? mp->glyph_map[(random() % mp->nglyphs)] + 1
		 : 0);
	if (spin_p) g = -g;
	s->glyphs[i] = g;
	s->highlight[i] = False;
      }

  s->spinner_glyph = - (mp->glyph_map[(random() % mp->nglyphs)] + 1);
}
static void node_to_xml(node_t* node, void *xml_struct)
{
    struct xml_node *xstruct = NULL;
    plist_data_t node_data = NULL;

    xmlNodePtr child_node = NULL;
    char isStruct = FALSE;
    char isUIDNode = FALSE;

    const xmlChar *tag = NULL;
    char *val = NULL;

    //for base64
    char *valtmp = NULL;

    uint32_t i = 0;

    if (!node)
        return;

    xstruct = (struct xml_node *) xml_struct;
    node_data = plist_get_data(node);

    switch (node_data->type)
    {
    case PLIST_BOOLEAN:
    {
        if (node_data->boolval)
            tag = XPLIST_TRUE;
        else
            tag = XPLIST_FALSE;
    }
    break;
	
    case PLIST_UINT:
        tag = XPLIST_INT;
        val = (char*)malloc(64);
        (void)_snprintf(val, 64, "%llu", node_data->intval);
        break;

    case PLIST_REAL:
        tag = XPLIST_REAL;
        val = (char*)malloc(64);
        (void)_snprintf(val, 64, "%f", node_data->realval);
        break;

    case PLIST_STRING:
        tag = XPLIST_STRING;
        val = strdup(node_data->strval);
        break;

    case PLIST_KEY:
        tag = XPLIST_KEY;
        val = strdup((char*) node_data->strval);
        break;

    case PLIST_DATA:
        tag = XPLIST_DATA;
        if (node_data->length)
        {
            size_t len = node_data->length;
            valtmp = base64encode(node_data->buff, &len);
            val = format_string(valtmp, len, 68, xstruct->depth);
            free(valtmp);
        }
        break;
    case PLIST_ARRAY:
        tag = XPLIST_ARRAY;
        isStruct = TRUE;
        break;
    case PLIST_DICT:
        tag = XPLIST_DICT;
        isStruct = TRUE;
        break;
    case PLIST_DATE:
        tag = XPLIST_DATE;
        {
            time_t time = (time_t)node_data->timeval.tv_sec;
            struct tm *btime = localtime(&time);
            if (btime) {
                val = (char*)malloc(24);
                memset(val, 0, 24);
                if (strftime(val, 24, "%Y-%m-%dT%H:%M:%SZ", btime) <= 0) {
                    free (val);
                    val = NULL;
                }
            }
        }
        break;
    case PLIST_UID:
        // special case for keyed encoding
        tag = XPLIST_DICT;
        isStruct = TRUE;
        isUIDNode = TRUE;
        node_data->type = PLIST_DICT;
        node_attach(node, new_key_node("CF$UID"));
        node_attach(node, new_uint_node(node_data->intval));
        break;
    default:
        break;
    }

    for (i = 0; i < xstruct->depth; i++)
    {
        xmlNodeAddContent(xstruct->xml, BAD_CAST("\t"));
    }
    if (node_data->type == PLIST_STRING) {
        /* make sure we convert the following predefined xml entities */
        /* < = &lt; > = &gt; ' = &apos; " = &quot; & = &amp; */
        child_node = xmlNewTextChild(xstruct->xml, NULL, tag, BAD_CAST(val));
    } else
        child_node = xmlNewChild(xstruct->xml, NULL, tag, BAD_CAST(val));
    xmlNodeAddContent(xstruct->xml, BAD_CAST("\n"));
    if (val) {
        free(val);
    }

    //add return for structured types
    if (node_data->type == PLIST_ARRAY || node_data->type == PLIST_DICT)
        xmlNodeAddContent(child_node, BAD_CAST("\n"));

    if (isStruct)
    {
        struct xml_node child = { child_node, xstruct->depth + 1 };
        node_iterator_t *ni = node_iterator_create(node->children);
        node_t *ch;
        while ((ch = node_iterator_next(ni))) {
            node_to_xml(ch, &child);
        }
        node_iterator_destroy(ni);
    }
    //fix indent for structured types
    if (node_data->type == PLIST_ARRAY || node_data->type == PLIST_DICT)
    {

        for (i = 0; i < xstruct->depth; i++)
        {
            xmlNodeAddContent(child_node, BAD_CAST("\t"));
        }
    }
    if (isUIDNode)
    {
        unsigned int num = node_n_children(node);
        unsigned int i;
        for (i = num; i > 0; i--) {
            node_t* ch = node_nth_child(node, i-1);
            node_detach(node, ch);
            node_destroy(ch);
        }
        node_data->type = PLIST_UID;
    }

    return;
}
Example #25
0
int
main(int argc, char *argv[])
{
    struct timezone tz;
    int ch, rflag;
    char *format, buf[1024], *outzone = NULL;

    setlocale(LC_ALL, "");

    tz.tz_dsttime = tz.tz_minuteswest = 0;
    rflag = 0;
    while ((ch = getopt(argc, argv, "ad:jr:ut:z:")) != -1)
        switch((char)ch) {
        case 'd':		/* daylight saving time */
            tz.tz_dsttime = atoi(optarg) ? 1 : 0;
            break;
        case 'a':
            slidetime++;
            break;
        case 'j':		/* don't set */
            jflag = 1;
            break;
        case 'r':		/* user specified seconds */
            rflag = 1;
            tval = atol(optarg);
            break;
        case 'u':		/* do everything in UTC */
            if (setenv("TZ", "UTC", 1) == -1)
                err(1, "cannot unsetenv TZ");
            break;
        case 't':		/* minutes west of GMT */
            /* error check; don't allow "PST" */
            if (isdigit(*optarg)) {
                tz.tz_minuteswest = atoi(optarg);
                break;
            }
        /* FALLTHROUGH */
        case 'z':
            outzone = optarg;
            break;
        default:
            usage();
        }
    argc -= optind;
    argv += optind;

    /*
     * If -d or -t, set the timezone or daylight saving time; this
     * doesn't belong here, the kernel should not know about either.
     */
    if ((tz.tz_minuteswest || tz.tz_dsttime) &&
            settimeofday(NULL, &tz))
        err(1, "settimeofday");

    if (!rflag && time(&tval) == -1)
        err(1, "time");

    format = "%a %b %e %H:%M:%S %Z %Y";

    /* allow the operands in any order */
    if (*argv && **argv == '+') {
        format = *argv + 1;
        argv++;
        argc--;
    }

    if (*argv) {
        setthetime(*argv);
        argv++;
        argc--;
    }

    if (*argv && **argv == '+') {
        format = *argv + 1;
        argc--;
    }

    if (argc > 0)
        errx(1, "too many arguments");

    if (outzone)
        setenv("TZ", outzone, 1);

    (void)strftime(buf, sizeof(buf), format, localtime(&tval));
    (void)printf("%s\n", buf);
    exit(retval);
}
Example #26
0
struct tm *getlt(void)
{
    time_t date;
    time (&date);
    return localtime(&date);
}
Example #27
0
void generateText(Main *main, Wind *wind, int *firstT, int *lastT, int *test)
{
    *lastT = SDL_GetTicks();
    if (*lastT > *firstT + 10)
    {
        SDL_Color black = {0, 0, 0};
        SDL_Surface *surfaceMessage;

        time_t now;
        time(&now);
        tm *myT = localtime(&now);

        *firstT = *lastT;
        

        /***** current time *****/
        sprintf(main->prog.genText, "current time %.2d:%.2d", myT->tm_hour, myT->tm_min);
        surfaceMessage = TTF_RenderText_Solid(main->draw.arial, main->prog.genText, black);
        if (main->timer.destroyTexture == 1)
            SDL_DestroyTexture(main->draw.tText[6].timeText);
        main->draw.tText[6].timeText = SDL_CreateTextureFromSurface(wind->renderer, surfaceMessage);
        SDL_FreeSurface(surfaceMessage);

    	/***** time when pressed *****/
    	sprintf(main->prog.genText, "time started %.2d:%.2d", main->timer.hPressed, main->timer.mPressed);
    	surfaceMessage = TTF_RenderText_Solid(main->draw.arial, main->prog.genText, black);
        if (main->timer.destroyTexture == 1)
            SDL_DestroyTexture(main->draw.tText[7].timeText);
    	main->draw.tText[7].timeText = SDL_CreateTextureFromSurface(wind->renderer, surfaceMessage);
        SDL_FreeSurface(surfaceMessage);


    	/***** time left *****/
    	sprintf(main->prog.genText, "time left %.2d:%.2d", main->timer.minCount, main->timer.secCount);
    	surfaceMessage = TTF_RenderText_Solid(main->draw.arial, main->prog.genText, black);
        if (main->timer.destroyTexture == 1)
            SDL_DestroyTexture(main->draw.tText[8].timeText);
    	main->draw.tText[8].timeText = SDL_CreateTextureFromSurface(wind->renderer, surfaceMessage);
        SDL_FreeSurface(surfaceMessage);

    	/***** show how long the session is *****/
    	sprintf(main->prog.genText, "%.2d minute session", main->timer.minutes);
    	surfaceMessage = TTF_RenderText_Solid(main->draw.arial, main->prog.genText, black);
        if (main->timer.destroyTexture == 1)
            SDL_DestroyTexture(main->draw.tText[9].timeText);
    	main->draw.tText[9].timeText = SDL_CreateTextureFromSurface(wind->renderer, surfaceMessage);
        SDL_FreeSurface(surfaceMessage);
    	

        /***** text for volume *****/
        sprintf(main->prog.genText, "%.2d", main->sound.volume);
        surfaceMessage = TTF_RenderText_Blended(main->draw.arial, main->prog.genText, black);
        if (main->timer.destroyTexture == 1)
            SDL_DestroyTexture(main->newText.volText);
        main->newText.volText = SDL_CreateTextureFromSurface(wind->renderer, surfaceMessage);
        SDL_FreeSurface(surfaceMessage);


        if (main->timer.destroyTexture == 0)
            main->timer.destroyTexture = 1;
       }
}
//int main (int argc, char * const argv[]) {
int main() {
	time_t startTime = time(0);
	time_t currentTime;
	unsigned long long sec;
	time_t treePairAverage = 0;

#ifndef MACOSX
	locale::global(locale("en_US.UTF-8"));
#endif //#ifdef MACOSX
	
	/*	chudInitialize();
	chudMarkPID(getpid(),1);
	chudAcquireRemoteAccess();
	chudStartRemotePerfMonitor("testthetester");*/
		
	Tree::binariseMode = false;
	wifstream input;
	wcout << "DATA_SET: " << DATA_SET << endl;
	//HomeCenter data
	if (DATA_SET == "HomeCentre") {
		NonTerminal::idBase.reset(500);
		Tree::pairedMode = true;
		input.open("/Users/ventzi/Desktop/курсове - университет/ATTEMPT/data/HomeCentre/new_manual.txt");
//		input.open("/Users/ventzi/Desktop/курсове - университет/ATTEMPT/data/HomeCentre/en-fr HomeCenter data.txt");
		//English-Spanish data
	} else if (DATA_SET == "en-sp") {
		Tree::pairedMode = false;
		input.open("/Users/ventzi/Desktop/курсове - университет/ATTEMPT/data/en-sp/pairs.txt");
		//English-German data
	} else if (DATA_SET == "en-de") {
		Tree::pairedMode = false;
		input.open("/Users/ventzi/Desktop/курсове - университет/ATTEMPT/data/en-de/10k/pairs.txt");
		//German News data
	} else if (DATA_SET == "de-news") {
		Tree::pairedMode = false;
		input.open("/Users/ventzi/Desktop/курсове - университет/ATTEMPT/data/de-news/pairs.txt");
	} else {
		exit(15);
	}
	
	//	exit(66);
	
	if (input.fail()) {
		wcout << "!!!Cannot open the pairs file!!!" << endl;
		exit(1);
	}
	
	TreePair treePair;
	int counter = 1;
	
	TreePair::linked = true;
	
	currentTime = time(0);
	
//	int pairNo = 1; //118
//	vector<TreePair> pairs;
	while (!input.eof()) {
		input >> treePair;
		if (!TreePair::error) {
//			pairs.push_back(treePair);
//			wcout << "size of treePair: " << sizeof(treePair) << endl;
//			exit(0);
			++counter;
			//			if (counter <= pairNo) continue;
//			wcout << "TreePair №" << counter - 1 << ":" << endl;
			//			treePair.printXML();
			//			wcout << treePair;
			//			wcout << ".";
//			wcout << endl;
			treePair.removeExtraNodes();
//			treePair.printTaggedSentences();
			treePair.printSentences();
//			treePair.freezeLinks();
//			treePair.printBracketed();
//			wcout << endl;
			//			if (counter > pairNo) break;
		} else {
			wcout << "TreePair №" << counter << ": !!!ERROR!!!" << endl;
		}
	}
	wcout << endl;
	
//	wcout << "Size of pairs: " <<  << endl;
	
	input.close();
	
	/*	chudStopRemotePerfMonitor();
	chudReleaseRemoteAccess();*/
	
	currentTime = time(0);
	tm* local = localtime(&currentTime);
	sec = difftime(currentTime, startTime);
	wcout << endl << "Elapsed: " << sec << "sec" << endl;
	wcout << "Finished at " << asctime(local);
	
	return 0;
}
Example #29
0
void rspfLocalTm::setTimeGivenEpoc(time_t ticks)
{
   *this = *localtime(&ticks);
}
Example #30
0
void print_message (int level, const struct message *msg) {
  begin_line ();
  print_spaces (level);
  struct user *user = 0;
  if (!disable_sql) {
    user = vk_db_lookup_user (msg->uid);
    if (!user) {
      aio_profiles_get (1, &msg->uid, 1);
    }
  }
  static char buf[1001];
  int len;
  /*
  if (!user) {  
    len = snprintf (buf, 1000, "Message #%d %s user %d", msg->id, msg->out ? "to" : "from", msg->uid);
  } else {
    len = snprintf (buf, 1000, "Message #%d %s user %d (%s %s)", msg->id, msg->out ? "to" : "from", msg->uid, user->first_name, user->last_name);
  }*/
  if (msg->out) {
    len = snprintf (buf, 1000, COLOR_RED);
  } else {
    len = snprintf (buf, 1000, COLOR_GREEN);
  }
  if (msg->chat_id) {
    len += snprintf (buf + len, 1000 - len, "Chat %s: ", msg->title);
    if (len >= 1000) { len = 1000; }
  }
  if (!user) {
    len += snprintf (buf + len, 1000 - len, "id%d ", msg->uid);
  } else {
    len += snprintf (buf + len, 1000 - len, "%s %s ", user->first_name, user->last_name);
  }
  add_string_line (buf, len);
  //end_line ();
  //begin_line ();

  int now = time (0);

  long _t = msg->date;
  struct tm *lctime = localtime ((void *)&_t);
  print_spaces (level + 1);

  if (now - msg->date <= 60 * 60 * 12) {
    len = snprintf (buf, 1000, "%02d:%02d ", lctime->tm_hour, lctime->tm_min);
  } else if (now - msg->date <= 60 * 60 * 24 * 30) {
    len = snprintf (buf, 1000, "%02d-%02d %02d:%02d ", lctime->tm_mon + 1, lctime->tm_mday, lctime->tm_hour, lctime->tm_min);
  } else {
    len = snprintf (buf, 1000, "%04d-%02d-%02d %02d:%02d ", lctime->tm_year + 1900, lctime->tm_mon + 1, lctime->tm_mday, lctime->tm_hour, lctime->tm_min);
  }
  /*len = snprintf (buf, 1000, "Created at [%04d-%02d-%02d %02d:%02d:%02d], state %s", 
    lctime->tm_year + 1900, lctime->tm_mon + 1, lctime->tm_mday, 
    lctime->tm_hour, lctime->tm_min, lctime->tm_sec,
    msg->deleted ? "deleted" : msg->read_state ? "read" : "unread");*/
  add_string_line (buf, len);
  
  len = snprintf (buf, 1000, "%s " COLOR_NORMAL, msg->out ? "<<<" : ">>>");
  add_string_line (buf, len);
  if (message_has_line_break (msg->body)) {
    end_line ();
    begin_line ();
    print_message_text (level + 1, msg->body ? msg->body : "<none>");
  } else {
    print_message_text (-1, msg->body ? msg->body : "<none>");
    if (line_pos) {
      end_line ();
    }
  }
  /*begin_line ();
  print_spaces (level + 1);
  if (msg->chat_id <= 0) {
    len = snprintf (buf, 1000, "No chat");
  } else {
    len = snprintf (buf, 1000, "Chat_id %d", msg->chat_id);
  }
  add_string_line (buf, len);
  end_line ();*/
}