Пример #1
0
main(int argc, char *argv[])
{
    if (TestAndLock()) {
        fprintf(stderr, "Another unwind running or abandoned, please check\n");
        exit(EXIT_FAILURE);
    }
    ParseArgs(argc, argv);

    InitSignals();

    InitLog();

    if (chdir(CodaUserDir)) {
        RemoveLock();
        Die("Could not cd into %s", CodaUserDir);
    }
    if (InitDB(DataBaseName)) {
        RemoveLock();
        fprintf(stderr, "Could not connect to database %s", DataBaseName);
        exit(EXIT_FAILURE);
    }
    LogMsg(100, LogLevel, LogFile, "Enter ProcessEachUser");
    ProcessEachUser();
    RemoveLock();
    Log_Done();
}
Пример #2
0
main (int argc, char *argv[])
{
    if (TestAndLock()) {
	fprintf(stderr,
		"Another unwind running or abandoned, please check\n");
	exit(-1);
    }
    ParseArgs(argc, argv);
    InitSignals();
    InitLog();
    if (chdir(WorkingDir)) {
	RemoveLock();
	Die("Could not cd into %s",WorkingDir);
    }
    if (InitDB(DataBaseName)) {
	RemoveLock();
	fprintf(stderr,"Could not connect to database %s",DataBaseName);
	exit(-1);
    }
    GetFilesAndSpool();
    RemoveLock();
    Log_Done();
}
Пример #3
0
/**
 *  @retval >0 Number of threads still working
 *  @retval 0  All threads are done
 *  @retval -1 Server didn't run
 */
int StartServer(EvalContext *ctx, Policy **policy, GenericAgentConfig *config)
{
    InitSignals();
    ServerTLSInitialize();
    int sd = SetServerListenState(ctx, QUEUESIZE, SERVER_LISTEN, &InitServer);

    /* Necessary for our use of select() to work in WaitForIncoming(): */
    assert(sd < sizeof(fd_set) * CHAR_BIT &&
           GetSignalPipe() < sizeof(fd_set) * CHAR_BIT);

    Policy *server_cfengine_policy = PolicyNew();
    CfLock thislock = AcquireServerLock(ctx, config, server_cfengine_policy);
    if (thislock.lock == NULL)
    {
        PolicyDestroy(server_cfengine_policy);
        if (sd >= 0)
        {
            cf_closesocket(sd);
        }
        return -1;
    }

    PrepareServer(sd);
    CollectCallStart(COLLECT_INTERVAL);

    while (!IsPendingTermination())
    {
        CollectCallIfDue(ctx);

        int selected = WaitForIncoming(sd);

        Log(LOG_LEVEL_DEBUG, "select(): %d", selected);
        if (selected == -1)
        {
            Log(LOG_LEVEL_ERR,
                "Error while waiting for connections. (select: %s)",
                GetErrorStr());
            break;
        }
        else if (selected >= 0) /* timeout or success */
        {
            PolicyUpdateIfSafe(ctx, policy, config);

            /* Is there a new connection pending at our listening socket? */
            if (selected > 0)
            {
                AcceptAndHandle(ctx, sd);
            }
        } /* else: interrupted, maybe pending termination. */
    }
    Log(LOG_LEVEL_NOTICE, "Cleaning up and exiting...");

    CollectCallStop();
    if (sd != -1)
    {
        Log(LOG_LEVEL_VERBOSE, "Closing listening socket");
        cf_closesocket(sd);                       /* Close listening socket */
    }

    /* This is a graceful exit, give 2 seconds chance to threads. */
    int threads_left = WaitOnThreads();
    YieldCurrentLock(thislock);
    PolicyDestroy(server_cfengine_policy);

    return threads_left;
}
Пример #4
0
void Anope::Init(int ac, char **av)
{
	/* Set file creation mask and group ID. */
#if defined(DEFUMASK) && HAVE_UMASK
	umask(DEFUMASK);
#endif

	/* Parse command line arguments */
	ParseCommandLineArguments(ac, av);

	if (GetCommandLineArgument("version", 'v'))
	{
		Log(LOG_TERMINAL) << "Anope-" << Anope::Version() << " -- " << Anope::VersionBuildString();
		throw CoreException();
	}

	if (GetCommandLineArgument("help", 'h'))
	{
		Log(LOG_TERMINAL) << "Anope-" << Anope::Version() << " -- " << Anope::VersionBuildString();
		Log(LOG_TERMINAL) << "Anope IRC Services (http://www.anope.org)";
		Log(LOG_TERMINAL) << "Usage ./" << Anope::ServicesBin << " [options] ...";
		Log(LOG_TERMINAL) << "-c, --config=filename.conf";
		Log(LOG_TERMINAL) << "    --confdir=conf file direcory";
		Log(LOG_TERMINAL) << "    --dbdir=database directory";
		Log(LOG_TERMINAL) << "-d, --debug[=level]";
		Log(LOG_TERMINAL) << "-h, --help";
		Log(LOG_TERMINAL) << "    --localedir=locale directory";
		Log(LOG_TERMINAL) << "    --logdir=logs directory";
		Log(LOG_TERMINAL) << "    --modulesdir=modules directory";
		Log(LOG_TERMINAL) << "-e, --noexpire";
		Log(LOG_TERMINAL) << "-n, --nofork";
		Log(LOG_TERMINAL) << "    --nothird";
		Log(LOG_TERMINAL) << "    --protocoldebug";
		Log(LOG_TERMINAL) << "-r, --readonly";
		Log(LOG_TERMINAL) << "-s, --support";
		Log(LOG_TERMINAL) << "-v, --version";
		Log(LOG_TERMINAL) << "";
		Log(LOG_TERMINAL) << "Further support is available from http://www.anope.org";
		Log(LOG_TERMINAL) << "Or visit us on IRC at irc.anope.org #anope";
		throw CoreException();
	}

	if (GetCommandLineArgument("nofork", 'n'))
		Anope::NoFork = true;

	if (GetCommandLineArgument("support", 's'))
	{
		Anope::NoFork = Anope::NoThird = true;
		++Anope::Debug;
	}

	if (GetCommandLineArgument("readonly", 'r'))
		Anope::ReadOnly = true;

	if (GetCommandLineArgument("nothird"))
		Anope::NoThird = true;

	if (GetCommandLineArgument("noexpire", 'e'))
		Anope::NoExpire = true;

	if (GetCommandLineArgument("protocoldebug"))
		Anope::ProtocolDebug = true;

	Anope::string arg;
	if (GetCommandLineArgument("debug", 'd', arg))
	{
		if (!arg.empty())
		{
			int level = arg.is_number_only() ? convertTo<int>(arg) : -1;
			if (level > 0)
				Anope::Debug = level;
			else
				throw CoreException("Invalid option given to --debug");
		}
		else
			++Anope::Debug;
	}

	if (GetCommandLineArgument("config", 'c', arg))
	{
		if (arg.empty())
			throw CoreException("The --config option requires a file name");
		ServicesConf = Configuration::File(arg, false);
	}

	if (GetCommandLineArgument("confdir", 0, arg))
	{
		if (arg.empty())
			throw CoreException("The --confdir option requires a path");
		Anope::ConfigDir = arg;
	}

	if (GetCommandLineArgument("dbdir", 0, arg))
	{
		if (arg.empty())
			throw CoreException("The --dbdir option requires a path");
		Anope::DataDir = arg;
	}

	if (GetCommandLineArgument("localedir", 0, arg))
	{
		if (arg.empty())
			throw CoreException("The --localedir option requires a path");
		Anope::LocaleDir = arg;
	}

	if (GetCommandLineArgument("modulesdir", 0, arg))
	{
		if (arg.empty())
			throw CoreException("The --modulesdir option requires a path");
		Anope::ModuleDir = arg;
	}

	if (GetCommandLineArgument("logdir", 0, arg))
	{
		if (arg.empty())
			throw CoreException("The --logdir option requires a path");
		Anope::LogDir = arg;
	}

	/* Chdir to Services data directory. */
	if (chdir(Anope::ServicesDir.c_str()) < 0)
	{
		throw CoreException("Unable to chdir to " + Anope::ServicesDir + ": " + Anope::LastError());
	}

	Log(LOG_TERMINAL) << "Anope " << Anope::Version() << ", " << Anope::VersionBuildString();

#ifdef _WIN32
	if (!SupportedWindowsVersion())
		throw CoreException(GetWindowsVersion() + " is not a supported version of Windows");
#else
	/* If we're root, issue a warning now */
	if (!getuid() && !getgid())
	{
		/* If we are configured to setuid later, don't issue a warning */
		Configuration::Block *options = Config->GetBlock("options");
		if (options->Get<Anope::string>("user").empty())
		{
			std::cerr << "WARNING: You are currently running Anope as the root superuser. Anope does not" << std::endl;
			std::cerr << "         require root privileges to run, and it is discouraged that you run Anope" << std::endl;
			std::cerr << "         as the root superuser." << std::endl;
			sleep(3);
		}
	}
#endif

#ifdef _WIN32
	Log(LOG_TERMINAL) << "Using configuration file " << Anope::ConfigDir << "\\" << ServicesConf.GetName();
#else
	Log(LOG_TERMINAL) << "Using configuration file " << Anope::ConfigDir << "/" << ServicesConf.GetName();

	/* Fork to background */
	if (!Anope::NoFork)
	{
		/* Install these before fork() - it is possible for the child to
		 * connect and kill() the parent before it is able to install the
		 * handler.
		 */
		struct sigaction sa, old_sigusr2, old_sigchld;

		sa.sa_flags = 0;
		sigemptyset(&sa.sa_mask);
		sa.sa_handler = parent_signal_handler;

		sigaction(SIGUSR2, &sa, &old_sigusr2);
		sigaction(SIGCHLD, &sa, &old_sigchld);

		int i = fork();
		if (i > 0)
		{
			sigset_t mask;

			sigemptyset(&mask);
			sigsuspend(&mask);

			exit(Anope::ReturnValue);
		}
		else if (i == -1)
		{
			Log() << "Error, unable to fork: " << Anope::LastError();
			Anope::NoFork = true;
		}

		/* Child doesn't need these */
		sigaction(SIGUSR2, &old_sigusr2, NULL);
		sigaction(SIGCHLD, &old_sigchld, NULL);
	}

#endif

	/* Initialize the socket engine. Note that some engines can not survive a fork(), so this must be here. */
	SocketEngine::Init();

	ServiceManager::Init();
	EventManager::Init();

	new BotInfoType();
	new XLineType(nullptr);
	new OperBlockType();

	/* Read configuration file; exit if there are problems. */
	try
	{
		Config = new Configuration::Conf();
	}
	catch (const ConfigException &ex)
	{
		Log(LOG_TERMINAL) << ex.GetReason();
		Log(LOG_TERMINAL) << "*** Support resources: Read through the anope.conf self-contained";
		Log(LOG_TERMINAL) << "*** documentation. Read the documentation files found in the 'docs'";
		Log(LOG_TERMINAL) << "*** folder. Visit our portal located at http://www.anope.org/. Join";
		Log(LOG_TERMINAL) << "*** our support channel on /server irc.anope.org channel #anope.";
		throw CoreException("Configuration file failed to validate");
	}

	/* Create me */
	Configuration::Block *block = Config->GetBlock("serverinfo");
	Me = new Server(NULL, block->Get<Anope::string>("name"), 0, block->Get<Anope::string>("description"), block->Get<Anope::string>("id"));
	for (std::pair<Anope::string, User *> p : UserListByNick)
	{
		User *u = p.second;
		if (u->type != UserType::BOT)
			continue;

		ServiceBot *bi = anope_dynamic_static_cast<ServiceBot *>(u);
		bi->server = Me;
		++Me->users;
	}

	/* Announce ourselves to the logfile. */
	Log() << "Anope " << Anope::Version() << " starting up" << (Anope::Debug || Anope::ReadOnly ? " (options:" : "") << (Anope::Debug ? " debug" : "") << (Anope::ReadOnly ? " readonly" : "") << (Anope::Debug || Anope::ReadOnly ? ")" : "");

	InitSignals();

	/* Initialize multi-language support */
	Language::InitLanguages();

	/* Initialize random number generator */
	block = Config->GetBlock("options");
	srand(block->Get<unsigned>("seed") ^ time(NULL));

	ModeManager::Apply(nullptr);

	/* load modules */
	Log() << "Loading modules...";
	for (int i = 0; i < Config->CountBlock("module"); ++i)
		ModuleManager::LoadModule(Config->GetBlock("module", i)->Get<Anope::string>("name"), NULL);

#ifndef _WIN32
	/* We won't background later, so we should setuid now */
	if (Anope::NoFork)
		setuidgid();
#endif

	Module *protocol = ModuleManager::FindFirstOf(PROTOCOL);
	if (protocol == NULL)
		throw CoreException("You must load a protocol module!");

	/* Write our PID to the PID file. */
	write_pidfile();

	Log() << "Using IRCd protocol " << protocol->name;

	/* Auto assign sid if applicable */
	if (IRCD->RequiresID)
	{
		Anope::string sid = IRCD->SID_Retrieve();
		if (Me->GetSID() == Me->GetName())
			Me->SetSID(sid);
		for (std::pair<Anope::string, User *> p : UserListByNick)
		{
			User *u = p.second;
			if (u->type != UserType::BOT)
				continue;

			ServiceBot *bi = anope_dynamic_static_cast<ServiceBot *>(u);
			bi->GenerateUID();
		}
	}

	/* Load up databases */
	Log() << "Loading databases...";
	EventReturn MOD_RESULT = EventManager::Get()->Dispatch(&Event::LoadDatabase::OnLoadDatabase);;
	static_cast<void>(MOD_RESULT);
	Log() << "Databases loaded";

	for (channel_map::const_iterator it = ChannelList.begin(), it_end = ChannelList.end(); it != it_end; ++it)
		it->second->Sync();
}
Пример #5
0
int main(int argc, char *argv[])
{
#if !defined DEBUGMODE && !defined DAEMONTOOLS
	pid_t pid; /* pid of this process */
#endif /* !DEBUGMODE && !DAEMONTOOLS */

#ifdef GDB_DEBUG

	int GDBAttached = 0;
#endif /* GDB_DEBUG */

#if defined GIMMECORE || defined DEBUGMODE

	struct rlimit rlim; /* resource limits -kre */
#endif /* GIMMECORE || DEBUGMODE */

	FILE *pidfile; /* to write our pid */
	uid_t uid; /* real user id */
	uid_t euid; /* effective user id */

#if defined HAVE_BOEHM_GC
	GC_INIT();
#endif /* HAVE_BOEHM_GC */

	myargv = argv;

	/* Initialise current TS for services -kre */
	TimeStarted = current_ts = time(NULL);

	/* Be sure, be paranoid, be safe. -kre */
	umask(077);

	fprintf(stderr,
	        "Hybserv2 TS services version %s by Hybserv2 team\n"
#if defined __DATE__ && defined __TIME__
	        "Compiled at %s, %s\n",
#endif
	        hVersion
#if defined __DATE__ && defined __TIME__
	        , __DATE__, __TIME__
#endif
	       );

#ifdef GDB_DEBUG

	while (!GDBAttached)
		sleep(1);
#endif /* GDB_DEBUG */

	/*
	 * Load SETPATH (settings.conf) - this must be done
	 * before the config file is loaded, and before any
	 * putlog() calls are made, since LogFile is specified
	 * in settings.conf
	 */
	if (LoadSettings(0) == 0)
	{
		fprintf(stderr, "Fatal errors encountered parsing %s, exiting\n"
		        "Check logfile %s/%s\n", SETPATH, LogPath ? LogPath : "",
		        LogFile ?  LogFile : "*unknown*");
		return (0);
	}

	/*
	 * If they run ./shownicks or ./showchans rather than ./hybserv
	 * display nicknames/channels
	 */
	if (strstr(argv[0], "shownicks"))
	{
#ifdef NICKSERVICES
		ShowNicknames(argc, argv);
#endif /* NICKSERVICES */

		return (0);
	}
	else if (strstr(argv[0], "showchans"))
	{
#if defined(NICKSERVICES) && defined(CHANNELSERVICES)
		ShowChannels(argc, argv);
#endif /* defined(NICKSERVICES) && defined(CHANNELSERVICES) */

		return 0;
	}

	/* Check for running services -kre */
	if ((pidfile = fopen(PidFile, "r")) == NULL)
		fprintf(stderr, "WARNING: Unable to read pid file %s\n",
		        PidFile);
	else
	{
		pid_t mypid;
		char line[MAXLINE + 1];

		if (fgets(line, sizeof(line), pidfile) != NULL)
		{
			mypid = atoi(line);
			if (mypid && !kill(mypid, 0))
			{
				fprintf(stderr, "FATAL: Services are already running!\n");
				fclose(pidfile);
				exit(EXIT_FAILURE);
			}
		}
		fclose(pidfile);
	}

	uid = getuid(); /* the user id of the user who ran the process */
	euid = geteuid(); /* the effective id (different if setuid) */

	if (!uid || !euid)
	{
		fprintf(stderr,
		        "FATAL: Please don't run services as root. Now exiting.\n");
		exit(EXIT_FAILURE);
	}

	if (chdir(HPath) != 0)
	{
		fprintf(stderr,
		        "HPath is an invalid directory, please check %s\n",
		        SETPATH);
		exit(EXIT_FAILURE);
	}

	putlog(LOG1, "Hybserv2 TS services version %s started", hVersion);

	/* Get the offset from GMT (London time) */
	gmt_offset = GetTZOffset(TimeStarted);

	/*
	 * the Network list must be initialized before the config
	 * file is loaded
	 */
	InitLists();

	/* load server, jupe, gline, user, admin info */
	LoadConfig();

	/* load nick/chan/memo/stat databases */
	LoadData();

#ifdef GLOBALSERVICES

	if (LogonNews)
	{
		Network->LogonNewsFile.filename = LogonNews;
		ReadMessageFile(&Network->LogonNewsFile);
	}

#endif /* GLOBALSERVICES */

	if (LocalHostName)
		SetupVirtualHost();

#if !defined DEBUGMODE && !defined GDB_DEBUG

	/* Daemontools compatibility stuff */
#ifndef DAEMONTOOLS

	pid = fork();
	if (pid == -1)
	{
		printf("Unable to fork(), exiting.\n");
		exit(EXIT_FAILURE);
	}
	if (pid != 0)
	{
		printf("Running in background (pid: %d)\n", (int)pid);
		exit(EXIT_SUCCESS);
	}

	close(STDIN_FILENO);
	close(STDOUT_FILENO);
	close(STDERR_FILENO);

	/* Make current process session leader -kre */
	if (setsid() == -1)
	{
		exit(EXIT_FAILURE);
	}
#else

	printf("Entering foreground debug mode\n");
#endif /* DEBUGMODE */
#endif /* DAEMONTOOLS */

#if defined GIMMECORE || defined DEBUGMODE

	printf("Setting corefile limit... ");
	/* Set corefilesize to maximum - therefore we ensure that core will be
	 * generated, no matter of shell limits -kre */
	getrlimit(RLIMIT_CORE, &rlim);
	rlim.rlim_cur = rlim.rlim_max;
	setrlimit(RLIMIT_CORE, &rlim);
	printf("done.\n");
#endif /* GIMMECORE || DEBUGMODE */

	/* Signals must be set up after fork(), since the parent exits */
	InitSignals();

	/* Initialise random number generator -kre */
	srandom(current_ts);
	srandom((unsigned int)random());

	/* Write our pid to a file */
	if ((pidfile = fopen(PidFile, "w")) == NULL)
		putlog(LOG1, "Unable to open %s", PidFile);
	else
	{
		char line[MAXLINE + 1];

		ircsprintf(line, "%d\n", getpid());
		fputs(line, pidfile);
		fclose(pidfile);
	}

	/* initialize tcm/user listening ports */
	InitListenPorts();

	/* initialize hash tables */
	ClearHashes(1);

#ifdef BLOCK_ALLOCATION

	InitHeaps();
#endif

	HubSock = NOSOCKET;
	CycleServers();

	while (1)
	{
		/* enter loop waiting for server info */
		ReadSocketInfo();

		if (Me.hub)
			SendUmode(OPERUMODE_Y, "*** Disconnected from %s", Me.hub->name);
		else
			SendUmode(OPERUMODE_Y, "*** Disconnected from hub server");

		if (currenthub)
		{
			if (currenthub->realname)
			{
				MyFree(currenthub->realname);
				currenthub->realname = NULL;
			}
			currenthub->connect_ts = 0;
		}

		close(HubSock); /* There was an error */
		HubSock = NOSOCKET;

		/*
		 * whenever Hybserv connects/reconnects to a server, clear
		 * users, servers, and chans
		 */
		ClearUsers();
		ClearChans();
		ClearServs();
		/*
		 * ClearHashes() must be called AFTER ClearUsers(),
		 * or StatServ's unique client counts will be off since
		 * cloneTable[] would be NULL while it was trying to find
		 * clones
		 */
		ClearHashes(0);

		PostCleanup();
	} /* while (1) */

	return 0;
} /* main() */
Пример #6
0
Mineserver::Mineserver(int args, char **argarray)
    :  argv(argarray),
       argc(args),
       m_socketlisten  (0),
       m_saveInterval  (0),
       m_lastSave      (std::time(NULL)),
       m_pvp_enabled   (false),
       m_damage_enabled(false),
       m_only_helmets  (false),
       m_running       (false),
       m_eventBase     (NULL),

       // core modules
       m_config        (new Config()),
       m_screen        (new CliScreen()),
       m_logger        (new Logger()),

       m_plugin        (NULL),
       m_chat          (NULL),
       m_furnaceManager(NULL),
       m_packetHandler (NULL),
       m_inventory     (NULL),
       m_mobs          (NULL)
{
    pthread_mutex_init(&m_validation_mutex,NULL);
    ServerInstance = this;
    InitSignals();

    std::srand((uint32_t)std::time(NULL));
    initPRNG();

    std::string cfg;
    std::vector<std::string> overrides;

    for (int i = 1; i < argc; i++)
    {
        const std::string arg(argv[i]);

        switch (arg[0])
        {
        case '-':   // option
            // we have only '-h' and '--help' now, so just return with help
            printHelp(0);
            throw CoreException();

        case '+':   // override
            overrides.push_back(arg.substr(1));
            break;

        default:    // otherwise, it is config file
            if (!cfg.empty())
                throw CoreException("Only single CONFIG_FILE argument is allowed!");
            cfg = arg;
            break;
        }
    }

    const std::string path_exe = "./";

    // If config file is provided as an argument
    if (!cfg.empty())
    {
        std::cout << "Searching for configuration file..." << std::endl;
        if (fileExists(cfg))
        {
            const std::pair<std::string, std::string> fullpath = pathOfFile(cfg);
            cfg = fullpath.first + PATH_SEPARATOR + fullpath.second;
            this->config()->config_path = fullpath.first;
        }
        else
        {
            std::cout << "Config not found...\n";;
            cfg.clear();
        }
    }

    if (cfg.empty())
    {
        if (fileExists(path_exe + PATH_SEPARATOR + CONFIG_FILE))
        {
            cfg = path_exe + PATH_SEPARATOR + CONFIG_FILE;
            this->config()->config_path = path_exe;
        }
        else
        {
            std::cout << "Config not found\n";
        }
    }

    // load config
    Config &configvar = *this->config();
    if (!configvar.load(cfg))
    {
        throw CoreException("Could not load config!");
    }

    m_plugin = new Plugin();

    LOG2(INFO, "Using config: " + cfg);

    if (overrides.size())
    {
        std::stringstream override_config;
        for (size_t i = 0; i < overrides.size(); i++)
        {
            LOG2(INFO, "Overriden: " + overrides[i]);
            override_config << overrides[i] << ';' << std::endl;
        }
        // override config
        if (!configvar.load(override_config))
            throw CoreException("Error when parsing overrides: maybe you forgot to doublequote string values?");
    }

    memset(&m_listenEvent, 0, sizeof(event));
    initConstants();
    // Write PID to file
    std::ofstream pid_out((config()->sData("system.pid_file")).c_str());
    if (!pid_out.fail())
    {
        pid_out << getpid();
    }
    pid_out.close();




    init_plugin_api();

    if (config()->bData("system.interface.use_cli"))
    {
        // Init our Screen
        screen()->init(VERSION);
    }


    LOG2(INFO, "Welcome to Mineserver v" + VERSION);
    LOG2(INFO, "Using zlib "+std::string(ZLIB_VERSION)+" libevent "+std::string(event_get_version()));

    LOG2(INFO, "Generating RSA key pair for protocol encryption");
    //Protocol encryption
    srand(microTime());
    if((rsa = RSA_generate_key(1024, 17, 0, 0)) == NULL)
    {
        LOG2(INFO, "KEY GENERATION FAILED!");
        exit(1);
    }
    LOG2(INFO, "RSA key pair generated.");

    /* Get ASN.1 format public key */
    x=X509_new();
    pk=EVP_PKEY_new();
    EVP_PKEY_assign_RSA(pk,rsa);
    X509_set_version(x,0);
    X509_set_pubkey(x,pk);

    int len;
    unsigned char *buf;
    buf = NULL;
    len = i2d_X509(x, &buf);

    //Glue + jesus tape, dont ask - Fador
    publicKey = std::string((char *)(buf+28),len-36);
    OPENSSL_free(buf);
    /* END key fetching */

    const std::string temp_nums="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890=-";

    const std::string temp_hex="0123456789abcdef";

    for(int i = 0; i < 4; i++)
    {
        encryptionBytes += (char)(temp_nums[rand()%temp_nums.size()]);
    }

    for(int i = 0; i < 16; i++)
    {
        serverID += (char)(temp_hex[rand()%temp_hex.size()]);
    }

    LOG2(INFO, "ServerID: " + serverID);

    if(!m_config->bData("system.user_validation"))
    {
        serverID = "-";
    }

    MapGen* mapgen = new MapGen();
    MapGen* nethergen = new NetherGen();
    MapGen* heavengen = new HeavenGen();
    MapGen* biomegen = new BiomeGen();
    MapGen* eximgen = new EximGen();
    m_mapGenNames.push_back(mapgen);
    m_mapGenNames.push_back(nethergen);
    m_mapGenNames.push_back(heavengen);
    m_mapGenNames.push_back(biomegen);
    m_mapGenNames.push_back(eximgen);

    m_saveInterval = m_config->iData("map.save_interval");

    m_only_helmets = m_config->bData("system.armour.helmet_strict");
    m_pvp_enabled = m_config->bData("system.pvp.enabled");
    m_damage_enabled = m_config->bData("system.damage.enabled");

    const char* key = "map.storage.nbt.directories"; // Prefix for worlds config
    if (m_config->has(key) && (m_config->type(key) == CONFIG_NODE_LIST))
    {
        std::list<std::string> tmp = m_config->mData(key)->keys();
        int n = 0;
        for (std::list<std::string>::const_iterator it = tmp.begin(); it != tmp.end(); ++it)
        {
            m_map.push_back(new Map());
            Physics* phy = new Physics;
            phy->map = n;

            m_physics.push_back(phy);
            RedstoneSimulation* red = new RedstoneSimulation;
            red->map = n;
            m_redstone.push_back(red);
            int k = m_config->iData((std::string(key) + ".") + (*it));
            if ((uint32_t)k >= m_mapGenNames.size())
            {
                std::ostringstream s;
                s << "Error! Mapgen number " << k << " in config. " << m_mapGenNames.size() << " Mapgens known";
                LOG2(INFO, s.str());
            }
            // WARNING: if k is too big this will be an access error! -- louisdx
            MapGen* m = m_mapGenNames[k];
            m_mapGen.push_back(m);
            n++;
        }
    }
    else
    {
        LOG2(WARNING, "Cannot find map.storage.nbt.directories.*");
    }

    if (m_map.size() == 0)
        throw CoreException("No worlds in Config");

    m_chat           = new Chat;
    m_furnaceManager = new FurnaceManager;
    m_packetHandler  = new PacketHandler;
    m_inventory      = new Inventory(m_config->sData("system.path.data") + '/' + "recipes", ".recipe", "ENABLED_RECIPES.cfg");
    m_mobs           = new Mobs;

} // End Mineserver constructor
Пример #7
0
int main(int argc, char **argv)
{
int i;
int timeout  = 10;
int si       =  1;
int debug    =  0;
THREAD tid;
char *pwd, *sta = NULL;
char RunFile[MAXPATHLEN+1], *log = (char *) NULL;
static char LogFile[MAXPATHLEN+1];
static char *default_server = "localhost";
ISP_SERVER ispd;
time_t idle = 600;

    server = default_server;

    for (i = 1; i < argc; i++) {
        if (strncasecmp(argv[i], "home=", strlen("home=")) == 0) {
            home = argv[i] + strlen("home=");
        } else if (strncasecmp(argv[i], "sta=", strlen("sta=")) == 0) {
            sta = argv[i] + strlen("sta=");
        } else if (strncasecmp(argv[i], "debug=", strlen("debug=")) == 0) {
            debug = atoi(argv[i] + strlen("debug="));
        } else if (strncasecmp(argv[i], "idle=", strlen("idle=")) == 0) {
            idle = atoi(argv[i] + strlen("idle="));
        } else if (strcasecmp(argv[i], "-h") == 0) {
            help(argv[0]);
        } else if (strcasecmp(argv[i], "help") == 0) {
            help(argv[0]);
        } else if (sta == (char *) NULL) {
            sta = argv[i];
        } else {
            help(argv[0]);
        }
    }

    SetMaxIdle(idle);

    if ((pwd = isp_setup(&home, &sta)) == (char *) NULL) exit(1);
    if ((Syscode = strdup(sta)) == NULL) {
        perror(argv[0]);
        exit(1);
    }
    util_lcase(Syscode);
    sprintf(RunFile, "%s/%s", pwd, ISP_RUN_FILE);
    if (!ispLoadRunParam(RunFile, sta, NULL, &ispd)) {
        fprintf(stderr, "%s: problems with parameter file\n", argv[0]);
        exit(1);
    }

    if (debug) util_logopen("syslogd", 1, 9, debug, "CONSOLE", argv[0]);

    console = (getppid() == 1);
    if (console) util_log(1, "Running as BOOT CONSOLE");

/* Start signal handling thread */

    InitSignals();

/* Allocate space for channel map */

    InitChanMap();

/* Initialize the display */

    sprintf(LogFile, "%s/log/nrtslog", home);
    if (OpenDisplay(server, ispd.port, LogFile) != 0) {
        fprintf(stderr, "%s: ABORT: Can't open display\n", argv[0]);
        sleep(1);
        Quit(1);
    }

/* Connect to the server */

    ServerConnect(server, ispd.port, ispd.to, TRUE);

/* Start status request thread */

    util_log(1, "Start routine status requests");
    if (!THREAD_CREATE(&tid, StatusRequest, NULL)) {
        EndWin();
        fprintf(stderr, "failed to create StatusRequest thread\n");
        exit(1);
    }

/* Start interactive thread */

    util_log(1, "Start interactive display");
    FirstDisplay();
    while (1) {
        switch (Digitizer()) {
          case ISP_DAS:
            util_log(1, "ISP_DAS detected, start DasDisplay");
            if (!THREAD_CREATE(&tid, DasDisplay, NULL)) {
                EndWin();
                fprintf(stderr, "failed to create DasDisplay thread\n");
                exit(1);
            }
            THREAD_EXIT(0);
          case ISP_SAN:
            util_log(1, "ISP_San detected, start SanDisplay");
            if (!THREAD_CREATE(&tid, SanDisplay, NULL)) {
                EndWin();
                fprintf(stderr, "failed to create SanDisplay thread\n");
                exit(1);
            }
            THREAD_EXIT(0);
          default:
            sleep(1);
        }
    }
}