void RequestParameters::parseUrl(const QUrl & url)
{
    if (!url.hasQuery())
    {
        return;
    }

    QList<QPair<QString, QVariant >> parameters;

    for (const QString & parameter : url.query().split('&'))
    {
        int splitIndex = parameter.indexOf('=');
        if (splitIndex<=0)
        {
            continue;
        }

        QString key = parameter.left(splitIndex);
        QString value = parameter.mid(splitIndex + 1);

        parameters << QPair<QString, QVariant>(key, value);
    }

    parseList(parameters);
}
Example #2
0
bool QUrlProto::hasQuery() const
{
  QUrl *item = qscriptvalue_cast<QUrl*>(thisObject());
  if (item)
    return item->hasQuery();
  return false;
}
Example #3
0
/*!
    Constructs a QUrlQuery object and parses the query string found in the \a
    url URL, using the default query delimiters. To parse a query string using
    other delimiters, you should first set them using setQueryDelimiters() and
    then set the query with setQuery().

    \sa QUrl::query()
*/
QUrlQuery::QUrlQuery(const QUrl &url)
    : d(0)
{
    // use internals to avoid unnecessary recoding
    // ### FIXME: actually do it
    if (url.hasQuery())
        d = new QUrlQueryPrivate(url.query());
}
Example #4
0
QUrl MainWindow::addQuery(QUrl url, QString key, QString value) {
  QString url_s = url.toDisplayString();

  if (url.hasQuery()) {
    url_s += "&" + key + "=" + value;
  } else {
    url_s += "?" + key + "=" + value;
  }

  return QUrl(url_s);
}
Example #5
0
QUrl BrowseWidget::addQuery(const QUrl &t_url, const QString &t_key,
                            const QString &t_value) {
  QString url = t_url.toDisplayString();

  if (t_url.hasQuery()) {
    url += "&" + t_key + "=" + t_value;
  } else {
    url += "?" + t_key + "=" + t_value;
  }

  return QUrl(url);
}
Example #6
0
HttpEngine::HttpEngine(QUrl url, QUrl referrer, QUuid proxyUuid) : m_pRemote(0), m_url(url)
{
	QString user_info;
	QString query, host;
//	QList<Proxy> listProxy = Proxy::loadProxys();


    m_proxyData.nType = Proxy::ProxyNone;
	
    host = url.host();
    if(url.port(80) != 80)
        host += QString(":") + QString::number(url.port(80));


    if (Proxy::isProxyEnabled()){
        Proxy p = Proxy:: loadProxy();
        if(p.uuid == proxyUuid)
        {
            m_proxyData = p;

        }
    }

	
	if(!url.hasQuery())
		query = url.path();
	else
		query = url.path()+"?"+url.encodedQuery();
	
	if(query.isEmpty())
		query = "/";
	
	if(m_proxyData.nType == Proxy::ProxyHttp)
	{
		m_header.setRequest("GET", QString("%1://%2%3").arg(url.scheme()).arg(host).arg(query));
		if(!m_proxyData.strUser.isEmpty())
			m_header.addValue("Proxy-Authorization", QString("Basic %1").arg((QString) (m_proxyData.strUser+":"+m_proxyData.strPassword).toUtf8().toBase64()) );
	}
	else
		m_header.setRequest("GET", query);
	
	user_info = url.userInfo();
	if(!user_info.isEmpty())
		m_header.addValue("Authorization", QString("Basic %1").arg( QString(user_info.toUtf8().toBase64()) ));
	
	if(referrer.isValid())
		m_header.addValue("Referrer", referrer.toString());
	
	m_header.addValue("Host", host);
	m_header.addValue("Connection", "close");
}
Example #7
0
QUrl BrowseWidget::addPage(const QUrl &t_url, const int t_page) {
  QString url = t_url.toDisplayString();

  if (t_url.hasQuery()) {
    if (url.contains("page=[0-9]")) {
      url.replace("page=[0-9]", "page=" + QString::number(t_page));
    } else {
      url += "&page=" + QString::number(t_page);
    }
  } else {
    url += "?page=" + QString::number(t_page);
  }

  return QUrl(url);
}
Example #8
0
QUrl MainWindow::addPage(QUrl url, int page) {
  QString url_s = url.toDisplayString();

  if (url.hasQuery()) {
    if (url_s.contains("page=[0-9]")) {
      url_s.replace("page=[0-9]", "page=" + QString::number(page));
    } else {
      url_s += "&page=" + QString::number(page);
    }
  } else {
    url_s += "?page=" + QString::number(page);
  }

  return QUrl(url_s);
}
Example #9
0
QString QzTools::urlEncodeQueryString(const QUrl &url)
{
    QString returnString = url.toString(QUrl::RemoveQuery | QUrl::RemoveFragment);

    if (url.hasQuery()) {
        returnString += QLatin1Char('?') + url.query(QUrl::FullyEncoded);
    }

    if (url.hasFragment()) {
        returnString += QLatin1Char('#') + url.fragment(QUrl::FullyEncoded);
    }

    returnString.replace(QLatin1Char(' '), QLatin1String("%20"));

    return returnString;
}
Example #10
0
    void 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);

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

        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);
        }
    }
Example #11
0
bool ActionURLHandlerWebEngine::handleClick(const QUrl &url, ArticleViewerWebEngine *articleViewer) const
{
    if (url.scheme() == QLatin1String("akregatoraction")) {
        const QString urlPath(url.path());
        if (url.hasQuery()) {
            const QUrlQuery urlQuery(url);
            const QString articleId = urlQuery.queryItemValue(QStringLiteral("id"));
            const QString feed = urlQuery.queryItemValue(QStringLiteral("feed"));
            if (!articleId.isEmpty()) {
                if (urlPath == QLatin1String("delete")) {
                    articleViewer->setArticleAction(ArticleViewerWebEngine::DeleteAction, articleId, feed);
                    return true;
                } else if (urlPath == QLatin1String("markAsRead")) {
                    articleViewer->setArticleAction(ArticleViewerWebEngine::MarkAsRead, articleId, feed);
                    return true;
                } else if (urlPath == QLatin1String("markAsUnRead")) {
                    articleViewer->setArticleAction(ArticleViewerWebEngine::MarkAsUnRead, articleId, feed);
                    return true;
                } else if (urlPath == QLatin1String("markAsImportant")) {
                    articleViewer->setArticleAction(ArticleViewerWebEngine::MarkAsImportant, articleId, feed);
                    return true;
                } else if (urlPath == QLatin1String("sendUrlArticle")) {
                    articleViewer->setArticleAction(ArticleViewerWebEngine::SendUrlArticle, articleId, feed);
                    return true;
                } else if (urlPath == QLatin1String("sendFileArticle")) {
                    articleViewer->setArticleAction(ArticleViewerWebEngine::SendFileArticle, articleId, feed);
                    return true;
                } else if (urlPath == QLatin1String("openInExternalBrowser")) {
                    articleViewer->setArticleAction(ArticleViewerWebEngine::OpenInExternalBrowser, articleId, feed);
                    return true;
                } else if (urlPath == QLatin1String("share")) {
                    articleViewer->setArticleAction(ArticleViewerWebEngine::Share, articleId, feed);
                    return true;
                } else if (urlPath == QLatin1String("openInBackgroundTab")) {
                    articleViewer->setArticleAction(ArticleViewerWebEngine::OpenInBackgroundTab, articleId, feed);
                    return true;
                }
            }
        } else {
            qCWarning(AKREGATOR_LOG) << "Undefined article id";
            return true;
        }
    }
    return false;
}
Example #12
0
void HttpComms::request(QUrl &url, int timeoutms, bool allowGzip)
{
    QString path = url.path();

    if (url.hasQuery())
        path += '?' + url.encodedQuery();

    QHttpRequestHeader header("GET", path);
    QString userAgent = "Mozilla/9.876 (X11; U; Linux 2.2.12-20 i686, en) "
                        "Gecko/25250101 Netscape/5.432b1";

    header.setValue("Host", url.host());
    header.setValue("User-Agent", userAgent);
    
    if (allowGzip)
        header.setValue( "Accept-Encoding", "gzip");
    
    request(url, header, timeoutms);
}
Example #13
0
    void setUrl(const QUrl &url)
    {
        QString hdr;
        hdr = QString("GET %PATH% HTTP/1.1\r\n"
                      "Host: %HOST%\r\n"
                      "User-Agent: MythMusic/%VERSION%\r\n"
                      "Accept: */*\r\n");

        QString path = url.path();
        QString host = url.host();

        if (path.isEmpty())
            path = "/";

        if (url.hasQuery())
            path += '?' + url.encodedQuery();

        if (url.port() != -1)
            host += QString(":%1").arg(url.port());

        hdr.replace("%PATH%", path);
        hdr.replace("%HOST%", host);
        hdr.replace("%VERSION%", MYTH_BINARY_VERSION);

        if (!url.userName().isEmpty() && !url.password().isEmpty()) 
        {
            QString authstring = url.userName() + ":" + url.password();
            QString auth = QCodecs::base64Encode(authstring.toLocal8Bit());

            hdr += "Authorization: Basic " + auth + "\r\n";
        }

        hdr += QString("TE: trailers\r\n"
                       "Icy-Metadata: 1\r\n"
                       "\r\n");

        LOG(VB_NETWORK, LOG_INFO, QString("ShoutCastRequest: '%1'").arg(hdr));

        m_data = hdr.toAscii();
    }
Example #14
0
static void extractMimeTypeFor(const QUrl& url, QString& mimeType)
{
    const QString fname(url.fileName());
 
    if (fname.isEmpty() || url.hasFragment() || url.hasQuery())
        return;
 
    KMimeType::Ptr pmt = KMimeType::findByPath(fname, 0, true);

    // Further check for mime types guessed from the extension which,
    // on a web page, are more likely to be a script delivering content
    // of undecidable type. If the mime type from the extension is one
    // of these, don't use it.  Retain the original type 'text/html'.
    if (pmt->name() == KMimeType::defaultMimeType() ||
        pmt->is(QL1S("application/x-perl")) ||
        pmt->is(QL1S("application/x-perl-module")) ||
        pmt->is(QL1S("application/x-php")) ||
        pmt->is(QL1S("application/x-python-bytecode")) ||
        pmt->is(QL1S("application/x-python")) ||
        pmt->is(QL1S("application/x-shellscript")))
        return;

    mimeType = pmt->name();
}
Example #15
0
QString QzTools::urlEncodeQueryString(const QUrl &url)
{
    QString returnString = url.toString(QUrl::RemoveQuery | QUrl::RemoveFragment);

    if (url.hasQuery()) {
#if QT_VERSION >= 0x050000
        returnString += QLatin1Char('?') + url.query(QUrl::FullyEncoded);
#else
        returnString += QLatin1Char('?') + url.encodedQuery();
#endif
    }

    if (url.hasFragment()) {
#if QT_VERSION >= 0x050000
        returnString += QLatin1Char('#') + url.fragment(QUrl::FullyEncoded);
#else
        returnString += QLatin1Char('#') + url.encodedFragment();
#endif
    }

    returnString.replace(QLatin1Char(' '), QLatin1String("%20"));

    return returnString;
}
Example #16
0
void KWebKitPart::slotLinkHovered(const QString& _link, const QString& /*title*/, const QString& /*content*/)
{
    QString message;

    if (_link.isEmpty()) {
        message = QL1S("");
        emit m_browserExtension->mouseOverInfo(KFileItem());
    } else {
        QUrl linkUrl (_link);
        const QString scheme = linkUrl.scheme();

        // Protect the user against URL spoofing!
        linkUrl.setUserName(QString());
        const QString link (linkUrl.toString());

        if (QString::compare(scheme, QL1S("mailto"), Qt::CaseInsensitive) == 0) {
            message += i18nc("status bar text when hovering email links; looks like \"Email: [email protected] - CC: [email protected] -BCC: [email protected] - Subject: Hi translator\"", "Email: ");

            // Workaround: for QUrl's parsing deficiencies of "mailto:[email protected]".
            if (!linkUrl.hasQuery())
              linkUrl = QUrl(scheme + '?' + linkUrl.path());

            QMap<QString, QStringList> fields;
            QList<QPair<QString, QString> > queryItems = linkUrl.queryItems();
            const int count = queryItems.count();

            for(int i = 0; i < count; ++i) {
                const QPair<QString, QString> queryItem (queryItems.at(i));
                //kDebug() << "query: " << queryItem.first << queryItem.second;
                if (queryItem.first.contains(QL1C('@')) && queryItem.second.isEmpty())
                    fields["to"] << queryItem.first;
                if (QString::compare(queryItem.first, QL1S("to"), Qt::CaseInsensitive) == 0)
                    fields["to"] << queryItem.second;
                if (QString::compare(queryItem.first, QL1S("cc"), Qt::CaseInsensitive) == 0)
                    fields["cc"] << queryItem.second;
                if (QString::compare(queryItem.first, QL1S("bcc"), Qt::CaseInsensitive) == 0)
                    fields["bcc"] << queryItem.second;
                if (QString::compare(queryItem.first, QL1S("subject"), Qt::CaseInsensitive) == 0)
                    fields["subject"] << queryItem.second;
            }

            if (fields.contains(QL1S("to")))
                message += fields.value(QL1S("to")).join(QL1S(", "));
            if (fields.contains(QL1S("cc")))
                message += i18nc("status bar text when hovering email links; looks like \"Email: [email protected] - CC: [email protected] -BCC: [email protected] - Subject: Hi translator\"", " - CC: ") + fields.value(QL1S("cc")).join(QL1S(", "));
            if (fields.contains(QL1S("bcc")))
                message += i18nc("status bar text when hovering email links; looks like \"Email: [email protected] - CC: [email protected] -BCC: [email protected] - Subject: Hi translator\"", " - BCC: ") + fields.value(QL1S("bcc")).join(QL1S(", "));
            if (fields.contains(QL1S("subject")))
                message += i18nc("status bar text when hovering email links; looks like \"Email: [email protected] - CC: [email protected] -BCC: [email protected] - Subject: Hi translator\"", " - Subject: ") + fields.value(QL1S("subject")).join(QL1S(" "));
        } else if (scheme == QL1S("javascript")) {
            message = KStringHandler::rsqueeze(link, 150);
            if (link.startsWith(QL1S("javascript:window.open")))
                message += i18n(" (In new window)");
        } else {
            message = link;
            QWebFrame* frame = page() ? page()->currentFrame() : 0;
            if (frame) {
                QWebHitTestResult result = frame->hitTestContent(page()->view()->mapFromGlobal(QCursor::pos()));
                QWebFrame* target = result.linkTargetFrame();
                if (frame->parentFrame() && target == frame->parentFrame()) {
                    message += i18n(" (In parent frame)");
                } else if (!target || target != frame) {
                    message += i18n(" (In new window)");
                }
            }
            KFileItem item (linkUrl, QString(), KFileItem::Unknown);
            emit m_browserExtension->mouseOverInfo(item);
        }
    }

    emit setStatusBarText(message);
}
void AbstractNetworkJob::slotFinished()
{
    _timer.stop();

    if (_reply->error() == QNetworkReply::SslHandshakeFailedError) {
        qCWarning(lcNetworkJob) << "SslHandshakeFailedError: " << errorString() << " : can be caused by a webserver wanting SSL client certificates";
    }

    if (_reply->error() != QNetworkReply::NoError) {
        if (!_ignoreCredentialFailure || _reply->error() != QNetworkReply::AuthenticationRequiredError) {
            qCWarning(lcNetworkJob) << _reply->error() << errorString()
                                    << _reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
            if (_reply->error() == QNetworkReply::ProxyAuthenticationRequiredError) {
                qCWarning(lcNetworkJob) << _reply->rawHeader("Proxy-Authenticate");
            }
        }
        emit networkError(_reply);
    }

    // get the Date timestamp from reply
    _responseTimestamp = _reply->rawHeader("Date");

    QUrl requestedUrl = reply()->request().url();
    QUrl redirectUrl = reply()->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
    if (_followRedirects && !redirectUrl.isEmpty()) {
        // Redirects may be relative
        if (redirectUrl.isRelative())
            redirectUrl = requestedUrl.resolved(redirectUrl);

        // For POST requests where the target url has query arguments, Qt automatically
        // moves these arguments to the body if no explicit body is specified.
        // This can cause problems with redirected requests, because the redirect url
        // will no longer contain these query arguments.
        if (reply()->operation() == QNetworkAccessManager::PostOperation
            && requestedUrl.hasQuery()
            && !redirectUrl.hasQuery()
            && !_requestBody) {
            qCWarning(lcNetworkJob) << "Redirecting a POST request with an implicit body loses that body";
        }

        // ### some of the qWarnings here should be exported via displayErrors() so they
        // ### can be presented to the user if the job executor has a GUI
        QByteArray verb = requestVerb(*reply());
        if (requestedUrl.scheme() == QLatin1String("https") && redirectUrl.scheme() == QLatin1String("http")) {
            qCWarning(lcNetworkJob) << this << "HTTPS->HTTP downgrade detected!";
        } else if (requestedUrl == redirectUrl || _redirectCount + 1 >= maxRedirects()) {
            qCWarning(lcNetworkJob) << this << "Redirect loop detected!";
        } else if (_requestBody && _requestBody->isSequential()) {
            qCWarning(lcNetworkJob) << this << "cannot redirect request with sequential body";
        } else if (verb.isEmpty()) {
            qCWarning(lcNetworkJob) << this << "cannot redirect request: could not detect original verb";
        } else {
            emit redirected(_reply, redirectUrl, _redirectCount);

            // The signal emission may have changed this value
            if (_followRedirects) {
                _redirectCount++;

                // Create the redirected request and send it
                qCInfo(lcNetworkJob) << "Redirecting" << verb << requestedUrl << redirectUrl;
                resetTimeout();
                if (_requestBody) {
                    _requestBody->seek(0);
                }
                sendRequest(
                    verb,
                    redirectUrl,
                    reply()->request(),
                    _requestBody);
                return;
            }
        }
    }

    AbstractCredentials *creds = _account->credentials();
    if (!creds->stillValid(_reply) && !_ignoreCredentialFailure) {
        _account->handleInvalidCredentials();
    }

    bool discard = finished();
    if (discard) {
        qCDebug(lcNetworkJob) << "Network job" << metaObject()->className() << "finished for" << path();
        deleteLater();
    }
}
Example #18
0
int Url::hasQuery ( lua_State * L )// const : bool
{
	QUrl* lhs = ValueInstaller2<QUrl>::check( L, 1 );
	Util::push( L, lhs->hasQuery() );
	return 1;
}
Example #19
0
bool isRootUrl(const QUrl &url)
{
    const QString path = url.adjusted(QUrl::StripTrailingSlash).path();
    return(!url.hasQuery() &&
           (path.isEmpty() || path == QLatin1String("/")));
}
Example #20
0
QDomDocument getCapabilities( QgsServerInterface* serverIface, const QString& version,
                              const QgsServerRequest& request, bool projectSettings )
{
    QDomDocument doc;
    QDomElement wmsCapabilitiesElement;

    QgsWmsConfigParser* configParser = getConfigParser( serverIface );

    QgsServerRequest::Parameters parameters = request.parameters();

    // Get service URL
    QUrl href = serviceUrl( request, configParser );

    //href needs to be a prefix
    QString hrefString = href.toString( QUrl::FullyDecoded );
    hrefString.append( href.hasQuery() ? "&" : "?" );

    // XML declaration
    QDomProcessingInstruction xmlDeclaration = doc.createProcessingInstruction( QStringLiteral( "xml" ),
            QStringLiteral( "version=\"1.0\" encoding=\"utf-8\"" ) );

    // Append format helper
    std::function < void ( QDomElement&, const QString& ) > appendFormat = [&doc]( QDomElement & elem, const QString & format )
    {
        QDomElement formatElem = doc.createElement( QStringLiteral( "Format" )/*wms:Format*/ );
        formatElem.appendChild( doc.createTextNode( format ) );
        elem.appendChild( formatElem );
    };

    if ( version == QLatin1String( "1.1.1" ) )
    {
        doc = QDomDocument( QStringLiteral( "WMT_MS_Capabilities SYSTEM 'http://schemas.opengis.net/wms/1.1.1/WMS_MS_Capabilities.dtd'" ) );  //WMS 1.1.1 needs DOCTYPE  "SYSTEM http://schemas.opengis.net/wms/1.1.1/WMS_MS_Capabilities.dtd"
        doc.appendChild( xmlDeclaration );
        wmsCapabilitiesElement = doc.createElement( QStringLiteral( "WMT_MS_Capabilities" )/*wms:WMS_Capabilities*/ );
    }
    else // 1.3.0 as default
    {
        doc.appendChild( xmlDeclaration );
        wmsCapabilitiesElement = doc.createElement( QStringLiteral( "WMS_Capabilities" )/*wms:WMS_Capabilities*/ );
        wmsCapabilitiesElement.setAttribute( QStringLiteral( "xmlns" ), QStringLiteral( "http://www.opengis.net/wms" ) );
        wmsCapabilitiesElement.setAttribute( QStringLiteral( "xmlns:sld" ), QStringLiteral( "http://www.opengis.net/sld" ) );
        wmsCapabilitiesElement.setAttribute( QStringLiteral( "xmlns:qgs" ), QStringLiteral( "http://www.qgis.org/wms" ) );
        wmsCapabilitiesElement.setAttribute( QStringLiteral( "xmlns:xsi" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema-instance" ) );
        QString schemaLocation = QStringLiteral( "http://www.opengis.net/wms" );
        schemaLocation += QLatin1String( " http://schemas.opengis.net/wms/1.3.0/capabilities_1_3_0.xsd" );
        schemaLocation += QLatin1String( " http://www.opengis.net/sld" );
        schemaLocation += QLatin1String( " http://schemas.opengis.net/sld/1.1.0/sld_capabilities.xsd" );
        schemaLocation += QLatin1String( " http://www.qgis.org/wms" );
        if ( configParser && configParser->wmsInspireActivated() )
        {
            wmsCapabilitiesElement.setAttribute( QStringLiteral( "xmlns:inspire_common" ), QStringLiteral( "http://inspire.ec.europa.eu/schemas/common/1.0" ) );
            wmsCapabilitiesElement.setAttribute( QStringLiteral( "xmlns:inspire_vs" ), QStringLiteral( "http://inspire.ec.europa.eu/schemas/inspire_vs/1.0" ) );
            schemaLocation += QLatin1String( " http://inspire.ec.europa.eu/schemas/inspire_vs/1.0" );
            schemaLocation += QLatin1String( " http://inspire.ec.europa.eu/schemas/inspire_vs/1.0/inspire_vs.xsd" );
        }

        schemaLocation += " " + hrefString + "SERVICE=WMS&REQUEST=GetSchemaExtension";
        wmsCapabilitiesElement.setAttribute( QStringLiteral( "xsi:schemaLocation" ), schemaLocation );
    }
    wmsCapabilitiesElement.setAttribute( QStringLiteral( "version" ), version );
    doc.appendChild( wmsCapabilitiesElement );

    configParser->serviceCapabilities( wmsCapabilitiesElement, doc );

    //wms:Capability element
    QDomElement capabilityElement = doc.createElement( QStringLiteral( "Capability" )/*wms:Capability*/ );
    wmsCapabilitiesElement.appendChild( capabilityElement );
    //wms:Request element
    QDomElement requestElement = doc.createElement( QStringLiteral( "Request" )/*wms:Request*/ );
    capabilityElement.appendChild( requestElement );

    QDomElement dcpTypeElement = doc.createElement( QStringLiteral( "DCPType" )/*wms:DCPType*/ );
    QDomElement httpElement = doc.createElement( QStringLiteral( "HTTP" )/*wms:HTTP*/ );
    dcpTypeElement.appendChild( httpElement );

    QDomElement elem;

    //wms:GetCapabilities
    elem = doc.createElement( QStringLiteral( "GetCapabilities" )/*wms:GetCapabilities*/ );
    appendFormat( elem, ( version == QLatin1String( "1.1.1" ) ? "application/vnd.ogc.wms_xml" : "text/xml" ) );
    elem.appendChild( dcpTypeElement );
    requestElement.appendChild( elem );

    // SOAP platform
    //only give this information if it is not a WMS request to be in sync with the WMS capabilities schema
    // XXX Not even sure that cam be ever true
    if ( parameters.value( QStringLiteral( "SERVICE" ) ).compare( QLatin1String( "WMS" ), Qt::CaseInsensitive ) != 0 )
    {
        QDomElement soapElement = doc.createElement( QStringLiteral( "SOAP" )/*wms:SOAP*/ );
        httpElement.appendChild( soapElement );
        QDomElement soapResourceElement = doc.createElement( QStringLiteral( "OnlineResource" )/*wms:OnlineResource*/ );
        soapResourceElement.setAttribute( QStringLiteral( "xmlns:xlink" ), QStringLiteral( "http://www.w3.org/1999/xlink" ) );
        soapResourceElement.setAttribute( QStringLiteral( "xlink:type" ), QStringLiteral( "simple" ) );
        soapResourceElement.setAttribute( QStringLiteral( "xlink:href" ), hrefString );
        soapElement.appendChild( soapResourceElement );
    }

    //only Get supported for the moment
    QDomElement getElement = doc.createElement( QStringLiteral( "Get" )/*wms:Get*/ );
    httpElement.appendChild( getElement );
    QDomElement olResourceElement = doc.createElement( QStringLiteral( "OnlineResource" )/*wms:OnlineResource*/ );
    olResourceElement.setAttribute( QStringLiteral( "xmlns:xlink" ), QStringLiteral( "http://www.w3.org/1999/xlink" ) );
    olResourceElement.setAttribute( QStringLiteral( "xlink:type" ), QStringLiteral( "simple" ) );
    olResourceElement.setAttribute( QStringLiteral( "xlink:href" ), hrefString );
    getElement.appendChild( olResourceElement );

    //wms:GetMap
    elem = doc.createElement( QStringLiteral( "GetMap" )/*wms:GetMap*/ );
    appendFormat( elem, QStringLiteral( "image/jpeg" ) );
    appendFormat( elem, QStringLiteral( "image/png" ) );
    appendFormat( elem, QStringLiteral( "image/png; mode=16bit" ) );
    appendFormat( elem, QStringLiteral( "image/png; mode=8bit" ) );
    appendFormat( elem, QStringLiteral( "image/png; mode=1bit" ) );
    appendFormat( elem, QStringLiteral( "application/dxf" ) );
    elem.appendChild( dcpTypeElement.cloneNode().toElement() ); //this is the same as for 'GetCapabilities'
    requestElement.appendChild( elem );

    //wms:GetFeatureInfo
    elem = doc.createElement( QStringLiteral( "GetFeatureInfo" ) );
    appendFormat( elem, QStringLiteral( "text/plain" ) );
    appendFormat( elem, QStringLiteral( "text/html" ) );
    appendFormat( elem, QStringLiteral( "text/xml" ) );
    appendFormat( elem, QStringLiteral( "application/vnd.ogc.gml" ) );
    appendFormat( elem, QStringLiteral( "application/vnd.ogc.gml/3.1.1" ) );
    elem.appendChild( dcpTypeElement.cloneNode().toElement() ); //this is the same as for 'GetCapabilities'
    requestElement.appendChild( elem );

    //wms:GetLegendGraphic
    elem = doc.createElement(( version == QLatin1String( "1.1.1" ) ? "GetLegendGraphic" : "sld:GetLegendGraphic" )/*wms:GetLegendGraphic*/ );
    appendFormat( elem, QStringLiteral( "image/jpeg" ) );
    appendFormat( elem, QStringLiteral( "image/png" ) );
    elem.appendChild( dcpTypeElement.cloneNode().toElement() ); // this is the same as for 'GetCapabilities'
    requestElement.appendChild( elem );

    //wms:DescribeLayer
    elem = doc.createElement(( version == QLatin1String( "1.1.1" ) ? "DescribeLayer" : "sld:DescribeLayer" )/*wms:GetLegendGraphic*/ );
    appendFormat( elem, QStringLiteral( "text/xml" ) );
    elem.appendChild( dcpTypeElement.cloneNode().toElement() ); // this is the same as for 'GetCapabilities'
    requestElement.appendChild( elem );

    //wms:GetStyles
    elem = doc.createElement(( version == QLatin1String( "1.1.1" ) ? "GetStyles" : "qgs:GetStyles" )/*wms:GetStyles*/ );
    appendFormat( elem, QStringLiteral( "text/xml" ) );
    elem.appendChild( dcpTypeElement.cloneNode().toElement() ); //this is the same as for 'GetCapabilities'
    requestElement.appendChild( elem );

    if ( projectSettings ) //remove composer templates from GetCapabilities in the long term
    {
        //wms:GetPrint
        elem = doc.createElement( QStringLiteral( "GetPrint" ) /*wms:GetPrint*/ );
        appendFormat( elem, QStringLiteral( "svg" ) );
        appendFormat( elem, QStringLiteral( "png" ) );
        appendFormat( elem, QStringLiteral( "pdf" ) );
        elem.appendChild( dcpTypeElement.cloneNode().toElement() ); //this is the same as for 'GetCapabilities'
        requestElement.appendChild( elem );
    }

    //Exception element is mandatory
    elem = doc.createElement( QStringLiteral( "Exception" ) );
    appendFormat( elem, ( version == QLatin1String( "1.1.1" ) ? "application/vnd.ogc.se_xml" : "XML" ) );
    capabilityElement.appendChild( elem );

    //UserDefinedSymbolization element
    if ( version == QLatin1String( "1.3.0" ) )
    {
        elem = doc.createElement( QStringLiteral( "sld:UserDefinedSymbolization" ) );
        elem.setAttribute( QStringLiteral( "SupportSLD" ), QStringLiteral( "1" ) );
        elem.setAttribute( QStringLiteral( "UserLayer" ), QStringLiteral( "0" ) );
        elem.setAttribute( QStringLiteral( "UserStyle" ), QStringLiteral( "1" ) );
        elem.setAttribute( QStringLiteral( "RemoteWFS" ), QStringLiteral( "0" ) );
        elem.setAttribute( QStringLiteral( "InlineFeature" ), QStringLiteral( "0" ) );
        elem.setAttribute( QStringLiteral( "RemoteWCS" ), QStringLiteral( "0" ) );
        capabilityElement.appendChild( elem );

        if ( configParser->wmsInspireActivated() )
        {
            configParser->inspireCapabilities( capabilityElement, doc );
        }
    }

    if ( projectSettings )
    {
        //Insert <ComposerTemplate> elements derived from wms:_ExtendedCapabilities
        configParser->printCapabilities( capabilityElement, doc );

        //WFS layers
        QStringList wfsLayers = configParser->wfsLayerNames();
        if ( !wfsLayers.isEmpty() )
        {
            QDomElement wfsLayersElem = doc.createElement( QStringLiteral( "WFSLayers" ) );
            for ( auto wfsIt = wfsLayers.constBegin() ; wfsIt != wfsLayers.constEnd(); ++wfsIt )
            {
                QDomElement wfsLayerElem = doc.createElement( QStringLiteral( "WFSLayer" ) );
                wfsLayerElem.setAttribute( QStringLiteral( "name" ), *wfsIt );
                wfsLayersElem.appendChild( wfsLayerElem );
            }
            capabilityElement.appendChild( wfsLayersElem );
        }
    }

    //add the xml content for the individual layers/styles
    configParser->layersAndStylesCapabilities( capabilityElement, doc, version, projectSettings );

    return doc;
}
Example #21
0
bool WebView::isUrlValid(const QUrl &url)
{
    // Valid url must have scheme and actually contains something (therefore scheme:// is invalid)
    return url.isValid() && !url.scheme().isEmpty() && (!url.host().isEmpty() || !url.path().isEmpty() || url.hasQuery());
}
void HttpProxy::onSocketReadyRead()
{
    QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
    QTcpSocket *proxySocket = nullptr;

    QByteArray reqData = socket->readAll();
    int pos = reqData.indexOf("\r\n");
    QByteArray reqLine = reqData.left(pos);
    reqData.remove(0, pos + 2);

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

    QString host;
    quint16 port;
    QString key;

    if (method != "CONNECT") {
        QUrl url = QUrl::fromEncoded(address);
        if (!url.isValid()) {
            emit info("Invalid URL: " + url.toString());
            socket->disconnectFromHost();
            return;
        }
        host = url.host();
        port = url.port(80);
        QString req = url.path();
        if (url.hasQuery()) {
            req.append('?').append(url.query());
        }
        reqLine = method + " " + req.toUtf8() + " " + version + "\r\n";
        reqData.prepend(reqLine);
        key = host + ':' + QString::number(port);
        proxySocket = socket->findChild<QTcpSocket *>(key);
        if (proxySocket) {
            proxySocket->write(reqData);
            return;//if we find an existing socket, then use it and return
        }
    } else {//CONNECT method
        /*
         * according to http://tools.ietf.org/html/draft-luotonen-ssl-tunneling-03
         * the first line would CONNECT HOST:PORT VERSION
         */
        QList<QByteArray> host_port_list = address.split(':');
        host = QString(host_port_list.first());
        port = host_port_list.last().toUShort();
    }

    proxySocket = new QTcpSocket(socket);
    proxySocket->setProxy(upstreamProxy);
    if (method != "CONNECT") {
        proxySocket->setObjectName(key);
        proxySocket->setProperty("reqData", reqData);
        connect (proxySocket, &QTcpSocket::connected, this, &HttpProxy::onProxySocketConnected);
        connect (proxySocket, &QTcpSocket::readyRead, this, &HttpProxy::onProxySocketReadyRead);
    } else {
        connect (proxySocket, &QTcpSocket::connected, this, &HttpProxy::onProxySocketConnectedHttps);
    }
    connect (proxySocket, &QTcpSocket::disconnected, proxySocket, &QTcpSocket::deleteLater);
    connect (proxySocket, static_cast<void (QTcpSocket::*)(QAbstractSocket::SocketError)>(&QTcpSocket::error), this, &HttpProxy::onSocketError);
    proxySocket->connectToHost(host, port);
}
Example #23
0
QByteArray BtQt::sendTrackerRequest(BtTrackerRequest const &req, QUrl trackerUrl)
{
    if(trackerUrl.scheme() != "http") {
        /* There may be "udp" or "https" or other schemes,
         * but not supported now */
        qDebug() << "Request to announce" << trackerUrl;
        qDebug() << "Protocol not supported!";
        return QByteArray();
    }
    /* For the reason that QUrl has used RFC3986 instead of RFC 1738,
     * I have to emulate an HTTP GET request using tcp socket. */
    QTcpSocket socket;
    QString host = trackerUrl.host();
    quint16 port = trackerUrl.port(80);
#ifndef QT_NO_DEBUG
    qDebug() << "Host: " << host;
    qDebug() << "Port: " << port;
#endif // QT_NO_DEBUG
    /*
     *QString host = trackerUrl.toEncoded(QUrl::RemoveScheme | QUrl::RemovePath
     *        | QUrl::RemoveAuthority);
     */
    socket.connectToHost(host, port);
    if(!socket.waitForConnected(1000)) {
        qDebug() << "Can not establish tcp connection to"  << host + ":" + QString::number(port);
        throw -1;
    }
    socket.setSocketOption(QAbstractSocket::KeepAliveOption, 1);

    /* HTTP 1.1 header, for more information please go to RFC2616 */
    QByteArray header;
    header.append("HOST: " + host + ":" + QString::number(port) + "\r\n");
    header.append("User-Agent: " + BtQt::application + " " + BtQt::version + "\r\n");
    header.append("Accept: */*\r\n");
    header.append("Connection: Keep-Alive\r\n");
    header.append("\r\n");

    QByteArray string;
    if(trackerUrl.hasQuery()) {
        string = "GET " + trackerUrl.toEncoded(QUrl::RemoveScheme | QUrl::RemoveAuthority) + '&' + req.toRequestData() + " HTTP/1.1\r\n";
    } else {
        string = "GET " + trackerUrl.toEncoded(QUrl::RemoveScheme | QUrl::RemoveAuthority) + '?' + req.toRequestData() + " HTTP/1.1\r\n";
    }

#ifndef QT_NO_DEBUG
    qDebug() << "Header: " << header;
    qDebug() << "String: " << string;
#endif // QT_NO_DEBUG

    socket.write(string + header);

    if(!socket.waitForReadyRead(1000)) {
        qDebug() << "There were some error occured or possibly time out! Can not get reply!";
        throw -1;
    }
    QByteArray trackerReply = socket.readAll();
    if(trackerReply.isEmpty()) {
        qDebug() << "Warnning! We got an empty reply!";
    }

    /* Get the reply data */
    int replyIdx = trackerReply.indexOf("\r\n\r\n") + 4;

    return trackerReply.mid(replyIdx);
}
Example #24
0
bool HttpGet::getFile(const QUrl &url)
{
    if (!url.isValid()) {
        qDebug() << "[HTTP] Error: Invalid URL" << endl;
        return false;
    }

    if (url.scheme() != "http") {
        qDebug() << "[HTTP] Error: URL must start with 'http:'" << endl;
        return false;
    }

    if (url.path().isEmpty()) {
        qDebug() << "[HTTP] Error: URL has no path" << endl;
        return false;
    }
    m_serverTimestamp = QDateTime();
    // if no output file was set write to buffer
    if(!outputToBuffer) {
        if (!outputFile->open(QIODevice::ReadWrite)) {
            qDebug() << "[HTTP] Error: Cannot open " << qPrintable(outputFile->fileName())
                     << " for writing: " << qPrintable(outputFile->errorString());
            return false;
        }
    }
    else {
        // output to buffer. Make sure buffer is empty so no old data gets
        // returned in case the object is reused.
        dataBuffer.clear();
    }
    qDebug() << "[HTTP] GET URI" << url.toEncoded();
    // create request
    http.setHost(url.host(), url.port(80));
    // construct query (if any)
    QList<QPair<QString, QString> > qitems = url.queryItems();
    if(url.hasQuery()) {
        m_query = "?";
        for(int i = 0; i < qitems.size(); i++)
            m_query += QUrl::toPercentEncoding(qitems.at(i).first, "/") + "="
                  + QUrl::toPercentEncoding(qitems.at(i).second, "/") + "&";
    }

    // create hash used for caching
    m_hash = QCryptographicHash::hash(url.toEncoded(), QCryptographicHash::Md5).toHex();
    // RFC2616: the absoluteURI form must get used when the request is being
    // sent to a proxy.
    m_path.clear();
    if(m_useproxy)
        m_path = url.scheme() + "://" + url.host();
    m_path += QString(QUrl::toPercentEncoding(url.path(), "/"));

    // construct request header
    m_header.setValue("Host", url.host());
    m_header.setValue("User-Agent", m_globalUserAgent);
    m_header.setValue("Connection", "Keep-Alive");

    if(m_dumbCache || !m_usecache) {
        getFileFinish();
    }
    else {
        // schedule HTTP header request
        m_header.setRequest("HEAD", m_path + m_query);
        headRequest = http.request(m_header);
        qDebug() << "[HTTP] HEAD scheduled:  " << headRequest;
    }

    return true;
}
Example #25
0
void VHttpProxy::run(VTcpSession* tcpSession)
{
  LOG_DEBUG("stt"); // gilgil temp 2013.10.19
  VTcpSession*          inSession = tcpSession;
  VHttpRequest           request;
  VTcpClient            outClient;
  VHttpProxyOutInThread* thread = NULL;

  QByteArray totalPacket;
  while (true)
  {
    QByteArray packet;
    int readLen = inSession->read(packet);
    if (readLen == VERR_FAIL) break;
    // LOG_DEBUG("%s", packet.data()); // gilgil temp

    totalPacket += packet;
    if (!request.parse(totalPacket))
    {
      if (outClient.active())
      {
        outClient.tcpSession->write(totalPacket);
        totalPacket = "";
      }
      continue;
    }

    QString host;
    int port;
    QUrl url = request.requestLine.path;
    if (!url.isRelative())
    {
      host = url.host();
      port = url.port();
      if (port == -1) port = 80;

      QByteArray newPath = url.path().toUtf8();
      if (url.hasQuery())
        newPath += "?" + url.query(QUrl::FullyEncoded).toLatin1();
      request.requestLine.path = newPath;
    } else
    if (!request.findHost(host, port))
    {
      LOG_ERROR("can not find host:%s", totalPacket.data());
      break;
    }

    if (outClient.host != host || outClient.port != port)
    {
      outClient.close();
      if (thread != NULL) delete thread;

      outClient.host = host;
      outClient.port = port;
      if (!outClient.open())
      {
        LOG_ERROR("%s", outClient.error.msg);
        break;
      }
      thread = new VHttpProxyOutInThread(&outClient, inSession, this);
      thread->open();
    }

    emit beforeRequest(request, inSession, &outClient);
    outClient.tcpSession->write(request.toByteArray());
    totalPacket = "";
  }
  LOG_DEBUG("end"); // gilgil temp 2013.10.19
  outClient.close();
  if (thread != NULL) delete thread;
}
Example #26
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