1 /****************************************************************************
3 ** Copyright (C) 2014 Kurt Pattyn <pattyn.kurt@gmail.com>.
4 ** Contact: http://www.qt-project.org/legal
6 ** This file is part of the QtWebSockets module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and Digia. For licensing terms and
14 ** conditions see http://qt.digia.com/licensing. For further information
15 ** use the contact form at http://qt.digia.com/contact-us.
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL included in the
21 ** packaging of this file. Please review the following information to
22 ** ensure the GNU Lesser General Public License version 2.1 requirements
23 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
25 ** In addition, as a special exception, Digia gives you certain additional
26 ** rights. These rights are described in the Digia Qt LGPL Exception
27 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
29 ** GNU General Public License Usage
30 ** Alternatively, this file may be used under the terms of the GNU
31 ** General Public License version 3.0 as published by the Free Software
32 ** Foundation and appearing in the file LICENSE.GPL included in the
33 ** packaging of this file. Please review the following information to
34 ** ensure the GNU General Public License version 3.0 requirements will be
35 ** met: http://www.gnu.org/copyleft/gpl.html.
40 ****************************************************************************/
42 #include "qwebsockethandshakeresponse_p.h"
43 #include "qwebsockethandshakerequest_p.h"
44 #include "qwebsocketprotocol.h"
45 #include "qwebsocketprotocol_p.h"
47 #include <QtCore/QString>
48 #include <QtCore/QTextStream>
49 #include <QtCore/QByteArray>
50 #include <QtCore/QStringList>
51 #include <QtCore/QDateTime>
52 #include <QtCore/QCryptographicHash>
53 #include <QtCore/QSet>
54 #include <QtCore/QList>
55 #include <QtCore/QStringBuilder> //for more efficient string concatenation
57 #include <functional> //for std::greater
64 QWebSocketHandshakeResponse::QWebSocketHandshakeResponse(
65 const QWebSocketHandshakeRequest &request,
66 const QString &serverName,
68 const QList<QWebSocketProtocol::Version> &supportedVersions,
69 const QList<QString> &supportedProtocols,
70 const QList<QString> &supportedExtensions) :
75 m_acceptedExtension(),
76 m_acceptedVersion(QWebSocketProtocol::VersionUnknown),
77 m_error(QWebSocketProtocol::CloseCodeNormal),
80 m_response = getHandshakeResponse(request, serverName,
81 isOriginAllowed, supportedVersions,
82 supportedProtocols, supportedExtensions);
89 QWebSocketHandshakeResponse::~QWebSocketHandshakeResponse()
96 bool QWebSocketHandshakeResponse::isValid() const
104 bool QWebSocketHandshakeResponse::canUpgrade() const
106 return m_isValid && m_canUpgrade;
112 QString QWebSocketHandshakeResponse::acceptedProtocol() const
114 return m_acceptedProtocol;
120 QString QWebSocketHandshakeResponse::calculateAcceptKey(const QString &key) const
122 //the UID comes from RFC6455
123 const QString tmpKey = key % QStringLiteral("258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
124 const QByteArray hash = QCryptographicHash::hash(tmpKey.toLatin1(), QCryptographicHash::Sha1);
125 return QString::fromLatin1(hash.toBase64());
131 QString QWebSocketHandshakeResponse::getHandshakeResponse(
132 const QWebSocketHandshakeRequest &request,
133 const QString &serverName,
134 bool isOriginAllowed,
135 const QList<QWebSocketProtocol::Version> &supportedVersions,
136 const QList<QString> &supportedProtocols,
137 const QList<QString> &supportedExtensions)
139 QStringList response;
140 m_canUpgrade = false;
142 if (!isOriginAllowed) {
144 m_error = QWebSocketProtocol::CloseCodePolicyViolated;
145 m_errorString = tr("Access forbidden.");
146 response << QStringLiteral("HTTP/1.1 403 Access Forbidden");
149 if (request.isValid()) {
150 const QString acceptKey = calculateAcceptKey(request.key());
151 const QList<QString> matchingProtocols =
152 supportedProtocols.toSet().intersect(request.protocols().toSet()).toList();
153 //TODO: extensions must be kept in the order in which they arrive
154 //cannot use set.intersect() to get the supported extensions
155 const QList<QString> matchingExtensions =
156 supportedExtensions.toSet().intersect(request.extensions().toSet()).toList();
157 QList<QWebSocketProtocol::Version> matchingVersions =
158 request.versions().toSet().intersect(supportedVersions.toSet()).toList();
159 std::sort(matchingVersions.begin(), matchingVersions.end(),
160 std::greater<QWebSocketProtocol::Version>()); //sort in descending order
162 if (Q_UNLIKELY(matchingVersions.isEmpty())) {
163 m_error = QWebSocketProtocol::CloseCodeProtocolError;
164 m_errorString = tr("Unsupported version requested.");
165 m_canUpgrade = false;
167 response << QStringLiteral("HTTP/1.1 101 Switching Protocols") <<
168 QStringLiteral("Upgrade: websocket") <<
169 QStringLiteral("Connection: Upgrade") <<
170 QStringLiteral("Sec-WebSocket-Accept: ") % acceptKey;
171 if (!matchingProtocols.isEmpty()) {
172 m_acceptedProtocol = matchingProtocols.first();
173 response << QStringLiteral("Sec-WebSocket-Protocol: ") % m_acceptedProtocol;
175 if (!matchingExtensions.isEmpty()) {
176 m_acceptedExtension = matchingExtensions.first();
177 response << QStringLiteral("Sec-WebSocket-Extensions: ") % m_acceptedExtension;
179 QString origin = request.origin().trimmed();
180 if (origin.contains(QStringLiteral("\r\n")) ||
181 serverName.contains(QStringLiteral("\r\n"))) {
182 m_error = QWebSocketProtocol::CloseCodeAbnormalDisconnection;
183 m_errorString = tr("One of the headers contains a newline. " \
184 "Possible attack detected.");
185 m_canUpgrade = false;
187 if (origin.isEmpty())
188 origin = QStringLiteral("*");
189 response << QStringLiteral("Server: ") % serverName <<
190 QStringLiteral("Access-Control-Allow-Credentials: false") <<
191 QStringLiteral("Access-Control-Allow-Methods: GET") <<
192 QStringLiteral("Access-Control-Allow-Headers: content-type") <<
193 QStringLiteral("Access-Control-Allow-Origin: ") % origin <<
194 QStringLiteral("Date: ") %
195 QDateTime::currentDateTimeUtc()
196 .toString(QStringLiteral("ddd, dd MMM yyyy hh:mm:ss 'GMT'"));
198 m_acceptedVersion = QWebSocketProtocol::currentVersion();
203 m_error = QWebSocketProtocol::CloseCodeProtocolError;
204 m_errorString = tr("Bad handshake request received.");
205 m_canUpgrade = false;
207 if (Q_UNLIKELY(!m_canUpgrade)) {
208 response << QStringLiteral("HTTP/1.1 400 Bad Request");
209 QStringList versions;
210 Q_FOREACH (const QWebSocketProtocol::Version &version, supportedVersions)
211 versions << QString::number(static_cast<int>(version));
212 response << QStringLiteral("Sec-WebSocket-Version: ")
213 % versions.join(QStringLiteral(", "));
216 response << QStringLiteral("\r\n"); //append empty line at end of header
217 return response.join(QStringLiteral("\r\n"));
223 QTextStream &QWebSocketHandshakeResponse::writeToStream(QTextStream &textStream) const
225 if (Q_LIKELY(!m_response.isEmpty()))
226 textStream << m_response.toLatin1().constData();
228 textStream.setStatus(QTextStream::WriteFailed);
235 QTextStream &operator <<(QTextStream &stream, const QWebSocketHandshakeResponse &response)
237 return response.writeToStream(stream);
243 QWebSocketProtocol::Version QWebSocketHandshakeResponse::acceptedVersion() const
245 return m_acceptedVersion;
251 QWebSocketProtocol::CloseCode QWebSocketHandshakeResponse::error() const
259 QString QWebSocketHandshakeResponse::errorString() const
261 return m_errorString;
267 QString QWebSocketHandshakeResponse::acceptedExtension() const
269 return m_acceptedExtension;