89a947c169f3e5e33c8ad6541cb428dcce6116e9
[contrib/qtwebsockets.git] / src / websockets / qwebsockethandshakeresponse.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2014 Kurt Pattyn <pattyn.kurt@gmail.com>.
4 ** Contact: http://www.qt-project.org/legal
5 **
6 ** This file is part of the QtWebSockets module 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 Digia.  For licensing terms and
14 ** conditions see http://qt.digia.com/licensing.  For further information
15 ** use the contact form at http://qt.digia.com/contact-us.
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 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL included in the
21 ** packaging of this file.  Please review the following information to
22 ** ensure the GNU Lesser General Public License version 2.1 requirements
23 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24 **
25 ** In addition, as a special exception, Digia gives you certain additional
26 ** rights.  These rights are described in the Digia Qt LGPL Exception
27 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
28 **
29 ** GNU General Public License Usage
30 ** Alternatively, this file may be used under the terms of the GNU
31 ** General Public License version 3.0 as published by the Free Software
32 ** Foundation and appearing in the file LICENSE.GPL included in the
33 ** packaging of this file.  Please review the following information to
34 ** ensure the GNU General Public License version 3.0 requirements will be
35 ** met: http://www.gnu.org/copyleft/gpl.html.
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include "qwebsockethandshakeresponse_p.h"
43 #include "qwebsockethandshakerequest_p.h"
44 #include "qwebsocketprotocol.h"
45 #include "qwebsocketprotocol_p.h"
46
47 #include <QtCore/QString>
48 #include <QtCore/QTextStream>
49 #include <QtCore/QByteArray>
50 #include <QtCore/QStringList>
51 #include <QtCore/QDateTime>
52 #include <QtCore/QLocale>
53 #include <QtCore/QCryptographicHash>
54 #include <QtCore/QSet>
55 #include <QtCore/QList>
56 #include <QtCore/QStringBuilder>   //for more efficient string concatenation
57
58 #include <functional>   //for std::greater
59
60 QT_BEGIN_NAMESPACE
61
62 /*!
63     \internal
64  */
65 QWebSocketHandshakeResponse::QWebSocketHandshakeResponse(
66         const QWebSocketHandshakeRequest &request,
67         const QString &serverName,
68         bool isOriginAllowed,
69         const QList<QWebSocketProtocol::Version> &supportedVersions,
70         const QList<QString> &supportedProtocols,
71         const QList<QString> &supportedExtensions) :
72     m_isValid(false),
73     m_canUpgrade(false),
74     m_response(),
75     m_acceptedProtocol(),
76     m_acceptedExtension(),
77     m_acceptedVersion(QWebSocketProtocol::VersionUnknown),
78     m_error(QWebSocketProtocol::CloseCodeNormal),
79     m_errorString()
80 {
81     m_response = getHandshakeResponse(request, serverName,
82                                       isOriginAllowed, supportedVersions,
83                                       supportedProtocols, supportedExtensions);
84     m_isValid = true;
85 }
86
87 /*!
88     \internal
89  */
90 QWebSocketHandshakeResponse::~QWebSocketHandshakeResponse()
91 {
92 }
93
94 /*!
95     \internal
96  */
97 bool QWebSocketHandshakeResponse::isValid() const
98 {
99     return m_isValid;
100 }
101
102 /*!
103     \internal
104  */
105 bool QWebSocketHandshakeResponse::canUpgrade() const
106 {
107     return m_isValid && m_canUpgrade;
108 }
109
110 /*!
111     \internal
112  */
113 QString QWebSocketHandshakeResponse::acceptedProtocol() const
114 {
115     return m_acceptedProtocol;
116 }
117
118 /*!
119     \internal
120  */
121 QString QWebSocketHandshakeResponse::calculateAcceptKey(const QString &key) const
122 {
123     //the UID comes from RFC6455
124     const QString tmpKey = key % QStringLiteral("258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
125     const QByteArray hash = QCryptographicHash::hash(tmpKey.toLatin1(), QCryptographicHash::Sha1);
126     return QString::fromLatin1(hash.toBase64());
127 }
128
129 /*!
130     \internal
131  */
132 QString QWebSocketHandshakeResponse::getHandshakeResponse(
133         const QWebSocketHandshakeRequest &request,
134         const QString &serverName,
135         bool isOriginAllowed,
136         const QList<QWebSocketProtocol::Version> &supportedVersions,
137         const QList<QString> &supportedProtocols,
138         const QList<QString> &supportedExtensions)
139 {
140     QStringList response;
141     m_canUpgrade = false;
142
143     if (!isOriginAllowed) {
144         if (!m_canUpgrade) {
145             m_error = QWebSocketProtocol::CloseCodePolicyViolated;
146             m_errorString = tr("Access forbidden.");
147             response << QStringLiteral("HTTP/1.1 403 Access Forbidden");
148         }
149     } else {
150         if (request.isValid()) {
151             const QString acceptKey = calculateAcceptKey(request.key());
152             const QList<QString> matchingProtocols =
153                     supportedProtocols.toSet().intersect(request.protocols().toSet()).toList();
154             //TODO: extensions must be kept in the order in which they arrive
155             //cannot use set.intersect() to get the supported extensions
156             const QList<QString> matchingExtensions =
157                     supportedExtensions.toSet().intersect(request.extensions().toSet()).toList();
158             QList<QWebSocketProtocol::Version> matchingVersions =
159                     request.versions().toSet().intersect(supportedVersions.toSet()).toList();
160             std::sort(matchingVersions.begin(), matchingVersions.end(),
161                       std::greater<QWebSocketProtocol::Version>());    //sort in descending order
162
163             if (Q_UNLIKELY(matchingVersions.isEmpty())) {
164                 m_error = QWebSocketProtocol::CloseCodeProtocolError;
165                 m_errorString = tr("Unsupported version requested.");
166                 m_canUpgrade = false;
167             } else {
168                 response << QStringLiteral("HTTP/1.1 101 Switching Protocols") <<
169                             QStringLiteral("Upgrade: websocket") <<
170                             QStringLiteral("Connection: Upgrade") <<
171                             QStringLiteral("Sec-WebSocket-Accept: ") % acceptKey;
172                 if (!matchingProtocols.isEmpty()) {
173                     m_acceptedProtocol = matchingProtocols.first();
174                     response << QStringLiteral("Sec-WebSocket-Protocol: ") % m_acceptedProtocol;
175                 }
176                 if (!matchingExtensions.isEmpty()) {
177                     m_acceptedExtension = matchingExtensions.first();
178                     response << QStringLiteral("Sec-WebSocket-Extensions: ") % m_acceptedExtension;
179                 }
180                 QString origin = request.origin().trimmed();
181                 if (origin.contains(QStringLiteral("\r\n")) ||
182                         serverName.contains(QStringLiteral("\r\n"))) {
183                     m_error = QWebSocketProtocol::CloseCodeAbnormalDisconnection;
184                     m_errorString = tr("One of the headers contains a newline. " \
185                                        "Possible attack detected.");
186                     m_canUpgrade = false;
187                 } else {
188                     if (origin.isEmpty())
189                         origin = QStringLiteral("*");
190                     QDateTime datetime = QDateTime::currentDateTimeUtc();
191                     response << QStringLiteral("Server: ") % serverName                      <<
192                                 QStringLiteral("Access-Control-Allow-Credentials: false")    <<
193                                 QStringLiteral("Access-Control-Allow-Methods: GET")          <<
194                                 QStringLiteral("Access-Control-Allow-Headers: content-type") <<
195                                 QStringLiteral("Access-Control-Allow-Origin: ") % origin     <<
196                                 QStringLiteral("Date: ") % QLocale::c()
197                                     .toString(datetime, QStringLiteral("ddd, dd MMM yyyy hh:mm:ss 'GMT'"));
198
199
200                     m_acceptedVersion = QWebSocketProtocol::currentVersion();
201                     m_canUpgrade = true;
202                 }
203             }
204         } else {
205             m_error = QWebSocketProtocol::CloseCodeProtocolError;
206             m_errorString = tr("Bad handshake request received.");
207             m_canUpgrade = false;
208         }
209         if (Q_UNLIKELY(!m_canUpgrade)) {
210             response << QStringLiteral("HTTP/1.1 400 Bad Request");
211             QStringList versions;
212             Q_FOREACH (const QWebSocketProtocol::Version &version, supportedVersions)
213                 versions << QString::number(static_cast<int>(version));
214             response << QStringLiteral("Sec-WebSocket-Version: ")
215                                 % versions.join(QStringLiteral(", "));
216         }
217     }
218     response << QStringLiteral("\r\n");    //append empty line at end of header
219     return response.join(QStringLiteral("\r\n"));
220 }
221
222 /*!
223     \internal
224  */
225 QTextStream &QWebSocketHandshakeResponse::writeToStream(QTextStream &textStream) const
226 {
227     if (Q_LIKELY(!m_response.isEmpty()))
228         textStream << m_response.toLatin1().constData();
229     else
230         textStream.setStatus(QTextStream::WriteFailed);
231     return textStream;
232 }
233
234 /*!
235     \internal
236  */
237 QTextStream &operator <<(QTextStream &stream, const QWebSocketHandshakeResponse &response)
238 {
239     return response.writeToStream(stream);
240 }
241
242 /*!
243     \internal
244  */
245 QWebSocketProtocol::Version QWebSocketHandshakeResponse::acceptedVersion() const
246 {
247     return m_acceptedVersion;
248 }
249
250 /*!
251     \internal
252  */
253 QWebSocketProtocol::CloseCode QWebSocketHandshakeResponse::error() const
254 {
255     return m_error;
256 }
257
258 /*!
259     \internal
260  */
261 QString QWebSocketHandshakeResponse::errorString() const
262 {
263     return m_errorString;
264 }
265
266 /*!
267     \internal
268  */
269 QString QWebSocketHandshakeResponse::acceptedExtension() const
270 {
271     return m_acceptedExtension;
272 }
273
274 QT_END_NAMESPACE