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 
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 /* An HTTP GET handler */
hello_get_handler(httpd_req_t * req)30 static esp_err_t hello_get_handler(httpd_req_t *req)
31 {
32     char*  buf;
33     size_t buf_len;
34 
35     /* Get header value string length and allocate memory for length + 1,
36      * extra byte for null termination */
37     buf_len = httpd_req_get_hdr_value_len(req, "Host") + 1;
38     if (buf_len > 1) {
39         buf = malloc(buf_len);
40         /* Copy null terminated value string into buffer */
41         if (httpd_req_get_hdr_value_str(req, "Host", buf, buf_len) == ESP_OK) {
42             ESP_LOGI(TAG, "Found header => Host: %s", buf);
43         }
44         free(buf);
45     }
46 
47     buf_len = httpd_req_get_hdr_value_len(req, "Test-Header-2") + 1;
48     if (buf_len > 1) {
49         buf = malloc(buf_len);
50         if (httpd_req_get_hdr_value_str(req, "Test-Header-2", buf, buf_len) == ESP_OK) {
51             ESP_LOGI(TAG, "Found header => Test-Header-2: %s", buf);
52         }
53         free(buf);
54     }
55 
56     buf_len = httpd_req_get_hdr_value_len(req, "Test-Header-1") + 1;
57     if (buf_len > 1) {
58         buf = malloc(buf_len);
59         if (httpd_req_get_hdr_value_str(req, "Test-Header-1", buf, buf_len) == ESP_OK) {
60             ESP_LOGI(TAG, "Found header => Test-Header-1: %s", buf);
61         }
62         free(buf);
63     }
64 
65     /* Read URL query string length and allocate memory for length + 1,
66      * extra byte for null termination */
67     buf_len = httpd_req_get_url_query_len(req) + 1;
68     if (buf_len > 1) {
69         buf = malloc(buf_len);
70         if (httpd_req_get_url_query_str(req, buf, buf_len) == ESP_OK) {
71             ESP_LOGI(TAG, "Found URL query => %s", buf);
72             char param[32];
73             /* Get value of expected key from query string */
74             if (httpd_query_key_value(buf, "query1", param, sizeof(param)) == ESP_OK) {
75                 ESP_LOGI(TAG, "Found URL query parameter => query1=%s", param);
76             }
77             if (httpd_query_key_value(buf, "query3", param, sizeof(param)) == ESP_OK) {
78                 ESP_LOGI(TAG, "Found URL query parameter => query3=%s", param);
79             }
80             if (httpd_query_key_value(buf, "query2", param, sizeof(param)) == ESP_OK) {
81                 ESP_LOGI(TAG, "Found URL query parameter => query2=%s", param);
82             }
83         }
84         free(buf);
85     }
86 
87     /* Set some custom headers */
88     httpd_resp_set_hdr(req, "Custom-Header-1", "Custom-Value-1");
89     httpd_resp_set_hdr(req, "Custom-Header-2", "Custom-Value-2");
90 
91     /* Send response with custom headers and body set as the
92      * string passed in user context*/
93     const char* resp_str = (const char*) req->user_ctx;
94     httpd_resp_send(req, resp_str, HTTPD_RESP_USE_STRLEN);
95 
96     /* After sending the HTTP response the old HTTP request
97      * headers are lost. Check if HTTP request headers can be read now. */
98     if (httpd_req_get_hdr_value_len(req, "Host") == 0) {
99         ESP_LOGI(TAG, "Request headers lost");
100     }
101     return ESP_OK;
102 }
103 
104 static const httpd_uri_t hello = {
105     .uri       = "/hello",
106     .method    = HTTP_GET,
107     .handler   = hello_get_handler,
108     /* Let's pass response string in user
109      * context to demonstrate it's usage */
110     .user_ctx  = "Hello World!"
111 };
112 
113 /* An HTTP POST handler */
echo_post_handler(httpd_req_t * req)114 static esp_err_t echo_post_handler(httpd_req_t *req)
115 {
116     char buf[100];
117     int ret, remaining = req->content_len;
118 
119     while (remaining > 0) {
120         /* Read the data for the request */
121         if ((ret = httpd_req_recv(req, buf,
122                         MIN(remaining, sizeof(buf)))) <= 0) {
123             if (ret == HTTPD_SOCK_ERR_TIMEOUT) {
124                 /* Retry receiving if timeout occurred */
125                 continue;
126             }
127             return ESP_FAIL;
128         }
129 
130         /* Send back the same data */
131         httpd_resp_send_chunk(req, buf, ret);
132         remaining -= ret;
133 
134         /* Log data received */
135         ESP_LOGI(TAG, "=========== RECEIVED DATA ==========");
136         ESP_LOGI(TAG, "%.*s", ret, buf);
137         ESP_LOGI(TAG, "====================================");
138     }
139 
140     // End response
141     httpd_resp_send_chunk(req, NULL, 0);
142     return ESP_OK;
143 }
144 
145 static const httpd_uri_t echo = {
146     .uri       = "/echo",
147     .method    = HTTP_POST,
148     .handler   = echo_post_handler,
149     .user_ctx  = NULL
150 };
151 
152 /* This handler allows the custom error handling functionality to be
153  * tested from client side. For that, when a PUT request 0 is sent to
154  * URI /ctrl, the /hello and /echo URIs are unregistered and following
155  * custom error handler http_404_error_handler() is registered.
156  * Afterwards, when /hello or /echo is requested, this custom error
157  * handler is invoked which, after sending an error message to client,
158  * either closes the underlying socket (when requested URI is /echo)
159  * or keeps it open (when requested URI is /hello). This allows the
160  * client to infer if the custom error handler is functioning as expected
161  * by observing the socket state.
162  */
http_404_error_handler(httpd_req_t * req,httpd_err_code_t err)163 esp_err_t http_404_error_handler(httpd_req_t *req, httpd_err_code_t err)
164 {
165     if (strcmp("/hello", req->uri) == 0) {
166         httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, "/hello URI is not available");
167         /* Return ESP_OK to keep underlying socket open */
168         return ESP_OK;
169     } else if (strcmp("/echo", req->uri) == 0) {
170         httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, "/echo URI is not available");
171         /* Return ESP_FAIL to close underlying socket */
172         return ESP_FAIL;
173     }
174     /* For any other URI send 404 and close socket */
175     httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, "Some 404 error message");
176     return ESP_FAIL;
177 }
178 
179 /* An HTTP PUT handler. This demonstrates realtime
180  * registration and deregistration of URI handlers
181  */
ctrl_put_handler(httpd_req_t * req)182 static esp_err_t ctrl_put_handler(httpd_req_t *req)
183 {
184     char buf;
185     int ret;
186 
187     if ((ret = httpd_req_recv(req, &buf, 1)) <= 0) {
188         if (ret == HTTPD_SOCK_ERR_TIMEOUT) {
189             httpd_resp_send_408(req);
190         }
191         return ESP_FAIL;
192     }
193 
194     if (buf == '0') {
195         /* URI handlers can be unregistered using the uri string */
196         ESP_LOGI(TAG, "Unregistering /hello and /echo URIs");
197         httpd_unregister_uri(req->handle, "/hello");
198         httpd_unregister_uri(req->handle, "/echo");
199         /* Register the custom error handler */
200         httpd_register_err_handler(req->handle, HTTPD_404_NOT_FOUND, http_404_error_handler);
201     }
202     else {
203         ESP_LOGI(TAG, "Registering /hello and /echo URIs");
204         httpd_register_uri_handler(req->handle, &hello);
205         httpd_register_uri_handler(req->handle, &echo);
206         /* Unregister custom error handler */
207         httpd_register_err_handler(req->handle, HTTPD_404_NOT_FOUND, NULL);
208     }
209 
210     /* Respond with empty body */
211     httpd_resp_send(req, NULL, 0);
212     return ESP_OK;
213 }
214 
215 static const httpd_uri_t ctrl = {
216     .uri       = "/ctrl",
217     .method    = HTTP_PUT,
218     .handler   = ctrl_put_handler,
219     .user_ctx  = NULL
220 };
221 
start_webserver(void)222 static httpd_handle_t start_webserver(void)
223 {
224     httpd_handle_t server = NULL;
225     httpd_config_t config = HTTPD_DEFAULT_CONFIG();
226     config.lru_purge_enable = true;
227 
228     // Start the httpd server
229     ESP_LOGI(TAG, "Starting server on port: '%d'", config.server_port);
230     if (httpd_start(&server, &config) == ESP_OK) {
231         // Set URI handlers
232         ESP_LOGI(TAG, "Registering URI handlers");
233         httpd_register_uri_handler(server, &hello);
234         httpd_register_uri_handler(server, &echo);
235         httpd_register_uri_handler(server, &ctrl);
236         return server;
237     }
238 
239     ESP_LOGI(TAG, "Error starting server!");
240     return NULL;
241 }
242 
stop_webserver(httpd_handle_t server)243 static void stop_webserver(httpd_handle_t server)
244 {
245     // Stop the httpd server
246     httpd_stop(server);
247 }
248 
disconnect_handler(void * arg,esp_event_base_t event_base,int32_t event_id,void * event_data)249 static void disconnect_handler(void* arg, esp_event_base_t event_base,
250                                int32_t event_id, void* event_data)
251 {
252     httpd_handle_t* server = (httpd_handle_t*) arg;
253     if (*server) {
254         ESP_LOGI(TAG, "Stopping webserver");
255         stop_webserver(*server);
256         *server = NULL;
257     }
258 }
259 
connect_handler(void * arg,esp_event_base_t event_base,int32_t event_id,void * event_data)260 static void connect_handler(void* arg, esp_event_base_t event_base,
261                             int32_t event_id, void* event_data)
262 {
263     httpd_handle_t* server = (httpd_handle_t*) arg;
264     if (*server == NULL) {
265         ESP_LOGI(TAG, "Starting webserver");
266         *server = start_webserver();
267     }
268 }
269 
270 
app_main(void)271 void app_main(void)
272 {
273     static httpd_handle_t server = NULL;
274 
275     ESP_ERROR_CHECK(nvs_flash_init());
276     ESP_ERROR_CHECK(esp_netif_init());
277     ESP_ERROR_CHECK(esp_event_loop_create_default());
278 
279     /* This helper function configures Wi-Fi or Ethernet, as selected in menuconfig.
280      * Read "Establishing Wi-Fi or Ethernet Connection" section in
281      * examples/protocols/README.md for more information about this function.
282      */
283     ESP_ERROR_CHECK(example_connect());
284 
285     /* Register event handlers to stop the server when Wi-Fi or Ethernet is disconnected,
286      * and re-start it upon connection.
287      */
288 #ifdef CONFIG_EXAMPLE_CONNECT_WIFI
289     ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &connect_handler, &server));
290     ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, WIFI_EVENT_STA_DISCONNECTED, &disconnect_handler, &server));
291 #endif // CONFIG_EXAMPLE_CONNECT_WIFI
292 #ifdef CONFIG_EXAMPLE_CONNECT_ETHERNET
293     ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_ETH_GOT_IP, &connect_handler, &server));
294     ESP_ERROR_CHECK(esp_event_handler_register(ETH_EVENT, ETHERNET_EVENT_DISCONNECTED, &disconnect_handler, &server));
295 #endif // CONFIG_EXAMPLE_CONNECT_ETHERNET
296 
297     /* Start the server for the first time */
298     server = start_webserver();
299 }
300