summaryrefslogtreecommitdiff
path: root/src/handshakeresponse_p.cpp
blob: c59b8758c43cfac3ddadb041c5fd0b402effdf34 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
/*
QWebSockets implements the WebSocket protocol as defined in RFC 6455.
Copyright (C) 2013 Kurt Pattyn (pattyn.kurt@gmail.com)

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "handshakeresponse_p.h"
#include "handshakerequest_p.h"
#include <QString>
#include <QTextStream>
#include <QByteArray>
#include <QStringList>
#include <QDateTime>
#include <QCryptographicHash>
#include <QSet>
#include <QList>
#include <QStringBuilder>   //for more efficient string concatenation

QT_BEGIN_NAMESPACE

/*!
    \internal
 */
HandshakeResponse::HandshakeResponse(const HandshakeRequest &request,
                                     const QString &serverName,
                                     bool isOriginAllowed,
                                     const QList<QWebSocketProtocol::Version> &supportedVersions,
                                     const QList<QString> &supportedProtocols,
                                     const QList<QString> &supportedExtensions) :
    m_isValid(false),
    m_canUpgrade(false),
    m_response(),
    m_acceptedProtocol(),
    m_acceptedExtension(),
    m_acceptedVersion(QWebSocketProtocol::V_Unknow)
{
    m_response = getHandshakeResponse(request, serverName, isOriginAllowed, supportedVersions, supportedProtocols, supportedExtensions);
    m_isValid = true;
}

/*!
    \internal
 */
HandshakeResponse::~HandshakeResponse()
{
}

/*!
    \internal
 */
bool HandshakeResponse::isValid() const
{
    return m_isValid;
}

/*!
    \internal
 */
bool HandshakeResponse::canUpgrade() const
{
    return m_isValid && m_canUpgrade;
}

/*!
    \internal
 */
QString HandshakeResponse::getAcceptedProtocol() const
{
    return m_acceptedProtocol;
}

/*!
    \internal
 */
QString HandshakeResponse::calculateAcceptKey(const QString &key) const
{
    QString tmpKey = key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";	//the UID comes from RFC6455
    QByteArray hash = QCryptographicHash::hash(tmpKey.toLatin1(), QCryptographicHash::Sha1);
    return QString(hash.toBase64());
}

/*!
    \internal
 */
QString HandshakeResponse::getHandshakeResponse(const HandshakeRequest &request,
                                                const QString &serverName,
                                                bool isOriginAllowed,
                                                const QList<QWebSocketProtocol::Version> &supportedVersions,
                                                const QList<QString> &supportedProtocols,
                                                const QList<QString> &supportedExtensions)
{
    QStringList response;
    m_canUpgrade = false;

    if (!isOriginAllowed)
    {
        if (!m_canUpgrade)
        {
            response << "HTTP/1.1 403 Access Forbidden";
        }
    }
    else
    {
        if (request.isValid())
        {
            QString acceptKey = calculateAcceptKey(request.getKey());
            QList<QString> matchingProtocols = supportedProtocols.toSet().intersect(request.getProtocols().toSet()).toList();
            QList<QString> matchingExtensions = supportedExtensions.toSet().intersect(request.getExtensions().toSet()).toList();
            QList<QWebSocketProtocol::Version> matchingVersions = request.getVersions().toSet().intersect(supportedVersions.toSet()).toList();
            qStableSort(matchingVersions.begin(), matchingVersions.end(), qGreater<QWebSocketProtocol::Version>());	//sort in descending order

            if (matchingVersions.isEmpty())
            {
                m_canUpgrade = false;
            }
            else
            {
                response << "HTTP/1.1 101 Switching Protocols" <<
                            "Upgrade: websocket" <<
                            "Connection: Upgrade" <<
                            "Sec-WebSocket-Accept: " % acceptKey;
                if (!matchingProtocols.isEmpty())
                {
                    m_acceptedProtocol = matchingProtocols.first();
                    response << "Sec-WebSocket-Protocol: " % m_acceptedProtocol;
                }
                if (!matchingExtensions.isEmpty())
                {
                    m_acceptedExtension = matchingExtensions.first();
                    response << "Sec-WebSocket-Extensions: " % m_acceptedExtension;
                }
                QString origin = request.getOrigin().trimmed();
                if (origin.isEmpty())
                {
                    origin = "*";
                }
                response << "Server: " + serverName <<
                            "Access-Control-Allow-Credentials: false"		<<	//do not allow credentialed request (containing cookies)
                            "Access-Control-Allow-Methods: GET"				<<	//only GET is allowed during handshaking
                            "Access-Control-Allow-Headers: content-type"	<<	//this is OK; only the content-type header is allowed, no other headers are accepted
                            "Access-Control-Allow-Origin: " % origin		<<
                            "Date: " % QDateTime::currentDateTimeUtc().toString("ddd, dd MMM yyyy hh:mm:ss 'GMT'");

                m_acceptedVersion = QWebSocketProtocol::currentVersion();
                m_canUpgrade = true;
            }
        }
        else
        {
            m_canUpgrade = false;
        }
        if (!m_canUpgrade)
        {
            response << "HTTP/1.1 400 Bad Request";
            QStringList versions;
            Q_FOREACH(QWebSocketProtocol::Version version, supportedVersions)
            {
                versions << QString::number(static_cast<int>(version));
            }
            response << "Sec-WebSocket-Version: " % versions.join(", ");
        }
    }
    response << "\r\n";	//append empty line at end of header
    return response.join("\r\n");
}

/*!
    \internal
 */
QTextStream &HandshakeResponse::writeToStream(QTextStream &textStream) const
{
    if (!m_response.isEmpty())
    {
        textStream << m_response.toLatin1().constData();
    }
    else
    {
        textStream.setStatus(QTextStream::WriteFailed);
    }
    return textStream;
}

/*!
    \internal
 */
QTextStream &operator <<(QTextStream &stream, const HandshakeResponse &response)
{
    return response.writeToStream(stream);
}

/*!
    \internal
 */
QWebSocketProtocol::Version HandshakeResponse::getAcceptedVersion() const
{
    return m_acceptedVersion;
}

/*!
    \internal
 */
QString HandshakeResponse::getAcceptedExtension() const
{
    return m_acceptedExtension;
}

QT_END_NAMESPACE