esp_http_server.h 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450
  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. #ifndef _ESP_HTTP_SERVER_H_
  15. #define _ESP_HTTP_SERVER_H_
  16. #include <stdio.h>
  17. #include <string.h>
  18. #include <freertos/FreeRTOS.h>
  19. #include <freertos/task.h>
  20. #include <http_parser.h>
  21. #include <sdkconfig.h>
  22. #include <esp_err.h>
  23. #ifdef __cplusplus
  24. extern "C" {
  25. #endif
  26. /*
  27. note: esp_https_server.h includes a customized copy of this
  28. initializer that should be kept in sync
  29. */
  30. #define HTTPD_DEFAULT_CONFIG() { \
  31. .task_priority = tskIDLE_PRIORITY+5, \
  32. .stack_size = 4096, \
  33. .server_port = 80, \
  34. .ctrl_port = 32768, \
  35. .max_open_sockets = 7, \
  36. .max_uri_handlers = 8, \
  37. .max_resp_headers = 8, \
  38. .backlog_conn = 5, \
  39. .lru_purge_enable = false, \
  40. .recv_wait_timeout = 5, \
  41. .send_wait_timeout = 5, \
  42. .global_user_ctx = NULL, \
  43. .global_user_ctx_free_fn = NULL, \
  44. .global_transport_ctx = NULL, \
  45. .global_transport_ctx_free_fn = NULL, \
  46. .open_fn = NULL, \
  47. .close_fn = NULL, \
  48. .uri_match_fn = NULL \
  49. }
  50. #define ESP_ERR_HTTPD_BASE (0x8000) /*!< Starting number of HTTPD error codes */
  51. #define ESP_ERR_HTTPD_HANDLERS_FULL (ESP_ERR_HTTPD_BASE + 1) /*!< All slots for registering URI handlers have been consumed */
  52. #define ESP_ERR_HTTPD_HANDLER_EXISTS (ESP_ERR_HTTPD_BASE + 2) /*!< URI handler with same method and target URI already registered */
  53. #define ESP_ERR_HTTPD_INVALID_REQ (ESP_ERR_HTTPD_BASE + 3) /*!< Invalid request pointer */
  54. #define ESP_ERR_HTTPD_RESULT_TRUNC (ESP_ERR_HTTPD_BASE + 4) /*!< Result string truncated */
  55. #define ESP_ERR_HTTPD_RESP_HDR (ESP_ERR_HTTPD_BASE + 5) /*!< Response header field larger than supported */
  56. #define ESP_ERR_HTTPD_RESP_SEND (ESP_ERR_HTTPD_BASE + 6) /*!< Error occured while sending response packet */
  57. #define ESP_ERR_HTTPD_ALLOC_MEM (ESP_ERR_HTTPD_BASE + 7) /*!< Failed to dynamically allocate memory for resource */
  58. #define ESP_ERR_HTTPD_TASK (ESP_ERR_HTTPD_BASE + 8) /*!< Failed to launch server task/thread */
  59. /* Symbol to be used as length parameter in httpd_resp_send APIs
  60. * for setting buffer length to string length */
  61. #define HTTPD_RESP_USE_STRLEN -1
  62. /* ************** Group: Initialization ************** */
  63. /** @name Initialization
  64. * APIs related to the Initialization of the web server
  65. * @{
  66. */
  67. /**
  68. * @brief HTTP Server Instance Handle
  69. *
  70. * Every instance of the server will have a unique handle.
  71. */
  72. typedef void* httpd_handle_t;
  73. /**
  74. * @brief HTTP Method Type wrapper over "enum http_method"
  75. * available in "http_parser" library
  76. */
  77. typedef enum http_method httpd_method_t;
  78. /**
  79. * @brief Prototype for freeing context data (if any)
  80. * @param[in] ctx object to free
  81. */
  82. typedef void (*httpd_free_ctx_fn_t)(void *ctx);
  83. /**
  84. * @brief Function prototype for opening a session.
  85. *
  86. * Called immediately after the socket was opened to set up the send/recv functions and
  87. * other parameters of the socket.
  88. *
  89. * @param[in] hd server instance
  90. * @param[in] sockfd session socket file descriptor
  91. * @return status
  92. */
  93. typedef esp_err_t (*httpd_open_func_t)(httpd_handle_t hd, int sockfd);
  94. /**
  95. * @brief Function prototype for closing a session.
  96. *
  97. * @note It's possible that the socket descriptor is invalid at this point, the function
  98. * is called for all terminated sessions. Ensure proper handling of return codes.
  99. *
  100. * @param[in] hd server instance
  101. * @param[in] sockfd session socket file descriptor
  102. */
  103. typedef void (*httpd_close_func_t)(httpd_handle_t hd, int sockfd);
  104. /**
  105. * @brief Function prototype for URI matching.
  106. *
  107. * @param[in] reference_uri URI/template with respect to which the other URI is matched
  108. * @param[in] uri_to_match URI/template being matched to the reference URI/template
  109. * @param[in] match_upto For specifying the actual length of `uri_to_match` up to
  110. * which the matching algorithm is to be applied (The maximum
  111. * value is `strlen(uri_to_match)`, independent of the length
  112. * of `reference_uri`)
  113. * @return true on match
  114. */
  115. typedef bool (*httpd_uri_match_func_t)(const char *reference_uri,
  116. const char *uri_to_match,
  117. size_t match_upto);
  118. /**
  119. * @brief HTTP Server Configuration Structure
  120. *
  121. * @note Use HTTPD_DEFAULT_CONFIG() to initialize the configuration
  122. * to a default value and then modify only those fields that are
  123. * specifically determined by the use case.
  124. */
  125. typedef struct httpd_config {
  126. unsigned task_priority; /*!< Priority of FreeRTOS task which runs the server */
  127. size_t stack_size; /*!< The maximum stack size allowed for the server task */
  128. /**
  129. * TCP Port number for receiving and transmitting HTTP traffic
  130. */
  131. uint16_t server_port;
  132. /**
  133. * UDP Port number for asynchronously exchanging control signals
  134. * between various components of the server
  135. */
  136. uint16_t ctrl_port;
  137. uint16_t max_open_sockets; /*!< Max number of sockets/clients connected at any time*/
  138. uint16_t max_uri_handlers; /*!< Maximum allowed uri handlers */
  139. uint16_t max_resp_headers; /*!< Maximum allowed additional headers in HTTP response */
  140. uint16_t backlog_conn; /*!< Number of backlog connections */
  141. bool lru_purge_enable; /*!< Purge "Least Recently Used" connection */
  142. uint16_t recv_wait_timeout; /*!< Timeout for recv function (in seconds)*/
  143. uint16_t send_wait_timeout; /*!< Timeout for send function (in seconds)*/
  144. /**
  145. * Global user context.
  146. *
  147. * This field can be used to store arbitrary user data within the server context.
  148. * The value can be retrieved using the server handle, available e.g. in the httpd_req_t struct.
  149. *
  150. * When shutting down, the server frees up the user context by
  151. * calling free() on the global_user_ctx field. If you wish to use a custom
  152. * function for freeing the global user context, please specify that here.
  153. */
  154. void * global_user_ctx;
  155. /**
  156. * Free function for global user context
  157. */
  158. httpd_free_ctx_fn_t global_user_ctx_free_fn;
  159. /**
  160. * Global transport context.
  161. *
  162. * Similar to global_user_ctx, but used for session encoding or encryption (e.g. to hold the SSL context).
  163. * It will be freed using free(), unless global_transport_ctx_free_fn is specified.
  164. */
  165. void * global_transport_ctx;
  166. /**
  167. * Free function for global transport context
  168. */
  169. httpd_free_ctx_fn_t global_transport_ctx_free_fn;
  170. /**
  171. * Custom session opening callback.
  172. *
  173. * Called on a new session socket just after accept(), but before reading any data.
  174. *
  175. * This is an opportunity to set up e.g. SSL encryption using global_transport_ctx
  176. * and the send/recv/pending session overrides.
  177. *
  178. * If a context needs to be maintained between these functions, store it in the session using
  179. * httpd_sess_set_transport_ctx() and retrieve it later with httpd_sess_get_transport_ctx()
  180. */
  181. httpd_open_func_t open_fn;
  182. /**
  183. * Custom session closing callback.
  184. *
  185. * Called when a session is deleted, before freeing user and transport contexts and before
  186. * closing the socket. This is a place for custom de-init code common to all sockets.
  187. *
  188. * Set the user or transport context to NULL if it was freed here, so the server does not
  189. * try to free it again.
  190. *
  191. * This function is run for all terminated sessions, including sessions where the socket
  192. * was closed by the network stack - that is, the file descriptor may not be valid anymore.
  193. */
  194. httpd_close_func_t close_fn;
  195. /**
  196. * URI matcher function.
  197. *
  198. * Called when searching for a matching URI:
  199. * 1) whose request handler is to be executed right
  200. * after an HTTP request is successfully parsed
  201. * 2) in order to prevent duplication while registering
  202. * a new URI handler using `httpd_register_uri_handler()`
  203. *
  204. * Available options are:
  205. * 1) NULL : Internally do basic matching using `strncmp()`
  206. * 2) `httpd_uri_match_wildcard()` : URI wildcard matcher
  207. *
  208. * Users can implement their own matching functions (See description
  209. * of the `httpd_uri_match_func_t` function prototype)
  210. */
  211. httpd_uri_match_func_t uri_match_fn;
  212. } httpd_config_t;
  213. /**
  214. * @brief Starts the web server
  215. *
  216. * Create an instance of HTTP server and allocate memory/resources for it
  217. * depending upon the specified configuration.
  218. *
  219. * Example usage:
  220. * @code{c}
  221. *
  222. * //Function for starting the webserver
  223. * httpd_handle_t start_webserver(void)
  224. * {
  225. * // Generate default configuration
  226. * httpd_config_t config = HTTPD_DEFAULT_CONFIG();
  227. *
  228. * // Empty handle to http_server
  229. * httpd_handle_t server = NULL;
  230. *
  231. * // Start the httpd server
  232. * if (httpd_start(&server, &config) == ESP_OK) {
  233. * // Register URI handlers
  234. * httpd_register_uri_handler(server, &uri_get);
  235. * httpd_register_uri_handler(server, &uri_post);
  236. * }
  237. * // If server failed to start, handle will be NULL
  238. * return server;
  239. * }
  240. *
  241. * @endcode
  242. *
  243. * @param[in] config Configuration for new instance of the server
  244. * @param[out] handle Handle to newly created instance of the server. NULL on error
  245. * @return
  246. * - ESP_OK : Instance created successfully
  247. * - ESP_ERR_INVALID_ARG : Null argument(s)
  248. * - ESP_ERR_HTTPD_ALLOC_MEM : Failed to allocate memory for instance
  249. * - ESP_ERR_HTTPD_TASK : Failed to launch server task
  250. */
  251. esp_err_t httpd_start(httpd_handle_t *handle, const httpd_config_t *config);
  252. /**
  253. * @brief Stops the web server
  254. *
  255. * Deallocates memory/resources used by an HTTP server instance and
  256. * deletes it. Once deleted the handle can no longer be used for accessing
  257. * the instance.
  258. *
  259. * Example usage:
  260. * @code{c}
  261. *
  262. * // Function for stopping the webserver
  263. * void stop_webserver(httpd_handle_t server)
  264. * {
  265. * // Ensure handle is non NULL
  266. * if (server != NULL) {
  267. * // Stop the httpd server
  268. * httpd_stop(server);
  269. * }
  270. * }
  271. *
  272. * @endcode
  273. *
  274. * @param[in] handle Handle to server returned by httpd_start
  275. * @return
  276. * - ESP_OK : Server stopped successfully
  277. * - ESP_ERR_INVALID_ARG : Handle argument is Null
  278. */
  279. esp_err_t httpd_stop(httpd_handle_t handle);
  280. /** End of Group Initialization
  281. * @}
  282. */
  283. /* ************** Group: URI Handlers ************** */
  284. /** @name URI Handlers
  285. * APIs related to the URI handlers
  286. * @{
  287. */
  288. /* Max supported HTTP request header length */
  289. #define HTTPD_MAX_REQ_HDR_LEN CONFIG_HTTPD_MAX_REQ_HDR_LEN
  290. /* Max supported HTTP request URI length */
  291. #define HTTPD_MAX_URI_LEN CONFIG_HTTPD_MAX_URI_LEN
  292. /**
  293. * @brief HTTP Request Data Structure
  294. */
  295. typedef struct httpd_req {
  296. httpd_handle_t handle; /*!< Handle to server instance */
  297. int method; /*!< The type of HTTP request, -1 if unsupported method */
  298. const char uri[HTTPD_MAX_URI_LEN + 1]; /*!< The URI of this request (1 byte extra for null termination) */
  299. size_t content_len; /*!< Length of the request body */
  300. void *aux; /*!< Internally used members */
  301. /**
  302. * User context pointer passed during URI registration.
  303. */
  304. void *user_ctx;
  305. /**
  306. * Session Context Pointer
  307. *
  308. * A session context. Contexts are maintained across 'sessions' for a
  309. * given open TCP connection. One session could have multiple request
  310. * responses. The web server will ensure that the context persists
  311. * across all these request and responses.
  312. *
  313. * By default, this is NULL. URI Handlers can set this to any meaningful
  314. * value.
  315. *
  316. * If the underlying socket gets closed, and this pointer is non-NULL,
  317. * the web server will free up the context by calling free(), unless
  318. * free_ctx function is set.
  319. */
  320. void *sess_ctx;
  321. /**
  322. * Pointer to free context hook
  323. *
  324. * Function to free session context
  325. *
  326. * If the web server's socket closes, it frees up the session context by
  327. * calling free() on the sess_ctx member. If you wish to use a custom
  328. * function for freeing the session context, please specify that here.
  329. */
  330. httpd_free_ctx_fn_t free_ctx;
  331. /**
  332. * Flag indicating if Session Context changes should be ignored
  333. *
  334. * By default, if you change the sess_ctx in some URI handler, the http server
  335. * will internally free the earlier context (if non NULL), after the URI handler
  336. * returns. If you want to manage the allocation/reallocation/freeing of
  337. * sess_ctx yourself, set this flag to true, so that the server will not
  338. * perform any checks on it. The context will be cleared by the server
  339. * (by calling free_ctx or free()) only if the socket gets closed.
  340. */
  341. bool ignore_sess_ctx_changes;
  342. } httpd_req_t;
  343. /**
  344. * @brief Structure for URI handler
  345. */
  346. typedef struct httpd_uri {
  347. const char *uri; /*!< The URI to handle */
  348. httpd_method_t method; /*!< Method supported by the URI */
  349. /**
  350. * Handler to call for supported request method. This must
  351. * return ESP_OK, or else the underlying socket will be closed.
  352. */
  353. esp_err_t (*handler)(httpd_req_t *r);
  354. /**
  355. * Pointer to user context data which will be available to handler
  356. */
  357. void *user_ctx;
  358. } httpd_uri_t;
  359. /**
  360. * @brief Registers a URI handler
  361. *
  362. * @note URI handlers can be registered in real time as long as the
  363. * server handle is valid.
  364. *
  365. * Example usage:
  366. * @code{c}
  367. *
  368. * esp_err_t my_uri_handler(httpd_req_t* req)
  369. * {
  370. * // Recv , Process and Send
  371. * ....
  372. * ....
  373. * ....
  374. *
  375. * // Fail condition
  376. * if (....) {
  377. * // Return fail to close session //
  378. * return ESP_FAIL;
  379. * }
  380. *
  381. * // On success
  382. * return ESP_OK;
  383. * }
  384. *
  385. * // URI handler structure
  386. * httpd_uri_t my_uri {
  387. * .uri = "/my_uri/path/xyz",
  388. * .method = HTTPD_GET,
  389. * .handler = my_uri_handler,
  390. * .user_ctx = NULL
  391. * };
  392. *
  393. * // Register handler
  394. * if (httpd_register_uri_handler(server_handle, &my_uri) != ESP_OK) {
  395. * // If failed to register handler
  396. * ....
  397. * }
  398. *
  399. * @endcode
  400. *
  401. * @param[in] handle handle to HTTPD server instance
  402. * @param[in] uri_handler pointer to handler that needs to be registered
  403. *
  404. * @return
  405. * - ESP_OK : On successfully registering the handler
  406. * - ESP_ERR_INVALID_ARG : Null arguments
  407. * - ESP_ERR_HTTPD_HANDLERS_FULL : If no slots left for new handler
  408. * - ESP_ERR_HTTPD_HANDLER_EXISTS : If handler with same URI and
  409. * method is already registered
  410. */
  411. esp_err_t httpd_register_uri_handler(httpd_handle_t handle,
  412. const httpd_uri_t *uri_handler);
  413. /**
  414. * @brief Unregister a URI handler
  415. *
  416. * @param[in] handle handle to HTTPD server instance
  417. * @param[in] uri URI string
  418. * @param[in] method HTTP method
  419. *
  420. * @return
  421. * - ESP_OK : On successfully deregistering the handler
  422. * - ESP_ERR_INVALID_ARG : Null arguments
  423. * - ESP_ERR_NOT_FOUND : Handler with specified URI and method not found
  424. */
  425. esp_err_t httpd_unregister_uri_handler(httpd_handle_t handle,
  426. const char *uri, httpd_method_t method);
  427. /**
  428. * @brief Unregister all URI handlers with the specified uri string
  429. *
  430. * @param[in] handle handle to HTTPD server instance
  431. * @param[in] uri uri string specifying all handlers that need
  432. * to be deregisterd
  433. *
  434. * @return
  435. * - ESP_OK : On successfully deregistering all such handlers
  436. * - ESP_ERR_INVALID_ARG : Null arguments
  437. * - ESP_ERR_NOT_FOUND : No handler registered with specified uri string
  438. */
  439. esp_err_t httpd_unregister_uri(httpd_handle_t handle, const char* uri);
  440. /** End of URI Handlers
  441. * @}
  442. */
  443. /* ************** Group: HTTP Error ************** */
  444. /** @name HTTP Error
  445. * Prototype for HTTP errors and error handling functions
  446. * @{
  447. */
  448. /**
  449. * @brief Error codes sent as HTTP response in case of errors
  450. * encountered during processing of an HTTP request
  451. */
  452. typedef enum {
  453. /* For any unexpected errors during parsing, like unexpected
  454. * state transitions, or unhandled errors.
  455. */
  456. HTTPD_500_INTERNAL_SERVER_ERROR = 0,
  457. /* For methods not supported by http_parser. Presently
  458. * http_parser halts parsing when such methods are
  459. * encountered and so the server responds with 400 Bad
  460. * Request error instead.
  461. */
  462. HTTPD_501_METHOD_NOT_IMPLEMENTED,
  463. /* When HTTP version is not 1.1 */
  464. HTTPD_505_VERSION_NOT_SUPPORTED,
  465. /* Returned when http_parser halts parsing due to incorrect
  466. * syntax of request, unsupported method in request URI or
  467. * due to chunked encoding / upgrade field present in headers
  468. */
  469. HTTPD_400_BAD_REQUEST,
  470. /* When requested URI is not found */
  471. HTTPD_404_NOT_FOUND,
  472. /* When URI found, but method has no handler registered */
  473. HTTPD_405_METHOD_NOT_ALLOWED,
  474. /* Intended for recv timeout. Presently it's being sent
  475. * for other recv errors as well. Client should expect the
  476. * server to immediately close the connection after
  477. * responding with this.
  478. */
  479. HTTPD_408_REQ_TIMEOUT,
  480. /* Intended for responding to chunked encoding, which is
  481. * not supported currently. Though unhandled http_parser
  482. * callback for chunked request returns "400 Bad Request"
  483. */
  484. HTTPD_411_LENGTH_REQUIRED,
  485. /* URI length greater than CONFIG_HTTPD_MAX_URI_LEN */
  486. HTTPD_414_URI_TOO_LONG,
  487. /* Headers section larger than CONFIG_HTTPD_MAX_REQ_HDR_LEN */
  488. HTTPD_431_REQ_HDR_FIELDS_TOO_LARGE,
  489. /* Used internally for retrieving the total count of errors */
  490. HTTPD_ERR_CODE_MAX
  491. } httpd_err_code_t;
  492. /**
  493. * @brief Function prototype for HTTP error handling.
  494. *
  495. * This function is executed upon HTTP errors generated during
  496. * internal processing of an HTTP request. This is used to override
  497. * the default behavior on error, which is to send HTTP error response
  498. * and close the underlying socket.
  499. *
  500. * @note
  501. * - If implemented, the server will not automatically send out HTTP
  502. * error response codes, therefore, httpd_resp_send_err() must be
  503. * invoked inside this function if user wishes to generate HTTP
  504. * error responses.
  505. * - When invoked, the validity of `uri`, `method`, `content_len`
  506. * and `user_ctx` fields of the httpd_req_t parameter is not
  507. * guaranteed as the HTTP request may be partially received/parsed.
  508. * - The function must return ESP_OK if underlying socket needs to
  509. * be kept open. Any other value will ensure that the socket is
  510. * closed. The return value is ignored when error is of type
  511. * `HTTPD_500_INTERNAL_SERVER_ERROR` and the socket closed anyway.
  512. *
  513. * @param[in] req HTTP request for which the error needs to be handled
  514. * @param[in] error Error type
  515. *
  516. * @return
  517. * - ESP_OK : error handled successful
  518. * - ESP_FAIL : failure indicates that the underlying socket needs to be closed
  519. */
  520. typedef esp_err_t (*httpd_err_handler_func_t)(httpd_req_t *req,
  521. httpd_err_code_t error);
  522. /**
  523. * @brief Function for registering HTTP error handlers
  524. *
  525. * This function maps a handler function to any supported error code
  526. * given by `httpd_err_code_t`. See prototype `httpd_err_handler_func_t`
  527. * above for details.
  528. *
  529. * @param[in] handle HTTP server handle
  530. * @param[in] error Error type
  531. * @param[in] handler_fn User implemented handler function
  532. * (Pass NULL to unset any previously set handler)
  533. *
  534. * @return
  535. * - ESP_OK : handler registered successfully
  536. * - ESP_ERR_INVALID_ARG : invalid error code or server handle
  537. */
  538. esp_err_t httpd_register_err_handler(httpd_handle_t handle,
  539. httpd_err_code_t error,
  540. httpd_err_handler_func_t handler_fn);
  541. /** End of HTTP Error
  542. * @}
  543. */
  544. /* ************** Group: TX/RX ************** */
  545. /** @name TX / RX
  546. * Prototype for HTTPDs low-level send/recv functions
  547. * @{
  548. */
  549. #define HTTPD_SOCK_ERR_FAIL -1
  550. #define HTTPD_SOCK_ERR_INVALID -2
  551. #define HTTPD_SOCK_ERR_TIMEOUT -3
  552. /**
  553. * @brief Prototype for HTTPDs low-level send function
  554. *
  555. * @note User specified send function must handle errors internally,
  556. * depending upon the set value of errno, and return specific
  557. * HTTPD_SOCK_ERR_ codes, which will eventually be conveyed as
  558. * return value of httpd_send() function
  559. *
  560. * @param[in] hd server instance
  561. * @param[in] sockfd session socket file descriptor
  562. * @param[in] buf buffer with bytes to send
  563. * @param[in] buf_len data size
  564. * @param[in] flags flags for the send() function
  565. * @return
  566. * - Bytes : The number of bytes sent successfully
  567. * - HTTPD_SOCK_ERR_INVALID : Invalid arguments
  568. * - HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket send()
  569. * - HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket send()
  570. */
  571. typedef int (*httpd_send_func_t)(httpd_handle_t hd, int sockfd, const char *buf, size_t buf_len, int flags);
  572. /**
  573. * @brief Prototype for HTTPDs low-level recv function
  574. *
  575. * @note User specified recv function must handle errors internally,
  576. * depending upon the set value of errno, and return specific
  577. * HTTPD_SOCK_ERR_ codes, which will eventually be conveyed as
  578. * return value of httpd_req_recv() function
  579. *
  580. * @param[in] hd server instance
  581. * @param[in] sockfd session socket file descriptor
  582. * @param[in] buf buffer with bytes to send
  583. * @param[in] buf_len data size
  584. * @param[in] flags flags for the send() function
  585. * @return
  586. * - Bytes : The number of bytes received successfully
  587. * - 0 : Buffer length parameter is zero / connection closed by peer
  588. * - HTTPD_SOCK_ERR_INVALID : Invalid arguments
  589. * - HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket recv()
  590. * - HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket recv()
  591. */
  592. typedef int (*httpd_recv_func_t)(httpd_handle_t hd, int sockfd, char *buf, size_t buf_len, int flags);
  593. /**
  594. * @brief Prototype for HTTPDs low-level "get pending bytes" function
  595. *
  596. * @note User specified pending function must handle errors internally,
  597. * depending upon the set value of errno, and return specific
  598. * HTTPD_SOCK_ERR_ codes, which will be handled accordingly in
  599. * the server task.
  600. *
  601. * @param[in] hd server instance
  602. * @param[in] sockfd session socket file descriptor
  603. * @return
  604. * - Bytes : The number of bytes waiting to be received
  605. * - HTTPD_SOCK_ERR_INVALID : Invalid arguments
  606. * - HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket pending()
  607. * - HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket pending()
  608. */
  609. typedef int (*httpd_pending_func_t)(httpd_handle_t hd, int sockfd);
  610. /** End of TX / RX
  611. * @}
  612. */
  613. /* ************** Group: Request/Response ************** */
  614. /** @name Request / Response
  615. * APIs related to the data send/receive by URI handlers.
  616. * These APIs are supposed to be called only from the context of
  617. * a URI handler where httpd_req_t* request pointer is valid.
  618. * @{
  619. */
  620. /**
  621. * @brief Override web server's receive function (by session FD)
  622. *
  623. * This function overrides the web server's receive function. This same function is
  624. * used to read HTTP request packets.
  625. *
  626. * @note This API is supposed to be called either from the context of
  627. * - an http session APIs where sockfd is a valid parameter
  628. * - a URI handler where sockfd is obtained using httpd_req_to_sockfd()
  629. *
  630. * @param[in] hd HTTPD instance handle
  631. * @param[in] sockfd Session socket FD
  632. * @param[in] recv_func The receive function to be set for this session
  633. *
  634. * @return
  635. * - ESP_OK : On successfully registering override
  636. * - ESP_ERR_INVALID_ARG : Null arguments
  637. */
  638. esp_err_t httpd_sess_set_recv_override(httpd_handle_t hd, int sockfd, httpd_recv_func_t recv_func);
  639. /**
  640. * @brief Override web server's send function (by session FD)
  641. *
  642. * This function overrides the web server's send function. This same function is
  643. * used to send out any response to any HTTP request.
  644. *
  645. * @note This API is supposed to be called either from the context of
  646. * - an http session APIs where sockfd is a valid parameter
  647. * - a URI handler where sockfd is obtained using httpd_req_to_sockfd()
  648. *
  649. * @param[in] hd HTTPD instance handle
  650. * @param[in] sockfd Session socket FD
  651. * @param[in] send_func The send function to be set for this session
  652. *
  653. * @return
  654. * - ESP_OK : On successfully registering override
  655. * - ESP_ERR_INVALID_ARG : Null arguments
  656. */
  657. esp_err_t httpd_sess_set_send_override(httpd_handle_t hd, int sockfd, httpd_send_func_t send_func);
  658. /**
  659. * @brief Override web server's pending function (by session FD)
  660. *
  661. * This function overrides the web server's pending function. This function is
  662. * used to test for pending bytes in a socket.
  663. *
  664. * @note This API is supposed to be called either from the context of
  665. * - an http session APIs where sockfd is a valid parameter
  666. * - a URI handler where sockfd is obtained using httpd_req_to_sockfd()
  667. *
  668. * @param[in] hd HTTPD instance handle
  669. * @param[in] sockfd Session socket FD
  670. * @param[in] pending_func The receive function to be set for this session
  671. *
  672. * @return
  673. * - ESP_OK : On successfully registering override
  674. * - ESP_ERR_INVALID_ARG : Null arguments
  675. */
  676. esp_err_t httpd_sess_set_pending_override(httpd_handle_t hd, int sockfd, httpd_pending_func_t pending_func);
  677. /**
  678. * @brief Get the Socket Descriptor from the HTTP request
  679. *
  680. * This API will return the socket descriptor of the session for
  681. * which URI handler was executed on reception of HTTP request.
  682. * This is useful when user wants to call functions that require
  683. * session socket fd, from within a URI handler, ie. :
  684. * httpd_sess_get_ctx(),
  685. * httpd_sess_trigger_close(),
  686. * httpd_sess_update_lru_counter().
  687. *
  688. * @note This API is supposed to be called only from the context of
  689. * a URI handler where httpd_req_t* request pointer is valid.
  690. *
  691. * @param[in] r The request whose socket descriptor should be found
  692. *
  693. * @return
  694. * - Socket descriptor : The socket descriptor for this request
  695. * - -1 : Invalid/NULL request pointer
  696. */
  697. int httpd_req_to_sockfd(httpd_req_t *r);
  698. /**
  699. * @brief API to read content data from the HTTP request
  700. *
  701. * This API will read HTTP content data from the HTTP request into
  702. * provided buffer. Use content_len provided in httpd_req_t structure
  703. * to know the length of data to be fetched. If content_len is too
  704. * large for the buffer then user may have to make multiple calls to
  705. * this function, each time fetching 'buf_len' number of bytes,
  706. * while the pointer to content data is incremented internally by
  707. * the same number.
  708. *
  709. * @note
  710. * - This API is supposed to be called only from the context of
  711. * a URI handler where httpd_req_t* request pointer is valid.
  712. * - If an error is returned, the URI handler must further return an error.
  713. * This will ensure that the erroneous socket is closed and cleaned up by
  714. * the web server.
  715. * - Presently Chunked Encoding is not supported
  716. *
  717. * @param[in] r The request being responded to
  718. * @param[in] buf Pointer to a buffer that the data will be read into
  719. * @param[in] buf_len Length of the buffer
  720. *
  721. * @return
  722. * - Bytes : Number of bytes read into the buffer successfully
  723. * - 0 : Buffer length parameter is zero / connection closed by peer
  724. * - HTTPD_SOCK_ERR_INVALID : Invalid arguments
  725. * - HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket recv()
  726. * - HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket recv()
  727. */
  728. int httpd_req_recv(httpd_req_t *r, char *buf, size_t buf_len);
  729. /**
  730. * @brief Search for a field in request headers and
  731. * return the string length of it's value
  732. *
  733. * @note
  734. * - This API is supposed to be called only from the context of
  735. * a URI handler where httpd_req_t* request pointer is valid.
  736. * - Once httpd_resp_send() API is called all request headers
  737. * are purged, so request headers need be copied into separate
  738. * buffers if they are required later.
  739. *
  740. * @param[in] r The request being responded to
  741. * @param[in] field The header field to be searched in the request
  742. *
  743. * @return
  744. * - Length : If field is found in the request URL
  745. * - Zero : Field not found / Invalid request / Null arguments
  746. */
  747. size_t httpd_req_get_hdr_value_len(httpd_req_t *r, const char *field);
  748. /**
  749. * @brief Get the value string of a field from the request headers
  750. *
  751. * @note
  752. * - This API is supposed to be called only from the context of
  753. * a URI handler where httpd_req_t* request pointer is valid.
  754. * - Once httpd_resp_send() API is called all request headers
  755. * are purged, so request headers need be copied into separate
  756. * buffers if they are required later.
  757. * - If output size is greater than input, then the value is truncated,
  758. * accompanied by truncation error as return value.
  759. * - Use httpd_req_get_hdr_value_len() to know the right buffer length
  760. *
  761. * @param[in] r The request being responded to
  762. * @param[in] field The field to be searched in the header
  763. * @param[out] val Pointer to the buffer into which the value will be copied if the field is found
  764. * @param[in] val_size Size of the user buffer "val"
  765. *
  766. * @return
  767. * - ESP_OK : Field found in the request header and value string copied
  768. * - ESP_ERR_NOT_FOUND : Key not found
  769. * - ESP_ERR_INVALID_ARG : Null arguments
  770. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid HTTP request pointer
  771. * - ESP_ERR_HTTPD_RESULT_TRUNC : Value string truncated
  772. */
  773. esp_err_t httpd_req_get_hdr_value_str(httpd_req_t *r, const char *field, char *val, size_t val_size);
  774. /**
  775. * @brief Get Query string length from the request URL
  776. *
  777. * @note This API is supposed to be called only from the context of
  778. * a URI handler where httpd_req_t* request pointer is valid
  779. *
  780. * @param[in] r The request being responded to
  781. *
  782. * @return
  783. * - Length : Query is found in the request URL
  784. * - Zero : Query not found / Null arguments / Invalid request
  785. */
  786. size_t httpd_req_get_url_query_len(httpd_req_t *r);
  787. /**
  788. * @brief Get Query string from the request URL
  789. *
  790. * @note
  791. * - Presently, the user can fetch the full URL query string, but decoding
  792. * will have to be performed by the user. Request headers can be read using
  793. * httpd_req_get_hdr_value_str() to know the 'Content-Type' (eg. Content-Type:
  794. * application/x-www-form-urlencoded) and then the appropriate decoding
  795. * algorithm needs to be applied.
  796. * - This API is supposed to be called only from the context of
  797. * a URI handler where httpd_req_t* request pointer is valid
  798. * - If output size is greater than input, then the value is truncated,
  799. * accompanied by truncation error as return value
  800. * - Use httpd_req_get_url_query_len() to know the right buffer length
  801. *
  802. * @param[in] r The request being responded to
  803. * @param[out] buf Pointer to the buffer into which the query string will be copied (if found)
  804. * @param[in] buf_len Length of output buffer
  805. *
  806. * @return
  807. * - ESP_OK : Query is found in the request URL and copied to buffer
  808. * - ESP_ERR_NOT_FOUND : Query not found
  809. * - ESP_ERR_INVALID_ARG : Null arguments
  810. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid HTTP request pointer
  811. * - ESP_ERR_HTTPD_RESULT_TRUNC : Query string truncated
  812. */
  813. esp_err_t httpd_req_get_url_query_str(httpd_req_t *r, char *buf, size_t buf_len);
  814. /**
  815. * @brief Helper function to get a URL query tag from a query
  816. * string of the type param1=val1&param2=val2
  817. *
  818. * @note
  819. * - The components of URL query string (keys and values) are not URLdecoded.
  820. * The user must check for 'Content-Type' field in the request headers and
  821. * then depending upon the specified encoding (URLencoded or otherwise) apply
  822. * the appropriate decoding algorithm.
  823. * - If actual value size is greater than val_size, then the value is truncated,
  824. * accompanied by truncation error as return value.
  825. *
  826. * @param[in] qry Pointer to query string
  827. * @param[in] key The key to be searched in the query string
  828. * @param[out] val Pointer to the buffer into which the value will be copied if the key is found
  829. * @param[in] val_size Size of the user buffer "val"
  830. *
  831. * @return
  832. * - ESP_OK : Key is found in the URL query string and copied to buffer
  833. * - ESP_ERR_NOT_FOUND : Key not found
  834. * - ESP_ERR_INVALID_ARG : Null arguments
  835. * - ESP_ERR_HTTPD_RESULT_TRUNC : Value string truncated
  836. */
  837. esp_err_t httpd_query_key_value(const char *qry, const char *key, char *val, size_t val_size);
  838. /**
  839. * @brief Test if a URI matches the given wildcard template.
  840. *
  841. * Template may end with "?" to make the previous character optional (typically a slash),
  842. * "*" for a wildcard match, and "?*" to make the previous character optional, and if present,
  843. * allow anything to follow.
  844. *
  845. * Example:
  846. * - * matches everything
  847. * - /foo/? matches /foo and /foo/
  848. * - /foo/\* (sans the backslash) matches /foo/ and /foo/bar, but not /foo or /fo
  849. * - /foo/?* or /foo/\*? (sans the backslash) matches /foo/, /foo/bar, and also /foo, but not /foox or /fo
  850. *
  851. * The special characters "?" and "*" anywhere else in the template will be taken literally.
  852. *
  853. * @param[in] uri_template URI template (pattern)
  854. * @param[in] uri_to_match URI to be matched
  855. * @param[in] match_upto how many characters of the URI buffer to test
  856. * (there may be trailing query string etc.)
  857. *
  858. * @return true if a match was found
  859. */
  860. bool httpd_uri_match_wildcard(const char *uri_template, const char *uri_to_match, size_t match_upto);
  861. /**
  862. * @brief API to send a complete HTTP response.
  863. *
  864. * This API will send the data as an HTTP response to the request.
  865. * This assumes that you have the entire response ready in a single
  866. * buffer. If you wish to send response in incremental chunks use
  867. * httpd_resp_send_chunk() instead.
  868. *
  869. * If no status code and content-type were set, by default this
  870. * will send 200 OK status code and content type as text/html.
  871. * You may call the following functions before this API to configure
  872. * the response headers :
  873. * httpd_resp_set_status() - for setting the HTTP status string,
  874. * httpd_resp_set_type() - for setting the Content Type,
  875. * httpd_resp_set_hdr() - for appending any additional field
  876. * value entries in the response header
  877. *
  878. * @note
  879. * - This API is supposed to be called only from the context of
  880. * a URI handler where httpd_req_t* request pointer is valid.
  881. * - Once this API is called, the request has been responded to.
  882. * - No additional data can then be sent for the request.
  883. * - Once this API is called, all request headers are purged, so
  884. * request headers need be copied into separate buffers if
  885. * they are required later.
  886. *
  887. * @param[in] r The request being responded to
  888. * @param[in] buf Buffer from where the content is to be fetched
  889. * @param[in] buf_len Length of the buffer, HTTPD_RESP_USE_STRLEN to use strlen()
  890. *
  891. * @return
  892. * - ESP_OK : On successfully sending the response packet
  893. * - ESP_ERR_INVALID_ARG : Null request pointer
  894. * - ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer
  895. * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
  896. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request
  897. */
  898. esp_err_t httpd_resp_send(httpd_req_t *r, const char *buf, ssize_t buf_len);
  899. /**
  900. * @brief API to send one HTTP chunk
  901. *
  902. * This API will send the data as an HTTP response to the
  903. * request. This API will use chunked-encoding and send the response
  904. * in the form of chunks. If you have the entire response contained in
  905. * a single buffer, please use httpd_resp_send() instead.
  906. *
  907. * If no status code and content-type were set, by default this will
  908. * send 200 OK status code and content type as text/html. You may
  909. * call the following functions before this API to configure the
  910. * response headers
  911. * httpd_resp_set_status() - for setting the HTTP status string,
  912. * httpd_resp_set_type() - for setting the Content Type,
  913. * httpd_resp_set_hdr() - for appending any additional field
  914. * value entries in the response header
  915. *
  916. * @note
  917. * - This API is supposed to be called only from the context of
  918. * a URI handler where httpd_req_t* request pointer is valid.
  919. * - When you are finished sending all your chunks, you must call
  920. * this function with buf_len as 0.
  921. * - Once this API is called, all request headers are purged, so
  922. * request headers need be copied into separate buffers if they
  923. * are required later.
  924. *
  925. * @param[in] r The request being responded to
  926. * @param[in] buf Pointer to a buffer that stores the data
  927. * @param[in] buf_len Length of the buffer, HTTPD_RESP_USE_STRLEN to use strlen()
  928. *
  929. * @return
  930. * - ESP_OK : On successfully sending the response packet chunk
  931. * - ESP_ERR_INVALID_ARG : Null request pointer
  932. * - ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer
  933. * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
  934. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  935. */
  936. esp_err_t httpd_resp_send_chunk(httpd_req_t *r, const char *buf, ssize_t buf_len);
  937. /**
  938. * @brief API to send a complete string as HTTP response.
  939. *
  940. * This API simply calls http_resp_send with buffer length
  941. * set to string length assuming the buffer contains a null
  942. * terminated string
  943. *
  944. * @param[in] r The request being responded to
  945. * @param[in] str String to be sent as response body
  946. *
  947. * @return
  948. * - ESP_OK : On successfully sending the response packet
  949. * - ESP_ERR_INVALID_ARG : Null request pointer
  950. * - ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer
  951. * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
  952. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request
  953. */
  954. static inline esp_err_t httpd_resp_sendstr(httpd_req_t *r, const char *str) {
  955. return httpd_resp_send(r, str, (str == NULL) ? 0 : strlen(str));
  956. }
  957. /**
  958. * @brief API to send a string as an HTTP response chunk.
  959. *
  960. * This API simply calls http_resp_send_chunk with buffer length
  961. * set to string length assuming the buffer contains a null
  962. * terminated string
  963. *
  964. * @param[in] r The request being responded to
  965. * @param[in] str String to be sent as response body (NULL to finish response packet)
  966. *
  967. * @return
  968. * - ESP_OK : On successfully sending the response packet
  969. * - ESP_ERR_INVALID_ARG : Null request pointer
  970. * - ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer
  971. * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
  972. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request
  973. */
  974. static inline esp_err_t httpd_resp_sendstr_chunk(httpd_req_t *r, const char *str) {
  975. return httpd_resp_send_chunk(r, str, (str == NULL) ? 0 : strlen(str));
  976. }
  977. /* Some commonly used status codes */
  978. #define HTTPD_200 "200 OK" /*!< HTTP Response 200 */
  979. #define HTTPD_204 "204 No Content" /*!< HTTP Response 204 */
  980. #define HTTPD_207 "207 Multi-Status" /*!< HTTP Response 207 */
  981. #define HTTPD_400 "400 Bad Request" /*!< HTTP Response 400 */
  982. #define HTTPD_404 "404 Not Found" /*!< HTTP Response 404 */
  983. #define HTTPD_408 "408 Request Timeout" /*!< HTTP Response 408 */
  984. #define HTTPD_500 "500 Internal Server Error" /*!< HTTP Response 500 */
  985. /**
  986. * @brief API to set the HTTP status code
  987. *
  988. * This API sets the status of the HTTP response to the value specified.
  989. * By default, the '200 OK' response is sent as the response.
  990. *
  991. * @note
  992. * - This API is supposed to be called only from the context of
  993. * a URI handler where httpd_req_t* request pointer is valid.
  994. * - This API only sets the status to this value. The status isn't
  995. * sent out until any of the send APIs is executed.
  996. * - Make sure that the lifetime of the status string is valid till
  997. * send function is called.
  998. *
  999. * @param[in] r The request being responded to
  1000. * @param[in] status The HTTP status code of this response
  1001. *
  1002. * @return
  1003. * - ESP_OK : On success
  1004. * - ESP_ERR_INVALID_ARG : Null arguments
  1005. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  1006. */
  1007. esp_err_t httpd_resp_set_status(httpd_req_t *r, const char *status);
  1008. /* Some commonly used content types */
  1009. #define HTTPD_TYPE_JSON "application/json" /*!< HTTP Content type JSON */
  1010. #define HTTPD_TYPE_TEXT "text/html" /*!< HTTP Content type text/HTML */
  1011. #define HTTPD_TYPE_OCTET "application/octet-stream" /*!< HTTP Content type octext-stream */
  1012. /**
  1013. * @brief API to set the HTTP content type
  1014. *
  1015. * This API sets the 'Content Type' field of the response.
  1016. * The default content type is 'text/html'.
  1017. *
  1018. * @note
  1019. * - This API is supposed to be called only from the context of
  1020. * a URI handler where httpd_req_t* request pointer is valid.
  1021. * - This API only sets the content type to this value. The type
  1022. * isn't sent out until any of the send APIs is executed.
  1023. * - Make sure that the lifetime of the type string is valid till
  1024. * send function is called.
  1025. *
  1026. * @param[in] r The request being responded to
  1027. * @param[in] type The Content Type of the response
  1028. *
  1029. * @return
  1030. * - ESP_OK : On success
  1031. * - ESP_ERR_INVALID_ARG : Null arguments
  1032. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  1033. */
  1034. esp_err_t httpd_resp_set_type(httpd_req_t *r, const char *type);
  1035. /**
  1036. * @brief API to append any additional headers
  1037. *
  1038. * This API sets any additional header fields that need to be sent in the response.
  1039. *
  1040. * @note
  1041. * - This API is supposed to be called only from the context of
  1042. * a URI handler where httpd_req_t* request pointer is valid.
  1043. * - The header isn't sent out until any of the send APIs is executed.
  1044. * - The maximum allowed number of additional headers is limited to
  1045. * value of max_resp_headers in config structure.
  1046. * - Make sure that the lifetime of the field value strings are valid till
  1047. * send function is called.
  1048. *
  1049. * @param[in] r The request being responded to
  1050. * @param[in] field The field name of the HTTP header
  1051. * @param[in] value The value of this HTTP header
  1052. *
  1053. * @return
  1054. * - ESP_OK : On successfully appending new header
  1055. * - ESP_ERR_INVALID_ARG : Null arguments
  1056. * - ESP_ERR_HTTPD_RESP_HDR : Total additional headers exceed max allowed
  1057. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  1058. */
  1059. esp_err_t httpd_resp_set_hdr(httpd_req_t *r, const char *field, const char *value);
  1060. /**
  1061. * @brief For sending out error code in response to HTTP request.
  1062. *
  1063. * @note
  1064. * - This API is supposed to be called only from the context of
  1065. * a URI handler where httpd_req_t* request pointer is valid.
  1066. * - Once this API is called, all request headers are purged, so
  1067. * request headers need be copied into separate buffers if
  1068. * they are required later.
  1069. * - If you wish to send additional data in the body of the
  1070. * response, please use the lower-level functions directly.
  1071. *
  1072. * @param[in] req Pointer to the HTTP request for which the response needs to be sent
  1073. * @param[in] error Error type to send
  1074. * @param[in] msg Error message string (pass NULL for default message)
  1075. *
  1076. * @return
  1077. * - ESP_OK : On successfully sending the response packet
  1078. * - ESP_ERR_INVALID_ARG : Null arguments
  1079. * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
  1080. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  1081. */
  1082. esp_err_t httpd_resp_send_err(httpd_req_t *req, httpd_err_code_t error, const char *msg);
  1083. /**
  1084. * @brief Helper function for HTTP 404
  1085. *
  1086. * Send HTTP 404 message. If you wish to send additional data in the body of the
  1087. * response, please use the lower-level functions directly.
  1088. *
  1089. * @note
  1090. * - This API is supposed to be called only from the context of
  1091. * a URI handler where httpd_req_t* request pointer is valid.
  1092. * - Once this API is called, all request headers are purged, so
  1093. * request headers need be copied into separate buffers if
  1094. * they are required later.
  1095. *
  1096. * @param[in] r The request being responded to
  1097. *
  1098. * @return
  1099. * - ESP_OK : On successfully sending the response packet
  1100. * - ESP_ERR_INVALID_ARG : Null arguments
  1101. * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
  1102. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  1103. */
  1104. static inline esp_err_t httpd_resp_send_404(httpd_req_t *r) {
  1105. return httpd_resp_send_err(r, HTTPD_404_NOT_FOUND, NULL);
  1106. }
  1107. /**
  1108. * @brief Helper function for HTTP 408
  1109. *
  1110. * Send HTTP 408 message. If you wish to send additional data in the body of the
  1111. * response, please use the lower-level functions directly.
  1112. *
  1113. * @note
  1114. * - This API is supposed to be called only from the context of
  1115. * a URI handler where httpd_req_t* request pointer is valid.
  1116. * - Once this API is called, all request headers are purged, so
  1117. * request headers need be copied into separate buffers if
  1118. * they are required later.
  1119. *
  1120. * @param[in] r The request being responded to
  1121. *
  1122. * @return
  1123. * - ESP_OK : On successfully sending the response packet
  1124. * - ESP_ERR_INVALID_ARG : Null arguments
  1125. * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
  1126. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  1127. */
  1128. static inline esp_err_t httpd_resp_send_408(httpd_req_t *r) {
  1129. return httpd_resp_send_err(r, HTTPD_408_REQ_TIMEOUT, NULL);
  1130. }
  1131. /**
  1132. * @brief Helper function for HTTP 500
  1133. *
  1134. * Send HTTP 500 message. If you wish to send additional data in the body of the
  1135. * response, please use the lower-level functions directly.
  1136. *
  1137. * @note
  1138. * - This API is supposed to be called only from the context of
  1139. * a URI handler where httpd_req_t* request pointer is valid.
  1140. * - Once this API is called, all request headers are purged, so
  1141. * request headers need be copied into separate buffers if
  1142. * they are required later.
  1143. *
  1144. * @param[in] r The request being responded to
  1145. *
  1146. * @return
  1147. * - ESP_OK : On successfully sending the response packet
  1148. * - ESP_ERR_INVALID_ARG : Null arguments
  1149. * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
  1150. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  1151. */
  1152. static inline esp_err_t httpd_resp_send_500(httpd_req_t *r) {
  1153. return httpd_resp_send_err(r, HTTPD_500_INTERNAL_SERVER_ERROR, NULL);
  1154. }
  1155. /**
  1156. * @brief Raw HTTP send
  1157. *
  1158. * Call this API if you wish to construct your custom response packet.
  1159. * When using this, all essential header, eg. HTTP version, Status Code,
  1160. * Content Type and Length, Encoding, etc. will have to be constructed
  1161. * manually, and HTTP delimeters (CRLF) will need to be placed correctly
  1162. * for separating sub-sections of the HTTP response packet.
  1163. *
  1164. * If the send override function is set, this API will end up
  1165. * calling that function eventually to send data out.
  1166. *
  1167. * @note
  1168. * - This API is supposed to be called only from the context of
  1169. * a URI handler where httpd_req_t* request pointer is valid.
  1170. * - Unless the response has the correct HTTP structure (which the
  1171. * user must now ensure) it is not guaranteed that it will be
  1172. * recognized by the client. For most cases, you wouldn't have
  1173. * to call this API, but you would rather use either of :
  1174. * httpd_resp_send(),
  1175. * httpd_resp_send_chunk()
  1176. *
  1177. * @param[in] r The request being responded to
  1178. * @param[in] buf Buffer from where the fully constructed packet is to be read
  1179. * @param[in] buf_len Length of the buffer
  1180. *
  1181. * @return
  1182. * - Bytes : Number of bytes that were sent successfully
  1183. * - HTTPD_SOCK_ERR_INVALID : Invalid arguments
  1184. * - HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket send()
  1185. * - HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket send()
  1186. */
  1187. int httpd_send(httpd_req_t *r, const char *buf, size_t buf_len);
  1188. /** End of Request / Response
  1189. * @}
  1190. */
  1191. /* ************** Group: Session ************** */
  1192. /** @name Session
  1193. * Functions for controlling sessions and accessing context data
  1194. * @{
  1195. */
  1196. /**
  1197. * @brief Get session context from socket descriptor
  1198. *
  1199. * Typically if a session context is created, it is available to URI handlers
  1200. * through the httpd_req_t structure. But, there are cases where the web
  1201. * server's send/receive functions may require the context (for example, for
  1202. * accessing keying information etc). Since the send/receive function only have
  1203. * the socket descriptor at their disposal, this API provides them with a way to
  1204. * retrieve the session context.
  1205. *
  1206. * @param[in] handle Handle to server returned by httpd_start
  1207. * @param[in] sockfd The socket descriptor for which the context should be extracted.
  1208. *
  1209. * @return
  1210. * - void* : Pointer to the context associated with this session
  1211. * - NULL : Empty context / Invalid handle / Invalid socket fd
  1212. */
  1213. void *httpd_sess_get_ctx(httpd_handle_t handle, int sockfd);
  1214. /**
  1215. * @brief Set session context by socket descriptor
  1216. *
  1217. * @param[in] handle Handle to server returned by httpd_start
  1218. * @param[in] sockfd The socket descriptor for which the context should be extracted.
  1219. * @param[in] ctx Context object to assign to the session
  1220. * @param[in] free_fn Function that should be called to free the context
  1221. */
  1222. void httpd_sess_set_ctx(httpd_handle_t handle, int sockfd, void *ctx, httpd_free_ctx_fn_t free_fn);
  1223. /**
  1224. * @brief Get session 'transport' context by socket descriptor
  1225. * @see httpd_sess_get_ctx()
  1226. *
  1227. * This context is used by the send/receive functions, for example to manage SSL context.
  1228. *
  1229. * @param[in] handle Handle to server returned by httpd_start
  1230. * @param[in] sockfd The socket descriptor for which the context should be extracted.
  1231. * @return
  1232. * - void* : Pointer to the transport context associated with this session
  1233. * - NULL : Empty context / Invalid handle / Invalid socket fd
  1234. */
  1235. void *httpd_sess_get_transport_ctx(httpd_handle_t handle, int sockfd);
  1236. /**
  1237. * @brief Set session 'transport' context by socket descriptor
  1238. * @see httpd_sess_set_ctx()
  1239. *
  1240. * @param[in] handle Handle to server returned by httpd_start
  1241. * @param[in] sockfd The socket descriptor for which the context should be extracted.
  1242. * @param[in] ctx Transport context object to assign to the session
  1243. * @param[in] free_fn Function that should be called to free the transport context
  1244. */
  1245. void httpd_sess_set_transport_ctx(httpd_handle_t handle, int sockfd, void *ctx, httpd_free_ctx_fn_t free_fn);
  1246. /**
  1247. * @brief Get HTTPD global user context (it was set in the server config struct)
  1248. *
  1249. * @param[in] handle Handle to server returned by httpd_start
  1250. * @return global user context
  1251. */
  1252. void *httpd_get_global_user_ctx(httpd_handle_t handle);
  1253. /**
  1254. * @brief Get HTTPD global transport context (it was set in the server config struct)
  1255. *
  1256. * @param[in] handle Handle to server returned by httpd_start
  1257. * @return global transport context
  1258. */
  1259. void *httpd_get_global_transport_ctx(httpd_handle_t handle);
  1260. /**
  1261. * @brief Trigger an httpd session close externally
  1262. *
  1263. * @note Calling this API is only required in special circumstances wherein
  1264. * some application requires to close an httpd client session asynchronously.
  1265. *
  1266. * @param[in] handle Handle to server returned by httpd_start
  1267. * @param[in] sockfd The socket descriptor of the session to be closed
  1268. *
  1269. * @return
  1270. * - ESP_OK : On successfully initiating closure
  1271. * - ESP_FAIL : Failure to queue work
  1272. * - ESP_ERR_NOT_FOUND : Socket fd not found
  1273. * - ESP_ERR_INVALID_ARG : Null arguments
  1274. */
  1275. esp_err_t httpd_sess_trigger_close(httpd_handle_t handle, int sockfd);
  1276. /**
  1277. * @brief Update LRU counter for a given socket
  1278. *
  1279. * LRU Counters are internally associated with each session to monitor
  1280. * how recently a session exchanged traffic. When LRU purge is enabled,
  1281. * if a client is requesting for connection but maximum number of
  1282. * sockets/sessions is reached, then the session having the earliest
  1283. * LRU counter is closed automatically.
  1284. *
  1285. * Updating the LRU counter manually prevents the socket from being purged
  1286. * due to the Least Recently Used (LRU) logic, even though it might not
  1287. * have received traffic for some time. This is useful when all open
  1288. * sockets/session are frequently exchanging traffic but the user specifically
  1289. * wants one of the sessions to be kept open, irrespective of when it last
  1290. * exchanged a packet.
  1291. *
  1292. * @note Calling this API is only necessary if the LRU Purge Enable option
  1293. * is enabled.
  1294. *
  1295. * @param[in] handle Handle to server returned by httpd_start
  1296. * @param[in] sockfd The socket descriptor of the session for which LRU counter
  1297. * is to be updated
  1298. *
  1299. * @return
  1300. * - ESP_OK : Socket found and LRU counter updated
  1301. * - ESP_ERR_NOT_FOUND : Socket not found
  1302. * - ESP_ERR_INVALID_ARG : Null arguments
  1303. */
  1304. esp_err_t httpd_sess_update_lru_counter(httpd_handle_t handle, int sockfd);
  1305. /** End of Session
  1306. * @}
  1307. */
  1308. /* ************** Group: Work Queue ************** */
  1309. /** @name Work Queue
  1310. * APIs related to the HTTPD Work Queue
  1311. * @{
  1312. */
  1313. /**
  1314. * @brief Prototype of the HTTPD work function
  1315. * Please refer to httpd_queue_work() for more details.
  1316. * @param[in] arg The arguments for this work function
  1317. */
  1318. typedef void (*httpd_work_fn_t)(void *arg);
  1319. /**
  1320. * @brief Queue execution of a function in HTTPD's context
  1321. *
  1322. * This API queues a work function for asynchronous execution
  1323. *
  1324. * @note Some protocols require that the web server generate some asynchronous data
  1325. * and send it to the persistently opened connection. This facility is for use
  1326. * by such protocols.
  1327. *
  1328. * @param[in] handle Handle to server returned by httpd_start
  1329. * @param[in] work Pointer to the function to be executed in the HTTPD's context
  1330. * @param[in] arg Pointer to the arguments that should be passed to this function
  1331. *
  1332. * @return
  1333. * - ESP_OK : On successfully queueing the work
  1334. * - ESP_FAIL : Failure in ctrl socket
  1335. * - ESP_ERR_INVALID_ARG : Null arguments
  1336. */
  1337. esp_err_t httpd_queue_work(httpd_handle_t handle, httpd_work_fn_t work, void *arg);
  1338. /** End of Group Work Queue
  1339. * @}
  1340. */
  1341. #ifdef __cplusplus
  1342. }
  1343. #endif
  1344. #endif /* ! _ESP_HTTP_SERVER_H_ */