Пример #1
0
/// Launch the auth server
extern int main(int argc, char **argv)
{
    // Command line parsing to get the configuration file name
    char const* cfg_file = _TRINITY_REALM_CONFIG;
    int c = 1;
    while (c < argc)
    {
        if (strcmp(argv[c], "-c") == 0)
        {
            if (++c >= argc)
            {
                printf("Runtime-Error: -c option requires an input argument\n");
                usage(argv[0]);
                return 1;
            }
            else
                cfg_file = argv[c];
        }
        ++c;
    }

    if (!ConfigMgr::Load(cfg_file))
    {
        printf("Invalid or missing configuration file : %s\n", cfg_file);
        printf("Verify that the file exists and has \'[authserver]\' written in the top of the file!\n");
        return 1;
    }

    sLog->outInfo(LOG_FILTER_AUTHSERVER, "NotaTank Rev1 (authserver) aka our first release!", _FULLVERSION);
    sLog->outInfo(LOG_FILTER_AUTHSERVER, "<Ctrl-C> to stop.\n");
    sLog->outInfo(LOG_FILTER_AUTHSERVER, "Using configuration file NotaTank Config.", cfg_file);

    sLog->outWarn(LOG_FILTER_AUTHSERVER, "%s (Library: %s)", OPENSSL_VERSION_TEXT, SSLeay_version(SSLEAY_VERSION));

#if defined (ACE_HAS_EVENT_POLL) || defined (ACE_HAS_DEV_POLL)
    ACE_Reactor::instance(new ACE_Reactor(new ACE_Dev_Poll_Reactor(ACE::max_handles(), 1), 1), true);
#else
    ACE_Reactor::instance(new ACE_Reactor(new ACE_TP_Reactor(), true), true);
#endif

    sLog->outDebug(LOG_FILTER_AUTHSERVER, "Max allowed open files is %d", ACE::max_handles());

    // authserver PID file creation
    std::string pidfile = ConfigMgr::GetStringDefault("PidFile", "");
    if (!pidfile.empty())
    {
        uint32 pid = CreatePIDFile(pidfile);
        if (!pid)
        {
            sLog->outError(LOG_FILTER_AUTHSERVER, "Cannot create PID file %s.\n", pidfile.c_str());
            return 1;
        }
        sLog->outInfo(LOG_FILTER_AUTHSERVER, "Daemon PID: %u\n", pid);
    }

    // Initialize the database connection
    if (!StartDB())
        return 1;

    // Get the list of realms for the server
    sRealmList->Initialize(ConfigMgr::GetIntDefault("RealmsStateUpdateDelay", 20));
    if (sRealmList->size() == 0)
    {
        sLog->outError(LOG_FILTER_AUTHSERVER, "No valid realms specified.");
        return 1;
    }

    // Launch the listening network socket
    RealmAcceptor acceptor;

    int32 rmport = ConfigMgr::GetIntDefault("RealmServerPort", 3724);
    if (rmport < 0 || rmport > 0xFFFF)
    {
        sLog->outError(LOG_FILTER_AUTHSERVER, "Specified port out of allowed range (1-65535)");
        return 1;
    }

    std::string bind_ip = ConfigMgr::GetStringDefault("BindIP", "0.0.0.0");

    ACE_INET_Addr bind_addr(uint16(rmport), bind_ip.c_str());

    if (acceptor.open(bind_addr, ACE_Reactor::instance(), ACE_NONBLOCK) == -1)
    {
        sLog->outError(LOG_FILTER_AUTHSERVER, "Auth server can not bind to %s:%d", bind_ip.c_str(), rmport);
        return 1;
    }

    // Initialise the signal handlers
    AuthServerSignalHandler SignalINT, SignalTERM;

    // Register authservers's signal handlers
    ACE_Sig_Handler Handler;
    Handler.register_handler(SIGINT, &SignalINT);
    Handler.register_handler(SIGTERM, &SignalTERM);

    ///- Handle affinity for multiple processors and process priority on Windows
#ifdef _WIN32
    {
        HANDLE hProcess = GetCurrentProcess();

        uint32 Aff = ConfigMgr::GetIntDefault("UseProcessors", 0);
        if (Aff > 0)
        {
            ULONG_PTR appAff;
            ULONG_PTR sysAff;

            if (GetProcessAffinityMask(hProcess, &appAff, &sysAff))
            {
                ULONG_PTR curAff = Aff & appAff;            // remove non accessible processors

                if (!curAff)
                    sLog->outError(LOG_FILTER_AUTHSERVER, "Processors marked in UseProcessors bitmask (hex) %x not accessible for authserver. Accessible processors bitmask (hex): %x", Aff, appAff);
                else if (SetProcessAffinityMask(hProcess, curAff))
                    sLog->outInfo(LOG_FILTER_AUTHSERVER, "Using processors (bitmask, hex): %x", curAff);
                else
                    sLog->outError(LOG_FILTER_AUTHSERVER, "Can't set used processors (hex): %x", curAff);
            }

        }

        bool Prio = ConfigMgr::GetBoolDefault("ProcessPriority", false);

        if (Prio)
        {
            if (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS))
                sLog->outInfo(LOG_FILTER_AUTHSERVER, "The auth server process priority class has been set to HIGH");
				sLog->outInfo(LOG_FILTER_AUTHSERVER, "Warning: NotaTank is an ALPHA project and is less complete than TC and MaNGOS 4.3.4, but stay with us. Thanks, regards --Nota & Tank");            

        }
    }
#endif

    // maximum counter for next ping
    uint32 numLoops = (ConfigMgr::GetIntDefault("MaxPingTime", 30) * (MINUTE * 1000000 / 100000));
    uint32 loopCounter = 0;

    // Wait for termination signal
    while (!stopEvent)
    {
        // dont move this outside the loop, the reactor will modify it
        ACE_Time_Value interval(0, 100000);

        if (ACE_Reactor::instance()->run_reactor_event_loop(interval) == -1)
            break;

        if ((++loopCounter) == numLoops)
        {
            loopCounter = 0;
            sLog->outInfo(LOG_FILTER_AUTHSERVER, "Ping MySQL to keep connection alive");
            LoginDatabase.KeepAlive();
        }
    }

    // Close the Database Pool and library
    StopDB();

    sLog->outInfo(LOG_FILTER_AUTHSERVER, "Halting process...");
    return 0;
}
Пример #2
0
/// Launch the Trinity server
extern int main(int argc, char **argv) {
	///- Command line parsing to get the configuration file name
	char const* cfg_file = _FRENCHCORE_CORE_CONFIG;
	int c = 1;
	while (c < argc) {
		if (strcmp(argv[c], "-c") == 0) {
			if (++c >= argc) {
				sLog->outError(
						"Runtime-Error: -c option requires an input argument");
				usage(argv[0]);
				return 1;
			} else
				cfg_file = argv[c];
		}

#ifdef _WIN32
		////////////
		//Services//
		////////////
		if (strcmp(argv[c], "-s") == 0)
		{
			if (++c >= argc)
			{
				sLog->outError("Runtime-Error: -s option requires an input argument");
				usage(argv[0]);
				return 1;
			}
			if (strcmp(argv[c], "install") == 0)
			{
				if (WinServiceInstall())
				sLog->outString("Installing service");
				return 1;
			}
			else if (strcmp(argv[c], "uninstall") == 0)
			{
				if (WinServiceUninstall())
				sLog->outString("Uninstalling service");
				return 1;
			}
			else
			{
				sLog->outError("Runtime-Error: unsupported option %s", argv[c]);
				usage(argv[0]);
				return 1;
			}
		}
		if (strcmp(argv[c], "--service") == 0)
		{
			WinServiceRun();
		}
		////
#endif
		++c;
	}

	if (!sConfig->SetSource(cfg_file)) {
		sLog->outError("Invalid or missing configuration file : %s", cfg_file);
		sLog->outError(
				"Verify that the file exists and has \'[worldserver]' written in the top of the file!");
		return 1;
	}
	sLog->outString("Using configuration file %s.", cfg_file);

	sLog->outDetail("%s (Library: %s)", OPENSSL_VERSION_TEXT,
			SSLeay_version(SSLEAY_VERSION));
	sLog->outDetail("Using ACE: %s", ACE_VERSION);

	///- and run the 'Master'
	/// \todo Why do we need this 'Master'? Can't all of this be in the Main as for Realmd?
	int ret = sMaster->Run();

	// at sMaster return function exist with codes
	// 0 - normal shutdown
	// 1 - shutdown at error
	// 2 - restart command used, this code can be used by restarter for restart Trinityd

	return ret;
}
Пример #3
0
/// Launch the realm server
extern int main(int argc, char** argv)
{
    ///- Command line parsing
    char const* cfg_file = REALMD_CONFIG_LOCATION;

    char const* options = ":c:s:";

    ACE_Get_Opt cmd_opts(argc, argv, options);
    cmd_opts.long_option("version", 'v');

    char serviceDaemonMode = '\0';

    int option;
    while ((option = cmd_opts()) != EOF)
    {
        switch (option)
        {
            case 'c':
                cfg_file = cmd_opts.opt_arg();
                break;
            case 'v':
                printf("%s\n", REVISION_NR);
                return 0;

            case 's':
            {
                const char* mode = cmd_opts.opt_arg();

                if (!strcmp(mode, "run"))
                    { serviceDaemonMode = 'r'; }
#ifdef WIN32
                else if (!strcmp(mode, "install"))
                    { serviceDaemonMode = 'i'; }
                else if (!strcmp(mode, "uninstall"))
                    { serviceDaemonMode = 'u'; }
#else
                else if (!strcmp(mode, "stop"))
                    { serviceDaemonMode = 's'; }
#endif
                else
                {
                    sLog.outError("Runtime-Error: -%c unsupported argument %s", cmd_opts.opt_opt(), mode);
                    usage(argv[0]);
                    Log::WaitBeforeContinueIfNeed();
                    return 1;
                }
                break;
            }
            case ':':
                sLog.outError("Runtime-Error: -%c option requires an input argument", cmd_opts.opt_opt());
                usage(argv[0]);
                Log::WaitBeforeContinueIfNeed();
                return 1;
            default:
                sLog.outError("Runtime-Error: bad format of commandline arguments");
                usage(argv[0]);
                Log::WaitBeforeContinueIfNeed();
                return 1;
        }
    }

#ifdef WIN32                                                // windows service command need execute before config read
    switch (serviceDaemonMode)
    {
        case 'i':
            if (WinServiceInstall())
                { sLog.outString("Installing service"); }
            return 1;
        case 'u':
            if (WinServiceUninstall())
                { sLog.outString("Uninstalling service"); }
            return 1;
        case 'r':
            WinServiceRun();
            break;
    }
#endif

    if (!sConfig.SetSource(cfg_file))
    {
        sLog.outError("Could not find configuration file %s.", cfg_file);
        Log::WaitBeforeContinueIfNeed();
        return 1;
    }

#ifndef WIN32                                               // posix daemon commands need apply after config read
    switch (serviceDaemonMode)
    {
        case 'r':
            startDaemon();
            break;
        case 's':
            stopDaemon();
            break;
    }
#endif

    sLog.Initialize();

	sLog.outString("%s [realm-daemon]", REVISION_NR);
    sLog.outString("<Ctrl-C> to stop.\n");
    sLog.outString("Using configuration file %s.", cfg_file);

    ///- Check the version of the configuration file
    uint32 confVersion = sConfig.GetIntDefault("ConfVersion", 0);
    if (confVersion < REALMD_CONFIG_VERSION)
    {
		sLog.outError("*****************************************************************************");
        sLog.outError(" WARNING: Your realmd.conf version indicates your conf file is out of date!");
        sLog.outError("          Please check for updates, as your current default values may cause");
        sLog.outError("          strange behavior.");
        sLog.outError("*****************************************************************************");
        Log::WaitBeforeContinueIfNeed();
    }

    DETAIL_LOG("%s (Library: %s)", OPENSSL_VERSION_TEXT, SSLeay_version(SSLEAY_VERSION));
    if (SSLeay() < 0x009080bfL)
    {
        DETAIL_LOG("WARNING: Outdated version of OpenSSL lib. Logins to server may not work!");
        DETAIL_LOG("WARNING: Minimal required version [OpenSSL 0.9.8k]");
    }

    DETAIL_LOG("Using ACE: %s", ACE_VERSION);

#if defined (ACE_HAS_EVENT_POLL) || defined (ACE_HAS_DEV_POLL)
    ACE_Reactor::instance(new ACE_Reactor(new ACE_Dev_Poll_Reactor(ACE::max_handles(), 1), 1), true);
#else
    ACE_Reactor::instance(new ACE_Reactor(new ACE_TP_Reactor(), true), true);
#endif

    sLog.outBasic("Max allowed open files is %d", ACE::max_handles());

    /// realmd PID file creation
    std::string pidfile = sConfig.GetStringDefault("PidFile", "");
    if (!pidfile.empty())
    {
        uint32 pid = CreatePIDFile(pidfile);
        if (!pid)
        {
            sLog.outError("Can not create PID file %s.\n", pidfile.c_str());
            Log::WaitBeforeContinueIfNeed();
            return 1;
        }

        sLog.outString("Daemon PID: %u\n", pid);
    }

    ///- Initialize the database connection
    if (!StartDB())
    {
        Log::WaitBeforeContinueIfNeed();
        return 1;
    }

    ///- Get the list of realms for the server
    sRealmList.Initialize(sConfig.GetIntDefault("RealmsStateUpdateDelay", 20));
    if (sRealmList.size() == 0)
    {
        sLog.outError("No valid realms specified.");
        Log::WaitBeforeContinueIfNeed();
        return 1;
    }

    // cleanup query
    // set expired bans to inactive
    LoginDatabase.BeginTransaction();
    LoginDatabase.Execute("UPDATE account_banned SET active = 0 WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
    LoginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
    LoginDatabase.CommitTransaction();

    ///- Launch the listening network socket
    ACE_Acceptor<AuthSocket, ACE_SOCK_Acceptor> acceptor;

    uint16 rmport = sConfig.GetIntDefault("RealmServerPort", DEFAULT_REALMSERVER_PORT);
    std::string bind_ip = sConfig.GetStringDefault("BindIP", "0.0.0.0");

    ACE_INET_Addr bind_addr(rmport, bind_ip.c_str());

    if (acceptor.open(bind_addr, ACE_Reactor::instance(), ACE_NONBLOCK) == -1)
    {
        sLog.outError("MaNGOS realmd can not bind to %s:%d", bind_ip.c_str(), rmport);
        Log::WaitBeforeContinueIfNeed();
        return 1;
    }

    ///- Catch termination signals
    HookSignals();

    ///- Handle affinity for multiple processors and process priority on Windows
#ifdef WIN32
    {
        HANDLE hProcess = GetCurrentProcess();

        uint32 Aff = sConfig.GetIntDefault("UseProcessors", 0);
        if (Aff > 0)
        {
            ULONG_PTR appAff;
            ULONG_PTR sysAff;

            if (GetProcessAffinityMask(hProcess, &appAff, &sysAff))
            {
                ULONG_PTR curAff = Aff & appAff;            // remove non accessible processors

                if (!curAff)
                {
                    sLog.outError("Processors marked in UseProcessors bitmask (hex) %x not accessible for realmd. Accessible processors bitmask (hex): %x", Aff, appAff);
                }
                else
                {
                    if (SetProcessAffinityMask(hProcess, curAff))
                        { sLog.outString("Using processors (bitmask, hex): %x", curAff); }
                    else
                        { sLog.outError("Can't set used processors (hex): %x", curAff); }
                }
            }
            sLog.outString();
        }

        bool Prio = sConfig.GetBoolDefault("ProcessPriority", false);

        if (Prio)
        {
            if (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS))
                { sLog.outString("realmd process priority class set to HIGH"); }
            else
                { sLog.outError("Can't set realmd process priority class."); }
            sLog.outString();
        }
    }
#endif

    // server has started up successfully => enable async DB requests
    LoginDatabase.AllowAsyncTransactions();

    // maximum counter for next ping
    uint32 numLoops = (sConfig.GetIntDefault("MaxPingTime", 30) * (MINUTE * 1000000 / 100000));
    uint32 loopCounter = 0;

#ifndef WIN32
    detachDaemon();
#endif
    ///- Wait for termination signal
    while (!stopEvent)
    {
        // dont move this outside the loop, the reactor will modify it
        ACE_Time_Value interval(0, 100000);

        if (ACE_Reactor::instance()->run_reactor_event_loop(interval) == -1)
            { break; }

        if ((++loopCounter) == numLoops)
        {
            loopCounter = 0;
            DETAIL_LOG("Ping MySQL to keep connection alive");
            LoginDatabase.Ping();
        }
#ifdef WIN32
        if (m_ServiceStatus == 0) { stopEvent = true; }
        while (m_ServiceStatus == 2) { Sleep(1000); }
#endif
    }

    ///- Wait for the delay thread to exit
    LoginDatabase.HaltDelayThread();

    ///- Remove signal handling before leaving
    UnhookSignals();

    sLog.outString("Halting process...");
    return 0;
}
Пример #4
0
/// Launch the realm server
extern int main(int argc, char **argv)
{
    sLog.SetLogDB(false);
    ///- Command line parsing to get the configuration file name
    char const* cfg_file = _RIBON_REALM_CONFIG;
    int c=1;
    while( c < argc )
    {
        if( strcmp(argv[c],"-c") == 0)
        {
            if( ++c >= argc )
            {
                sLog.outError("Runtime-Error: -c option requires an input argument");
                usage(argv[0]);
                return 1;
            }
            else
                cfg_file = argv[c];
        }

        #ifdef WIN32
        ////////////
        //Services//
        ////////////
        if( strcmp(argv[c],"-s") == 0)
        {
            if( ++c >= argc )
            {
                sLog.outError("Runtime-Error: -s option requires an input argument");
                usage(argv[0]);
                return 1;
            }
            if( strcmp(argv[c],"install") == 0)
            {
                if (WinServiceInstall())
                    sLog.outString("Installing service");
                return 1;
            }
            else if( strcmp(argv[c],"uninstall") == 0)
            {
                if(WinServiceUninstall())
                    sLog.outString("Uninstalling service");
                return 1;
            }
            else
            {
                sLog.outError("Runtime-Error: unsupported option %s",argv[c]);
                usage(argv[0]);
                return 1;
            }
        }
        if( strcmp(argv[c],"--service") == 0)
        {
            WinServiceRun();
        }
        ////
        #endif
        ++c;
    }

    if (!sConfig.SetSource(cfg_file))
    {
        sLog.outError("Could not find configuration file %s.", cfg_file);
        return 1;
    }

    sLog.outString( "(logon-daemon) Revision: %s ", _FULLVERSION );
    sLog.outString( "Build Date: %s", __DATE__ );
    sLog.outString( "Build Time: %s", __TIME__ );
    sLog.outString( "<Ctrl-C> to stop.\n" );

    sLog.outString( "'########::'####:'########:::'#######::'##::: ##:");
    sLog.outString( " ##.... ##:. ##:: ##.... ##:'##.... ##: ###:: ##:");
    sLog.outString( " ##:::: ##:: ##:: ##:::: ##: ##:::: ##: ####: ##:");
    sLog.outString( " ########::: ##:: ########:: ##:::: ##: ## ## ##:");
    sLog.outString( " ##.. ##:::: ##:: ##.... ##: ##:::: ##: ##. ####:");
    sLog.outString( " ##::. ##::: ##:: ##:::: ##: ##:::: ##: ##:. ###:");
    sLog.outString( " ##:::. ##:'####: ########::. #######:: ##::. ##:");
    sLog.outString( "..:::::..::....::........::::.......:::..::::..::");
    sLog.outString( "                                        L O G O N");
    sLog.outString( "http://www.dark-resurrection.de/wowsp/         \n");

    sLog.outString("Using configuration file %s.", cfg_file);

    ///- Check the version of the configuration file
    uint32 confVersion = sConfig.GetIntDefault("ConfVersion", 0);
    if (confVersion < _REALMDCONFVERSION)
    {
        sLog.outError("*****************************************************************************");
        sLog.outError(" WARNING: Your RibonLogon.conf version indicates your conf file is out of date!");
        sLog.outError("          Please check for updates, as your current default values may cause");
        sLog.outError("          strange behavior.");
        sLog.outError("*****************************************************************************");
        clock_t pause = 3000 + clock();

        while (pause > clock()) {}
    }

    sLog.outDetail("%s (Library: %s)", OPENSSL_VERSION_TEXT, SSLeay_version(SSLEAY_VERSION));
    if (SSLeay() < 0x009080bfL )
    {
        sLog.outDetail("WARNING: Outdated version of OpenSSL lib. Logins to server impossible!");
        sLog.outDetail("WARNING: Minimal required version [OpenSSL 0.9.8k]");
    }

    /// realmd PID file creation
    std::string pidfile = sConfig.GetStringDefault("PidFile", "");
    if(!pidfile.empty())
    {
        uint32 pid = CreatePIDFile(pidfile);
        if( !pid )
        {
            sLog.outError( "Cannot create PID file %s.\n", pidfile.c_str() );
            return 1;
        }

        sLog.outString( "Daemon PID: %u\n", pid );
    }

    ///- Initialize the database connection
    if(!StartDB())
        return 1;

    ///- Initialize the log database
    if(sConfig.GetBoolDefault("EnableLogDB", false))
    {
        // everything successful - set var to enable DB logging once startup finished.
        sLog.SetLogDBLater(true);
        sLog.SetLogDB(false);
        // ensure we've set realm to 0 (realmd realmid)
        sLog.SetRealmID(0);
    }
    else
    {
        sLog.SetLogDBLater(false);
        sLog.SetLogDB(false);
        sLog.SetRealmID(0);
    }

    ///- Get the list of realms for the server
    m_realmList.Initialize(sConfig.GetIntDefault("RealmsStateUpdateDelay", 20));
    if (m_realmList.size() == 0)
    {
        sLog.outError("No valid realms specified.");
        return 1;
    }

    ///- Launch the listening network socket
    port_t rmport = sConfig.GetIntDefault( "RealmServerPort", DEFAULT_REALMSERVER_PORT );
    std::string bind_ip = sConfig.GetStringDefault("BindIP", "0.0.0.0");

    SocketHandler h;
    ListenSocket<AuthSocket> authListenSocket(h);
    if ( authListenSocket.Bind(bind_ip.c_str(),rmport))
    {
        sLog.outError( "RibonLogon can not bind to %s:%d",bind_ip.c_str(), rmport );
        return 1;
    }

    h.Add(&authListenSocket);

    ///- Catch termination signals
    HookSignals();

    ///- Handle affinity for multiple processors and process priority on Windows
    #ifdef WIN32
    {
        HANDLE hProcess = GetCurrentProcess();

        uint32 Aff = sConfig.GetIntDefault("UseProcessors", 0);
        if(Aff > 0)
        {
            ULONG_PTR appAff;
            ULONG_PTR sysAff;

            if(GetProcessAffinityMask(hProcess,&appAff,&sysAff))
            {
                ULONG_PTR curAff = Aff & appAff;            // remove non accessible processors

                if(!curAff )
                {
                    sLog.outError("Processors marked in UseProcessors bitmask (hex) %x not accessible for realmd. Accessible processors bitmask (hex): %x",Aff,appAff);
                }
                else
                {
                    if(SetProcessAffinityMask(hProcess,curAff))
                        sLog.outString("Using processors (bitmask, hex): %x", curAff);
                    else
                        sLog.outError("Can't set used processors (hex): %x", curAff);
                }
            }
            sLog.outString();
        }

        bool Prio = sConfig.GetBoolDefault("ProcessPriority", false);

        if(Prio)
        {
            if(SetPriorityClass(hProcess,HIGH_PRIORITY_CLASS))
                sLog.outString("RibonLogon process priority class set to HIGH");
            else
                sLog.outError("ERROR: Can't set realmd process priority class.");
            sLog.outString();
        }
    }
    #endif

    // maximum counter for next ping
    uint32 numLoops = (sConfig.GetIntDefault( "MaxPingTime", 30 ) * (MINUTE * 1000000 / 100000));
    uint32 loopCounter = 0;

    // possibly enable db logging; avoid massive startup spam by doing it here.
    if (sLog.GetLogDBLater())
    {
        sLog.outString("Enabling database logging...");
        sLog.SetLogDBLater(false);
        // login db needs thread for logging
        sLog.SetLogDB(true);
    }
    else
    {
        sLog.SetLogDB(false);
        sLog.SetLogDBLater(false);
    }

    ///- Wait for termination signal
    while (!stopEvent)
    {

        h.Select(0, 100000);

        if( (++loopCounter) == numLoops )
        {
            loopCounter = 0;
            sLog.outDetail("Ping MySQL to keep connection alive");
            delete loginDatabase.Query("SELECT 1 FROM realmlist LIMIT 1");
        }
#ifdef WIN32
        if (m_ServiceStatus == 0) stopEvent = true;
        while (m_ServiceStatus == 2) Sleep(1000);
#endif
    }

    ///- Wait for the delay thread to exit
    loginDatabase.ThreadEnd();
    loginDatabase.HaltDelayThread();

    ///- Remove signal handling before leaving
    UnhookSignals();

    sLog.outString( "Halting process..." );
    return 0;
}
int main(int argc, char **argv)
{
  char *pass = NULL;
  char *salt = NULL;
  char *expected = NULL;
  uint32_t iterations = 0;
  uint32_t outputBytes = 0;
  uint16_t algo = 0;
  int c;
  uint8_t verbose = 0;
  uint8_t help = 0;
  uint8_t oType = 0;
  uint8_t sType = 0;
  
  opterr = 0;
  
//    printf("%s\n", hex2val("73616C7473616C74", 16));

  while ((c = getopt (argc, argv, "nhva:p:P:s:S:i:o:O:e:")) != -1)
    switch (c)
      {
      case 'a':
        if (strcmp(optarg,"SHA-512")==0)
          {
            algo = SHA_512_openssl;
          }
        else if (strcmp(optarg,"SHA-384")==0)
          {
            algo = SHA_384_openssl;
          }
        else if (strcmp(optarg,"SHA-256")==0)
          {
            algo = SHA_256_openssl;
          }
        else if (strcmp(optarg,"SHA-224")==0)
          {
            algo = SHA_224_openssl;
          }
        else if (strcmp(optarg,"SHA-1")==0)
          {
            algo = SHA_1_openssl;
          }
        else if (strcmp(optarg,"SHA-1nat")==0)
          {
            algo = SHA_1_openssl_native;
          }
        else if (strcmp(optarg,"MD5")==0)
          {
            algo = MD5_openssl;
          }
        else
          {
            printf("ERROR: -a argument %s unknown.\n",optarg);
            return -4;
          }
        break;
      case 'p':
        pass = optarg;
        break;
      case 's':
        salt = optarg;
        break;
      case 'i':
        iterations = atoi(optarg);
        break;
      case 'o':
        outputBytes = atoi(optarg);
        break;
      case 'v':
        verbose = 1;
        break;
      case 'h':
        help = 1;
        break;
      case 'e':
        expected = optarg;
        break;
      case 'O':
	if (strcmp(optarg,"hex")==0)
		oType = OUT_HEX;
	else if(strcmp(optarg,"Hex")==0)
		oType = OUT_HEXU;
	else if(strcmp(optarg,"hexc")==0)
		oType = OUT_HEXC;
	else if(strcmp(optarg,"Hexc")==0)
		oType = OUT_HEXUC;
	else if(strcmp(optarg,"base64")==0)
		oType = OUT_BASE64;
	else if(strcmp(optarg,"bin")==0)
		oType = OUT_BIN;
	else
	{
            printf("ERROR: For -O (Outputfmt) argument %s unknown.\n", optarg);
            return -5;
	}
      break;
      case 'S':
      	if(strcmp(optarg, "hex")==0)
		    sType = SFMT_HEX;
	    else if(strcmp(optarg, "str")==0)
		    sType = SFMT_STR;
        else if (strcmp(optarg, "base64"))
            sType = SFMT_B64;
	    else
	    {
            printf("ERROR: For -S (saltfmt) argument %s unknown.\n", optarg);
            return -6;
	    }

      break;
      case '?':
        puts("Case ?");fflush;
       if (optopt == 'c')
         fprintf (stderr, "Option -%c requires an argument.\n", optopt);
       else if (isprint (optopt))
         fprintf (stderr, "Unknown option `-%c'.\n", optopt);
       else
         fprintf (stderr,
                  "Unknown option character `\\x%x'.\n",
                  optopt);
       return 1;
      default:
        puts("Case default");fflush;
        break;//abort ();
      }

  if (help)
  {
    printf("Compiled with OpenSSL version: %s\n",OPENSSL_VERSION_TEXT);
    printf("Running with OpenSSL version: %s\n",SSLeay_version(SSLEAY_VERSION));
    printf("Example: %s -a SHA-512 -p password -s salt -i 131072 -o 64\n",argv[0]);
    puts("\nOptions: ");
    puts("  -h                 help");
    puts("  -v                 Verbose");
    puts("  -a algo            algorithm, valid values SHA-512|SHA-384|SHA-256|SHA-224|SHA-1|SHA-1nat|MD5   Note that in particular, SHA-384 and SHA-512 use 64-bit operations which as of 2014 penalize GPU's (attackers) much, much more than CPU's (you).  Use one of these two if at all possible.");
    puts("  -p password        Password to hash");
    puts("  -P passwordfmt     NOT YET IMPLEMENTED - always string");
    puts("  -s salt            Salt for the hash.  Should be long and cryptographically random.");
    puts("  -S saltfmt         hex: for Hex (default) / str: for String / base64: for Base64 string format");
    puts("  -i iterations      Number of iterations, as high as you can handle the delay for, at least 16384 recommended.");
    puts("  -o bytes           Number of bytes of output; for password hashing, keep less than or equal to native hash size (MD5 <=16, SHA-1 <=20, SHA-256 <=32, SHA-512 <=64)");
    //puts("  -O outputfmt       Output format NOT YET IMPLEMENTED - always HEX (lowercase)");
    puts("  -O outputfmt       Output format:");
    puts("                            - hex:		Lowercase Hex (default)");
    puts("                            - Hex:		Uppercase Hex");
    puts("                            - hexc:		Lowercase Hex with : deliminated");
    puts("                            - Hexc:		Uppercase Hex with : deliminated");
    puts("                            - base64:		Base64");
    puts("                            - bin:		Binary");
    puts("  -e hash            Expected hash (in the same format as outputfmt) results in output of 0 <actual> <expected> = different, 1 = same NOT YET IMPLEMENTED");
    puts("  -n                 Interactive mode; NOT YET IMPLEMENTED");
  }
     
  if (verbose)
  {
        printf("Interpreted arguments: algo %i password %s salt %s iterations %i outputbytes %i\n\n",algo,pass,salt,iterations,outputBytes);
  }


  if (algo <= 0)
    {
    puts("You must select a known algorithm identifier.");
    return 10;
    }

  if (iterations <= 0)
    {
    puts("You must select at least one iteration (and preferably tens of thousands or (much) more.");
    return 11;
    }

  if (outputBytes <= 0)
    {
    puts("You must select at least one byte of output length.");
    return 12;
    }

  switch (sType)
  {
	  case SFMT_HEX: // this is the default
        salt = hex2val(salt, strlen(salt));
        break;
      case SFMT_B64:
        salt= Base64PlusSlashEqualsMultiLine2bin(salt, strlen(salt));
        break;
	  case SFMT_STR:
	  break; 
  }
    
  // 2*outputBytes+1 is 2 hex bytes per binary byte, and one character at the end for the string-terminating \0
  char hexResult[2*outputBytes+1];
  memset(hexResult,0,sizeof(hexResult));
  uint8_t binResult[outputBytes+1];
  memset(binResult,0,sizeof(binResult));
  char *finResult = NULL;

//    printf("Computing PBKDF2(HMAC-SHA512, '%s', '%s', %d, %d) ...\n", pass, salt, iterations, outputBytes);
  switch (algo)
    {
    case SHA_512_openssl:
      if (verbose && outputBytes > 64)
      {
        puts("WARNING: If you intend to use the result for password hashing, you should not choose a length greater than the native output size of the underlying hash function.");
      }
      PBKDF2_HMAC_SHA_512(pass, salt, iterations, outputBytes, hexResult, binResult);
      break;
    case SHA_384_openssl:
      if (verbose && outputBytes > 48)
      {
        puts("WARNING: If you intend to use the result for password hashing, you should not choose a length greater than the native output size of the underlying hash function.");
      }
      PBKDF2_HMAC_SHA_384(pass, salt, iterations, outputBytes, hexResult, binResult);
      break;
    case SHA_256_openssl:
      if (verbose && outputBytes > 32)
      {
        puts("WARNING: If you intend to use the result for password hashing, you should not choose a length greater than the native output size of the underlying hash function.");
      }
      PBKDF2_HMAC_SHA_256(pass, salt, iterations, outputBytes, hexResult, binResult);
      break;
    case SHA_224_openssl:
      if (verbose && outputBytes > 28)
      {
        puts("WARNING: If you intend to use the result for password hashing, you should not choose a length greater than the native output size of the underlying hash function.");
      }
      PBKDF2_HMAC_SHA_224(pass, salt, iterations, outputBytes, hexResult, binResult);
      break;
    case SHA_1_openssl:
      if (verbose && outputBytes > 20)
      {
        puts("WARNING: If you intend to use the result for password hashing, you should not choose a length greater than the native output size of the underlying hash function.");
      }
      PBKDF2_HMAC_SHA_1(pass, salt, iterations, outputBytes, hexResult, binResult);
      break;
    case SHA_1_openssl_native:
      if (verbose && outputBytes > 20)
      {
        puts("WARNING: If you intend to use the result for password hashing, you should not choose a length greater than the native output size of the underlying hash function.");
      }
      PBKDF2_HMAC_SHA_1nat(pass, salt, iterations, outputBytes, hexResult, binResult);
      break;
    case MD5_openssl:
      if (verbose && outputBytes > 16)
      {
        puts("WARNING: If you intend to use the result for password hashing, you should not choose a length greater than the native output size of the underlying hash function.");
      }
      PBKDF2_HMAC_MD5(pass, salt, iterations, outputBytes, hexResult, binResult);
      break;
    default:
      printf("Invalid algorithm choice.  Internal value %i\n",algo);
      return 2;
    }

    switch(oType)
    {
    //		case OUT_HEX: // this is the default in this case goto default:
    //			printf("%s\n", hexResult);
    //			break;
		case OUT_HEXU:
            finResult = toUpper(hexResult, strlen(hexResult));
			break;
		case OUT_HEXC:
            finResult = colonDeliminate(hexResult, strlen(hexResult));
			break;
		case OUT_HEXUC:
            finResult = colonDeliminate(toUpper(hexResult, strlen(hexResult)), strlen(hexResult));
			break;
		case OUT_BASE64:
            finResult = bin2Base64PlusSlashEqualsMultiLine(binResult, strlen(binResult));
			break;
		case OUT_BIN:
            finResult = binResult;
			break;
		default:
		    finResult = hexResult;	
    }

  if (expected == NULL)
  {
    // Normal output
    //
        printf("%s\n",finResult);
  }
  else 
  {
 	   // Did it match or not?
    	if (strcmp(expected,finResult)==0)
      	{
      		puts("1");
      	}
    	else
      	{
      		printf("0 %s %s\n",finResult,expected);
      	}
  }
    
  
  return 0;
}
Пример #6
0
/// Launch the mangos server
extern int main(int argc, char **argv)
{
    // - Construct Memory Manager Instance
    MaNGOS::Singleton<MemoryManager>::Instance();

    //char *leak = new char[1000];                          // test leak detection

    ///- Command line parsing
    char const* cfg_file = _MANGOSD_CONFIG;

#ifdef WIN32
    char const *options = ":c:s:";
#else
    char const *options = ":c:";
#endif

    ACE_Get_Opt cmd_opts(argc, argv, options);
    cmd_opts.long_option("version", 'v');

    int option;
    while ((option = cmd_opts()) != EOF)
    {
        switch (option)
        {
            case 'c':
                cfg_file = cmd_opts.opt_arg();
                break;
            case 'v':
                printf("%s\n", _FULLVERSION(REVISION_DATE,REVISION_TIME,REVISION_NR,REVISION_ID));
                return 0;
#ifdef WIN32
            case 's':
            {
                const char *mode = cmd_opts.opt_arg();

                if (!strcmp(mode, "install"))
                {
                    if (WinServiceInstall())
                        sLog.outString("Installing service");
                    return 1;
                }
                else if (!strcmp(mode, "uninstall"))
                {
                    if (WinServiceUninstall())
                        sLog.outString("Uninstalling service");
                    return 1;
                }
                else if (!strcmp(mode, "run"))
                    WinServiceRun();
                else
                {
                    sLog.outError("Runtime-Error: -%c unsupported argument %s", cmd_opts.opt_opt(), mode);
                    usage(argv[0]);
                    Log::WaitBeforeContinueIfNeed();
                    return 1;
                }
                break;
            }
#endif
            case ':':
                sLog.outError("Runtime-Error: -%c option requires an input argument", cmd_opts.opt_opt());
                usage(argv[0]);
                Log::WaitBeforeContinueIfNeed();
                return 1;
            default:
                sLog.outError("Runtime-Error: bad format of commandline arguments");
                usage(argv[0]);
                Log::WaitBeforeContinueIfNeed();
                return 1;
        }
    }

    if (!sConfig.SetSource(cfg_file))
    {
        sLog.outError("Could not find configuration file %s.", cfg_file);
        Log::WaitBeforeContinueIfNeed();
        return 1;
    }

    sLog.outString( "%s [world-daemon]", _FULLVERSION(REVISION_DATE,REVISION_TIME,REVISION_NR,REVISION_ID) );
    sLog.outString( "<Ctrl-C> to stop.\n\n" );

    sLog.outTitle( "___  ___          _            _              ___ ");
    sLog.outTitle( "|  \\/  |         | |          (_)            /   |");
    sLog.outTitle( "| .  . |_   _ ___| |_ ___ _ __ _  __ _      / /| |");
    sLog.outTitle( "| |\\/| | | | / __| __/ _ \\ '__| |/ _` |    / /_| |");
    sLog.outTitle( "| |  | | |_| \\__ \\ ||  __/ |  | | (_| |    \\___  |");
    sLog.outTitle( "\\_|  |_/\\__, |___/\\__\\___|_|  |_|\\__,_|        |_/");
    sLog.outTitle( "         __/ |                                    ");
    sLog.outTitle( "        |___/  http://www.mysteriaserver.sk/wow/  ");
    sLog.outTitle( "");

    sLog.outString("Using configuration file %s.", cfg_file);

    DETAIL_LOG("%s (Library: %s)", OPENSSL_VERSION_TEXT, SSLeay_version(SSLEAY_VERSION));
    if (SSLeay() < 0x009080bfL )
    {
        DETAIL_LOG("WARNING: Outdated version of OpenSSL lib. Logins to server may not work!");
        DETAIL_LOG("WARNING: Minimal required version [OpenSSL 0.9.8k]");
    }

    DETAIL_LOG("Using ACE: %s", ACE_VERSION);

    ///- Set progress bars show mode
    barGoLink::SetOutputState(sConfig.GetBoolDefault("ShowProgressBars", true));

    ///- and run the 'Master'
    /// \todo Why do we need this 'Master'? Can't all of this be in the Main as for Realmd?
    return sMaster.Run();

    // at sMaster return function exist with codes
    // 0 - normal shutdown
    // 1 - shutdown at error
    // 2 - restart command used, this code can be used by restarter for restart mangosd
}
Пример #7
0
int LshttpdMain::init(int argc, char *argv[])
{
    int ret;
    ServerProcessConfig &procConfig = ServerProcessConfig::getInstance();
    if (argc > 1)
        parseOpt(argc, argv);
    if (getServerRoot(argc, argv) != 0)
    {
        //LS_ERROR("Failed to determine the root directory of server!" ));
        fprintf(stderr,
                "Can't determine the Home of LiteSpeed Web Server, exit!\n");
        return 1;
    }

    mkdir(DEFAULT_TMP_DIR,  0755);

    if (testRunningServer() != 0)
        return 2;


    if (m_pServer->configServerBasics(0, m_pBuilder->getRoot()))
        return 1;

    if (!MainServerConfig::getInstance().getDisableLogRotateAtStartup())
        LOG4CXX_NS::LogRotate::roll(HttpLog::getErrorLogger()->getAppender(),
                                    procConfig.getUid(),
                                    procConfig.getGid(), 1);

    if (procConfig.getUid() <= 10 || procConfig.getGid() < 10)
    {
        MainServerConfig  &MainServerConfigObj =  MainServerConfig::getInstance();
        LS_ERROR("It is not allowed to run LiteSpeed web server on behalf of a "
                 "privileged user/group, user id must not be "
                 "less than 50 and group id must not be less than 10."
                 "UID of user '%s' is %d, GID of group '%s' is %d. "
                 "Please fix above problem first!",
                 MainServerConfigObj.getUser(), procConfig.getUid(),
                 MainServerConfigObj.getGroup(), procConfig.getGid());
        return 1;
    }
    changeOwner();

    plainconf::flushErrorLog();
    LS_NOTICE("Loading %s ...", HttpServerVersion::getVersion());
    LS_NOTICE("Using [%s]", SSLeay_version(SSLEAY_VERSION));

    if (!m_noDaemon)
    {
        if (Daemonize::daemonize(1, 1))
            return 3;
        LS_DBG_L("Daemonized!");
#ifndef RUN_TEST
        Daemonize::close();
#endif
    }

    enableCoreDump();


    if (testRunningServer() != 0)
        return 2;
    m_pid = getpid();
    if (m_pidFile.writePid(m_pid))
        return 2;


    startAdminSocket();
    ret = config();
    if (ret)
    {
        LS_ERROR("Fatal error in configuration, exit!");
        fprintf(stderr, "[ERROR] Fatal error in configuration, shutdown!\n");
        return ret;
    }
    removeOldRtreport();
    {
        char achBuf[8192];

        if (procConfig.getChroot() != NULL)
        {
            PidFile pidfile;
            ConfigCtx::getCurConfigCtx()->getAbsolute(achBuf, PID_FILE, 0);
            pidfile.writePidFile(achBuf, m_pid);
        }
    }

#if defined(__FreeBSD__)
    //setproctitle( "%s", "lshttpd" );
#else
    argv[1] = NULL;
    strcpy(argv[0], "openlitespeed (lshttpd - main)");
#endif
    //if ( !m_noCrashGuard && ( m_pBuilder->getCrashGuard() ))
    s_iCpuCount = PCUtil::getNumProcessors();

    //Server init done
    if (GlobalServerSessionHooks->isEnabled(LSI_HKPT_MAIN_INITED))
        GlobalServerSessionHooks->runCallbackNoParam(LSI_HKPT_MAIN_INITED, NULL);

    if (!m_noCrashGuard && (MainServerConfig::getInstance().getCrashGuard()))
    {
        if (guardCrash())
            return 8;
        m_pidFile.closePidFile();
    }
    else
    {
        HttpServerConfig::getInstance().setProcNo(1);
        allocatePidTracker();
        m_pServer->initAdns();
        m_pServer->enableAioLogging();
        if ((HttpServerConfig::getInstance().getUseSendfile() == 2)
            && (m_pServer->initAioSendFile() != 0))
            return LS_FAIL;
    }
    //if ( fcntl( 5, F_GETFD, 0 ) > 0 )
    //    printf( "find it!\n" );
    if (getuid() == 0)
    {
        if (m_pServer->changeUserChroot() == -1)
            return LS_FAIL;
        if (procConfig.getChroot() != NULL)
            m_pServer->offsetChroot();
    }

    if (1 == HttpServerConfig::getInstance().getProcNo())
        ExtAppRegistry::runOnStartUp();

    return 0;
}
Пример #8
0
/*
 * Output the ID response.
 * We do NOT close the parameter list so other stuff can be added later.
 */
EXPORTED void id_response(struct protstream *pout)
{
    struct utsname os;
    const char *sasl_imp;
    int sasl_ver;
    char env_buf[MAXIDVALUELEN+1];

    prot_printf(pout, "* ID ("
                "\"name\" \"Cyrus IMAPD\""
                " \"version\" \"%s\""
                " \"vendor\" \"Project Cyrus\""
                " \"support-url\" \"http://www.cyrusimap.org\"",
                CYRUS_VERSION);

    /* add the os info */
    if (uname(&os) != -1)
        prot_printf(pout,
                    " \"os\" \"%s\""
                    " \"os-version\" \"%s\"",
                    os.sysname, os.release);

#ifdef ID_SAVE_CMDLINE
    /* add the command line info */
    prot_printf(pout, " \"command\" \"%s\"", id_resp_command);
    if (strlen(id_resp_arguments)) {
        prot_printf(pout, " \"arguments\" \"%s\"", id_resp_arguments);
    } else {
        prot_printf(pout, " \"arguments\" NIL");
    }
#endif

    /* SASL information */
    snprintf(env_buf, MAXIDVALUELEN,"Built w/Cyrus SASL %d.%d.%d",
             SASL_VERSION_MAJOR, SASL_VERSION_MINOR, SASL_VERSION_STEP);

    sasl_version(&sasl_imp, &sasl_ver);
    snprintf(env_buf + strlen(env_buf), MAXIDVALUELEN - strlen(env_buf),
             "; Running w/%s %d.%d.%d", sasl_imp,
             (sasl_ver & 0xFF000000) >> 24,
             (sasl_ver & 0x00FF0000) >> 16,
             (sasl_ver & 0x0000FFFF));

    /* add the environment info */
#ifdef DB_VERSION_STRING
    snprintf(env_buf + strlen(env_buf), MAXIDVALUELEN - strlen(env_buf),
             "; Built w/%s", DB_VERSION_STRING);
    snprintf(env_buf + strlen(env_buf), MAXIDVALUELEN - strlen(env_buf),
             "; Running w/%s", db_version(NULL, NULL, NULL));
#endif
#ifdef HAVE_SSL
    snprintf(env_buf + strlen(env_buf), MAXIDVALUELEN - strlen(env_buf),
             "; Built w/%s", OPENSSL_VERSION_TEXT);
    snprintf(env_buf + strlen(env_buf), MAXIDVALUELEN - strlen(env_buf),
             "; Running w/%s", SSLeay_version(SSLEAY_VERSION));
#ifdef EGD_SOCKET
    snprintf(env_buf + strlen(env_buf), MAXIDVALUELEN - strlen(env_buf),
             " (with EGD)");
#endif
#endif
#ifdef HAVE_ZLIB
    snprintf(env_buf + strlen(env_buf), MAXIDVALUELEN - strlen(env_buf),
             "; Built w/zlib %s", ZLIB_VERSION);
    snprintf(env_buf + strlen(env_buf), MAXIDVALUELEN - strlen(env_buf),
             "; Running w/zlib %s", zlibVersion());
#endif
#ifdef USE_SIEVE
    snprintf(env_buf + strlen(env_buf), MAXIDVALUELEN - strlen(env_buf),
             "; %s", SIEVE_VERSION);
#endif
#ifdef HAVE_LIBWRAP
    snprintf(env_buf + strlen(env_buf), MAXIDVALUELEN - strlen(env_buf),
             "; TCP Wrappers");
#endif
#ifdef HAVE_UCDSNMP
    snprintf(env_buf + strlen(env_buf), MAXIDVALUELEN - strlen(env_buf),
             "; UCD-SNMP %s", VersionInfo);
#endif
#ifdef HAVE_NETSNMP
    snprintf(env_buf + strlen(env_buf), MAXIDVALUELEN - strlen(env_buf),
             "; NET-SNMP");
#endif
    snprintf(env_buf + strlen(env_buf), MAXIDVALUELEN - strlen(env_buf),
             "; mmap = %s", map_method_desc);
    snprintf(env_buf + strlen(env_buf), MAXIDVALUELEN - strlen(env_buf),
             "; lock = %s", lock_method_desc);
    snprintf(env_buf + strlen(env_buf), MAXIDVALUELEN - strlen(env_buf),
             "; nonblock = %s", nonblock_method_desc);
#ifdef HAVE_KRB
    snprintf(env_buf + strlen(env_buf), MAXIDVALUELEN - strlen(env_buf),
             " (%s)", krb4_version);
#endif
    if (idle_method_desc)
        snprintf(env_buf + strlen(env_buf), MAXIDVALUELEN - strlen(env_buf),
                 "; idle = %s", idle_method_desc);

    prot_printf(pout, " \"environment\" \"%s\"", env_buf);
}
Пример #9
0
/// Launch the Trinity server
extern int main(int argc, char** argv)
{
    ///- Command line parsing to get the configuration file name
    char const* cfg_file = _TRINITY_CORE_CONFIG;
    int c = 1;
    while (c < argc)
    {
        if (!strcmp(argv[c], "-c"))
        {
            if (++c >= argc)
            {
                printf("Runtime-Error: -c option requires an input argument");
                usage(argv[0]);
                return 1;
            }
            else
                cfg_file = argv[c];
        }

        #ifdef _WIN32
        if (strcmp(argv[c], "-s") == 0) // Services
        {
            if (++c >= argc)
            {
                printf("Runtime-Error: -s option requires an input argument");
                usage(argv[0]);
                return 1;
            }

            if (strcmp(argv[c], "install") == 0)
            {
                if (WinServiceInstall())
                    printf("Installing service\n");
                return 1;
            }
            else if (strcmp(argv[c], "uninstall") == 0)
            {
                if (WinServiceUninstall())
                    printf("Uninstalling service\n");
                return 1;
            }
            else
            {
                printf("Runtime-Error: unsupported option %s", argv[c]);
                usage(argv[0]);
                return 1;
            }
        }

        if (strcmp(argv[c], "--service") == 0)
            WinServiceRun();
        #endif
        ++c;
    }

    if (!sConfigMgr->LoadInitial(cfg_file))
    {
        printf("Invalid or missing configuration file : %s\n", cfg_file);
        printf("Verify that the file exists and has \'[worldserver]' written in the top of the file!\n");
        return 1;
    }

    TC_LOG_INFO("server.worldserver", "Using configuration file %s.", cfg_file);

    TC_LOG_INFO("server.worldserver", "Using SSL version: %s (library: %s)", OPENSSL_VERSION_TEXT, SSLeay_version(SSLEAY_VERSION));
    TC_LOG_INFO("server.worldserver", "Using ACE version: %s", ACE_VERSION);

    ///- and run the 'Master'
    /// @todo Why do we need this 'Master'? Can't all of this be in the Main as for Realmd?
    int ret = sMaster->Run();

    // at sMaster return function exist with codes
    // 0 - normal shutdown
    // 1 - shutdown at error
    // 2 - restart command used, this code can be used by restarter for restart Trinityd

    return ret;
}
Пример #10
0
/*
 * Print OpenSSL version and build-time configuration to standard error and
 * return.
 */
void
ssl_openssl_version(void)
{
	fprintf(stderr, "compiled against %s (%lx)\n",
	                OPENSSL_VERSION_TEXT,
	                (long unsigned int)OPENSSL_VERSION_NUMBER);
	fprintf(stderr, "rtlinked against %s (%lx)\n",
	                SSLeay_version(SSLEAY_VERSION),
	                SSLeay());
#ifndef OPENSSL_NO_TLSEXT
	fprintf(stderr, "TLS Server Name Indication (SNI) supported\n");
#else /* OPENSSL_NO_TLSEXT */
	fprintf(stderr, "TLS Server Name Indication (SNI) not supported\n");
#endif /* OPENSSL_NO_TLSEXT */
#ifdef OPENSSL_THREADS
#ifndef OPENSSL_NO_THREADID
	fprintf(stderr, "OpenSSL is thread-safe with THREADID\n");
#else /* OPENSSL_NO_THREADID */
	fprintf(stderr, "OpenSSL is thread-safe without THREADID\n");
#endif /* OPENSSL_NO_THREADID */
#else /* !OPENSSL_THREADS */
	fprintf(stderr, "OpenSSL is not thread-safe\n");
#endif /* !OPENSSL_THREADS */
#ifdef SSL_MODE_RELEASE_BUFFERS
	fprintf(stderr, "Using SSL_MODE_RELEASE_BUFFERS\n");
#else /* !SSL_MODE_RELEASE_BUFFERS */
	fprintf(stderr, "Not using SSL_MODE_RELEASE_BUFFERS\n");
#endif /* !SSL_MODE_RELEASE_BUFFERS */
#if (OPENSSL_VERSION_NUMBER == 0x0090819fL) || \
    (OPENSSL_VERSION_NUMBER == 0x100000bfL) || \
    (OPENSSL_VERSION_NUMBER == 0x1000105fL)
	fprintf(stderr, "Using direct access workaround when loading certs\n");
#endif /* OpenSSL 0.9.8y, 1.0.0k or 1.0.1e */

	fprintf(stderr, "SSL/TLS protocol availability: %s\n",
	                SSL_PROTO_SUPPORT_S);

	fprintf(stderr, "SSL/TLS algorithm availability:");
#ifndef OPENSSL_NO_RSA
	fprintf(stderr, " RSA");
#else /* OPENSSL_NO_RSA */
	fprintf(stderr, " !RSA");
#endif /* OPENSSL_NO_RSA */
#ifndef OPENSSL_NO_DSA
	fprintf(stderr, " DSA");
#else /* OPENSSL_NO_DSA */
	fprintf(stderr, " !DSA");
#endif /* OPENSSL_NO_DSA */
#ifndef OPENSSL_NO_ECDSA
	fprintf(stderr, " ECDSA");
#else /* OPENSSL_NO_ECDSA */
	fprintf(stderr, " !ECDSA");
#endif /* OPENSSL_NO_ECDSA */
#ifndef OPENSSL_NO_DH
	fprintf(stderr, " DH");
#else /* OPENSSL_NO_DH */
	fprintf(stderr, " !DH");
#endif /* OPENSSL_NO_DH */
#ifndef OPENSSL_NO_ECDH
	fprintf(stderr, " ECDH");
#else /* OPENSSL_NO_ECDH */
	fprintf(stderr, " !ECDH");
#endif /* OPENSSL_NO_ECDH */
#ifndef OPENSSL_NO_EC
	fprintf(stderr, " EC");
#else /* OPENSSL_NO_EC */
	fprintf(stderr, " !EC");
#endif /* OPENSSL_NO_EC */
	fprintf(stderr, "\n");

	fprintf(stderr, "OpenSSL option availability:");
#ifdef SSL_OP_NO_COMPRESSION
	fprintf(stderr, " SSL_OP_NO_COMPRESSION");
#else /* !SSL_OP_NO_COMPRESSION */
	fprintf(stderr, " !SSL_OP_NO_COMPRESSION");
#endif /* SSL_OP_NO_COMPRESSION */
#ifdef SSL_OP_NO_TICKET
	fprintf(stderr, " SSL_OP_NO_TICKET");
#else /* !SSL_OP_NO_TICKET */
	fprintf(stderr, " !SSL_OP_NO_TICKET");
#endif /* SSL_OP_NO_TICKET */
#ifdef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
	fprintf(stderr, " SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION");
#else /* !SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION */
	fprintf(stderr, " !SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION");
#endif /* !SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION */
#ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
	fprintf(stderr, " SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS");
#else /* !SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS */
	fprintf(stderr, " !SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS");
#endif /* !SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS */
#ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
	fprintf(stderr, " SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION");
#else /* !SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION */
	fprintf(stderr, " !SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION");
#endif /* !SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION */
#ifdef SSL_OP_TLS_ROLLBACK_BUG
	fprintf(stderr, " SSL_OP_TLS_ROLLBACK_BUG");
#else /* !SSL_OP_TLS_ROLLBACK_BUG */
	fprintf(stderr, " !SSL_OP_TLS_ROLLBACK_BUG");
#endif /* !SSL_OP_TLS_ROLLBACK_BUG */
	fprintf(stderr, "\n");
}
Пример #11
0
    static bool HandleServerDebugCommand(ChatHandler* handler, char const* /*args*/)
    {
        uint16 worldPort = uint16(sWorld->getIntConfig(CONFIG_PORT_WORLD));
        std::string dbPortOutput;

        {
            uint16 dbPort = 0;
            if (QueryResult res = LoginDatabase.PQuery("SELECT port FROM realmlist WHERE id = %u", realm.Id.Realm))
                dbPort = (*res)[0].GetUInt16();

            if (dbPort)
                dbPortOutput = Trinity::StringFormat("Realmlist (Realm Id: %u) configured in port %" PRIu16, realm.Id.Realm, dbPort);
            else
                dbPortOutput = Trinity::StringFormat("Realm Id: %u not found in `realmlist` table. Please check your setup", realm.Id.Realm);
        }

        handler->PSendSysMessage("%s", GitRevision::GetFullVersion());
        handler->PSendSysMessage("Using SSL version: %s (library: %s)", OPENSSL_VERSION_TEXT, SSLeay_version(SSLEAY_VERSION));
        handler->PSendSysMessage("Using Boost version: %i.%i.%i", BOOST_VERSION / 100000, BOOST_VERSION / 100 % 1000, BOOST_VERSION % 100);
        handler->PSendSysMessage("Using MySQL version: %s", MYSQL_SERVER_VERSION);
        handler->PSendSysMessage("Using CMake version: %s", GitRevision::GetCMakeVersion());

        handler->PSendSysMessage("Compiled on: %s", GitRevision::GetHostOSVersion());

        uint32 updateFlags = sConfigMgr->GetIntDefault("Updates.EnableDatabases", DatabaseLoader::DATABASE_NONE);
        if (!updateFlags)
            handler->SendSysMessage("Automatic database updates are disabled for all databases!");
        else
        {
            static char const* const databaseNames[3 /*TOTAL_DATABASES*/] =
            {
                "Auth",
                "Characters",
                "World"
            };

            std::string availableUpdateDatabases;
            for (uint32 i = 0; i < 3 /* TOTAL_DATABASES*/; ++i)
            {
                if (!(updateFlags & (1 << i)))
                    continue;

                availableUpdateDatabases += databaseNames[i];
                if (i != 3 /*TOTAL_DATABASES*/ - 1)
                    availableUpdateDatabases += ", ";
            }

            handler->PSendSysMessage("Automatic database updates are enabled for the following databases: %s", availableUpdateDatabases.c_str());
        }

        handler->PSendSysMessage("Worldserver listening connections on port %" PRIu16, worldPort);
        handler->PSendSysMessage("%s", dbPortOutput.c_str());

        bool vmapIndoorCheck = sWorld->getBoolConfig(CONFIG_VMAP_INDOOR_CHECK);
        bool vmapLOSCheck = VMAP::VMapFactory::createOrGetVMapManager()->isLineOfSightCalcEnabled();
        bool vmapHeightCheck = VMAP::VMapFactory::createOrGetVMapManager()->isHeightCalcEnabled();

        bool mmapEnabled = sWorld->getBoolConfig(CONFIG_ENABLE_MMAPS);

        std::string dataDir = sWorld->GetDataPath();
        std::vector<std::string> subDirs;
        subDirs.emplace_back("maps");
        if (vmapIndoorCheck || vmapLOSCheck || vmapHeightCheck)
        {
            handler->PSendSysMessage("VMAPs status: Enabled. LineOfSight: %i, getHeight: %i, indoorCheck: %i", vmapLOSCheck, vmapHeightCheck, vmapIndoorCheck);
            subDirs.emplace_back("vmaps");
        }
        else
            handler->SendSysMessage("VMAPs status: Disabled");

        if (mmapEnabled)
        {
            handler->SendSysMessage("MMAPs status: Enabled");
            subDirs.emplace_back("mmaps");
        }
        else
            handler->SendSysMessage("MMAPs status: Disabled");

        for (std::string const& subDir : subDirs)
        {
            boost::filesystem::path mapPath(dataDir);
            mapPath.append(subDir);

            if (!boost::filesystem::exists(mapPath))
            {
                handler->PSendSysMessage("%s directory doesn't exist!. Using path: %s", subDir.c_str(), mapPath.generic_string().c_str());
                continue;
            }

            auto end = boost::filesystem::directory_iterator();
            std::size_t folderSize = std::accumulate(boost::filesystem::directory_iterator(mapPath), end, std::size_t(0), [](std::size_t val, boost::filesystem::path const& mapFile)
            {
                if (boost::filesystem::is_regular_file(mapFile))
                    val += boost::filesystem::file_size(mapFile);
                return val;
            });

            handler->PSendSysMessage("%s directory located in %s. Total size: " SZFMTD " bytes", subDir.c_str(), mapPath.generic_string().c_str(), folderSize);
        }

        LocaleConstant defaultLocale = sWorld->GetDefaultDbcLocale();
        uint32 availableLocalesMask = (1 << defaultLocale);

        for (uint8 i = 0; i < TOTAL_LOCALES; ++i)
        {
            LocaleConstant locale = static_cast<LocaleConstant>(i);
            if (locale == defaultLocale)
                continue;

            if (sWorld->GetAvailableDbcLocale(locale) != defaultLocale)
                availableLocalesMask |= (1 << locale);
        }

        std::string availableLocales;
        for (uint8 i = 0; i < TOTAL_LOCALES; ++i)
        {
            if (!(availableLocalesMask & (1 << i)))
                continue;

            availableLocales += localeNames[i];
            if (i != TOTAL_LOCALES - 1)
                availableLocales += " ";
        }

        handler->PSendSysMessage("Using %s DBC Locale as default. All available DBC locales: %s", localeNames[defaultLocale], availableLocales.c_str());

        handler->PSendSysMessage("Using World DB: %s", sWorld->GetDBVersion());
        return true;
    }
Пример #12
0
/// Launch the realm server
int main(int argc, char *argv[])
{
    std::string configFile, serviceParameter;

    boost::program_options::options_description desc("Allowed options");
    desc.add_options()
        ("config,c", boost::program_options::value<std::string>(&configFile)->default_value(_REALMD_CONFIG), "configuration file")
        ("version,v", "print version and exit")
#ifdef _WIN32
        ("s", boost::program_options::value<std::string>(&serviceParameter), "<run, install, uninstall> service");
#else
        ("s", boost::program_options::value<std::string>(&serviceParameter), "<run, stop> service");
#endif

    boost::program_options::variables_map vm;

    try
    {
        boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
        boost::program_options::notify(vm);
    }
    catch (boost::program_options::error const &e)
    {
        std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
        std::cerr << desc << std::endl;

        return 1;
    }

#ifdef _WIN32                                                // windows service command need execute before config read
    if (vm.count("s"))
    {
        switch (::tolower(serviceParameter[0]))
        {
            case 'i':
                if (WinServiceInstall())
                    sLog.outString("Installing service");
                return 1;
            case 'u':
                if (WinServiceUninstall())
                    sLog.outString("Uninstalling service");
                return 1;
            case 'r':
                WinServiceRun();
                break;
        }
    }
#endif

    if (!sConfig.SetSource(configFile))
    {
        sLog.outError("Could not find configuration file %s.", configFile.c_str());
        Log::WaitBeforeContinueIfNeed();
        return 1;
    }

#ifndef _WIN32                                               // posix daemon commands need apply after config read
    if (vm.count("s"))
    {
        switch (::tolower(serviceParameter[0]))
        {
            case 'r':
                startDaemon();
                break;
            case 's':
                stopDaemon();
                break;
        }
    }
#endif

    sLog.Initialize();

    sLog.outString("%s [realm-daemon]", _FULLVERSION(REVISION_DATE, REVISION_TIME, REVISION_ID));
    sLog.outString("<Ctrl-C> to stop.\n");
    sLog.outString("Using configuration file %s.", configFile.c_str());

    ///- Check the version of the configuration file
    uint32 confVersion = sConfig.GetIntDefault("ConfVersion", 0);
    if (confVersion < _REALMDCONFVERSION)
    {
        sLog.outError("*****************************************************************************");
        sLog.outError(" WARNING: Your realmd.conf version indicates your conf file is out of date!");
        sLog.outError("          Please check for updates, as your current default values may cause");
        sLog.outError("          strange behavior.");
        sLog.outError("*****************************************************************************");
        Log::WaitBeforeContinueIfNeed();
    }

    DETAIL_LOG("%s (Library: %s)", OPENSSL_VERSION_TEXT, SSLeay_version(SSLEAY_VERSION));
    if (SSLeay() < 0x009080bfL)
    {
        DETAIL_LOG("WARNING: Outdated version of OpenSSL lib. Logins to server may not work!");
        DETAIL_LOG("WARNING: Minimal required version [OpenSSL 0.9.8k]");
    }

    /// realmd PID file creation
    std::string pidfile = sConfig.GetStringDefault("PidFile");
    if (!pidfile.empty())
    {
        uint32 pid = CreatePIDFile(pidfile);
        if (!pid)
        {
            sLog.outError("Cannot create PID file %s.\n", pidfile.c_str());
            Log::WaitBeforeContinueIfNeed();
            return 1;
        }

        sLog.outString("Daemon PID: %u\n", pid);
    }

    ///- Initialize the database connection
    if (!StartDB())
    {
        Log::WaitBeforeContinueIfNeed();
        return 1;
    }

    ///- Get the list of realms for the server
    sRealmList.Initialize(sConfig.GetIntDefault("RealmsStateUpdateDelay", 20));
    if (sRealmList.size() == 0)
    {
        sLog.outError("No valid realms specified.");
        Log::WaitBeforeContinueIfNeed();
        return 1;
    }

    // cleanup query
    // set expired bans to inactive
    LoginDatabase.BeginTransaction();
    LoginDatabase.Execute("UPDATE account_banned SET active = 0 WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
    LoginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
    LoginDatabase.CommitTransaction();

    auto rmport = sConfig.GetIntDefault("RealmServerPort", DEFAULT_REALMSERVER_PORT);
    std::string bind_ip = sConfig.GetStringDefault("BindIP", "0.0.0.0");

    // FIXME - more intelligent selection of thread count is needed here.  config option?
    MaNGOS::Listener<AuthSocket> listener(rmport, 1);

    ///- Catch termination signals
    HookSignals();

    ///- Handle affinity for multiple processors and process priority on Windows
#ifdef _WIN32
    {
        HANDLE hProcess = GetCurrentProcess();

        uint32 Aff = sConfig.GetIntDefault("UseProcessors", 0);
        if (Aff > 0)
        {
            ULONG_PTR appAff;
            ULONG_PTR sysAff;

            if (GetProcessAffinityMask(hProcess, &appAff, &sysAff))
            {
                ULONG_PTR curAff = Aff & appAff;            // remove non accessible processors

                if (!curAff)
                {
                    sLog.outError("Processors marked in UseProcessors bitmask (hex) %x not accessible for realmd. Accessible processors bitmask (hex): %x", Aff, appAff);
                }
                else
                {
                    if (SetProcessAffinityMask(hProcess, curAff))
                        sLog.outString("Using processors (bitmask, hex): %x", curAff);
                    else
                        sLog.outError("Can't set used processors (hex): %x", curAff);
                }
            }
            sLog.outString();
        }

        bool Prio = sConfig.GetBoolDefault("ProcessPriority", false);

        if (Prio)
        {
            if (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS))
                sLog.outString("realmd process priority class set to HIGH");
            else
                sLog.outError("Can't set realmd process priority class.");
            sLog.outString();
        }
    }
#endif

    // server has started up successfully => enable async DB requests
    LoginDatabase.AllowAsyncTransactions();

    // maximum counter for next ping
    auto const numLoops = sConfig.GetIntDefault("MaxPingTime", 30) * MINUTE * 10;
    uint32 loopCounter = 0;

#ifndef _WIN32
    detachDaemon();
#endif
    ///- Wait for termination signal
    while (!stopEvent)
    {
        if ((++loopCounter) == numLoops)
        {
            loopCounter = 0;
            DETAIL_LOG("Ping MySQL to keep connection alive");
            LoginDatabase.Ping();
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
#ifdef _WIN32
        if (m_ServiceStatus == 0) stopEvent = true;
        while (m_ServiceStatus == 2) Sleep(1000);
#endif
    }


    ///- Wait for the delay thread to exit
    LoginDatabase.HaltDelayThread();

    ///- Remove signal handling before leaving
    UnhookSignals();

    sLog.outString("Halting process...");
    return 0;
}
Пример #13
0
RPCConsole::RPCConsole(QWidget* parent) : QDialog(parent),
                                          ui(new Ui::RPCConsole),
                                          clientModel(0),
                                          historyPtr(0),
                                          cachedNodeid(-1),
                                          peersTableContextMenu(0),
                                          banTableContextMenu(0)
{
    ui->setupUi(this);
    GUIUtil::restoreWindowGeometry("nRPCConsoleWindow", this->size(), this);

#ifndef Q_OS_MAC
    ui->openDebugLogfileButton->setIcon(QIcon(":/icons/export"));
#endif

    // Install event filter for up and down arrow
    ui->lineEdit->installEventFilter(this);
    ui->messagesWidget->installEventFilter(this);

    connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
    connect(ui->btnClearTrafficGraph, SIGNAL(clicked()), ui->trafficGraph, SLOT(clear()));

    // Wallet Repair Buttons
    connect(ui->btn_salvagewallet, SIGNAL(clicked()), this, SLOT(walletSalvage()));
    connect(ui->btn_rescan, SIGNAL(clicked()), this, SLOT(walletRescan()));
    connect(ui->btn_zapwallettxes1, SIGNAL(clicked()), this, SLOT(walletZaptxes1()));
    connect(ui->btn_zapwallettxes2, SIGNAL(clicked()), this, SLOT(walletZaptxes2()));
    connect(ui->btn_upgradewallet, SIGNAL(clicked()), this, SLOT(walletUpgrade()));
    connect(ui->btn_reindex, SIGNAL(clicked()), this, SLOT(walletReindex()));
    connect(ui->btn_resync, SIGNAL(clicked()), this, SLOT(walletResync()));

    // set library version labels
    ui->openSSLVersion->setText(SSLeay_version(SSLEAY_VERSION));
#ifdef ENABLE_WALLET
    std::string strPathCustom = GetArg("-backuppath", "");
    std::string strzXAPPathCustom = GetArg("-zxapbackuppath", "");
    int nCustomBackupThreshold = GetArg("-custombackupthreshold", DEFAULT_CUSTOMBACKUPTHRESHOLD);

    if(!strPathCustom.empty()) {
        ui->wallet_custombackuppath->setText(QString::fromStdString(strPathCustom));
        ui->wallet_custombackuppath_label->show();
        ui->wallet_custombackuppath->show();
    }

    if(!strzXAPPathCustom.empty()) {
        ui->wallet_customzxapbackuppath->setText(QString::fromStdString(strzXAPPathCustom));
        ui->wallet_customzxapbackuppath_label->setVisible(true);
        ui->wallet_customzxapbackuppath->setVisible(true);
    }

    if((!strPathCustom.empty() || !strzXAPPathCustom.empty()) && nCustomBackupThreshold > 0) {
        ui->wallet_custombackupthreshold->setText(QString::fromStdString(std::to_string(nCustomBackupThreshold)));
        ui->wallet_custombackupthreshold_label->setVisible(true);
        ui->wallet_custombackupthreshold->setVisible(true);
    }

    ui->berkeleyDBVersion->setText(DbEnv::version(0, 0, 0));
    ui->wallet_path->setText(QString::fromStdString(GetDataDir().string() + QDir::separator().toLatin1() + GetArg("-wallet", "wallet.dat")));
#else

    ui->label_berkeleyDBVersion->hide();
    ui->berkeleyDBVersion->hide();
#endif
    // Register RPC timer interface
    rpcTimerInterface = new QtRPCTimerInterface();
    RPCRegisterTimerInterface(rpcTimerInterface);

    startExecutor();
    setTrafficGraphRange(INITIAL_TRAFFIC_GRAPH_MINS);

    ui->peerHeading->setText(tr("Select a peer to view detailed information."));

    clear();
}
Пример #14
0
/// Launch the Trinity server
extern int main(int argc, char **argv)
{
    ///- Command line parsing to get the configuration file name
    char const* cfg_file = _PHANTOM_CORE_CONFIG;
    int c=1;
    while( c < argc )
    {
        if( strcmp(argv[c],"-c") == 0)
        {
            if( ++c >= argc )
            {
                sLog.outError("Runtime-Error: -c option requires an input argument");
                usage(argv[0]);
                return 1;
            }
            else
                cfg_file = argv[c];
        }

#ifdef WIN32
        ////////////
        //Services//
        ////////////
        if( strcmp(argv[c],"-s") == 0)
        {
            if( ++c >= argc )
            {
                sLog.outError("Runtime-Error: -s option requires an input argument");
                usage(argv[0]);
                Log::WaitBeforeContinueIfNeed();
                return 1;
            }
            if( strcmp(argv[c],"install") == 0)
            {
                if (WinServiceInstall())
                    sLog.outString("Installing service");
                return 1;
            }
            else if( strcmp(argv[c],"uninstall") == 0)
            {
                if(WinServiceUninstall())
                    sLog.outString("Uninstalling service");
                return 1;
            }
            else
            {
                sLog.outError("Runtime-Error: unsupported option %s",argv[c]);
                usage(argv[0]);
                Log::WaitBeforeContinueIfNeed();
                return 1;
            }
        }
        if( strcmp(argv[c],"--service") == 0)
        {
            WinServiceRun();
        }
        ////
#endif
        ++c;
    }

    if (!sConfig.SetSource(cfg_file))
    {
        sLog.outError("Could not find configuration file %s.", cfg_file);
        return 1;
    }
    sLog.outString("Using configuration file %s.", cfg_file);

    sLog.outDetail("%s (Library: %s)", OPENSSL_VERSION_TEXT, SSLeay_version(SSLEAY_VERSION));
    sLog.outDetail("Using ACE: %s", ACE_VERSION);

    ///- and run the 'Master'
    /// \todo Why do we need this 'Master'? Can't all of this be in the Main as for Realmd?
    return sMaster.Run();

    // at sMaster return function exist with codes
    // 0 - normal shutdown
    // 1 - shutdown at error
    // 2 - restart command used, this code can be used by restarter for restart Trinityd
}
Пример #15
0
int main(int argc,char **argv)
{
    char
        *x,
        *y,
        buf[BUFSIZ],
        encrypted_pass[128], /* 80 bytes actually */
        *cipher=NULL,
        *option;

    int
        smtp_info=0,
        is_mime=0,
        add_dateh=1,
        port=(-1),
        rc = (-1),
        no_cc=1,
        no_bcc=1,
        i;

    char
        *address_file=NULL,
        *helo_domain=NULL,
        *smtp_server=NULL,
        *attach_file=NULL,
        *msg_body_file=NULL, /* back in 1.17b15 */ 
        *the_msg=NULL,
        *custom_header=NULL,
        *to=NULL,
        *save_to=NULL,
        *save_cc=NULL,
        *save_bcc=NULL,
        *from=NULL,
        *sub=NULL,
        *cc=NULL,
        *bcc=NULL,
        *rt=NULL,
        *rrr=NULL;

    g_verbose=0;
    g_connect_timeout = DEFAULT_CONNECT_TIMEOUT; /* 5 secs */
    g_quiet=0;
    g_wait_for_cr=0;
    g_do_auth=0;
    g_esmtp=0;
    g_auth_plain=0;
    g_auth_cram_md5=0;
    g_auth_login=0;
    g_do_ssl=0;
    g_do_starttls=0;
    g_log_fp = NULL;
    g_show_attachment_in_log = 0;
    g_use_protocol = MSOCK_USE_AUTO; /* detect IPv4 or IPv6 */
    g_force = MUTILS_FALSE;

    memset(g_log_file,0,sizeof(g_log_file));
    memset(g_username,0,sizeof(g_username));
    memset(g_userpass,0,sizeof(g_userpass));
    memset(encrypted_pass, 0, sizeof(encrypted_pass));
    memset(g_from_name,0,sizeof(g_from_name));
	memset(g_content_type,0,sizeof(g_content_type));
    memset(g_attach_sep, 0, sizeof(g_attach_sep));
    memset(g_attach_name, 0, sizeof(g_attach_name));
    memset(g_content_transfer_encoding, 0, sizeof(g_content_transfer_encoding));
    memset(g_mime_type, 0, sizeof(g_mime_type));
    memset(g_content_id, 0, sizeof(g_content_id));

    /* (void) strcpy(g_content_transfer_encoding,"base64"); */ /* no default */
    (void) strcpy(g_content_disposition,"attachment");
    (void) strcpy(g_attach_sep,",");
    (void) strcpy(g_charset,DEFAULT_CHARSET);
    /*
        No default for mime_type, we will detect from file extensinon
        if no mime type is specified with -mime-type
    */
    /*
    (void) strcpy(g_mime_type,"text/plain");
    */


    for  (i=1; i < argc; i++)
    {
        option=argv[i];
        switch (*(option+1))
        {
            case 'a':
            {
                if (strncmp("attach",option+1,6) == 0)
                {
                    if (*option == '-')
                    {
                        i++;
                        if (i == argc)
                        {
                            errorMsg("Missing file to attach");
                            rc = 1;
                            goto ExitProcessing;
                        }
                        attach_file=argv[i];
                        add_attachment_to_list(attach_file);
                    }
                }
                else if (strncmp("aname",option+1,5) == 0)
                {
                    if (*option == '-')
                    {
                        i++;
                        if (i == argc)
                        {
                            errorMsg("Missing attachment name");
                            rc = 1;
                            goto ExitProcessing;
                        }
                        mutilsSafeStrcpy(g_attach_name,argv[i],sizeof(g_attach_name)-1);
                    }
                }
                else if (strncmp("auth-plain",option+1,
                            strlen("auth-plain"))==0)
                {
                    if (*option == '-')
                    {
                        g_auth_plain=1;
                    }
                }
                else if (strncmp("auth-cram-md5",option+1,
                            strlen("auth-cram-md5"))==0)
                {
                    if (*option == '-')
                    {
                        g_auth_cram_md5=1;
                    }
                }
                else if (strncmp("auth-login",option+1,
                            strlen("auth-login"))==0)
                {
                    if (*option == '-')
                    {
                        g_auth_login=1;
                    }
                }
                else if (strncmp("auth",option+1,
                            strlen("auth"))==0)
                {
                    if (*option == '-')
                    {
                        g_auth_plain=1;
                        g_auth_login=1;
                        g_auth_cram_md5=1;
                        g_auth_login=1;
                        g_do_auth=1;
                    }
                }
                else
                {
                    errorMsg("Unknown flag: %s\n",option);
                    rc = 1;
                    goto ExitProcessing;
                }
                break;
            }

            case 'b':
            {
                if (strncmp("bcc",option+1,2) == 0)
                {
                    if (*option == '-')
                    {
                        i++;
                        if (i == argc)
                        {
                            errorMsg("Missing BCc address/es");
                            rc = 1;
                            goto ExitProcessing;
                        }
                        bcc=argv[i];
                        save_bcc=mutilsStrdup(bcc);

                        /* collapse all spaces to a comma */
                        mutilsSpacesToChar(bcc,',');
                        addAddressToList(bcc,"Bcc");
                    }
                    else if (*option == '+')
                    {
                        no_bcc=1;
                    }
                }
                else
                {
                    errorMsg("Unknown flag: %s\n",option);
                    rc = 1;
                    goto ExitProcessing;
                }
                break;
            }

            case '4':
            {
                if (strncmp("4", option + 1,1) == 0)
                {
                    if (*option == '-')
                    {
                        g_use_protocol = MSOCK_USE_IPV4;
                    }
                }
                break;
            }

            case '6':
            {
                if (strncmp("6", option + 1,1) == 0)
                {
                    if (*option == '-')
                    {
                        g_use_protocol = MSOCK_USE_IPV6;
                    }
                }

                break;
            }



            case 'c':
            {
                if (strncmp("cc",option+1,2) == 0)
                {
                    if (*option == '-')
                    {
                        i++;
                        if (i == argc)
                        {
                            errorMsg("Missing Cc address/es");
                            rc = 1;
                            goto ExitProcessing;
                        }
                        cc=argv[i];
                        save_cc=mutilsStrdup(cc);

                        /* collapse all spaces to a comma */
                        mutilsSpacesToChar(cc,',');
                        addAddressToList(cc,"Cc");
                    }
                    else if (*option == '+')
                    {
                        no_cc=1;
                    }
                }
                else if (strncmp("cs",option+1,2) == 0)
                {
                    if (*option == '-')
                    {
                        i++;
                        if (i == argc)
                        {
                            errorMsg("Missing character set");
                            rc = 1;
                            goto ExitProcessing;
                        }
                        mutilsSafeStrcpy(g_charset,argv[i],sizeof(g_charset)-1);
                    }

                }
                else if (strncmp("ct", option + 1, 2) == 0)
                {
                    if (*option == '-')
                    {
                        i++;
                        if (i == argc)
                        {
                            errorMsg("Missing connect timeout with -ct");
                            rc = 1;
                            goto ExitProcessing;
                        }
                        g_connect_timeout = atoi(argv[i]);
                    }
                }
                else if (strncmp("content-type", option+1, 12)==0) 
                {
                    if (*option == '-')
                    {
                        i++;
                        if (i == argc)
                        {
                            errorMsg("Missing content-type value");
                            rc = 1;
                            goto ExitProcessing;
                        }
                        mutilsSafeStrcpy(g_content_type,argv[i],sizeof(g_content_type)-1);
                    }
                }
                else if (strncmp("content-disposition", option + 1, 12) == 0)
                {
                    if (*option == '-')
                    {
                        i++;
                        if (i == argc)
                        {
                            errorMsg("Missing content-dispostion value");
                            rc = 1;
                            goto ExitProcessing;
                        }
                        if ((strcmp(argv[i],"inline") == 0) || strcmp(argv[i], "attachment") == 0)
                        {
                            mutilsSafeStrcpy(g_content_disposition,argv[i],
                                    sizeof(g_content_disposition)-1);
                        }
                        else
                        {
                            errorMsg("Invalid value for -content-disposition");
                            rc = 1;
                            goto ExitProcessing;
                        }
                    }
                }
                else if (strncmp("content-id", option + 1, 10) == 0)
                {
                    if (*option == '-')
                    {
                        i++;
                        if (i == argc)
                        {
                            errorMsg("Missing content-id value");
                            rc = 1;
                            goto ExitProcessing;
                        }

                        mutilsSafeStrcpy(g_content_id,argv[i],sizeof(g_content_id)-1);
                    }

                }
                else if (strncmp("copyright", option + 1, 5) == 0)
                {
                    print_copyright();
                    rc = 0;
                    goto ExitProcessing;
                }
                else
                {
                    errorMsg("Unknown flag: %s\n",option);
                    rc = 1;
                    goto ExitProcessing;
                }
                break;
            }

            case 'D':
            {
                if (strncmp("D",option+1,1) == 0)
                {
                    if (*option == '+')
                    {
                        add_dateh=0;
                    }
                }
                break;
            }


            case 'd':
            {
                if (strncmp("domain",option+1,6) == 0)
                {
                    if (*option == '-')
                    {
                        i++;
                        if (i == argc)
                        {
                            errorMsg("Missing domain name");
                            rc = 1;
                            goto ExitProcessing;
                        }
                        helo_domain=argv[i];
                    }
                }
                else if (strncmp("disposition", option + 1, 6) == 0)
                {
                    if (*option == '-')
                    {
                        i++;
                        if (i == argc)
                        {
                            errorMsg("Missing content dispostion value");
                            rc = 1;
                            goto ExitProcessing;
                        }
                        if ((strcmp(argv[i],"inline") == 0) || strcmp(argv[i], "attachment") == 0)
                        {
                            mutilsSafeStrcpy(g_content_disposition,argv[i],sizeof(g_content_disposition)-1);
                        }
                        else
                        {
                            errorMsg("Invalid value for -disposition");
                            rc = 1;
                            goto ExitProcessing;
                        }
                    }
                }

                break;
            }

            case 'e':
            {
                if (strncmp("example",option+1,2) == 0)
                {
                    if (*option == '-')
                    {
                        show_examples();
                        rc = 1;
                        goto ExitProcessing;
                    }
                }
                else if (strncmp("ehlo",option+1,4) == 0)
                {
                    if (*option == '-')
                    {
                        g_esmtp=1;
                    }
                }
                else if (strncmp("enc-type",option+1,5) == 0)
                {
                    if (*option == '-')
                    {
                        i++;
                        if (i == argc)
                        {
                            errorMsg("Missing encoding type");
                            rc = 1;
                            goto ExitProcessing;
                        }
                        mutilsSafeStrcpy(g_content_transfer_encoding,
                                argv[i],
                                sizeof(g_content_transfer_encoding)-1);
                    }
                }
                else if (strncmp("embed-image", option + 1, 7) == 0)
                {
                    if (*option == '-')
                    {
                        i++;
                        if (i == argc)
                        {
                            errorMsg("Missing image for -embded-image");
                            rc = 1;
                            goto ExitProcessing;
                        }
                        add_embed_image_to_attachment_list(argv[i]);
                        /* TODO */
                    }

                }
                break;
            }

            case 'f':
            {
                if (strncmp("from",option+1,1) == 0)
                {
                    if (*option == '-')
                    {
                        i++;
                        if (i == argc)
                        {
                            errorMsg("Missing From address/es");
                            rc = 1;
                            goto ExitProcessing;
                        }
                        from=argv[i];
                    }
                }
                break;
            }

            case 'x':
            {
                if (strncmp("xforce",option+1,1) == 0)
                {
                    if (*option == '-')
                    {
                        g_force = MUTILS_TRUE;
                    }
                }
                break;
            }

            case 'h':
            {
                if (strncmp("help",option+1,1) == 0)
                {
                    usage();
                    rc = 0;
                    goto ExitProcessing;
                }
                /* won't be here */
                break;
            }

            case 'i':
            {
                if (strncmp("info",option+1,2) == 0)
                {
                    smtp_info=1;
                }
                break;
            }

            case 'l':
            {
                if (strncmp("list_address",option+1,3) == 0)
                {
                    if (*option == '-')
                    {
                        i++;
                        if (i == argc)
                        {
                            errorMsg("Missing address list file"); 
                            rc = 1;
                            goto ExitProcessing;
                        }
                        address_file=argv[i];
                    }
                }

                if (strncmp("log",option+1,3) == 0)
                {
                    if (*option == '-')
                    {
                        i++;
                        if (i == argc)
                        {
                            errorMsg("Missing address log file"); 
                            rc = 1;
                            goto ExitProcessing;
                        }
                        g_log_fp = fopen(argv[i], "a");
                        if (g_log_fp == NULL)
                        {
                            errorMsg("Could not open log file %s for writing (%s)",
                                    argv[i],
                                    strerror(errno));
                            rc = 1;
                            goto ExitProcessing;
                        }
                        /*
                        ** tell msock lib to write error message to log file
                        */
                        msock_set_logfp(g_log_fp);
                        mutilsSafeStrcpy(g_log_file,argv[i],sizeof(g_log_file)-1);
                    }
                }
                break;
            }

            case 'p':
            {
                if (strncmp("port",option+1,2) == 0)
                {
                    if (*option == '-')
                    {
                        i++;
                        if (i == argc)
                        {
                            errorMsg("Missing SMTP Port with -port");
                            rc = 1;
                            goto ExitProcessing;
                        }
                        port=atoi(argv[i]);
                    }
                }
                else if (strncmp("pass",option+1,2) == 0)
                {
                    if (*option == '-')
                    {
                        i++;
                        if (i == argc)
                        {
                            errorMsg("Missing password with -pass");
                            rc = 1;
                            goto ExitProcessing;
                        }
                        (void) snprintf(g_userpass,sizeof(g_userpass)-1,
                                        "%s",argv[i]);
                    }

                }
                else
                {
                    errorMsg("Unknown flag: %s\n",option);
                    rc = 1;
                    goto ExitProcessing;
                }
                break;
            }

            case 'H':
            {
                if (strncmp("Header",option+1,1) == 0)
                {
                    if (*option == '-')
                    {
                        i++;
                        if (i == argc)
                        {
                            errorMsg("Missing custom header");
                            rc = 1;
                            goto ExitProcessing;
                        }
                        custom_header=argv[i];
                        add_customer_header_to_list(custom_header);
                    }
                }
                else
                {
                    errorMsg("Unknown flag: %s\n",option);
                    rc = 1;
                    goto ExitProcessing;
                }

                break;
            }


            case 'M':
            {
                if (strncmp("Message",option+1,1) == 0)
                {
                    if (*option == '-')
                    {
                        i++;
                        if (i == argc)
                        {
                            errorMsg("Missing text message");
                            rc = 1;
                            goto ExitProcessing;
                        }
                        the_msg=xStrdup(argv[i]);
                        add_oneline_to_attachment_list(the_msg);
                    }
                }
                else
                {
                    errorMsg("Unknown flag: %s\n",option);
                    rc = 1;
                    goto ExitProcessing;
                }

                break;
            }

            case 'm':
            {
                if (strncmp("mime-type",option+1,9) == 0)
                {
                    if (*option == '-')
                    {
                        i++;
                        if (i == argc)
                        {
                            errorMsg("Missing mime type");
                            rc = 1;
                            goto ExitProcessing;
                        }
                        mutilsSafeStrcpy(g_mime_type,argv[i],sizeof(g_mime_type)-1);
                    }
                }
                else if (strncmp("msg-body",option+1,5) == 0)
                {
                    if (*option == '-')
                    {
                        i++;
                        if (i == argc)
                        {
                            errorMsg("Missing path of message body file");
                            rc = 1;
                            goto ExitProcessing;
                        }
                        msg_body_file = argv[i];
                        add_msg_body_to_attachment_list(argv[i]);
                    }
                }
                else
                {
                    errorMsg("Unknown flag: %s\n",option);
                    rc = 1;
                    goto ExitProcessing;
                }
                break;
            }

            case 'n':
            {
                if (strncmp("name",option+1,3) == 0)
                {
                    if (*option == '-')
                    {
                        i++;
                        if (i == argc)
                        {
                            errorMsg("Missing Name with -n");
                            rc = 1;
                            goto ExitProcessing;
                        }
                        (void) snprintf(g_from_name,sizeof(g_from_name)-1,
                                        "%s",argv[i]);
                    }
                }
                else
                {
                    errorMsg("Unknown flag: %s\n",option);
                    rc = 1;
                    goto ExitProcessing;
                }

                break;
            }

            case 's':
            {
                if (strncmp("smtp",option+1,3) == 0)
                {
                    if (*option == '-')
                    {
                        i++;
                        if (i == argc)
                        {
                            errorMsg("Missing smtp server");
                            rc = 1;
                            goto ExitProcessing;
                        }
                        smtp_server=argv[i];
                    }
                }
                else if (strncmp("subject",option+1,3) == 0)
                {
                    if (*option == '-')
                    {
                        i++;
                        if (i == argc)
                        {
                            errorMsg("Missing subject with -sub");
                            rc = 1;
                            goto ExitProcessing;
                        }
                        sub=argv[i];
                    }
                }
                else if (strncmp("ssl", option + 1, 3) == 0)
                {
#ifdef HAVE_OPENSSL
                    g_do_ssl=1;
#else
                    (void) fprintf(stderr,"Error: '-ssl' not available, not compiled with OpenSSL\n");
                    rc = 1;
                    goto ExitProcessing;
#endif /* HAVE_OPENSSL */

                }
                else if (strncmp("starttls",option+1,3) == 0)
                {
#ifdef HAVE_OPENSSL
                    g_do_starttls=1;
#else
                    (void) fprintf(stderr,"Error: '-starttls' not available, not compiled with OpenSSL\n");
                    rc = 1;
                    goto ExitProcessing;
                    
#endif /* HAVE_OPENSSL */
                }
                else if (strncmp("show-attach", option + 1, 9) == 0)
                {
                    g_show_attachment_in_log = 1;
                }
                else if (strncmp("show-mime-types",option+1,9) == 0)
                {
                    show_mime_types();
                    rc = 0;
                    goto ExitProcessing;
                }

                else if (strncmp("separator", option + 1, 4) == 0)
                {
                    if (*option == '-')
                    {
                        i++;
                        if (i == argc)
                        {
                            errorMsg("Missing separator");
                            rc = 1;
                            goto ExitProcessing;
                        }
                        (void) snprintf(g_attach_sep,sizeof(g_attach_sep)-1,"%s",argv[i]);
                        if (strlen(g_attach_sep) != 1)
                        {
                            errorMsg("Invalid separator character specified");
                            rc = 1;
                            goto ExitProcessing;
                        }
                    }
                }
                else
                {
                    errorMsg("Unknown flag: %s\n",option);
                    rc = 1;
                    goto ExitProcessing;
                }

                break;
            }

            case 'u':
            {
                if (strncmp("user",option+1,2) == 0)
                {
                    if (*option == '-')
                    {
                        i++;
                        if (i == argc)
                        {
                            errorMsg("Missing smtp server");
                            rc = 1;
                            goto ExitProcessing;
                        }
                        (void) snprintf(g_username,sizeof(g_username)-1,
                                        "%s",argv[i]);
                    }
                }
                else
                {
                    errorMsg("Unknown flag: %s\n",option);
                    rc = 1;
                    goto ExitProcessing;
                }

                break;
            }



            case 'v':
            {
                if (strncmp("verbose",option+1,1) == 0)
                {
                    if (*option == '-')
                    {
                        g_verbose=1;
                        msock_set_debug(g_verbose);
                    }
                }
                break;
            }

            case 'q':
            {
                if (strncmp("quiet",option+1,1) == 0)
                {
                    if (*option == '-')
                    {
                        g_quiet=1;
                    }
                }
                break;
            }
            

            case 'V':
            {
                (void) fprintf(stderr,"mailsend Version: %.1024s\n",MAILSEND_VERSION);
#ifdef HAVE_OPENSSL
                (void) fprintf(stderr,"Compiled with OpenSSL: %s\n",
                               SSLeay_version(SSLEAY_VERSION));
#else
                (void) fprintf(stderr,"Not Compiled OpenSSL, some auth methods will be unavailable\n");
#endif /* ! HAVE_OPENSSL */
                rc = 0;
                goto ExitProcessing;
                break;
            }

           case 't':
           {
                if (strncmp("to",option+1,1) == 0)
                {
                    if (*option == '-')
                    {
                        i++;
                        if (i == argc)
                        {
                            (void) fprintf(stderr,"Error: missing to addresses\n");
                            rc = 1;
                            goto ExitProcessing;
                        }
                        to=argv[i];
                        save_to=mutilsStrdup(to);
                        if (save_to == NULL)
                        {
                            errorMsg("memory allocation problem for -to");
                            rc = 1;
                            goto ExitProcessing;
                        }
                        save_to=fix_to(save_to);
                        to=fix_to(to);
                        /* collapse all spaces to a comma */
                        mutilsSpacesToChar(to,',');

                        /* add addresses to a singly linked list */
                        addAddressToList(to,"To");
                        /* Note: to is modifed now! */
                    }
                }
                break;
            }

            case 'r':
            {
                if (strncmp("rrr",option+1,3) == 0)
                {
                    if (*option == '-')
                    {
                        i++;
                        if (i == argc)
                        {
                            (void) fprintf(stderr,"Error: missing to addresses for -rrr\n");
                            rc = 1;
                            goto ExitProcessing;
                        }
                        rrr=mutilsStrdup(argv[i]);
                        if (rrr == NULL)
                        {
                            errorMsg("memory allocation problem for -rrr");
                            rc = 1;
                            goto ExitProcessing;
                        }
                    }
                }
                else if (strncmp("rt",option+1,2) == 0)
                {
                    if (*option == '-')
                    {
                        i++;
                        if (i == argc)
                        {
                            (void) fprintf(stderr,"Error: missing to addresses for -rt\n");
                            rc = 1;
                            goto ExitProcessing;
                        }
                        rt=mutilsStrdup(argv[i]);
                        if (rt == NULL)
                        {
                            errorMsg("memory allocation problem for -rt");
                            rc = 1;
                            goto ExitProcessing;
                        }
                    }
                }
                else
                {
                    errorMsg("Unknown flag: %s\n",option);
                    rc = 1;
                    goto ExitProcessing;
                }

                break;
            }

            case 'w':
            {
                if (strncmp("wait",option+1,1) == 0)
                {
                    if (*option == '-')
                    {
                        g_wait_for_cr=1;
                    }
                }

                break;
            }

            default:
            {
                (void) fprintf(stderr,"Error: Unrecognized option: %s\n",
                               option);
                rc = 1;
                goto ExitProcessing;
            }


        }
    }

    x=getenv("SMTP_USER_PASS");
    y=NULL;
    if (x && y)
    {
        (void) fprintf(stderr,"SMTP_USER_PASS and SMTP_USER_PASS_ENC can not be set. Exiting..\n");
        rc = 1;
        goto ExitProcessing;
    }
    if (x)
    {
        if (*g_userpass == '\0')
        {
            (void) snprintf(g_userpass,sizeof(g_userpass)-1,"%s",x);
        }
    }

#ifdef HAVE_OPENSSL
    if (g_do_ssl && g_do_starttls)
    {
        (void) fprintf(stderr,"Options -ssl and -starttls are mutually exclusive\n");
        rc = 1;
        goto ExitProcessing;
    }
#endif /* HAVE_OPENSSL */

    initialize_openssl(cipher);

    if (port == -1)
        port=MAILSEND_SMTP_PORT;
    if (smtp_info)
    {
        if (smtp_server == NULL)
            smtp_server="localhost";
    }
    if (smtp_info && smtp_server)
    {
        if (helo_domain == NULL)
            helo_domain="localhost";
        rc = show_smtp_info(smtp_server,port,helo_domain);
        if (rc < 0)
            rc = 1;
        goto ExitProcessing;
    }


    /*
    print_attachment_list();
    print_oneline_attachment_list();
    */

    /*
    ** attaching a file or a one line message will make the mail a 
    ** MIME mail
    */
    if (attach_file || the_msg || msg_body_file)
    {
        is_mime=1;
    }

    if (smtp_server == NULL)
    {
        memset(buf,0,sizeof(buf));
        x=askFor(buf,sizeof(buf)-1,"SMTP server address/IP: ",EMPTY_NOT_OK);
        if (x)
            smtp_server=xStrdup(x);
    }

    if (helo_domain == NULL)
    {
        /*
        memset(buf,0,sizeof(buf));
        x=askFor(buf,sizeof(buf)-1,"Domain: ",EMPTY_NOT_OK);
        if (x)
            helo_domain=xStrdup(x);
        */
        /* use localhost */
        helo_domain=xStrdup("localhost");
    }

    if (from == NULL)
    {
        memset(buf,0,sizeof(buf));
        x=askFor(buf,sizeof(buf)-1,"From: ",EMPTY_NOT_OK);
        if (x)
            from=xStrdup(x);
    }

    /* if address file specified, add the addresses to the list as well */
    if (address_file != NULL)
    {
        addAddressesFromFileToList(address_file);
        printAddressList();
    }

   /*
    ** The To address must be speicifed, even if the file with the list of
    ** addresses is specified. The specified To will be shown in the 
    ** envelope. None of the To, Cc and Bcc from the address list file will
    ** be shown anywhre.. that's how I like it. I hate long To, Cc or Bcc.
    ** [email protected], Thu Mar 29 11:56:45 EST 2001 
    */

    if (save_to == NULL)
    {
        /* don't ask for To add addresses are specified with -l file */
        if (getAddressList() == NULL)
        {
            memset(buf,0,sizeof(buf));
            x=askFor(buf,sizeof(buf)-1,"To: ",EMPTY_NOT_OK);
            if (x)
            {
                save_to=xStrdup(x);
                addAddressToList(x,"To");
            }
        }
    }

    /*
    ** if msg file specified, dont ask for unneeded things, as it could
    ** be used from other programs, and it will wait for input
    ** [email protected] Tue Apr 10 18:02:12 EST 2001 
    */

#ifdef WINNT
    if (attach_file == NULL && isInConsole(_fileno(stdin)))
#else
    if (attach_file == NULL && isatty(fileno(stdin)))
#endif /* WINNT */
    {
        if (save_cc == NULL && !no_cc)
        {
            memset(buf,0,sizeof(buf));
            x=askFor(buf,sizeof(buf)-1,"Carbon copy: ",EMPTY_OK);
            if (x)
            {
                save_cc=xStrdup(x);
                addAddressToList(x,"Cc");
            }
        }

        if (save_bcc == NULL && ! no_bcc)
        {
            memset(buf,0,sizeof(buf));
            x=askFor(buf,sizeof(buf)-1,"Blind Carbon copy: ",EMPTY_OK);
            if (x)
            {
                save_bcc=xStrdup(x);
                addAddressToList(x,"BCc");
            }
        }

        if (sub == NULL)
        {
            memset(buf,0,sizeof(buf));
            x=askFor(buf,sizeof(buf)-1,"Subject: ",EMPTY_OK);
            if (x)
                sub=xStrdup(x);
        }

        if (g_do_ssl || g_do_starttls)
        {
            if (*g_username == '\0')
            {
                memset(buf,0,sizeof(buf));
                x=askFor(buf,sizeof(buf)-1,"Auth user: "******"%s",x);
                }
            }

            if (*g_userpass == '\0')
            {
                (void) fprintf(stderr,"\nPlease specify auth password with -pass\n");
                (void) fprintf(stderr,"Or by environment variable SMTP_USER_PASS\n");
                rc = 1;
                goto ExitProcessing;
            }
        }
    }

    rc=validateMusts(from,save_to,smtp_server,helo_domain);
    if (rc != 0)
    {
        rc = 1;
        goto ExitProcessing;
    }

#ifdef UNIX
    signal(SIGPIPE,SIG_IGN);
#endif /* UNIX */

#if 0
    {
        MutilsTime
            mt;
        char
            timebuf[64];
        mutils_time_now(&mt);
        mutils_time_fmt(&mt, timebuf, sizeof(timebuf));
        (void) fprintf(stderr,"timebuf: %s\n",timebuf);
        return 1;
    }
#endif /* 0 */

    write_log("mailsend v%s\n",MAILSEND_VERSION);
    rc=send_the_mail(from,save_to,save_cc,save_bcc,sub,smtp_server,port,
                helo_domain,attach_file,msg_body_file,the_msg,is_mime,rrr,rt,add_dateh);

    if (rc == 0)
    {
        if (isInteractive())
        {
            if (!g_quiet)
            {
                (void) printf("Mail sent successfully\n");
                (void) fflush(stdout);
            }
        }
        if (!g_quiet)
        {
            write_log("Mail sent successfully\n");
        }
    }
    else
    {
        if (isInteractive())
        {
            (void) printf("Could not send mail\n");
        }
        write_log("Could not send mail\n");
    }

    if (isInteractive())
    {
        if (g_wait_for_cr)
        {
            printf("\nPress Enter to Exit: ");
            x=fgets(buf,sizeof(buf)-1,stdin);
        }
    }

    if (rc != 0)
    {
        rc = 1;
    }

ExitProcessing:
    close_log();
    return (rc);
}
Пример #16
0
/// Launch the realm server
extern int main(int argc, char **argv)
{
    ///- Command line parsing to get the configuration file name
    char const* cfg_file = _REALMD_CONFIG;
    int c=1;
    while( c < argc )
    {
        if( strcmp(argv[c],"-c") == 0)
        {
            if( ++c >= argc )
            {
                sLog.outError("Runtime-Error: -c option requires an input argument");
                usage(argv[0]);
                return 1;
            }
            else
                cfg_file = argv[c];
        }

        if( strcmp(argv[c],"--version") == 0)
        {
            printf("%s\n", _FULLVERSION(REVISION_DATE,REVISION_TIME,REVISION_NR,REVISION_ID));
            return 0;
        }

        #ifdef WIN32
        ////////////
        //Services//
        ////////////
        if( strcmp(argv[c],"-s") == 0)
        {
            if( ++c >= argc )
            {
                sLog.outError("Runtime-Error: -s option requires an input argument");
                usage(argv[0]);
                return 1;
            }
            if( strcmp(argv[c],"install") == 0)
            {
                if (WinServiceInstall())
                    sLog.outString("Installing service");
                return 1;
            }
            else if( strcmp(argv[c],"uninstall") == 0)
            {
                if(WinServiceUninstall())
                    sLog.outString("Uninstalling service");
                return 1;
            }
            else
            {
                sLog.outError("Runtime-Error: unsupported option %s",argv[c]);
                usage(argv[0]);
                return 1;
            }
        }
        if( strcmp(argv[c],"--service") == 0)
        {
            WinServiceRun();
        }
        ////
        #endif
        ++c;
    }

    if (!sConfig.SetSource(cfg_file))
    {
        sLog.outError("Could not find configuration file %s.", cfg_file);
        return 1;
    }
    sLog.Initialize();

    sLog.outString( "%s [realm-daemon]", _FULLVERSION(REVISION_DATE,REVISION_TIME,REVISION_NR,REVISION_ID) );
    sLog.outString( "<Ctrl-C> to stop.\n" );
    sLog.outString("Using configuration file %s.", cfg_file);

    ///- Check the version of the configuration file
    uint32 confVersion = sConfig.GetIntDefault("ConfVersion", 0);
    if (confVersion < _REALMDCONFVERSION)
    {
        sLog.outError("*****************************************************************************");
        sLog.outError(" WARNING: Your realmd.conf version indicates your conf file is out of date!");
        sLog.outError("          Please check for updates, as your current default values may cause");
        sLog.outError("          strange behavior.");
        sLog.outError("*****************************************************************************");
        clock_t pause = 3000 + clock();

        while (pause > clock()) {}
    }

    sLog.outDetail("%s (Library: %s)", OPENSSL_VERSION_TEXT, SSLeay_version(SSLEAY_VERSION));
    if (SSLeay() < 0x009080bfL )
    {
        sLog.outDetail("WARNING: Outdated version of OpenSSL lib. Logins to server may not work!");
        sLog.outDetail("WARNING: Minimal required version [OpenSSL 0.9.8k]");
    }

    /// realmd PID file creation
    std::string pidfile = sConfig.GetStringDefault("PidFile", "");
    if(!pidfile.empty())
    {
        uint32 pid = CreatePIDFile(pidfile);
        if( !pid )
        {
            sLog.outError( "Cannot create PID file %s.\n", pidfile.c_str() );
            return 1;
        }

        sLog.outString( "Daemon PID: %u\n", pid );
    }

    ///- Initialize the database connection
    if(!StartDB())
        return 1;

    ///- Get the list of realms for the server
    sRealmList.Initialize(sConfig.GetIntDefault("RealmsStateUpdateDelay", 20));
    if (sRealmList.size() == 0)
    {
        sLog.outError("No valid realms specified.");
        return 1;
    }

    ///- Launch the listening network socket
    port_t rmport = sConfig.GetIntDefault( "RealmServerPort", DEFAULT_REALMSERVER_PORT );
    std::string bind_ip = sConfig.GetStringDefault("BindIP", "0.0.0.0");

    SocketHandler h;
    ListenSocket<AuthSocket> authListenSocket(h);
    if ( authListenSocket.Bind(bind_ip.c_str(),rmport))
    {
        sLog.outError( "MaNGOS realmd can not bind to %s:%d",bind_ip.c_str(), rmport );
        return 1;
    }

    // cleanup query
    //set expired bans to inactive
    loginDatabase.Execute("UPDATE account_banned SET active = 0 WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
    loginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");

    h.Add(&authListenSocket);

    ///- Catch termination signals
    HookSignals();

    ///- Handle affinity for multiple processors and process priority on Windows
    #ifdef WIN32
    {
        HANDLE hProcess = GetCurrentProcess();

        uint32 Aff = sConfig.GetIntDefault("UseProcessors", 0);
        if(Aff > 0)
        {
            ULONG_PTR appAff;
            ULONG_PTR sysAff;

            if(GetProcessAffinityMask(hProcess,&appAff,&sysAff))
            {
                ULONG_PTR curAff = Aff & appAff;            // remove non accessible processors

                if(!curAff )
                {
                    sLog.outError("Processors marked in UseProcessors bitmask (hex) %x not accessible for realmd. Accessible processors bitmask (hex): %x",Aff,appAff);
                }
                else
                {
                    if(SetProcessAffinityMask(hProcess,curAff))
                        sLog.outString("Using processors (bitmask, hex): %x", curAff);
                    else
                        sLog.outError("Can't set used processors (hex): %x", curAff);
                }
            }
            sLog.outString();
        }

        bool Prio = sConfig.GetBoolDefault("ProcessPriority", false);

        if(Prio)
        {
            if(SetPriorityClass(hProcess,HIGH_PRIORITY_CLASS))
                sLog.outString("realmd process priority class set to HIGH");
            else
                sLog.outError("ERROR: Can't set realmd process priority class.");
            sLog.outString();
        }
    }
    #endif

    // maximum counter for next ping
    uint32 numLoops = (sConfig.GetIntDefault( "MaxPingTime", 30 ) * (MINUTE * 1000000 / 100000));
    uint32 loopCounter = 0;

    ///- Wait for termination signal
    while (!stopEvent)
    {

        h.Select(0, 100000);

        if( (++loopCounter) == numLoops )
        {
            loopCounter = 0;
            sLog.outDetail("Ping MySQL to keep connection alive");
            delete loginDatabase.Query("SELECT 1 FROM realmlist LIMIT 1");
        }
#ifdef WIN32
        if (m_ServiceStatus == 0) stopEvent = true;
        while (m_ServiceStatus == 2) Sleep(1000);
#endif
    }

    ///- Wait for the delay thread to exit
    loginDatabase.HaltDelayThread();

    ///- Remove signal handling before leaving
    UnhookSignals();

    sLog.outString( "Halting process..." );
    return 0;
}
Пример #17
0
/* exits after writing the usage */
static void usage(void)
{
    char
        **p;

    static char
        *options[]=
        {
"  -copyright            - show copyright information",
"  -4                    - Force to use IPv4 address of SMTP server",
"  -6                    - Force to use IPv6 address of SMTP server",
"  -smtp hostname/IP*    - Hostname/IP address of the SMTP server",
"  -port SMTP port       - SMTP port",
"  -domain    domain     - domain name for SMTP HELO/EHLO",
"  -t    to,to..*        - email address/es of the recipient/s",
"  -cc   cc,cc..         - carbon copy address/es",
"  +cc                   - do not ask for Carbon Copy",
"  -ct   seconds         - Connect timeout. Default is 5 seconds",
"  -bc   bcc,bcc..       - blind carbon copy address/es",
"  +bc                   - do not ask for Blind carbon copy",
"  +D                    - do not add Date header",
"  -f    address*        - email address of the sender",
"  -sub  subject         - subject",
"  -lilst file           - a file containing a list of email addresses",
"  -log file             - write log messages to this file",
"  -cs   character set   - for text/plain attachments (default is us-ascii)",
"  -separator character  - sepatorator used with -attach. Default is comma (,)",
"                          If used must be specified before -attach",
"  -enc-type type        - encoding type. base64, 8bit, 7bit etc.",
"                          Default is base64. Special type is \"none\"",
"  -aname name           - name of the attachment. Default is filename",
"  -content-id id        - content-id in the attachment",
"  -mime-type type       - MIME type",
"  -dispostion val       - \"attachment\" or \"inline\". Default is \"attachment\"",
"  -attach file,mime_type,[i/a] (i=inline,a=attachment)",
"                        - attach this file as attachment or inline",
"  -show-attach          - show attachment in verbose mode, default is no",
"  -show-mime-types      - show the compiled in MIME types",
"  -M    \"one line msg\"  - attach this one line text message",
"  -content-type type    - Content type. Default: multipart/mixed",
"  -msg-body path        - Path of the file to include as body of mail",
"  -embed-image image    - Path of image to embed in HTML",
"  -H    \"header\"        - Add custom Header",
"  -name \"Full Name\"     - add name in the From header",
"  -v                    - verbose mode",
"  -V                    - show version info",
"  -w                    - wait for a CR after sending the mail",
"  -rt  email_address    - add Reply-To header",
"  -rrr email_address    - request read receipts to this address",
"  -ssl                  - SMTP over SSL",
"  -starttls             - use STARTTLS if the server supports it",
"  -auth                 - try CRAM-MD5,LOGIN,PLAIN in that order",
"  -auth-cram-md5        - use AUTH CRAM-MD5 authentication",
"  -auth-plain           - use AUTH PLAIN authentication",
"  -auth-login           - use AUTH LOGIN authentication",
"  -user username        - username for ESMTP authentication",
"  -pass password        - password for ESMTP authentication",
"  -example              - show examples",
"  -ehlo                 - force EHLO",
"  -info                 - show SMTP server information",
"  -help                 - shows this help",
"  -q                    - quiet",
            (char *) NULL
        };
    (void) printf("\n");
    (void) printf(" Version: %.1024s\n\n",MAILSEND_VERSION);
    (void) printf(" Copyright: %.1024s\n\n",NO_SPAM_STATEMENT);
#ifdef HAVE_OPENSSL
    (void) fprintf(stdout," (Compiled with OpenSSL version: %s)\n",
                   SSLeay_version(SSLEAY_VERSION));
#else
    (void) fprintf(stdout," (Not compiled with OpenSSL)\n");
#endif /* HAVE_OPENSSL */

    (void) printf(" usage: mailsend [options]\n");
    (void) printf(" Where the options are:\n");

    for (p=options; *p != NULL; p++)
        (void) printf("%s\n",*p);

    (void) fprintf(stdout,"\n The options with * must be specified\n");
    (void) fprintf(stdout,
" Environment variables:\n"
"  SMTP_USER_PASS for plain text password (-pass)\n");
}
Пример #18
0
int MAIN(int argc, char **argv)
{
    int i,ret=0;
    int cflags=0,version=0,date=0,options=0,platform=0,dir=0;

    apps_startup();

    if (bio_err == NULL)
        if ((bio_err=BIO_new(BIO_s_file())) != NULL)
            BIO_set_fp(bio_err,stderr,BIO_NOCLOSE|BIO_FP_TEXT);

    if (argc == 1) version=1;
    for (i=1; i<argc; i++)
    {
        if (strcmp(argv[i],"-v") == 0)
            version=1;
        else if (strcmp(argv[i],"-b") == 0)
            date=1;
        else if (strcmp(argv[i],"-f") == 0)
            cflags=1;
        else if (strcmp(argv[i],"-o") == 0)
            options=1;
        else if (strcmp(argv[i],"-p") == 0)
            platform=1;
        else if (strcmp(argv[i],"-d") == 0)
            dir=1;
        else if (strcmp(argv[i],"-a") == 0)
            date=version=cflags=options=platform=dir=1;
        else
        {
            BIO_printf(bio_err,"usage:version -[avbofp]\n");
            ret=1;
            goto end;
        }
    }

    if (version) printf("%s\n",SSLeay_version(SSLEAY_VERSION));
    if (date)    printf("%s\n",SSLeay_version(SSLEAY_BUILT_ON));
    if (platform) printf("%s\n",SSLeay_version(SSLEAY_PLATFORM));
    if (options)
    {
        printf("options:  ");
        printf("%s ",BN_options());
#ifndef OPENSSL_NO_MD2
        printf("%s ",MD2_options());
#endif
#ifndef OPENSSL_NO_RC4
        printf("%s ",RC4_options());
#endif
#ifndef OPENSSL_NO_DES
        printf("%s ",DES_options());
#endif
#ifndef OPENSSL_NO_IDEA
        printf("%s ",idea_options());
#endif
#ifndef OPENSSL_NO_BF
        printf("%s ",BF_options());
#endif
        printf("\n");
    }
    if (cflags)  printf("%s\n",SSLeay_version(SSLEAY_CFLAGS));
    if (dir)  printf("%s\n",SSLeay_version(SSLEAY_DIR));
end:
    apps_shutdown();
    OPENSSL_EXIT(ret);
}
Пример #19
0
/// Launch the mangos server
int main(int argc, char *argv[])
{
    std::string auctionBotConfig, configFile, serviceParameter;

    boost::program_options::options_description desc("Allowed options");
    desc.add_options()
        ("ahbot,a", boost::program_options::value<std::string>(&auctionBotConfig), "ahbot configuration file")
        ("config,c", boost::program_options::value<std::string>(&configFile)->default_value(_MANGOSD_CONFIG), "configuration file")
        ("help,h", "prints usage")
        ("version,v", "print version and exit")
#ifdef WIN32
        ("s", boost::program_options::value<std::string>(&serviceParameter), "<run, install, uninstall> service");
#else
        ("s", boost::program_options::value<std::string>(&serviceParameter), "<run, stop> service");
#endif

    boost::program_options::variables_map vm;

    try
    {
        boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
        boost::program_options::notify(vm);

        if (vm.count("help"))
        {
            std::cout << desc << std::endl;
            return 0;
        }

        if (vm.count("version"))
        {
            std::cout << _FULLVERSION(REVISION_DATE, REVISION_TIME, REVISION_ID) << std::endl;
            std::cout << "Boost version " << (BOOST_VERSION / 10000) << "." << ((BOOST_VERSION / 100) % 1000) << "." << (BOOST_VERSION % 100) << std::endl;
            return 0;
        }
    }
    catch (boost::program_options::error const &e)
    {
        std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
        std::cerr << desc << std::endl;

        return 1;
    }

    if (vm.count("ahbot"))
        sAuctionBotConfig.SetConfigFileName(auctionBotConfig);

#ifdef WIN32                                                // windows service command need execute before config read
    if (vm.count("s"))
    {
        switch (::tolower(serviceParameter[0]))
        {
            case 'i':
                if (WinServiceInstall())
                    sLog.outString("Installing service");
                return 1;
            case 'u':
                if (WinServiceUninstall())
                    sLog.outString("Uninstalling service");
                return 1;
            case 'r':
                WinServiceRun();
                break;
        }
    }
#endif

    if (!sConfig.SetSource(configFile))
    {
        sLog.outError("Could not find configuration file %s.", configFile.c_str());
        Log::WaitBeforeContinueIfNeed();
        return 1;
    }

#ifndef WIN32                                               // posix daemon commands need apply after config read
    if (vm.count("s"))
    {
        switch (::tolower(serviceParameter[0]))
        {
            case 'r':
                startDaemon();
                break;
            case 's':
                stopDaemon();
                break;
        }
    }
#endif

    sLog.outString("%s [world-daemon]", _FULLVERSION(REVISION_DATE, REVISION_TIME, REVISION_ID));
    sLog.outString("<Ctrl-C> to stop.");
    sLog.outString("\n\n"
                   "       _____     __  __       _   _  _____  ____   _____ \n"
                   "      / ____|   |  \\/  |     | \\ | |/ ____|/ __ \\ / ____|\n"
                   "     | |        | \\  / |     |  \\| | |  __  |  | | (___  \n"
                   "     | |ontinued| |\\/| | __ _| . ` | | |_ | |  | |\\___ \\ \n"
                   "     | |____    | |  | |/ _` | |\\  | |__| | |__| |____) |\n"
                   "      \\_____|   |_|  |_| (_| |_| \\_|\\_____|\\____/ \\____/ \n"
                   "      http://cmangos.net\\__,_|     Doing things right!\n\n");

    sLog.outString("Using configuration file %s.", configFile.c_str());

    DETAIL_LOG("%s (Library: %s)", OPENSSL_VERSION_TEXT, SSLeay_version(SSLEAY_VERSION));
    if (SSLeay() < 0x009080bfL)
    {
        DETAIL_LOG("WARNING: Outdated version of OpenSSL lib. Logins to server may not work!");
        DETAIL_LOG("WARNING: Minimal required version [OpenSSL 0.9.8k]");
    }

    DETAIL_LOG("Using Boost: %s", BOOST_LIB_VERSION);

    ///- Set progress bars show mode
    BarGoLink::SetOutputState(sConfig.GetBoolDefault("ShowProgressBars", false));

    ///- and run the 'Master'
    /// \todo Why do we need this 'Master'? Can't all of this be in the Main as for Realmd?
    return sMaster.Run();

    // at sMaster return function exist with codes
    // 0 - normal shutdown
    // 1 - shutdown at error
    // 2 - restart command used, this code can be used by restarter for restart mangosd
}
Пример #20
0
void
rb_get_ssl_info(char *buf, size_t len)
{
	rb_snprintf(buf, len, "Using SSL: %s compiled: 0x%lx, library 0x%lx", 
		    SSLeay_version(SSLEAY_VERSION), OPENSSL_VERSION_NUMBER, SSLeay());
}
Пример #21
0
const char *
get_ssl_library_version(void)
{
    return SSLeay_version(SSLEAY_VERSION);
}
Пример #22
0
/// Launch the auth server
extern int main(int argc, char** argv)
{
    // Command line parsing to get the configuration file name
    char const* configFile = _TRINITY_REALM_CONFIG;
    int count = 1;
    while (count < argc)
    {
        if (strcmp(argv[count], "-c") == 0)
        {
            if (++count >= argc)
            {
                printf("Runtime-Error: -c option requires an input argument\n");
                usage(argv[0]);
                return 1;
            }
            else
                configFile = argv[count];
        }
        ++count;
    }

    if (!sConfigMgr->LoadInitial(configFile))
    {
        printf("Invalid or missing configuration file : %s\n", configFile);
        printf("Verify that the file exists and has \'[authserver]\' written in the top of the file!\n");
        return 1;
    }

    TC_LOG_INFO(LOG_FILTER_AUTHSERVER, "%s (authserver)", _FULLVERSION);
	TC_LOG_INFO(LOG_FILTER_AUTHSERVER, " ");
	TC_LOG_INFO(LOG_FILTER_AUTHSERVER, " A World of Warcraft: Cataclysm Core Emulator	");
	TC_LOG_INFO(LOG_FILTER_AUTHSERVER, "       _/_/              _/          _/_/_/    _/_/    _/_/_/    _/_/_/_/  ");
	TC_LOG_INFO(LOG_FILTER_AUTHSERVER, "    _/    _/  _/  _/_/  _/  _/    _/        _/    _/  _/    _/  _/         ");
	TC_LOG_INFO(LOG_FILTER_AUTHSERVER, "   _/_/_/_/  _/_/      _/_/      _/        _/    _/  _/_/_/    _/_/_/      ");
	TC_LOG_INFO(LOG_FILTER_AUTHSERVER, "  _/    _/  _/        _/  _/    _/        _/    _/  _/    _/  _/           ");
	TC_LOG_INFO(LOG_FILTER_AUTHSERVER, " _/    _/  _/        _/    _/    _/_/_/    _/_/    _/    _/  _/_/_/_/  	");
	TC_LOG_INFO(LOG_FILTER_AUTHSERVER, " Arkania Community (c) 2013");
	TC_LOG_INFO(LOG_FILTER_AUTHSERVER, "      <http://arkania.net/>");
	TC_LOG_INFO(LOG_FILTER_AUTHSERVER, " ");    
	TC_LOG_INFO(LOG_FILTER_AUTHSERVER, "<Ctrl-C> to stop.\n");
    TC_LOG_INFO(LOG_FILTER_AUTHSERVER, "Using configuration file %s.", configFile);
    TC_LOG_WARN(LOG_FILTER_AUTHSERVER, "%s (Library: %s)", OPENSSL_VERSION_TEXT, SSLeay_version(SSLEAY_VERSION));

#if defined (ACE_HAS_EVENT_POLL) || defined (ACE_HAS_DEV_POLL)
    ACE_Reactor::instance(new ACE_Reactor(new ACE_Dev_Poll_Reactor(ACE::max_handles(), 1), 1), true);
#else
    ACE_Reactor::instance(new ACE_Reactor(new ACE_TP_Reactor(), true), true);
#endif

    TC_LOG_DEBUG(LOG_FILTER_AUTHSERVER, "Max allowed open files is %d", ACE::max_handles());

    // authserver PID file creation
    std::string pidFile = sConfigMgr->GetStringDefault("PidFile", "");
    if (!pidFile.empty())
    {
        if (uint32 pid = CreatePIDFile(pidFile))
            TC_LOG_INFO(LOG_FILTER_AUTHSERVER, "Daemon PID: %u\n", pid);
        else
        {
            TC_LOG_ERROR(LOG_FILTER_AUTHSERVER, "Cannot create PID file %s.\n", pidFile.c_str());
            return 1;
        }
    }

    // Initialize the database connection
    if (!StartDB())
        return 1;

    // Get the list of realms for the server
    sRealmList->Initialize(sConfigMgr->GetIntDefault("RealmsStateUpdateDelay", 20));
    if (sRealmList->size() == 0)
    {
        TC_LOG_ERROR(LOG_FILTER_AUTHSERVER, "No valid realms specified.");
        return 1;
    }

    // Launch the listening network socket
    RealmAcceptor acceptor;

    int32 rmport = sConfigMgr->GetIntDefault("RealmServerPort", 3724);
    if (rmport < 0 || rmport > 0xFFFF)
    {
        TC_LOG_ERROR(LOG_FILTER_AUTHSERVER, "Specified port out of allowed range (1-65535)");
        return 1;
    }

    std::string bind_ip = sConfigMgr->GetStringDefault("BindIP", "0.0.0.0");

    ACE_INET_Addr bind_addr(uint16(rmport), bind_ip.c_str());

    if (acceptor.open(bind_addr, ACE_Reactor::instance(), ACE_NONBLOCK) == -1)
    {
        TC_LOG_ERROR(LOG_FILTER_AUTHSERVER, "Auth server can not bind to %s:%d", bind_ip.c_str(), rmport);
        return 1;
    }

    // Initialize the signal handlers
    AuthServerSignalHandler SignalINT, SignalTERM;

    // Register authservers's signal handlers
    ACE_Sig_Handler Handler;
    Handler.register_handler(SIGINT, &SignalINT);
    Handler.register_handler(SIGTERM, &SignalTERM);

    ///- Handle affinity for multiple processors and process priority
    uint32 affinity = sConfigMgr->GetIntDefault("UseProcessors", 0);
    bool highPriority = sConfigMgr->GetBoolDefault("ProcessPriority", false);

#ifdef _WIN32 // Windows
    {
        HANDLE hProcess = GetCurrentProcess();

        if (affinity > 0)
        {
            ULONG_PTR appAff;
            ULONG_PTR sysAff;

            if (GetProcessAffinityMask(hProcess, &appAff, &sysAff))
            {
                ULONG_PTR currentAffinity = affinity & appAff;            // remove non accessible processors

                if (!currentAffinity)
                    TC_LOG_ERROR(LOG_FILTER_AUTHSERVER, "Processors marked in UseProcessors bitmask (hex) %x are not accessible for the authserver. Accessible processors bitmask (hex): %x", affinity, appAff);
                else if (SetProcessAffinityMask(hProcess, currentAffinity))
                    TC_LOG_INFO(LOG_FILTER_AUTHSERVER, "Using processors (bitmask, hex): %x", currentAffinity);
                else
                    TC_LOG_ERROR(LOG_FILTER_AUTHSERVER, "Can't set used processors (hex): %x", currentAffinity);
            }
        }

        if (highPriority)
        {
            if (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS))
                TC_LOG_INFO(LOG_FILTER_AUTHSERVER, "authserver process priority class set to HIGH");
            else
                TC_LOG_ERROR(LOG_FILTER_AUTHSERVER, "Can't set authserver process priority class.");
        }
    }
#elif __linux__ // Linux

    if (affinity > 0)
    {
        cpu_set_t mask;
        CPU_ZERO(&mask);

        for (unsigned int i = 0; i < sizeof(affinity) * 8; ++i)
            if (affinity & (1 << i))
                CPU_SET(i, &mask);

        if (sched_setaffinity(0, sizeof(mask), &mask))
            TC_LOG_ERROR(LOG_FILTER_AUTHSERVER, "Can't set used processors (hex): %x, error: %s", affinity, strerror(errno));
        else
        {
            CPU_ZERO(&mask);
            sched_getaffinity(0, sizeof(mask), &mask);
            TC_LOG_INFO(LOG_FILTER_AUTHSERVER, "Using processors (bitmask, hex): %x", *(uint32*)(&mask));
        }
    }

    if (highPriority)
    {
        if (setpriority(PRIO_PROCESS, 0, PROCESS_HIGH_PRIORITY))
            TC_LOG_ERROR(LOG_FILTER_AUTHSERVER, "Can't set authserver process priority class, error: %s", strerror(errno));
        else
            TC_LOG_INFO(LOG_FILTER_AUTHSERVER, "authserver process priority class set to %i", getpriority(PRIO_PROCESS, 0));
    }

#endif

    // maximum counter for next ping
    uint32 numLoops = (sConfigMgr->GetIntDefault("MaxPingTime", 30) * (MINUTE * 1000000 / 100000));
    uint32 loopCounter = 0;

    // Wait for termination signal
    while (!stopEvent)
    {
        // dont move this outside the loop, the reactor will modify it
        ACE_Time_Value interval(0, 100000);

        if (ACE_Reactor::instance()->run_reactor_event_loop(interval) == -1)
            break;

        if ((++loopCounter) == numLoops)
        {
            loopCounter = 0;
            TC_LOG_INFO(LOG_FILTER_AUTHSERVER, "Ping MySQL to keep connection alive");
            LoginDatabase.KeepAlive();
        }
    }

    // Close the Database Pool and library
    StopDB();

    TC_LOG_INFO(LOG_FILTER_AUTHSERVER, "Halting process...");
    return 0;
}
Пример #23
0
/// Launch the mangos server
extern int main(int argc, char** argv)
{
    ///- Command line parsing
    std::string cfg_file;
    std::string serviceDaemonMode;

    boost::program_options::options_description description("Allowed options");
    description.add_options()
        ("version,v", "print version and exit")
        ("help,h", "print commandline help and exit")
        ("config,c", boost::program_options::value<std::string>(&cfg_file)->default_value(_MANGOSD_CONFIG), "use as configuration file")
        ("ahbot,a", boost::program_options::value<std::string>(), "use as ahbot configuration file")
#ifdef WIN32
        ("service,s", boost::program_options::value<std::string>(&serviceDaemonMode), "running as service, arg functions: run, install, uninstall")
#else
        ("service,s", boost::program_options::value<std::string>(&serviceDaemonMode), "running as daemon, arg functions: run, stop")
#endif
        ;

    // parse option
    boost::program_options::variables_map vm;

    try {
        boost::program_options::store(boost::program_options::command_line_parser(argc, argv).
        options(description).run(), vm);
        boost::program_options::notify(vm);
    }
    catch(boost::program_options::unknown_option const& ex)
    {
        sLog.outError("Runtime-Error: unknown option %s", ex.get_option_name().c_str());
        usage(description, argv[0]);
        Log::WaitBeforeContinueIfNeed();
        return 1;
    }
    catch(boost::program_options::invalid_command_line_syntax const& ex)
    {
        sLog.outError("Runtime-Error: invalid syntax for option %s", ex.get_option_name().c_str());
        usage(description, argv[0]);
        Log::WaitBeforeContinueIfNeed();
        return 1;
    }

    if (vm.count("version"))
    {
        return 0;
    }

    if (vm.count("help"))
    {
        usage(description, argv[0]);
        return 0;
    }

    if (!serviceDaemonMode.empty())
    {
#ifdef WIN32
        char const* const serviceModes[] =  { "run", "install", "uninstall", NULL };
#else
        char const* const serviceModes[] =  { "run", "stop", NULL };
#endif
        char const* const* mode_ptr = &serviceModes[0];
        for(; *mode_ptr != NULL; ++mode_ptr)
            if (*mode_ptr == serviceDaemonMode)
                break;

        if (!*mode_ptr)
        {
            sLog.outError("Runtime-Error: -s unsupported argument %s", serviceDaemonMode.c_str());
            usage(description, argv[0]);
            Log::WaitBeforeContinueIfNeed();
            return 1;
        }
    }

#ifdef WIN32                                                // windows service command need execute before config read
    switch (serviceDaemonMode[0])
    {
        case 'i':
            if (WinServiceInstall())
                sLog.outString("Installing service");
            return 1;
        case 'u':
            if (WinServiceUninstall())
                sLog.outString("Uninstalling service");
            return 1;
        case 'r':
            WinServiceRun();
            break;
    }
#endif

    if (!sConfig.SetSource(cfg_file, "MangosdConf"))
    {
        sLog.outError("Could not find configuration file %s.", cfg_file.c_str());
        usage(description, argv[0]);
        Log::WaitBeforeContinueIfNeed();
        return 1;
    }

#ifndef WIN32                                               // posix daemon commands need apply after config read
    switch (serviceDaemonMode[0])
    {
        case 'r':
            startDaemon();
            break;
        case 's':
            stopDaemon();
            break;
    }
#endif

    sLog.outString("<Ctrl-C> to stop.");
    sLog.outString("\n\n"
                   "MM   MM         MM   MM  MMMMM   MMMM   MMMMM\n"
                   "MM   MM         MM   MM MMM MMM MM  MM MMM MMM\n"
                   "MMM MMM         MMM  MM MMM MMM MM  MM MMM\n"
                   "MM M MM         MMMM MM MMM     MM  MM  MMM\n"
                   "MM M MM  MMMMM  MM MMMM MMM     MM  MM   MMM\n"
                   "MM M MM M   MMM MM  MMM MMMMMMM MM  MM    MMM\n"
                   "MM   MM     MMM MM   MM MM  MMM MM  MM     MMM\n"
                   "MM   MM MMMMMMM MM   MM MMM MMM MM  MM MMM MMM\n"
                   "MM   MM MM  MMM MM   MM  MMMMMM  MMMM   MMMMM\n"
                   "        MM  MMM http://getmangos.com\n"
                   "        MMMMMM\n\n");
    sLog.outString("Using configuration file %s.", cfg_file.c_str());

    DETAIL_LOG("%s (Library: %s)", OPENSSL_VERSION_TEXT, SSLeay_version(SSLEAY_VERSION));
    if (SSLeay() < 0x009080bfL)
    {
        DETAIL_LOG("WARNING: Outdated version of OpenSSL lib. Logins to server may not work!");
        DETAIL_LOG("WARNING: Minimal required version [OpenSSL 0.9.8k]");
    }

    //DETAIL_LOG("Using ACE: %s", ACE_VERSION);
    DETAIL_LOG("Using BOOST: %i.%i.%i", BOOST_VERSION / 100000, BOOST_VERSION / 100 % 1000, BOOST_VERSION % 100);

    ///- Set progress bars show mode
    BarGoLink::SetOutputState(sConfig.GetBoolDefault("ShowProgressBars", true));

    ///- and run the 'Master'
    /// \todo Why do we need this 'Master'? Can't all of this be in the Main as for Realmd?
    return sMaster.Run();

    // at sMaster return function exist with codes
    // 0 - normal shutdown
    // 1 - shutdown at error
    // 2 - restart command used, this code can be used by restarter for restart mangosd
}
Пример #24
0
const char *
tls_backend_version(void)
{
	return SSLeay_version(SSLEAY_VERSION);
}
Пример #25
0
/// Launch the mangos server
extern int main(int argc, char **argv)
{
    // - Construct Memory Manager Instance
    MaNGOS::Singleton<MemoryManager>::Instance();

    //char *leak = new char[1000];                          // test leak detection

    ///- Command line parsing to get the configuration file name
    char const* cfg_file = _MANGOSD_CONFIG;
    int c=1;
    while( c < argc )
    {
        if( strcmp(argv[c],"-c") == 0)
        {
            if( ++c >= argc )
            {
                sLog.outError("Runtime-Error: -c option requires an input argument");
                usage(argv[0]);
                return 1;
            }
            else
                cfg_file = argv[c];
        }

        if( strcmp(argv[c],"--version") == 0)
        {
            printf("%s\n", _FULLVERSION(REVISION_DATE,REVISION_TIME,REVISION_NR,REVISION_ID));
            return 0;
        }

        #ifdef WIN32
        ////////////
        //Services//
        ////////////
        if( strcmp(argv[c],"-s") == 0)
        {
            if( ++c >= argc )
            {
                sLog.outError("Runtime-Error: -s option requires an input argument");
                usage(argv[0]);
                return 1;
            }
            if( strcmp(argv[c],"install") == 0)
            {
                if (WinServiceInstall())
                    sLog.outString("Installing service");
                return 1;
            }
            else if( strcmp(argv[c],"uninstall") == 0)
            {
                if(WinServiceUninstall())
                    sLog.outString("Uninstalling service");
                return 1;
            }
            else
            {
                sLog.outError("Runtime-Error: unsupported option %s",argv[c]);
                usage(argv[0]);
                return 1;
            }
        }
        if( strcmp(argv[c],"--service") == 0)
        {
            WinServiceRun();
        }
        ////
        #endif
        ++c;
    }

    if (!sConfig.SetSource(cfg_file))
    {
        sLog.outError("Could not find configuration file %s.", cfg_file);
        return 1;
    }

    sLog.outString( "%s [world-daemon]", _FULLVERSION(REVISION_DATE,REVISION_TIME,REVISION_NR,REVISION_ID) );
    sLog.outString( "<Ctrl-C> to stop.\n\n" );

    sLog.outTitle( "MM   MM         MM   MM  MMMMM   MMMM   MMMMM");
    sLog.outTitle( "MM   MM         MM   MM MMM MMM MM  MM MMM MMM");
    sLog.outTitle( "MMM MMM         MMM  MM MMM MMM MM  MM MMM");
    sLog.outTitle( "MM M MM         MMMM MM MMM     MM  MM  MMM");
    sLog.outTitle( "MM M MM  MMMMM  MM MMMM MMM     MM  MM   MMM");
    sLog.outTitle( "MM M MM M   MMM MM  MMM MMMMMMM MM  MM    MMM");
    sLog.outTitle( "MM   MM     MMM MM   MM MM  MMM MM  MM     MMM");
    sLog.outTitle( "MM   MM MMMMMMM MM   MM MMM MMM MM  MM MMM MMM");
    sLog.outTitle( "MM   MM MM  MMM MM   MM  MMMMMM  MMMM   MMMMM");
    sLog.outTitle( "        MM  MMM http://getmangos.com");
    sLog.outTitle( "        MMMMMM\n\n");

    sLog.outString("Using configuration file %s.", cfg_file);

    sLog.outDetail("%s (Library: %s)", OPENSSL_VERSION_TEXT, SSLeay_version(SSLEAY_VERSION));
    if (SSLeay() < 0x009080bfL )
    {
        sLog.outDetail("WARNING: Outdated version of OpenSSL lib. Logins to server may not work!");
        sLog.outDetail("WARNING: Minimal required version [OpenSSL 0.9.8k]");
    }
    sLog.outDetail("Using ACE: %s", ACE_VERSION);

    ///- and run the 'Master'
    /// \todo Why do we need this 'Master'? Can't all of this be in the Main as for Realmd?
    return sMaster.Run();

    // at sMaster return function exist with codes
    // 0 - normal shutdown
    // 1 - shutdown at error
    // 2 - restart command used, this code can be used by restarter for restart mangosd
}
Пример #26
0
/*
 * Main program for the ssh client.
 */
int
main(int ac, char **av)
{
	int i, r, opt, exit_status, use_syslog;
	char *p, *cp, *line, *argv0, buf[MAXPATHLEN], *host_arg;
	char thishost[NI_MAXHOST], shorthost[NI_MAXHOST], portstr[NI_MAXSERV];
	struct stat st;
	struct passwd *pw;
	int dummy, timeout_ms;
	extern int optind, optreset;
	extern char *optarg;

	struct servent *sp;
	Forward fwd;

	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
	sanitise_stdfd();

	__progname = ssh_get_progname(av[0]);

#ifndef HAVE_SETPROCTITLE
	/* Prepare for later setproctitle emulation */
	/* Save argv so it isn't clobbered by setproctitle() emulation */
	saved_av = xcalloc(ac + 1, sizeof(*saved_av));
	for (i = 0; i < ac; i++)
		saved_av[i] = xstrdup(av[i]);
	saved_av[i] = NULL;
	compat_init_setproctitle(ac, av);
	av = saved_av;
#endif

	/*
	 * Discard other fds that are hanging around. These can cause problem
	 * with backgrounded ssh processes started by ControlPersist.
	 */
	closefrom(STDERR_FILENO + 1);

	/*
	 * Save the original real uid.  It will be needed later (uid-swapping
	 * may clobber the real uid).
	 */
	original_real_uid = getuid();
	original_effective_uid = geteuid();

	/*
	 * Use uid-swapping to give up root privileges for the duration of
	 * option processing.  We will re-instantiate the rights when we are
	 * ready to create the privileged port, and will permanently drop
	 * them when the port has been created (actually, when the connection
	 * has been made, as we may need to create the port several times).
	 */
	PRIV_END;

#ifdef HAVE_SETRLIMIT
	/* If we are installed setuid root be careful to not drop core. */
	if (original_real_uid != original_effective_uid) {
		struct rlimit rlim;
		rlim.rlim_cur = rlim.rlim_max = 0;
		if (setrlimit(RLIMIT_CORE, &rlim) < 0)
			fatal("setrlimit failed: %.100s", strerror(errno));
	}
#endif
	/* Get user data. */
	pw = getpwuid(original_real_uid);
	if (!pw) {
		logit("You don't exist, go away!");
		exit(255);
	}
	/* Take a copy of the returned structure. */
	pw = pwcopy(pw);

	/*
	 * Set our umask to something reasonable, as some files are created
	 * with the default umask.  This will make them world-readable but
	 * writable only by the owner, which is ok for all files for which we
	 * don't set the modes explicitly.
	 */
	umask(022);

	/*
	 * Initialize option structure to indicate that no values have been
	 * set.
	 */
	initialize_options(&options);

	/* Parse command-line arguments. */
	host = NULL;
	use_syslog = 0;
	argv0 = av[0];

 again:
	while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
	    "ACD:F:I:KL:MNO:PR:S:TVw:W:XYy")) != -1) {
		switch (opt) {
		case '1':
			options.protocol = SSH_PROTO_1;
			break;
		case '2':
			options.protocol = SSH_PROTO_2;
			break;
		case '4':
			options.address_family = AF_INET;
			break;
		case '6':
			options.address_family = AF_INET6;
			break;
		case 'n':
			stdin_null_flag = 1;
			break;
		case 'f':
			fork_after_authentication_flag = 1;
			stdin_null_flag = 1;
			break;
		case 'x':
			options.forward_x11 = 0;
			break;
		case 'X':
			options.forward_x11 = 1;
			break;
		case 'y':
			use_syslog = 1;
			break;
		case 'Y':
			options.forward_x11 = 1;
			options.forward_x11_trusted = 1;
			break;
		case 'g':
			options.gateway_ports = 1;
			break;
		case 'O':
			if (stdio_forward_host != NULL)
				fatal("Cannot specify multiplexing "
				    "command with -W");
			else if (muxclient_command != 0)
				fatal("Multiplexing command already specified");
			if (strcmp(optarg, "check") == 0)
				muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
			else if (strcmp(optarg, "forward") == 0)
				muxclient_command = SSHMUX_COMMAND_FORWARD;
			else if (strcmp(optarg, "exit") == 0)
				muxclient_command = SSHMUX_COMMAND_TERMINATE;
			else if (strcmp(optarg, "stop") == 0)
				muxclient_command = SSHMUX_COMMAND_STOP;
			else if (strcmp(optarg, "cancel") == 0)
				muxclient_command = SSHMUX_COMMAND_CANCEL_FWD;
			else
				fatal("Invalid multiplex command.");
			break;
		case 'P':	/* deprecated */
			options.use_privileged_port = 0;
			break;
		case 'a':
			options.forward_agent = 0;
			break;
		case 'A':
			options.forward_agent = 1;
			break;
		case 'k':
			options.gss_deleg_creds = 0;
			break;
		case 'K':
			options.gss_authentication = 1;
			options.gss_deleg_creds = 1;
			break;
		case 'i':
			if (stat(optarg, &st) < 0) {
				fprintf(stderr, "Warning: Identity file %s "
				    "not accessible: %s.\n", optarg,
				    strerror(errno));
				break;
			}
			if (options.num_identity_files >=
			    SSH_MAX_IDENTITY_FILES)
				fatal("Too many identity files specified "
				    "(max %d)", SSH_MAX_IDENTITY_FILES);
			options.identity_files[options.num_identity_files++] =
			    xstrdup(optarg);
			break;
		case 'I':
#ifdef ENABLE_PKCS11
			options.pkcs11_provider = xstrdup(optarg);
#else
			fprintf(stderr, "no support for PKCS#11.\n");
#endif
			break;
		case 't':
			if (options.request_tty == REQUEST_TTY_YES)
				options.request_tty = REQUEST_TTY_FORCE;
			else
				options.request_tty = REQUEST_TTY_YES;
			break;
		case 'v':
			if (debug_flag == 0) {
				debug_flag = 1;
				options.log_level = SYSLOG_LEVEL_DEBUG1;
			} else {
				if (options.log_level < SYSLOG_LEVEL_DEBUG3)
					options.log_level++;
				break;
			}
			/* FALLTHROUGH */
		case 'V':
			if (options.version_addendum &&
			    *options.version_addendum != '\0')
				fprintf(stderr, "%s%s %s, %s\n", SSH_RELEASE,
				    options.hpn_disabled ? "" : SSH_VERSION_HPN,
				    options.version_addendum,
				    SSLeay_version(SSLEAY_VERSION));
			else
				fprintf(stderr, "%s%s, %s\n", SSH_RELEASE,
				    options.hpn_disabled ? "" : SSH_VERSION_HPN,
				    SSLeay_version(SSLEAY_VERSION));
			if (opt == 'V')
				exit(0);
			break;
		case 'w':
			if (options.tun_open == -1)
				options.tun_open = SSH_TUNMODE_DEFAULT;
			options.tun_local = a2tun(optarg, &options.tun_remote);
			if (options.tun_local == SSH_TUNID_ERR) {
				fprintf(stderr,
				    "Bad tun device '%s'\n", optarg);
				exit(255);
			}
			break;
		case 'W':
			if (stdio_forward_host != NULL)
				fatal("stdio forward already specified");
			if (muxclient_command != 0)
				fatal("Cannot specify stdio forward with -O");
			if (parse_forward(&fwd, optarg, 1, 0)) {
				stdio_forward_host = fwd.listen_host;
				stdio_forward_port = fwd.listen_port;
				xfree(fwd.connect_host);
			} else {
				fprintf(stderr,
				    "Bad stdio forwarding specification '%s'\n",
				    optarg);
				exit(255);
			}
			options.request_tty = REQUEST_TTY_NO;
			no_shell_flag = 1;
			options.clear_forwardings = 1;
			options.exit_on_forward_failure = 1;
			break;
		case 'q':
			options.log_level = SYSLOG_LEVEL_QUIET;
			break;
		case 'e':
			if (optarg[0] == '^' && optarg[2] == 0 &&
			    (u_char) optarg[1] >= 64 &&
			    (u_char) optarg[1] < 128)
				options.escape_char = (u_char) optarg[1] & 31;
			else if (strlen(optarg) == 1)
				options.escape_char = (u_char) optarg[0];
			else if (strcmp(optarg, "none") == 0)
				options.escape_char = SSH_ESCAPECHAR_NONE;
			else {
				fprintf(stderr, "Bad escape character '%s'.\n",
				    optarg);
				exit(255);
			}
			break;
		case 'c':
			if (ciphers_valid(optarg)) {
				/* SSH2 only */
				options.ciphers = xstrdup(optarg);
				options.cipher = SSH_CIPHER_INVALID;
			} else {
				/* SSH1 only */
				options.cipher = cipher_number(optarg);
				if (options.cipher == -1) {
					fprintf(stderr,
					    "Unknown cipher type '%s'\n",
					    optarg);
					exit(255);
				}
				if (options.cipher == SSH_CIPHER_3DES)
					options.ciphers = "3des-cbc";
				else if (options.cipher == SSH_CIPHER_BLOWFISH)
					options.ciphers = "blowfish-cbc";
				else
					options.ciphers = (char *)-1;
			}
			break;
		case 'm':
			if (mac_valid(optarg))
				options.macs = xstrdup(optarg);
			else {
				fprintf(stderr, "Unknown mac type '%s'\n",
				    optarg);
				exit(255);
			}
			break;
		case 'M':
			if (options.control_master == SSHCTL_MASTER_YES)
				options.control_master = SSHCTL_MASTER_ASK;
			else
				options.control_master = SSHCTL_MASTER_YES;
			break;
		case 'p':
			options.port = a2port(optarg);
			if (options.port <= 0) {
				fprintf(stderr, "Bad port '%s'\n", optarg);
				exit(255);
			}
			break;
		case 'l':
			options.user = optarg;
			break;

		case 'L':
			if (parse_forward(&fwd, optarg, 0, 0))
				add_local_forward(&options, &fwd);
			else {
				fprintf(stderr,
				    "Bad local forwarding specification '%s'\n",
				    optarg);
				exit(255);
			}
			break;

		case 'R':
			if (parse_forward(&fwd, optarg, 0, 1)) {
				add_remote_forward(&options, &fwd);
			} else {
				fprintf(stderr,
				    "Bad remote forwarding specification "
				    "'%s'\n", optarg);
				exit(255);
			}
			break;

		case 'D':
			if (parse_forward(&fwd, optarg, 1, 0)) {
				add_local_forward(&options, &fwd);
			} else {
				fprintf(stderr,
				    "Bad dynamic forwarding specification "
				    "'%s'\n", optarg);
				exit(255);
			}
			break;

		case 'C':
			options.compression = 1;
			break;
		case 'N':
			no_shell_flag = 1;
			options.request_tty = REQUEST_TTY_NO;
			break;
		case 'T':
			options.request_tty = REQUEST_TTY_NO;
#ifdef	NONE_CIPHER_ENABLED
			/*
			 * Ensure that the user does not try to backdoor a
			 * NONE cipher switch on an interactive session by
			 * explicitly disabling it if the user asks for a
			 * session without a tty.
			 */
			options.none_switch = 0;
#endif
			break;
		case 'o':
			dummy = 1;
			line = xstrdup(optarg);
			if (process_config_line(&options, host ? host : "",
			    line, "command-line", 0, &dummy) != 0)
				exit(255);
			xfree(line);
			break;
		case 's':
			subsystem_flag = 1;
			break;
		case 'S':
			if (options.control_path != NULL)
				free(options.control_path);
			options.control_path = xstrdup(optarg);
			break;
		case 'b':
			options.bind_address = optarg;
			break;
		case 'F':
			config = optarg;
			break;
		default:
			usage();
		}
	}

	ac -= optind;
	av += optind;

	if (ac > 0 && !host) {
		if (strrchr(*av, '@')) {
			p = xstrdup(*av);
			cp = strrchr(p, '@');
			if (cp == NULL || cp == p)
				usage();
			options.user = p;
			*cp = '\0';
			host = ++cp;
		} else
			host = *av;
		if (ac > 1) {
			optind = optreset = 1;
			goto again;
		}
		ac--, av++;
	}

	/* Check that we got a host name. */
	if (!host)
		usage();

	OpenSSL_add_all_algorithms();
	ERR_load_crypto_strings();

	/* Initialize the command to execute on remote host. */
	buffer_init(&command);

	/*
	 * Save the command to execute on the remote host in a buffer. There
	 * is no limit on the length of the command, except by the maximum
	 * packet size.  Also sets the tty flag if there is no command.
	 */
	if (!ac) {
		/* No command specified - execute shell on a tty. */
		if (subsystem_flag) {
			fprintf(stderr,
			    "You must specify a subsystem to invoke.\n");
			usage();
		}
	} else {
		/* A command has been specified.  Store it into the buffer. */
		for (i = 0; i < ac; i++) {
			if (i)
				buffer_append(&command, " ", 1);
			buffer_append(&command, av[i], strlen(av[i]));
		}
	}

	/* Cannot fork to background if no command. */
	if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
	    !no_shell_flag)
		fatal("Cannot fork into background without a command "
		    "to execute.");

	/*
	 * Initialize "log" output.  Since we are the client all output
	 * actually goes to stderr.
	 */
	log_init(argv0,
	    options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
	    SYSLOG_FACILITY_USER, !use_syslog);

	/*
	 * Read per-user configuration file.  Ignore the system wide config
	 * file if the user specifies a config file on the command line.
	 */
	if (config != NULL) {
		if (!read_config_file(config, host, &options, 0))
			fatal("Can't open user config file %.100s: "
			    "%.100s", config, strerror(errno));
	} else {
		r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
		    _PATH_SSH_USER_CONFFILE);
		if (r > 0 && (size_t)r < sizeof(buf))
			(void)read_config_file(buf, host, &options, 1);

		/* Read systemwide configuration file after user config. */
		(void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
		    &options, 0);
	}

	/* Fill configuration defaults. */
	fill_default_options(&options);

	channel_set_af(options.address_family);

	/* reinit */
	log_init(argv0, options.log_level, SYSLOG_FACILITY_USER, !use_syslog);

	if (options.request_tty == REQUEST_TTY_YES ||
	    options.request_tty == REQUEST_TTY_FORCE)
		tty_flag = 1;

	/* Allocate a tty by default if no command specified. */
	if (buffer_len(&command) == 0)
		tty_flag = options.request_tty != REQUEST_TTY_NO;

	/* Force no tty */
	if (options.request_tty == REQUEST_TTY_NO || muxclient_command != 0)
		tty_flag = 0;
	/* Do not allocate a tty if stdin is not a tty. */
	if ((!isatty(fileno(stdin)) || stdin_null_flag) &&
	    options.request_tty != REQUEST_TTY_FORCE) {
		if (tty_flag)
			logit("Pseudo-terminal will not be allocated because "
			    "stdin is not a terminal.");
		tty_flag = 0;
	}

	seed_rng();

	if (options.user == NULL)
		options.user = xstrdup(pw->pw_name);

	/* Get default port if port has not been set. */
	if (options.port == 0) {
		sp = getservbyname(SSH_SERVICE_NAME, "tcp");
		options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
	}

	/* preserve host name given on command line for %n expansion */
	host_arg = host;
	if (options.hostname != NULL) {
		host = percent_expand(options.hostname,
		    "h", host, (char *)NULL);
	}

	if (gethostname(thishost, sizeof(thishost)) == -1)
		fatal("gethostname: %s", strerror(errno));
	strlcpy(shorthost, thishost, sizeof(shorthost));
	shorthost[strcspn(thishost, ".")] = '\0';
	snprintf(portstr, sizeof(portstr), "%d", options.port);

	if (options.local_command != NULL) {
		debug3("expanding LocalCommand: %s", options.local_command);
		cp = options.local_command;
		options.local_command = percent_expand(cp, "d", pw->pw_dir,
		    "h", host, "l", thishost, "n", host_arg, "r", options.user,
		    "p", portstr, "u", pw->pw_name, "L", shorthost,
		    (char *)NULL);
		debug3("expanded LocalCommand: %s", options.local_command);
		xfree(cp);
	}

	/* Find canonic host name. */
	if (strchr(host, '.') == 0) {
		struct addrinfo hints;
		struct addrinfo *ai = NULL;
		int errgai;
		memset(&hints, 0, sizeof(hints));
		hints.ai_family = options.address_family;
		hints.ai_flags = AI_CANONNAME;
		hints.ai_socktype = SOCK_STREAM;
		errgai = getaddrinfo(host, NULL, &hints, &ai);
		if (errgai == 0) {
			if (ai->ai_canonname != NULL)
				host = xstrdup(ai->ai_canonname);
			freeaddrinfo(ai);
		}
	}

	/* force lowercase for hostkey matching */
	if (options.host_key_alias != NULL) {
		for (p = options.host_key_alias; *p; p++)
			if (isupper(*p))
				*p = (char)tolower(*p);
	}

	if (options.proxy_command != NULL &&
	    strcmp(options.proxy_command, "none") == 0) {
		xfree(options.proxy_command);
		options.proxy_command = NULL;
	}
	if (options.control_path != NULL &&
	    strcmp(options.control_path, "none") == 0) {
		xfree(options.control_path);
		options.control_path = NULL;
	}

	if (options.control_path != NULL) {
		cp = tilde_expand_filename(options.control_path,
		    original_real_uid);
		xfree(options.control_path);
		options.control_path = percent_expand(cp, "h", host,
		    "l", thishost, "n", host_arg, "r", options.user,
		    "p", portstr, "u", pw->pw_name, "L", shorthost,
		    (char *)NULL);
		xfree(cp);
	}
	if (muxclient_command != 0 && options.control_path == NULL)
		fatal("No ControlPath specified for \"-O\" command");
	if (options.control_path != NULL)
		muxclient(options.control_path);

	timeout_ms = options.connection_timeout * 1000;

	/* Open a connection to the remote host. */
	if (ssh_connect(host, &hostaddr, options.port,
	    options.address_family, options.connection_attempts, &timeout_ms,
	    options.tcp_keep_alive, 
#ifdef HAVE_CYGWIN
	    options.use_privileged_port,
#else
	    original_effective_uid == 0 && options.use_privileged_port,
#endif
	    options.proxy_command) != 0)
		exit(255);

	if (timeout_ms > 0)
		debug3("timeout: %d ms remain after connect", timeout_ms);

	/*
	 * If we successfully made the connection, load the host private key
	 * in case we will need it later for combined rsa-rhosts
	 * authentication. This must be done before releasing extra
	 * privileges, because the file is only readable by root.
	 * If we cannot access the private keys, load the public keys
	 * instead and try to execute the ssh-keysign helper instead.
	 */
	sensitive_data.nkeys = 0;
	sensitive_data.keys = NULL;
	sensitive_data.external_keysign = 0;
	if (options.rhosts_rsa_authentication ||
	    options.hostbased_authentication) {
		sensitive_data.nkeys = 7;
		sensitive_data.keys = xcalloc(sensitive_data.nkeys,
		    sizeof(Key));
		for (i = 0; i < sensitive_data.nkeys; i++)
			sensitive_data.keys[i] = NULL;

		PRIV_START;
		sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
		    _PATH_HOST_KEY_FILE, "", NULL, NULL);
		sensitive_data.keys[1] = key_load_private_cert(KEY_DSA,
		    _PATH_HOST_DSA_KEY_FILE, "", NULL);
#ifdef OPENSSL_HAS_ECC
		sensitive_data.keys[2] = key_load_private_cert(KEY_ECDSA,
		    _PATH_HOST_ECDSA_KEY_FILE, "", NULL);
#endif
		sensitive_data.keys[3] = key_load_private_cert(KEY_RSA,
		    _PATH_HOST_RSA_KEY_FILE, "", NULL);
		sensitive_data.keys[4] = key_load_private_type(KEY_DSA,
		    _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
#ifdef OPENSSL_HAS_ECC
		sensitive_data.keys[5] = key_load_private_type(KEY_ECDSA,
		    _PATH_HOST_ECDSA_KEY_FILE, "", NULL, NULL);
#endif
		sensitive_data.keys[6] = key_load_private_type(KEY_RSA,
		    _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
		PRIV_END;

		if (options.hostbased_authentication == 1 &&
		    sensitive_data.keys[0] == NULL &&
		    sensitive_data.keys[4] == NULL &&
		    sensitive_data.keys[5] == NULL &&
		    sensitive_data.keys[6] == NULL) {
			sensitive_data.keys[1] = key_load_cert(
			    _PATH_HOST_DSA_KEY_FILE);
#ifdef OPENSSL_HAS_ECC
			sensitive_data.keys[2] = key_load_cert(
			    _PATH_HOST_ECDSA_KEY_FILE);
#endif
			sensitive_data.keys[3] = key_load_cert(
			    _PATH_HOST_RSA_KEY_FILE);
			sensitive_data.keys[4] = key_load_public(
			    _PATH_HOST_DSA_KEY_FILE, NULL);
#ifdef OPENSSL_HAS_ECC
			sensitive_data.keys[5] = key_load_public(
			    _PATH_HOST_ECDSA_KEY_FILE, NULL);
#endif
			sensitive_data.keys[6] = key_load_public(
			    _PATH_HOST_RSA_KEY_FILE, NULL);
			sensitive_data.external_keysign = 1;
		}
	}
	/*
	 * Get rid of any extra privileges that we may have.  We will no
	 * longer need them.  Also, extra privileges could make it very hard
	 * to read identity files and other non-world-readable files from the
	 * user's home directory if it happens to be on a NFS volume where
	 * root is mapped to nobody.
	 */
	if (original_effective_uid == 0) {
		PRIV_START;
		permanently_set_uid(pw);
	}

	/*
	 * Now that we are back to our own permissions, create ~/.ssh
	 * directory if it doesn't already exist.
	 */
	if (config == NULL) {
		r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir,
		    strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
		if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0) {
#ifdef WITH_SELINUX
			ssh_selinux_setfscreatecon(buf);
#endif
			if (mkdir(buf, 0700) < 0)
				error("Could not create directory '%.200s'.",
				    buf);
#ifdef WITH_SELINUX
			ssh_selinux_setfscreatecon(NULL);
#endif
		}
	}
	/* load options.identity_files */
	load_public_identity_files();

	/* Expand ~ in known host file names. */
	tilde_expand_paths(options.system_hostfiles,
	    options.num_system_hostfiles);
	tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);

	signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
	signal(SIGCHLD, main_sigchld_handler);

	/* Log into the remote system.  Never returns if the login fails. */
	ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
	    options.port, pw, timeout_ms);

	if (packet_connection_is_on_socket()) {
		verbose("Authenticated to %s ([%s]:%d).", host,
		    get_remote_ipaddr(), get_remote_port());
	} else {
		verbose("Authenticated to %s (via proxy).", host);
	}

	/* We no longer need the private host keys.  Clear them now. */
	if (sensitive_data.nkeys != 0) {
		for (i = 0; i < sensitive_data.nkeys; i++) {
			if (sensitive_data.keys[i] != NULL) {
				/* Destroys contents safely */
				debug3("clear hostkey %d", i);
				key_free(sensitive_data.keys[i]);
				sensitive_data.keys[i] = NULL;
			}
		}
		xfree(sensitive_data.keys);
	}
	for (i = 0; i < options.num_identity_files; i++) {
		if (options.identity_files[i]) {
			xfree(options.identity_files[i]);
			options.identity_files[i] = NULL;
		}
		if (options.identity_keys[i]) {
			key_free(options.identity_keys[i]);
			options.identity_keys[i] = NULL;
		}
	}

	exit_status = compat20 ? ssh_session2() : ssh_session();
	packet_close();

	if (options.control_path != NULL && muxserver_sock != -1)
		unlink(options.control_path);

	/* Kill ProxyCommand if it is running. */
	ssh_kill_proxy_command();

	return exit_status;
}
Пример #27
0
/// Launch the mangos server
extern int main(int argc, char** argv)
{
    ///- Command line parsing
    char const* cfg_file = _MANGOSD_CONFIG;


    char const* options = ":a:c:s:";

    ACE_Get_Opt cmd_opts(argc, argv, options);
    cmd_opts.long_option("version", 'v', ACE_Get_Opt::NO_ARG);
    cmd_opts.long_option("ahbot", 'a', ACE_Get_Opt::ARG_REQUIRED);

    char serviceDaemonMode = '\0';

    int option;
    while ((option = cmd_opts()) != EOF)
    {
        switch (option)
        {
            case 'a':
                sAuctionBotConfig.SetConfigFileName(cmd_opts.opt_arg());
                break;
            case 'c':
                cfg_file = cmd_opts.opt_arg();
                break;
            case 'v':
                printf("%s\n", _FULLVERSION(REVISION_DATE, REVISION_TIME, REVISION_NR, REVISION_ID));
                return 0;
            case 's':
            {
                const char* mode = cmd_opts.opt_arg();

                if (!strcmp(mode, "run"))
                    serviceDaemonMode = 'r';
#ifdef WIN32
                else if (!strcmp(mode, "install"))
                    serviceDaemonMode = 'i';
                else if (!strcmp(mode, "uninstall"))
                    serviceDaemonMode = 'u';
#else
                else if (!strcmp(mode, "stop"))
                    serviceDaemonMode = 's';
#endif
                else
                {
                    sLog.outError("Runtime-Error: -%c unsupported argument %s", cmd_opts.opt_opt(), mode);
                    usage(argv[0]);
                    Log::WaitBeforeContinueIfNeed();
                    return 1;
                }
                break;
            }
            case ':':
                sLog.outError("Runtime-Error: -%c option requires an input argument", cmd_opts.opt_opt());
                usage(argv[0]);
                Log::WaitBeforeContinueIfNeed();
                return 1;
            default:
                sLog.outError("Runtime-Error: bad format of commandline arguments");
                usage(argv[0]);
                Log::WaitBeforeContinueIfNeed();
                return 1;
        }
    }

#ifdef WIN32                                                // windows service command need execute before config read
    switch (serviceDaemonMode)
    {
        case 'i':
            if (WinServiceInstall())
                sLog.outString("Installing service");
            return 1;
        case 'u':
            if (WinServiceUninstall())
                sLog.outString("Uninstalling service");
            return 1;
        case 'r':
            WinServiceRun();
            break;
    }
#endif

    if (!sConfig.SetSource(cfg_file))
    {
        sLog.outError("Could not find configuration file %s.", cfg_file);
        Log::WaitBeforeContinueIfNeed();
        return 1;
    }

#ifndef WIN32                                               // posix daemon commands need apply after config read
    switch (serviceDaemonMode)
    {
        case 'r':
            startDaemon();
            break;
        case 's':
            stopDaemon();
            break;
    }
#endif

    sLog.outString("%s [world-daemon]", _FULLVERSION(REVISION_DATE, REVISION_TIME, REVISION_NR, REVISION_ID));
    sLog.outString("<Ctrl-C> to stop.");
    sLog.outString("\n\n"
                   "MM   MM         MM   MM  MMMMM   MMMM   MMMMM\n"
                   "MM   MM         MM   MM MMM MMM MM  MM MMM MMM\n"
                   "MMM MMM         MMM  MM MMM MMM MM  MM MMM\n"
                   "MM M MM         MMMM MM MMM     MM  MM  MMM\n"
                   "MM M MM  MMMMM  MM MMMM MMM     MM  MM   MMM\n"
                   "MM M MM M   MMM MM  MMM MMMMMMM MM  MM    MMM\n"
                   "MM   MM     MMM MM   MM MM  MMM MM  MM     MMM\n"
                   "MM   MM MMMMMMM MM   MM MMM MMM MM  MM MMM MMM\n"
                   "MM   MM MM  MMM MM   MM  MMMMMM  MMMM   MMMMM\n"
                   "        MM  MMM http://getmangos.com\n"
                   "        MMMMMM\n\n");
    sLog.outString("Using configuration file %s.", cfg_file);

    DETAIL_LOG("%s (Library: %s)", OPENSSL_VERSION_TEXT, SSLeay_version(SSLEAY_VERSION));
    if (SSLeay() < 0x009080bfL)
    {
        DETAIL_LOG("WARNING: Outdated version of OpenSSL lib. Logins to server may not work!");
        DETAIL_LOG("WARNING: Minimal required version [OpenSSL 0.9.8k]");
    }

    DETAIL_LOG("Using ACE: %s", ACE_VERSION);

    ///- Set progress bars show mode
    BarGoLink::SetOutputState(sConfig.GetBoolDefault("ShowProgressBars", true));

    ///- and run the 'Master'
    /// \todo Why do we need this 'Master'? Can't all of this be in the Main as for Realmd?
    return sMaster.Run();

    // at sMaster return function exist with codes
    // 0 - normal shutdown
    // 1 - shutdown at error
    // 2 - restart command used, this code can be used by restarter for restart mangosd
}
Пример #28
0
int ngx_cdecl
main(int argc, char *const *argv)
{
    ngx_buf_t        *b;
    ngx_log_t        *log;
    ngx_uint_t        i;
    ngx_cycle_t      *cycle, init_cycle;
    ngx_conf_dump_t  *cd;
    ngx_core_conf_t  *ccf;

    ngx_debug_init();

    if (ngx_strerror_init() != NGX_OK) {
        return 1;
    }

    if (ngx_get_options(argc, argv) != NGX_OK) {
        return 1;
    }

    if (ngx_show_version) {
        ngx_write_stderr("nginx version: " NGINX_VER_BUILD NGX_LINEFEED);

        if (ngx_show_help) {
            ngx_write_stderr(
                "Usage: nginx [-?hvVtTq] [-s signal] [-c filename] "
                             "[-p prefix] [-g directives]" NGX_LINEFEED
                             NGX_LINEFEED
                "Options:" NGX_LINEFEED
                "  -?,-h         : this help" NGX_LINEFEED
                "  -v            : show version and exit" NGX_LINEFEED
                "  -V            : show version and configure options then exit"
                                   NGX_LINEFEED
                "  -t            : test configuration and exit" NGX_LINEFEED
                "  -T            : test configuration, dump it and exit"
                                   NGX_LINEFEED
                "  -q            : suppress non-error messages "
                                   "during configuration testing" NGX_LINEFEED
                "  -s signal     : send signal to a master process: "
                                   "stop, quit, reopen, reload" NGX_LINEFEED
#ifdef NGX_PREFIX
                "  -p prefix     : set prefix path (default: "
                                   NGX_PREFIX ")" NGX_LINEFEED
#else
                "  -p prefix     : set prefix path (default: NONE)" NGX_LINEFEED
#endif
                "  -c filename   : set configuration file (default: "
                                   NGX_CONF_PATH ")" NGX_LINEFEED
                "  -g directives : set global directives out of configuration "
                                   "file" NGX_LINEFEED NGX_LINEFEED
                );
        }

        if (ngx_show_configure) {

#ifdef NGX_COMPILER
            ngx_write_stderr("built by " NGX_COMPILER NGX_LINEFEED);
#endif

#if (NGX_SSL)
            if (SSLeay() == SSLEAY_VERSION_NUMBER) {
                ngx_write_stderr("built with " OPENSSL_VERSION_TEXT
                                 NGX_LINEFEED);
            } else {
                ngx_write_stderr("built with " OPENSSL_VERSION_TEXT
                                 " (running with ");
                ngx_write_stderr((char *) (uintptr_t)
                                 SSLeay_version(SSLEAY_VERSION));
                ngx_write_stderr(")" NGX_LINEFEED);
            }
#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
            ngx_write_stderr("TLS SNI support enabled" NGX_LINEFEED);
#else
            ngx_write_stderr("TLS SNI support disabled" NGX_LINEFEED);
#endif
#endif

            ngx_write_stderr("configure arguments:" NGX_CONFIGURE NGX_LINEFEED);
        }

        if (!ngx_test_config) {
            return 0;
        }
    }

    /* TODO */ ngx_max_sockets = -1;

    ngx_time_init();

#if (NGX_PCRE)
    ngx_regex_init();
#endif

    ngx_pid = ngx_getpid();

    log = ngx_log_init(ngx_prefix);
    if (log == NULL) {
        return 1;
    }

    /* STUB */
#if (NGX_OPENSSL)
    ngx_ssl_init(log);
#endif

    /*
     * init_cycle->log is required for signal handlers and
     * ngx_process_options()
     */

    ngx_memzero(&init_cycle, sizeof(ngx_cycle_t));
    init_cycle.log = log;
    ngx_cycle = &init_cycle;

    init_cycle.pool = ngx_create_pool(1024, log);
    if (init_cycle.pool == NULL) {
        return 1;
    }

    if (ngx_save_argv(&init_cycle, argc, argv) != NGX_OK) {
        return 1;
    }

    if (ngx_process_options(&init_cycle) != NGX_OK) {
        return 1;
    }

    if (ngx_os_init(log) != NGX_OK) {
        return 1;
    }

    /*
     * ngx_crc32_table_init() requires ngx_cacheline_size set in ngx_os_init()
     */

    if (ngx_crc32_table_init() != NGX_OK) {
        return 1;
    }

    if (ngx_add_inherited_sockets(&init_cycle) != NGX_OK) {
        return 1;
    }

    ngx_max_module = 0;
    for (i = 0; ngx_modules[i]; i++) {
        ngx_modules[i]->index = ngx_max_module++;
    }

    cycle = ngx_init_cycle(&init_cycle);
    if (cycle == NULL) {
        if (ngx_test_config) {
            ngx_log_stderr(0, "configuration file %s test failed",
                           init_cycle.conf_file.data);
        }

        return 1;
    }

    if (ngx_test_config) {
        if (!ngx_quiet_mode) {
            ngx_log_stderr(0, "configuration file %s test is successful",
                           cycle->conf_file.data);
        }

        if (ngx_dump_config) {
            cd = cycle->config_dump.elts;

            for (i = 0; i < cycle->config_dump.nelts; i++) {

                ngx_write_stdout("# configuration file ");
                (void) ngx_write_fd(ngx_stdout, cd[i].name.data,
                                    cd[i].name.len);
                ngx_write_stdout(":" NGX_LINEFEED);

                b = cd[i].buffer;

                (void) ngx_write_fd(ngx_stdout, b->pos, b->last - b->pos);
                ngx_write_stdout(NGX_LINEFEED);
            }
        }

        return 0;
    }

    if (ngx_signal) {
        return ngx_signal_process(cycle, ngx_signal);
    }

    ngx_os_status(cycle->log);

    ngx_cycle = cycle;

    zlog_init_conf_path();
    if (zlog_load_conf(zlog_init))
    {
        return 1;
    }

    ccf = (ngx_core_conf_t *) ngx_get_conf(cycle->conf_ctx, ngx_core_module);

    if (ccf->master && ngx_process == NGX_PROCESS_SINGLE) {
        ngx_process = NGX_PROCESS_MASTER;
    }

#if !(NGX_WIN32)

    if (ngx_init_signals(cycle->log) != NGX_OK) {
        return 1;
    }

    if (!ngx_inherited && ccf->daemon) {
        if (ngx_daemon(cycle->log) != NGX_OK) {
            return 1;
        }

        ngx_daemonized = 1;
    }

    if (ngx_inherited) {
        ngx_daemonized = 1;
    }

#endif

    if (ngx_create_pidfile(&ccf->pid, cycle->log) != NGX_OK) {
        return 1;
    }

    if (ngx_log_redirect_stderr(cycle) != NGX_OK) {
        return 1;
    }

    if (log->file->fd != ngx_stderr) {
        if (ngx_close_file(log->file->fd) == NGX_FILE_ERROR) {
            ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                          ngx_close_file_n " built-in log failed");
        }
    }

    ngx_use_stderr = 0;

    struct sigaction act;
    memset(&act, 0, sizeof(struct sigaction));
	sigemptyset(&act.sa_mask);
	act.sa_sigaction = sig_user1_handler;
	act.sa_flags = SA_SIGINFO;
	if(-1 == sigaction(SIGUSR1, &act, NULL)) {
		return 1;
	}

    if (ngx_process == NGX_PROCESS_SINGLE) {
        ngx_single_process_cycle(cycle);

    } else {
        if (NGX_OK != ngx_before_master_cycle(cycle))
        {
            return 1;
        }
        ngx_master_process_cycle(cycle);
    }

    return 0;
}
Пример #29
0
// Launch the auth server
extern int main(int argc, char **argv)
{
    sLog->SetLogDB(false);
    // Command line parsing to get the configuration file name
    char const* cfg_file = _AUTHSERVER_CONFIG;
    int c = 1;
    while (c < argc)
    {
        if (strcmp(argv[c], "-c") == 0)
        {
            if (++c >= argc)
            {
                sLog->outError("Runtime-Error: -c option requires an input argument");
                usage(argv[0]);
                return 1;
            }
            else
                cfg_file = argv[c];
        }
        ++c;
    }

    if (!ConfigMgr::Load(cfg_file))
    {
        sLog->outError("Invalid or missing configuration file : %s", cfg_file);
        sLog->outError("Verify that the file exists and has \'[authserver]\' written in the top of the file!");
        return 1;
    }
    sLog->Initialize();

    sLog->outString("%s (authserver)", _FULLVERSION);
    sLog->outString("<Ctrl-C> to stop.\n");
    sLog->outString("Using configuration file %s.", cfg_file);

    sLog->outString("   ______  __  __  __  __  ______ __  ______  ______ ");
    sLog->outString("  /\\  ___\\/\\ \\/ / /\\ \\_\\ \\/\\  ___/\\ \\/\\  == \\/\\  ___\\ ");
    sLog->outString("  \\ \\___  \\ \\  _'-\\ \\____ \\ \\  __\\ \\ \\ \\  __<\\ \\  __\\ ");
    sLog->outString("   \\/\\_____\\ \\_\\ \\_\\/\\_____\\ \\_\\  \\ \\_\\ \\_\\ \\_\\ \\_____\\ ");
    sLog->outString("    \\/_____/\\/_/\\/_/\\/_____/\\/_/   \\/_/\\/_/ /_/\\/_____/ ");
    sLog->outString("  Project SkyFireEmu 2012(c) Open-sourced Game Emulation ");
    sLog->outString("           <http://www.projectskyfire.org/> \n");

    sLog->outDetail("%s (Library: %s)", OPENSSL_VERSION_TEXT, SSLeay_version(SSLEAY_VERSION));

#if defined (ACE_HAS_EVENT_POLL) || defined (ACE_HAS_DEV_POLL)
    ACE_Reactor::instance(new ACE_Reactor(new ACE_Dev_Poll_Reactor(ACE::max_handles(), 1), 1), true);
#else
    ACE_Reactor::instance(new ACE_Reactor(new ACE_TP_Reactor(), true), true);
#endif

    sLog->outBasic("Max allowed open files is %d", ACE::max_handles());

    // authserver PID file creation
    std::string pidfile = ConfigMgr::GetStringDefault("PidFile", "");
    if (!pidfile.empty())
    {
        uint32 pid = CreatePIDFile(pidfile);
        if (!pid)
        {
            sLog->outError("Cannot create PID file %s.\n", pidfile.c_str());
            return 1;
        }

        sLog->outString("Daemon PID: %u\n", pid);
    }

    // Initialize the database connection
    if (!StartDB())
        return 1;

    // Initialize the log database
    sLog->SetLogDBLater(ConfigMgr::GetBoolDefault("EnableLogDB", false)); // set var to enable DB logging once startup finished.
    sLog->SetLogDB(false);
    sLog->SetRealmID(0);                                               // ensure we've set realm to 0 (authserver realmid)

    // Get the list of realms for the server
    sRealmList->Initialize(ConfigMgr::GetIntDefault("RealmsStateUpdateDelay", 20));
    if (sRealmList->size() == 0)
    {
        sLog->outError("No valid realms specified.");
        return 1;
    }

    // Launch the listening network socket
    RealmAcceptor acceptor;

    uint16 rmport = ConfigMgr::GetIntDefault("RealmServerPort", 3724);
    std::string bind_ip = ConfigMgr::GetStringDefault("BindIP", "0.0.0.0");

    ACE_INET_Addr bind_addr(rmport, bind_ip.c_str());

    if (acceptor.open(bind_addr, ACE_Reactor::instance(), ACE_NONBLOCK) == -1)
    {
        sLog->outError("Auth server can not bind to %s:%d", bind_ip.c_str(), rmport);
        return 1;
    }

    // Initialize the signal handlers
    AuthServerSignalHandler SignalINT, SignalTERM;

    // Register authservers's signal handlers
    ACE_Sig_Handler Handler;
    Handler.register_handler(SIGINT, &SignalINT);
    Handler.register_handler(SIGTERM, &SignalTERM);

    ///- Handle affinity for multiple processors and process priority on Windows
#ifdef _WIN32
    {
        HANDLE hProcess = GetCurrentProcess();

        uint32 Aff = ConfigMgr::GetIntDefault("UseProcessors", 0);
        if (Aff > 0)
        {
            ULONG_PTR appAff;
            ULONG_PTR sysAff;

            if (GetProcessAffinityMask(hProcess, &appAff, &sysAff))
            {
                ULONG_PTR curAff = Aff & appAff;            // remove non accessible processors

                if (!curAff)
                    sLog->outError("Processors marked in UseProcessors bitmask (hex) %x not accessible for authserver. Accessible processors bitmask (hex): %x", Aff, appAff);
                else if (SetProcessAffinityMask(hProcess, curAff))
                    sLog->outString("Using processors (bitmask, hex): %x", curAff);
                else
                    sLog->outError("Can't set used processors (hex): %x", curAff);
            }
            sLog->outString();
        }

        bool Prio = ConfigMgr::GetBoolDefault("ProcessPriority", false);

        if (Prio)
        {
            if (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS))
                sLog->outString("The auth server process priority class has been set to HIGH");
            else
                sLog->outError("Can't set auth server process priority class.");
            sLog->outString();
        }
    }
#endif

    // maximum counter for next ping
    uint32 numLoops = (ConfigMgr::GetIntDefault("MaxPingTime", 30) * (MINUTE * 1000000 / 100000));
    uint32 loopCounter = 0;

    // possibly enable db logging; avoid massive startup spam by doing it here.
    if (sLog->GetLogDBLater())
    {
        sLog->outString("Enabling database logging...");
        sLog->SetLogDBLater(false);
        // login db needs thread for logging
        sLog->SetLogDB(true);
    }
    else
        sLog->SetLogDB(false);

    // Wait for termination signal
    while (!stopEvent)
    {
        // dont move this outside the loop, the reactor will modify it
        ACE_Time_Value interval(0, 100000);

        if (ACE_Reactor::instance()->run_reactor_event_loop(interval) == -1)
            break;

        if ((++loopCounter) == numLoops)
        {
            loopCounter = 0;
            sLog->outDetail("Ping MySQL to keep connection alive");
            LoginDatabase.KeepAlive();
        }
    }

    // Close the Database Pool and library
    StopDB();

    sLog->outString("Halting process...");
    return 0;
}
Пример #30
0
/** Print the current linked version of Openssl
 *
 * Print the currently linked version of the OpenSSL library.
 */
char const *ssl_version(void)
{
	return SSLeay_version(SSLEAY_VERSION);
}