1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the QtNetwork module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
48 \brief The QNetworkProxy class provides a network layer proxy.
54 QNetworkProxy provides the method for configuring network layer
55 proxy support to the Qt network classes. The currently supported
56 classes are QAbstractSocket, QTcpSocket, QUdpSocket, QTcpServer
57 and QNetworkAccessManager. The proxy support is designed to
58 be as transparent as possible. This means that existing
59 network-enabled applications that you have written should
60 automatically support network proxy using the following code.
62 \snippet code/src_network_kernel_qnetworkproxy.cpp 0
64 An alternative to setting an application wide proxy is to specify
65 the proxy for individual sockets using QAbstractSocket::setProxy()
66 and QTcpServer::setProxy(). In this way, it is possible to disable
67 the use of a proxy for specific sockets using the following code:
69 \snippet code/src_network_kernel_qnetworkproxy.cpp 1
71 Network proxy is not used if the address used in \l
72 {QAbstractSocket::connectToHost()}{connectToHost()}, \l
73 {QUdpSocket::bind()}{bind()} or \l
74 {QTcpServer::listen()}{listen()} is equivalent to
75 QHostAddress::LocalHost or QHostAddress::LocalHostIPv6.
77 Each type of proxy support has certain restrictions associated with it.
78 You should read the \l{ProxyType} documentation carefully before
79 selecting a proxy type to use.
81 \note Changes made to currently connected sockets do not take effect.
82 If you need to change a connected socket, you should reconnect it.
86 The SOCKS5 support in Qt 4 is based on \l{RFC 1928} and \l{RFC 1929}.
87 The supported authentication methods are no authentication and
88 username/password authentication. Both IPv4 and IPv6 are
89 supported. Domain names are resolved through the SOCKS5 server if
90 the QNetworkProxy::HostNameLookupCapability is enabled, otherwise
91 they are resolved locally and the IP address is sent to the
92 server. There are several things to remember when using SOCKS5
93 with QUdpSocket and QTcpServer:
95 With QUdpSocket, a call to \l {QUdpSocket::bind()}{bind()} may fail
96 with a timeout error. If a port number other than 0 is passed to
97 \l {QUdpSocket::bind()}{bind()}, it is not guaranteed that it is the
98 specified port that will be used.
99 Use \l{QUdpSocket::localPort()}{localPort()} and
100 \l{QUdpSocket::localAddress()}{localAddress()} to get the actual
101 address and port number in use. Because proxied UDP goes through
102 two UDP connections, it is more likely that packets will be dropped.
104 With QTcpServer a call to \l{QTcpServer::listen()}{listen()} may
105 fail with a timeout error. If a port number other than 0 is passed
106 to \l{QTcpServer::listen()}{listen()}, then it is not guaranteed
107 that it is the specified port that will be used.
108 Use \l{QTcpServer::serverPort()}{serverPort()} and
109 \l{QTcpServer::serverAddress()}{serverAddress()} to get the actual
110 address and port used to listen for connections. SOCKS5 only supports
111 one accepted connection per call to \l{QTcpServer::listen()}{listen()},
112 and each call is likely to result in a different
113 \l{QTcpServer::serverPort()}{serverPort()} being used.
115 \sa QAbstractSocket, QTcpServer
119 \enum QNetworkProxy::ProxyType
121 This enum describes the types of network proxying provided in Qt.
123 There are two types of proxies that Qt understands:
124 transparent proxies and caching proxies. The first group consists
125 of proxies that can handle any arbitrary data transfer, while the
126 second can only handle specific requests. The caching proxies only
127 make sense for the specific classes where they can be used.
129 \value NoProxy No proxying is used
130 \value DefaultProxy Proxy is determined based on the application proxy set using setApplicationProxy()
131 \value Socks5Proxy \l Socks5 proxying is used
132 \value HttpProxy HTTP transparent proxying is used
133 \value HttpCachingProxy Proxying for HTTP requests only
134 \value FtpCachingProxy Proxying for FTP requests only
136 The table below lists different proxy types and their
137 capabilities. Since each proxy type has different capabilities, it
138 is important to understand them before choosing a proxy type.
144 \li Default capabilities
148 \li Generic proxy for any kind of connection. Supports TCP,
149 UDP, binding to a port (incoming connections) and
151 \li TunnelingCapability, ListeningCapability,
152 UdpTunnelingCapability, HostNameLookupCapability
156 \li Implemented using the "CONNECT" command, supports only
157 outgoing TCP connections; supports authentication.
158 \li TunnelingCapability, CachingCapability, HostNameLookupCapability
161 \li Caching-only HTTP
162 \li Implemented using normal HTTP commands, it is useful only
163 in the context of HTTP requests (see QNetworkAccessManager)
164 \li CachingCapability, HostNameLookupCapability
168 \li Implemented using an FTP proxy, it is useful only in the
169 context of FTP requests (see QNetworkAccessManager)
170 \li CachingCapability, HostNameLookupCapability
174 Also note that you shouldn't set the application default proxy
175 (setApplicationProxy()) to a proxy that doesn't have the
176 TunnelingCapability capability. If you do, QTcpSocket will not
177 know how to open connections.
179 \sa setType(), type(), capabilities(), setCapabilities()
183 \enum QNetworkProxy::Capability
186 These flags indicate the capabilities that a given proxy server
189 QNetworkProxy sets different capabilities by default when the
190 object is created (see QNetworkProxy::ProxyType for a list of the
191 defaults). However, it is possible to change the capabitilies
192 after the object has been created with setCapabilities().
194 The capabilities that QNetworkProxy supports are:
196 \value TunnelingCapability Ability to open transparent, tunneled
197 TCP connections to a remote host. The proxy server relays the
198 transmission verbatim from one side to the other and does no
201 \value ListeningCapability Ability to create a listening socket
202 and wait for an incoming TCP connection from a remote host.
204 \value UdpTunnelingCapability Ability to relay UDP datagrams via
205 the proxy server to and from a remote host.
207 \value CachingCapability Ability to cache the contents of the
208 transfer. This capability is specific to each protocol and proxy
209 type. For example, HTTP proxies can cache the contents of web data
210 transferred with "GET" commands.
212 \value HostNameLookupCapability Ability to connect to perform the
213 lookup on a remote host name and connect to it, as opposed to
214 requiring the application to perform the name lookup and request
215 connection to IP addresses only.
218 #include "qnetworkproxy.h"
220 #ifndef QT_NO_NETWORKPROXY
222 #include "private/qnetworkproxy_p.h"
223 #include "private/qnetworkrequest_p.h"
224 #include "private/qsocks5socketengine_p.h"
225 #include "private/qhttpsocketengine_p.h"
226 #include "qauthenticator.h"
230 #include "qstringlist.h"
233 #ifndef QT_NO_BEARERMANAGEMENT
234 #include <QtNetwork/QNetworkConfiguration>
239 class QSocks5SocketEngineHandler;
240 class QHttpSocketEngineHandler;
242 class QGlobalNetworkProxy
245 QGlobalNetworkProxy()
246 : mutex(QMutex::Recursive)
247 , applicationLevelProxy(0)
248 , applicationLevelProxyFactory(0)
249 , socks5SocketEngineHandler(0)
250 , httpSocketEngineHandler(0)
253 socks5SocketEngineHandler = new QSocks5SocketEngineHandler();
256 httpSocketEngineHandler = new QHttpSocketEngineHandler();
260 ~QGlobalNetworkProxy()
262 delete applicationLevelProxy;
263 delete applicationLevelProxyFactory;
264 delete socks5SocketEngineHandler;
265 delete httpSocketEngineHandler;
268 void setApplicationProxy(const QNetworkProxy &proxy)
270 QMutexLocker lock(&mutex);
271 if (!applicationLevelProxy)
272 applicationLevelProxy = new QNetworkProxy;
273 *applicationLevelProxy = proxy;
274 delete applicationLevelProxyFactory;
275 applicationLevelProxyFactory = 0;
278 void setApplicationProxyFactory(QNetworkProxyFactory *factory)
280 QMutexLocker lock(&mutex);
281 if (factory == applicationLevelProxyFactory)
283 if (applicationLevelProxy)
284 *applicationLevelProxy = QNetworkProxy();
285 delete applicationLevelProxyFactory;
286 applicationLevelProxyFactory = factory;
289 QNetworkProxy applicationProxy()
291 return proxyForQuery(QNetworkProxyQuery()).first();
294 QList<QNetworkProxy> proxyForQuery(const QNetworkProxyQuery &query);
298 QNetworkProxy *applicationLevelProxy;
299 QNetworkProxyFactory *applicationLevelProxyFactory;
300 QSocks5SocketEngineHandler *socks5SocketEngineHandler;
301 QHttpSocketEngineHandler *httpSocketEngineHandler;
304 QList<QNetworkProxy> QGlobalNetworkProxy::proxyForQuery(const QNetworkProxyQuery &query)
306 QMutexLocker locker(&mutex);
308 QList<QNetworkProxy> result;
309 if (!applicationLevelProxyFactory) {
310 if (applicationLevelProxy
311 && applicationLevelProxy->type() != QNetworkProxy::DefaultProxy)
312 result << *applicationLevelProxy;
314 result << QNetworkProxy(QNetworkProxy::NoProxy);
319 result = applicationLevelProxyFactory->queryProxy(query);
320 if (result.isEmpty()) {
321 qWarning("QNetworkProxyFactory: factory %p has returned an empty result set",
322 applicationLevelProxyFactory);
323 result << QNetworkProxy(QNetworkProxy::NoProxy);
328 Q_GLOBAL_STATIC(QGlobalNetworkProxy, globalNetworkProxy)
331 template<bool> struct StaticAssertTest;
332 template<> struct StaticAssertTest<true> { enum { Value = 1 }; };
335 static inline void qt_noop_with_arg(int) {}
336 #define q_static_assert(expr) qt_noop_with_arg(sizeof(StaticAssertTest< expr >::Value))
338 static QNetworkProxy::Capabilities defaultCapabilitiesForType(QNetworkProxy::ProxyType type)
340 q_static_assert(int(QNetworkProxy::DefaultProxy) == 0);
341 q_static_assert(int(QNetworkProxy::FtpCachingProxy) == 5);
342 static const int defaults[] =
344 /* [QNetworkProxy::DefaultProxy] = */
345 (int(QNetworkProxy::ListeningCapability) |
346 int(QNetworkProxy::TunnelingCapability) |
347 int(QNetworkProxy::UdpTunnelingCapability)),
348 /* [QNetworkProxy::Socks5Proxy] = */
349 (int(QNetworkProxy::TunnelingCapability) |
350 int(QNetworkProxy::ListeningCapability) |
351 int(QNetworkProxy::UdpTunnelingCapability) |
352 int(QNetworkProxy::HostNameLookupCapability)),
353 // it's weird to talk about the proxy capabilities of a "not proxy"...
354 /* [QNetworkProxy::NoProxy] = */
355 (int(QNetworkProxy::ListeningCapability) |
356 int(QNetworkProxy::TunnelingCapability) |
357 int(QNetworkProxy::UdpTunnelingCapability)),
358 /* [QNetworkProxy::HttpProxy] = */
359 (int(QNetworkProxy::TunnelingCapability) |
360 int(QNetworkProxy::CachingCapability) |
361 int(QNetworkProxy::HostNameLookupCapability)),
362 /* [QNetworkProxy::HttpCachingProxy] = */
363 (int(QNetworkProxy::CachingCapability) |
364 int(QNetworkProxy::HostNameLookupCapability)),
365 /* [QNetworkProxy::FtpCachingProxy] = */
366 (int(QNetworkProxy::CachingCapability) |
367 int(QNetworkProxy::HostNameLookupCapability)),
370 if (int(type) < 0 || int(type) > int(QNetworkProxy::FtpCachingProxy))
371 type = QNetworkProxy::DefaultProxy;
372 return QNetworkProxy::Capabilities(defaults[int(type)]);
375 class QNetworkProxyPrivate: public QSharedData
381 QNetworkProxy::Capabilities capabilities;
383 QNetworkProxy::ProxyType type;
384 bool capabilitiesSet;
385 QNetworkHeadersPrivate headers;
387 inline QNetworkProxyPrivate(QNetworkProxy::ProxyType t = QNetworkProxy::DefaultProxy,
388 const QString &h = QString(), quint16 p = 0,
389 const QString &u = QString(), const QString &pw = QString())
393 capabilities(defaultCapabilitiesForType(t)),
396 capabilitiesSet(false)
399 inline bool operator==(const QNetworkProxyPrivate &other) const
401 return type == other.type &&
402 port == other.port &&
403 hostName == other.hostName &&
404 user == other.user &&
405 password == other.password &&
406 capabilities == other.capabilities;
410 template<> void QSharedDataPointer<QNetworkProxyPrivate>::detach()
412 if (d && d->ref.load() == 1)
414 QNetworkProxyPrivate *x = (d ? new QNetworkProxyPrivate(*d)
415 : new QNetworkProxyPrivate);
417 if (d && !d->ref.deref())
423 Constructs a QNetworkProxy with DefaultProxy type; the proxy type is
424 determined by applicationProxy(), which defaults to NoProxy.
426 \sa setType(), setApplicationProxy()
428 QNetworkProxy::QNetworkProxy()
431 // make sure we have QGlobalNetworkProxy singleton created, otherwise
432 // you don't have any socket engine handler created when directly setting
433 // a proxy to a socket
434 globalNetworkProxy();
438 Constructs a QNetworkProxy with \a type, \a hostName, \a port,
439 \a user and \a password.
441 The default capabilities for proxy type \a type are set automatically.
445 QNetworkProxy::QNetworkProxy(ProxyType type, const QString &hostName, quint16 port,
446 const QString &user, const QString &password)
447 : d(new QNetworkProxyPrivate(type, hostName, port, user, password))
449 // make sure we have QGlobalNetworkProxy singleton created, otherwise
450 // you don't have any socket engine handler created when directly setting
451 // a proxy to a socket
452 globalNetworkProxy();
456 Constructs a copy of \a other.
458 QNetworkProxy::QNetworkProxy(const QNetworkProxy &other)
464 Destroys the QNetworkProxy object.
466 QNetworkProxy::~QNetworkProxy()
468 // QSharedDataPointer takes care of deleting for us
474 Compares the value of this network proxy to \a other and returns true
475 if they are equal (same proxy type, server as well as username and password)
477 bool QNetworkProxy::operator==(const QNetworkProxy &other) const
479 return d == other.d || (d && other.d && *d == *other.d);
483 \fn bool QNetworkProxy::operator!=(const QNetworkProxy &other) const
486 Compares the value of this network proxy to \a other and returns true
493 Assigns the value of the network proxy \a other to this network proxy.
495 QNetworkProxy &QNetworkProxy::operator=(const QNetworkProxy &other)
502 Sets the proxy type for this instance to be \a type.
504 Note that changing the type of a proxy does not change
505 the set of capabilities this QNetworkProxy object holds if any
506 capabilities have been set with setCapabilities().
508 \sa type(), setCapabilities()
510 void QNetworkProxy::setType(QNetworkProxy::ProxyType type)
513 if (!d->capabilitiesSet)
514 d->capabilities = defaultCapabilitiesForType(type);
518 Returns the proxy type for this instance.
522 QNetworkProxy::ProxyType QNetworkProxy::type() const
524 return d ? d->type : DefaultProxy;
530 Sets the capabilities of this proxy to \a capabilities.
532 \sa setType(), capabilities()
534 void QNetworkProxy::setCapabilities(Capabilities capabilities)
536 d->capabilities = capabilities;
537 d->capabilitiesSet = true;
543 Returns the capabilities of this proxy server.
545 \sa setCapabilities(), type()
547 QNetworkProxy::Capabilities QNetworkProxy::capabilities() const
549 return d ? d->capabilities : defaultCapabilitiesForType(DefaultProxy);
555 Returns true if this proxy supports the
556 QNetworkProxy::CachingCapability capability.
558 In Qt 4.4, the capability was tied to the proxy type, but since Qt
559 4.5 it is possible to remove the capability of caching from a
560 proxy by calling setCapabilities().
562 \sa capabilities(), type(), isTransparentProxy()
564 bool QNetworkProxy::isCachingProxy() const
566 return capabilities() & CachingCapability;
572 Returns true if this proxy supports transparent tunneling of TCP
573 connections. This matches the QNetworkProxy::TunnelingCapability
576 In Qt 4.4, the capability was tied to the proxy type, but since Qt
577 4.5 it is possible to remove the capability of caching from a
578 proxy by calling setCapabilities().
580 \sa capabilities(), type(), isCachingProxy()
582 bool QNetworkProxy::isTransparentProxy() const
584 return capabilities() & TunnelingCapability;
588 Sets the user name for proxy authentication to be \a user.
590 \sa user(), setPassword(), password()
592 void QNetworkProxy::setUser(const QString &user)
598 Returns the user name used for authentication.
600 \sa setUser(), setPassword(), password()
602 QString QNetworkProxy::user() const
604 return d ? d->user : QString();
608 Sets the password for proxy authentication to be \a password.
610 \sa user(), setUser(), password()
612 void QNetworkProxy::setPassword(const QString &password)
614 d->password = password;
618 Returns the password used for authentication.
620 \sa user(), setPassword(), setUser()
622 QString QNetworkProxy::password() const
624 return d ? d->password : QString();
628 Sets the host name of the proxy host to be \a hostName.
630 \sa hostName(), setPort(), port()
632 void QNetworkProxy::setHostName(const QString &hostName)
634 d->hostName = hostName;
638 Returns the host name of the proxy host.
640 \sa setHostName(), setPort(), port()
642 QString QNetworkProxy::hostName() const
644 return d ? d->hostName : QString();
648 Sets the port of the proxy host to be \a port.
650 \sa hostName(), setHostName(), port()
652 void QNetworkProxy::setPort(quint16 port)
658 Returns the port of the proxy host.
660 \sa setHostName(), setPort(), hostName()
662 quint16 QNetworkProxy::port() const
664 return d ? d->port : 0;
668 Sets the application level network proxying to be \a networkProxy.
670 If a QAbstractSocket or QTcpSocket has the
671 QNetworkProxy::DefaultProxy type, then the QNetworkProxy set with
672 this function is used. If you want more flexibility in determining
673 which the proxy, use the QNetworkProxyFactory class.
675 Setting a default proxy value with this function will override the
676 application proxy factory set with
677 QNetworkProxyFactory::setApplicationProxyFactory.
679 \sa QNetworkProxyFactory, applicationProxy(), QAbstractSocket::setProxy(), QTcpServer::setProxy()
681 void QNetworkProxy::setApplicationProxy(const QNetworkProxy &networkProxy)
683 if (globalNetworkProxy()) {
684 // don't accept setting the proxy to DefaultProxy
685 if (networkProxy.type() == DefaultProxy)
686 globalNetworkProxy()->setApplicationProxy(QNetworkProxy::NoProxy);
688 globalNetworkProxy()->setApplicationProxy(networkProxy);
693 Returns the application level network proxying.
695 If a QAbstractSocket or QTcpSocket has the
696 QNetworkProxy::DefaultProxy type, then the QNetworkProxy returned
697 by this function is used.
699 \sa QNetworkProxyFactory, setApplicationProxy(), QAbstractSocket::proxy(), QTcpServer::proxy()
701 QNetworkProxy QNetworkProxy::applicationProxy()
703 if (globalNetworkProxy())
704 return globalNetworkProxy()->applicationProxy();
705 return QNetworkProxy();
710 Returns the value of the known network header \a header if it is
711 in use for this proxy. If it is not present, returns QVariant()
712 (i.e., an invalid variant).
714 \sa QNetworkRequest::KnownHeaders, rawHeader(), setHeader()
716 QVariant QNetworkProxy::header(QNetworkRequest::KnownHeaders header) const
718 if (d->type != HttpProxy && d->type != HttpCachingProxy)
720 return d->headers.cookedHeaders.value(header);
725 Sets the value of the known header \a header to be \a value,
726 overriding any previously set headers. This operation also sets
727 the equivalent raw HTTP header.
729 If the proxy is not of type HttpProxy or HttpCachingProxy this has no
732 \sa QNetworkRequest::KnownHeaders, setRawHeader(), header()
734 void QNetworkProxy::setHeader(QNetworkRequest::KnownHeaders header, const QVariant &value)
736 if (d->type == HttpProxy || d->type == HttpCachingProxy)
737 d->headers.setCookedHeader(header, value);
742 Returns true if the raw header \a headerName is in use for this
743 proxy. Returns false if the proxy is not of type HttpProxy or
746 \sa rawHeader(), setRawHeader()
748 bool QNetworkProxy::hasRawHeader(const QByteArray &headerName) const
750 if (d->type != HttpProxy && d->type != HttpCachingProxy)
752 return d->headers.findRawHeader(headerName) != d->headers.rawHeaders.constEnd();
757 Returns the raw form of header \a headerName. If no such header is
758 present or the proxy is not of type HttpProxy or HttpCachingProxy,
759 an empty QByteArray is returned, which may be indistinguishable
760 from a header that is present but has no content (use hasRawHeader()
761 to find out if the header exists or not).
763 Raw headers can be set with setRawHeader() or with setHeader().
765 \sa header(), setRawHeader()
767 QByteArray QNetworkProxy::rawHeader(const QByteArray &headerName) const
769 if (d->type != HttpProxy && d->type != HttpCachingProxy)
771 QNetworkHeadersPrivate::RawHeadersList::ConstIterator it =
772 d->headers.findRawHeader(headerName);
773 if (it != d->headers.rawHeaders.constEnd())
780 Returns a list of all raw headers that are set in this network
781 proxy. The list is in the order that the headers were set.
783 If the proxy is not of type HttpProxy or HttpCachingProxy an empty
786 \sa hasRawHeader(), rawHeader()
788 QList<QByteArray> QNetworkProxy::rawHeaderList() const
790 if (d->type != HttpProxy && d->type != HttpCachingProxy)
791 return QList<QByteArray>();
792 return d->headers.rawHeadersKeys();
797 Sets the header \a headerName to be of value \a headerValue. If \a
798 headerName corresponds to a known header (see
799 QNetworkRequest::KnownHeaders), the raw format will be parsed and
800 the corresponding "cooked" header will be set as well.
803 \snippet code/src_network_access_qnetworkrequest.cpp 0
805 will also set the known header LastModifiedHeader to be the
806 QDateTime object of the parsed date.
808 Note: setting the same header twice overrides the previous
809 setting. To accomplish the behaviour of multiple HTTP headers of
810 the same name, you should concatenate the two values, separating
811 them with a comma (",") and set one single raw header.
813 If the proxy is not of type HttpProxy or HttpCachingProxy this has no
816 \sa QNetworkRequest::KnownHeaders, setHeader(), hasRawHeader(), rawHeader()
818 void QNetworkProxy::setRawHeader(const QByteArray &headerName, const QByteArray &headerValue)
820 if (d->type == HttpProxy || d->type == HttpCachingProxy)
821 d->headers.setRawHeader(headerName, headerValue);
824 class QNetworkProxyQueryPrivate: public QSharedData
827 inline QNetworkProxyQueryPrivate()
828 : localPort(-1), type(QNetworkProxyQuery::TcpSocket)
831 bool operator==(const QNetworkProxyQueryPrivate &other) const
833 return type == other.type &&
834 localPort == other.localPort &&
835 remote == other.remote;
840 QNetworkProxyQuery::QueryType type;
841 #ifndef QT_NO_BEARERMANAGEMENT
842 QNetworkConfiguration config;
846 template<> void QSharedDataPointer<QNetworkProxyQueryPrivate>::detach()
848 if (d && d->ref.load() == 1)
850 QNetworkProxyQueryPrivate *x = (d ? new QNetworkProxyQueryPrivate(*d)
851 : new QNetworkProxyQueryPrivate);
853 if (d && !d->ref.deref())
859 \class QNetworkProxyQuery
862 \brief The QNetworkProxyQuery class is used to query the proxy
863 settings for a socket.
865 QNetworkProxyQuery holds the details of a socket being created or
866 request being made. It is used by QNetworkProxy and
867 QNetworkProxyFactory to allow applications to have a more
868 fine-grained control over which proxy servers are used, depending
869 on the details of the query. This allows an application to apply
870 different settings, according to the protocol or destination
871 hostname, for instance.
873 QNetworkProxyQuery supports the following criteria for selecting
877 \li the type of query
878 \li the local port number to use
879 \li the destination host name
880 \li the destination port number
881 \li the protocol name, such as "http" or "ftp"
882 \li the URL being requested
885 The destination host name is the host in the connection in the
886 case of outgoing connection sockets. It is the \c hostName
887 parameter passed to QTcpSocket::connectToHost() or the host
888 component of a URL requested with QNetworkRequest.
890 The destination port number is the requested port to connect to in
891 the case of outgoing sockets, while the local port number is the
892 port the socket wishes to use locally before attempting the
893 external connection. In most cases, the local port number is used
894 by listening sockets only (QTcpSocket) or by datagram sockets
897 The protocol name is an arbitrary string that indicates the type
898 of connection being attempted. For example, it can match the
899 scheme of a URL, like "http", "https" and "ftp". In most cases,
900 the proxy selection will not change depending on the protocol, but
901 this information is provided in case a better choice can be made,
902 like choosing an caching HTTP proxy for HTTP-based connections,
903 but a more powerful SOCKSv5 proxy for all others.
905 The network configuration specifies which configuration to use,
906 when bearer management is used. For example on a mobile phone
907 the proxy settings are likely to be different for the cellular
910 Some of the criteria may not make sense in all of the types of
911 query. The following table lists the criteria that are most
912 commonly used, according to the type of query.
921 \li Normal sockets requesting a connection to a remote server,
922 like QTcpSocket. The peer hostname and peer port match the
923 values passed to QTcpSocket::connectToHost(). The local port
924 is usually -1, indicating the socket has no preference in
925 which port should be used. The URL component is not used.
929 \li Datagram-based sockets, which can both send and
930 receive. The local port, remote host or remote port fields
931 can all be used or be left unused, depending on the
932 characteristics of the socket. The URL component is not used.
936 \li Passive server sockets that listen on a port and await
937 incoming connections from the network. Normally, only the
938 local port is used, but the remote address could be used in
939 specific circumstances, for example to indicate which remote
940 host a connection is expected from. The URL component is not used.
944 \li A more high-level request, such as those coming from
945 QNetworkAccessManager. These requests will inevitably use an
946 outgoing TCP socket, but the this query type is provided to
947 indicate that more detailed information is present in the URL
948 component. For ease of implementation, the URL's host and
949 port are set as the destination address.
952 It should be noted that any of the criteria may be missing or
953 unknown (an empty QString for the hostname or protocol name, -1
954 for the port numbers). If that happens, the functions executing
955 the query should make their best guess or apply some
956 implementation-defined default values.
958 \sa QNetworkProxy, QNetworkProxyFactory, QNetworkAccessManager,
959 QAbstractSocket::setProxy()
963 \enum QNetworkProxyQuery::QueryType
965 Describes the type of one QNetworkProxyQuery query.
967 \value TcpSocket a normal, outgoing TCP socket
968 \value UdpSocket a datagram-based UDP socket, which could send
969 to multiple destinations
970 \value TcpServer a TCP server that listens for incoming
971 connections from the network
972 \value UrlRequest a more complex request which involves loading
975 \sa queryType(), setQueryType()
979 Constructs a default QNetworkProxyQuery object. By default, the
980 query type will be QNetworkProxyQuery::TcpSocket.
982 QNetworkProxyQuery::QNetworkProxyQuery()
987 Constructs a QNetworkProxyQuery with the URL \a requestUrl and
988 sets the query type to \a queryType.
990 \sa protocolTag(), peerHostName(), peerPort()
992 QNetworkProxyQuery::QNetworkProxyQuery(const QUrl &requestUrl, QueryType queryType)
994 d->remote = requestUrl;
999 Constructs a QNetworkProxyQuery of type \a queryType and sets the
1000 protocol tag to be \a protocolTag. This constructor is suitable
1001 for QNetworkProxyQuery::TcpSocket queries, because it sets the
1002 peer hostname to \a hostname and the peer's port number to \a
1005 QNetworkProxyQuery::QNetworkProxyQuery(const QString &hostname, int port,
1006 const QString &protocolTag,
1007 QueryType queryType)
1009 d->remote.setScheme(protocolTag);
1010 d->remote.setHost(hostname);
1011 d->remote.setPort(port);
1012 d->type = queryType;
1016 Constructs a QNetworkProxyQuery of type \a queryType and sets the
1017 protocol tag to be \a protocolTag. This constructor is suitable
1018 for QNetworkProxyQuery::TcpSocket queries because it sets the
1019 local port number to \a bindPort.
1021 Note that \a bindPort is of type quint16 to indicate the exact
1022 port number that is requested. The value of -1 (unknown) is not
1023 allowed in this context.
1027 QNetworkProxyQuery::QNetworkProxyQuery(quint16 bindPort, const QString &protocolTag,
1028 QueryType queryType)
1030 d->remote.setScheme(protocolTag);
1031 d->localPort = bindPort;
1032 d->type = queryType;
1035 #ifndef QT_NO_BEARERMANAGEMENT
1037 Constructs a QNetworkProxyQuery with the URL \a requestUrl and
1038 sets the query type to \a queryType. The specified \a networkConfiguration
1039 is used to resolve the proxy settings.
1041 \sa protocolTag(), peerHostName(), peerPort(), networkConfiguration()
1043 QNetworkProxyQuery::QNetworkProxyQuery(const QNetworkConfiguration &networkConfiguration,
1044 const QUrl &requestUrl, QueryType queryType)
1046 d->config = networkConfiguration;
1047 d->remote = requestUrl;
1048 d->type = queryType;
1052 Constructs a QNetworkProxyQuery of type \a queryType and sets the
1053 protocol tag to be \a protocolTag. This constructor is suitable
1054 for QNetworkProxyQuery::TcpSocket queries, because it sets the
1055 peer hostname to \a hostname and the peer's port number to \a
1056 port. The specified \a networkConfiguration
1057 is used to resolve the proxy settings.
1059 \sa networkConfiguration()
1061 QNetworkProxyQuery::QNetworkProxyQuery(const QNetworkConfiguration &networkConfiguration,
1062 const QString &hostname, int port,
1063 const QString &protocolTag,
1064 QueryType queryType)
1066 d->config = networkConfiguration;
1067 d->remote.setScheme(protocolTag);
1068 d->remote.setHost(hostname);
1069 d->remote.setPort(port);
1070 d->type = queryType;
1074 Constructs a QNetworkProxyQuery of type \a queryType and sets the
1075 protocol tag to be \a protocolTag. This constructor is suitable
1076 for QNetworkProxyQuery::TcpSocket queries because it sets the
1077 local port number to \a bindPort. The specified \a networkConfiguration
1078 is used to resolve the proxy settings.
1080 Note that \a bindPort is of type quint16 to indicate the exact
1081 port number that is requested. The value of -1 (unknown) is not
1082 allowed in this context.
1084 \sa localPort(), networkConfiguration()
1086 QNetworkProxyQuery::QNetworkProxyQuery(const QNetworkConfiguration &networkConfiguration,
1087 quint16 bindPort, const QString &protocolTag,
1088 QueryType queryType)
1090 d->config = networkConfiguration;
1091 d->remote.setScheme(protocolTag);
1092 d->localPort = bindPort;
1093 d->type = queryType;
1098 Constructs a QNetworkProxyQuery object that is a copy of \a other.
1100 QNetworkProxyQuery::QNetworkProxyQuery(const QNetworkProxyQuery &other)
1106 Destroys this QNetworkProxyQuery object.
1108 QNetworkProxyQuery::~QNetworkProxyQuery()
1110 // QSharedDataPointer automatically deletes
1114 Copies the contents of \a other.
1116 QNetworkProxyQuery &QNetworkProxyQuery::operator=(const QNetworkProxyQuery &other)
1123 Returns true if this QNetworkProxyQuery object contains the same
1126 bool QNetworkProxyQuery::operator==(const QNetworkProxyQuery &other) const
1128 return d == other.d || (d && other.d && *d == *other.d);
1132 \fn bool QNetworkProxyQuery::operator!=(const QNetworkProxyQuery &other) const
1134 Returns true if this QNetworkProxyQuery object does not contain
1135 the same data as \a other.
1139 Returns the query type.
1141 QNetworkProxyQuery::QueryType QNetworkProxyQuery::queryType() const
1143 return d ? d->type : TcpSocket;
1147 Sets the query type of this object to be \a type.
1149 void QNetworkProxyQuery::setQueryType(QueryType type)
1155 Returns the port number for the outgoing request or -1 if the port
1156 number is not known.
1158 If the query type is QNetworkProxyQuery::UrlRequest, this function
1159 returns the port number of the URL being requested. In general,
1160 frameworks will fill in the port number from their default values.
1162 \sa peerHostName(), localPort(), setPeerPort()
1164 int QNetworkProxyQuery::peerPort() const
1166 return d ? d->remote.port() : -1;
1170 Sets the requested port number for the outgoing connection to be
1171 \a port. Valid values are 1 to 65535, or -1 to indicate that the
1172 remote port number is unknown.
1174 The peer port number can also be used to indicate the expected
1175 port number of an incoming connection in the case of
1176 QNetworkProxyQuery::UdpSocket or QNetworkProxyQuery::TcpServer
1179 \sa peerPort(), setPeerHostName(), setLocalPort()
1181 void QNetworkProxyQuery::setPeerPort(int port)
1183 d->remote.setPort(port);
1187 Returns the host name or IP address being of the outgoing
1188 connection being requested, or an empty string if the remote
1189 hostname is not known.
1191 If the query type is QNetworkProxyQuery::UrlRequest, this function
1192 returns the host component of the URL being requested.
1194 \sa peerPort(), localPort(), setPeerHostName()
1196 QString QNetworkProxyQuery::peerHostName() const
1198 return d ? d->remote.host() : QString();
1202 Sets the hostname of the outgoing connection being requested to \a
1203 hostname. An empty hostname can be used to indicate that the
1204 remote host is unknown.
1206 The peer host name can also be used to indicate the expected
1207 source address of an incoming connection in the case of
1208 QNetworkProxyQuery::UdpSocket or QNetworkProxyQuery::TcpServer
1211 \sa peerHostName(), setPeerPort(), setLocalPort()
1213 void QNetworkProxyQuery::setPeerHostName(const QString &hostname)
1215 d->remote.setHost(hostname);
1219 Returns the port number of the socket that will accept incoming
1220 packets from remote servers or -1 if the port is not known.
1222 \sa peerPort(), peerHostName(), setLocalPort()
1224 int QNetworkProxyQuery::localPort() const
1226 return d ? d->localPort : -1;
1230 Sets the port number that the socket wishes to use locally to
1231 accept incoming packets from remote servers to \a port. The local
1232 port is most often used with the QNetworkProxyQuery::TcpServer
1233 and QNetworkProxyQuery::UdpSocket query types.
1235 Valid values are 0 to 65535 (with 0 indicating that any port
1236 number will be acceptable) or -1, which means the local port
1237 number is unknown or not applicable.
1239 In some circumstances, for special protocols, it's the local port
1240 number can also be used with a query of type
1241 QNetworkProxyQuery::TcpSocket. When that happens, the socket is
1242 indicating it wishes to use the port number \a port when
1243 connecting to a remote host.
1245 \sa localPort(), setPeerPort(), setPeerHostName()
1247 void QNetworkProxyQuery::setLocalPort(int port)
1249 d->localPort = port;
1253 Returns the protocol tag for this QNetworkProxyQuery object, or an
1254 empty QString in case the protocol tag is unknown.
1256 In the case of queries of type QNetworkProxyQuery::UrlRequest,
1257 this function returns the value of the scheme component of the
1260 \sa setProtocolTag(), url()
1262 QString QNetworkProxyQuery::protocolTag() const
1264 return d ? d->remote.scheme() : QString();
1268 Sets the protocol tag for this QNetworkProxyQuery object to be \a
1271 The protocol tag is an arbitrary string that indicates which
1272 protocol is being talked over the socket, such as "http", "xmpp",
1273 "telnet", etc. The protocol tag is used by the backend to
1274 return a request that is more specific to the protocol in
1275 question: for example, a HTTP connection could be use a caching
1276 HTTP proxy server, while all other connections use a more powerful
1277 SOCKSv5 proxy server.
1281 void QNetworkProxyQuery::setProtocolTag(const QString &protocolTag)
1283 d->remote.setScheme(protocolTag);
1287 Returns the URL component of this QNetworkProxyQuery object in
1288 case of a query of type QNetworkProxyQuery::UrlRequest.
1292 QUrl QNetworkProxyQuery::url() const
1294 return d ? d->remote : QUrl();
1298 Sets the URL component of this QNetworkProxyQuery object to be \a
1299 url. Setting the URL will also set the protocol tag, the remote
1300 host name and port number. This is done so as to facilitate the
1301 implementation of the code that determines the proxy server to be
1304 \sa url(), peerHostName(), peerPort()
1306 void QNetworkProxyQuery::setUrl(const QUrl &url)
1311 #ifndef QT_NO_BEARERMANAGEMENT
1313 Returns the network configuration component of the query.
1315 \sa setNetworkConfiguration()
1317 QNetworkConfiguration QNetworkProxyQuery::networkConfiguration() const
1319 return d ? d->config : QNetworkConfiguration();
1323 Sets the network configuration component of this QNetworkProxyQuery
1324 object to be \a networkConfiguration. The network configuration can
1325 be used to return different proxy settings based on the network in
1326 use, for example WLAN vs cellular networks on a mobile phone.
1328 In the case of "user choice" or "service network" configurations,
1329 you should first start the QNetworkSession and obtain the active
1330 configuration from its properties.
1332 \sa networkConfiguration()
1334 void QNetworkProxyQuery::setNetworkConfiguration(const QNetworkConfiguration &networkConfiguration)
1336 d->config = networkConfiguration;
1341 \class QNetworkProxyFactory
1342 \brief The QNetworkProxyFactory class provides fine-grained proxy selection.
1348 QNetworkProxyFactory is an extension to QNetworkProxy, allowing
1349 applications to have a more fine-grained control over which proxy
1350 servers are used, depending on the socket requesting the
1351 proxy. This allows an application to apply different settings,
1352 according to the protocol or destination hostname, for instance.
1354 QNetworkProxyFactory can be set globally for an application, in
1355 which case it will override any global proxies set with
1356 QNetworkProxy::setApplicationProxy(). If set globally, any sockets
1357 created with Qt will query the factory to determine the proxy to
1360 A factory can also be set in certain frameworks that support
1361 multiple connections, such as QNetworkAccessManager. When set on
1362 such object, the factory will be queried for sockets created by
1363 that framework only.
1365 \section1 System Proxies
1367 You can configure a factory to use the system proxy's settings.
1368 Call the setUseSystemConfiguration() function with true to enable
1369 this behavior, or false to disable it.
1371 Similarly, you can use a factory to make queries directly to the
1372 system proxy by calling its systemProxyForQuery() function.
1374 \warning Depending on the configuration of the user's system, the
1375 use of system proxy features on certain platforms may be subject
1376 to limitations. The systemProxyForQuery() documentation contains a
1377 list of these limitations for those platforms that are affected.
1381 Creates a QNetworkProxyFactory object.
1383 Since QNetworkProxyFactory is an abstract class, you cannot create
1384 objects of type QNetworkProxyFactory directly.
1386 QNetworkProxyFactory::QNetworkProxyFactory()
1391 Destroys the QNetworkProxyFactory object.
1393 QNetworkProxyFactory::~QNetworkProxyFactory()
1401 Enables the use of the platform-specific proxy settings, and only those.
1402 See systemProxyForQuery() for more information.
1404 Internally, this method (when called with \a enable set to true)
1405 sets an application-wide proxy factory. For this reason, this method
1406 is mutually exclusive with setApplicationProxyFactory(): calling
1407 setApplicationProxyFactory() overrides the use of the system-wide proxy,
1408 and calling setUseSystemConfiguration() overrides any
1409 application proxy or proxy factory that was previously set.
1411 \note See the systemProxyForQuery() documentation for a list of
1412 limitations related to the use of system proxies.
1414 void QNetworkProxyFactory::setUseSystemConfiguration(bool enable)
1417 setApplicationProxyFactory(new QSystemConfigurationProxyFactory);
1419 setApplicationProxyFactory(0);
1424 Sets the application-wide proxy factory to be \a factory. This
1425 function will take ownership of that object and will delete it
1428 The application-wide proxy is used as a last-resort when all other
1429 proxy selection requests returned QNetworkProxy::DefaultProxy. For
1430 example, QTcpSocket objects can have a proxy set with
1431 QTcpSocket::setProxy, but if none is set, the proxy factory class
1432 set with this function will be queried.
1434 If you set a proxy factory with this function, any application
1435 level proxies set with QNetworkProxy::setApplicationProxy will be
1438 \sa QNetworkProxy::setApplicationProxy(),
1439 QAbstractSocket::proxy(), QAbstractSocket::setProxy()
1441 void QNetworkProxyFactory::setApplicationProxyFactory(QNetworkProxyFactory *factory)
1443 if (globalNetworkProxy())
1444 globalNetworkProxy()->setApplicationProxyFactory(factory);
1448 \fn QList<QNetworkProxy> QNetworkProxyFactory::queryProxy(const QNetworkProxyQuery &query)
1450 This function takes the query request, \a query,
1451 examines the details of the type of socket or request and returns
1452 a list of QNetworkProxy objects that indicate the proxy servers to
1453 be used, in order of preference.
1455 When reimplementing this class, take care to return at least one
1458 If you cannot determine a better proxy alternative, use
1459 QNetworkProxy::DefaultProxy, which tells the code querying for a
1460 proxy to use a higher alternative. For example, if this factory is
1461 set to a QNetworkAccessManager object, DefaultProxy will tell it
1462 to query the application-level proxy settings.
1464 If this factory is set as the application proxy factory,
1465 DefaultProxy and NoProxy will have the same meaning.
1469 \fn QList<QNetworkProxy> QNetworkProxyFactory::systemProxyForQuery(const QNetworkProxyQuery &query)
1471 This function takes the query request, \a query,
1472 examines the details of the type of socket or request and returns
1473 a list of QNetworkProxy objects that indicate the proxy servers to
1474 be used, in order of preference.
1476 This function can be used to determine the platform-specific proxy
1477 settings. This function will use the libraries provided by the
1478 operating system to determine the proxy for a given connection, if
1479 such libraries exist. If they don't, this function will just return a
1480 QNetworkProxy of type QNetworkProxy::NoProxy.
1482 On Windows, this function will use the WinHTTP DLL functions. Despite
1483 its name, Microsoft suggests using it for all applications that
1484 require network connections, not just HTTP. This will respect the
1485 proxy settings set on the registry with the proxycfg.exe tool. If
1486 those settings are not found, this function will attempt to obtain
1487 Internet Explorer's settings and use them.
1489 On MacOS X, this function will obtain the proxy settings using the
1490 SystemConfiguration framework from Apple. It will apply the FTP,
1491 HTTP and HTTPS proxy configurations for queries that contain the
1492 protocol tag "ftp", "http" and "https", respectively. If the SOCKS
1493 proxy is enabled in that configuration, this function will use the
1494 SOCKS server for all queries. If SOCKS isn't enabled, it will use
1495 the HTTPS proxy for all TcpSocket and UrlRequest queries.
1497 On other systems, this function will pick up proxy settings from
1498 the "http_proxy" environment variable. This variable must be a URL
1499 using one of the following schemes: "http", "socks5" or "socks5h".
1501 \section1 Limitations
1503 These are the limitations for the current version of this
1504 function. Future versions of Qt may lift some of the limitations
1508 \li On MacOS X, this function will ignore the Proxy Auto Configuration
1509 settings, since it cannot execute the associated ECMAScript code.
1511 \li On Windows platforms, this function may take several seconds to
1512 execute depending on the configuration of the user's system.
1517 This function takes the query request, \a query,
1518 examines the details of the type of socket or request and returns
1519 a list of QNetworkProxy objects that indicate the proxy servers to
1520 be used, in order of preference.
1522 QList<QNetworkProxy> QNetworkProxyFactory::proxyForQuery(const QNetworkProxyQuery &query)
1524 if (!globalNetworkProxy())
1525 return QList<QNetworkProxy>() << QNetworkProxy(QNetworkProxy::NoProxy);
1526 return globalNetworkProxy()->proxyForQuery(query);
1529 #ifndef QT_NO_DEBUG_STREAM
1532 Outputs a QNetworkProxy details to a debug stream
1534 QDebug operator<<(QDebug debug, const QNetworkProxy &proxy)
1536 QNetworkProxy::ProxyType type = proxy.type();
1538 case QNetworkProxy::NoProxy:
1539 debug << "NoProxy ";
1541 case QNetworkProxy::DefaultProxy:
1542 debug << "DefaultProxy ";
1544 case QNetworkProxy::Socks5Proxy:
1545 debug << "Socks5Proxy ";
1547 case QNetworkProxy::HttpProxy:
1548 debug << "HttpProxy ";
1550 case QNetworkProxy::HttpCachingProxy:
1551 debug << "HttpCachingProxy ";
1553 case QNetworkProxy::FtpCachingProxy:
1554 debug << "FtpCachingProxy ";
1557 debug << "Unknown proxy " << int(type);
1560 debug << "\"" << proxy.hostName() << ":" << proxy.port() << "\" ";
1561 QNetworkProxy::Capabilities caps = proxy.capabilities();
1563 if (caps & QNetworkProxy::TunnelingCapability)
1564 scaps << QStringLiteral("Tunnel");
1565 if (caps & QNetworkProxy::ListeningCapability)
1566 scaps << QStringLiteral("Listen");
1567 if (caps & QNetworkProxy::UdpTunnelingCapability)
1568 scaps << QStringLiteral("UDP");
1569 if (caps & QNetworkProxy::CachingCapability)
1570 scaps << QStringLiteral("Caching");
1571 if (caps & QNetworkProxy::HostNameLookupCapability)
1572 scaps << QStringLiteral("NameLookup");
1573 debug << "[" << scaps.join(QStringLiteral(" ")) << "]";
1580 #endif // QT_NO_NETWORKPROXY