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 doc/src/snippets/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 doc/src/snippets/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 \o Default capabilities
148 \o Generic proxy for any kind of connection. Supports TCP,
149 UDP, binding to a port (incoming connections) and
151 \o TunnelingCapability, ListeningCapability,
152 UdpTunnelingCapability, HostNameLookupCapability
156 \o Implemented using the "CONNECT" command, supports only
157 outgoing TCP connections; supports authentication.
158 \o TunnelingCapability, CachingCapability, HostNameLookupCapability
162 \o Implemented using normal HTTP commands, it is useful only
163 in the context of HTTP requests (see QNetworkAccessManager)
164 \o CachingCapability, HostNameLookupCapability
168 \o Implemented using an FTP proxy, it is useful only in the
169 context of FTP requests (see QNetworkAccessManager)
170 \o 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"
231 #ifndef QT_NO_BEARERMANAGEMENT
232 #include <QtNetwork/QNetworkConfiguration>
237 class QSocks5SocketEngineHandler;
238 class QHttpSocketEngineHandler;
240 class QGlobalNetworkProxy
243 QGlobalNetworkProxy()
244 : mutex(QMutex::Recursive)
245 , applicationLevelProxy(0)
246 , applicationLevelProxyFactory(0)
247 , socks5SocketEngineHandler(0)
248 , httpSocketEngineHandler(0)
252 ~QGlobalNetworkProxy()
254 delete applicationLevelProxy;
255 delete applicationLevelProxyFactory;
256 delete socks5SocketEngineHandler;
257 delete httpSocketEngineHandler;
262 QMutexLocker lock(&mutex);
264 if (!socks5SocketEngineHandler)
265 socks5SocketEngineHandler = new QSocks5SocketEngineHandler();
268 if (!httpSocketEngineHandler)
269 httpSocketEngineHandler = new QHttpSocketEngineHandler();
273 void setApplicationProxy(const QNetworkProxy &proxy)
275 QMutexLocker lock(&mutex);
276 if (!applicationLevelProxy)
277 applicationLevelProxy = new QNetworkProxy;
278 *applicationLevelProxy = proxy;
279 delete applicationLevelProxyFactory;
280 applicationLevelProxyFactory = 0;
283 void setApplicationProxyFactory(QNetworkProxyFactory *factory)
285 QMutexLocker lock(&mutex);
286 if (applicationLevelProxy)
287 *applicationLevelProxy = QNetworkProxy();
288 delete applicationLevelProxyFactory;
289 applicationLevelProxyFactory = factory;
292 QNetworkProxy applicationProxy()
294 return proxyForQuery(QNetworkProxyQuery()).first();
297 QList<QNetworkProxy> proxyForQuery(const QNetworkProxyQuery &query);
301 QNetworkProxy *applicationLevelProxy;
302 QNetworkProxyFactory *applicationLevelProxyFactory;
303 QSocks5SocketEngineHandler *socks5SocketEngineHandler;
304 QHttpSocketEngineHandler *httpSocketEngineHandler;
307 QList<QNetworkProxy> QGlobalNetworkProxy::proxyForQuery(const QNetworkProxyQuery &query)
309 QMutexLocker locker(&mutex);
311 QList<QNetworkProxy> result;
312 if (!applicationLevelProxyFactory) {
313 if (applicationLevelProxy
314 && applicationLevelProxy->type() != QNetworkProxy::DefaultProxy)
315 result << *applicationLevelProxy;
317 result << QNetworkProxy(QNetworkProxy::NoProxy);
322 result = applicationLevelProxyFactory->queryProxy(query);
323 if (result.isEmpty()) {
324 qWarning("QNetworkProxyFactory: factory %p has returned an empty result set",
325 applicationLevelProxyFactory);
326 result << QNetworkProxy(QNetworkProxy::NoProxy);
331 Q_GLOBAL_STATIC(QGlobalNetworkProxy, globalNetworkProxy)
334 template<bool> struct StaticAssertTest;
335 template<> struct StaticAssertTest<true> { enum { Value = 1 }; };
338 static inline void qt_noop_with_arg(int) {}
339 #define q_static_assert(expr) qt_noop_with_arg(sizeof(StaticAssertTest< expr >::Value))
341 static QNetworkProxy::Capabilities defaultCapabilitiesForType(QNetworkProxy::ProxyType type)
343 q_static_assert(int(QNetworkProxy::DefaultProxy) == 0);
344 q_static_assert(int(QNetworkProxy::FtpCachingProxy) == 5);
345 static const int defaults[] =
347 /* [QNetworkProxy::DefaultProxy] = */
348 (int(QNetworkProxy::ListeningCapability) |
349 int(QNetworkProxy::TunnelingCapability) |
350 int(QNetworkProxy::UdpTunnelingCapability)),
351 /* [QNetworkProxy::Socks5Proxy] = */
352 (int(QNetworkProxy::TunnelingCapability) |
353 int(QNetworkProxy::ListeningCapability) |
354 int(QNetworkProxy::UdpTunnelingCapability) |
355 int(QNetworkProxy::HostNameLookupCapability)),
356 // it's weird to talk about the proxy capabilities of a "not proxy"...
357 /* [QNetworkProxy::NoProxy] = */
358 (int(QNetworkProxy::ListeningCapability) |
359 int(QNetworkProxy::TunnelingCapability) |
360 int(QNetworkProxy::UdpTunnelingCapability)),
361 /* [QNetworkProxy::HttpProxy] = */
362 (int(QNetworkProxy::TunnelingCapability) |
363 int(QNetworkProxy::CachingCapability) |
364 int(QNetworkProxy::HostNameLookupCapability)),
365 /* [QNetworkProxy::HttpCachingProxy] = */
366 (int(QNetworkProxy::CachingCapability) |
367 int(QNetworkProxy::HostNameLookupCapability)),
368 /* [QNetworkProxy::FtpCachingProxy] = */
369 (int(QNetworkProxy::CachingCapability) |
370 int(QNetworkProxy::HostNameLookupCapability)),
373 if (int(type) < 0 || int(type) > int(QNetworkProxy::FtpCachingProxy))
374 type = QNetworkProxy::DefaultProxy;
375 return QNetworkProxy::Capabilities(defaults[int(type)]);
378 class QNetworkProxyPrivate: public QSharedData
384 QNetworkProxy::Capabilities capabilities;
386 QNetworkProxy::ProxyType type;
387 bool capabilitiesSet;
388 QNetworkHeadersPrivate headers;
390 inline QNetworkProxyPrivate(QNetworkProxy::ProxyType t = QNetworkProxy::DefaultProxy,
391 const QString &h = QString(), quint16 p = 0,
392 const QString &u = QString(), const QString &pw = QString())
396 capabilities(defaultCapabilitiesForType(t)),
399 capabilitiesSet(false)
402 inline bool operator==(const QNetworkProxyPrivate &other) const
404 return type == other.type &&
405 port == other.port &&
406 hostName == other.hostName &&
407 user == other.user &&
408 password == other.password &&
409 capabilities == other.capabilities;
413 template<> void QSharedDataPointer<QNetworkProxyPrivate>::detach()
415 if (d && d->ref.load() == 1)
417 QNetworkProxyPrivate *x = (d ? new QNetworkProxyPrivate(*d)
418 : new QNetworkProxyPrivate);
420 if (d && !d->ref.deref())
426 Constructs a QNetworkProxy with DefaultProxy type; the proxy type is
427 determined by applicationProxy(), which defaults to NoProxy.
429 \sa setType(), setApplicationProxy()
431 QNetworkProxy::QNetworkProxy()
434 if (QGlobalNetworkProxy *globalProxy = globalNetworkProxy())
439 Constructs a QNetworkProxy with \a type, \a hostName, \a port,
440 \a user and \a password.
442 The default capabilities for proxy type \a type are set automatically.
446 QNetworkProxy::QNetworkProxy(ProxyType type, const QString &hostName, quint16 port,
447 const QString &user, const QString &password)
448 : d(new QNetworkProxyPrivate(type, hostName, port, user, password))
450 if (QGlobalNetworkProxy *globalProxy = globalNetworkProxy())
455 Constructs a copy of \a other.
457 QNetworkProxy::QNetworkProxy(const QNetworkProxy &other)
463 Destroys the QNetworkProxy object.
465 QNetworkProxy::~QNetworkProxy()
467 // QSharedDataPointer takes care of deleting for us
473 Compares the value of this network proxy to \a other and returns true
474 if they are equal (same proxy type, server as well as username and password)
476 bool QNetworkProxy::operator==(const QNetworkProxy &other) const
478 return d == other.d || (d && other.d && *d == *other.d);
482 \fn bool QNetworkProxy::operator!=(const QNetworkProxy &other) const
485 Compares the value of this network proxy to \a other and returns true
492 Assigns the value of the network proxy \a other to this network proxy.
494 QNetworkProxy &QNetworkProxy::operator=(const QNetworkProxy &other)
501 Sets the proxy type for this instance to be \a type.
503 Note that changing the type of a proxy does not change
504 the set of capabilities this QNetworkProxy object holds if any
505 capabilities have been set with setCapabilities().
507 \sa type(), setCapabilities()
509 void QNetworkProxy::setType(QNetworkProxy::ProxyType type)
512 if (!d->capabilitiesSet)
513 d->capabilities = defaultCapabilitiesForType(type);
517 Returns the proxy type for this instance.
521 QNetworkProxy::ProxyType QNetworkProxy::type() const
523 return d ? d->type : DefaultProxy;
529 Sets the capabilities of this proxy to \a capabilities.
531 \sa setType(), capabilities()
533 void QNetworkProxy::setCapabilities(Capabilities capabilities)
535 d->capabilities = capabilities;
536 d->capabilitiesSet = true;
542 Returns the capabilities of this proxy server.
544 \sa setCapabilities(), type()
546 QNetworkProxy::Capabilities QNetworkProxy::capabilities() const
548 return d ? d->capabilities : defaultCapabilitiesForType(DefaultProxy);
554 Returns true if this proxy supports the
555 QNetworkProxy::CachingCapability capability.
557 In Qt 4.4, the capability was tied to the proxy type, but since Qt
558 4.5 it is possible to remove the capability of caching from a
559 proxy by calling setCapabilities().
561 \sa capabilities(), type(), isTransparentProxy()
563 bool QNetworkProxy::isCachingProxy() const
565 return capabilities() & CachingCapability;
571 Returns true if this proxy supports transparent tunneling of TCP
572 connections. This matches the QNetworkProxy::TunnelingCapability
575 In Qt 4.4, the capability was tied to the proxy type, but since Qt
576 4.5 it is possible to remove the capability of caching from a
577 proxy by calling setCapabilities().
579 \sa capabilities(), type(), isCachingProxy()
581 bool QNetworkProxy::isTransparentProxy() const
583 return capabilities() & TunnelingCapability;
587 Sets the user name for proxy authentication to be \a user.
589 \sa user(), setPassword(), password()
591 void QNetworkProxy::setUser(const QString &user)
597 Returns the user name used for authentication.
599 \sa setUser(), setPassword(), password()
601 QString QNetworkProxy::user() const
603 return d ? d->user : QString();
607 Sets the password for proxy authentication to be \a password.
609 \sa user(), setUser(), password()
611 void QNetworkProxy::setPassword(const QString &password)
613 d->password = password;
617 Returns the password used for authentication.
619 \sa user(), setPassword(), setUser()
621 QString QNetworkProxy::password() const
623 return d ? d->password : QString();
627 Sets the host name of the proxy host to be \a hostName.
629 \sa hostName(), setPort(), port()
631 void QNetworkProxy::setHostName(const QString &hostName)
633 d->hostName = hostName;
637 Returns the host name of the proxy host.
639 \sa setHostName(), setPort(), port()
641 QString QNetworkProxy::hostName() const
643 return d ? d->hostName : QString();
647 Sets the port of the proxy host to be \a port.
649 \sa hostName(), setHostName(), port()
651 void QNetworkProxy::setPort(quint16 port)
657 Returns the port of the proxy host.
659 \sa setHostName(), setPort(), hostName()
661 quint16 QNetworkProxy::port() const
663 return d ? d->port : 0;
667 Sets the application level network proxying to be \a networkProxy.
669 If a QAbstractSocket or QTcpSocket has the
670 QNetworkProxy::DefaultProxy type, then the QNetworkProxy set with
671 this function is used. If you want more flexibility in determining
672 which the proxy, use the QNetworkProxyFactory class.
674 Setting a default proxy value with this function will override the
675 application proxy factory set with
676 QNetworkProxyFactory::setApplicationProxyFactory.
678 \sa QNetworkProxyFactory, applicationProxy(), QAbstractSocket::setProxy(), QTcpServer::setProxy()
680 void QNetworkProxy::setApplicationProxy(const QNetworkProxy &networkProxy)
682 if (globalNetworkProxy()) {
683 // don't accept setting the proxy to DefaultProxy
684 if (networkProxy.type() == DefaultProxy)
685 globalNetworkProxy()->setApplicationProxy(QNetworkProxy::NoProxy);
687 globalNetworkProxy()->setApplicationProxy(networkProxy);
692 Returns the application level network proxying.
694 If a QAbstractSocket or QTcpSocket has the
695 QNetworkProxy::DefaultProxy type, then the QNetworkProxy returned
696 by this function is used.
698 \sa QNetworkProxyFactory, setApplicationProxy(), QAbstractSocket::proxy(), QTcpServer::proxy()
700 QNetworkProxy QNetworkProxy::applicationProxy()
702 if (globalNetworkProxy())
703 return globalNetworkProxy()->applicationProxy();
704 return QNetworkProxy();
708 Returns the value of the known network header \a header if it is
709 in use for this proxy. If it is not present, returns QVariant()
710 (i.e., an invalid variant).
712 \sa QNetworkRequest::KnownHeaders, rawHeader(), setHeader()
714 QVariant QNetworkProxy::header(QNetworkRequest::KnownHeaders header) const
716 if (d->type != HttpProxy && d->type != HttpCachingProxy)
718 return d->headers.cookedHeaders.value(header);
722 Sets the value of the known header \a header to be \a value,
723 overriding any previously set headers. This operation also sets
724 the equivalent raw HTTP header.
726 If the proxy is not of type HttpProxy or HttpCachingProxy this has no
729 \sa QNetworkRequest::KnownHeaders, setRawHeader(), header()
731 void QNetworkProxy::setHeader(QNetworkRequest::KnownHeaders header, const QVariant &value)
733 if (d->type == HttpProxy || d->type == HttpCachingProxy)
734 d->headers.setCookedHeader(header, value);
738 Returns true if the raw header \a headerName is in use for this
739 proxy. Returns false if the proxy is not of type HttpProxy or
742 \sa rawHeader(), setRawHeader()
744 bool QNetworkProxy::hasRawHeader(const QByteArray &headerName) const
746 if (d->type != HttpProxy && d->type != HttpCachingProxy)
748 return d->headers.findRawHeader(headerName) != d->headers.rawHeaders.constEnd();
752 Returns the raw form of header \a headerName. If no such header is
753 present or the proxy is not of type HttpProxy or HttpCachingProxy,
754 an empty QByteArray is returned, which may be indistinguishable
755 from a header that is present but has no content (use hasRawHeader()
756 to find out if the header exists or not).
758 Raw headers can be set with setRawHeader() or with setHeader().
760 \sa header(), setRawHeader()
762 QByteArray QNetworkProxy::rawHeader(const QByteArray &headerName) const
764 if (d->type != HttpProxy && d->type != HttpCachingProxy)
766 QNetworkHeadersPrivate::RawHeadersList::ConstIterator it =
767 d->headers.findRawHeader(headerName);
768 if (it != d->headers.rawHeaders.constEnd())
774 Returns a list of all raw headers that are set in this network
775 proxy. The list is in the order that the headers were set.
777 If the proxy is not of type HttpProxy or HttpCachingProxy an empty
780 \sa hasRawHeader(), rawHeader()
782 QList<QByteArray> QNetworkProxy::rawHeaderList() const
784 if (d->type != HttpProxy && d->type != HttpCachingProxy)
785 return QList<QByteArray>();
786 return d->headers.rawHeadersKeys();
790 Sets the header \a headerName to be of value \a headerValue. If \a
791 headerName corresponds to a known header (see
792 QNetworkRequest::KnownHeaders), the raw format will be parsed and
793 the corresponding "cooked" header will be set as well.
796 \snippet doc/src/snippets/code/src_network_access_qnetworkrequest.cpp 0
798 will also set the known header LastModifiedHeader to be the
799 QDateTime object of the parsed date.
801 Note: setting the same header twice overrides the previous
802 setting. To accomplish the behaviour of multiple HTTP headers of
803 the same name, you should concatenate the two values, separating
804 them with a comma (",") and set one single raw header.
806 If the proxy is not of type HttpProxy or HttpCachingProxy this has no
809 \sa QNetworkRequest::KnownHeaders, setHeader(), hasRawHeader(), rawHeader()
811 void QNetworkProxy::setRawHeader(const QByteArray &headerName, const QByteArray &headerValue)
813 if (d->type == HttpProxy || d->type == HttpCachingProxy)
814 d->headers.setRawHeader(headerName, headerValue);
817 class QNetworkProxyQueryPrivate: public QSharedData
820 inline QNetworkProxyQueryPrivate()
821 : localPort(-1), type(QNetworkProxyQuery::TcpSocket)
824 bool operator==(const QNetworkProxyQueryPrivate &other) const
826 return type == other.type &&
827 localPort == other.localPort &&
828 remote == other.remote;
833 QNetworkProxyQuery::QueryType type;
834 #ifndef QT_NO_BEARERMANAGEMENT
835 QNetworkConfiguration config;
839 template<> void QSharedDataPointer<QNetworkProxyQueryPrivate>::detach()
841 if (d && d->ref.load() == 1)
843 QNetworkProxyQueryPrivate *x = (d ? new QNetworkProxyQueryPrivate(*d)
844 : new QNetworkProxyQueryPrivate);
846 if (d && !d->ref.deref())
852 \class QNetworkProxyQuery
855 \brief The QNetworkProxyQuery class is used to query the proxy
856 settings for a socket
858 QNetworkProxyQuery holds the details of a socket being created or
859 request being made. It is used by QNetworkProxy and
860 QNetworkProxyFactory to allow applications to have a more
861 fine-grained control over which proxy servers are used, depending
862 on the details of the query. This allows an application to apply
863 different settings, according to the protocol or destination
864 hostname, for instance.
866 QNetworkProxyQuery supports the following criteria for selecting
871 \o the local port number to use
872 \o the destination host name
873 \o the destination port number
874 \o the protocol name, such as "http" or "ftp"
875 \o the URL being requested
878 The destination host name is the host in the connection in the
879 case of outgoing connection sockets. It is the \c hostName
880 parameter passed to QTcpSocket::connectToHost() or the host
881 component of a URL requested with QNetworkRequest.
883 The destination port number is the requested port to connect to in
884 the case of outgoing sockets, while the local port number is the
885 port the socket wishes to use locally before attempting the
886 external connection. In most cases, the local port number is used
887 by listening sockets only (QTcpSocket) or by datagram sockets
890 The protocol name is an arbitrary string that indicates the type
891 of connection being attempted. For example, it can match the
892 scheme of a URL, like "http", "https" and "ftp". In most cases,
893 the proxy selection will not change depending on the protocol, but
894 this information is provided in case a better choice can be made,
895 like choosing an caching HTTP proxy for HTTP-based connections,
896 but a more powerful SOCKSv5 proxy for all others.
898 The network configuration specifies which configuration to use,
899 when bearer management is used. For example on a mobile phone
900 the proxy settings are likely to be different for the cellular
903 Some of the criteria may not make sense in all of the types of
904 query. The following table lists the criteria that are most
905 commonly used, according to the type of query.
914 \o Normal sockets requesting a connection to a remote server,
915 like QTcpSocket. The peer hostname and peer port match the
916 values passed to QTcpSocket::connectToHost(). The local port
917 is usually -1, indicating the socket has no preference in
918 which port should be used. The URL component is not used.
922 \o Datagram-based sockets, which can both send and
923 receive. The local port, remote host or remote port fields
924 can all be used or be left unused, depending on the
925 characteristics of the socket. The URL component is not used.
929 \o Passive server sockets that listen on a port and await
930 incoming connections from the network. Normally, only the
931 local port is used, but the remote address could be used in
932 specific circumstances, for example to indicate which remote
933 host a connection is expected from. The URL component is not used.
937 \o A more high-level request, such as those coming from
938 QNetworkAccessManager. These requests will inevitably use an
939 outgoing TCP socket, but the this query type is provided to
940 indicate that more detailed information is present in the URL
941 component. For ease of implementation, the URL's host and
942 port are set as the destination address.
945 It should be noted that any of the criteria may be missing or
946 unknown (an empty QString for the hostname or protocol name, -1
947 for the port numbers). If that happens, the functions executing
948 the query should make their best guess or apply some
949 implementation-defined default values.
951 \sa QNetworkProxy, QNetworkProxyFactory, QNetworkAccessManager,
952 QAbstractSocket::setProxy()
956 \enum QNetworkProxyQuery::QueryType
958 Describes the type of one QNetworkProxyQuery query.
960 \value TcpSocket a normal, outgoing TCP socket
961 \value UdpSocket a datagram-based UDP socket, which could send
962 to multiple destinations
963 \value TcpServer a TCP server that listens for incoming
964 connections from the network
965 \value UrlRequest a more complex request which involves loading
968 \sa queryType(), setQueryType()
972 Constructs a default QNetworkProxyQuery object. By default, the
973 query type will be QNetworkProxyQuery::TcpSocket.
975 QNetworkProxyQuery::QNetworkProxyQuery()
980 Constructs a QNetworkProxyQuery with the URL \a requestUrl and
981 sets the query type to \a queryType.
983 \sa protocolTag(), peerHostName(), peerPort()
985 QNetworkProxyQuery::QNetworkProxyQuery(const QUrl &requestUrl, QueryType queryType)
987 d->remote = requestUrl;
992 Constructs a QNetworkProxyQuery of type \a queryType and sets the
993 protocol tag to be \a protocolTag. This constructor is suitable
994 for QNetworkProxyQuery::TcpSocket queries, because it sets the
995 peer hostname to \a hostname and the peer's port number to \a
998 QNetworkProxyQuery::QNetworkProxyQuery(const QString &hostname, int port,
999 const QString &protocolTag,
1000 QueryType queryType)
1002 d->remote.setScheme(protocolTag);
1003 d->remote.setHost(hostname);
1004 d->remote.setPort(port);
1005 d->type = queryType;
1009 Constructs a QNetworkProxyQuery of type \a queryType and sets the
1010 protocol tag to be \a protocolTag. This constructor is suitable
1011 for QNetworkProxyQuery::TcpSocket queries because it sets the
1012 local port number to \a bindPort.
1014 Note that \a bindPort is of type quint16 to indicate the exact
1015 port number that is requested. The value of -1 (unknown) is not
1016 allowed in this context.
1020 QNetworkProxyQuery::QNetworkProxyQuery(quint16 bindPort, const QString &protocolTag,
1021 QueryType queryType)
1023 d->remote.setScheme(protocolTag);
1024 d->localPort = bindPort;
1025 d->type = queryType;
1028 #ifndef QT_NO_BEARERMANAGEMENT
1030 Constructs a QNetworkProxyQuery with the URL \a requestUrl and
1031 sets the query type to \a queryType. The specified \a networkConfiguration
1032 is used to resolve the proxy settings.
1034 \sa protocolTag(), peerHostName(), peerPort(), networkConfiguration()
1036 QNetworkProxyQuery::QNetworkProxyQuery(const QNetworkConfiguration &networkConfiguration,
1037 const QUrl &requestUrl, QueryType queryType)
1039 d->config = networkConfiguration;
1040 d->remote = requestUrl;
1041 d->type = queryType;
1045 Constructs a QNetworkProxyQuery of type \a queryType and sets the
1046 protocol tag to be \a protocolTag. This constructor is suitable
1047 for QNetworkProxyQuery::TcpSocket queries, because it sets the
1048 peer hostname to \a hostname and the peer's port number to \a
1049 port. The specified \a networkConfiguration
1050 is used to resolve the proxy settings.
1052 \sa networkConfiguration()
1054 QNetworkProxyQuery::QNetworkProxyQuery(const QNetworkConfiguration &networkConfiguration,
1055 const QString &hostname, int port,
1056 const QString &protocolTag,
1057 QueryType queryType)
1059 d->config = networkConfiguration;
1060 d->remote.setScheme(protocolTag);
1061 d->remote.setHost(hostname);
1062 d->remote.setPort(port);
1063 d->type = queryType;
1067 Constructs a QNetworkProxyQuery of type \a queryType and sets the
1068 protocol tag to be \a protocolTag. This constructor is suitable
1069 for QNetworkProxyQuery::TcpSocket queries because it sets the
1070 local port number to \a bindPort. The specified \a networkConfiguration
1071 is used to resolve the proxy settings.
1073 Note that \a bindPort is of type quint16 to indicate the exact
1074 port number that is requested. The value of -1 (unknown) is not
1075 allowed in this context.
1077 \sa localPort(), networkConfiguration()
1079 QNetworkProxyQuery::QNetworkProxyQuery(const QNetworkConfiguration &networkConfiguration,
1080 quint16 bindPort, const QString &protocolTag,
1081 QueryType queryType)
1083 d->config = networkConfiguration;
1084 d->remote.setScheme(protocolTag);
1085 d->localPort = bindPort;
1086 d->type = queryType;
1091 Constructs a QNetworkProxyQuery object that is a copy of \a other.
1093 QNetworkProxyQuery::QNetworkProxyQuery(const QNetworkProxyQuery &other)
1099 Destroys this QNetworkProxyQuery object.
1101 QNetworkProxyQuery::~QNetworkProxyQuery()
1103 // QSharedDataPointer automatically deletes
1107 Copies the contents of \a other.
1109 QNetworkProxyQuery &QNetworkProxyQuery::operator=(const QNetworkProxyQuery &other)
1116 Returns true if this QNetworkProxyQuery object contains the same
1119 bool QNetworkProxyQuery::operator==(const QNetworkProxyQuery &other) const
1121 return d == other.d || (d && other.d && *d == *other.d);
1125 \fn bool QNetworkProxyQuery::operator!=(const QNetworkProxyQuery &other) const
1127 Returns true if this QNetworkProxyQuery object does not contain
1128 the same data as \a other.
1132 Returns the query type.
1134 QNetworkProxyQuery::QueryType QNetworkProxyQuery::queryType() const
1136 return d ? d->type : TcpSocket;
1140 Sets the query type of this object to be \a type.
1142 void QNetworkProxyQuery::setQueryType(QueryType type)
1148 Returns the port number for the outgoing request or -1 if the port
1149 number is not known.
1151 If the query type is QNetworkProxyQuery::UrlRequest, this function
1152 returns the port number of the URL being requested. In general,
1153 frameworks will fill in the port number from their default values.
1155 \sa peerHostName(), localPort(), setPeerPort()
1157 int QNetworkProxyQuery::peerPort() const
1159 return d ? d->remote.port() : -1;
1163 Sets the requested port number for the outgoing connection to be
1164 \a port. Valid values are 1 to 65535, or -1 to indicate that the
1165 remote port number is unknown.
1167 The peer port number can also be used to indicate the expected
1168 port number of an incoming connection in the case of
1169 QNetworkProxyQuery::UdpSocket or QNetworkProxyQuery::TcpServer
1172 \sa peerPort(), setPeerHostName(), setLocalPort()
1174 void QNetworkProxyQuery::setPeerPort(int port)
1176 d->remote.setPort(port);
1180 Returns the host name or IP address being of the outgoing
1181 connection being requested, or an empty string if the remote
1182 hostname is not known.
1184 If the query type is QNetworkProxyQuery::UrlRequest, this function
1185 returns the host component of the URL being requested.
1187 \sa peerPort(), localPort(), setPeerHostName()
1189 QString QNetworkProxyQuery::peerHostName() const
1191 return d ? d->remote.host() : QString();
1195 Sets the hostname of the outgoing connection being requested to \a
1196 hostname. An empty hostname can be used to indicate that the
1197 remote host is unknown.
1199 The peer host name can also be used to indicate the expected
1200 source address of an incoming connection in the case of
1201 QNetworkProxyQuery::UdpSocket or QNetworkProxyQuery::TcpServer
1204 \sa peerHostName(), setPeerPort(), setLocalPort()
1206 void QNetworkProxyQuery::setPeerHostName(const QString &hostname)
1208 d->remote.setHost(hostname);
1212 Returns the port number of the socket that will accept incoming
1213 packets from remote servers or -1 if the port is not known.
1215 \sa peerPort(), peerHostName(), setLocalPort()
1217 int QNetworkProxyQuery::localPort() const
1219 return d ? d->localPort : -1;
1223 Sets the port number that the socket wishes to use locally to
1224 accept incoming packets from remote servers to \a port. The local
1225 port is most often used with the QNetworkProxyQuery::TcpServer
1226 and QNetworkProxyQuery::UdpSocket query types.
1228 Valid values are 0 to 65535 (with 0 indicating that any port
1229 number will be acceptable) or -1, which means the local port
1230 number is unknown or not applicable.
1232 In some circumstances, for special protocols, it's the local port
1233 number can also be used with a query of type
1234 QNetworkProxyQuery::TcpSocket. When that happens, the socket is
1235 indicating it wishes to use the port number \a port when
1236 connecting to a remote host.
1238 \sa localPort(), setPeerPort(), setPeerHostName()
1240 void QNetworkProxyQuery::setLocalPort(int port)
1242 d->localPort = port;
1246 Returns the protocol tag for this QNetworkProxyQuery object, or an
1247 empty QString in case the protocol tag is unknown.
1249 In the case of queries of type QNetworkProxyQuery::UrlRequest,
1250 this function returns the value of the scheme component of the
1253 \sa setProtocolTag(), url()
1255 QString QNetworkProxyQuery::protocolTag() const
1257 return d ? d->remote.scheme() : QString();
1261 Sets the protocol tag for this QNetworkProxyQuery object to be \a
1264 The protocol tag is an arbitrary string that indicates which
1265 protocol is being talked over the socket, such as "http", "xmpp",
1266 "telnet", etc. The protocol tag is used by the backend to
1267 return a request that is more specific to the protocol in
1268 question: for example, a HTTP connection could be use a caching
1269 HTTP proxy server, while all other connections use a more powerful
1270 SOCKSv5 proxy server.
1274 void QNetworkProxyQuery::setProtocolTag(const QString &protocolTag)
1276 d->remote.setScheme(protocolTag);
1280 Returns the URL component of this QNetworkProxyQuery object in
1281 case of a query of type QNetworkProxyQuery::UrlRequest.
1285 QUrl QNetworkProxyQuery::url() const
1287 return d ? d->remote : QUrl();
1291 Sets the URL component of this QNetworkProxyQuery object to be \a
1292 url. Setting the URL will also set the protocol tag, the remote
1293 host name and port number. This is done so as to facilitate the
1294 implementation of the code that determines the proxy server to be
1297 \sa url(), peerHostName(), peerPort()
1299 void QNetworkProxyQuery::setUrl(const QUrl &url)
1304 #ifndef QT_NO_BEARERMANAGEMENT
1306 Returns the network configuration component of the query.
1308 \sa setNetworkConfiguration()
1310 QNetworkConfiguration QNetworkProxyQuery::networkConfiguration() const
1312 return d ? d->config : QNetworkConfiguration();
1316 Sets the network configuration component of this QNetworkProxyQuery
1317 object to be \a networkConfiguration. The network configuration can
1318 be used to return different proxy settings based on the network in
1319 use, for example WLAN vs cellular networks on a mobile phone.
1321 In the case of "user choice" or "service network" configurations,
1322 you should first start the QNetworkSession and obtain the active
1323 configuration from its properties.
1325 \sa networkConfiguration()
1327 void QNetworkProxyQuery::setNetworkConfiguration(const QNetworkConfiguration &networkConfiguration)
1329 d->config = networkConfiguration;
1334 \class QNetworkProxyFactory
1335 \brief The QNetworkProxyFactory class provides fine-grained proxy selection.
1341 QNetworkProxyFactory is an extension to QNetworkProxy, allowing
1342 applications to have a more fine-grained control over which proxy
1343 servers are used, depending on the socket requesting the
1344 proxy. This allows an application to apply different settings,
1345 according to the protocol or destination hostname, for instance.
1347 QNetworkProxyFactory can be set globally for an application, in
1348 which case it will override any global proxies set with
1349 QNetworkProxy::setApplicationProxy(). If set globally, any sockets
1350 created with Qt will query the factory to determine the proxy to
1353 A factory can also be set in certain frameworks that support
1354 multiple connections, such as QNetworkAccessManager. When set on
1355 such object, the factory will be queried for sockets created by
1356 that framework only.
1358 \section1 System Proxies
1360 You can configure a factory to use the system proxy's settings.
1361 Call the setUseSystemConfiguration() function with true to enable
1362 this behavior, or false to disable it.
1364 Similarly, you can use a factory to make queries directly to the
1365 system proxy by calling its systemProxyForQuery() function.
1367 \warning Depending on the configuration of the user's system, the
1368 use of system proxy features on certain platforms may be subject
1369 to limitations. The systemProxyForQuery() documentation contains a
1370 list of these limitations for those platforms that are affected.
1374 Creates a QNetworkProxyFactory object.
1376 Since QNetworkProxyFactory is an abstract class, you cannot create
1377 objects of type QNetworkProxyFactory directly.
1379 QNetworkProxyFactory::QNetworkProxyFactory()
1384 Destroys the QNetworkProxyFactory object.
1386 QNetworkProxyFactory::~QNetworkProxyFactory()
1394 Enables the use of the platform-specific proxy settings, and only those.
1395 See systemProxyForQuery() for more information.
1397 Internally, this method (when called with \a enable set to true)
1398 sets an application-wide proxy factory. For this reason, this method
1399 is mutually exclusive with setApplicationProxyFactory(): calling
1400 setApplicationProxyFactory() overrides the use of the system-wide proxy,
1401 and calling setUseSystemConfiguration() overrides any
1402 application proxy or proxy factory that was previously set.
1404 \note See the systemProxyForQuery() documentation for a list of
1405 limitations related to the use of system proxies.
1407 void QNetworkProxyFactory::setUseSystemConfiguration(bool enable)
1410 setApplicationProxyFactory(new QSystemConfigurationProxyFactory);
1412 setApplicationProxyFactory(0);
1417 Sets the application-wide proxy factory to be \a factory. This
1418 function will take ownership of that object and will delete it
1421 The application-wide proxy is used as a last-resort when all other
1422 proxy selection requests returned QNetworkProxy::DefaultProxy. For
1423 example, QTcpSocket objects can have a proxy set with
1424 QTcpSocket::setProxy, but if none is set, the proxy factory class
1425 set with this function will be queried.
1427 If you set a proxy factory with this function, any application
1428 level proxies set with QNetworkProxy::setApplicationProxy will be
1431 \sa QNetworkProxy::setApplicationProxy(),
1432 QAbstractSocket::proxy(), QAbstractSocket::setProxy()
1434 void QNetworkProxyFactory::setApplicationProxyFactory(QNetworkProxyFactory *factory)
1436 if (globalNetworkProxy())
1437 globalNetworkProxy()->setApplicationProxyFactory(factory);
1441 \fn QList<QNetworkProxy> QNetworkProxyFactory::queryProxy(const QNetworkProxyQuery &query)
1443 This function takes the query request, \a query,
1444 examines the details of the type of socket or request and returns
1445 a list of QNetworkProxy objects that indicate the proxy servers to
1446 be used, in order of preference.
1448 When reimplementing this class, take care to return at least one
1451 If you cannot determine a better proxy alternative, use
1452 QNetworkProxy::DefaultProxy, which tells the code querying for a
1453 proxy to use a higher alternative. For example, if this factory is
1454 set to a QNetworkAccessManager object, DefaultProxy will tell it
1455 to query the application-level proxy settings.
1457 If this factory is set as the application proxy factory,
1458 DefaultProxy and NoProxy will have the same meaning.
1462 \fn QList<QNetworkProxy> QNetworkProxyFactory::systemProxyForQuery(const QNetworkProxyQuery &query)
1464 This function takes the query request, \a query,
1465 examines the details of the type of socket or request and returns
1466 a list of QNetworkProxy objects that indicate the proxy servers to
1467 be used, in order of preference.
1469 This function can be used to determine the platform-specific proxy
1470 settings. This function will use the libraries provided by the
1471 operating system to determine the proxy for a given connection, if
1472 such libraries exist. If they don't, this function will just return a
1473 QNetworkProxy of type QNetworkProxy::NoProxy.
1475 On Windows, this function will use the WinHTTP DLL functions. Despite
1476 its name, Microsoft suggests using it for all applications that
1477 require network connections, not just HTTP. This will respect the
1478 proxy settings set on the registry with the proxycfg.exe tool. If
1479 those settings are not found, this function will attempt to obtain
1480 Internet Explorer's settings and use them.
1482 On MacOS X, this function will obtain the proxy settings using the
1483 SystemConfiguration framework from Apple. It will apply the FTP,
1484 HTTP and HTTPS proxy configurations for queries that contain the
1485 protocol tag "ftp", "http" and "https", respectively. If the SOCKS
1486 proxy is enabled in that configuration, this function will use the
1487 SOCKS server for all queries. If SOCKS isn't enabled, it will use
1488 the HTTPS proxy for all TcpSocket and UrlRequest queries.
1490 On other systems, this function will pick up proxy settings from
1491 the "http_proxy" environment variable. This variable must be a URL
1492 using one of the following schemes: "http", "socks5" or "socks5h".
1494 \section1 Limitations
1496 These are the limitations for the current version of this
1497 function. Future versions of Qt may lift some of the limitations
1501 \o On MacOS X, this function will ignore the Proxy Auto Configuration
1502 settings, since it cannot execute the associated ECMAScript code.
1504 \o On Windows platforms, this function may take several seconds to
1505 execute depending on the configuration of the user's system.
1510 This function takes the query request, \a query,
1511 examines the details of the type of socket or request and returns
1512 a list of QNetworkProxy objects that indicate the proxy servers to
1513 be used, in order of preference.
1515 QList<QNetworkProxy> QNetworkProxyFactory::proxyForQuery(const QNetworkProxyQuery &query)
1517 if (!globalNetworkProxy())
1518 return QList<QNetworkProxy>() << QNetworkProxy(QNetworkProxy::NoProxy);
1519 return globalNetworkProxy()->proxyForQuery(query);
1524 #endif // QT_NO_NETWORKPROXY