void QWebFrameAdapter::load(const QNetworkRequest& req, QNetworkAccessManager::Operation operation, const QByteArray& body) { if (frame->tree()->parent()) pageAdapter->insideOpenCall = true; QUrl url = ensureAbsoluteUrl(req.url()); WebCore::ResourceRequest request(url); switch (operation) { case QNetworkAccessManager::HeadOperation: request.setHTTPMethod("HEAD"); break; case QNetworkAccessManager::GetOperation: request.setHTTPMethod("GET"); break; case QNetworkAccessManager::PutOperation: request.setHTTPMethod("PUT"); break; case QNetworkAccessManager::PostOperation: request.setHTTPMethod("POST"); break; case QNetworkAccessManager::DeleteOperation: request.setHTTPMethod("DELETE"); break; case QNetworkAccessManager::CustomOperation: request.setHTTPMethod(req.attribute(QNetworkRequest::CustomVerbAttribute).toByteArray().constData()); break; case QNetworkAccessManager::UnknownOperation: // eh? break; } QVariant cacheLoad = req.attribute(QNetworkRequest::CacheLoadControlAttribute); if (cacheLoad.isValid()) { bool ok; uint cacheLoadValue = cacheLoad.toUInt(&ok); if (ok) request.setCachePolicy(cacheLoadControlToCachePolicy(cacheLoadValue)); } QList<QByteArray> httpHeaders = req.rawHeaderList(); for (int i = 0; i < httpHeaders.size(); ++i) { const QByteArray &headerName = httpHeaders.at(i); request.addHTTPHeaderField(QString::fromLatin1(headerName), QString::fromLatin1(req.rawHeader(headerName))); } if (!body.isEmpty()) request.setHTTPBody(WebCore::FormData::create(body.constData(), body.size())); frame->loader()->load(WebCore::FrameLoadRequest(frame, request)); if (frame->tree()->parent()) pageAdapter->insideOpenCall = false; }
void ZAPI::finished() { QNetworkReply* reply = (QNetworkReply*)sender(); QNetworkRequest request = reply->request(); int role = request.attribute(ATTR_ROLE).toInt(); QString strReply = reply->readAll(); QJsonDocument jsonDoc = QJsonDocument::fromJson(strReply.toUtf8()); QJsonObject jsonObject = jsonDoc.object(); //qDebug() << jsonDoc.toJson(); switch(role) { case ROLE_LOGIN: access_token = jsonObject["access_token"].toString(); token_type = jsonObject["token_type"].toString(); emit loginSignal(jsonObject); break; case ROLE_REFRESH: break; case ROLE_URL: emit urlSignal(jsonObject); break; case ROLE_FEEDS: emit feedsSignal(jsonObject); break; } reply->deleteLater(); }
void Pastebin::onDeletePasteFinished() { QNetworkReply *networkReply = qobject_cast<QNetworkReply *>(sender()); QNetworkRequest networkRequest = networkReply->request(); QVariant statusCode = networkReply->attribute(QNetworkRequest::HttpStatusCodeAttribute); const QString pasteKey = networkRequest.attribute(QNetworkRequest::Attribute(QNetworkRequest::User + 1)).toString(); qDebug() << "Delete paste complete:" << statusCode.toInt(); if(networkReply->error() == QNetworkReply::NoError) { QString response = networkReply->readAll(); qDebug() << "Response:" << response; if(response.startsWith("Bad API request")) { qWarning() << "Error with delete paste"; emit deletePasteError(pasteKey, response); } else { qDebug() << "Delete paste successful"; emit deletePasteComplete(pasteKey); } } else { qWarning() << "Error with delete paste" << networkReply->errorString(); emit deletePasteError(pasteKey, QString::null); } }
void DownloadManager::downloadRequested(const QNetworkRequest& request) { std::cout << "DownloadManager::DownloadRequested()\n"; QString src = request.url().toString(); QString dest = request.attribute(QNetworkRequest::User, "~").toString(); QFile* fileDestination = new QFile(dest); fileDestination->open(QIODevice::ReadWrite); QNetworkReply* reply = mNetworkAccess.get(request); reply->setReadBufferSize(0); mActiveDownloads.insert(reply, fileDestination); connect(reply, SIGNAL(finished()), this, SLOT(downloadFinished())); connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(downloadError(QNetworkReply::NetworkError))); connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(downloadProgress(qint64, qint64))); connect(reply, SIGNAL(readyRead()), this, SLOT(downloadReadyRead())); DownloadData* data = new DownloadData(); data->mRemotePath = src; data->mLocalPath = dest; connect(reply, SIGNAL(finished()), data, SLOT(finished())); connect(reply, SIGNAL(downloadProgress(qint64, qint64)), data, SLOT(catchProgress(qint64, qint64))); connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), data, SIGNAL(error(QNetworkReply::NetworkError))); connect(data, SIGNAL(stopMe()), this, SLOT(stopDownload())); connect(data, SIGNAL(removeMe()), this, SLOT(removeDownload())); //connect(data, SIGNAL(reloadMe()), this, SLOT(reloadDownload())); emit downloadStarted(data); emit controller_showSystemTrayMessage("", "Download Started: " + data->localName()); mModel.addDownload(data); mDownloads.insert(data, reply); }
void QNetworkReplyImplPrivate::setup(QNetworkAccessManager::Operation op, const QNetworkRequest &req, QIODevice *data) { Q_Q(QNetworkReplyImpl); outgoingData = data; request = req; url = request.url(); operation = op; if (outgoingData && backend) { // there is data to be uploaded, e.g. HTTP POST. if (!backend->needsResetableUploadData() || !outgoingData->isSequential()) { // backend does not need upload buffering or // fixed size non-sequential // just start the operation QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection); } else { bool bufferingDisallowed = req.attribute(QNetworkRequest::DoNotBufferUploadDataAttribute, false).toBool(); if (bufferingDisallowed) { // if a valid content-length header for the request was supplied, we can disable buffering // if not, we will buffer anyway if (req.header(QNetworkRequest::ContentLengthHeader).isValid()) { QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection); } else { state = Buffering; QMetaObject::invokeMethod(q, "_q_bufferOutgoingData", Qt::QueuedConnection); } } else { // _q_startOperation will be called when the buffering has finished. state = Buffering; QMetaObject::invokeMethod(q, "_q_bufferOutgoingData", Qt::QueuedConnection); } } } else { // No outgoing data (e.g. HTTP GET request) // or no backend // if no backend, _q_startOperation will handle the error of this // for HTTP, we want to send out the request as fast as possible to the network, without // invoking methods in a QueuedConnection #ifndef QT_NO_HTTP if (qobject_cast<QNetworkAccessHttpBackend *>(backend)) { _q_startOperation(); } else { QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection); } #else QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection); #endif // QT_NO_HTTP } q->QIODevice::open(QIODevice::ReadOnly); }
void QgsWcsCapabilities::capabilitiesReplyFinished() { if ( mCapabilitiesReply->error() == QNetworkReply::NoError ) { QVariant redirect = mCapabilitiesReply->attribute( QNetworkRequest::RedirectionTargetAttribute ); if ( !redirect.isNull() ) { emit statusChanged( tr( "Capabilities request redirected." ) ); QNetworkRequest request( redirect.toUrl() ); setAuthorization( request ); request.setAttribute( QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferNetwork ); request.setAttribute( QNetworkRequest::CacheSaveControlAttribute, true ); mCapabilitiesReply->deleteLater(); QgsDebugMsg( QString( "redirected getcapabilities: %1" ).arg( redirect.toString() ) ); mCapabilitiesReply = QgsNetworkAccessManager::instance()->get( request ); connect( mCapabilitiesReply, SIGNAL( finished() ), this, SLOT( capabilitiesReplyFinished() ) ); connect( mCapabilitiesReply, SIGNAL( downloadProgress( qint64, qint64 ) ), this, SLOT( capabilitiesReplyProgress( qint64, qint64 ) ) ); return; } mCapabilitiesResponse = mCapabilitiesReply->readAll(); if ( mCapabilitiesResponse.isEmpty() ) { mErrorFormat = "text/plain"; mError = tr( "empty of capabilities: %1" ).arg( mCapabilitiesReply->errorString() ); } } else { // Resend request if AlwaysCache QNetworkRequest request = mCapabilitiesReply->request(); if ( request.attribute( QNetworkRequest::CacheLoadControlAttribute ).toInt() == QNetworkRequest::AlwaysCache ) { QgsDebugMsg( "Resend request with PreferCache" ); request.setAttribute( QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache ); mCapabilitiesReply->deleteLater(); mCapabilitiesReply = QgsNetworkAccessManager::instance()->get( request ); connect( mCapabilitiesReply, SIGNAL( finished() ), this, SLOT( capabilitiesReplyFinished() ) ); connect( mCapabilitiesReply, SIGNAL( downloadProgress( qint64, qint64 ) ), this, SLOT( capabilitiesReplyProgress( qint64, qint64 ) ) ); return; } mErrorFormat = "text/plain"; mError = tr( "Download of capabilities failed: %1" ).arg( mCapabilitiesReply->errorString() ); QgsMessageLog::logMessage( mError, tr( "WCS" ) ); mCapabilitiesResponse.clear(); } mCapabilitiesReply->deleteLater(); mCapabilitiesReply = 0; }
/*! Returns a new QNetworkReply object to handle the operation \a op and request \a req. The device \a outgoingData is always 0 for Get and Head requests, but is the value passed to post() and put() in those operations (the QByteArray variants will pass a QBuffer object). The default implementation calls QNetworkCookieJar::cookiesForUrl() on the cookie jar set with setCookieJar() to obtain the cookies to be sent to the remote server. The returned object must be in an open state. */ QNetworkReply *QNetworkAccessManager::createRequest(QNetworkAccessManager::Operation op, const QNetworkRequest &req, QIODevice *outgoingData) { Q_D(QNetworkAccessManager); QNetworkRequest request = req; if (!request.header(QNetworkRequest::ContentLengthHeader).isValid() && outgoingData && !outgoingData->isSequential()) { // request has no Content-Length // but the data that is outgoing is random-access request.setHeader(QNetworkRequest::ContentLengthHeader, outgoingData->size()); } if (d->cookieJar) { QList<QNetworkCookie> cookies = d->cookieJar->cookiesForUrl(request.url()); if (!cookies.isEmpty()) request.setHeader(QNetworkRequest::CookieHeader, qVariantFromValue(cookies)); } // first step: create the reply QUrl url = request.url(); QNetworkReplyImpl *reply = new QNetworkReplyImpl(this); QNetworkReplyImplPrivate *priv = reply->d_func(); priv->manager = this; // second step: fetch cached credentials QNetworkAuthenticationCredential *cred = d->fetchCachedCredentials(url); if (cred) { url.setUserName(cred->user); url.setPassword(cred->password); priv->urlForLastAuthentication = url; } // third step: setup the reply priv->setup(op, request, outgoingData); if (request.attribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferNetwork).toInt() != QNetworkRequest::AlwaysNetwork) priv->setNetworkCache(d->networkCache); #ifndef QT_NO_NETWORKPROXY QList<QNetworkProxy> proxyList = d->queryProxy(QNetworkProxyQuery(request.url())); priv->proxyList = proxyList; #endif // fourth step: find a backend priv->backend = d->findBackend(op, request); if (priv->backend) { priv->backend->setParent(reply); priv->backend->reply = priv; } #ifndef QT_NO_OPENSSL reply->setSslConfiguration(request.sslConfiguration()); #endif return reply; }
static inline QString Source(const QNetworkRequest &request) { switch (request.attribute(QNetworkRequest::CacheLoadControlAttribute).toInt()) { case QNetworkRequest::AlwaysCache: return "cache"; case QNetworkRequest::PreferCache: return "cache-preferred"; case QNetworkRequest::PreferNetwork: return "net-preferred"; case QNetworkRequest::AlwaysNetwork: return "net"; } return "unknown"; }
void KWebPage::downloadRequest(const QNetworkRequest& request) { KIO::TransferJob* job = KIO::get(request.url()); connect(job, SIGNAL(mimetype(KIO::Job*,QString)), this, SLOT(_k_receivedContentType(KIO::Job*,QString))); connect(job, SIGNAL(result(KJob*)), this, SLOT(_k_receivedContentTypeResult(KJob*))); job->setMetaData(request.attribute(static_cast<QNetworkRequest::Attribute>(KIO::AccessManager::MetaData)).toMap()); job->addMetaData(QL1S("MaxCacheSize"), QL1S("0")); // Don't store in http cache. job->addMetaData(QL1S("cache"), QL1S("cache")); // Use entry from cache if available. job->ui()->setWindow(d->windowWidget()); }
GM_Downloader::GM_Downloader(const QNetworkRequest &request, GM_Manager* manager) : QObject() , m_manager(manager) , m_widget(0) { m_reply = new FollowRedirectReply(request.url(), mApp->networkManager()); connect(m_reply, SIGNAL(finished()), this, SLOT(scriptDownloaded())); QVariant v = request.attribute((QNetworkRequest::Attribute)(QNetworkRequest::User + 100)); WebPage* webPage = static_cast<WebPage*>(v.value<void*>()); if (WebPage::isPointerSafeToUse(webPage)) { m_widget = webPage->view(); } }
QNetworkReply* NetworkManager::createRequest(QNetworkAccessManager::Operation op, const QNetworkRequest &request, QIODevice* outgoingData) { if (op == PostOperation && outgoingData) { QByteArray outgoingDataByteArray = outgoingData->peek(1024 * 1024); mApp->autoFill()->post(request, outgoingDataByteArray); } QNetworkRequest req = request; QNetworkReply* reply = 0; if (m_doNotTrack) { req.setRawHeader("DNT", "1"); } if (!m_sendReferer) { req.setRawHeader("Referer", ""); } req.setRawHeader("Accept-Language", m_acceptLanguage); //SchemeHandlers if (req.url().scheme() == "qupzilla") { reply = m_qupzillaSchemeHandler->createRequest(op, req, outgoingData); if (reply) { return reply; } } req.setAttribute(QNetworkRequest::HttpPipeliningAllowedAttribute, true); if (req.attribute(QNetworkRequest::CacheLoadControlAttribute).toInt() == QNetworkRequest::PreferNetwork) { req.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache); } // Adblock if (op == QNetworkAccessManager::GetOperation) { if (!m_adblockNetwork) { m_adblockNetwork = AdBlockManager::instance()->network(); } reply = m_adblockNetwork->block(req); if (reply) { return reply; } } reply = QNetworkAccessManager::createRequest(op, req, outgoingData); return reply; }
void NetworkManager::setSSLConfiguration(QNetworkReply* reply) { if (!reply->sslConfiguration().isNull()) { QSslCertificate cert = reply->sslConfiguration().peerCertificate(); if (!cert.isValid() || reply->property("downReply").toBool()) { return; } QNetworkRequest request = reply->request(); QVariant v = request.attribute((QNetworkRequest::Attribute)(QNetworkRequest::User + 100)); WebPage* webPage = static_cast<WebPage*>(v.value<void*>()); if (!webPage) { return; } if (webPage->url().host() == reply->url().host()) { webPage->setSSLCertificate(cert); } } }
void Pastebin::onRequestRawPasteFinished() { QNetworkReply *networkReply = qobject_cast<QNetworkReply *>(sender()); QNetworkRequest networkRequest = networkReply->request(); QVariant statusCode = networkReply->attribute(QNetworkRequest::HttpStatusCodeAttribute); const QString pasteKey = networkRequest.attribute(QNetworkRequest::Attribute(QNetworkRequest::User + 1)).toString(); qDebug() << "Paste request complete:" << statusCode.toInt(); networkReply->deleteLater(); if(networkReply->error() == QNetworkReply::NoError) { const QByteArray data = networkReply->readAll(); if(!data.isEmpty()) { emit rawPasteAvailable(pasteKey, data); } else { emit rawPasteError(pasteKey); } } else { qWarning() << "Error requesting raw paste:" << networkReply->errorString(); emit rawPasteError(pasteKey); } }
void Ssu::requestFinished(QNetworkReply *reply){ QSslConfiguration sslConfiguration = reply->sslConfiguration(); SsuLog *ssuLog = SsuLog::instance(); SsuCoreConfig *settings = SsuCoreConfig::instance(); QNetworkRequest request = reply->request(); QVariant originalDomainVariant = request.attribute(SSU_NETWORK_REQUEST_DOMAIN_DATA); #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) ssuLog->print(LOG_DEBUG, QString("Certificate used was issued for '%1' by '%2'. Complete chain:") .arg(sslConfiguration.peerCertificate().subjectInfo(QSslCertificate::CommonName).join("")) .arg(sslConfiguration.peerCertificate().issuerInfo(QSslCertificate::CommonName).join(""))); foreach (const QSslCertificate cert, sslConfiguration.peerCertificateChain()){ ssuLog->print(LOG_DEBUG, QString("-> %1").arg(cert.subjectInfo(QSslCertificate::CommonName).join(""))); } #else ssuLog->print(LOG_DEBUG, QString("Certificate used was issued for '%1' by '%2'. Complete chain:") .arg(sslConfiguration.peerCertificate().subjectInfo(QSslCertificate::CommonName)) .arg(sslConfiguration.peerCertificate().issuerInfo(QSslCertificate::CommonName))); foreach (const QSslCertificate cert, sslConfiguration.peerCertificateChain()){ ssuLog->print(LOG_DEBUG, QString("-> %1").arg(cert.subjectInfo(QSslCertificate::CommonName))); } #endif pendingRequests--; QString action; QByteArray data; QDomDocument doc; QString xmlError; /// @TODO: indicate that the device is not registered if there's a 404 on credentials update url if (settings->contains("home-url")){ QString homeUrl = settings->value("home-url").toString().arg(""); homeUrl.remove(QRegExp("//+$")); if (request.url().toString().startsWith(homeUrl, Qt::CaseInsensitive)){ // we don't care about errors on download request if (reply->error() == 0) { QByteArray data = reply->readAll(); storeAuthorizedKeys(data); } goto success; } } if (reply->error() > 0){ setError(reply->errorString()); goto failure; } data = reply->readAll(); ssuLog->print(LOG_DEBUG, QString("RequestOutput %1") .arg(data.data())); if (!doc.setContent(data, &xmlError)){ setError(tr("Unable to parse server response (%1)").arg(xmlError)); goto failure; } action = doc.elementsByTagName("action").at(0).toElement().text(); if (!verifyResponse(&doc)) { goto failure; } ssuLog->print(LOG_DEBUG, QString("Handling request of type %1") .arg(action)); if (action == "register") { if (registerDevice(&doc)) { goto success; } } else if (action == "credentials") { if (setCredentials(&doc)) { goto success; } } else { setError(tr("Response to unknown action encountered: %1").arg(action)); } failure: // Restore the original domain in case of failures with the registration if (!originalDomainVariant.isNull()) { QString originalDomain = originalDomainVariant.toString(); ssuLog->print(LOG_DEBUG, QString("Restoring domain on error: '%1'").arg(originalDomain)); setDomain(originalDomain); } // Fall through to cleanup handling in success from failure label success: ssuLog->print(LOG_DEBUG, QString("Request finished, pending requests: %1").arg(pendingRequests)); if (pendingRequests == 0) { emit done(); } }
void Petrel::replyFinished(QNetworkReply *reply) { QNetworkRequest request = reply->request(); QString replyStr( reply->readAll() ); int role = request.attribute( (QNetworkRequest::Attribute)(QNetworkRequest::User + ATTR_ROLE) ).toInt(); QDomDocument doc; doc.setContent(replyStr); switch(role){ //autogenerated choice case AVAILABLE_TRENDS: { locations_t l(doc.documentElement()); emit availableTrendsReceived(l); break; } case BLOCKING_IDS_BLOCKS: { ids_t i(doc.documentElement()); emit blocking_IdsBlocksReceived(i); break; } case CREATE_BLOCK: { user_t u(doc.documentElement()); emit createBlockReceived(u); break; } case CREATE_FAVORITE: { status_t s(doc.documentElement()); emit createFavoriteReceived(s); break; } case CREATE_FRIENDSHIP: { user_t u(doc.documentElement()); emit createFriendshipReceived(u); break; } case CREATE_SAVED_SEARCH: { saved_search_t s(doc.documentElement()); emit createSavedSearchReceived(s); break; } case DELETE_LIST_ID: { list_t l(doc.documentElement()); emit deleteListIdReceived(l); break; } case DELETE_LIST_MEMBER: { list_t l(doc.documentElement()); emit deleteListMemberReceived(l); break; } case DELETE_LIST_SUBSCRIBER: { list_t l(doc.documentElement()); emit deleteListSubscriberReceived(l); break; } case DESTROY: { status_t s(doc.documentElement()); emit destroyReceived(s); break; } case DESTROY_BLOCK: { user_t u(doc.documentElement()); emit destroyBlockReceived(u); break; } case DESTROY_DIRECT_MESSAGE: { direct_message_t d(doc.documentElement()); emit destroyDirectMessageReceived(d); break; } case DESTROY_FAVORITE: { status_t s(doc.documentElement()); emit destroyFavoriteReceived(s); break; } case DESTROY_FRIENDSHIP: { user_t u(doc.documentElement()); emit destroyFriendshipReceived(u); break; } case DESTROY_SAVED_SEARCH: { saved_search_t s(doc.documentElement()); emit destroySavedSearchReceived(s); break; } case DIRECT_MESSAGES: { direct_messages_t d(doc.documentElement()); emit directMessagesReceived(d); break; } case EXISTS_FRIENDSHIPS: { friends_t f(doc.documentElement()); emit existsFriendshipsReceived(f); break; } case FAVORITES: { statuses_t s(doc.documentElement()); emit favoritesReceived(s); break; } case FOLLOW_NOTIFICATION: { user_t u(doc.documentElement()); emit followNotificationReceived(u); break; } case FOLLOWERS: { users_t u(doc.documentElement()); emit followersReceived(u,0,0); // temp break; } case FRIENDS: { users_t u(doc.documentElement()); emit friendsReceived(u,0,0); // temp break; } case FRIENDS_TIMELINE: { statuses_t s(doc.documentElement()); emit friendsTimelineReceived(s); break; } case GET_LIST_ID: { list_t l(doc.documentElement()); emit getListIdReceived(l); break; } case GET_LIST_MEMBERS: { users_list_t u(doc.documentElement()); emit getListMembersReceived(u); break; } case GET_LIST_MEMBERS_ID: { user_t u(doc.documentElement()); emit getListMembersIdReceived(u); break; } case GET_LIST_MEMBERSHIPS: { lists_list_t l(doc.documentElement()); emit getListMembershipsReceived(l); break; } case GET_LIST_STATUSES: { statuses_t s(doc.documentElement()); emit getListStatusesReceived(s); break; } case GET_LIST_SUBSCRIBERS: { users_list_t u(doc.documentElement()); emit getListSubscribersReceived(u); break; } case GET_LIST_SUBSCRIBERS_ID: { user_t u(doc.documentElement()); emit getListSubscribersIdReceived(u); break; } case GET_LIST_SUBSCRIPTIONS: { lists_list_t l(doc.documentElement()); emit getListSubscriptionsReceived(l); break; } case GET_LISTS: { lists_list_t l(doc.documentElement()); emit getListsReceived(l); break; } case HOME_TIMELINE: { statuses_t s(doc.documentElement()); emit homeTimelineReceived(s); break; } case IDS_FOLLOWERS: { id_list_t i(doc.documentElement()); emit idsFollowersReceived(i); break; } case IDS_FRIENDS: { id_list_t i(doc.documentElement()); emit idsFriendsReceived(i); break; } case LEAVE_NOTIFICATION: { user_t u(doc.documentElement()); emit leaveNotificationReceived(u); break; } case LOCATION_TRENDS: { matching_trends_t m(doc.documentElement()); emit locationTrendsReceived(m); break; } case MENTIONS: { statuses_t s(doc.documentElement()); emit mentionsReceived(s); break; } case NEW_DIRECT_MESSAGE: { direct_message_t d(doc.documentElement()); emit newDirectMessageReceived(d); break; } case POST_LIST: { list_t l(doc.documentElement()); emit postListReceived(l); break; } case POST_LIST_MEMBER: { list_t l(doc.documentElement()); emit postListMemberReceived(l); break; } case POST_LIST_SUBSCRIBER: { list_t l(doc.documentElement()); emit postListSubscriberReceived(l); break; } case POST_LISTS_ID: { list_t l(doc.documentElement()); emit postListsIdReceived(l); break; } case PUBLIC_TIMELINE: { statuses_t s(doc.documentElement()); emit publicTimelineReceived(s); break; } case RATE_LIMIT_STATUS: { hash_t h(doc.documentElement()); emit rateLimitStatusReceived(h); break; } case REPORT_SPAM: { user_t u(doc.documentElement()); emit reportSpamReceived(u); break; } case RETWEET: { status_t s(doc.documentElement()); emit retweetReceived(s); break; } case RETWEETED_BY_ME: { statuses_t s(doc.documentElement()); emit retweetedByMeReceived(s); break; } case RETWEETED_TO_ME: { statuses_t s(doc.documentElement()); emit retweetedToMeReceived(s); break; } case RETWEETS: { statuses_t s(doc.documentElement()); emit retweetsReceived(s); break; } case RETWEETS_OF_ME: { statuses_t s(doc.documentElement()); emit retweetsOfMeReceived(s); break; } case SAVED_SEARCHES: { saved_searches_t s(doc.documentElement()); emit savedSearchesReceived(s); break; } case SEARCH_USERS: { users_t u(doc.documentElement()); emit searchUsersReceived(u); break; } case SENT_DIRECT_MESSAGES: { direct_messages_t d(doc.documentElement()); emit sentDirectMessagesReceived(d); break; } case SHOW: { status_t s(doc.documentElement()); emit showReceived(s); break; } case SHOW_FRIENDSHIPS: { relationship_t r(doc.documentElement()); emit showFriendshipsReceived(r); break; } case SHOW_SAVED_SEARCH: { saved_search_t s(doc.documentElement()); emit showSavedSearchReceived(s); break; } case SHOW_USERS: { user_t u(doc.documentElement()); emit showUsersReceived(u); break; } case TEST_HELP: { ok_t o(doc.documentElement()); emit testHelpReceived(o); break; } case UPDATE: { status_t s(doc.documentElement()); emit updateReceived(s); break; } case UPDATE_DELIVERY_DEVICE: { user_t u(doc.documentElement()); emit updateDeliveryDeviceReceived(u); break; } case UPDATE_PROFILE: { user_t u(doc.documentElement()); emit updateProfileReceived(u); break; } case UPDATE_PROFILE_BACKGROUND_IMAGE: { user_t u(doc.documentElement()); emit updateProfileBackgroundImageReceived(u); break; } case UPDATE_PROFILE_COLOR: { user_t u(doc.documentElement()); emit updateProfileColorReceived(u); break; } case UPDATE_PROFILE_IMAGE: { user_t u(doc.documentElement()); emit updateProfileImageReceived(u); break; } case USER_TIMELINE: { statuses_t s(doc.documentElement()); emit userTimelineReceived(s); break; } case VERIFY_CREDENTIALS: { user_t u(doc.documentElement()); emit verifyCredentialsReceived(u); break; } } reply->deleteLater(); }
void QNetworkReplyImplPrivate::setup(QNetworkAccessManager::Operation op, const QNetworkRequest &req, QIODevice *data) { Q_Q(QNetworkReplyImpl); outgoingData = data; request = req; url = request.url(); operation = op; q->QIODevice::open(QIODevice::ReadOnly); // Internal code that does a HTTP reply for the synchronous Ajax // in QtWebKit. QVariant synchronousHttpAttribute = req.attribute( static_cast<QNetworkRequest::Attribute>(QNetworkRequest::SynchronousRequestAttribute)); // The synchronous HTTP is a corner case, we will put all upload data in one big QByteArray in the outgoingDataBuffer. // Yes, this is not the most efficient thing to do, but on the other hand synchronous XHR needs to die anyway. if (synchronousHttpAttribute.toBool() && outgoingData) { outgoingDataBuffer = QSharedPointer<QRingBuffer>(new QRingBuffer()); qint64 previousDataSize = 0; do { previousDataSize = outgoingDataBuffer->size(); outgoingDataBuffer->append(outgoingData->readAll()); } while (outgoingDataBuffer->size() != previousDataSize); } if (backend) backend->setSynchronous(synchronousHttpAttribute.toBool()); if (outgoingData && backend && !backend->isSynchronous()) { // there is data to be uploaded, e.g. HTTP POST. if (!backend->needsResetableUploadData() || !outgoingData->isSequential()) { // backend does not need upload buffering or // fixed size non-sequential // just start the operation QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection); } else { bool bufferingDisallowed = req.attribute(QNetworkRequest::DoNotBufferUploadDataAttribute, false).toBool(); if (bufferingDisallowed) { // if a valid content-length header for the request was supplied, we can disable buffering // if not, we will buffer anyway if (req.header(QNetworkRequest::ContentLengthHeader).isValid()) { QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection); } else { state = Buffering; QMetaObject::invokeMethod(q, "_q_bufferOutgoingData", Qt::QueuedConnection); } } else { // _q_startOperation will be called when the buffering has finished. state = Buffering; QMetaObject::invokeMethod(q, "_q_bufferOutgoingData", Qt::QueuedConnection); } } } else { // for HTTP, we want to send out the request as fast as possible to the network, without // invoking methods in a QueuedConnection #ifndef QT_NO_HTTP if (backend && backend->isSynchronous()) { _q_startOperation(); } else { QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection); } #else if (backend && backend->isSynchronous()) _q_startOperation(); else QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection); #endif // QT_NO_HTTP } }
/*! Returns a new QNetworkReply object to handle the operation \a op and request \a req. The device \a outgoingData is always 0 for Get and Head requests, but is the value passed to post() and put() in those operations (the QByteArray variants will pass a QBuffer object). The default implementation calls QNetworkCookieJar::cookiesForUrl() on the cookie jar set with setCookieJar() to obtain the cookies to be sent to the remote server. The returned object must be in an open state. */ QNetworkReply *QNetworkAccessManager::createRequest(QNetworkAccessManager::Operation op, const QNetworkRequest &req, QIODevice *outgoingData) { Q_D(QNetworkAccessManager); bool isLocalFile = req.url().isLocalFile(); QString scheme = req.url().scheme().toLower(); // fast path for GET on file:// URLs // The QNetworkAccessFileBackend will right now only be used for PUT if ((op == QNetworkAccessManager::GetOperation || op == QNetworkAccessManager::HeadOperation) && (isLocalFile || scheme == QLatin1String("qrc"))) { return new QNetworkReplyFileImpl(this, req, op); } if ((op == QNetworkAccessManager::GetOperation || op == QNetworkAccessManager::HeadOperation) && scheme == QLatin1String("data")) { return new QNetworkReplyDataImpl(this, req, op); } // A request with QNetworkRequest::AlwaysCache does not need any bearer management QNetworkRequest::CacheLoadControl mode = static_cast<QNetworkRequest::CacheLoadControl>( req.attribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferNetwork).toInt()); if (mode == QNetworkRequest::AlwaysCache && (op == QNetworkAccessManager::GetOperation || op == QNetworkAccessManager::HeadOperation)) { // FIXME Implement a QNetworkReplyCacheImpl instead, see QTBUG-15106 QNetworkReplyImpl *reply = new QNetworkReplyImpl(this); QNetworkReplyImplPrivate *priv = reply->d_func(); priv->manager = this; priv->backend = new QNetworkAccessCacheBackend(); priv->backend->manager = this->d_func(); priv->backend->setParent(reply); priv->backend->reply = priv; priv->setup(op, req, outgoingData); return reply; } #ifndef QT_NO_BEARERMANAGEMENT // Return a disabled network reply if network access is disabled. // Except if the scheme is empty or file://. if (!d->networkAccessible && !isLocalFile) { return new QDisabledNetworkReply(this, req, op); } if (!d->networkSession && (d->initializeSession || !d->networkConfiguration.isEmpty())) { QNetworkConfigurationManager manager; if (!d->networkConfiguration.isEmpty()) { d->createSession(manager.configurationFromIdentifier(d->networkConfiguration)); } else { if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired) d->createSession(manager.defaultConfiguration()); else d->initializeSession = false; } } if (d->networkSession) d->networkSession->setSessionProperty(QLatin1String("AutoCloseSessionTimeout"), -1); #endif QNetworkRequest request = req; if (!request.header(QNetworkRequest::ContentLengthHeader).isValid() && outgoingData && !outgoingData->isSequential()) { // request has no Content-Length // but the data that is outgoing is random-access request.setHeader(QNetworkRequest::ContentLengthHeader, outgoingData->size()); } if (static_cast<QNetworkRequest::LoadControl> (request.attribute(QNetworkRequest::CookieLoadControlAttribute, QNetworkRequest::Automatic).toInt()) == QNetworkRequest::Automatic) { if (d->cookieJar) { QList<QNetworkCookie> cookies = d->cookieJar->cookiesForUrl(request.url()); if (!cookies.isEmpty()) request.setHeader(QNetworkRequest::CookieHeader, QVariant::fromValue(cookies)); } } // first step: create the reply QUrl url = request.url(); QNetworkReplyImpl *reply = new QNetworkReplyImpl(this); #ifndef QT_NO_BEARERMANAGEMENT if (!isLocalFile) { connect(this, SIGNAL(networkSessionConnected()), reply, SLOT(_q_networkSessionConnected())); } #endif QNetworkReplyImplPrivate *priv = reply->d_func(); priv->manager = this; // second step: fetch cached credentials // This is not done for the time being, we should use signal emissions to request // the credentials from cache. // third step: find a backend priv->backend = d->findBackend(op, request); if (priv->backend) { priv->backend->setParent(reply); priv->backend->reply = priv; } #ifndef QT_NO_OPENSSL reply->setSslConfiguration(request.sslConfiguration()); #endif // fourth step: setup the reply priv->setup(op, request, outgoingData); return reply; }
void KWebPage::downloadRequest(const QNetworkRequest &request) { downloadResource(request.url(), QString(), view(), request.attribute(static_cast<QNetworkRequest::Attribute>(KIO::AccessManager::MetaData)).toMap()); }
void AccessManager::AccessManagerPrivate::setMetaDataForRequest(QNetworkRequest request, KIO::MetaData& metaData) { // Add any meta data specified within request... QVariant userMetaData = request.attribute (static_cast<QNetworkRequest::Attribute>(MetaData)); if (userMetaData.isValid() && userMetaData.type() == QVariant::Map) metaData += userMetaData.toMap(); metaData.insert(QL1S("PropagateHttpHeader"), QL1S("true")); if (request.hasRawHeader("User-Agent")) { metaData.insert(QL1S("UserAgent"), request.rawHeader("User-Agent")); request.setRawHeader("User-Agent", QByteArray()); } if (request.hasRawHeader("Accept")) { metaData.insert(QL1S("accept"), request.rawHeader("Accept")); request.setRawHeader("Accept", QByteArray()); } if (request.hasRawHeader("Accept-Charset")) { metaData.insert(QL1S("Charsets"), request.rawHeader("Accept-Charset")); request.setRawHeader("Accept-Charset", QByteArray()); } if (request.hasRawHeader("Accept-Language")) { metaData.insert(QL1S("Languages"), request.rawHeader("Accept-Language")); request.setRawHeader("Accept-Language", QByteArray()); } if (request.hasRawHeader("Referer")) { metaData.insert(QL1S("referrer"), request.rawHeader("Referer")); request.setRawHeader("Referer", QByteArray()); } if (request.hasRawHeader("Content-Type")) { metaData.insert(QL1S("content-type"), request.rawHeader("Content-Type")); request.setRawHeader("Content-Type", QByteArray()); } if (request.attribute(QNetworkRequest::AuthenticationReuseAttribute) == QNetworkRequest::Manual) { metaData.insert(QL1S("no-preemptive-auth-reuse"), QL1S("true")); } request.setRawHeader("Content-Length", QByteArray()); request.setRawHeader("Connection", QByteArray()); request.setRawHeader("If-None-Match", QByteArray()); request.setRawHeader("If-Modified-Since", QByteArray()); request.setRawHeader("x-kdewebkit-ignore-disposition", QByteArray()); QStringList customHeaders; Q_FOREACH(const QByteArray &key, request.rawHeaderList()) { const QByteArray value = request.rawHeader(key); if (value.length()) customHeaders << (key + QL1S(": ") + value); } if (!customHeaders.isEmpty()) { metaData.insert(QL1S("customHTTPHeader"), customHeaders.join("\r\n")); } // Append per request meta data, if any... if (!requestMetaData.isEmpty()) { metaData += requestMetaData; // Clear per request meta data... requestMetaData.clear(); } // Append per session meta data, if any... if (!sessionMetaData.isEmpty()) { metaData += sessionMetaData; } }
void AutoFillModel::post(const QNetworkRequest &request, const QByteArray &outgoingData) { //Dont save in private browsing if (mApp->webSettings()->testAttribute(QWebSettings::PrivateBrowsingEnabled)) { return; } m_lastOutgoingData = outgoingData; QVariant v = request.attribute((QNetworkRequest::Attribute)(QNetworkRequest::User + 100)); WebPage* webPage = static_cast<WebPage*>(v.value<void*>()); if (!webPage) { return; } WebView* webView = qobject_cast<WebView*>(webPage->view()); if (!webView) { return; } v = request.attribute((QNetworkRequest::Attribute)(QNetworkRequest::User + 101)); QWebPage::NavigationType type = (QWebPage::NavigationType)v.toInt(); if (type != QWebPage::NavigationTypeFormSubmitted) { return; } QString usernameName; QString usernameValue; QString passwordName; QString passwordValue; QUrl siteUrl = webPage->url(); if (!isStoringEnabled(siteUrl)) { return; } QWebElementCollection allForms; // All form elements on page QWebElement foundForm; // Sent form element QList<QWebFrame*> frames; frames.append(webPage->mainFrame()); // Find all form elements while (!frames.isEmpty()) { QWebFrame* frame = frames.takeFirst(); allForms.append(frame->findAllElements("form")); frames += frame->childFrames(); } foreach(const QWebElement & formElement, allForms) { foreach(const QWebElement &inputElement, formElement.findAll("input[type=\"password\"]")) { passwordName = inputElement.attribute("name"); passwordValue = getValueFromData(outgoingData, inputElement); if (!passwordValue.isEmpty() && dataContains(outgoingData, passwordName)) { foundForm = formElement; break; } } if (!foundForm.isNull()) { break; } }
void Discogs::handleRelease( QNetworkReply* reply ){ Album album; QNetworkRequest request = reply->request(); QString key = request.attribute(QNetworkRequest::User).toString(); if( albums_.contains(key) ){ album = albums_[key]; //album.setArtists( QStringList() ); //album.setSongs( QList<Song>() ); } //cover->setText(""); QString err; QByteArray response(reply->readAll()); QXmlStreamReader xml(response); QList<Artist> Artists; QList<QUrl> images; QStringList artists,roles; QList<Song> songs; while (!xml.atEnd()) { xml.readNext(); //qDebug()<<xml.name(); if( xml.name() == "release" && xml.attributes().hasAttribute("id") ){ QString id = xml.attributes().value("id").toString(); album.setRelease(id); } if(xml.tokenType() == QXmlStreamReader::StartElement){ if( xml.attributes().hasAttribute("stat") ){ QString stat = xml.attributes().value("stat").toString(); if(stat=="fail"){ while(xml.readNextStartElement()){ if( xml.name() == "error" ){ err.append(xml.readElementText()+"\n"); }else{ xml.skipCurrentElement(); } } } } if( xml.attributes().hasAttribute("requests") ){ //&nSearches = xml.attributes().value("requests").toString().toInt(); //info->setText(QString::number(nSearches)+" searches performed within the last 24 hours"); } if(xml.name() == "images"){ xml.readNext(); while(xml.name()=="image"){ if( xml.attributes().hasAttribute("uri") ){ images.append( QUrl( xml.attributes().value("uri").toString() ) ); //qDebug()<<"found image "<<xml.attributes().value("uri").toString(); } xml.readNext(); } } if(xml.name() == "artists"){ while(xml.readNextStartElement()){ if(xml.name() == "artist"){ while(xml.readNextStartElement()){ if(xml.name() == "name"){ artists.append( xml.readElementText() ); }else{ xml.skipCurrentElement(); } } }else{ xml.skipCurrentElement(); } } } if(xml.name() == "extraartists"){ while(xml.readNextStartElement()){ if(xml.name() == "artist"){ //QString name;QString role; Artist a; while(xml.readNextStartElement()){ if(xml.name() == "name"){ a.setName( xml.readElementText() ); }else if(xml.name() == "role"){ a.setRole( xml.readElementText() ); }else{ xml.skipCurrentElement(); } Artists.append(a); } //qDebug()<<role+": "+name; //album.roles.append( role+": "+name ); }else{ xml.skipCurrentElement(); } } } if(xml.name() == "formats"){ while(xml.readNextStartElement()){ if( xml.name()=="format" && xml.attributes().hasAttribute("name") ){ QString sep=", "; if(album.format().isEmpty()){ sep=""; } album.setFormat( album.format() + sep + xml.attributes().value("name").toString() ); }else{ xml.skipCurrentElement(); } } } if(xml.name() == "title"){ album.setTitle( xml.readElementText() ); } if(xml.name() == "labels"){ xml.readNext(); while(xml.name()=="label"){ if( xml.attributes().hasAttribute("name") ){ QString sep=", "; if(album.label().isEmpty()){ sep=""; } album.setLabel( album.label()+sep+xml.attributes().value("name").toString() ); } xml.readNext(); } } if(xml.name() == "genres"){ while(xml.readNextStartElement()){ if(xml.name() == "genre"){ QString sep=", "; if(album.genre().isEmpty()){ sep=""; } album.setGenre( album.genre() + sep + xml.readElementText() ); }else{ xml.skipCurrentElement(); } } } if(xml.name() == "styles"){ while(xml.readNextStartElement()){ if(xml.name() == "style"){ QString sep=", "; if(album.style().isEmpty()){ sep=""; } album.setStyle( album.style() + sep + xml.readElementText() ); }else{ xml.skipCurrentElement(); } } } if(xml.name() == "country"){ album.setCountry( xml.readElementText() ); } if(xml.name() == "released"){ album.setYear( xml.readElementText().toInt() ); } if(xml.name() == "notes"){ album.setNotes( xml.readElementText() ); } if(xml.name() == "tracklist"){ while(xml.readNextStartElement()){ if(xml.name() == "track"){ Song s; while(xml.readNextStartElement()){ //qDebug()<<xml.name()<<xml.readElementText(); if(xml.name() == "position"){ s.setTrack( xml.readElementText() ); }else if(xml.name() == "title"){ s.setTitle( xml.readElementText() ); }else if(xml.name() == "duration"){ QStringList tmp = xml.readElementText().split(":"); int sum=0; for(int j=0;j<tmp.size();j++){ sum = sum + ( tmp[j].toInt()*pow(60,tmp.size()-j-1) ); } s.setLength(sum); }else{ xml.skipCurrentElement(); } } songs.append(s); }else{ xml.skipCurrentElement(); } } } } } //fix/compress roles for artists //QList<artist> newArtists; while( Artists.size()>0 ){ QString role = Artists[0].role(); if(role.isEmpty()){ Artists.removeAt(0); continue; } Artist a;a.setRole(role);a.setName(Artists[0].name()); //qDebug()<<role; for(int j=Artists.size()-1;j>=1;j--){ if( Artists[j].role()==role ){ if( !a.name().contains( Artists[j].name() ) ){ a.setName(a.name()+"/"+Artists[j].name()); //qDebug()<<a.name; } Artists.removeAt(j); } } Artists.removeAt(0); roles.append( a.role()+": "+a.name() ); //newArtists.append(a); } //remove html links from notes QString notes = album.notes(); while(1){ int ind = notes.indexOf("<a href"); if(ind==-1){ break; } int ind2 = notes.indexOf(">",ind); notes.remove(ind,ind2-ind+1); } notes.remove("</a>",Qt::CaseInsensitive); album.setNotes(notes); if( reply->error() || !err.isEmpty() ){ if( reply->error() ){ err = reply->errorString()+":\n"+err; } QMessageBox::critical(0, "Error", err, QMessageBox::Ok, QMessageBox::Ok); } album.setArtists(artists); album.setRoles(roles); album.setImages(images); album.setSongs(songs); albums_.insert(album.key(),album); reply->deleteLater(); /* if(images.size()>0){ //qDebug()<<"starting image downloading for album "+album.title()<<", images: "<<images; QNetworkRequest coverRequest(images[0]); coverRequest.setAttribute(QNetworkRequest::User,album.key()); QNetworkAccessManager *coverManager = new QNetworkAccessManager; connect(coverManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(handleCover(QNetworkReply*))); coverManager->get(coverRequest); }else { */ nDownloaded_++; qDebug()<<"downloaded album "<<album.title(); if( downloadImmediately_ && nDownloaded_==albums_.size() ){ emit albumsDownloaded( albums_ ); } if(!downloadImmediately_){ emit albumDownloaded( album ); } //} }
void NetworkManager::sslError(QNetworkReply* reply, QList<QSslError> errors) { if (m_ignoreAllWarnings || reply->property("downReply").toBool()) { reply->ignoreSslErrors(errors); return; } QNetworkRequest request = reply->request(); QVariant v = request.attribute((QNetworkRequest::Attribute)(QNetworkRequest::User + 100)); WebPage* webPage = static_cast<WebPage*>(v.value<void*>()); if (!WebPage::isPointerSafeToUse(webPage)) { return; } QHash<QSslCertificate, QStringList> errorHash; foreach(const QSslError & error, errors) { // Weird behavior on Windows if (error.error() == QSslError::NoError) { continue; } const QSslCertificate &cert = error.certificate(); if (errorHash.contains(cert)) { errorHash[cert].append(error.errorString()); } else { errorHash.insert(cert, QStringList(error.errorString())); } } // User already rejected those certs on this page if (webPage->containsRejectedCerts(errorHash.keys())) { return; } QString title = tr("SSL Certificate Error!"); QString text1 = tr("The page you are trying to access has the following errors in the SSL certificate:"); QString certs; QHash<QSslCertificate, QStringList>::const_iterator i = errorHash.constBegin(); while (i != errorHash.constEnd()) { const QSslCertificate &cert = i.key(); const QStringList &errors = i.value(); if (m_localCerts.contains(cert) || errors.isEmpty()) { ++i; continue; } certs += "<ul><li>"; certs += tr("<b>Organization: </b>") + CertificateInfoWidget::clearCertSpecialSymbols(cert.subjectInfo(QSslCertificate::Organization)); certs += "</li><li>"; certs += tr("<b>Domain Name: </b>") + CertificateInfoWidget::clearCertSpecialSymbols(cert.subjectInfo(QSslCertificate::CommonName)); certs += "</li><li>"; certs += tr("<b>Expiration Date: </b>") + cert.expiryDate().toString("hh:mm:ss dddd d. MMMM yyyy"); certs += "</li></ul>"; certs += "<ul>"; foreach(const QString & error, errors) { certs += "<li>"; certs += tr("<b>Error: </b>") + error; certs += "</li>"; } certs += "</ul>"; ++i; }
/*! Returns a new QNetworkReply object to handle the operation \a op and request \a req. The device \a outgoingData is always 0 for Get and Head requests, but is the value passed to post() and put() in those operations (the QByteArray variants will pass a QBuffer object). The default implementation calls QNetworkCookieJar::cookiesForUrl() on the cookie jar set with setCookieJar() to obtain the cookies to be sent to the remote server. The returned object must be in an open state. */ QNetworkReply *QNetworkAccessManager::createRequest(QNetworkAccessManager::Operation op, const QNetworkRequest &req, QIODevice *outgoingData) { Q_D(QNetworkAccessManager); // fast path for GET on file:// URLs // Also if the scheme is empty we consider it a file. // The QNetworkAccessFileBackend will right now only be used // for PUT or qrc:// if ((op == QNetworkAccessManager::GetOperation || op == QNetworkAccessManager::HeadOperation) && (req.url().scheme() == QLatin1String("file") || req.url().scheme().isEmpty())) { return new QFileNetworkReply(this, req, op); } #ifndef QT_NO_BEARERMANAGEMENT // Return a disabled network reply if network access is disabled. // Except if the scheme is empty or file://. if (!d->networkAccessible && !(req.url().scheme() == QLatin1String("file") || req.url().scheme().isEmpty())) { return new QDisabledNetworkReply(this, req, op); } if (!d->networkSession && (d->initializeSession || !d->networkConfiguration.isEmpty())) { QNetworkConfigurationManager manager; if (!d->networkConfiguration.isEmpty()) { d->createSession(manager.configurationFromIdentifier(d->networkConfiguration)); } else { if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired) d->createSession(manager.defaultConfiguration()); else d->initializeSession = false; } } if (d->networkSession) d->networkSession->setSessionProperty(QLatin1String("AutoCloseSessionTimeout"), -1); #endif QNetworkRequest request = req; if (!request.header(QNetworkRequest::ContentLengthHeader).isValid() && outgoingData && !outgoingData->isSequential()) { // request has no Content-Length // but the data that is outgoing is random-access request.setHeader(QNetworkRequest::ContentLengthHeader, outgoingData->size()); } if (static_cast<QNetworkRequest::LoadControl> (request.attribute(QNetworkRequest::CookieLoadControlAttribute, QNetworkRequest::Automatic).toInt()) == QNetworkRequest::Automatic) { if (d->cookieJar) { QList<QNetworkCookie> cookies = d->cookieJar->cookiesForUrl(request.url()); if (!cookies.isEmpty()) request.setHeader(QNetworkRequest::CookieHeader, qVariantFromValue(cookies)); } } // first step: create the reply QUrl url = request.url(); QNetworkReplyImpl *reply = new QNetworkReplyImpl(this); #ifndef QT_NO_BEARERMANAGEMENT if (req.url().scheme() != QLatin1String("file") && !req.url().scheme().isEmpty()) { connect(this, SIGNAL(networkSessionConnected()), reply, SLOT(_q_networkSessionConnected())); } #endif QNetworkReplyImplPrivate *priv = reply->d_func(); priv->manager = this; // second step: fetch cached credentials if (static_cast<QNetworkRequest::LoadControl> (request.attribute(QNetworkRequest::AuthenticationReuseAttribute, QNetworkRequest::Automatic).toInt()) == QNetworkRequest::Automatic) { QNetworkAuthenticationCredential *cred = d->fetchCachedCredentials(url); if (cred) { url.setUserName(cred->user); url.setPassword(cred->password); priv->urlForLastAuthentication = url; } } // third step: find a backend priv->backend = d->findBackend(op, request); #ifndef QT_NO_NETWORKPROXY QList<QNetworkProxy> proxyList = d->queryProxy(QNetworkProxyQuery(request.url())); priv->proxyList = proxyList; #endif if (priv->backend) { priv->backend->setParent(reply); priv->backend->reply = priv; } // fourth step: setup the reply priv->setup(op, request, outgoingData); #ifndef QT_NO_OPENSSL reply->setSslConfiguration(request.sslConfiguration()); #endif return reply; }
void NetworkManager::sslError(QNetworkReply* reply, QList<QSslError> errors) { if (m_ignoreAllWarnings) { reply->ignoreSslErrors(errors); return; } if (reply->property("downReply").toBool()) { return; } int errorsIgnored = 0; foreach(const QSslError & error, errors) { if (m_ignoredCerts.contains(error.certificate())) { ++errorsIgnored; } } if (errorsIgnored == errors.count()) { return; } QNetworkRequest request = reply->request(); QVariant v = request.attribute((QNetworkRequest::Attribute)(QNetworkRequest::User + 100)); WebPage* webPage = static_cast<WebPage*>(v.value<void*>()); if (!webPage) { return; } QString title = tr("SSL Certificate Error!"); QString text1 = tr("The page you are trying to access has the following errors in the SSL certificate:"); QString certs; foreach(const QSslError & error, errors) { if (m_localCerts.contains(error.certificate())) { continue; } if (error.error() == QSslError::NoError) { //Weird behavior on Windows continue; } QSslCertificate cert = error.certificate(); certs.append("<ul><li>"); certs.append(tr("<b>Organization: </b>") + CertificateInfoWidget::clearCertSpecialSymbols(cert.subjectInfo(QSslCertificate::Organization))); certs.append("</li><li>"); certs.append(tr("<b>Domain Name: </b>") + CertificateInfoWidget::clearCertSpecialSymbols(cert.subjectInfo(QSslCertificate::CommonName))); certs.append("</li><li>"); certs.append(tr("<b>Expiration Date: </b>") + cert.expiryDate().toString("hh:mm:ss dddd d. MMMM yyyy")); certs.append("</li><li>"); certs.append(tr("<b>Error: </b>") + error.errorString()); certs.append("</li></ul>"); } QString text2 = tr("Would you like to make an exception for this certificate?"); QString message = QString("<b>%1</b><p>%2</p>%3<p>%4</p>").arg(title, text1, certs, text2); if (!certs.isEmpty()) { if (QMessageBox::critical(webPage->view(), tr("SSL Certificate Error!"), message, QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::No) { return; } foreach(const QSslError & error, errors) { if (!m_localCerts.contains(error.certificate())) { addLocalCertificate(error.certificate()); } } } reply->ignoreSslErrors(errors); }
void QgsWcsCapabilities::capabilitiesReplyFinished() { if ( mCapabilitiesReply->error() == QNetworkReply::NoError ) { QVariant redirect = mCapabilitiesReply->attribute( QNetworkRequest::RedirectionTargetAttribute ); if ( !redirect.isNull() ) { emit statusChanged( tr( "Capabilities request redirected." ) ); QNetworkRequest request( redirect.toUrl() ); QgsSetRequestInitiatorClass( request, QStringLiteral( "QgsWcsCapabilities" ) ); if ( !setAuthorization( request ) ) { mCapabilitiesResponse.clear(); mError = tr( "Download of capabilities failed: network request update failed for authentication config" ); QgsMessageLog::logMessage( mError, tr( "WCS" ) ); return; } request.setAttribute( QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferNetwork ); request.setAttribute( QNetworkRequest::CacheSaveControlAttribute, true ); mCapabilitiesReply->deleteLater(); QgsDebugMsg( QStringLiteral( "redirected getcapabilities: %1" ).arg( redirect.toString() ) ); mCapabilitiesReply = QgsNetworkAccessManager::instance()->get( request ); if ( !setAuthorizationReply( mCapabilitiesReply ) ) { mCapabilitiesResponse.clear(); mCapabilitiesReply->deleteLater(); mCapabilitiesReply = nullptr; mError = tr( "Download of capabilities failed: network reply update failed for authentication config" ); QgsMessageLog::logMessage( mError, tr( "WCS" ) ); return; } connect( mCapabilitiesReply, &QNetworkReply::finished, this, &QgsWcsCapabilities::capabilitiesReplyFinished ); connect( mCapabilitiesReply, &QNetworkReply::downloadProgress, this, &QgsWcsCapabilities::capabilitiesReplyProgress ); return; } mCapabilitiesResponse = mCapabilitiesReply->readAll(); if ( mCapabilitiesResponse.isEmpty() ) { mErrorFormat = QStringLiteral( "text/plain" ); mError = tr( "empty of capabilities: %1" ).arg( mCapabilitiesReply->errorString() ); } } else { // Resend request if AlwaysCache QNetworkRequest request = mCapabilitiesReply->request(); QgsSetRequestInitiatorClass( request, QStringLiteral( "QgsWcsCapabilities" ) ); if ( request.attribute( QNetworkRequest::CacheLoadControlAttribute ).toInt() == QNetworkRequest::AlwaysCache ) { QgsDebugMsg( QStringLiteral( "Resend request with PreferCache" ) ); request.setAttribute( QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache ); mCapabilitiesReply->deleteLater(); mCapabilitiesReply = QgsNetworkAccessManager::instance()->get( request ); if ( !setAuthorizationReply( mCapabilitiesReply ) ) { mCapabilitiesResponse.clear(); mCapabilitiesReply->deleteLater(); mCapabilitiesReply = nullptr; mError = tr( "Download of capabilities failed: network reply update failed for authentication config" ); QgsMessageLog::logMessage( mError, tr( "WCS" ) ); return; } connect( mCapabilitiesReply, &QNetworkReply::finished, this, &QgsWcsCapabilities::capabilitiesReplyFinished ); connect( mCapabilitiesReply, &QNetworkReply::downloadProgress, this, &QgsWcsCapabilities::capabilitiesReplyProgress ); return; } mErrorFormat = QStringLiteral( "text/plain" ); mError = tr( "Download of capabilities failed: %1" ).arg( mCapabilitiesReply->errorString() ); QgsMessageLog::logMessage( mError, tr( "WCS" ) ); mCapabilitiesResponse.clear(); } mCapabilitiesReply->deleteLater(); mCapabilitiesReply = nullptr; emit downloadFinished(); }