Skip to content

Commit 1eb1ac1

Browse files
committed
Added random sec key generation and user agent header
1 parent 1a406a8 commit 1eb1ac1

File tree

2 files changed

+18
-6
lines changed

2 files changed

+18
-6
lines changed

mbed_lib.json

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,11 @@
55
"help": "Whether to use Mbed HTTP - if disabled, it will remove any code related to Mbed HTTP",
66
"value": true,
77
"macro_name": "MBED_WS_HAS_MBED_HTTP"
8+
},
9+
"user-agent": {
10+
"help": "User-Agent header presented to server",
11+
"value": "Mbed-WS-Client",
12+
"macro_name": "MBED_WS_USER_AGENT"
813
}
914
}
1015
}

source/ws_client_base.h

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020

2121
#include "mbed.h"
2222
#include "Socket.h"
23+
#include "mbedtls/base64.h"
2324

2425
#ifdef MBED_WS_HAS_MBED_HTTP
2526
#include "http_request.h"
@@ -42,6 +43,10 @@
4243
#define MBED_WS_PING_INTERVAL_MS 10000
4344
#endif
4445

46+
#ifndef MBED_WS_USER_AGENT
47+
#define MBED_WS_USER_AGENT "Mbed-WS-Client"
48+
#endif
49+
4550
// #define MBED_WS_DEBUG 1
4651

4752
// this library returns nsapi_error_t codes, plus these
@@ -174,22 +179,24 @@ class WebsocketClientBase {
174179
return r;
175180
}
176181

177-
// @todo: calculate new keys myself
178-
// var key = 'L159VM0TWUzyDxwJEIEzjw=='
179-
// var combined = 'L159VM0TWUzyDxwJEIEzjw==' + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
180-
// var h = require('crypto').createHash('sha1')
181-
// h.update(combined).digest('base64')
182-
183182
// This might seem weird... because we support both ws:// and wss://
184183
// but we already have a good working socket with TLS connection, and so the only thing
185184
// we do is act on that socket. So it's fine to reference HttpRequest
186185
// the TCPSocket casting is also weird, but it's just setting pointers, so it's fine for now
187186
// This might break if Mbed HTTP changes inner workings though!!
187+
188+
uint8_t randomBytes[16], wsSecKey[24];
189+
for (size_t i = 0; i < 16; i++) {
190+
randomBytes[i] = rand();
191+
}
192+
mbedtls_base64_encode(&wsSecKey[0], sizeof(wsSecKey), NULL, &randomBytes[0], sizeof(randomBytes));
193+
188194
HttpRequest* req = new HttpRequest((TCPSocket*)_socket, HTTP_GET, _url);
189195
req->set_header("Upgrade", "Websocket");
190196
req->set_header("Connection", "Upgrade");
191197
req->set_header("Sec-WebSocket-Key", "L159VM0TWUzyDxwJEIEzjw==");
192198
req->set_header("Sec-WebSocket-Version", "13");
199+
req->set_header("User-Agent", MBED_WS_USER_AGENT);
193200

194201
HttpResponse* res = req->send();
195202
if (!res) {

0 commit comments

Comments
 (0)