2
0

_esp_httpd_main.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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. int ctrl_fd = cs_create_ctrl_sock(hd->config.ctrl_port);
  68. if (ctrl_fd < 0) {
  69. ESP_LOGE(TAG, LOG_FMT("error in creating ctrl socket (%d)"), errno);
  70. close(fd);
  71. return ESP_FAIL;
  72. }
  73. int msg_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  74. if (msg_fd < 0) {
  75. ESP_LOGE(TAG, LOG_FMT("error in creating msg socket (%d)"), errno);
  76. close(fd);
  77. close(ctrl_fd);
  78. return ESP_FAIL;
  79. }
  80. hd->listen_fd = fd;
  81. hd->ctrl_fd = ctrl_fd;
  82. hd->msg_fd = msg_fd;
  83. return ESP_OK;
  84. }
  85. static void _httpd_process_ctrl_msg(struct httpd_data *hd)
  86. {
  87. struct httpd_ctrl_data msg;
  88. int ret = recv(hd->ctrl_fd, &msg, sizeof(msg), 0);
  89. if (ret <= 0) {
  90. ESP_LOGW(TAG, LOG_FMT("error in recv (%d)"), errno);
  91. return;
  92. }
  93. if (ret != sizeof(msg)) {
  94. ESP_LOGW(TAG, LOG_FMT("incomplete msg"));
  95. return;
  96. }
  97. switch (msg.hc_msg) {
  98. case HTTPD_CTRL_WORK:
  99. if (msg.hc_work) {
  100. ESP_LOGD(TAG, LOG_FMT("work"));
  101. (*msg.hc_work)(msg.hc_work_arg);
  102. }
  103. break;
  104. case HTTPD_CTRL_SHUTDOWN:
  105. ESP_LOGD(TAG, LOG_FMT("shutdown"));
  106. hd->hd_td.status = THREAD_STOPPING;
  107. break;
  108. default:
  109. break;
  110. }
  111. }
  112. static esp_err_t _httpd_accept_conn(struct httpd_data *hd, int listen_fd)
  113. {
  114. /* If no space is available for new session, close the least recently used one */
  115. if (hd->config.lru_purge_enable == true) {
  116. if (!httpd_is_sess_available(hd)) {
  117. /* Queue asynchronous closure of the least recently used session */
  118. return httpd_sess_close_lru(hd);
  119. /* Returning from this allowes the main server thread to process
  120. * the queued asynchronous control message for closing LRU session.
  121. * Since connection request hasn't been addressed yet using accept()
  122. * therefore _httpd_accept_conn() will be called again, but this time
  123. * with space available for one session
  124. */
  125. }
  126. }
  127. struct sockaddr_in addr_from;
  128. socklen_t addr_from_len = sizeof(addr_from);
  129. int new_fd = accept(listen_fd, (struct sockaddr *)&addr_from, &addr_from_len);
  130. if (new_fd < 0) {
  131. ESP_LOGW(TAG, LOG_FMT("error in accept (%d)"), errno);
  132. return ESP_FAIL;
  133. }
  134. ESP_LOGD(TAG, LOG_FMT("newfd = %d"), new_fd);
  135. struct timeval tv;
  136. /* Set recv timeout of this fd as per config */
  137. tv.tv_sec = hd->config.recv_wait_timeout;
  138. tv.tv_usec = 0;
  139. setsockopt(new_fd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof(tv));
  140. /* Set send timeout of this fd as per config */
  141. tv.tv_sec = hd->config.send_wait_timeout;
  142. tv.tv_usec = 0;
  143. setsockopt(new_fd, SOL_SOCKET, SO_SNDTIMEO, (const char*)&tv, sizeof(tv));
  144. if (ESP_OK != httpd_sess_new(hd, new_fd)) {
  145. ESP_LOGW(TAG, LOG_FMT("session creation failed"));
  146. close(new_fd);
  147. return ESP_FAIL;
  148. }
  149. ESP_LOGD(TAG, LOG_FMT("complete"));
  150. return ESP_OK;
  151. }
  152. /* Manage in-coming connection or data requests */
  153. static esp_err_t _httpd_server(struct httpd_data *hd)
  154. {
  155. fd_set read_set;
  156. FD_ZERO(&read_set);
  157. if (hd->config.lru_purge_enable || httpd_is_sess_available(hd)) {
  158. /* Only listen for new connections if server has capacity to
  159. * handle more (or when LRU purge is enabled, in which case
  160. * older connections will be closed) */
  161. FD_SET(hd->listen_fd, &read_set);
  162. }
  163. FD_SET(hd->ctrl_fd, &read_set);
  164. int tmp_max_fd;
  165. httpd_sess_set_descriptors(hd, &read_set, &tmp_max_fd);
  166. int maxfd = MAX(hd->listen_fd, tmp_max_fd);
  167. tmp_max_fd = maxfd;
  168. maxfd = MAX(hd->ctrl_fd, tmp_max_fd);
  169. ESP_LOGD(TAG, LOG_FMT("doing select maxfd+1 = %d"), maxfd + 1);
  170. int active_cnt = select(maxfd + 1, &read_set, NULL, NULL, NULL);
  171. if (active_cnt < 0) {
  172. ESP_LOGE(TAG, LOG_FMT("error in select (%d)"), errno);
  173. httpd_sess_delete_invalid(hd);
  174. return ESP_OK;
  175. }
  176. /* Case0: Do we have a control message? */
  177. if (FD_ISSET(hd->ctrl_fd, &read_set)) {
  178. ESP_LOGD(TAG, LOG_FMT("processing ctrl message"));
  179. _httpd_process_ctrl_msg(hd);
  180. if (hd->hd_td.status == THREAD_STOPPING) {
  181. ESP_LOGD(TAG, LOG_FMT("stopping thread"));
  182. return ESP_FAIL;
  183. }
  184. }
  185. /* Case1: Do we have any activity on the current data
  186. * sessions? */
  187. int fd = -1;
  188. while ((fd = httpd_sess_iterate(hd, fd)) != -1) {
  189. if (FD_ISSET(fd, &read_set) || (httpd_sess_pending(hd, fd))) {
  190. ESP_LOGD(TAG, LOG_FMT("processing socket %d"), fd);
  191. if (httpd_sess_process(hd, fd) != ESP_OK) {
  192. ESP_LOGD(TAG, LOG_FMT("closing socket %d"), fd);
  193. close(fd);
  194. /* Delete session and update fd to that
  195. * preceding the one being deleted */
  196. fd = httpd_sess_delete(hd, fd);
  197. }
  198. }
  199. }
  200. /* Case2: Do we have any incoming connection requests to
  201. * process? */
  202. if (FD_ISSET(hd->listen_fd, &read_set)) {
  203. ESP_LOGD(TAG, LOG_FMT("processing listen socket %d"), hd->listen_fd);
  204. if (_httpd_accept_conn(hd, hd->listen_fd) != ESP_OK) {
  205. ESP_LOGW(TAG, LOG_FMT("error accepting new connection"));
  206. }
  207. }
  208. return ESP_OK;
  209. }
  210. static void _httpd_close_all_sessions(struct httpd_data *hd)
  211. {
  212. int fd = -1;
  213. while ((fd = httpd_sess_iterate(hd, fd)) != -1) {
  214. ESP_LOGD(TAG, LOG_FMT("cleaning up socket %d"), fd);
  215. httpd_sess_delete(hd, fd);
  216. close(fd);
  217. }
  218. }
  219. /* The main HTTPD thread */
  220. static void _httpd_thread(void *arg)
  221. {
  222. int ret;
  223. struct httpd_data *hd = (struct httpd_data *) arg;
  224. hd->hd_td.status = THREAD_RUNNING;
  225. ESP_LOGD(TAG, LOG_FMT("web server started"));
  226. while (1) {
  227. ret = _httpd_server(hd);
  228. if (ret != ESP_OK) {
  229. break;
  230. }
  231. }
  232. ESP_LOGD(TAG, LOG_FMT("web server exiting"));
  233. close(hd->msg_fd);
  234. cs_free_ctrl_sock(hd->ctrl_fd);
  235. _httpd_close_all_sessions(hd);
  236. close(hd->listen_fd);
  237. hd->hd_td.status = THREAD_STOPPED;
  238. httpd_os_thread_delete();
  239. }
  240. static struct httpd_data *__httpd_create(const httpd_config_t *config)
  241. {
  242. /* Allocate memory for httpd instance data */
  243. struct httpd_data *hd = calloc(1, sizeof(struct httpd_data));
  244. if (!hd) {
  245. ESP_LOGE(TAG, LOG_FMT("Failed to allocate memory for HTTP server instance"));
  246. return NULL;
  247. }
  248. hd->hd_calls = calloc(config->max_uri_handlers, sizeof(httpd_uri_t *));
  249. if (!hd->hd_calls) {
  250. ESP_LOGE(TAG, LOG_FMT("Failed to allocate memory for HTTP URI handlers"));
  251. free(hd);
  252. return NULL;
  253. }
  254. hd->hd_sd = calloc(config->max_open_sockets, sizeof(struct sock_db));
  255. if (!hd->hd_sd) {
  256. ESP_LOGE(TAG, LOG_FMT("Failed to allocate memory for HTTP session data"));
  257. free(hd->hd_calls);
  258. free(hd);
  259. return NULL;
  260. }
  261. struct httpd_req_aux *ra = &hd->hd_req_aux;
  262. ra->resp_hdrs = calloc(config->max_resp_headers, sizeof(struct resp_hdr));
  263. if (!ra->resp_hdrs) {
  264. ESP_LOGE(TAG, LOG_FMT("Failed to allocate memory for HTTP response headers"));
  265. free(hd->hd_sd);
  266. free(hd->hd_calls);
  267. free(hd);
  268. return NULL;
  269. }
  270. hd->err_handler_fns = calloc(HTTPD_ERR_CODE_MAX, sizeof(httpd_err_handler_func_t));
  271. if (!hd->err_handler_fns) {
  272. ESP_LOGE(TAG, LOG_FMT("Failed to allocate memory for HTTP error handlers"));
  273. free(ra->resp_hdrs);
  274. free(hd->hd_sd);
  275. free(hd->hd_calls);
  276. free(hd);
  277. return NULL;
  278. }
  279. /* Save the configuration for this instance */
  280. hd->config = *config;
  281. return hd;
  282. }
  283. static void _httpd_delete(struct httpd_data *hd)
  284. {
  285. struct httpd_req_aux *ra = &hd->hd_req_aux;
  286. /* Free memory of httpd instance data */
  287. free(hd->err_handler_fns);
  288. free(ra->resp_hdrs);
  289. free(hd->hd_sd);
  290. /* Free registered URI handlers */
  291. httpd_unregister_all_uri_handlers(hd);
  292. free(hd->hd_calls);
  293. free(hd);
  294. }
  295. esp_err_t __httpd_start(httpd_handle_t *handle, const httpd_config_t *config)
  296. {
  297. if (handle == NULL || config == NULL) {
  298. return ESP_ERR_INVALID_ARG;
  299. }
  300. /* Sanity check about whether LWIP is configured for providing the
  301. * maximum number of open sockets sufficient for the server. Though,
  302. * this check doesn't guarantee that many sockets will actually be
  303. * available at runtime as other processes may use up some sockets.
  304. * Note that server also uses 3 sockets for its internal use :
  305. * 1) listening for new TCP connections
  306. * 2) for sending control messages over UDP
  307. * 3) for receiving control messages over UDP
  308. * So the total number of required sockets is max_open_sockets + 3
  309. */
  310. if (CONFIG_LWIP_MAX_SOCKETS < config->max_open_sockets + 3) {
  311. ESP_LOGE(TAG, "Configuration option max_open_sockets is too large (max allowed %d)\n\t"
  312. "Either decrease this or configure LWIP_MAX_SOCKETS to a larger value",
  313. CONFIG_LWIP_MAX_SOCKETS - 3);
  314. return ESP_ERR_INVALID_ARG;
  315. }
  316. struct httpd_data *hd = __httpd_create(config);
  317. if (hd == NULL) {
  318. /* Failed to allocate memory */
  319. return ESP_ERR_HTTPD_ALLOC_MEM;
  320. }
  321. if (_httpd_server_init(hd) != ESP_OK) {
  322. _httpd_delete(hd);
  323. return ESP_FAIL;
  324. }
  325. httpd_sess_init(hd);
  326. if (__httpd_os_thread_create_static(&hd->hd_td.handle, "httpd",
  327. hd->config.stack_size,
  328. hd->config.task_priority,
  329. _httpd_thread, hd,
  330. hd->config.core_id) != ESP_OK) {
  331. /* Failed to launch task */
  332. _httpd_delete(hd);
  333. return ESP_ERR_HTTPD_TASK;
  334. }
  335. *handle = (httpd_handle_t *)hd;
  336. return ESP_OK;
  337. }