http_client.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. // Copyright 2015-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. // http://www.apache.org/licenses/LICENSE-2.0
  7. //
  8. // Unless required by applicable law or agreed to in writing, software
  9. // distributed under the License is distributed on an "AS IS" BASIS,
  10. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. // See the License for the specific language governing permissions and
  12. // limitations under the License.
  13. #ifndef __HTTP_CLIENT_H__
  14. #define __HTTP_CLIENT_H__
  15. #include <stdint.h>
  16. #include <stdbool.h>
  17. #ifdef __cplusplus
  18. extern "C" {
  19. #endif
  20. #define DEFAULT_HTTP_BUF_SIZE (512)
  21. typedef struct http_client *http_client_handle_t;
  22. typedef struct http_client_event *http_client_event_handle_t;
  23. typedef enum {
  24. HTTP_CLI_OK = 0,
  25. HTTP_CLI_FAIL = -1,
  26. HTTP_CLI_ERR_NO_MEM = 0x101, /*!< Out of memory */
  27. HTTP_CLI_ERR_INVALID_ARG = 0x102, /*!< Invalid argument */
  28. HTTP_CLI_ERR_INVALID_STATE = 0x103, /*!< Invalid state */
  29. HTTP_CLI_ERR_INVALID_SIZE = 0x104, /*!< Invalid size */
  30. HTTP_CLI_ERR_NOT_FOUND = 0x105, /*!< Requested resource not found */
  31. HTTP_CLI_ERR_NOT_SUPPORTED = 0x106, /*!< Operation or feature not supported */
  32. HTTP_CLI_ERR_TIMEOUT = 0x107, /*!< Operation timed out */
  33. HTTP_CLI_ERR_INVALID_RESPONSE = 0x108, /*!< Received response was invalid */
  34. HTTP_CLI_ERR_INVALID_CRC = 0x109, /*!< CRC or checksum was invalid */
  35. HTTP_CLI_ERR_INVALID_VERSION = 0x10A, /*!< Version was invalid */
  36. HTTP_CLI_ERR_INVALID_MAC = 0x10B /*!< MAC address was invalid */
  37. } http_errors_t;
  38. /**
  39. * @brief HTTP Client events id
  40. */
  41. typedef enum {
  42. HTTP_EVENT_ERROR = 0, /*!< This event occurs when there are any errors during execution */
  43. HTTP_EVENT_ON_CONNECTED, /*!< Once the HTTP has been connected to the server, no data exchange has been performed */
  44. HTTP_EVENT_HEADER_SENT, /*!< After sending all the headers to the server */
  45. HTTP_EVENT_ON_HEADER, /*!< Occurs when receiving each header sent from the server */
  46. HTTP_EVENT_ON_DATA, /*!< Occurs when receiving data from the server, possibly multiple portions of the packet */
  47. HTTP_EVENT_ON_FINISH, /*!< Occurs when finish a HTTP session */
  48. HTTP_EVENT_DISCONNECTED, /*!< The connection has been disconnected */
  49. } http_client_event_id_t;
  50. /**
  51. * @brief HTTP Client events data
  52. */
  53. typedef struct http_client_event {
  54. http_client_event_id_t event_id; /*!< event_id, to know the cause of the event */
  55. http_client_handle_t client; /*!< http_client_handle_t context */
  56. void *data; /*!< data of the event */
  57. int data_len; /*!< data length of data */
  58. void *user_data; /*!< user_data context, from http_client_config_t user_data */
  59. char *header_key; /*!< For HTTP_EVENT_ON_HEADER event_id, it's store current http header key */
  60. char *header_value; /*!< For HTTP_EVENT_ON_HEADER event_id, it's store current http header value */
  61. } http_client_event_t;
  62. /**
  63. * @brief HTTP Client transport
  64. */
  65. typedef enum {
  66. HTTP_TRANSPORT_UNKNOWN = 0x0, /*!< Unknown */
  67. HTTP_TRANSPORT_OVER_TCP, /*!< Transport over tcp */
  68. HTTP_TRANSPORT_OVER_SSL, /*!< Transport over ssl */
  69. } http_client_transport_t;
  70. typedef int (*http_event_handle_cb)(http_client_event_t *evt);
  71. /**
  72. * @brief HTTP method
  73. */
  74. typedef enum {
  75. HTTP_METHOD_GET = 0, /*!< HTTP GET Method */
  76. HTTP_METHOD_POST, /*!< HTTP POST Method */
  77. HTTP_METHOD_PUT, /*!< HTTP PUT Method */
  78. HTTP_METHOD_PATCH, /*!< HTTP PATCH Method */
  79. HTTP_METHOD_DELETE, /*!< HTTP DELETE Method */
  80. HTTP_METHOD_HEAD, /*!< HTTP HEAD Method */
  81. HTTP_METHOD_NOTIFY, /*!< HTTP NOTIFY Method */
  82. HTTP_METHOD_SUBSCRIBE, /*!< HTTP SUBSCRIBE Method */
  83. HTTP_METHOD_UNSUBSCRIBE,/*!< HTTP UNSUBSCRIBE Method */
  84. HTTP_METHOD_OPTIONS, /*!< HTTP OPTIONS Method */
  85. HTTP_METHOD_MAX,
  86. } http_client_method_t;
  87. /**
  88. * @brief HTTP Authentication type
  89. */
  90. typedef enum {
  91. HTTP_AUTH_TYPE_NONE = 0, /*!< No authention */
  92. HTTP_AUTH_TYPE_BASIC, /*!< HTTP Basic authentication */
  93. HTTP_AUTH_TYPE_DIGEST, /*!< HTTP Disgest authentication */
  94. } http_client_auth_type_t;
  95. /**
  96. * @brief HTTP configuration
  97. */
  98. typedef struct {
  99. const char *url; /*!< HTTP URL, the information on the URL is most important, it overrides the other fields below, if any */
  100. const char *host; /*!< Domain or IP as string */
  101. int port; /*!< Port to connect, default depend on http_client_transport_t (80 or 443) */
  102. const char *username; /*!< Using for Http authentication */
  103. const char *password; /*!< Using for Http authentication */
  104. http_client_auth_type_t auth_type; /*!< Http authentication type, see `http_client_auth_type_t` */
  105. const char *path; /*!< HTTP Path, if not set, default is `/` */
  106. const char *query; /*!< HTTP query */
  107. const char *cert_pem; /*!< SSL server certification, PEM format as string, if the client requires to verify server */
  108. const char *client_cert_pem; /*!< SSL client certification, PEM format as string, if the server requires to verify client */
  109. const char *client_key_pem; /*!< SSL client key, PEM format as string, if the server requires to verify client */
  110. http_client_method_t method; /*!< HTTP Method */
  111. int timeout_ms; /*!< Network timeout in milliseconds */
  112. bool disable_auto_redirect; /*!< Disable HTTP automatic redirects */
  113. int max_redirection_count; /*!< Max redirection number, using default value if zero*/
  114. http_event_handle_cb event_handler; /*!< HTTP Event Handle */
  115. http_client_transport_t transport_type; /*!< HTTP transport type, see `http_client_transport_t` */
  116. int buffer_size; /*!< HTTP buffer size (both send and receive) */
  117. void *user_data; /*!< HTTP user_data context */
  118. bool is_async; /*!< Set asynchronous mode, only supported with HTTPS for now */
  119. bool use_global_ca_store; /*!< Use a global ca_store for all the connections in which this bool is set. */
  120. } http_client_config_t;
  121. /**
  122. * Enum for the HTTP status codes.
  123. */
  124. typedef enum {
  125. /* 3xx - Redirection */
  126. HttpStatus_MovedPermanently = 301,
  127. HttpStatus_Found = 302,
  128. HttpStatus_TemporaryRedirect = 307,
  129. /* 4xx - Client Error */
  130. HttpStatus_Unauthorized = 401,
  131. HttpStatus_Forbidden = 403,
  132. HttpStatus_NotFound = 404,
  133. /* 5xx - Server Error */
  134. HttpStatus_InternalError = 500
  135. } HttpStatus_Code;
  136. /**
  137. * @brief Start a HTTP session
  138. * This function must be the first function to call,
  139. * and it returns a http_client_handle_t that you must use as input to other functions in the interface.
  140. * This call MUST have a corresponding call to http_client_cleanup when the operation is complete.
  141. *
  142. * @param[in] config The configurations, see `http_client_config_t`
  143. *
  144. * @return
  145. * - `http_client_handle_t`
  146. * - NULL if any errors
  147. */
  148. http_client_handle_t http_client_init(const http_client_config_t *config);
  149. /**
  150. * @brief Invoke this function after `http_client_init` and all the options calls are made, and will perform the
  151. * transfer as described in the options. It must be called with the same http_client_handle_t as input as the http_client_init call returned.
  152. * http_client_perform performs the entire request in either blocking or non-blocking manner. By default, the API performs request in a blocking manner and returns when done,
  153. * or if it failed, and in non-blocking manner, it returns if EAGAIN/EWOULDBLOCK or EINPROGRESS is encountered, or if it failed. And in case of non-blocking request,
  154. * the user may call this API multiple times unless request & response is complete or there is a failure. To enable non-blocking http_client_perform(), `is_async` member of http_client_config_t
  155. * must be set while making a call to http_client_init() API.
  156. * You can do any amount of calls to http_client_perform while using the same http_client_handle_t. The underlying connection may be kept open if the server allows it.
  157. * If you intend to transfer more than one file, you are even encouraged to do so.
  158. * http_client will then attempt to re-use the same connection for the following transfers, thus making the operations faster, less CPU intense and using less network resources.
  159. * Just note that you will have to use `http_client_set_**` between the invokes to set options for the following http_client_perform.
  160. *
  161. * @note You must never call this function simultaneously from two places using the same client handle.
  162. * Let the function return first before invoking it another time.
  163. * If you want parallel transfers, you must use several http_client_handle_t.
  164. * This function include `http_client_open` -> `http_client_write` -> `http_client_fetch_headers` -> `http_client_read` (and option) `http_client_close`.
  165. *
  166. * @param client The http_client handle
  167. *
  168. * @return
  169. * - HTTP_CLI_OK on successful
  170. * - HTTP_CLI_FAIL on error
  171. */
  172. http_errors_t http_client_perform(http_client_handle_t client);
  173. /**
  174. * @brief Set URL for client, when performing this behavior, the options in the URL will replace the old ones
  175. *
  176. * @param[in] client The http_client handle
  177. * @param[in] url The url
  178. *
  179. * @return
  180. * - HTTP_CLI_OK
  181. * - HTTP_CLI_FAIL
  182. */
  183. http_errors_t http_client_set_url(http_client_handle_t client, const char *url);
  184. /**
  185. * @brief Set post data, this function must be called before `http_client_perform`.
  186. * Note: The data parameter passed to this function is a pointer and this function will not copy the data
  187. *
  188. * @param[in] client The http_client handle
  189. * @param[in] data post data pointer
  190. * @param[in] len post length
  191. *
  192. * @return
  193. * - HTTP_CLI_OK
  194. * - HTTP_CLI_FAIL
  195. */
  196. http_errors_t http_client_set_post_field(http_client_handle_t client, const char *data, int len);
  197. /**
  198. * @brief Get current post field information
  199. *
  200. * @param[in] client The client
  201. * @param[out] data Point to post data pointer
  202. *
  203. * @return Size of post data
  204. */
  205. int http_client_get_post_field(http_client_handle_t client, char **data);
  206. /**
  207. * @brief Set http request header, this function must be called after http_client_init and before any
  208. * perform function
  209. *
  210. * @param[in] client The http_client handle
  211. * @param[in] key The header key
  212. * @param[in] value The header value
  213. *
  214. * @return
  215. * - HTTP_CLI_OK
  216. * - HTTP_CLI_FAIL
  217. */
  218. http_errors_t http_client_set_header(http_client_handle_t client, const char *key, const char *value);
  219. /**
  220. * @brief Get http request header.
  221. * The value parameter will be set to NULL if there is no header which is same as
  222. * the key specified, otherwise the address of header value will be assigned to value parameter.
  223. * This function must be called after `http_client_init`.
  224. *
  225. * @param[in] client The http_client handle
  226. * @param[in] key The header key
  227. * @param[out] value The header value
  228. *
  229. * @return
  230. * - HTTP_CLI_OK
  231. * - HTTP_CLI_FAIL
  232. */
  233. http_errors_t http_client_get_header(http_client_handle_t client, const char *key, char **value);
  234. /**
  235. * @brief Get http request username.
  236. * The address of username buffer will be assigned to value parameter.
  237. * This function must be called after `http_client_init`.
  238. *
  239. * @param[in] client The http_client handle
  240. * @param[out] value The username value
  241. *
  242. * @return
  243. * - HTTP_CLI_OK
  244. * - HTTP_CLI_ERR_INVALID_ARG
  245. */
  246. http_errors_t http_client_get_username(http_client_handle_t client, char **value);
  247. /**
  248. * @brief Get http request password.
  249. * The address of password buffer will be assigned to value parameter.
  250. * This function must be called after `http_client_init`.
  251. *
  252. * @param[in] client The http_client handle
  253. * @param[out] value The password value
  254. *
  255. * @return
  256. * - HTTP_CLI_OK
  257. * - HTTP_CLI_ERR_INVALID_ARG
  258. */
  259. http_errors_t http_client_get_password(http_client_handle_t client, char **value);
  260. /**
  261. * @brief Set http request method
  262. *
  263. * @param[in] client The http_client handle
  264. * @param[in] method The method
  265. *
  266. * @return
  267. * - HTTP_CLI_OK
  268. * - HTTP_CLI_ERR_INVALID_ARG
  269. */
  270. http_errors_t http_client_set_method(http_client_handle_t client, http_client_method_t method);
  271. /**
  272. * @brief Delete http request header
  273. *
  274. * @param[in] client The http_client handle
  275. * @param[in] key The key
  276. *
  277. * @return
  278. * - HTTP_CLI_OK
  279. * - HTTP_CLI_FAIL
  280. */
  281. http_errors_t http_client_delete_header(http_client_handle_t client, const char *key);
  282. /**
  283. * @brief This function will be open the connection, write all header strings and return
  284. *
  285. * @param[in] client The http_client handle
  286. * @param[in] write_len HTTP Content length need to write to the server
  287. *
  288. * @return
  289. * - HTTP_CLI_OK
  290. * - HTTP_CLI_FAIL
  291. */
  292. http_errors_t http_client_open(http_client_handle_t client, int write_len);
  293. /**
  294. * @brief This function will write data to the HTTP connection previously opened by http_client_open()
  295. *
  296. * @param[in] client The http_client handle
  297. * @param buffer The buffer
  298. * @param[in] len This value must not be larger than the write_len parameter provided to http_client_open()
  299. *
  300. * @return
  301. * - (-1) if any errors
  302. * - Length of data written
  303. */
  304. int http_client_write(http_client_handle_t client, const char *buffer, int len);
  305. /**
  306. * @brief This function need to call after http_client_open, it will read from http stream, process all receive headers
  307. *
  308. * @param[in] client The http_client handle
  309. *
  310. * @return
  311. * - (0) if stream doesn't contain content-length header, or chunked encoding (checked by `http_client_is_chunked` response)
  312. * - (-1: HTTP_CLI_FAIL) if any errors
  313. * - Download data length defined by content-length header
  314. */
  315. int http_client_fetch_headers(http_client_handle_t client);
  316. /**
  317. * @brief Check response data is chunked
  318. *
  319. * @param[in] client The http_client handle
  320. *
  321. * @return true or false
  322. */
  323. bool http_client_is_chunked_response(http_client_handle_t client);
  324. /**
  325. * @brief Read data from http stream
  326. *
  327. * @param[in] client The http_client handle
  328. * @param buffer The buffer
  329. * @param[in] len The length
  330. *
  331. * @return
  332. * - (-1) if any errors
  333. * - Length of data was read
  334. */
  335. int http_client_read(http_client_handle_t client, char *buffer, int len);
  336. /**
  337. * @brief Get http response status code, the valid value if this function invoke after `http_client_perform`
  338. *
  339. * @param[in] client The http_client handle
  340. *
  341. * @return Status code
  342. */
  343. int http_client_get_status_code(http_client_handle_t client);
  344. /**
  345. * @brief Get http response content length (from header Content-Length)
  346. * the valid value if this function invoke after `http_client_perform`
  347. *
  348. * @param[in] client The http_client handle
  349. *
  350. * @return
  351. * - (-1) Chunked transfer
  352. * - Content-Length value as bytes
  353. */
  354. int http_client_get_content_length(http_client_handle_t client);
  355. /**
  356. * @brief Close http connection, still kept all http request resources
  357. *
  358. * @param[in] client The http_client handle
  359. *
  360. * @return
  361. * - HTTP_CLI_OK
  362. * - HTTP_CLI_FAIL
  363. */
  364. http_errors_t http_client_close(http_client_handle_t client);
  365. /**
  366. * @brief This function must be the last function to call for an session.
  367. * It is the opposite of the http_client_init function and must be called with the same handle as input that a http_client_init call returned.
  368. * This might close all connections this handle has used and possibly has kept open until now.
  369. * Don't call this function if you intend to transfer more files, re-using handles is a key to good performance with http_client.
  370. *
  371. * @param[in] client The http_client handle
  372. *
  373. * @return
  374. * - HTTP_CLI_OK
  375. * - HTTP_CLI_FAIL
  376. */
  377. http_errors_t http_client_cleanup(http_client_handle_t client);
  378. /**
  379. * @brief Get transport type
  380. *
  381. * @param[in] client The http_client handle
  382. *
  383. * @return
  384. * - HTTP_TRANSPORT_UNKNOWN
  385. * - HTTP_TRANSPORT_OVER_TCP
  386. * - HTTP_TRANSPORT_OVER_SSL
  387. */
  388. http_client_transport_t http_client_get_transport_type(http_client_handle_t client);
  389. /**
  390. * @brief Set redirection URL.
  391. * When received the 30x code from the server, the client stores the redirect URL provided by the server.
  392. * This function will set the current URL to redirect to enable client to execute the redirection request.
  393. *
  394. * @param[in] client The http_client handle
  395. *
  396. * @return
  397. * - HTTP_CLI_OK
  398. * - HTTP_CLI_FAIL
  399. */
  400. http_errors_t http_client_set_redirection(http_client_handle_t client);
  401. /**
  402. * @brief Checks if entire data in the response has been read without any error.
  403. *
  404. * @param[in] client The http_client handle
  405. *
  406. * @return
  407. * - true
  408. * - false
  409. */
  410. bool http_client_is_complete_data_received(http_client_handle_t client);
  411. /**
  412. * @brief Helper API to read larger data chunks
  413. * This is a helper API which internally calls `http_client_read` multiple times till the end of data is reached or till the buffer gets full.
  414. *
  415. * @param[in] client The http_client handle
  416. * @param buffer The buffer
  417. * @param[in] len The buffer length
  418. *
  419. * @return
  420. * - Length of data was read
  421. */
  422. int http_client_read_response(http_client_handle_t client, char *buffer, int len);
  423. #ifdef __cplusplus
  424. }
  425. #endif
  426. #endif