-
Notifications
You must be signed in to change notification settings - Fork 234
/
httpd.c
2705 lines (2457 loc) · 97.4 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 <[email protected]>
* Simon Goldschmidt
*
*/
/**
* @defgroup httpd HTTP server
* @ingroup apps
*
* This httpd supports for a
* rudimentary server-side-include facility which will replace tags of the form
* <!--#tag--> in any file whose extension is .shtml, .shtm or .ssi with
* strings provided by an include handler whose pointer is provided to the
* module via function http_set_ssi_handler().
* Additionally, a simple common
* gateway interface (CGI) handling mechanism has been added to allow clients
* to hook functions to particular request URIs.
*
* To enable SSI support, define label LWIP_HTTPD_SSI in lwipopts.h.
* To enable CGI support, define label LWIP_HTTPD_CGI in lwipopts.h.
*
* By default, the server assumes that HTTP headers are already present in
* each file stored in the file system. By defining LWIP_HTTPD_DYNAMIC_HEADERS in
* lwipopts.h, this behavior can be changed such that the server inserts the
* headers automatically based on the extension of the file being served. If
* this mode is used, be careful to ensure that the file system image used
* does not already contain the header information.
*
* File system images without headers can be created using the makefsfile
* tool with the -h command line option.
*
*
* Notes about valid SSI tags
* --------------------------
*
* The following assumptions are made about tags used in SSI markers:
*
* 1. No tag may contain '-' or whitespace characters within the tag name.
* 2. Whitespace is allowed between the tag leadin "<!--#" and the start of
* the tag name and between the tag name and the leadout string "-->".
* 3. The maximum tag name length is LWIP_HTTPD_MAX_TAG_NAME_LEN, currently 8 characters.
*
* 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 'g_psHTTPHeaders' list.
*/
#include "lwip/init.h"
#include "httpd.h"
#include "lwip/debug.h"
#include "lwip/stats.h"
#include "lwip/apps/fs.h"
#include "httpd_structs.h"
#include "lwip/def.h"
#include "lwip/altcp.h"
#include "lwip/altcp_tcp.h"
#if HTTPD_ENABLE_HTTPS
#include "lwip/altcp_tls.h"
#endif
#ifdef LWIP_HOOK_FILENAME
#include LWIP_HOOK_FILENAME
#endif
#if LWIP_HTTPD_TIMING
#include "lwip/sys.h"
#endif /* LWIP_HTTPD_TIMING */
#include <string.h> /* memset */
#include <stdlib.h> /* atoi */
#include <stdio.h>
#include "stdbool.h"
/******* Customization ***************************************/
#include "wui_REST_api.h"
#include "wui_api.h"
#include "wui.h"
#include "dbg.h"
#define WUI_API_ROOT_STR_LEN 5
#define POST_REQUEST_BUFFSIZE 600
#define RESPONSE_BODY_SIZE 512
#define MAX_MARLIN_REQUEST_LEN 100
#define POST_URL_STR_MAX_LEN 50
static char response_body_buf[RESPONSE_BODY_SIZE];
/***************************************************************/
#if LWIP_TCP && LWIP_CALLBACK_API
/** 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
/* Return values for http_send_*() */
#define HTTP_DATA_TO_SEND_FREED 3
#define HTTP_DATA_TO_SEND_BREAK 2
#define HTTP_DATA_TO_SEND_CONTINUE 1
#define HTTP_NO_DATA_TO_SEND 0
typedef struct {
const char *name;
u8_t shtml;
} default_filename;
static const default_filename httpd_default_filenames[] = {
{ "/index.shtml", 1 },
{ "/index.ssi", 1 },
{ "/index.shtm", 1 },
{ "/index.html", 0 },
{ "/index.htm", 0 }
};
#define NUM_DEFAULT_FILENAMES LWIP_ARRAYSIZE(httpd_default_filenames)
#if LWIP_HTTPD_SUPPORT_REQUESTLIST
/** HTTP request is copied here from pbufs for simple parsing */
static char httpd_req_buf[LWIP_HTTPD_MAX_REQ_LENGTH + 1];
#endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */
#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
#if LWIP_HTTPD_SUPPORT_POST
/* 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
#endif
#if LWIP_HTTPD_DYNAMIC_HEADERS
/* The number of individual strings that comprise the headers sent before each
* requested file.
*/
#define NUM_FILE_HDR_STRINGS 5
#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_LEN_KEEPALIVE 2 /* e.g. "Content-Length: xy\r\n" and/or "Connection: keep-alive\r\n" */
#define HDR_STRINGS_IDX_CONTENT_LEN_NR 3 /* the byte count, when content-length is used */
#define HDR_STRINGS_IDX_CONTENT_TYPE 4 /* the content type (or default answer content type including default document) */
/* The dynamically generated Content-Length buffer needs space for CRLF + NULL */
#define LWIP_HTTPD_MAX_CONTENT_LEN_OFFSET 3
#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
#endif /* LWIP_HTTPD_DYNAMIC_HEADERS */
#if LWIP_HTTPD_SSI
#define HTTPD_LAST_TAG_PART 0xFFFF
enum tag_check_state {
TAG_NONE, /* Not processing an SSI tag */
TAG_LEADIN, /* Tag lead in "<!--#" being processed */
TAG_FOUND, /* Tag name being read, looking for lead-out start */
TAG_LEADOUT, /* Tag lead out "-->" being processed */
TAG_SENDING /* Sending tag replacement string */
};
struct http_ssi_state {
const char *parsed; /* Pointer to the first unparsed byte in buf. */
#if !LWIP_HTTPD_SSI_INCLUDE_TAG
const char *tag_started; /* Pointer to the first opening '<' of the tag. */
#endif /* !LWIP_HTTPD_SSI_INCLUDE_TAG */
const char *tag_end; /* Pointer to char after the closing '>' of the tag. */
u32_t parse_left; /* Number of unparsed bytes in buf. */
u16_t tag_index; /* Counter used by tag parsing state machine */
u16_t tag_insert_len; /* Length of insert in string tag_insert */
#if LWIP_HTTPD_SSI_MULTIPART
u16_t tag_part; /* Counter passed to and changed by tag insertion function to insert multiple times */
#endif /* LWIP_HTTPD_SSI_MULTIPART */
u8_t tag_type; /* index into http_ssi_tag_desc array */
u8_t tag_name_len; /* Length of the tag name in string tag_name */
char tag_name[LWIP_HTTPD_MAX_TAG_NAME_LEN + 1]; /* Last tag name extracted */
char tag_insert[LWIP_HTTPD_MAX_TAG_INSERT_LEN + 1]; /* Insert string for tag_name */
enum tag_check_state tag_state; /* State of the tag processor */
};
struct http_ssi_tag_description {
const char *lead_in;
const char *lead_out;
};
#endif /* LWIP_HTTPD_SSI */
struct http_state {
#if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED
struct http_state *next;
#endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */
struct fs_file file_handle;
struct fs_file *handle;
const char *file; /* Pointer to first unsent byte in buf. */
struct altcp_pcb *pcb;
#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 */
u32_t left; /* Number of unsent bytes in buf. */
u8_t retries;
#if LWIP_HTTPD_SUPPORT_11_KEEPALIVE
u8_t keepalive;
#endif /* LWIP_HTTPD_SUPPORT_11_KEEPALIVE */
#if LWIP_HTTPD_SSI
struct http_ssi_state *ssi;
#endif /* LWIP_HTTPD_SSI */
#if LWIP_HTTPD_CGI
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 */
#endif /* LWIP_HTTPD_CGI */
#if LWIP_HTTPD_DYNAMIC_HEADERS
const char *hdrs[NUM_FILE_HDR_STRINGS]; /* HTTP headers to be sent. */
char hdr_content_len[LWIP_HTTPD_MAX_CONTENT_LEN_SIZE];
u16_t hdr_pos; /* The position of the first unsent header byte in the
current string */
u16_t hdr_index; /* The index of the hdr string currently being sent. */
#endif /* LWIP_HTTPD_DYNAMIC_HEADERS */
#if LWIP_HTTPD_TIMING
u32_t time_started;
#endif /* LWIP_HTTPD_TIMING */
#if LWIP_HTTPD_SUPPORT_POST
u32_t post_content_len_left;
#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 */
#endif /* LWIP_HTTPD_SUPPORT_POST*/
};
#if HTTPD_USE_MEM_POOL
LWIP_MEMPOOL_DECLARE(HTTPD_STATE, MEMP_NUM_PARALLEL_HTTPD_CONNS, sizeof(struct http_state), "HTTPD_STATE")
#if LWIP_HTTPD_SSI
LWIP_MEMPOOL_DECLARE(HTTPD_SSI_STATE, MEMP_NUM_PARALLEL_HTTPD_SSI_CONNS, sizeof(struct http_ssi_state), "HTTPD_SSI_STATE")
#define HTTP_FREE_SSI_STATE(x) LWIP_MEMPOOL_FREE(HTTPD_SSI_STATE, (x))
#define HTTP_ALLOC_SSI_STATE() (struct http_ssi_state *)LWIP_MEMPOOL_ALLOC(HTTPD_SSI_STATE)
#endif /* LWIP_HTTPD_SSI */
#define HTTP_ALLOC_HTTP_STATE() (struct http_state *)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() (struct http_state *)mem_malloc(sizeof(struct http_state))
#define HTTP_FREE_HTTP_STATE(x) mem_free(x)
#if LWIP_HTTPD_SSI
#define HTTP_ALLOC_SSI_STATE() (struct http_ssi_state *)mem_malloc(sizeof(struct http_ssi_state))
#define HTTP_FREE_SSI_STATE(x) mem_free(x)
#endif /* LWIP_HTTPD_SSI */
#endif /* HTTPD_USE_MEM_POOL */
static err_t http_close_conn(struct altcp_pcb *pcb, struct http_state *hs);
static err_t http_close_or_abort_conn(struct altcp_pcb *pcb, struct http_state *hs, u8_t abort_conn);
static err_t http_find_file(struct http_state *hs, const char *uri, int is_09);
static err_t http_init_file(struct http_state *hs, struct fs_file *file, int is_09, const char *uri, u8_t tag_check, char *params);
static err_t http_poll(void *arg, struct altcp_pcb *pcb);
static u8_t http_check_eof(struct altcp_pcb *pcb, struct http_state *hs);
#if LWIP_HTTPD_FS_ASYNC_READ
static void http_continue(void *connection);
#endif /* LWIP_HTTPD_FS_ASYNC_READ */
#if LWIP_HTTPD_SSI
/* SSI insert handler function pointer. */
static tSSIHandler httpd_ssi_handler;
#if !LWIP_HTTPD_SSI_RAW
static int httpd_num_tags;
static const char **httpd_tags;
#endif /* !LWIP_HTTPD_SSI_RAW */
/* Define the available tag lead-ins and corresponding lead-outs.
* ATTENTION: for the algorithm below using this array, it is essential
* that the lead in differs in the first character! */
const struct http_ssi_tag_description http_ssi_tag_desc[] = {
{ "<!--#", "-->" },
{ "/*#", "*/" }
};
#endif /* LWIP_HTTPD_SSI */
#if LWIP_HTTPD_CGI
/* CGI handler information */
static const tCGI *httpd_cgis;
static int httpd_num_cgis;
static int http_cgi_paramcount;
#define http_cgi_params hs->params
#define http_cgi_param_vals hs->param_vals
#elif LWIP_HTTPD_CGI_SSI
static char *http_cgi_params[LWIP_HTTPD_MAX_CGI_PARAMETERS]; /* Params extracted from the request URI */
static char *http_cgi_param_vals[LWIP_HTTPD_MAX_CGI_PARAMETERS]; /* Values for each extracted param */
#endif /* LWIP_HTTPD_CGI */
#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 struct http_state *http_connections;
static void
http_add_connection(struct http_state *hs) {
/* add the connection to the list */
hs->next = http_connections;
http_connections = hs;
}
static void
http_remove_connection(struct http_state *hs) {
/* take the connection off the list */
if (http_connections) {
if (http_connections == hs) {
http_connections = hs->next;
} else {
struct http_state *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) {
struct http_state *hs = http_connections;
struct http_state *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 */
#if LWIP_HTTPD_SSI
/** Allocate as struct http_ssi_state. */
static struct http_ssi_state *
http_ssi_state_alloc(void) {
struct http_ssi_state *ret = HTTP_ALLOC_SSI_STATE();
#if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED
if (ret == NULL) {
http_kill_oldest_connection(1);
ret = HTTP_ALLOC_SSI_STATE();
}
#endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */
if (ret != NULL) {
memset(ret, 0, sizeof(struct http_ssi_state));
}
return ret;
}
/** Free a struct http_ssi_state. */
static void
http_ssi_state_free(struct http_ssi_state *ssi) {
if (ssi != NULL) {
HTTP_FREE_SSI_STATE(ssi);
}
}
#endif /* LWIP_HTTPD_SSI */
/** Initialize a struct http_state.
*/
static void
http_state_init(struct http_state *hs) {
/* Initialize the structure. */
memset(hs, 0, sizeof(struct http_state));
#if LWIP_HTTPD_DYNAMIC_HEADERS
/* Indicate that the headers are not yet valid */
hs->hdr_index = NUM_FILE_HDR_STRINGS;
#endif /* LWIP_HTTPD_DYNAMIC_HEADERS */
}
/** Allocate a struct http_state. */
static struct http_state *
http_state_alloc(void) {
struct http_state *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 struct http_state.
* Also frees the file data if dynamic.
*/
static void
http_state_eof(struct http_state *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 */
fs_close(hs->handle);
hs->handle = NULL;
}
#if LWIP_HTTPD_DYNAMIC_FILE_READ
if (hs->buf != NULL) {
mem_free(hs->buf);
hs->buf = NULL;
}
#endif /* LWIP_HTTPD_DYNAMIC_FILE_READ */
#if LWIP_HTTPD_SSI
if (hs->ssi) {
http_ssi_state_free(hs->ssi);
hs->ssi = NULL;
}
#endif /* LWIP_HTTPD_SSI */
#if LWIP_HTTPD_SUPPORT_REQUESTLIST
if (hs->req) {
pbuf_free(hs->req);
hs->req = NULL;
}
#endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */
}
/** Free a struct http_state.
* Also frees the file data if dynamic.
*/
static void
http_state_free(struct http_state *hs) {
if (hs != NULL) {
http_state_eof(hs);
http_remove_connection(hs);
HTTP_FREE_HTTP_STATE(hs);
}
}
/** 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));
err = altcp_write(pcb, ptr, len, apiflags);
if (err == 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, struct http_state *hs, u8_t abort_conn) {
err_t err;
LWIP_DEBUGF(HTTPD_DEBUG, ("Closing connection %p\n", (void *)pcb));
#if LWIP_HTTPD_SUPPORT_POST
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] = 0;
httpd_post_finished(hs, http_uri_buf, LWIP_HTTPD_URI_BUF_LEN);
}
}
#endif /* LWIP_HTTPD_SUPPORT_POST*/
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;
}
err = altcp_close(pcb);
if (err != 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, struct http_state *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, struct http_state *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);
}
}
#if LWIP_HTTPD_CGI || LWIP_HTTPD_CGI_SSI
/**
* 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 int
extract_uri_parameters(struct http_state *hs, char *params) {
char *pair;
char *equals;
int loop;
LWIP_UNUSED_ARG(hs);
/* 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 */
http_cgi_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. */
pair = strchr(pair, '&');
if (pair) {
*pair = '\0';
pair++;
} else {
/* We didn't find a new parameter so find the end of the URI and
* replace the space with a '\0' */
pair = strchr(equals, ' ');
if (pair) {
*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. */
equals = strchr(equals, '=');
if (equals) {
*equals = '\0';
http_cgi_param_vals[loop] = equals + 1;
} else {
http_cgi_param_vals[loop] = NULL;
}
}
return loop;
}
#endif /* LWIP_HTTPD_CGI || LWIP_HTTPD_CGI_SSI */
#if LWIP_HTTPD_SSI
/**
* Insert a tag (found in an shtml in the form of "<!--#tagname-->" into the file.
* The tag's name is stored in ssi->tag_name (NULL-terminated), the replacement
* should be written to hs->tag_insert (up to a length of LWIP_HTTPD_MAX_TAG_INSERT_LEN).
* The amount of data written is stored to ssi->tag_insert_len.
*
* @todo: return tag_insert_len - maybe it can be removed from struct http_state?
*
* @param hs http connection state
*/
static void
get_tag_insert(struct http_state *hs) {
#if LWIP_HTTPD_SSI_RAW
const char *tag;
#else /* LWIP_HTTPD_SSI_RAW */
int tag;
#endif /* LWIP_HTTPD_SSI_RAW */
size_t len;
struct http_ssi_state *ssi;
#if LWIP_HTTPD_SSI_MULTIPART
u16_t current_tag_part;
#endif /* LWIP_HTTPD_SSI_MULTIPART */
LWIP_ASSERT("hs != NULL", hs != NULL);
ssi = hs->ssi;
LWIP_ASSERT("ssi != NULL", ssi != NULL);
#if LWIP_HTTPD_SSI_MULTIPART
current_tag_part = ssi->tag_part;
ssi->tag_part = HTTPD_LAST_TAG_PART;
#endif /* LWIP_HTTPD_SSI_MULTIPART */
#if LWIP_HTTPD_SSI_RAW
tag = ssi->tag_name;
#endif
if (httpd_ssi_handler
#if !LWIP_HTTPD_SSI_RAW
&& httpd_tags && httpd_num_tags
#endif /* !LWIP_HTTPD_SSI_RAW */
) {
/* Find this tag in the list we have been provided. */
#if LWIP_HTTPD_SSI_RAW
{
#else /* LWIP_HTTPD_SSI_RAW */
for (tag = 0; tag < httpd_num_tags; tag++) {
if (strcmp(ssi->tag_name, httpd_tags[tag]) == 0)
#endif /* LWIP_HTTPD_SSI_RAW */
{
ssi->tag_insert_len = httpd_ssi_handler(tag, ssi->tag_insert,
LWIP_HTTPD_MAX_TAG_INSERT_LEN
#if LWIP_HTTPD_SSI_MULTIPART
,
current_tag_part, &ssi->tag_part
#endif /* LWIP_HTTPD_SSI_MULTIPART */
#if LWIP_HTTPD_FILE_STATE
,
(hs->handle ? hs->handle->state : NULL)
#endif /* LWIP_HTTPD_FILE_STATE */
);
#if LWIP_HTTPD_SSI_RAW
if (ssi->tag_insert_len != HTTPD_SSI_TAG_UNKNOWN)
#endif /* LWIP_HTTPD_SSI_RAW */
{
return;
}
}
}
}
/* If we drop out, we were asked to serve a page which contains tags that
* we don't have a handler for. Merely echo back the tags with an error
* marker. */
#define UNKNOWN_TAG1_TEXT "<b>***UNKNOWN TAG "
#define UNKNOWN_TAG1_LEN 18
#define UNKNOWN_TAG2_TEXT "***</b>"
#define UNKNOWN_TAG2_LEN 7
len = LWIP_MIN(sizeof(ssi->tag_name), LWIP_MIN(strlen(ssi->tag_name), LWIP_HTTPD_MAX_TAG_INSERT_LEN - (UNKNOWN_TAG1_LEN + UNKNOWN_TAG2_LEN)));
MEMCPY(ssi->tag_insert, UNKNOWN_TAG1_TEXT, UNKNOWN_TAG1_LEN);
MEMCPY(&ssi->tag_insert[UNKNOWN_TAG1_LEN], ssi->tag_name, len);
MEMCPY(&ssi->tag_insert[UNKNOWN_TAG1_LEN + len], UNKNOWN_TAG2_TEXT, UNKNOWN_TAG2_LEN);
ssi->tag_insert[UNKNOWN_TAG1_LEN + len + UNKNOWN_TAG2_LEN] = 0;
len = strlen(ssi->tag_insert);
LWIP_ASSERT("len <= 0xffff", len <= 0xffff);
ssi->tag_insert_len = (u16_t)len;
}
#endif /* LWIP_HTTPD_SSI */
#if LWIP_HTTPD_DYNAMIC_HEADERS
/**
* Generate the relevant HTTP headers for the given filename and write
* them into the supplied buffer.
*/
static void
get_http_headers(struct http_state *hs, const char *uri) {
size_t content_type;
char *tmp;
char *ext;
char *vars;
/* In all cases, the second header we send is the server identification
so set it here. */
hs->hdrs[HDR_STRINGS_IDX_SERVER_NAME] = g_psHTTPHeaderStrings[HTTP_HDR_SERVER];
hs->hdrs[HDR_STRINGS_IDX_CONTENT_LEN_KEEPALIVE] = NULL;
hs->hdrs[HDR_STRINGS_IDX_CONTENT_LEN_NR] = 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) {
hs->hdrs[HDR_STRINGS_IDX_HTTP_STATUS] = g_psHTTPHeaderStrings[HTTP_HDR_NOT_FOUND];
#if LWIP_HTTPD_SUPPORT_11_KEEPALIVE
if (hs->keepalive) {
hs->hdrs[HDR_STRINGS_IDX_CONTENT_TYPE] = g_psHTTPHeaderStrings[DEFAULT_404_HTML_PERSISTENT];
} else
#endif
{
hs->hdrs[HDR_STRINGS_IDX_CONTENT_TYPE] = g_psHTTPHeaderStrings[DEFAULT_404_HTML];
}
/* Set up to send the first header string. */
hs->hdr_index = 0;
hs->hdr_pos = 0;
return;
}
/* 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->hdrs[HDR_STRINGS_IDX_HTTP_STATUS] = g_psHTTPHeaderStrings[HTTP_HDR_NOT_FOUND];
} else if (strstr(uri, "400")) {
hs->hdrs[HDR_STRINGS_IDX_HTTP_STATUS] = g_psHTTPHeaderStrings[HTTP_HDR_BAD_REQUEST];
} else if (strstr(uri, "501")) {
hs->hdrs[HDR_STRINGS_IDX_HTTP_STATUS] = g_psHTTPHeaderStrings[HTTP_HDR_NOT_IMPL];
} else if (strstr(uri, "200")) {
hs->hdrs[HDR_STRINGS_IDX_HTTP_STATUS] = g_psHTTPHeaderStrings[HTTP_HDR_OK_11];
} else if (strstr(uri, "500")) {
hs->hdrs[HDR_STRINGS_IDX_HTTP_STATUS] = g_psHTTPHeaderStrings[HTTP_HDR_500];
} else if (strstr(uri, "401")) {
hs->hdrs[HDR_STRINGS_IDX_HTTP_STATUS] = g_psHTTPHeaderStrings[HTTP_HDR_401];
} else if (strstr(uri, "304")) {
hs->hdrs[HDR_STRINGS_IDX_HTTP_STATUS] = g_psHTTPHeaderStrings[HTTP_HDR_304];
} else if (strstr(uri, "409")) {
hs->hdrs[HDR_STRINGS_IDX_HTTP_STATUS] = g_psHTTPHeaderStrings[HTTP_HDR_409];
} else if (strstr(uri, "415")) {
hs->hdrs[HDR_STRINGS_IDX_HTTP_STATUS] = g_psHTTPHeaderStrings[HTTP_HDR_415];
} else if (strstr(uri, "503")) {
hs->hdrs[HDR_STRINGS_IDX_HTTP_STATUS] = g_psHTTPHeaderStrings[HTTP_HDR_503];
} else {
hs->hdrs[HDR_STRINGS_IDX_HTTP_STATUS] = g_psHTTPHeaderStrings[HTTP_HDR_OK];
}
/* Determine if the URI has any variables and, if so, temporarily remove
them. */
vars = strchr(uri, '?');
if (vars) {
*vars = '\0';
}
/* Get a pointer to the file extension. We find this by looking for the
last occurrence of "." in the filename passed. */
ext = NULL;
tmp = strchr(uri, '.');
while (tmp) {
ext = tmp + 1;
tmp = strchr(ext, '.');
}
if (ext != NULL) {
/* Now determine the content type and add the relevant header for that. */
for (content_type = 0; content_type < NUM_HTTP_HEADERS; content_type++) {
/* Have we found a matching extension? */
if (!lwip_stricmp(g_psHTTPHeaders[content_type].extension, ext)) {
break;
}
}
} else {
content_type = NUM_HTTP_HEADERS;
}
/* Reinstate the parameter marker if there was one in the original URI. */
if (vars) {
*vars = '?';
}
#if LWIP_HTTPD_OMIT_HEADER_FOR_EXTENSIONLESS_URI
/* Does the URL passed have any file extension? If not, we assume it
is a special-case URL used for control state notification and we do
not send any HTTP headers with the response. */
if (!ext) {
/* Force the header index to a value indicating that all headers
have already been sent. */
hs->hdr_index = NUM_FILE_HDR_STRINGS;
return;
}
#endif /* LWIP_HTTPD_OMIT_HEADER_FOR_EXTENSIONLESS_URI */
/* Did we find a matching extension? */
if (content_type < NUM_HTTP_HEADERS) {
/* yes, store it */
hs->hdrs[HDR_STRINGS_IDX_CONTENT_TYPE] = g_psHTTPHeaders[content_type].content_type;
} else if (!ext) {
/* no, no extension found -> use binary transfer to prevent the browser adding '.txt' on save */
hs->hdrs[HDR_STRINGS_IDX_CONTENT_TYPE] = HTTP_HDR_APP;
} else {
/* No - use the default, plain text file type. */
hs->hdrs[HDR_STRINGS_IDX_CONTENT_TYPE] = HTTP_HDR_DEFAULT_TYPE;
}
/* Set up to send the first header string. */
hs->hdr_index = 0;
hs->hdr_pos = 0;
}
/* Add content-length header? */
static void
get_http_content_length(struct http_state *hs) {
u8_t add_content_len = 0;
LWIP_ASSERT("already been here?", hs->hdrs[HDR_STRINGS_IDX_CONTENT_LEN_KEEPALIVE] == NULL);
add_content_len = 0;
#if LWIP_HTTPD_SSI
if (hs->ssi == NULL) /* @todo: get maximum file length from SSI */
#endif /* LWIP_HTTPD_SSI */
{
if ((hs->handle != NULL) && (hs->handle->flags & FS_FILE_FLAGS_HEADER_PERSISTENT)) {
add_content_len = 1;
}
}
if (add_content_len) {
size_t len;
lwip_itoa(hs->hdr_content_len, (size_t)LWIP_HTTPD_MAX_CONTENT_LEN_SIZE,
hs->handle->len);
len = strlen(hs->hdr_content_len);
if (len <= LWIP_HTTPD_MAX_CONTENT_LEN_SIZE - LWIP_HTTPD_MAX_CONTENT_LEN_OFFSET) {
SMEMCPY(&hs->hdr_content_len[len], CRLF, 3);
hs->hdrs[HDR_STRINGS_IDX_CONTENT_LEN_NR] = hs->hdr_content_len;
} else {
add_content_len = 0;
}
}
#if LWIP_HTTPD_SUPPORT_11_KEEPALIVE
if (add_content_len) {
hs->hdrs[HDR_STRINGS_IDX_CONTENT_LEN_KEEPALIVE] = g_psHTTPHeaderStrings[HTTP_HDR_KEEPALIVE_LEN];
} else {
hs->hdrs[HDR_STRINGS_IDX_CONTENT_LEN_KEEPALIVE] = g_psHTTPHeaderStrings[HTTP_HDR_CONN_CLOSE];
hs->keepalive = 0;
}
#else /* LWIP_HTTPD_SUPPORT_11_KEEPALIVE */
if (add_content_len) {
hs->hdrs[HDR_STRINGS_IDX_CONTENT_LEN_KEEPALIVE] = g_psHTTPHeaderStrings[HTTP_HDR_CONTENT_LENGTH];
}