• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * @file
3  * LWIP HTTP server implementation
4  */
5 
6 /*
7  * Copyright (c) 2001-2003 Swedish Institute of Computer Science.
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without modification,
11  * are permitted provided that the following conditions are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright notice,
14  *    this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright notice,
16  *    this list of conditions and the following disclaimer in the documentation
17  *    and/or other materials provided with the distribution.
18  * 3. The name of the author may not be used to endorse or promote products
19  *    derived from this software without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
22  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
23  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
24  * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
25  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
26  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
29  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
30  * OF SUCH DAMAGE.
31  *
32  * This file is part of the lwIP TCP/IP stack.
33  *
34  * Author: Adam Dunkels <adam@sics.se>
35  *         Simon Goldschmidt
36  *
37  */
38 
39 /**
40  * @defgroup httpd HTTP server
41  * @ingroup apps
42  *
43  * This httpd supports for a
44  * rudimentary server-side-include facility which will replace tags of the form
45  * <!--#tag--> in any file whose extension is .shtml, .shtm or .ssi with
46  * strings provided by an include handler whose pointer is provided to the
47  * module via function http_set_ssi_handler().
48  * Additionally, a simple common
49  * gateway interface (CGI) handling mechanism has been added to allow clients
50  * to hook functions to particular request URIs.
51  *
52  * To enable SSI support, define label LWIP_HTTPD_SSI in lwipopts.h.
53  * To enable CGI support, define label LWIP_HTTPD_CGI in lwipopts.h.
54  *
55  * By default, the server assumes that HTTP headers are already present in
56  * each file stored in the file system.  By defining LWIP_HTTPD_DYNAMIC_HEADERS in
57  * lwipopts.h, this behavior can be changed such that the server inserts the
58  * headers automatically based on the extension of the file being served.  If
59  * this mode is used, be careful to ensure that the file system image used
60  * does not already contain the header information.
61  *
62  * File system images without headers can be created using the makefsfile
63  * tool with the -h command line option.
64  *
65  *
66  * Notes about valid SSI tags
67  * --------------------------
68  *
69  * The following assumptions are made about tags used in SSI markers:
70  *
71  * 1. No tag may contain '-' or whitespace characters within the tag name.
72  * 2. Whitespace is allowed between the tag leadin "<!--#" and the start of
73  *    the tag name and between the tag name and the leadout string "-->".
74  * 3. The maximum tag name length is LWIP_HTTPD_MAX_TAG_NAME_LEN, currently 8 characters.
75  *
76  * Notes on CGI usage
77  * ------------------
78  *
79  * The simple CGI support offered here works with GET method requests only
80  * and can handle up to 16 parameters encoded into the URI. The handler
81  * function may not write directly to the HTTP output but must return a
82  * filename that the HTTP server will send to the browser as a response to
83  * the incoming CGI request.
84  *
85  *
86  *
87  * The list of supported file types is quite short, so if makefsdata complains
88  * about an unknown extension, make sure to add it (and its doctype) to
89  * the 'g_psHTTPHeaders' list.
90  */
91 #include "lwip/init.h"
92 #include "lwip/apps/httpd.h"
93 #include "lwip/debug.h"
94 #include "lwip/stats.h"
95 #include "lwip/apps/fs.h"
96 #include "httpd_structs.h"
97 #include "lwip/def.h"
98 
99 #include "lwip/altcp.h"
100 #include "lwip/altcp_tcp.h"
101 #if HTTPD_ENABLE_HTTPS
102 #include "lwip/altcp_tls.h"
103 #endif
104 #ifdef LWIP_HOOK_FILENAME
105 #include LWIP_HOOK_FILENAME
106 #endif
107 #if LWIP_HTTPD_TIMING
108 #include "lwip/sys.h"
109 #endif /* LWIP_HTTPD_TIMING */
110 
111 #include <string.h> /* memset */
112 #include <stdlib.h> /* atoi */
113 #include <stdio.h>
114 
115 #if LWIP_TCP && LWIP_CALLBACK_API
116 
117 /** Minimum length for a valid HTTP/0.9 request: "GET /\r\n" -> 7 bytes */
118 #define MIN_REQ_LEN   7
119 
120 #define CRLF "\r\n"
121 #if LWIP_HTTPD_SUPPORT_11_KEEPALIVE
122 #define HTTP11_CONNECTIONKEEPALIVE  "Connection: keep-alive"
123 #define HTTP11_CONNECTIONKEEPALIVE2 "Connection: Keep-Alive"
124 #endif
125 
126 #if LWIP_HTTPD_DYNAMIC_FILE_READ
127 #define HTTP_IS_DYNAMIC_FILE(hs) ((hs)->buf != NULL)
128 #else
129 #define HTTP_IS_DYNAMIC_FILE(hs) 0
130 #endif
131 
132 /* This defines checks whether tcp_write has to copy data or not */
133 
134 #ifndef HTTP_IS_DATA_VOLATILE
135 /** tcp_write does not have to copy data when sent from rom-file-system directly */
136 #define HTTP_IS_DATA_VOLATILE(hs)       (HTTP_IS_DYNAMIC_FILE(hs) ? TCP_WRITE_FLAG_COPY : 0)
137 #endif
138 /** Default: dynamic headers are sent from ROM (non-dynamic headers are handled like file data) */
139 #ifndef HTTP_IS_HDR_VOLATILE
140 #define HTTP_IS_HDR_VOLATILE(hs, ptr)   0
141 #endif
142 
143 /* Return values for http_send_*() */
144 #define HTTP_DATA_TO_SEND_FREED    3
145 #define HTTP_DATA_TO_SEND_BREAK    2
146 #define HTTP_DATA_TO_SEND_CONTINUE 1
147 #define HTTP_NO_DATA_TO_SEND       0
148 
149 typedef struct {
150   const char *name;
151   u8_t shtml;
152 } default_filename;
153 
154 static const default_filename httpd_default_filenames[] = {
155   {"/index.shtml", 1 },
156   {"/index.ssi",   1 },
157   {"/index.shtm",  1 },
158   {"/index.html",  0 },
159   {"/index.htm",   0 }
160 };
161 
162 #define NUM_DEFAULT_FILENAMES LWIP_ARRAYSIZE(httpd_default_filenames)
163 
164 #if LWIP_HTTPD_SUPPORT_REQUESTLIST
165 /** HTTP request is copied here from pbufs for simple parsing */
166 static char httpd_req_buf[LWIP_HTTPD_MAX_REQ_LENGTH + 1];
167 #endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */
168 
169 #if LWIP_HTTPD_SUPPORT_POST
170 #if LWIP_HTTPD_POST_MAX_RESPONSE_URI_LEN > LWIP_HTTPD_MAX_REQUEST_URI_LEN
171 #define LWIP_HTTPD_URI_BUF_LEN LWIP_HTTPD_POST_MAX_RESPONSE_URI_LEN
172 #endif
173 #endif
174 #ifndef LWIP_HTTPD_URI_BUF_LEN
175 #define LWIP_HTTPD_URI_BUF_LEN LWIP_HTTPD_MAX_REQUEST_URI_LEN
176 #endif
177 #if LWIP_HTTPD_URI_BUF_LEN
178 /* Filename for response file to send when POST is finished or
179  * search for default files when a directory is requested. */
180 static char http_uri_buf[LWIP_HTTPD_URI_BUF_LEN + 1];
181 #endif
182 
183 #if LWIP_HTTPD_DYNAMIC_HEADERS
184 /* The number of individual strings that comprise the headers sent before each
185  * requested file.
186  */
187 #define NUM_FILE_HDR_STRINGS 5
188 #define HDR_STRINGS_IDX_HTTP_STATUS           0 /* e.g. "HTTP/1.0 200 OK\r\n" */
189 #define HDR_STRINGS_IDX_SERVER_NAME           1 /* e.g. "Server: "HTTPD_SERVER_AGENT"\r\n" */
190 #define HDR_STRINGS_IDX_CONTENT_LEN_KEEPALIVE 2 /* e.g. "Content-Length: xy\r\n" and/or "Connection: keep-alive\r\n" */
191 #define HDR_STRINGS_IDX_CONTENT_LEN_NR        3 /* the byte count, when content-length is used */
192 #define HDR_STRINGS_IDX_CONTENT_TYPE          4 /* the content type (or default answer content type including default document) */
193 
194 /* The dynamically generated Content-Length buffer needs space for CRLF + NULL */
195 #define LWIP_HTTPD_MAX_CONTENT_LEN_OFFSET 3
196 #ifndef LWIP_HTTPD_MAX_CONTENT_LEN_SIZE
197 /* The dynamically generated Content-Length buffer shall be able to work with
198    ~953 MB (9 digits) */
199 #define LWIP_HTTPD_MAX_CONTENT_LEN_SIZE   (9 + LWIP_HTTPD_MAX_CONTENT_LEN_OFFSET)
200 #endif
201 #endif /* LWIP_HTTPD_DYNAMIC_HEADERS */
202 
203 #if LWIP_HTTPD_SSI
204 
205 #define HTTPD_LAST_TAG_PART 0xFFFF
206 
207 enum tag_check_state {
208   TAG_NONE,       /* Not processing an SSI tag */
209   TAG_LEADIN,     /* Tag lead in "<!--#" being processed */
210   TAG_FOUND,      /* Tag name being read, looking for lead-out start */
211   TAG_LEADOUT,    /* Tag lead out "-->" being processed */
212   TAG_SENDING     /* Sending tag replacement string */
213 };
214 
215 struct http_ssi_state {
216   const char *parsed;     /* Pointer to the first unparsed byte in buf. */
217 #if !LWIP_HTTPD_SSI_INCLUDE_TAG
218   const char *tag_started;/* Pointer to the first opening '<' of the tag. */
219 #endif /* !LWIP_HTTPD_SSI_INCLUDE_TAG */
220   const char *tag_end;    /* Pointer to char after the closing '>' of the tag. */
221   u32_t parse_left; /* Number of unparsed bytes in buf. */
222   u16_t tag_index;   /* Counter used by tag parsing state machine */
223   u16_t tag_insert_len; /* Length of insert in string tag_insert */
224 #if LWIP_HTTPD_SSI_MULTIPART
225   u16_t tag_part; /* Counter passed to and changed by tag insertion function to insert multiple times */
226 #endif /* LWIP_HTTPD_SSI_MULTIPART */
227   u8_t tag_type; /* index into http_ssi_tag_desc array */
228   u8_t tag_name_len; /* Length of the tag name in string tag_name */
229   char tag_name[LWIP_HTTPD_MAX_TAG_NAME_LEN + 1]; /* Last tag name extracted */
230   char tag_insert[LWIP_HTTPD_MAX_TAG_INSERT_LEN + 1]; /* Insert string for tag_name */
231   enum tag_check_state tag_state; /* State of the tag processor */
232 };
233 
234 struct http_ssi_tag_description {
235   const char *lead_in;
236   const char *lead_out;
237 };
238 
239 #endif /* LWIP_HTTPD_SSI */
240 
241 struct http_state {
242 #if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED
243   struct http_state *next;
244 #endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */
245   struct fs_file file_handle;
246   struct fs_file *handle;
247   const char *file;       /* Pointer to first unsent byte in buf. */
248 
249   struct altcp_pcb *pcb;
250 #if LWIP_HTTPD_SUPPORT_REQUESTLIST
251   struct pbuf *req;
252 #endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */
253 
254 #if LWIP_HTTPD_DYNAMIC_FILE_READ
255   char *buf;        /* File read buffer. */
256   int buf_len;      /* Size of file read buffer, buf. */
257 #endif /* LWIP_HTTPD_DYNAMIC_FILE_READ */
258   u32_t left;       /* Number of unsent bytes in buf. */
259   u8_t retries;
260 #if LWIP_HTTPD_SUPPORT_11_KEEPALIVE
261   u8_t keepalive;
262 #endif /* LWIP_HTTPD_SUPPORT_11_KEEPALIVE */
263 #if LWIP_HTTPD_SSI
264   struct http_ssi_state *ssi;
265 #endif /* LWIP_HTTPD_SSI */
266 #if LWIP_HTTPD_CGI
267   char *params[LWIP_HTTPD_MAX_CGI_PARAMETERS]; /* Params extracted from the request URI */
268   char *param_vals[LWIP_HTTPD_MAX_CGI_PARAMETERS]; /* Values for each extracted param */
269 #endif /* LWIP_HTTPD_CGI */
270 #if LWIP_HTTPD_DYNAMIC_HEADERS
271   const char *hdrs[NUM_FILE_HDR_STRINGS]; /* HTTP headers to be sent. */
272   char hdr_content_len[LWIP_HTTPD_MAX_CONTENT_LEN_SIZE];
273   u16_t hdr_pos;     /* The position of the first unsent header byte in the
274                         current string */
275   u16_t hdr_index;   /* The index of the hdr string currently being sent. */
276 #endif /* LWIP_HTTPD_DYNAMIC_HEADERS */
277 #if LWIP_HTTPD_TIMING
278   u32_t time_started;
279 #endif /* LWIP_HTTPD_TIMING */
280 #if LWIP_HTTPD_SUPPORT_POST
281   u32_t post_content_len_left;
282 #if LWIP_HTTPD_POST_MANUAL_WND
283   u32_t unrecved_bytes;
284   u8_t no_auto_wnd;
285   u8_t post_finished;
286 #endif /* LWIP_HTTPD_POST_MANUAL_WND */
287 #endif /* LWIP_HTTPD_SUPPORT_POST*/
288 };
289 
290 #if HTTPD_USE_MEM_POOL
291 LWIP_MEMPOOL_DECLARE(HTTPD_STATE,     MEMP_NUM_PARALLEL_HTTPD_CONNS,     sizeof(struct http_state),     "HTTPD_STATE")
292 #if LWIP_HTTPD_SSI
293 LWIP_MEMPOOL_DECLARE(HTTPD_SSI_STATE, MEMP_NUM_PARALLEL_HTTPD_SSI_CONNS, sizeof(struct http_ssi_state), "HTTPD_SSI_STATE")
294 #define HTTP_FREE_SSI_STATE(x)  LWIP_MEMPOOL_FREE(HTTPD_SSI_STATE, (x))
295 #define HTTP_ALLOC_SSI_STATE()  (struct http_ssi_state *)LWIP_MEMPOOL_ALLOC(HTTPD_SSI_STATE)
296 #endif /* LWIP_HTTPD_SSI */
297 #define HTTP_ALLOC_HTTP_STATE() (struct http_state *)LWIP_MEMPOOL_ALLOC(HTTPD_STATE)
298 #define HTTP_FREE_HTTP_STATE(x) LWIP_MEMPOOL_FREE(HTTPD_STATE, (x))
299 #else /* HTTPD_USE_MEM_POOL */
300 #define HTTP_ALLOC_HTTP_STATE() (struct http_state *)mem_malloc(sizeof(struct http_state))
301 #define HTTP_FREE_HTTP_STATE(x) mem_free(x)
302 #if LWIP_HTTPD_SSI
303 #define HTTP_ALLOC_SSI_STATE()  (struct http_ssi_state *)mem_malloc(sizeof(struct http_ssi_state))
304 #define HTTP_FREE_SSI_STATE(x)  mem_free(x)
305 #endif /* LWIP_HTTPD_SSI */
306 #endif /* HTTPD_USE_MEM_POOL */
307 
308 static err_t http_close_conn(struct altcp_pcb *pcb, struct http_state *hs);
309 static err_t http_close_or_abort_conn(struct altcp_pcb *pcb, struct http_state *hs, u8_t abort_conn);
310 static err_t http_find_file(struct http_state *hs, const char *uri, int is_09);
311 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);
312 static err_t http_poll(void *arg, struct altcp_pcb *pcb);
313 static u8_t http_check_eof(struct altcp_pcb *pcb, struct http_state *hs);
314 #if LWIP_HTTPD_FS_ASYNC_READ
315 static void http_continue(void *connection);
316 #endif /* LWIP_HTTPD_FS_ASYNC_READ */
317 
318 #if LWIP_HTTPD_SSI
319 /* SSI insert handler function pointer. */
320 static tSSIHandler httpd_ssi_handler;
321 #if !LWIP_HTTPD_SSI_RAW
322 static int httpd_num_tags;
323 static const char **httpd_tags;
324 #endif /* !LWIP_HTTPD_SSI_RAW */
325 
326 /* Define the available tag lead-ins and corresponding lead-outs.
327  * ATTENTION: for the algorithm below using this array, it is essential
328  * that the lead in differs in the first character! */
329 const struct http_ssi_tag_description http_ssi_tag_desc[] = {
330   {"<!--#", "-->"},
331   {"/*#", "*/"}
332 };
333 
334 #endif /* LWIP_HTTPD_SSI */
335 
336 #if LWIP_HTTPD_CGI
337 /* CGI handler information */
338 static const tCGI *httpd_cgis;
339 static int httpd_num_cgis;
340 static int http_cgi_paramcount;
341 #define http_cgi_params     hs->params
342 #define http_cgi_param_vals hs->param_vals
343 #elif LWIP_HTTPD_CGI_SSI
344 static char *http_cgi_params[LWIP_HTTPD_MAX_CGI_PARAMETERS]; /* Params extracted from the request URI */
345 static char *http_cgi_param_vals[LWIP_HTTPD_MAX_CGI_PARAMETERS]; /* Values for each extracted param */
346 #endif /* LWIP_HTTPD_CGI */
347 
348 #if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED
349 /** global list of active HTTP connections, use to kill the oldest when
350     running out of memory */
351 static struct http_state *http_connections;
352 
353 static void
http_add_connection(struct http_state * hs)354 http_add_connection(struct http_state *hs)
355 {
356   /* add the connection to the list */
357   hs->next = http_connections;
358   http_connections = hs;
359 }
360 
361 static void
http_remove_connection(struct http_state * hs)362 http_remove_connection(struct http_state *hs)
363 {
364   /* take the connection off the list */
365   if (http_connections) {
366     if (http_connections == hs) {
367       http_connections = hs->next;
368     } else {
369       struct http_state *last;
370       for (last = http_connections; last->next != NULL; last = last->next) {
371         if (last->next == hs) {
372           last->next = hs->next;
373           break;
374         }
375       }
376     }
377   }
378 }
379 
380 static void
http_kill_oldest_connection(u8_t ssi_required)381 http_kill_oldest_connection(u8_t ssi_required)
382 {
383   struct http_state *hs = http_connections;
384   struct http_state *hs_free_next = NULL;
385   while (hs && hs->next) {
386 #if LWIP_HTTPD_SSI
387     if (ssi_required) {
388       if (hs->next->ssi != NULL) {
389         hs_free_next = hs;
390       }
391     } else
392 #else /* LWIP_HTTPD_SSI */
393     LWIP_UNUSED_ARG(ssi_required);
394 #endif /* LWIP_HTTPD_SSI */
395     {
396       hs_free_next = hs;
397     }
398     LWIP_ASSERT("broken list", hs != hs->next);
399     hs = hs->next;
400   }
401   if (hs_free_next != NULL) {
402     LWIP_ASSERT("hs_free_next->next != NULL", hs_free_next->next != NULL);
403     LWIP_ASSERT("hs_free_next->next->pcb != NULL", hs_free_next->next->pcb != NULL);
404     /* send RST when killing a connection because of memory shortage */
405     http_close_or_abort_conn(hs_free_next->next->pcb, hs_free_next->next, 1); /* this also unlinks the http_state from the list */
406   }
407 }
408 #else /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */
409 
410 #define http_add_connection(hs)
411 #define http_remove_connection(hs)
412 
413 #endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */
414 
415 #if LWIP_HTTPD_SSI
416 /** Allocate as struct http_ssi_state. */
417 static struct http_ssi_state *
http_ssi_state_alloc(void)418 http_ssi_state_alloc(void)
419 {
420   struct http_ssi_state *ret = HTTP_ALLOC_SSI_STATE();
421 #if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED
422   if (ret == NULL) {
423     http_kill_oldest_connection(1);
424     ret = HTTP_ALLOC_SSI_STATE();
425   }
426 #endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */
427   if (ret != NULL) {
428     memset(ret, 0, sizeof(struct http_ssi_state));
429   }
430   return ret;
431 }
432 
433 /** Free a struct http_ssi_state. */
434 static void
http_ssi_state_free(struct http_ssi_state * ssi)435 http_ssi_state_free(struct http_ssi_state *ssi)
436 {
437   if (ssi != NULL) {
438     HTTP_FREE_SSI_STATE(ssi);
439   }
440 }
441 #endif /* LWIP_HTTPD_SSI */
442 
443 /** Initialize a struct http_state.
444  */
445 static void
http_state_init(struct http_state * hs)446 http_state_init(struct http_state *hs)
447 {
448   /* Initialize the structure. */
449   memset(hs, 0, sizeof(struct http_state));
450 #if LWIP_HTTPD_DYNAMIC_HEADERS
451   /* Indicate that the headers are not yet valid */
452   hs->hdr_index = NUM_FILE_HDR_STRINGS;
453 #endif /* LWIP_HTTPD_DYNAMIC_HEADERS */
454 }
455 
456 /** Allocate a struct http_state. */
457 static struct http_state *
http_state_alloc(void)458 http_state_alloc(void)
459 {
460   struct http_state *ret = HTTP_ALLOC_HTTP_STATE();
461 #if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED
462   if (ret == NULL) {
463     http_kill_oldest_connection(0);
464     ret = HTTP_ALLOC_HTTP_STATE();
465   }
466 #endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */
467   if (ret != NULL) {
468     http_state_init(ret);
469     http_add_connection(ret);
470   }
471   return ret;
472 }
473 
474 /** Make sure the post code knows that the connection is closed */
475 static void
http_state_close_post(struct http_state * hs)476 http_state_close_post(struct http_state* hs)
477 {
478 #if LWIP_HTTPD_SUPPORT_POST
479   if (hs != NULL) {
480     if ((hs->post_content_len_left != 0)
481 #if LWIP_HTTPD_POST_MANUAL_WND
482       || ((hs->no_auto_wnd != 0) && (hs->unrecved_bytes != 0))
483 #endif /* LWIP_HTTPD_POST_MANUAL_WND */
484       ) {
485       /* prevent calling httpd_post_finished twice */
486       hs->post_content_len_left = 0;
487 #if LWIP_HTTPD_POST_MANUAL_WND
488       hs->unrecved_bytes = 0;
489 #endif /* LWIP_HTTPD_POST_MANUAL_WND */
490       /* make sure the post code knows that the connection is closed */
491       http_uri_buf[0] = 0;
492       httpd_post_finished(hs, http_uri_buf, LWIP_HTTPD_URI_BUF_LEN);
493     }
494   }
495 #else /* LWIP_HTTPD_SUPPORT_POST*/
496   LWIP_UNUSED_ARG(hs);
497 #endif /* LWIP_HTTPD_SUPPORT_POST*/
498 }
499 
500 /** Free a struct http_state.
501  * Also frees the file data if dynamic.
502  */
503 static void
http_state_eof(struct http_state * hs)504 http_state_eof(struct http_state *hs)
505 {
506   if (hs->handle) {
507 #if LWIP_HTTPD_TIMING
508     u32_t ms_needed = sys_now() - hs->time_started;
509     u32_t needed = LWIP_MAX(1, (ms_needed / 100));
510     LWIP_DEBUGF(HTTPD_DEBUG_TIMING, ("httpd: needed %"U32_F" ms to send file of %d bytes -> %"U32_F" bytes/sec\n",
511                                      ms_needed, hs->handle->len, ((((u32_t)hs->handle->len) * 10) / needed)));
512 #endif /* LWIP_HTTPD_TIMING */
513     fs_close(hs->handle);
514     hs->handle = NULL;
515   }
516 #if LWIP_HTTPD_DYNAMIC_FILE_READ
517   if (hs->buf != NULL) {
518     mem_free(hs->buf);
519     hs->buf = NULL;
520   }
521 #endif /* LWIP_HTTPD_DYNAMIC_FILE_READ */
522 #if LWIP_HTTPD_SSI
523   if (hs->ssi) {
524     http_ssi_state_free(hs->ssi);
525     hs->ssi = NULL;
526   }
527 #endif /* LWIP_HTTPD_SSI */
528 #if LWIP_HTTPD_SUPPORT_REQUESTLIST
529   if (hs->req) {
530     pbuf_free(hs->req);
531     hs->req = NULL;
532   }
533 #endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */
534   http_state_close_post(hs);
535 }
536 
537 /** Free a struct http_state.
538  * Also frees the file data if dynamic.
539  */
540 static void
http_state_free(struct http_state * hs)541 http_state_free(struct http_state *hs)
542 {
543   if (hs != NULL) {
544     http_state_eof(hs);
545     http_remove_connection(hs);
546     HTTP_FREE_HTTP_STATE(hs);
547   }
548 }
549 
550 /** Call tcp_write() in a loop trying smaller and smaller length
551  *
552  * @param pcb altcp_pcb to send
553  * @param ptr Data to send
554  * @param length Length of data to send (in/out: on return, contains the
555  *        amount of data sent)
556  * @param apiflags directly passed to tcp_write
557  * @return the return value of tcp_write
558  */
559 static err_t
http_write(struct altcp_pcb * pcb,const void * ptr,u16_t * length,u8_t apiflags)560 http_write(struct altcp_pcb *pcb, const void *ptr, u16_t *length, u8_t apiflags)
561 {
562   u16_t len, max_len;
563   err_t err;
564   LWIP_ASSERT("length != NULL", length != NULL);
565   len = *length;
566   if (len == 0) {
567     return ERR_OK;
568   }
569   /* We cannot send more data than space available in the send buffer. */
570   max_len = altcp_sndbuf(pcb);
571   if (max_len < len) {
572     len = max_len;
573   }
574 #ifdef HTTPD_MAX_WRITE_LEN
575   /* Additional limitation: e.g. don't enqueue more than 2*mss at once */
576   max_len = HTTPD_MAX_WRITE_LEN(pcb);
577   if (len > max_len) {
578     len = max_len;
579   }
580 #endif /* HTTPD_MAX_WRITE_LEN */
581   do {
582     LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Trying to send %d bytes\n", len));
583     err = altcp_write(pcb, ptr, len, apiflags);
584     if (err == ERR_MEM) {
585       if ((altcp_sndbuf(pcb) == 0) ||
586           (altcp_sndqueuelen(pcb) >= TCP_SND_QUEUELEN)) {
587         /* no need to try smaller sizes */
588         len = 1;
589       } else {
590         len /= 2;
591       }
592       LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE,
593                   ("Send failed, trying less (%d bytes)\n", len));
594     }
595   } while ((err == ERR_MEM) && (len > 1));
596 
597   if (err == ERR_OK) {
598     LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Sent %d bytes\n", len));
599     *length = len;
600   } else {
601     LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Send failed with err %d (\"%s\")\n", err, lwip_strerr(err)));
602     *length = 0;
603   }
604 
605 #if LWIP_HTTPD_SUPPORT_11_KEEPALIVE
606   /* ensure nagle is normally enabled (only disabled for persistent connections
607      when all data has been enqueued but the connection stays open for the next
608      request */
609   altcp_nagle_enable(pcb);
610 #endif
611 
612   return err;
613 }
614 
615 /**
616  * The connection shall be actively closed (using RST to close from fault states).
617  * Reset the sent- and recv-callbacks.
618  *
619  * @param pcb the tcp pcb to reset callbacks
620  * @param hs connection state to free
621  */
622 static err_t
http_close_or_abort_conn(struct altcp_pcb * pcb,struct http_state * hs,u8_t abort_conn)623 http_close_or_abort_conn(struct altcp_pcb *pcb, struct http_state *hs, u8_t abort_conn)
624 {
625   err_t err;
626   LWIP_DEBUGF(HTTPD_DEBUG, ("Closing connection %p\n", (void *)pcb));
627 
628   http_state_close_post(hs);
629 
630   altcp_arg(pcb, NULL);
631   altcp_recv(pcb, NULL);
632   altcp_err(pcb, NULL);
633   altcp_poll(pcb, NULL, 0);
634   altcp_sent(pcb, NULL);
635   if (hs != NULL) {
636     http_state_free(hs);
637   }
638 
639   if (abort_conn) {
640     altcp_abort(pcb);
641     return ERR_OK;
642   }
643   err = altcp_close(pcb);
644   if (err != ERR_OK) {
645     LWIP_DEBUGF(HTTPD_DEBUG, ("Error %d closing %p\n", err, (void *)pcb));
646     /* error closing, try again later in poll */
647     altcp_poll(pcb, http_poll, HTTPD_POLL_INTERVAL);
648   }
649   return err;
650 }
651 
652 /**
653  * The connection shall be actively closed.
654  * Reset the sent- and recv-callbacks.
655  *
656  * @param pcb the tcp pcb to reset callbacks
657  * @param hs connection state to free
658  */
659 static err_t
http_close_conn(struct altcp_pcb * pcb,struct http_state * hs)660 http_close_conn(struct altcp_pcb *pcb, struct http_state *hs)
661 {
662   return http_close_or_abort_conn(pcb, hs, 0);
663 }
664 
665 /** End of file: either close the connection (Connection: close) or
666  * close the file (Connection: keep-alive)
667  */
668 static void
http_eof(struct altcp_pcb * pcb,struct http_state * hs)669 http_eof(struct altcp_pcb *pcb, struct http_state *hs)
670 {
671   /* HTTP/1.1 persistent connection? (Not supported for SSI) */
672 #if LWIP_HTTPD_SUPPORT_11_KEEPALIVE
673   if (hs->keepalive) {
674     http_remove_connection(hs);
675 
676     http_state_eof(hs);
677     http_state_init(hs);
678     /* restore state: */
679     hs->pcb = pcb;
680     hs->keepalive = 1;
681     http_add_connection(hs);
682     /* ensure nagle doesn't interfere with sending all data as fast as possible: */
683     altcp_nagle_disable(pcb);
684   } else
685 #endif /* LWIP_HTTPD_SUPPORT_11_KEEPALIVE */
686   {
687     http_close_conn(pcb, hs);
688   }
689 }
690 
691 #if LWIP_HTTPD_CGI || LWIP_HTTPD_CGI_SSI
692 /**
693  * Extract URI parameters from the parameter-part of an URI in the form
694  * "test.cgi?x=y" @todo: better explanation!
695  * Pointers to the parameters are stored in hs->param_vals.
696  *
697  * @param hs http connection state
698  * @param params pointer to the NULL-terminated parameter string from the URI
699  * @return number of parameters extracted
700  */
701 static int
extract_uri_parameters(struct http_state * hs,char * params)702 extract_uri_parameters(struct http_state *hs, char *params)
703 {
704   char *pair;
705   char *equals;
706   int loop;
707 
708   LWIP_UNUSED_ARG(hs);
709 
710   /* If we have no parameters at all, return immediately. */
711   if (!params || (params[0] == '\0')) {
712     return (0);
713   }
714 
715   /* Get a pointer to our first parameter */
716   pair = params;
717 
718   /* Parse up to LWIP_HTTPD_MAX_CGI_PARAMETERS from the passed string and ignore the
719    * remainder (if any) */
720   for (loop = 0; (loop < LWIP_HTTPD_MAX_CGI_PARAMETERS) && pair; loop++) {
721 
722     /* Save the name of the parameter */
723     http_cgi_params[loop] = pair;
724 
725     /* Remember the start of this name=value pair */
726     equals = pair;
727 
728     /* Find the start of the next name=value pair and replace the delimiter
729      * with a 0 to terminate the previous pair string. */
730     pair = strchr(pair, '&');
731     if (pair) {
732       *pair = '\0';
733       pair++;
734     } else {
735       /* We didn't find a new parameter so find the end of the URI and
736        * replace the space with a '\0' */
737       pair = strchr(equals, ' ');
738       if (pair) {
739         *pair = '\0';
740       }
741 
742       /* Revert to NULL so that we exit the loop as expected. */
743       pair = NULL;
744     }
745 
746     /* Now find the '=' in the previous pair, replace it with '\0' and save
747      * the parameter value string. */
748     equals = strchr(equals, '=');
749     if (equals) {
750       *equals = '\0';
751       http_cgi_param_vals[loop] = equals + 1;
752     } else {
753       http_cgi_param_vals[loop] = NULL;
754     }
755   }
756 
757   return loop;
758 }
759 #endif /* LWIP_HTTPD_CGI || LWIP_HTTPD_CGI_SSI */
760 
761 #if LWIP_HTTPD_SSI
762 /**
763  * Insert a tag (found in an shtml in the form of "<!--#tagname-->" into the file.
764  * The tag's name is stored in ssi->tag_name (NULL-terminated), the replacement
765  * should be written to hs->tag_insert (up to a length of LWIP_HTTPD_MAX_TAG_INSERT_LEN).
766  * The amount of data written is stored to ssi->tag_insert_len.
767  *
768  * @todo: return tag_insert_len - maybe it can be removed from struct http_state?
769  *
770  * @param hs http connection state
771  */
772 static void
get_tag_insert(struct http_state * hs)773 get_tag_insert(struct http_state *hs)
774 {
775 #if LWIP_HTTPD_SSI_RAW
776   const char *tag;
777 #else /* LWIP_HTTPD_SSI_RAW */
778   int tag;
779 #endif /* LWIP_HTTPD_SSI_RAW */
780   size_t len;
781   struct http_ssi_state *ssi;
782 #if LWIP_HTTPD_SSI_MULTIPART
783   u16_t current_tag_part;
784 #endif /* LWIP_HTTPD_SSI_MULTIPART */
785 
786   LWIP_ASSERT("hs != NULL", hs != NULL);
787   ssi = hs->ssi;
788   LWIP_ASSERT("ssi != NULL", ssi != NULL);
789 #if LWIP_HTTPD_SSI_MULTIPART
790   current_tag_part = ssi->tag_part;
791   ssi->tag_part = HTTPD_LAST_TAG_PART;
792 #endif /* LWIP_HTTPD_SSI_MULTIPART */
793 #if LWIP_HTTPD_SSI_RAW
794   tag = ssi->tag_name;
795 #endif
796 
797   if (httpd_ssi_handler
798 #if !LWIP_HTTPD_SSI_RAW
799       && httpd_tags && httpd_num_tags
800 #endif /* !LWIP_HTTPD_SSI_RAW */
801      ) {
802 
803     /* Find this tag in the list we have been provided. */
804 #if LWIP_HTTPD_SSI_RAW
805     {
806 #else /* LWIP_HTTPD_SSI_RAW */
807     for (tag = 0; tag < httpd_num_tags; tag++) {
808       if (strcmp(ssi->tag_name, httpd_tags[tag]) == 0)
809 #endif /* LWIP_HTTPD_SSI_RAW */
810       {
811         ssi->tag_insert_len = httpd_ssi_handler(tag, ssi->tag_insert,
812                                               LWIP_HTTPD_MAX_TAG_INSERT_LEN
813 #if LWIP_HTTPD_SSI_MULTIPART
814                                               , current_tag_part, &ssi->tag_part
815 #endif /* LWIP_HTTPD_SSI_MULTIPART */
816 #if LWIP_HTTPD_FILE_STATE
817                                               , (hs->handle ? hs->handle->state : NULL)
818 #endif /* LWIP_HTTPD_FILE_STATE */
819                                              );
820 #if LWIP_HTTPD_SSI_RAW
821         if (ssi->tag_insert_len != HTTPD_SSI_TAG_UNKNOWN)
822 #endif /* LWIP_HTTPD_SSI_RAW */
823         {
824           return;
825         }
826       }
827     }
828   }
829 
830   /* If we drop out, we were asked to serve a page which contains tags that
831    * we don't have a handler for. Merely echo back the tags with an error
832    * marker. */
833 #define UNKNOWN_TAG1_TEXT "<b>***UNKNOWN TAG "
834 #define UNKNOWN_TAG1_LEN  18
835 #define UNKNOWN_TAG2_TEXT "***</b>"
836 #define UNKNOWN_TAG2_LEN  7
837   len = LWIP_MIN(sizeof(ssi->tag_name), LWIP_MIN(strlen(ssi->tag_name),
838                  LWIP_HTTPD_MAX_TAG_INSERT_LEN - (UNKNOWN_TAG1_LEN + UNKNOWN_TAG2_LEN)));
839   MEMCPY(ssi->tag_insert, UNKNOWN_TAG1_TEXT, UNKNOWN_TAG1_LEN);
840   MEMCPY(&ssi->tag_insert[UNKNOWN_TAG1_LEN], ssi->tag_name, len);
841   MEMCPY(&ssi->tag_insert[UNKNOWN_TAG1_LEN + len], UNKNOWN_TAG2_TEXT, UNKNOWN_TAG2_LEN);
842   ssi->tag_insert[UNKNOWN_TAG1_LEN + len + UNKNOWN_TAG2_LEN] = 0;
843 
844   len = strlen(ssi->tag_insert);
845   LWIP_ASSERT("len <= 0xffff", len <= 0xffff);
846   ssi->tag_insert_len = (u16_t)len;
847 }
848 #endif /* LWIP_HTTPD_SSI */
849 
850 #if LWIP_HTTPD_DYNAMIC_HEADERS
851 /**
852  * Generate the relevant HTTP headers for the given filename and write
853  * them into the supplied buffer.
854  */
855 static void
856 get_http_headers(struct http_state *hs, const char *uri)
857 {
858   size_t content_type;
859   char *tmp;
860   char *ext;
861   char *vars;
862 
863   /* In all cases, the second header we send is the server identification
864      so set it here. */
865   hs->hdrs[HDR_STRINGS_IDX_SERVER_NAME] = g_psHTTPHeaderStrings[HTTP_HDR_SERVER];
866   hs->hdrs[HDR_STRINGS_IDX_CONTENT_LEN_KEEPALIVE] = NULL;
867   hs->hdrs[HDR_STRINGS_IDX_CONTENT_LEN_NR] = NULL;
868 
869   /* Is this a normal file or the special case we use to send back the
870      default "404: Page not found" response? */
871   if (uri == NULL) {
872     hs->hdrs[HDR_STRINGS_IDX_HTTP_STATUS] = g_psHTTPHeaderStrings[HTTP_HDR_NOT_FOUND];
873 #if LWIP_HTTPD_SUPPORT_11_KEEPALIVE
874     if (hs->keepalive) {
875       hs->hdrs[HDR_STRINGS_IDX_CONTENT_TYPE] = g_psHTTPHeaderStrings[DEFAULT_404_HTML_PERSISTENT];
876     } else
877 #endif
878     {
879       hs->hdrs[HDR_STRINGS_IDX_CONTENT_TYPE] = g_psHTTPHeaderStrings[DEFAULT_404_HTML];
880     }
881 
882     /* Set up to send the first header string. */
883     hs->hdr_index = 0;
884     hs->hdr_pos = 0;
885     return;
886   }
887   /* We are dealing with a particular filename. Look for one other
888      special case.  We assume that any filename with "404" in it must be
889      indicative of a 404 server error whereas all other files require
890      the 200 OK header. */
891   if (memcmp(uri, "/404.", 5) == 0) {
892     hs->hdrs[HDR_STRINGS_IDX_HTTP_STATUS] = g_psHTTPHeaderStrings[HTTP_HDR_NOT_FOUND];
893   } else if (memcmp(uri, "/400.", 5) == 0) {
894     hs->hdrs[HDR_STRINGS_IDX_HTTP_STATUS] = g_psHTTPHeaderStrings[HTTP_HDR_BAD_REQUEST];
895   } else if (memcmp(uri, "/501.", 5) == 0) {
896     hs->hdrs[HDR_STRINGS_IDX_HTTP_STATUS] = g_psHTTPHeaderStrings[HTTP_HDR_NOT_IMPL];
897   } else {
898     hs->hdrs[HDR_STRINGS_IDX_HTTP_STATUS] = g_psHTTPHeaderStrings[HTTP_HDR_OK];
899   }
900 
901   /* Determine if the URI has any variables and, if so, temporarily remove
902       them. */
903   vars = strchr(uri, '?');
904   if (vars) {
905     *vars = '\0';
906   }
907 
908   /* Get a pointer to the file extension.  We find this by looking for the
909       last occurrence of "." in the filename passed. */
910   ext = NULL;
911   tmp = strchr(uri, '.');
912   while (tmp) {
913     ext = tmp + 1;
914     tmp = strchr(ext, '.');
915   }
916   if (ext != NULL) {
917     /* Now determine the content type and add the relevant header for that. */
918     for (content_type = 0; content_type < NUM_HTTP_HEADERS; content_type++) {
919       /* Have we found a matching extension? */
920       if (!lwip_stricmp(g_psHTTPHeaders[content_type].extension, ext)) {
921         break;
922       }
923     }
924   } else {
925     content_type = NUM_HTTP_HEADERS;
926   }
927 
928   /* Reinstate the parameter marker if there was one in the original URI. */
929   if (vars) {
930     *vars = '?';
931   }
932 
933 #if LWIP_HTTPD_OMIT_HEADER_FOR_EXTENSIONLESS_URI
934   /* Does the URL passed have any file extension?  If not, we assume it
935      is a special-case URL used for control state notification and we do
936      not send any HTTP headers with the response. */
937   if (!ext) {
938     /* Force the header index to a value indicating that all headers
939        have already been sent. */
940     hs->hdr_index = NUM_FILE_HDR_STRINGS;
941     return;
942   }
943 #endif /* LWIP_HTTPD_OMIT_HEADER_FOR_EXTENSIONLESS_URI */
944   /* Did we find a matching extension? */
945   if (content_type < NUM_HTTP_HEADERS) {
946     /* yes, store it */
947     hs->hdrs[HDR_STRINGS_IDX_CONTENT_TYPE] = g_psHTTPHeaders[content_type].content_type;
948   } else if (!ext) {
949     /* no, no extension found -> use binary transfer to prevent the browser adding '.txt' on save */
950     hs->hdrs[HDR_STRINGS_IDX_CONTENT_TYPE] = HTTP_HDR_APP;
951   } else {
952     /* No - use the default, plain text file type. */
953     hs->hdrs[HDR_STRINGS_IDX_CONTENT_TYPE] = HTTP_HDR_DEFAULT_TYPE;
954   }
955   /* Set up to send the first header string. */
956   hs->hdr_index = 0;
957   hs->hdr_pos = 0;
958 }
959 
960 /* Add content-length header? */
961 static void
962 get_http_content_length(struct http_state *hs)
963 {
964   u8_t add_content_len = 0;
965 
966   LWIP_ASSERT("already been here?", hs->hdrs[HDR_STRINGS_IDX_CONTENT_LEN_KEEPALIVE] == NULL);
967 
968   add_content_len = 0;
969 #if LWIP_HTTPD_SSI
970   if (hs->ssi == NULL) /* @todo: get maximum file length from SSI */
971 #endif /* LWIP_HTTPD_SSI */
972   {
973     if ((hs->handle != NULL) && (hs->handle->flags & FS_FILE_FLAGS_HEADER_PERSISTENT)) {
974       add_content_len = 1;
975     }
976   }
977   if (add_content_len) {
978     size_t len;
979     lwip_itoa(hs->hdr_content_len, (size_t)LWIP_HTTPD_MAX_CONTENT_LEN_SIZE,
980               hs->handle->len);
981     len = strlen(hs->hdr_content_len);
982     if (len <= LWIP_HTTPD_MAX_CONTENT_LEN_SIZE - LWIP_HTTPD_MAX_CONTENT_LEN_OFFSET) {
983       SMEMCPY(&hs->hdr_content_len[len], CRLF, 3);
984       hs->hdrs[HDR_STRINGS_IDX_CONTENT_LEN_NR] = hs->hdr_content_len;
985     } else {
986       add_content_len = 0;
987     }
988   }
989 #if LWIP_HTTPD_SUPPORT_11_KEEPALIVE
990   if (add_content_len) {
991     hs->hdrs[HDR_STRINGS_IDX_CONTENT_LEN_KEEPALIVE] = g_psHTTPHeaderStrings[HTTP_HDR_KEEPALIVE_LEN];
992   } else {
993     hs->hdrs[HDR_STRINGS_IDX_CONTENT_LEN_KEEPALIVE] = g_psHTTPHeaderStrings[HTTP_HDR_CONN_CLOSE];
994     hs->keepalive = 0;
995   }
996 #else /* LWIP_HTTPD_SUPPORT_11_KEEPALIVE */
997   if (add_content_len) {
998     hs->hdrs[HDR_STRINGS_IDX_CONTENT_LEN_KEEPALIVE] = g_psHTTPHeaderStrings[HTTP_HDR_CONTENT_LENGTH];
999   }
1000 #endif /* LWIP_HTTPD_SUPPORT_11_KEEPALIVE */
1001 }
1002 
1003 /** Sub-function of http_send(): send dynamic headers
1004  *
1005  * @returns: - HTTP_NO_DATA_TO_SEND: no new data has been enqueued
1006  *           - HTTP_DATA_TO_SEND_CONTINUE: continue with sending HTTP body
1007  *           - HTTP_DATA_TO_SEND_BREAK: data has been enqueued, headers pending,
1008  *                                      so don't send HTTP body yet
1009  *           - HTTP_DATA_TO_SEND_FREED: http_state and pcb are already freed
1010  */
1011 static u8_t
1012 http_send_headers(struct altcp_pcb *pcb, struct http_state *hs)
1013 {
1014   err_t err;
1015   u16_t len;
1016   u8_t data_to_send = HTTP_NO_DATA_TO_SEND;
1017   u16_t hdrlen, sendlen;
1018 
1019   if (hs->hdrs[HDR_STRINGS_IDX_CONTENT_LEN_KEEPALIVE] == NULL) {
1020     /* set up "content-length" and "connection:" headers */
1021     get_http_content_length(hs);
1022   }
1023 
1024   /* How much data can we send? */
1025   len = altcp_sndbuf(pcb);
1026   sendlen = len;
1027 
1028   while (len && (hs->hdr_index < NUM_FILE_HDR_STRINGS) && sendlen) {
1029     const void *ptr;
1030     u16_t old_sendlen;
1031     u8_t apiflags;
1032     /* How much do we have to send from the current header? */
1033     hdrlen = (u16_t)strlen(hs->hdrs[hs->hdr_index]);
1034 
1035     /* How much of this can we send? */
1036     sendlen = (len < (hdrlen - hs->hdr_pos)) ? len : (hdrlen - hs->hdr_pos);
1037 
1038     /* Send this amount of data or as much as we can given memory
1039      * constraints. */
1040     ptr = (const void *)(hs->hdrs[hs->hdr_index] + hs->hdr_pos);
1041     old_sendlen = sendlen;
1042     apiflags = HTTP_IS_HDR_VOLATILE(hs, ptr);
1043     if (hs->hdr_index == HDR_STRINGS_IDX_CONTENT_LEN_NR) {
1044       /* content-length is always volatile */
1045       apiflags |= TCP_WRITE_FLAG_COPY;
1046     }
1047     if (hs->hdr_index < NUM_FILE_HDR_STRINGS - 1) {
1048       apiflags |= TCP_WRITE_FLAG_MORE;
1049     }
1050     err = http_write(pcb, ptr, &sendlen, apiflags);
1051     if ((err == ERR_OK) && (old_sendlen != sendlen)) {
1052       /* Remember that we added some more data to be transmitted. */
1053       data_to_send = HTTP_DATA_TO_SEND_CONTINUE;
1054     } else if (err != ERR_OK) {
1055       /* special case: http_write does not try to send 1 byte */
1056       sendlen = 0;
1057     }
1058 
1059     /* Fix up the header position for the next time round. */
1060     hs->hdr_pos += sendlen;
1061     len -= sendlen;
1062 
1063     /* Have we finished sending this string? */
1064     if (hs->hdr_pos == hdrlen) {
1065       /* Yes - move on to the next one */
1066       hs->hdr_index++;
1067       /* skip headers that are NULL (not all headers are required) */
1068       while ((hs->hdr_index < NUM_FILE_HDR_STRINGS) &&
1069              (hs->hdrs[hs->hdr_index] == NULL)) {
1070         hs->hdr_index++;
1071       }
1072       hs->hdr_pos = 0;
1073     }
1074   }
1075 
1076   if ((hs->hdr_index >= NUM_FILE_HDR_STRINGS) && (hs->file == NULL)) {
1077     /* When we are at the end of the headers, check for data to send
1078      * instead of waiting for ACK from remote side to continue
1079      * (which would happen when sending files from async read). */
1080     if (http_check_eof(pcb, hs)) {
1081       data_to_send = HTTP_DATA_TO_SEND_BREAK;
1082     } else {
1083       /* At this point, for non-keepalive connections, hs is deallocated an
1084          pcb is closed. */
1085       return HTTP_DATA_TO_SEND_FREED;
1086     }
1087   }
1088   /* If we get here and there are still header bytes to send, we send
1089    * the header information we just wrote immediately. If there are no
1090    * more headers to send, but we do have file data to send, drop through
1091    * to try to send some file data too. */
1092   if ((hs->hdr_index < NUM_FILE_HDR_STRINGS) || !hs->file) {
1093     LWIP_DEBUGF(HTTPD_DEBUG, ("tcp_output\n"));
1094     return HTTP_DATA_TO_SEND_BREAK;
1095   }
1096   return data_to_send;
1097 }
1098 #endif /* LWIP_HTTPD_DYNAMIC_HEADERS */
1099 
1100 /** Sub-function of http_send(): end-of-file (or block) is reached,
1101  * either close the file or read the next block (if supported).
1102  *
1103  * @returns: 0 if the file is finished or no data has been read
1104  *           1 if the file is not finished and data has been read
1105  */
1106 static u8_t
1107 http_check_eof(struct altcp_pcb *pcb, struct http_state *hs)
1108 {
1109   int bytes_left;
1110 #if LWIP_HTTPD_DYNAMIC_FILE_READ
1111   int count;
1112 #ifdef HTTPD_MAX_WRITE_LEN
1113   int max_write_len;
1114 #endif /* HTTPD_MAX_WRITE_LEN */
1115 #endif /* LWIP_HTTPD_DYNAMIC_FILE_READ */
1116 
1117   /* Do we have a valid file handle? */
1118   if (hs->handle == NULL) {
1119     /* No - close the connection. */
1120     http_eof(pcb, hs);
1121     return 0;
1122   }
1123   bytes_left = fs_bytes_left(hs->handle);
1124   if (bytes_left <= 0) {
1125     /* We reached the end of the file so this request is done. */
1126     LWIP_DEBUGF(HTTPD_DEBUG, ("End of file.\n"));
1127     http_eof(pcb, hs);
1128     return 0;
1129   }
1130 #if LWIP_HTTPD_DYNAMIC_FILE_READ
1131   /* Do we already have a send buffer allocated? */
1132   if (hs->buf) {
1133     /* Yes - get the length of the buffer */
1134     count = LWIP_MIN(hs->buf_len, bytes_left);
1135   } else {
1136     /* We don't have a send buffer so allocate one now */
1137     count = altcp_sndbuf(pcb);
1138     if (bytes_left < count) {
1139       count = bytes_left;
1140     }
1141 #ifdef HTTPD_MAX_WRITE_LEN
1142     /* Additional limitation: e.g. don't enqueue more than 2*mss at once */
1143     max_write_len = HTTPD_MAX_WRITE_LEN(pcb);
1144     if (count > max_write_len) {
1145       count = max_write_len;
1146     }
1147 #endif /* HTTPD_MAX_WRITE_LEN */
1148     do {
1149       hs->buf = (char *)mem_malloc((mem_size_t)count);
1150       if (hs->buf != NULL) {
1151         hs->buf_len = count;
1152         break;
1153       }
1154       count = count / 2;
1155     } while (count > 100);
1156 
1157     /* Did we get a send buffer? If not, return immediately. */
1158     if (hs->buf == NULL) {
1159       LWIP_DEBUGF(HTTPD_DEBUG, ("No buff\n"));
1160       return 0;
1161     }
1162   }
1163 
1164   /* Read a block of data from the file. */
1165   LWIP_DEBUGF(HTTPD_DEBUG, ("Trying to read %d bytes.\n", count));
1166 
1167 #if LWIP_HTTPD_FS_ASYNC_READ
1168   count = fs_read_async(hs->handle, hs->buf, count, http_continue, hs);
1169 #else /* LWIP_HTTPD_FS_ASYNC_READ */
1170   count = fs_read(hs->handle, hs->buf, count);
1171 #endif /* LWIP_HTTPD_FS_ASYNC_READ */
1172   if (count < 0) {
1173     if (count == FS_READ_DELAYED) {
1174       /* Delayed read, wait for FS to unblock us */
1175       return 0;
1176     }
1177     /* We reached the end of the file so this request is done.
1178      * @todo: close here for HTTP/1.1 when reading file fails */
1179     LWIP_DEBUGF(HTTPD_DEBUG, ("End of file.\n"));
1180     http_eof(pcb, hs);
1181     return 0;
1182   }
1183 
1184   /* Set up to send the block of data we just read */
1185   LWIP_DEBUGF(HTTPD_DEBUG, ("Read %d bytes.\n", count));
1186   hs->left = count;
1187   hs->file = hs->buf;
1188 #if LWIP_HTTPD_SSI
1189   if (hs->ssi) {
1190     hs->ssi->parse_left = count;
1191     hs->ssi->parsed = hs->buf;
1192   }
1193 #endif /* LWIP_HTTPD_SSI */
1194 #else /* LWIP_HTTPD_DYNAMIC_FILE_READ */
1195   LWIP_ASSERT("SSI and DYNAMIC_HEADERS turned off but eof not reached", 0);
1196 #endif /* LWIP_HTTPD_SSI || LWIP_HTTPD_DYNAMIC_HEADERS */
1197   return 1;
1198 }
1199 
1200 /** Sub-function of http_send(): This is the normal send-routine for non-ssi files
1201  *
1202  * @returns: - 1: data has been written (so call tcp_ouput)
1203  *           - 0: no data has been written (no need to call tcp_output)
1204  */
1205 static u8_t
1206 http_send_data_nonssi(struct altcp_pcb *pcb, struct http_state *hs)
1207 {
1208   err_t err;
1209   u16_t len;
1210   u8_t data_to_send = 0;
1211 
1212   /* We are not processing an SHTML file so no tag checking is necessary.
1213    * Just send the data as we received it from the file. */
1214   len = (u16_t)LWIP_MIN(hs->left, 0xffff);
1215 
1216   err = http_write(pcb, hs->file, &len, HTTP_IS_DATA_VOLATILE(hs));
1217   if (err == ERR_OK) {
1218     data_to_send = 1;
1219     hs->file += len;
1220     hs->left -= len;
1221   }
1222 
1223   return data_to_send;
1224 }
1225 
1226 #if LWIP_HTTPD_SSI
1227 /** Sub-function of http_send(): This is the send-routine for ssi files
1228  *
1229  * @returns: - 1: data has been written (so call tcp_ouput)
1230  *           - 0: no data has been written (no need to call tcp_output)
1231  */
1232 static u8_t
1233 http_send_data_ssi(struct altcp_pcb *pcb, struct http_state *hs)
1234 {
1235   err_t err = ERR_OK;
1236   u16_t len;
1237   u8_t data_to_send = 0;
1238   u8_t tag_type;
1239 
1240   struct http_ssi_state *ssi = hs->ssi;
1241   LWIP_ASSERT("ssi != NULL", ssi != NULL);
1242   /* We are processing an SHTML file so need to scan for tags and replace
1243    * them with insert strings. We need to be careful here since a tag may
1244    * straddle the boundary of two blocks read from the file and we may also
1245    * have to split the insert string between two tcp_write operations. */
1246 
1247   /* How much data could we send? */
1248   len = altcp_sndbuf(pcb);
1249 
1250   /* Do we have remaining data to send before parsing more? */
1251   if (ssi->parsed > hs->file) {
1252     len = (u16_t)LWIP_MIN(ssi->parsed - hs->file, 0xffff);
1253 
1254     err = http_write(pcb, hs->file, &len, HTTP_IS_DATA_VOLATILE(hs));
1255     if (err == ERR_OK) {
1256       data_to_send = 1;
1257       hs->file += len;
1258       hs->left -= len;
1259     }
1260 
1261     /* If the send buffer is full, return now. */
1262     if (altcp_sndbuf(pcb) == 0) {
1263       return data_to_send;
1264     }
1265   }
1266 
1267   LWIP_DEBUGF(HTTPD_DEBUG, ("State %d, %d left\n", ssi->tag_state, (int)ssi->parse_left));
1268 
1269   /* We have sent all the data that was already parsed so continue parsing
1270    * the buffer contents looking for SSI tags. */
1271   while (((ssi->tag_state == TAG_SENDING) || ssi->parse_left) && (err == ERR_OK)) {
1272     if (len == 0) {
1273       return data_to_send;
1274     }
1275     switch (ssi->tag_state) {
1276       case TAG_NONE:
1277         /* We are not currently processing an SSI tag so scan for the
1278          * start of the lead-in marker. */
1279         for (tag_type = 0; tag_type < LWIP_ARRAYSIZE(http_ssi_tag_desc); tag_type++) {
1280           if (*ssi->parsed == http_ssi_tag_desc[tag_type].lead_in[0]) {
1281             /* We found what could be the lead-in for a new tag so change
1282              * state appropriately. */
1283             ssi->tag_type = tag_type;
1284             ssi->tag_state = TAG_LEADIN;
1285             ssi->tag_index = 1;
1286   #if !LWIP_HTTPD_SSI_INCLUDE_TAG
1287             ssi->tag_started = ssi->parsed;
1288   #endif /* !LWIP_HTTPD_SSI_INCLUDE_TAG */
1289             break;
1290           }
1291         }
1292 
1293         /* Move on to the next character in the buffer */
1294         ssi->parse_left--;
1295         ssi->parsed++;
1296         break;
1297 
1298       case TAG_LEADIN:
1299         /* We are processing the lead-in marker, looking for the start of
1300          * the tag name. */
1301 
1302         /* Have we reached the end of the leadin? */
1303         if (http_ssi_tag_desc[ssi->tag_type].lead_in[ssi->tag_index] == 0) {
1304           ssi->tag_index = 0;
1305           ssi->tag_state = TAG_FOUND;
1306         } else {
1307           /* Have we found the next character we expect for the tag leadin? */
1308           if (*ssi->parsed == http_ssi_tag_desc[ssi->tag_type].lead_in[ssi->tag_index]) {
1309             /* Yes - move to the next one unless we have found the complete
1310              * leadin, in which case we start looking for the tag itself */
1311             ssi->tag_index++;
1312           } else {
1313             /* We found an unexpected character so this is not a tag. Move
1314              * back to idle state. */
1315             ssi->tag_state = TAG_NONE;
1316           }
1317 
1318 #if LWIP_HTTPD_DYNAMIC_FILE_READ && !LWIP_HTTPD_SSI_INCLUDE_TAG
1319           if ((ssi->tag_state == TAG_NONE) &&
1320               (ssi->parsed - hs->file < ssi->tag_index)) {
1321             for(u16_t i = 0;i < ssi->tag_index;i++) {
1322               ssi->tag_insert[i] = http_ssi_tag_desc[ssi->tag_type].lead_in[i];
1323             }
1324             ssi->tag_insert_len = ssi->tag_index;
1325             hs->file += ssi->parsed - hs->file;
1326             hs->left -= ssi->parsed - hs->file;
1327             ssi->tag_end = hs->file;
1328             ssi->tag_index = 0;
1329             ssi->tag_state = TAG_SENDING;
1330             break;
1331           }
1332 #endif
1333 
1334           /* Move on to the next character in the buffer */
1335           ssi->parse_left--;
1336           ssi->parsed++;
1337         }
1338         break;
1339 
1340       case TAG_FOUND:
1341         /* We are reading the tag name, looking for the start of the
1342          * lead-out marker and removing any whitespace found. */
1343 
1344         /* Remove leading whitespace between the tag leading and the first
1345          * tag name character. */
1346         if ((ssi->tag_index == 0) && ((*ssi->parsed == ' ') ||
1347                                       (*ssi->parsed == '\t') || (*ssi->parsed == '\n') ||
1348                                       (*ssi->parsed == '\r'))) {
1349           /* Move on to the next character in the buffer */
1350           ssi->parse_left--;
1351           ssi->parsed++;
1352           break;
1353         }
1354 
1355         /* Have we found the end of the tag name? This is signalled by
1356          * us finding the first leadout character or whitespace */
1357         if ((*ssi->parsed == http_ssi_tag_desc[ssi->tag_type].lead_out[0]) ||
1358             (*ssi->parsed == ' ')  || (*ssi->parsed == '\t') ||
1359             (*ssi->parsed == '\n') || (*ssi->parsed == '\r')) {
1360 
1361           if (ssi->tag_index == 0) {
1362             /* We read a zero length tag so ignore it. */
1363             ssi->tag_state = TAG_NONE;
1364           } else {
1365             /* We read a non-empty tag so go ahead and look for the
1366              * leadout string. */
1367             ssi->tag_state = TAG_LEADOUT;
1368             LWIP_ASSERT("ssi->tag_index <= 0xff", ssi->tag_index <= 0xff);
1369             ssi->tag_name_len = (u8_t)ssi->tag_index;
1370             ssi->tag_name[ssi->tag_index] = '\0';
1371             if (*ssi->parsed == http_ssi_tag_desc[ssi->tag_type].lead_out[0]) {
1372               ssi->tag_index = 1;
1373             } else {
1374               ssi->tag_index = 0;
1375             }
1376           }
1377         } else {
1378           /* This character is part of the tag name so save it */
1379           if (ssi->tag_index < LWIP_HTTPD_MAX_TAG_NAME_LEN) {
1380             ssi->tag_name[ssi->tag_index++] = *ssi->parsed;
1381           } else {
1382             /* The tag was too long so ignore it. */
1383             ssi->tag_state = TAG_NONE;
1384           }
1385         }
1386 
1387         /* Move on to the next character in the buffer */
1388         ssi->parse_left--;
1389         ssi->parsed++;
1390 
1391         break;
1392 
1393       /* We are looking for the end of the lead-out marker. */
1394       case TAG_LEADOUT:
1395         /* Remove leading whitespace between the tag leading and the first
1396          * tag leadout character. */
1397         if ((ssi->tag_index == 0) && ((*ssi->parsed == ' ') ||
1398                                       (*ssi->parsed == '\t') || (*ssi->parsed == '\n') ||
1399                                       (*ssi->parsed == '\r'))) {
1400           /* Move on to the next character in the buffer */
1401           ssi->parse_left--;
1402           ssi->parsed++;
1403           break;
1404         }
1405 
1406         /* Have we found the next character we expect for the tag leadout? */
1407         if (*ssi->parsed == http_ssi_tag_desc[ssi->tag_type].lead_out[ssi->tag_index]) {
1408           /* Yes - move to the next one unless we have found the complete
1409            * leadout, in which case we need to call the client to process
1410            * the tag. */
1411 
1412           /* Move on to the next character in the buffer */
1413           ssi->parse_left--;
1414           ssi->parsed++;
1415           ssi->tag_index++;
1416 
1417           if (http_ssi_tag_desc[ssi->tag_type].lead_out[ssi->tag_index] == 0) {
1418             /* Call the client to ask for the insert string for the
1419              * tag we just found. */
1420 #if LWIP_HTTPD_SSI_MULTIPART
1421             ssi->tag_part = 0; /* start with tag part 0 */
1422 #endif /* LWIP_HTTPD_SSI_MULTIPART */
1423             get_tag_insert(hs);
1424 
1425             /* Next time through, we are going to be sending data
1426              * immediately, either the end of the block we start
1427              * sending here or the insert string. */
1428             ssi->tag_index = 0;
1429             ssi->tag_state = TAG_SENDING;
1430             ssi->tag_end = ssi->parsed;
1431 #if !LWIP_HTTPD_SSI_INCLUDE_TAG
1432             ssi->parsed = ssi->tag_started;
1433 #endif /* !LWIP_HTTPD_SSI_INCLUDE_TAG*/
1434 
1435             /* If there is any unsent data in the buffer prior to the
1436              * tag, we need to send it now. */
1437             if (ssi->tag_end > hs->file) {
1438               /* How much of the data can we send? */
1439 #if LWIP_HTTPD_SSI_INCLUDE_TAG
1440               len = (u16_t)LWIP_MIN(ssi->tag_end - hs->file, 0xffff);
1441 #else /* LWIP_HTTPD_SSI_INCLUDE_TAG*/
1442               /* we would include the tag in sending */
1443               len = (u16_t)LWIP_MIN(ssi->tag_started - hs->file, 0xffff);
1444 #endif /* LWIP_HTTPD_SSI_INCLUDE_TAG*/
1445 
1446               err = http_write(pcb, hs->file, &len, HTTP_IS_DATA_VOLATILE(hs));
1447               if (err == ERR_OK) {
1448                 data_to_send = 1;
1449 #if !LWIP_HTTPD_SSI_INCLUDE_TAG
1450                 if (ssi->tag_started <= hs->file) {
1451                   /* pretend to have sent the tag, too */
1452                   len += (u16_t)(ssi->tag_end - ssi->tag_started);
1453                 }
1454 #endif /* !LWIP_HTTPD_SSI_INCLUDE_TAG*/
1455                 hs->file += len;
1456                 hs->left -= len;
1457               }
1458             }
1459           }
1460         } else {
1461           /* We found an unexpected character so this is not a tag. Move
1462            * back to idle state. */
1463           ssi->parse_left--;
1464           ssi->parsed++;
1465           ssi->tag_state = TAG_NONE;
1466         }
1467         break;
1468 
1469       /*
1470        * We have found a valid tag and are in the process of sending
1471        * data as a result of that discovery. We send either remaining data
1472        * from the file prior to the insert point or the insert string itself.
1473        */
1474       case TAG_SENDING:
1475         /* Do we have any remaining file data to send from the buffer prior
1476          * to the tag? */
1477         if (ssi->tag_end > hs->file) {
1478           /* How much of the data can we send? */
1479 #if LWIP_HTTPD_SSI_INCLUDE_TAG
1480           len = (u16_t)LWIP_MIN(ssi->tag_end - hs->file, 0xffff);
1481 #else /* LWIP_HTTPD_SSI_INCLUDE_TAG*/
1482           LWIP_ASSERT("hs->started >= hs->file", ssi->tag_started >= hs->file);
1483           /* we would include the tag in sending */
1484           len = (u16_t)LWIP_MIN(ssi->tag_started - hs->file, 0xffff);
1485 #endif /* LWIP_HTTPD_SSI_INCLUDE_TAG*/
1486           if (len != 0) {
1487             err = http_write(pcb, hs->file, &len, HTTP_IS_DATA_VOLATILE(hs));
1488           } else {
1489             err = ERR_OK;
1490           }
1491           if (err == ERR_OK) {
1492             data_to_send = 1;
1493 #if !LWIP_HTTPD_SSI_INCLUDE_TAG
1494             if (ssi->tag_started <= hs->file) {
1495               /* pretend to have sent the tag, too */
1496               len += (u16_t)(ssi->tag_end - ssi->tag_started);
1497             }
1498 #endif /* !LWIP_HTTPD_SSI_INCLUDE_TAG*/
1499             hs->file += len;
1500             hs->left -= len;
1501           }
1502         } else {
1503 #if LWIP_HTTPD_SSI_MULTIPART
1504           if (ssi->tag_index >= ssi->tag_insert_len) {
1505             /* Did the last SSIHandler have more to send? */
1506             if (ssi->tag_part != HTTPD_LAST_TAG_PART) {
1507               /* If so, call it again */
1508               ssi->tag_index = 0;
1509               get_tag_insert(hs);
1510             }
1511           }
1512 #endif /* LWIP_HTTPD_SSI_MULTIPART */
1513 
1514           /* Do we still have insert data left to send? */
1515           if (ssi->tag_index < ssi->tag_insert_len) {
1516             /* We are sending the insert string itself. How much of the
1517              * insert can we send? */
1518             len = (ssi->tag_insert_len - ssi->tag_index);
1519 
1520             /* Note that we set the copy flag here since we only have a
1521              * single tag insert buffer per connection. If we don't do
1522              * this, insert corruption can occur if more than one insert
1523              * is processed before we call tcp_output. */
1524             err = http_write(pcb, &(ssi->tag_insert[ssi->tag_index]), &len,
1525                              HTTP_IS_TAG_VOLATILE(hs));
1526             if (err == ERR_OK) {
1527               data_to_send = 1;
1528               ssi->tag_index += len;
1529               /* Don't return here: keep on sending data */
1530             }
1531           } else {
1532 #if LWIP_HTTPD_SSI_MULTIPART
1533             if (ssi->tag_part == HTTPD_LAST_TAG_PART)
1534 #endif /* LWIP_HTTPD_SSI_MULTIPART */
1535             {
1536               /* We have sent all the insert data so go back to looking for
1537                * a new tag. */
1538               LWIP_DEBUGF(HTTPD_DEBUG, ("Everything sent.\n"));
1539               ssi->tag_index = 0;
1540               ssi->tag_state = TAG_NONE;
1541 #if !LWIP_HTTPD_SSI_INCLUDE_TAG
1542               ssi->parsed = ssi->tag_end;
1543 #endif /* !LWIP_HTTPD_SSI_INCLUDE_TAG*/
1544             }
1545           }
1546           break;
1547         default:
1548           break;
1549         }
1550     }
1551   }
1552 
1553   /* If we drop out of the end of the for loop, this implies we must have
1554    * file data to send so send it now. In TAG_SENDING state, we've already
1555    * handled this so skip the send if that's the case. */
1556   if ((ssi->tag_state != TAG_SENDING) && (ssi->parsed > hs->file)) {
1557 #if LWIP_HTTPD_DYNAMIC_FILE_READ && !LWIP_HTTPD_SSI_INCLUDE_TAG
1558     if ((ssi->tag_state != TAG_NONE) && (ssi->tag_started > ssi->tag_end)) {
1559       /* If we found tag on the edge of the read buffer: just throw away the first part
1560          (we have copied/saved everything required for parsing on later). */
1561       len = (u16_t)(ssi->tag_started - hs->file);
1562       hs->left -= (ssi->parsed - ssi->tag_started);
1563       ssi->parsed = ssi->tag_started;
1564       ssi->tag_started = hs->buf;
1565     } else
1566 #endif /* LWIP_HTTPD_DYNAMIC_FILE_READ && !LWIP_HTTPD_SSI_INCLUDE_TAG */
1567     {
1568       len = (u16_t)LWIP_MIN(ssi->parsed - hs->file, 0xffff);
1569     }
1570 
1571     err = http_write(pcb, hs->file, &len, HTTP_IS_DATA_VOLATILE(hs));
1572     if (err == ERR_OK) {
1573       data_to_send = 1;
1574       hs->file += len;
1575       hs->left -= len;
1576     }
1577   }
1578   return data_to_send;
1579 }
1580 #endif /* LWIP_HTTPD_SSI */
1581 
1582 /**
1583  * Try to send more data on this pcb.
1584  *
1585  * @param pcb the pcb to send data
1586  * @param hs connection state
1587  */
1588 static u8_t
1589 http_send(struct altcp_pcb *pcb, struct http_state *hs)
1590 {
1591   u8_t data_to_send = HTTP_NO_DATA_TO_SEND;
1592 
1593   LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("http_send: pcb=%p hs=%p left=%d\n", (void *)pcb,
1594               (void *)hs, hs != NULL ? (int)hs->left : 0));
1595 
1596 #if LWIP_HTTPD_SUPPORT_POST && LWIP_HTTPD_POST_MANUAL_WND
1597   if (hs->unrecved_bytes != 0) {
1598     return 0;
1599   }
1600 #endif /* LWIP_HTTPD_SUPPORT_POST && LWIP_HTTPD_POST_MANUAL_WND */
1601 
1602   /* If we were passed a NULL state structure pointer, ignore the call. */
1603   if (hs == NULL) {
1604     return 0;
1605   }
1606 
1607 #if LWIP_HTTPD_FS_ASYNC_READ
1608   /* Check if we are allowed to read from this file.
1609      (e.g. SSI might want to delay sending until data is available) */
1610   if (!fs_is_file_ready(hs->handle, http_continue, hs)) {
1611     return 0;
1612   }
1613 #endif /* LWIP_HTTPD_FS_ASYNC_READ */
1614 
1615 #if LWIP_HTTPD_DYNAMIC_HEADERS
1616   /* Do we have any more header data to send for this file? */
1617   if (hs->hdr_index < NUM_FILE_HDR_STRINGS) {
1618     data_to_send = http_send_headers(pcb, hs);
1619     if ((data_to_send == HTTP_DATA_TO_SEND_FREED) ||
1620         ((data_to_send != HTTP_DATA_TO_SEND_CONTINUE) &&
1621          (hs->hdr_index < NUM_FILE_HDR_STRINGS))) {
1622       return data_to_send;
1623     }
1624   }
1625 #endif /* LWIP_HTTPD_DYNAMIC_HEADERS */
1626 
1627 #if LWIP_HTTPD_SSI
1628   if (hs->ssi && (hs->ssi->tag_state == TAG_SENDING)) {
1629     /* do not check the condition below */
1630   } else
1631 #endif
1632   /* Have we run out of file data to send? If so, we need to read the next
1633    * block from the file. */
1634   if (hs->left == 0) {
1635     if (!http_check_eof(pcb, hs)) {
1636       return 0;
1637     }
1638   }
1639 
1640 #if LWIP_HTTPD_SSI
1641   if (hs->ssi) {
1642     data_to_send = http_send_data_ssi(pcb, hs);
1643     if (hs->ssi->tag_state == TAG_SENDING) {
1644       return data_to_send;
1645     }
1646   } else
1647 #endif /* LWIP_HTTPD_SSI */
1648   {
1649     data_to_send = http_send_data_nonssi(pcb, hs);
1650   }
1651 
1652   if ((hs->left == 0) && (fs_bytes_left(hs->handle) <= 0)) {
1653     /* We reached the end of the file so this request is done.
1654      * This adds the FIN flag right into the last data segment. */
1655     LWIP_DEBUGF(HTTPD_DEBUG, ("End of file.\n"));
1656     http_eof(pcb, hs);
1657     return 0;
1658   }
1659   LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("send_data end.\n"));
1660   return data_to_send;
1661 }
1662 
1663 #if LWIP_HTTPD_SUPPORT_EXTSTATUS
1664 /** Initialize a http connection with a file to send for an error message
1665  *
1666  * @param hs http connection state
1667  * @param error_nr HTTP error number
1668  * @return ERR_OK if file was found and hs has been initialized correctly
1669  *         another err_t otherwise
1670  */
1671 static err_t
1672 http_find_error_file(struct http_state *hs, u16_t error_nr)
1673 {
1674   const char *uri, *uri1, *uri2, *uri3;
1675 
1676   if (error_nr == 501) {
1677     uri1 = "/501.html";
1678     uri2 = "/501.htm";
1679     uri3 = "/501.shtml";
1680   } else {
1681     /* 400 (bad request is the default) */
1682     uri1 = "/400.html";
1683     uri2 = "/400.htm";
1684     uri3 = "/400.shtml";
1685   }
1686   if (fs_open(&hs->file_handle, uri1) == ERR_OK) {
1687     uri = uri1;
1688   } else if (fs_open(&hs->file_handle, uri2) == ERR_OK) {
1689     uri = uri2;
1690   } else if (fs_open(&hs->file_handle, uri3) == ERR_OK) {
1691     uri = uri3;
1692   } else {
1693     LWIP_DEBUGF(HTTPD_DEBUG, ("Error page for error %"U16_F" not found\n",
1694                               error_nr));
1695     return ERR_ARG;
1696   }
1697   return http_init_file(hs, &hs->file_handle, 0, uri, 0, NULL);
1698 }
1699 #else /* LWIP_HTTPD_SUPPORT_EXTSTATUS */
1700 #define http_find_error_file(hs, error_nr) ERR_ARG
1701 #endif /* LWIP_HTTPD_SUPPORT_EXTSTATUS */
1702 
1703 /**
1704  * Get the file struct for a 404 error page.
1705  * Tries some file names and returns NULL if none found.
1706  *
1707  * @param uri pointer that receives the actual file name URI
1708  * @return file struct for the error page or NULL no matching file was found
1709  */
1710 static struct fs_file *
1711 http_get_404_file(struct http_state *hs, const char **uri)
1712 {
1713   err_t err;
1714 
1715   *uri = "/404.html";
1716   err = fs_open(&hs->file_handle, *uri);
1717   if (err != ERR_OK) {
1718     /* 404.html doesn't exist. Try 404.htm instead. */
1719     *uri = "/404.htm";
1720     err = fs_open(&hs->file_handle, *uri);
1721     if (err != ERR_OK) {
1722       /* 404.htm doesn't exist either. Try 404.shtml instead. */
1723       *uri = "/404.shtml";
1724       err = fs_open(&hs->file_handle, *uri);
1725       if (err != ERR_OK) {
1726         /* 404.htm doesn't exist either. Indicate to the caller that it should
1727          * send back a default 404 page.
1728          */
1729         *uri = NULL;
1730         return NULL;
1731       }
1732     }
1733   }
1734 
1735   return &hs->file_handle;
1736 }
1737 
1738 #if LWIP_HTTPD_SUPPORT_POST
1739 static err_t
1740 http_handle_post_finished(struct http_state *hs)
1741 {
1742 #if LWIP_HTTPD_POST_MANUAL_WND
1743   /* Prevent multiple calls to httpd_post_finished, since it might have already
1744      been called before from httpd_post_data_recved(). */
1745   if (hs->post_finished) {
1746     return ERR_OK;
1747   }
1748   hs->post_finished = 1;
1749 #endif /* LWIP_HTTPD_POST_MANUAL_WND */
1750   /* application error or POST finished */
1751   /* NULL-terminate the buffer */
1752   http_uri_buf[0] = 0;
1753   httpd_post_finished(hs, http_uri_buf, LWIP_HTTPD_URI_BUF_LEN);
1754   return http_find_file(hs, http_uri_buf, 0);
1755 }
1756 
1757 /** Pass received POST body data to the application and correctly handle
1758  * returning a response document or closing the connection.
1759  * ATTENTION: The application is responsible for the pbuf now, so don't free it!
1760  *
1761  * @param hs http connection state
1762  * @param p pbuf to pass to the application
1763  * @return ERR_OK if passed successfully, another err_t if the response file
1764  *         hasn't been found (after POST finished)
1765  */
1766 static err_t
1767 http_post_rxpbuf(struct http_state *hs, struct pbuf *p)
1768 {
1769   err_t err;
1770 
1771   if (p != NULL) {
1772     /* adjust remaining Content-Length */
1773     if (hs->post_content_len_left < p->tot_len) {
1774       hs->post_content_len_left = 0;
1775     } else {
1776       hs->post_content_len_left -= p->tot_len;
1777     }
1778   }
1779 #if LWIP_HTTPD_SUPPORT_POST && LWIP_HTTPD_POST_MANUAL_WND
1780   /* prevent connection being closed if httpd_post_data_recved() is called nested */
1781   hs->unrecved_bytes++;
1782 #endif
1783   if (p != NULL) {
1784     err = httpd_post_receive_data(hs, p);
1785   } else {
1786     err = ERR_OK;
1787   }
1788 #if LWIP_HTTPD_SUPPORT_POST && LWIP_HTTPD_POST_MANUAL_WND
1789   hs->unrecved_bytes--;
1790 #endif
1791   if (err != ERR_OK) {
1792     /* Ignore remaining content in case of application error */
1793     hs->post_content_len_left = 0;
1794   }
1795   if (hs->post_content_len_left == 0) {
1796 #if LWIP_HTTPD_SUPPORT_POST && LWIP_HTTPD_POST_MANUAL_WND
1797     if (hs->unrecved_bytes != 0) {
1798       return ERR_OK;
1799     }
1800 #endif /* LWIP_HTTPD_SUPPORT_POST && LWIP_HTTPD_POST_MANUAL_WND */
1801     /* application error or POST finished */
1802     return http_handle_post_finished(hs);
1803   }
1804 
1805   return ERR_OK;
1806 }
1807 
1808 /** Handle a post request. Called from http_parse_request when method 'POST'
1809  * is found.
1810  *
1811  * @param p The input pbuf (containing the POST header and body).
1812  * @param hs The http connection state.
1813  * @param data HTTP request (header and part of body) from input pbuf(s).
1814  * @param data_len Size of 'data'.
1815  * @param uri The HTTP URI parsed from input pbuf(s).
1816  * @param uri_end Pointer to the end of 'uri' (here, the rest of the HTTP
1817  *                header starts).
1818  * @return ERR_OK: POST correctly parsed and accepted by the application.
1819  *         ERR_INPROGRESS: POST not completely parsed (no error yet)
1820  *         another err_t: Error parsing POST or denied by the application
1821  */
1822 static err_t
1823 http_post_request(struct pbuf *inp, struct http_state *hs,
1824                   char *data, u16_t data_len, char *uri, char *uri_end)
1825 {
1826   err_t err;
1827   /* search for end-of-header (first double-CRLF) */
1828   char *crlfcrlf = lwip_strnstr(uri_end + 1, CRLF CRLF, data_len - (uri_end + 1 - data));
1829 
1830   if (crlfcrlf != NULL) {
1831     /* search for "Content-Length: " */
1832 #define HTTP_HDR_CONTENT_LEN                "Content-Length: "
1833 #define HTTP_HDR_CONTENT_LEN_LEN            16
1834 #define HTTP_HDR_CONTENT_LEN_DIGIT_MAX_LEN  10
1835     char *scontent_len = lwip_strnistr(uri_end + 1, HTTP_HDR_CONTENT_LEN, crlfcrlf - (uri_end + 1));
1836     if (scontent_len != NULL) {
1837       char *scontent_len_end = lwip_strnstr(scontent_len + HTTP_HDR_CONTENT_LEN_LEN, CRLF, HTTP_HDR_CONTENT_LEN_DIGIT_MAX_LEN);
1838       if (scontent_len_end != NULL) {
1839         int content_len;
1840         char *content_len_num = scontent_len + HTTP_HDR_CONTENT_LEN_LEN;
1841         content_len = atoi(content_len_num);
1842         if (content_len == 0) {
1843           /* if atoi returns 0 on error, fix this */
1844           if ((content_len_num[0] != '0') || (content_len_num[1] != '\r')) {
1845             content_len = -1;
1846           }
1847         }
1848         if (content_len >= 0) {
1849           /* adjust length of HTTP header passed to application */
1850           const char *hdr_start_after_uri = uri_end + 1;
1851           u16_t hdr_len = (u16_t)LWIP_MIN(data_len, crlfcrlf + 4 - data);
1852           u16_t hdr_data_len = (u16_t)LWIP_MIN(data_len, crlfcrlf + 4 - hdr_start_after_uri);
1853           u8_t post_auto_wnd = 1;
1854           http_uri_buf[0] = 0;
1855           /* trim http header */
1856           *crlfcrlf = 0;
1857           err = httpd_post_begin(hs, uri, hdr_start_after_uri, hdr_data_len, content_len,
1858                                  http_uri_buf, LWIP_HTTPD_URI_BUF_LEN, &post_auto_wnd);
1859           if (err == ERR_OK) {
1860             /* try to pass in data of the first pbuf(s) */
1861             struct pbuf *q = inp;
1862             u16_t start_offset = hdr_len;
1863 #if LWIP_HTTPD_POST_MANUAL_WND
1864             hs->no_auto_wnd = !post_auto_wnd;
1865 #endif /* LWIP_HTTPD_POST_MANUAL_WND */
1866             /* set the Content-Length to be received for this POST */
1867             hs->post_content_len_left = (u32_t)content_len;
1868 
1869             /* get to the pbuf where the body starts */
1870             while ((q != NULL) && (q->len <= start_offset)) {
1871               start_offset -= q->len;
1872               q = q->next;
1873             }
1874             if (q != NULL) {
1875               /* hide the remaining HTTP header */
1876               pbuf_remove_header(q, start_offset);
1877 #if LWIP_HTTPD_POST_MANUAL_WND
1878               if (!post_auto_wnd) {
1879                 /* already tcp_recved() this data... */
1880                 hs->unrecved_bytes = q->tot_len;
1881               }
1882 #endif /* LWIP_HTTPD_POST_MANUAL_WND */
1883               pbuf_ref(q);
1884               return http_post_rxpbuf(hs, q);
1885             } else if (hs->post_content_len_left == 0) {
1886               q = pbuf_alloc(PBUF_RAW, 0, PBUF_REF);
1887               return http_post_rxpbuf(hs, q);
1888             } else {
1889               return ERR_OK;
1890             }
1891           } else {
1892             /* return file passed from application */
1893             return http_find_file(hs, http_uri_buf, 0);
1894           }
1895         } else {
1896           LWIP_DEBUGF(HTTPD_DEBUG, ("POST received invalid Content-Length: %s\n",
1897                                     content_len_num));
1898           return ERR_ARG;
1899         }
1900       }
1901     }
1902     /* If we come here, headers are fully received (double-crlf), but Content-Length
1903        was not included. Since this is currently the only supported method, we have
1904        to fail in this case! */
1905     LWIP_DEBUGF(HTTPD_DEBUG, ("Error when parsing Content-Length\n"));
1906     return ERR_ARG;
1907   }
1908   /* if we come here, the POST is incomplete */
1909 #if LWIP_HTTPD_SUPPORT_REQUESTLIST
1910   return ERR_INPROGRESS;
1911 #else /* LWIP_HTTPD_SUPPORT_REQUESTLIST */
1912   return ERR_ARG;
1913 #endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */
1914 }
1915 
1916 #if LWIP_HTTPD_POST_MANUAL_WND
1917 /**
1918  * @ingroup httpd
1919  * A POST implementation can call this function to update the TCP window.
1920  * This can be used to throttle data reception (e.g. when received data is
1921  * programmed to flash and data is received faster than programmed).
1922  *
1923  * @param connection A connection handle passed to httpd_post_begin for which
1924  *        httpd_post_finished has *NOT* been called yet!
1925  * @param recved_len Length of data received (for window update)
1926  */
1927 void httpd_post_data_recved(void *connection, u16_t recved_len)
1928 {
1929   struct http_state *hs = (struct http_state *)connection;
1930   if (hs != NULL) {
1931     if (hs->no_auto_wnd) {
1932       u16_t len = recved_len;
1933       if (hs->unrecved_bytes >= recved_len) {
1934         hs->unrecved_bytes -= recved_len;
1935       } else {
1936         LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_LEVEL_WARNING, ("httpd_post_data_recved: recved_len too big\n"));
1937         len = (u16_t)hs->unrecved_bytes;
1938         hs->unrecved_bytes = 0;
1939       }
1940       if (hs->pcb != NULL) {
1941         if (len != 0) {
1942           altcp_recved(hs->pcb, len);
1943         }
1944         if ((hs->post_content_len_left == 0) && (hs->unrecved_bytes == 0)) {
1945           /* finished handling POST */
1946           http_handle_post_finished(hs);
1947           http_send(hs->pcb, hs);
1948         }
1949       }
1950     }
1951   }
1952 }
1953 #endif /* LWIP_HTTPD_POST_MANUAL_WND */
1954 
1955 #endif /* LWIP_HTTPD_SUPPORT_POST */
1956 
1957 #if LWIP_HTTPD_FS_ASYNC_READ
1958 /** Try to send more data if file has been blocked before
1959  * This is a callback function passed to fs_read_async().
1960  */
1961 static void
1962 http_continue(void *connection)
1963 {
1964   struct http_state *hs = (struct http_state *)connection;
1965   LWIP_ASSERT_CORE_LOCKED();
1966   if (hs && (hs->pcb) && (hs->handle)) {
1967     LWIP_ASSERT("hs->pcb != NULL", hs->pcb != NULL);
1968     LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("httpd_continue: try to send more data\n"));
1969     if (http_send(hs->pcb, hs)) {
1970       /* If we wrote anything to be sent, go ahead and send it now. */
1971       LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("tcp_output\n"));
1972       altcp_output(hs->pcb);
1973     }
1974   }
1975 }
1976 #endif /* LWIP_HTTPD_FS_ASYNC_READ */
1977 
1978 /**
1979  * When data has been received in the correct state, try to parse it
1980  * as a HTTP request.
1981  *
1982  * @param inp the received pbuf
1983  * @param hs the connection state
1984  * @param pcb the altcp_pcb which received this packet
1985  * @return ERR_OK if request was OK and hs has been initialized correctly
1986  *         ERR_INPROGRESS if request was OK so far but not fully received
1987  *         another err_t otherwise
1988  */
1989 static err_t
1990 http_parse_request(struct pbuf *inp, struct http_state *hs, struct altcp_pcb *pcb)
1991 {
1992   char *data;
1993   char *crlf;
1994   u16_t data_len;
1995   struct pbuf *p = inp;
1996 #if LWIP_HTTPD_SUPPORT_REQUESTLIST
1997   u16_t clen;
1998 #endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */
1999 #if LWIP_HTTPD_SUPPORT_POST
2000   err_t err;
2001 #endif /* LWIP_HTTPD_SUPPORT_POST */
2002 
2003   LWIP_UNUSED_ARG(pcb); /* only used for post */
2004   LWIP_ASSERT("p != NULL", p != NULL);
2005   LWIP_ASSERT("hs != NULL", hs != NULL);
2006 
2007   if ((hs->handle != NULL) || (hs->file != NULL)) {
2008     LWIP_DEBUGF(HTTPD_DEBUG, ("Received data while sending a file\n"));
2009     /* already sending a file */
2010     /* @todo: abort? */
2011     return ERR_USE;
2012   }
2013 
2014 #if LWIP_HTTPD_SUPPORT_REQUESTLIST
2015 
2016   LWIP_DEBUGF(HTTPD_DEBUG, ("Received %"U16_F" bytes\n", p->tot_len));
2017 
2018   /* first check allowed characters in this pbuf? */
2019 
2020   /* enqueue the pbuf */
2021   if (hs->req == NULL) {
2022     LWIP_DEBUGF(HTTPD_DEBUG, ("First pbuf\n"));
2023     hs->req = p;
2024   } else {
2025     LWIP_DEBUGF(HTTPD_DEBUG, ("pbuf enqueued\n"));
2026     pbuf_cat(hs->req, p);
2027   }
2028   /* increase pbuf ref counter as it is freed when we return but we want to
2029      keep it on the req list */
2030   pbuf_ref(p);
2031 
2032   if (hs->req->next != NULL) {
2033     data_len = LWIP_MIN(hs->req->tot_len, LWIP_HTTPD_MAX_REQ_LENGTH);
2034     pbuf_copy_partial(hs->req, httpd_req_buf, data_len, 0);
2035     data = httpd_req_buf;
2036   } else
2037 #endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */
2038   {
2039     data = (char *)p->payload;
2040     data_len = p->len;
2041     if (p->len != p->tot_len) {
2042       LWIP_DEBUGF(HTTPD_DEBUG, ("Warning: incomplete header due to chained pbufs\n"));
2043     }
2044   }
2045 
2046   /* received enough data for minimal request? */
2047   if (data_len >= MIN_REQ_LEN) {
2048     /* wait for CRLF before parsing anything */
2049     crlf = lwip_strnstr(data, CRLF, data_len);
2050     if (crlf != NULL) {
2051 #if LWIP_HTTPD_SUPPORT_POST
2052       int is_post = 0;
2053 #endif /* LWIP_HTTPD_SUPPORT_POST */
2054       int is_09 = 0;
2055       char *sp1, *sp2;
2056       u16_t left_len, uri_len;
2057       LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("CRLF received, parsing request\n"));
2058       /* parse method */
2059       if (!strncmp(data, "GET ", 4)) {
2060         sp1 = data + 3;
2061         /* received GET request */
2062         LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Received GET request\"\n"));
2063 #if LWIP_HTTPD_SUPPORT_POST
2064       } else if (!strncmp(data, "POST ", 5)) {
2065         /* store request type */
2066         is_post = 1;
2067         sp1 = data + 4;
2068         /* received GET request */
2069         LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Received POST request\n"));
2070 #endif /* LWIP_HTTPD_SUPPORT_POST */
2071       } else {
2072         /* null-terminate the METHOD (pbuf is freed anyway wen returning) */
2073         data[4] = 0;
2074         /* unsupported method! */
2075         LWIP_DEBUGF(HTTPD_DEBUG, ("Unsupported request method (not implemented): \"%s\"\n",
2076                                   data));
2077         return http_find_error_file(hs, 501);
2078       }
2079       /* if we come here, method is OK, parse URI */
2080       left_len = (u16_t)(data_len - ((sp1 + 1) - data));
2081       sp2 = lwip_strnstr(sp1 + 1, " ", left_len);
2082 #if LWIP_HTTPD_SUPPORT_V09
2083       if (sp2 == NULL) {
2084         /* HTTP 0.9: respond with correct protocol version */
2085         sp2 = lwip_strnstr(sp1 + 1, CRLF, left_len);
2086         is_09 = 1;
2087 #if LWIP_HTTPD_SUPPORT_POST
2088         if (is_post) {
2089           /* HTTP/0.9 does not support POST */
2090           goto badrequest;
2091         }
2092 #endif /* LWIP_HTTPD_SUPPORT_POST */
2093       }
2094 #endif /* LWIP_HTTPD_SUPPORT_V09 */
2095       uri_len = (u16_t)(sp2 - (sp1 + 1));
2096       if ((sp2 != NULL) && (sp2 > sp1)) {
2097         /* wait for CRLFCRLF (indicating end of HTTP headers) before parsing anything */
2098         if (lwip_strnstr(data, CRLF CRLF, data_len) != NULL) {
2099           char *uri = sp1 + 1;
2100 #if LWIP_HTTPD_SUPPORT_11_KEEPALIVE
2101           /* This is HTTP/1.0 compatible: for strict 1.1, a connection
2102              would always be persistent unless "close" was specified. */
2103           if (!is_09 && (lwip_strnistr(data, HTTP11_CONNECTIONKEEPALIVE, data_len) ||
2104                          lwip_strnistr(data, HTTP11_CONNECTIONKEEPALIVE2, data_len))) {
2105             hs->keepalive = 1;
2106           } else {
2107             hs->keepalive = 0;
2108           }
2109 #endif /* LWIP_HTTPD_SUPPORT_11_KEEPALIVE */
2110           /* null-terminate the METHOD (pbuf is freed anyway wen returning) */
2111           *sp1 = 0;
2112           uri[uri_len] = 0;
2113           LWIP_DEBUGF(HTTPD_DEBUG, ("Received \"%s\" request for URI: \"%s\"\n",
2114                                     data, uri));
2115 #if LWIP_HTTPD_SUPPORT_POST
2116           if (is_post) {
2117 #if LWIP_HTTPD_SUPPORT_REQUESTLIST
2118             struct pbuf *q = hs->req;
2119 #else /* LWIP_HTTPD_SUPPORT_REQUESTLIST */
2120             struct pbuf *q = inp;
2121 #endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */
2122             err = http_post_request(q, hs, data, data_len, uri, sp2);
2123             if (err != ERR_OK) {
2124               /* restore header for next try */
2125               *sp1 = ' ';
2126               *sp2 = ' ';
2127               uri[uri_len] = ' ';
2128             }
2129             if (err == ERR_ARG) {
2130               goto badrequest;
2131             }
2132             return err;
2133           } else
2134 #endif /* LWIP_HTTPD_SUPPORT_POST */
2135           {
2136             return http_find_file(hs, uri, is_09);
2137           }
2138         }
2139       } else {
2140         LWIP_DEBUGF(HTTPD_DEBUG, ("invalid URI\n"));
2141       }
2142     }
2143   }
2144 
2145 #if LWIP_HTTPD_SUPPORT_REQUESTLIST
2146   clen = pbuf_clen(hs->req);
2147   if ((hs->req->tot_len <= LWIP_HTTPD_REQ_BUFSIZE) &&
2148       (clen <= LWIP_HTTPD_REQ_QUEUELEN)) {
2149     /* request not fully received (too short or CRLF is missing) */
2150     return ERR_INPROGRESS;
2151   } else
2152 #endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */
2153   {
2154 #if LWIP_HTTPD_SUPPORT_POST
2155 badrequest:
2156 #endif /* LWIP_HTTPD_SUPPORT_POST */
2157     LWIP_DEBUGF(HTTPD_DEBUG, ("bad request\n"));
2158     /* could not parse request */
2159     return http_find_error_file(hs, 400);
2160   }
2161 }
2162 
2163 #if LWIP_HTTPD_SSI && (LWIP_HTTPD_SSI_BY_FILE_EXTENSION == 1)
2164 /* Check if SSI should be parsed for this file/URL
2165  * (With LWIP_HTTPD_SSI_BY_FILE_EXTENSION == 2, this function can be
2166  * overridden by an external implementation.)
2167  *
2168  * @return 1 for SSI, 0 for standard files
2169  */
2170 static u8_t
2171 http_uri_is_ssi(struct fs_file *file, const char *uri)
2172 {
2173   size_t loop;
2174   u8_t tag_check = 0;
2175   if (file != NULL) {
2176     /* See if we have been asked for an shtml file and, if so,
2177         enable tag checking. */
2178     const char *ext = NULL, *sub;
2179     char *param = (char *)strstr(uri, "?");
2180     if (param != NULL) {
2181       /* separate uri from parameters for now, set back later */
2182       *param = 0;
2183     }
2184     sub = uri;
2185     ext = uri;
2186     for (sub = strstr(sub, "."); sub != NULL; sub = strstr(sub, ".")) {
2187       ext = sub;
2188       sub++;
2189     }
2190     for (loop = 0; loop < NUM_SHTML_EXTENSIONS; loop++) {
2191       if (!lwip_stricmp(ext, g_pcSSIExtensions[loop])) {
2192         tag_check = 1;
2193         break;
2194       }
2195     }
2196     if (param != NULL) {
2197       *param = '?';
2198     }
2199   }
2200   return tag_check;
2201 }
2202 #endif /* LWIP_HTTPD_SSI */
2203 
2204 /** Try to find the file specified by uri and, if found, initialize hs
2205  * accordingly.
2206  *
2207  * @param hs the connection state
2208  * @param uri the HTTP header URI
2209  * @param is_09 1 if the request is HTTP/0.9 (no HTTP headers in response)
2210  * @return ERR_OK if file was found and hs has been initialized correctly
2211  *         another err_t otherwise
2212  */
2213 static err_t
2214 http_find_file(struct http_state *hs, const char *uri, int is_09)
2215 {
2216   size_t loop;
2217   struct fs_file *file = NULL;
2218   char *params = NULL;
2219   err_t err;
2220 #if LWIP_HTTPD_CGI
2221   int i;
2222 #endif /* LWIP_HTTPD_CGI */
2223 #if !LWIP_HTTPD_SSI
2224   const
2225 #endif /* !LWIP_HTTPD_SSI */
2226   /* By default, assume we will not be processing server-side-includes tags */
2227   u8_t tag_check = 0;
2228 
2229   /* Have we been asked for the default file (in root or a directory) ? */
2230 #if LWIP_HTTPD_MAX_REQUEST_URI_LEN
2231   size_t uri_len = strlen(uri);
2232   if ((uri_len > 0) && (uri[uri_len - 1] == '/') &&
2233       ((uri != http_uri_buf) || (uri_len == 1))) {
2234     size_t copy_len = LWIP_MIN(sizeof(http_uri_buf) - 1, uri_len - 1);
2235     if (copy_len > 0) {
2236       MEMCPY(http_uri_buf, uri, copy_len);
2237       http_uri_buf[copy_len] = 0;
2238     }
2239 #else /* LWIP_HTTPD_MAX_REQUEST_URI_LEN */
2240   if ((uri[0] == '/') &&  (uri[1] == 0)) {
2241 #endif /* LWIP_HTTPD_MAX_REQUEST_URI_LEN */
2242     /* Try each of the configured default filenames until we find one
2243        that exists. */
2244     for (loop = 0; loop < NUM_DEFAULT_FILENAMES; loop++) {
2245       const char *file_name;
2246 #if LWIP_HTTPD_MAX_REQUEST_URI_LEN
2247       if (copy_len > 0) {
2248         size_t len_left = sizeof(http_uri_buf) - copy_len - 1;
2249         if (len_left > 0) {
2250           size_t name_len = strlen(httpd_default_filenames[loop].name);
2251           size_t name_copy_len = LWIP_MIN(len_left, name_len);
2252           MEMCPY(&http_uri_buf[copy_len], httpd_default_filenames[loop].name, name_copy_len);
2253           http_uri_buf[copy_len + name_copy_len] = 0;
2254         }
2255         file_name = http_uri_buf;
2256       } else
2257 #endif /* LWIP_HTTPD_MAX_REQUEST_URI_LEN */
2258       {
2259         file_name = httpd_default_filenames[loop].name;
2260       }
2261       LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Looking for %s...\n", file_name));
2262       err = fs_open(&hs->file_handle, file_name);
2263       if (err == ERR_OK) {
2264         uri = file_name;
2265         file = &hs->file_handle;
2266         LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Opened.\n"));
2267 #if LWIP_HTTPD_SSI
2268         tag_check = httpd_default_filenames[loop].shtml;
2269 #endif /* LWIP_HTTPD_SSI */
2270         break;
2271       }
2272     }
2273   }
2274   if (file == NULL) {
2275     /* No - we've been asked for a specific file. */
2276     /* First, isolate the base URI (without any parameters) */
2277     params = (char *)strchr(uri, '?');
2278     if (params != NULL) {
2279       /* URI contains parameters. NULL-terminate the base URI */
2280       *params = '\0';
2281       params++;
2282     }
2283 
2284 #if LWIP_HTTPD_CGI
2285     http_cgi_paramcount = -1;
2286     /* Does the base URI we have isolated correspond to a CGI handler? */
2287     if (httpd_num_cgis && httpd_cgis) {
2288       for (i = 0; i < httpd_num_cgis; i++) {
2289         if (strcmp(uri, httpd_cgis[i].pcCGIName) == 0) {
2290           /*
2291            * We found a CGI that handles this URI so extract the
2292            * parameters and call the handler.
2293            */
2294           http_cgi_paramcount = extract_uri_parameters(hs, params);
2295           uri = httpd_cgis[i].pfnCGIHandler(i, http_cgi_paramcount, hs->params,
2296                                          hs->param_vals);
2297           break;
2298         }
2299       }
2300     }
2301 #endif /* LWIP_HTTPD_CGI */
2302 
2303     LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Opening %s\n", uri));
2304 
2305     err = fs_open(&hs->file_handle, uri);
2306     if (err == ERR_OK) {
2307       file = &hs->file_handle;
2308     } else {
2309       file = http_get_404_file(hs, &uri);
2310     }
2311 #if LWIP_HTTPD_SSI
2312     if (file != NULL) {
2313       if (file->flags & FS_FILE_FLAGS_SSI) {
2314         tag_check = 1;
2315       } else {
2316 #if LWIP_HTTPD_SSI_BY_FILE_EXTENSION
2317         tag_check = http_uri_is_ssi(file, uri);
2318 #endif /* LWIP_HTTPD_SSI_BY_FILE_EXTENSION */
2319       }
2320     }
2321 #endif /* LWIP_HTTPD_SSI */
2322   }
2323   if (file == NULL) {
2324     /* None of the default filenames exist so send back a 404 page */
2325     file = http_get_404_file(hs, &uri);
2326   }
2327   return http_init_file(hs, file, is_09, uri, tag_check, params);
2328 }
2329 
2330 /** Initialize a http connection with a file to send (if found).
2331  * Called by http_find_file and http_find_error_file.
2332  *
2333  * @param hs http connection state
2334  * @param file file structure to send (or NULL if not found)
2335  * @param is_09 1 if the request is HTTP/0.9 (no HTTP headers in response)
2336  * @param uri the HTTP header URI
2337  * @param tag_check enable SSI tag checking
2338  * @param params != NULL if URI has parameters (separated by '?')
2339  * @return ERR_OK if file was found and hs has been initialized correctly
2340  *         another err_t otherwise
2341  */
2342 static err_t
2343 http_init_file(struct http_state *hs, struct fs_file *file, int is_09, const char *uri,
2344                u8_t tag_check, char *params)
2345 {
2346 #if !LWIP_HTTPD_SUPPORT_V09
2347   LWIP_UNUSED_ARG(is_09);
2348 #endif
2349   if (file != NULL) {
2350     /* file opened, initialise struct http_state */
2351 #if !LWIP_HTTPD_DYNAMIC_FILE_READ
2352     /* If dynamic read is disabled, file data must be in one piece and available now */
2353     LWIP_ASSERT("file->data != NULL", file->data != NULL);
2354 #endif
2355 
2356 #if LWIP_HTTPD_SSI
2357     if (tag_check) {
2358       struct http_ssi_state *ssi = http_ssi_state_alloc();
2359       if (ssi != NULL) {
2360         ssi->tag_index = 0;
2361         ssi->tag_state = TAG_NONE;
2362         ssi->parsed = file->data;
2363         ssi->parse_left = file->len;
2364         ssi->tag_end = file->data;
2365         hs->ssi = ssi;
2366       }
2367     }
2368 #else /* LWIP_HTTPD_SSI */
2369     LWIP_UNUSED_ARG(tag_check);
2370 #endif /* LWIP_HTTPD_SSI */
2371     hs->handle = file;
2372 #if LWIP_HTTPD_CGI_SSI
2373     if (params != NULL) {
2374       /* URI contains parameters, call generic CGI handler */
2375       int count;
2376 #if LWIP_HTTPD_CGI
2377       if (http_cgi_paramcount >= 0) {
2378         count = http_cgi_paramcount;
2379       } else
2380 #endif
2381       {
2382         count = extract_uri_parameters(hs, params);
2383       }
2384       httpd_cgi_handler(file, uri, count, http_cgi_params, http_cgi_param_vals
2385 #if defined(LWIP_HTTPD_FILE_STATE) && LWIP_HTTPD_FILE_STATE
2386                         , file->state
2387 #endif /* LWIP_HTTPD_FILE_STATE */
2388                        );
2389     }
2390 #else /* LWIP_HTTPD_CGI_SSI */
2391     LWIP_UNUSED_ARG(params);
2392 #endif /* LWIP_HTTPD_CGI_SSI */
2393     hs->file = file->data;
2394     LWIP_ASSERT("File length must be positive!", (file->len >= 0));
2395 #if LWIP_HTTPD_CUSTOM_FILES
2396     if (((file->flags & FS_FILE_FLAGS_CUSTOM) != 0) && (file->data == NULL)) {
2397       /* custom file, need to read data first (via fs_read_custom) */
2398       hs->left = 0;
2399     } else
2400 #endif /* LWIP_HTTPD_CUSTOM_FILES */
2401     {
2402       hs->left = (u32_t)file->len;
2403     }
2404     hs->retries = 0;
2405 #if LWIP_HTTPD_TIMING
2406     hs->time_started = sys_now();
2407 #endif /* LWIP_HTTPD_TIMING */
2408 #if !LWIP_HTTPD_DYNAMIC_HEADERS
2409     LWIP_ASSERT("HTTP headers not included in file system",
2410                 (hs->handle->flags & FS_FILE_FLAGS_HEADER_INCLUDED) != 0);
2411 #endif /* !LWIP_HTTPD_DYNAMIC_HEADERS */
2412 #if LWIP_HTTPD_SUPPORT_V09
2413     if (is_09 && ((hs->handle->flags & FS_FILE_FLAGS_HEADER_INCLUDED) != 0)) {
2414       /* HTTP/0.9 responses are sent without HTTP header,
2415          search for the end of the header. */
2416       char *file_start = lwip_strnstr(hs->file, CRLF CRLF, hs->left);
2417       if (file_start != NULL) {
2418         size_t diff = file_start + 4 - hs->file;
2419         hs->file += diff;
2420         hs->left -= (u32_t)diff;
2421       }
2422     }
2423 #endif /* LWIP_HTTPD_SUPPORT_V09*/
2424   } else {
2425     hs->handle = NULL;
2426     hs->file = NULL;
2427     hs->left = 0;
2428     hs->retries = 0;
2429   }
2430 #if LWIP_HTTPD_DYNAMIC_HEADERS
2431   /* Determine the HTTP headers to send based on the file extension of
2432    * the requested URI. */
2433   if ((hs->handle == NULL) || ((hs->handle->flags & FS_FILE_FLAGS_HEADER_INCLUDED) == 0)) {
2434     get_http_headers(hs, uri);
2435   }
2436 #else /* LWIP_HTTPD_DYNAMIC_HEADERS */
2437   LWIP_UNUSED_ARG(uri);
2438 #endif /* LWIP_HTTPD_DYNAMIC_HEADERS */
2439 #if LWIP_HTTPD_SUPPORT_11_KEEPALIVE
2440   if (hs->keepalive) {
2441 #if LWIP_HTTPD_SSI
2442     if (hs->ssi != NULL) {
2443       hs->keepalive = 0;
2444     } else
2445 #endif /* LWIP_HTTPD_SSI */
2446     {
2447       if ((hs->handle != NULL) &&
2448           ((hs->handle->flags & (FS_FILE_FLAGS_HEADER_INCLUDED | FS_FILE_FLAGS_HEADER_PERSISTENT)) == FS_FILE_FLAGS_HEADER_INCLUDED)) {
2449         hs->keepalive = 0;
2450       }
2451     }
2452   }
2453 #endif /* LWIP_HTTPD_SUPPORT_11_KEEPALIVE */
2454   return ERR_OK;
2455 }
2456 
2457 /**
2458  * The pcb had an error and is already deallocated.
2459  * The argument might still be valid (if != NULL).
2460  */
2461 static void
2462 http_err(void *arg, err_t err)
2463 {
2464   struct http_state *hs = (struct http_state *)arg;
2465   LWIP_UNUSED_ARG(err);
2466 
2467   LWIP_DEBUGF(HTTPD_DEBUG, ("http_err: %s\n", lwip_strerr(err)));
2468 
2469   if (hs != NULL) {
2470     http_state_free(hs);
2471   }
2472 }
2473 
2474 /**
2475  * Data has been sent and acknowledged by the remote host.
2476  * This means that more data can be sent.
2477  */
2478 static err_t
2479 http_sent(void *arg, struct altcp_pcb *pcb, u16_t len)
2480 {
2481   struct http_state *hs = (struct http_state *)arg;
2482 
2483   LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("http_sent %p\n", (void *)pcb));
2484 
2485   LWIP_UNUSED_ARG(len);
2486 
2487   if (hs == NULL) {
2488     return ERR_OK;
2489   }
2490 
2491   hs->retries = 0;
2492 
2493   http_send(pcb, hs);
2494 
2495   return ERR_OK;
2496 }
2497 
2498 /**
2499  * The poll function is called every 2nd second.
2500  * If there has been no data sent (which resets the retries) in 8 seconds, close.
2501  * If the last portion of a file has not been sent in 2 seconds, close.
2502  *
2503  * This could be increased, but we don't want to waste resources for bad connections.
2504  */
2505 static err_t
2506 http_poll(void *arg, struct altcp_pcb *pcb)
2507 {
2508   struct http_state *hs = (struct http_state *)arg;
2509   LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("http_poll: pcb=%p hs=%p pcb_state=%s\n",
2510               (void *)pcb, (void *)hs, tcp_debug_state_str(altcp_dbg_get_tcp_state(pcb))));
2511 
2512   if (hs == NULL) {
2513     err_t closed;
2514     /* arg is null, close. */
2515     LWIP_DEBUGF(HTTPD_DEBUG, ("http_poll: arg is NULL, close\n"));
2516     closed = http_close_conn(pcb, NULL);
2517     LWIP_UNUSED_ARG(closed);
2518 #if LWIP_HTTPD_ABORT_ON_CLOSE_MEM_ERROR
2519     if (closed == ERR_MEM) {
2520       altcp_abort(pcb);
2521       return ERR_ABRT;
2522     }
2523 #endif /* LWIP_HTTPD_ABORT_ON_CLOSE_MEM_ERROR */
2524     return ERR_OK;
2525   } else {
2526     hs->retries++;
2527     if (hs->retries == HTTPD_MAX_RETRIES) {
2528       LWIP_DEBUGF(HTTPD_DEBUG, ("http_poll: too many retries, close\n"));
2529       http_close_conn(pcb, hs);
2530       return ERR_OK;
2531     }
2532 
2533     /* If this connection has a file open, try to send some more data. If
2534      * it has not yet received a GET request, don't do this since it will
2535      * cause the connection to close immediately. */
2536     if (hs->handle) {
2537       LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("http_poll: try to send more data\n"));
2538       if (http_send(pcb, hs)) {
2539         /* If we wrote anything to be sent, go ahead and send it now. */
2540         LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("tcp_output\n"));
2541         altcp_output(pcb);
2542       }
2543     }
2544   }
2545 
2546   return ERR_OK;
2547 }
2548 
2549 /**
2550  * Data has been received on this pcb.
2551  * For HTTP 1.0, this should normally only happen once (if the request fits in one packet).
2552  */
2553 static err_t
2554 http_recv(void *arg, struct altcp_pcb *pcb, struct pbuf *p, err_t err)
2555 {
2556   struct http_state *hs = (struct http_state *)arg;
2557   LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("http_recv: pcb=%p pbuf=%p err=%s\n", (void *)pcb,
2558               (void *)p, lwip_strerr(err)));
2559 
2560   if ((err != ERR_OK) || (p == NULL) || (hs == NULL)) {
2561     /* error or closed by other side? */
2562     if (p != NULL) {
2563       /* Inform TCP that we have taken the data. */
2564       altcp_recved(pcb, p->tot_len);
2565       pbuf_free(p);
2566     }
2567     if (hs == NULL) {
2568       /* this should not happen, only to be robust */
2569       LWIP_DEBUGF(HTTPD_DEBUG, ("Error, http_recv: hs is NULL, close\n"));
2570     }
2571     http_close_conn(pcb, hs);
2572     return ERR_OK;
2573   }
2574 
2575 #if LWIP_HTTPD_SUPPORT_POST && LWIP_HTTPD_POST_MANUAL_WND
2576   if (hs->no_auto_wnd) {
2577     hs->unrecved_bytes += p->tot_len;
2578   } else
2579 #endif /* LWIP_HTTPD_SUPPORT_POST && LWIP_HTTPD_POST_MANUAL_WND */
2580   {
2581     /* Inform TCP that we have taken the data. */
2582     altcp_recved(pcb, p->tot_len);
2583   }
2584 
2585 #if LWIP_HTTPD_SUPPORT_POST
2586   if (hs->post_content_len_left > 0) {
2587     /* reset idle counter when POST data is received */
2588     hs->retries = 0;
2589     /* this is data for a POST, pass the complete pbuf to the application */
2590     http_post_rxpbuf(hs, p);
2591     /* pbuf is passed to the application, don't free it! */
2592     if (hs->post_content_len_left == 0) {
2593       /* all data received, send response or close connection */
2594       http_send(pcb, hs);
2595     }
2596     return ERR_OK;
2597   } else
2598 #endif /* LWIP_HTTPD_SUPPORT_POST */
2599   {
2600     if (hs->handle == NULL) {
2601       err_t parsed = http_parse_request(p, hs, pcb);
2602       LWIP_ASSERT("http_parse_request: unexpected return value", parsed == ERR_OK
2603                   || parsed == ERR_INPROGRESS || parsed == ERR_ARG || parsed == ERR_USE);
2604 #if LWIP_HTTPD_SUPPORT_REQUESTLIST
2605       if (parsed != ERR_INPROGRESS) {
2606         /* request fully parsed or error */
2607         if (hs->req != NULL) {
2608           pbuf_free(hs->req);
2609           hs->req = NULL;
2610         }
2611       }
2612 #endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */
2613       pbuf_free(p);
2614       if (parsed == ERR_OK) {
2615 #if LWIP_HTTPD_SUPPORT_POST
2616         if (hs->post_content_len_left == 0)
2617 #endif /* LWIP_HTTPD_SUPPORT_POST */
2618         {
2619           LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("http_recv: data %p len %"S32_F"\n", (const void *)hs->file, hs->left));
2620           http_send(pcb, hs);
2621         }
2622       } else if (parsed == ERR_ARG) {
2623         /* @todo: close on ERR_USE? */
2624         http_close_conn(pcb, hs);
2625       }
2626     } else {
2627       LWIP_DEBUGF(HTTPD_DEBUG, ("http_recv: already sending data\n"));
2628       /* already sending but still receiving data, we might want to RST here? */
2629       pbuf_free(p);
2630     }
2631   }
2632   return ERR_OK;
2633 }
2634 
2635 /**
2636  * A new incoming connection has been accepted.
2637  */
2638 static err_t
2639 http_accept(void *arg, struct altcp_pcb *pcb, err_t err)
2640 {
2641   struct http_state *hs;
2642   LWIP_UNUSED_ARG(err);
2643   LWIP_UNUSED_ARG(arg);
2644   LWIP_DEBUGF(HTTPD_DEBUG, ("http_accept %p / %p\n", (void *)pcb, arg));
2645 
2646   if ((err != ERR_OK) || (pcb == NULL)) {
2647     return ERR_VAL;
2648   }
2649 
2650   /* Set priority */
2651   altcp_setprio(pcb, HTTPD_TCP_PRIO);
2652 
2653   /* Allocate memory for the structure that holds the state of the
2654      connection - initialized by that function. */
2655   hs = http_state_alloc();
2656   if (hs == NULL) {
2657     LWIP_DEBUGF(HTTPD_DEBUG, ("http_accept: Out of memory, RST\n"));
2658     return ERR_MEM;
2659   }
2660   hs->pcb = pcb;
2661 
2662   /* Tell TCP that this is the structure we wish to be passed for our
2663      callbacks. */
2664   altcp_arg(pcb, hs);
2665 
2666   /* Set up the various callback functions */
2667   altcp_recv(pcb, http_recv);
2668   altcp_err(pcb, http_err);
2669   altcp_poll(pcb, http_poll, HTTPD_POLL_INTERVAL);
2670   altcp_sent(pcb, http_sent);
2671 
2672   return ERR_OK;
2673 }
2674 
2675 static void
2676 httpd_init_pcb(struct altcp_pcb *pcb, u16_t port)
2677 {
2678   err_t err;
2679 
2680   if (pcb) {
2681     altcp_setprio(pcb, HTTPD_TCP_PRIO);
2682     /* set SOF_REUSEADDR here to explicitly bind httpd to multiple interfaces */
2683     err = altcp_bind(pcb, IP_ANY_TYPE, port);
2684     LWIP_UNUSED_ARG(err); /* in case of LWIP_NOASSERT */
2685     LWIP_ASSERT("httpd_init: tcp_bind failed", err == ERR_OK);
2686     pcb = altcp_listen(pcb);
2687     LWIP_ASSERT("httpd_init: tcp_listen failed", pcb != NULL);
2688     altcp_accept(pcb, http_accept);
2689   }
2690 }
2691 
2692 /**
2693  * @ingroup httpd
2694  * Initialize the httpd: set up a listening PCB and bind it to the defined port
2695  */
2696 void
2697 httpd_init(void)
2698 {
2699   struct altcp_pcb *pcb;
2700 
2701 #if HTTPD_USE_MEM_POOL
2702   LWIP_MEMPOOL_INIT(HTTPD_STATE);
2703 #if LWIP_HTTPD_SSI
2704   LWIP_MEMPOOL_INIT(HTTPD_SSI_STATE);
2705 #endif
2706 #endif
2707   LWIP_DEBUGF(HTTPD_DEBUG, ("httpd_init\n"));
2708 
2709   /* LWIP_ASSERT_CORE_LOCKED(); is checked by tcp_new() */
2710 
2711   pcb = altcp_tcp_new_ip_type(IPADDR_TYPE_ANY);
2712   LWIP_ASSERT("httpd_init: tcp_new failed", pcb != NULL);
2713   httpd_init_pcb(pcb, HTTPD_SERVER_PORT);
2714 }
2715 
2716 #if HTTPD_ENABLE_HTTPS
2717 /**
2718  * @ingroup httpd
2719  * Initialize the httpd: set up a listening PCB and bind it to the defined port.
2720  * Also set up TLS connection handling (HTTPS).
2721  */
2722 void
2723 httpd_inits(struct altcp_tls_config *conf)
2724 {
2725 #if LWIP_ALTCP_TLS
2726   struct altcp_pcb *pcb_tls = altcp_tls_new(conf, IPADDR_TYPE_ANY);
2727   LWIP_ASSERT("httpd_init: altcp_tls_new failed", pcb_tls != NULL);
2728   httpd_init_pcb(pcb_tls, HTTPD_SERVER_PORT_HTTPS);
2729 #else /* LWIP_ALTCP_TLS */
2730   LWIP_UNUSED_ARG(conf);
2731 #endif /* LWIP_ALTCP_TLS */
2732 }
2733 #endif /* HTTPD_ENABLE_HTTPS */
2734 
2735 #if LWIP_HTTPD_SSI
2736 /**
2737  * @ingroup httpd
2738  * Set the SSI handler function.
2739  *
2740  * @param ssi_handler the SSI handler function
2741  * @param tags an array of SSI tag strings to search for in SSI-enabled files
2742  * @param num_tags number of tags in the 'tags' array
2743  */
2744 void
2745 http_set_ssi_handler(tSSIHandler ssi_handler, const char **tags, int num_tags)
2746 {
2747   LWIP_DEBUGF(HTTPD_DEBUG, ("http_set_ssi_handler\n"));
2748 
2749   LWIP_ASSERT("no ssi_handler given", ssi_handler != NULL);
2750   httpd_ssi_handler = ssi_handler;
2751 
2752 #if LWIP_HTTPD_SSI_RAW
2753   LWIP_UNUSED_ARG(tags);
2754   LWIP_UNUSED_ARG(num_tags);
2755 #else /* LWIP_HTTPD_SSI_RAW */
2756   LWIP_ASSERT("no tags given", tags != NULL);
2757   LWIP_ASSERT("invalid number of tags", num_tags > 0);
2758 
2759   httpd_tags = tags;
2760   httpd_num_tags = num_tags;
2761 #endif /* !LWIP_HTTPD_SSI_RAW */
2762 }
2763 #endif /* LWIP_HTTPD_SSI */
2764 
2765 #if LWIP_HTTPD_CGI
2766 /**
2767  * @ingroup httpd
2768  * Set an array of CGI filenames/handler functions
2769  *
2770  * @param cgis an array of CGI filenames/handler functions
2771  * @param num_handlers number of elements in the 'cgis' array
2772  */
2773 void
2774 http_set_cgi_handlers(const tCGI *cgis, int num_handlers)
2775 {
2776   LWIP_ASSERT("no cgis given", cgis != NULL);
2777   LWIP_ASSERT("invalid number of handlers", num_handlers > 0);
2778 
2779   httpd_cgis = cgis;
2780   httpd_num_cgis = num_handlers;
2781 }
2782 #endif /* LWIP_HTTPD_CGI */
2783 
2784 #endif /* LWIP_TCP && LWIP_CALLBACK_API */
2785