-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
enduser_setup.c
2153 lines (1800 loc) · 60.9 KB
/
enduser_setup.c
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
/*
* Copyright 2015 Robert Foss. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
* - Neither the name of the copyright holders nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Robert Foss <dev@robertfoss.se>
*
* Additions & fixes: Johny Mattsson <jmattsson@dius.com.au>
* Jason Follas <jfollas@gmail.com>
*/
#include "module.h"
#include "lauxlib.h"
#include "lmem.h"
#include "platform.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "ctype.h"
#include "user_interface.h"
#include "espconn.h"
#include "lwip/tcp.h"
#include "lwip/pbuf.h"
#include "vfs.h"
#include "task/task.h"
/* Set this to 1 to generate debug messages. Uses debug callback provided by Lua. Example: enduser_setup.start(successFn, print, print) */
#define ENDUSER_SETUP_DEBUG_ENABLE 0
/* Set this to 1 to output the contents of HTTP requests when debugging. Useful if you need it, but can get pretty noisy */
#define ENDUSER_SETUP_DEBUG_SHOW_HTTP_REQUEST 0
#define MIN(x, y) (((x) < (y)) ? (x) : (y))
#define LITLEN(strliteral) (sizeof (strliteral) -1)
#define STRINGIFY(x) #x
#define NUMLEN(x) (sizeof(STRINGIFY(x)) - 1)
#define ENDUSER_SETUP_ERR_FATAL (1 << 0)
#define ENDUSER_SETUP_ERR_NONFATAL (1 << 1)
#define ENDUSER_SETUP_ERR_NO_RETURN (1 << 2)
#define ENDUSER_SETUP_ERR_OUT_OF_MEMORY 1
#define ENDUSER_SETUP_ERR_CONNECTION_NOT_FOUND 2
#define ENDUSER_SETUP_ERR_UNKOWN_ERROR 3
#define ENDUSER_SETUP_ERR_SOCKET_ALREADY_OPEN 4
#define ENDUSER_SETUP_ERR_MAX_NUMBER 5
#define ENDUSER_SETUP_ERR_ALREADY_INITIALIZED 6
/**
* DNS Response Packet:
*
* |DNS ID - 16 bits|
* |dns_header|
* |QNAME|
* |dns_body|
* |ip - 32 bits|
*
* DNS Header Part | FLAGS | | Q COUNT | | A CNT | |AUTH CNT| | ADD CNT| */
static const char dns_header[] = { 0x80, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00 };
/* DNS Query Part | Q TYPE | | Q CLASS| */
static const char dns_body[] = { 0x00, 0x01, 0x00, 0x01,
/* DNS Answer Part |LBL OFFS| | TYPE | | CLASS | | TTL | | RD LEN | */
0xC0, 0x0C, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x78, 0x00, 0x04 };
static const char http_html_gz_filename[] = "enduser_setup.html.gz";
static const char http_html_filename[] = "enduser_setup.html";
static const char http_header_200[] = "HTTP/1.1 200 OK\r\nCache-control:no-cache\r\nConnection:close\r\nContent-Type:text/html; charset=utf-8\r\n"; /* Note single \r\n here! */
static const char http_header_204[] = "HTTP/1.1 204 No Content\r\nContent-Length:0\r\nConnection:close\r\n\r\n";
static const char http_header_302[] = "HTTP/1.1 302 Moved\r\nLocation: http://nodemcu.portal/\r\nContent-Length:0\r\nConnection:close\r\n\r\n";
static const char http_header_302_trying[] = "HTTP/1.1 302 Moved\r\nLocation: /?trying=true\r\nContent-Length:0\r\nConnection:close\r\n\r\n";
static const char http_header_400[] = "HTTP/1.1 400 Bad request\r\nContent-Length:0\r\nConnection:close\r\n\r\n";
static const char http_header_404[] = "HTTP/1.1 404 Not found\r\nContent-Length:10\r\nConnection:close\r\n\r\nNot found\n";
static const char http_header_405[] = "HTTP/1.1 405 Method Not Allowed\r\nContent-Length:0\r\nConnection:close\r\n\r\n";
static const char http_header_500[] = "HTTP/1.1 500 Internal Error\r\nContent-Length:6\r\nConnection:close\r\n\r\nError\n";
static const char http_header_content_len_fmt[] = "Content-length:%5d\r\n\r\n";
static const char http_html_gzip_contentencoding[] = "Content-Encoding: gzip\r\n";
/* Externally defined: static const char enduser_setup_html_default[] = ... */
#include "enduser_setup/enduser_setup.html.gz.def.h"
// The tcp_arg can be either a pointer to the scan_listener_t or http_request_buffer_t.
// The enum defines which one it is.
typedef enum {
SCAN_LISTENER_STRUCT_TYPE = 1,
HTTP_REQUEST_BUFFER_STRUCT_TYPE = 2
} struct_type_t;
typedef struct {
struct_type_t struct_type;
} tcp_arg_t;
typedef struct scan_listener
{
struct_type_t struct_type;
struct tcp_pcb *conn;
struct scan_listener *next;
} scan_listener_t;
typedef struct {
struct_type_t struct_type;
size_t length;
char data[0];
} http_request_buffer_t;
typedef struct
{
struct espconn *espconn_dns_udp;
struct tcp_pcb *http_pcb;
char *http_payload_data;
uint32_t http_payload_len;
char *ap_ssid;
os_timer_t check_station_timer;
os_timer_t shutdown_timer;
int lua_connected_cb_ref;
int lua_err_cb_ref;
int lua_dbg_cb_ref;
scan_listener_t *scan_listeners;
uint8_t softAPchannel;
uint8_t success;
uint8_t callbackDone;
uint8_t lastStationStatus;
uint8_t connecting;
} enduser_setup_state_t;
static enduser_setup_state_t *state;
static bool manual = false;
static task_handle_t do_station_cfg_handle;
static int enduser_setup_manual(lua_State* L);
static int enduser_setup_start(lua_State* L);
static int enduser_setup_stop(lua_State* L);
static void enduser_setup_stop_callback(void *ptr);
static void enduser_setup_station_start(void);
static void enduser_setup_ap_start(void);
static void enduser_setup_ap_stop(void);
static void enduser_setup_check_station(void *p);
static void enduser_setup_debug(int line, const char *str);
static char ipaddr[16];
#if ENDUSER_SETUP_DEBUG_ENABLE
#define ENDUSER_SETUP_DEBUG(str) enduser_setup_debug(__LINE__, str)
#else
#define ENDUSER_SETUP_DEBUG(str) do {} while(0)
#endif
#define ENDUSER_SETUP_ERROR(str, err, err_severity) \
do { \
ENDUSER_SETUP_DEBUG(str); \
if (err_severity & ENDUSER_SETUP_ERR_FATAL) enduser_setup_stop(lua_getstate());\
enduser_setup_error(__LINE__, str, err);\
if (!(err_severity & ENDUSER_SETUP_ERR_NO_RETURN)) \
return err; \
} while (0)
#define ENDUSER_SETUP_ERROR_VOID(str, err, err_severity) \
do { \
ENDUSER_SETUP_DEBUG(str); \
if (err_severity & ENDUSER_SETUP_ERR_FATAL) enduser_setup_stop(lua_getstate());\
enduser_setup_error(__LINE__, str, err);\
if (!(err_severity & ENDUSER_SETUP_ERR_NO_RETURN)) \
return; \
} while (0)
static void enduser_setup_debug(int line, const char *str)
{
lua_State *L = lua_getstate();
if(state != NULL && state->lua_dbg_cb_ref != LUA_NOREF)
{
lua_rawgeti(L, LUA_REGISTRYINDEX, state->lua_dbg_cb_ref);
lua_pushfstring(L, "%d: \t%s", line, str);
luaL_pcallx(L, 1, 0);
}
}
static void enduser_setup_error(int line, const char *str, int err)
{
ENDUSER_SETUP_DEBUG("enduser_setup_error");
lua_State *L = lua_getstate();
if (state != NULL && state->lua_err_cb_ref != LUA_NOREF)
{
lua_rawgeti (L, LUA_REGISTRYINDEX, state->lua_err_cb_ref);
lua_pushinteger(L, err);
lua_pushfstring(L, "%d: \t%s", line, str);
luaL_pcallx (L, 2, 0);
}
}
static void enduser_setup_connected_callback()
{
ENDUSER_SETUP_DEBUG("enduser_setup_connected_callback");
lua_State *L = lua_getstate();
if (state != NULL && state->lua_connected_cb_ref != LUA_NOREF)
{
lua_rawgeti(L, LUA_REGISTRYINDEX, state->lua_connected_cb_ref);
luaL_pcallx(L, 0, 0);
}
}
#include "pm/swtimer.h"
static void enduser_setup_check_station_start(void)
{
ENDUSER_SETUP_DEBUG("enduser_setup_check_station_start");
os_timer_setfn(&(state->check_station_timer), enduser_setup_check_station, NULL);
SWTIMER_REG_CB(enduser_setup_check_station, SWTIMER_RESUME);
//The function enduser_setup_check_station checks for a successful connection to the configured AP
//My guess: I'm not sure about whether or not user feedback is given via the web interface, but I don't see a problem with letting this timer resume.
os_timer_arm(&(state->check_station_timer), 3*1000, TRUE);
}
static void enduser_setup_check_station_stop(void)
{
ENDUSER_SETUP_DEBUG("enduser_setup_check_station_stop");
if (state != NULL)
{
os_timer_disarm(&(state->check_station_timer));
}
}
/**
* Check Station
*
* Check that we've successfully entered station mode.
*/
static void enduser_setup_check_station(void *p)
{
ENDUSER_SETUP_DEBUG("enduser_setup_check_station");
(void)p;
struct ip_info ip;
memset(&ip, 0, sizeof(struct ip_info));
wifi_get_ip_info(STATION_IF, &ip);
int i;
char has_ip = 0;
for (i = 0; i < sizeof(struct ip_info); ++i)
{
has_ip |= ((char *) &ip)[i];
}
uint8_t currChan = wifi_get_channel();
if (has_ip == 0)
{
/* No IP Address yet, so check the reported status */
uint8_t curr_status = wifi_station_get_connect_status();
char buf[20];
sprintf(buf, "status=%d,chan=%d", curr_status, currChan);
ENDUSER_SETUP_DEBUG(buf);
if (curr_status == 2 || curr_status == 3 || curr_status == 4)
{
state->connecting = 0;
/* If the status is an error status and the channel changed, then cache the
* status to state since the Station won't be able to report the same status
* after switching the channel back to the SoftAP's
*/
if (currChan != state->softAPchannel) {
state->lastStationStatus = curr_status;
ENDUSER_SETUP_DEBUG("Turning off Station due to different channel than AP");
wifi_station_disconnect();
wifi_set_opmode(SOFTAP_MODE);
enduser_setup_ap_start();
}
}
return;
}
sprintf (ipaddr, "%d.%d.%d.%d", IP2STR(&ip.ip.addr));
state->success = 1;
state->lastStationStatus = 5; /* We have an IP Address, so the status is 5 (as of SDK 1.5.1) */
state->connecting = 0;
#if ENDUSER_SETUP_DEBUG_ENABLE
char debuginfo[100];
sprintf(debuginfo, "AP_CHAN: %d, STA_CHAN: %d", state->softAPchannel, currChan);
ENDUSER_SETUP_DEBUG(debuginfo);
#endif
if (currChan == state->softAPchannel)
{
enduser_setup_connected_callback();
state->callbackDone = 1;
}
else
{
ENDUSER_SETUP_DEBUG("Turning off Station due to different channel than AP");
wifi_station_disconnect();
wifi_set_opmode(SOFTAP_MODE);
enduser_setup_ap_start();
}
enduser_setup_check_station_stop();
/* Trigger shutdown, but allow time for HTTP client to fetch last status. */
if (!manual)
{
os_timer_setfn(&(state->shutdown_timer), enduser_setup_stop_callback, NULL);
SWTIMER_REG_CB(enduser_setup_stop_callback, SWTIMER_RESUME);
//The function enduser_setup_stop_callback frees services and resources used by enduser setup.
//My guess: Since it would lead to a memory leak, it's probably best to resume this timer.
os_timer_arm(&(state->shutdown_timer), 10*1000, FALSE);
}
}
/* --- Connection closing handling ----------------------------------------- */
/* It is far more memory efficient to let the other end close the connection
* first and respond to that, than us initiating the closing. The latter
* seems to leave the pcb in a fin_wait state for a long time, which can
* starve us of memory over time.
*
* By instead using the poll function to schedule a hard abort a few seconds
* from now we achieve a deadline close. The downside is a (very) slight
* risk of dropping the connection early, but in this application that's
* hidden by the retries on the JavaScript side anyway.
*/
/* Callback on timeout to hard-close a connection */
static err_t force_abort (void *arg, struct tcp_pcb *pcb)
{
ENDUSER_SETUP_DEBUG("force_abort");
(void)arg;
tcp_poll (pcb, 0, 0);
tcp_abort (pcb);
return ERR_ABRT;
}
/* Callback to detect a remote-close of a connection */
static err_t handle_remote_close (void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err)
{
ENDUSER_SETUP_DEBUG("handle_remote_close");
(void)arg; (void)err;
if (p) /* server sent us data, just ACK and move on */
{
tcp_recved (pcb, p->tot_len);
pbuf_free (p);
}
else /* hey, remote end closed, we can do a soft close safely, yay! */
{
tcp_recv (pcb, 0);
tcp_poll (pcb, 0, 0);
tcp_close (pcb);
}
return ERR_OK;
}
/* Set up a deferred close of a connection, as discussed above. */
static inline void deferred_close (struct tcp_pcb *pcb)
{
ENDUSER_SETUP_DEBUG("deferred_close");
tcp_poll (pcb, force_abort, 15); /* ~3sec from now */
tcp_recv (pcb, handle_remote_close);
tcp_sent (pcb, 0);
}
/* Convenience function to queue up a close-after-send. */
static err_t close_once_sent (void *arg, struct tcp_pcb *pcb, u16_t len)
{
ENDUSER_SETUP_DEBUG("close_once_sent");
(void)arg; (void)len;
deferred_close (pcb);
return ERR_OK;
}
/* ------------------------------------------------------------------------- */
/**
* Get length of param value
*
* This is being called with a fragment of the parameters passed in the
* URL for GET requests or part of the body of a POST request.
* The string will look like one of these
* "SecretPassword HTTP/1.1"
* "SecretPassword&wifi_ssid=..."
* "SecretPassword"
* The string is searched for the first occurence of deliemiter '&' or ' '.
* If found return the length up to that position.
* If not found return the length of the string.
*
*/
static int enduser_setup_get_lenth_of_param_value(const char *str)
{
char *found = strpbrk (str, "& ");
if (!found)
{
return strlen(str);
}
else
{
return found - str;
}
}
/**
* Load HTTP Payload
*
* @return - 0 if payload loaded successfully
* 1 if default html was loaded
* 2 if out of memory
*/
static int enduser_setup_http_load_payload(void)
{
ENDUSER_SETUP_DEBUG("enduser_setup_http_load_payload");
int err = VFS_RES_ERR;
int err2 = VFS_RES_ERR;
int file_len = 0;
/* Try to open enduser_setup.html.gz from SPIFFS first */
int f = vfs_open(http_html_gz_filename, "r");
if (f)
{
err = vfs_lseek(f, 0, VFS_SEEK_END);
file_len = (int) vfs_tell(f);
err2 = vfs_lseek(f, 0, VFS_SEEK_SET);
}
if (!f || err == VFS_RES_ERR || err2 == VFS_RES_ERR)
{
if (f)
{
vfs_close(f);
}
/* If that didn't work, try to open enduser_setup.html from SPIFFS */
f = vfs_open(http_html_filename, "r");
if (f)
{
err = vfs_lseek(f, 0, VFS_SEEK_END);
file_len = (int) vfs_tell(f);
err2 = vfs_lseek(f, 0, VFS_SEEK_SET);
}
}
char cl_hdr[30];
size_t ce_len = 0;
sprintf(cl_hdr, http_header_content_len_fmt, file_len);
size_t cl_len = strlen(cl_hdr);
if (!f || err == VFS_RES_ERR || err2 == VFS_RES_ERR)
{
ENDUSER_SETUP_DEBUG("Unable to load file enduser_setup.html, loading default HTML...");
if (f)
{
vfs_close(f);
}
sprintf(cl_hdr, http_header_content_len_fmt, sizeof(enduser_setup_html_default));
cl_len = strlen(cl_hdr);
int html_len = LITLEN(enduser_setup_html_default);
if (enduser_setup_html_default[0] == 0x1f && enduser_setup_html_default[1] == 0x8b)
{
ce_len = strlen(http_html_gzip_contentencoding);
html_len = enduser_setup_html_default_len; /* Defined in enduser_setup/enduser_setup.html.gz.def.h by xxd -i */
ENDUSER_SETUP_DEBUG("Content is gzipped");
}
int payload_len = LITLEN(http_header_200) + cl_len + ce_len + html_len;
state->http_payload_len = payload_len;
state->http_payload_data = (char *) malloc(payload_len);
if (state->http_payload_data == NULL)
{
return 2;
}
int offset = 0;
memcpy(&(state->http_payload_data[offset]), &(http_header_200), LITLEN(http_header_200));
offset += LITLEN(http_header_200);
if (ce_len > 0)
{
offset += sprintf(state->http_payload_data + offset, http_html_gzip_contentencoding, ce_len);
}
memcpy(&(state->http_payload_data[offset]), &(cl_hdr), cl_len);
offset += cl_len;
memcpy(&(state->http_payload_data[offset]), &(enduser_setup_html_default), sizeof(enduser_setup_html_default));
return 1;
}
char magic[2];
vfs_read(f, magic, 2);
if (magic[0] == 0x1f && magic[1] == 0x8b)
{
ce_len = strlen(http_html_gzip_contentencoding);
ENDUSER_SETUP_DEBUG("Content is gzipped");
}
int payload_len = LITLEN(http_header_200) + cl_len + ce_len + file_len;
state->http_payload_len = payload_len;
state->http_payload_data = (char *) malloc(payload_len);
if (state->http_payload_data == NULL)
{
return 2;
}
vfs_lseek(f, 0, VFS_SEEK_SET);
int offset = 0;
memcpy(&(state->http_payload_data[offset]), &(http_header_200), LITLEN(http_header_200));
offset += LITLEN(http_header_200);
if (ce_len > 0)
{
offset += sprintf(state->http_payload_data + offset, http_html_gzip_contentencoding, ce_len);
}
memcpy(&(state->http_payload_data[offset]), &(cl_hdr), cl_len);
offset += cl_len;
vfs_read(f, &(state->http_payload_data[offset]), file_len);
vfs_close(f);
return 0;
}
/**
* De-escape URL data
*
* Parse escaped and form encoded data of request.
*
* @return - return 0 if the HTTP parameter is decoded into a valid string.
*/
static int enduser_setup_http_urldecode(char *dst, const char *src, int src_len, int dst_len)
{
ENDUSER_SETUP_DEBUG("enduser_setup_http_urldecode");
char *dst_start = dst;
char *dst_last = dst + dst_len - 1; /* -1 to reserve space for last \0 */
char a, b;
int i;
for (i = 0; i < src_len && *src && dst < dst_last; ++i)
{
if ((*src == '%') && ((a = src[1]) && (b = src[2])) && (isxdigit(a) && isxdigit(b)))
{
if (a >= 'a')
{
a -= 'a'-'A';
}
if (a >= 'A')
{
a -= ('A' - 10);
}
else
{
a -= '0';
}
if (b >= 'a')
{
b -= 'a'-'A';
}
if (b >= 'A')
{
b -= ('A' - 10);
}
else
{
b -= '0';
}
*dst++ = 16 * a + b;
src += 3;
i += 2;
} else {
char c = *src++;
if (c == '+')
{
c = ' ';
}
*dst++ = c;
}
}
*dst++ = '\0';
return (i < src_len); /* did we fail to process all the input? */
}
/**
* Task to do the actual station configuration.
* This config *cannot* be done in the network receive callback or serious
* issues like memory corruption occur.
*/
static void do_station_cfg (task_param_t param, uint8_t prio)
{
ENDUSER_SETUP_DEBUG("do_station_cfg");
state->connecting = 1;
struct station_config *cnf = (struct station_config *)param;
(void)prio;
/* Best-effort disconnect-reconfig-reconnect. If the device is currently
* connected, the disconnect will work but the connect will report failure
* (though it will actually start connecting). If the devices is not
* connected, the disconnect may fail but the connect will succeed. A
* solid head-in-the-sand approach seems to be the best tradeoff on
* functionality-vs-code-size.
* TODO: maybe use an error callback to at least report if the set config
* call fails.
*/
wifi_station_disconnect ();
wifi_station_set_config (cnf);
wifi_station_connect ();
luaM_free(lua_getstate(), cnf);
}
/**
* Count the number of occurences of a character in a string
*
* return the number of times the character was encountered in the string
*/
static int count_char_occurence(const char *input, const char char_to_count) {
const char *current = input;
int occur = 0;
while (*current != 0) {
if (*current == char_to_count) occur++;
current++;
}
return occur;
}
/* structure used to store the key/value pairs that we find in a HTTP POST body */
struct keypairs_t {
char **keypairs;
int keypairs_nb;
};
static void enduser_setup_free_keypairs(struct keypairs_t *kp) {
if (kp == NULL) return;
if (kp->keypairs != NULL) {
for (int i = 0; i < kp->keypairs_nb * 2; i++) {
free(kp->keypairs[i]);
}
}
free(kp->keypairs);
free(kp);
}
static struct keypairs_t * enduser_setup_alloc_keypairs(int kp_number ){
struct keypairs_t *kp = malloc(sizeof(struct keypairs_t));
os_memset(kp, 0, sizeof(struct keypairs_t));
kp->keypairs = malloc(kp_number * 2 * sizeof(char *));
kp->keypairs_nb = kp_number;
return kp;
}
/**
* Parses a form-urlencoded body into a struct keypairs_t, which contains an array of key,values strings and the size of the array.
*/
static struct keypairs_t *enduser_setup_get_keypairs_from_form(char *form_body, int form_length) {
int keypair_nb = count_char_occurence(form_body, '&') + 1;
int equal_nb = count_char_occurence(form_body, '=');
if (keypair_nb == 1 && equal_nb == 0) {
ENDUSER_SETUP_DEBUG("No keypair in form body");
return NULL;
}
struct keypairs_t *kp = enduser_setup_alloc_keypairs(keypair_nb);
int current_idx = 0;
int err;
char *body_copy = malloc(form_length+1);
os_bzero(body_copy, form_length+1);
os_memcpy(body_copy, form_body, form_length);
char *tok = strtok(body_copy, "=");
char last_tok = '=';
while (tok) {
size_t len = strlen(tok);
kp->keypairs[current_idx] = malloc(len + 1);
err = enduser_setup_http_urldecode(kp->keypairs[current_idx], tok, len, len + 1);
if (err) {
ENDUSER_SETUP_DEBUG("Unable to decode parameter");
enduser_setup_free_keypairs(kp);
free(body_copy);
return NULL;
}
current_idx++;
if (current_idx > keypair_nb*2) {
ENDUSER_SETUP_DEBUG("Too many keypairs!");
enduser_setup_free_keypairs(kp);
free(body_copy);
return NULL;
}
if (last_tok == '=') {
tok = strtok(NULL, "&"); // now search for the '&'
last_tok='&';
} else {
tok = strtok(NULL, "="); // search for the next '='
last_tok='=';
}
}
free(body_copy);
return kp;
}
/**
* This function saves the form data received when the configuration is sent to the ESP into a eus_params.lua file
*/
static int enduser_setup_write_file_with_extra_configuration_data(char *form_body, int form_length) {
ENDUSER_SETUP_DEBUG("enduser: write data from posted form");
ENDUSER_SETUP_DEBUG(form_body);
// We will save the form data into a file in the LUA format: KEY="VALUE", so that configuration data is available for load in the lua code.
// As input, we have a string as such: "key1=value1&key2=value2&key3=value%203" (urlencoded), the number of '&' tells us how many keypairs there are (the count + 1)
struct keypairs_t *kp = enduser_setup_get_keypairs_from_form(form_body, form_length);
if (kp == NULL || kp->keypairs_nb == 0) {
ENDUSER_SETUP_DEBUG("enduser: No extra configuration.");
if (kp != NULL) enduser_setup_free_keypairs(kp);
return 1;
}
// Now that we have the keys and the values, let's save them in a lua file
int p_file = vfs_open("eus_params.lua", "w");
if (p_file == 0)
{
ENDUSER_SETUP_DEBUG("Can't open file in write mode!");
enduser_setup_free_keypairs(kp);
return 1;
}
// write all key pairs as KEY="VALUE"\n into a Lua table, example:
// local p = {}
// p.wifi_ssid="ssid"
// p.wifi_password="password"
// p.device_name="foo-node"
// return p
vfs_write(p_file, "local p={}\n", 11);
int idx = 0;
for( idx = 0; idx < kp->keypairs_nb*2; idx=idx+2){
char* to_write = kp->keypairs[idx];
size_t length = strlen(to_write);
vfs_write(p_file, "p.", 2);
vfs_write(p_file, to_write, length);
vfs_write(p_file, "=\"", 2);
to_write = kp->keypairs[idx+1];
length = strlen(to_write);
vfs_write(p_file, to_write, length);
vfs_write(p_file, "\"\n", 2);
}
vfs_write(p_file, "return p\n", 9);
vfs_close(p_file);
enduser_setup_free_keypairs(kp);
// TODO: we could call back in the LUA with an associative table setup, but this is MVP2...
return 0;
}
/**
* Handle HTTP Credentials
*
* @return - return 0 if credentials are found and handled successfully
* return 1 if credentials aren't found
* return 2 if an error occured
*/
static int enduser_setup_http_handle_credentials(char *data, unsigned short data_len)
{
ENDUSER_SETUP_DEBUG("enduser_setup_http_handle_credentials");
state->success = 0;
state->lastStationStatus = 0;
char *name_str = strstr(data, "wifi_ssid=");
char *pwd_str = strstr(data, "wifi_password=");
if (name_str == NULL || pwd_str == NULL)
{
ENDUSER_SETUP_DEBUG("Password or SSID string not found");
return 1;
}
int name_field_len = LITLEN("wifi_ssid=");
int pwd_field_len = LITLEN("wifi_password=");
char *name_str_start = name_str + name_field_len;
char *pwd_str_start = pwd_str + pwd_field_len;
int name_str_len = enduser_setup_get_lenth_of_param_value(name_str_start);
int pwd_str_len = enduser_setup_get_lenth_of_param_value(pwd_str_start);
struct station_config *cnf = luaM_malloc(lua_getstate(), sizeof(struct station_config));
memset(cnf, 0, sizeof(struct station_config));
cnf->threshold.rssi = -127;
cnf->threshold.authmode = AUTH_OPEN;
int err;
err = enduser_setup_http_urldecode(cnf->ssid, name_str_start, name_str_len, sizeof(cnf->ssid));
err |= enduser_setup_http_urldecode(cnf->password, pwd_str_start, pwd_str_len, sizeof(cnf->password));
if (err != 0 || strlen(cnf->ssid) == 0)
{
ENDUSER_SETUP_DEBUG("Unable to decode HTTP parameter to valid password or SSID");
return 1;
}
ENDUSER_SETUP_DEBUG("");
ENDUSER_SETUP_DEBUG("WiFi Credentials Stored");
ENDUSER_SETUP_DEBUG("-----------------------");
ENDUSER_SETUP_DEBUG("name: ");
ENDUSER_SETUP_DEBUG(cnf->ssid);
ENDUSER_SETUP_DEBUG("pass: ");
ENDUSER_SETUP_DEBUG(cnf->password);
ENDUSER_SETUP_DEBUG("-----------------------");
ENDUSER_SETUP_DEBUG("");
task_post_medium(do_station_cfg_handle, (task_param_t) cnf);
return 0;
}
/**
* Serve HTML
*
* @return - return 0 if html was served successfully
*/
static int enduser_setup_http_serve_header(struct tcp_pcb *http_client, const char *header, uint32_t header_len)
{
ENDUSER_SETUP_DEBUG("enduser_setup_http_serve_header");
err_t err = tcp_write (http_client, header, header_len, TCP_WRITE_FLAG_COPY);
if (err != ERR_OK)
{
deferred_close (http_client);
ENDUSER_SETUP_ERROR("http_serve_header failed on tcp_write", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_NONFATAL);
}
return 0;
}
static err_t streamout_sent (void *arg, struct tcp_pcb *pcb, u16_t len)
{
ENDUSER_SETUP_DEBUG("streamout_sent");
(void)len;
unsigned offs = (unsigned)arg;
if (!state || !state->http_payload_data)
{
tcp_abort (pcb);
return ERR_ABRT;
}
unsigned wanted_len = state->http_payload_len - offs;
unsigned buf_free = tcp_sndbuf (pcb);
if (buf_free < wanted_len)
wanted_len = buf_free;
/* no-copy write */
err_t err = tcp_write (pcb, state->http_payload_data + offs, wanted_len, 0);
if (err != ERR_OK)
{
ENDUSER_SETUP_DEBUG("streaming out html failed");
tcp_abort (pcb);
return ERR_ABRT;
}
offs += wanted_len;
if (offs >= state->http_payload_len)
{
tcp_sent (pcb, 0);
deferred_close (pcb);
free(state->http_payload_data);
state->http_payload_data = NULL;
}
else
tcp_arg (pcb, (void *)offs);
return ERR_OK;
}
/**
* Serve HTML
*
* @return - return 0 if html was served successfully
*/
static int enduser_setup_http_serve_html(struct tcp_pcb *http_client)
{
ENDUSER_SETUP_DEBUG("enduser_setup_http_serve_html");
if (state->http_payload_data == NULL)
{
enduser_setup_http_load_payload();
}
unsigned chunklen = tcp_sndbuf (http_client);
tcp_arg (http_client, (void *)chunklen);
tcp_recv (http_client, 0); /* avoid confusion about the tcp_arg */
tcp_sent (http_client, streamout_sent);
/* Begin the no-copy stream-out here */
err_t err = tcp_write (http_client, state->http_payload_data, chunklen, 0);
if (err != 0)
{
ENDUSER_SETUP_ERROR("http_serve_html failed. tcp_write failed", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_NONFATAL);
}
return 0;
}
static void enduser_setup_serve_status(struct tcp_pcb *conn)
{
ENDUSER_SETUP_DEBUG("enduser_setup_serve_status");
const char fmt[] =
"HTTP/1.1 200 OK\r\n"
"Cache-control:no-cache\r\n"
"Connection:close\r\n"
"Access-Control-Allow-Origin: *\r\n"
"Content-type:text/plain\r\n"
"Content-length: %d\r\n"
"\r\n"
"%s";
const char *states[] =
{
"Idle.",
"Connecting to \"%s\".",
"Failed to connect to \"%s\" - Wrong password.",
"Failed to connect to \"%s\" - Network not found.",
"Failed to connect.",
"Connected to \"%s\" (%s)."
};
const size_t num_states = sizeof(states)/sizeof(states[0]);
uint8_t curr_state = state->lastStationStatus > 0 ? state->lastStationStatus : wifi_station_get_connect_status ();
if (curr_state < num_states)
{