37#include <QAuthenticator>
39#include <QNetworkReply>
40#include <QRecursiveMutex>
41#include <QStandardPaths>
43#include <QThreadStorage>
48#include "moc_qgsnetworkaccessmanager.cpp"
50using namespace Qt::StringLiterals;
66#include <QSslConfiguration>
74static std::vector< std::pair< QString, std::function< void( QNetworkRequest * ) > > > sCustomPreprocessors;
75static std::vector< std::pair< QString, std::function< void( QNetworkRequest *,
int &op, QByteArray *data ) > > > sCustomAdvancedPreprocessors;
76static std::vector< std::pair< QString, std::function< void(
const QNetworkRequest &, QNetworkReply * ) > > > sCustomReplyPreprocessors;
79class QgsNetworkProxyFactory :
public QNetworkProxyFactory
82 QgsNetworkProxyFactory() =
default;
84 QList<QNetworkProxy> queryProxy(
const QNetworkProxyQuery &query = QNetworkProxyQuery() )
override
90 for ( QNetworkProxyFactory *f : constProxyFactories )
92 QList<QNetworkProxy> systemproxies = QNetworkProxyFactory::systemProxyForQuery( query );
93 if ( !systemproxies.isEmpty() )
96 QList<QNetworkProxy> proxies = f->queryProxy( query );
97 if ( !proxies.isEmpty() )
102 if ( query.queryType() != QNetworkProxyQuery::UrlRequest )
105 const QString url = query.url().toString();
108 for (
const QString &noProxy : constNoProxyList )
110 if ( !noProxy.trimmed().isEmpty() && url.startsWith( noProxy ) )
112 QgsDebugMsgLevel( u
"don't using any proxy for %1 [exclude %2]"_s.arg( url, noProxy ), 4 );
113 return QList<QNetworkProxy>() << QNetworkProxy( QNetworkProxy::NoProxy );
118 for (
const QString &exclude : constExcludeList )
120 if ( !exclude.trimmed().isEmpty() && url.startsWith( exclude ) )
122 QgsDebugMsgLevel( u
"using default proxy for %1 [exclude %2]"_s.arg( url, exclude ), 4 );
123 return QList<QNetworkProxy>() << QNetworkProxy( QNetworkProxy::DefaultProxy );
129 QgsDebugMsgLevel( u
"requesting system proxy for query %1"_s.arg( url ), 4 );
130 QList<QNetworkProxy> proxies = QNetworkProxyFactory::systemProxyForQuery( query );
131 if ( !proxies.isEmpty() )
133 QgsDebugMsgLevel( u
"using system proxy %1:%2 for query"_s.arg( proxies.first().hostName() ).arg( proxies.first().port() ), 4 );
145class QgsNetworkCookieJar :
public QNetworkCookieJar
150 QgsNetworkCookieJar( QgsNetworkAccessManager *parent )
151 : QNetworkCookieJar( parent )
155 bool deleteCookie(
const QNetworkCookie &cookie )
override
157 const QMutexLocker locker( &mMutex );
158 if ( QNetworkCookieJar::deleteCookie( cookie ) )
160 emit mNam->cookiesChanged( allCookies() );
165 bool insertCookie(
const QNetworkCookie &cookie )
override
167 const QMutexLocker locker( &mMutex );
168 if ( QNetworkCookieJar::insertCookie( cookie ) )
170 emit mNam->cookiesChanged( allCookies() );
175 bool setCookiesFromUrl(
const QList<QNetworkCookie> &cookieList,
const QUrl &url )
override
177 const QMutexLocker locker( &mMutex );
178 return QNetworkCookieJar::setCookiesFromUrl( cookieList, url );
180 bool updateCookie(
const QNetworkCookie &cookie )
override
182 const QMutexLocker locker( &mMutex );
183 if ( QNetworkCookieJar::updateCookie( cookie ) )
185 emit mNam->cookiesChanged( allCookies() );
192 QList<QNetworkCookie> allCookies()
const
194 const QMutexLocker locker( &mMutex );
195 return QNetworkCookieJar::allCookies();
197 void setAllCookies(
const QList<QNetworkCookie> &cookieList )
199 const QMutexLocker locker( &mMutex );
200 QNetworkCookieJar::setAllCookies( cookieList );
203 QgsNetworkAccessManager *mNam =
nullptr;
204 mutable QRecursiveMutex mMutex;
214 static QThreadStorage<QgsNetworkAccessManager> sInstances;
217 if ( nam->thread() == qApp->thread() )
220 if ( !nam->mInitialized )
222 QgsDebugMsgLevel( u
"Initializing new network access manager for %1thread: %2"_s.arg( QThread::currentThread() == qApp->thread() ? u
"MAIN "_s : QString() ).arg(
reinterpret_cast< qint64
>( QThread::currentThread() ), 0, 16 ), 2 );
228 QgsDebugMsgLevel( u
"Network access manager retrieved for %1thread: %2"_s.arg( QThread::currentThread() == qApp->thread() ? u
"MAIN "_s : QString() ).arg(
reinterpret_cast< qint64
>( QThread::currentThread() ), 0, 16 ), 4 );
235 : QNetworkAccessManager( parent )
236 , mSslErrorHandlerSemaphore( 1 )
237 , mAuthRequestHandlerSemaphore( 1 )
239 setRedirectPolicy( QNetworkRequest::NoLessSafeRedirectPolicy );
240 setProxyFactory(
new QgsNetworkProxyFactory() );
241 setCookieJar(
new QgsNetworkCookieJar(
this ) );
242 enableStrictTransportSecurityStore(
true );
243 setStrictTransportSecurityEnabled(
true );
257 Q_ASSERT( sMainNAM ==
this );
258 mSslErrorHandler = std::move( handler );
263 Q_ASSERT( sMainNAM ==
this );
264 mAuthHandler = std::move( handler );
269 mProxyFactories.insert( 0, factory );
274 mProxyFactories.removeAll( factory );
279 return mProxyFactories;
284 return mExcludedURLs;
294 return mFallbackProxy;
300 u
"proxy settings: (type:%1 host: %2:%3, user:%4, password:%5"_s
302 proxy.type() == QNetworkProxy::DefaultProxy ? u
"DefaultProxy"_s
303 : proxy.type() == QNetworkProxy::Socks5Proxy ? u
"Socks5Proxy"_s
304 : proxy.type() == QNetworkProxy::NoProxy ? u
"NoProxy"_s
305 : proxy.type() == QNetworkProxy::HttpProxy ? u
"HttpProxy"_s
306 : proxy.type() == QNetworkProxy::HttpCachingProxy ? u
"HttpCachingProxy"_s
307 : proxy.type() == QNetworkProxy::FtpCachingProxy ? u
"FtpCachingProxy"_s
312 .arg( proxy.user(), proxy.password().isEmpty() ? u
"not set"_s : u
"set"_s ),
316 mFallbackProxy = proxy;
317 mExcludedURLs = excludes;
321 mExcludedURLs.begin(),
323 [](
const QString &url ) { return url.trimmed().isEmpty(); }
328 mNoProxyURLs = noProxyURLs;
331 mNoProxyURLs.begin(),
333 [](
const QString &url ) { return url.trimmed().isEmpty(); }
341 QgsDebugMsgLevel( u
"Creating new network request on thread: %1 for %2"_s.arg(
reinterpret_cast< qint64
>( QThread::currentThread() ), 0, 16 ).arg( req.url().toString() ), 3 );
344 QNetworkRequest modifiedRequest( req );
347 const QVariant userAgentCustomSuffix = modifiedRequest.attribute( attrSuffix );
350 if ( !userAgentCustomSuffix.toString().isEmpty() )
352 userAgent.append(
' ' + userAgentCustomSuffix.toString() );
355 modifiedRequest.setRawHeader(
"User-Agent",
userAgent.toLatin1() );
358 const bool ishttps = modifiedRequest.url().scheme().compare(
"https"_L1, Qt::CaseInsensitive ) == 0;
362 QSslConfiguration sslconfig( modifiedRequest.sslConfiguration() );
364 sslconfig.setCaCertificates( QgsAuthCertUtils::casMerge(
QgsApplication::authManager()->trustedCaCertsCache(), sslconfig.caCertificates() ) );
366 const QString hostport( u
"%1:%2"_s.arg( modifiedRequest.url().host().trimmed() ).arg( modifiedRequest.url().port() != -1 ? modifiedRequest.url().port() : 443 ) );
368 if ( !servconfig.
isNull() )
370 QgsDebugMsgLevel( u
"Adding SSL custom config to request for %1"_s.arg( hostport ), 2 );
376 modifiedRequest.setSslConfiguration( sslconfig );
380 if ( modifiedRequest.url().port() != -1 )
382 QUrl requestUrl = modifiedRequest.url();
383 const QString scheme = requestUrl.scheme();
384 const bool isDefaultPort = ( scheme ==
"http"_L1 && requestUrl.port() == 80 ) || ( scheme ==
"https"_L1 && requestUrl.port() == 443 );
387 QgsDebugMsgLevel( u
"Removing explicit default port %2 from url %1"_s.arg( requestUrl.port() ).arg( requestUrl.toString() ), 2 );
388 requestUrl.setPort( -1 );
389 modifiedRequest.setUrl( requestUrl );
393 if ( sMainNAM->mCacheDisabled )
396 modifiedRequest.setAttribute( QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::AlwaysNetwork );
397 modifiedRequest.setAttribute( QNetworkRequest::CacheSaveControlAttribute,
false );
400 for (
const auto &preprocessor : sCustomPreprocessors )
402 preprocessor.second( &modifiedRequest );
405 static QAtomicInt sRequestId = 0;
406 const int requestId = ++sRequestId;
408 if ( QBuffer *buffer = qobject_cast<QBuffer *>( outgoingData ) )
410 content = buffer->buffer();
413 for (
const auto &preprocessor : sCustomAdvancedPreprocessors )
415 int intOp =
static_cast< int >( op );
416 preprocessor.second( &modifiedRequest, intOp, &content );
417 op =
static_cast< QNetworkAccessManager::Operation
>( intOp );
420 bool needsCachePendingRequestCleanup =
false;
423 if ( modifiedRequest.attribute( QNetworkRequest::CacheLoadControlAttribute ) != QNetworkRequest::AlwaysNetwork )
427 if ( diskCache->hasInvalidMatchForRequest( modifiedRequest ) )
429 if ( modifiedRequest.attribute( QNetworkRequest::CacheSaveControlAttribute ).toBool() )
432 diskCache->remove( modifiedRequest.url() );
437 modifiedRequest.setAttribute( QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::AlwaysNetwork );
438 modifiedRequest.setAttribute( QNetworkRequest::CacheSaveControlAttribute,
false );
443 if ( modifiedRequest.attribute( QNetworkRequest::CacheSaveControlAttribute,
true ).toBool() )
445 if ( diskCache->hasPendingRequestForUrl( modifiedRequest.url() ) )
448 modifiedRequest.setAttribute( QNetworkRequest::CacheSaveControlAttribute,
false );
452 QVariantMap currentHeaders;
453 const QList<QByteArray> rawHeaderList = modifiedRequest.rawHeaderList();
454 for (
const QByteArray &header : rawHeaderList )
456 currentHeaders.insert( QString::fromUtf8( header ).toLower(), modifiedRequest.rawHeader( header ) );
458 diskCache->insertPendingRequestHeaders( modifiedRequest.url(), currentHeaders );
459 needsCachePendingRequestCleanup =
true;
468 QNetworkReply *reply = QNetworkAccessManager::createRequest( op, modifiedRequest, outgoingData );
469 reply->setProperty(
"requestId", requestId );
476 connect( reply, &QNetworkReply::downloadProgress,
this, &QgsNetworkAccessManager::onReplyDownloadProgress );
478 connect( reply, &QNetworkReply::sslErrors,
this, &QgsNetworkAccessManager::onReplySslErrors );
481 for (
const auto &replyPreprocessor : sCustomReplyPreprocessors )
483 replyPreprocessor.second( modifiedRequest, reply );
486 if ( needsCachePendingRequestCleanup )
490 const QUrl url = modifiedRequest.url();
491 connect( reply, &QNetworkReply::finished, diskCache, [url, diskCache] { diskCache->removePendingRequestForUrl( url ); } );
500 QTimer *timer =
new QTimer( reply );
501 timer->setObjectName( u
"timeoutTimer"_s );
502 connect( timer, &QTimer::timeout,
this, &QgsNetworkAccessManager::abortRequest );
503 timer->setSingleShot(
true );
506 connect( reply, &QNetworkReply::downloadProgress, timer, [timer] { timer->start(); } );
507 connect( reply, &QNetworkReply::uploadProgress, timer, [timer] { timer->start(); } );
508 connect( reply, &QNetworkReply::finished, timer, &QTimer::stop );
510 QgsDebugMsgLevel( u
"Created [reply:%1]"_s.arg(
reinterpret_cast< qint64
>( reply ), 0, 16 ), 3 );
515void QgsNetworkAccessManager::abortRequest()
517 QTimer *timer = qobject_cast<QTimer *>( sender() );
520 QNetworkReply *reply = qobject_cast<QNetworkReply *>( timer->parent() );
524 QgsDebugMsgLevel( u
"Abort [reply:%1] %2"_s.arg(
reinterpret_cast< qint64
>( reply ), 0, 16 ).arg( reply->url().toString() ), 3 );
531void QgsNetworkAccessManager::onReplyFinished( QNetworkReply *reply )
533 emit
finished( QgsNetworkReplyContent( reply ) );
536void QgsNetworkAccessManager::onReplyDownloadProgress( qint64 bytesReceived, qint64 bytesTotal )
538 if ( QNetworkReply *reply = qobject_cast< QNetworkReply *>( sender() ) )
544int QgsNetworkAccessManager::getRequestId( QNetworkReply *reply )
546 return reply->property(
"requestId" ).toInt();
549void QgsNetworkAccessManager::pauseTimeout( QNetworkReply *reply )
551 Q_ASSERT( reply->manager() ==
this );
553 QTimer *timer = reply->findChild<QTimer *>( u
"timeoutTimer"_s );
554 if ( timer && timer->isActive() )
560void QgsNetworkAccessManager::restartTimeout( QNetworkReply *reply )
562 Q_ASSERT( reply->manager() ==
this );
564 QTimer *timer = reply->findChild<QTimer *>( u
"timeoutTimer"_s );
567 Q_ASSERT( !timer->isActive() );
569 timer->setSingleShot(
true );
574void QgsNetworkAccessManager::afterAuthRequestHandled( QNetworkReply *reply )
576 if ( reply->manager() ==
this )
578 restartTimeout( reply );
579 emit authRequestHandled( reply );
584void QgsNetworkAccessManager::onReplySslErrors(
const QList<QSslError> &errors )
586 QNetworkReply *reply = qobject_cast< QNetworkReply *>( sender() );
588 Q_ASSERT( reply->manager() ==
this );
590 QgsDebugMsgLevel( u
"Stopping network reply timeout whilst SSL error is handled"_s, 2 );
591 pauseTimeout( reply );
596 mSslErrorHandlerSemaphore.acquire();
600 emit sslErrorsOccurred( reply, errors );
601 if (
this != sMainNAM )
605 mSslErrorHandlerSemaphore.acquire();
606 mSslErrorHandlerSemaphore.release();
607 afterSslErrorHandled( reply );
611void QgsNetworkAccessManager::afterSslErrorHandled( QNetworkReply *reply )
613 if ( reply->manager() ==
this )
615 restartTimeout( reply );
616 emit sslErrorsHandled( reply );
620void QgsNetworkAccessManager::handleSslErrors( QNetworkReply *reply,
const QList<QSslError> &errors )
622 mSslErrorHandler->handleSslErrors( reply, errors );
623 afterSslErrorHandled( reply );
624 qobject_cast<QgsNetworkAccessManager *>( reply->manager() )->mSslErrorHandlerSemaphore.release();
629void QgsNetworkAccessManager::onAuthRequired( QNetworkReply *reply, QAuthenticator *auth )
632 Q_ASSERT( reply->manager() ==
this );
634 QgsDebugMsgLevel( u
"Stopping network reply timeout whilst auth request is handled"_s, 2 );
635 pauseTimeout( reply );
640 mAuthRequestHandlerSemaphore.acquire();
644 emit authRequestOccurred( reply, auth );
646 if (
this != sMainNAM )
650 mAuthRequestHandlerSemaphore.acquire();
651 mAuthRequestHandlerSemaphore.release();
652 afterAuthRequestHandled( reply );
658 if (
this != sMainNAM )
660 sMainNAM->requestAuthOpenBrowser( url );
664 mAuthHandler->handleAuthRequestOpenBrowser( url );
669 if (
this != sMainNAM )
671 sMainNAM->requestAuthCloseBrowser();
675 mAuthHandler->handleAuthRequestCloseBrowser();
680 if (
this != sMainNAM )
687void QgsNetworkAccessManager::handleAuthRequest( QNetworkReply *reply, QAuthenticator *auth )
689 mAuthHandler->handleAuthRequest( reply, auth );
693 afterAuthRequestHandled( reply );
694 qobject_cast<QgsNetworkAccessManager *>( reply->manager() )->mAuthRequestHandlerSemaphore.release();
701 case QNetworkRequest::AlwaysNetwork:
702 return u
"AlwaysNetwork"_s;
703 case QNetworkRequest::PreferNetwork:
704 return u
"PreferNetwork"_s;
705 case QNetworkRequest::PreferCache:
706 return u
"PreferCache"_s;
707 case QNetworkRequest::AlwaysCache:
708 return u
"AlwaysCache"_s;
710 return u
"PreferNetwork"_s;
715 if ( name ==
"AlwaysNetwork"_L1 )
717 return QNetworkRequest::AlwaysNetwork;
719 else if ( name ==
"PreferNetwork"_L1 )
721 return QNetworkRequest::PreferNetwork;
723 else if ( name ==
"PreferCache"_L1 )
725 return QNetworkRequest::PreferCache;
727 else if ( name ==
"AlwaysCache"_L1 )
729 return QNetworkRequest::AlwaysCache;
731 return QNetworkRequest::PreferNetwork;
737 mUseSystemProxy =
false;
739 Q_ASSERT( sMainNAM );
741 if ( sMainNAM !=
this )
743 connect(
this, &QNetworkAccessManager::proxyAuthenticationRequired, sMainNAM, &QNetworkAccessManager::proxyAuthenticationRequired, connectionType );
758 connect(
this, &QNetworkAccessManager::sslErrors, sMainNAM, &QNetworkAccessManager::sslErrors, connectionType );
770 if ( !mSslErrorHandler )
774 setAuthHandler( std::make_unique< QgsNetworkAuthenticationHandler>() );
777 connect(
this, &QgsNetworkAccessManager::sslErrorsOccurred, sMainNAM, &QgsNetworkAccessManager::handleSslErrors );
779 connect(
this, &QNetworkAccessManager::authenticationRequired,
this, &QgsNetworkAccessManager::onAuthRequired );
780 connect(
this, &QgsNetworkAccessManager::authRequestOccurred, sMainNAM, &QgsNetworkAccessManager::handleAuthRequest );
782 connect(
this, &QNetworkAccessManager::finished,
this, &QgsNetworkAccessManager::onReplyFinished );
786 QStringList excludes;
787 QStringList noProxyURLs;
807 if ( proxyTypeString ==
"DefaultProxy"_L1 )
809 mUseSystemProxy =
true;
810 QNetworkProxyFactory::setUseSystemConfiguration(
true );
811 QList<QNetworkProxy> proxies = QNetworkProxyFactory::systemProxyForQuery();
812 if ( !proxies.isEmpty() )
814 proxy = proxies.first();
820 QNetworkProxy::ProxyType proxyType = QNetworkProxy::DefaultProxy;
821 if ( proxyTypeString ==
"Socks5Proxy"_L1 )
823 proxyType = QNetworkProxy::Socks5Proxy;
825 else if ( proxyTypeString ==
"HttpProxy"_L1 )
827 proxyType = QNetworkProxy::HttpProxy;
829 else if ( proxyTypeString ==
"HttpCachingProxy"_L1 )
831 proxyType = QNetworkProxy::HttpCachingProxy;
833 else if ( proxyTypeString ==
"FtpCachingProxy"_L1 )
835 proxyType = QNetworkProxy::FtpCachingProxy;
837 QgsDebugMsgLevel( u
"setting proxy %1 %2:%3 %4/%5"_s.arg( proxyType ).arg( proxyHost ).arg( proxyPort ).arg( proxyUser, proxyPassword ), 2 );
838 proxy = QNetworkProxy( proxyType, proxyHost, proxyPort, proxyUser, proxyPassword );
842 if ( !authcfg.isEmpty() )
845 QgsDebugMsgLevel( u
"setting proxy from stored authentication configuration %1"_s.arg( authcfg ), 2 );
848 authManager->updateNetworkProxy( proxy, authcfg );
850 QgsDebugError( u
"Auth manager is not available - cannot update network proxy for authcfg: %1"_s.arg( authcfg ) );
862 if ( cacheDirectory.isEmpty() )
863 cacheDirectory = QStandardPaths::writableLocation( QStandardPaths::CacheLocation );
871 if ( cache() != newcache )
872 setCache( newcache );
874 if (
this != sMainNAM )
876 static_cast<QgsNetworkCookieJar *
>( cookieJar() )->setAllCookies(
static_cast<QgsNetworkCookieJar *
>( sMainNAM->cookieJar() )->allCookies() );
880void QgsNetworkAccessManager::syncCookies(
const QList<QNetworkCookie> &cookies )
882 if ( sender() !=
this )
884 static_cast<QgsNetworkCookieJar *
>( cookieJar() )->setAllCookies( cookies );
885 if (
this == sMainNAM )
906 br.
get( request, forceRefresh, feedback );
916 ( void ) br.
post( request, data, forceRefresh, feedback );
922 QString
id = QUuid::createUuid().toString();
923 sCustomPreprocessors.emplace_back( std::make_pair(
id, processor ) );
929 const size_t prevCount = sCustomPreprocessors.size();
930 sCustomPreprocessors.erase(
931 std::remove_if( sCustomPreprocessors.begin(), sCustomPreprocessors.end(), [
id]( std::pair< QString, std::function<
void( QNetworkRequest * ) > > &a ) { return a.first == id; } ),
932 sCustomPreprocessors.end()
934 return prevCount != sCustomPreprocessors.size();
939 const size_t prevCount = sCustomAdvancedPreprocessors.size();
940 sCustomAdvancedPreprocessors.erase(
942 sCustomAdvancedPreprocessors.begin(),
943 sCustomAdvancedPreprocessors.end(),
944 [
id]( std::pair< QString, std::function<
void( QNetworkRequest *,
int &, QByteArray * ) > > &a ) { return a.first == id; }
946 sCustomAdvancedPreprocessors.end()
948 return prevCount != sCustomAdvancedPreprocessors.size();
953 QString
id = QUuid::createUuid().toString();
954 sCustomAdvancedPreprocessors.emplace_back( std::make_pair(
id, processor ) );
960 QString
id = QUuid::createUuid().toString();
961 sCustomReplyPreprocessors.emplace_back( std::make_pair(
id, processor ) );
967 const size_t prevCount = sCustomReplyPreprocessors.size();
968 sCustomReplyPreprocessors.erase(
970 sCustomReplyPreprocessors.begin(), sCustomReplyPreprocessors.end(), [
id]( std::pair< QString, std::function<
void(
const QNetworkRequest &, QNetworkReply * ) > > &a ) { return a.first == id; }
972 sCustomReplyPreprocessors.end()
974 return prevCount != sCustomReplyPreprocessors.size();
979 for (
const auto &preprocessor : sCustomPreprocessors )
981 preprocessor.second( req );
993 , mOriginatingThreadId( u
"0x%2"_s.arg( reinterpret_cast<quintptr>( QThread::currentThread() ), 2 * QT_POINTER_SIZE, 16,
'0'_L1 ) )
1008 QgsDebugError( u
"SSL errors occurred accessing URL:\n%1"_s.arg( reply->request().url().toString() ) );
1018 QgsDebugError( u
"Network reply required authentication, but no handler was in place to provide this authentication request while accessing the URL:\n%1"_s.arg( reply->request().url().toString() ) );
1024 QgsDebugError( u
"Network authentication required external browser to open URL %1, but no handler was in place"_s.arg( url.toString() ) );
1029 QgsDebugError( u
"Network authentication required external browser closed, but no handler was in place"_s );
1033#include "qgsnetworkaccessmanager.moc"
QFlags< NetworkRequestFlag > NetworkRequestFlags
Flags controlling behavior of network requests.
static int versionInt()
Version number used for comparing versions using the "Check QGIS Version" function.
static QgsAuthManager * authManager()
Returns the application's authentication manager instance.
Configuration container for SSL server connection exceptions or overrides.
QSsl::SslProtocol sslProtocol() const
SSL server protocol to use in connections.
int sslPeerVerifyDepth() const
Number or SSL client's peer to verify in connections.
bool isNull() const
Whether configuration is null (missing components).
QSslSocket::PeerVerifyMode sslPeerVerifyMode() const
SSL client's peer verify mode to use in connections.
Singleton which offers an interface to manage the authentication configuration database and to utiliz...
const QgsAuthConfigSslServer sslCertCustomConfigByHost(const QString &hostport)
sslCertCustomConfigByHost get an SSL certificate custom config by hostport (host:port)
A thread safe class for performing blocking (sync) network requests, with full support for QGIS proxy...
ErrorCode post(QNetworkRequest &request, QIODevice *data, bool forceRefresh=false, QgsFeedback *feedback=nullptr)
Performs a "post" operation on the specified request, using the given data.
void setAuthCfg(const QString &authCfg)
Sets the authentication config id which should be used during the request.
ErrorCode get(QNetworkRequest &request, bool forceRefresh=false, QgsFeedback *feedback=nullptr, RequestFlags requestFlags=QgsBlockingNetworkRequest::RequestFlags())
Performs a "get" operation on the specified request.
QgsNetworkReplyContent reply() const
Returns the content of the network reply, after a get(), post(), head() or put() request has been mad...
Base class for feedback objects to be used for cancellation of something running in a worker thread.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true, const char *file=__builtin_FILE(), const char *function=__builtin_FUNCTION(), int line=__builtin_LINE(), Qgis::StringFormat format=Qgis::StringFormat::PlainText)
Adds a message to the log instance (and creates it if necessary).
QNetworkAccessManager with additional QGIS specific logic.
QStringList noProxyList() const
Returns the no proxy list.
void finished(QgsNetworkReplyContent reply)
Emitted whenever a pending network reply is finished.
static const QgsSettingsEntryString * settingsProxyAuthCfg
Settings entry for proxy authentication configuration.
static const QgsSettingsEntryInteger * settingsNetworkTimeout
Settings entry network timeout.
void cookiesChanged(const QList< QNetworkCookie > &cookies)
Emitted when the cookies changed.
void insertProxyFactory(QNetworkProxyFactory *factory)
Inserts a factory into the proxy factories list.
void setSslErrorHandler(std::unique_ptr< QgsSslErrorHandler > handler)
Sets the application SSL error handler, which is used to respond to SSL errors encountered during net...
Q_DECL_DEPRECATED void requestAboutToBeCreated(QNetworkAccessManager::Operation operation, const QNetworkRequest &request, QIODevice *device)
void abortAuthBrowser()
Abort any outstanding external browser login request.
void setCacheDisabled(bool disabled)
Sets whether all network caching should be disabled.
const QList< QNetworkProxyFactory * > proxyFactories() const
Returns a list of proxy factories used by the manager.
void downloadProgress(int requestId, qint64 bytesReceived, qint64 bytesTotal)
Emitted when a network reply receives a progress report.
void requestAuthOpenBrowser(const QUrl &url) const
Forwards an external browser login url opening request to the authentication handler.
void requestAuthCloseBrowser() const
Forwards an external browser login closure request to the authentication handler.
void requestEncounteredSslErrors(int requestId, const QList< QSslError > &errors)
Emitted when a network request encounters SSL errors.
static const QgsSettingsEntryString * settingsProxyUser
Settings entry for proxy user.
static QString cacheLoadControlName(QNetworkRequest::CacheLoadControl control)
Returns the name for QNetworkRequest::CacheLoadControl.
static const QgsSettingsEntryString * settingsProxyHost
Settings entry for proxy host.
void requestCreated(const QgsNetworkRequestParameters &request)
Emitted when a network request has been created.
static QgsNetworkReplyContent blockingGet(QNetworkRequest &request, const QString &authCfg=QString(), bool forceRefresh=false, QgsFeedback *feedback=nullptr, Qgis::NetworkRequestFlags flags=Qgis::NetworkRequestFlags())
Posts a GET request to obtain the contents of the target request and returns a new QgsNetworkReplyCon...
static QString setReplyPreprocessor(const std::function< void(const QNetworkRequest &, QNetworkReply *)> &processor)
Sets a reply pre-processor function, which allows manipulation of QNetworkReply objects after they ar...
static bool removeRequestPreprocessor(const QString &id)
Removes the custom request pre-processor function with matching id.
void requestAuthDetailsAdded(int requestId, const QString &realm, const QString &user, const QString &password)
Emitted when network authentication details have been added to a request.
static QString userAgent()
Returns the user agent string used by QGIS for network requests.
static const QgsSettingsEntryString * settingsProxyPort
Settings entry for proxy port.
static QNetworkRequest::CacheLoadControl cacheLoadControlFromName(const QString &name)
Returns QNetworkRequest::CacheLoadControl from a name.
static const QgsSettingsEntryString * settingsProxyExcludedUrls
Settings entry for proxy excluded URLs (legacy, falls back to system proxy for these).
static bool removeAdvancedRequestPreprocessor(const QString &id)
Removes an advanced request pre-processor function with matching id.
QgsNetworkAccessManager(QObject *parent=nullptr)
void requestRequiresAuth(int requestId, const QString &realm)
Emitted when a network request prompts an authentication request.
void preprocessRequest(QNetworkRequest *req) const
Preprocesses request.
void setAuthHandler(std::unique_ptr< QgsNetworkAuthenticationHandler > handler)
Sets the application network authentication handler, which is used to respond to network authenticati...
static void setTimeout(int time)
Sets the maximum timeout time for network requests, in milliseconds.
static QString setAdvancedRequestPreprocessor(const std::function< void(QNetworkRequest *, int &op, QByteArray *data)> &processor)
Sets an advanced request pre-processor function, which allows manipulation of a network request befor...
const QNetworkProxy & fallbackProxy() const
Returns the fallback proxy used by the manager.
static const QgsSettingsEntryString * settingsUserAgent
Settings entry for user agent string.
static QgsNetworkReplyContent blockingPost(QNetworkRequest &request, const QByteArray &data, const QString &authCfg=QString(), bool forceRefresh=false, QgsFeedback *feedback=nullptr, Qgis::NetworkRequestFlags flags=Qgis::NetworkRequestFlags())
Posts a POST request to obtain the contents of the target request, using the given data,...
static const QgsSettingsEntryBool * settingsProxyEnabled
Settings entry for whether proxy is enabled.
static int timeout()
Returns the network timeout length, in milliseconds.
void setupDefaultProxyAndCache(Qt::ConnectionType connectionType=Qt::BlockingQueuedConnection)
Setup the QgsNetworkAccessManager (NAM) according to the user's settings.
static QString setRequestPreprocessor(const std::function< void(QNetworkRequest *request)> &processor)
Sets a request pre-processor function, which allows manipulation of a network request before it is pr...
void setFallbackProxyAndExcludes(const QNetworkProxy &proxy, const QStringList &excludes, const QStringList &noProxyURLs)
Sets the fallback proxy and URLs which shouldn't use it.
static const QgsSettingsEntryString * settingsProxyPassword
Settings entry for proxy password.
static bool removeReplyPreprocessor(const QString &id)
Removes the custom reply pre-processor function with matching id.
QStringList excludeList() const
Returns the proxy exclude list.
static const QgsSettingsEntryStringList * settingsNoProxyUrls
Settings entry for no-proxy URLs.
static QgsNetworkAccessManager * instance(Qt::ConnectionType connectionType=Qt::BlockingQueuedConnection)
Returns a pointer to the active QgsNetworkAccessManager for the current thread.
void removeProxyFactory(QNetworkProxyFactory *factory)
Removes a factory from the proxy factories list.
static const QgsSettingsEntryString * settingsProxyType
Settings entry for proxy type.
void authBrowserAborted()
Emitted when external browser logins are to be aborted.
void requestTimedOut(QgsNetworkRequestParameters request)
Emitted when a network request has timed out.
bool useSystemProxy() const
Returns whether the system proxy should be used.
QNetworkReply * createRequest(QNetworkAccessManager::Operation op, const QNetworkRequest &req, QIODevice *outgoingData=nullptr) override
virtual void handleAuthRequest(QNetworkReply *reply, QAuthenticator *auth)
Called whenever network authentication requests are encountered during a network reply.
virtual void handleAuthRequestCloseBrowser()
Called to terminate a network authentication through external browser.
virtual void handleAuthRequestOpenBrowser(const QUrl &url)
Called to initiate a network authentication through external browser url.
Wrapper implementation of QNetworkDiskCache with all methods guarded by a mutex solely for internal u...
void setCacheDirectory(const QString &cacheDir)
qint64 maximumCacheSize() const
void setMaximumCacheSize(qint64 size)
QString cacheDirectory() const
Encapsulates a network reply within a container which is inexpensive to copy and safe to pass between...
Encapsulates parameters and properties of a network request.
int requestId() const
Returns a unique ID identifying the request.
@ AttributeUserAgentSuffix
Custom string to append to the default User-Agent header.
@ AttributeInitiatorClass
Class name of original object which created the request.
@ AttributeInitiatorRequestId
Internal ID used by originator object to identify requests.
QgsNetworkRequestParameters()=default
QNetworkAccessManager::Operation operation() const
Returns the request operation, e.g.
QNetworkRequest request() const
Returns the network request.
QByteArray content() const
Returns the request's content.
A boolean settings entry.
An integer settings entry.
A string list settings entry.
static const QgsSettingsEntryInteger64 * settingsNetworkCacheSize
Settings entry network cache directory.
static const QgsSettingsEntryString * settingsNetworkCacheDirectory
Settings entry network cache directory.
static QgsSettingsTreeNode * sTreeProxy
static QgsSettingsTreeNode * sTreeNetwork
virtual void handleSslErrors(QNetworkReply *reply, const QList< QSslError > &errors)
Called whenever SSL errors are encountered during a network reply.
#define Q_NOWARN_DEPRECATED_POP
#define Q_NOWARN_DEPRECATED_PUSH
#define QgsDebugMsgLevel(str, level)
#define QgsDebugError(str)