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