-
Notifications
You must be signed in to change notification settings - Fork 6
/
httpd.c
2296 lines (1964 loc) · 77 KB
/
httpd.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
/**
* @file
* LWIP HTTP server implementation
*/
/*
* Copyright (c) 2001-2003 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. 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.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
* Simon Goldschmidt
*
*/
/*
* 2022-08-14: Modified by Terje Io for grblHAL networking.
* 2022-08-27: Modified by Terje Io for grblHAL VFS
* 2023-04-11: Modified by Terje Io to improve handling of content encoding
*/
/**
* @defgroup httpd HTTP server
* @ingroup apps
*
* A simple common
* gateway interface (CGI) handling mechanism has been added to allow clients
* to hook functions to particular request URIs.
*
* Notes on CGI usage
* ------------------
*
* The simple CGI support offered here works with GET method requests only
* and can handle up to 16 parameters encoded into the URI. The handler
* function may not write directly to the HTTP output but must return a
* filename that the HTTP server will send to the browser as a response to
* the incoming CGI request.
*
*
* The list of supported file types is quite short, so if makefsdata complains
* about an unknown extension, make sure to add it (and its doctype) to
* the 'httpd_headers' list.
*/
#ifdef ARDUINO
#include "../driver.h"
#else
#include "driver.h"
#endif
#if HTTP_ENABLE
#include "httpd.h"
#if LWIP_TCP && LWIP_CALLBACK_API
#include <string.h> /* memset */
#include <stdlib.h> /* atoi */
#include <stdio.h>
#include <stdbool.h>
#include "lwip/debug.h"
#include "lwip/stats.h"
#include "lwip/def.h"
#ifdef LWIP_HOOK_FILENAME
#include LWIP_HOOK_FILENAME
#endif
#if LWIP_HTTPD_TIMING
#include "lwip/sys.h"
#endif /* LWIP_HTTPD_TIMING */
#include "strutils.h"
#include "urldecode.h"
/**/
#if LWIP_HTTPD_DYNAMIC_HEADERS
/* The number of individual strings that comprise the headers sent before each requested file. */
#define NUM_FILE_HDR_STRINGS 8
#define HDR_STRINGS_IDX_HTTP_STATUS 0 /* e.g. "HTTP/1.0 200 OK\r\n" */
#define HDR_STRINGS_IDX_SERVER_NAME 1 /* e.g. "Server: "HTTPD_SERVER_AGENT"\r\n" */
#define HDR_STRINGS_IDX_CONTENT_NEXT 2 /* the content type (or default answer content type including default document) */
/* The dynamically generated Content-Length buffer needs space for CRLF + CRLF + NULL */
#define LWIP_HTTPD_MAX_CONTENT_LEN_OFFSET 5
#ifndef LWIP_HTTPD_MAX_CONTENT_LEN_SIZE
/* The dynamically generated Content-Length buffer shall be able to work with ~953 MB (9 digits) */
#define LWIP_HTTPD_MAX_CONTENT_LEN_SIZE (9 + LWIP_HTTPD_MAX_CONTENT_LEN_OFFSET)
#endif
// Keep in sync with http_encoding_t!
static const char *httpd_encodings[] = {
"Content-Encoding: compress\r\n",
"Content-Encoding: deflate\r\n",
"Content-Encoding: gzip\r\n"
};
/** This struct is used for a list of HTTP header strings for various filename extensions. */
typedef struct {
const char *extension;
const char *content_type;
} http_header_t;
#define HTTP_CONTENT_TYPE(contenttype) "Content-Type: " contenttype "\r\n"
#define HTTP_CONTENT_TYPE_ENCODING(contenttype, encoding) "Content-Type: " contenttype "\r\nContent-Encoding: " encoding "\r\n"
#define HTTP_HDR_HTML HTTP_CONTENT_TYPE("text/html; charset=UTF-8")
#define HTTP_HDR_SSI HTTP_CONTENT_TYPE("text/html\r\nExpires: Fri, 10 Apr 2008 14:00:00 GMT\r\nPragma: no-cache")
#define HTTP_HDR_GIF HTTP_CONTENT_TYPE("image/gif")
#define HTTP_HDR_PNG HTTP_CONTENT_TYPE("image/png")
#define HTTP_HDR_JPG HTTP_CONTENT_TYPE("image/jpeg")
#define HTTP_HDR_BMP HTTP_CONTENT_TYPE("image/bmp")
#define HTTP_HDR_ICO HTTP_CONTENT_TYPE("image/x-icon")
#define HTTP_HDR_APP HTTP_CONTENT_TYPE("application/octet-stream")
#define HTTP_HDR_JS HTTP_CONTENT_TYPE("application/javascript")
#define HTTP_HDR_RA HTTP_CONTENT_TYPE("application/javascript")
#define HTTP_HDR_CSS HTTP_CONTENT_TYPE("text/css")
#define HTTP_HDR_SWF HTTP_CONTENT_TYPE("application/x-shockwave-flash")
#define HTTP_HDR_XML HTTP_CONTENT_TYPE("text/xml")
#define HTTP_HDR_PDF HTTP_CONTENT_TYPE("application/pdf")
#define HTTP_HDR_JSON HTTP_CONTENT_TYPE("application/json")
#define HTTP_HDR_CSV HTTP_CONTENT_TYPE("text/csv")
#define HTTP_HDR_TSV HTTP_CONTENT_TYPE("text/tsv")
#define HTTP_HDR_SVG HTTP_CONTENT_TYPE("image/svg+xml")
#define HTTP_HDR_GZIP HTTP_CONTENT_TYPE("application/gzip")
#define HTTP_HDR_SVGZ HTTP_CONTENT_TYPE_ENCODING("image/svg+xml", "gzip")
#define HTTP_HDR_DEFAULT_TYPE HTTP_CONTENT_TYPE("text/plain")
/** A list of extension-to-HTTP header strings (see outdated RFC 1700 MEDIA TYPES
* and http://www.iana.org/assignments/media-types for registered content types
* and subtypes) */
PROGMEM static const http_header_t httpd_headers[] = {
{ "html", HTTP_HDR_HTML},
{ "json", HTTP_HDR_JSON},
{ "htm", HTTP_HDR_HTML},
{ "gif", HTTP_HDR_GIF},
{ "png", HTTP_HDR_PNG},
{ "jpg", HTTP_HDR_JPG},
{ "bmp", HTTP_HDR_BMP},
{ "ico", HTTP_HDR_ICO},
{ "class", HTTP_HDR_APP},
{ "cls", HTTP_HDR_APP},
{ "js", HTTP_HDR_JS},
{ "ram", HTTP_HDR_RA},
{ "css", HTTP_HDR_CSS},
{ "swf", HTTP_HDR_SWF},
{ "xml", HTTP_HDR_XML},
{ "xsl", HTTP_HDR_XML},
{ "pdf", HTTP_HDR_PDF},
{ "gz", HTTP_HDR_GZIP}
#ifdef HTTPD_ADDITIONAL_CONTENT_TYPES
/* If you need to add content types not listed here:
* #define HTTPD_ADDITIONAL_CONTENT_TYPES {"ct1", HTTP_CONTENT_TYPE("text/ct1")}, {"exe", HTTP_CONTENT_TYPE("application/exe")}
*/
, HTTPD_ADDITIONAL_CONTENT_TYPES
#endif
};
#define NUM_HTTP_HEADERS LWIP_ARRAYSIZE(httpd_headers)
#endif /* LWIP_HTTPD_DYNAMIC_HEADERS */
// NOTE: Methods list must match http_method_t enumeration entries!
#if LWIP_HTTPD_SUPPORT_POST
#define HTTP_METHODS "HEAD,GET,,POST,,OPTIONS"
#else
#define HTTP_METHODS "HEAD,GET,,,,OPTIONS"
#endif
typedef enum {
HTTP_Status200 = 200,
HTTP_Status404 = 404,
HTTP_Status405 = 405,
HTTP_Status500 = 500
} http_response_status_t;
typedef enum {
HTTP_HeaderTypeROM = 0,
HTTP_HeaderTypeVolatile,
HTTP_HeaderTypeAllocated,
} http_headertype_t;
typedef struct {
const char *string[NUM_FILE_HDR_STRINGS]; /* HTTP headers to be sent. */
http_headertype_t type[NUM_FILE_HDR_STRINGS]; /* HTTP headers to be sent. */
char content_len[LWIP_HTTPD_MAX_CONTENT_LEN_SIZE];
u16_t pos; /* The position of the first unsent header byte in the current string */
u16_t index; /* The index of the hdr string currently being sent. */
u16_t next; /* The index of the hdr string to add next. */
} http_headers_t;
struct http_state {
#if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED
http_state_t *next;
#endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */
vfs_file_t *handle;
const char *file; /* Pointer to first unsent byte in buf. */
const char *uri; /* Pointer to uri. */
const char *hdr; /* Pointer to header. */
u32_t hdr_len;
u32_t payload_offset;
http_method_t method;
struct altcp_pcb *pcb;
u32_t left; /* Number of unsent bytes in buf. */
u8_t retries;
uint_fast8_t param_count;
char *params[LWIP_HTTPD_MAX_CGI_PARAMETERS]; /* Params extracted from the request URI */
char *param_vals[LWIP_HTTPD_MAX_CGI_PARAMETERS]; /* Values for each extracted param */
#if LWIP_HTTPD_SUPPORT_REQUESTLIST
struct pbuf *req;
#endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */
#if LWIP_HTTPD_DYNAMIC_FILE_READ
char *buf; /* File read buffer. */
int buf_len; /* Size of file read buffer, buf. */
#endif /* LWIP_HTTPD_DYNAMIC_FILE_READ */
#if LWIP_HTTPD_SUPPORT_11_KEEPALIVE
u8_t keepalive;
#endif /* LWIP_HTTPD_SUPPORT_11_KEEPALIVE */
#if LWIP_HTTPD_DYNAMIC_HEADERS
http_headers_t response_hdr;
#endif /* LWIP_HTTPD_DYNAMIC_HEADERS */
#if LWIP_HTTPD_TIMING
u32_t time_started;
#endif /* LWIP_HTTPD_TIMING */
u32_t post_content_len_left;
http_request_t request;
#if LWIP_HTTPD_POST_MANUAL_WND
u32_t unrecved_bytes;
u8_t no_auto_wnd;
u8_t post_finished;
#endif /* LWIP_HTTPD_POST_MANUAL_WND */
};
/**/
#if LWIP_HTTPD_SSI
#error SSI support has been removed!
#endif
#if LWIP_HTTPD_SUPPORT_V09
#error HTTP v0.9 support has been removed!
#endif
#if LWIP_HTTPD_OMIT_HEADER_FOR_EXTENSIONLESS_URI
#error Support for LWIP_HTTPD_OMIT_HEADER_FOR_EXTENSIONLESS_URI has been removed!
#endif
/** Minimum length for a valid HTTP/0.9 request: "GET /\r\n" -> 7 bytes */
#define MIN_REQ_LEN 7
#define CRLF "\r\n"
#if LWIP_HTTPD_SUPPORT_11_KEEPALIVE
#define HTTP11_CONNECTIONKEEPALIVE "Connection: keep-alive"
#define HTTP11_CONNECTIONKEEPALIVE2 "Connection: Keep-Alive"
#endif
#if LWIP_HTTPD_DYNAMIC_FILE_READ
#define HTTP_IS_DYNAMIC_FILE(hs) ((hs)->buf != NULL)
#else
#define HTTP_IS_DYNAMIC_FILE(hs) 0
#endif
/* This defines checks whether tcp_write has to copy data or not */
#ifndef HTTP_IS_DATA_VOLATILE
/** tcp_write does not have to copy data when sent from rom-file-system directly */
#define HTTP_IS_DATA_VOLATILE(hs) (HTTP_IS_DYNAMIC_FILE(hs) ? TCP_WRITE_FLAG_COPY : 0)
#endif
/** Default: dynamic headers are sent from ROM (non-dynamic headers are handled like file data) */
#ifndef HTTP_IS_HDR_VOLATILE
#define HTTP_IS_HDR_VOLATILE(hs, ptr) 0
#endif
#define HTTP_HDR_CONTENT_LEN_DIGIT_MAX_LEN 10
/* Return type and values for http_send_*() */
typedef enum {
HTTPSend_NoData = 0,
HTTPSend_Continue,
HTTPSend_Break,
HTTPSend_Freed
} http_send_state_t;
#ifdef LWIP_DEBUGF
/*
#undef LWIP_DEBUGF
#define LWIP_DEBUGF(debug, message) do { dbg message; } while(0)
#include <stdio.h>
#include <stdarg.h>
#include <ctype.h>
#include <string.h>
#include <time.h>
#include "driver.h"
void dbg (char *msg, ...)
{
char buffer[200];
va_list arg;
va_start(arg, msg);
vsprintf(buffer, msg, arg);
va_end(arg);
hal.stream.write(buffer);
}
*/
#endif
typedef struct {
const char *name;
u8_t shtml;
http_encoding_t encoding;
} default_filename;
PROGMEM static const default_filename httpd_default_filenames[] = {
{"/index.html", 0, HTTPEncoding_None },
{"/index.html.gz", 0, HTTPEncoding_GZIP },
{"/index.htm", 0, HTTPEncoding_None }
};
http_event_t httpd = {0};
static const char *msg200 = "HTTP/1.1 200 OK" CRLF;
static const char *msg400 = "HTTP/1.1 400 Bad Request" CRLF;
static const char *msg404 = "HTTP/1.1 404 File not found" CRLF;
static const char *msg501 = "HTTP/1.1 501 Not Implemented" CRLF;
static const char *agent = "Server: " HTTPD_SERVER_AGENT CRLF;
static const char *conn_close = "Connection: Close" CRLF CRLF;
static const char *conn_keep = "Connection: keep-alive" CRLF CRLF;
static const char *conn_keep2 = "Connection: keep-alive" CRLF "Content-Length: ";
//static const char *cont_len = "Content-Length: ";
static const char *rsp404 = "<html><body><h2>404: The requested file cannot be found.</h2></body></html>" CRLF;
static const char *http_methods = HTTP_METHODS;
#define NUM_DEFAULT_FILENAMES LWIP_ARRAYSIZE(httpd_default_filenames)
/** HTTP request is copied here from pbufs for simple parsing */
static char httpd_req_buf[LWIP_HTTPD_MAX_REQ_LENGTH + 1];
//#if LWIP_HTTPD_SUPPORT_POST
#if LWIP_HTTPD_POST_MAX_RESPONSE_URI_LEN > LWIP_HTTPD_MAX_REQUEST_URI_LEN
#define LWIP_HTTPD_URI_BUF_LEN LWIP_HTTPD_POST_MAX_RESPONSE_URI_LEN
#endif
//#endif
#ifndef LWIP_HTTPD_URI_BUF_LEN
#define LWIP_HTTPD_URI_BUF_LEN LWIP_HTTPD_MAX_REQUEST_URI_LEN
#endif
#if LWIP_HTTPD_URI_BUF_LEN
/* Filename for response file to send when POST is finished or
* search for default files when a directory is requested. */
static char http_uri_buf[LWIP_HTTPD_URI_BUF_LEN + 1];
#endif
#if HTTPD_USE_MEM_POOL
LWIP_MEMPOOL_DECLARE(HTTPD_STATE, MEMP_NUM_PARALLEL_HTTPD_CONNS, sizeof(http_state_t), "HTTPD_STATE")
#define HTTP_ALLOC_HTTP_STATE() (http_state_t *)LWIP_MEMPOOL_ALLOC(HTTPD_STATE)
#define HTTP_FREE_HTTP_STATE(x) LWIP_MEMPOOL_FREE(HTTPD_STATE, (x))
#else /* HTTPD_USE_MEM_POOL */
#define HTTP_ALLOC_HTTP_STATE() (http_state_t *)mem_malloc(sizeof(http_state_t))
#define HTTP_FREE_HTTP_STATE(x) mem_free(x)
#endif /* HTTPD_USE_MEM_POOL */
static err_t http_close_conn (struct altcp_pcb *pcb, http_state_t *hs);
static err_t http_close_or_abort_conn (struct altcp_pcb *pcb, http_state_t *hs, u8_t abort_conn);
static err_t http_init_file (http_state_t *hs, vfs_file_t *file, const char *uri, char *params);
static err_t http_poll (void *arg, struct altcp_pcb *pcb);
static bool http_check_eof (struct altcp_pcb *pcb, http_state_t *hs);
static err_t http_process_request (http_state_t *hs, const char *uri);
#if LWIP_HTTPD_FS_ASYNC_READ
static void http_continue (void *connection);
#endif /* LWIP_HTTPD_FS_ASYNC_READ */
/* URI handler information */
static const httpd_uri_handler_t *uri_handlers;
static uint_fast8_t num_uri_handlers;
#if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED
/** global list of active HTTP connections, use to kill the oldest when running out of memory */
static http_state_t *http_connections;
static void http_add_connection (http_state_t *hs)
{
/* add the connection to the list */
hs->next = http_connections;
http_connections = hs;
}
static void http_remove_connection (http_state_t *hs)
{
/* take the connection off the list */
if (http_connections) {
if (http_connections == hs) {
http_connections = hs->next;
} else {
http_state_t *last;
for (last = http_connections; last->next != NULL; last = last->next) {
if (last->next == hs) {
last->next = hs->next;
break;
}
}
}
}
}
static void http_kill_oldest_connection (u8_t ssi_required)
{
http_state_t *hs = http_connections;
http_state_t *hs_free_next = NULL;
while (hs && hs->next) {
#if LWIP_HTTPD_SSI
if (ssi_required) {
if (hs->next->ssi != NULL) {
hs_free_next = hs;
}
} else
#else /* LWIP_HTTPD_SSI */
LWIP_UNUSED_ARG(ssi_required);
#endif /* LWIP_HTTPD_SSI */
{
hs_free_next = hs;
}
LWIP_ASSERT("broken list", hs != hs->next);
hs = hs->next;
}
if (hs_free_next != NULL) {
LWIP_ASSERT("hs_free_next->next != NULL", hs_free_next->next != NULL);
LWIP_ASSERT("hs_free_next->next->pcb != NULL", hs_free_next->next->pcb != NULL);
/* send RST when killing a connection because of memory shortage */
http_close_or_abort_conn(hs_free_next->next->pcb, hs_free_next->next, 1); /* this also unlinks the http_state from the list */
}
}
#else /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */
#define http_add_connection(hs)
#define http_remove_connection(hs)
#endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */
/** Initialize a http_state_t.
*/
static void http_state_init (http_state_t *hs)
{
/* Initialize the structure. */
memset(hs, 0, sizeof(http_state_t));
hs->request.handle = hs;
#if LWIP_HTTPD_DYNAMIC_HEADERS
/* Indicate that the headers are not yet valid */
hs->response_hdr.index = NUM_FILE_HDR_STRINGS;
#endif /* LWIP_HTTPD_DYNAMIC_HEADERS */
}
/** Allocate a http_state_t. */
static http_state_t *http_state_alloc (void)
{
http_state_t *ret = HTTP_ALLOC_HTTP_STATE();
#if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED
if (ret == NULL) {
http_kill_oldest_connection(0);
ret = HTTP_ALLOC_HTTP_STATE();
}
#endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */
if (ret != NULL) {
http_state_init(ret);
http_add_connection(ret);
}
return ret;
}
/** Free a http_state_t.
* Also frees the file data if dynamic.
*/
static void http_state_eof (http_state_t *hs)
{
if (hs->handle) {
#if LWIP_HTTPD_TIMING
u32_t ms_needed = sys_now() - hs->time_started;
u32_t needed = LWIP_MAX(1, (ms_needed / 100));
LWIP_DEBUGF(HTTPD_DEBUG_TIMING, ("httpd: needed %"U32_F" ms to send file of %d bytes -> %"U32_F" bytes/sec\n",
ms_needed, hs->handle->len, ((((u32_t)hs->handle->len) * 10) / needed)));
#endif /* LWIP_HTTPD_TIMING */
vfs_close(hs->handle);
hs->handle = NULL;
}
uint_fast8_t i = NUM_FILE_HDR_STRINGS;
do {
i--;
if (hs->response_hdr.type[i] == HTTP_HeaderTypeAllocated && hs->response_hdr.string[i])
mem_free((void *)hs->response_hdr.string[i]);
} while(i);
memset(&hs->response_hdr, 0, sizeof(http_headers_t));
#if LWIP_HTTPD_DYNAMIC_FILE_READ
if (hs->buf != NULL) {
mem_free(hs->buf);
hs->buf = NULL;
}
#endif /* LWIP_HTTPD_DYNAMIC_FILE_READ */
if (hs->req) {
pbuf_free(hs->req);
hs->req = NULL;
}
}
void http_set_allowed_methods (const char *methods)
{
http_methods = methods;
}
/** Free a http_state_t.
* Also frees the file data if dynamic.
*/
static void http_state_free (http_state_t *hs)
{
if (hs != NULL) {
if(hs->request.on_request_completed)
hs->request.on_request_completed(hs->request.private_data);
http_state_eof(hs);
http_remove_connection(hs);
HTTP_FREE_HTTP_STATE(hs);
}
}
ip_addr_t http_get_remote_ip (http_request_t *request)
{
return request ? request->handle->pcb->remote_ip : (ip_addr_t){0};
}
uint16_t http_get_remote_port (http_request_t *request)
{
return request ? request->handle->pcb->remote_port : 0;
}
const char *http_get_uri (http_request_t *request)
{
return request ? request->handle->uri : NULL;
}
uint8_t http_get_param_count (http_request_t *request)
{
return request ? request->handle->param_count : 0;
}
char *http_get_param_value (http_request_t *request, const char *name, char *value, uint32_t size)
{
bool found = false;
http_state_t *hs = request->handle;
uint_fast8_t idx = hs->param_count;
*value = '\0';
if(idx) do {
if((found = strcmp(name, hs->params[--idx]) == 0))
urldecode(value, hs->param_vals[idx]);
} while(idx && !found);
return found ? value : NULL;
}
int http_get_header_value_len (http_request_t *request, const char *name)
{
int len = -1;
char *hdr, *end;
http_state_t *hs = request->handle;
if ((hdr = strnistr(hs->hdr, name, hs->hdr_len))) {
hdr += strlen(name);
if(*hdr == ':') {
hdr++;
if(*hdr == ' ')
hdr++;
if ((end = lwip_strnstr(hdr, CRLF, hs->hdr_len)))
len = end - hdr;
}
}
return len;
}
char *http_get_header_value (http_request_t *request, const char *name, char *value, uint32_t size)
{
char *hdr, *end = NULL;
http_state_t *hs = request->handle;
size_t len = strlen(name);
*value = '\0';
if ((hdr = strnistr(hs->hdr, name, hs->hdr_len))) {
hdr += len;
if(*hdr == ':') {
hdr++;
if(*hdr == ' ')
hdr++;
if ((end = lwip_strnstr(hdr, CRLF, size + 2)) && end - hdr <= size) {
len = end - hdr;
memcpy(value, hdr, len);
value[len] = '\0';
}
}
}
return end ? value : NULL;
}
/** Call tcp_write() in a loop trying smaller and smaller length
*
* @param pcb altcp_pcb to send
* @param ptr Data to send
* @param length Length of data to send (in/out: on return, contains the amount of data sent)
* @param apiflags directly passed to tcp_write
* @return the return value of tcp_write
*/
static err_t http_write (struct altcp_pcb *pcb, const void *ptr, u16_t *length, u8_t apiflags)
{
u16_t len, max_len;
err_t err;
// LWIP_ASSERT("length != NULL", length != NULL);
len = *length;
if (len == 0)
return ERR_OK;
/* We cannot send more data than space available in the send buffer. */
max_len = altcp_sndbuf(pcb);
if (max_len < len)
len = max_len;
#ifdef HTTPD_MAX_WRITE_LEN
/* Additional limitation: e.g. don't enqueue more than 2*mss at once */
max_len = HTTPD_MAX_WRITE_LEN(pcb);
if (len > max_len)
len = max_len;
#endif /* HTTPD_MAX_WRITE_LEN */
do {
// LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Trying to send %d bytes\n", len));
if ((err = altcp_write(pcb, ptr, len, apiflags)) == ERR_MEM) {
if ((altcp_sndbuf(pcb) == 0) ||
(altcp_sndqueuelen(pcb) >= TCP_SND_QUEUELEN)) {
/* no need to try smaller sizes */
len = 1;
} else
len /= 2;
// LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Send failed, trying less (%d bytes)\n", len));
}
} while ((err == ERR_MEM) && (len > 1));
if (err == ERR_OK) {
LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Sent %d bytes\n", len));
*length = len;
} else {
LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Send failed with err %d (\"%s\")\n", err, lwip_strerr(err)));
*length = 0;
}
#if LWIP_HTTPD_SUPPORT_11_KEEPALIVE
/* ensure nagle is normally enabled (only disabled for persistent connections
when all data has been enqueued but the connection stays open for the next
request */
altcp_nagle_enable(pcb);
#endif
return err;
}
/**
* The connection shall be actively closed (using RST to close from fault states).
* Reset the sent- and recv-callbacks.
*
* @param pcb the tcp pcb to reset callbacks
* @param hs connection state to free
*/
static err_t http_close_or_abort_conn (struct altcp_pcb *pcb, http_state_t *hs, u8_t abort_conn)
{
err_t err;
LWIP_DEBUGF(HTTPD_DEBUG, ("Closing connection %p\n", (void *)pcb));
if (hs != NULL) {
if ((hs->post_content_len_left != 0)
#if LWIP_HTTPD_POST_MANUAL_WND
|| ((hs->no_auto_wnd != 0) && (hs->unrecved_bytes != 0))
#endif /* LWIP_HTTPD_POST_MANUAL_WND */
) {
/* make sure the post code knows that the connection is closed */
*http_uri_buf = '\0';
hs->request.post_finished(&hs->request, http_uri_buf, LWIP_HTTPD_URI_BUF_LEN);
}
}
altcp_arg(pcb, NULL);
altcp_recv(pcb, NULL);
altcp_err(pcb, NULL);
altcp_poll(pcb, NULL, 0);
altcp_sent(pcb, NULL);
if (hs != NULL)
http_state_free(hs);
if (abort_conn) {
altcp_abort(pcb);
return ERR_OK;
}
if ((err = altcp_close(pcb)) != ERR_OK) {
LWIP_DEBUGF(HTTPD_DEBUG, ("Error %d closing %p\n", err, (void *)pcb));
/* error closing, try again later in poll */
altcp_poll(pcb, http_poll, HTTPD_POLL_INTERVAL);
}
return err;
}
/**
* The connection shall be actively closed.
* Reset the sent- and recv-callbacks.
*
* @param pcb the tcp pcb to reset callbacks
* @param hs connection state to free
*/
static err_t http_close_conn (struct altcp_pcb *pcb, http_state_t *hs)
{
return http_close_or_abort_conn(pcb, hs, 0);
}
/** End of file: either close the connection (Connection: close) or
* close the file (Connection: keep-alive)
*/
static void http_eof (struct altcp_pcb *pcb, http_state_t *hs)
{
/* HTTP/1.1 persistent connection? (Not supported for SSI) */
#if LWIP_HTTPD_SUPPORT_11_KEEPALIVE
if (hs->keepalive) {
http_remove_connection(hs);
http_state_eof(hs);
http_state_init(hs);
/* restore state: */
hs->pcb = pcb;
hs->keepalive = 1;
http_add_connection(hs);
/* ensure nagle doesn't interfere with sending all data as fast as possible: */
altcp_nagle_disable(pcb);
} else
#endif /* LWIP_HTTPD_SUPPORT_11_KEEPALIVE */
http_close_conn(pcb, hs);
}
/**
* Extract URI parameters from the parameter-part of an URI in the form
* "test.cgi?x=y" @todo: better explanation!
* Pointers to the parameters are stored in hs->param_vals.
*
* @param hs http connection state
* @param params pointer to the NULL-terminated parameter string from the URI
* @return number of parameters extracted
*/
static uint_fast8_t extract_uri_parameters (http_state_t *hs, char *params)
{
char *pair, *equals;
uint_fast8_t loop;
/* If we have no parameters at all, return immediately. */
if (!params || (params[0] == '\0'))
return 0;
/* Get a pointer to our first parameter */
pair = params;
/* Parse up to LWIP_HTTPD_MAX_CGI_PARAMETERS from the passed string and ignore the remainder (if any) */
for (loop = 0; (loop < LWIP_HTTPD_MAX_CGI_PARAMETERS) && pair; loop++) {
/* Save the name of the parameter */
hs->params[loop] = pair;
/* Remember the start of this name=value pair */
equals = pair;
/* Find the start of the next name=value pair and replace the delimiter
* with a 0 to terminate the previous pair string. */
if ((pair = strchr(pair, '&')))
*pair++ = '\0';
else {
/* We didn't find a new parameter so find the end of the URI and replace the space with a '\0' */
if ((pair = strchr(equals, ' ')))
*pair = '\0';
/* Revert to NULL so that we exit the loop as expected. */
pair = NULL;
}
/* Now find the '=' in the previous pair, replace it with '\0' and save the parameter value string. */
if ((equals = strchr(equals, '='))) {
*equals = '\0';
hs->param_vals[loop] = equals + 1;
} else
hs->param_vals[loop] = NULL;
}
return loop;
}
#if LWIP_HTTPD_DYNAMIC_HEADERS
static bool is_response_header_set (http_state_t *hs, const char *name)
{
bool is_set = false;
uint_fast8_t i = NUM_FILE_HDR_STRINGS, len = strlen(name);
do {
i--;
is_set = hs->response_hdr.string[i] && !strncmp(name, hs->response_hdr.string[i], len);
} while(i && !is_set);
return is_set;
}
bool http_set_response_header (http_request_t *request, const char *name, const char *value)
{
bool ok;
http_state_t *hs = request->handle;
if((ok = hs->response_hdr.next < (NUM_FILE_HDR_STRINGS - 1))) {
char *hdr;
if((hdr = mem_malloc(strlen(name) + strlen(value) + 5))) {
strcat(strcat(strcat(strcpy(hdr, name), ": "), value), CRLF);
hs->response_hdr.string[hs->response_hdr.next] = hdr;
hs->response_hdr.type[hs->response_hdr.next++] = HTTP_HeaderTypeAllocated;
} else
ok = false;
}
return ok;
}
void http_set_response_status (http_request_t *request, const char *status)
{
http_state_t *hs = request->handle;
char *hdr;
if(status && (hdr = mem_malloc(strlen(status) + 12))) {
strcat(strcat(strcpy(hdr, "HTTP/1.1 "), status), CRLF);
hs->response_hdr.string[HDR_STRINGS_IDX_HTTP_STATUS] = hdr;
hs->response_hdr.type[HDR_STRINGS_IDX_HTTP_STATUS] = HTTP_HeaderTypeAllocated;
}
}
/* We are dealing with a particular filename. Look for one other
special case. We assume that any filename with "404" in it must be
indicative of a 404 server error whereas all other files require
the 200 OK header. */
static void set_content_type (http_state_t *hs, const char *uri)
{
if(!is_response_header_set(hs, "Content-Type") && hs->response_hdr.next < NUM_FILE_HDR_STRINGS) {
char *end, *ext;
bool ext_found = false;
uint_fast8_t content_type = NUM_HTTP_HEADERS;
if (!(end = strchr(uri, '?')))
end = strchr(uri, '\0');
ext_found = (ext = strrchr(uri, '.')) && ext < end;
if(end != uri) {
for (content_type = 0; content_type < NUM_HTTP_HEADERS; content_type++) {
size_t len = strlen(httpd_headers[content_type].extension);
ext = end - len;
if(ext > uri && *(ext - 1) == '.' && !lwip_strnicmp(httpd_headers[content_type].extension, ext, len))
break;
}
}
/* Did we find a matching extension? */
if (content_type < NUM_HTTP_HEADERS) {
/* yes, store it */
hs->response_hdr.string[hs->response_hdr.next++] = httpd_headers[content_type].content_type;
} else if (!ext_found) {
/* no, no extension found -> use binary transfer to prevent the browser adding '.txt' on save */
hs->response_hdr.string[hs->response_hdr.next++] = HTTP_HDR_APP;
} else {
const char *content_type;
if(httpd.on_unknown_content_type && (content_type = httpd.on_unknown_content_type(ext)))
hs->response_hdr.string[hs->response_hdr.next++] = content_type;
else /* No - use the default, plain text file type. */
hs->response_hdr.string[hs->response_hdr.next++] = HTTP_HDR_DEFAULT_TYPE;
}
if(hs->request.encoding)
hs->response_hdr.string[hs->response_hdr.next++] = httpd_encodings[hs->request.encoding - 1];
}
}
/* Add content-length header? */
static void get_http_content_length (http_state_t *hs, int file_len)
{
bool add_content_len = false;
if ((add_content_len = file_len >= 0 && hs->response_hdr.next < (NUM_FILE_HDR_STRINGS - 1))) {
size_t len;
lwip_itoa(hs->response_hdr.content_len, (size_t)LWIP_HTTPD_MAX_CONTENT_LEN_SIZE, file_len);
len = strlen(hs->response_hdr.content_len);
if ((add_content_len = len <= LWIP_HTTPD_MAX_CONTENT_LEN_SIZE - LWIP_HTTPD_MAX_CONTENT_LEN_OFFSET)) {
SMEMCPY(&hs->response_hdr.content_len[len], CRLF CRLF, 5);
hs->response_hdr.string[hs->response_hdr.next + 1] = hs->response_hdr.content_len;
hs->response_hdr.type[hs->response_hdr.next + 1] = HTTP_HeaderTypeVolatile;
}
}
#if LWIP_HTTPD_SUPPORT_11_KEEPALIVE
if (add_content_len) {
hs->response_hdr.string[hs->response_hdr.next] = conn_keep2;
hs->response_hdr.next += 2;
} else {
hs->response_hdr.string[hs->response_hdr.next++] = conn_close;
hs->keepalive = 0;
}
#else /* LWIP_HTTPD_SUPPORT_11_KEEPALIVE */
if (add_content_len) {
hs->response_hdr.string[hs->response_hdr.next] = cont_len;
hs->response_hdr.next += 2;
}
#endif /* LWIP_HTTPD_SUPPORT_11_KEEPALIVE */
}
/**
* Generate the relevant HTTP headers for the given filename and write
* them into the supplied buffer.
*/
static void get_http_headers (http_state_t *hs, const char *uri)
{
if(hs->response_hdr.string[HDR_STRINGS_IDX_HTTP_STATUS] == NULL) {
/* Is this a normal file or the special case we use to send back the default "404: Page not found" response? */
if (uri == NULL) {
if(hs->method == HTTP_Post) {
hs->response_hdr.string[HDR_STRINGS_IDX_HTTP_STATUS] = msg200;
hs->response_hdr.string[hs->response_hdr.next++] = conn_keep;
} else {
hs->response_hdr.string[HDR_STRINGS_IDX_HTTP_STATUS] = msg404;
set_content_type(hs, ".html");
get_http_content_length(hs, strlen(rsp404));
hs->response_hdr.string[hs->response_hdr.next++] = rsp404;
}
} else {
/* We are dealing with a particular filename. Look for one other
special case. We assume that any filename with "404" in it must be
indicative of a 404 server error whereas all other files require
the 200 OK header. */
if (strstr(uri, "404"))
hs->response_hdr.string[HDR_STRINGS_IDX_HTTP_STATUS] = msg404;
else if (strstr(uri, "400"))
hs->response_hdr.string[HDR_STRINGS_IDX_HTTP_STATUS] = msg400;
else if (strstr(uri, "501"))
hs->response_hdr.string[HDR_STRINGS_IDX_HTTP_STATUS] = msg501;
else
hs->response_hdr.string[HDR_STRINGS_IDX_HTTP_STATUS] = msg200;
set_content_type(hs, uri);
}