2
0

_esp_httpd_main.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. // Copyright 2018 Espressif Systems (Shanghai) PTE LTD
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include <string.h>
  15. #include <sys/socket.h>
  16. #include <sys/param.h>
  17. #include <errno.h>
  18. #include <esp_log.h>
  19. #include <esp_err.h>
  20. #include <assert.h>
  21. #include <esp_http_server.h>
  22. #include <_esp_http_server.h>
  23. #include "esp_httpd_priv.h"
  24. #include "ctrl_sock.h"
  25. static const char *TAG = "_httpd";
  26. struct httpd_ctrl_data {
  27. enum httpd_ctrl_msg {
  28. HTTPD_CTRL_SHUTDOWN,
  29. HTTPD_CTRL_WORK,
  30. } hc_msg;
  31. httpd_work_fn_t hc_work;
  32. void *hc_work_arg;
  33. };
  34. static esp_err_t _httpd_server_init(struct httpd_data *hd)
  35. {
  36. int fd = socket(PF_INET6, SOCK_STREAM, 0);
  37. if (fd < 0) {
  38. ESP_LOGE(TAG, LOG_FMT("error in socket (%d)"), errno);
  39. return ESP_FAIL;
  40. }
  41. struct in6_addr inaddr_any = IN6ADDR_ANY_INIT;
  42. struct sockaddr_in6 serv_addr = {
  43. .sin6_family = PF_INET6,
  44. .sin6_addr = inaddr_any,
  45. .sin6_port = htons(hd->config.server_port)
  46. };
  47. /* Enable SO_REUSEADDR to allow binding to the same
  48. * address and port when restarting the server */
  49. int enable = 1;
  50. if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) < 0) {
  51. /* This will fail if CONFIG_LWIP_SO_REUSE is not enabled. But
  52. * it does not affect the normal working of the HTTP Server */
  53. ESP_LOGW(TAG, LOG_FMT("error enabling SO_REUSEADDR (%d)"), errno);
  54. }
  55. int ret = bind(fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
  56. if (ret < 0) {
  57. ESP_LOGE(TAG, LOG_FMT("error in bind (%d)"), errno);
  58. close(fd);
  59. return ESP_FAIL;
  60. }
  61. ret = listen(fd, hd->config.backlog_conn);
  62. if (ret < 0) {
  63. ESP_LOGE(TAG, LOG_FMT("error in listen (%d)"), errno);
  64. close(fd);
  65. return ESP_FAIL;
  66. }
  67. hd->listen_fd = fd;
  68. return ESP_OK;
  69. }
  70. static esp_err_t _httpd_accept_conn(struct httpd_data *hd, int listen_fd)
  71. {
  72. /* If no space is available for new session, close the least recently used one */
  73. if (hd->config.lru_purge_enable == true) {
  74. if (!httpd_is_sess_available(hd)) {
  75. /* Queue asynchronous closure of the least recently used session */
  76. return httpd_sess_close_lru(hd);
  77. /* Returning from this allowes the main server thread to process
  78. * the queued asynchronous control message for closing LRU session.
  79. * Since connection request hasn't been addressed yet using accept()
  80. * therefore _httpd_accept_conn() will be called again, but this time
  81. * with space available for one session
  82. */
  83. }
  84. }
  85. struct sockaddr_in addr_from;
  86. socklen_t addr_from_len = sizeof(addr_from);
  87. int new_fd = accept(listen_fd, (struct sockaddr *)&addr_from, &addr_from_len);
  88. if (new_fd < 0) {
  89. ESP_LOGW(TAG, LOG_FMT("error in accept (%d)"), errno);
  90. return ESP_FAIL;
  91. }
  92. ESP_LOGD(TAG, LOG_FMT("newfd = %d"), new_fd);
  93. struct timeval tv;
  94. /* Set recv timeout of this fd as per config */
  95. tv.tv_sec = hd->config.recv_wait_timeout;
  96. tv.tv_usec = 0;
  97. setsockopt(new_fd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof(tv));
  98. /* Set send timeout of this fd as per config */
  99. tv.tv_sec = hd->config.send_wait_timeout;
  100. tv.tv_usec = 0;
  101. setsockopt(new_fd, SOL_SOCKET, SO_SNDTIMEO, (const char*)&tv, sizeof(tv));
  102. if (ESP_OK != httpd_sess_new(hd, new_fd)) {
  103. ESP_LOGW(TAG, LOG_FMT("session creation failed"));
  104. close(new_fd);
  105. return ESP_FAIL;
  106. }
  107. ESP_LOGD(TAG, LOG_FMT("complete"));
  108. return ESP_OK;
  109. }
  110. /* Manage in-coming connection or data requests */
  111. static esp_err_t _httpd_server(struct httpd_data *hd)
  112. {
  113. fd_set read_set;
  114. FD_ZERO(&read_set);
  115. if (hd->config.lru_purge_enable || httpd_is_sess_available(hd)) {
  116. /* Only listen for new connections if server has capacity to
  117. * handle more (or when LRU purge is enabled, in which case
  118. * older connections will be closed) */
  119. FD_SET(hd->listen_fd, &read_set);
  120. }
  121. int maxfd;
  122. httpd_sess_set_descriptors(hd, &read_set, &maxfd);
  123. maxfd = MAX(hd->listen_fd, maxfd);
  124. ESP_LOGD(TAG, LOG_FMT("doing select maxfd+1 = %d"), maxfd + 1);
  125. int active_cnt = select(maxfd + 1, &read_set, NULL, NULL, NULL);
  126. if (active_cnt < 0) {
  127. ESP_LOGE(TAG, LOG_FMT("error in select (%d)"), errno);
  128. httpd_sess_delete_invalid(hd);
  129. return ESP_OK;
  130. }
  131. /* Case1: Do we have any activity on the current data
  132. * sessions? */
  133. int fd = -1;
  134. while ((fd = httpd_sess_iterate(hd, fd)) != -1) {
  135. if (FD_ISSET(fd, &read_set) || (httpd_sess_pending(hd, fd))) {
  136. ESP_LOGD(TAG, LOG_FMT("processing socket %d"), fd);
  137. if (httpd_sess_process(hd, fd) != ESP_OK) {
  138. ESP_LOGD(TAG, LOG_FMT("closing socket %d"), fd);
  139. close(fd);
  140. /* Delete session and update fd to that
  141. * preceding the one being deleted */
  142. fd = httpd_sess_delete(hd, fd);
  143. }
  144. }
  145. }
  146. /* Case2: Do we have any incoming connection requests to
  147. * process? */
  148. if (FD_ISSET(hd->listen_fd, &read_set)) {
  149. ESP_LOGD(TAG, LOG_FMT("processing listen socket %d"), hd->listen_fd);
  150. if (_httpd_accept_conn(hd, hd->listen_fd) != ESP_OK) {
  151. ESP_LOGW(TAG, LOG_FMT("error accepting new connection"));
  152. }
  153. }
  154. return ESP_OK;
  155. }
  156. static void _httpd_close_all_sessions(struct httpd_data *hd)
  157. {
  158. int fd = -1;
  159. while ((fd = httpd_sess_iterate(hd, fd)) != -1) {
  160. ESP_LOGD(TAG, LOG_FMT("cleaning up socket %d"), fd);
  161. httpd_sess_delete(hd, fd);
  162. close(fd);
  163. }
  164. }
  165. /* The main HTTPD thread */
  166. static void _httpd_thread(void *arg)
  167. {
  168. int ret;
  169. struct httpd_data *hd = (struct httpd_data *) arg;
  170. hd->hd_td.status = THREAD_RUNNING;
  171. ESP_LOGD(TAG, LOG_FMT("web server started"));
  172. while (1) {
  173. ret = _httpd_server(hd);
  174. if (ret != ESP_OK) {
  175. break;
  176. }
  177. }
  178. ESP_LOGD(TAG, LOG_FMT("web server exiting"));
  179. _httpd_close_all_sessions(hd);
  180. close(hd->listen_fd);
  181. hd->hd_td.status = THREAD_STOPPED;
  182. httpd_os_thread_delete();
  183. }
  184. static struct httpd_data *__httpd_create(const httpd_config_t *config)
  185. {
  186. /* Allocate memory for httpd instance data */
  187. struct httpd_data *hd = calloc(1, sizeof(struct httpd_data));
  188. if (!hd) {
  189. ESP_LOGE(TAG, LOG_FMT("Failed to allocate memory for HTTP server instance"));
  190. return NULL;
  191. }
  192. hd->hd_calls = calloc(config->max_uri_handlers, sizeof(httpd_uri_t *));
  193. if (!hd->hd_calls) {
  194. ESP_LOGE(TAG, LOG_FMT("Failed to allocate memory for HTTP URI handlers"));
  195. free(hd);
  196. return NULL;
  197. }
  198. hd->hd_sd = calloc(config->max_open_sockets, sizeof(struct sock_db));
  199. if (!hd->hd_sd) {
  200. ESP_LOGE(TAG, LOG_FMT("Failed to allocate memory for HTTP session data"));
  201. free(hd->hd_calls);
  202. free(hd);
  203. return NULL;
  204. }
  205. struct httpd_req_aux *ra = &hd->hd_req_aux;
  206. ra->resp_hdrs = calloc(config->max_resp_headers, sizeof(struct resp_hdr));
  207. if (!ra->resp_hdrs) {
  208. ESP_LOGE(TAG, LOG_FMT("Failed to allocate memory for HTTP response headers"));
  209. free(hd->hd_sd);
  210. free(hd->hd_calls);
  211. free(hd);
  212. return NULL;
  213. }
  214. hd->err_handler_fns = calloc(HTTPD_ERR_CODE_MAX, sizeof(httpd_err_handler_func_t));
  215. if (!hd->err_handler_fns) {
  216. ESP_LOGE(TAG, LOG_FMT("Failed to allocate memory for HTTP error handlers"));
  217. free(ra->resp_hdrs);
  218. free(hd->hd_sd);
  219. free(hd->hd_calls);
  220. free(hd);
  221. return NULL;
  222. }
  223. /* Save the configuration for this instance */
  224. hd->config = *config;
  225. return hd;
  226. }
  227. static void _httpd_delete(struct httpd_data *hd)
  228. {
  229. struct httpd_req_aux *ra = &hd->hd_req_aux;
  230. /* Free memory of httpd instance data */
  231. free(hd->err_handler_fns);
  232. free(ra->resp_hdrs);
  233. free(hd->hd_sd);
  234. /* Free registered URI handlers */
  235. httpd_unregister_all_uri_handlers(hd);
  236. free(hd->hd_calls);
  237. free(hd);
  238. }
  239. esp_err_t __httpd_start(httpd_handle_t *handle, const httpd_config_t *config)
  240. {
  241. if (handle == NULL || config == NULL) {
  242. return ESP_ERR_INVALID_ARG;
  243. }
  244. /* Sanity check about whether LWIP is configured for providing the
  245. * maximum number of open sockets sufficient for the server. Though,
  246. * this check doesn't guarantee that many sockets will actually be
  247. * available at runtime as other processes may use up some sockets.
  248. * Note that server also uses 3 sockets for its internal use :
  249. * 1) listening for new TCP connections
  250. * 2) for sending control messages over UDP
  251. * 3) for receiving control messages over UDP
  252. * So the total number of required sockets is max_open_sockets + 3
  253. */
  254. if (CONFIG_LWIP_MAX_SOCKETS < config->max_open_sockets + 3) {
  255. ESP_LOGE(TAG, "Configuration option max_open_sockets is too large (max allowed %d)\n\t"
  256. "Either decrease this or configure LWIP_MAX_SOCKETS to a larger value",
  257. CONFIG_LWIP_MAX_SOCKETS - 3);
  258. return ESP_ERR_INVALID_ARG;
  259. }
  260. struct httpd_data *hd = __httpd_create(config);
  261. if (hd == NULL) {
  262. /* Failed to allocate memory */
  263. return ESP_ERR_HTTPD_ALLOC_MEM;
  264. }
  265. if (_httpd_server_init(hd) != ESP_OK) {
  266. _httpd_delete(hd);
  267. return ESP_FAIL;
  268. }
  269. httpd_sess_init(hd);
  270. if (__httpd_os_thread_create_static(&hd->hd_td.handle, "httpd",
  271. hd->config.stack_size,
  272. hd->config.task_priority,
  273. _httpd_thread, hd,
  274. hd->config.core_id) != ESP_OK) {
  275. /* Failed to launch task */
  276. _httpd_delete(hd);
  277. return ESP_ERR_HTTPD_TASK;
  278. }
  279. *handle = (httpd_handle_t *)hd;
  280. return ESP_OK;
  281. }