void QNetworkAccessHttpBackend::open()
{
    QUrl url = request().url();
    bool encrypt = url.scheme() == QLatin1String("https");
    setAttribute(QNetworkRequest::ConnectionEncryptedAttribute, encrypt);

    // set the port number in the reply if it wasn't set
    url.setPort(url.port(encrypt ? DefaultHttpsPort : DefaultHttpPort));

    // check if we have an open connection to this host
    QByteArray cacheKey = makeCacheKey(this->url());
    QNetworkAccessCache *cache = QNetworkAccessManagerPrivate::getCache(this);
    if ((http = static_cast<QNetworkAccessHttpBackendCache *>(cache->requestEntryNow(cacheKey))) == 0) {
        // no entry in cache; create an object
        http = new QNetworkAccessHttpBackendCache(url.host(), url.port(), encrypt);

#ifndef QT_NO_NETWORKPROXY
        QNetworkProxy networkProxy = proxy();
        if (encrypt || networkProxy.type() == QNetworkProxy::HttpProxy)
            http->setTransparentProxy(networkProxy);
        else
            http->setCacheProxy(networkProxy);
#endif

        cache->addEntry(cacheKey, http);
    }

    setupConnection();
    postRequest();
}
Ejemplo n.º 2
0
int
SmugMug::WebService::_httpGet (const QUrl &Url, QIODevice *to) {

    int id = 0;

    if (Url.port (80) == 443) {

        _ssl = true;
        _https.setHost (Url.host (), Url.port (443));
        id = _https.get (Url.toEncoded (), to);
    }
    else {

        _ssl = false;
        _http.setHost (Url.host (), Url.port (80));
        id = _http.get (Url.toEncoded (), to);
    }

    if (id) {

        emit actionStarted ();
        qDebug () << "actionStarted: " << id;
    }

    return id;
}
void SwitchAccountDialog::initAccountList()
{
    accounts_ = seafApplet->accountManager()->loadAccounts();
    int i, n = accounts_.size();
    for (i = 0; i < n; i++) {
        Account account = accounts_[i];
        QIcon icon = QIcon(":/images/account.svg");
        QUrl url = account.serverUrl;
        QString text = account.username + "\t" + url.host();
        if (url.port() > 0) {
            text += QString().sprintf(":%d", url.port());
        }
        if (url.path().length() > 0) {
            text += url.path();
        }

        QListWidgetItem *item = new QListWidgetItem(icon, text);
        mAccountsList->addItem(item);
    }

    if (!accounts_.empty()) {
        mAccountsList->setCurrentRow(0);
    }

    mAccountsList->setSelectionMode(QAbstractItemView::SingleSelection);
}
Ejemplo n.º 4
0
int
SmugMug::WebService::_httpRequest (
    const QUrl &Url,
    const QHttpRequestHeader &Header,
    const QByteArray &Data) {

    int id = 0;

    if (Url.port (80) == 443) {

        _ssl = true;
        _https.setHost (Url.host (), Url.port (80));
        id = _https.request (Header, Data);
    }
    else {

        _ssl = false;
        _http.setHost (Url.host (), Url.port (80));
        id = _http.request (Header, Data);
    }

    if (id) {

        emit actionStarted ();
        qDebug () << "actionStarted: " << id;
    }

    return id;
}
Ejemplo n.º 5
0
void RtspSocket::stream(QUrl url,QString chid, bool aud)
{
    qDebug("Start Streaming");
    audioEnabled = aud;
    channelid = chid;

    if(url.port() == -1 || url.port()==0 )
        url.setPort(554);

    QDEBUG << url.toString();
    qWarning() << tr("Stream: ") + url.toString();

    if( state == statePlay || state == statePlaying || state == stateTeardown )
    {
        state = stateTeardown;
        // set this after the teardown message
        _url = url;
    } else
    {
        _url = url;
        // restart the state machine
        state = stateInit;
    }
    slotStateMachine();
}
Ejemplo n.º 6
0
void VagrantProviderWidget::loadData()
{
  VagrantSettings vagrantSettings;
  QUrl url;
  QString temp;  

  m_cloudDialog->m_iAcceptCheckBox->setChecked(vagrantSettings.userAgreementSigned()); 

  bool isChecked = true;
  m_runOnStartUpCheckBox->setChecked(isChecked);

  m_serverUsernameLineEdit->setText(vagrantSettings.username().c_str());
  m_serverPasswordLineEdit->setText(vagrantSettings.password().c_str());

  url = vagrantSettings.serverUrl();
  m_serverAddressIpLineEdit->setText(url.host());
  m_serverPortIpLineEdit->setText(temp.setNum(url.port()));
  m_serverDirLineEdit->setText(toQString(vagrantSettings.serverPath()));

  url = vagrantSettings.serverUrl();
  m_workerAddressIpLineEdit->setText(url.host());
  m_workerPortIpLineEdit->setText(temp.setNum(url.port()));
  m_workerDirLineEdit->setText(toQString(vagrantSettings.workerPath()));

  //m_waitCheckBox->setChecked(vagrantSettings.terminationDelayEnabled());

  //m_waitLineEdit->setText(temp.setNum(vagrantSettings.terminationDelay()));
}
Ejemplo n.º 7
0
bool Http::get(QUrl url, QByteArray data, QByteArray &result, QMap<QString, QString> cookies, int timeout)
{
    QByteArray body;
    QByteArray cookiesData = convertData(cookies);

    QString urlstr;
    if (!data.isEmpty()) {
        urlstr.append(url.toEncoded());
        urlstr.append('?');
        urlstr.append(data);
    } else {
        urlstr = url.toEncoded();
    }

    body.append(QString("GET %1 HTTP/1.1\r\n").arg(urlstr));
    body.append(QString("Host: %1:%2\r\n").arg(url.host()).arg(url.port()));
    body.append("Connection: close\r\n");
    if (!cookies.isEmpty()) {
        body.append("Cookie: ");
        body.append(cookiesData);
        body.append("\r\n");
    }
    body.append("\r\n");
    return send(url.host(),url.port(),body,result,timeout);
}
void MediaCaptureDevicesDispatcher::handleMediaAccessPermissionResponse(content::WebContents *webContents, const QUrl &securityOrigin
                                                                        , WebContentsAdapterClient::MediaRequestFlags authorizationFlags)
{
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

    content::MediaStreamDevices devices;
    std::map<content::WebContents*, RequestsQueue>::iterator it = m_pendingRequests.find(webContents);

    if (it == m_pendingRequests.end())
        // WebContents has been destroyed. Don't need to do anything.
        return;

    RequestsQueue &queue(it->second);
    if (queue.empty())
        return;

    content::MediaStreamRequest &request = queue.front().request;

    const QUrl requestSecurityOrigin(toQt(request.security_origin));
    bool securityOriginsMatch = (requestSecurityOrigin.host() == securityOrigin.host()
                                   && requestSecurityOrigin.scheme() == securityOrigin.scheme()
                                   && requestSecurityOrigin.port() == securityOrigin.port());
    if (!securityOriginsMatch)
        qWarning("Security origin mismatch for media access permission: %s requested and %s provided\n", qPrintable(requestSecurityOrigin.toString())
                 , qPrintable(securityOrigin.toString()));


    bool microphoneRequested =
        (request.audio_type && authorizationFlags & WebContentsAdapterClient::MediaAudioCapture);
    bool webcamRequested =
        (request.video_type && authorizationFlags & WebContentsAdapterClient::MediaVideoCapture);
    if (securityOriginsMatch && (microphoneRequested || webcamRequested)) {
        switch (request.request_type) {
        case content::MEDIA_OPEN_DEVICE:
            Q_UNREACHABLE(); // only speculative as this is for Pepper
            getDefaultDevices("", "", microphoneRequested, webcamRequested, &devices);
            break;
        case content::MEDIA_DEVICE_ACCESS:
        case content::MEDIA_GENERATE_STREAM:
        case content::MEDIA_ENUMERATE_DEVICES:
            getDefaultDevices(request.requested_audio_device_id, request.requested_video_device_id,
                        microphoneRequested, webcamRequested, &devices);
            break;
        }
    }

    content::MediaResponseCallback callback = queue.front().callback;
    queue.pop_front();

    if (!queue.empty()) {
        // Post a task to process next queued request. It has to be done
        // asynchronously to make sure that calling infobar is not destroyed until
        // after this function returns.
        BrowserThread::PostTask(
                    BrowserThread::UI, FROM_HERE, base::Bind(&MediaCaptureDevicesDispatcher::ProcessQueuedAccessRequest, base::Unretained(this), webContents));
    }

    callback.Run(devices, devices.empty() ? content::MEDIA_DEVICE_INVALID_STATE : content::MEDIA_DEVICE_OK, scoped_ptr<content::MediaStreamUI>());
}
void LocalQmlProfilerRunnerTest::testFindFreePort()
{
    QUrl serverUrl = Utils::urlFromLocalHostAndFreePort();
    QVERIFY(serverUrl.port() != -1);
    QVERIFY(!serverUrl.host().isEmpty());
    QTcpServer server;
    QVERIFY(server.listen(QHostAddress(serverUrl.host()), serverUrl.port()));
}
Ejemplo n.º 10
0
CetonRTSP::CetonRTSP(const QUrl &url) :
    _ip(url.host()),
    _port((url.port() >= 0) ? url.port() : 554),
    _sequenceNumber(0),
    _sessionId("0"),
    _responseCode(-1)
{
    _requestUrl = url.toString();
}
Ejemplo n.º 11
0
int main(int argc, char **argv)
{
    QCoreApplication app(argc, argv);
    QStringList args = app.arguments();
    QString appName = args.takeFirst();
    bool notification = args.contains("-n");
    if (notification)
        args.removeAll("-n");

    if (args.size() < 2) {
        qDebug("usage: %s [-n] <service> <method> <arguments>", appName.toLocal8Bit().data());
        return -1;
    }

    // try to process socket
    QIODevice *device = 0;
    QScopedPointer<QIODevice> devicePtr(device);
    QString service = args.takeFirst();
    QUrl serviceUrl = QUrl::fromUserInput(service);
    QHostAddress serviceAddress(serviceUrl.host());
    if (serviceAddress.isNull()) {
        QLocalSocket *localSocket = new QLocalSocket;
        device = localSocket;
        localSocket->connectToServer(service);
        if (!localSocket->waitForConnected(5000)) {
            qDebug("could not connect to service: %s", service.toLocal8Bit().data());
            return -1;
        }
    } else {
        QTcpSocket *tcpSocket = new QTcpSocket;
        device = tcpSocket;
        int servicePort = serviceUrl.port() ? serviceUrl.port() : 5555;
        tcpSocket->connectToHost(serviceAddress, servicePort);
        if (!tcpSocket->waitForConnected(5000)) {
            qDebug("could not connect to host at %s:%d", serviceUrl.host().toLocal8Bit().data(),
                   servicePort);
            return -1;
        }
    }

    QJsonRpcSocket socket(device);
    QString method = args.takeFirst();
    QVariantList arguments;
    foreach (QString arg, args)
        arguments.append(arg);

    QJsonRpcMessage request = notification ? QJsonRpcMessage::createNotification(method, arguments) :
                                             QJsonRpcMessage::createRequest(method, arguments);
    QJsonRpcMessage response = socket.sendMessageBlocking(request, 5000);
    if (response.type() == QJsonRpcMessage::Error) {
        qDebug("error(%d): %s", response.errorCode(), response.errorMessage().toLocal8Bit().data());
        return -1;
    }

    qDebug() << response.result();
}
Ejemplo n.º 12
0
static void setApplicationProxy(QUrl url)
{
    if (!url.isEmpty())
    {
        if (url.port() == -1)
            url.setPort(8080);
        QNetworkProxy proxy(QNetworkProxy::HttpProxy, url.host(), url.port(), url.userName(), url.password());
        QNetworkProxy::setApplicationProxy(proxy);
    }
}
Ejemplo n.º 13
0
void NfcHandler::ndefMessageRead(QNdefMessage message)
{
    foreach (const QNdefRecord &record, message) {
        if (record.isRecordType<QNdefNfcUriRecord>()) {
            QNdefNfcUriRecord uriRecord(record);
            qDebug() << "********** Got URI record:" << uriRecord.uri();
            QUrl uri = uriRecord.uri();
            if(uri.scheme() == "kodi") {
                qDebug() << "Got and xmbc:// uri" << uri.host() << uri.port() << uri.path();

                KodiHost host;
                host.setAddress(uri.host());
                host.setPort(uri.port());
                QString path = uri.path().right(uri.path().length() - 1);
                if(path.split('/').count() >= 1) {
                    host.setHostname(path.split('/').first());
                }
                if(path.split('/').count() >= 2) {
                    host.setHwAddr(path.split('/').at(1));
                }
                qDebug() << "Should connect to" << host.address() << ':' << host.port() << host.hostname() << host.hwAddr();
                int index = Kodi::instance()->hostModel()->insertOrUpdateHost(host);
                Kodi::instance()->hostModel()->connectToHost(index);
            } else {
                qDebug() << "NDEF uri record not compatible with kodimote:" << uriRecord.uri();
                emit tagError(tr("NFC tag is not compatible with Kodimote. In order to use it with Kodimote you need to write connection information to it."));
            }
        } else if (record.isRecordType<QNdefNfcTextRecord>()) {
            QNdefNfcTextRecord textRecord(record);
            qDebug() << "********** Got Text record:" << textRecord.text();
            if(textRecord.text().startsWith("kodi:")) {
                qDebug() << "outdated tag detected";
                emit tagError(tr("NFC tag is outdated. In order to use it with Kodimote you need to update it by rewriting connection information to it."));
            } else {
                emit tagError(tr("NFC tag is not compatible with Kodimote. In order to use it with Kodimote you need to write connection information to it."));
            }
        }else {
            if (record.typeNameFormat() == QNdefRecord::Mime &&
                    record.type().startsWith("image/")) {
                qDebug() << "got image...";
            }else if (record.typeNameFormat() == QNdefRecord::NfcRtd ) {
                qDebug() << "Got Rtd tag" << record.payload();
                QNdefNfcUriRecord uri(record);
                qDebug() << "uri:" << uri.uri();
            }else if (record.typeNameFormat() == QNdefRecord::ExternalRtd ){
                qDebug() << "Got ExtRtd tag";
            } else if (record.isEmpty()) {
                qDebug() << "got empty record...";
            } else {
                qDebug() << "got unknown ndef message type";
            }
            emit tagError(tr("NFC tag is not compatible with Kodimote. In order to use it with Kodimote you need to write connection information to it."));
        }
    }
}
Ejemplo n.º 14
0
void FileDownloader::download(QUrl url) {
	QHttp::ConnectionMode mode = url.scheme().toLower() == "https" ? QHttp::ConnectionModeHttps : QHttp::ConnectionModeHttp;
	http->setHost(url.host(), mode, url.port() == -1 ? 0 : url.port());
    
	if (!url.userName().isEmpty())
		http->setUser(url.userName(), url.password());

	http_request_aborted = false;
	http_get_id = http->get(url.path(), &buffer);

	setLabelText(tr("Downloading %1").arg(url.toString()));
}
Ejemplo n.º 15
0
	void setup(const QUrl &uri, const HttpHeaders &_headers, const QHostAddress &connectAddr = QHostAddress(), int connectPort = -1, int _maxRedirects = -1)
	{
		assert(!method.isEmpty());

		QUrl tmp = uri;
		if(connectPort != -1)
			tmp.setPort(connectPort);
		else if(tmp.port() == -1)
		{
			if(uri.scheme() == "https")
				tmp.setPort(443);
			else
				tmp.setPort(80);
		}

		curl_easy_setopt(easy, CURLOPT_URL, tmp.toEncoded().data());

		if(!connectAddr.isNull())
		{
			curl_slist_free_all(dnsCache);
			QByteArray cacheEntry = tmp.encodedHost() + ':' + QByteArray::number(tmp.port()) + ':' + connectAddr.toString().toUtf8();
			dnsCache = curl_slist_append(dnsCache, cacheEntry.data());
			curl_easy_setopt(easy, CURLOPT_RESOLVE, dnsCache);
		}

		HttpHeaders headers = _headers;

		bool chunked = false;
		if(headers.contains("Content-Length"))
		{
			curl_off_t content_len = (curl_off_t)headers.get("Content-Length").toLongLong();
			/*if(method == "POST")
				curl_easy_setopt(easy, CURLOPT_POSTFIELDSIZE_LARGE, content_len);
			else*/
				curl_easy_setopt(easy, CURLOPT_INFILESIZE_LARGE, content_len);

			// curl will set this for us
			headers.removeAll("Content-Length");
		}
		else
		{
			if(expectBody)
				chunked = true;
			else if(alwaysSetBody)
				curl_easy_setopt(easy, CURLOPT_INFILESIZE_LARGE, (curl_off_t)0);
		}

		curl_slist_free_all(headersList);
		foreach(const HttpHeader &h, headers)
		{
			QByteArray i = h.first + ": " + h.second;
			headersList = curl_slist_append(headersList, i.data());
		}
Ejemplo n.º 16
0
int Url::port ( lua_State * L )// const : int
{
	QUrl* lhs = ValueInstaller2<QUrl>::check( L, 1 );
	if(Util::isNum( L, 2 ))
	{
		Util::push( L, lhs->port(Util::toInt( L, 2 )) );
	}
	else
	{
		Util::push( L, lhs->port() );
	}
	return 1;
}
Ejemplo n.º 17
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");
}
Ejemplo n.º 18
0
void Config::setSystemProxy(bool checked)
{
    ui.proxyPort->setEnabled(!checked);
    ui.proxyHost->setEnabled(!checked);
    ui.proxyUser->setEnabled(!checked);
    ui.proxyPass->setEnabled(!checked);
    if(checked) {
        // save values in input box
        proxy.setScheme("http");
        proxy.setUserName(ui.proxyUser->text());
        proxy.setPassword(ui.proxyPass->text());
        proxy.setHost(ui.proxyHost->text());
        proxy.setPort(ui.proxyPort->text().toInt());
        // show system values in input box
        QUrl envproxy = System::systemProxy();
        qDebug() << "[Config] setting system proxy" << envproxy;

        ui.proxyHost->setText(envproxy.host());
        ui.proxyPort->setText(QString("%1").arg(envproxy.port()));
        ui.proxyUser->setText(envproxy.userName());
        ui.proxyPass->setText(envproxy.password());

        if(envproxy.host().isEmpty() || envproxy.port() == -1) {
            qDebug() << "[Config] sytem proxy is invalid.";
            QMessageBox::warning(this, tr("Proxy Detection"),
                    tr("The System Proxy settings are invalid!\n"
                        "Rockbox Utility can't work with this proxy settings. "
                        "Make sure the system proxy is set correctly. Note that "
                        "\"proxy auto-config (PAC)\" scripts are not supported by "
                        "Rockbox Utility. If your system uses this you need "
                        "to use manual proxy settings."),
                    QMessageBox::Ok ,QMessageBox::Ok);
            // the current proxy settings are invalid. Check the saved proxy
            // type again.
            if(RbSettings::value(RbSettings::ProxyType).toString() == "manual")
                ui.radioManualProxy->setChecked(true);
            else
                ui.radioNoProxy->setChecked(true);
        }

    }
    else {
        ui.proxyHost->setText(proxy.host());
        if(proxy.port() > 0)
            ui.proxyPort->setText(QString("%1").arg(proxy.port()));
        else ui.proxyPort->setText("");
        ui.proxyUser->setText(proxy.userName());
        ui.proxyPass->setText(proxy.password());
    }

}
Ejemplo n.º 19
0
void HttpPoll::connectToHost(const QString &proxyHost, int proxyPort, const QUrl &url)
{
	resetConnection(true);

	bool useSsl = false;
	d->port = 80;
	// using proxy?
	if(!proxyHost.isEmpty()) {
		d->host = proxyHost;
		d->port = proxyPort;
		d->url = url;
		d->use_proxy = true;
	}
	else {
		d->host = url.host();
		if(url.port() != -1)
			d->port = url.port();
		else if (url.scheme() == "https") {
			d->port = 443;
			useSsl = true;
		}
#if QT_VERSION < 0x050000
		d->url = url.path() + "?" + url.encodedQuery();
#else
		d->url.setUrl(url.path() + "?" + url.query(QUrl::FullyEncoded), QUrl::StrictMode);
#endif
		d->use_proxy = false;
	}

	resetKey();
	bool last;
	QString key = getKey(&last);

#ifdef PROX_DEBUG
	fprintf(stderr, "HttpPoll: Connecting to %s:%d [%s]", d->host.latin1(), d->port, d->url.latin1());
	if(d->user.isEmpty())
		fprintf(stderr, "\n");
	else
		fprintf(stderr, ", auth {%s,%s}\n", d->user.latin1(), d->pass.latin1());
#endif
	QPointer<QObject> self = this;
	syncStarted();
	if(!self)
		return;

	d->state = 1;
	d->http.setUseSsl(useSsl);
	d->http.setAuth(d->user, d->pass);
	d->http.post(d->host, d->port, d->url, makePacket("0", key, "", QByteArray()), d->use_proxy);
}
Ejemplo n.º 20
0
int
LastFmParser::make_request (const QString &artist,
							const QUrl &url)
{
	QBuffer *buff = new QBuffer (this);
	buff->open (QIODevice::WriteOnly);

	m_http->setHost (url.host (), url.port () != -1 ? url.port () : 80);
	int id = m_http->get (QString (url.toEncoded ()), buff);

	m_requests[id] = buff;
	m_cache_map[id] = artist;

	return id;
}
Ejemplo n.º 21
0
QList<QNetworkProxy> PackageManagerProxyFactory::queryProxy(const QNetworkProxyQuery &query)
{
    const Settings &settings = m_core->settings();
    QList<QNetworkProxy> list;

    if (settings.proxyType() == Settings::SystemProxy) {
#if defined(Q_OS_UNIX) && !defined(Q_OS_OSX)
        QUrl proxyUrl = QUrl::fromUserInput(QString::fromUtf8(qgetenv("http_proxy")));
        if (proxyUrl.isValid()) {
            return list << QNetworkProxy(QNetworkProxy::HttpProxy, proxyUrl.host(), proxyUrl.port(),
                proxyUrl.userName(), proxyUrl.password());
        }
#endif
        return QNetworkProxyFactory::systemProxyForQuery(query);
    }

    if ((settings.proxyType() == Settings::NoProxy))
        return list << QNetworkProxy(QNetworkProxy::NoProxy);

    if (query.queryType() == QNetworkProxyQuery::UrlRequest) {
        if (query.url().scheme() == QLatin1String("ftp"))
            return list << settings.ftpProxy();

        if ((query.url().scheme() == QLatin1String("http"))
            || (query.url().scheme() == QLatin1String("https"))) {
                return list << settings.httpProxy();
            }
    }
    return list << QNetworkProxy(QNetworkProxy::DefaultProxy);
}
Ejemplo n.º 22
0
bool ConnectionBackend::connectToRemote(const QUrl &url)
{
    Q_ASSERT(state == Idle);
    Q_ASSERT(!socket);
    Q_ASSERT(!localServer);     // !tcpServer as well

    if (mode == LocalSocketMode) {
        KLocalSocket *sock = new KLocalSocket(this);
        QString path = url.path();
#if 0
        // TODO: Activate once abstract socket support is implemented in Qt.
        KLocalSocket::LocalSocketType type = KLocalSocket::UnixSocket;

        if (url.queryItem(QLatin1String("abstract")) == QLatin1String("1")) {
            type = KLocalSocket::AbstractUnixSocket;
        }
#endif
        sock->connectToPath(path);
        socket = sock;
    } else {
        socket = new QTcpSocket(this);
        socket->connectToHost(url.host(), url.port());

        if (!socket->waitForConnected(1000)) {
            state = Idle;
            qCDebug(KIO_CORE) << "could not connect to" << url;
            return false;
        }
    }
    connect(socket, SIGNAL(readyRead()), SLOT(socketReadyRead()));
    connect(socket, SIGNAL(disconnected()), SLOT(socketDisconnected()));
    state = Connected;
    return true;
}
Ejemplo n.º 23
0
void HttpGet::downloadFile(const QUrl &url,const QString &path)
{
	qDebug()<<url.path();
	file = new QFile(path);
	if (!file->open(QIODevice::WriteOnly))
	{
		delete file;
		file = 0;
		return;
	}

	QHttp::ConnectionMode mode = url.scheme().toLower() == "https" ? QHttp::ConnectionModeHttps : QHttp::ConnectionModeHttp;
	http->setHost(url.host(),mode,url.port()==-1? 0:url.port());
	http->get(url.path(),file);
	http->close();
}
Ejemplo n.º 24
0
void NewsFeed::getUpdates() {
	QMap<QString, QUrl>::iterator it = m_urls.begin();
	while (it != m_urls.end()) {
		QString title = it.key();
		logDebug("Getting updates for feed " + title);
		QUrl url = it.value();
		if (m_links[title]) {
			m_links[title]->deleteLater();
		}
		m_links[title] = new QHttp(url.host(), url.port(80), this);
		m_reqs[m_links[title]->get(url.path())] = title;
		connect(
			m_links[title], SIGNAL(requestStarted(int)), 
			SLOT(requestStarted(int))
		);
		connect(
			m_links[title], SIGNAL(requestFinished(int, bool)), 
			SLOT(requestFinished(int, bool))
		);
		++it;
	}
	QSettings conf(confDir() + "gui.ini", QSettings::IniFormat);
	conf.setValue(
		objectName() + "Updated", 
		QDateTime::currentDateTime().toString(Qt::ISODate)
	);

	if (!m_timer->isActive()) {
		logDebug("Next feeds update in one hour.");
		m_timer->start(1000 * 60 * 60);
	}
}
Ejemplo n.º 25
0
int QUrlProto::port(int defaultPort) const
{
  QUrl *item = qscriptvalue_cast<QUrl*>(thisObject());
  if (item)
    return item->port(defaultPort);
  return 0;
}
Ejemplo n.º 26
0
void AccessManager::slotAuthenticationRequired(QNetworkReply *reply, QAuthenticator *authenticator)
{
#ifndef TOKEN_AUTH_ONLY
    // do not handle 401 created by the networkjobs. We may want
    // to eventually exempt some, but for now we need
    // it only for other things, e.g. the browser. Would we handle
    // network jobs, this would break the wizard logic
    if (reply->property("doNotHandleAuth").toBool()) {
        return;
    }
    QUrl url = reply->url();
    // show only scheme, host and port
    QUrl reducedUrl;
    reducedUrl.setScheme(url.scheme());
    reducedUrl.setHost(url.host());
    reducedUrl.setPort(url.port());

    AuthenticationDialog dialog(authenticator->realm(), reducedUrl.toString());
    if (dialog.exec() == QDialog::Accepted) {
        authenticator->setUser(dialog.user());
        authenticator->setPassword(dialog.password());
    }
#else
    Q_UNUSED(reply) Q_UNUSED(authenticator)
    Q_ASSERT(!"OCC::AccessManager::slotAuthenticationRequired called");
#endif
}
Ejemplo n.º 27
0
void BrisaControlPoint::replyFinished(QNetworkReply *reply) {
    QTemporaryFile *rootXml = new QTemporaryFile();
    if (!rootXml->open()) {
        qWarning() << "Brisa Control Point: Failed to open file for writing root XML.";
    } else {
        rootXml->write(reply->readAll());
        rootXml->seek(0);
        QUrl *urlBase = new QUrl(reply->url());

        BrisaControlPointDevice *device = new BrisaControlPointDevice(rootXml, urlBase);

        /* Fix embedded devices host/port attributes */
        QList<BrisaControlPointService*> serviceList = device->getServiceList();
        foreach(BrisaControlPointService *s, serviceList) {
                s->setAttribute(BrisaControlPointService::Host, urlBase->host());
                s->setAttribute(BrisaControlPointService::Port,
                        QString().setNum(urlBase->port()));
        }

        rootXml->remove();
        delete rootXml;
        delete urlBase;
        // deleteLater as per Qt documentation (see Detailed Description section of
        // QNetworkAccessManager class documentation for more details;
        reply->deleteLater();

        emit deviceFound(device);
    }
Ejemplo n.º 28
0
bool ImageWidget::getFile(const QUrl &url)
{
    if (!url.isValid()) {
        qDebug() << "Error: Invalid URL";
        return false;
    }

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

    if (url.path().isEmpty()) {
        qDebug() << "Error: URL has no path";
        return false;
    }

    QString localFileName = QFileInfo(url.path()).fileName();
    if (localFileName.isEmpty())
        localFileName = "httpget.out";

    file.setFileName(QDir::tempPath()+"/"+localFileName);
    if (!file.open(QIODevice::WriteOnly)) {
        qDebug() << "Error: Cannot open " << qPrintable(file.fileName())
             << " for writing: " << qPrintable(file.errorString());
        return false;
    }        
    http.setHost(url.host(), url.port(80));
    http.get(url.path(), &file);
    http.close();
    return true;
}
Ejemplo n.º 29
0
bool WebPage::acceptNavigationRequest(QWebFrame*,
                                       const QNetworkRequest& request,
                                       NavigationType navType)
{
   QUrl url = request.url();

   if (url.toString() == QString::fromAscii("about:blank"))
      return true;

   if (url.scheme() != QString::fromAscii("http")
       && url.scheme() != QString::fromAscii("https")
       && url.scheme() != QString::fromAscii("mailto"))
   {
      return false;
   }

   if (baseUrl_.isEmpty() ||
       (url.scheme() == baseUrl_.scheme()
        && url.host() == baseUrl_.host()
        && url.port() == baseUrl_.port()))
   {
      navigated_ = true;
      return true;
   }
   else
   {
      QDesktopServices::openUrl(url);

      if (!navigated_)
         this->view()->window()->deleteLater();

      return false;
   }
}
Ejemplo n.º 30
0
/*!
  \a url points to the new WAP gateway.

  \sa gateway()
*/
void QWapAccount::setGateway( const QUrl& url )
{
    d->conf->setValue( QLatin1String("Wap/Gateway"), url.host() );
    d->conf->setValue( QLatin1String("Wap/UserName"), url.userName() );
    d->conf->setValue( QLatin1String("Wap/Password"), url.password() );
    d->conf->setValue( QLatin1String("Wap/Port"), url.port() );
}