Exemple #1
0
SocketHandler *MythSocketManager::GetConnectionBySocket(MythSocket *sock)
{
    QReadLocker rlock(&m_socketLock);
    if (!m_socketMap.contains(sock))
        return NULL;

    SocketHandler *handler = m_socketMap[sock];
    handler->UpRef();
    return handler;
}
Exemple #2
0
std::string get_http(const char *host, int port, const char *request)
{
	SocketHandler h;
	GetHttp sock(h, request);
	sock.Open( host, port );
	h.Add(&sock);
	while (h.GetCount()) {
		h.Select(1, 0);
	}
	return sock.Response();
}
void server(int & sockfd) {
  struct sockaddr_in remote_addr;
  socklen_t sin_size = sizeof (struct sockaddr_in);

  int client_fd = accept(sockfd, (struct sockaddr *) &remote_addr, &sin_size);

  cout << "Received a connection from " << inet_ntoa(remote_addr.sin_addr) << ":" << intToString(remote_addr.sin_port) << endl;
  SocketHandler * socket = new SocketHandler(client_fd);
  socket->receiveFile("tests/test-recv.bott");
  delete socket;
}
void client() {
  int sockfd = socket(AF_INET, SOCK_STREAM, 0);
  struct sockaddr_in server;
  bzero(&server, sizeof (server));
  server.sin_family = AF_INET;
  server.sin_port = htons(6636);
  server.sin_addr.s_addr = inet_addr("127.0.0.1");
  connect(sockfd, (struct sockaddr *) & server, sizeof (server));

  SocketHandler * socket = new SocketHandler(sockfd);
  socket->sendFile("tests/test.bott");
  delete socket;
}
	// ----------------------------------------
	void BindedHandler::pollRead() {
		static socklen_t len = sizeof(struct sockaddr_in);
		sockaddr_in address;

		// Check limit
		if (sockets.size() >= maxConn) {
			Common::Logger::critical("Too many connections on Port %d", port);
			acceptConnections(0);
			return;
		}

		// Try to accept connection
		int clientFd = ::accept(socketFd, (sockaddr *) &address, &len);
		char buf[30];
		Tools::IP::sprintfAddress(buf, address);
		Common::Logger::debug("New connection from %s", buf);

		// Error?
		if (clientFd == -1) {
			if (errno == EAGAIN) {
				return;
			}
			else if (errno == EMFILE) {
				perror("Error on accept");
				acceptConnections(0);
				return;
			}
			else {
				perror("Error on accept");
				return;
			}
		}

		SocketHandler* userData = newSocketHandler(address);

		// Non allowed address?
		if (userData == NULL) {
			Common::Logger::critical("Paff! %s", buf);
			close(clientFd);
			return;
		}

		// Add to epoll
		userData->socketFd = clientFd;
		((BufferedSocketHandler*) userData)->parentHandler = this;
		userData->socketAddress = address.sin_addr.s_addr;
		Tools::IP::sprintfAddress(userData->socketAddressStr, address);
		sockets.push_front(userData);
		userData->registerEvents(10);
	}
Exemple #6
0
int main(int argc, char *argv[])
{
	SocketHandler h;
	ListenSocket<IOSocket> l(h);
	l.Bind(12344);
	h.Add(&l);
	IOSocket sock(h);
	sock.Open("192.168.7.4", 12344);
	h.Add(&sock);
	while (!quit)
	{
		h.Select(1, 0);
	}
}
bool OutboundRequestHandler::DoConnectToMaster(void)
{
    if (m_socket)
        m_socket->DecrRef();

    m_socket = new MythSocket(-1, m_parent);

    QString server   = gCoreContext->GetMasterServerIP();
    QString hostname = gCoreContext->GetMasterHostName();
    int port         = gCoreContext->GetMasterServerPort();

    if (!m_socket->ConnectToHost(server, port))
    {
        LOG(VB_GENERAL, LOG_ERR, "Failed to connect to master backend.");
        m_socket->DecrRef();
        m_socket = NULL;
        return false;
    }

#ifndef IGNORE_PROTO_VER_MISMATCH
    if (!m_socket->Validate())
    {
        LOG(VB_GENERAL, LOG_NOTICE, "Unable to confirm protocol version with backend.");
        m_socket->DecrRef();
        m_socket = NULL;
        return false;
    }
#endif

    if (!AnnounceSocket())
    {
        LOG(VB_GENERAL, LOG_NOTICE, "Announcement to upstream master backend failed.");
        m_socket->DecrRef();
        m_socket = NULL;
        return false;
    }

    SocketHandler *handler = new SocketHandler(m_socket, m_parent, hostname);
    handler->BlockShutdown(true);
    handler->AllowStandardEvents(true);
    handler->AllowSystemEvents(true);
    m_parent->AddSocketHandler(handler); // register socket for reception of events
    handler->DecrRef(); // drop local instance in counter
    handler = NULL;

    LOG(VB_GENERAL, LOG_NOTICE, "Connected to master backend.");

    return true;
}
Exemple #8
0
int main()
{
	SocketHandler h;
	ListenSocket<ServerSocket> l(h);
	if (l.Bind(40001,10))
	{
		exit(-1);
	}
	h.Add(&l);
	h.Select(1,0);
	while (h.GetCount())
	{
		h.Select(1,0);
	}
}
int main2()
{
	SocketHandler h;
	ListenSocket<ServerSocket> ll(h);
	if (ll.Bind(443))
	{
		return -1;
	}
	h.Add(&ll);
	h.Select(1,0);
	while (h.GetCount())
	{
		h.Select(1,0);
	}
}
Exemple #10
0
int main(int argc,char *argv[])
{
	if (argc > 1)
	{
		SocketHandler h;
		ClientSocket cc(h,argv[1]);
		cc.Open("127.0.0.1",40001);
		// Add after Open
		h.Add(&cc);
		h.Select(1,0);
		while (h.GetCount())
		{
			h.Select(1,0);
		}
	}
}
Exemple #11
0
void Socket::SocketThread::Run()
{
	SocketHandler h;
	h.SetSlave();
	h.Add(m_socket);
	m_socket -> SetSlaveHandler(&h);
	m_socket -> OnDetached();
	while (h.GetCount() && IsRunning())
	{
		h.Select(0, 500000);
	}
	// m_socket now deleted oops
	// yeah oops m_socket delete its socket thread, that means this
	// so Socket will no longer delete its socket thread, instead we do this:
	SetDeleteOnExit();
}
Exemple #12
0
int main(int argc, char *argv[])
{
	std::string host = argc > 1 ? argv[1] : "www.alhem.net";
	int port = argc > 2 ? atoi(argv[2]) : 80;
	SocketHandler h;
	for (int i = 1; i < 255; i++)
	{
		char host[40];
		sprintf(host, "10.170.23.%d", i);
		tSocket *p = new tSocket(h, host, 23);
		h.Add(p);
	}
	while (h.GetCount())
	{
		h.Select(1, 0);
	}
}
Exemple #13
0
    void run ()
    {
        SocketHandler h;

        // Launch the RA listener socket
        ListenSocket<RASocket> RAListenSocket (h);
        bool usera = sConfig.GetBoolDefault ("Ra.Enable", false);

        if (usera)
        {
            port_t raport = sConfig.GetIntDefault ("Ra.Port", 3443);
            std::string stringip = sConfig.GetStringDefault ("Ra.IP", "0.0.0.0");
            ipaddr_t raip;
            if (!Utility::u2ip (stringip, raip))
                sLog.outError ("MaNGOS RA can not bind to ip %s", stringip.c_str ());
            else if (RAListenSocket.Bind (raip, raport))
                sLog.outError ("MaNGOS RA can not bind to port %d on %s", raport, stringip.c_str ());
            else
            {
                h.Add (&RAListenSocket);

                sLog.outString ("Starting Remote access listner on port %d on %s", raport, stringip.c_str ());
            }
        }

        // Socket Selet time is in microseconds , not miliseconds!!
        uint32 socketSelecttime = sWorld.getConfig (CONFIG_SOCKET_SELECTTIME);

        // if use ra spend time waiting for io, if not use ra ,just sleep
        if (usera)
        {
            while (!World::IsStopped())
            {
                h.Select (0, socketSelecttime);
                checkping ();
            }
        }
        else
        {
            while (!World::IsStopped())
            {
                ACE_Based::Thread::Sleep(static_cast<unsigned long> (socketSelecttime / 1000));
                checkping ();
            }
        }
    }
Exemple #14
0
int main(int argc, char *argv[])
{
    try
    {
        SocketHandler h;
        if (argc > 1 && !strcmp(argv[1], "-server"))
        {
            ListenSocket<tSocket> l(h);
            l.Bind(4443);
            h.Add(&l);
            while (h.GetCount())
            {
                h.Select(1, 0);
            }
        }
        else
        {
            std::string host = argc > 1 ? argv[1] : "www.alhem.net";
            tSocket sock(h, host);
            h.Add(&sock);
            while (h.GetCount())
            {
                h.Select(1, 0);
            }
        }
    }
    catch (const Exception& e)
    {
        printf("%s\n", e.ToString().c_str());
    }
}
Exemple #15
0
void ResolvServer::Run()
{
//  StdoutLog log;
    SocketHandler h;
    ListenSocket<ResolvSocket> l(h);

    if (l.Bind("127.0.0.1", m_port))
    {
        return;
    }
    h.Add(&l);

    m_ready = true;
    while (!m_quit && IsRunning() )
    {
        h.Select(0, 500000);
    }
    SetRunning(false);
}
void MythSocketManager::connectionClosed(MythSocket *sock)
{
    {
        QReadLocker rlock(&m_handlerLock);

        QMap<QString, SocketRequestHandler*>::const_iterator i;
        for (i = m_handlerMap.constBegin(); i != m_handlerMap.constEnd(); ++i)
            (*i)->connectionClosed(sock); 
    }

    {
        QWriteLocker wlock(&m_socketLock);
        if (m_socketMap.contains(sock))
        {
            SocketHandler *handler = m_socketMap.take(sock);
            handler->DownRef();
        }
    }
}
int main()
{
	SocketHandler h;
	ListenSocket<DisplaySocket> l(h);
	StdoutLog log;

	h.RegStdLog(&log);

	if (l.Bind(9001))
	{
		exit(-1);
	}
	h.Add(&l);
	h.Select(1,0);
	while (!quit)
	{
		h.Select(1,0);
	}
}
int main(int argc,char *argv[])
{
	if (argc != 3)
	{
		fprintf(stderr, "Usage: %s <-hostname> <-port>\n", *argv);
		exit(-1);
	}
	SocketHandler h;
	MyClient sock(h);
	port_t port = atoi(argv[2]);
	if (port == 2222)
	{
		sock.EnableSSL();
	}
	sock.Open(argv[1], port);
	h.Add(&sock);
	while (h.GetCount())
	{
		h.Select();
	}
}
static void WINAPI Load() {

	string cmdline = GetCommandLineA();
	string ip;
	int port = NULL;
	std::vector<std::string> a;

	Log *log = new Log("log.txt");

	a = split(cmdline, ' ');

	log->Write((char*)cmdline.c_str());
	for (vector<string>::iterator i = a.begin(); i != a.end(); i++) {
		if (!i->compare("-h"))
		{
			advance(i, 1);
			ip = (*i);

		}
		else if (!i->compare("-p"))
		{
			advance(i, 1);
			port = atoi((*i).c_str());
		}
	}
	log->Write("before try");
	log->Write((char*)ip.c_str());
	try {
		SocketHandler s = SocketHandler(ip, 7667);
		log->Write("just connected");

		//s.AddDataFile("HANDLING");
		s.AddDataFile("WEAPON");
		s.AddDataFile("surfinfo");
		s.AddDataFile("melee");
		s.AddDataFile("ANIMGRP");
		
		disableSampAC();

		while(true) {
			s.WaitForServerResponse();
		}
	} catch (SocketException e) { 
		log->Write((char*)e.what());
		return;
	}
	//log->Write(buf);

	delete log;
	
}
int main(int argc,char *argv[])
{
	SocketHandler h;

	// enable socks4 client
#ifdef ENABLE_SOCKS4
	h.SetSocks4Host("somehost.com");
	h.SetSocks4Port(1080);
	h.SetSocks4Userid("myname.net");
	h.SetSocks4TryDirect(false);
#endif

	for (int i = 1; i < argc; i++)
	{
		Get(h,argv[i]);
	}
	h.Select(1,0);
	while (h.GetCount())
	{
		h.Select(1,0);
	}
}
Exemple #21
0
int main()
{
	SocketHandler h;
	StdoutLog log;
	h.RegStdLog(&log);
	ListenSocket<ServerSocket> l(h);

	l.SetIpv6();
	if (l.Bind(40001,10))
	{
		exit(-1);
	}
	h.Add(&l);
	h.Select(1,0);
	while (h.GetCount())
	{
		h.Select(1,0);
	}
}
Exemple #22
0
bool BaseRequestHandler::HandleAnnounce(MythSocket *socket,
                                QStringList &commands, QStringList &slist)
{
    if (commands.size() != 4)
        return false;

    bool blockShutdown;
    if (commands[1] == "Playback")
        blockShutdown = true;
    else if (commands[1] == "Monitor")
        blockShutdown = false;
    else
        return false;

    QString hostname = commands[2];

    int eventlevel = commands[3].toInt();
    bool systemevents = ( (eventlevel == 1) || (eventlevel == 3));
    bool normalevents = ( (eventlevel == 1) || (eventlevel == 2));

    SocketHandler *handler = new SocketHandler(socket, m_parent, hostname);
    socket->setAnnounce(slist);

    handler->BlockShutdown(blockShutdown);
    handler->AllowStandardEvents(normalevents);
    handler->AllowSystemEvents(systemevents);

    m_parent->AddSocketHandler(handler);

    QStringList sl; sl << "OK";
    handler->SendStringList(sl);
    handler->DownRef();
    handler = NULL;

    LOG(VB_GENERAL, LOG_DEBUG, QString("MainServer::ANN %1")
                                    .arg(commands[1]));
    LOG(VB_GENERAL, LOG_NOTICE, QString("adding: %1 as a client (events: %2)")
                               .arg(commands[2]).arg(eventlevel));
    SendMythSystemEvent(QString("CLIENT_CONNECTED HOSTNAME %1")
                                    .arg(commands[2]));

    return true;
}
int main(int argc, char** argv)
{
    CmdLineParser clp;
    loadCmdLine(clp);

    ConfigInput input;
    if(!parseCommandLine(argc, argv, clp, input))
    {
        return 1;
    }

    setupSignalHandling();

    //
    // Create and Initialize the SocketHandler and MessageHandler
    //
    SocketHandler *server = new TcpSocketHandlerImpl(input.listenPort, input.ipAddress);
    MessageHandler *msgHandler = new EchoServerTcpMessageHandler();
    msgHandler->setDebug(input.isVerbose);
    server->setMessageHandler(msgHandler);
    server->setHandlerMode(SocketHandler::MODE_SERVER);
    server->setDebug(input.isVerbose);

    if(!server->initialize())
    {
        cerr << "Error Initializing the SocketServer, exiting";
        return 1;
    }
    SOCKET_SERVER = server;

    //
    // Run the Echo Server
    // It will be stopped by a SIGINT (CTRL-C) signal
    //
    server->run(); // This call blocks
    cout << "Server stopped" << endl;

    delete server;
    delete msgHandler;

    return 0;
}
Exemple #24
0
int main(int argc,char *argv[])
{
	if (argc < 2)
	{
		printf("Usage: %s <command>\n",*argv);
		return -1;
	}
	SocketHandler h;
	StdoutLog log;
	h.RegStdLog(&log);
	ClientSocket cc(h,argv[1]);

	cc.SetIpv6();
	cc.Open("localhost",40001);
	// Add after Open
	h.Add(&cc);
	h.Select(1,0);
	while (h.GetCount())
	{
		h.Select(1,0);
	}
}
Exemple #25
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];
        }

        #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("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.outString( "MaNGOS realm daemon %s", _FULLVERSION );
    sLog.outString( "<Ctrl-C> to stop.\n" );

    /// 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 );
    }

    ///- Initialise the database connection
    std::string dbstring;
    if(!StartDB(dbstring))
        return 1;

    ///- 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( "MaNGOS realmd 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("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 dbRealmServer.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
    dbRealmServer.HaltDelayThread();

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

    sLog.outString( "Halting process..." );
    return 0;
}
Exemple #26
0
bool FileServerHandler::HandleGetFileList(SocketHandler *socket,
                                          QStringList &slist)
{
    QStringList res;

    bool fileNamesOnly = false;
    if (slist.size() == 5)
        fileNamesOnly = slist[4].toInt();
    else if (slist.size() != 4)
    {
        LOG(VB_GENERAL, LOG_ERR, QString("Invalid Request. %1")
                                     .arg(slist.join("[]:[]")));
        res << "EMPTY LIST";
        socket->SendStringList(res);
        return true;
    }

    QString host = gCoreContext->GetHostName();
    QString wantHost = slist[1];
    QString groupname = slist[2];
    QString path = slist[3];

    LOG(VB_FILE, LOG_INFO,
        QString("HandleSGGetFileList: group = %1  host = %2  "
                "path = %3 wanthost = %4")
            .arg(groupname).arg(host).arg(path).arg(wantHost));

    if ((host.toLower() == wantHost.toLower()) ||
        gCoreContext->IsThisHost(wantHost))
    {
        StorageGroup sg(groupname, host);
        LOG(VB_FILE, LOG_INFO, "Getting local info");
        if (fileNamesOnly)
            res = sg.GetFileList(path);
        else
            res = sg.GetFileInfoList(path);

        if (res.count() == 0)
            res << "EMPTY LIST";
    }
    else
    {
        // handle request on remote server
        SocketHandler *remsock = NULL;
        {
            QReadLocker rlock(&m_fsLock);
            if (m_fsMap.contains(wantHost))
            {
                remsock = m_fsMap[wantHost];
                remsock->IncrRef();
            }
        }

        if (remsock)
        {
            LOG(VB_FILE, LOG_INFO, "Getting remote info");
            res << "QUERY_SG_GETFILELIST" << wantHost << groupname << path
                << QString::number(fileNamesOnly);
            remsock->SendReceiveStringList(res);
            remsock->DecrRef();
        }
        else
        {
            LOG(VB_FILE, LOG_ERR, QString("Failed to grab slave socket : %1 :")
                     .arg(wantHost));
            res << "SLAVE UNREACHABLE: " << wantHost;
        }
    }

    socket->SendStringList(res);
    return true;
}
Exemple #27
0
bool FileServerHandler::HandleAnnounce(MythSocket *socket,
                  QStringList &commands, QStringList &slist)
{
    if (commands[1] == "FileServer")
    {
        if (slist.size() >= 3)
        {
            SocketHandler *handler =
                new SocketHandler(socket, m_parent, commands[2]);

            handler->BlockShutdown(true);
            handler->AllowStandardEvents(true);
            handler->AllowSystemEvents(true);

            QWriteLocker wlock(&m_fsLock);
            m_fsMap.insert(commands[2], handler);
            m_parent->AddSocketHandler(handler);

            slist.clear();
            slist << "OK";
            handler->SendStringList(slist);
            return true;
        }
        return false;
    }

    if (commands[1] != "FileTransfer")
        return false;

    if (slist.size() < 3)
        return false;

    if ((commands.size() < 3) || (commands.size() > 6))
        return false;

    FileTransfer *ft    = NULL;
    QString hostname    = "";
    QString filename    = "";
    bool writemode      = false;
    bool usereadahead   = true;
    int timeout_ms      = 2000;
    switch (commands.size())
    {
      case 6:
        timeout_ms      = commands[5].toInt();
      case 5:
        usereadahead    = commands[4].toInt();
      case 4:
        writemode       = commands[3].toInt();
      default:
        hostname        = commands[2];
    }

    QStringList::const_iterator it = slist.begin();
    QUrl qurl           = *(++it);
    QString wantgroup   = *(++it);

    QStringList checkfiles;
    while (++it != slist.end())
        checkfiles += *(it);

    slist.clear();

    LOG(VB_GENERAL, LOG_DEBUG, "FileServerHandler::HandleAnnounce");
    LOG(VB_GENERAL, LOG_INFO, QString("adding: %1 as remote file transfer")
                            .arg(hostname));

    if (writemode)
    {
        if (wantgroup.isEmpty())
            wantgroup = "Default";

        StorageGroup sgroup(wantgroup, gCoreContext->GetHostName(), false);
        QString dir = sgroup.FindNextDirMostFree();
        if (dir.isEmpty())
        {
            LOG(VB_GENERAL, LOG_ERR, "Unable to determine directory "
                    "to write to in FileTransfer write command");

            slist << "ERROR" << "filetransfer_directory_not_found";
            socket->writeStringList(slist);
            return true;
        }

        QString basename = qurl.path();
        if (basename.isEmpty())
        {
            LOG(VB_GENERAL, LOG_ERR, QString("FileTransfer write "
                    "filename is empty in url '%1'.")
                    .arg(qurl.toString()));

            slist << "ERROR" << "filetransfer_filename_empty";
            socket->writeStringList(slist);
            return true;
        }

        if ((basename.contains("/../")) ||
            (basename.startsWith("../")))
        {
            LOG(VB_GENERAL, LOG_ERR, QString("FileTransfer write "
                    "filename '%1' does not pass sanity checks.")
                    .arg(basename));

            slist << "ERROR" << "filetransfer_filename_dangerous";
            socket->writeStringList(slist);
            return true;
        }

        filename = dir + "/" + basename;
    }
    else
        filename = LocalFilePath(qurl, wantgroup);

    QFileInfo finfo(filename);
    if (finfo.isDir())
    {
        LOG(VB_GENERAL, LOG_ERR, QString("FileTransfer filename "
                "'%1' is actually a directory, cannot transfer.")
                .arg(filename));

        slist << "ERROR" << "filetransfer_filename_is_a_directory";
        socket->writeStringList(slist);
        return true;
    }

    if (writemode)
    {
        QString dirPath = finfo.absolutePath();
        QDir qdir(dirPath);
        if (!qdir.exists())
        {
            if (!qdir.mkpath(dirPath))
            {
                LOG(VB_GENERAL, LOG_ERR, QString("FileTransfer "
                        "filename '%1' is in a subdirectory which does "
                        "not exist, but can not be created.")
                        .arg(filename));

                slist << "ERROR" << "filetransfer_unable_to_create_subdirectory";
                socket->writeStringList(slist);
                return true;
            }
        }

        ft = new FileTransfer(filename, socket, m_parent, writemode);
    }
    else
        ft = new FileTransfer(filename, socket, m_parent, usereadahead, timeout_ms);

    ft->BlockShutdown(true);

    {
        QWriteLocker wlock(&m_ftLock);
        m_ftMap.insert(socket->socket(), ft);
    }

    slist << "OK"
          << QString::number(socket->socket())
          << QString::number(ft->GetFileSize());

    if (checkfiles.size())
    {
        QFileInfo fi(filename);
        QDir dir = fi.absoluteDir();
        for (it = checkfiles.begin(); it != checkfiles.end(); ++it)
        {
            if (dir.exists(*it) &&
                QFileInfo(dir, *it).size() >= kReadTestSize)
                    slist << *it;
        }
    }

    socket->writeStringList(slist);
    m_parent->AddSocketHandler(ft);
    return true;
}
void Get(SocketHandler& h,const std::string& url_in)
{
	HttpGetSocket *s = new HttpGetSocket(h, url_in);
	s -> SetDeleteByHandler();
	h.Add(s);
}
Exemple #29
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;
}
void ProxyHandler::Proxy( SocketHandler &ProxyServerT )
{
    int ret, CommunicationAnswer, retries;

    int requests = 0;
    alivecount = 0;

    ServerConnected = BrowserDropped = DropBrowser = false;

    //Wait for first connection
    while ( ProxyServerT.AcceptClient( ToBrowser ) == false ) sleep(10);
    //Infinite Processing Loop
    for(;;)
    {
        ++requests;

        ToBrowser.ClearVars();
        ToServer.ClearVars();

        Header = "";
        UnlockDone = AnswerDone = ReinitDone = HeaderSend = DropServer = false;
        TransferredHeader = TransferredBody = 0;

        //New connection needed?
        if ( DropBrowser || BrowserDropped )
        {
            ToBrowser.Close();
            ToServer.Close();

            ServerConnected = BrowserDropped = DropBrowser = false;
            alivecount = 0;
        }

        if ( ++alivecount > 1 )
        {
            //Keep-Alive timeout 10 seconds
            if ( ToBrowser.CheckForData(10) == false )
            {
                DropBrowser = true;
                continue;
            }
        }
        if ( ToBrowser.ReadHeader( Header ) == false )
        {
            if (LL>0) if (alivecount==1) LogFile::ErrorMessage("(%s) Could not read browser header\n", ToBrowser.GetIP().c_str());
            DropBrowser = true;
            continue;
        }
        if ( (ret = ToBrowser.AnalyseHeader( Header )) < 0 )
        {
            if (LL>0) LogFile::ErrorMessage("(%s) Invalid request from browser\n", ToBrowser.GetIP().c_str());
            ProxyMessage( ret, "" );
            DropBrowser = true;
            continue;
        }
        
        if ( ToBrowser.GetHost() == "" || ToBrowser.GetPort() == -1 )
        {
            LogFile::ErrorMessage("(%s) Invalid request from browser (no Host-header?)\n%s", ToBrowser.GetIP().c_str(),Header.c_str());
            ProxyMessage( -201, "" );
            DropBrowser = true;
            continue;
        }

        //Keep-Alive?
        if ( ToBrowser.IsItKeepAlive() == false || ToBrowser.GetRequestType() != "GET" || ( (alivecount > 99) && (ToBrowser.CheckForData(0) == false) ) )
        {
            DropBrowser = true;
        }

        //HTTP REQUEST
        if ( ToBrowser.GetRequestProtocol() == "http" )
        {
            CommunicationAnswer = CommunicationHTTP();
        }
        //FTP REQUEST
        else if ( ToBrowser.GetRequestProtocol() == "ftp" )
        {
            if ( UseParentProxy )
            {
                CommunicationAnswer = CommunicationHTTP();
            }
            else
            {
                //TODO: Support ftp even without parentproxy :-)
                ProxyMessage( -110, "" );
                DropBrowser = true;
                continue;
            }
        }
#ifdef SSLTUNNEL
        //SSL CONNECT REQUEST
        else if ( ToBrowser.GetRequestProtocol() == "connect" )
        {
            //Drop Keep-Alive
            ToServer.Close();

            CommunicationAnswer = CommunicationSSL();

            //Close connection
            ToServer.Close();
            ServerConnected = false;

            if ( CommunicationAnswer != 0 ) ProxyMessage( CommunicationAnswer, "" );

            DropBrowser = true;
            continue;
        }
#endif
        else
        {
            LogFile::ErrorMessage("Program Error: Unsupported RequestProtocol: %s\n", ToBrowser.GetRequestProtocol().c_str());
            DropBrowser = true;
            continue;
        }
        if ( LOK )
        {
            //Clean request
            LogFile::AccessMessage("%s %s/%d "LLD" %s %s - NONE/- -\n", ToBrowser.GetIP().c_str(), ToServer.msghit.c_str(), ToServer.GetResponse(), TransferredHeader + TransferredBody, ToBrowser.GetRequestType().c_str(), ToBrowser.GetCompleteRequest().c_str());
        }
        //Retry GET connection if ReadHeader error (-80) or Connect error (-60, -61)
        //Also reconnect if server closed Keep-Alive connection (-60)
        retries = 0;
        while ( (CommunicationAnswer == -80 && ToBrowser.GetRequestType() == "GET") || CommunicationAnswer == -60 || CommunicationAnswer == -61 )
        {
            ToServer.Close();
            ServerConnected = false;

            //Sleep second before retry
            sleep(1);

            CommunicationAnswer = CommunicationHTTP();

            //No need to stop Keep-Alive if retry is clean
            if ( CommunicationAnswer == 0 ) DropServer = false;

            //Too many retries?
            if ( ++retries >= ToServer.IPCount() ) break;
        }

        //Make sure server connection is closed if needed
        if ( DropServer || DropBrowser || BrowserDropped )
        {
            ToServer.Close();
            ServerConnected = false;
        }

        if ( CommunicationAnswer != 0 )
        {
            //Request not clean
            ProxyMessage( CommunicationAnswer, "Error request answer" );
            DropBrowser = true;
        }

        //If some scanner timed out, bail out..
        if ( CommunicationAnswer == 3 ) break;

    }

    //Make sure browser connection is closed
    ToBrowser.Close();

    //Exit process
    exit(1);
}