forked from micropython/micropython
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathweb_workflow.c
More file actions
1697 lines (1538 loc) · 62 KB
/
web_workflow.c
File metadata and controls
1697 lines (1538 loc) · 62 KB
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This file is part of the CircuitPython project: https://circuitpython.org
//
// SPDX-FileCopyrightText: Copyright (c) 2022 Scott Shawcroft for Adafruit Industries
//
// SPDX-License-Identifier: MIT
// Include strchrnul()
#define _GNU_SOURCE
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "extmod/vfs.h"
#include "extmod/vfs_fat.h"
#include "genhdr/mpversion.h"
#include "py/mperrno.h"
#include "py/mpstate.h"
#include "shared-bindings/wifi/Radio.h"
#include "shared/timeutils/timeutils.h"
#include "supervisor/fatfs.h"
#include "supervisor/filesystem.h"
#include "supervisor/port.h"
#include "supervisor/shared/reload.h"
#include "supervisor/shared/web_workflow/web_workflow.h"
#include "supervisor/shared/web_workflow/websocket.h"
#include "supervisor/shared/workflow.h"
#include "shared-bindings/hashlib/__init__.h"
#include "shared-bindings/hashlib/Hash.h"
#if CIRCUITPY_FOURWIRE
#include "shared-module/displayio/__init__.h"
#endif
#if CIRCUITPY_MDNS
#include "shared-bindings/mdns/RemoteService.h"
#include "shared-bindings/mdns/Server.h"
#endif
#include "shared-bindings/microcontroller/Processor.h"
#include "shared-bindings/socketpool/Socket.h"
#include "shared-bindings/socketpool/SocketPool.h"
#if CIRCUITPY_HOSTNETWORK
#include "bindings/hostnetwork/__init__.h"
#endif
#if CIRCUITPY_WIFI
#include "shared-bindings/wifi/__init__.h"
#endif
#if CIRCUITPY_SETTINGS_TOML
#include "supervisor/shared/settings.h"
#endif
enum request_state {
STATE_METHOD,
STATE_PATH,
STATE_VERSION,
STATE_HEADER_KEY,
STATE_HEADER_VALUE,
STATE_BODY
};
typedef struct {
enum request_state state;
char method[8];
char path[256];
char destination[256];
char header_key[64];
char header_value[256];
char origin[64]; // We store the origin so we can reply back with it.
char host[64]; // We store the host to check against origin.
size_t content_length;
size_t offset;
uint64_t timestamp_ms;
bool redirect;
bool done;
bool in_progress;
bool authenticated;
bool expect;
bool json;
bool websocket;
bool new_socket;
uint32_t websocket_version;
// RFC6455 for websockets says this header should be 24 base64 characters long.
char websocket_key[24 + 1];
} _request;
#if CIRCUITPY_WIFI
static wifi_radio_error_t _wifi_status = WIFI_RADIO_ERROR_NONE;
#endif
#if CIRCUITPY_STATUS_BAR && (CIRCUITPY_WIFI || CIRCUITPY_HOSTNETWORK)
// Store various last states to compute if status bar needs an update.
static bool _last_enabled = false;
static uint32_t _last_ip = 0;
static mp_int_t _last_web_api_port = 80;
#endif
#if CIRCUITPY_STATUS_BAR && CIRCUITPY_WIFI
static wifi_radio_error_t _last_wifi_status = WIFI_RADIO_ERROR_NONE;
#endif
#if CIRCUITPY_MDNS
static mdns_server_obj_t mdns;
#endif
static mp_int_t web_api_port = 80;
static socketpool_socketpool_obj_t pool;
static socketpool_socket_obj_t listening;
static socketpool_socket_obj_t active;
static _request active_request;
static char _api_password[64];
static char web_instance_name[50];
// Store the encoded IP so we don't duplicate work.
static uint32_t _encoded_ip = 0;
static char _our_ip_encoded[4 * 4];
// in_len is the number of bytes to encode. out_len is the number of bytes we
// have to do it.
static bool _base64_in_place(char *buf, size_t in_len, size_t out_len) {
size_t triples = (((in_len - 1) / 3) + 1);
size_t encoded_len = triples * 4;
if (encoded_len + 1 > out_len) {
return false;
}
// First pass, we convert input buffer to numeric base 64 values
char *in = buf + (triples - 1) * 3;
char *out = buf + (triples - 1) * 4;
int r = in_len % 3;
int partial = 0;
if (r != 0) {
out[3] = 64;
if (r == 2) {
out[2] = (in[1] & 0x0F) << 2;
out[1] = (in[0] & 0x03) << 4 | (in[1] & 0xF0) >> 4;
} else {
out[2] = 64;
out[1] = (in[0] & 0x03) << 4;
}
out[0] = (in[0] & 0xFC) >> 2;
in -= 3;
out -= 4;
partial = 1;
}
buf[encoded_len] = '\0';
for (size_t i = 0; i < triples - partial; i++) {
out[3] = in[2] & 0x3F;
out[2] = (in[1] & 0x0F) << 2 | (in[2] & 0xC0) >> 6;
out[1] = (in[0] & 0x03) << 4 | (in[1] & 0xF0) >> 4;
out[0] = (in[0] & 0xFC) >> 2;
in -= 3;
out -= 4;
}
// Second pass, we convert number base 64 values to actual base64 ascii encoding
out = buf;
for (mp_uint_t j = 0; j < encoded_len; j++) {
if (*out < 26) {
*out += 'A';
} else if (*out < 52) {
*out += 'a' - 26;
} else if (*out < 62) {
*out += '0' - 52;
} else if (*out == 62) {
*out = '+';
} else if (*out == 63) {
*out = '/';
} else {
*out = '=';
}
out++;
}
return true;
}
static void _update_encoded_ip(uint32_t ipv4_address) {
if (_encoded_ip != ipv4_address) {
uint8_t *octets = (uint8_t *)&ipv4_address;
snprintf(_our_ip_encoded, sizeof(_our_ip_encoded), "%d.%d.%d.%d", octets[0], octets[1], octets[2], octets[3]);
_encoded_ip = ipv4_address;
}
}
static bool _get_web_workflow_ip(uint32_t *ipv4_address) {
*ipv4_address = 0;
#if CIRCUITPY_WIFI
if (!common_hal_wifi_radio_get_enabled(&common_hal_wifi_radio_obj)) {
return false;
}
*ipv4_address = wifi_radio_get_ipv4_address(&common_hal_wifi_radio_obj);
return true;
#elif CIRCUITPY_HOSTNETWORK
// hostnetwork uses the host network namespace and is reachable via localhost.
*ipv4_address = 0x0100007f; // 127.0.0.1
return true;
#else
return false;
#endif
}
#if CIRCUITPY_STATUS_BAR
static void _print_web_workflow_endpoint(void) {
mp_printf(&mp_plat_print, "%s", _our_ip_encoded);
if (web_api_port != 80) {
mp_printf(&mp_plat_print, ":%d", web_api_port);
}
}
#endif
mdns_server_obj_t *supervisor_web_workflow_mdns(mp_obj_t network_interface) {
#if CIRCUITPY_MDNS && CIRCUITPY_WIFI
if (network_interface == &common_hal_wifi_radio_obj &&
mdns.base.type == &mdns_server_type) {
return &mdns;
}
#endif
(void)network_interface;
return NULL;
}
#if CIRCUITPY_STATUS_BAR
bool supervisor_web_workflow_status_dirty(void) {
#if CIRCUITPY_WIFI || CIRCUITPY_HOSTNETWORK
uint32_t ipv4_address = 0;
bool enabled = _get_web_workflow_ip(&ipv4_address);
if (enabled != _last_enabled || ipv4_address != _last_ip || web_api_port != _last_web_api_port) {
return true;
}
#if CIRCUITPY_WIFI
if (_last_wifi_status != _wifi_status) {
return true;
}
#endif
return false;
#else
return false;
#endif
}
#endif
#if CIRCUITPY_STATUS_BAR
void supervisor_web_workflow_status(void) {
#if CIRCUITPY_WIFI || CIRCUITPY_HOSTNETWORK
uint32_t ipv4_address = 0;
_last_enabled = _get_web_workflow_ip(&ipv4_address);
_last_web_api_port = web_api_port;
if (_last_enabled) {
_update_encoded_ip(ipv4_address);
_last_ip = _encoded_ip;
if (ipv4_address != 0) {
_print_web_workflow_endpoint();
// TODO: Use these unicode to show signal strength: ▂▄▆█
return;
}
}
#if CIRCUITPY_WIFI
serial_write_compressed(MP_ERROR_TEXT("Wi-Fi: "));
_last_wifi_status = _wifi_status;
if (!_last_enabled) {
serial_write_compressed(MP_ERROR_TEXT("off"));
} else if (_wifi_status == WIFI_RADIO_ERROR_AUTH_EXPIRE ||
_wifi_status == WIFI_RADIO_ERROR_AUTH_FAIL) {
serial_write_compressed(MP_ERROR_TEXT("Authentication failure"));
} else if (_wifi_status != WIFI_RADIO_ERROR_NONE) {
mp_printf(&mp_plat_print, "%d", _wifi_status);
} else {
_last_ip = 0;
serial_write_compressed(MP_ERROR_TEXT("No IP"));
}
#endif
#else
return;
#endif
}
#endif
bool supervisor_start_web_workflow(void) {
#if CIRCUITPY_WEB_WORKFLOW && CIRCUITPY_SETTINGS_TOML && (CIRCUITPY_WIFI || CIRCUITPY_HOSTNETWORK)
#if CIRCUITPY_WIFI
mp_obj_t socketpool_radio = MP_OBJ_FROM_PTR(&common_hal_wifi_radio_obj);
#else
mp_obj_t socketpool_radio = MP_OBJ_FROM_PTR(&common_hal_hostnetwork_obj);
#endif
settings_err_t result;
#if CIRCUITPY_WIFI
char ssid[33];
char password[64];
result = settings_get_str("CIRCUITPY_WIFI_SSID", ssid, sizeof(ssid));
if (result != SETTINGS_OK || strlen(ssid) < 1) {
return false;
}
result = settings_get_str("CIRCUITPY_WIFI_PASSWORD", password, sizeof(password));
if (result == SETTINGS_ERR_NOT_FOUND) {
// if password is unspecified, assume an open network
password[0] = '\0';
} else if (result != SETTINGS_OK) {
return false;
}
if (!common_hal_wifi_radio_get_enabled(&common_hal_wifi_radio_obj)) {
common_hal_wifi_init(false);
common_hal_wifi_radio_set_enabled(&common_hal_wifi_radio_obj, true);
}
// TODO: Do our own scan so that we can find the channel we want before calling connect.
// Otherwise, connect will do a full slow scan to pick the best AP.
// We can all connect again because it will return early if we're already connected to the
// network. If we are connected to a different network, then it will disconnect before
// attempting to connect to the given network.
_wifi_status = common_hal_wifi_radio_connect(
&common_hal_wifi_radio_obj, (uint8_t *)ssid, strlen(ssid), (uint8_t *)password, strlen(password),
0, 8, NULL, 0);
if (_wifi_status != WIFI_RADIO_ERROR_NONE) {
common_hal_wifi_radio_set_enabled(&common_hal_wifi_radio_obj, false);
return false;
}
#endif
// Skip starting the workflow if we're not starting from power on or reset.
const mcu_reset_reason_t reset_reason = common_hal_mcu_processor_get_reset_reason();
if (reset_reason != RESET_REASON_POWER_ON &&
reset_reason != RESET_REASON_RESET_PIN &&
reset_reason != RESET_REASON_DEEP_SLEEP_ALARM &&
reset_reason != RESET_REASON_WATCHDOG &&
reset_reason != RESET_REASON_UNKNOWN &&
reset_reason != RESET_REASON_SOFTWARE) {
return false;
}
bool initialized = pool.base.type == &socketpool_socketpool_type;
if (!initialized) {
result = settings_get_str("CIRCUITPY_WEB_INSTANCE_NAME", web_instance_name, sizeof(web_instance_name));
if (result != SETTINGS_OK || web_instance_name[0] == '\0') {
strcpy(web_instance_name, MICROPY_HW_BOARD_NAME);
}
// (leaves new_port unchanged on any failure)
(void)settings_get_int("CIRCUITPY_WEB_API_PORT", &web_api_port);
const size_t api_password_len = sizeof(_api_password) - 1;
result = settings_get_str("CIRCUITPY_WEB_API_PASSWORD", _api_password + 1, api_password_len);
if (result == SETTINGS_OK) {
_api_password[0] = ':';
_base64_in_place(_api_password, strlen(_api_password), sizeof(_api_password) - 1);
} else { // Skip starting web-workflow when no password is passed.
return false;
}
pool.base.type = &socketpool_socketpool_type;
common_hal_socketpool_socketpool_construct(&pool, socketpool_radio);
socketpool_socket_reset(&listening);
socketpool_socket_reset(&active);
websocket_init();
}
initialized = pool.base.type == &socketpool_socketpool_type;
if (initialized) {
if (!common_hal_socketpool_socket_get_closed(&active)) {
common_hal_socketpool_socket_close(&active);
}
#if CIRCUITPY_MDNS
// Try to start MDNS if the user deinited it.
if (mdns.base.type != &mdns_server_type ||
common_hal_mdns_server_deinited(&mdns)) {
mdns_server_construct(&mdns, true);
mdns.base.type = &mdns_server_type;
if (!common_hal_mdns_server_deinited(&mdns)) {
common_hal_mdns_server_set_instance_name(&mdns, web_instance_name);
}
}
if (!common_hal_mdns_server_deinited(&mdns)) {
common_hal_mdns_server_advertise_service(&mdns, "_circuitpython", "_tcp", web_api_port, NULL, 0);
}
#endif
if (common_hal_socketpool_socket_get_closed(&listening)) {
#if CIRCUITPY_SOCKETPOOL_IPV6
socketpool_socket(&pool, SOCKETPOOL_AF_INET6, SOCKETPOOL_SOCK_STREAM, 0, &listening);
#else
socketpool_socket(&pool, SOCKETPOOL_AF_INET, SOCKETPOOL_SOCK_STREAM, 0, &listening);
#endif
common_hal_socketpool_socket_settimeout(&listening, 0);
// Bind to any ip. (Not checking for failures)
common_hal_socketpool_socket_bind(&listening, "", 0, web_api_port);
common_hal_socketpool_socket_listen(&listening, 1);
}
// Wake polling thread (maybe)
socketpool_socket_poll_resume();
return true;
}
#endif
return false;
}
void web_workflow_send_raw(socketpool_socket_obj_t *socket, bool flush, const uint8_t *buf, int len) {
int total_sent = 0;
int sent = -MP_EAGAIN;
int nodelay_ok = -1;
// When flushing, disable Nagle's combining algorithm so that buf is sent immediately.
if (flush) {
int nodelay = 1;
nodelay_ok = common_hal_socketpool_socket_setsockopt(socket, SOCKETPOOL_IPPROTO_TCP, SOCKETPOOL_TCP_NODELAY, &nodelay, sizeof(nodelay));
}
while ((sent == -MP_EAGAIN || (sent > 0 && total_sent < len)) &&
common_hal_socketpool_socket_get_connected(socket)) {
sent = socketpool_socket_send(socket, buf + total_sent, len - total_sent);
if (sent > 0) {
total_sent += sent;
if (total_sent < len) {
// Yield so that network code can run.
port_task_sleep_ms(4);
}
}
}
// Re-enable Nagle's algorithm when done sending.
if (nodelay_ok == 0) {
int nodelay = 0;
nodelay_ok = common_hal_socketpool_socket_setsockopt(socket, SOCKETPOOL_IPPROTO_TCP, SOCKETPOOL_TCP_NODELAY, &nodelay, sizeof(nodelay));
}
}
static void _print_raw(void *env, const char *str, size_t len) {
web_workflow_send_raw((socketpool_socket_obj_t *)env, false, (const uint8_t *)str, (size_t)len);
}
static void _send_str(socketpool_socket_obj_t *socket, const char *str) {
web_workflow_send_raw(socket, false, (const uint8_t *)str, strlen(str));
}
static void _send_str_maybe_flush(socketpool_socket_obj_t *socket, bool flush, const char *str) {
web_workflow_send_raw(socket, flush, (const uint8_t *)str, strlen(str));
}
static void _send_final_str(socketpool_socket_obj_t *socket, const char *str) {
web_workflow_send_raw(socket, true, (const uint8_t *)str, strlen(str));
}
// The last argument must be NULL! Otherwise, it won't stop.
static __attribute__((sentinel)) void _send_strs(socketpool_socket_obj_t *socket, ...) {
va_list ap;
va_start(ap, socket);
const char *str = va_arg(ap, const char *);
const char *next_str = va_arg(ap, const char *);
assert(str != NULL);
_send_str(socket, str);
while (next_str != NULL) {
str = next_str;
next_str = va_arg(ap, const char *);
_send_str_maybe_flush(socket, next_str == NULL, str);
}
va_end(ap);
}
static void _send_chunk(socketpool_socket_obj_t *socket, const char *chunk) {
mp_print_t _socket_print = {socket, _print_raw};
mp_printf(&_socket_print, "%X\r\n", strlen(chunk));
web_workflow_send_raw(socket, false, (const uint8_t *)chunk, strlen(chunk));
web_workflow_send_raw(socket, strlen(chunk) == 0, (const uint8_t *)"\r\n", 2);
}
static void _print_chunk(void *env, const char *str, size_t len) {
mp_print_t _socket_print = {env, _print_raw};
mp_printf(&_socket_print, "%X\r\n", len);
web_workflow_send_raw((socketpool_socket_obj_t *)env, false, (const uint8_t *)str, len);
web_workflow_send_raw((socketpool_socket_obj_t *)env, true, (const uint8_t *)"\r\n", 2);
}
// A bit of a misnomer because it sends all arguments as one chunk.
// The last argument must be NULL! Otherwise, it won't stop.
static void _send_chunks(socketpool_socket_obj_t *socket, ...) {
va_list strs_to_count;
va_start(strs_to_count, socket);
va_list strs_to_send;
va_copy(strs_to_send, strs_to_count);
size_t chunk_len = 0;
const char *str = va_arg(strs_to_count, const char *);
while (str != NULL) {
chunk_len += strlen(str);
str = va_arg(strs_to_count, const char *);
}
va_end(strs_to_count);
mp_print_t _socket_print = {socket, _print_raw};
mp_printf(&_socket_print, "%X\r\n", chunk_len);
str = va_arg(strs_to_send, const char *);
while (str != NULL) {
_send_str(socket, str);
str = va_arg(strs_to_send, const char *);
}
va_end(strs_to_send);
_send_str(socket, "\r\n");
}
static bool _endswith(const char *str, const char *suffix) {
if (str == NULL || suffix == NULL) {
return false;
}
if (strlen(suffix) > strlen(str)) {
return false;
}
return strcmp(str + (strlen(str) - strlen(suffix)), suffix) == 0;
}
const char http_scheme[] = "http://";
#define PREFIX_HTTP_LEN (sizeof(http_scheme) - 1)
static bool _origin_ok(_request *request) {
// Origin may be 'null'
if (request->origin[0] == '\0') {
return true;
}
// Origin has http prefix?
if (strncmp(request->origin, http_scheme, PREFIX_HTTP_LEN) != 0) {
// Not HTTP scheme request - ok
request->origin[0] = '\0';
return true;
}
// Host given?
if (request->host[0] != '\0') {
// OK if host and origin match (fqdn + port #)
if (strcmp(request->host, &request->origin[PREFIX_HTTP_LEN]) == 0) {
return true;
}
// DEBUG: OK if origin is 'localhost' (ignoring port #)
char *cptr = strchrnul(&request->origin[PREFIX_HTTP_LEN], ':');
char csave = *cptr; // NULL or colon
*cptr = '\0';
if (strcmp(&request->origin[PREFIX_HTTP_LEN], "localhost") == 0) {
// Restore removed colon if non-null host terminator
*cptr = csave;
return true;
}
}
// Otherwise deny request
return false;
}
static const char *OK_JSON = "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nContent-Type: application/json\r\n";
static void _cors_header(socketpool_socket_obj_t *socket, _request *request) {
_send_strs(socket,
"Access-Control-Allow-Credentials: true\r\n",
"Vary: Origin, Accept, Upgrade\r\n",
"Access-Control-Allow-Origin: ",
(request->origin[0] == '\0') ? "*" : request->origin, "\r\n", NULL);
}
static void _reply_continue(socketpool_socket_obj_t *socket, _request *request) {
_send_str(socket, "HTTP/1.1 100 Continue\r\n");
_cors_header(socket, request);
_send_final_str(socket, "\r\n");
}
static void _reply_created(socketpool_socket_obj_t *socket, _request *request) {
_send_strs(socket,
"HTTP/1.1 201 Created\r\n",
"Content-Length: 0\r\n", NULL);
_cors_header(socket, request);
_send_final_str(socket, "\r\n");
}
static void _reply_no_content(socketpool_socket_obj_t *socket, _request *request) {
_send_strs(socket,
"HTTP/1.1 204 No Content\r\n",
"Content-Length: 0\r\n", NULL);
_cors_header(socket, request);
_send_final_str(socket, "\r\n");
}
static void _reply_access_control(socketpool_socket_obj_t *socket, _request *request) {
_send_strs(socket,
"HTTP/1.1 204 No Content\r\n",
"Content-Length: 0\r\n",
"Access-Control-Expose-Headers: Access-Control-Allow-Methods\r\n",
"Access-Control-Allow-Headers: X-Timestamp, X-Destination, Content-Type, Authorization\r\n",
"Access-Control-Allow-Methods:GET, OPTIONS, PUT, DELETE, MOVE", NULL);
_send_str(socket, "\r\n");
_cors_header(socket, request);
_send_final_str(socket, "\r\n");
}
static void _reply_missing(socketpool_socket_obj_t *socket, _request *request) {
_send_strs(socket,
"HTTP/1.1 404 Not Found\r\n",
"Content-Length: 0\r\n", NULL);
_cors_header(socket, request);
_send_final_str(socket, "\r\n");
}
static void _reply_method_not_allowed(socketpool_socket_obj_t *socket, _request *request) {
_send_strs(socket,
"HTTP/1.1 405 Method Not Allowed\r\n",
"Content-Length: 0\r\n", NULL);
_cors_header(socket, request);
_send_final_str(socket, "\r\n");
}
static void _reply_forbidden(socketpool_socket_obj_t *socket, _request *request) {
_send_strs(socket,
"HTTP/1.1 403 Forbidden\r\n",
"Content-Length: 0\r\n", NULL);
_cors_header(socket, request);
_send_final_str(socket, "\r\n");
}
static void _reply_conflict(socketpool_socket_obj_t *socket, _request *request) {
_send_strs(socket,
"HTTP/1.1 409 Conflict\r\n",
"Content-Length: 19\r\n", NULL);
_cors_header(socket, request);
_send_final_str(socket, "\r\nUSB storage active.");
}
static void _reply_precondition_failed(socketpool_socket_obj_t *socket, _request *request) {
_send_strs(socket,
"HTTP/1.1 412 Precondition Failed\r\n",
"Content-Length: 0\r\n", NULL);
_cors_header(socket, request);
_send_final_str(socket, "\r\n");
}
static void _reply_payload_too_large(socketpool_socket_obj_t *socket, _request *request) {
_send_strs(socket,
"HTTP/1.1 413 Payload Too Large\r\n",
"Content-Length: 0\r\n", NULL);
_cors_header(socket, request);
_send_final_str(socket, "\r\n");
}
static void _reply_expectation_failed(socketpool_socket_obj_t *socket, _request *request) {
_send_strs(socket,
"HTTP/1.1 417 Expectation Failed\r\n",
"Content-Length: 0\r\n", NULL);
_cors_header(socket, request);
_send_final_str(socket, "\r\n");
}
static void _reply_unauthorized(socketpool_socket_obj_t *socket, _request *request) {
_send_strs(socket,
"HTTP/1.1 401 Unauthorized\r\n",
"Content-Length: 0\r\n",
"WWW-Authenticate: Basic realm=\"CircuitPython\"\r\n", NULL);
_cors_header(socket, request);
_send_final_str(socket, "\r\n");
}
static void _reply_server_error(socketpool_socket_obj_t *socket, _request *request) {
_send_strs(socket,
"HTTP/1.1 500 Internal Server Error\r\n",
"Content-Length: 0\r\n", NULL);
_cors_header(socket, request);
_send_final_str(socket, "\r\n");
}
#if CIRCUITPY_MDNS
static void _reply_redirect(socketpool_socket_obj_t *socket, _request *request, const char *path) {
int nodelay = 1;
common_hal_socketpool_socket_setsockopt(socket, SOCKETPOOL_IPPROTO_TCP, SOCKETPOOL_TCP_NODELAY, &nodelay, sizeof(nodelay));
const char *hostname = common_hal_mdns_server_get_hostname(&mdns);
_send_strs(socket,
"HTTP/1.1 307 Temporary Redirect\r\n",
"Connection: close\r\n",
"Content-Length: 0\r\n",
"Location: ", NULL);
if (request->websocket) {
_send_str(socket, "ws");
} else {
_send_str(socket, "http");
}
_send_strs(socket, "://", hostname, ".local", NULL);
if (web_api_port != 80) {
mp_print_t _socket_print = {socket, _print_raw};
mp_printf(&_socket_print, ":%d", web_api_port);
}
_send_strs(socket, path, "\r\n", NULL);
_cors_header(socket, request);
_send_final_str(socket, "\r\n");
}
#endif
static void _reply_directory_json(socketpool_socket_obj_t *socket, _request *request, fs_user_mount_t *fs_mount, FF_DIR *dir, const char *request_path, const char *path) {
FILINFO file_info;
char *fn = file_info.fname;
FRESULT res = f_readdir(dir, &file_info);
if (res != FR_OK) {
_reply_missing(socket, request);
return;
}
socketpool_socket_send(socket, (const uint8_t *)OK_JSON, strlen(OK_JSON));
_cors_header(socket, request);
_send_str(socket, "\r\n");
mp_print_t _socket_print = {socket, _print_chunk};
// Send mount info.
DWORD free_clusters = 0;
FATFS *fatfs = &fs_mount->fatfs;
f_getfree(fatfs, &free_clusters);
size_t ssize;
#if FF_MAX_SS != FF_MIN_SS
ssize = fatfs->ssize;
#else
ssize = FF_MIN_SS;
#endif
uint32_t cluster_size = fatfs->csize * ssize;
uint32_t total_clusters = fatfs->n_fatent - 2;
const char *writable = "false";
// Test to see if we can grab the write lock. USB will grab the underlying
// blockdev lock once it says it is writable. Unlock immediately since we
// aren't actually writing.
if (filesystem_lock(fs_mount)) {
filesystem_unlock(fs_mount);
writable = "true";
}
mp_printf(&_socket_print,
"{\"free\": %u, "
"\"total\": %u, "
"\"block_size\": %u, "
"\"writable\": %s, ", free_clusters, total_clusters, cluster_size, writable);
// Send file list
_send_chunk(socket, "\"files\": [");
bool first = true;
while (res == FR_OK && fn[0] != 0) {
if (!first) {
_send_chunk(socket, ",");
}
_send_chunks(socket,
"{\"name\": \"", file_info.fname, "\",",
"\"directory\": ", NULL);
if ((file_info.fattrib & AM_DIR) != 0) {
_send_chunk(socket, "true");
} else {
_send_chunk(socket, "false");
}
// We use nanoseconds past Jan 1, 1970 for consistency with BLE API and
// LittleFS.
_send_chunk(socket, ", ");
uint32_t truncated_time = timeutils_mktime(1980 + (file_info.fdate >> 9),
(file_info.fdate >> 5) & 0xf,
file_info.fdate & 0x1f,
file_info.ftime >> 11,
(file_info.ftime >> 5) & 0x3f,
(file_info.ftime & 0x1f) * 2);
// Manually append zeros to make the time nanoseconds. Support for printing 64 bit numbers
// varies across chipsets.
mp_printf(&_socket_print, "\"modified_ns\": %lu000000000, ", truncated_time);
size_t file_size = 0;
if ((file_info.fattrib & AM_DIR) == 0) {
file_size = file_info.fsize;
}
mp_printf(&_socket_print, "\"file_size\": %d }", file_size);
first = false;
res = f_readdir(dir, &file_info);
}
_send_chunk(socket, "]}");
_send_chunk(socket, "");
}
static void _reply_with_file(socketpool_socket_obj_t *socket, _request *request, const char *filename, FIL *active_file) {
uint32_t total_length = f_size(active_file);
_send_str(socket, "HTTP/1.1 200 OK\r\n");
mp_print_t _socket_print = {socket, _print_raw};
mp_printf(&_socket_print, "Content-Length: %d\r\n", total_length);
// TODO: Make this a table to save space.
if (_endswith(filename, ".txt") || _endswith(filename, ".py") || _endswith(filename, ".toml")) {
_send_strs(socket, "Content-Type:", "text/plain", ";charset=UTF-8\r\n", NULL);
} else if (_endswith(filename, ".js")) {
_send_strs(socket, "Content-Type:", "text/javascript", ";charset=UTF-8\r\n", NULL);
} else if (_endswith(filename, ".html")) {
_send_strs(socket, "Content-Type:", "text/html", ";charset=UTF-8\r\n", NULL);
} else if (_endswith(filename, ".json")) {
_send_strs(socket, "Content-Type:", "application/json", ";charset=UTF-8\r\n", NULL);
} else {
_send_strs(socket, "Content-Type:", "application/octet-stream\r\n", NULL);
}
_cors_header(socket, request);
_send_str(socket, "\r\n");
uint32_t total_read = 0;
int nodelay_ok = -1;
while (total_read < total_length) {
uint8_t data_buffer[64];
size_t quantity_read;
f_read(active_file, data_buffer, 64, &quantity_read);
total_read += quantity_read;
// When getting near the end of the file, disable Nagle's combining algorithm so that
// data is sent immediately.
if (total_length - total_read < 64) {
int nodelay = 1;
// Returns 0 when it works.
nodelay_ok = common_hal_socketpool_socket_setsockopt(socket, SOCKETPOOL_IPPROTO_TCP, SOCKETPOOL_TCP_NODELAY, &nodelay, sizeof(nodelay));
}
uint32_t send_offset = 0;
while (send_offset < quantity_read) {
int sent = socketpool_socket_send(socket, data_buffer + send_offset, quantity_read - send_offset);
if (sent < 0) {
if (sent == -MP_EAGAIN) {
sent = 0;
} else {
break;
}
}
send_offset += sent;
}
}
if (total_read < total_length) {
socketpool_socket_close(socket);
}
// Re-enable Nagle's algorithm when done sending.
if (nodelay_ok == 0) {
int nodelay = 0;
nodelay_ok = common_hal_socketpool_socket_setsockopt(socket, SOCKETPOOL_IPPROTO_TCP, SOCKETPOOL_TCP_NODELAY, &nodelay, sizeof(nodelay));
}
}
static void _reply_with_devices_json(socketpool_socket_obj_t *socket, _request *request) {
size_t total_results = 0;
#if CIRCUITPY_MDNS
mdns_remoteservice_obj_t found_devices[32];
if (!common_hal_mdns_server_deinited(&mdns)) {
total_results = mdns_server_find(&mdns, "_circuitpython", "_tcp", 1, found_devices, MP_ARRAY_SIZE(found_devices));
}
size_t count = MIN(total_results, MP_ARRAY_SIZE(found_devices));
#endif
socketpool_socket_send(socket, (const uint8_t *)OK_JSON, strlen(OK_JSON));
_cors_header(socket, request);
_send_str(socket, "\r\n");
mp_print_t _socket_print = {socket, _print_chunk};
mp_printf(&_socket_print, "{\"total\": %d, \"devices\": [", total_results);
#if CIRCUITPY_MDNS
for (size_t i = 0; i < count; i++) {
if (i > 0) {
_send_chunk(socket, ",");
}
const char *hostname = common_hal_mdns_remoteservice_get_hostname(&found_devices[i]);
const char *instance_name = common_hal_mdns_remoteservice_get_instance_name(&found_devices[i]);
int port = common_hal_mdns_remoteservice_get_port(&found_devices[i]);
uint32_t ipv4_address = mdns_remoteservice_get_ipv4_address(&found_devices[i]);
uint8_t *octets = (uint8_t *)&ipv4_address;
mp_printf(&_socket_print,
"{\"hostname\": \"%s\", "
"\"instance_name\": \"%s\", "
"\"port\": %d, "
"\"ip\": \"%d.%d.%d.%d\"}", hostname, instance_name, port, octets[0], octets[1], octets[2], octets[3]);
common_hal_mdns_remoteservice_deinit(&found_devices[i]);
}
#endif
_send_chunk(socket, "]}");
// Empty chunk signals the end of the response.
_send_chunk(socket, "");
}
static void _reply_with_version_json(socketpool_socket_obj_t *socket, _request *request) {
_send_str(socket, OK_JSON);
_cors_header(socket, request);
_send_str(socket, "\r\n");
mp_print_t _socket_print = {socket, _print_chunk};
const char *hostname = "";
const char *instance_name = "";
#if CIRCUITPY_MDNS
if (!common_hal_mdns_server_deinited(&mdns)) {
hostname = common_hal_mdns_server_get_hostname(&mdns);
instance_name = common_hal_mdns_server_get_instance_name(&mdns);
}
#endif
uint32_t ipv4_address = 0;
(void)_get_web_workflow_ip(&ipv4_address);
_update_encoded_ip(ipv4_address);
// Note: this leverages the fact that C concats consecutive string literals together.
mp_printf(&_socket_print,
"{\"web_api_version\": 4, "
"\"version\": \"" MICROPY_GIT_TAG "\", "
"\"build_date\": \"" MICROPY_BUILD_DATE "\", "
"\"board_name\": \"%s\", "
"\"mcu_name\": \"" MICROPY_HW_MCU_NAME "\", "
"\"board_id\": \"" CIRCUITPY_BOARD_ID "\", "
"\"creator_id\": %u, "
"\"creation_id\": %u, "
"\"hostname\": \"%s\", "
"\"port\": %d, ", instance_name, CIRCUITPY_CREATOR_ID, CIRCUITPY_CREATION_ID, hostname, web_api_port, _our_ip_encoded);
#if CIRCUITPY_MICROCONTROLLER && COMMON_HAL_MCU_PROCESSOR_UID_LENGTH > 0
uint8_t raw_id[COMMON_HAL_MCU_PROCESSOR_UID_LENGTH];
common_hal_mcu_processor_get_uid(raw_id);
mp_printf(&_socket_print, "\"UID\": \"");
for (uint8_t i = 0; i < COMMON_HAL_MCU_PROCESSOR_UID_LENGTH; i++) {
mp_printf(&_socket_print, "%02X", raw_id[i]);
}
mp_printf(&_socket_print, "\", ");
#endif
mp_printf(&_socket_print, "\"ip\": \"%s\"}", _our_ip_encoded);
// Empty chunk signals the end of the response.
_send_chunk(socket, "");
}
static void _reply_with_diskinfo_json(socketpool_socket_obj_t *socket, _request *request) {
_send_str(socket, OK_JSON);
_cors_header(socket, request);
_send_str(socket, "\r\n");
mp_print_t _socket_print = {socket, _print_chunk};
_send_chunk(socket, "[");
mp_vfs_mount_t *vfs = MP_STATE_VM(vfs_mount_table);
size_t i = 0;
while (vfs != NULL) {
if (i > 0) {
_send_chunk(socket, ",");
}
fs_user_mount_t *fs = MP_OBJ_TO_PTR(vfs->obj);
// Skip non-fat and non-native block file systems.
if (fs->base.type != &mp_fat_vfs_type || (fs->blockdev.flags & MP_BLOCKDEV_FLAG_NATIVE) == 0) {
vfs = vfs->next;
continue;
}
DWORD free_clusters = 0;
FATFS *fatfs = &fs->fatfs;
f_getfree(fatfs, &free_clusters);
size_t ssize;
#if FF_MAX_SS != FF_MIN_SS
ssize = fatfs->ssize;
#else
ssize = FF_MIN_SS;
#endif
size_t block_size = fatfs->csize * ssize;
size_t total_size = fatfs->n_fatent - 2;
const char *writable = "false";
if (filesystem_lock(fs)) {
filesystem_unlock(fs);
writable = "true";
}
mp_printf(&_socket_print,
"{\"root\": \"%s\", "
"\"free\": %u, "
"\"total\": %u, "
"\"block_size\": %u, "
"\"writable\": %s}", vfs->str, free_clusters, total_size, block_size, writable);
i++;
vfs = vfs->next;
}
_send_chunk(socket, "]");
// Empty chunk signals the end of the response.
_send_chunk(socket, "");
}
// FATFS has a two second timestamp resolution but the BLE API allows for nanosecond resolution.
// This function truncates the time the time to a resolution storable by FATFS and fills in the
// FATFS encoded version into fattime.
static uint64_t truncate_time(uint64_t input_time, DWORD *fattime) {
timeutils_struct_time_t tm;
uint64_t seconds_since_epoch = timeutils_seconds_since_epoch_from_nanoseconds_since_1970(input_time);
timeutils_seconds_since_epoch_to_struct_time(seconds_since_epoch, &tm);
uint64_t truncated_time = timeutils_nanoseconds_since_epoch_to_nanoseconds_since_1970((seconds_since_epoch / 2) * 2 * 1000000000);