1 /* Simple HTTP Server Example
2 
3    This example code is in the Public Domain (or CC0 licensed, at your option.)
4 
5    Unless required by applicable law or agreed to in writing, this
6    software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
7    CONDITIONS OF ANY KIND, either express or implied.
8 */
9 
10 #include <esp_wifi.h>
11 #include <esp_event.h>
12 #include <esp_log.h>
13 #include <esp_system.h>
14 #include <nvs_flash.h>
15 #include <sys/param.h>
16 #include "nvs_flash.h"
17 #include "esp_netif.h"
18 #include "esp_eth.h"
19 #include "protocol_examples_common.h"
20 #include "esp_tls_crypto.h"
21 #include <esp_http_server.h>
22 
23 /* A simple example that demonstrates how to create GET and POST
24  * handlers for the web server.
25  */
26 
27 static const char *TAG = "example";
28 
29 #if CONFIG_EXAMPLE_BASIC_AUTH
30 
31 typedef struct {
32     char    *username;
33     char    *password;
34 } basic_auth_info_t;
35 
36 #define HTTPD_401      "401 UNAUTHORIZED"           /*!< HTTP Response 401 */
37 
http_auth_basic(const char * username,const char * password)38 static char *http_auth_basic(const char *username, const char *password)
39 {
40     int out;
41     char *user_info = NULL;
42     char *digest = NULL;
43     size_t n = 0;
44     asprintf(&user_info, "%s:%s", username, password);
45     if (!user_info) {
46         ESP_LOGE(TAG, "No enough memory for user information");
47         return NULL;
48     }
49     esp_crypto_base64_encode(NULL, 0, &n, (const unsigned char *)user_info, strlen(user_info));
50 
51     /* 6: The length of the "Basic " string
52      * n: Number of bytes for a base64 encode format
53      * 1: Number of bytes for a reserved which be used to fill zero
54     */
55     digest = calloc(1, 6 + n + 1);
56     if (digest) {
57         strcpy(digest, "Basic ");
58         esp_crypto_base64_encode((unsigned char *)digest + 6, n, (size_t *)&out, (const unsigned char *)user_info, strlen(user_info));
59     }
60     free(user_info);
61     return digest;
62 }
63 
64 /* An HTTP GET handler */
basic_auth_get_handler(httpd_req_t * req)65 static esp_err_t basic_auth_get_handler(httpd_req_t *req)
66 {
67     char *buf = NULL;
68     size_t buf_len = 0;
69     basic_auth_info_t *basic_auth_info = req->user_ctx;
70 
71     buf_len = httpd_req_get_hdr_value_len(req, "Authorization") + 1;
72     if (buf_len > 1) {
73         buf = calloc(1, buf_len);
74         if (!buf) {
75             ESP_LOGE(TAG, "No enough memory for basic authorization");
76             return ESP_ERR_NO_MEM;
77         }
78 
79         if (httpd_req_get_hdr_value_str(req, "Authorization", buf, buf_len) == ESP_OK) {
80             ESP_LOGI(TAG, "Found header => Authorization: %s", buf);
81         } else {
82             ESP_LOGE(TAG, "No auth value received");
83         }
84 
85         char *auth_credentials = http_auth_basic(basic_auth_info->username, basic_auth_info->password);
86         if (!auth_credentials) {
87             ESP_LOGE(TAG, "No enough memory for basic authorization credentials");
88             free(buf);
89             return ESP_ERR_NO_MEM;
90         }
91 
92         if (strncmp(auth_credentials, buf, buf_len)) {
93             ESP_LOGE(TAG, "Not authenticated");
94             httpd_resp_set_status(req, HTTPD_401);
95             httpd_resp_set_type(req, "application/json");
96             httpd_resp_set_hdr(req, "Connection", "keep-alive");
97             httpd_resp_set_hdr(req, "WWW-Authenticate", "Basic realm=\"Hello\"");
98             httpd_resp_send(req, NULL, 0);
99         } else {
100             ESP_LOGI(TAG, "Authenticated!");
101             char *basic_auth_resp = NULL;
102             httpd_resp_set_status(req, HTTPD_200);
103             httpd_resp_set_type(req, "application/json");
104             httpd_resp_set_hdr(req, "Connection", "keep-alive");
105             asprintf(&basic_auth_resp, "{\"authenticated\": true,\"user\": \"%s\"}", basic_auth_info->username);
106             if (!basic_auth_resp) {
107                 ESP_LOGE(TAG, "No enough memory for basic authorization response");
108                 free(auth_credentials);
109                 free(buf);
110                 return ESP_ERR_NO_MEM;
111             }
112             httpd_resp_send(req, basic_auth_resp, strlen(basic_auth_resp));
113             free(basic_auth_resp);
114         }
115         free(auth_credentials);
116         free(buf);
117     } else {
118         ESP_LOGE(TAG, "No auth header received");
119         httpd_resp_set_status(req, HTTPD_401);
120         httpd_resp_set_type(req, "application/json");
121         httpd_resp_set_hdr(req, "Connection", "keep-alive");
122         httpd_resp_set_hdr(req, "WWW-Authenticate", "Basic realm=\"Hello\"");
123         httpd_resp_send(req, NULL, 0);
124     }
125 
126     return ESP_OK;
127 }
128 
129 static httpd_uri_t basic_auth = {
130     .uri       = "/basic_auth",
131     .method    = HTTP_GET,
132     .handler   = basic_auth_get_handler,
133 };
134 
httpd_register_basic_auth(httpd_handle_t server)135 static void httpd_register_basic_auth(httpd_handle_t server)
136 {
137     basic_auth_info_t *basic_auth_info = calloc(1, sizeof(basic_auth_info_t));
138     if (basic_auth_info) {
139         basic_auth_info->username = CONFIG_EXAMPLE_BASIC_AUTH_USERNAME;
140         basic_auth_info->password = CONFIG_EXAMPLE_BASIC_AUTH_PASSWORD;
141 
142         basic_auth.user_ctx = basic_auth_info;
143         httpd_register_uri_handler(server, &basic_auth);
144     }
145 }
146 #endif
147 
148 /* An HTTP GET handler */
hello_get_handler(httpd_req_t * req)149 static esp_err_t hello_get_handler(httpd_req_t *req)
150 {
151     char*  buf;
152     size_t buf_len;
153 
154     /* Get header value string length and allocate memory for length + 1,
155      * extra byte for null termination */
156     buf_len = httpd_req_get_hdr_value_len(req, "Host") + 1;
157     if (buf_len > 1) {
158         buf = malloc(buf_len);
159         /* Copy null terminated value string into buffer */
160         if (httpd_req_get_hdr_value_str(req, "Host", buf, buf_len) == ESP_OK) {
161             ESP_LOGI(TAG, "Found header => Host: %s", buf);
162         }
163         free(buf);
164     }
165 
166     buf_len = httpd_req_get_hdr_value_len(req, "Test-Header-2") + 1;
167     if (buf_len > 1) {
168         buf = malloc(buf_len);
169         if (httpd_req_get_hdr_value_str(req, "Test-Header-2", buf, buf_len) == ESP_OK) {
170             ESP_LOGI(TAG, "Found header => Test-Header-2: %s", buf);
171         }
172         free(buf);
173     }
174 
175     buf_len = httpd_req_get_hdr_value_len(req, "Test-Header-1") + 1;
176     if (buf_len > 1) {
177         buf = malloc(buf_len);
178         if (httpd_req_get_hdr_value_str(req, "Test-Header-1", buf, buf_len) == ESP_OK) {
179             ESP_LOGI(TAG, "Found header => Test-Header-1: %s", buf);
180         }
181         free(buf);
182     }
183 
184     /* Read URL query string length and allocate memory for length + 1,
185      * extra byte for null termination */
186     buf_len = httpd_req_get_url_query_len(req) + 1;
187     if (buf_len > 1) {
188         buf = malloc(buf_len);
189         if (httpd_req_get_url_query_str(req, buf, buf_len) == ESP_OK) {
190             ESP_LOGI(TAG, "Found URL query => %s", buf);
191             char param[32];
192             /* Get value of expected key from query string */
193             if (httpd_query_key_value(buf, "query1", param, sizeof(param)) == ESP_OK) {
194                 ESP_LOGI(TAG, "Found URL query parameter => query1=%s", param);
195             }
196             if (httpd_query_key_value(buf, "query3", param, sizeof(param)) == ESP_OK) {
197                 ESP_LOGI(TAG, "Found URL query parameter => query3=%s", param);
198             }
199             if (httpd_query_key_value(buf, "query2", param, sizeof(param)) == ESP_OK) {
200                 ESP_LOGI(TAG, "Found URL query parameter => query2=%s", param);
201             }
202         }
203         free(buf);
204     }
205 
206     /* Set some custom headers */
207     httpd_resp_set_hdr(req, "Custom-Header-1", "Custom-Value-1");
208     httpd_resp_set_hdr(req, "Custom-Header-2", "Custom-Value-2");
209 
210     /* Send response with custom headers and body set as the
211      * string passed in user context*/
212     const char* resp_str = (const char*) req->user_ctx;
213     httpd_resp_send(req, resp_str, HTTPD_RESP_USE_STRLEN);
214 
215     /* After sending the HTTP response the old HTTP request
216      * headers are lost. Check if HTTP request headers can be read now. */
217     if (httpd_req_get_hdr_value_len(req, "Host") == 0) {
218         ESP_LOGI(TAG, "Request headers lost");
219     }
220     return ESP_OK;
221 }
222 
223 static const httpd_uri_t hello = {
224     .uri       = "/hello",
225     .method    = HTTP_GET,
226     .handler   = hello_get_handler,
227     /* Let's pass response string in user
228      * context to demonstrate it's usage */
229     .user_ctx  = "Hello World!"
230 };
231 
232 /* An HTTP POST handler */
echo_post_handler(httpd_req_t * req)233 static esp_err_t echo_post_handler(httpd_req_t *req)
234 {
235     char buf[100];
236     int ret, remaining = req->content_len;
237 
238     while (remaining > 0) {
239         /* Read the data for the request */
240         if ((ret = httpd_req_recv(req, buf,
241                         MIN(remaining, sizeof(buf)))) <= 0) {
242             if (ret == HTTPD_SOCK_ERR_TIMEOUT) {
243                 /* Retry receiving if timeout occurred */
244                 continue;
245             }
246             return ESP_FAIL;
247         }
248 
249         /* Send back the same data */
250         httpd_resp_send_chunk(req, buf, ret);
251         remaining -= ret;
252 
253         /* Log data received */
254         ESP_LOGI(TAG, "=========== RECEIVED DATA ==========");
255         ESP_LOGI(TAG, "%.*s", ret, buf);
256         ESP_LOGI(TAG, "====================================");
257     }
258 
259     // End response
260     httpd_resp_send_chunk(req, NULL, 0);
261     return ESP_OK;
262 }
263 
264 static const httpd_uri_t echo = {
265     .uri       = "/echo",
266     .method    = HTTP_POST,
267     .handler   = echo_post_handler,
268     .user_ctx  = NULL
269 };
270 
271 /* This handler allows the custom error handling functionality to be
272  * tested from client side. For that, when a PUT request 0 is sent to
273  * URI /ctrl, the /hello and /echo URIs are unregistered and following
274  * custom error handler http_404_error_handler() is registered.
275  * Afterwards, when /hello or /echo is requested, this custom error
276  * handler is invoked which, after sending an error message to client,
277  * either closes the underlying socket (when requested URI is /echo)
278  * or keeps it open (when requested URI is /hello). This allows the
279  * client to infer if the custom error handler is functioning as expected
280  * by observing the socket state.
281  */
http_404_error_handler(httpd_req_t * req,httpd_err_code_t err)282 esp_err_t http_404_error_handler(httpd_req_t *req, httpd_err_code_t err)
283 {
284     if (strcmp("/hello", req->uri) == 0) {
285         httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, "/hello URI is not available");
286         /* Return ESP_OK to keep underlying socket open */
287         return ESP_OK;
288     } else if (strcmp("/echo", req->uri) == 0) {
289         httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, "/echo URI is not available");
290         /* Return ESP_FAIL to close underlying socket */
291         return ESP_FAIL;
292     }
293     /* For any other URI send 404 and close socket */
294     httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, "Some 404 error message");
295     return ESP_FAIL;
296 }
297 
298 /* An HTTP PUT handler. This demonstrates realtime
299  * registration and deregistration of URI handlers
300  */
ctrl_put_handler(httpd_req_t * req)301 static esp_err_t ctrl_put_handler(httpd_req_t *req)
302 {
303     char buf;
304     int ret;
305 
306     if ((ret = httpd_req_recv(req, &buf, 1)) <= 0) {
307         if (ret == HTTPD_SOCK_ERR_TIMEOUT) {
308             httpd_resp_send_408(req);
309         }
310         return ESP_FAIL;
311     }
312 
313     if (buf == '0') {
314         /* URI handlers can be unregistered using the uri string */
315         ESP_LOGI(TAG, "Unregistering /hello and /echo URIs");
316         httpd_unregister_uri(req->handle, "/hello");
317         httpd_unregister_uri(req->handle, "/echo");
318         /* Register the custom error handler */
319         httpd_register_err_handler(req->handle, HTTPD_404_NOT_FOUND, http_404_error_handler);
320     }
321     else {
322         ESP_LOGI(TAG, "Registering /hello and /echo URIs");
323         httpd_register_uri_handler(req->handle, &hello);
324         httpd_register_uri_handler(req->handle, &echo);
325         /* Unregister custom error handler */
326         httpd_register_err_handler(req->handle, HTTPD_404_NOT_FOUND, NULL);
327     }
328 
329     /* Respond with empty body */
330     httpd_resp_send(req, NULL, 0);
331     return ESP_OK;
332 }
333 
334 static const httpd_uri_t ctrl = {
335     .uri       = "/ctrl",
336     .method    = HTTP_PUT,
337     .handler   = ctrl_put_handler,
338     .user_ctx  = NULL
339 };
340 
start_webserver(void)341 static httpd_handle_t start_webserver(void)
342 {
343     httpd_handle_t server = NULL;
344     httpd_config_t config = HTTPD_DEFAULT_CONFIG();
345     config.lru_purge_enable = true;
346 
347     // Start the httpd server
348     ESP_LOGI(TAG, "Starting server on port: '%d'", config.server_port);
349     if (httpd_start(&server, &config) == ESP_OK) {
350         // Set URI handlers
351         ESP_LOGI(TAG, "Registering URI handlers");
352         httpd_register_uri_handler(server, &hello);
353         httpd_register_uri_handler(server, &echo);
354         httpd_register_uri_handler(server, &ctrl);
355         #if CONFIG_EXAMPLE_BASIC_AUTH
356         httpd_register_basic_auth(server);
357         #endif
358         return server;
359     }
360 
361     ESP_LOGI(TAG, "Error starting server!");
362     return NULL;
363 }
364 
stop_webserver(httpd_handle_t server)365 static void stop_webserver(httpd_handle_t server)
366 {
367     // Stop the httpd server
368     httpd_stop(server);
369 }
370 
disconnect_handler(void * arg,esp_event_base_t event_base,int32_t event_id,void * event_data)371 static void disconnect_handler(void* arg, esp_event_base_t event_base,
372                                int32_t event_id, void* event_data)
373 {
374     httpd_handle_t* server = (httpd_handle_t*) arg;
375     if (*server) {
376         ESP_LOGI(TAG, "Stopping webserver");
377         stop_webserver(*server);
378         *server = NULL;
379     }
380 }
381 
connect_handler(void * arg,esp_event_base_t event_base,int32_t event_id,void * event_data)382 static void connect_handler(void* arg, esp_event_base_t event_base,
383                             int32_t event_id, void* event_data)
384 {
385     httpd_handle_t* server = (httpd_handle_t*) arg;
386     if (*server == NULL) {
387         ESP_LOGI(TAG, "Starting webserver");
388         *server = start_webserver();
389     }
390 }
391 
392 
app_main(void)393 void app_main(void)
394 {
395     static httpd_handle_t server = NULL;
396 
397     ESP_ERROR_CHECK(nvs_flash_init());
398     ESP_ERROR_CHECK(esp_netif_init());
399     ESP_ERROR_CHECK(esp_event_loop_create_default());
400 
401     /* This helper function configures Wi-Fi or Ethernet, as selected in menuconfig.
402      * Read "Establishing Wi-Fi or Ethernet Connection" section in
403      * examples/protocols/README.md for more information about this function.
404      */
405     ESP_ERROR_CHECK(example_connect());
406 
407     /* Register event handlers to stop the server when Wi-Fi or Ethernet is disconnected,
408      * and re-start it upon connection.
409      */
410 #ifdef CONFIG_EXAMPLE_CONNECT_WIFI
411     ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &connect_handler, &server));
412     ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, WIFI_EVENT_STA_DISCONNECTED, &disconnect_handler, &server));
413 #endif // CONFIG_EXAMPLE_CONNECT_WIFI
414 #ifdef CONFIG_EXAMPLE_CONNECT_ETHERNET
415     ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_ETH_GOT_IP, &connect_handler, &server));
416     ESP_ERROR_CHECK(esp_event_handler_register(ETH_EVENT, ETHERNET_EVENT_DISCONNECTED, &disconnect_handler, &server));
417 #endif // CONFIG_EXAMPLE_CONNECT_ETHERNET
418 
419     /* Start the server for the first time */
420     server = start_webserver();
421 }
422