esp_http_server.h 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438
  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. } httpd_req_t;
  332. /**
  333. * @brief Structure for URI handler
  334. */
  335. typedef struct httpd_uri {
  336. const char *uri; /*!< The URI to handle */
  337. httpd_method_t method; /*!< Method supported by the URI */
  338. /**
  339. * Handler to call for supported request method. This must
  340. * return ESP_OK, or else the underlying socket will be closed.
  341. */
  342. esp_err_t (*handler)(httpd_req_t *r);
  343. /**
  344. * Pointer to user context data which will be available to handler
  345. */
  346. void *user_ctx;
  347. } httpd_uri_t;
  348. /**
  349. * @brief Registers a URI handler
  350. *
  351. * @note URI handlers can be registered in real time as long as the
  352. * server handle is valid.
  353. *
  354. * Example usage:
  355. * @code{c}
  356. *
  357. * esp_err_t my_uri_handler(httpd_req_t* req)
  358. * {
  359. * // Recv , Process and Send
  360. * ....
  361. * ....
  362. * ....
  363. *
  364. * // Fail condition
  365. * if (....) {
  366. * // Return fail to close session //
  367. * return ESP_FAIL;
  368. * }
  369. *
  370. * // On success
  371. * return ESP_OK;
  372. * }
  373. *
  374. * // URI handler structure
  375. * httpd_uri_t my_uri {
  376. * .uri = "/my_uri/path/xyz",
  377. * .method = HTTPD_GET,
  378. * .handler = my_uri_handler,
  379. * .user_ctx = NULL
  380. * };
  381. *
  382. * // Register handler
  383. * if (httpd_register_uri_handler(server_handle, &my_uri) != ESP_OK) {
  384. * // If failed to register handler
  385. * ....
  386. * }
  387. *
  388. * @endcode
  389. *
  390. * @param[in] handle handle to HTTPD server instance
  391. * @param[in] uri_handler pointer to handler that needs to be registered
  392. *
  393. * @return
  394. * - ESP_OK : On successfully registering the handler
  395. * - ESP_ERR_INVALID_ARG : Null arguments
  396. * - ESP_ERR_HTTPD_HANDLERS_FULL : If no slots left for new handler
  397. * - ESP_ERR_HTTPD_HANDLER_EXISTS : If handler with same URI and
  398. * method is already registered
  399. */
  400. esp_err_t httpd_register_uri_handler(httpd_handle_t handle,
  401. const httpd_uri_t *uri_handler);
  402. /**
  403. * @brief Unregister a URI handler
  404. *
  405. * @param[in] handle handle to HTTPD server instance
  406. * @param[in] uri URI string
  407. * @param[in] method HTTP method
  408. *
  409. * @return
  410. * - ESP_OK : On successfully deregistering the handler
  411. * - ESP_ERR_INVALID_ARG : Null arguments
  412. * - ESP_ERR_NOT_FOUND : Handler with specified URI and method not found
  413. */
  414. esp_err_t httpd_unregister_uri_handler(httpd_handle_t handle,
  415. const char *uri, httpd_method_t method);
  416. /**
  417. * @brief Unregister all URI handlers with the specified uri string
  418. *
  419. * @param[in] handle handle to HTTPD server instance
  420. * @param[in] uri uri string specifying all handlers that need
  421. * to be deregisterd
  422. *
  423. * @return
  424. * - ESP_OK : On successfully deregistering all such handlers
  425. * - ESP_ERR_INVALID_ARG : Null arguments
  426. * - ESP_ERR_NOT_FOUND : No handler registered with specified uri string
  427. */
  428. esp_err_t httpd_unregister_uri(httpd_handle_t handle, const char* uri);
  429. /** End of URI Handlers
  430. * @}
  431. */
  432. /* ************** Group: HTTP Error ************** */
  433. /** @name HTTP Error
  434. * Prototype for HTTP errors and error handling functions
  435. * @{
  436. */
  437. /**
  438. * @brief Error codes sent as HTTP response in case of errors
  439. * encountered during processing of an HTTP request
  440. */
  441. typedef enum {
  442. /* For any unexpected errors during parsing, like unexpected
  443. * state transitions, or unhandled errors.
  444. */
  445. HTTPD_500_INTERNAL_SERVER_ERROR = 0,
  446. /* For methods not supported by http_parser. Presently
  447. * http_parser halts parsing when such methods are
  448. * encountered and so the server responds with 400 Bad
  449. * Request error instead.
  450. */
  451. HTTPD_501_METHOD_NOT_IMPLEMENTED,
  452. /* When HTTP version is not 1.1 */
  453. HTTPD_505_VERSION_NOT_SUPPORTED,
  454. /* Returned when http_parser halts parsing due to incorrect
  455. * syntax of request, unsupported method in request URI or
  456. * due to chunked encoding / upgrade field present in headers
  457. */
  458. HTTPD_400_BAD_REQUEST,
  459. /* When requested URI is not found */
  460. HTTPD_404_NOT_FOUND,
  461. /* When URI found, but method has no handler registered */
  462. HTTPD_405_METHOD_NOT_ALLOWED,
  463. /* Intended for recv timeout. Presently it's being sent
  464. * for other recv errors as well. Client should expect the
  465. * server to immediately close the connection after
  466. * responding with this.
  467. */
  468. HTTPD_408_REQ_TIMEOUT,
  469. /* Intended for responding to chunked encoding, which is
  470. * not supported currently. Though unhandled http_parser
  471. * callback for chunked request returns "400 Bad Request"
  472. */
  473. HTTPD_411_LENGTH_REQUIRED,
  474. /* URI length greater than CONFIG_HTTPD_MAX_URI_LEN */
  475. HTTPD_414_URI_TOO_LONG,
  476. /* Headers section larger than CONFIG_HTTPD_MAX_REQ_HDR_LEN */
  477. HTTPD_431_REQ_HDR_FIELDS_TOO_LARGE,
  478. /* Used internally for retrieving the total count of errors */
  479. HTTPD_ERR_CODE_MAX
  480. } httpd_err_code_t;
  481. /**
  482. * @brief Function prototype for HTTP error handling.
  483. *
  484. * This function is executed upon HTTP errors generated during
  485. * internal processing of an HTTP request. This is used to override
  486. * the default behavior on error, which is to send HTTP error response
  487. * and close the underlying socket.
  488. *
  489. * @note
  490. * - If implemented, the server will not automatically send out HTTP
  491. * error response codes, therefore, httpd_resp_send_err() must be
  492. * invoked inside this function if user wishes to generate HTTP
  493. * error responses.
  494. * - When invoked, the validity of `uri`, `method`, `content_len`
  495. * and `user_ctx` fields of the httpd_req_t parameter is not
  496. * guaranteed as the HTTP request may be partially received/parsed.
  497. * - The function must return ESP_OK if underlying socket needs to
  498. * be kept open. Any other value will ensure that the socket is
  499. * closed. The return value is ignored when error is of type
  500. * `HTTPD_500_INTERNAL_SERVER_ERROR` and the socket closed anyway.
  501. *
  502. * @param[in] req HTTP request for which the error needs to be handled
  503. * @param[in] error Error type
  504. *
  505. * @return
  506. * - ESP_OK : error handled successful
  507. * - ESP_FAIL : failure indicates that the underlying socket needs to be closed
  508. */
  509. typedef esp_err_t (*httpd_err_handler_func_t)(httpd_req_t *req,
  510. httpd_err_code_t error);
  511. /**
  512. * @brief Function for registering HTTP error handlers
  513. *
  514. * This function maps a handler function to any supported error code
  515. * given by `httpd_err_code_t`. See prototype `httpd_err_handler_func_t`
  516. * above for details.
  517. *
  518. * @param[in] handle HTTP server handle
  519. * @param[in] error Error type
  520. * @param[in] handler_fn User implemented handler function
  521. * (Pass NULL to unset any previously set handler)
  522. *
  523. * @return
  524. * - ESP_OK : handler registered successfully
  525. * - ESP_ERR_INVALID_ARG : invalid error code or server handle
  526. */
  527. esp_err_t httpd_register_err_handler(httpd_handle_t handle,
  528. httpd_err_code_t error,
  529. httpd_err_handler_func_t handler_fn);
  530. /** End of HTTP Error
  531. * @}
  532. */
  533. /* ************** Group: TX/RX ************** */
  534. /** @name TX / RX
  535. * Prototype for HTTPDs low-level send/recv functions
  536. * @{
  537. */
  538. #define HTTPD_SOCK_ERR_FAIL -1
  539. #define HTTPD_SOCK_ERR_INVALID -2
  540. #define HTTPD_SOCK_ERR_TIMEOUT -3
  541. /**
  542. * @brief Prototype for HTTPDs low-level send function
  543. *
  544. * @note User specified send function must handle errors internally,
  545. * depending upon the set value of errno, and return specific
  546. * HTTPD_SOCK_ERR_ codes, which will eventually be conveyed as
  547. * return value of httpd_send() function
  548. *
  549. * @param[in] hd server instance
  550. * @param[in] sockfd session socket file descriptor
  551. * @param[in] buf buffer with bytes to send
  552. * @param[in] buf_len data size
  553. * @param[in] flags flags for the send() function
  554. * @return
  555. * - Bytes : The number of bytes sent successfully
  556. * - HTTPD_SOCK_ERR_INVALID : Invalid arguments
  557. * - HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket send()
  558. * - HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket send()
  559. */
  560. typedef int (*httpd_send_func_t)(httpd_handle_t hd, int sockfd, const char *buf, size_t buf_len, int flags);
  561. /**
  562. * @brief Prototype for HTTPDs low-level recv function
  563. *
  564. * @note User specified recv function must handle errors internally,
  565. * depending upon the set value of errno, and return specific
  566. * HTTPD_SOCK_ERR_ codes, which will eventually be conveyed as
  567. * return value of httpd_req_recv() function
  568. *
  569. * @param[in] hd server instance
  570. * @param[in] sockfd session socket file descriptor
  571. * @param[in] buf buffer with bytes to send
  572. * @param[in] buf_len data size
  573. * @param[in] flags flags for the send() function
  574. * @return
  575. * - Bytes : The number of bytes received successfully
  576. * - 0 : Buffer length parameter is zero / connection closed by peer
  577. * - HTTPD_SOCK_ERR_INVALID : Invalid arguments
  578. * - HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket recv()
  579. * - HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket recv()
  580. */
  581. typedef int (*httpd_recv_func_t)(httpd_handle_t hd, int sockfd, char *buf, size_t buf_len, int flags);
  582. /**
  583. * @brief Prototype for HTTPDs low-level "get pending bytes" function
  584. *
  585. * @note User specified pending function must handle errors internally,
  586. * depending upon the set value of errno, and return specific
  587. * HTTPD_SOCK_ERR_ codes, which will be handled accordingly in
  588. * the server task.
  589. *
  590. * @param[in] hd server instance
  591. * @param[in] sockfd session socket file descriptor
  592. * @return
  593. * - Bytes : The number of bytes waiting to be received
  594. * - HTTPD_SOCK_ERR_INVALID : Invalid arguments
  595. * - HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket pending()
  596. * - HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket pending()
  597. */
  598. typedef int (*httpd_pending_func_t)(httpd_handle_t hd, int sockfd);
  599. /** End of TX / RX
  600. * @}
  601. */
  602. /* ************** Group: Request/Response ************** */
  603. /** @name Request / Response
  604. * APIs related to the data send/receive by URI handlers.
  605. * These APIs are supposed to be called only from the context of
  606. * a URI handler where httpd_req_t* request pointer is valid.
  607. * @{
  608. */
  609. /**
  610. * @brief Override web server's receive function (by session FD)
  611. *
  612. * This function overrides the web server's receive function. This same function is
  613. * used to read HTTP request packets.
  614. *
  615. * @note This API is supposed to be called either from the context of
  616. * - an http session APIs where sockfd is a valid parameter
  617. * - a URI handler where sockfd is obtained using httpd_req_to_sockfd()
  618. *
  619. * @param[in] hd HTTPD instance handle
  620. * @param[in] sockfd Session socket FD
  621. * @param[in] recv_func The receive function to be set for this session
  622. *
  623. * @return
  624. * - ESP_OK : On successfully registering override
  625. * - ESP_ERR_INVALID_ARG : Null arguments
  626. */
  627. esp_err_t httpd_sess_set_recv_override(httpd_handle_t hd, int sockfd, httpd_recv_func_t recv_func);
  628. /**
  629. * @brief Override web server's send function (by session FD)
  630. *
  631. * This function overrides the web server's send function. This same function is
  632. * used to send out any response to any HTTP request.
  633. *
  634. * @note This API is supposed to be called either from the context of
  635. * - an http session APIs where sockfd is a valid parameter
  636. * - a URI handler where sockfd is obtained using httpd_req_to_sockfd()
  637. *
  638. * @param[in] hd HTTPD instance handle
  639. * @param[in] sockfd Session socket FD
  640. * @param[in] send_func The send function to be set for this session
  641. *
  642. * @return
  643. * - ESP_OK : On successfully registering override
  644. * - ESP_ERR_INVALID_ARG : Null arguments
  645. */
  646. esp_err_t httpd_sess_set_send_override(httpd_handle_t hd, int sockfd, httpd_send_func_t send_func);
  647. /**
  648. * @brief Override web server's pending function (by session FD)
  649. *
  650. * This function overrides the web server's pending function. This function is
  651. * used to test for pending bytes in a socket.
  652. *
  653. * @note This API is supposed to be called either from the context of
  654. * - an http session APIs where sockfd is a valid parameter
  655. * - a URI handler where sockfd is obtained using httpd_req_to_sockfd()
  656. *
  657. * @param[in] hd HTTPD instance handle
  658. * @param[in] sockfd Session socket FD
  659. * @param[in] pending_func The receive function to be set for this session
  660. *
  661. * @return
  662. * - ESP_OK : On successfully registering override
  663. * - ESP_ERR_INVALID_ARG : Null arguments
  664. */
  665. esp_err_t httpd_sess_set_pending_override(httpd_handle_t hd, int sockfd, httpd_pending_func_t pending_func);
  666. /**
  667. * @brief Get the Socket Descriptor from the HTTP request
  668. *
  669. * This API will return the socket descriptor of the session for
  670. * which URI handler was executed on reception of HTTP request.
  671. * This is useful when user wants to call functions that require
  672. * session socket fd, from within a URI handler, ie. :
  673. * httpd_sess_get_ctx(),
  674. * httpd_sess_trigger_close(),
  675. * httpd_sess_update_lru_counter().
  676. *
  677. * @note This API is supposed to be called only from the context of
  678. * a URI handler where httpd_req_t* request pointer is valid.
  679. *
  680. * @param[in] r The request whose socket descriptor should be found
  681. *
  682. * @return
  683. * - Socket descriptor : The socket descriptor for this request
  684. * - -1 : Invalid/NULL request pointer
  685. */
  686. int httpd_req_to_sockfd(httpd_req_t *r);
  687. /**
  688. * @brief API to read content data from the HTTP request
  689. *
  690. * This API will read HTTP content data from the HTTP request into
  691. * provided buffer. Use content_len provided in httpd_req_t structure
  692. * to know the length of data to be fetched. If content_len is too
  693. * large for the buffer then user may have to make multiple calls to
  694. * this function, each time fetching 'buf_len' number of bytes,
  695. * while the pointer to content data is incremented internally by
  696. * the same number.
  697. *
  698. * @note
  699. * - This API is supposed to be called only from the context of
  700. * a URI handler where httpd_req_t* request pointer is valid.
  701. * - If an error is returned, the URI handler must further return an error.
  702. * This will ensure that the erroneous socket is closed and cleaned up by
  703. * the web server.
  704. * - Presently Chunked Encoding is not supported
  705. *
  706. * @param[in] r The request being responded to
  707. * @param[in] buf Pointer to a buffer that the data will be read into
  708. * @param[in] buf_len Length of the buffer
  709. *
  710. * @return
  711. * - Bytes : Number of bytes read into the buffer successfully
  712. * - 0 : Buffer length parameter is zero / connection closed by peer
  713. * - HTTPD_SOCK_ERR_INVALID : Invalid arguments
  714. * - HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket recv()
  715. * - HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket recv()
  716. */
  717. int httpd_req_recv(httpd_req_t *r, char *buf, size_t buf_len);
  718. /**
  719. * @brief Search for a field in request headers and
  720. * return the string length of it's value
  721. *
  722. * @note
  723. * - This API is supposed to be called only from the context of
  724. * a URI handler where httpd_req_t* request pointer is valid.
  725. * - Once httpd_resp_send() API is called all request headers
  726. * are purged, so request headers need be copied into separate
  727. * buffers if they are required later.
  728. *
  729. * @param[in] r The request being responded to
  730. * @param[in] field The header field to be searched in the request
  731. *
  732. * @return
  733. * - Length : If field is found in the request URL
  734. * - Zero : Field not found / Invalid request / Null arguments
  735. */
  736. size_t httpd_req_get_hdr_value_len(httpd_req_t *r, const char *field);
  737. /**
  738. * @brief Get the value string of a field from the request headers
  739. *
  740. * @note
  741. * - This API is supposed to be called only from the context of
  742. * a URI handler where httpd_req_t* request pointer is valid.
  743. * - Once httpd_resp_send() API is called all request headers
  744. * are purged, so request headers need be copied into separate
  745. * buffers if they are required later.
  746. * - If output size is greater than input, then the value is truncated,
  747. * accompanied by truncation error as return value.
  748. * - Use httpd_req_get_hdr_value_len() to know the right buffer length
  749. *
  750. * @param[in] r The request being responded to
  751. * @param[in] field The field to be searched in the header
  752. * @param[out] val Pointer to the buffer into which the value will be copied if the field is found
  753. * @param[in] val_size Size of the user buffer "val"
  754. *
  755. * @return
  756. * - ESP_OK : Field found in the request header and value string copied
  757. * - ESP_ERR_NOT_FOUND : Key not found
  758. * - ESP_ERR_INVALID_ARG : Null arguments
  759. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid HTTP request pointer
  760. * - ESP_ERR_HTTPD_RESULT_TRUNC : Value string truncated
  761. */
  762. esp_err_t httpd_req_get_hdr_value_str(httpd_req_t *r, const char *field, char *val, size_t val_size);
  763. /**
  764. * @brief Get Query string length from the request URL
  765. *
  766. * @note This API is supposed to be called only from the context of
  767. * a URI handler where httpd_req_t* request pointer is valid
  768. *
  769. * @param[in] r The request being responded to
  770. *
  771. * @return
  772. * - Length : Query is found in the request URL
  773. * - Zero : Query not found / Null arguments / Invalid request
  774. */
  775. size_t httpd_req_get_url_query_len(httpd_req_t *r);
  776. /**
  777. * @brief Get Query string from the request URL
  778. *
  779. * @note
  780. * - Presently, the user can fetch the full URL query string, but decoding
  781. * will have to be performed by the user. Request headers can be read using
  782. * httpd_req_get_hdr_value_str() to know the 'Content-Type' (eg. Content-Type:
  783. * application/x-www-form-urlencoded) and then the appropriate decoding
  784. * algorithm needs to be applied.
  785. * - This API is supposed to be called only from the context of
  786. * a URI handler where httpd_req_t* request pointer is valid
  787. * - If output size is greater than input, then the value is truncated,
  788. * accompanied by truncation error as return value
  789. * - Use httpd_req_get_url_query_len() to know the right buffer length
  790. *
  791. * @param[in] r The request being responded to
  792. * @param[out] buf Pointer to the buffer into which the query string will be copied (if found)
  793. * @param[in] buf_len Length of output buffer
  794. *
  795. * @return
  796. * - ESP_OK : Query is found in the request URL and copied to buffer
  797. * - ESP_ERR_NOT_FOUND : Query not found
  798. * - ESP_ERR_INVALID_ARG : Null arguments
  799. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid HTTP request pointer
  800. * - ESP_ERR_HTTPD_RESULT_TRUNC : Query string truncated
  801. */
  802. esp_err_t httpd_req_get_url_query_str(httpd_req_t *r, char *buf, size_t buf_len);
  803. /**
  804. * @brief Helper function to get a URL query tag from a query
  805. * string of the type param1=val1&param2=val2
  806. *
  807. * @note
  808. * - The components of URL query string (keys and values) are not URLdecoded.
  809. * The user must check for 'Content-Type' field in the request headers and
  810. * then depending upon the specified encoding (URLencoded or otherwise) apply
  811. * the appropriate decoding algorithm.
  812. * - If actual value size is greater than val_size, then the value is truncated,
  813. * accompanied by truncation error as return value.
  814. *
  815. * @param[in] qry Pointer to query string
  816. * @param[in] key The key to be searched in the query string
  817. * @param[out] val Pointer to the buffer into which the value will be copied if the key is found
  818. * @param[in] val_size Size of the user buffer "val"
  819. *
  820. * @return
  821. * - ESP_OK : Key is found in the URL query string and copied to buffer
  822. * - ESP_ERR_NOT_FOUND : Key not found
  823. * - ESP_ERR_INVALID_ARG : Null arguments
  824. * - ESP_ERR_HTTPD_RESULT_TRUNC : Value string truncated
  825. */
  826. esp_err_t httpd_query_key_value(const char *qry, const char *key, char *val, size_t val_size);
  827. /**
  828. * @brief Test if a URI matches the given wildcard template.
  829. *
  830. * Template may end with "?" to make the previous character optional (typically a slash),
  831. * "*" for a wildcard match, and "?*" to make the previous character optional, and if present,
  832. * allow anything to follow.
  833. *
  834. * Example:
  835. * - * matches everything
  836. * - /foo/? matches /foo and /foo/
  837. * - /foo/\* (sans the backslash) matches /foo/ and /foo/bar, but not /foo or /fo
  838. * - /foo/?* or /foo/\*? (sans the backslash) matches /foo/, /foo/bar, and also /foo, but not /foox or /fo
  839. *
  840. * The special characters "?" and "*" anywhere else in the template will be taken literally.
  841. *
  842. * @param[in] uri_template URI template (pattern)
  843. * @param[in] uri_to_match URI to be matched
  844. * @param[in] match_upto how many characters of the URI buffer to test
  845. * (there may be trailing query string etc.)
  846. *
  847. * @return true if a match was found
  848. */
  849. bool httpd_uri_match_wildcard(const char *uri_template, const char *uri_to_match, size_t match_upto);
  850. /**
  851. * @brief API to send a complete HTTP response.
  852. *
  853. * This API will send the data as an HTTP response to the request.
  854. * This assumes that you have the entire response ready in a single
  855. * buffer. If you wish to send response in incremental chunks use
  856. * httpd_resp_send_chunk() instead.
  857. *
  858. * If no status code and content-type were set, by default this
  859. * will send 200 OK status code and content type as text/html.
  860. * You may call the following functions before this API to configure
  861. * the response headers :
  862. * httpd_resp_set_status() - for setting the HTTP status string,
  863. * httpd_resp_set_type() - for setting the Content Type,
  864. * httpd_resp_set_hdr() - for appending any additional field
  865. * value entries in the response header
  866. *
  867. * @note
  868. * - This API is supposed to be called only from the context of
  869. * a URI handler where httpd_req_t* request pointer is valid.
  870. * - Once this API is called, the request has been responded to.
  871. * - No additional data can then be sent for the request.
  872. * - Once this API is called, all request headers are purged, so
  873. * request headers need be copied into separate buffers if
  874. * they are required later.
  875. *
  876. * @param[in] r The request being responded to
  877. * @param[in] buf Buffer from where the content is to be fetched
  878. * @param[in] buf_len Length of the buffer, HTTPD_RESP_USE_STRLEN to use strlen()
  879. *
  880. * @return
  881. * - ESP_OK : On successfully sending the response packet
  882. * - ESP_ERR_INVALID_ARG : Null request pointer
  883. * - ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer
  884. * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
  885. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request
  886. */
  887. esp_err_t httpd_resp_send(httpd_req_t *r, const char *buf, ssize_t buf_len);
  888. /**
  889. * @brief API to send one HTTP chunk
  890. *
  891. * This API will send the data as an HTTP response to the
  892. * request. This API will use chunked-encoding and send the response
  893. * in the form of chunks. If you have the entire response contained in
  894. * a single buffer, please use httpd_resp_send() instead.
  895. *
  896. * If no status code and content-type were set, by default this will
  897. * send 200 OK status code and content type as text/html. You may
  898. * call the following functions before this API to configure the
  899. * response headers
  900. * httpd_resp_set_status() - for setting the HTTP status string,
  901. * httpd_resp_set_type() - for setting the Content Type,
  902. * httpd_resp_set_hdr() - for appending any additional field
  903. * value entries in the response header
  904. *
  905. * @note
  906. * - This API is supposed to be called only from the context of
  907. * a URI handler where httpd_req_t* request pointer is valid.
  908. * - When you are finished sending all your chunks, you must call
  909. * this function with buf_len as 0.
  910. * - Once this API is called, all request headers are purged, so
  911. * request headers need be copied into separate buffers if they
  912. * are required later.
  913. *
  914. * @param[in] r The request being responded to
  915. * @param[in] buf Pointer to a buffer that stores the data
  916. * @param[in] buf_len Length of the buffer, HTTPD_RESP_USE_STRLEN to use strlen()
  917. *
  918. * @return
  919. * - ESP_OK : On successfully sending the response packet chunk
  920. * - ESP_ERR_INVALID_ARG : Null request pointer
  921. * - ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer
  922. * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
  923. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  924. */
  925. esp_err_t httpd_resp_send_chunk(httpd_req_t *r, const char *buf, ssize_t buf_len);
  926. /**
  927. * @brief API to send a complete string as HTTP response.
  928. *
  929. * This API simply calls http_resp_send with buffer length
  930. * set to string length assuming the buffer contains a null
  931. * terminated string
  932. *
  933. * @param[in] r The request being responded to
  934. * @param[in] str String to be sent as response body
  935. *
  936. * @return
  937. * - ESP_OK : On successfully sending the response packet
  938. * - ESP_ERR_INVALID_ARG : Null request pointer
  939. * - ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer
  940. * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
  941. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request
  942. */
  943. static inline esp_err_t httpd_resp_sendstr(httpd_req_t *r, const char *str) {
  944. return httpd_resp_send(r, str, (str == NULL) ? 0 : strlen(str));
  945. }
  946. /**
  947. * @brief API to send a string as an HTTP response chunk.
  948. *
  949. * This API simply calls http_resp_send_chunk with buffer length
  950. * set to string length assuming the buffer contains a null
  951. * terminated string
  952. *
  953. * @param[in] r The request being responded to
  954. * @param[in] str String to be sent as response body (NULL to finish response packet)
  955. *
  956. * @return
  957. * - ESP_OK : On successfully sending the response packet
  958. * - ESP_ERR_INVALID_ARG : Null request pointer
  959. * - ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer
  960. * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
  961. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request
  962. */
  963. static inline esp_err_t httpd_resp_sendstr_chunk(httpd_req_t *r, const char *str) {
  964. return httpd_resp_send_chunk(r, str, (str == NULL) ? 0 : strlen(str));
  965. }
  966. /* Some commonly used status codes */
  967. #define HTTPD_200 "200 OK" /*!< HTTP Response 200 */
  968. #define HTTPD_204 "204 No Content" /*!< HTTP Response 204 */
  969. #define HTTPD_207 "207 Multi-Status" /*!< HTTP Response 207 */
  970. #define HTTPD_400 "400 Bad Request" /*!< HTTP Response 400 */
  971. #define HTTPD_404 "404 Not Found" /*!< HTTP Response 404 */
  972. #define HTTPD_408 "408 Request Timeout" /*!< HTTP Response 408 */
  973. #define HTTPD_500 "500 Internal Server Error" /*!< HTTP Response 500 */
  974. /**
  975. * @brief API to set the HTTP status code
  976. *
  977. * This API sets the status of the HTTP response to the value specified.
  978. * By default, the '200 OK' response is sent as the response.
  979. *
  980. * @note
  981. * - This API is supposed to be called only from the context of
  982. * a URI handler where httpd_req_t* request pointer is valid.
  983. * - This API only sets the status to this value. The status isn't
  984. * sent out until any of the send APIs is executed.
  985. * - Make sure that the lifetime of the status string is valid till
  986. * send function is called.
  987. *
  988. * @param[in] r The request being responded to
  989. * @param[in] status The HTTP status code of this response
  990. *
  991. * @return
  992. * - ESP_OK : On success
  993. * - ESP_ERR_INVALID_ARG : Null arguments
  994. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  995. */
  996. esp_err_t httpd_resp_set_status(httpd_req_t *r, const char *status);
  997. /* Some commonly used content types */
  998. #define HTTPD_TYPE_JSON "application/json" /*!< HTTP Content type JSON */
  999. #define HTTPD_TYPE_TEXT "text/html" /*!< HTTP Content type text/HTML */
  1000. #define HTTPD_TYPE_OCTET "application/octet-stream" /*!< HTTP Content type octext-stream */
  1001. /**
  1002. * @brief API to set the HTTP content type
  1003. *
  1004. * This API sets the 'Content Type' field of the response.
  1005. * The default content type is 'text/html'.
  1006. *
  1007. * @note
  1008. * - This API is supposed to be called only from the context of
  1009. * a URI handler where httpd_req_t* request pointer is valid.
  1010. * - This API only sets the content type to this value. The type
  1011. * isn't sent out until any of the send APIs is executed.
  1012. * - Make sure that the lifetime of the type string is valid till
  1013. * send function is called.
  1014. *
  1015. * @param[in] r The request being responded to
  1016. * @param[in] type The Content Type of the response
  1017. *
  1018. * @return
  1019. * - ESP_OK : On success
  1020. * - ESP_ERR_INVALID_ARG : Null arguments
  1021. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  1022. */
  1023. esp_err_t httpd_resp_set_type(httpd_req_t *r, const char *type);
  1024. /**
  1025. * @brief API to append any additional headers
  1026. *
  1027. * This API sets any additional header fields that need to be sent in the response.
  1028. *
  1029. * @note
  1030. * - This API is supposed to be called only from the context of
  1031. * a URI handler where httpd_req_t* request pointer is valid.
  1032. * - The header isn't sent out until any of the send APIs is executed.
  1033. * - The maximum allowed number of additional headers is limited to
  1034. * value of max_resp_headers in config structure.
  1035. * - Make sure that the lifetime of the field value strings are valid till
  1036. * send function is called.
  1037. *
  1038. * @param[in] r The request being responded to
  1039. * @param[in] field The field name of the HTTP header
  1040. * @param[in] value The value of this HTTP header
  1041. *
  1042. * @return
  1043. * - ESP_OK : On successfully appending new header
  1044. * - ESP_ERR_INVALID_ARG : Null arguments
  1045. * - ESP_ERR_HTTPD_RESP_HDR : Total additional headers exceed max allowed
  1046. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  1047. */
  1048. esp_err_t httpd_resp_set_hdr(httpd_req_t *r, const char *field, const char *value);
  1049. /**
  1050. * @brief For sending out error code in response to HTTP request.
  1051. *
  1052. * @note
  1053. * - This API is supposed to be called only from the context of
  1054. * a URI handler where httpd_req_t* request pointer is valid.
  1055. * - Once this API is called, all request headers are purged, so
  1056. * request headers need be copied into separate buffers if
  1057. * they are required later.
  1058. * - If you wish to send additional data in the body of the
  1059. * response, please use the lower-level functions directly.
  1060. *
  1061. * @param[in] req Pointer to the HTTP request for which the response needs to be sent
  1062. * @param[in] error Error type to send
  1063. * @param[in] msg Error message string (pass NULL for default message)
  1064. *
  1065. * @return
  1066. * - ESP_OK : On successfully sending the response packet
  1067. * - ESP_ERR_INVALID_ARG : Null arguments
  1068. * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
  1069. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  1070. */
  1071. esp_err_t httpd_resp_send_err(httpd_req_t *req, httpd_err_code_t error, const char *msg);
  1072. /**
  1073. * @brief Helper function for HTTP 404
  1074. *
  1075. * Send HTTP 404 message. If you wish to send additional data in the body of the
  1076. * response, please use the lower-level functions directly.
  1077. *
  1078. * @note
  1079. * - This API is supposed to be called only from the context of
  1080. * a URI handler where httpd_req_t* request pointer is valid.
  1081. * - Once this API is called, all request headers are purged, so
  1082. * request headers need be copied into separate buffers if
  1083. * they are required later.
  1084. *
  1085. * @param[in] r The request being responded to
  1086. *
  1087. * @return
  1088. * - ESP_OK : On successfully sending the response packet
  1089. * - ESP_ERR_INVALID_ARG : Null arguments
  1090. * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
  1091. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  1092. */
  1093. static inline esp_err_t httpd_resp_send_404(httpd_req_t *r) {
  1094. return httpd_resp_send_err(r, HTTPD_404_NOT_FOUND, NULL);
  1095. }
  1096. /**
  1097. * @brief Helper function for HTTP 408
  1098. *
  1099. * Send HTTP 408 message. If you wish to send additional data in the body of the
  1100. * response, please use the lower-level functions directly.
  1101. *
  1102. * @note
  1103. * - This API is supposed to be called only from the context of
  1104. * a URI handler where httpd_req_t* request pointer is valid.
  1105. * - Once this API is called, all request headers are purged, so
  1106. * request headers need be copied into separate buffers if
  1107. * they are required later.
  1108. *
  1109. * @param[in] r The request being responded to
  1110. *
  1111. * @return
  1112. * - ESP_OK : On successfully sending the response packet
  1113. * - ESP_ERR_INVALID_ARG : Null arguments
  1114. * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
  1115. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  1116. */
  1117. static inline esp_err_t httpd_resp_send_408(httpd_req_t *r) {
  1118. return httpd_resp_send_err(r, HTTPD_408_REQ_TIMEOUT, NULL);
  1119. }
  1120. /**
  1121. * @brief Helper function for HTTP 500
  1122. *
  1123. * Send HTTP 500 message. If you wish to send additional data in the body of the
  1124. * response, please use the lower-level functions directly.
  1125. *
  1126. * @note
  1127. * - This API is supposed to be called only from the context of
  1128. * a URI handler where httpd_req_t* request pointer is valid.
  1129. * - Once this API is called, all request headers are purged, so
  1130. * request headers need be copied into separate buffers if
  1131. * they are required later.
  1132. *
  1133. * @param[in] r The request being responded to
  1134. *
  1135. * @return
  1136. * - ESP_OK : On successfully sending the response packet
  1137. * - ESP_ERR_INVALID_ARG : Null arguments
  1138. * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
  1139. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  1140. */
  1141. static inline esp_err_t httpd_resp_send_500(httpd_req_t *r) {
  1142. return httpd_resp_send_err(r, HTTPD_500_INTERNAL_SERVER_ERROR, NULL);
  1143. }
  1144. /**
  1145. * @brief Raw HTTP send
  1146. *
  1147. * Call this API if you wish to construct your custom response packet.
  1148. * When using this, all essential header, eg. HTTP version, Status Code,
  1149. * Content Type and Length, Encoding, etc. will have to be constructed
  1150. * manually, and HTTP delimeters (CRLF) will need to be placed correctly
  1151. * for separating sub-sections of the HTTP response packet.
  1152. *
  1153. * If the send override function is set, this API will end up
  1154. * calling that function eventually to send data out.
  1155. *
  1156. * @note
  1157. * - This API is supposed to be called only from the context of
  1158. * a URI handler where httpd_req_t* request pointer is valid.
  1159. * - Unless the response has the correct HTTP structure (which the
  1160. * user must now ensure) it is not guaranteed that it will be
  1161. * recognized by the client. For most cases, you wouldn't have
  1162. * to call this API, but you would rather use either of :
  1163. * httpd_resp_send(),
  1164. * httpd_resp_send_chunk()
  1165. *
  1166. * @param[in] r The request being responded to
  1167. * @param[in] buf Buffer from where the fully constructed packet is to be read
  1168. * @param[in] buf_len Length of the buffer
  1169. *
  1170. * @return
  1171. * - Bytes : Number of bytes that were sent successfully
  1172. * - HTTPD_SOCK_ERR_INVALID : Invalid arguments
  1173. * - HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket send()
  1174. * - HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket send()
  1175. */
  1176. int httpd_send(httpd_req_t *r, const char *buf, size_t buf_len);
  1177. /** End of Request / Response
  1178. * @}
  1179. */
  1180. /* ************** Group: Session ************** */
  1181. /** @name Session
  1182. * Functions for controlling sessions and accessing context data
  1183. * @{
  1184. */
  1185. /**
  1186. * @brief Get session context from socket descriptor
  1187. *
  1188. * Typically if a session context is created, it is available to URI handlers
  1189. * through the httpd_req_t structure. But, there are cases where the web
  1190. * server's send/receive functions may require the context (for example, for
  1191. * accessing keying information etc). Since the send/receive function only have
  1192. * the socket descriptor at their disposal, this API provides them with a way to
  1193. * retrieve the session context.
  1194. *
  1195. * @param[in] handle Handle to server returned by httpd_start
  1196. * @param[in] sockfd The socket descriptor for which the context should be extracted.
  1197. *
  1198. * @return
  1199. * - void* : Pointer to the context associated with this session
  1200. * - NULL : Empty context / Invalid handle / Invalid socket fd
  1201. */
  1202. void *httpd_sess_get_ctx(httpd_handle_t handle, int sockfd);
  1203. /**
  1204. * @brief Set session context by socket descriptor
  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. * @param[in] ctx Context object to assign to the session
  1209. * @param[in] free_fn Function that should be called to free the context
  1210. */
  1211. void httpd_sess_set_ctx(httpd_handle_t handle, int sockfd, void *ctx, httpd_free_ctx_fn_t free_fn);
  1212. /**
  1213. * @brief Get session 'transport' context by socket descriptor
  1214. * @see httpd_sess_get_ctx()
  1215. *
  1216. * This context is used by the send/receive functions, for example to manage SSL context.
  1217. *
  1218. * @param[in] handle Handle to server returned by httpd_start
  1219. * @param[in] sockfd The socket descriptor for which the context should be extracted.
  1220. * @return
  1221. * - void* : Pointer to the transport context associated with this session
  1222. * - NULL : Empty context / Invalid handle / Invalid socket fd
  1223. */
  1224. void *httpd_sess_get_transport_ctx(httpd_handle_t handle, int sockfd);
  1225. /**
  1226. * @brief Set session 'transport' context by socket descriptor
  1227. * @see httpd_sess_set_ctx()
  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. * @param[in] ctx Transport context object to assign to the session
  1232. * @param[in] free_fn Function that should be called to free the transport context
  1233. */
  1234. void httpd_sess_set_transport_ctx(httpd_handle_t handle, int sockfd, void *ctx, httpd_free_ctx_fn_t free_fn);
  1235. /**
  1236. * @brief Get HTTPD global user context (it was set in the server config struct)
  1237. *
  1238. * @param[in] handle Handle to server returned by httpd_start
  1239. * @return global user context
  1240. */
  1241. void *httpd_get_global_user_ctx(httpd_handle_t handle);
  1242. /**
  1243. * @brief Get HTTPD global transport context (it was set in the server config struct)
  1244. *
  1245. * @param[in] handle Handle to server returned by httpd_start
  1246. * @return global transport context
  1247. */
  1248. void *httpd_get_global_transport_ctx(httpd_handle_t handle);
  1249. /**
  1250. * @brief Trigger an httpd session close externally
  1251. *
  1252. * @note Calling this API is only required in special circumstances wherein
  1253. * some application requires to close an httpd client session asynchronously.
  1254. *
  1255. * @param[in] handle Handle to server returned by httpd_start
  1256. * @param[in] sockfd The socket descriptor of the session to be closed
  1257. *
  1258. * @return
  1259. * - ESP_OK : On successfully initiating closure
  1260. * - ESP_FAIL : Failure to queue work
  1261. * - ESP_ERR_NOT_FOUND : Socket fd not found
  1262. * - ESP_ERR_INVALID_ARG : Null arguments
  1263. */
  1264. esp_err_t httpd_sess_trigger_close(httpd_handle_t handle, int sockfd);
  1265. /**
  1266. * @brief Update LRU counter for a given socket
  1267. *
  1268. * LRU Counters are internally associated with each session to monitor
  1269. * how recently a session exchanged traffic. When LRU purge is enabled,
  1270. * if a client is requesting for connection but maximum number of
  1271. * sockets/sessions is reached, then the session having the earliest
  1272. * LRU counter is closed automatically.
  1273. *
  1274. * Updating the LRU counter manually prevents the socket from being purged
  1275. * due to the Least Recently Used (LRU) logic, even though it might not
  1276. * have received traffic for some time. This is useful when all open
  1277. * sockets/session are frequently exchanging traffic but the user specifically
  1278. * wants one of the sessions to be kept open, irrespective of when it last
  1279. * exchanged a packet.
  1280. *
  1281. * @note Calling this API is only necessary if the LRU Purge Enable option
  1282. * is enabled.
  1283. *
  1284. * @param[in] handle Handle to server returned by httpd_start
  1285. * @param[in] sockfd The socket descriptor of the session for which LRU counter
  1286. * is to be updated
  1287. *
  1288. * @return
  1289. * - ESP_OK : Socket found and LRU counter updated
  1290. * - ESP_ERR_NOT_FOUND : Socket not found
  1291. * - ESP_ERR_INVALID_ARG : Null arguments
  1292. */
  1293. esp_err_t httpd_sess_update_lru_counter(httpd_handle_t handle, int sockfd);
  1294. /** End of Session
  1295. * @}
  1296. */
  1297. /* ************** Group: Work Queue ************** */
  1298. /** @name Work Queue
  1299. * APIs related to the HTTPD Work Queue
  1300. * @{
  1301. */
  1302. /**
  1303. * @brief Prototype of the HTTPD work function
  1304. * Please refer to httpd_queue_work() for more details.
  1305. * @param[in] arg The arguments for this work function
  1306. */
  1307. typedef void (*httpd_work_fn_t)(void *arg);
  1308. /**
  1309. * @brief Queue execution of a function in HTTPD's context
  1310. *
  1311. * This API queues a work function for asynchronous execution
  1312. *
  1313. * @note Some protocols require that the web server generate some asynchronous data
  1314. * and send it to the persistently opened connection. This facility is for use
  1315. * by such protocols.
  1316. *
  1317. * @param[in] handle Handle to server returned by httpd_start
  1318. * @param[in] work Pointer to the function to be executed in the HTTPD's context
  1319. * @param[in] arg Pointer to the arguments that should be passed to this function
  1320. *
  1321. * @return
  1322. * - ESP_OK : On successfully queueing the work
  1323. * - ESP_FAIL : Failure in ctrl socket
  1324. * - ESP_ERR_INVALID_ARG : Null arguments
  1325. */
  1326. esp_err_t httpd_queue_work(httpd_handle_t handle, httpd_work_fn_t work, void *arg);
  1327. /** End of Group Work Queue
  1328. * @}
  1329. */
  1330. #ifdef __cplusplus
  1331. }
  1332. #endif
  1333. #endif /* ! _ESP_HTTP_SERVER_H_ */