esp_http_server.h 63 KB

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