QGIS API Documentation 4.5.0-Master (3b5d115045b)
Loading...
Searching...
No Matches
qgsnetworkaccessmanager.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsnetworkaccessmanager.cpp
3 This class implements a QNetworkManager with the ability to chain in
4 own proxy factories.
5
6 -------------------
7 begin : 2010-05-08
8 copyright : (C) 2010 by Juergen E. Fischer
9 email : jef at norbit dot de
10
11***************************************************************************/
12
13/***************************************************************************
14 * *
15 * This program is free software; you can redistribute it and/or modify *
16 * it under the terms of the GNU General Public License as published by *
17 * the Free Software Foundation; either version 2 of the License, or *
18 * (at your option) any later version. *
19 * *
20 ***************************************************************************/
21
23
24#include "qgis.h"
25#include "qgsapplication.h"
26#include "qgsauthmanager.h"
28#include "qgslogger.h"
29#include "qgsmessagelog.h"
30#include "qgsnetworkdiskcache.h"
31#include "qgsnetworkreply.h"
32#include "qgssettings.h"
35#include "qgssettingstree.h"
36
37#include <QAuthenticator>
38#include <QBuffer>
39#include <QNetworkReply>
40#include <QRecursiveMutex>
41#include <QStandardPaths>
42#include <QString>
43#include <QThreadStorage>
44#include <QTimer>
45#include <QUrl>
46#include <QUuid>
47
48#include "moc_qgsnetworkaccessmanager.cpp"
49
50using namespace Qt::StringLiterals;
51
52const QgsSettingsEntryInteger *QgsNetworkAccessManager::settingsNetworkTimeout = new QgsSettingsEntryInteger( u"network-timeout"_s, QgsSettingsTree::sTreeNetwork, 60000, QObject::tr( "Network timeout" ) );
54 = new QgsSettingsEntryString( u"user-agent"_s, QgsSettingsTree::sTreeNetwork, u"Mozilla/5.0"_s, u"User agent string for network requests"_s );
55const QgsSettingsEntryBool *QgsNetworkAccessManager::settingsProxyEnabled = new QgsSettingsEntryBool( u"proxy-enabled"_s, QgsSettingsTree::sTreeProxy, false, u"Whether network proxy is enabled"_s );
61const QgsSettingsEntryString *QgsNetworkAccessManager::settingsProxyExcludedUrls = new QgsSettingsEntryString( u"proxy-excluded-urls"_s, QgsSettingsTree::sTreeProxy, QString(), u"Proxy excluded URLs"_s );
63const QgsSettingsEntryString *QgsNetworkAccessManager::settingsProxyAuthCfg = new QgsSettingsEntryString( u"auth-cfg"_s, QgsSettingsTree::sTreeProxy, QString(), u"Proxy authentication configuration"_s );
64
65#ifndef QT_NO_SSL
66#include <QSslConfiguration>
67#endif
68
69#include "qgsnetworkdiskcache.h"
70#include "qgsauthmanager.h"
71
72QgsNetworkAccessManager *QgsNetworkAccessManager::sMainNAM = nullptr;
73
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;
77
79class QgsNetworkProxyFactory : public QNetworkProxyFactory
80{
81 public:
82 QgsNetworkProxyFactory() = default;
83
84 QList<QNetworkProxy> queryProxy( const QNetworkProxyQuery &query = QNetworkProxyQuery() ) override
85 {
86 QgsNetworkAccessManager *nam = QgsNetworkAccessManager::instance();
87
88 // iterate proxies factories and take first non empty list
89 const auto constProxyFactories = nam->proxyFactories();
90 for ( QNetworkProxyFactory *f : constProxyFactories )
91 {
92 QList<QNetworkProxy> systemproxies = QNetworkProxyFactory::systemProxyForQuery( query );
93 if ( !systemproxies.isEmpty() )
94 return systemproxies;
95
96 QList<QNetworkProxy> proxies = f->queryProxy( query );
97 if ( !proxies.isEmpty() )
98 return proxies;
99 }
100
101 // no proxies from the proxy factory list check for excludes
102 if ( query.queryType() != QNetworkProxyQuery::UrlRequest )
103 return QList<QNetworkProxy>() << nam->fallbackProxy();
104
105 const QString url = query.url().toString();
106
107 const auto constNoProxyList = nam->noProxyList();
108 for ( const QString &noProxy : constNoProxyList )
109 {
110 if ( !noProxy.trimmed().isEmpty() && url.startsWith( noProxy ) )
111 {
112 QgsDebugMsgLevel( u"don't using any proxy for %1 [exclude %2]"_s.arg( url, noProxy ), 4 );
113 return QList<QNetworkProxy>() << QNetworkProxy( QNetworkProxy::NoProxy );
114 }
115 }
116
117 const auto constExcludeList = nam->excludeList();
118 for ( const QString &exclude : constExcludeList )
119 {
120 if ( !exclude.trimmed().isEmpty() && url.startsWith( exclude ) )
121 {
122 QgsDebugMsgLevel( u"using default proxy for %1 [exclude %2]"_s.arg( url, exclude ), 4 );
123 return QList<QNetworkProxy>() << QNetworkProxy( QNetworkProxy::DefaultProxy );
124 }
125 }
126
127 if ( nam->useSystemProxy() )
128 {
129 QgsDebugMsgLevel( u"requesting system proxy for query %1"_s.arg( url ), 4 );
130 QList<QNetworkProxy> proxies = QNetworkProxyFactory::systemProxyForQuery( query );
131 if ( !proxies.isEmpty() )
132 {
133 QgsDebugMsgLevel( u"using system proxy %1:%2 for query"_s.arg( proxies.first().hostName() ).arg( proxies.first().port() ), 4 );
134 return proxies;
135 }
136 }
137
138 QgsDebugMsgLevel( u"using fallback proxy for %1"_s.arg( url ), 4 );
139 return QList<QNetworkProxy>() << nam->fallbackProxy();
140 }
141};
143
145class QgsNetworkCookieJar : public QNetworkCookieJar
146{
147 Q_OBJECT
148
149 public:
150 QgsNetworkCookieJar( QgsNetworkAccessManager *parent )
151 : QNetworkCookieJar( parent )
152 , mNam( parent )
153 {}
154
155 bool deleteCookie( const QNetworkCookie &cookie ) override
156 {
157 const QMutexLocker locker( &mMutex );
158 if ( QNetworkCookieJar::deleteCookie( cookie ) )
159 {
160 emit mNam->cookiesChanged( allCookies() );
161 return true;
162 }
163 return false;
164 }
165 bool insertCookie( const QNetworkCookie &cookie ) override
166 {
167 const QMutexLocker locker( &mMutex );
168 if ( QNetworkCookieJar::insertCookie( cookie ) )
169 {
170 emit mNam->cookiesChanged( allCookies() );
171 return true;
172 }
173 return false;
174 }
175 bool setCookiesFromUrl( const QList<QNetworkCookie> &cookieList, const QUrl &url ) override
176 {
177 const QMutexLocker locker( &mMutex );
178 return QNetworkCookieJar::setCookiesFromUrl( cookieList, url );
179 }
180 bool updateCookie( const QNetworkCookie &cookie ) override
181 {
182 const QMutexLocker locker( &mMutex );
183 if ( QNetworkCookieJar::updateCookie( cookie ) )
184 {
185 emit mNam->cookiesChanged( allCookies() );
186 return true;
187 }
188 return false;
189 }
190
191 // Override these to make them public
192 QList<QNetworkCookie> allCookies() const
193 {
194 const QMutexLocker locker( &mMutex );
195 return QNetworkCookieJar::allCookies();
196 }
197 void setAllCookies( const QList<QNetworkCookie> &cookieList )
198 {
199 const QMutexLocker locker( &mMutex );
200 QNetworkCookieJar::setAllCookies( cookieList );
201 }
202
203 QgsNetworkAccessManager *mNam = nullptr;
204 mutable QRecursiveMutex mMutex;
205};
207
208
209//
210// Static calls to enforce singleton behavior
211//
213{
214 static QThreadStorage<QgsNetworkAccessManager> sInstances;
215 QgsNetworkAccessManager *nam = &sInstances.localData();
216
217 if ( nam->thread() == qApp->thread() )
218 sMainNAM = nam;
219
220 if ( !nam->mInitialized )
221 {
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 );
223 nam->setupDefaultProxyAndCache( connectionType );
224 nam->setCacheDisabled( sMainNAM->cacheDisabled() );
225 }
226 else
227 {
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 );
229 }
230
231 return nam;
232}
233
235 : QNetworkAccessManager( parent )
236 , mSslErrorHandlerSemaphore( 1 )
237 , mAuthRequestHandlerSemaphore( 1 )
238{
239 setRedirectPolicy( QNetworkRequest::NoLessSafeRedirectPolicy );
240 setProxyFactory( new QgsNetworkProxyFactory() );
241 setCookieJar( new QgsNetworkCookieJar( this ) );
242 enableStrictTransportSecurityStore( true );
243 setStrictTransportSecurityEnabled( true );
244}
245
247{
248 QString userAgent = settingsUserAgent->value();
249 if ( !userAgent.isEmpty() )
250 userAgent += ' ';
251 userAgent += u"QGIS/%1/%2"_s.arg( Qgis::versionInt() ).arg( QSysInfo::prettyProductName() );
252 return userAgent;
253}
254
255void QgsNetworkAccessManager::setSslErrorHandler( std::unique_ptr<QgsSslErrorHandler> handler )
256{
257 Q_ASSERT( sMainNAM == this );
258 mSslErrorHandler = std::move( handler );
259}
260
261void QgsNetworkAccessManager::setAuthHandler( std::unique_ptr<QgsNetworkAuthenticationHandler> handler )
262{
263 Q_ASSERT( sMainNAM == this );
264 mAuthHandler = std::move( handler );
265}
266
267void QgsNetworkAccessManager::insertProxyFactory( QNetworkProxyFactory *factory )
268{
269 mProxyFactories.insert( 0, factory );
270}
271
272void QgsNetworkAccessManager::removeProxyFactory( QNetworkProxyFactory *factory )
273{
274 mProxyFactories.removeAll( factory );
275}
276
277const QList<QNetworkProxyFactory *> QgsNetworkAccessManager::proxyFactories() const
278{
279 return mProxyFactories;
280}
281
283{
284 return mExcludedURLs;
285}
286
288{
289 return mNoProxyURLs;
290}
291
292const QNetworkProxy &QgsNetworkAccessManager::fallbackProxy() const
293{
294 return mFallbackProxy;
295}
296
297void QgsNetworkAccessManager::setFallbackProxyAndExcludes( const QNetworkProxy &proxy, const QStringList &excludes, const QStringList &noProxyURLs )
298{
300 u"proxy settings: (type:%1 host: %2:%3, user:%4, password:%5"_s
301 .arg(
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
308 : u"Undefined"_s,
309 proxy.hostName()
310 )
311 .arg( proxy.port() )
312 .arg( proxy.user(), proxy.password().isEmpty() ? u"not set"_s : u"set"_s ),
313 4
314 );
315
316 mFallbackProxy = proxy;
317 mExcludedURLs = excludes;
318 // remove empty records from excludes list -- these would otherwise match ANY url, so the proxy would always be skipped!
319 mExcludedURLs.erase(
320 std::remove_if(
321 mExcludedURLs.begin(),
322 mExcludedURLs.end(), // clazy:exclude=detaching-member
323 []( const QString &url ) { return url.trimmed().isEmpty(); }
324 ),
325 mExcludedURLs.end()
326 ); // clazy:exclude=detaching-member
327
328 mNoProxyURLs = noProxyURLs;
329 mNoProxyURLs.erase(
330 std::remove_if(
331 mNoProxyURLs.begin(),
332 mNoProxyURLs.end(), // clazy:exclude=detaching-member
333 []( const QString &url ) { return url.trimmed().isEmpty(); }
334 ),
335 mNoProxyURLs.end()
336 ); // clazy:exclude=detaching-member
337}
338
339QNetworkReply *QgsNetworkAccessManager::createRequest( QNetworkAccessManager::Operation op, const QNetworkRequest &req, QIODevice *outgoingData )
340{
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 );
342
343 // copy request so we can modify it
344 QNetworkRequest modifiedRequest( req );
345
346 constexpr QNetworkRequest::Attribute attrSuffix = static_cast< QNetworkRequest::Attribute >( QgsNetworkRequestParameters::AttributeUserAgentSuffix );
347 const QVariant userAgentCustomSuffix = modifiedRequest.attribute( attrSuffix );
348
350 if ( !userAgentCustomSuffix.toString().isEmpty() )
351 {
352 userAgent.append( ' ' + userAgentCustomSuffix.toString() );
353 }
354
355 modifiedRequest.setRawHeader( "User-Agent", userAgent.toLatin1() );
356
357#ifndef QT_NO_SSL
358 const bool ishttps = modifiedRequest.url().scheme().compare( "https"_L1, Qt::CaseInsensitive ) == 0;
359 if ( ishttps && !QgsApplication::authManager()->isDisabled() )
360 {
361 QgsDebugMsgLevel( u"Adding trusted CA certs to request"_s, 3 );
362 QSslConfiguration sslconfig( modifiedRequest.sslConfiguration() );
363 // Merge trusted CAs with any additional CAs added by the authentication methods
364 sslconfig.setCaCertificates( QgsAuthCertUtils::casMerge( QgsApplication::authManager()->trustedCaCertsCache(), sslconfig.caCertificates() ) );
365 // check for SSL cert custom config
366 const QString hostport( u"%1:%2"_s.arg( modifiedRequest.url().host().trimmed() ).arg( modifiedRequest.url().port() != -1 ? modifiedRequest.url().port() : 443 ) );
367 const QgsAuthConfigSslServer servconfig = QgsApplication::authManager()->sslCertCustomConfigByHost( hostport.trimmed() );
368 if ( !servconfig.isNull() )
369 {
370 QgsDebugMsgLevel( u"Adding SSL custom config to request for %1"_s.arg( hostport ), 2 );
371 sslconfig.setProtocol( servconfig.sslProtocol() );
372 sslconfig.setPeerVerifyMode( servconfig.sslPeerVerifyMode() );
373 sslconfig.setPeerVerifyDepth( servconfig.sslPeerVerifyDepth() );
374 }
375
376 modifiedRequest.setSslConfiguration( sslconfig );
377 }
378#endif
379
380 if ( modifiedRequest.url().port() != -1 )
381 {
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 );
385 if ( isDefaultPort )
386 {
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 );
390 }
391 }
392
393 if ( sMainNAM->mCacheDisabled )
394 {
395 // if caching is disabled then we override whatever the request actually has set!
396 modifiedRequest.setAttribute( QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::AlwaysNetwork );
397 modifiedRequest.setAttribute( QNetworkRequest::CacheSaveControlAttribute, false );
398 }
399
400 for ( const auto &preprocessor : sCustomPreprocessors )
401 {
402 preprocessor.second( &modifiedRequest );
403 }
404
405 static QAtomicInt sRequestId = 0;
406 const int requestId = ++sRequestId;
407 QByteArray content;
408 if ( QBuffer *buffer = qobject_cast<QBuffer *>( outgoingData ) )
409 {
410 content = buffer->buffer();
411 }
412
413 for ( const auto &preprocessor : sCustomAdvancedPreprocessors )
414 {
415 int intOp = static_cast< int >( op );
416 preprocessor.second( &modifiedRequest, intOp, &content );
417 op = static_cast< QNetworkAccessManager::Operation >( intOp );
418 }
419
420 bool needsCachePendingRequestCleanup = false;
421 if ( QgsNetworkDiskCache *diskCache = qobject_cast< QgsNetworkDiskCache * >( cache() ) )
422 {
423 if ( modifiedRequest.attribute( QNetworkRequest::CacheLoadControlAttribute ) != QNetworkRequest::AlwaysNetwork )
424 {
425 // if we are going to attempt to retrieve this request from cache, first do some checks
426 // on the version in the cache
427 if ( diskCache->hasInvalidMatchForRequest( modifiedRequest ) )
428 {
429 if ( modifiedRequest.attribute( QNetworkRequest::CacheSaveControlAttribute ).toBool() )
430 {
431 // evict the previous invalid response, so this response will be cached
432 diskCache->remove( modifiedRequest.url() );
433 }
434 else
435 {
436 // can't use the previously cached response for this request, so explicitly block that
437 modifiedRequest.setAttribute( QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::AlwaysNetwork );
438 modifiedRequest.setAttribute( QNetworkRequest::CacheSaveControlAttribute, false );
439 }
440 }
441 }
442
443 if ( modifiedRequest.attribute( QNetworkRequest::CacheSaveControlAttribute, true ).toBool() )
444 {
445 if ( diskCache->hasPendingRequestForUrl( modifiedRequest.url() ) )
446 {
447 // don't allow multiple requests to attempt to write to the same cache resource
448 modifiedRequest.setAttribute( QNetworkRequest::CacheSaveControlAttribute, false );
449 }
450 else
451 {
452 QVariantMap currentHeaders;
453 const QList<QByteArray> rawHeaderList = modifiedRequest.rawHeaderList();
454 for ( const QByteArray &header : rawHeaderList )
455 {
456 currentHeaders.insert( QString::fromUtf8( header ).toLower(), modifiedRequest.rawHeader( header ) );
457 }
458 diskCache->insertPendingRequestHeaders( modifiedRequest.url(), currentHeaders );
459 needsCachePendingRequestCleanup = true;
460 }
461 }
462 }
463
464 emit requestAboutToBeCreated( QgsNetworkRequestParameters( op, modifiedRequest, requestId, content ) );
466 emit requestAboutToBeCreated( op, modifiedRequest, outgoingData );
468 QNetworkReply *reply = QNetworkAccessManager::createRequest( op, modifiedRequest, outgoingData );
469 reply->setProperty( "requestId", requestId );
470
471 emit requestCreated( QgsNetworkRequestParameters( op, reply->request(), requestId, content ) );
473 emit requestCreated( reply );
475
476 connect( reply, &QNetworkReply::downloadProgress, this, &QgsNetworkAccessManager::onReplyDownloadProgress );
477#ifndef QT_NO_SSL
478 connect( reply, &QNetworkReply::sslErrors, this, &QgsNetworkAccessManager::onReplySslErrors );
479#endif
480
481 for ( const auto &replyPreprocessor : sCustomReplyPreprocessors )
482 {
483 replyPreprocessor.second( modifiedRequest, reply );
484 }
485
486 if ( needsCachePendingRequestCleanup )
487 {
488 if ( QgsNetworkDiskCache *diskCache = qobject_cast< QgsNetworkDiskCache * >( cache() ) )
489 {
490 const QUrl url = modifiedRequest.url();
491 connect( reply, &QNetworkReply::finished, diskCache, [url, diskCache] { diskCache->removePendingRequestForUrl( url ); } );
492 }
493 }
494
495 // The timer will call abortRequest slot to abort the connection if needed.
496 // The timer is stopped by the finished signal and is restarted on downloadProgress and
497 // uploadProgress.
498 if ( timeout() )
499 {
500 QTimer *timer = new QTimer( reply );
501 timer->setObjectName( u"timeoutTimer"_s );
502 connect( timer, &QTimer::timeout, this, &QgsNetworkAccessManager::abortRequest );
503 timer->setSingleShot( true );
504 timer->start( timeout() );
505
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 );
509 }
510 QgsDebugMsgLevel( u"Created [reply:%1]"_s.arg( reinterpret_cast< qint64 >( reply ), 0, 16 ), 3 );
511
512 return reply;
513}
514
515void QgsNetworkAccessManager::abortRequest()
516{
517 QTimer *timer = qobject_cast<QTimer *>( sender() );
518 Q_ASSERT( timer );
519
520 QNetworkReply *reply = qobject_cast<QNetworkReply *>( timer->parent() );
521 Q_ASSERT( reply );
522
523 reply->abort();
524 QgsDebugMsgLevel( u"Abort [reply:%1] %2"_s.arg( reinterpret_cast< qint64 >( reply ), 0, 16 ).arg( reply->url().toString() ), 3 );
525 QgsMessageLog::logMessage( tr( "Network request %1 timed out" ).arg( reply->url().toString() ), tr( "Network" ) );
526 // Notify the application
527 emit requestTimedOut( QgsNetworkRequestParameters( reply->operation(), reply->request(), getRequestId( reply ) ) );
528 emit requestTimedOut( reply );
529}
530
531void QgsNetworkAccessManager::onReplyFinished( QNetworkReply *reply )
532{
533 emit finished( QgsNetworkReplyContent( reply ) );
534}
535
536void QgsNetworkAccessManager::onReplyDownloadProgress( qint64 bytesReceived, qint64 bytesTotal )
537{
538 if ( QNetworkReply *reply = qobject_cast< QNetworkReply *>( sender() ) )
539 {
540 emit downloadProgress( getRequestId( reply ), bytesReceived, bytesTotal );
541 }
542}
543
544int QgsNetworkAccessManager::getRequestId( QNetworkReply *reply )
545{
546 return reply->property( "requestId" ).toInt();
547}
548
549void QgsNetworkAccessManager::pauseTimeout( QNetworkReply *reply )
550{
551 Q_ASSERT( reply->manager() == this );
552
553 QTimer *timer = reply->findChild<QTimer *>( u"timeoutTimer"_s );
554 if ( timer && timer->isActive() )
555 {
556 timer->stop();
557 }
558}
559
560void QgsNetworkAccessManager::restartTimeout( QNetworkReply *reply )
561{
562 Q_ASSERT( reply->manager() == this );
563 // restart reply timeout
564 QTimer *timer = reply->findChild<QTimer *>( u"timeoutTimer"_s );
565 if ( timer )
566 {
567 Q_ASSERT( !timer->isActive() );
568 QgsDebugMsgLevel( u"Restarting network reply timeout"_s, 2 );
569 timer->setSingleShot( true );
570 timer->start( timeout() );
571 }
572}
573
574void QgsNetworkAccessManager::afterAuthRequestHandled( QNetworkReply *reply )
575{
576 if ( reply->manager() == this )
577 {
578 restartTimeout( reply );
579 emit authRequestHandled( reply );
580 }
581}
582
583#ifndef QT_NO_SSL
584void QgsNetworkAccessManager::onReplySslErrors( const QList<QSslError> &errors )
585{
586 QNetworkReply *reply = qobject_cast< QNetworkReply *>( sender() );
587 Q_ASSERT( reply );
588 Q_ASSERT( reply->manager() == this );
589
590 QgsDebugMsgLevel( u"Stopping network reply timeout whilst SSL error is handled"_s, 2 );
591 pauseTimeout( reply );
592
593 emit requestEncounteredSslErrors( getRequestId( reply ), errors );
594
595 // acquire semaphore a first time, so we block next acquire until release is called
596 mSslErrorHandlerSemaphore.acquire();
597
598 // in main thread this will trigger SSL error handler immediately and return once the errors are handled,
599 // while in worker thread the signal will be queued (and return immediately) -- hence the need to lock the thread in the next block
600 emit sslErrorsOccurred( reply, errors );
601 if ( this != sMainNAM )
602 {
603 // lock thread and wait till error is handled. If we return from this slot now, then the reply will resume
604 // without actually giving the main thread the chance to act on the ssl error and possibly ignore it.
605 mSslErrorHandlerSemaphore.acquire();
606 mSslErrorHandlerSemaphore.release();
607 afterSslErrorHandled( reply );
608 }
609}
610
611void QgsNetworkAccessManager::afterSslErrorHandled( QNetworkReply *reply )
612{
613 if ( reply->manager() == this )
614 {
615 restartTimeout( reply );
616 emit sslErrorsHandled( reply );
617 }
618}
619
620void QgsNetworkAccessManager::handleSslErrors( QNetworkReply *reply, const QList<QSslError> &errors )
621{
622 mSslErrorHandler->handleSslErrors( reply, errors );
623 afterSslErrorHandled( reply );
624 qobject_cast<QgsNetworkAccessManager *>( reply->manager() )->mSslErrorHandlerSemaphore.release();
625}
626
627#endif
628
629void QgsNetworkAccessManager::onAuthRequired( QNetworkReply *reply, QAuthenticator *auth )
630{
631 Q_ASSERT( reply );
632 Q_ASSERT( reply->manager() == this );
633
634 QgsDebugMsgLevel( u"Stopping network reply timeout whilst auth request is handled"_s, 2 );
635 pauseTimeout( reply );
636
637 emit requestRequiresAuth( getRequestId( reply ), auth->realm() );
638
639 // acquire semaphore a first time, so we block next acquire until release is called
640 mAuthRequestHandlerSemaphore.acquire();
641
642 // in main thread this will trigger auth handler immediately and return once the request is satisfied,
643 // while in worker thread the signal will be queued (and return immediately) -- hence the need to lock the thread in the next block
644 emit authRequestOccurred( reply, auth );
645
646 if ( this != sMainNAM )
647 {
648 // lock thread and wait till error is handled. If we return from this slot now, then the reply will resume
649 // without actually giving the main thread the chance to act on the ssl error and possibly ignore it.
650 mAuthRequestHandlerSemaphore.acquire();
651 mAuthRequestHandlerSemaphore.release();
652 afterAuthRequestHandled( reply );
653 }
654}
655
657{
658 if ( this != sMainNAM )
659 {
660 sMainNAM->requestAuthOpenBrowser( url );
662 return;
663 }
664 mAuthHandler->handleAuthRequestOpenBrowser( url );
665}
666
668{
669 if ( this != sMainNAM )
670 {
671 sMainNAM->requestAuthCloseBrowser();
673 return;
674 }
675 mAuthHandler->handleAuthRequestCloseBrowser();
676}
677
679{
680 if ( this != sMainNAM )
681 {
683 }
684 emit authBrowserAborted();
685}
686
687void QgsNetworkAccessManager::handleAuthRequest( QNetworkReply *reply, QAuthenticator *auth )
688{
689 mAuthHandler->handleAuthRequest( reply, auth );
690
691 emit requestAuthDetailsAdded( getRequestId( reply ), auth->realm(), auth->user(), auth->password() );
692
693 afterAuthRequestHandled( reply );
694 qobject_cast<QgsNetworkAccessManager *>( reply->manager() )->mAuthRequestHandlerSemaphore.release();
695}
696
697QString QgsNetworkAccessManager::cacheLoadControlName( QNetworkRequest::CacheLoadControl control )
698{
699 switch ( control )
700 {
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;
709 }
710 return u"PreferNetwork"_s;
711}
712
713QNetworkRequest::CacheLoadControl QgsNetworkAccessManager::cacheLoadControlFromName( const QString &name )
714{
715 if ( name == "AlwaysNetwork"_L1 )
716 {
717 return QNetworkRequest::AlwaysNetwork;
718 }
719 else if ( name == "PreferNetwork"_L1 )
720 {
721 return QNetworkRequest::PreferNetwork;
722 }
723 else if ( name == "PreferCache"_L1 )
724 {
725 return QNetworkRequest::PreferCache;
726 }
727 else if ( name == "AlwaysCache"_L1 )
728 {
729 return QNetworkRequest::AlwaysCache;
730 }
731 return QNetworkRequest::PreferNetwork;
732}
733
734void QgsNetworkAccessManager::setupDefaultProxyAndCache( Qt::ConnectionType connectionType )
735{
736 mInitialized = true;
737 mUseSystemProxy = false;
738
739 Q_ASSERT( sMainNAM );
740
741 if ( sMainNAM != this )
742 {
743 connect( this, &QNetworkAccessManager::proxyAuthenticationRequired, sMainNAM, &QNetworkAccessManager::proxyAuthenticationRequired, connectionType );
744
745 connect( this, qOverload< QNetworkReply *>( &QgsNetworkAccessManager::requestTimedOut ), sMainNAM, qOverload< QNetworkReply *>( &QgsNetworkAccessManager::requestTimedOut ) );
746
747 connect( this, qOverload< QgsNetworkRequestParameters >( &QgsNetworkAccessManager::requestTimedOut ), sMainNAM, qOverload< QgsNetworkRequestParameters >( &QgsNetworkAccessManager::requestTimedOut ) );
748
749 connect( this, qOverload< QgsNetworkRequestParameters >( &QgsNetworkAccessManager::requestAboutToBeCreated ), sMainNAM, qOverload< QgsNetworkRequestParameters >( &QgsNetworkAccessManager::requestAboutToBeCreated ) );
750
751 connect( this, qOverload< const QgsNetworkRequestParameters & >( &QgsNetworkAccessManager::requestCreated ), sMainNAM, qOverload< const QgsNetworkRequestParameters & >( &QgsNetworkAccessManager::requestCreated ) );
752
753 connect( this, qOverload< QgsNetworkReplyContent >( &QgsNetworkAccessManager::finished ), sMainNAM, qOverload< QgsNetworkReplyContent >( &QgsNetworkAccessManager::finished ) );
754
756
757#ifndef QT_NO_SSL
758 connect( this, &QNetworkAccessManager::sslErrors, sMainNAM, &QNetworkAccessManager::sslErrors, connectionType );
759
761#endif
762
764 connect( sMainNAM, &QgsNetworkAccessManager::cookiesChanged, this, &QgsNetworkAccessManager::syncCookies );
765 connect( this, &QgsNetworkAccessManager::cookiesChanged, sMainNAM, &QgsNetworkAccessManager::syncCookies );
766 }
767 else
768 {
769#ifndef QT_NO_SSL
770 if ( !mSslErrorHandler )
771 setSslErrorHandler( std::make_unique< QgsSslErrorHandler >() );
772#endif
773 if ( !mAuthHandler )
774 setAuthHandler( std::make_unique< QgsNetworkAuthenticationHandler>() );
775 }
776#ifndef QT_NO_SSL
777 connect( this, &QgsNetworkAccessManager::sslErrorsOccurred, sMainNAM, &QgsNetworkAccessManager::handleSslErrors );
778#endif
779 connect( this, &QNetworkAccessManager::authenticationRequired, this, &QgsNetworkAccessManager::onAuthRequired );
780 connect( this, &QgsNetworkAccessManager::authRequestOccurred, sMainNAM, &QgsNetworkAccessManager::handleAuthRequest );
781
782 connect( this, &QNetworkAccessManager::finished, this, &QgsNetworkAccessManager::onReplyFinished );
783
784 // check if proxy is enabled
785 QNetworkProxy proxy;
786 QStringList excludes;
787 QStringList noProxyURLs;
788
789 const bool proxyEnabled = settingsProxyEnabled->value();
790 if ( proxyEnabled )
791 {
792 // This settings is keep for retrocompatibility, the returned proxy for these URL is the default one,
793 // meaning the system one
794 excludes = settingsProxyExcludedUrls->value().split( '|', Qt::SkipEmptyParts );
795
796 noProxyURLs = settingsNoProxyUrls->value();
797
798 //read type, host, port, user, passw from settings
799 const QString proxyHost = settingsProxyHost->value();
800 const int proxyPort = settingsProxyPort->value().toInt();
801
802 const QString proxyUser = settingsProxyUser->value();
803 const QString proxyPassword = settingsProxyPassword->value();
804
805 const QString proxyTypeString = settingsProxyType->value();
806
807 if ( proxyTypeString == "DefaultProxy"_L1 )
808 {
809 mUseSystemProxy = true;
810 QNetworkProxyFactory::setUseSystemConfiguration( true );
811 QList<QNetworkProxy> proxies = QNetworkProxyFactory::systemProxyForQuery();
812 if ( !proxies.isEmpty() )
813 {
814 proxy = proxies.first();
815 }
816 QgsDebugMsgLevel( u"setting default proxy"_s, 4 );
817 }
818 else
819 {
820 QNetworkProxy::ProxyType proxyType = QNetworkProxy::DefaultProxy;
821 if ( proxyTypeString == "Socks5Proxy"_L1 )
822 {
823 proxyType = QNetworkProxy::Socks5Proxy;
824 }
825 else if ( proxyTypeString == "HttpProxy"_L1 )
826 {
827 proxyType = QNetworkProxy::HttpProxy;
828 }
829 else if ( proxyTypeString == "HttpCachingProxy"_L1 )
830 {
831 proxyType = QNetworkProxy::HttpCachingProxy;
832 }
833 else if ( proxyTypeString == "FtpCachingProxy"_L1 )
834 {
835 proxyType = QNetworkProxy::FtpCachingProxy;
836 }
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 );
839 }
840 // Setup network proxy authentication configuration
841 const QString authcfg = settingsProxyAuthCfg->value();
842 if ( !authcfg.isEmpty() )
843 {
844#ifdef HAVE_AUTH
845 QgsDebugMsgLevel( u"setting proxy from stored authentication configuration %1"_s.arg( authcfg ), 2 );
846 // Never crash! Never.
847 if ( QgsAuthManager *authManager = QgsApplication::authManager() )
848 authManager->updateNetworkProxy( proxy, authcfg );
849#else
850 QgsDebugError( u"Auth manager is not available - cannot update network proxy for authcfg: %1"_s.arg( authcfg ) );
851#endif
852 }
853 }
854
855 setFallbackProxyAndExcludes( proxy, excludes, noProxyURLs );
856
857 QgsNetworkDiskCache *newcache = qobject_cast<QgsNetworkDiskCache *>( cache() );
858 if ( !newcache )
859 newcache = new QgsNetworkDiskCache( this );
860
861 QString cacheDirectory = QgsSettingsRegistryCore::settingsNetworkCacheDirectory->value();
862 if ( cacheDirectory.isEmpty() )
863 cacheDirectory = QStandardPaths::writableLocation( QStandardPaths::CacheLocation );
864 newcache->setCacheDirectory( cacheDirectory );
865 qint64 cacheSize = QgsSettingsRegistryCore::settingsNetworkCacheSize->value();
866 newcache->setMaximumCacheSize( cacheSize );
867
868 QgsDebugMsgLevel( u"cacheDirectory: %1"_s.arg( newcache->cacheDirectory() ), 4 );
869 QgsDebugMsgLevel( u"maximumCacheSize: %1"_s.arg( newcache->maximumCacheSize() ), 4 );
870
871 if ( cache() != newcache )
872 setCache( newcache );
873
874 if ( this != sMainNAM )
875 {
876 static_cast<QgsNetworkCookieJar *>( cookieJar() )->setAllCookies( static_cast<QgsNetworkCookieJar *>( sMainNAM->cookieJar() )->allCookies() );
877 }
878}
879
880void QgsNetworkAccessManager::syncCookies( const QList<QNetworkCookie> &cookies )
881{
882 if ( sender() != this )
883 {
884 static_cast<QgsNetworkCookieJar *>( cookieJar() )->setAllCookies( cookies );
885 if ( this == sMainNAM )
886 {
887 emit cookiesChanged( cookies );
888 }
889 }
890}
891
893{
894 return settingsNetworkTimeout->value();
895}
896
898{
899 settingsNetworkTimeout->setValue( time );
900}
901
902QgsNetworkReplyContent QgsNetworkAccessManager::blockingGet( QNetworkRequest &request, const QString &authCfg, bool forceRefresh, QgsFeedback *feedback, Qgis::NetworkRequestFlags flags )
903{
904 QgsBlockingNetworkRequest br( flags );
905 br.setAuthCfg( authCfg );
906 br.get( request, forceRefresh, feedback );
907 return br.reply();
908}
909
911 QNetworkRequest &request, const QByteArray &data, const QString &authCfg, bool forceRefresh, QgsFeedback *feedback, Qgis::NetworkRequestFlags flags
912)
913{
914 QgsBlockingNetworkRequest br( flags );
915 br.setAuthCfg( authCfg );
916 ( void ) br.post( request, data, forceRefresh, feedback );
917 return br.reply();
918}
919
920QString QgsNetworkAccessManager::setRequestPreprocessor( const std::function<void( QNetworkRequest * )> &processor )
921{
922 QString id = QUuid::createUuid().toString();
923 sCustomPreprocessors.emplace_back( std::make_pair( id, processor ) );
924 return id;
925}
926
928{
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()
933 );
934 return prevCount != sCustomPreprocessors.size();
935}
936
938{
939 const size_t prevCount = sCustomAdvancedPreprocessors.size();
940 sCustomAdvancedPreprocessors.erase(
941 std::remove_if(
942 sCustomAdvancedPreprocessors.begin(),
943 sCustomAdvancedPreprocessors.end(),
944 [id]( std::pair< QString, std::function< void( QNetworkRequest *, int &, QByteArray * ) > > &a ) { return a.first == id; }
945 ),
946 sCustomAdvancedPreprocessors.end()
947 );
948 return prevCount != sCustomAdvancedPreprocessors.size();
949}
950
951QString QgsNetworkAccessManager::setAdvancedRequestPreprocessor( const std::function<void( QNetworkRequest *, int &, QByteArray * )> &processor )
952{
953 QString id = QUuid::createUuid().toString();
954 sCustomAdvancedPreprocessors.emplace_back( std::make_pair( id, processor ) );
955 return id;
956}
957
958QString QgsNetworkAccessManager::setReplyPreprocessor( const std::function<void( const QNetworkRequest &, QNetworkReply * )> &processor )
959{
960 QString id = QUuid::createUuid().toString();
961 sCustomReplyPreprocessors.emplace_back( std::make_pair( id, processor ) );
962 return id;
963}
964
966{
967 const size_t prevCount = sCustomReplyPreprocessors.size();
968 sCustomReplyPreprocessors.erase(
969 std::remove_if(
970 sCustomReplyPreprocessors.begin(), sCustomReplyPreprocessors.end(), [id]( std::pair< QString, std::function< void( const QNetworkRequest &, QNetworkReply * ) > > &a ) { return a.first == id; }
971 ),
972 sCustomReplyPreprocessors.end()
973 );
974 return prevCount != sCustomReplyPreprocessors.size();
975}
976
977void QgsNetworkAccessManager::preprocessRequest( QNetworkRequest *req ) const
978{
979 for ( const auto &preprocessor : sCustomPreprocessors )
980 {
981 preprocessor.second( req );
982 }
983}
984
985
986//
987// QgsNetworkRequestParameters
988//
989
990QgsNetworkRequestParameters::QgsNetworkRequestParameters( QNetworkAccessManager::Operation operation, const QNetworkRequest &request, int requestId, const QByteArray &content )
991 : mOperation( operation )
992 , mRequest( request )
993 , mOriginatingThreadId( u"0x%2"_s.arg( reinterpret_cast<quintptr>( QThread::currentThread() ), 2 * QT_POINTER_SIZE, 16, '0'_L1 ) )
994 , mRequestId( requestId )
995 , mContent( content )
996 , mInitiatorClass( request.attribute( static_cast< QNetworkRequest::Attribute >( QgsNetworkRequestParameters::AttributeInitiatorClass ) ).toString() )
997 , mInitiatorRequestId( request.attribute( static_cast< QNetworkRequest::Attribute >( QgsNetworkRequestParameters::AttributeInitiatorRequestId ) ) )
998{}
999
1000
1001//
1002// QgsSslErrorHandler
1003//
1004
1005void QgsSslErrorHandler::handleSslErrors( QNetworkReply *reply, const QList<QSslError> & )
1006{
1007 Q_UNUSED( reply )
1008 QgsDebugError( u"SSL errors occurred accessing URL:\n%1"_s.arg( reply->request().url().toString() ) );
1009}
1010
1011//
1012// QgsNetworkAuthenticationHandler
1013//
1014
1015void QgsNetworkAuthenticationHandler::handleAuthRequest( QNetworkReply *reply, QAuthenticator * )
1016{
1017 Q_UNUSED( reply )
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() ) );
1019}
1020
1022{
1023 Q_UNUSED( url )
1024 QgsDebugError( u"Network authentication required external browser to open URL %1, but no handler was in place"_s.arg( url.toString() ) );
1025}
1026
1028{
1029 QgsDebugError( u"Network authentication required external browser closed, but no handler was in place"_s );
1030}
1031
1032// For QgsNetworkCookieJar
1033#include "qgsnetworkaccessmanager.moc"
QFlags< NetworkRequestFlag > NetworkRequestFlags
Flags controlling behavior of network requests.
Definition qgis.h:197
static int versionInt()
Version number used for comparing versions using the "Check QGIS Version" function.
Definition qgis.cpp:687
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.
Definition qgsfeedback.h:44
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)
void setMaximumCacheSize(qint64 size)
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.
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.
A string 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
Definition qgis.h:8462
#define Q_NOWARN_DEPRECATED_PUSH
Definition qgis.h:8461
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:80
#define QgsDebugError(str)
Definition qgslogger.h:71