esp_http_server.h 49 KB

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