aboutsummaryrefslogtreecommitdiffstats
path: root/src/websockets/qwebsocket_wasm_p.cpp
blob: b91d96eb1729b557ea482b734262f28d37c2ecee (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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
// Copyright (C) 2018 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include "qwebsocket_p.h"

#if QT_CONFIG(thread)
#include <QtCore/qthread.h>
#include <emscripten/threading.h>
#endif

#include <emscripten.h>
#include <emscripten/websocket.h>
#include <emscripten/val.h>

#include <QHostAddress>

static EM_BOOL q_onWebSocketErrorCallback(int eventType,
                                          const EmscriptenWebSocketErrorEvent *e,
                                          void *userData)
{
    Q_UNUSED(eventType)
    Q_UNUSED(e)

    QWebSocketPrivate *wsp = reinterpret_cast<QWebSocketPrivate *>(userData);
    Q_ASSERT (wsp);

    emit wsp->q_func()->error(wsp->error());
    return EM_FALSE;
}

static EM_BOOL q_onWebSocketCloseCallback(int eventType,
                                          const EmscriptenWebSocketCloseEvent *emCloseEvent,
                                          void *userData)
{
    Q_UNUSED(eventType)
    QWebSocketPrivate *wsp = reinterpret_cast<QWebSocketPrivate *>(userData);
    Q_ASSERT (wsp);

    wsp->setSocketClosed(emCloseEvent);
    return EM_FALSE;
}

static EM_BOOL q_onWebSocketOpenCallback(int eventType,
                                         const EmscriptenWebSocketOpenEvent *e, void *userData)
{
    Q_UNUSED(eventType)
    Q_UNUSED(e)

    QWebSocketPrivate *wsp = reinterpret_cast<QWebSocketPrivate *>(userData);
    Q_ASSERT (wsp);

    wsp->setSocketState(QAbstractSocket::ConnectedState);
    emit wsp->q_func()->connected();
    return EM_FALSE;
}

static EM_BOOL q_onWebSocketIncomingMessageCallback(int eventType,
                                                    const EmscriptenWebSocketMessageEvent *e,
                                                    void *userData)
{
    Q_UNUSED(eventType)
    QWebSocketPrivate *wsp = reinterpret_cast<QWebSocketPrivate *>(userData);
    Q_ASSERT(wsp);

    if (!e->isText) {
        QByteArray buffer(reinterpret_cast<const char *>(e->data), e->numBytes);
        if (!buffer.isEmpty())
            emit wsp->q_func()->binaryMessageReceived(buffer);
    } else {
        QString buffer = QString::fromUtf8(reinterpret_cast<const char *>(e->data), e->numBytes - 1);
        emit wsp->q_func()->textMessageReceived(buffer);
    }

    return 0;
}

qint64 QWebSocketPrivate::sendTextMessage(const QString &message)
{
    int result = 0;
    emscripten_websocket_get_ready_state(m_socketContext, &m_readyState);

    if (m_readyState == 1) {
        result = emscripten_websocket_send_utf8_text(m_socketContext, message.toUtf8());
        if (result < 0)
            emit q_func()->error(QAbstractSocket::UnknownSocketError);
    } else
        qWarning() << "Could not send message. Websocket is not open";

    return result;
}

qint64 QWebSocketPrivate::sendBinaryMessage(const QByteArray &data)
{
    int result = 0;
    emscripten_websocket_get_ready_state(m_socketContext, &m_readyState);
    if (m_readyState == 1) {
        result = emscripten_websocket_send_binary(
                m_socketContext, const_cast<void *>(reinterpret_cast<const void *>(data.constData())),
                data.size());
        if (result < 0)
            emit q_func()->error(QAbstractSocket::UnknownSocketError);
    } else
        qWarning() << "Could not send message. Websocket is not open";

    return result;
}

void QWebSocketPrivate::close(QWebSocketProtocol::CloseCode closeCode, QString reason)
{
    Q_Q(QWebSocket);
    m_closeCode = closeCode;
    m_closeReason = reason;
    Q_EMIT q->aboutToClose();
    setSocketState(QAbstractSocket::ClosingState);

    emscripten_websocket_get_ready_state(m_socketContext, &m_readyState);

    if (m_readyState == 1) {
        emscripten_websocket_close(m_socketContext, (int)closeCode, reason.toUtf8());
    }
    setSocketState(QAbstractSocket::UnconnectedState);
    emit q->disconnected();
    emscripten_websocket_get_ready_state(m_socketContext, &m_readyState);
}

void QWebSocketPrivate::open(const QNetworkRequest &request,
                             const QWebSocketHandshakeOptions &options, bool mask)
{
    Q_UNUSED(mask);
    Q_UNUSED(options)
    Q_Q(QWebSocket);

    emscripten_websocket_get_ready_state(m_socketContext, &m_readyState);

    if ((m_readyState == 1 || m_readyState == 3) && m_socketContext != 0) {
        emit q->error(QAbstractSocket::OperationError);
        return;
    }

    const QUrl url = request.url();

    emscripten::val navProtocol = emscripten::val::global("self")["location"]["protocol"];

    //  An insecure WebSocket connection may not be initiated from a page loaded over HTTPS.
    // and causes emscripten to assert
    bool isSecureContext = (navProtocol.as<std::string>().find("https") == 0);

    if (!url.isValid()
            || url.toString().contains(QStringLiteral("\r\n"))) {
        setErrorString(QWebSocket::tr("Connection refused"));
        Q_EMIT q->error(QAbstractSocket::ConnectionRefusedError);
        return;
    }
    // exception for localhost/127.0.0.1/[::1]
    // localhost has special privledges

    QHostAddress hostAddress(url.host());

    bool hostAddressIsLocal = (hostAddress == QHostAddress::LocalHost
            || hostAddress == QHostAddress::LocalHostIPv6);

    if (url.host() != QStringLiteral("localhost") && !hostAddressIsLocal) {
        if (isSecureContext && url.scheme() == QStringLiteral("ws")) {
            const QString message =
                    QWebSocket::tr("Unsupported WebSocket scheme: %1").arg(url.scheme());
        setErrorString(message);
        emit q->error(QAbstractSocket::UnsupportedSocketOperationError);
        return;
        }
    }

    EmscriptenWebSocketCreateAttributes attr;

    emscripten_websocket_init_create_attributes(&attr); // memset
    QByteArray thisUrl = url.toString(QUrl::FullyEncoded).toUtf8();
    attr.url = thisUrl.constData();

#if QT_CONFIG(thread)
    // see https://github.com/emscripten-core/emscripten/blob/main/system/include/emscripten/websocket.h
    // choose a default: create websocket on calling thread
    attr.createOnMainThread = false;
#endif
    // HTML WebSockets do not support arbitrary request headers, but
    // do support the WebSocket protocol header. This header is
    // required for some use cases like MQTT.

    // add user subprotocol options
    QStringList protocols = requestedSubProtocols();
    QByteArray secProto;
    if (!protocols.isEmpty()) {
        // comma-separated list of protocol strings, no spaces
        secProto = protocols.join(QStringLiteral(",")).toLatin1();
        attr.protocols = secProto.constData();
    }

    // create and connect
    setSocketState(QAbstractSocket::ConnectingState);
    m_socketContext = emscripten_websocket_new(&attr);

    if (m_socketContext <= 0) { // m_readyState might not be changed yet
        // error
        emit q->error(QAbstractSocket::UnknownSocketError);
        return;
    }

#if QT_CONFIG(thread)
    emscripten_websocket_set_onopen_callback_on_thread(m_socketContext, (void *)this,
                                                       q_onWebSocketOpenCallback,
                                                       (quintptr)QThread::currentThreadId());
    emscripten_websocket_set_onmessage_callback_on_thread(m_socketContext, (void *)this,
                                                          q_onWebSocketIncomingMessageCallback,
                                                          (quintptr)QThread::currentThreadId());
    emscripten_websocket_set_onerror_callback_on_thread(m_socketContext, (void *)this,
                                                        q_onWebSocketErrorCallback,
                                                        (quintptr)QThread::currentThreadId());
    emscripten_websocket_set_onclose_callback_on_thread(m_socketContext, (void *)this,
                                                        q_onWebSocketCloseCallback,
                                                        (quintptr)QThread::currentThreadId());
#else
    emscripten_websocket_set_onopen_callback(m_socketContext, (void *)this,
                                             q_onWebSocketOpenCallback);
    emscripten_websocket_set_onmessage_callback(m_socketContext, (void *)this,
                                                q_onWebSocketIncomingMessageCallback);
    emscripten_websocket_set_onerror_callback(m_socketContext, (void *)this,
                                              q_onWebSocketErrorCallback);
    emscripten_websocket_set_onclose_callback(m_socketContext, (void *)this,
                                              q_onWebSocketCloseCallback);
#endif
}

bool QWebSocketPrivate::isValid() const
{
    return (m_socketContext > 0 && m_socketState == QAbstractSocket::ConnectedState);
}

void QWebSocketPrivate::setSocketClosed(const EmscriptenWebSocketCloseEvent *emCloseEvent)
{
    Q_Q(QWebSocket);
    m_closeCode = (QWebSocketProtocol::CloseCode)emCloseEvent->code;

    m_closeReason = QString::fromUtf8(emCloseEvent->reason);

    if (m_closeReason.isEmpty()) {
        m_closeReason = closeCodeToString(m_closeCode);
    }

    if (m_socketState == QAbstractSocket::ConnectedState) {
        Q_EMIT q->aboutToClose();
        setSocketState(QAbstractSocket::ClosingState);
    }

    if (!emCloseEvent->wasClean) {
        m_errorString = QStringLiteral("The remote host closed the connection");
        emit q->error(error());
    }

    emscripten_websocket_get_ready_state(m_socketContext, &m_readyState);

    if (m_readyState == 3) { // closed
        emscripten_websocket_delete(emCloseEvent->socket);
        m_socketContext = 0;
    }
}

QString QWebSocketPrivate::closeCodeToString(QWebSocketProtocol::CloseCode code)
{
    switch (code) {
        case QWebSocketProtocol::CloseCodeNormal: return QStringLiteral("Normal closure");
        case QWebSocketProtocol::CloseCodeGoingAway: return QStringLiteral("Going away");
        case QWebSocketProtocol::CloseCodeProtocolError: return QStringLiteral("Protocol error");
        case QWebSocketProtocol::CloseCodeDatatypeNotSupported: return QStringLiteral("Unsupported data");
        case QWebSocketProtocol::CloseCodeReserved1004: return QStringLiteral("Reserved");
        case QWebSocketProtocol::CloseCodeMissingStatusCode: return QStringLiteral("No status received");
        case QWebSocketProtocol::CloseCodeAbnormalDisconnection: return QStringLiteral("Abnormal closure");
        case QWebSocketProtocol::CloseCodeWrongDatatype: return QStringLiteral("Invalid frame payload data");
        case QWebSocketProtocol::CloseCodePolicyViolated: return QStringLiteral("Policy violation");
        case QWebSocketProtocol::CloseCodeTooMuchData: return QStringLiteral("Message too big");
        case QWebSocketProtocol::CloseCodeMissingExtension: return QStringLiteral("Mandatory extension missing");
        case QWebSocketProtocol::CloseCodeBadOperation: return QStringLiteral("Internal server error");
        case QWebSocketProtocol::CloseCodeTlsHandshakeFailed: return QStringLiteral("TLS handshake failed");
    };
    return QStringLiteral("");
}