esp_http_server.h 55 KB

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