Update copyright headers
[qt:qt.git] / demos / browser / networkaccessmanager.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2015 The Qt Company Ltd.
4 ** Contact: http://www.qt.io/licensing/
5 **
6 ** This file is part of the demonstration applications of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and The Qt Company. For licensing terms
14 ** and conditions see http://www.qt.io/terms-conditions. For further
15 ** information use the contact form at http://www.qt.io/contact-us.
16 **
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 or version 3 as published by the Free
20 ** Software Foundation and appearing in the file LICENSE.LGPLv21 and
21 ** LICENSE.LGPLv3 included in the packaging of this file. Please review the
22 ** following information to ensure the GNU Lesser General Public License
23 ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
24 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
25 **
26 ** As a special exception, The Qt Company gives you certain additional
27 ** rights. These rights are described in The Qt Company LGPL Exception
28 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
29 **
30 ** GNU General Public License Usage
31 ** Alternatively, this file may be used under the terms of the GNU
32 ** General Public License version 3.0 as published by the Free Software
33 ** Foundation and appearing in the file LICENSE.GPL included in the
34 ** packaging of this file.  Please review the following information to
35 ** ensure the GNU General Public License version 3.0 requirements will be
36 ** met: http://www.gnu.org/copyleft/gpl.html.
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include "networkaccessmanager.h"
43
44 #include "browserapplication.h"
45 #include "browsermainwindow.h"
46 #include "ui_passworddialog.h"
47 #include "ui_proxy.h"
48
49 #include <QtCore/QSettings>
50
51 #include <QtGui/QDesktopServices>
52 #include <QtGui/QDialog>
53 #include <QtGui/QMessageBox>
54 #include <QtGui/QStyle>
55 #include <QtGui/QTextDocument>
56
57 #include <QtNetwork/QAuthenticator>
58 #include <QtNetwork/QNetworkDiskCache>
59 #include <QtNetwork/QNetworkProxy>
60 #include <QtNetwork/QNetworkRequest>
61 #include <QtNetwork/QNetworkReply>
62 #include <QtNetwork/QSslError>
63
64 NetworkAccessManager::NetworkAccessManager(QObject *parent)
65     : QNetworkAccessManager(parent),
66     requestFinishedCount(0), requestFinishedFromCacheCount(0), requestFinishedPipelinedCount(0),
67     requestFinishedSecureCount(0), requestFinishedDownloadBufferCount(0)
68 {
69     connect(this, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)),
70             SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*)));
71     connect(this, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)),
72             SLOT(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)));
73     connect(this, SIGNAL(finished(QNetworkReply*)),
74             SLOT(requestFinished(QNetworkReply*)));
75 #ifndef QT_NO_OPENSSL
76     connect(this, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)),
77             SLOT(sslErrors(QNetworkReply*,QList<QSslError>)));
78 #endif
79     loadSettings();
80
81     QNetworkDiskCache *diskCache = new QNetworkDiskCache(this);
82     QString location = QDesktopServices::storageLocation(QDesktopServices::CacheLocation);
83     diskCache->setCacheDirectory(location);
84     setCache(diskCache);
85 }
86
87 QNetworkReply* NetworkAccessManager::createRequest(Operation op, const QNetworkRequest & req, QIODevice * outgoingData)
88 {
89     QNetworkRequest request = req; // copy so we can modify
90     // this is a temporary hack until we properly use the pipelining flags from QtWebkit
91     // pipeline everything! :)
92     request.setAttribute(QNetworkRequest::HttpPipeliningAllowedAttribute, true);
93     return QNetworkAccessManager::createRequest(op, request, outgoingData);
94 }
95
96 void NetworkAccessManager::requestFinished(QNetworkReply *reply)
97 {
98     requestFinishedCount++;
99
100     if (reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool() == true)
101         requestFinishedFromCacheCount++;
102
103     if (reply->attribute(QNetworkRequest::HttpPipeliningWasUsedAttribute).toBool() == true)
104         requestFinishedPipelinedCount++;
105
106     if (reply->attribute(QNetworkRequest::ConnectionEncryptedAttribute).toBool() == true)
107         requestFinishedSecureCount++;
108
109     if (reply->attribute(QNetworkRequest::DownloadBufferAttribute).isValid() == true)
110         requestFinishedDownloadBufferCount++;
111
112     if (requestFinishedCount % 10)
113         return;
114
115     double pctCached = (double(requestFinishedFromCacheCount) * 100.0/ double(requestFinishedCount));
116     double pctPipelined = (double(requestFinishedPipelinedCount) * 100.0/ double(requestFinishedCount));
117     double pctSecure = (double(requestFinishedSecureCount) * 100.0/ double(requestFinishedCount));
118     double pctDownloadBuffer = (double(requestFinishedDownloadBufferCount) * 100.0/ double(requestFinishedCount));
119
120 #ifdef QT_DEBUG
121     qDebug("STATS [%lli requests total] [%3.2f%% from cache] [%3.2f%% pipelined] [%3.2f%% SSL/TLS] [%3.2f%% Zerocopy]", requestFinishedCount, pctCached, pctPipelined, pctSecure, pctDownloadBuffer);
122 #endif
123 }
124
125 void NetworkAccessManager::loadSettings()
126 {
127     QSettings settings;
128     settings.beginGroup(QLatin1String("proxy"));
129     QNetworkProxy proxy;
130     if (settings.value(QLatin1String("enabled"), false).toBool()) {
131         if (settings.value(QLatin1String("type"), 0).toInt() == 0)
132             proxy = QNetworkProxy::Socks5Proxy;
133         else
134             proxy = QNetworkProxy::HttpProxy;
135         proxy.setHostName(settings.value(QLatin1String("hostName")).toString());
136         proxy.setPort(settings.value(QLatin1String("port"), 1080).toInt());
137         proxy.setUser(settings.value(QLatin1String("userName")).toString());
138         proxy.setPassword(settings.value(QLatin1String("password")).toString());
139     }
140     setProxy(proxy);
141 }
142
143 void NetworkAccessManager::authenticationRequired(QNetworkReply *reply, QAuthenticator *auth)
144 {
145     BrowserMainWindow *mainWindow = BrowserApplication::instance()->mainWindow();
146
147     QDialog dialog(mainWindow);
148     dialog.setWindowFlags(Qt::Sheet);
149
150     Ui::PasswordDialog passwordDialog;
151     passwordDialog.setupUi(&dialog);
152
153     passwordDialog.iconLabel->setText(QString());
154     passwordDialog.iconLabel->setPixmap(mainWindow->style()->standardIcon(QStyle::SP_MessageBoxQuestion, 0, mainWindow).pixmap(32, 32));
155
156     QString introMessage = tr("<qt>Enter username and password for \"%1\" at %2</qt>");
157     introMessage = introMessage.arg(Qt::escape(reply->url().toString())).arg(Qt::escape(reply->url().toString()));
158     passwordDialog.introLabel->setText(introMessage);
159     passwordDialog.introLabel->setWordWrap(true);
160
161     if (dialog.exec() == QDialog::Accepted) {
162         auth->setUser(passwordDialog.userNameLineEdit->text());
163         auth->setPassword(passwordDialog.passwordLineEdit->text());
164     }
165 }
166
167 void NetworkAccessManager::proxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *auth)
168 {
169     BrowserMainWindow *mainWindow = BrowserApplication::instance()->mainWindow();
170
171     QDialog dialog(mainWindow);
172     dialog.setWindowFlags(Qt::Sheet);
173
174     Ui::ProxyDialog proxyDialog;
175     proxyDialog.setupUi(&dialog);
176
177     proxyDialog.iconLabel->setText(QString());
178     proxyDialog.iconLabel->setPixmap(mainWindow->style()->standardIcon(QStyle::SP_MessageBoxQuestion, 0, mainWindow).pixmap(32, 32));
179
180     QString introMessage = tr("<qt>Connect to proxy \"%1\" using:</qt>");
181     introMessage = introMessage.arg(Qt::escape(proxy.hostName()));
182     proxyDialog.introLabel->setText(introMessage);
183     proxyDialog.introLabel->setWordWrap(true);
184
185     if (dialog.exec() == QDialog::Accepted) {
186         auth->setUser(proxyDialog.userNameLineEdit->text());
187         auth->setPassword(proxyDialog.passwordLineEdit->text());
188     }
189 }
190
191 #ifndef QT_NO_OPENSSL
192 void NetworkAccessManager::sslErrors(QNetworkReply *reply, const QList<QSslError> &error)
193 {
194     // check if SSL certificate has been trusted already
195     QString replyHost = reply->url().host() + QString(":%1").arg(reply->url().port());
196     if(! sslTrustedHostList.contains(replyHost)) {
197         BrowserMainWindow *mainWindow = BrowserApplication::instance()->mainWindow();
198
199         QStringList errorStrings;
200         for (int i = 0; i < error.count(); ++i)
201             errorStrings += error.at(i).errorString();
202         QString errors = errorStrings.join(QLatin1String("\n"));
203         int ret = QMessageBox::warning(mainWindow, QCoreApplication::applicationName(),
204                 tr("SSL Errors:\n\n%1\n\n%2\n\n"
205                         "Do you want to ignore these errors for this host?").arg(reply->url().toString()).arg(errors),
206                         QMessageBox::Yes | QMessageBox::No,
207                         QMessageBox::No);
208         if (ret == QMessageBox::Yes) {
209             reply->ignoreSslErrors();
210             sslTrustedHostList.append(replyHost);
211         }
212     }
213 }
214 #endif