esp_http_server.h 61 KB

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