1 #include <stdlib.h>
2 #include <stdbool.h>
3 
4 #include <esp_log.h>
5 #include <esp_system.h>
6 #include <esp_http_server.h>
7 
8 #include "tests.h"
9 
10 static const char *TAG = "TESTS";
11 
12 static int pre_start_mem, post_stop_mem;
13 
14 struct async_resp_arg {
15     httpd_handle_t hd;
16     int fd;
17 };
18 
19 /********************* Basic Handlers Start *******************/
20 
hello_get_handler(httpd_req_t * req)21 static esp_err_t hello_get_handler(httpd_req_t *req)
22 {
23 #define STR "Hello World!"
24     ESP_LOGI(TAG, "Free Stack for server task: '%d'", uxTaskGetStackHighWaterMark(NULL));
25     httpd_resp_send(req, STR, HTTPD_RESP_USE_STRLEN);
26     return ESP_OK;
27 #undef STR
28 }
29 
30 /* This handler is intended to check what happens in case of empty values of headers.
31  * Here `Header2` is an empty header and `Header1` and `Header3` will have `Value1`
32  * and `Value3` in them. */
test_header_get_handler(httpd_req_t * req)33 static esp_err_t test_header_get_handler(httpd_req_t *req)
34 {
35     httpd_resp_set_type(req, HTTPD_TYPE_TEXT);
36     int buf_len;
37     char *buf;
38 
39     buf_len = httpd_req_get_hdr_value_len(req, "Header1");
40     if (buf_len > 0) {
41         buf = malloc(++buf_len);
42         if (!buf) {
43             ESP_LOGE(TAG, "Failed to allocate memory of %d bytes!", buf_len);
44             httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Memory allocation failed");
45             return ESP_ERR_NO_MEM;
46         }
47         /* Copy null terminated value string into buffer */
48         if (httpd_req_get_hdr_value_str(req, "Header1", buf, buf_len) == ESP_OK) {
49             ESP_LOGI(TAG, "Header1 content: %s", buf);
50             if (strcmp("Value1", buf) != 0) {
51                 httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Wrong value of Header1 received");
52                 free(buf);
53                 return ESP_ERR_INVALID_ARG;
54             } else {
55                 ESP_LOGI(TAG, "Expected value and received value matched for Header1");
56             }
57         } else {
58             ESP_LOGE(TAG, "Error in getting value of Header1");
59             httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Error in getting value of Header1");
60             free(buf);
61             return ESP_FAIL;
62         }
63         free(buf);
64     } else {
65         ESP_LOGE(TAG, "Header1 not found");
66         httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Header1 not found");
67         return ESP_ERR_NOT_FOUND;
68     }
69 
70     buf_len = httpd_req_get_hdr_value_len(req, "Header3");
71     if (buf_len > 0) {
72         buf = malloc(++buf_len);
73         if (!buf) {
74             ESP_LOGE(TAG, "Failed to allocate memory of %d bytes!", buf_len);
75             httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Memory allocation failed");
76             return ESP_ERR_NO_MEM;
77         }
78         /* Copy null terminated value string into buffer */
79         if (httpd_req_get_hdr_value_str(req, "Header3", buf, buf_len) == ESP_OK) {
80             ESP_LOGI(TAG, "Header3 content: %s", buf);
81             if (strcmp("Value3", buf) != 0) {
82                 httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Wrong value of Header3 received");
83                 free(buf);
84                 return ESP_ERR_INVALID_ARG;
85             } else {
86                 ESP_LOGI(TAG, "Expected value and received value matched for Header3");
87             }
88         } else {
89             ESP_LOGE(TAG, "Error in getting value of Header3");
90             httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Error in getting value of Header3");
91             free(buf);
92             return ESP_FAIL;
93         }
94         free(buf);
95     } else {
96         ESP_LOGE(TAG, "Header3 not found");
97         httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Header3 not found");
98         return ESP_ERR_NOT_FOUND;
99     }
100 
101     buf_len = httpd_req_get_hdr_value_len(req, "Header2");
102     buf = malloc(++buf_len);
103     if (!buf) {
104         ESP_LOGE(TAG, "Failed to allocate memory of %d bytes!", buf_len);
105         httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Memory allocation failed");
106         return ESP_ERR_NO_MEM;
107     }
108     if (httpd_req_get_hdr_value_str(req, "Header2", buf, buf_len) == ESP_OK) {
109         ESP_LOGI(TAG, "Header2 content: %s", buf);
110         httpd_resp_send(req, buf, HTTPD_RESP_USE_STRLEN);
111     } else {
112         ESP_LOGE(TAG, "Header2 not found");
113         httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Header2 not found");
114         return ESP_FAIL;
115     }
116 
117     return ESP_OK;
118 }
119 
hello_type_get_handler(httpd_req_t * req)120 static esp_err_t hello_type_get_handler(httpd_req_t *req)
121 {
122 #define STR "Hello World!"
123     httpd_resp_set_type(req, HTTPD_TYPE_TEXT);
124     httpd_resp_send(req, STR, HTTPD_RESP_USE_STRLEN);
125     return ESP_OK;
126 #undef STR
127 }
128 
hello_status_get_handler(httpd_req_t * req)129 static esp_err_t hello_status_get_handler(httpd_req_t *req)
130 {
131 #define STR "Hello World!"
132     httpd_resp_set_status(req, HTTPD_500);
133     httpd_resp_send(req, STR, HTTPD_RESP_USE_STRLEN);
134     return ESP_OK;
135 #undef STR
136 }
137 
echo_post_handler(httpd_req_t * req)138 static esp_err_t echo_post_handler(httpd_req_t *req)
139 {
140     ESP_LOGI(TAG, "/echo handler read content length %d", req->content_len);
141 
142     char*  buf = malloc(req->content_len + 1);
143     size_t off = 0;
144     int    ret;
145 
146     if (!buf) {
147         ESP_LOGE(TAG, "Failed to allocate memory of %d bytes!", req->content_len + 1);
148         httpd_resp_send_500(req);
149         return ESP_FAIL;
150     }
151 
152     while (off < req->content_len) {
153         /* Read data received in the request */
154         ret = httpd_req_recv(req, buf + off, req->content_len - off);
155         if (ret <= 0) {
156             if (ret == HTTPD_SOCK_ERR_TIMEOUT) {
157                 httpd_resp_send_408(req);
158             }
159             free (buf);
160             return ESP_FAIL;
161         }
162         off += ret;
163         ESP_LOGI(TAG, "/echo handler recv length %d", ret);
164     }
165     buf[off] = '\0';
166 
167     if (req->content_len < 128) {
168         ESP_LOGI(TAG, "/echo handler read %s", buf);
169     }
170 
171     /* Search for Custom header field */
172     char*  req_hdr = 0;
173     size_t hdr_len = httpd_req_get_hdr_value_len(req, "Custom");
174     if (hdr_len) {
175         /* Read Custom header value */
176         req_hdr = malloc(hdr_len + 1);
177         if (!req_hdr) {
178             ESP_LOGE(TAG, "Failed to allocate memory of %d bytes!", hdr_len + 1);
179             httpd_resp_send_500(req);
180             return ESP_FAIL;
181         }
182         httpd_req_get_hdr_value_str(req, "Custom", req_hdr, hdr_len + 1);
183 
184         /* Set as additional header for response packet */
185         httpd_resp_set_hdr(req, "Custom", req_hdr);
186     }
187     httpd_resp_send(req, buf, req->content_len);
188     free (req_hdr);
189     free (buf);
190     return ESP_OK;
191 }
192 
adder_free_func(void * ctx)193 static void adder_free_func(void *ctx)
194 {
195     ESP_LOGI(TAG, "Custom Free Context function called");
196     free(ctx);
197 }
198 
199 /* Create a context, keep incrementing value in the context, by whatever was
200  * received. Return the result
201  */
adder_post_handler(httpd_req_t * req)202 static esp_err_t adder_post_handler(httpd_req_t *req)
203 {
204     char buf[10];
205     char outbuf[50];
206     int  ret;
207 
208     /* Read data received in the request */
209     ret = httpd_req_recv(req, buf, sizeof(buf));
210     if (ret <= 0) {
211         if (ret == HTTPD_SOCK_ERR_TIMEOUT) {
212             httpd_resp_send_408(req);
213         }
214         return ESP_FAIL;
215     }
216 
217     buf[ret] = '\0';
218     int val = atoi(buf);
219     ESP_LOGI(TAG, "/adder handler read %d", val);
220 
221     if (! req->sess_ctx) {
222         ESP_LOGI(TAG, "/adder allocating new session");
223         req->sess_ctx = malloc(sizeof(int));
224         req->free_ctx = adder_free_func;
225         *(int *)req->sess_ctx = 0;
226     }
227     int *adder = (int *)req->sess_ctx;
228     *adder += val;
229 
230     snprintf(outbuf, sizeof(outbuf),"%d", *adder);
231     httpd_resp_send(req, outbuf, HTTPD_RESP_USE_STRLEN);
232     return ESP_OK;
233 }
234 
leftover_data_post_handler(httpd_req_t * req)235 static esp_err_t leftover_data_post_handler(httpd_req_t *req)
236 {
237     /* Only echo the first 10 bytes of the request, leaving the rest of the
238      * request data as is.
239      */
240     char buf[11];
241     int  ret;
242 
243     /* Read data received in the request */
244     ret = httpd_req_recv(req, buf, sizeof(buf) - 1);
245     if (ret <= 0) {
246         if (ret == HTTPD_SOCK_ERR_TIMEOUT) {
247             httpd_resp_send_408(req);
248         }
249         return ESP_FAIL;
250     }
251 
252     buf[ret] = '\0';
253     ESP_LOGI(TAG, "leftover data handler read %s", buf);
254     httpd_resp_send(req, buf, HTTPD_RESP_USE_STRLEN);
255     return ESP_OK;
256 }
257 
generate_async_resp(void * arg)258 static void generate_async_resp(void *arg)
259 {
260     char buf[250];
261     struct async_resp_arg *resp_arg = (struct async_resp_arg *)arg;
262     httpd_handle_t hd = resp_arg->hd;
263     int fd = resp_arg->fd;
264 #define HTTPD_HDR_STR      "HTTP/1.1 200 OK\r\n"                   \
265                            "Content-Type: text/html\r\n"           \
266                            "Content-Length: %d\r\n"
267 #define STR "Hello Double World!"
268 
269     ESP_LOGI(TAG, "Executing queued work fd : %d", fd);
270 
271     snprintf(buf, sizeof(buf), HTTPD_HDR_STR,
272          strlen(STR));
273     httpd_socket_send(hd, fd, buf, strlen(buf), 0);
274     /* Space for sending additional headers based on set_header */
275     httpd_socket_send(hd, fd, "\r\n", strlen("\r\n"), 0);
276     httpd_socket_send(hd, fd, STR, strlen(STR), 0);
277 #undef STR
278     free(arg);
279 }
280 
async_get_handler(httpd_req_t * req)281 static esp_err_t async_get_handler(httpd_req_t *req)
282 {
283 #define STR "Hello World!"
284     httpd_resp_send(req, STR, HTTPD_RESP_USE_STRLEN);
285     /* Also register a HTTPD Work which sends the same data on the same
286      * socket again
287      */
288     struct async_resp_arg *resp_arg = malloc(sizeof(struct async_resp_arg));
289     resp_arg->hd = req->handle;
290     resp_arg->fd = httpd_req_to_sockfd(req);
291     if (resp_arg->fd < 0) {
292         return ESP_FAIL;
293     }
294 
295     ESP_LOGI(TAG, "Queuing work fd : %d", resp_arg->fd);
296     httpd_queue_work(req->handle, generate_async_resp, resp_arg);
297     return ESP_OK;
298 #undef STR
299 }
300 
301 
302 static const httpd_uri_t basic_handlers[] = {
303     { .uri      = "/hello/type_html",
304       .method   = HTTP_GET,
305       .handler  = hello_type_get_handler,
306       .user_ctx = NULL,
307     },
308     { .uri      = "/test_header",
309       .method   = HTTP_GET,
310       .handler  = test_header_get_handler,
311       .user_ctx = NULL,
312     },
313     { .uri      = "/hello",
314       .method   = HTTP_GET,
315       .handler  = hello_get_handler,
316       .user_ctx = NULL,
317     },
318     { .uri      = "/hello/status_500",
319       .method   = HTTP_GET,
320       .handler  = hello_status_get_handler,
321       .user_ctx = NULL,
322     },
323     { .uri      = "/echo",
324       .method   = HTTP_POST,
325       .handler  = echo_post_handler,
326       .user_ctx = NULL,
327     },
328     { .uri      = "/echo",
329       .method   = HTTP_PUT,
330       .handler  = echo_post_handler,
331       .user_ctx = NULL,
332     },
333     { .uri      = "/leftover_data",
334       .method   = HTTP_POST,
335       .handler  = leftover_data_post_handler,
336       .user_ctx = NULL,
337     },
338     { .uri      = "/adder",
339       .method   = HTTP_POST,
340       .handler  = adder_post_handler,
341       .user_ctx = NULL,
342     },
343     { .uri      = "/async_data",
344       .method   = HTTP_GET,
345       .handler  = async_get_handler,
346       .user_ctx = NULL,
347     }
348 };
349 
350 static const int basic_handlers_no = sizeof(basic_handlers)/sizeof(httpd_uri_t);
351 
register_basic_handlers(httpd_handle_t hd)352 static void register_basic_handlers(httpd_handle_t hd)
353 {
354     int i;
355     ESP_LOGI(TAG, "Registering basic handlers");
356     ESP_LOGI(TAG, "No of handlers = %d", basic_handlers_no);
357     for (i = 0; i < basic_handlers_no; i++) {
358         if (httpd_register_uri_handler(hd, &basic_handlers[i]) != ESP_OK) {
359             ESP_LOGW(TAG, "register uri failed for %d", i);
360             return;
361         }
362     }
363     ESP_LOGI(TAG, "Success");
364 }
365 
test_httpd_start(void)366 static httpd_handle_t test_httpd_start(void)
367 {
368     pre_start_mem = esp_get_free_heap_size();
369     httpd_handle_t hd;
370     httpd_config_t config = HTTPD_DEFAULT_CONFIG();
371     /* Modify this setting to match the number of test URI handlers */
372     config.max_uri_handlers  = 9;
373     config.server_port = 1234;
374 
375     /* This check should be a part of http_server */
376     config.max_open_sockets = (CONFIG_LWIP_MAX_SOCKETS - 3);
377 
378     if (httpd_start(&hd, &config) == ESP_OK) {
379         ESP_LOGI(TAG, "Started HTTP server on port: '%d'", config.server_port);
380         ESP_LOGI(TAG, "Max URI handlers: '%d'", config.max_uri_handlers);
381         ESP_LOGI(TAG, "Max Open Sessions: '%d'", config.max_open_sockets);
382         ESP_LOGI(TAG, "Max Header Length: '%d'", HTTPD_MAX_REQ_HDR_LEN);
383         ESP_LOGI(TAG, "Max URI Length: '%d'", HTTPD_MAX_URI_LEN);
384         ESP_LOGI(TAG, "Max Stack Size: '%d'", config.stack_size);
385         return hd;
386     }
387     return NULL;
388 }
389 
test_httpd_stop(httpd_handle_t hd)390 static void test_httpd_stop(httpd_handle_t hd)
391 {
392     httpd_stop(hd);
393     post_stop_mem = esp_get_free_heap_size();
394     ESP_LOGI(TAG, "HTTPD Stop: Current free memory: %d", post_stop_mem);
395 }
396 
start_tests(void)397 httpd_handle_t start_tests(void)
398 {
399     httpd_handle_t hd = test_httpd_start();
400     if (hd) {
401         register_basic_handlers(hd);
402     }
403     return hd;
404 }
405 
stop_tests(httpd_handle_t hd)406 void stop_tests(httpd_handle_t hd)
407 {
408     ESP_LOGI(TAG, "Stopping httpd");
409     test_httpd_stop(hd);
410 }
411