Skip to content

Commit 07b2697

Browse files
committed
WIP websocket to serial
1 parent 7589e53 commit 07b2697

File tree

7 files changed

+288
-9
lines changed

7 files changed

+288
-9
lines changed

ports/espressif/common-hal/hashlib/Hash.c

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,12 @@ void common_hal_hashlib_hash_digest(hashlib_hash_obj_t *self, uint8_t *data, siz
4040
return;
4141
}
4242
if (self->hash_type == MBEDTLS_SSL_HASH_SHA1) {
43+
// We copy the sha1 state so we can continue to update if needed or get
44+
// the digest a second time.
45+
mbedtls_sha1_context copy;
46+
mbedtls_sha1_clone(&copy, &self->sha1);
4347
mbedtls_sha1_finish_ret(&self->sha1, data);
48+
mbedtls_sha1_clone(&self->sha1, &copy);
4449
}
4550
}
4651

py/circuitpy_mpconfig.mk

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,9 @@ CFLAGS += -DCIRCUITPY_GIFIO=$(CIRCUITPY_GIFIO)
242242
CIRCUITPY_GNSS ?= 0
243243
CFLAGS += -DCIRCUITPY_GNSS=$(CIRCUITPY_GNSS)
244244

245+
CIRCUITPY_HASHLIB ?= $(CIRCUITPY_WEB_WORKFLOW)
246+
CFLAGS += -DCIRCUITPY_HASHLIB=$(CIRCUITPY_HASHLIB)
247+
245248
CIRCUITPY_I2CPERIPHERAL ?= $(CIRCUITPY_FULL_BUILD)
246249
CFLAGS += -DCIRCUITPY_I2CPERIPHERAL=$(CIRCUITPY_I2CPERIPHERAL)
247250

supervisor/shared/serial.c

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,10 @@
4545
#include "tusb.h"
4646
#endif
4747

48+
#if CIRCUITPY_WEB_WORKFLOW
49+
#include "supervisor/shared/web_workflow/websocket.h"
50+
#endif
51+
4852
/*
4953
* Note: DEBUG_UART currently only works on STM32 and nRF.
5054
* Enabling on another platform will cause a crash.
@@ -165,6 +169,13 @@ bool serial_connected(void) {
165169
}
166170
#endif
167171

172+
#if CIRCUITPY_WEB_WORKFLOW
173+
if (websocket_connected()) {
174+
return true;
175+
}
176+
#endif
177+
178+
168179
if (port_serial_connected()) {
169180
return true;
170181
}
@@ -195,6 +206,12 @@ char serial_read(void) {
195206
}
196207
#endif
197208

209+
#if CIRCUITPY_WEB_WORKFLOW
210+
if (websocket_available()) {
211+
return websocket_read_char();
212+
}
213+
#endif
214+
198215
#if CIRCUITPY_USB_CDC
199216
if (!usb_cdc_console_enabled()) {
200217
return -1;
@@ -229,6 +246,12 @@ bool serial_bytes_available(void) {
229246
}
230247
#endif
231248

249+
#if CIRCUITPY_WEB_WORKFLOW
250+
if (websocket_available()) {
251+
return true;
252+
}
253+
#endif
254+
232255
#if CIRCUITPY_USB_CDC
233256
if (usb_cdc_console_enabled() && tud_cdc_available() > 0) {
234257
return true;
@@ -271,6 +294,10 @@ void serial_write_substring(const char *text, uint32_t length) {
271294
ble_serial_write(text, length);
272295
#endif
273296

297+
#if CIRCUITPY_WEB_WORKFLOW
298+
websocket_write(text, length);
299+
#endif
300+
274301
#if CIRCUITPY_USB_CDC
275302
if (!usb_cdc_console_enabled()) {
276303
return;

supervisor/shared/web_workflow/web_workflow.c

Lines changed: 34 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,11 @@
3939
#include "supervisor/shared/reload.h"
4040
#include "supervisor/shared/translate/translate.h"
4141
#include "supervisor/shared/web_workflow/web_workflow.h"
42+
#include "supervisor/shared/web_workflow/websocket.h"
4243
#include "supervisor/usb.h"
4344

45+
#include "shared-bindings/hashlib/__init__.h"
46+
#include "shared-bindings/hashlib/Hash.h"
4447
#include "shared-bindings/mdns/RemoteService.h"
4548
#include "shared-bindings/mdns/Server.h"
4649
#include "shared-bindings/socketpool/__init__.h"
@@ -260,20 +263,19 @@ void supervisor_start_web_workflow(void) {
260263
active.num = -1;
261264
active.connected = false;
262265

266+
websocket_init();
267+
263268
// TODO:
264269
// GET /cp/serial.txt
265270
// - Most recent 1k of serial output.
266271
// GET /edit/
267272
// - Super basic editor
268-
// GET /ws/circuitpython
269-
// GET /ws/user
270-
// - WebSockets
271273
#endif
272274
}
273275

274276
static void _send_raw(socketpool_socket_obj_t *socket, const uint8_t *buf, int len) {
275277
int sent = -EAGAIN;
276-
while (sent == -EAGAIN) {
278+
while (sent == -EAGAIN && common_hal_socketpool_socket_get_connected(socket)) {
277279
sent = socketpool_socket_send(socket, buf, len);
278280
}
279281
if (sent < len) {
@@ -851,17 +853,39 @@ static void _reply_static(socketpool_socket_obj_t *socket, _request *request, co
851853

852854
#define _REPLY_STATIC(socket, request, filename) _reply_static(socket, request, filename, filename##_length, filename##_content_type)
853855

856+
857+
854858
static void _reply_websocket_upgrade(socketpool_socket_obj_t *socket, _request *request) {
855859
ESP_LOGI(TAG, "websocket!");
856860
// Compute accept key
861+
hashlib_hash_obj_t hash;
862+
common_hal_hashlib_new(&hash, "sha1");
863+
common_hal_hashlib_hash_update(&hash, (const uint8_t *)request->websocket_key, strlen(request->websocket_key));
864+
const char *magic_string = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
865+
common_hal_hashlib_hash_update(&hash, (const uint8_t *)magic_string, strlen(magic_string));
866+
size_t digest_size = common_hal_hashlib_hash_get_digest_size(&hash);
867+
size_t encoded_size = (digest_size + 1) * 4 / 3 + 1;
868+
uint8_t encoded_accept[encoded_size];
869+
common_hal_hashlib_hash_digest(&hash, encoded_accept, sizeof(encoded_accept));
870+
_base64_in_place((char *)encoded_accept, digest_size, encoded_size);
871+
857872
// Reply with upgrade
858-
// Copy socket state into websocket and mark given socket as closed even though it isn't actually.
873+
_send_strs(socket, "HTTP/1.1 101 Switching Protocols\r\n",
874+
"Upgrade: websocket\r\n",
875+
"Connection: Upgrade\r\n",
876+
"Sec-WebSocket-Accept: ", encoded_accept, "\r\n",
877+
"\r\n", NULL);
878+
websocket_handoff(socket);
879+
880+
ESP_LOGI(TAG, "socket upgrade done");
881+
// socket is now closed and "disconnected".
859882
}
860883

861884
static bool _reply(socketpool_socket_obj_t *socket, _request *request) {
862885
if (request->redirect) {
863886
_reply_redirect(socket, request, request->path);
864887
} else if (strlen(request->origin) > 0 && !_origin_ok(request->origin)) {
888+
ESP_LOGI(TAG, "bad origin %s", request->origin);
865889
_reply_forbidden(socket, request);
866890
} else if (memcmp(request->path, "/fs/", 4) == 0) {
867891
if (!request->authenticated) {
@@ -995,7 +1019,7 @@ static bool _reply(socketpool_socket_obj_t *socket, _request *request) {
9951019
} else if (strcmp(path, "/version.json") == 0) {
9961020
_reply_with_version_json(socket, request);
9971021
} else if (strcmp(path, "/serial/") == 0) {
998-
if (!request->authenticated) {
1022+
if (false && !request->authenticated) {
9991023
if (_api_password[0] != '\0') {
10001024
_reply_unauthorized(socket, request);
10011025
} else {
@@ -1007,7 +1031,6 @@ static bool _reply(socketpool_socket_obj_t *socket, _request *request) {
10071031
} else {
10081032
_REPLY_STATIC(socket, request, serial_html);
10091033
}
1010-
_reply_with_version_json(socket, request);
10111034
} else {
10121035
_reply_missing(socket, request);
10131036
}
@@ -1177,6 +1200,7 @@ static void _process_request(socketpool_socket_obj_t *socket, _request *request)
11771200
return;
11781201
}
11791202
bool reload = _reply(socket, request);
1203+
ESP_LOGI(TAG, "reply done");
11801204
_reset_request(request);
11811205
autoreload_resume(AUTORELOAD_SUSPEND_WEB);
11821206
if (reload) {
@@ -1194,10 +1218,12 @@ void supervisor_web_workflow_background(void) {
11941218
uint32_t port;
11951219
int newsoc = socketpool_socket_accept(&listening, (uint8_t *)&ip, &port);
11961220
if (newsoc == -EBADF) {
1221+
ESP_LOGI(TAG, "listen closed");
11971222
common_hal_socketpool_socket_close(&listening);
11981223
return;
11991224
}
12001225
if (newsoc > 0) {
1226+
ESP_LOGI(TAG, "new socket %d", newsoc);
12011227
// Close the active socket because we have another we accepted.
12021228
if (!common_hal_socketpool_socket_get_closed(&active)) {
12031229
common_hal_socketpool_socket_close(&active);
@@ -1218,6 +1244,7 @@ void supervisor_web_workflow_background(void) {
12181244

12191245
// If we have a request in progress, continue working on it.
12201246
if (common_hal_socketpool_socket_get_connected(&active)) {
1247+
ESP_LOGI(TAG, "active connected");
12211248
_process_request(&active, &active_request);
12221249
}
12231250
}
Lines changed: 179 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,179 @@
1+
/*
2+
* This file is part of the MicroPython project, http://micropython.org/
3+
*
4+
* The MIT License (MIT)
5+
*
6+
* Copyright (c) 2022 Scott Shawcroft for Adafruit Industries
7+
*
8+
* Permission is hereby granted, free of charge, to any person obtaining a copy
9+
* of this software and associated documentation files (the "Software"), to deal
10+
* in the Software without restriction, including without limitation the rights
11+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12+
* copies of the Software, and to permit persons to whom the Software is
13+
* furnished to do so, subject to the following conditions:
14+
*
15+
* The above copyright notice and this permission notice shall be included in
16+
* all copies or substantial portions of the Software.
17+
*
18+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24+
* THE SOFTWARE.
25+
*/
26+
27+
#include "supervisor/shared/web_workflow/websocket.h"
28+
29+
typedef struct {
30+
socketpool_socket_obj_t socket;
31+
uint8_t opcode;
32+
uint8_t frame_len;
33+
uint8_t payload_len_size;
34+
bool masked;
35+
uint32_t mask;
36+
size_t frame_index;
37+
size_t payload_remaining;
38+
} _websocket;
39+
40+
static _websocket cp_serial;
41+
42+
static const char *TAG = "CP websocket";
43+
44+
void websocket_init(void) {
45+
cp_serial.socket.num = -1;
46+
cp_serial.socket.connected = false;
47+
}
48+
49+
void websocket_handoff(socketpool_socket_obj_t *socket) {
50+
ESP_LOGI(TAG, "socket handed off");
51+
cp_serial.socket = *socket;
52+
// Mark the original socket object as closed without telling the lower level.
53+
socket->connected = false;
54+
socket->num = -1;
55+
ESP_LOGI(TAG, "socket hand off done");
56+
}
57+
58+
bool websocket_connected(void) {
59+
return common_hal_socketpool_socket_get_connected(&cp_serial.socket);
60+
}
61+
62+
static bool _read_byte(uint8_t *c) {
63+
int len = socketpool_socket_recv_into(&cp_serial.socket, c, 1);
64+
if (len != 1) {
65+
if (len != -EAGAIN) {
66+
ESP_LOGE(TAG, "recv error %d", len);
67+
}
68+
return false;
69+
}
70+
return true;
71+
}
72+
73+
static void _read_next_frame_header(void) {
74+
uint8_t h;
75+
if (cp_serial.frame_index == 0 && _read_byte(&h)) {
76+
cp_serial.frame_index++;
77+
cp_serial.opcode = h & 0xf;
78+
ESP_LOGI(TAG, "fin %d opcode %x", h >> 7, cp_serial.opcode);
79+
}
80+
if (cp_serial.frame_index == 1 && _read_byte(&h)) {
81+
cp_serial.frame_index++;
82+
uint8_t len = h & 0xf;
83+
cp_serial.masked = (h >> 7) == 1;
84+
if (len <= 125) {
85+
cp_serial.payload_remaining = len;
86+
cp_serial.payload_len_size = 0;
87+
} else if (len == 126) { // 16 bit length
88+
cp_serial.payload_len_size = 2;
89+
} else if (len == 127) { // 64 bit length
90+
cp_serial.payload_len_size = 8;
91+
}
92+
cp_serial.frame_len = 2 + cp_serial.payload_len_size;
93+
if (cp_serial.masked) {
94+
cp_serial.frame_len += 4;
95+
}
96+
97+
ESP_LOGI(TAG, "mask %d length %x", cp_serial.masked, len);
98+
}
99+
while (cp_serial.frame_index > 1 &&
100+
cp_serial.frame_index < (cp_serial.payload_len_size + 2) &&
101+
_read_byte(&h)) {
102+
cp_serial.frame_index++;
103+
cp_serial.payload_remaining = cp_serial.payload_remaining << 8 | c;
104+
}
105+
while (cp_serial.frame_index > (cp_serial.payload_len_size + 2) &&
106+
cp_serial.frame_index < cp_serial.frame_len &&
107+
_read_byte(&h)) {
108+
cp_serial.frame_index++;
109+
cp_serial.mask = cp_serial.mask << 8 | c;
110+
}
111+
}
112+
113+
static bool _read_next_payload_byte(uint8_t *c) {
114+
_read_next_frame_header();
115+
if (cp_serial.frame_index > cp_serial.frame_len &&
116+
cp_serial.payload_remaining > 0) {
117+
if (_read_byte(c)) {
118+
cp_serial.frame_index++;
119+
cp_serial.payload_remaining--;
120+
return true;
121+
}
122+
}
123+
return false;
124+
}
125+
126+
bool websocket_available(void) {
127+
if (!websocket_connected()) {
128+
return false;
129+
}
130+
_read_next_frame_header();
131+
return cp_serial.payload_remaining > 0 && cp_serial.frame_index >= cp_serial.frame_len;
132+
}
133+
134+
char websocket_read_char(void) {
135+
return _read_next_payload_byte();
136+
}
137+
138+
static void _send_raw(socketpool_socket_obj_t *socket, const uint8_t *buf, int len) {
139+
int sent = -EAGAIN;
140+
while (sent == -EAGAIN) {
141+
sent = socketpool_socket_send(socket, buf, len);
142+
}
143+
if (sent < len) {
144+
ESP_LOGE(TAG, "short send %d %d", sent, len);
145+
}
146+
}
147+
148+
static void _websocket_send(_websocket *ws, const char *text, size_t len) {
149+
if (!websocket_connected()) {
150+
return;
151+
}
152+
uint32_t opcode = 1;
153+
uint8_t frame_header[2];
154+
frame_header[0] = 1 << 7 | opcode;
155+
uint8_t payload_len;
156+
if (len <= 125) {
157+
payload_len = len;
158+
} else if (len < (1 << 16)) {
159+
payload_len = 126;
160+
} else {
161+
payload_len = 127;
162+
}
163+
frame_header[1] = payload_len;
164+
_send_raw(&ws->socket, (const uint8_t *)frame_header, 2);
165+
if (payload_len == 126) {
166+
_send_raw(&ws->socket, (const uint8_t *)&len, 2);
167+
} else if (payload_len == 127) {
168+
uint32_t zero = 0;
169+
// 64 bits where top four bytes are zero.
170+
_send_raw(&ws->socket, (const uint8_t *)&zero, 4);
171+
_send_raw(&ws->socket, (const uint8_t *)&len, 4);
172+
}
173+
_send_raw(&ws->socket, (const uint8_t *)text, len);
174+
ESP_LOGI(TAG, "sent over websocket: %s", text);
175+
}
176+
177+
void websocket_write(const char *text, size_t len) {
178+
_websocket_send(&cp_serial, text, len);
179+
}

0 commit comments

Comments
 (0)