1 /****************************************************************************
3 ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
6 ** This file is part of the QtNetwork module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and Digia. For licensing terms and
14 ** conditions see http://qt.digia.com/licensing. For further information
15 ** use the contact form at http://qt.digia.com/contact-us.
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL included in the
21 ** packaging of this file. Please review the following information to
22 ** ensure the GNU Lesser General Public License version 2.1 requirements
23 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
25 ** In addition, as a special exception, Digia gives you certain additional
26 ** rights. These rights are described in the Digia Qt LGPL Exception
27 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
29 ** GNU General Public License Usage
30 ** Alternatively, this file may be used under the terms of the GNU
31 ** General Public License version 3.0 as published by the Free Software
32 ** Foundation and appearing in the file LICENSE.GPL included in the
33 ** packaging of this file. Please review the following information to
34 ** ensure the GNU General Public License version 3.0 requirements will be
35 ** met: http://www.gnu.org/copyleft/gpl.html.
40 ****************************************************************************/
48 \brief The QNetworkProxy class provides a network layer proxy.
55 QNetworkProxy provides the method for configuring network layer
56 proxy support to the Qt network classes. The currently supported
57 classes are QAbstractSocket, QTcpSocket, QUdpSocket, QTcpServer
58 and QNetworkAccessManager. The proxy support is designed to
59 be as transparent as possible. This means that existing
60 network-enabled applications that you have written should
61 automatically support network proxy using the following code.
63 \snippet code/src_network_kernel_qnetworkproxy.cpp 0
65 An alternative to setting an application wide proxy is to specify
66 the proxy for individual sockets using QAbstractSocket::setProxy()
67 and QTcpServer::setProxy(). In this way, it is possible to disable
68 the use of a proxy for specific sockets using the following code:
70 \snippet code/src_network_kernel_qnetworkproxy.cpp 1
72 Network proxy is not used if the address used in \l
73 {QAbstractSocket::connectToHost()}{connectToHost()}, \l
74 {QUdpSocket::bind()}{bind()} or \l
75 {QTcpServer::listen()}{listen()} is equivalent to
76 QHostAddress::LocalHost or QHostAddress::LocalHostIPv6.
78 Each type of proxy support has certain restrictions associated with it.
79 You should read the \l{ProxyType} documentation carefully before
80 selecting a proxy type to use.
82 \note Changes made to currently connected sockets do not take effect.
83 If you need to change a connected socket, you should reconnect it.
87 The SOCKS5 support in Qt 4 is based on \l{RFC 1928} and \l{RFC 1929}.
88 The supported authentication methods are no authentication and
89 username/password authentication. Both IPv4 and IPv6 are
90 supported. Domain names are resolved through the SOCKS5 server if
91 the QNetworkProxy::HostNameLookupCapability is enabled, otherwise
92 they are resolved locally and the IP address is sent to the
93 server. There are several things to remember when using SOCKS5
94 with QUdpSocket and QTcpServer:
96 With QUdpSocket, a call to \l {QUdpSocket::bind()}{bind()} may fail
97 with a timeout error. If a port number other than 0 is passed to
98 \l {QUdpSocket::bind()}{bind()}, it is not guaranteed that it is the
99 specified port that will be used.
100 Use \l{QUdpSocket::localPort()}{localPort()} and
101 \l{QUdpSocket::localAddress()}{localAddress()} to get the actual
102 address and port number in use. Because proxied UDP goes through
103 two UDP connections, it is more likely that packets will be dropped.
105 With QTcpServer a call to \l{QTcpServer::listen()}{listen()} may
106 fail with a timeout error. If a port number other than 0 is passed
107 to \l{QTcpServer::listen()}{listen()}, then it is not guaranteed
108 that it is the specified port that will be used.
109 Use \l{QTcpServer::serverPort()}{serverPort()} and
110 \l{QTcpServer::serverAddress()}{serverAddress()} to get the actual
111 address and port used to listen for connections. SOCKS5 only supports
112 one accepted connection per call to \l{QTcpServer::listen()}{listen()},
113 and each call is likely to result in a different
114 \l{QTcpServer::serverPort()}{serverPort()} being used.
116 \sa QAbstractSocket, QTcpServer
120 \enum QNetworkProxy::ProxyType
122 This enum describes the types of network proxying provided in Qt.
124 There are two types of proxies that Qt understands:
125 transparent proxies and caching proxies. The first group consists
126 of proxies that can handle any arbitrary data transfer, while the
127 second can only handle specific requests. The caching proxies only
128 make sense for the specific classes where they can be used.
130 \value NoProxy No proxying is used
131 \value DefaultProxy Proxy is determined based on the application proxy set using setApplicationProxy()
132 \value Socks5Proxy \l Socks5 proxying is used
133 \value HttpProxy HTTP transparent proxying is used
134 \value HttpCachingProxy Proxying for HTTP requests only
135 \value FtpCachingProxy Proxying for FTP requests only
137 The table below lists different proxy types and their
138 capabilities. Since each proxy type has different capabilities, it
139 is important to understand them before choosing a proxy type.
145 \li Default capabilities
149 \li Generic proxy for any kind of connection. Supports TCP,
150 UDP, binding to a port (incoming connections) and
152 \li TunnelingCapability, ListeningCapability,
153 UdpTunnelingCapability, HostNameLookupCapability
157 \li Implemented using the "CONNECT" command, supports only
158 outgoing TCP connections; supports authentication.
159 \li TunnelingCapability, CachingCapability, HostNameLookupCapability
162 \li Caching-only HTTP
163 \li Implemented using normal HTTP commands, it is useful only
164 in the context of HTTP requests (see QNetworkAccessManager)
165 \li CachingCapability, HostNameLookupCapability
169 \li Implemented using an FTP proxy, it is useful only in the
170 context of FTP requests (see QNetworkAccessManager)
171 \li CachingCapability, HostNameLookupCapability
175 Also note that you shouldn't set the application default proxy
176 (setApplicationProxy()) to a proxy that doesn't have the
177 TunnelingCapability capability. If you do, QTcpSocket will not
178 know how to open connections.
180 \sa setType(), type(), capabilities(), setCapabilities()
184 \enum QNetworkProxy::Capability
187 These flags indicate the capabilities that a given proxy server
190 QNetworkProxy sets different capabilities by default when the
191 object is created (see QNetworkProxy::ProxyType for a list of the
192 defaults). However, it is possible to change the capabitilies
193 after the object has been created with setCapabilities().
195 The capabilities that QNetworkProxy supports are:
197 \value TunnelingCapability Ability to open transparent, tunneled
198 TCP connections to a remote host. The proxy server relays the
199 transmission verbatim from one side to the other and does no
202 \value ListeningCapability Ability to create a listening socket
203 and wait for an incoming TCP connection from a remote host.
205 \value UdpTunnelingCapability Ability to relay UDP datagrams via
206 the proxy server to and from a remote host.
208 \value CachingCapability Ability to cache the contents of the
209 transfer. This capability is specific to each protocol and proxy
210 type. For example, HTTP proxies can cache the contents of web data
211 transferred with "GET" commands.
213 \value HostNameLookupCapability Ability to connect to perform the
214 lookup on a remote host name and connect to it, as opposed to
215 requiring the application to perform the name lookup and request
216 connection to IP addresses only.
219 #include "qnetworkproxy.h"
221 #ifndef QT_NO_NETWORKPROXY
223 #include "private/qnetworkproxy_p.h"
224 #include "private/qnetworkrequest_p.h"
225 #include "private/qsocks5socketengine_p.h"
226 #include "private/qhttpsocketengine_p.h"
227 #include "qauthenticator.h"
231 #include "qstringlist.h"
234 #ifndef QT_NO_BEARERMANAGEMENT
235 #include <QtNetwork/QNetworkConfiguration>
240 class QSocks5SocketEngineHandler;
241 class QHttpSocketEngineHandler;
243 class QGlobalNetworkProxy
246 QGlobalNetworkProxy()
247 : mutex(QMutex::Recursive)
248 , applicationLevelProxy(0)
249 , applicationLevelProxyFactory(0)
251 , socks5SocketEngineHandler(0)
254 , httpSocketEngineHandler(0)
257 #ifdef QT_USE_SYSTEM_PROXIES
258 setApplicationProxyFactory(new QSystemConfigurationProxyFactory);
261 socks5SocketEngineHandler = new QSocks5SocketEngineHandler();
264 httpSocketEngineHandler = new QHttpSocketEngineHandler();
268 ~QGlobalNetworkProxy()
270 delete applicationLevelProxy;
271 delete applicationLevelProxyFactory;
273 delete socks5SocketEngineHandler;
276 delete httpSocketEngineHandler;
280 void setApplicationProxy(const QNetworkProxy &proxy)
282 QMutexLocker lock(&mutex);
283 if (!applicationLevelProxy)
284 applicationLevelProxy = new QNetworkProxy;
285 *applicationLevelProxy = proxy;
286 delete applicationLevelProxyFactory;
287 applicationLevelProxyFactory = 0;
290 void setApplicationProxyFactory(QNetworkProxyFactory *factory)
292 QMutexLocker lock(&mutex);
293 if (factory == applicationLevelProxyFactory)
295 if (applicationLevelProxy)
296 *applicationLevelProxy = QNetworkProxy();
297 delete applicationLevelProxyFactory;
298 applicationLevelProxyFactory = factory;
301 QNetworkProxy applicationProxy()
303 return proxyForQuery(QNetworkProxyQuery()).first();
306 QList<QNetworkProxy> proxyForQuery(const QNetworkProxyQuery &query);
310 QNetworkProxy *applicationLevelProxy;
311 QNetworkProxyFactory *applicationLevelProxyFactory;
313 QSocks5SocketEngineHandler *socks5SocketEngineHandler;
316 QHttpSocketEngineHandler *httpSocketEngineHandler;
320 QList<QNetworkProxy> QGlobalNetworkProxy::proxyForQuery(const QNetworkProxyQuery &query)
322 QMutexLocker locker(&mutex);
324 QList<QNetworkProxy> result;
326 // don't look for proxies for a local connection
328 QString hostname = query.url().host();
329 if (hostname == QLatin1String("localhost")
330 || hostname.startsWith(QLatin1String("localhost."))
331 || (parsed.setAddress(hostname)
332 && (parsed.isLoopback()))) {
333 result << QNetworkProxy(QNetworkProxy::NoProxy);
337 if (!applicationLevelProxyFactory) {
338 if (applicationLevelProxy
339 && applicationLevelProxy->type() != QNetworkProxy::DefaultProxy)
340 result << *applicationLevelProxy;
342 result << QNetworkProxy(QNetworkProxy::NoProxy);
347 result = applicationLevelProxyFactory->queryProxy(query);
348 if (result.isEmpty()) {
349 qWarning("QNetworkProxyFactory: factory %p has returned an empty result set",
350 applicationLevelProxyFactory);
351 result << QNetworkProxy(QNetworkProxy::NoProxy);
356 Q_GLOBAL_STATIC(QGlobalNetworkProxy, globalNetworkProxy)
359 template<bool> struct StaticAssertTest;
360 template<> struct StaticAssertTest<true> { enum { Value = 1 }; };
363 static inline void qt_noop_with_arg(int) {}
364 #define q_static_assert(expr) qt_noop_with_arg(sizeof(StaticAssertTest< expr >::Value))
366 static QNetworkProxy::Capabilities defaultCapabilitiesForType(QNetworkProxy::ProxyType type)
368 q_static_assert(int(QNetworkProxy::DefaultProxy) == 0);
369 q_static_assert(int(QNetworkProxy::FtpCachingProxy) == 5);
370 static const int defaults[] =
372 /* [QNetworkProxy::DefaultProxy] = */
373 (int(QNetworkProxy::ListeningCapability) |
374 int(QNetworkProxy::TunnelingCapability) |
375 int(QNetworkProxy::UdpTunnelingCapability)),
376 /* [QNetworkProxy::Socks5Proxy] = */
377 (int(QNetworkProxy::TunnelingCapability) |
378 int(QNetworkProxy::ListeningCapability) |
379 int(QNetworkProxy::UdpTunnelingCapability) |
380 int(QNetworkProxy::HostNameLookupCapability)),
381 // it's weird to talk about the proxy capabilities of a "not proxy"...
382 /* [QNetworkProxy::NoProxy] = */
383 (int(QNetworkProxy::ListeningCapability) |
384 int(QNetworkProxy::TunnelingCapability) |
385 int(QNetworkProxy::UdpTunnelingCapability)),
386 /* [QNetworkProxy::HttpProxy] = */
387 (int(QNetworkProxy::TunnelingCapability) |
388 int(QNetworkProxy::CachingCapability) |
389 int(QNetworkProxy::HostNameLookupCapability)),
390 /* [QNetworkProxy::HttpCachingProxy] = */
391 (int(QNetworkProxy::CachingCapability) |
392 int(QNetworkProxy::HostNameLookupCapability)),
393 /* [QNetworkProxy::FtpCachingProxy] = */
394 (int(QNetworkProxy::CachingCapability) |
395 int(QNetworkProxy::HostNameLookupCapability)),
398 if (int(type) < 0 || int(type) > int(QNetworkProxy::FtpCachingProxy))
399 type = QNetworkProxy::DefaultProxy;
400 return QNetworkProxy::Capabilities(defaults[int(type)]);
403 class QNetworkProxyPrivate: public QSharedData
409 QNetworkProxy::Capabilities capabilities;
411 QNetworkProxy::ProxyType type;
412 bool capabilitiesSet;
413 QNetworkHeadersPrivate headers;
415 inline QNetworkProxyPrivate(QNetworkProxy::ProxyType t = QNetworkProxy::DefaultProxy,
416 const QString &h = QString(), quint16 p = 0,
417 const QString &u = QString(), const QString &pw = QString())
421 capabilities(defaultCapabilitiesForType(t)),
424 capabilitiesSet(false)
427 inline bool operator==(const QNetworkProxyPrivate &other) const
429 return type == other.type &&
430 port == other.port &&
431 hostName == other.hostName &&
432 user == other.user &&
433 password == other.password &&
434 capabilities == other.capabilities;
438 template<> void QSharedDataPointer<QNetworkProxyPrivate>::detach()
440 if (d && d->ref.load() == 1)
442 QNetworkProxyPrivate *x = (d ? new QNetworkProxyPrivate(*d)
443 : new QNetworkProxyPrivate);
445 if (d && !d->ref.deref())
451 Constructs a QNetworkProxy with DefaultProxy type; the proxy type is
452 determined by applicationProxy(), which defaults to NoProxy.
454 \sa setType(), setApplicationProxy()
456 QNetworkProxy::QNetworkProxy()
459 // make sure we have QGlobalNetworkProxy singleton created, otherwise
460 // you don't have any socket engine handler created when directly setting
461 // a proxy to a socket
462 globalNetworkProxy();
466 Constructs a QNetworkProxy with \a type, \a hostName, \a port,
467 \a user and \a password.
469 The default capabilities for proxy type \a type are set automatically.
473 QNetworkProxy::QNetworkProxy(ProxyType type, const QString &hostName, quint16 port,
474 const QString &user, const QString &password)
475 : d(new QNetworkProxyPrivate(type, hostName, port, user, password))
477 // make sure we have QGlobalNetworkProxy singleton created, otherwise
478 // you don't have any socket engine handler created when directly setting
479 // a proxy to a socket
480 globalNetworkProxy();
484 Constructs a copy of \a other.
486 QNetworkProxy::QNetworkProxy(const QNetworkProxy &other)
492 Destroys the QNetworkProxy object.
494 QNetworkProxy::~QNetworkProxy()
496 // QSharedDataPointer takes care of deleting for us
502 Compares the value of this network proxy to \a other and returns true
503 if they are equal (same proxy type, server as well as username and password)
505 bool QNetworkProxy::operator==(const QNetworkProxy &other) const
507 return d == other.d || (d && other.d && *d == *other.d);
511 \fn bool QNetworkProxy::operator!=(const QNetworkProxy &other) const
514 Compares the value of this network proxy to \a other and returns true
521 Assigns the value of the network proxy \a other to this network proxy.
523 QNetworkProxy &QNetworkProxy::operator=(const QNetworkProxy &other)
530 \fn void QNetworkProxy::swap(QNetworkProxy &other)
533 Swaps this network proxy instance with \a other. This function is
534 very fast and never fails.
538 Sets the proxy type for this instance to be \a type.
540 Note that changing the type of a proxy does not change
541 the set of capabilities this QNetworkProxy object holds if any
542 capabilities have been set with setCapabilities().
544 \sa type(), setCapabilities()
546 void QNetworkProxy::setType(QNetworkProxy::ProxyType type)
549 if (!d->capabilitiesSet)
550 d->capabilities = defaultCapabilitiesForType(type);
554 Returns the proxy type for this instance.
558 QNetworkProxy::ProxyType QNetworkProxy::type() const
560 return d ? d->type : DefaultProxy;
566 Sets the capabilities of this proxy to \a capabilities.
568 \sa setType(), capabilities()
570 void QNetworkProxy::setCapabilities(Capabilities capabilities)
572 d->capabilities = capabilities;
573 d->capabilitiesSet = true;
579 Returns the capabilities of this proxy server.
581 \sa setCapabilities(), type()
583 QNetworkProxy::Capabilities QNetworkProxy::capabilities() const
585 return d ? d->capabilities : defaultCapabilitiesForType(DefaultProxy);
591 Returns true if this proxy supports the
592 QNetworkProxy::CachingCapability capability.
594 In Qt 4.4, the capability was tied to the proxy type, but since Qt
595 4.5 it is possible to remove the capability of caching from a
596 proxy by calling setCapabilities().
598 \sa capabilities(), type(), isTransparentProxy()
600 bool QNetworkProxy::isCachingProxy() const
602 return capabilities() & CachingCapability;
608 Returns true if this proxy supports transparent tunneling of TCP
609 connections. This matches the QNetworkProxy::TunnelingCapability
612 In Qt 4.4, the capability was tied to the proxy type, but since Qt
613 4.5 it is possible to remove the capability of caching from a
614 proxy by calling setCapabilities().
616 \sa capabilities(), type(), isCachingProxy()
618 bool QNetworkProxy::isTransparentProxy() const
620 return capabilities() & TunnelingCapability;
624 Sets the user name for proxy authentication to be \a user.
626 \sa user(), setPassword(), password()
628 void QNetworkProxy::setUser(const QString &user)
634 Returns the user name used for authentication.
636 \sa setUser(), setPassword(), password()
638 QString QNetworkProxy::user() const
640 return d ? d->user : QString();
644 Sets the password for proxy authentication to be \a password.
646 \sa user(), setUser(), password()
648 void QNetworkProxy::setPassword(const QString &password)
650 d->password = password;
654 Returns the password used for authentication.
656 \sa user(), setPassword(), setUser()
658 QString QNetworkProxy::password() const
660 return d ? d->password : QString();
664 Sets the host name of the proxy host to be \a hostName.
666 \sa hostName(), setPort(), port()
668 void QNetworkProxy::setHostName(const QString &hostName)
670 d->hostName = hostName;
674 Returns the host name of the proxy host.
676 \sa setHostName(), setPort(), port()
678 QString QNetworkProxy::hostName() const
680 return d ? d->hostName : QString();
684 Sets the port of the proxy host to be \a port.
686 \sa hostName(), setHostName(), port()
688 void QNetworkProxy::setPort(quint16 port)
694 Returns the port of the proxy host.
696 \sa setHostName(), setPort(), hostName()
698 quint16 QNetworkProxy::port() const
700 return d ? d->port : 0;
704 Sets the application level network proxying to be \a networkProxy.
706 If a QAbstractSocket or QTcpSocket has the
707 QNetworkProxy::DefaultProxy type, then the QNetworkProxy set with
708 this function is used. If you want more flexibility in determining
709 which the proxy, use the QNetworkProxyFactory class.
711 Setting a default proxy value with this function will override the
712 application proxy factory set with
713 QNetworkProxyFactory::setApplicationProxyFactory.
715 \sa QNetworkProxyFactory, applicationProxy(), QAbstractSocket::setProxy(), QTcpServer::setProxy()
717 void QNetworkProxy::setApplicationProxy(const QNetworkProxy &networkProxy)
719 if (globalNetworkProxy()) {
720 // don't accept setting the proxy to DefaultProxy
721 if (networkProxy.type() == DefaultProxy)
722 globalNetworkProxy()->setApplicationProxy(QNetworkProxy::NoProxy);
724 globalNetworkProxy()->setApplicationProxy(networkProxy);
729 Returns the application level network proxying.
731 If a QAbstractSocket or QTcpSocket has the
732 QNetworkProxy::DefaultProxy type, then the QNetworkProxy returned
733 by this function is used.
735 \sa QNetworkProxyFactory, setApplicationProxy(), QAbstractSocket::proxy(), QTcpServer::proxy()
737 QNetworkProxy QNetworkProxy::applicationProxy()
739 if (globalNetworkProxy())
740 return globalNetworkProxy()->applicationProxy();
741 return QNetworkProxy();
746 Returns the value of the known network header \a header if it is
747 in use for this proxy. If it is not present, returns QVariant()
748 (i.e., an invalid variant).
750 \sa QNetworkRequest::KnownHeaders, rawHeader(), setHeader()
752 QVariant QNetworkProxy::header(QNetworkRequest::KnownHeaders header) const
754 if (d->type != HttpProxy && d->type != HttpCachingProxy)
756 return d->headers.cookedHeaders.value(header);
761 Sets the value of the known header \a header to be \a value,
762 overriding any previously set headers. This operation also sets
763 the equivalent raw HTTP header.
765 If the proxy is not of type HttpProxy or HttpCachingProxy this has no
768 \sa QNetworkRequest::KnownHeaders, setRawHeader(), header()
770 void QNetworkProxy::setHeader(QNetworkRequest::KnownHeaders header, const QVariant &value)
772 if (d->type == HttpProxy || d->type == HttpCachingProxy)
773 d->headers.setCookedHeader(header, value);
778 Returns true if the raw header \a headerName is in use for this
779 proxy. Returns false if the proxy is not of type HttpProxy or
782 \sa rawHeader(), setRawHeader()
784 bool QNetworkProxy::hasRawHeader(const QByteArray &headerName) const
786 if (d->type != HttpProxy && d->type != HttpCachingProxy)
788 return d->headers.findRawHeader(headerName) != d->headers.rawHeaders.constEnd();
793 Returns the raw form of header \a headerName. If no such header is
794 present or the proxy is not of type HttpProxy or HttpCachingProxy,
795 an empty QByteArray is returned, which may be indistinguishable
796 from a header that is present but has no content (use hasRawHeader()
797 to find out if the header exists or not).
799 Raw headers can be set with setRawHeader() or with setHeader().
801 \sa header(), setRawHeader()
803 QByteArray QNetworkProxy::rawHeader(const QByteArray &headerName) const
805 if (d->type != HttpProxy && d->type != HttpCachingProxy)
807 QNetworkHeadersPrivate::RawHeadersList::ConstIterator it =
808 d->headers.findRawHeader(headerName);
809 if (it != d->headers.rawHeaders.constEnd())
816 Returns a list of all raw headers that are set in this network
817 proxy. The list is in the order that the headers were set.
819 If the proxy is not of type HttpProxy or HttpCachingProxy an empty
822 \sa hasRawHeader(), rawHeader()
824 QList<QByteArray> QNetworkProxy::rawHeaderList() const
826 if (d->type != HttpProxy && d->type != HttpCachingProxy)
827 return QList<QByteArray>();
828 return d->headers.rawHeadersKeys();
833 Sets the header \a headerName to be of value \a headerValue. If \a
834 headerName corresponds to a known header (see
835 QNetworkRequest::KnownHeaders), the raw format will be parsed and
836 the corresponding "cooked" header will be set as well.
839 \snippet code/src_network_access_qnetworkrequest.cpp 0
841 will also set the known header LastModifiedHeader to be the
842 QDateTime object of the parsed date.
844 Note: setting the same header twice overrides the previous
845 setting. To accomplish the behaviour of multiple HTTP headers of
846 the same name, you should concatenate the two values, separating
847 them with a comma (",") and set one single raw header.
849 If the proxy is not of type HttpProxy or HttpCachingProxy this has no
852 \sa QNetworkRequest::KnownHeaders, setHeader(), hasRawHeader(), rawHeader()
854 void QNetworkProxy::setRawHeader(const QByteArray &headerName, const QByteArray &headerValue)
856 if (d->type == HttpProxy || d->type == HttpCachingProxy)
857 d->headers.setRawHeader(headerName, headerValue);
860 class QNetworkProxyQueryPrivate: public QSharedData
863 inline QNetworkProxyQueryPrivate()
864 : localPort(-1), type(QNetworkProxyQuery::TcpSocket)
867 bool operator==(const QNetworkProxyQueryPrivate &other) const
869 return type == other.type &&
870 localPort == other.localPort &&
871 remote == other.remote;
876 QNetworkProxyQuery::QueryType type;
877 #ifndef QT_NO_BEARERMANAGEMENT
878 QNetworkConfiguration config;
882 template<> void QSharedDataPointer<QNetworkProxyQueryPrivate>::detach()
884 if (d && d->ref.load() == 1)
886 QNetworkProxyQueryPrivate *x = (d ? new QNetworkProxyQueryPrivate(*d)
887 : new QNetworkProxyQueryPrivate);
889 if (d && !d->ref.deref())
895 \class QNetworkProxyQuery
899 \brief The QNetworkProxyQuery class is used to query the proxy
900 settings for a socket.
902 QNetworkProxyQuery holds the details of a socket being created or
903 request being made. It is used by QNetworkProxy and
904 QNetworkProxyFactory to allow applications to have a more
905 fine-grained control over which proxy servers are used, depending
906 on the details of the query. This allows an application to apply
907 different settings, according to the protocol or destination
908 hostname, for instance.
910 QNetworkProxyQuery supports the following criteria for selecting
914 \li the type of query
915 \li the local port number to use
916 \li the destination host name
917 \li the destination port number
918 \li the protocol name, such as "http" or "ftp"
919 \li the URL being requested
922 The destination host name is the host in the connection in the
923 case of outgoing connection sockets. It is the \c hostName
924 parameter passed to QTcpSocket::connectToHost() or the host
925 component of a URL requested with QNetworkRequest.
927 The destination port number is the requested port to connect to in
928 the case of outgoing sockets, while the local port number is the
929 port the socket wishes to use locally before attempting the
930 external connection. In most cases, the local port number is used
931 by listening sockets only (QTcpSocket) or by datagram sockets
934 The protocol name is an arbitrary string that indicates the type
935 of connection being attempted. For example, it can match the
936 scheme of a URL, like "http", "https" and "ftp". In most cases,
937 the proxy selection will not change depending on the protocol, but
938 this information is provided in case a better choice can be made,
939 like choosing an caching HTTP proxy for HTTP-based connections,
940 but a more powerful SOCKSv5 proxy for all others.
942 The network configuration specifies which configuration to use,
943 when bearer management is used. For example on a mobile phone
944 the proxy settings are likely to be different for the cellular
947 Some of the criteria may not make sense in all of the types of
948 query. The following table lists the criteria that are most
949 commonly used, according to the type of query.
958 \li Normal sockets requesting a connection to a remote server,
959 like QTcpSocket. The peer hostname and peer port match the
960 values passed to QTcpSocket::connectToHost(). The local port
961 is usually -1, indicating the socket has no preference in
962 which port should be used. The URL component is not used.
966 \li Datagram-based sockets, which can both send and
967 receive. The local port, remote host or remote port fields
968 can all be used or be left unused, depending on the
969 characteristics of the socket. The URL component is not used.
973 \li Passive server sockets that listen on a port and await
974 incoming connections from the network. Normally, only the
975 local port is used, but the remote address could be used in
976 specific circumstances, for example to indicate which remote
977 host a connection is expected from. The URL component is not used.
981 \li A more high-level request, such as those coming from
982 QNetworkAccessManager. These requests will inevitably use an
983 outgoing TCP socket, but the this query type is provided to
984 indicate that more detailed information is present in the URL
985 component. For ease of implementation, the URL's host and
986 port are set as the destination address.
989 It should be noted that any of the criteria may be missing or
990 unknown (an empty QString for the hostname or protocol name, -1
991 for the port numbers). If that happens, the functions executing
992 the query should make their best guess or apply some
993 implementation-defined default values.
995 \sa QNetworkProxy, QNetworkProxyFactory, QNetworkAccessManager,
996 QAbstractSocket::setProxy()
1000 \enum QNetworkProxyQuery::QueryType
1002 Describes the type of one QNetworkProxyQuery query.
1004 \value TcpSocket a normal, outgoing TCP socket
1005 \value UdpSocket a datagram-based UDP socket, which could send
1006 to multiple destinations
1007 \value TcpServer a TCP server that listens for incoming
1008 connections from the network
1009 \value UrlRequest a more complex request which involves loading
1012 \sa queryType(), setQueryType()
1016 Constructs a default QNetworkProxyQuery object. By default, the
1017 query type will be QNetworkProxyQuery::TcpSocket.
1019 QNetworkProxyQuery::QNetworkProxyQuery()
1024 Constructs a QNetworkProxyQuery with the URL \a requestUrl and
1025 sets the query type to \a queryType.
1027 \sa protocolTag(), peerHostName(), peerPort()
1029 QNetworkProxyQuery::QNetworkProxyQuery(const QUrl &requestUrl, QueryType queryType)
1031 d->remote = requestUrl;
1032 d->type = queryType;
1036 Constructs a QNetworkProxyQuery of type \a queryType and sets the
1037 protocol tag to be \a protocolTag. This constructor is suitable
1038 for QNetworkProxyQuery::TcpSocket queries, because it sets the
1039 peer hostname to \a hostname and the peer's port number to \a
1042 QNetworkProxyQuery::QNetworkProxyQuery(const QString &hostname, int port,
1043 const QString &protocolTag,
1044 QueryType queryType)
1046 d->remote.setScheme(protocolTag);
1047 d->remote.setHost(hostname);
1048 d->remote.setPort(port);
1049 d->type = queryType;
1053 Constructs a QNetworkProxyQuery of type \a queryType and sets the
1054 protocol tag to be \a protocolTag. This constructor is suitable
1055 for QNetworkProxyQuery::TcpSocket queries because it sets the
1056 local port number to \a bindPort.
1058 Note that \a bindPort is of type quint16 to indicate the exact
1059 port number that is requested. The value of -1 (unknown) is not
1060 allowed in this context.
1064 QNetworkProxyQuery::QNetworkProxyQuery(quint16 bindPort, const QString &protocolTag,
1065 QueryType queryType)
1067 d->remote.setScheme(protocolTag);
1068 d->localPort = bindPort;
1069 d->type = queryType;
1072 #ifndef QT_NO_BEARERMANAGEMENT
1074 Constructs a QNetworkProxyQuery with the URL \a requestUrl and
1075 sets the query type to \a queryType. The specified \a networkConfiguration
1076 is used to resolve the proxy settings.
1078 \sa protocolTag(), peerHostName(), peerPort(), networkConfiguration()
1080 QNetworkProxyQuery::QNetworkProxyQuery(const QNetworkConfiguration &networkConfiguration,
1081 const QUrl &requestUrl, QueryType queryType)
1083 d->config = networkConfiguration;
1084 d->remote = requestUrl;
1085 d->type = queryType;
1089 Constructs a QNetworkProxyQuery of type \a queryType and sets the
1090 protocol tag to be \a protocolTag. This constructor is suitable
1091 for QNetworkProxyQuery::TcpSocket queries, because it sets the
1092 peer hostname to \a hostname and the peer's port number to \a
1093 port. The specified \a networkConfiguration
1094 is used to resolve the proxy settings.
1096 \sa networkConfiguration()
1098 QNetworkProxyQuery::QNetworkProxyQuery(const QNetworkConfiguration &networkConfiguration,
1099 const QString &hostname, int port,
1100 const QString &protocolTag,
1101 QueryType queryType)
1103 d->config = networkConfiguration;
1104 d->remote.setScheme(protocolTag);
1105 d->remote.setHost(hostname);
1106 d->remote.setPort(port);
1107 d->type = queryType;
1111 Constructs a QNetworkProxyQuery of type \a queryType and sets the
1112 protocol tag to be \a protocolTag. This constructor is suitable
1113 for QNetworkProxyQuery::TcpSocket queries because it sets the
1114 local port number to \a bindPort. The specified \a networkConfiguration
1115 is used to resolve the proxy settings.
1117 Note that \a bindPort is of type quint16 to indicate the exact
1118 port number that is requested. The value of -1 (unknown) is not
1119 allowed in this context.
1121 \sa localPort(), networkConfiguration()
1123 QNetworkProxyQuery::QNetworkProxyQuery(const QNetworkConfiguration &networkConfiguration,
1124 quint16 bindPort, const QString &protocolTag,
1125 QueryType queryType)
1127 d->config = networkConfiguration;
1128 d->remote.setScheme(protocolTag);
1129 d->localPort = bindPort;
1130 d->type = queryType;
1135 Constructs a QNetworkProxyQuery object that is a copy of \a other.
1137 QNetworkProxyQuery::QNetworkProxyQuery(const QNetworkProxyQuery &other)
1143 Destroys this QNetworkProxyQuery object.
1145 QNetworkProxyQuery::~QNetworkProxyQuery()
1147 // QSharedDataPointer automatically deletes
1151 Copies the contents of \a other.
1153 QNetworkProxyQuery &QNetworkProxyQuery::operator=(const QNetworkProxyQuery &other)
1160 \fn void QNetworkProxyQuery::swap(QNetworkProxyQuery &other)
1163 Swaps this network proxy query instance with \a other. This
1164 function is very fast and never fails.
1168 Returns true if this QNetworkProxyQuery object contains the same
1171 bool QNetworkProxyQuery::operator==(const QNetworkProxyQuery &other) const
1173 return d == other.d || (d && other.d && *d == *other.d);
1177 \fn bool QNetworkProxyQuery::operator!=(const QNetworkProxyQuery &other) const
1179 Returns true if this QNetworkProxyQuery object does not contain
1180 the same data as \a other.
1184 Returns the query type.
1186 QNetworkProxyQuery::QueryType QNetworkProxyQuery::queryType() const
1188 return d ? d->type : TcpSocket;
1192 Sets the query type of this object to be \a type.
1194 void QNetworkProxyQuery::setQueryType(QueryType type)
1200 Returns the port number for the outgoing request or -1 if the port
1201 number is not known.
1203 If the query type is QNetworkProxyQuery::UrlRequest, this function
1204 returns the port number of the URL being requested. In general,
1205 frameworks will fill in the port number from their default values.
1207 \sa peerHostName(), localPort(), setPeerPort()
1209 int QNetworkProxyQuery::peerPort() const
1211 return d ? d->remote.port() : -1;
1215 Sets the requested port number for the outgoing connection to be
1216 \a port. Valid values are 1 to 65535, or -1 to indicate that the
1217 remote port number is unknown.
1219 The peer port number can also be used to indicate the expected
1220 port number of an incoming connection in the case of
1221 QNetworkProxyQuery::UdpSocket or QNetworkProxyQuery::TcpServer
1224 \sa peerPort(), setPeerHostName(), setLocalPort()
1226 void QNetworkProxyQuery::setPeerPort(int port)
1228 d->remote.setPort(port);
1232 Returns the host name or IP address being of the outgoing
1233 connection being requested, or an empty string if the remote
1234 hostname is not known.
1236 If the query type is QNetworkProxyQuery::UrlRequest, this function
1237 returns the host component of the URL being requested.
1239 \sa peerPort(), localPort(), setPeerHostName()
1241 QString QNetworkProxyQuery::peerHostName() const
1243 return d ? d->remote.host() : QString();
1247 Sets the hostname of the outgoing connection being requested to \a
1248 hostname. An empty hostname can be used to indicate that the
1249 remote host is unknown.
1251 The peer host name can also be used to indicate the expected
1252 source address of an incoming connection in the case of
1253 QNetworkProxyQuery::UdpSocket or QNetworkProxyQuery::TcpServer
1256 \sa peerHostName(), setPeerPort(), setLocalPort()
1258 void QNetworkProxyQuery::setPeerHostName(const QString &hostname)
1260 d->remote.setHost(hostname);
1264 Returns the port number of the socket that will accept incoming
1265 packets from remote servers or -1 if the port is not known.
1267 \sa peerPort(), peerHostName(), setLocalPort()
1269 int QNetworkProxyQuery::localPort() const
1271 return d ? d->localPort : -1;
1275 Sets the port number that the socket wishes to use locally to
1276 accept incoming packets from remote servers to \a port. The local
1277 port is most often used with the QNetworkProxyQuery::TcpServer
1278 and QNetworkProxyQuery::UdpSocket query types.
1280 Valid values are 0 to 65535 (with 0 indicating that any port
1281 number will be acceptable) or -1, which means the local port
1282 number is unknown or not applicable.
1284 In some circumstances, for special protocols, it's the local port
1285 number can also be used with a query of type
1286 QNetworkProxyQuery::TcpSocket. When that happens, the socket is
1287 indicating it wishes to use the port number \a port when
1288 connecting to a remote host.
1290 \sa localPort(), setPeerPort(), setPeerHostName()
1292 void QNetworkProxyQuery::setLocalPort(int port)
1294 d->localPort = port;
1298 Returns the protocol tag for this QNetworkProxyQuery object, or an
1299 empty QString in case the protocol tag is unknown.
1301 In the case of queries of type QNetworkProxyQuery::UrlRequest,
1302 this function returns the value of the scheme component of the
1305 \sa setProtocolTag(), url()
1307 QString QNetworkProxyQuery::protocolTag() const
1309 return d ? d->remote.scheme() : QString();
1313 Sets the protocol tag for this QNetworkProxyQuery object to be \a
1316 The protocol tag is an arbitrary string that indicates which
1317 protocol is being talked over the socket, such as "http", "xmpp",
1318 "telnet", etc. The protocol tag is used by the backend to
1319 return a request that is more specific to the protocol in
1320 question: for example, a HTTP connection could be use a caching
1321 HTTP proxy server, while all other connections use a more powerful
1322 SOCKSv5 proxy server.
1326 void QNetworkProxyQuery::setProtocolTag(const QString &protocolTag)
1328 d->remote.setScheme(protocolTag);
1332 Returns the URL component of this QNetworkProxyQuery object in
1333 case of a query of type QNetworkProxyQuery::UrlRequest.
1337 QUrl QNetworkProxyQuery::url() const
1339 return d ? d->remote : QUrl();
1343 Sets the URL component of this QNetworkProxyQuery object to be \a
1344 url. Setting the URL will also set the protocol tag, the remote
1345 host name and port number. This is done so as to facilitate the
1346 implementation of the code that determines the proxy server to be
1349 \sa url(), peerHostName(), peerPort()
1351 void QNetworkProxyQuery::setUrl(const QUrl &url)
1356 #ifndef QT_NO_BEARERMANAGEMENT
1358 Returns the network configuration component of the query.
1360 \sa setNetworkConfiguration()
1362 QNetworkConfiguration QNetworkProxyQuery::networkConfiguration() const
1364 return d ? d->config : QNetworkConfiguration();
1368 Sets the network configuration component of this QNetworkProxyQuery
1369 object to be \a networkConfiguration. The network configuration can
1370 be used to return different proxy settings based on the network in
1371 use, for example WLAN vs cellular networks on a mobile phone.
1373 In the case of "user choice" or "service network" configurations,
1374 you should first start the QNetworkSession and obtain the active
1375 configuration from its properties.
1377 \sa networkConfiguration()
1379 void QNetworkProxyQuery::setNetworkConfiguration(const QNetworkConfiguration &networkConfiguration)
1381 d->config = networkConfiguration;
1386 \class QNetworkProxyFactory
1387 \brief The QNetworkProxyFactory class provides fine-grained proxy selection.
1393 QNetworkProxyFactory is an extension to QNetworkProxy, allowing
1394 applications to have a more fine-grained control over which proxy
1395 servers are used, depending on the socket requesting the
1396 proxy. This allows an application to apply different settings,
1397 according to the protocol or destination hostname, for instance.
1399 QNetworkProxyFactory can be set globally for an application, in
1400 which case it will override any global proxies set with
1401 QNetworkProxy::setApplicationProxy(). If set globally, any sockets
1402 created with Qt will query the factory to determine the proxy to
1405 A factory can also be set in certain frameworks that support
1406 multiple connections, such as QNetworkAccessManager. When set on
1407 such object, the factory will be queried for sockets created by
1408 that framework only.
1410 \section1 System Proxies
1412 You can configure a factory to use the system proxy's settings.
1413 Call the setUseSystemConfiguration() function with true to enable
1414 this behavior, or false to disable it.
1416 Similarly, you can use a factory to make queries directly to the
1417 system proxy by calling its systemProxyForQuery() function.
1419 \warning Depending on the configuration of the user's system, the
1420 use of system proxy features on certain platforms may be subject
1421 to limitations. The systemProxyForQuery() documentation contains a
1422 list of these limitations for those platforms that are affected.
1426 Creates a QNetworkProxyFactory object.
1428 Since QNetworkProxyFactory is an abstract class, you cannot create
1429 objects of type QNetworkProxyFactory directly.
1431 QNetworkProxyFactory::QNetworkProxyFactory()
1436 Destroys the QNetworkProxyFactory object.
1438 QNetworkProxyFactory::~QNetworkProxyFactory()
1446 Enables the use of the platform-specific proxy settings, and only those.
1447 See systemProxyForQuery() for more information.
1449 Internally, this method (when called with \a enable set to true)
1450 sets an application-wide proxy factory. For this reason, this method
1451 is mutually exclusive with setApplicationProxyFactory(): calling
1452 setApplicationProxyFactory() overrides the use of the system-wide proxy,
1453 and calling setUseSystemConfiguration() overrides any
1454 application proxy or proxy factory that was previously set.
1456 \note See the systemProxyForQuery() documentation for a list of
1457 limitations related to the use of system proxies.
1459 void QNetworkProxyFactory::setUseSystemConfiguration(bool enable)
1462 setApplicationProxyFactory(new QSystemConfigurationProxyFactory);
1464 setApplicationProxyFactory(0);
1469 Sets the application-wide proxy factory to be \a factory. This
1470 function will take ownership of that object and will delete it
1473 The application-wide proxy is used as a last-resort when all other
1474 proxy selection requests returned QNetworkProxy::DefaultProxy. For
1475 example, QTcpSocket objects can have a proxy set with
1476 QTcpSocket::setProxy, but if none is set, the proxy factory class
1477 set with this function will be queried.
1479 If you set a proxy factory with this function, any application
1480 level proxies set with QNetworkProxy::setApplicationProxy will be
1483 \sa QNetworkProxy::setApplicationProxy(),
1484 QAbstractSocket::proxy(), QAbstractSocket::setProxy()
1486 void QNetworkProxyFactory::setApplicationProxyFactory(QNetworkProxyFactory *factory)
1488 if (globalNetworkProxy())
1489 globalNetworkProxy()->setApplicationProxyFactory(factory);
1493 \fn QList<QNetworkProxy> QNetworkProxyFactory::queryProxy(const QNetworkProxyQuery &query)
1495 This function takes the query request, \a query,
1496 examines the details of the type of socket or request and returns
1497 a list of QNetworkProxy objects that indicate the proxy servers to
1498 be used, in order of preference.
1500 When reimplementing this class, take care to return at least one
1503 If you cannot determine a better proxy alternative, use
1504 QNetworkProxy::DefaultProxy, which tells the code querying for a
1505 proxy to use a higher alternative. For example, if this factory is
1506 set to a QNetworkAccessManager object, DefaultProxy will tell it
1507 to query the application-level proxy settings.
1509 If this factory is set as the application proxy factory,
1510 DefaultProxy and NoProxy will have the same meaning.
1514 \fn QList<QNetworkProxy> QNetworkProxyFactory::systemProxyForQuery(const QNetworkProxyQuery &query)
1516 This function takes the query request, \a query,
1517 examines the details of the type of socket or request and returns
1518 a list of QNetworkProxy objects that indicate the proxy servers to
1519 be used, in order of preference.
1521 This function can be used to determine the platform-specific proxy
1522 settings. This function will use the libraries provided by the
1523 operating system to determine the proxy for a given connection, if
1524 such libraries exist. If they don't, this function will just return a
1525 QNetworkProxy of type QNetworkProxy::NoProxy.
1527 On Windows, this function will use the WinHTTP DLL functions. Despite
1528 its name, Microsoft suggests using it for all applications that
1529 require network connections, not just HTTP. This will respect the
1530 proxy settings set on the registry with the proxycfg.exe tool. If
1531 those settings are not found, this function will attempt to obtain
1532 Internet Explorer's settings and use them.
1534 On MacOS X, this function will obtain the proxy settings using the
1535 SystemConfiguration framework from Apple. It will apply the FTP,
1536 HTTP and HTTPS proxy configurations for queries that contain the
1537 protocol tag "ftp", "http" and "https", respectively. If the SOCKS
1538 proxy is enabled in that configuration, this function will use the
1539 SOCKS server for all queries. If SOCKS isn't enabled, it will use
1540 the HTTPS proxy for all TcpSocket and UrlRequest queries.
1542 On BlackBerry, this function obtains proxy settings for the default
1543 configuration using system configuration. The type will be set based on
1544 protocol tag "http", "https", "ftp", respectively. By default, it
1545 assumes http type. Proxy username and password are also set during
1546 the query using system configuration.
1548 On other systems, this function will pick up proxy settings from
1549 the "http_proxy" environment variable. This variable must be a URL
1550 using one of the following schemes: "http", "socks5" or "socks5h".
1552 \section1 Limitations
1554 These are the limitations for the current version of this
1555 function. Future versions of Qt may lift some of the limitations
1559 \li On MacOS X, this function will ignore the Proxy Auto Configuration
1560 settings, since it cannot execute the associated ECMAScript code.
1562 \li On Windows platforms, this function may take several seconds to
1563 execute depending on the configuration of the user's system.
1565 \li On BlackBerry, only UrlRequest queries are supported. SOCKS is
1566 not supported. The proxy credentials are only retrieved for the
1567 default configuration.
1572 This function takes the query request, \a query,
1573 examines the details of the type of socket or request and returns
1574 a list of QNetworkProxy objects that indicate the proxy servers to
1575 be used, in order of preference.
1577 QList<QNetworkProxy> QNetworkProxyFactory::proxyForQuery(const QNetworkProxyQuery &query)
1579 if (!globalNetworkProxy())
1580 return QList<QNetworkProxy>() << QNetworkProxy(QNetworkProxy::NoProxy);
1581 return globalNetworkProxy()->proxyForQuery(query);
1584 #ifndef QT_NO_DEBUG_STREAM
1587 Outputs a QNetworkProxy details to a debug stream
1589 QDebug operator<<(QDebug debug, const QNetworkProxy &proxy)
1591 QNetworkProxy::ProxyType type = proxy.type();
1593 case QNetworkProxy::NoProxy:
1594 debug << "NoProxy ";
1596 case QNetworkProxy::DefaultProxy:
1597 debug << "DefaultProxy ";
1599 case QNetworkProxy::Socks5Proxy:
1600 debug << "Socks5Proxy ";
1602 case QNetworkProxy::HttpProxy:
1603 debug << "HttpProxy ";
1605 case QNetworkProxy::HttpCachingProxy:
1606 debug << "HttpCachingProxy ";
1608 case QNetworkProxy::FtpCachingProxy:
1609 debug << "FtpCachingProxy ";
1612 debug << "Unknown proxy " << int(type);
1615 debug << "\"" << proxy.hostName() << ":" << proxy.port() << "\" ";
1616 QNetworkProxy::Capabilities caps = proxy.capabilities();
1618 if (caps & QNetworkProxy::TunnelingCapability)
1619 scaps << QStringLiteral("Tunnel");
1620 if (caps & QNetworkProxy::ListeningCapability)
1621 scaps << QStringLiteral("Listen");
1622 if (caps & QNetworkProxy::UdpTunnelingCapability)
1623 scaps << QStringLiteral("UDP");
1624 if (caps & QNetworkProxy::CachingCapability)
1625 scaps << QStringLiteral("Caching");
1626 if (caps & QNetworkProxy::HostNameLookupCapability)
1627 scaps << QStringLiteral("NameLookup");
1628 debug << "[" << scaps.join(QLatin1Char(' ')) << "]";
1635 #endif // QT_NO_NETWORKPROXY