esp_http_server.h 55 KB

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