Move currentVersion method to private namespace
[contrib/qtwebsockets.git] / src / websockets / qwebsockethandshakeresponse.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
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/QCryptographicHash>
53 #include <QtCore/QSet>
54 #include <QtCore/QList>
55 #include <QtCore/QStringBuilder>   //for more efficient string concatenation
56
57 #include <functional>   //for std::greater
58
59 QT_BEGIN_NAMESPACE
60
61 /*!
62     \internal
63  */
64 QWebSocketHandshakeResponse::QWebSocketHandshakeResponse(
65         const QWebSocketHandshakeRequest &request,
66         const QString &serverName,
67         bool isOriginAllowed,
68         const QList<QWebSocketProtocol::Version> &supportedVersions,
69         const QList<QString> &supportedProtocols,
70         const QList<QString> &supportedExtensions) :
71     m_isValid(false),
72     m_canUpgrade(false),
73     m_response(),
74     m_acceptedProtocol(),
75     m_acceptedExtension(),
76     m_acceptedVersion(QWebSocketProtocol::VersionUnknown),
77     m_error(QWebSocketProtocol::CloseCodeNormal),
78     m_errorString()
79 {
80     m_response = getHandshakeResponse(request, serverName,
81                                       isOriginAllowed, supportedVersions,
82                                       supportedProtocols, supportedExtensions);
83     m_isValid = true;
84 }
85
86 /*!
87     \internal
88  */
89 QWebSocketHandshakeResponse::~QWebSocketHandshakeResponse()
90 {
91 }
92
93 /*!
94     \internal
95  */
96 bool QWebSocketHandshakeResponse::isValid() const
97 {
98     return m_isValid;
99 }
100
101 /*!
102     \internal
103  */
104 bool QWebSocketHandshakeResponse::canUpgrade() const
105 {
106     return m_isValid && m_canUpgrade;
107 }
108
109 /*!
110     \internal
111  */
112 QString QWebSocketHandshakeResponse::acceptedProtocol() const
113 {
114     return m_acceptedProtocol;
115 }
116
117 /*!
118     \internal
119  */
120 QString QWebSocketHandshakeResponse::calculateAcceptKey(const QString &key) const
121 {
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());
126 }
127
128 /*!
129     \internal
130  */
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)
138 {
139     QStringList response;
140     m_canUpgrade = false;
141
142     if (!isOriginAllowed) {
143         if (!m_canUpgrade) {
144             m_error = QWebSocketProtocol::CloseCodePolicyViolated;
145             m_errorString = tr("Access forbidden.");
146             response << QStringLiteral("HTTP/1.1 403 Access Forbidden");
147         }
148     } else {
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             const QList<QString> matchingExtensions =
154                     supportedExtensions.toSet().intersect(request.extensions().toSet()).toList();
155             QList<QWebSocketProtocol::Version> matchingVersions =
156                     request.versions().toSet().intersect(supportedVersions.toSet()).toList();
157             std::sort(matchingVersions.begin(), matchingVersions.end(),
158                       std::greater<QWebSocketProtocol::Version>());    //sort in descending order
159
160             if (Q_UNLIKELY(matchingVersions.isEmpty())) {
161                 m_error = QWebSocketProtocol::CloseCodeProtocolError;
162                 m_errorString = tr("Unsupported version requested.");
163                 m_canUpgrade = false;
164             } else {
165                 response << QStringLiteral("HTTP/1.1 101 Switching Protocols") <<
166                             QStringLiteral("Upgrade: websocket") <<
167                             QStringLiteral("Connection: Upgrade") <<
168                             QStringLiteral("Sec-WebSocket-Accept: ") % acceptKey;
169                 if (!matchingProtocols.isEmpty()) {
170                     m_acceptedProtocol = matchingProtocols.first();
171                     response << QStringLiteral("Sec-WebSocket-Protocol: ") % m_acceptedProtocol;
172                 }
173                 if (!matchingExtensions.isEmpty()) {
174                     m_acceptedExtension = matchingExtensions.first();
175                     response << QStringLiteral("Sec-WebSocket-Extensions: ") % m_acceptedExtension;
176                 }
177                 QString origin = request.origin().trimmed();
178                 if (origin.isEmpty())
179                     origin = QStringLiteral("*");
180                 response << QStringLiteral("Server: ") % serverName                      <<
181                             QStringLiteral("Access-Control-Allow-Credentials: false")    <<
182                             QStringLiteral("Access-Control-Allow-Methods: GET")          <<
183                             QStringLiteral("Access-Control-Allow-Headers: content-type") <<
184                             QStringLiteral("Access-Control-Allow-Origin: ") % origin     <<
185                             QStringLiteral("Date: ") %
186                                 QDateTime::currentDateTimeUtc()
187                                     .toString(QStringLiteral("ddd, dd MMM yyyy hh:mm:ss 'GMT'"));
188
189                 m_acceptedVersion = QWebSocketProtocol::currentVersion();
190                 m_canUpgrade = true;
191             }
192         } else {
193             m_error = QWebSocketProtocol::CloseCodeProtocolError;
194             m_errorString = tr("Bad handshake request received.");
195             m_canUpgrade = false;
196         }
197         if (Q_UNLIKELY(!m_canUpgrade)) {
198             response << QStringLiteral("HTTP/1.1 400 Bad Request");
199             QStringList versions;
200             Q_FOREACH (QWebSocketProtocol::Version version, supportedVersions)
201                 versions << QString::number(static_cast<int>(version));
202             response << QStringLiteral("Sec-WebSocket-Version: ")
203                                 % versions.join(QStringLiteral(", "));
204         }
205     }
206     response << QStringLiteral("\r\n");    //append empty line at end of header
207     return response.join(QStringLiteral("\r\n"));
208 }
209
210 /*!
211     \internal
212  */
213 QTextStream &QWebSocketHandshakeResponse::writeToStream(QTextStream &textStream) const
214 {
215     if (Q_LIKELY(!m_response.isEmpty()))
216         textStream << m_response.toLatin1().constData();
217     else
218         textStream.setStatus(QTextStream::WriteFailed);
219     return textStream;
220 }
221
222 /*!
223     \internal
224  */
225 QTextStream &operator <<(QTextStream &stream, const QWebSocketHandshakeResponse &response)
226 {
227     return response.writeToStream(stream);
228 }
229
230 /*!
231     \internal
232  */
233 QWebSocketProtocol::Version QWebSocketHandshakeResponse::acceptedVersion() const
234 {
235     return m_acceptedVersion;
236 }
237
238 /*!
239     \internal
240  */
241 QWebSocketProtocol::CloseCode QWebSocketHandshakeResponse::error() const
242 {
243     return m_error;
244 }
245
246 /*!
247     \internal
248  */
249 QString QWebSocketHandshakeResponse::errorString() const
250 {
251     return m_errorString;
252 }
253
254 /*!
255     \internal
256  */
257 QString QWebSocketHandshakeResponse::acceptedExtension() const
258 {
259     return m_acceptedExtension;
260 }
261
262 QT_END_NAMESPACE