main.c 16 KB

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