Exemple #1
0
int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    qmlRegisterType<Graph>("Graph", 1, 0, "Graph");

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    app.setWindowIcon(QIcon(":/content/icon.png"));

    QMLHandlerCppSide alertLamp(engine.rootObjects()[0], "alertLamp");
    QMLHandlerCppSide lineSens(engine.rootObjects()[0], "lineSens");
    QMLHandlerCppSide textAccelX(engine.rootObjects()[0], "textAccelX");
    QMLHandlerCppSide textAccelY(engine.rootObjects()[0], "textAccelY");
    QMLHandlerCppSide textAccelZ(engine.rootObjects()[0], "textAccelZ");
    QMLHandlerCppSide textGyroX(engine.rootObjects()[0], "textGyroX");
    QMLHandlerCppSide textGyroY(engine.rootObjects()[0], "textGyroY");
    QMLHandlerCppSide textGyroZ(engine.rootObjects()[0], "textGyroZ");
    QMLHandlerCppSide textCurStatus(engine.rootObjects()[0], "textCurStatus");
    QMLHandlerCppSide comboSetStatus(engine.rootObjects()[0], "comboSetStatus");
    QMLHandlerCppSide textCurSpeed(engine.rootObjects()[0], "textCurSpeed");
    QMLHandlerCppSide editSetSpeed(engine.rootObjects()[0], "editSetSpeed");
    QMLHandlerCppSide wheels(engine.rootObjects()[0], "wheels");
    QMLHandlerCppSide carAccelY(engine.rootObjects()[0], "carAccelY");
    QMLHandlerCppSide carGyroX(engine.rootObjects()[0], "carGyroX");
    QMLHandlerCppSide carGyroY(engine.rootObjects()[0], "carGyroY");
    QMLHandlerCppSide carGyroZ(engine.rootObjects()[0], "carGyroZ");
    QMLHandlerCppSide statusHistory(engine.rootObjects()[0], "statusHistory");
    QMLHandlerCppSide speedGraph(engine.rootObjects()[0], "speedGraph");
    QMLHandlerCppSide buttonConDiscon(engine.rootObjects()[0], "buttonConDiscon");
    QMLHandlerCppSide buttonSendStatus(engine.rootObjects()[0], "buttonSendStatus");
    QMLHandlerCppSide buttonSendSpeed(engine.rootObjects()[0], "buttonSendSpeed");
    QMLHandlerCppSide buttonCarSelfTest(engine.rootObjects()[0], "buttonCarSelfTest");

    GuiHandler guihandle(&alertLamp, &lineSens, &textAccelX, &textAccelY, &textAccelZ, &textGyroX, &textGyroY, &textGyroZ, &textCurStatus, &comboSetStatus, &textCurSpeed, &editSetSpeed, &wheels, &carAccelY, &carGyroX, &carGyroY, &carGyroZ, &statusHistory, &speedGraph, &buttonConDiscon, &buttonSendStatus, &buttonSendSpeed, &buttonCarSelfTest);
    Robot mikrobi;

    QObject::connect(&guihandle, SIGNAL(buttonConClicked()), &mikrobi, SLOT(connect()));
    QObject::connect(&guihandle, SIGNAL(buttonDisClicked()), &mikrobi, SLOT(disconnect()));
    QObject::connect(&guihandle, SIGNAL(buttonCarSelfTestClicked()), &mikrobi, SLOT(selfTest()));
    QObject::connect(&guihandle, SIGNAL(buttonSendStatusClicked(QString)), &mikrobi, SLOT(status(QString)));
    QObject::connect(&guihandle, SIGNAL(buttonSendSpeedClicked(float)), &mikrobi, SLOT(speed(float)));

    QObject::connect(&mikrobi, SIGNAL(connected()), &guihandle, SLOT(robotConnected()));
    QObject::connect(&mikrobi, SIGNAL(setAlert(int)), &guihandle, SLOT(setAlert(int)));
    QObject::connect(&mikrobi, SIGNAL(disconnected()), &guihandle, SLOT(robotDisconnected()));

    QObject::connect(&mikrobi, SIGNAL(setLedStrip(QVarLengthArray<bool>)), &guihandle, SLOT(setLedStrip(QVarLengthArray<bool>)));
    QObject::connect(&mikrobi, SIGNAL(setTextAccelX(float)), &guihandle, SLOT(setTextAccelX(float)));
    QObject::connect(&mikrobi, SIGNAL(setTextAccelY(float)), &guihandle, SLOT(setTextAccelY(float)));
    QObject::connect(&mikrobi, SIGNAL(setTextAccelZ(float)), &guihandle, SLOT(setTextAccelZ(float)));
    QObject::connect(&mikrobi, SIGNAL(setTextGyroX(float)), &guihandle, SLOT(setTextGyroX(float)));
    QObject::connect(&mikrobi, SIGNAL(setTextGyroY(float)), &guihandle, SLOT(setTextGyroY(float)));
    QObject::connect(&mikrobi, SIGNAL(setTextGyroZ(float)), &guihandle, SLOT(setTextGyroZ(float)));
    QObject::connect(&mikrobi, SIGNAL(setTextStatus(QString)), &guihandle, SLOT(setTextStatus(QString)));
    QObject::connect(&mikrobi, SIGNAL(setTextSpeed(float)), &guihandle, SLOT(setTextSpeed(float)));
    QObject::connect(&mikrobi, SIGNAL(setWheels(QVarLengthArray<float>, const float)), &guihandle, SLOT(setWheels(QVarLengthArray<float>, const float)));
    QObject::connect(&mikrobi, SIGNAL(setCarAccelY(QVarLengthArray<float>, float)), &guihandle, SLOT(setCarAccelY(QVarLengthArray<float>, float)));
    QObject::connect(&mikrobi, SIGNAL(setCarGyroX(float)), &guihandle, SLOT(setCarGyroX(float)));
    QObject::connect(&mikrobi, SIGNAL(setCarGyroY(float)), &guihandle, SLOT(setCarGyroY(float)));
    QObject::connect(&mikrobi, SIGNAL(setCarGyroZ(float)), &guihandle, SLOT(setCarGyroZ(float)));
    QObject::connect(&mikrobi, SIGNAL(drawSpeedGraph(float)), &guihandle, SLOT(drawSpeedGraph(float)));
    QObject::connect(&mikrobi, SIGNAL(setTextStatus(QString)), &guihandle, SLOT(addStatusHistory(QString)));

    return app.exec();
}
/**
 * write all  message body / payload to Stream
 * @param stream Stream *
 * @return bytes written ( negative values are error codes )
 */
int HTTPClient::writeToStream(Stream * stream) {

    if(!stream) {
        return returnError(HTTPC_ERROR_NO_STREAM);
    }

    if(!connected()) {
        return returnError(HTTPC_ERROR_NOT_CONNECTED);
    }

    // get length of document (is -1 when Server sends no Content-Length header)
    int len = _size;
    int ret = 0;

    if(_transferEncoding == HTTPC_TE_IDENTITY) {
        ret = writeToStreamDataBlock(stream, len);

        // have we an error?
        if(ret < 0) {
            return returnError(ret);
        }
    } else if(_transferEncoding == HTTPC_TE_CHUNKED) {
        int size = 0;
        while(1) {
            if(!connected()) {
                return returnError(HTTPC_ERROR_CONNECTION_LOST);
            }
            String chunkHeader = _tcp->readStringUntil('\n');

            if(chunkHeader.length() <= 0) {
                return returnError(HTTPC_ERROR_READ_TIMEOUT);
            }

            chunkHeader.trim(); // remove \r

            // read size of chunk
            len = (uint32_t) strtol((const char *) chunkHeader.c_str(), NULL, 16);
            size += len;
            DEBUG_HTTPCLIENT("[HTTP-Client] read chunk len: %d\n", len);

            // data left?
            if(len > 0) {
                int r = writeToStreamDataBlock(stream, len);
                if(r < 0) {
                    // error in writeToStreamDataBlock
                    return returnError(r);
                }
                ret += r;
            } else {

                // if no length Header use global chunk size
                if(_size <= 0) {
                    _size = size;
                }

                // check if we have write all data out
                if(ret != _size) {
                    return returnError(HTTPC_ERROR_STREAM_WRITE);
                }
                break;
            }

            delay(0);
        }
    } else {
        return returnError(HTTPC_ERROR_ENCODING);
    }

    end();
    return ret;
}
/**
 * write one Data Block to Stream
 * @param stream Stream *
 * @param size int
 * @return < 0 = error >= 0 = size written
 */
int HTTPClient::writeToStreamDataBlock(Stream * stream, int size) {
    int buff_size = HTTP_TCP_BUFFER_SIZE;
    int len = size;
    int bytesWritten = 0;

    // if possible create smaller buffer then HTTP_TCP_BUFFER_SIZE
    if((len > 0) && (len < HTTP_TCP_BUFFER_SIZE)) {
        buff_size = len;
    }

    // create buffer for read
    uint8_t * buff = (uint8_t *) malloc(buff_size);

    if(buff) {
        // read all data from server
        while(connected() && (len > 0 || len == -1)) {

            // get available data size
            size_t sizeAvailable = _tcp->available();

            if(sizeAvailable) {

                int readBytes = sizeAvailable;

                // read only the asked bytes
                if(len > 0 && readBytes > len) {
                    readBytes = len;
                }

                // not read more the buffer can handle
                if(readBytes > buff_size) {
                    readBytes = buff_size;
                }

                // read data
                int bytesRead = _tcp->readBytes(buff, readBytes);

                // write it to Stream
                int bytesWrite = stream->write(buff, bytesRead);
                bytesWritten += bytesWrite;

                // are all Bytes a writen to stream ?
                if(bytesWrite != bytesRead) {
                    DEBUG_HTTPCLIENT("[HTTP-Client][writeToStream] short write asked for %d but got %d retry...\n", bytesRead, bytesWrite);

                    // check for write error
                    if(stream->getWriteError()) {
                        DEBUG_HTTPCLIENT("[HTTP-Client][writeToStreamDataBlock] stream write error %d\n", stream->getWriteError());

                        //reset write error for retry
                        stream->clearWriteError();
                    }

                    // some time for the stream
                    delay(1);

                    int leftBytes = (readBytes - bytesWrite);

                    // retry to send the missed bytes
                    bytesWrite = stream->write((buff + bytesWrite), leftBytes);
                    bytesWritten += bytesWrite;

                    if(bytesWrite != leftBytes) {
                        // failed again
                        DEBUG_HTTPCLIENT("[HTTP-Client][writeToStream] short write asked for %d but got %d failed.\n", leftBytes, bytesWrite);
                        free(buff);
                        return HTTPC_ERROR_STREAM_WRITE;
                    }
                }

                // check for write error
                if(stream->getWriteError()) {
                    DEBUG_HTTPCLIENT("[HTTP-Client][writeToStreamDataBlock] stream write error %d\n", stream->getWriteError());
                    free(buff);
                    return HTTPC_ERROR_STREAM_WRITE;
                }

                // count bytes to read left
                if(len > 0) {
                    len -= readBytes;
                }

                delay(0);
            } else {
                delay(1);
            }
        }

        free(buff);

        DEBUG_HTTPCLIENT("[HTTP-Client][writeToStreamDataBlock] connection closed or file end (written: %d).\n", bytesWritten);

        if((size > 0) && (size != bytesWritten)) {
            DEBUG_HTTPCLIENT("[HTTP-Client][writeToStreamDataBlock] bytesWritten %d and size %d mismatch!.\n", bytesWritten, size);
            return HTTPC_ERROR_STREAM_WRITE;
        }

    } else {
        DEBUG_HTTPCLIENT("[HTTP-Client][writeToStreamDataBlock] too less ram! need %d\n", HTTP_TCP_BUFFER_SIZE);
        return HTTPC_ERROR_TOO_LESS_RAM;
    }

    return bytesWritten;
}
Exemple #4
0
    /*------------------------------------------------------------------------------*

     *------------------------------------------------------------------------------*/
    void WebProxy::processQuery() {
        QTcpSocket *socket = qobject_cast<QTcpSocket*>(sender());
        QByteArray requestData = socket->readAll();

        int pos = requestData.indexOf("\r\n");
        QByteArray requestLine = requestData.left(pos);
        requestData.remove(0, pos + 2);

        QList<QByteArray> entries = requestLine.split(' ');
        QByteArray method = entries.value(0);
        QByteArray address = entries.value(1);
        QByteArray version = entries.value(2);

        qDebug( )  << __FILE__ << __FUNCTION__ << "Processing " << address;

        QUrl url = QUrl::fromEncoded(address);
        if (!url.isValid()) {
            //qWarning() << "Invalid URL:" << url;
            socket->disconnectFromHost();
            return;
        }

        //Act as server is request are for local server
        if ((url.host() == "") && (QFile(address).exists())) {
            //qDebug( )  << __FILE__ << __FUNCTION__ << "Sending " << address;
            QByteArray header;
            QTextStream headerStream(&header, QIODevice::WriteOnly);
            //Construct response header
            headerStream << "HTTP/1.0 200 OK" << endl;
            headerStream << "Server: gpsbook/" << qApp->applicationVersion() << endl;
            headerStream << "Date: " << QDateTime::currentDateTime().toUTC().toString("ddd, dd MMM yyyy hh:mm:ss") << "GMT" << endl;
            headerStream << "Content-Type: text/html; charset=utf-8" << endl;
            headerStream << "Connection: close" << endl;
            headerStream << "Pragma: no-cache" << endl;
            headerStream << "Cache-Control: no-cache" << endl;
            QFile file(address);
            if (!file.open(QFile::ReadOnly | QFile::Text))
            {
                 qWarning() << "Cannot open:" << address;
                 socket->disconnectFromHost();
                 return ;
            }

            QByteArray content;
            QTextStream contentStream(&content, QIODevice::WriteOnly);

            while (!file.atEnd()) {
                contentStream << file.readLine() << endl;
            }

            headerStream << "Content-Length:" << content.size() << endl;
            headerStream << "" << endl;

            socket->write(header);
            socket->write(content);
            //qDebug( )  << __FILE__ << __FUNCTION__ << "File sent (" << content.size() << "bytes) :-)";
            socket->disconnectFromHost();
        return;
        }


#if ( QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) )
        // Some finction of QUrl have been deprecated
        // This code is require for the internet browser and should be reviewed.
#else


#ifdef Q_OS_LINUX
        //Remove advert to speedup development ;-)
        if (url.toString().contains("googlesyndication") ||
            url.toString().contains("yieldmanager.com")) {
            socket->disconnectFromHost();
            return;
        }
#endif

        qDebug( )  << __FILE__ << __FUNCTION__ << "URL: " << url.toString();

        QString host = url.host();
        int port = (url.port() < 0) ? 80 : url.port();
        QByteArray req = url.encodedPath();
        if (url.hasQuery())
            req.append('?').append(url.encodedQuery());
        requestLine = method + " " + req + " " + version + "\r\n";
        requestData.prepend(requestLine);

        QString key = host + ':' + QString::number(port);
        QTcpSocket *proxySocket = socket->findChild<QTcpSocket*>(key);
        if (proxySocket) {
            proxySocket->setObjectName(key);
            proxySocket->setProperty("url", url);
            proxySocket->setProperty("requestData", requestData);
            proxySocket->write(requestData);
        } else {
            proxySocket = new QTcpSocket(socket);
            proxySocket->setObjectName(key);
            proxySocket->setProperty("url", url);
            proxySocket->setProperty("requestData", requestData);
            connect(proxySocket, SIGNAL(connected()), this, SLOT(sendRequest()));
            connect(proxySocket, SIGNAL(readyRead()), this, SLOT(transferData()));
            connect(proxySocket, SIGNAL(disconnected()), this, SLOT(closeConnection()));
            connect(proxySocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(closeConnection()));
            proxySocket->connectToHost(host, port);
        }
#endif
    } //WebProxy::processQuery
/**
 * set the timeout for the TCP connection
  * @param timeout unsigned int
 */
void HTTPClient::setTimeout(uint16_t timeout) {
    _tcpTimeout = timeout;
    if(connected()) {
        _tcp->setTimeout(timeout);
    }
}
Exemple #6
0
  bool Client::handleNormalNode( Tag* tag )
  {
    if( tag->name() == "features" && tag->xmlns() == XMLNS_STREAM )
    {
      m_streamFeatures = getStreamFeatures( tag );

      if( m_tls == TLSRequired && !m_encryptionActive
          && ( !m_encryption || !( m_streamFeatures & StreamFeatureStartTls ) ) )
      {
        logInstance().err( LogAreaClassClient, "Client is configured to require"
                                " TLS but either the server didn't offer TLS or"
                                " TLS support is not compiled in." );
        disconnect( ConnTlsNotAvailable );
      }
      else if( m_tls > TLSDisabled && m_encryption && !m_encryptionActive
          && ( m_streamFeatures & StreamFeatureStartTls ) )
      {
        notifyStreamEvent( StreamEventEncryption );
        startTls();
      }
      else if( m_compress && m_compression && !m_compressionActive
          && ( m_streamFeatures & StreamFeatureCompressZlib ) )
      {
        notifyStreamEvent( StreamEventCompression );
        logInstance().warn( LogAreaClassClient, "The server offers compression, but negotiating Compression at this stage is not recommended. See XEP-0170 for details. We'll continue anyway." );
        negotiateCompression( StreamFeatureCompressZlib );
      }
      else if( m_sasl )
      {
        if( m_authed )
        {
          if( m_streamFeatures & StreamFeatureBind )
          {
            notifyStreamEvent( StreamEventResourceBinding );
            bindResource( resource() );
          }
        }
        else if( m_doAuth && !username().empty() && !password().empty() )
        {
          if( m_streamFeatures & SaslMechDigestMd5 && m_availableSaslMechs & SaslMechDigestMd5
              && !m_forceNonSasl )
          {
            notifyStreamEvent( StreamEventAuthentication );
            startSASL( SaslMechDigestMd5 );
          }
          else if( m_streamFeatures & SaslMechPlain && m_availableSaslMechs & SaslMechPlain
                   && !m_forceNonSasl )
          {
            notifyStreamEvent( StreamEventAuthentication );
            startSASL( SaslMechPlain );
          }
          else if( m_streamFeatures & StreamFeatureIqAuth || m_forceNonSasl )
          {
            notifyStreamEvent( StreamEventAuthentication );
            nonSaslLogin();
          }
          else
          {
            logInstance().err( LogAreaClassClient, "the server doesn't support"
                                           " any auth mechanisms we know about" );
            disconnect( ConnNoSupportedAuth );
          }
        }
        else if( m_doAuth && !m_clientCerts.empty() && !m_clientKey.empty()
                 && m_streamFeatures & SaslMechExternal && m_availableSaslMechs & SaslMechExternal )
        {
          notifyStreamEvent( StreamEventAuthentication );
          startSASL( SaslMechExternal );
        }
#ifdef _WIN32
        else if( m_doAuth && m_streamFeatures & SaslMechGssapi && m_availableSaslMechs & SaslMechGssapi )
        {
          notifyStreamEvent( StreamEventAuthentication );
          startSASL( SaslMechGssapi );
        }
#endif
        else if( m_doAuth && m_streamFeatures & SaslMechAnonymous
                 && m_availableSaslMechs & SaslMechAnonymous )
        {
          notifyStreamEvent( StreamEventAuthentication );
          startSASL( SaslMechAnonymous );
        }
        else
        {
          notifyStreamEvent( StreamEventFinished );
          connected();
        }
      }
      else if( m_compress && m_compression && !m_compressionActive
          && ( m_streamFeatures & StreamFeatureCompressZlib ) )
      {
        notifyStreamEvent( StreamEventCompression );
        negotiateCompression( StreamFeatureCompressZlib );
      }
//       else if( ( m_streamFeatures & StreamFeatureCompressDclz )
//               && m_connection->initCompression( StreamFeatureCompressDclz ) )
//       {
//         negotiateCompression( StreamFeatureCompressDclz );
//       }
      else if( m_streamFeatures & StreamFeatureIqAuth )
      {
        notifyStreamEvent( StreamEventAuthentication );
        nonSaslLogin();
      }
      else
      {
        logInstance().err( LogAreaClassClient, "fallback: the server doesn't "
                                   "support any auth mechanisms we know about" );
        disconnect( ConnNoSupportedAuth );
      }
    }
    else
    {
      const std::string& name  = tag->name(),
                         xmlns = tag->findAttribute( XMLNS );
      if( name == "proceed" && xmlns == XMLNS_STREAM_TLS )
      {
        logInstance().dbg( LogAreaClassClient, "starting TLS handshake..." );

        if( m_encryption )
        {
          m_encryptionActive = true;
          m_encryption->handshake();
        }
      }
      else if( name == "failure" )
      {
        if( xmlns == XMLNS_STREAM_TLS )
        {
          logInstance().err( LogAreaClassClient, "TLS handshake failed (server-side)!" );
          disconnect( ConnTlsFailed );
        }
        else if( xmlns == XMLNS_COMPRESSION )
        {
          logInstance().err( LogAreaClassClient, "stream compression init failed!" );
          disconnect( ConnCompressionFailed );
        }
        else if( xmlns == XMLNS_STREAM_SASL )
        {
          logInstance().err( LogAreaClassClient, "SASL authentication failed!" );
          processSASLError( tag );
          disconnect( ConnAuthenticationFailed );
        }
      }
      else if( name == "compressed" && xmlns == XMLNS_COMPRESSION )
      {
        logInstance().dbg( LogAreaClassClient, "stream compression inited" );
        m_compressionActive = true;
        header();
      }
      else if( name == "challenge" && xmlns == XMLNS_STREAM_SASL )
      {
        logInstance().dbg( LogAreaClassClient, "processing SASL challenge" );
        processSASLChallenge( tag->cdata() );
      }
      else if( name == "success" && xmlns == XMLNS_STREAM_SASL )
      {
        logInstance().dbg( LogAreaClassClient, "SASL authentication successful" );
        setAuthed( true );
        header();
      }
      else
        return false;
    }

    return true;
  }
Exemple #7
0
//! [connected]
void ChatClient::connected()
{
    emit connected(socket->peerName());
}
Exemple #8
0
	void start(const QVariant &vrequest, Mode mode)
	{
		outSeq = 0;
		outCredits = 0;
		quiet = false;

		ZhttpRequestPacket request;
		if(!request.fromVariant(vrequest))
		{
			log_warning("failed to parse zurl request");

			QVariantHash vhash = vrequest.toHash();
			rid = vhash.value("id").toByteArray();
			toAddress = vhash.value("from").toByteArray();
			QByteArray type = vhash.value("type").toByteArray();
			if(!toAddress.isEmpty() && type != "error" && type != "cancel")
			{
				QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
			}
			else
			{
				cleanup();
				QMetaObject::invokeMethod(q, "finished", Qt::QueuedConnection);
			}

			return;
		}

		rid = request.id;
		toAddress = request.from;
		userData = request.userData;
		sentHeader = false;
		stuffToRead = false;
		bytesReceived = 0;

		ignorePolicies = request.ignorePolicies;

		if(request.uri.isEmpty())
		{
			log_warning("missing request uri");

			QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
			return;
		}

		QString scheme = request.uri.scheme();
		if(scheme == "https" || scheme == "http")
		{
			transport = HttpTransport;
		}
		else if(scheme == "wss" || scheme == "ws")
		{
			transport = WebSocketTransport;
		}
		else
		{
			log_warning("unsupported scheme");

			QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
			return;
		}

		if(transport == WebSocketTransport && mode != Worker::Stream)
		{
			log_warning("websocket must be used from stream interface");

			QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
			return;
		}

		int defaultPort;
		if(scheme == "https" || scheme == "wss")
			defaultPort = 443;
		else // http || wss
			defaultPort = 80;

		HttpHeaders headers = request.headers;

		if(transport == HttpTransport)
		{
			// fire and forget
			if(mode == Worker::Stream && (rid.isEmpty() || toAddress.isEmpty()))
				quiet = true;

			// streaming only allowed on streaming interface
			if(mode == Worker::Stream)
				outStream = request.stream;
			else
				outStream = false;

			if(request.method.isEmpty())
			{
				log_warning("missing request method");

				QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
				return;
			}

			log_info("IN id=%s, %s %s", request.id.data(), qPrintable(request.method), request.uri.toEncoded().data());

			// inbound streaming must start with sequence number of 0
			if(mode == Worker::Stream && request.more && request.seq != 0)
			{
				log_warning("streamed input must start with seq 0");

				QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
				return;
			}

			// can't use these two together
			if(mode == Worker::Single && request.more)
			{
				log_warning("cannot use streamed input on router interface");

				QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
				return;
			}

			bodySent = false;

			inSeq = request.seq;

			if(!isAllowed(request.uri.host()) || (!request.connectHost.isEmpty() && !isAllowed(request.connectHost)))
			{
				QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "policy-violation"));
				return;
			}

			QByteArray hostHeader = request.uri.host().toUtf8();

			// only tack on the port if it isn't being overridden
			int port = request.uri.port(defaultPort);
			if(request.connectPort == -1 && port != defaultPort)
				hostHeader += ":" + QByteArray::number(port);

			headers.removeAll("Host");
			headers += HttpHeader("Host", hostHeader);

			hreq = new HttpRequest(dns, this);
			connect(hreq, SIGNAL(nextAddress(const QHostAddress &)), SLOT(req_nextAddress(const QHostAddress &)));
			connect(hreq, SIGNAL(readyRead()), SLOT(req_readyRead()));
			connect(hreq, SIGNAL(bytesWritten(int)), SLOT(req_bytesWritten(int)));
			connect(hreq, SIGNAL(error()), SLOT(req_error()));

			maxResponseSize = request.maxSize;
			sessionTimeout = request.timeout;

			if(!request.connectHost.isEmpty())
				hreq->setConnectHost(request.connectHost);
			if(request.connectPort != -1)
				request.uri.setPort(request.connectPort);

			hreq->setIgnoreTlsErrors(request.ignoreTlsErrors);
			if(request.followRedirects)
				hreq->setFollowRedirects(8);

			if(request.credits != -1)
				outCredits += request.credits;
		}
		else // WebSocketTransport
		{
			log_info("IN id=%s, %s", request.id.data(), request.uri.toEncoded().data());

			// inbound streaming must start with sequence number of 0
			if(request.seq != 0)
			{
				log_warning("websocket input must start with seq 0");

				QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
				return;
			}

			if(toAddress.isEmpty())
			{
				log_warning("websocket input must provide from address");

				QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
				return;
			}

			inSeq = request.seq;

			if(!isAllowed(request.uri.host()) || (!request.connectHost.isEmpty() && !isAllowed(request.connectHost)))
			{
				QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "policy-violation"));
				return;
			}

			QByteArray hostHeader = request.uri.host().toUtf8();

			// only tack on the port if it isn't being overridden
			int port = request.uri.port(defaultPort);
			if(request.connectPort == -1 && port != defaultPort)
				hostHeader += ":" + QByteArray::number(port);

			headers.removeAll("Host");
			headers += HttpHeader("Host", hostHeader);

			ws = new WebSocket(dns, this);
			connect(ws, SIGNAL(nextAddress(const QHostAddress &)), SLOT(req_nextAddress(const QHostAddress &)));
			connect(ws, SIGNAL(connected()), SLOT(ws_connected()));
			connect(ws, SIGNAL(readyRead()), SLOT(ws_readyRead()));
			connect(ws, SIGNAL(framesWritten(int)), SLOT(ws_framesWritten(int)));
			connect(ws, SIGNAL(peerClosing()), SLOT(ws_peerClosing()));
			connect(ws, SIGNAL(closed()), SLOT(ws_closed()));
			connect(ws, SIGNAL(error()), SLOT(ws_error()));

			if(!request.connectHost.isEmpty())
				ws->setConnectHost(request.connectHost);
			if(request.connectPort != -1)
				request.uri.setPort(request.connectPort);

			ws->setIgnoreTlsErrors(request.ignoreTlsErrors);
			ws->setMaxFrameSize(config->sessionBufferSize);

			if(request.credits != -1)
				outCredits += request.credits;
		}

		httpActivityTimer = new QTimer(this);
		connect(httpActivityTimer, SIGNAL(timeout()), SLOT(httpActivity_timeout()));
		httpActivityTimer->setSingleShot(true);
		httpActivityTimer->start(config->activityTimeout * 1000);

		if(sessionTimeout != -1)
		{
			httpSessionTimer = new QTimer(this);
			connect(httpSessionTimer, SIGNAL(timeout()), SLOT(httpSession_timeout()));
			httpSessionTimer->setSingleShot(true);
			httpSessionTimer->start(sessionTimeout);
		}

		if(transport == WebSocketTransport || (transport == HttpTransport && mode == Worker::Stream))
		{
			expireTimer = new QTimer(this);
			connect(expireTimer, SIGNAL(timeout()), SLOT(expire_timeout()));
			expireTimer->setSingleShot(true);
			expireTimer->start(SESSION_EXPIRE);

			keepAliveTimer = new QTimer(this);
			connect(keepAliveTimer, SIGNAL(timeout()), SLOT(keepAlive_timeout()));
			keepAliveTimer->start(SESSION_EXPIRE / 2);
		}

		if(transport == HttpTransport)
		{
			if(!request.body.isEmpty() && !request.more && !headers.contains("Content-Length"))
				headers += HttpHeader("Content-Length", QByteArray::number(request.body.size()));

			bool hasOrMightHaveBody = (!request.body.isEmpty() || request.more);

			hreq->start(request.method, request.uri, headers, hasOrMightHaveBody);

			if(hasOrMightHaveBody)
			{
				if(!request.body.isEmpty())
					hreq->writeBody(request.body);

				if(!request.more)
				{
					bodySent = true;
					hreq->endBody();
				}
			}
			else
				bodySent = true;

			if(mode == Stream)
			{
				if(request.more)
				{
					// send cts
					ZhttpResponsePacket resp;
					resp.type = ZhttpResponsePacket::Credit;
					resp.credits = config->sessionBufferSize;
					writeResponse(resp);
				}
				else
				{
					// send ack
					ZhttpResponsePacket resp;
					resp.type = ZhttpResponsePacket::KeepAlive;
					writeResponse(resp);
				}
			}
		}
		else // WebSocketTransport
		{
			ws->start(request.uri, headers);
		}
	}
void CoorImpl::emitConnected() {
    emit connected();
}
Exemple #10
0
 num degre(vertex v) {
  num aux=0;
  for( num k=0; k<size(); k++) 
   aux+=connected(v,k);
  return aux;
 }
Exemple #11
0
void TcpStream::onConnected(TcpSocket&)
{
    connected(*this);
}
Exemple #12
0
Application::Application(int &argc, char **argv) : PsApplication(argc, argv),
    serverName(psServerPrefix() + cGUIDStr()), closing(false),
	updateRequestId(0), updateReply(0), updateThread(0), updateDownloader(0) {

	DEBUG_LOG(("Application Info: creation.."));

	QByteArray d(QDir((cPlatform() == dbipWindows ? cExeDir() : cWorkingDir()).toLower()).absolutePath().toUtf8());
	char h[33] = { 0 };
	hashMd5Hex(d.constData(), d.size(), h);
	serverName = psServerPrefix() + h + '-' + cGUIDStr();

	if (mainApp) {
		DEBUG_LOG(("Application Error: another Application was created, terminating.."));
		exit(0);
	}
	mainApp = this;

	installEventFilter(new _DebugWaiter(this));

#if defined Q_OS_LINUX || defined Q_OS_LINUX64
    QFontDatabase::addApplicationFont(qsl(":/gui/art/fonts/DejaVuSans.ttf"));
    QFontDatabase::addApplicationFont(qsl(":/gui/art/fonts/NanumMyeongjo-Regular.ttf"));
#endif
    QFontDatabase::addApplicationFont(qsl(":/gui/art/fonts/OpenSans-Regular.ttf"));
    QFontDatabase::addApplicationFont(qsl(":/gui/art/fonts/OpenSans-Bold.ttf"));
    QFontDatabase::addApplicationFont(qsl(":/gui/art/fonts/OpenSans-Semibold.ttf"));

	float64 dpi = primaryScreen()->logicalDotsPerInch();
	if (dpi <= 108) { // 0-96-108
		cSetScreenScale(dbisOne);
	} else if (dpi <= 132) { // 108-120-132
		cSetScreenScale(dbisOneAndQuarter);
	} else if (dpi <= 168) { // 132-144-168
		cSetScreenScale(dbisOneAndHalf);
	} else { // 168-192-inf
		cSetScreenScale(dbisTwo);
	}

    if (devicePixelRatio() > 1) {
        cSetRetina(true);
        cSetRetinaFactor(devicePixelRatio());
        cSetIntRetinaFactor(int32(cRetinaFactor()));
    }

	if (!cLangFile().isEmpty()) {
		LangLoaderPlain loader(cLangFile());
		if (!loader.errors().isEmpty()) {
			LOG(("Lang load errors: %1").arg(loader.errors()));
		} else if (!loader.warnings().isEmpty()) {
			LOG(("Lang load warnings: %1").arg(loader.warnings()));
		}
	}

	Local::start();
	style::startManager();
	anim::startManager();
	historyInit();

	DEBUG_LOG(("Application Info: inited.."));

    window = new Window();

	psInstallEventFilter();

	connect(&socket, SIGNAL(connected()), this, SLOT(socketConnected()));
	connect(&socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
	connect(&socket, SIGNAL(error(QLocalSocket::LocalSocketError)), this, SLOT(socketError(QLocalSocket::LocalSocketError)));
	connect(&socket, SIGNAL(bytesWritten(qint64)), this, SLOT(socketWritten(qint64)));
	connect(&socket, SIGNAL(readyRead()), this, SLOT(socketReading()));
	connect(&server, SIGNAL(newConnection()), this, SLOT(newInstanceConnected()));
	connect(this, SIGNAL(aboutToQuit()), this, SLOT(closeApplication()));
	connect(&updateCheckTimer, SIGNAL(timeout()), this, SLOT(startUpdateCheck()));
	connect(this, SIGNAL(updateFailed()), this, SLOT(onUpdateFailed()));
	connect(this, SIGNAL(updateReady()), this, SLOT(onUpdateReady()));
	connect(this, SIGNAL(applicationStateChanged(Qt::ApplicationState)), this, SLOT(onAppStateChanged(Qt::ApplicationState)));
	connect(&writeUserConfigTimer, SIGNAL(timeout()), this, SLOT(onWriteUserConfig()));
	writeUserConfigTimer.setSingleShot(true);

	connect(&killDownloadSessionsTimer, SIGNAL(timeout()), this, SLOT(killDownloadSessions()));

	if (cManyInstance()) {
		startApp();
	} else {
        DEBUG_LOG(("Application Info: connecting local socket to %1..").arg(serverName));
		socket.connectToServer(serverName);
	}
}
void UsageTrackerPlugin::shutdown()
{
    if (m_telemetryManager != NULL) {
        disconnect(m_telemetryManager, SIGNAL(connected()), this, SLOT(onAutopilotConnect()));
    }
}
Exemple #14
0
MainWindow::MainWindow(QWidget *parent, Qt::WindowFlags flags)
    : QMainWindow(parent, flags), loginWindow_(NULL), connectWindow_(NULL), serverListWindow_(0),
      timer_(NULL), settingsMenu_(0), connected_(0), getServers_(NULL)
{
	QCoreApplication::setOrganizationName("CPPP");
    QCoreApplication::setApplicationName("VPNht");

	ui.setupUi(this);
    setWindowTitle("VPN.ht " + QString(VERSION));

    g_openVPNConnection = new OpenVPNConnectorQt(this);
    if (!g_openVPNConnection->installHelper(SERVICE_NAME))
    {
        QMessageBox::information(this,
                                 "VPNht", "Failed to install helper for program. Please contact support.");
        QTimer::singleShot(1, this, SLOT(close()));
        return;
    }

#if defined Q_OS_MAC
    //setAttribute(Qt::WA_QuitOnClose, false);
#endif

    trayIcon_ = new QSystemTrayIcon(this);       

    trayMenu_ = new QMenu(this);
    actConnect_ = new QAction("Connect", this);
    actDisconnect_ = new QAction("Disconnect", this);
    actHelp_ = new QAction("Help", this);
    actLiveChat_ = new QAction("Live chat", this);
    actExit_ = new QAction("Quit", this);
    trayMenu_->addAction(actConnect_);
    trayMenu_->addAction(actDisconnect_);
    trayMenu_->addSeparator();
    trayMenu_->addAction(actHelp_);
    trayMenu_->addAction(actLiveChat_);
    trayMenu_->addAction(actExit_);
    trayIcon_->setContextMenu(trayMenu_);
    trayIcon_->hide();    

    setTrayStatusDisconnected(false);

    settingsMenu_ = new QMenu(this);
    settingsMenu_->addAction("Settings", this, SLOT(onSettings()));
    settingsMenu_->addAction("Status", this, SLOT(onStatus()));
    settingsMenu_->addAction("Help", this, SLOT(onHelp()));
    settingsMenu_->addAction("Proxy", this, SLOT(onProxy()));
    settingsMenu_->addAction("Show logs", this, SLOT(onShowLogs()));
    settingsMenu_->addAction("Logout", this, SLOT(onReturnToSignUp()));
    settingsMenu_->setStyleSheet(ctxMenuStyle);    

    loginWindow_ = new LoginWindow(this);
	ui.verticalLayout->addWidget(loginWindow_);
	loginWindow_->loadSettings();
    loginWindow_->hide();
	connect(loginWindow_, SIGNAL(signedIn(QString, QString)), SLOT(onSignIn(QString, QString)));

    waitWindow_ = new WaitWindow(this);
    ui.verticalLayout->addWidget(waitWindow_);

    settingsWindow_ = new SettingsWindow(settingsMenu_, this);
    connect(settingsWindow_, SIGNAL(back()), SLOT(onBack()));
	ui.verticalLayout->addWidget(settingsWindow_);
    settingsWindow_->hide();

    connectWindow_ = new ConnectWindow(settingsMenu_, this);
    connect(connectWindow_, SIGNAL(serverList()), SLOT(onServerList()));
    connect(connectWindow_, SIGNAL(connected()), SLOT(onConnected()));
        ui.verticalLayout->addWidget(connectWindow_);

    ui.verticalLayout->addWidget(connectWindow_);
	connectWindow_->hide();

    serverListWindow_ = new ServerListWindow(this);
    connect(serverListWindow_, SIGNAL(serverSelected(const QString &)),
            this, SLOT( onChangeServer(const QString &) ));
    ui.verticalLayout->addWidget(serverListWindow_);
    serverListWindow_->hide();

    proxySettingsWindow_ = new ProxySettingsWindow(settingsMenu_, this);
    connect(proxySettingsWindow_, SIGNAL(back()), SLOT(onBack()));
    ui.verticalLayout->addWidget(proxySettingsWindow_);
    proxySettingsWindow_->hide();


    // tray action
    connect(actConnect_, SIGNAL(triggered()), connectWindow_, SLOT(onClickConnect()));
    connect(actDisconnect_, SIGNAL(triggered()), connectWindow_, SLOT(onClickConnect()));
    connect(actHelp_, SIGNAL(triggered()), SLOT(onActHelp()));
    connect(actLiveChat_, SIGNAL(triggered()), SLOT(onLiveChat()));
    connect(actExit_, SIGNAL(triggered()), SLOT(onExit()));


#if defined Q_OS_WIN
    connect(trayIcon_, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
            SLOT( onTrayActivated(QSystemTrayIcon::ActivationReason) ));
#endif

    QSettings settings;
    if (settings.value("savePass", "true").toString() == "true")
    {
		QString username = settings.value("login", "").toString();
		QString password = settings.value("password", "").toString();
		if (!username.isEmpty() && !password.isEmpty())
        {
            adjustSize();
            setFixedSize(size());
            skipLoginScreen(username, password);
		}
		else
		{
            waitWindow_->hide();
            loginWindow_->show();
            adjustSize();
            setFixedSize(size());
		}
    }
    else
    {
        waitWindow_->hide();
        loginWindow_->show();
        adjustSize();
        setFixedSize(size());
    }
}
Exemple #15
0
void Simulator::onStart()
{
    QMutexLocker locker(&lock);

    QThread *mainThread = QThread::currentThread();

    qDebug() << "Simulator Thread: " << mainThread;

    // Get required UAVObjects
    ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance();
    UAVObjectManager *objManager = pm->getObject<UAVObjectManager>();
    actDesired     = ActuatorDesired::GetInstance(objManager);
    actCommand     = ActuatorCommand::GetInstance(objManager);
    manCtrlCommand = ManualControlCommand::GetInstance(objManager);
    gcsReceiver    = GCSReceiver::GetInstance(objManager);
    flightStatus   = FlightStatus::GetInstance(objManager);
    posHome        = HomeLocation::GetInstance(objManager);
    velActual      = VelocityActual::GetInstance(objManager);
    posActual      = PositionActual::GetInstance(objManager);
    baroAlt        = BaroAltitude::GetInstance(objManager);
    flightBatt     = FlightBatteryState::GetInstance(objManager);
    airspeedActual = AirspeedActual::GetInstance(objManager);
    attActual      = AttitudeActual::GetInstance(objManager);
    attSettings    = AttitudeSettings::GetInstance(objManager);
    accels      = Accels::GetInstance(objManager);
    gyros       = Gyros::GetInstance(objManager);
    gpsPos      = GPSPosition::GetInstance(objManager);
    gpsVel      = GPSVelocity::GetInstance(objManager);
    telStats    = GCSTelemetryStats::GetInstance(objManager);
    groundTruth = GroundTruth::GetInstance(objManager);

    // Listen to autopilot connection events
    TelemetryManager *telMngr = pm->getObject<TelemetryManager>();
    connect(telMngr, SIGNAL(connected()), this, SLOT(onAutopilotConnect()));
    connect(telMngr, SIGNAL(disconnected()), this, SLOT(onAutopilotDisconnect()));
    // connect(telStats, SIGNAL(objectUpdated(UAVObject*)), this, SLOT(telStatsUpdated(UAVObject*)));

    // If already connect setup autopilot
    GCSTelemetryStats::DataFields stats = telStats->getData();
    if (stats.Status == GCSTelemetryStats::STATUS_CONNECTED) {
        onAutopilotConnect();
    }

    inSocket  = new QUdpSocket();
    outSocket = new QUdpSocket();
    setupUdpPorts(settings.hostAddress, settings.inPort, settings.outPort);

    emit processOutput("\nLocal interface: " + settings.hostAddress + "\n" + \
                       "Remote interface: " + settings.remoteAddress + "\n" + \
                       "inputPort: " + QString::number(settings.inPort) + "\n" + \
                       "outputPort: " + QString::number(settings.outPort) + "\n");

    qxtLog->info("\nLocal interface: " + settings.hostAddress + "\n" + \
                 "Remote interface: " + settings.remoteAddress + "\n" + \
                 "inputPort: " + QString::number(settings.inPort) + "\n" + \
                 "outputPort: " + QString::number(settings.outPort) + "\n");

// if(!inSocket->waitForConnected(5000))
// emit processOutput(QString("Can't connect to %1 on %2 port!").arg(settings.hostAddress).arg(settings.inPort));
// outSocket->connectToHost(settings.hostAddress,settings.outPort); // FG
// if(!outSocket->waitForConnected(5000))
// emit processOutput(QString("Can't connect to %1 on %2 port!").arg(settings.hostAddress).arg(settings.outPort));


    connect(inSocket, SIGNAL(readyRead()), this, SLOT(receiveUpdate()), Qt::DirectConnection);

    // Setup transmit timer
    txTimer = new QTimer();
    connect(txTimer, SIGNAL(timeout()), this, SLOT(transmitUpdate()), Qt::DirectConnection);
    txTimer->setInterval(updatePeriod);
    txTimer->start();
    // Setup simulator connection timer
    simTimer = new QTimer();
    connect(simTimer, SIGNAL(timeout()), this, SLOT(onSimulatorConnectionTimeout()), Qt::DirectConnection);
    simTimer->setInterval(simTimeout);
    simTimer->start();

    // setup time
    time = new QTime();
    time->start();
    current.T = 0;
    current.i = 0;
}
Exemple #16
0
MainWindow::MainWindow(QWidget *parent, const QString& theHostName)
    : QMainWindow(parent), hostName(theHostName) {

    setObjectName(QStringLiteral("MainWindow"));
    resize(400, 300);

    QMediaPlaylist* playlist = new QMediaPlaylist;
    playlist->addMedia(QUrl("http://" + hostName + "/~andreas/out.mpg"));
//    playlist->addMedia(QUrl("http://" + hostName + ":1234/dvd.mp4"));

    player = new QMediaPlayer(this); // , QMediaPlayer::StreamPlayback);
    player->setPlaylist(playlist);

    QWidget* centralWidget = new QWidget(this);
    QBoxLayout* mainLayout = new QVBoxLayout();
    centralWidget->setLayout(mainLayout);

    QWidget* buttonArea = new QWidget(this);
    QHBoxLayout* buttonLayout = new QHBoxLayout();
    buttonArea->setLayout(buttonLayout);

    QVideoWidget* videoWidget = new QVideoWidget(centralWidget);
    mainLayout->addWidget(videoWidget, 1);
    mainLayout->addWidget(buttonArea);

    connectButton = new QPushButton("Connect", buttonArea);
    startPlayButton = new QPushButton("Play", buttonArea);
    startPlayButton->setEnabled(false);
    stopPlayButton = new QPushButton("Stop", buttonArea);
    stopPlayButton->setEnabled(false);
    streamButton = new QPushButton("Stream", buttonArea);
    streamButton->setEnabled(false);
    buttonLayout->addWidget(connectButton);
    buttonLayout->addWidget(startPlayButton);
    buttonLayout->addWidget(stopPlayButton);
    buttonLayout->addWidget(streamButton);

    tcpSocket = new QTcpSocket(this);

    connect(player, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)),
            this,   SLOT(statusChanged(QMediaPlayer::MediaStatus)));
    connect(connectButton, SIGNAL(clicked()),
            this,   SLOT(doConnect()));
    connect(startPlayButton, SIGNAL(clicked()),
            this,   SLOT(doStartPlay()));
    connect(stopPlayButton, SIGNAL(clicked()),
            this,   SLOT(doStopPlay()));
    connect(streamButton, SIGNAL(clicked()),
            this,   SLOT(doStream()));
    connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
            this,      SLOT(socketError(QAbstractSocket::SocketError)));
    connect(tcpSocket, SIGNAL(connected()),
            this,      SLOT(socketConnected()));
    connect(tcpSocket, SIGNAL(disconnected()),
            this,      SLOT(socketDisconnected()));
    connect(tcpSocket, SIGNAL(readyRead()),
            this,      SLOT(readData()));
    player->setVideoOutput(videoWidget);

    setCentralWidget(centralWidget);
    player->play();
}
Exemple #17
0
int main(int argc, char* argv[])
{
    // a global variable defined in errno.h that's "set by system 
    // calls and some library functions [to a nonzero value]
    // in the event of an error to indicate what went wrong"
    errno = 0;

    // default to a random port
    int port = 0;

    // usage
    const char* usage = "Usage: server [-p port] /path/to/root";

    // parse command-line arguments
    int opt;
    while ((opt = getopt(argc, argv, "hp:")) != -1)
    {
        switch (opt)
        {
            // -h
            case 'h':
                printf("%s\n", usage);
                return 0;

            // -p port
            case 'p':
                port = atoi(optarg);
                break;
        }
    }

    // ensure port is a non-negative short and path to server's root is specified
    if (port < 0 || port > SHRT_MAX || argv[optind] == NULL || strlen(argv[optind]) == 0)
    {
        // announce usage
        printf("%s\n", usage);

        // return 2 just like bash's builtins
        return 2;
    }

    // start server
    start(port, argv[optind]);

    // listen for SIGINT (aka control-c)
    signal(SIGINT, handler);

    // accept connections one at a time
    while (true)
    {
        // reset server's state
        reset();

        // wait until client is connected
        if (connected())
        {
            // parse client's HTTP request
            ssize_t octets = parse();
            if (octets == -1)
            {
                continue;
            }

            // extract request's request-line
            // http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html
            const char* haystack = request;
            char* needle = strstr(haystack, "\r\n");
            if (needle == NULL)
            {
                error(400);
                continue;
            }
            else if (needle - haystack + 2 > LimitRequestLine)
            {
                error(414);
                continue;
            }   
            char line[needle - haystack + 2 + 1];
            strncpy(line, haystack, needle - haystack + 2);
            line[needle - haystack + 2] = '\0';

            // log request-line
            printf("%s", line);

            // validate request-line
            char lineTokens[needle - haystack + 1];
            strncpy(lineTokens, haystack, needle - haystack);
            lineTokens[needle - haystack + 1] = '\0';
            
            char* requestLine[3] = {NULL, NULL, NULL};
            requestLine[METHOD] = strtok(lineTokens, " ");
            int i = 0;
            
            while (requestLine[i] != NULL && i < 2)
            {
                i++;
                requestLine[i] = strtok(lineTokens, " ");
            }
            
            if (requestLine[METHOD] == NULL || strcmp("GET", requestLine[METHOD]) != 0)
            {
                error(405);
                continue;
            }
            
            if (requestLine[REQUEST_TARGET] == NULL)
            {
                error(400);
                continue;
            }
            
            else if (requestLine[REQUEST_TARGET][0] != '/')
            {
                error(501);
                continue;
            }
            
            else if (strchr(requestLine[REQUEST_TARGET], '\"') != NULL);
            {
                error(400);
                continue;
            }
            
            if (requestLine[HTTP_VERSION] == NULL || strcmp("HTTP/1.1", requestLine[HTTP_VERSION]) != 0)
            {
                error(505);
                continue;
            }
            

            // extract query from request-target
            char* queryInd = strchrnul(requestLine[REQUEST_TARGET], '?');
            char* eosInd = strchr(requestLine[REQUEST_TARGET], '\0');
            char query[(eosInd - queryInd < 1) ? 1 : eosInd - queryInd];
            
            memcpy(query, (strncmp(queryInd, "\0", 1) ? queryInd : queryInd + 1), (eosInd - queryInd < 1) ? 1 : eosInd - queryInd);

            // get absolute-path
            char* query_Ind = strchrnul(requestLine[REQUEST_TARGET], '?');
            char absolutePath[query_Ind - requestLine[REQUEST_TARGET] + 1];
            strncpy(absolutePath, requestLine[REQUEST_TARGET], query_Ind - requestLine[REQUEST_TARGET]);
            absolutePath[query_Ind - requestLine[REQUEST_TARGET]] = '\0';
            
            // is absolute path missing a "." for the extension?
            char* extInd = strchr(absolutePath, '.');
            if (extInd == NULL)
            {
                error(501);
                continue;
            }
            
            // extract path extension
            char* eos_Ind = strchr(absolutePath, '\0');
            char extension[eos_Ind - extInd];
            memcpy(extension, extInd + 1, eos_Ind - extInd);
            
            // concatenate root and absolute-path
            char path[strlen(root) + strlen(absolutePath) + 1];
            strcpy(path, root);
            strcat(path, absolutePath);
            

            // ensure path exists
            if (access(path, F_OK) == -1)
            {
                error(404);
                continue;
            }
            
            // ensure path is readable
            if (access(path, R_OK) == -1)
            {
                error(403);
                continue;
            }
           

            // dynamic content
            if (strcasecmp("php", extension) == 0)
            {
                // open pipe to PHP interpreter
                char* format = "QUERY_STRING=\"%s\" REDIRECT_STATUS=200 SCRIPT_FILENAME=\"%s\" php-cgi";
                char command[strlen(format) + (strlen(path) - 2) + (strlen(query) - 2) + 1];
                sprintf(command, format, query, path);
                file = popen(command, "r");
                if (file == NULL)
                {
                    error(500);
                    continue;
                }

                // load file
                ssize_t size = load();
                if (size == -1)
                {
                    error(500);
                    continue;
                }

                // subtract php-cgi's headers from body's size to get content's length
                haystack = body;
                needle = memmem(haystack, size, "\r\n\r\n", 4);
                if (needle == NULL)
                {
                    error(500);
                    continue;
                }
                size_t length = size - (needle - haystack + 4);

                // respond to client
                if (dprintf(cfd, "HTTP/1.1 200 OK\r\n") < 0)
                {
                    continue;
                }
                if (dprintf(cfd, "Connection: close\r\n") < 0)
                {
                    continue;
                }
                if (dprintf(cfd, "Content-Length: %i\r\n", length) < 0)
                {
                    continue;
                }
                if (write(cfd, body, size) == -1)
                {
                    continue;
                }
            }

            // static content
            else
            {
                // look up file's MIME type
                const char* type = lookup(extension);
                if (type == NULL)
                {
                    error(501);
                    continue;
                }

                // open file
                file = fopen(path, "r");
                if (file == NULL)
                {
                    error(500);
                    continue;
                }

                // load file
                ssize_t length = load();
                if (length == -1)
                {
                    error(500);
                    continue;
                }

                // respond to client
                if (dprintf(cfd, "HTTP/1.1 200 OK\r\n") < 0)
                {
                    continue;
                }
                if (dprintf(cfd, "Connection: close\r\n") < 0)
                {
                    continue;
                }
                if (dprintf(cfd, "Content-Length: %i\r\n", length) < 0)
                {
                    continue;
                }
                if (dprintf(cfd, "Content-Type: %s\r\n\r\n", type) < 0)
                {
                    continue;
                }
                if (write(cfd, body, length) == -1)
                {
                    continue;
                }
            }
            
            // announce OK
            printf("\033[32m");
            printf("HTTP/1.1 200 OK");
            printf("\033[39m\n");
        }
    }
}
XMPP::XMPP(QObject *parent) : QXmppClient(parent),
        m_Hub(NULL),
        m_App(NULL),
        m_Connected(false),
        m_LastError(0),
        m_SendContactWhenAvailable(false),
        m_ConnectionType(OTHER),

        m_Port(27015),
        m_NotificationEnabled(true),
        m_Restarting(false),
        m_VcardManagerConnected(false) {


    m_PauseService = false;

    bool check = connect(this, SIGNAL(messageReceived(QXmppMessage)), this, SLOT(messageReceived(QXmppMessage)));
    Q_ASSERT(check);

    check = connect(&this->rosterManager(), SIGNAL(rosterReceived()), this, SLOT(rosterReceived()));
    Q_ASSERT(check);
    Q_UNUSED(check);


    check = connect(this, SIGNAL(connected()), this, SLOT(logConnection()));
    Q_ASSERT(check);
    Q_UNUSED(check);

    check = connect(this, SIGNAL(error(QXmppClient::Error)), this, SLOT(logConnectionError(QXmppClient::Error)));
    Q_ASSERT(check);


    check = connect(&this->rosterManager(), SIGNAL(presenceChanged(QString,QString)), SLOT(presenceChanged(QString,QString)));
    Q_ASSERT(check);


    // ---------------------------------------------------------------------
    // communication controls
    m_Server = boost::shared_ptr<QTcpServer>(new QTcpServer(this));

    bool ok = connect(m_Server.get(), SIGNAL(newConnection()), this, SLOT(newConnection()));
    Q_ASSERT(ok);
    Q_UNUSED(ok);

    // put the handling of the server into a thread --> avoid blocking the XMPP client while listening a new UI client...
    m_TcpThreadBind = boost::shared_ptr<TcpThreadBind>(new TcpThreadBind());
    m_TcpThreadBind->m_Server = m_Server;
    m_TcpThreadBind->m_Port   = m_Port;



    initOTR();


    // ---------------------------------------------------------------------
    // connection using oauth (PREFERED)

    QSettings settings("Amonchakai", "Hg10");
    if(!settings.value("access_token").value<QString>().isEmpty()) {

        m_GoogleConnect = boost::shared_ptr<GoogleConnectController>(new GoogleConnectController());
        bool check = connect(m_GoogleConnect.get(), SIGNAL(tokenObtained(const QString&)), this, SLOT(readyRestart(const QString &)));
        Q_ASSERT(check);
        Q_UNUSED(check);

        check = connect(m_GoogleConnect.get(), SIGNAL(failedRenew()), this, SLOT(oauth2Restart()));
        Q_ASSERT(check);

        //check = connect(m_GoogleConnect.get(), SIGNAL(failedConnection()), this, SLOT(waitForInternet()));
        //Q_ASSERT(check);

        check = connect(this, SIGNAL(disconnected()), this, SLOT(oauthDisconnected()));
        Q_ASSERT(check);

        oauth2Restart();

    } else {
Exemple #19
0
void AccountNotificationService::ignoreErrors(const Notification &notification)
{
	auto account = qvariant_cast<Account>(notification.data[QStringLiteral("account")]);
	account.addProperty(QStringLiteral("notify:ignore-connection-errors"), false, CustomProperties::NonStorable);
	connect(account, SIGNAL(connected()), this, SLOT(accountConnected()));
}
ConfigServoWidget::ConfigServoWidget(QWidget *parent) : ConfigTaskWidget(parent)
{
    m_config = new Ui_SettingsWidget();
    m_config->setupUi(this);

	ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance();
	UAVObjectManager *objManager = pm->getObject<UAVObjectManager>();

	// First of all, put all the channel widgets into lists, so that we can
    // manipulate those:

	// NOTE: for historical reasons, we have objects below called ch0 to ch7, but the convention for OP is Channel 1 to Channel 8.
    outLabels << m_config->ch0OutValue
            << m_config->ch1OutValue
            << m_config->ch2OutValue
            << m_config->ch3OutValue
            << m_config->ch4OutValue
            << m_config->ch5OutValue
            << m_config->ch6OutValue
            << m_config->ch7OutValue;

    outSliders << m_config->ch0OutSlider
            << m_config->ch1OutSlider
            << m_config->ch2OutSlider
            << m_config->ch3OutSlider
            << m_config->ch4OutSlider
            << m_config->ch5OutSlider
            << m_config->ch6OutSlider
            << m_config->ch7OutSlider;

    outMin << m_config->ch0OutMin
            << m_config->ch1OutMin
            << m_config->ch2OutMin
            << m_config->ch3OutMin
            << m_config->ch4OutMin
            << m_config->ch5OutMin
            << m_config->ch6OutMin
            << m_config->ch7OutMin;

    outMax << m_config->ch0OutMax
            << m_config->ch1OutMax
            << m_config->ch2OutMax
            << m_config->ch3OutMax
            << m_config->ch4OutMax
            << m_config->ch5OutMax
            << m_config->ch6OutMax
            << m_config->ch7OutMax;

    reversals << m_config->ch0Rev
            << m_config->ch1Rev
            << m_config->ch2Rev
            << m_config->ch3Rev
            << m_config->ch4Rev
            << m_config->ch5Rev
            << m_config->ch6Rev
            << m_config->ch7Rev;

	inMaxLabels << m_config->ch0Max
			<< m_config->ch1Max
			<< m_config->ch2Max
			<< m_config->ch3Max
			<< m_config->ch4Max
			<< m_config->ch5Max
			<< m_config->ch6Max
			<< m_config->ch7Max;

	inMinLabels << m_config->ch0Min
			<< m_config->ch1Min
			<< m_config->ch2Min
			<< m_config->ch3Min
			<< m_config->ch4Min
			<< m_config->ch5Min
			<< m_config->ch6Min
			<< m_config->ch7Min;

	inNeuLabels << m_config->ch0Cur
			<< m_config->ch1Cur
			<< m_config->ch2Cur
			<< m_config->ch3Cur
			<< m_config->ch4Cur
			<< m_config->ch5Cur
			<< m_config->ch6Cur
			<< m_config->ch7Cur;

	inSliders << m_config->inSlider0
			  << m_config->inSlider1
			  << m_config->inSlider2
			  << m_config->inSlider3
			  << m_config->inSlider4
			  << m_config->inSlider5
			  << m_config->inSlider6
			  << m_config->inSlider7;

    // Now connect the widget to the ManualControlCommand / Channel UAVObject

    UAVDataObject* obj = dynamic_cast<UAVDataObject*>(objManager->getObject(QString("ManualControlCommand")));
    connect(obj, SIGNAL(objectUpdated(UAVObject*)), this, SLOT(updateChannels(UAVObject*)));

    // Get the receiver types supported by OpenPilot and fill the corresponding
    // dropdown menu:
    obj = dynamic_cast<UAVDataObject*>(objManager->getObject(QString("ManualControlSettings")));
    QString fieldName = QString("InputMode");
    UAVObjectField *field = obj->getField(fieldName);
    m_config->receiverType->addItems(field->getOptions());
    m_config->receiverType->setDisabled(true); // This option does not work for now, it is a compile-time option.

    // Fill in the dropdown menus for the channel RC Input assignement.
    QStringList channelsList;
        channelsList << "None";
    QList<UAVObjectField*> fieldList = obj->getFields();
    foreach (UAVObjectField* field, fieldList) {
        if (field->getUnits().contains("channel")) {
            channelsList.append(field->getName());
        }
    }

    m_config->ch0Assign->addItems(channelsList);
    m_config->ch1Assign->addItems(channelsList);
    m_config->ch2Assign->addItems(channelsList);
    m_config->ch3Assign->addItems(channelsList);
    m_config->ch4Assign->addItems(channelsList);
    m_config->ch5Assign->addItems(channelsList);
    m_config->ch6Assign->addItems(channelsList);
    m_config->ch7Assign->addItems(channelsList);

    // And for the channel output assignement options
    m_config->ch0Output->addItem("None");
    m_config->ch1Output->addItem("None");
    m_config->ch2Output->addItem("None");
    m_config->ch3Output->addItem("None");
    m_config->ch4Output->addItem("None");
    m_config->ch5Output->addItem("None");
    m_config->ch6Output->addItem("None");
    m_config->ch7Output->addItem("None");

    // And the flight mode settings:
    field = obj->getField(QString("FlightModePosition"));
    m_config->fmsModePos1->addItems(field->getOptions());
    m_config->fmsModePos2->addItems(field->getOptions());
    m_config->fmsModePos3->addItems(field->getOptions());
    field = obj->getField(QString("Stabilization1Settings"));
    channelsList.clear();
    channelsList.append(field->getOptions());
    m_config->fmsSsPos1Roll->addItems(channelsList);
    m_config->fmsSsPos1Pitch->addItems(channelsList);
    m_config->fmsSsPos1Yaw->addItems(channelsList);
    m_config->fmsSsPos2Roll->addItems(channelsList);
    m_config->fmsSsPos2Pitch->addItems(channelsList);
    m_config->fmsSsPos2Yaw->addItems(channelsList);
    m_config->fmsSsPos3Roll->addItems(channelsList);
    m_config->fmsSsPos3Pitch->addItems(channelsList);
    m_config->fmsSsPos3Yaw->addItems(channelsList);

    // And the Armin configurations:
    field = obj->getField(QString("Arming"));
    m_config->armControl->clear();
    m_config->armControl->addItems(field->getOptions());

    obj = dynamic_cast<UAVDataObject*>(objManager->getObject(QString("ActuatorSettings")));
    fieldList = obj->getFields();
    foreach (UAVObjectField* field, fieldList) {
        if (field->getUnits().contains("channel")) {
            m_config->ch0Output->addItem(field->getName());
            m_config->ch1Output->addItem(field->getName());
            m_config->ch2Output->addItem(field->getName());
            m_config->ch3Output->addItem(field->getName());
            m_config->ch4Output->addItem(field->getName());
            m_config->ch5Output->addItem(field->getName());
            m_config->ch6Output->addItem(field->getName());
            m_config->ch7Output->addItem(field->getName());
        }
    }

	// set the RC input tneutral value textees
	for (int i = 0; i < 8; i++)
		inNeuLabels[i]->setText(QString::number(inSliders[i]->value()));

	for (int i = 0; i < 8; i++) {
        connect(outMin[i], SIGNAL(editingFinished()), this, SLOT(setChOutRange()));
        connect(outMax[i], SIGNAL(editingFinished()), this, SLOT(setChOutRange()));
        connect(reversals[i], SIGNAL(toggled(bool)), this, SLOT(reverseChannel(bool)));
        // Now connect the channel out sliders to our signal to send updates in test mode
        connect(outSliders[i], SIGNAL(valueChanged(int)), this, SLOT(sendChannelTest(int)));
    }

    connect(m_config->channelOutTest, SIGNAL(toggled(bool)), this, SLOT(runChannelTests(bool)));

    requestRCInputUpdate();
    requestRCOutputUpdate();

    connect(m_config->saveRCInputToSD, SIGNAL(clicked()), this, SLOT(saveRCInputObject()));
    connect(m_config->saveRCInputToRAM, SIGNAL(clicked()), this, SLOT(sendRCInputUpdate()));
    connect(m_config->getRCInputCurrent, SIGNAL(clicked()), this, SLOT(requestRCInputUpdate()));

       // Flightmode panel is connected to the same as rcinput because
    // the underlying object is the same!
    connect(m_config->saveFmsToSD, SIGNAL(clicked()), this, SLOT(saveRCInputObject()));
    connect(m_config->saveFmsToRAM, SIGNAL(clicked()), this, SLOT(sendRCInputUpdate()));
    connect(m_config->getFmsCurrent, SIGNAL(clicked()), this, SLOT(requestRCInputUpdate()));

    connect(m_config->saveArmToSD, SIGNAL(clicked()), this, SLOT(saveRCInputObject()));
    connect(m_config->saveArmToRAM, SIGNAL(clicked()), this, SLOT(sendRCInputUpdate()));
    connect(m_config->getArmCurrent, SIGNAL(clicked()), this, SLOT(requestRCInputUpdate()));

    connect(m_config->saveRCOutputToSD, SIGNAL(clicked()), this, SLOT(saveRCOutputObject()));
    connect(m_config->saveRCOutputToRAM, SIGNAL(clicked()), this, SLOT(sendRCOutputUpdate()));
    connect(m_config->getRCOutputCurrent, SIGNAL(clicked()), this, SLOT(requestRCOutputUpdate()));

    connect(parent, SIGNAL(autopilotConnected()),this, SLOT(requestRCInputUpdate()));
    connect(parent, SIGNAL(autopilotConnected()),this, SLOT(requestRCOutputUpdate()));

	connect(m_config->inSlider0, SIGNAL(valueChanged(int)),this, SLOT(onInSliderValueChanged0(int)));
	connect(m_config->inSlider1, SIGNAL(valueChanged(int)),this, SLOT(onInSliderValueChanged1(int)));
	connect(m_config->inSlider2, SIGNAL(valueChanged(int)),this, SLOT(onInSliderValueChanged2(int)));
	connect(m_config->inSlider3, SIGNAL(valueChanged(int)),this, SLOT(onInSliderValueChanged3(int)));
	connect(m_config->inSlider4, SIGNAL(valueChanged(int)),this, SLOT(onInSliderValueChanged4(int)));
	connect(m_config->inSlider5, SIGNAL(valueChanged(int)),this, SLOT(onInSliderValueChanged5(int)));
	connect(m_config->inSlider6, SIGNAL(valueChanged(int)),this, SLOT(onInSliderValueChanged6(int)));
	connect(m_config->inSlider7, SIGNAL(valueChanged(int)),this, SLOT(onInSliderValueChanged7(int)));

    firstUpdate = true;

	enableControls(false);

	// Listen to telemetry connection events
	if (pm)
	{
		TelemetryManager *tm = pm->getObject<TelemetryManager>();
		if (tm)
		{
			connect(tm, SIGNAL(myStart()), this, SLOT(onTelemetryStart()));
			connect(tm, SIGNAL(myStop()), this, SLOT(onTelemetryStop()));
			connect(tm, SIGNAL(connected()), this, SLOT(onTelemetryConnect()));
			connect(tm, SIGNAL(disconnected()), this, SLOT(onTelemetryDisconnect()));
		}
	}
}
Exemple #21
0
void BooRedisAsync::doWrite(const std::string &msg)
{
    m_writeBuffer.push_back(msg);
    if (connected() && !m_writeInProgress)
        writeStart();
}
Exemple #22
0
int user_find_cuts(void *user, int varnum, int iter_num, int level,
		   int index, double objval, int *indices, double *values,
		   double ub, double etol, int *num_cuts, int *alloc_cuts,
		   cut_data ***cuts)
{
   vrp_cg_problem *vrp = (vrp_cg_problem *)user;
   int vertnum = vrp->vertnum;
   network *n;
   vertex *verts = NULL;
   int *compdemands = NULL, *compnodes = NULL, *compnodes_copy = NULL;
   int *compmembers = NULL, comp_num = 0;
   /*__BEGIN_EXPERIMENTAL_SECTION__*/
   int *compdemands_copy = NULL;
   double *compcuts_copy = NULL, *compdensity = NULL, density;
   /*___END_EXPERIMENTAL_SECTION___*/
   double node_cut, max_node_cut, *compcuts = NULL;
   int rcnt, cur_bins = 0, k;
   char **coef_list;
   int i, max_node;
   double cur_slack = 0.0;
   int capacity = vrp->capacity;
   int cut_size = (vertnum >> DELETE_POWER) + 1;
   cut_data *new_cut = NULL;
   elist *cur_edge = NULL;
   int which_connected_routine = vrp->par.which_connected_routine;
   int *ref = vrp->ref;
   double *cut_val = vrp->cut_val;
   char *in_set = vrp->in_set;
   char *cut_list = vrp->cut_list;

   elist *cur_edge1 = NULL, *cur_edge2 = NULL;
/*__BEGIN_EXPERIMENTAL_SECTION__*/
#ifdef COMPILE_OUR_DECOMP
   edge *edge_pt;
#endif
/*___END_EXPERIMENTAL_SECTION___*/
   int node1 = 0, node2 = 0;
   int *demand = vrp->demand;
   int *new_demand = vrp->new_demand;
   int total_demand = demand[0]; 
   int num_routes = vrp->numroutes, num_trials;
   int triangle_cuts = 0;
   char *coef; 

   if (iter_num == 1) SRANDOM(1);
/*__BEGIN_EXPERIMENTAL_SECTION__*/
#if 0
   CCutil_sprand(1, &rand_state);
#endif
/*___END_EXPERIMENTAL_SECTION___*/
   
/*__BEGIN_EXPERIMENTAL_SECTION__*/

#if 0   
   if (vrp->dg_id && vrp->par.verbosity > 3){
      sprintf(name, "support graph");
      display_support_graph(vrp->dg_id, (p->cur_sol.xindex == 0 &&
			    p->cur_sol.xiter_num == 1) ? TRUE: FALSE, name,
			    varnum, xind, xval,
			    etol, CTOI_WAIT_FOR_CLICK_AND_REPORT);
   }      
#endif
/*___END_EXPERIMENTAL_SECTION___*/
   
   /* This creates a fractional graph representing the LP solution */
   n = createnet(indices, values, varnum, etol, vrp->edges, demand, vertnum);
   if (n->is_integral){
      /* if the network is integral, check for connectivity */
      check_connectivity(n, etol, capacity, num_routes, cuts, num_cuts,
			 alloc_cuts);
      free_net(n);
      return(USER_SUCCESS);
   }

#ifdef DO_TSP_CUTS
   if (vrp->par.which_tsp_cuts && vrp->par.tsp_prob){
      tsp_cuts(n, vrp->par.verbosity, vrp->par.tsp_prob,
	       vrp->par.which_tsp_cuts, cuts, num_cuts, alloc_cuts);
      free_net(n);
      return(USER_SUCCESS);
   }      
#endif
   
/*__BEGIN_EXPERIMENTAL_SECTION__*/
   if (!vrp->par.always_do_mincut){/*user_par.always_do_mincut indicates
				     whether we should just always do the
				     min_cut routine or whether we should also
				     try this routine*/
/*___END_EXPERIMENTAL_SECTION___*/
/*UNCOMMENT FOR PRODUCTION CODE*/
#if 0
   {
#endif
      verts = n->verts;
      if (which_connected_routine == BOTH)
	 which_connected_routine = CONNECTED;
      
      new_cut = (cut_data *) calloc(1, sizeof(cut_data));
      new_cut->size = cut_size;
      compnodes_copy = (int *) malloc((vertnum + 1) * sizeof(int));
      compmembers = (int *) malloc((vertnum + 1) * sizeof(int));
      /*__BEGIN_EXPERIMENTAL_SECTION__*/
      compdemands_copy = (int *) calloc(vertnum + 1, sizeof(int));
      compcuts_copy = (double *) calloc(vertnum + 1, sizeof(double));
#ifdef COMPILE_OUR_DECOMP
      compdensity = vrp->par.do_our_decomp ?
	 (double *) calloc(vertnum+1, sizeof(double)) : NULL;
#endif
      /*___END_EXPERIMENTAL_SECTION___*/
      
      do{
	 compnodes = (int *) calloc(vertnum + 1, sizeof(int));
	 compdemands = (int *) calloc(vertnum + 1, sizeof(int));
	 compcuts = (double *) calloc(vertnum + 1, sizeof(double));
	 
         /*------------------------------------------------------------------*\
          * Get the connected components of the solution graph without the
          * depot and see if the number of components is more than one
         \*------------------------------------------------------------------*/
	 rcnt = (which_connected_routine == BICONNECTED ?
		      biconnected(n, compnodes, compdemands, compcuts) :
		      connected(n, compnodes, compdemands, compmembers,
				/*__BEGIN_EXPERIMENTAL_SECTION__*/
				compcuts, compdensity));
	                        /*___END_EXPERIMENTAL_SECTION___*/
	                        /*UNCOMMENT FOR PRODUCTION CODE*/
#if 0
				compcuts, NULL));
#endif

	 /* copy the arrays as they will be needed later */
	 if (!which_connected_routine &&
	     /*__BEGIN_EXPERIMENTAL_SECTION__*/
	     (vrp->par.do_greedy || vrp->par.do_our_decomp)){
	    /*___END_EXPERIMENTAL_SECTION___*/
	    /*UNCOMMENT FOR PRODUCTION CODE*/
#if 0
	    vrp->par.do_greedy){
#endif
	    compnodes_copy = (int *) memcpy((char *)compnodes_copy, 
					    (char*)compnodes,
					    (vertnum+1)*sizeof(int));
	    /*__BEGIN_EXPERIMENTAL_SECTION__*/
	    compdemands_copy = (int *) memcpy((char *)compdemands_copy,
				       (char *)compdemands, (vertnum+1)*ISIZE);
	    compcuts_copy = (double *) memcpy((char *)compcuts_copy,
					      (char *)compcuts,
					      (vertnum+1)*DSIZE);
	    /*___END_EXPERIMENTAL_SECTION___*/
	    n->compnodes = compnodes_copy;
	    comp_num = rcnt;
	 }
	 if (rcnt > 1){
	    /*---------------------------------------------------------------*\
	     * If the number of components is more then one, then check each
	     * component to see if it violates a capacity constraint
	    \*---------------------------------------------------------------*/
	    
	    coef_list = (char **) calloc(rcnt, sizeof(char *));
	    coef_list[0] = (char *) calloc(rcnt*cut_size, sizeof(char));
	    for(i = 1; i<rcnt; i++)
	       coef_list[i] = coef_list[0]+i*cut_size;
	    
	    for(i = 1; i < vertnum; i++)
	       (coef_list[(verts[i].comp)-1][i >> DELETE_POWER]) |=
		  (1 << (i & DELETE_AND));
	    
	    for (i = 0; i < rcnt; i++){
	       if (compnodes[i+1] < 2) continue;
	       /*check ith component to see if it violates a constraint*/
	       if (vrp->par.which_connected_routine == BOTH &&
		   which_connected_routine == BICONNECTED && compcuts[i+1]==0)
		  continue;
	       if (compcuts[i+1] < 2*BINS(compdemands[i+1], capacity)-etol){
		  /*the constraint is violated so impose it*/
		  new_cut->coef = (char *) (coef_list[i]);
		  new_cut->type = (compnodes[i+1] < vertnum/2 ?
				 SUBTOUR_ELIM_SIDE:SUBTOUR_ELIM_ACROSS);
		  new_cut->rhs = (new_cut->type == SUBTOUR_ELIM_SIDE ?
				  RHS(compnodes[i+1],compdemands[i+1],
				      capacity): 2*BINS(compdemands[i+1],
							capacity));
		  cg_send_cut(new_cut, num_cuts, alloc_cuts, cuts);
	       }
	       else{/*if the constraint is not violated, then try generating a
		      violated constraint by deleting customers that don't
		      change the number of trucks required by the customers in
		      the component but decrease the value of the cut*/
		  cur_bins = BINS(compdemands[i+1], capacity);/*the current
						    number of trucks required*/
		  /*current slack in the constraint*/
		  cur_slack = (compcuts[i+1] - 2*cur_bins);
		  while (compnodes[i+1]){/*while there are still nodes in the
					   component*/
		     for (max_node = 0, max_node_cut = 0, k = 1;
			  k < vertnum; k++){
			if (verts[k].comp == i+1){
			   if (BINS(compdemands[i+1]-verts[k].demand, capacity)
			       == cur_bins){
			      /*if the number of trucks doesn't decrease upon
				deleting this customer*/
			      for (node_cut = 0, cur_edge = verts[k].first;
				   cur_edge; cur_edge = cur_edge->next_edge){
				 node_cut += (cur_edge->other_end ?
					      -cur_edge->data->weight :
					      cur_edge->data->weight);
			      }
			      if (node_cut > max_node_cut){/*check whether the
					 value of the cut decrease is the best
					 seen so far*/
				 max_node = k;
				 max_node_cut = node_cut;
			      }
			   }
			}
		     }
		     if (!max_node){
			break;
		     }
		     /*delete the customer that exhibited the greatest
		       decrease in cut value*/
		     compnodes[i+1]--;
		     compdemands[i+1] -= verts[max_node].demand;
		     compcuts[i+1] -= max_node_cut;
		     cur_slack -= max_node_cut;
		     verts[max_node].comp = 0;
		     coef_list[i][max_node >> DELETE_POWER] ^=
			(1 << (max_node & DELETE_AND));
		     if (cur_slack < 0){/*if the cut is now violated, impose
					  it*/
			new_cut->coef = (char *) (coef_list[i]);
			new_cut->type = (compnodes[i+1] < vertnum/2 ?
				       SUBTOUR_ELIM_SIDE:SUBTOUR_ELIM_ACROSS);
			new_cut->size = cut_size;
			new_cut->rhs = (new_cut->type == SUBTOUR_ELIM_SIDE ?
					RHS(compnodes[i+1], compdemands[i+1],
					    capacity): 2*cur_bins);
			cg_send_cut(new_cut, num_cuts, alloc_cuts, cuts);
			break;
		     }
		  }
	       }
	    }
	    FREE(coef_list[0]);
	    FREE(coef_list);
	 }
	 which_connected_routine++;
	 FREE(compnodes);
	 FREE(compdemands);
	 FREE(compcuts);
      }while((!(*num_cuts) && vrp->par.which_connected_routine == BOTH)
Exemple #23
0
JAccount::JAccount(const QString &id) :
	Account(id, JProtocol::instance()),
	d_ptr(new JAccountPrivate(this))
{
	Q_D(JAccount);
	d->client.reset(new Client(id));
	connect(d->client.data(), SIGNAL(disconnected(Jreen::Client::DisconnectReason)),
			this, SLOT(_q_disconnected(Jreen::Client::DisconnectReason)));
	connect(d->client.data(), SIGNAL(serverFeaturesReceived(QSet<QString>)),
			this ,SLOT(_q_init_extensions(QSet<QString>)));

	Account::setStatus(Status::instance(Status::Offline, "jabber"));
	d->loadedModules = 0;
	d->roster = new JRoster(this);
	d->privacyManager = new PrivacyManager(d->client.data());
	Jreen::Capabilities::Ptr caps = d->client->presence().payload<Jreen::Capabilities>();
	caps->setNode(QLatin1String("http://qutim.org/"));
	d->privateXml = new Jreen::PrivateXml(d->client.data());
	d->pubSubManager = new Jreen::PubSub::Manager(d->client.data());
	d->conferenceManager = new JMUCManager(this, this);
	d->messageSessionManager = new JMessageSessionManager(this);
	d->softwareDetection = new JSoftwareDetection(this);
	d->client->presence().addExtension(new VCardUpdate());

	Jreen::Disco *disco = d->client->disco();
	disco->setSoftwareVersion(QLatin1String("qutIM"),
							  versionString(),
							  SystemInfo::getFullName());

	disco->addIdentity(Jreen::Disco::Identity(QLatin1String("client"),
											  QLatin1String("type"),
											  QLatin1String("qutIM"),
											  QLatin1String("en")));
	QString qutim = tr("qutIM", "Local qutIM's name");
	QString lang = tr("en", "Default language");
	if(qutim != QLatin1String("qutIM") && lang != QLatin1String("en"))
		disco->addIdentity(Jreen::Disco::Identity(QLatin1String("client"), QLatin1String("type"),qutim,lang));
	
	connect(d->roster, SIGNAL(loaded()), &d->signalMapper, SLOT(map()));
	connect(d->privacyManager, SIGNAL(listsReceived()), &d->signalMapper, SLOT(map()));
	d->signalMapper.setMapping(d->roster, 1);
	d->signalMapper.setMapping(d->privacyManager, 2);
	connect(d->client.data(), SIGNAL(connected()), d->privacyManager, SLOT(request()));
	connect(&d->signalMapper, SIGNAL(mapped(int)), this, SLOT(_q_on_module_loaded(int)));
	//	connect(d->roster, SIGNAL(loaded()), d, SLOT(onConnected()));
	//	connect(d->client.data(),SIGNAL(connected()), d, SLOT(onConnected()));
	
	d->roster->loadFromStorage();

	connect(d->conferenceManager.data(), SIGNAL(conferenceCreated(qutim_sdk_0_3::Conference*)),
			this, SIGNAL(conferenceCreated(qutim_sdk_0_3::Conference*)));
	
//	d->params.addItem<Jreen::Client>(d->client);
//	d->params.addItem<Jreen::PubSub::Manager>(d->pubSubManager);
	//	d->params.addItem<Adhoc>(p->adhoc);
	//	d->params.addItem<VCardManager>(p->vCardManager->manager());
	//	d->params.addItem<SIManager>(p->siManager);

	//	d->softwareDetection = new JSoftwareDetection(p->account, p->params);

	foreach (const ObjectGenerator *gen, ObjectGenerator::module<JabberExtension>()) {
		if (JabberExtension *ext = gen->generate<JabberExtension>()) {
			d->extensions.append(ext);
			ext->init(this);
		}
	}
}
Exemple #24
0
int main(int argc, char* argv[])
{
    // a global variable defined in errno.h that's "set by system 
    // calls and some library functions [to a nonzero value]
    // in the event of an error to indicate what went wrong"
    errno = 0;

    // default to port 8080
    int port = 8080;

    // usage
    const char* usage = "Usage: server [-p port] /path/to/root";

    // parse command-line arguments
    int opt;
    while ((opt = getopt(argc, argv, "hp:")) != -1)
    {
        switch (opt)
        {
            // -h
            case 'h':
                printf("%s\n", usage);
                return 0;

            // -p port
            case 'p':
                port = atoi(optarg);
                break;
        }
    }

    // ensure port is a non-negative short and path to server's root is specified
    if (port < 0 || port > SHRT_MAX || argv[optind] == NULL || strlen(argv[optind]) == 0)
    {
        // announce usage
        printf("%s\n", usage);

        // return 2 just like bash's builtins
        return 2;
    }

    // start server
    start(port, argv[optind]);

    // listen for SIGINT (aka control-c)
    struct sigaction act;
    act.sa_handler = handler;
    act.sa_flags = 0;
    sigemptyset(&act.sa_mask);
    sigaction(SIGINT, &act, NULL);

    // a message and its length
    char* message = NULL;
    size_t length = 0;

    // path requested
    char* path = NULL;

    // accept connections one at a time
    while (true)
    {
        // free last path, if any
        if (path != NULL)
        {
            free(path);
            path = NULL;
        }

        // free last message, if any
        if (message != NULL)
        {
            free(message);
            message = NULL;
        }
        length = 0;

        // close last client's socket, if any
        if (cfd != -1)
        {
            close(cfd);
            cfd = -1;
        }

        // check for control-c
        if (signaled)
        {
            stop();
        }

        // check whether client has connected
        if (connected())
        {
            // check for request
            if (request(&message, &length))
            {
                // extract message's request-line
                // http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html
                const char* haystack = message;
                const char* needle = strstr(haystack, "\r\n");
                if (needle == NULL)
                {
                    error(500);
                    continue;
                }
                char line[needle - haystack + 2 + 1];
                strncpy(line, haystack, needle - haystack + 2);
                line[needle - haystack + 2] = '\0';

                // log request-line
                printf("%s", line);

                // parse request-line
                char abs_path[LimitRequestLine + 1];
                char query[LimitRequestLine + 1];
                if (parse(line, abs_path, query))
                {
                    // URL-decode absolute-path
                    char* p = urldecode(abs_path);
                    if (p == NULL)
                    {
                        error(500);
                        continue;
                    }

                    // resolve absolute-path to local path
                    path = malloc(strlen(root) + strlen(p) + 1);
                    if (path == NULL)
                    {
                        error(500);
                        continue;
                    }
                    strcpy(path, root);
                    strcat(path, p);
                    free(p);

                    // ensure path exists
                    if (access(path, F_OK) == -1)
                    {
                        error(404);
                        continue;
                    }

                    // if path to directory
                    struct stat sb;
                    if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode))
                    {
                        // redirect from absolute-path to absolute-path/
                        if (abs_path[strlen(abs_path) - 1] != '/')
                        {
                            char uri[strlen(abs_path) + 1 + 1];
                            strcpy(uri, abs_path);
                            strcat(uri, "/");
                            redirect(uri);
                            continue;
                        }

                        // use path/index.php or path/index.html, if present, instead of directory's path
                        char* index = indexes(path);
                        if (index != NULL)
                        {
                            free(path);
                            path = index;
                        }

                        // list contents of directory
                        else
                        {
                            list(path);
                            continue;
                        }
                    }

                    // look up MIME type for file at path
                    const char* type = lookup(path);
                    if (type == NULL)
                    {
                        error(501);
                        continue;
                    }

                    // interpret PHP script at path
                    if (strcasecmp("text/x-php", type) == 0)
                    {
                        interpret(path, query);
                    }

                    // transfer file at path
                    else
                    {
                        transfer(path, type);
                    }
                }
            }
        }
    }
}
Exemple #25
0
/**
 * sendRequest
 * @param type const char *     "GET", "POST", ....
 * @param stream Stream *       data stream for the message body
 * @param size size_t           size for the message body if 0 not Content-Length is send
 * @return -1 if no info or > 0 when Content-Length is set by server
 */
int HTTPClient::sendRequest(const char * type, Stream * stream, size_t size) {

    if(!stream) {
        return returnError(HTTPC_ERROR_NO_STREAM);
    }

    // connect to server
    if(!connect()) {
        return returnError(HTTPC_ERROR_CONNECTION_REFUSED);
    }

    if(size > 0) {
        addHeader("Content-Length", String(size));
    }

    // send Header
    if(!sendHeader(type)) {
        return returnError(HTTPC_ERROR_SEND_HEADER_FAILED);
    }

    int buff_size = HTTP_TCP_BUFFER_SIZE;

    int len = size;
    int bytesWritten = 0;

    if(len == 0) {
        len = -1;
    }

    // if possible create smaller buffer then HTTP_TCP_BUFFER_SIZE
    if((len > 0) && (len < HTTP_TCP_BUFFER_SIZE)) {
        buff_size = len;
    }

    // create buffer for read
    uint8_t * buff = (uint8_t *) malloc(buff_size);


    if(buff) {
        // read all data from stream and send it to server
        while(connected() && (stream->available() > -1) && (len > 0 || len == -1)) {

            // get available data size
            int sizeAvailable = stream->available();

            if(sizeAvailable) {

                int readBytes = sizeAvailable;

                // read only the asked bytes
                if(len > 0 && readBytes > len) {
                    readBytes = len;
                }

                // not read more the buffer can handle
                if(readBytes > buff_size) {
                    readBytes = buff_size;
                }

                // read data
                int bytesRead = stream->readBytes(buff, readBytes);

                // write it to Stream
                int bytesWrite = _tcp->write((const uint8_t *) buff, bytesRead);
                bytesWritten += bytesWrite;

                // are all Bytes a writen to stream ?
                if(bytesWrite != bytesRead) {
                    DEBUG_HTTPCLIENT("[HTTP-Client][sendRequest] short write, asked for %d but got %d retry...\n", bytesRead, bytesWrite);

                    // check for write error
                    if(_tcp->getWriteError()) {
                        DEBUG_HTTPCLIENT("[HTTP-Client][sendRequest] stream write error %d\n", _tcp->getWriteError());

                        //reset write error for retry
                        _tcp->clearWriteError();
                    }

                    // some time for the stream
                    delay(1);

                    int leftBytes = (readBytes - bytesWrite);

                    // retry to send the missed bytes
                    bytesWrite = _tcp->write((const uint8_t *) (buff + bytesWrite), leftBytes);
                    bytesWritten += bytesWrite;

                    if(bytesWrite != leftBytes) {
                        // failed again
                        DEBUG_HTTPCLIENT("[HTTP-Client][sendRequest] short write, asked for %d but got %d failed.\n", leftBytes, bytesWrite);
                        free(buff);
                        return returnError(HTTPC_ERROR_SEND_PAYLOAD_FAILED);
                    }
                }

                // check for write error
                if(_tcp->getWriteError()) {
                    DEBUG_HTTPCLIENT("[HTTP-Client][sendRequest] stream write error %d\n", _tcp->getWriteError());
                    free(buff);
                    return returnError(HTTPC_ERROR_SEND_PAYLOAD_FAILED);
                }

                // count bytes to read left
                if(len > 0) {
                    len -= readBytes;
                }

                delay(0);
            } else {
                delay(1);
            }
        }

        free(buff);

        if(size && (int) size != bytesWritten) {
            DEBUG_HTTPCLIENT("[HTTP-Client][sendRequest] Stream payload bytesWritten %d and size %d mismatch!.\n", bytesWritten, size);
            DEBUG_HTTPCLIENT("[HTTP-Client][sendRequest] ERROR SEND PAYLOAD FAILED!");
            return returnError(HTTPC_ERROR_SEND_PAYLOAD_FAILED);
        } else {
            DEBUG_HTTPCLIENT("[HTTP-Client][sendRequest] Stream payload written: %d\n", bytesWritten);
        }

    } else {
        DEBUG_HTTPCLIENT("[HTTP-Client][sendRequest] too less ram! need %d\n", HTTP_TCP_BUFFER_SIZE);
        return returnError(HTTPC_ERROR_TOO_LESS_RAM);
    }

    // handle Server Response (Header)
    return returnError(handleHeaderResponse());
}
Exemple #26
0
bool CSSLComm::PushNotification(const char *pToken, const char *pMsg)
{
    CMyLock lock(&m_lock);
	bool bResult = false;

	if (connected()) {
		// 填入数据
		PUSHDATA pushdata;
		memset(&pushdata, 0, sizeof(pushdata));
		int nDataLen = Gen(pToken, pMsg, pushdata);
		
		// 发送
		//for (int i = 0; i < 10; i++) {
			int ret = SSL_write(m_pssl, (void*)&pushdata, nDataLen);
			printf("ret:%d, nDataLen:%d, Identifier:%d\n", ret, nDataLen, pushdata.nIdentifier);
			if (ret == nDataLen) {
				//// 发送成功
				//unsigned char buffer[1024] = {0};
				//int len = SSL_read(m_pssl, buffer, sizeof(buffer));
				//printf("len:%d\n", len);
				//if (len >= sizeof(PUSHRETURN)) {
				//	PUSHRETURN* pPushReturn = (PUSHRETURN*)buffer;
				//	printf("Command:%d, Status:%d, Identifier:%d\n", pPushReturn->nCommand, pPushReturn->nStatus, pPushReturn->nIdentifier);
				//	switch(pPushReturn->nStatus) 
				//	{
				//	case 0:
				//		printf("Success\n");
				//		break;
				//	case 1:
				//		printf("Processing error\n");
				//		break;
				//	case 2:
				//		printf("Missing device token\n");
				//		break;
				//	case 3:
				//		printf("Missing topic\n");
				//		break;
				//	case 4:
				//		printf("Missing payload\n");
				//		break;
				//	case 5:
				//		printf("Invalid token size\n");
				//		break;
				//	case 6:
				//		printf("Invalid topic size\n");
				//		break;
				//	case 7:
				//		printf("Invalid payload size\n");
				//		break;
				//	case 8:
				//		printf("Invalid token\n");
				//		break;
				//	case 10:
				//		printf("Shutdown\n");
				//		break;
				//	case 255:
				//		printf("None (unknown)\n");
				//		break;
				//	}
				//}
			}
			printf("\n");
			//int ret1 = SSL_read(m_pssl, buffer, 10240);
			//ret = SSL_write(m_pssl, (void*)"123456789", 10);
			//ret = SSL_get_error(m_pssl, ret); //SSL_ERROR_SSL
			bResult = ret > 0;
		//}
	}

	/*int paylen = GenPayloadData(1,pMsg);
    GenPushData(pToken);
    int ret = SSL_write(m_pssl, (void*)&m_data, 35 + paylen);*/

	return bResult;
}
Exemple #27
0
/**
 * reads the response from the server
 * @return int http code
 */
int HTTPClient::handleHeaderResponse() {

    if(!connected()) {
        return HTTPC_ERROR_NOT_CONNECTED;
    }
    String transferEncoding;
    _returnCode = -1;
    _size = -1;
    _transferEncoding = HTTPC_TE_IDENTITY;

    while(connected()) {
        size_t len = _tcp->available();
        if(len > 0) {
            String headerLine = _tcp->readStringUntil('\n');
            headerLine.trim(); // remove \r

            DEBUG_HTTPCLIENT("[HTTP-Client][handleHeaderResponse] RX: '%s'\n", headerLine.c_str());

            if(headerLine.startsWith("HTTP/1.")) {
                _returnCode = headerLine.substring(9, headerLine.indexOf(' ', 9)).toInt();
            } else if(headerLine.indexOf(':')) {
                String headerName = headerLine.substring(0, headerLine.indexOf(':'));
                String headerValue = headerLine.substring(headerLine.indexOf(':') + 2);

                if(headerName.equalsIgnoreCase("Content-Length")) {
                    _size = headerValue.toInt();
                }

                if(headerName.equalsIgnoreCase("Connection")) {
                    _canReuse = headerValue.equalsIgnoreCase("keep-alive");
                }

                if(headerName.equalsIgnoreCase("Transfer-Encoding")) {
                    transferEncoding = headerValue;
                }

                for(size_t i = 0; i < _headerKeysCount; i++) {
                    if(_currentHeaders[i].key.equalsIgnoreCase(headerName)) {
                        _currentHeaders[i].value = headerValue;
                        break;
                    }
                }
            }

            if(headerLine == "") {
                DEBUG_HTTPCLIENT("[HTTP-Client][handleHeaderResponse] code: %d\n", _returnCode);

                if(_size > 0) {
                    DEBUG_HTTPCLIENT("[HTTP-Client][handleHeaderResponse] size: %d\n", _size);
                }

                if(transferEncoding.length() > 0) {
                    DEBUG_HTTPCLIENT("[HTTP-Client][handleHeaderResponse] Transfer-Encoding: %s\n", transferEncoding.c_str());
                    if(transferEncoding.equalsIgnoreCase("chunked")) {
                        _transferEncoding = HTTPC_TE_CHUNKED;
                    } else {
                        return HTTPC_ERROR_ENCODING;
                    }
                } else {
                    _transferEncoding = HTTPC_TE_IDENTITY;
                }

                if(_returnCode) {
                    return _returnCode;
                } else {
                    DEBUG_HTTPCLIENT("[HTTP-Client][handleHeaderResponse] Remote host is not an HTTP Server!");
                    return HTTPC_ERROR_NO_HTTP_SERVER;
                }
            }

        } else {
            delay(0);
        }
    }

    return HTTPC_ERROR_CONNECTION_LOST;
}
Exemple #28
0
void HttpPoll::http_result()
{
	// check for death :)
	QPointer<QObject> self = this;
	syncFinished();
	if(!self)
		return;

	// get id and packet
	QString id;
	QString cookie = d->http.getHeader("Set-Cookie");
	int n = cookie.indexOf("ID=");
	if(n == -1) {
		reset();
		error(ErrRead);
		return;
	}
	n += 3;
	int n2 = cookie.indexOf(';', n);
	if(n2 != -1)
		id = cookie.mid(n, n2-n);
	else
		id = cookie.mid(n);
	QByteArray block = d->http.body();

	// session error?
	if(id.right(2) == ":0") {
		if(id == "0:0" && d->state == 2) {
			reset();
			connectionClosed();
			return;
		}
		else {
			reset();
			error(ErrRead);
			return;
		}
	}

	d->ident = id;
	bool justNowConnected = false;
	if(d->state == 1) {
		d->state = 2;
		justNowConnected = true;
	}

	// sync up again soon
	if(bytesToWrite() > 0 || !d->closing) {
		d->t->start(d->polltime * 1000);
  }

	// connecting
	if(justNowConnected) {
		connected();
	}
	else {
		if(!d->out.isEmpty()) {
			int x = d->out.size();
			d->out.resize(0);
			takeWrite(x);
			bytesWritten(x);
		}
	}

	if(!self)
		return;

	if(!block.isEmpty()) {
		appendRead(block);
		readyRead();
	}

	if(!self)
		return;

	if(bytesToWrite() > 0) {
		do_sync();
	}
	else {
		if(d->closing) {
			reset();
			delayedCloseFinished();
			return;
		}
	}
}
void HTTPClientSession::setHost(const std::string& host) {
    if (!connected())
        _host = host;
    else
        throw IllegalStateException("Cannot set the host for an already connected session");
}
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
{
    _port = new QSpinBox(this);
    _port->setMaximum(99999);
    _port->setValue(8796);
    _host = new QLineEdit(this);
    _host->setFixedWidth(100);
    _connectServer = new QPushButton(tr("Connect"), this);
    _connectServer->setCheckable(true);
    _consult = new QPushButton(tr("Consult"), this);
    _sendCmd  = new QPushButton(tr("Send"), this);
    _cmd  = new QLineEdit(this);
    _serverOutput = new QTextEdit(this);
    _serverOutput->setReadOnly(true);
    _codeEditor = new CodeEditor(this);

    _consult->setEnabled(false);
    _cmd->setEnabled(false);
    _sendCmd->setEnabled(false);

    _client = new Client();

    QObject::connect(_connectServer, SIGNAL(clicked(bool)), this, SLOT(changeServerStatus(bool)));
    QObject::connect(_client, SIGNAL(connected()), this, SLOT(serverConnected()));
    QObject::connect(_client, SIGNAL(disconnected()), this, SLOT(serverDisconnected()));
    QObject::connect(_client, SIGNAL(dataReceived(QString)), this, SLOT(writeServerOutput(QString)));
    QObject::connect(_client, SIGNAL(errorSocket(QString)), this, SLOT(writeServerOutput(QString)));
    QObject::connect(_sendCmd, SIGNAL(clicked()), this, SLOT(sendCmd()));
    QObject::connect(_consult, SIGNAL(clicked()), this, SLOT(consultFile()));

    QHBoxLayout *layoutHeader = new QHBoxLayout;
    layoutHeader->setContentsMargins(10,0,0,10);
    layoutHeader->addWidget(new QLabel(tr("Host"), this));
    layoutHeader->addWidget(_host);
    layoutHeader->addSpacing(10);
    layoutHeader->addWidget(new QLabel(tr("Port"), this));
    layoutHeader->addWidget(_port);
    layoutHeader->addStretch(100);
    layoutHeader->addWidget(_connectServer);

    QSplitter *centralSplitter = new QSplitter(this);
    centralSplitter->addWidget(_codeEditor);
    centralSplitter->addWidget(_serverOutput);

    QHBoxLayout *layoutBottom = new QHBoxLayout;
    layoutBottom->addWidget(_consult, 1);
    layoutBottom->addWidget(_cmd, 100);
    layoutBottom->addWidget(_sendCmd, 1);

    QVBoxLayout *mainLayout = new QVBoxLayout;
    mainLayout->setMargin(0);
    mainLayout->setSpacing(0);
    mainLayout->addLayout(layoutHeader, 1);
    mainLayout->addWidget(centralSplitter);
    mainLayout->addLayout(layoutBottom, 1);

    QWidget *centralWidget = new QWidget(this);
    centralWidget->setLayout(mainLayout);

    this->setCentralWidget(centralWidget);
}