void SendThread::run()
{
QTcpSocket client;
qDebug() << "Thread Descriptor :" << socketDescriptor;
if (!client.setSocketDescriptor(socketDescriptor))
{
qDebug() << client.error();
return;
}
qDebug() << "Thread : Connected";

//send File
QFile inputFile(FILENAME);
QByteArray read;
inputFile.open(QIODevice::ReadOnly);
while(1)
{
read.clear();
read = inputFile.read(32768*8);
qDebug() << "Read : " << read.size();
if(read.size()==0)
break;

qDebug() << "Written : " << client.write(read);
client.waitForBytesWritten();
read.clear();
}
inputFile.close();
client.disconnectFromHost();
client.waitForDisconnected();
qDebug() << "Thread : File transfer completed";
}
Exemplo n.º 2
0
Connection* SharedDaemon::createCustomConnection(int listenSocketNum, void *data)
{
    SharedDaemon::ConnectionType typeOfConnection = *((SharedDaemon::ConnectionType*)(data));
    if(typeOfConnection == SharedDaemon::WSocketConnection )
    {
        int descriptor = SingleThreadedAcceptSocket(listenSocketNum);

        QTcpSocket * tcpSocket = new QTcpSocket();
        tcpSocket->setSocketDescriptor( descriptor, QAbstractSocket::ConnectedState );
        tcpSocket->waitForReadyRead();

        QString request = QString(tcpSocket->readAll());

        if(request.size() == 0) /// firefox works differently, and sends 0 size messages
        {
            tcpSocket->close();
            tcpSocket->disconnectFromHost();
            tcpSocket->waitForDisconnected();
            tcpSocket->deleteLater();

            descriptor = SingleThreadedAcceptSocket(listenSocketNum);
            tcpSocket = new QTcpSocket();
            tcpSocket->setSocketDescriptor( descriptor, QAbstractSocket::ConnectedState );
            tcpSocket->waitForReadyRead();
            request = QString(tcpSocket->readAll());
        }

        return new WebSocketConnection(tcpSocket,request);
    }
    else
    {
        int descriptor = SingleThreadedAcceptSocket(listenSocketNum);
        return new SocketConnection(descriptor);
    }
}
void lsLogServitemThreated::run()
{
    QTcpSocket tcpSocket;

    if (!tcpSocket.setSocketDescriptor(socketDescriptor)) {
        emit error(tcpSocket.error());
        return;
    }

    while ( tcpSocket.isOpen() )
    {
        QByteArray block;
        QDataStream out(&block, QIODevice::WriteOnly);
        out.setVersion(QDataStream::Qt_4_0);
        out << (quint16)0;
        out << text;
        text.clear();
        out.device()->seek(0);
        out << (quint16)(block.size() - sizeof(quint16));

        tcpSocket.write(block);
        tcpSocket.flush();

        while ( tcpSocket.isOpen() && text.isEmpty() )
        {
            msleep(100);
        }
    }

    tcpSocket.disconnectFromHost();
    tcpSocket.waitForDisconnected();
}
Exemplo n.º 4
0
void QServerThread::run()
{
   QTcpSocket qsocket;
   if( qsocket.setSocketDescriptor( sd) == false)
   {
      AFERROR("QThreadServer::run: Can't set socket descriptor.\n");
      return;
   }

   af::Msg* msg = new af::Msg;
   if( afqt::recvMessage( &qsocket, msg))
   {
      if( recvMessage_handler_ptr == NULL )
      {
         emit newmsg( msg);
      }
      else
      {
         if( recvMessage_handler_ptr( &qsocket, msg) == false)
         {
            emit newmsg( msg);
         }
      }
   }
   qsocket.disconnectFromHost();
   if( qsocket.state() != QAbstractSocket::UnconnectedState ) qsocket.waitForDisconnected();
}
Exemplo n.º 5
0
void SharedDaemon::AddNewClient(const std::string &host, const stringVector &args, void *cbdata)
{
    /// Send appropriate message for TCP or WebConnection
    void** data = (void**)cbdata;
    ConnectionType typeOfConnection = *((ConnectionType*)(data[0]));
    QAbstractSocket* socket = static_cast<QAbstractSocket*>(data[1]);
    ViewerState* viewerState = static_cast<ViewerState*>(data[2]);

    JSONNode node;

    QString hostname = typeOfConnection == TcpConnection ? socket->localAddress().toString():
                        dynamic_cast<QWsSocket*>(socket)->internalSocket()->localAddress().toString();

    if(hostMap.contains(hostname)) hostname = hostMap[hostname];

    node["host"] = hostname.toStdString(); //host
    node["port"]  = args[7]; //port
    node["version"] = args[2]; //version
    node["securityKey"] = args[9]; //key
    node["numStates"] = viewerState->GetNumStateObjects(); //number of states

    JSONNode::JSONArray rpc_array = JSONNode::JSONArray();

    for(size_t i = 0; i < ViewerRPC::MaxRPC; ++i) {
        rpc_array.push_back(ViewerRPC::ViewerRPCType_ToString((ViewerRPC::ViewerRPCType)i));
    }
    node["rpc_array"] = rpc_array;

    if(typeOfConnection == TcpConnection)
    {
        QTcpSocket *tsocket = dynamic_cast<QTcpSocket*>(socket);

        std::string message = node.ToString();
        tsocket->write(message.c_str(),message.length());

        if(tsocket->state() != QAbstractSocket::UnconnectedState)
            tsocket->waitForBytesWritten();
        tsocket->disconnectFromHost();
        if(tsocket->state() != QAbstractSocket::UnconnectedState)
            tsocket->waitForDisconnected();
        //HKTODO: Do not delete connection (test fix for ORNL machines)
        //tsocket->deleteLater();
    }
    else
    {
        QWsSocket *wsocket = dynamic_cast<QWsSocket*>(socket);

        wsocket->write(QString(node.ToString().c_str()));
        wsocket->flush();
        if(wsocket->internalSocket()->state() != QAbstractSocket::UnconnectedState)
            wsocket->internalSocket()->waitForBytesWritten();

        wsocket->close("");
        wsocket->internalSocket()->disconnectFromHost();
        if(wsocket->internalSocket()->state() != QAbstractSocket::UnconnectedState)
            wsocket->internalSocket()->waitForDisconnected();
        wsocket->deleteLater();
    }
}
Exemplo n.º 6
0
void ConnectionListener::incomingConnection(qintptr socketDescriptor)
{
    if (m_accept) {
        emit log("Listener", "New connection: accepted.");
        m_accept = false;
        emit clientSuccessfullyConnected();

        m_proxy.reset(new Proxy(m_mapData,
                                m_pathMachine,
                                m_prespammedPath,
                                m_groupManager,
                                m_mumeClock,
                                m_mapCanvas,
                                socketDescriptor,
                                this));

        if (getConfig().connection.proxyThreaded) {
            m_thread.reset(new QThread);
            m_proxy->moveToThread(m_thread.get());

            // Proxy destruction stops the thread which then destroys itself on completion
            connect(m_proxy.get(), &QObject::destroyed, m_thread.get(), &QThread::quit);
            connect(m_thread.get(), &QThread::finished, m_thread.get(), &QObject::deleteLater);
            connect(m_thread.get(), &QObject::destroyed, this, [this]() {
                m_accept = true;
                m_proxy.release();
                m_thread.release();
            });

            // Make sure if the thread is interrupted that we kill the proxy
            connect(m_thread.get(), &QThread::finished, m_proxy.get(), &QObject::deleteLater);

            // Start the proxy when the thread starts
            connect(m_thread.get(), &QThread::started, m_proxy.get(), &Proxy::start);
            m_thread->start();

        } else {
            connect(m_proxy.get(), &QObject::destroyed, this, [this]() {
                m_accept = true;
                m_proxy.release();
            });
            m_proxy->start();
        }

    } else {
        emit log("Listener", "New connection: rejected.");
        QTcpSocket tcpSocket;
        if (tcpSocket.setSocketDescriptor(socketDescriptor)) {
            QByteArray ba("\033[1;37;41mYou can't connect to MMapper more than once!\r\n"
                          "Please close the existing connection.\033[0m\r\n");
            tcpSocket.write(ba);
            tcpSocket.flush();
            tcpSocket.disconnectFromHost();
            tcpSocket.waitForDisconnected();
        }
    }
}
Exemplo n.º 7
0
void CmdServer::onNewConnection()
{
	QTcpSocket *sk = listenner_.nextPendingConnection();
	sk->waitForDisconnected(50);
	QString cmd = sk->readAll();
	QString handlerStr  = cmd.section(" ", 0, 0);
	QObject *handlerObj = handlers_[handlerStr];
	if (handlerObj)
		QMetaObject::invokeMethod(handlerObj, "commandReceived", Q_ARG(QString, cmd.section(" ", 1)));
}
Exemplo n.º 8
0
void TCPThread::run() {
    QTcpSocket tcpSocket;
    if (!tcpSocket.setSocketDescriptor(socketDescriptor_)) {
        emit error(tcpSocket.error());
        return;
    }

    qint64 x = 0;
    while(x < data.size()){
        qint64 y= tcpSocket.write(data);
        x+= y;
        qDebug()<< x << " to: " << socketDescriptor_;
    }

    tcpSocket.disconnectFromHost();
    tcpSocket.waitForDisconnected();


}
 void UekiAccessServerThread::run()
 {
     QTcpSocket tcpSocket;
     if (!tcpSocket.setSocketDescriptor(socketDescriptor)) {
         emit error(tcpSocket.error());
         return;
     }

     QByteArray block;
     QDataStream out(&block, QIODevice::WriteOnly);
     out.setVersion(QDataStream::Qt_4_0);
     out << (quint16)0;
     out.device()->seek(0);
     out << (quint16)(block.size() - sizeof(quint16));

     tcpSocket.write(block);
     tcpSocket.disconnectFromHost();
     tcpSocket.waitForDisconnected();
 }
Exemplo n.º 10
0
//! [1]
void FortuneThread::run()
{
    QTcpSocket tcpSocket;
//! [1] //! [2]
    if (!tcpSocket.setSocketDescriptor(socketDescriptor)) {
        emit error(tcpSocket.error());
        return;
    }
//! [2] //! [3]

    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_0);
    out << text;
//! [3] //! [4]

    tcpSocket.write(block);
    tcpSocket.disconnectFromHost();
    tcpSocket.waitForDisconnected();
}
Exemplo n.º 11
0
void
ITunesScript::transmit( const QString& data )
{
    // thread-safe, basically
    int const port = m_listener->GetPort();

    LOGL( 3, "ITunesScript data being sent " << data << " to port " << port );

    QTcpSocket socket;
    socket.connectToHost( QHostAddress::LocalHost, port );
    if ( socket.waitForConnected( 1000 ) ) //FIXME hangs GUI thread?
    {
        int bytesWritten = socket.write( data.toUtf8() );
        socket.flush();
        socket.waitForDisconnected( 1000 ); //FIXME hangs?

        if ( bytesWritten == -1 )
        {
            LOGL( 1, "Sending submission through socket failed." )
        }
    }
Exemplo n.º 12
0
void SharedDaemon::AddNewClient(const std::string &host, const stringVector &args, void *cbdata)
{
    /// Send appropriate message for TCP or WebConnection
    void** data = (void**)cbdata;
    ConnectionType typeOfConnection = *((ConnectionType*)(data[0]));
    QAbstractSocket* socket = static_cast<QAbstractSocket*>(data[1]);

    JSONNode node;

    node["host"] = args[5]; //host
    node["port"]  = args[7]; //port
    node["version"] = args[2]; //version
    node["securityKey"] = args[9]; //key

    if(typeOfConnection == TcpConnection)
    {
        QTcpSocket *tsocket = dynamic_cast<QTcpSocket*>(socket);

        std::string message = node.ToString();
        tsocket->write(message.c_str(),message.length());
        tsocket->waitForBytesWritten();
        tsocket->disconnectFromHost();
        tsocket->waitForDisconnected();
        tsocket->deleteLater();
    }
    else
    {
        QWsSocket *wsocket = dynamic_cast<QWsSocket*>(socket);

        wsocket->write(QString(node.ToString().c_str()));
        wsocket->flush();
        wsocket->internalSocket()->waitForBytesWritten();

        wsocket->close();
        wsocket->internalSocket()->disconnectFromHost();
        wsocket->internalSocket()->waitForDisconnected();
        wsocket->deleteLater();
    }
}
Exemplo n.º 13
0
void QxTransaction::executeClient(IxService * pService, const QString & sMethod)
{
   if ((pService == NULL) || sMethod.isEmpty()) { qAssert(false); return; }
   if (pService->getServiceName().isEmpty()) { pService->setMessageReturn(qx_bool(QX_ERROR_SERVICE_NOT_SPECIFIED, "[QxOrm] empty service name")); return; }
   pService->registerClass();

   QTcpSocket socket;
   QString serverName = QxConnect::getSingleton()->getIp();
   long serverPort = QxConnect::getSingleton()->getPort();
   socket.connectToHost(serverName, serverPort);
   if (! socket.waitForConnected(QxConnect::getSingleton()->getMaxWait()))
   { pService->setMessageReturn(qx_bool(QX_ERROR_SERVER_NOT_FOUND, "[QxOrm] unable to connect to server")); return; }

   if (m_sTransactionId.isEmpty())
   { setTransactionId(QUuid::createUuid().toString()); }

   setIpSource(socket.localAddress().toString());
   setPortSource(socket.localPort());
   setIpTarget(serverName);
   setPortTarget(serverPort);
   setServiceName(pService->getServiceName());
   setServiceMethod(sMethod);
   setTransactionBegin(QDateTime::currentDateTime());
   setInputParameter(pService->getInputParameter_BaseClass());

   qx_bool bWriteOk = writeSocket(socket);
   if (! bWriteOk) { pService->setMessageReturn(qx_bool(QX_ERROR_SERVICE_WRITE_ERROR, QString("[QxOrm] unable to write request to socket : '") + bWriteOk.getDesc() + QString("'"))); return; }
   qx_bool bReadOk = readSocket(socket);
   if (! bReadOk) { pService->setMessageReturn(qx_bool(QX_ERROR_SERVICE_READ_ERROR, QString("[QxOrm] unable to read reply from socket : '") + bReadOk.getDesc() + QString("'"))); return; }

   pService->setOutputParameter(getOutputParameter());
   pService->setMessageReturn(getMessageReturn());
   setTransactionEnd(QDateTime::currentDateTime());
   socket.disconnectFromHost();
   if (socket.state() != QAbstractSocket::UnconnectedState)
   { socket.waitForDisconnected(QxConnect::getSingleton()->getMaxWait()); }
}
Exemplo n.º 14
0
void QxThread::run()
{
    m_bIsRunning = true;
    while (m_bIsRunning)
    {
        while (m_iSocketDescriptor == 0) {
            if (! m_bIsRunning) {
                return;
            }
            msleep(5);
        }
        QTcpSocket socket;
        doProcess(socket);
        socket.disconnectFromHost();
        if (socket.state() != QAbstractSocket::UnconnectedState)
        {
            socket.waitForDisconnected(QxConnect::getSingleton()->getMaxWait());
        }
        clearData();
        if (m_pThreadPool) {
            m_pThreadPool->setAvailable(this);
        }
    }
}
Exemplo n.º 15
0
void Task::run() {
    QTcpSocket socket;
    QString answerID,type,lang;
    socket.setSocketDescriptor(this->socketDescriptor);
    socket.waitForReadyRead();
    data=socket.readAll();
    dateTime = QDateTime::currentDateTime();
    QStringList params;
    QFile file;
    token=QUuid::createUuid().toString();
    token=token.left(token.size()-1);
    token=token.right(token.size()-1);
    conName=cdb.connectionName()+QString::number(id);
    {
        QSqlDatabase db=QSqlDatabase(QSqlDatabase::cloneDatabase(cdb,conName));
        db.open();
        QSqlQuery query(db);

        sc = engine.evaluate("(" + QString(data) + ")");
        QScriptValueIterator it(sc);
        while (it.hasNext()) {
            it.next();
            if (it.name()=="program")
            {
                program_id=it.value().toString();
                token=token+"-"+program_id;
                params<<program_id;
                if (!params.at(0).isNull()||!params.at(0).isEmpty())
                {
                    query.exec("INSERT INTO math.answer (an_user_id, an_token, an_complete,  an_start_date, an_cp_id) VALUES (0, '"+token+"', 0,  '"+dateTime.toString("yyyy-MM-dd hh:mm:ss")+"', '"+program_id+"');");
                    query.exec("SELECT @an_id:=LAST_INSERT_ID();");
                    query.next();
                    answerID = query.value(0).toString();
                    params<<answerID;
                }
            }
            if (it.name()=="exec")
            {
                type=it.value().toString();
            }
            if (it.name()=="lang")
            {
                lang=it.value().toString();
                params<<lang;
            }
            if (it.value().isObject())
            {
                if (type=="execute")
                {
                    QScriptValueIterator sit(it.value());
                    while (sit.hasNext()) {
                        sit.next();
                        if (sit.value().isObject())//--- jeigu tai failas
                        {
                            QScriptValueIterator sits(sit.value());
                            while (sits.hasNext()) {
                                sits.next();
                                if (sits.value().toString()=="file")
                                {
                                    sits.next();

                                    query.exec("SELECT @pp_id:=pp_id FROM math.program_param_list,math.program_param WHERE ppl_pp_id=pp_id and ppl_cp_id="+program_id+" and pp_name='"+sits.name()+"'");
                                    cout << program_id.toStdString() << " program id \n";
                                    query.prepare("INSERT INTO math.answer_param_value (pv_value, pv_pp_id) VALUES (:val, @pp_id);");
                                    query.bindValue(":val",sits.value().toString());
                                    query.exec();
                                    query.exec("SELECT @pv_id:=LAST_INSERT_ID();");
                                    query.exec("INSERT INTO math.answer_param_list (anpl_an_id, anpl_pv_id) VALUES (@an_id, @pv_id)");
                                    query.exec("SELECT BD_DATA FROM math.big_data where BD_ID="+sits.value().toString());
                                    query.next();
                                    file.setFileName(this->binaryPath+"/binaries/"+program_id+"/"+sits.value().toString());
                                    params<<this->binaryPath+"/binaries/"+program_id+"/"+sits.value().toString();
                                    if (file.open(QIODevice::WriteOnly | QIODevice::Text))
                                    {
                                        QTextStream out(&file);
                                        out << query.value(0).toByteArray();
                                    }
                                    file.close();
                                }
                            }
                        }
                        else {
                            params<<sit.value().toString();
                            query.exec("SELECT @pp_id:=pp_id FROM math.program_param_list,math.program_param WHERE ppl_pp_id=pp_id and ppl_cp_id="+program_id+" and pp_name='"+sit.name()+"'");
                            query.prepare("INSERT INTO math.answer_param_value (pv_value, pv_pp_id) VALUES (:val, @pp_id);");
                            query.bindValue(":val",sit.value().toString());
                            query.exec();
                            query.exec("SELECT @pv_id:=LAST_INSERT_ID();");
                            query.exec("INSERT INTO math.answer_param_list (anpl_an_id, anpl_pv_id) VALUES (@an_id, @pv_id)");
                        }
                    }
                }
            }
        }
    }
    QSqlDatabase::removeDatabase(conName);
    if (type=="execute")
    {
        if (params.at(0).isNull()||params.at(0).isEmpty())
        {
            socket.write("Nurodykite programa");
            socket.waitForBytesWritten();
        }
        else  emit this->requestExecute(params);
    }
    if (type=="compile")
    {
        if (params.at(0).isNull()||params.at(0).isEmpty())
        {
            socket.write("Nurodykite programa");
            socket.waitForBytesWritten();
        }
        else  emit this->requestCompile(params);
    }
    // qDebug()<<QString(data);
    socket.write(token.toLatin1());
    socket.flush();
    socket.waitForBytesWritten();
    socket.waitForDisconnected();
    socket.close();

}
Exemplo n.º 16
0
void MySocketClient::run()
{
    cout << "Starting MySocketClient::run()" << endl;
    QTcpSocket tcpSocket;

    // ON RECUPERE LE LIEN DE COMMUNICATION AVEC LE CLIENT ET ON QUITTE EN CAS
    // DE PROBLEME...
    if (!tcpSocket.setSocketDescriptor(socketDescriptor)) {
        emit error(tcpSocket.error());
        return;
    }

    // SI LE CLIENT N'A PAS EU LE TEMPS DE NOUS TRANSMETTRE SA REQUETE,
    // ON SE MET EN ATTENTE PENDANT 1s
    while (tcpSocket.bytesAvailable() < (int)sizeof(quint16)) {
        if (!tcpSocket.waitForReadyRead( 1000 )) {
                cout << "(EE) Erreur de time out !" << endl;
                return;
        }
    }

    // LA PREMIERE REQUETE CORRESPOND AU GET NORMALEMENT
    char tampon[65536];

    // ON RECUPERE LA REQUETE ET SA TAILLE
    int lineLength = tcpSocket.readLine(tampon, 65536);

    // ON TRANSFORME LA REQUETE SOUS FORME DE STRING
    string ligne( tampon );
    ligne = removeEndLine( ligne );

    // ON AFFICHE LA COMMANDE A L'ECRAN...
    cout << "COMMANDE : =>" << ligne << "<=" << endl;

   int pos1 = ligne.find(" ");
   string cmde = ligne.substr(0, pos1);
   ligne = ligne.substr(pos1+1, ligne.length()-pos1);

   cout << "1. : " << cmde  << endl;
   cout << "2. : " << ligne << endl;

   int pos2 = ligne.find(" ");
   string file = ligne.substr(0, pos2);
   ligne = ligne.substr(pos2+1, ligne.length()-pos2);

   cout << "3. : " << file  << endl;
   cout << "4. : '" << ligne << "'" << endl;

        while( tcpSocket.bytesAvailable() > 0 ){
        lineLength = tcpSocket.readLine(tampon, 65536);
        if (lineLength != -1 &&  lineLength != 0) {
                //cout << "C" << lineLength << " :: " << tampon;
        }else if(lineLength != -1 ){
                cout << "Nothing for the moment !" << endl;
        }
    }

    QString str = tr("./public_html") + tr(file.c_str()); //Adresse du fichier ou dossier (./public_html//essai.html)
    statistiques->AddPeer(tcpSocket.peerAddress().toString());
    statistiques->AddRequete(str);
    QByteArray temp("");
    QFile f( str );
    QDir  d( str );
    bool found;

    if( f.exists() == true )
    {
        statistiques->AddFile(f.fileName());
    }


    found = str.contains("statistiques.html", Qt::CaseInsensitive) ||str.contains("???", Qt::CaseInsensitive) ;
    if(found==true)
    {
       temp = statistiques->GenerateHtml();

    }

    else
    {
        if(!MyHash->contains( str ))    /* si le hash ne contient pas ce fichier*/
        {                               /*alors on ajoute la page dans Hash*/

            cout << " - Chemin du fichier : " << str.toStdString() << endl;
            cout << " - isFile :          : " << f.exists() << endl;
            cout << " - isDirectory       : " << d.exists() << endl;

            if( f.exists() == false &&  d.exists() == false )
            {
                str = tr("erreur404");
            }
            else if( d.exists() == true )//LE CHAMP SAISI EST UN REPERTOIRE
            {
                QByteArray* NewByteArray = new QByteArray;

                *NewByteArray = "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Type: text/html\r\n\n";
                for(int i = 0 ; i < d.entryList().size() ; i++)
                {
                    *NewByteArray+=QByteArray("<p>") + QByteArray("<a href=\"")+QString::fromStdString(file);
                    if(QString::compare(QString::fromStdString(file),QString("/")))//Dans le cas d'un sous dossier il faut rajouter un / dans le path
                        *NewByteArray+=QByteArray("/");
                    *NewByteArray+=d.entryList()[i]+QByteArray("\">")+d.entryList()[i] +QByteArray("</a></p>");
                }
                MyHash->insert(str, NewByteArray);
                *MyHashSize+=NewByteArray->size();
                MyHashKeys->append(str);
            }
            else if( f.exists() == true )/* On ajoute le fichier dans le Hash en ByteArray*/
            {

                QFile* file = new QFile( str );

                 if (!file->open(QIODevice::ReadOnly))
                 {
                         delete file;
                         return;
                 }

                 /*concatener des types QByteArray? avec le +
                 utiliser l'en tête ci-dessous
                 HTTP/1.1 200 OK
                 Connection: close
                 Content-Type: text/html
                 construction de cette en-tête HTTP, il est nécessaire de la faire suivre par un saut de ligne
                 avant la partie html*/

                 QByteArray* NewByteArray = new QByteArray;

                 found = str.contains(".jpg", Qt::CaseInsensitive);
                 if (found==true)
                 {
                     *NewByteArray = "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Type: image/jpeg\r\n\n";
                     // creation d'un QbyteArray indiquant une image au format jpeg
                 }

                 found = str.contains(".html", Qt::CaseInsensitive);
                 if (found==true)
                 {
                     *NewByteArray = "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Type: text/html\r\n\n";
                     // creation d'un QbyteArray indiquant un texte au format html
                 }

                 found = str.contains(".pdf", Qt::CaseInsensitive);
                 if (found==true)
                 {
                     *NewByteArray = "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Type: application/pdf\r\n\n";
                     // creation d'un QbyteArray indiquant un texte au format html
                 }

                 found = str.contains(".mp3", Qt::CaseInsensitive);
                 if (found==true)
                 {
                     *NewByteArray = "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Type: audio/mp3\r\n\n";
                     // creation d'un QbyteArray indiquant un texte au format html
                 }
                 found = str.contains(".doc", Qt::CaseInsensitive) || str.contains(".docx", Qt::CaseInsensitive);
                 if (found==true)
                 {
                     *NewByteArray = "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document\r\n\n";
                 }
                 found = str.contains(".pptx", Qt::CaseInsensitive);
                 if (found==true)
                 {
                     *NewByteArray = "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Type: application/vnd.ms-powerpoint\r\n\n";
                 }


                 *NewByteArray += file->readAll();


                 // temp a été redimensionné automatiquement

                 file->close();
                 MyHash->insert(str, NewByteArray);/*insère bytearray dans Hash*/
                 *MyHashSize+=NewByteArray->size();
                 MyHashKeys->append(str);
            }
            else
            {
                 str =tr("erreur404");
            }


        }
        else //requete deja dans le hash        
            MyHashKeys->append(MyHashKeys->takeAt(MyHashKeys->lastIndexOf(str))); //on met la key en derniere position de la liste (premiere pos = LRU)

        temp = *MyHash->value(str);

    }
    if(str.contains("erreur404"))
        statistiques->AddErreur404();
    else
        statistiques->AddTraitee();
    statistiques->AddOctets(temp.size());
    tcpSocket.write(temp);


    //Gestion de la taille du cache, suppression du LRU (last recently used)
    while(*MyHashSize > CACHE_SIZE && MyHash->count()>1 )//Tant qu'on ne dépasse pas la taille max et qu'il reste plus d'un item dans le Hash (on ne veut pas supprimer erreur 404)
    {
        *MyHashSize-=MyHash->value(MyHashKeys->first())->size();//On soustrait la taille du fichier qu'on va enlever
        delete MyHash->value(MyHashKeys->first());
        MyHash->remove(MyHashKeys->first());//On retire le LRU du cache
        MyHashKeys->removeFirst();//on enlève la LRU key

    }

//    for(int i = 0;i<MyHashKeys->size();i++)
//        cout<<MyHashKeys->value(i).toStdString()<<endl;
//    cout<<*MyHashSize<<endl;

    statistiques->SetCacheSize(*MyHashSize);
    cout << "Finishing MySocketClient::run()" << endl;

//! [2] //! [3]
    tcpSocket.disconnectFromHost();
    tcpSocket.waitForDisconnected();


}
Exemplo n.º 17
0
void SharedDaemon::handleConnection()
{
    QTcpSocket *socket = nextPendingConnection();

    if ( !socket ) return;

    //the connecting socket should have sent password..
    //the client should be sending a password..
    socket->waitForReadyRead();

    if (!socket->bytesAvailable())
    {
        //std::cout << "no bytes available to read" << std::endl;
        socket->close();
        return;
    }
    std::cout << "user: "******" is attempting to connect" << std::endl;

    QAbstractSocket* finalSocket = NULL;
    ConnectionType typeOfConnection = TcpConnection;

    QByteArray result = socket->readAll();
    QString input(result);

    /// initial connection must pass password, but can optionally pass
    /// whether the client canRender and what the threshold value should be..
    JSONNode output;

    /// check if this is a WebSocketConnection
    QString response = "";
    if(input.startsWith("{") && ParseInput(input,output))
    {
        finalSocket = socket;
        typeOfConnection = TcpConnection;
    } /// check if this is a WebSocketConnection..
    else if(QWsSocket::initializeWebSocket(result,response))
    {
        /// this is a websocket connection, respond and get frame..
        socket->write(response.toLatin1());
        socket->flush();

        QEventLoop loop;

        matched_input = "";

        QWsSocket* wssocket = new QWsSocket(socket);

        connect(wssocket,SIGNAL(frameReceived(QString)),
                this,SLOT(getPasswordMessage(QString)));

        connect(wssocket,SIGNAL(frameReceived(QString)),
                &loop,SLOT(quit()));

        /// wait for password to be sent ..
        /// std::cout << "waiting for password from websocket" << std::endl;
        loop.exec();

        disconnect(wssocket,SIGNAL(frameReceived(QString)),
                this,SLOT(getPasswordMessage(QString)));

        disconnect(wssocket,SIGNAL(frameReceived(QString)),
                &loop,SLOT(quit()));

        //std::cout << matched_input.toStdString() << std::endl;

        if( !ParseInput(matched_input,output) )
        {
            //std::cout << "passwords do not match: "
            //          << matched_password.toStdString()
            //          << " " << password << std::endl;

            wssocket->close("passwords do not match or operation timed out");

            if(socket->state() != QAbstractSocket::UnconnectedState)
                socket->waitForDisconnected();

            wssocket->deleteLater();
            return;
        }

        finalSocket = wssocket;
        typeOfConnection = WSocketConnection;

    } /// not sure what connection this is, reject it..
    else
    {
        //send rejection notice..
        std::string errorString = "Unknown connection..";
        socket->write(errorString.c_str(),errorString.length());
        socket->disconnectFromHost();
        socket->waitForDisconnected();
        return;
    }

    //passwords match enable RemoteProcess and get port remote Process is listening to.
    //send host,port,security_key and whatever else so that remote machine can successfully reverse connect
    std::string program = "remoteApp";
    std::string clientName = "newclient1";

    ViewerClientConnection *newClient = new
            ViewerClientConnection(subject->GetViewerState(),
                                   this,
                                   clientName.c_str(),
                                   true);

    ViewerClientAttributes& clientAtts = newClient->GetViewerClientAttributes();
    JSONNode::JSONObject jo = output.GetJsonObject();

    clientAtts.SetExternalClient(true);

    if(jo.count("name") == 0 || jo["name"].GetString().size() == 0)
        clientAtts.SetTitle(socket->peerAddress().toString().toStdString());
    else
        clientAtts.SetTitle(jo["name"].GetString());

    if(jo.count("windowIds") > 0 && jo["windowIds"].GetType() == JSONNode::JSONARRAY)
    {
        const JSONNode::JSONArray& array = jo["windowIds"].GetArray();

        for(size_t i = 0; i < array.size(); ++i)
        {
            const JSONNode& node = array[i];

            if(node.GetType() != JSONNode::JSONINTEGER)
                continue;

            std::cout << clientAtts.GetTitle() <<  " requesting window: " << node.GetInt() << " " << std::endl;
            clientAtts.GetWindowIds().push_back(node.GetInt());
        }
    }

    if(jo.count("geometry") > 0)
    {
        std::string geometry = jo["geometry"].GetString();

        /// split into width & height...
        size_t index = geometry.find("x");
        if(index != std::string::npos && index != 0 && index != geometry.size()-1)
        {
            int geometryWidth = atoi(geometry.substr(0,index).c_str());
            int geometryHeight = atoi(geometry.substr(index+1).c_str());

            clientAtts.SetImageWidth(geometryWidth);
            clientAtts.SetImageHeight(geometryHeight);
            //std::cout << "geometry: " << clientAtts.clientWidth << " " << clientAtts.clientHeight << std::endl;
        }
    }

    /// advanced rendering can be true or false (image only), or string none,image,data
    if(jo.count("canRender") == 0) {
        clientAtts.SetRenderingType(ViewerClientAttributes::None);
        clientAtts.GetRenderingTypes().push_back(ViewerClientAttributes::None);
    }
    else
    {
        const JSONNode& node = jo["canRender"];
        QString type = node.GetString().c_str();
        type = type.toLower();

        /// TODO: remove the boolean check and make all current clients comply..
        if(node.GetType() == JSONNode::JSONBOOL) {
            clientAtts.SetRenderingType( node.GetBool() ? ViewerClientAttributes::Image :
                                                          ViewerClientAttributes::None);
            clientAtts.GetRenderingTypes().push_back(node.GetBool() ? ViewerClientAttributes::Image :
                                                                      ViewerClientAttributes::None);
        }
        else if(node.GetType() == JSONNode::JSONSTRING)
        {
            if(type == "image") {
                clientAtts.SetRenderingType(ViewerClientAttributes::Image);
                clientAtts.GetRenderingTypes().push_back((int)ViewerClientAttributes::Image);
            }
            else if(type == "data") {
                clientAtts.SetRenderingType(ViewerClientAttributes::Data);
                clientAtts.GetRenderingTypes().push_back((int)ViewerClientAttributes::Data);
            }
            else {
                clientAtts.SetRenderingType(ViewerClientAttributes::None);
                clientAtts.GetRenderingTypes().push_back((int)ViewerClientAttributes::None);
            }
        }
        else
        {
            clientAtts.SetRenderingType(ViewerClientAttributes::None);
            clientAtts.GetRenderingTypes().push_back((int)ViewerClientAttributes::None);
        }
    }
    stringVector args;

    /// assign whether connection is of type WebSocket or TCPConnection
    /// Register Type & Register Callback
    RemoteProcess::SetCustomConnectionCallback(createCustomConnection,&typeOfConnection);

    TRY
    {
        void* data[3];
        data[0] = &typeOfConnection;
        data[1] = (void*)finalSocket;
        data[2] = (void*)subject->GetViewerState();

        newClient->LaunchClient(program,args,AddNewClient,data,0,0);

        /// Now that client has launched RemoveCallback..
        subject->AddNewViewerClientConnection(newClient);
        std::cout << "user: "******" successfully connected" << std::endl;
    }
    CATCHALL
    {
        std::cout << "user: "******" failed to connected" << std::endl;
        delete newClient;
    }
    ENDTRY

    RemoteProcess::SetCustomConnectionCallback(0,0); /// reset connection..
}
Exemplo n.º 18
0
int main(int argc, char *argv[])
{
    int debugMode = DEBUGMODE;


    if(debugMode)
    {

    } else {
        qInstallMessageHandler(myMessageOutputDisable);

    }

    QDEBUG() << "number of arguments:" << argc;
    QStringList args;
    QDEBUGVAR(RAND_MAX);
    if(argc > 1) {
        QCoreApplication a(argc, argv);
        args = a.arguments();

        QDEBUGVAR(args);

        qRegisterMetaType<Packet>();



        QDEBUG() << "Running command line mode.";

        Packet sendPacket;
        sendPacket.init();
        QString outBuilder;

        QTextStream o(&outBuilder);


        QTextStream out(stdout);

        QDate vDate = QDate::fromString(QString(__DATE__).simplified(), "MMM d yyyy");
        QCoreApplication::setApplicationName("Packet Sender");
        QCoreApplication::setApplicationVersion("version " + vDate.toString("yyyy-MM-dd"));

        QCommandLineParser parser;
        parser.setApplicationDescription("Packet Sender is a Network TCP and UDP Test Utility by Dan Nagle\nSee http://PacketSender.com/ for more information.");
        parser.addHelpOption();
        parser.addVersionOption();

        // A boolean option with a single name (-p)
        QCommandLineOption quietOption(QStringList() << "q" << "quiet", "Quiet mode. Only output received data.");
        parser.addOption(quietOption);


        QCommandLineOption hexOption(QStringList() << "x" << "hex", "Parse data as hex (default).");
        parser.addOption(hexOption);

        QCommandLineOption asciiOption(QStringList() << "a" << "ascii", "Parse data as mixed-ascii (like the GUI).");
        parser.addOption(asciiOption);

        QCommandLineOption pureAsciiOption(QStringList() << "A" << "ASCII", "Parse data as pure ascii (no \\xx translation).");
        parser.addOption(pureAsciiOption);

        // An option with a value
        QCommandLineOption waitOption(QStringList() << "w" << "wait",
                "Wait up to <milliseconds> for a response after sending. Zero means do not wait (Default).",
                "milliseconds");
        parser.addOption(waitOption);

        // An option with a value
        QCommandLineOption fileOption(QStringList() << "f" << "file",
                "Send contents of specified path. Max 1024 for UDP, 10 MiB for TCP.",
                "path");
        parser.addOption(fileOption);


        // An option with a value
        QCommandLineOption bindPortOption(QStringList() << "b" << "bind",
                "Bind port. Default is 0 (dynamic).",
                "port");
        parser.addOption(bindPortOption);


        QCommandLineOption tcpOption(QStringList() << "t" << "tcp", "Send TCP (default).");
        parser.addOption(tcpOption);

        // A boolean option with multiple names (-f, --force)
        QCommandLineOption udpOption(QStringList() << "u" << "udp", "Send UDP.");
        parser.addOption(udpOption);

        // An option with a value
        QCommandLineOption nameOption(QStringList() << "n" << "name",
                                      "Send previously saved packet named <name>. Other options overrides saved packet parameters.",
                                      "name");
        parser.addOption(nameOption);


        parser.addPositionalArgument("address", "Destination address. Optional for saved packet.");
        parser.addPositionalArgument("port", "Destination port. Optional for saved packet.");
        parser.addPositionalArgument("data", "Data to send. Optional for saved packet.");


        // Process the actual command line arguments given by the user
        parser.process(a);

        const QStringList args = parser.positionalArguments();

        bool quiet = parser.isSet(quietOption);
        bool hex = parser.isSet(hexOption);
        bool mixedascii = parser.isSet(asciiOption);
        bool ascii = parser.isSet(pureAsciiOption);
        unsigned int wait = parser.value(waitOption).toUInt();
        unsigned int bind = parser.value(bindPortOption).toUInt();
        bool tcp = parser.isSet(tcpOption);
        bool udp = parser.isSet(udpOption);
        bool ipv6  = false;

        QString name = parser.value(nameOption);

        QString filePath = parser.value(fileOption);


        QString address = "";
        unsigned int port = 0;

        int argssize = args.size();
        QString data, dataString;
        data.clear();
        dataString.clear();
        if(argssize >= 1) {
            address = args[0];
        }
        if(argssize >= 2) {
            port = args[1].toUInt();
        }
        if(argssize >= 3) {
            data = (args[2]);
        }

        //check for invalid options..

        if(argssize > 3) {
            OUTIF() << "Warning: Extra parameters detected. Try surrounding your data with quotes.";
        }

        if(hex && mixedascii) {
            OUTIF() << "Warning: both hex and pure ascii set. Defaulting to hex.";
            mixedascii = false;
        }

        if(hex && ascii) {
            OUTIF() << "Warning: both hex and pure ascii set. Defaulting to hex.";
            ascii = false;
        }

        if(mixedascii && ascii) {
            OUTIF() << "Warning: both mixed ascii and pure ascii set. Defaulting to pure ascii.";
            mixedascii = false;
        }

        if(tcp && udp) {
            OUTIF() << "Warning: both TCP and UDP set. Defaulting to TCP.";
            udp = false;
        }

        if(!filePath.isEmpty() && !QFile::exists(filePath)) {
            OUTIF() << "Error: specified path "<< filePath <<" does not exist.";
            filePath.clear();
            OUTPUT();
            return -1;
        }

        //bind is now default 0

        if(!bind && parser.isSet(bindPortOption)) {
            OUTIF() << "Warning: Binding to port zero is dynamic.";
        }


        if(!port && name.isEmpty()) {
            OUTIF() << "Warning: Sending to port zero.";
        }

        //set default choices
        if(!hex && !ascii && !mixedascii) {
            hex = true;
        }

        if(!tcp && !udp) {
            tcp = true;
        }

        //Create the packet to send.
        if(!name.isEmpty()) {
            sendPacket = Packet::fetchFromDB(name);
            if(sendPacket.name.isEmpty()) {
                OUTIF() << "Error: Saved packet \""<< name <<"\" not found.";
                OUTPUT();
                return -1;
            } else {
                if(data.isEmpty()) {
                    data  = sendPacket.hexString;
                    hex = true;
                    ascii = false;
                    mixedascii = false;
                }
                if(!port) {
                    port  = sendPacket.port;
                }
                if(address.isEmpty()) {
                    address  = sendPacket.toIP;
                }
                if(!parser.isSet(tcpOption) && !parser.isSet(udpOption)) {

                    if(sendPacket.tcpOrUdp.toUpper() == "TCP") {
                        tcp=true;
                        udp = false;
                    } else {
                        tcp=false;
                        udp = true;
                    }

                }

            }

        }

        if(!parser.isSet(bindPortOption)) {
            bind = 0;
        }

        if(!filePath.isEmpty() && QFile::exists(filePath)) {
            QFile dataFile(filePath);
            if(dataFile.open(QFile::ReadOnly)) {

                if(tcp) {
                    QByteArray dataArray = dataFile.read(1024*1024*10);;
                    dataString = Packet::byteArrayToHex(dataArray);
                } else {

                    QByteArray dataArray = dataFile.read(1024);
                    dataString = Packet::byteArrayToHex(dataArray);
                }

                //data format is raw.
                ascii = 0;
                hex = 0;
                mixedascii = 0;

            }
        }



        QDEBUGVAR(argssize);
        QDEBUGVAR(quiet);
        QDEBUGVAR(hex);
        QDEBUGVAR(mixedascii);
        QDEBUGVAR(ascii);
        QDEBUGVAR(address);
        QDEBUGVAR(port);
        QDEBUGVAR(wait);
        QDEBUGVAR(bind);
        QDEBUGVAR(tcp);
        QDEBUGVAR(udp);
        QDEBUGVAR(name);
        QDEBUGVAR(data);
        QDEBUGVAR(filePath);

        //NOW LETS DO THIS!

        if(ascii) { //pure ascii
            dataString = Packet::byteArrayToHex(data.toLatin1());
        }

        if(hex) { //hex
            dataString = Packet::byteArrayToHex(Packet::HEXtoByteArray(data));
        }
        if(mixedascii) { //mixed ascii
            dataString = Packet::ASCIITohex(data);
        }

        if(dataString.isEmpty()) {
            OUTIF() << "Warning: No data to send. Is your formatting correct?";
        }

        QHostAddress addy;
        if(!addy.setAddress(address)) {
            QHostInfo info = QHostInfo::fromName(address);
            if (info.error() != QHostInfo::NoError)
            {
                OUTIF() << "Error: Could not resolve address:" + address;
                OUTPUT();
                return -1;
            } else {
                addy = info.addresses().at(0);
                address = addy.toString();
            }
        }

        QHostAddress theAddress(address);
        if (QAbstractSocket::IPv6Protocol == theAddress.protocol())
        {
           QDEBUG() << "Valid IPv6 address.";
           ipv6 = true;
        }


        QByteArray sendData = sendPacket.HEXtoByteArray(dataString);
        QByteArray recvData;
        recvData.clear();
        int bytesWriten = 0;
        int bytesRead = 0;


        if(tcp) {
            QTcpSocket sock;


            if(ipv6) {
                sock.bind(QHostAddress::AnyIPv6, bind);
            } else {
                sock.bind(QHostAddress::AnyIPv4, bind);
            }
            sock.connectToHost(addy, port);
            sock.waitForConnected(1000);
            if(sock.state() == QAbstractSocket::ConnectedState)
            {
                OUTIF() << "TCP (" <<sock.localPort() <<")://" << address << ":" << port << " " << dataString;
                bytesWriten = sock.write(sendData);
                sock.waitForBytesWritten(1000);
                //OUTIF() << "Sent:" << Packet::byteArrayToHex(sendData);
                if(wait) {
                    sock.waitForReadyRead(wait);
                    recvData = sock.readAll();
                    bytesRead = recvData.size();
                    QString hexString = Packet::byteArrayToHex(recvData);
                    if(quiet) {
                        o << "\n" << hexString;
                    } else {
                        o << "\nResponse Time:" << QDateTime::currentDateTime().toString(DATETIMEFORMAT);
                        o << "\nResponse HEX:" << hexString;
                        o << "\nResponse ASCII:" << Packet::hexToASCII(hexString);
                    }
                }
                sock.disconnectFromHost();
                sock.waitForDisconnected(1000);
                sock.close();

                OUTPUT();
                return bytesWriten;


            } else {
                OUTIF() << "Error: Failed to connect to " << address;

                OUTPUT();
                return -1;
            }


        } else {
            QUdpSocket sock;
            if(ipv6) {
                if(!sock.bind(QHostAddress::AnyIPv6, bind)) {
                    OUTIF() << "Error: Could not bind to " << bind;

                    OUTPUT();
                    return -1;
                }

            } else {
                if(!sock.bind(QHostAddress::AnyIPv4, bind)) {
                    OUTIF() << "Error: Could not bind to " << bind;

                    OUTPUT();
                    return -1;
                }

            }
            OUTIF() << "UDP (" <<sock.localPort() <<")://" << address << ":" << port << " " << dataString;

            bytesWriten = sock.writeDatagram(sendData, addy, port);
            //OUTIF() << "Wrote " << bytesWriten << " bytes";
            sock.waitForBytesWritten(1000);

            if(wait) {
                sock.waitForReadyRead(wait);

                if(sock.hasPendingDatagrams()) {
                    QHostAddress sender;
                    quint16 senderPort;
                    recvData.resize(sock.pendingDatagramSize());

                    sock.readDatagram(recvData.data(), recvData.size(),
                                            &sender, &senderPort);

                    QString hexString = Packet::byteArrayToHex(recvData);
                    if(quiet) {
                        o << "\n" << hexString;
                    } else {
                        o << "\nResponse Time:" << QDateTime::currentDateTime().toString(DATETIMEFORMAT);
                        o << "\nResponse HEX:" << hexString;
                        o << "\nResponse ASCII:" << Packet::hexToASCII(hexString);
                    }
                }
            }

            sock.close();

            OUTPUT();
            return bytesWriten;

        }





        OUTPUT();



    } else {
        QApplication a(argc, argv);

        QDEBUGVAR(args);

        qRegisterMetaType<Packet>();

        QFile file(":/packetsender.css");
        if(file.open(QFile::ReadOnly)) {
           QString StyleSheet = QLatin1String(file.readAll());
         //  qDebug() << "stylesheet: " << StyleSheet;
           a.setStyleSheet(StyleSheet);
        }

        MainWindow w;


        w.show();

        return a.exec();

    }



    return 0;

}
Exemplo n.º 19
0
void SharedDaemon::handleConnection()
{
    QTcpSocket *socket = nextPendingConnection();

    if ( !socket ) return;

    //the connecting socket should have sent password..
    //the client should be sending a password..
    socket->waitForReadyRead();

    if (!socket->bytesAvailable())
    {
        //std::cout << "no bytes available to read" << std::endl;
        socket->close();
        return;
    }

    QAbstractSocket* finalSocket = NULL;
    ConnectionType typeOfConnection = TcpConnection;

    QByteArray result = socket->readAll();
    QString input(result);

    /// initial connection must pass password, but can optionally pass
    /// whether the client canRender and what the threshold value should be..
    std::string lpasswd = "";
    bool canRender = false;

    /// check if this is a WebSocketConnection
    QString response = "";

    if(input.startsWith("{") && ParseInput(input,lpasswd,canRender))
    {
        finalSocket = socket;
        typeOfConnection = TcpConnection;
    } /// check if this is a WebSocketConnection..
    else if(QWsSocket::initializeWebSocket(result,response))
    {
        /// this is a websocket connection, respond and get frame..
        socket->write(response.toAscii());
        socket->flush();

        QEventLoop loop;

        matched_input = "";

        QWsSocket* wssocket = new QWsSocket(socket);

        connect(wssocket,SIGNAL(frameReceived(QString)),
                this,SLOT(getPasswordMessage(QString)));

        connect(wssocket,SIGNAL(frameReceived(QString)),
                &loop,SLOT(quit()));

        /// wait for password to be sent ..
        /// std::cout << "waiting for password from websocket" << std::endl;
        loop.exec();

        disconnect(wssocket,SIGNAL(frameReceived(QString)),
                this,SLOT(getPasswordMessage(QString)));

        disconnect(wssocket,SIGNAL(frameReceived(QString)),
                &loop,SLOT(quit()));

        //std::cout << matched_input.toStdString() << std::endl;

        if( !ParseInput(matched_input,lpasswd,canRender) )
        {
            //std::cout << "passwords do not match: "
            //          << matched_password.toStdString()
            //          << " " << password << std::endl;

            disconnect(wssocket,SIGNAL(frameReceived(QString)),
                    this,SLOT(getPasswordMessage(QString)));
            wssocket->close("passwords do not match or operation timed out");
            socket->waitForDisconnected();

            wssocket->deleteLater();
            return;
        }

        finalSocket = wssocket;
        typeOfConnection = WSocketConnection;

    } /// not sure what connection this is, reject it..
    else
    {
        //send rejection notice..
        std::string errorString = "Unknown connection..";
        socket->write(errorString.c_str(),errorString.length());
        socket->disconnectFromHost();
        socket->waitForDisconnected();
        return;
    }

    //passwords match enable RemoteProcess and get port remote Process is listening to.
    //send host,port,security_key and whatever else so that remote machine can successfully reverse connect
    std::string program = "remoteApp";
    std::string clientName = "newclient1";

    ViewerClientConnection *newClient = new
            ViewerClientConnection(subject->GetViewerState(),
                                   this,
                                   clientName.c_str(),
                                   true);

    newClient->SetExternalClient(true);
    newClient->SetAdvancedRendering(canRender);
    stringVector args;

    /// assign whether connection is of type WebSocket or TCPConnection
    /// Register Type & Register Callback
    RemoteProcess::SetCustomConnectionCallback(createCustomConnection,&typeOfConnection);

    void* data[2];
    data[0] = &typeOfConnection;
    data[1] = (void*)finalSocket;
    newClient->LaunchClient(program,args,AddNewClient,data,0,0);

    RemoteProcess::SetCustomConnectionCallback(0,0); /// reset connection..

    /// Now that client has launched RemoveCallback..
    subject->AddNewViewerClientConnection(newClient);
}
Exemplo n.º 20
0
void FileServerThread::run()    //TODO: use mutexes
{
    QString filename;
    QString ID;
    QFile file;
    QTcpSocket socket;
    socket.setSocketDescriptor (m_descriptor);

    while (!m_doQuit) {
        m_status = Waiting;
        while (!socket.bytesAvailable() && !m_doQuit) {
            socket.waitForReadyRead();
        }
        if (m_doQuit)
            break;

        QString data (socket.readAll());

        if (!Kapotah::TransferManager::instance()->pathForId (data).isEmpty()) {
            setStatus(PreparingToSend);
            ID = data;
            filename = Kapotah::TransferManager::instance()->pathForId (data);

            file.setFileName (filename);

            if (!file.open (QIODevice::ReadOnly)) {
                setStatus(ErrorFileNotFound);
                break;
            }

            socket.write ("OK");
            socket.waitForBytesWritten();
            emit startedTransfer (ID);
            setStatus(Sending);

            while (!file.atEnd() && !m_doQuit) {
                if (socket.state() != QTcpSocket::ConnectedState) {
                    emit finishedTransfer (ID);
                    setStatus(Finished);
                    break;
                }

                socket.write (file.read (s_bytesPerBlock));
                socket.waitForBytesWritten();

                while (socket.bytesToWrite())
                    socket.flush();

                emit transferProgress (ID, file.pos() / file.size() *100);
            }

            file.close();

            if (m_doQuit) {
                setStatus(Canceled);
                emit canceledTransfer(ID);
                socket.disconnectFromHost();
            } else {
                setStatus(Finished);
                emit finishedTransfer (ID);
            }

            socket.waitForDisconnected ();
            break;
        } else {
            setStatus(ErrorIDNotFound);
            emit transferNotFound(ID);
            break;
        }

        deleteLater();
    }
}