bool processNetwork(void *)
{
	//	Receive data from the server
	if(state.enableClient == true){
		receiveData(state.client);
	}

	//	Process the server events
	if(state.enableServer == true){
		socketlist_t remote;
		//	Are there any waiting clients to connect?
		if(state.server->WaitForConnections(netLatency) == true){
			serverMessage("/info,newClient");
			remote = state.server->GetConnections();
		}
		
		//	Receive data from the clients
		for(unsigned int a=0;a<remote.size();a++){
			IClientSocket *s = (IClientSocket *)remote[a];
			receiveData(s);
		}
	}
	
	return true;
}
bool AdministrationServerConnection::checkAuthentication(void) {
	if (sessionAuthenticated == false) {
		serverMessage(400);
		return false;
	}

	return true;
}
示例#3
0
void CreateUserThread::run()
{
	QString *response = new QString();
	bool r;
	if((r = QNapiProjektEngine::createUser(nick, pass, mail, response)))
		emit serverMessage(*response);

	delete response;
	emit creatingFinished(r);
}
示例#4
0
QByteArray QQmlDebugTestClient::waitForResponse()
{
    lastMsg.clear();
    QQmlDebugTest::waitForSignal(this, SIGNAL(serverMessage(QByteArray)));
    if (lastMsg.isEmpty()) {
        qWarning() << "no response from server!";
        return QByteArray();
    }
    return lastMsg;
}
void startServer(void)
{
	if(state.enableServer == false && state.enableClient == false){
		//	If the server socket is null, this is the first 
		//	time you started the server so create a new socket
		if(state.server == NULL){
			state.server = fusion->Network->CreateServerSocket();
		}
		
		//	If the socket was created ok, lets start listening for clients
		if(state.server != NULL){
			serverMessage("/info,serverStart");
			state.server->Listen(state.port,5);
			serverMessage("/info,listening");
		}
		
		state.enableServer = true;
	}
}
void stopServer(void)
{
	if(state.enableServer == true){
		state.enableServer = false;
		
		if(state.server != NULL){
			disconnectClients();
			state.server->Disconnect();
			
			serverMessage("/info,serverStop");
		}
	}
}
示例#7
0
frmCreateUser::frmCreateUser(QWidget * parent, Qt::WFlags f) : QDialog(parent, f)
{
	ui.setupUi(this);

#ifdef Q_WS_MAC
	setAttribute(Qt::WA_MacBrushedMetal, GlobalConfig().useBrushedMetal());
#endif
	setAttribute(Qt::WA_QuitOnClose, false);

	connect(ui.pbCreate, SIGNAL(clicked()), this, SLOT(pbCreateClicked()));

	connect(ui.leLogin, SIGNAL(textChanged(QString)), this, SLOT(checkCreateEnable()));
	connect(ui.lePass, SIGNAL(textChanged(QString)), this, SLOT(checkCreateEnable()));
	connect(ui.leRepeatPass, SIGNAL(textChanged(QString)), this, SLOT(checkCreateEnable()));
	connect(ui.leMail, SIGNAL(textChanged(QString)), this, SLOT(checkCreateEnable()));
	connect(&createUserThread, SIGNAL(creatingFinished(bool)), this, SLOT(creatingFinished(bool)));
	connect(&createUserThread, SIGNAL(serverMessage(QString)), this, SLOT(serverMessage(QString)));
	connect(&createUserThread, SIGNAL(terminated()), this, SLOT(creatingFinished()));

	// workaround dla compiza?
	move((QApplication::desktop()->width() - width()) / 2, 
		(QApplication::desktop()->height() - height()) / 2);
}
示例#8
0
文件: Store.cpp 项目: dc-sics/VoloDB
inline void Store::sendTaskToExecutor(FrameMessagesTupleListPointer& messagesListPointer, shared_ptr<zmq::socket_t>& taskSenderSocket)
{
    size_t size = sizeof(FrameMessagesTupleListPointer*);
    FrameMessagesTupleListPointer* taskListPointerToPass = new FrameMessagesTupleListPointer(messagesListPointer);
    char* rawBuffer = new char[size];
    memcpy(rawBuffer, (void*)&taskListPointerToPass, size);
    
    zmq::message_t serverMessage(reinterpret_cast<void*>(rawBuffer), size, _free_handler_default);

    
#if INCLUDE_LOCK_STATEMENTS == 1
    if(!_isLockFreeExecutorAssignment)
    {
        executorAssignerMutex.lock();
        taskSenderSocket->send(serverMessage);
        executorAssignerMutex.unlock();
    }
    else
#endif
    {
        taskSenderSocket->send(serverMessage);
    }
}
示例#9
0
void QQmlDebugTestClient::messageReceived(const QByteArray &ba)
{
    lastMsg = ba;
    emit serverMessage(ba);
}
示例#10
0
void Player::userData(QString data, World*world)
{
    if (data == "+37")
        turningLeft = true;
    if (data == "-37")
        turningLeft = false;

    if (data == "+39")
        turningRight = true;
    if (data == "-39")
        turningRight = false;

    if (data == "+32" && alive)
    {
        isBoosting = true;
    }
    if (data == "-32" && alive)
    {
        isBoosting = false;
    }

    if (data == "+32" && !alive)
    {
        float x = 2.f*rand()/(float)RAND_MAX - 1.f;
        // Find a new position further out (any direction possible, outwards is highly likely)
        float a = atan2((float)pos.y, (float)pos.x) + x*x*x*M_PI;
        float r = BLOCK_SIZE*(0.1f + .5f*rand()/RAND_MAX);

        // TODO find the closest one who is alive and start from there instead from taking just a random one.
        // pPlayer p = world->getRandomAlivePlayer();
        pPlayer p = world->getAlivePlayerNearest(pos);
        if (p)
            pos = p->pos;
        else
            pos = world->startPos;

        pos.x += cos(a)*r;
        pos.y += sin(a)*r;
        dir = 2.f*M_PI*rand()/(float)RAND_MAX;
        alive = true;
        currentPatch = 0;
        timeSinceVisible = 0;
        turningLeft = false;
        turningRight = false;
        newTargetVisibleTime();

        serverMessage(world->sender, "{\"serverMessage\":\"Steer with left and right arrows\"}");
    }

    if (data.length() > 1 && data[0]=='m')
    {
        QStringList strs = data.mid(1).split(",");
        if (strs.size()==2 && !alive)
        {
            float clientX = strs[0].toFloat();
            float clientY = strs[1].toFloat();
            pos.x -= clientX * 100.f + 0.5f;
            pos.y -= clientY * 100.f + 0.5f;
            wasDragged_ = true;
        }
    }
}
示例#11
0
// Constructor
MainWindow::MainWindow(QWidget *parent, QStringList torrentCmdLine)
    :
      QMainWindow(parent),
      m_posInitialized(false),
      force_exit(false),
      icon_TrayConn(res::trayConnected()),
      icon_TrayDisconn(res::trayDisconnected()),
      icon_CurTray(icon_TrayDisconn)
{
    setupUi(this);
    stackedWidget->addWidget(new transfers_widget(this));
    stackedWidget->addWidget(new search_widget(this));
    stackedWidget->addWidget(new preferences_widget(this));
    stackedWidget->setCurrentIndex(0);
    setWindowTitle(tr("qDonkey %1").arg(misc::versionString()));
    QCoreApplication::instance()->installEventFilter(this);

    //QApplication::setOverrideCursor(Qt::WaitCursor);
    m_last_file_error = QDateTime::currentDateTime().addSecs(-1); // imagine last file error event was 1 seconds in past

#ifdef Q_WS_WIN
    m_nTaskbarButtonCreated = RegisterWindowMessage(L"TaskbarButtonCreated");
#else
    m_nTaskbarButtonCreated = 0;
#endif

    Preferences pref;

    // Clean exit on log out
    connect(static_cast<SessionApplication*>(qApp), SIGNAL(sessionIsShuttingDown()), this, SLOT(deleteSession()));

    this->setWindowIcon(QIcon(res::favicon()));

#ifdef Q_WS_MAC
    connect(static_cast<QMacApplication*>(qApp), SIGNAL(newFileOpenMacEvent(QString)), this, SLOT(processParams(QString)));
#endif

    statusBar = new status_bar(this, QMainWindow::statusBar());
    m_pwr = new PowerManagement(this);

    // Configure session according to options
    loadPreferences(false);

    // Start connection checking timer
    guiUpdater = new QTimer(this);
    connect(guiUpdater, SIGNAL(timeout()), this, SLOT(updateGUI()));
    guiUpdater->start(2000);

    // Accept drag 'n drops
    //setAcceptDrops(true);
    createKeyboardShortcuts();

#ifdef Q_WS_MAC
    setUnifiedTitleAndToolBarOnMac(true);
#endif

    // View settings



    // Auto shutdown actions
/*    QActionGroup * autoShutdownGroup = new QActionGroup(this);
    autoShutdownGroup->setExclusive(true);
    autoShutdownGroup->addAction(actionAutoShutdown_Disabled);
    autoShutdownGroup->addAction(actionAutoExit_mule);
    autoShutdownGroup->addAction(actionAutoShutdown_system);
    autoShutdownGroup->addAction(actionAutoSuspend_system);

#if !defined(Q_WS_X11) || defined(QT_DBUS_LIB)
    actionAutoShutdown_system->setChecked(pref.shutdownWhenDownloadsComplete());
    actionAutoSuspend_system->setChecked(pref.suspendWhenDownloadsComplete());
#else
    actionAutoShutdown_system->setDisabled(true);
    actionAutoSuspend_system->setDisabled(true);
#endif

    actionAutoExit_mule->setChecked(pref.shutdownqBTWhenDownloadsComplete());

    if (!autoShutdownGroup->checkedAction())
        actionAutoShutdown_Disabled->setChecked(true);
*/

    readSettings();

    show();
    activateWindow();
    raise();

    // Start watching the executable for updates
    executable_watcher = new QFileSystemWatcher();
    connect(executable_watcher, SIGNAL(fileChanged(QString)), this, SLOT(notifyOfUpdate(QString)));
    executable_watcher->addPath(qApp->applicationFilePath());

    // Add torrent given on command line
    processParams(torrentCmdLine);
#ifdef Q_WS_MAC
    //qt_mac_set_dock_menu(icon_CurTray);
#endif

    // Make sure the Window is visible if we don't have a tray icon
    if (!systrayIcon && isHidden())  {
        show();
        activateWindow();
        raise();
    }

    connect(Session::instance(), SIGNAL(serverNameResolved(QString)), this, SLOT(handleServerNameResolved(QString)));
    connect(Session::instance(), SIGNAL(serverConnectionInitialized(quint32,quint32,quint32)), this, SLOT(handleServerConnectionInitialized(quint32,quint32,quint32)));
    connect(Session::instance(), SIGNAL(serverConnectionClosed(QString)), this, SLOT(handleServerConnectionClosed(QString)));
    connect(Session::instance(), SIGNAL(serverStatus(int,int)), this, SLOT(handleServerStatus(int,int)));
    connect(Session::instance(), SIGNAL(serverMessage(QString)), this, SLOT(handleServerMessage(QString)));
    connect(Session::instance(), SIGNAL(serverIdentity(QString,QString)), this, SLOT(handleServerIdentity(QString,QString)));

    connect(Session::instance(), SIGNAL(transferAdded(QED2KHandle)), SLOT(addedTransfer(QED2KHandle)));
    connect(Session::instance(), SIGNAL(transferFinished(QED2KHandle)), SLOT(finishedTransfer(QED2KHandle)));

    //Tray actions.
    //connect(actionToggleVisibility, SIGNAL(triggered()), this, SLOT(toggleVisibility()));
    //connect(actionStart_All, SIGNAL(triggered()), Session::instance(), SLOT(resumeAllTransfers()));
    //connect(actionPause_All, SIGNAL(triggered()), Session::instance(), SLOT(pauseAllTransfers()));

    actionConnect->trigger();
    Session::instance()->loadDirectory(pref.inputDir());
}
示例#12
0
void HWNewNet::ParseCmd(const QStringList & lst)
{
    qDebug() << "Server: " << lst;

    if(!lst.size())
    {
        qWarning("Net client: Bad message");
        return;
    }

    if (lst[0] == "NICK")
    {
        mynick = lst[1];
        m_playersModel->setNickname(mynick);
        m_nick_registered = false;
        return ;
    }

    if (lst[0] == "PROTO")
        return ;

    if (lst[0] == "ERROR")
    {
        if (lst.size() == 2)
            emit Error(HWApplication::translate("server", lst[1].toAscii().constData()));
        else
            emit Error("Unknown error");
        return;
    }

    if (lst[0] == "WARNING")
    {
        if (lst.size() == 2)
            emit Warning(HWApplication::translate("server", lst[1].toAscii().constData()));
        else
            emit Warning("Unknown warning");
        return;
    }

    if (lst[0] == "CONNECTED")
    {
        if(lst.size() < 3 || lst[2].toInt() < cMinServerVersion)
        {
            // TODO: Warn user, disconnect
            qWarning() << "Server too old";
            RawSendNet(QString("QUIT%1%2").arg(delimeter).arg("Server too old"));
            Disconnect();
            emit disconnected(tr("The server is too old. Disconnecting now."));
            return;
        }

        RawSendNet(QString("NICK%1%2").arg(delimeter).arg(mynick));
        RawSendNet(QString("PROTO%1%2").arg(delimeter).arg(*cProtoVer));
        netClientState = Connected;
        m_game_connected = true;
        emit adminAccess(false);
        return;
    }

    if (lst[0] == "SERVER_AUTH")
    {
        if(lst.size() < 2)
        {
            qWarning("Net: Malformed SERVER_AUTH message");
            return;
        }

        if(lst[1] != m_serverHash)
        {
            Error("Server authentication error");
            Disconnect();
        } else
        {
            // empty m_serverHash variable means no authentication was performed
            // or server passed authentication
            m_serverHash.clear();
        }

        return;
    }

    if (lst[0] == "PING")
    {
        if (lst.size() > 1)
            RawSendNet(QString("PONG%1%2").arg(delimeter).arg(lst[1]));
        else
            RawSendNet(QString("PONG"));
        return;
    }

    if (lst[0] == "ROOMS")
    {
        if(lst.size() % 9 != 1)
        {
            qWarning("Net: Malformed ROOMS message");
            return;
        }
        m_roomsListModel->setRoomsList(lst.mid(1));
        if (m_private_game == false && m_nick_registered == false)
        {
            emit NickNotRegistered(mynick);
        }
        return;
    }

    if (lst[0] == "SERVER_MESSAGE")
    {
        if(lst.size() < 2)
        {
            qWarning("Net: Empty SERVERMESSAGE message");
            return;
        }
        emit serverMessage(lst[1]);
        return;
    }

    if (lst[0] == "CHAT")
    {
        if(lst.size() < 3)
        {
            qWarning("Net: Empty CHAT message");
            return;
        }

        QString action = HWProto::chatStringToAction(lst[2]);

        if (netClientState == InLobby)
        {
            if (action != NULL)
                emit lobbyChatAction(lst[1], action);
            else
                emit lobbyChatMessage(lst[1], lst[2]);
        }
        else
        {
            emit chatStringFromNet(HWProto::formatChatMsg(lst[1], lst[2]));
            if (action != NULL)
                emit roomChatAction(lst[1], action);
            else
                emit roomChatMessage(lst[1], lst[2]);
        }
        return;
    }

    if (lst[0] == "INFO")
    {
        if(lst.size() < 5)
        {
            qWarning("Net: Malformed INFO message");
            return;
        }
        emit playerInfo(lst[1], lst[2], lst[3], lst[4]);
        if (netClientState != InLobby)
        {
            QStringList tmp = lst;
            tmp.removeFirst();
            emit chatStringFromNet(tmp.join(" ").prepend('\x01'));
        }
        return;
    }

    if (lst[0] == "SERVER_VARS")
    {
        QStringList tmp = lst;
        tmp.removeFirst();
        while (tmp.size() >= 2)
        {
            if(tmp[0] == "MOTD_NEW") emit serverMessageNew(tmp[1]);
            else if(tmp[0] == "MOTD_OLD") emit serverMessageOld(tmp[1]);
            else if(tmp[0] == "LATEST_PROTO") emit latestProtocolVar(tmp[1].toInt());

            tmp.removeFirst();
            tmp.removeFirst();
        }
        return;
    }

    if (lst[0] == "BANLIST")
    {
        QStringList tmp = lst;
        tmp.removeFirst();
        emit bansList(tmp);
        return;
    }

    if (lst[0] == "CLIENT_FLAGS" || lst[0] == "CF")
    {
        if(lst.size() < 3 || lst[1].size() < 2)
        {
            qWarning("Net: Malformed CLIENT_FLAGS message");
            return;
        }

        QString flags = lst[1];
        bool setFlag = flags[0] == '+';
        const QStringList nicks = lst.mid(2);

        while(flags.size() > 1)
        {
            flags.remove(0, 1);
            char c = flags[0].toAscii();
            bool inRoom = (netClientState == InRoom || netClientState == InGame);

            switch(c)
            {
                // flag indicating if a player is ready to start a game
                case 'r':
                    if(inRoom)
                        foreach (const QString & nick, nicks)
                        {
                            if (nick == mynick)
                            {
                                emit setMyReadyStatus(setFlag);
                            }
                            m_playersModel->setFlag(nick, PlayersListModel::Ready, setFlag);
                        }
                        break;

                // flag indicating if a player is a registered user
                case 'u':
                        foreach(const QString & nick, nicks)
                            m_playersModel->setFlag(nick, PlayersListModel::Registered, setFlag);
                        break;
                // flag indicating if a player is in room
                case 'i':
                        foreach(const QString & nick, nicks)
                            m_playersModel->setFlag(nick, PlayersListModel::InRoom, setFlag);
                        break;
                // flag indicating if a player is contributor
                case 'c':
                        foreach(const QString & nick, nicks)
                            m_playersModel->setFlag(nick, PlayersListModel::Contributor, setFlag);
                        break;
                // flag indicating if a player has engine running
                case 'g':
                    if(inRoom)
                        foreach(const QString & nick, nicks)
                            m_playersModel->setFlag(nick, PlayersListModel::InGame, setFlag);
                        break;

                // flag indicating if a player is the host/master of the room
                case 'h':
                    if(inRoom)
                        foreach (const QString & nick, nicks)
                        {
                            if (nick == mynick)
                            {
                                isChief = setFlag;
                                emit roomMaster(isChief);
                            }

                            m_playersModel->setFlag(nick, PlayersListModel::RoomAdmin, setFlag);
                        }
                        break;

                // flag indicating if a player is admin (if so -> worship them!)
                case 'a':
                        foreach (const QString & nick, nicks)
                        {
                            if (nick == mynick)
                                emit adminAccess(setFlag);

                            m_playersModel->setFlag(nick, PlayersListModel::ServerAdmin, setFlag);
                        }
                        break;

                default:
                        qWarning() << "Net: Unknown client-flag: " << c;
            }
        }

        return;
    }

    if(lst[0] == "KICKED")
    {
        netClientState = InLobby;
        askRoomsList();
        emit LeftRoom(tr("You got kicked"));
        m_playersModel->resetRoomFlags();

        return;
    }

    if(lst[0] == "LOBBY:JOINED")
    {
        if(lst.size() < 2)
        {
            qWarning("Net: Bad JOINED message");
            return;
        }

        for(int i = 1; i < lst.size(); ++i)
        {
            if (lst[i] == mynick)
            {
                // check if server is authenticated or no authentication was performed at all
                if(!m_serverHash.isEmpty())
                {
                    Error(tr("Server authentication error"));

                    Disconnect();
                }

                netClientState = InLobby;
                RawSendNet(QString("LIST"));
                emit connected();
            }

            m_playersModel->addPlayer(lst[i], false);
        }
        return;
    }

    if(lst[0] == "ROOM" && lst.size() == 11 && lst[1] == "ADD")
    {
        QStringList tmp = lst;
        tmp.removeFirst();
        tmp.removeFirst();

        m_roomsListModel->addRoom(tmp);
        return;
    }

    if(lst[0] == "ROOM" && lst.size() == 12 && lst[1] == "UPD")
    {
        QStringList tmp = lst;
        tmp.removeFirst();
        tmp.removeFirst();

        QString roomName = tmp.takeFirst();
        m_roomsListModel->updateRoom(roomName, tmp);

        // keep track of room name so correct name is displayed
        if(myroom == roomName && myroom != tmp[1])
        {
            myroom = tmp[1];
            emit roomNameUpdated(myroom);
        }

        return;
    }

    if(lst[0] == "ROOM" && lst.size() == 3 && lst[1] == "DEL")
    {
        m_roomsListModel->removeRoom(lst[2]);
        return;
    }

    if(lst[0] == "LOBBY:LEFT")
    {
        if(lst.size() < 2)
        {
            qWarning("Net: Bad LOBBY:LEFT message");
            return;
        }

        if (lst.size() < 3)
            m_playersModel->removePlayer(lst[1]);
        else
            m_playersModel->removePlayer(lst[1], lst[2]);

        return;
    }

    if (lst[0] == "ASKPASSWORD")
    {
        // server should send us salt of at least 16 characters

        if(lst.size() < 2 || lst[1].size() < 16)
        {
            qWarning("Net: Bad ASKPASSWORD message");
            return;
        }

        emit NickRegistered(mynick);
        m_nick_registered = true;

        // store server salt
        // when this variable is set, it is assumed that server asked us for a password
        m_serverSalt = lst[1];
        m_clientSalt = QUuid::createUuid().toString();

        maybeSendPassword();

        return;
    }

    if (lst[0] == "NOTICE")
    {
        if(lst.size() < 2)
        {
            qWarning("Net: Bad NOTICE message");
            return;
        }

        bool ok;
        int n = lst[1].toInt(&ok);
        if(!ok)
        {
            qWarning("Net: Bad NOTICE message");
            return;
        }

        handleNotice(n);

        return;
    }

    if (lst[0] == "BYE")
    {
        if (lst.size() < 2)
        {
            qWarning("Net: Bad BYE message");
            return;
        }
        if (lst[1] == "Authentication failed")
        {
            emit AuthFailed();
            m_game_connected = false;
            Disconnect();
            //omitted 'emit disconnected()', we don't want the error message
            return;
        }
        m_game_connected = false;
        Disconnect();
        emit disconnected(HWApplication::translate("server", lst[1].toAscii().constData()));
        return;
    }

    if(lst[0] == "JOINING")
    {
        if(lst.size() != 2)
        {
            qWarning("Net: Bad JOINING message");
            return;
        }

        myroom = lst[1];
        emit roomNameUpdated(myroom);
        return;
    }

    if(netClientState == InLobby && lst[0] == "JOINED")
    {
        if(lst.size() < 2 || lst[1] != mynick)
        {
            qWarning("Net: Bad JOINED message");
            return;
        }

        for(int i = 1; i < lst.size(); ++i)
        {
            if (lst[i] == mynick)
            {
                netClientState = InRoom;
                emit EnteredGame();
                emit roomMaster(isChief);
                if (isChief)
                    emit configAsked();
            }

            m_playersModel->playerJoinedRoom(lst[i], isChief && (lst[i] != mynick));

            emit chatStringFromNet(tr("%1 *** %2 has joined the room").arg('\x03').arg(lst[i]));
        }
        return;
    }

    if(netClientState == InRoom || netClientState == InGame)
    {
        if (lst[0] == "EM")
        {
            if(lst.size() < 2)
            {
                qWarning("Net: Bad EM message");
                return;
            }
            for(int i = 1; i < lst.size(); ++i)
            {
                QByteArray em = QByteArray::fromBase64(lst[i].toAscii());
                emit FromNet(em);
            }
            return;
        }

        if (lst[0] == "ROUND_FINISHED")
        {
            emit FromNet(QByteArray("\x01o"));
            return;
        }

        if (lst[0] == "ADD_TEAM")
        {
            if(lst.size() != 24)
            {
                qWarning("Net: Bad ADDTEAM message");
                return;
            }
            QStringList tmp = lst;
            tmp.removeFirst();
            emit AddNetTeam(tmp);
            return;
        }

        if (lst[0] == "REMOVE_TEAM")
        {
            if(lst.size() != 2)
            {
                qWarning("Net: Bad REMOVETEAM message");
                return;
            }
            emit RemoveNetTeam(HWTeam(lst[1]));
            return;
        }

        if(lst[0] == "ROOMABANDONED")
        {
            netClientState = InLobby;
            m_playersModel->resetRoomFlags();
            emit LeftRoom(tr("Room destroyed"));
            return;
        }

        if (lst[0] == "RUN_GAME")
        {
            netClientState = InGame;
            emit AskForRunGame();
            return;
        }

        if (lst[0] == "TEAM_ACCEPTED")
        {
            if (lst.size() != 2)
            {
                qWarning("Net: Bad TEAM_ACCEPTED message");
                return;
            }
            emit TeamAccepted(lst[1]);
            return;
        }

        if (lst[0] == "CFG")
        {
            if(lst.size() < 3)
            {
                qWarning("Net: Bad CFG message");
                return;
            }
            QStringList tmp = lst;
            tmp.removeFirst();
            tmp.removeFirst();
            if (lst[1] == "SCHEME")
                emit netSchemeConfig(tmp);
            else
                emit paramChanged(lst[1], tmp);
            return;
        }

        if (lst[0] == "HH_NUM")
        {
            if (lst.size() != 3)
            {
                qWarning("Net: Bad TEAM_ACCEPTED message");
                return;
            }
            HWTeam tmptm(lst[1]);
            tmptm.setNumHedgehogs(lst[2].toUInt());
            emit hhnumChanged(tmptm);
            return;
        }

        if (lst[0] == "TEAM_COLOR")
        {
            if (lst.size() != 3)
            {
                qWarning("Net: Bad TEAM_COLOR message");
                return;
            }
            HWTeam tmptm(lst[1]);
            tmptm.setColor(lst[2].toInt());
            emit teamColorChanged(tmptm);
            return;
        }

        if(lst[0] == "JOINED")
        {
            if(lst.size() < 2)
            {
                qWarning("Net: Bad JOINED message");
                return;
            }

            for(int i = 1; i < lst.size(); ++i)
            {
                emit chatStringFromNet(tr("%1 *** %2 has joined the room").arg('\x03').arg(lst[i]));
                m_playersModel->playerJoinedRoom(lst[i], isChief && (lst[i] != mynick));
            }
            return;
        }

        if(lst[0] == "LEFT")
        {
            if(lst.size() < 2)
            {
                qWarning("Net: Bad LEFT message");
                return;
            }

            if (lst.size() < 3)
                emit chatStringFromNet(tr("%1 *** %2 has left").arg('\x03').arg(lst[1]));
            else
                emit chatStringFromNet(tr("%1 *** %2 has left (%3)").arg('\x03').arg(lst[1], lst[2]));
            m_playersModel->playerLeftRoom(lst[1]);
            return;
        }
    }

    qWarning() << "Net: Unknown message or wrong state:" << lst;
}
bool AdministrationServerConnection::executeCommand(socketMsg *smsg) {
	Parser *parseCommand;
	Parser *parseArgument;
	List<Memory<char> *> *tokensCommand;
	List<Memory<char> *> *tokensArgument;
	int **hashtablePtr;
	int hashtableSize;
	HashTableElt *hashtableElt;
	struct CatalogData *catalogData;
	socketMsg smsgSend;
	size_t sizeSent;
	char specialDelimiter[2];
	char timeBuffer[64];
	int counter = 0;
	bool wantToQuit = false;
	char *argument;
	int i;
	size_t catalogBufferSize;
	char *catalogBuffer;
	int returnCode;

	specialDelimiter[0] = ';';
	specialDelimiter[1] = 0x00;
	parseCommand = new Parser(" ");
	parseArgument = new Parser(specialDelimiter);
	tokensCommand = parseCommand->tokenizeData(smsg->recvmsg, 1, smsg->brecv);
	while (commandsList[counter]) {
		if (! strncmp(tokensCommand->getFirstElement()->bloc, commandsList[counter], strlen(commandsList[counter])))
			break;
		counter++;
	}
	if (! commandsList[counter]) {
		systemLog->sysLog(ERROR, "( %s:%d ) unrecognized administration command : %s\n", inet_ntoa(sourceAddress->sin_addr), ntohs(sourceAddress->sin_port), tokensCommand->getFirstElement()->bloc);
		counter = -1;
	}
	tokensCommand->removeFirst();
  
	// Local Initializations
	serverAnswer->initialize();
	bzero(timeBuffer, sizeof(timeBuffer));

	switch (counter) {
	case 0:
		/* AUTH <user> <pass> - authentication */
		tokensArgument = parseArgument->tokenizeData(tokensCommand->getFirstElement()->bloc, 2, tokensCommand->getFirstElement()->getBlocSize());
		if ((! tokensArgument) || (tokensArgument->getListSize() != 2)) {
			serverMessage(300);
			break;
		}
		if (! strcmp(tokensArgument->getElement(1)->getBloc(), "admin")) {
			if (! strncmp(tokensArgument->getElement(2)->getBloc(), "a02sg32", 7)) {
				serverMessage(201);
				sessionAuthenticated = true;
			}
			else
				serverMessage(306);
		}
		else
			serverMessage(306);
		delete tokensArgument;
		break;
	case 1:
		/* DAEMONRELOAD - reload configuration */
		if (checkAuthentication() == true) {
			configuration->parseConfigurationFile();
			serverMessage(200);
		}
		break;
	case 2:
		/* DAEMONSTATS - get the stats */
		if (checkAuthentication() == true)
			serverMessage(201);
		break;
	case 3:
		/* DAEMONPING - check if daemon is ok */
		if (checkAuthentication() == true)
			serverMessage(305);
		break;
	case 4:
		/* DAEMONVERSION - return the daemon revision */
		if (checkAuthentication() == true)
			serverMessage(203);
		break;
	case 5:
		/* QUIT - quit the administration interface */
		serverMessage(101);
		wantToQuit = true;
		break;
	case 6:
		/* SET - set some startup parameters */
		if (checkAuthentication() == false)
			break;
		tokensArgument = parseArgument->tokenizeData(tokensCommand->getFirstElement()->bloc, 2, tokensCommand->getFirstElement()->getBlocSize());
		if ((! tokensArgument) || (tokensArgument->getListSize() != 2)) {
			serverMessage(301);
			break;
		}
		i = 0;
		argument = tokensArgument->getElement(2)->bloc;
		while (argument[i]) {
			if ((argument[i] == '\n') || (argument[i] == '\r'))
				argument[i] = '\0';
			i++;
		}
		if (! strcmp(tokensArgument->getElement(1)->bloc, "nokeycheck")) {
			if (! strcmp(tokensArgument->getElement(2)->bloc, "true")) {
				configuration->noKeyCheck = true;
				serverMessage(204);
			}
			else
				if (! strcmp(tokensArgument->getElement(2)->bloc, "false")) {
					configuration->noKeyCheck = false;
					serverMessage(204);
				}
				else
					serverMessage(302);
			delete tokensArgument;
			break;
		}
		if (! strcmp(tokensArgument->getElement(1)->bloc, "keytimeout")) {
			int keyTimeout;

			keyTimeout = atoi(tokensArgument->getElement(2)->bloc);
			if (keyTimeout) {
				configuration->keyTimeout = keyTimeout;
				serverMessage(204);
			}
			else
				serverMessage(302);
			delete tokensArgument;
			break;
		}
		if (! strcmp(tokensArgument->getElement(1)->bloc, "readtimeout")) {
			int readTimeout;

			readTimeout = atoi(tokensArgument->getElement(2)->bloc);
			if (readTimeout) {
				configuration->readTimeout = readTimeout;
				serverMessage(204);
			}
			else
				serverMessage(302);
			delete tokensArgument;
			break;
		}
		if (! strcmp(tokensArgument->getElement(1)->bloc, "writetimeout")) {
			int writeTimeout;

			writeTimeout = atoi(tokensArgument->getElement(2)->bloc);
			if (writeTimeout) {
				configuration->writeTimeout = writeTimeout;
				serverMessage(204);
			}
			else
				serverMessage(302);
			delete tokensArgument;
			break;
		}
		if (! strcmp(tokensArgument->getElement(1)->bloc, "shappingtimeout")) {
			int shappingTimeout;

			shappingTimeout = atoi(tokensArgument->getElement(2)->bloc);
			if (shappingTimeout) {
				configuration->shappingTimeout = shappingTimeout;
				serverMessage(204);
			}
			else
				serverMessage(302);
			delete tokensArgument;
			break;
		}
		
		serverMessage(302);
		delete tokensArgument;
		break;
	case 7:
		catalogHashtable->lock();
		hashtablePtr = catalogHashtable->getHashtable();
		hashtableSize = catalogHashtable->getSize();
		i = 0;
		if (! catalogHashtable->getNumberOfElements()) {
			serverMessage(401);
			catalogHashtable->unlock();
			break;
		}
		catalogBufferSize = 0;
		catalogBuffer = (char *)malloc(1);
		catalogBuffer[0] = '\0';
		while (i < hashtableSize) {
			if (hashtablePtr[i]) {
				hashtableElt = (HashTableElt *)hashtablePtr[i];
				while (hashtableElt) {
					catalogData = (struct CatalogData *)hashtableElt->getData();
					serverAnswer->snPrintf("%s|%s|%d\n", hashtableElt->getKey(), inet_ntoa(*((struct in_addr *)&catalogData->host)), catalogData->counter);
					catalogBufferSize += strlen(serverAnswer->bloc);
					catalogBuffer = (char *)realloc(catalogBuffer, catalogBufferSize+1);
					if (! catalogBuffer) {
						systemLog->sysLog(CRITICAL, "cannot reallocate catalogBuffer: %s", strerror(errno));
						serverMessage(502);
						catalogHashtable->unlock();
						break;
					}
					strcat(catalogBuffer, serverAnswer->bloc);
					hashtableElt = hashtableElt->getNext();
				}
			}
			i++;
		}
		catalogHashtable->unlock();
		serverMessage(205);
		usleep(500);
		serverAnswer->snPrintf("%d\n", catalogBufferSize);
		smsgSend.len = strlen(serverAnswer->bloc);
		smsgSend.sendmsg = serverAnswer->bloc;
		server->sendMessage(clientSocket, &smsgSend);
		usleep(500);
		sizeSent = 0;
		while (sizeSent != catalogBufferSize) {
			smsgSend.len = catalogBufferSize - sizeSent;
			smsgSend.sendmsg = &catalogBuffer[sizeSent];
			returnCode = server->sendMessage(clientSocket, &smsgSend);
			if (returnCode < 0) {
				systemLog->sysLog(ERROR, "cannot send catalog buffer to client: %s", strerror(errno));
				free(catalogBuffer);
				return -1;
			}
			sizeSent += smsgSend.bsent;
		}
		if (catalogBuffer)
			free(catalogBuffer);

		break;
	default:
		serverMessage(500);
		break;
	}

	delete tokensCommand;
	delete parseCommand;
	delete parseArgument;

	return wantToQuit;
}
示例#14
0
void QED2KSession::readAlerts()
{
    std::auto_ptr<libed2k::alert> a = m_session->pop_alert();

    while (a.get())
    {
        if (libed2k::server_name_resolved_alert* p =
            dynamic_cast<libed2k::server_name_resolved_alert*>(a.get()))
        {
            emit serverNameResolved(QString::fromUtf8(p->endpoint.c_str(), p->endpoint.size()));
        }
        if (libed2k::server_connection_initialized_alert* p =
            dynamic_cast<libed2k::server_connection_initialized_alert*>(a.get()))
        {
            emit serverConnectionInitialized(p->client_id, p->tcp_flags, p->aux_port);
            qDebug() << "server initialized: " << QString::fromStdString(p->name) << " " << QString::fromStdString(p->host) << " " << p->port;
        }
        else if (libed2k::server_status_alert* p = dynamic_cast<libed2k::server_status_alert*>(a.get()))
        {
            emit serverStatus(p->files_count, p->users_count);
        }
        else if (libed2k::server_identity_alert* p = dynamic_cast<libed2k::server_identity_alert*>(a.get()))
        {
            emit serverIdentity(QString::fromUtf8(p->server_name.c_str(), p->server_name.size()),
                                QString::fromUtf8(p->server_descr.c_str(), p->server_descr.size()));
        }
        else if (libed2k::server_message_alert* p = dynamic_cast<libed2k::server_message_alert*>(a.get()))
        {
            emit serverMessage(QString::fromUtf8(p->server_message.c_str(), p->server_message.size()));
        }
        else if (libed2k::server_connection_closed* p =
                 dynamic_cast<libed2k::server_connection_closed*>(a.get()))
        {
            emit serverConnectionClosed(QString::fromLocal8Bit(p->m_error.message().c_str()));
        }
        else if (libed2k::shared_files_alert* p = dynamic_cast<libed2k::shared_files_alert*>(a.get()))
        {
            QList<QED2KSearchResultEntry> vRes;
            vRes.reserve(p->m_files.m_collection.size());
            bool bMoreResult = p->m_more;

            for (size_t n = 0; n < p->m_files.m_collection.size(); ++n)
            {
                QED2KSearchResultEntry sre = QED2KSearchResultEntry::fromSharedFileEntry(p->m_files.m_collection[n]);
                if (sre.isCorrect()) vRes.push_back(sre);
            }

            // emit special signal for derived class
            if (libed2k::shared_directory_files_alert* p2 =
                dynamic_cast<libed2k::shared_directory_files_alert*>(p))
            {
                emit peerSharedDirectoryFiles(
                    p2->m_np, md4toQString(p2->m_hash),
                    QString::fromUtf8(p2->m_strDirectory.c_str(), p2->m_strDirectory.size()), vRes);
            }
            else if (libed2k::ismod_shared_directory_files_alert* p2 =
                     dynamic_cast<libed2k::ismod_shared_directory_files_alert*>(p))
            {
                emit peerIsModSharedFiles(p2->m_np, md4toQString(p2->m_hash), md4toQString(p2->m_dir_hash), vRes);
            }
            else
            {
                emit searchResult(p->m_np, md4toQString(p->m_hash), vRes, bMoreResult);
            }
        }
        else if (libed2k::listen_failed_alert* p = dynamic_cast<libed2k::listen_failed_alert*>(a.get()))
        {
            Q_UNUSED(p)
            // TODO - process signal - it means we have different client on same port
        }
        else if (libed2k::peer_connected_alert* p = dynamic_cast<libed2k::peer_connected_alert*>(a.get()))
        {
            emit peerConnected(p->m_np, md4toQString(p->m_hash), p->m_active);
        }
        else if (libed2k::peer_disconnected_alert* p = dynamic_cast<libed2k::peer_disconnected_alert*>(a.get()))
        {
            emit peerDisconnected(p->m_np, md4toQString(p->m_hash), p->m_ec);
        }
        else if (libed2k::peer_message_alert* p = dynamic_cast<libed2k::peer_message_alert*>(a.get()))
        {
            emit peerMessage(p->m_np, md4toQString(p->m_hash),
                             QString::fromUtf8(p->m_strMessage.c_str(), p->m_strMessage.size()));
        }
        else if (libed2k::peer_captcha_request_alert* p =
                 dynamic_cast<libed2k::peer_captcha_request_alert*>(a.get()))
        {
            QPixmap pm;
            if (!p->m_captcha.empty()) pm.loadFromData((const uchar*)&p->m_captcha[0], p->m_captcha.size()); // avoid windows rtl error
            emit peerCaptchaRequest(p->m_np, md4toQString(p->m_hash), pm);
        }
        else if (libed2k::peer_captcha_result_alert* p =
                 dynamic_cast<libed2k::peer_captcha_result_alert*>(a.get()))
        {
            emit peerCaptchaResult(p->m_np, md4toQString(p->m_hash), p->m_nResult);
        }
        else if (libed2k::shared_files_access_denied* p =
                 dynamic_cast<libed2k::shared_files_access_denied*>(a.get()))
        {
            emit peerSharedFilesAccessDenied(p->m_np, md4toQString(p->m_hash));
        }
        else if (libed2k::shared_directories_alert* p = dynamic_cast<libed2k::shared_directories_alert*>(a.get()))
        {
            QStringList qstrl;

            for (size_t n = 0; n < p->m_dirs.size(); ++n)
            {
                qstrl.append(QString::fromUtf8(p->m_dirs[n].c_str(), p->m_dirs[n].size()));
            }

            emit peerSharedDirectories(p->m_np, md4toQString(p->m_hash), qstrl);
        }
        else if (libed2k::added_transfer_alert* p =
                 dynamic_cast<libed2k::added_transfer_alert*>(a.get()))
        {
            QED2KHandle h(p->m_handle);
            if (!h.is_seed()) m_currentSessionTransfers.insert(h.hash());

            if (!m_addTimes.contains(h.hash())) {
                m_addTimes.insert(h.hash(), QDateTime::currentDateTime());
            }

            if (m_sharedFiles.contains(h.hash())) {
                emit transferShared(h);
            } else {
                emit transferAdded(QED2KHandle(h));
            }
        }
        else if (libed2k::paused_transfer_alert* p =
                 dynamic_cast<libed2k::paused_transfer_alert*>(a.get()))
        {
            emit transferPaused(QED2KHandle(p->m_handle));
        }
        else if (libed2k::resumed_transfer_alert* p =
                 dynamic_cast<libed2k::resumed_transfer_alert*>(a.get()))
        {
            emit transferResumed(QED2KHandle(p->m_handle));
        }
        else if (libed2k::deleted_transfer_alert* p =
                 dynamic_cast<libed2k::deleted_transfer_alert*>(a.get()))
        {            
            emit transferDeleted(QString::fromStdString(p->m_hash.toString()));
        }
        else if (libed2k::finished_transfer_alert* p =
                 dynamic_cast<libed2k::finished_transfer_alert*>(a.get()))
        {
            QED2KHandle h(p->m_handle);

            if (m_sharedFiles.contains(h.hash())) {
                emit transferRestored(h);
            } else {
                emit transferFinished(h);
            }
        }
        else if (libed2k::save_resume_data_alert* p = dynamic_cast<libed2k::save_resume_data_alert*>(a.get()))
        {
            Preferences pref;
            QED2KHandle h(p->m_handle);
            QDateTime t;
            writeResumeData(p, misc::metadataDirectory(pref.inputDir()), QFile::exists(h.filepath()), m_addTimes.value(h.hash(), t));
        }
        else if (libed2k::transfer_params_alert* p = dynamic_cast<libed2k::transfer_params_alert*>(a.get()))
        {
            QFileInfo info(misc::toQStringU(p->m_atp.file_path));
            if (info.absoluteDir() == QDir(m_currentPath)) {
                emit transferParametersReady(p->m_atp, p->m_ec);
                if (!p->m_ec) m_sharedFiles << addTransfer(p->m_atp).hash();
                else qDebug() << "transfer params error: " << misc::toQStringU(p->m_ec.message());
            } else {
                qDebug() << "ignore add transfer parameters for old directory: " << misc::toQStringU(p->m_atp.file_path);
            }
        }
        else if (libed2k::file_renamed_alert* p = dynamic_cast<libed2k::file_renamed_alert*>(a.get()))
        {
            emit transferSavePathChanged(QED2KHandle(p->m_handle));
        }
        else if (libed2k::storage_moved_alert* p = dynamic_cast<libed2k::storage_moved_alert*>(a.get()))
        {
            emit transferStorageMoved(QED2KHandle(p->m_handle));
        }
        else if (libed2k::file_error_alert* p = dynamic_cast<libed2k::file_error_alert*>(a.get()))
        {
            QED2KHandle h(p->m_handle);
            if (h.is_valid()) {
                emit fileError(h, QString::fromLocal8Bit(p->error.message().c_str(), p->error.message().size()));
                h.pause();
            }
        }
        else if (libed2k::portmap_error_alert* p = dynamic_cast<libed2k::portmap_error_alert*>(a.get()))
        {
            qDebug("UPnP Failure, msg: %s", p->message().c_str());
            //addConsoleMessage(tr("UPnP/NAT-PMP: Port mapping failure, message: %1")
            //                  .arg(misc::toQString(p->message())), "red");
        }
        else if (libed2k::portmap_alert* p = dynamic_cast<libed2k::portmap_alert*>(a.get()))
        {
            qDebug("UPnP Success, msg: %s", p->message().c_str());
            //addConsoleMessage(tr("UPnP/NAT-PMP: Port mapping successful, message: %1")
            //                  .arg(misc::toQString(p->message())), "blue");
        }

        a = m_session->pop_alert();
    }

    // deferred transfers loading and files sharing
    if (!m_fastTransfers.empty()) {
        QList<QString> keys = m_fastTransfers.keys();
        int counter = 10;

        while(!keys.empty() && counter != 0 ) {
            QString key = keys.takeFirst();
            libed2k::transfer_resume_data trd = m_fastTransfers.take(key);
            libed2k::add_transfer_params atp;
            QString filepath = QDir(m_currentPath).filePath(misc::toQStringU(trd.m_filename.m_collection));
            boost::shared_ptr<libed2k::base_tag> onDisk = trd.m_fast_resume_data.getTagByNameId(libed2k::CT_EMULE_RESERVED1);

            Q_ASSERT(onDisk);

            if (QFile::exists(filepath) || !onDisk->asBool()) {
                atp.seed_mode = false;
                // make full path for transfer startup
                atp.file_path = filepath.toUtf8().constData();
                atp.file_size = trd.m_filesize;
                atp.file_hash = trd.m_hash;

                if (trd.m_fast_resume_data.count() > 0) {
                    atp.resume_data = const_cast<std::vector<char>* >(
                        &trd.m_fast_resume_data.getTagByNameId(libed2k::FT_FAST_RESUME_DATA)->asBlob());
                }

                QED2KHandle h = addTransfer(atp);
                m_sharedFiles << h.hash();
                boost::shared_ptr<libed2k::base_tag> addDt = trd.m_fast_resume_data.getTagByNameId(libed2k::CT_EMULE_RESERVED2);

                if (addDt) {
                    m_addTimes.insert(h.hash(), QDateTime::fromString(misc::toQStringU(addDt->asString()), Qt::ISODate));
                }
            } else {
                qDebug() << "fast resume data file" << key << " lost target file, remove resume data";
                if (QFile::remove(QDir(misc::metadataDirectory(m_currentPath)).filePath(key))) {
                    qDebug() << "fast resume data file erased";
                }
            }

            --counter;
        }
    } else {
        int counter = 4;
        while(!m_pendingFiles.empty() && counter != 0) {
            makeTransferParametersAsync(m_pendingFiles.takeFirst());
            --counter;
        }
    }
}
//	The network commandMessage method
void commandMessage(std::string text, IClientSocket *socket)
{
	std::string command, option, data;
	decodeMessage(text,command,option,data);
	
	fusion->errlog << "command = " << command << ", option = " << option << ", data = " << data << std::endl;
	
	//	If all strings are empty, error occured, a blank
	//	string, or messed up string	cannot be processed
	if(command.empty() == true && option.empty() == true && data.empty() == true) return;
	
	if(socket == state.client)	clientMessage(command,option,data,socket);
	else						serverMessage(command,option,data,socket);
	
	/*
		Client/Server commands go here, where they are not resolved
		in the specific clientMessage/serverMessage methods
	*/	
	
	//	Client/Server command: both can change their userName they are chatting with
	if(command == "setUsername")
	{
		if(option.empty() == true){
			//	No ID passed with this command
			
			//	WAITING CLIENT
			if(state.enableClient == true && getConnected() == "Connect"){
				remoteMessage("/newClient,"+data);
			}else{
				std::string name;
				std::string idcode = state.id;

				if(state.enableClient == true){
					if(getConnected() == "Disconnect")	name	= state.username;
					else								socket	= state.client;
				}else if(state.enableServer == true){
					if(socket == NULL)					name	= state.username;
					else								idcode	= idstring(socket);
				}
				
				clientMessage("/info,socket = "+idcode);
				remoteMessage("/setUsername,"+name+";"+data+":"+idcode,socket);
			}
		}else{
			//	ID was passed with this command
			
			size_t pos = option.find(";");
			if(pos > 0){
				std::string oldUser = option.substr(0,pos);
				std::string newUser = option.substr(pos+1);
				
				if(renameUser(oldUser,newUser,data) == true){
					broadcastMessage("/setUsername,"+option+":"+data, socket);
				}else{
					clientMessage("/error,userFound");
				}
			}else{
				updateUsername(option.substr(1));
			}
		}
	}
	
	if(command == "quit") closeApp();
}
void serverMessage(std::string text)
{
	std::string command, option, data;
	decodeMessage(text,command,option,data);
	serverMessage(command, option, data, NULL);
}
示例#17
0
void FKSimpleCore::installComponents(){
    connect(_realmComponent,SIGNAL(messageRequested(QString)),SLOT(realmMessage(QString)));
    connect(_serverComponent,SIGNAL(messageRequested(QString)),SLOT(serverMessage(QString)));
    connect(_clientComponent,SIGNAL(messageRequested(QString)),SLOT(clientMessage(QString)));
}