esp_http_client.c 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782
  1. /*
  2. * SPDX-FileCopyrightText: 2015-2023 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. #include <string.h>
  7. #include <inttypes.h>
  8. #include "esp_log.h"
  9. #include "esp_assert.h"
  10. #include "esp_check.h"
  11. #include "http_parser.h"
  12. #include "http_header.h"
  13. #include "esp_transport.h"
  14. #include "esp_transport_tcp.h"
  15. #include "http_utils.h"
  16. #include "http_auth.h"
  17. #include "sdkconfig.h"
  18. #include "esp_http_client.h"
  19. #include "errno.h"
  20. #include "esp_random.h"
  21. #include "esp_tls.h"
  22. #ifdef CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS
  23. #include "esp_transport_ssl.h"
  24. #endif
  25. ESP_EVENT_DEFINE_BASE(ESP_HTTP_CLIENT_EVENT);
  26. static const char *TAG = "HTTP_CLIENT";
  27. ESP_STATIC_ASSERT((int)ESP_HTTP_CLIENT_TLS_VER_ANY == (int)ESP_TLS_VER_ANY, "Enum mismatch in esp_http_client and esp-tls");
  28. ESP_STATIC_ASSERT((int)ESP_HTTP_CLIENT_TLS_VER_MAX <= (int)ESP_TLS_VER_TLS_MAX, "HTTP client supported TLS is not supported in esp-tls");
  29. /**
  30. * HTTP Buffer
  31. */
  32. typedef struct {
  33. char *data; /*!< The HTTP data received from the server */
  34. int len; /*!< The HTTP data len received from the server */
  35. char *raw_data; /*!< The HTTP data after decoding */
  36. char *orig_raw_data;/*!< The Original pointer to HTTP data after decoding */
  37. int raw_len; /*!< The HTTP data len after decoding */
  38. char *output_ptr; /*!< The destination address of the data to be copied to after decoding */
  39. } esp_http_buffer_t;
  40. /**
  41. * private HTTP Data structure
  42. */
  43. typedef struct {
  44. http_header_handle_t headers; /*!< http header */
  45. esp_http_buffer_t *buffer; /*!< data buffer as linked list */
  46. int status_code; /*!< status code (integer) */
  47. int64_t content_length; /*!< data length */
  48. int chunk_length; /*!< chunk length */
  49. int data_offset; /*!< offset to http data (Skip header) */
  50. int64_t data_process; /*!< data processed */
  51. int method; /*!< http method */
  52. bool is_chunked;
  53. } esp_http_data_t;
  54. typedef struct {
  55. char *url;
  56. char *scheme;
  57. char *host;
  58. int port;
  59. char *username;
  60. char *password;
  61. char *path;
  62. char *query;
  63. char *cert_pem;
  64. esp_http_client_method_t method;
  65. esp_http_client_auth_type_t auth_type;
  66. esp_http_client_transport_t transport_type;
  67. int max_store_header_size;
  68. } connection_info_t;
  69. typedef enum {
  70. HTTP_STATE_UNINIT = 0,
  71. HTTP_STATE_INIT,
  72. HTTP_STATE_CONNECTED,
  73. HTTP_STATE_REQ_COMPLETE_HEADER,
  74. HTTP_STATE_REQ_COMPLETE_DATA,
  75. HTTP_STATE_RES_COMPLETE_HEADER,
  76. HTTP_STATE_RES_ON_DATA_START,
  77. HTTP_STATE_RES_COMPLETE_DATA,
  78. HTTP_STATE_CLOSE
  79. } esp_http_state_t;
  80. /**
  81. * HTTP client class
  82. */
  83. struct esp_http_client {
  84. int redirect_counter;
  85. int max_redirection_count;
  86. int max_authorization_retries;
  87. int process_again;
  88. struct http_parser *parser;
  89. struct http_parser_settings *parser_settings;
  90. esp_transport_list_handle_t transport_list;
  91. esp_transport_handle_t transport;
  92. esp_http_data_t *request;
  93. esp_http_data_t *response;
  94. void *user_data;
  95. esp_http_auth_data_t *auth_data;
  96. char *post_data;
  97. char *location;
  98. char *auth_header;
  99. char *current_header_key;
  100. char *current_header_value;
  101. int post_len;
  102. connection_info_t connection_info;
  103. bool is_chunk_complete;
  104. esp_http_state_t state;
  105. http_event_handle_cb event_handler;
  106. int timeout_ms;
  107. int buffer_size_rx;
  108. int buffer_size_tx;
  109. bool disable_auto_redirect;
  110. esp_http_client_event_t event;
  111. int data_written_index;
  112. int data_write_left;
  113. bool first_line_prepared;
  114. int header_index;
  115. bool is_async;
  116. esp_transport_keep_alive_t keep_alive_cfg;
  117. struct ifreq *if_name;
  118. unsigned cache_data_in_fetch_hdr: 1;
  119. };
  120. typedef struct esp_http_client esp_http_client_t;
  121. static esp_err_t _clear_connection_info(esp_http_client_handle_t client);
  122. /**
  123. * Default settings
  124. */
  125. #define DEFAULT_HTTP_PORT (80)
  126. #define DEFAULT_HTTPS_PORT (443)
  127. #define ASYNC_TRANS_CONNECT_FAIL -1
  128. #define ASYNC_TRANS_CONNECTING 0
  129. #define ASYNC_TRANS_CONNECT_PASS 1
  130. static const char *DEFAULT_HTTP_USER_AGENT = "ESP32 HTTP Client/1.0";
  131. static const char *DEFAULT_HTTP_PROTOCOL = "HTTP/1.1";
  132. static const char *DEFAULT_HTTP_PATH = "/";
  133. static const int DEFAULT_MAX_REDIRECT = 10;
  134. static const int DEFAULT_MAX_AUTH_RETRIES = 10;
  135. static const int DEFAULT_TIMEOUT_MS = 5000;
  136. static const int DEFAULT_KEEP_ALIVE_IDLE = 5;
  137. static const int DEFAULT_KEEP_ALIVE_INTERVAL= 5;
  138. static const int DEFAULT_KEEP_ALIVE_COUNT= 3;
  139. static const char *HTTP_METHOD_MAPPING[] = {
  140. "GET",
  141. "POST",
  142. "PUT",
  143. "PATCH",
  144. "DELETE",
  145. "HEAD",
  146. "NOTIFY",
  147. "SUBSCRIBE",
  148. "UNSUBSCRIBE",
  149. "OPTIONS",
  150. "COPY",
  151. "MOVE",
  152. "LOCK",
  153. "UNLOCK",
  154. "PROPFIND",
  155. "PROPPATCH",
  156. "MKCOL"
  157. };
  158. static esp_err_t esp_http_client_request_send(esp_http_client_handle_t client, int write_len);
  159. static esp_err_t esp_http_client_connect(esp_http_client_handle_t client);
  160. static esp_err_t esp_http_client_send_post_data(esp_http_client_handle_t client);
  161. static esp_err_t http_dispatch_event(esp_http_client_t *client, esp_http_client_event_id_t event_id, void *data, int len)
  162. {
  163. esp_http_client_event_t *event = &client->event;
  164. if (client->event_handler) {
  165. event->event_id = event_id;
  166. event->user_data = client->user_data;
  167. event->data = data;
  168. event->data_len = len;
  169. return client->event_handler(event);
  170. }
  171. return ESP_OK;
  172. }
  173. static void http_dispatch_event_to_event_loop(int32_t event_id, const void* event_data, size_t event_data_size)
  174. {
  175. esp_err_t err = esp_event_post(ESP_HTTP_CLIENT_EVENT, event_id, event_data, event_data_size, portMAX_DELAY);
  176. if (err != ESP_OK) {
  177. ESP_LOGE(TAG, "Failed to post https_ota event: %"PRId32", error: %s", event_id, esp_err_to_name(err));
  178. }
  179. }
  180. static int http_on_message_begin(http_parser *parser)
  181. {
  182. esp_http_client_t *client = parser->data;
  183. ESP_LOGD(TAG, "on_message_begin");
  184. client->response->is_chunked = false;
  185. client->is_chunk_complete = false;
  186. return 0;
  187. }
  188. static int http_on_url(http_parser *parser, const char *at, size_t length)
  189. {
  190. ESP_LOGD(TAG, "http_on_url");
  191. return 0;
  192. }
  193. static int http_on_status(http_parser *parser, const char *at, size_t length)
  194. {
  195. return 0;
  196. }
  197. static int http_on_header_event(esp_http_client_handle_t client)
  198. {
  199. if (client->current_header_key != NULL && client->current_header_value != NULL) {
  200. ESP_LOGD(TAG, "HEADER=%s:%s", client->current_header_key, client->current_header_value);
  201. client->event.header_key = client->current_header_key;
  202. client->event.header_value = client->current_header_value;
  203. http_dispatch_event(client, HTTP_EVENT_ON_HEADER, NULL, 0);
  204. http_dispatch_event_to_event_loop(HTTP_EVENT_ON_HEADER, &client, sizeof(esp_http_client_handle_t));
  205. free(client->current_header_key);
  206. free(client->current_header_value);
  207. client->current_header_key = NULL;
  208. client->current_header_value = NULL;
  209. }
  210. return 0;
  211. }
  212. static int http_on_header_field(http_parser *parser, const char *at, size_t length)
  213. {
  214. esp_http_client_t *client = parser->data;
  215. http_utils_append_string(&client->current_header_key, at, length);
  216. return 0;
  217. }
  218. static int http_on_header_value(http_parser *parser, const char *at, size_t length)
  219. {
  220. esp_http_client_handle_t client = parser->data;
  221. if (client->current_header_key == NULL) {
  222. return 0;
  223. }
  224. if (strcasecmp(client->current_header_key, "Location") == 0) {
  225. http_utils_append_string(&client->location, at, length);
  226. } else if (strcasecmp(client->current_header_key, "Transfer-Encoding") == 0
  227. && memcmp(at, "chunked", length) == 0) {
  228. client->response->is_chunked = true;
  229. } else if (strcasecmp(client->current_header_key, "WWW-Authenticate") == 0) {
  230. http_utils_append_string(&client->auth_header, at, length);
  231. }
  232. http_utils_append_string(&client->current_header_value, at, length);
  233. http_on_header_event(client);
  234. return 0;
  235. }
  236. static int http_on_headers_complete(http_parser *parser)
  237. {
  238. esp_http_client_handle_t client = parser->data;
  239. http_on_header_event(client);
  240. client->response->status_code = parser->status_code;
  241. client->response->data_offset = parser->nread;
  242. client->response->content_length = parser->content_length;
  243. client->response->data_process = 0;
  244. ESP_LOGD(TAG, "http_on_headers_complete, status=%d, offset=%d, nread=%" PRId32, parser->status_code, client->response->data_offset, parser->nread);
  245. client->state = HTTP_STATE_RES_COMPLETE_HEADER;
  246. if (client->connection_info.method == HTTP_METHOD_HEAD) {
  247. /* In a HTTP_RESPONSE parser returning '1' from on_headers_complete will tell the
  248. parser that it should not expect a body. This is used when receiving a response
  249. to a HEAD request which may contain 'Content-Length' or 'Transfer-Encoding: chunked'
  250. headers that indicate the presence of a body.*/
  251. return 1;
  252. }
  253. return 0;
  254. }
  255. static int http_on_body(http_parser *parser, const char *at, size_t length)
  256. {
  257. esp_http_client_t *client = parser->data;
  258. ESP_LOGD(TAG, "http_on_body %zu", length);
  259. if (client->response->buffer->output_ptr) {
  260. memcpy(client->response->buffer->output_ptr, (char *)at, length);
  261. client->response->buffer->output_ptr += length;
  262. } else {
  263. /* Do not cache body when http_on_body is called from esp_http_client_perform */
  264. if (client->state < HTTP_STATE_RES_ON_DATA_START && client->cache_data_in_fetch_hdr) {
  265. ESP_LOGD(TAG, "Body received in fetch header state, %p, %zu", at, length);
  266. esp_http_buffer_t *res_buffer = client->response->buffer;
  267. assert(res_buffer->orig_raw_data == res_buffer->raw_data);
  268. res_buffer->orig_raw_data = (char *)realloc(res_buffer->orig_raw_data, res_buffer->raw_len + length);
  269. if (!res_buffer->orig_raw_data) {
  270. ESP_LOGE(TAG, "Failed to allocate memory for storing decoded data");
  271. return -1;
  272. }
  273. memcpy(res_buffer->orig_raw_data + res_buffer->raw_len, at, length);
  274. res_buffer->raw_data = res_buffer->orig_raw_data;
  275. }
  276. }
  277. client->response->data_process += length;
  278. client->response->buffer->raw_len += length;
  279. http_dispatch_event(client, HTTP_EVENT_ON_DATA, (void *)at, length);
  280. esp_http_client_on_data_t evt_data = {};
  281. evt_data.data_process = client->response->data_process;
  282. evt_data.client = client;
  283. http_dispatch_event_to_event_loop(HTTP_EVENT_ON_DATA, &evt_data, sizeof(esp_http_client_on_data_t));
  284. return 0;
  285. }
  286. static int http_on_message_complete(http_parser *parser)
  287. {
  288. ESP_LOGD(TAG, "http_on_message_complete, parser=%p", parser);
  289. esp_http_client_handle_t client = parser->data;
  290. client->is_chunk_complete = true;
  291. return 0;
  292. }
  293. static int http_on_chunk_complete(http_parser *parser)
  294. {
  295. ESP_LOGD(TAG, "http_on_chunk_complete");
  296. return 0;
  297. }
  298. static int http_on_chunk_header(http_parser *parser)
  299. {
  300. esp_http_client_handle_t client = parser->data;
  301. client->response->chunk_length = parser->content_length;
  302. ESP_LOGD(TAG, "http_on_chunk_header, chunk_length");
  303. return 0;
  304. }
  305. esp_err_t esp_http_client_set_header(esp_http_client_handle_t client, const char *key, const char *value)
  306. {
  307. return http_header_set(client->request->headers, key, value);
  308. }
  309. esp_err_t esp_http_client_get_header(esp_http_client_handle_t client, const char *key, char **value)
  310. {
  311. return http_header_get(client->request->headers, key, value);
  312. }
  313. esp_err_t esp_http_client_delete_header(esp_http_client_handle_t client, const char *key)
  314. {
  315. return http_header_delete(client->request->headers, key);
  316. }
  317. esp_err_t esp_http_client_get_username(esp_http_client_handle_t client, char **value)
  318. {
  319. if (client == NULL || value == NULL) {
  320. ESP_LOGE(TAG, "client or value must not be NULL");
  321. return ESP_ERR_INVALID_ARG;
  322. }
  323. *value = client->connection_info.username;
  324. return ESP_OK;
  325. }
  326. esp_err_t esp_http_client_set_username(esp_http_client_handle_t client, const char *username)
  327. {
  328. if (client == NULL) {
  329. ESP_LOGE(TAG, "client must not be NULL");
  330. return ESP_ERR_INVALID_ARG;
  331. }
  332. if (client->connection_info.username != NULL) {
  333. free(client->connection_info.username);
  334. }
  335. client->connection_info.username = username ? strdup(username) : NULL;
  336. return ESP_OK;
  337. }
  338. esp_err_t esp_http_client_get_password(esp_http_client_handle_t client, char **value)
  339. {
  340. if (client == NULL || value == NULL) {
  341. ESP_LOGE(TAG, "client or value must not be NULL");
  342. return ESP_ERR_INVALID_ARG;
  343. }
  344. *value = client->connection_info.password;
  345. return ESP_OK;
  346. }
  347. esp_err_t esp_http_client_cancel_request(esp_http_client_handle_t client)
  348. {
  349. if (client == NULL) {
  350. ESP_LOGD(TAG, "Client handle is NULL");
  351. return ESP_ERR_INVALID_ARG;
  352. }
  353. if (client->state < HTTP_STATE_CONNECTED) {
  354. ESP_LOGD(TAG, "Invalid State: %d", client->state);
  355. return ESP_ERR_INVALID_STATE;
  356. }
  357. if (esp_transport_close(client->transport) != 0) {
  358. return ESP_FAIL;
  359. }
  360. esp_err_t err = esp_http_client_connect(client);
  361. // esp_http_client_connect() will return ESP_ERR_HTTP_CONNECTING in case of non-blocking mode and if the connection has not been established.
  362. if (err == ESP_OK || (client->is_async && err == ESP_ERR_HTTP_CONNECTING)) {
  363. client->response->data_process = client->response->content_length;
  364. return ESP_OK;
  365. }
  366. return ESP_FAIL;
  367. }
  368. esp_err_t esp_http_client_set_password(esp_http_client_handle_t client, const char *password)
  369. {
  370. if (client == NULL) {
  371. ESP_LOGE(TAG, "client must not be NULL");
  372. return ESP_ERR_INVALID_ARG;
  373. }
  374. if (client->connection_info.password != NULL) {
  375. memset(client->connection_info.password, 0, strlen(client->connection_info.password));
  376. free(client->connection_info.password);
  377. }
  378. client->connection_info.password = password ? strdup(password) : NULL;
  379. return ESP_OK;
  380. }
  381. esp_err_t esp_http_client_set_authtype(esp_http_client_handle_t client, esp_http_client_auth_type_t auth_type)
  382. {
  383. if (client == NULL) {
  384. ESP_LOGE(TAG, "client must not be NULL");
  385. return ESP_ERR_INVALID_ARG;
  386. }
  387. client->connection_info.auth_type = auth_type;
  388. return ESP_OK;
  389. }
  390. esp_err_t esp_http_client_get_user_data(esp_http_client_handle_t client, void **data)
  391. {
  392. if (NULL == client || NULL == data) {
  393. ESP_LOGE(TAG, "client or data must not be NULL");
  394. return ESP_ERR_INVALID_ARG;
  395. }
  396. *data = client->user_data;
  397. return ESP_OK;
  398. }
  399. esp_err_t esp_http_client_set_user_data(esp_http_client_handle_t client, void *data)
  400. {
  401. if (NULL == client) {
  402. ESP_LOGE(TAG, "client must not be NULL");
  403. return ESP_ERR_INVALID_ARG;
  404. }
  405. client->user_data = data;
  406. return ESP_OK;
  407. }
  408. static esp_err_t _set_config(esp_http_client_handle_t client, const esp_http_client_config_t *config)
  409. {
  410. esp_err_t ret = ESP_OK;
  411. client->connection_info.method = config->method;
  412. client->connection_info.port = config->port;
  413. client->connection_info.auth_type = config->auth_type;
  414. client->event_handler = config->event_handler;
  415. client->timeout_ms = config->timeout_ms;
  416. client->max_redirection_count = config->max_redirection_count;
  417. client->max_authorization_retries = config->max_authorization_retries;
  418. client->user_data = config->user_data;
  419. client->buffer_size_rx = config->buffer_size;
  420. client->buffer_size_tx = config->buffer_size_tx;
  421. client->disable_auto_redirect = config->disable_auto_redirect;
  422. if (config->buffer_size == 0) {
  423. client->buffer_size_rx = DEFAULT_HTTP_BUF_SIZE;
  424. }
  425. if (config->buffer_size_tx == 0) {
  426. client->buffer_size_tx = DEFAULT_HTTP_BUF_SIZE;
  427. }
  428. if (client->max_redirection_count == 0) {
  429. client->max_redirection_count = DEFAULT_MAX_REDIRECT;
  430. }
  431. if (client->max_authorization_retries == 0) {
  432. client->max_authorization_retries = DEFAULT_MAX_AUTH_RETRIES;
  433. } else if (client->max_authorization_retries == -1) {
  434. client->max_authorization_retries = 0;
  435. }
  436. if (config->path) {
  437. client->connection_info.path = strdup(config->path);
  438. } else {
  439. client->connection_info.path = strdup(DEFAULT_HTTP_PATH);
  440. }
  441. ESP_RETURN_ON_FALSE(client->connection_info.path, ESP_ERR_NO_MEM, TAG, "Memory exhausted");
  442. if (config->host) {
  443. client->connection_info.host = strdup(config->host);
  444. ESP_GOTO_ON_FALSE(client->connection_info.host, ESP_ERR_NO_MEM, error, TAG, "Memory exhausted");
  445. }
  446. if (config->query) {
  447. client->connection_info.query = strdup(config->query);
  448. ESP_GOTO_ON_FALSE(client->connection_info.query, ESP_ERR_NO_MEM, error, TAG, "Memory exhausted");
  449. }
  450. if (config->username) {
  451. client->connection_info.username = strdup(config->username);
  452. ESP_GOTO_ON_FALSE(client->connection_info.username, ESP_ERR_NO_MEM, error, TAG, "Memory exhausted");
  453. }
  454. if (config->password) {
  455. client->connection_info.password = strdup(config->password);
  456. ESP_GOTO_ON_FALSE(client->connection_info.password, ESP_ERR_NO_MEM, error, TAG, "Memory exhausted");
  457. }
  458. if (config->transport_type == HTTP_TRANSPORT_OVER_SSL) {
  459. http_utils_assign_string(&client->connection_info.scheme, "https", -1);
  460. if (client->connection_info.port == 0) {
  461. client->connection_info.port = DEFAULT_HTTPS_PORT;
  462. }
  463. } else {
  464. http_utils_assign_string(&client->connection_info.scheme, "http", -1);
  465. if (client->connection_info.port == 0) {
  466. client->connection_info.port = DEFAULT_HTTP_PORT;
  467. }
  468. }
  469. if (client->timeout_ms == 0) {
  470. client->timeout_ms = DEFAULT_TIMEOUT_MS;
  471. }
  472. if (config->is_async) {
  473. client->is_async = true;
  474. }
  475. return ret;
  476. error:
  477. _clear_connection_info(client);
  478. return ret;
  479. }
  480. static esp_err_t _clear_connection_info(esp_http_client_handle_t client)
  481. {
  482. free(client->connection_info.path);
  483. free(client->connection_info.host);
  484. free(client->connection_info.query);
  485. free(client->connection_info.username);
  486. if (client->connection_info.password) {
  487. memset(client->connection_info.password, 0, strlen(client->connection_info.password));
  488. free(client->connection_info.password);
  489. }
  490. free(client->connection_info.scheme);
  491. free(client->connection_info.url);
  492. memset(&client->connection_info, 0, sizeof(connection_info_t));
  493. return ESP_OK;
  494. }
  495. static esp_err_t _clear_auth_data(esp_http_client_handle_t client)
  496. {
  497. if (client->auth_data == NULL) {
  498. return ESP_FAIL;
  499. }
  500. free(client->auth_data->method);
  501. free(client->auth_data->realm);
  502. free(client->auth_data->algorithm);
  503. free(client->auth_data->qop);
  504. free(client->auth_data->nonce);
  505. free(client->auth_data->opaque);
  506. memset(client->auth_data, 0, sizeof(esp_http_auth_data_t));
  507. return ESP_OK;
  508. }
  509. static esp_err_t esp_http_client_prepare(esp_http_client_handle_t client)
  510. {
  511. client->process_again = 0;
  512. client->response->data_process = 0;
  513. client->first_line_prepared = false;
  514. /**
  515. * Clear location field before making a new HTTP request. Location
  516. * field should not be cleared in http_on_header* callbacks because
  517. * callbacks can be invoked multiple times for same header, and
  518. * hence can lead to data corruption.
  519. */
  520. if (client->location != NULL) {
  521. free(client->location);
  522. client->location = NULL;
  523. }
  524. if (client->auth_header != NULL) {
  525. free(client->auth_header);
  526. client->auth_header = NULL;
  527. }
  528. http_parser_init(client->parser, HTTP_RESPONSE);
  529. if (client->connection_info.username) {
  530. char *auth_response = NULL;
  531. if (client->connection_info.auth_type == HTTP_AUTH_TYPE_BASIC) {
  532. auth_response = http_auth_basic(client->connection_info.username, client->connection_info.password);
  533. #ifdef CONFIG_ESP_HTTP_CLIENT_ENABLE_DIGEST_AUTH
  534. } else if (client->connection_info.auth_type == HTTP_AUTH_TYPE_DIGEST && client->auth_data) {
  535. client->auth_data->uri = client->connection_info.path;
  536. client->auth_data->cnonce = ((uint64_t)esp_random() << 32) + esp_random();
  537. auth_response = http_auth_digest(client->connection_info.username, client->connection_info.password, client->auth_data);
  538. client->auth_data->nc ++;
  539. #endif
  540. }
  541. if (auth_response) {
  542. ESP_LOGD(TAG, "auth_response=%s", auth_response);
  543. esp_http_client_set_header(client, "Authorization", auth_response);
  544. free(auth_response);
  545. }
  546. }
  547. return ESP_OK;
  548. }
  549. static char *_get_host_header(char *host, int port)
  550. {
  551. int err = 0;
  552. char *host_name;
  553. if (port != DEFAULT_HTTP_PORT && port != DEFAULT_HTTPS_PORT) {
  554. err = asprintf(&host_name, "%s:%d", host, port);
  555. } else {
  556. err = asprintf(&host_name, "%s", host);
  557. }
  558. if (err == -1) {
  559. return NULL;
  560. }
  561. return host_name;
  562. }
  563. static bool init_common_tcp_transport(esp_http_client_handle_t client, const esp_http_client_config_t *config, esp_transport_handle_t transport)
  564. {
  565. if (config->keep_alive_enable == true) {
  566. client->keep_alive_cfg.keep_alive_enable = true;
  567. client->keep_alive_cfg.keep_alive_idle = (config->keep_alive_idle == 0) ? DEFAULT_KEEP_ALIVE_IDLE : config->keep_alive_idle;
  568. client->keep_alive_cfg.keep_alive_interval = (config->keep_alive_interval == 0) ? DEFAULT_KEEP_ALIVE_INTERVAL : config->keep_alive_interval;
  569. client->keep_alive_cfg.keep_alive_count = (config->keep_alive_count == 0) ? DEFAULT_KEEP_ALIVE_COUNT : config->keep_alive_count;
  570. esp_transport_tcp_set_keep_alive(transport, &client->keep_alive_cfg);
  571. }
  572. if (config->if_name) {
  573. client->if_name = calloc(1, sizeof(struct ifreq));
  574. ESP_RETURN_ON_FALSE(client->if_name, false, TAG, "Memory exhausted");
  575. memcpy(client->if_name, config->if_name, sizeof(struct ifreq));
  576. esp_transport_tcp_set_interface_name(transport, client->if_name);
  577. }
  578. return true;
  579. }
  580. esp_http_client_handle_t esp_http_client_init(const esp_http_client_config_t *config)
  581. {
  582. esp_http_client_handle_t client;
  583. esp_err_t ret = ESP_OK;
  584. esp_transport_handle_t tcp = NULL;
  585. char *host_name;
  586. bool _success;
  587. _success = (
  588. (client = calloc(1, sizeof(esp_http_client_t))) &&
  589. (client->parser = calloc(1, sizeof(struct http_parser))) &&
  590. (client->parser_settings = calloc(1, sizeof(struct http_parser_settings))) &&
  591. (client->auth_data = calloc(1, sizeof(esp_http_auth_data_t))) &&
  592. (client->request = calloc(1, sizeof(esp_http_data_t))) &&
  593. (client->request->headers = http_header_init()) &&
  594. (client->request->buffer = calloc(1, sizeof(esp_http_buffer_t))) &&
  595. (client->response = calloc(1, sizeof(esp_http_data_t))) &&
  596. (client->response->headers = http_header_init()) &&
  597. (client->response->buffer = calloc(1, sizeof(esp_http_buffer_t)))
  598. );
  599. if (!_success) {
  600. ESP_LOGE(TAG, "Error allocate memory");
  601. goto error;
  602. }
  603. _success = (
  604. (client->transport_list = esp_transport_list_init()) &&
  605. (tcp = esp_transport_tcp_init()) &&
  606. (esp_transport_set_default_port(tcp, DEFAULT_HTTP_PORT) == ESP_OK) &&
  607. (esp_transport_list_add(client->transport_list, tcp, "http") == ESP_OK)
  608. );
  609. if (!_success) {
  610. ESP_LOGE(TAG, "Error initialize transport");
  611. goto error;
  612. }
  613. ESP_GOTO_ON_FALSE(init_common_tcp_transport(client, config, tcp), ESP_FAIL, error, TAG, "Failed to set TCP config");
  614. #ifdef CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS
  615. esp_transport_handle_t ssl = NULL;
  616. _success = (
  617. (ssl = esp_transport_ssl_init()) &&
  618. (esp_transport_set_default_port(ssl, DEFAULT_HTTPS_PORT) == ESP_OK) &&
  619. (esp_transport_list_add(client->transport_list, ssl, "https") == ESP_OK)
  620. );
  621. if (!_success) {
  622. ESP_LOGE(TAG, "Error initialize SSL Transport");
  623. goto error;
  624. }
  625. ESP_GOTO_ON_FALSE(init_common_tcp_transport(client, config, ssl), ESP_FAIL, error, TAG, "Failed to set SSL config");
  626. if (config->crt_bundle_attach != NULL) {
  627. #ifdef CONFIG_MBEDTLS_CERTIFICATE_BUNDLE
  628. esp_transport_ssl_crt_bundle_attach(ssl, config->crt_bundle_attach);
  629. #else //CONFIG_MBEDTLS_CERTIFICATE_BUNDLE
  630. ESP_LOGE(TAG, "use_crt_bundle configured but not enabled in menuconfig: Please enable MBEDTLS_CERTIFICATE_BUNDLE option");
  631. #endif
  632. } else if (config->use_global_ca_store == true) {
  633. esp_transport_ssl_enable_global_ca_store(ssl);
  634. } else if (config->cert_pem) {
  635. if (!config->cert_len) {
  636. esp_transport_ssl_set_cert_data(ssl, config->cert_pem, strlen(config->cert_pem));
  637. } else {
  638. esp_transport_ssl_set_cert_data_der(ssl, config->cert_pem, config->cert_len);
  639. }
  640. }
  641. if (config->client_cert_pem) {
  642. if (!config->client_cert_len) {
  643. esp_transport_ssl_set_client_cert_data(ssl, config->client_cert_pem, strlen(config->client_cert_pem));
  644. } else {
  645. esp_transport_ssl_set_client_cert_data_der(ssl, config->client_cert_pem, config->client_cert_len);
  646. }
  647. }
  648. esp_transport_ssl_set_tls_version(ssl, config->tls_version);
  649. #if CONFIG_ESP_TLS_USE_SECURE_ELEMENT
  650. if (config->use_secure_element) {
  651. esp_transport_ssl_use_secure_element(ssl);
  652. }
  653. #endif
  654. #if CONFIG_ESP_TLS_USE_DS_PERIPHERAL
  655. if (config->ds_data != NULL) {
  656. esp_transport_ssl_set_ds_data(ssl, config->ds_data);
  657. }
  658. #endif
  659. if (config->client_key_pem) {
  660. if (!config->client_key_len) {
  661. esp_transport_ssl_set_client_key_data(ssl, config->client_key_pem, strlen(config->client_key_pem));
  662. } else {
  663. esp_transport_ssl_set_client_key_data_der(ssl, config->client_key_pem, config->client_key_len);
  664. }
  665. }
  666. #ifdef CONFIG_MBEDTLS_HARDWARE_ECDSA_SIGN
  667. if (config->use_ecdsa_peripheral) {
  668. esp_transport_ssl_set_client_key_ecdsa_peripheral(ssl, config->ecdsa_key_efuse_blk);
  669. }
  670. #endif
  671. if (config->client_key_password && config->client_key_password_len > 0) {
  672. esp_transport_ssl_set_client_key_password(ssl, config->client_key_password, config->client_key_password_len);
  673. }
  674. if (config->skip_cert_common_name_check) {
  675. esp_transport_ssl_skip_common_name_check(ssl);
  676. }
  677. if (config->common_name) {
  678. esp_transport_ssl_set_common_name(ssl, config->common_name);
  679. }
  680. #endif
  681. if (_set_config(client, config) != ESP_OK) {
  682. ESP_LOGE(TAG, "Error set configurations");
  683. goto error;
  684. }
  685. _success = (
  686. (client->request->buffer->data = malloc(client->buffer_size_tx)) &&
  687. (client->response->buffer->data = malloc(client->buffer_size_rx))
  688. );
  689. if (!_success) {
  690. ESP_LOGE(TAG, "Allocation failed");
  691. goto error;
  692. }
  693. const char *user_agent = config->user_agent == NULL ? DEFAULT_HTTP_USER_AGENT : config->user_agent;
  694. if (config->host != NULL && config->path != NULL) {
  695. if (client->connection_info.host == NULL) {
  696. ESP_LOGE(TAG, "invalid host");
  697. goto error;
  698. }
  699. host_name = _get_host_header(client->connection_info.host, client->connection_info.port);
  700. if (host_name == NULL) {
  701. ESP_LOGE(TAG, "Failed to allocate memory for host header");
  702. goto error;
  703. }
  704. _success = (
  705. (esp_http_client_set_header(client, "User-Agent", user_agent) == ESP_OK) &&
  706. (esp_http_client_set_header(client, "Host", host_name) == ESP_OK)
  707. );
  708. free(host_name);
  709. if (!_success) {
  710. ESP_LOGE(TAG, "Error while setting default configurations");
  711. goto error;
  712. }
  713. } else if (config->url != NULL) {
  714. if (esp_http_client_set_url(client, config->url) != ESP_OK) {
  715. ESP_LOGE(TAG, "Failed to set URL");
  716. goto error;
  717. }
  718. if (client->connection_info.host == NULL) {
  719. ESP_LOGE(TAG, "invalid host");
  720. goto error;
  721. }
  722. host_name = _get_host_header(client->connection_info.host, client->connection_info.port);
  723. if (host_name == NULL) {
  724. ESP_LOGE(TAG, "Failed to allocate memory for host header");
  725. goto error;
  726. }
  727. _success = (
  728. (esp_http_client_set_header(client, "User-Agent", user_agent) == ESP_OK) &&
  729. (esp_http_client_set_header(client, "Host", host_name) == ESP_OK)
  730. );
  731. free(host_name);
  732. if (!_success) {
  733. ESP_LOGE(TAG, "Error while setting default configurations");
  734. goto error;
  735. }
  736. } else {
  737. ESP_LOGE(TAG, "config should have either URL or host & path");
  738. goto error;
  739. }
  740. /* As default behavior, cache data received in fetch header state. This will be
  741. * used in esp_http_client_read API only. For esp_http_perform we shall disable
  742. * this as data will be processed by event handler */
  743. client->cache_data_in_fetch_hdr = 1;
  744. client->parser_settings->on_message_begin = http_on_message_begin;
  745. client->parser_settings->on_url = http_on_url;
  746. client->parser_settings->on_status = http_on_status;
  747. client->parser_settings->on_header_field = http_on_header_field;
  748. client->parser_settings->on_header_value = http_on_header_value;
  749. client->parser_settings->on_headers_complete = http_on_headers_complete;
  750. client->parser_settings->on_body = http_on_body;
  751. client->parser_settings->on_message_complete = http_on_message_complete;
  752. client->parser_settings->on_chunk_complete = http_on_chunk_complete;
  753. client->parser_settings->on_chunk_header = http_on_chunk_header;
  754. client->parser->data = client;
  755. client->event.client = client;
  756. client->state = HTTP_STATE_INIT;
  757. if (ret == ESP_OK) {
  758. return client;
  759. }
  760. error:
  761. esp_http_client_cleanup(client);
  762. return NULL;
  763. }
  764. static void esp_http_client_cached_buf_cleanup(esp_http_buffer_t *res_buffer)
  765. {
  766. /* Free cached data if any, that was received during fetch header stage */
  767. if (res_buffer && res_buffer->orig_raw_data) {
  768. free(res_buffer->orig_raw_data);
  769. res_buffer->orig_raw_data = NULL;
  770. res_buffer->raw_data = NULL;
  771. res_buffer->raw_len = 0;
  772. }
  773. }
  774. esp_err_t esp_http_client_cleanup(esp_http_client_handle_t client)
  775. {
  776. if (client == NULL) {
  777. return ESP_FAIL;
  778. }
  779. esp_http_client_close(client);
  780. if (client->transport_list) {
  781. esp_transport_list_destroy(client->transport_list);
  782. }
  783. if (client->request) {
  784. http_header_destroy(client->request->headers);
  785. if (client->request->buffer) {
  786. free(client->request->buffer->data);
  787. }
  788. free(client->request->buffer);
  789. free(client->request);
  790. }
  791. if (client->response) {
  792. http_header_destroy(client->response->headers);
  793. if (client->response->buffer) {
  794. free(client->response->buffer->data);
  795. esp_http_client_cached_buf_cleanup(client->response->buffer);
  796. }
  797. free(client->response->buffer);
  798. free(client->response);
  799. }
  800. if (client->if_name) {
  801. free(client->if_name);
  802. }
  803. free(client->parser);
  804. free(client->parser_settings);
  805. _clear_connection_info(client);
  806. _clear_auth_data(client);
  807. free(client->auth_data);
  808. free(client->current_header_key);
  809. free(client->location);
  810. free(client->auth_header);
  811. free(client);
  812. return ESP_OK;
  813. }
  814. esp_err_t esp_http_client_set_redirection(esp_http_client_handle_t client)
  815. {
  816. if (client == NULL) {
  817. return ESP_ERR_INVALID_ARG;
  818. }
  819. if (client->location == NULL) {
  820. return ESP_ERR_INVALID_ARG;
  821. }
  822. ESP_LOGD(TAG, "Redirect to %s", client->location);
  823. esp_err_t err = esp_http_client_set_url(client, client->location);
  824. if (err == ESP_OK) {
  825. client->redirect_counter ++;
  826. client->process_again = 1; // used only in the blocking mode (when esp_http_client_perform() is called)
  827. }
  828. return err;
  829. }
  830. static esp_err_t esp_http_check_response(esp_http_client_handle_t client)
  831. {
  832. if (client->response->status_code >= HttpStatus_Ok && client->response->status_code < HttpStatus_MultipleChoices) {
  833. return ESP_OK;
  834. }
  835. if (client->redirect_counter >= client->max_redirection_count) {
  836. ESP_LOGE(TAG, "Error, reach max_redirection_count count=%d", client->redirect_counter);
  837. return ESP_ERR_HTTP_MAX_REDIRECT;
  838. }
  839. switch (client->response->status_code) {
  840. case HttpStatus_MovedPermanently:
  841. case HttpStatus_Found:
  842. case HttpStatus_SeeOther:
  843. case HttpStatus_TemporaryRedirect:
  844. case HttpStatus_PermanentRedirect:
  845. if (client->disable_auto_redirect) {
  846. http_dispatch_event(client, HTTP_EVENT_REDIRECT, NULL, 0);
  847. } else {
  848. if (esp_http_client_set_redirection(client) != ESP_OK){
  849. return ESP_FAIL;
  850. };
  851. }
  852. esp_http_client_redirect_event_data_t evt_data = {
  853. .status_code = client->response->status_code,
  854. .client = client,
  855. };
  856. http_dispatch_event_to_event_loop(HTTP_EVENT_REDIRECT, &evt_data, sizeof(esp_http_client_redirect_event_data_t));
  857. break;
  858. case HttpStatus_Unauthorized:
  859. esp_http_client_add_auth(client);
  860. }
  861. return ESP_OK;
  862. }
  863. esp_err_t esp_http_client_set_url(esp_http_client_handle_t client, const char *url)
  864. {
  865. esp_err_t ret = ESP_OK;
  866. char *old_host = NULL;
  867. struct http_parser_url purl;
  868. int old_port;
  869. if (client == NULL || url == NULL) {
  870. ESP_LOGE(TAG, "client or url must not NULL");
  871. return ESP_ERR_INVALID_ARG;
  872. }
  873. http_parser_url_init(&purl);
  874. int parser_status = http_parser_parse_url(url, strlen(url), 0, &purl);
  875. if (parser_status != 0) {
  876. ESP_LOGE(TAG, "Error parse url %s", url);
  877. return ESP_ERR_INVALID_ARG;
  878. }
  879. if (client->connection_info.host) {
  880. old_host = strdup(client->connection_info.host);
  881. }
  882. old_port = client->connection_info.port;
  883. if (purl.field_data[UF_HOST].len) {
  884. http_utils_assign_string(&client->connection_info.host, url + purl.field_data[UF_HOST].off, purl.field_data[UF_HOST].len);
  885. ESP_GOTO_ON_FALSE(client->connection_info.host, ESP_ERR_NO_MEM, error, TAG, "Memory exhausted");
  886. }
  887. // Close the connection if host was changed
  888. if (old_host && client->connection_info.host
  889. && strcasecmp(old_host, (const void *)client->connection_info.host) != 0) {
  890. ESP_LOGD(TAG, "New host assign = %s", client->connection_info.host);
  891. if (esp_http_client_set_header(client, "Host", client->connection_info.host) != ESP_OK) {
  892. free(old_host);
  893. return ESP_ERR_NO_MEM;
  894. }
  895. /* Free cached data if any, as we are closing this connection */
  896. esp_http_client_cached_buf_cleanup(client->response->buffer);
  897. esp_http_client_close(client);
  898. }
  899. if (old_host) {
  900. free(old_host);
  901. old_host = NULL;
  902. }
  903. if (purl.field_data[UF_SCHEMA].len) {
  904. http_utils_assign_string(&client->connection_info.scheme, url + purl.field_data[UF_SCHEMA].off, purl.field_data[UF_SCHEMA].len);
  905. ESP_RETURN_ON_FALSE(client->connection_info.scheme, ESP_ERR_NO_MEM, TAG, "Memory exhausted");
  906. if (strcasecmp(client->connection_info.scheme, "http") == 0) {
  907. client->connection_info.port = DEFAULT_HTTP_PORT;
  908. } else if (strcasecmp(client->connection_info.scheme, "https") == 0) {
  909. client->connection_info.port = DEFAULT_HTTPS_PORT;
  910. }
  911. }
  912. if (purl.field_data[UF_PORT].len) {
  913. client->connection_info.port = strtol((const char*)(url + purl.field_data[UF_PORT].off), NULL, 10);
  914. }
  915. if (old_port != client->connection_info.port) {
  916. /* Free cached data if any, as we are closing this connection */
  917. esp_http_client_cached_buf_cleanup(client->response->buffer);
  918. esp_http_client_close(client);
  919. }
  920. if (purl.field_data[UF_USERINFO].len) {
  921. char *user_info = NULL;
  922. http_utils_assign_string(&user_info, url + purl.field_data[UF_USERINFO].off, purl.field_data[UF_USERINFO].len);
  923. if (user_info) {
  924. char *username = user_info;
  925. char *password = strchr(user_info, ':');
  926. if (password) {
  927. *password = 0;
  928. password ++;
  929. http_utils_assign_string(&client->connection_info.password, password, -1);
  930. ESP_RETURN_ON_FALSE(client->connection_info.password, ESP_ERR_NO_MEM, TAG, "Memory exhausted");
  931. }
  932. http_utils_assign_string(&client->connection_info.username, username, -1);
  933. ESP_RETURN_ON_FALSE(client->connection_info.username, ESP_ERR_NO_MEM, TAG, "Memory exhausted");
  934. free(user_info);
  935. } else {
  936. return ESP_ERR_NO_MEM;
  937. }
  938. }
  939. //Reset path and query if there are no information
  940. if (purl.field_data[UF_PATH].len) {
  941. http_utils_assign_string(&client->connection_info.path, url + purl.field_data[UF_PATH].off, purl.field_data[UF_PATH].len);
  942. } else {
  943. http_utils_assign_string(&client->connection_info.path, "/", -1);
  944. }
  945. ESP_RETURN_ON_FALSE(client->connection_info.path, ESP_ERR_NO_MEM, TAG, "Memory exhausted");
  946. if (purl.field_data[UF_QUERY].len) {
  947. http_utils_assign_string(&client->connection_info.query, url + purl.field_data[UF_QUERY].off, purl.field_data[UF_QUERY].len);
  948. ESP_RETURN_ON_FALSE(client->connection_info.query, ESP_ERR_NO_MEM, TAG, "Memory exhausted");
  949. } else if (client->connection_info.query) {
  950. free(client->connection_info.query);
  951. client->connection_info.query = NULL;
  952. }
  953. return ret;
  954. error:
  955. free(old_host);
  956. return ret;
  957. }
  958. int esp_http_client_get_errno(esp_http_client_handle_t client)
  959. {
  960. if (!client) {
  961. ESP_LOGE(TAG, "Invalid client handle");
  962. return -1;
  963. }
  964. return esp_transport_get_errno(client->transport);
  965. }
  966. esp_err_t esp_http_client_set_method(esp_http_client_handle_t client, esp_http_client_method_t method)
  967. {
  968. client->connection_info.method = method;
  969. return ESP_OK;
  970. }
  971. esp_err_t esp_http_client_set_timeout_ms(esp_http_client_handle_t client, int timeout_ms)
  972. {
  973. if (client == NULL) {
  974. return ESP_ERR_INVALID_ARG;
  975. }
  976. client->timeout_ms = timeout_ms;
  977. return ESP_OK;
  978. }
  979. static int esp_http_client_get_data(esp_http_client_handle_t client)
  980. {
  981. if (client->state < HTTP_STATE_RES_ON_DATA_START) {
  982. return ESP_FAIL;
  983. }
  984. if (client->connection_info.method == HTTP_METHOD_HEAD) {
  985. return 0;
  986. }
  987. esp_http_buffer_t *res_buffer = client->response->buffer;
  988. ESP_LOGD(TAG, "data_process=%"PRId64", content_length=%"PRId64, client->response->data_process, client->response->content_length);
  989. int rlen = esp_transport_read(client->transport, res_buffer->data, client->buffer_size_rx, client->timeout_ms);
  990. if (rlen >= 0) {
  991. http_parser_execute(client->parser, client->parser_settings, res_buffer->data, rlen);
  992. }
  993. return rlen;
  994. }
  995. bool esp_http_client_is_complete_data_received(esp_http_client_handle_t client)
  996. {
  997. if (client->response->is_chunked) {
  998. if (!client->is_chunk_complete) {
  999. ESP_LOGD(TAG, "Chunks were not completely read");
  1000. return false;
  1001. }
  1002. } else {
  1003. if (client->response->data_process != client->response->content_length) {
  1004. ESP_LOGD(TAG, "Data processed %"PRId64" != Data specified in content length %"PRId64, client->response->data_process, client->response->content_length);
  1005. return false;
  1006. }
  1007. }
  1008. return true;
  1009. }
  1010. int esp_http_client_read(esp_http_client_handle_t client, char *buffer, int len)
  1011. {
  1012. esp_http_buffer_t *res_buffer = client->response->buffer;
  1013. int rlen = ESP_FAIL, ridx = 0;
  1014. if (res_buffer->raw_len) {
  1015. int remain_len = client->response->buffer->raw_len;
  1016. if (remain_len > len) {
  1017. remain_len = len;
  1018. }
  1019. memcpy(buffer, res_buffer->raw_data, remain_len);
  1020. res_buffer->raw_len -= remain_len;
  1021. res_buffer->raw_data += remain_len;
  1022. ridx = remain_len;
  1023. if (res_buffer->raw_len == 0) {
  1024. esp_http_client_cached_buf_cleanup(res_buffer);
  1025. }
  1026. }
  1027. int need_read = len - ridx;
  1028. bool is_data_remain = true;
  1029. while (need_read > 0 && is_data_remain) {
  1030. if (client->response->is_chunked) {
  1031. is_data_remain = !client->is_chunk_complete;
  1032. } else {
  1033. is_data_remain = client->response->data_process < client->response->content_length;
  1034. }
  1035. ESP_LOGD(TAG, "is_data_remain=%d, is_chunked=%d, content_length=%"PRId64, is_data_remain, client->response->is_chunked, client->response->content_length);
  1036. if (!is_data_remain) {
  1037. break;
  1038. }
  1039. int byte_to_read = need_read;
  1040. if (byte_to_read > client->buffer_size_rx) {
  1041. byte_to_read = client->buffer_size_rx;
  1042. }
  1043. errno = 0;
  1044. rlen = esp_transport_read(client->transport, res_buffer->data, byte_to_read, client->timeout_ms);
  1045. ESP_LOGD(TAG, "need_read=%d, byte_to_read=%d, rlen=%d, ridx=%d", need_read, byte_to_read, rlen, ridx);
  1046. if (rlen <= 0) {
  1047. if (errno != 0) {
  1048. esp_log_level_t sev = ESP_LOG_WARN;
  1049. /* Check for cleanly closed connection */
  1050. if (rlen == ERR_TCP_TRANSPORT_CONNECTION_CLOSED_BY_FIN && client->response->is_chunked) {
  1051. /* Explicit call to parser for invoking `message_complete` callback */
  1052. http_parser_execute(client->parser, client->parser_settings, res_buffer->data, 0);
  1053. /* ...and lowering the message severity, as closed connection from server side is expected in chunked transport */
  1054. sev = ESP_LOG_DEBUG;
  1055. }
  1056. ESP_LOG_LEVEL(sev, TAG, "esp_transport_read returned:%d and errno:%d ", rlen, errno);
  1057. }
  1058. if (rlen == ERR_TCP_TRANSPORT_CONNECTION_TIMEOUT) {
  1059. ESP_LOGD(TAG, "Connection timed out before data was ready!");
  1060. /* Returning the number of bytes read upto the point where connection timed out */
  1061. if (ridx) {
  1062. return ridx;
  1063. }
  1064. return -ESP_ERR_HTTP_EAGAIN;
  1065. }
  1066. if (rlen != ERR_TCP_TRANSPORT_CONNECTION_CLOSED_BY_FIN) {
  1067. esp_err_t err = esp_transport_translate_error(rlen);
  1068. ESP_LOGE(TAG, "transport_read: error - %d | %s", err, esp_err_to_name(err));
  1069. }
  1070. if (rlen < 0 && ridx == 0 && !esp_http_client_is_complete_data_received(client)) {
  1071. http_dispatch_event(client, HTTP_EVENT_ERROR, esp_transport_get_error_handle(client->transport), 0);
  1072. http_dispatch_event_to_event_loop(HTTP_EVENT_ERROR, &client, sizeof(esp_http_client_handle_t));
  1073. return ESP_FAIL;
  1074. }
  1075. return ridx;
  1076. }
  1077. res_buffer->output_ptr = buffer + ridx;
  1078. http_parser_execute(client->parser, client->parser_settings, res_buffer->data, rlen);
  1079. ridx += res_buffer->raw_len;
  1080. need_read -= res_buffer->raw_len;
  1081. res_buffer->raw_len = 0; //clear
  1082. res_buffer->output_ptr = NULL;
  1083. }
  1084. return ridx;
  1085. }
  1086. esp_err_t esp_http_client_perform(esp_http_client_handle_t client)
  1087. {
  1088. esp_err_t err;
  1089. do {
  1090. if (client->process_again) {
  1091. esp_http_client_prepare(client);
  1092. }
  1093. switch (client->state) {
  1094. /* In case of blocking esp_http_client_perform(), the following states will fall through one after the after;
  1095. in case of non-blocking esp_http_client_perform(), if there is an error condition, like EINPROGRESS or EAGAIN,
  1096. then the esp_http_client_perform() API will return ESP_ERR_HTTP_EAGAIN error. The user may call
  1097. esp_http_client_perform API again, and for this reason, we maintain the states */
  1098. case HTTP_STATE_INIT:
  1099. if ((err = esp_http_client_connect(client)) != ESP_OK) {
  1100. if (client->is_async && err == ESP_ERR_HTTP_CONNECTING) {
  1101. return ESP_ERR_HTTP_EAGAIN;
  1102. }
  1103. http_dispatch_event(client, HTTP_EVENT_ERROR, esp_transport_get_error_handle(client->transport), 0);
  1104. http_dispatch_event_to_event_loop(HTTP_EVENT_ERROR, &client, sizeof(esp_http_client_handle_t));
  1105. return err;
  1106. }
  1107. /* falls through */
  1108. case HTTP_STATE_CONNECTED:
  1109. if ((err = esp_http_client_request_send(client, client->post_len)) != ESP_OK) {
  1110. if (client->is_async && errno == EAGAIN) {
  1111. return ESP_ERR_HTTP_EAGAIN;
  1112. }
  1113. http_dispatch_event(client, HTTP_EVENT_ERROR, esp_transport_get_error_handle(client->transport), 0);
  1114. http_dispatch_event_to_event_loop(HTTP_EVENT_ERROR, &client, sizeof(esp_http_client_handle_t));
  1115. return err;
  1116. }
  1117. /* falls through */
  1118. case HTTP_STATE_REQ_COMPLETE_HEADER:
  1119. if ((err = esp_http_client_send_post_data(client)) != ESP_OK) {
  1120. if (client->is_async && errno == EAGAIN) {
  1121. return ESP_ERR_HTTP_EAGAIN;
  1122. }
  1123. http_dispatch_event(client, HTTP_EVENT_ERROR, esp_transport_get_error_handle(client->transport), 0);
  1124. http_dispatch_event_to_event_loop(HTTP_EVENT_ERROR, &client, sizeof(esp_http_client_handle_t));
  1125. return err;
  1126. }
  1127. /* falls through */
  1128. case HTTP_STATE_REQ_COMPLETE_DATA:
  1129. /* Disable caching response body, as data should
  1130. * be handled by application event handler */
  1131. client->cache_data_in_fetch_hdr = 0;
  1132. int64_t ret = esp_http_client_fetch_headers(client);
  1133. if (ret < 0) {
  1134. if ((client->is_async && errno == EAGAIN) || ret == -ESP_ERR_HTTP_EAGAIN) {
  1135. return ESP_ERR_HTTP_EAGAIN;
  1136. }
  1137. /* Enable caching after error condition because next
  1138. * request could be performed using native APIs */
  1139. client->cache_data_in_fetch_hdr = 1;
  1140. if (esp_transport_get_errno(client->transport) == ENOTCONN) {
  1141. ESP_LOGW(TAG, "Close connection due to FIN received");
  1142. esp_http_client_close(client);
  1143. http_dispatch_event(client, HTTP_EVENT_ERROR, esp_transport_get_error_handle(client->transport), 0);
  1144. http_dispatch_event_to_event_loop(HTTP_EVENT_ERROR, &client, sizeof(esp_http_client_handle_t));
  1145. return ESP_ERR_HTTP_CONNECTION_CLOSED;
  1146. }
  1147. http_dispatch_event(client, HTTP_EVENT_ERROR, esp_transport_get_error_handle(client->transport), 0);
  1148. http_dispatch_event_to_event_loop(HTTP_EVENT_ERROR, &client, sizeof(esp_http_client_handle_t));
  1149. return ESP_ERR_HTTP_FETCH_HEADER;
  1150. }
  1151. /* falls through */
  1152. case HTTP_STATE_RES_ON_DATA_START:
  1153. /* Enable caching after fetch headers state because next
  1154. * request could be performed using native APIs */
  1155. client->cache_data_in_fetch_hdr = 1;
  1156. if ((err = esp_http_check_response(client)) != ESP_OK) {
  1157. ESP_LOGE(TAG, "Error response");
  1158. http_dispatch_event(client, HTTP_EVENT_ERROR, esp_transport_get_error_handle(client->transport), 0);
  1159. http_dispatch_event_to_event_loop(HTTP_EVENT_ERROR, &client, sizeof(esp_http_client_handle_t));
  1160. return err;
  1161. }
  1162. while (client->response->is_chunked && !client->is_chunk_complete) {
  1163. if (esp_http_client_get_data(client) <= 0) {
  1164. if (client->is_async && errno == EAGAIN) {
  1165. return ESP_ERR_HTTP_EAGAIN;
  1166. }
  1167. ESP_LOGD(TAG, "Read finish or server requests close");
  1168. break;
  1169. }
  1170. }
  1171. while (client->response->data_process < client->response->content_length) {
  1172. if (esp_http_client_get_data(client) <= 0) {
  1173. if (client->is_async && errno == EAGAIN) {
  1174. return ESP_ERR_HTTP_EAGAIN;
  1175. }
  1176. ESP_LOGD(TAG, "Read finish or server requests close");
  1177. break;
  1178. }
  1179. }
  1180. http_dispatch_event(client, HTTP_EVENT_ON_FINISH, NULL, 0);
  1181. http_dispatch_event_to_event_loop(HTTP_EVENT_ON_FINISH, &client, sizeof(esp_http_client_handle_t));
  1182. client->response->buffer->raw_len = 0;
  1183. if (!http_should_keep_alive(client->parser)) {
  1184. ESP_LOGD(TAG, "Close connection");
  1185. esp_http_client_close(client);
  1186. } else {
  1187. if (client->state > HTTP_STATE_CONNECTED) {
  1188. client->state = HTTP_STATE_CONNECTED;
  1189. client->first_line_prepared = false;
  1190. }
  1191. }
  1192. break;
  1193. default:
  1194. break;
  1195. }
  1196. } while (client->process_again);
  1197. return ESP_OK;
  1198. }
  1199. int64_t esp_http_client_fetch_headers(esp_http_client_handle_t client)
  1200. {
  1201. if (client->state < HTTP_STATE_REQ_COMPLETE_HEADER) {
  1202. return ESP_FAIL;
  1203. }
  1204. client->state = HTTP_STATE_REQ_COMPLETE_DATA;
  1205. esp_http_buffer_t *buffer = client->response->buffer;
  1206. client->response->status_code = -1;
  1207. while (client->state < HTTP_STATE_RES_COMPLETE_HEADER) {
  1208. buffer->len = esp_transport_read(client->transport, buffer->data, client->buffer_size_rx, client->timeout_ms);
  1209. if (buffer->len <= 0) {
  1210. if (buffer->len == ERR_TCP_TRANSPORT_CONNECTION_TIMEOUT) {
  1211. ESP_LOGW(TAG, "Connection timed out before data was ready!");
  1212. return -ESP_ERR_HTTP_EAGAIN;
  1213. }
  1214. return ESP_FAIL;
  1215. }
  1216. http_parser_execute(client->parser, client->parser_settings, buffer->data, buffer->len);
  1217. }
  1218. client->state = HTTP_STATE_RES_ON_DATA_START;
  1219. ESP_LOGD(TAG, "content_length = %"PRId64, client->response->content_length);
  1220. if (client->response->content_length <= 0) {
  1221. client->response->is_chunked = true;
  1222. return 0;
  1223. }
  1224. return client->response->content_length;
  1225. }
  1226. static esp_err_t esp_http_client_connect(esp_http_client_handle_t client)
  1227. {
  1228. esp_err_t err;
  1229. if (client->state == HTTP_STATE_UNINIT) {
  1230. ESP_LOGE(TAG, "Client has not been initialized");
  1231. return ESP_ERR_INVALID_STATE;
  1232. }
  1233. if ((err = esp_http_client_prepare(client)) != ESP_OK) {
  1234. ESP_LOGE(TAG, "Failed to initialize request data");
  1235. esp_http_client_close(client);
  1236. return err;
  1237. }
  1238. if (client->state < HTTP_STATE_CONNECTED) {
  1239. ESP_LOGD(TAG, "Begin connect to: %s://%s:%d", client->connection_info.scheme, client->connection_info.host, client->connection_info.port);
  1240. client->transport = esp_transport_list_get_transport(client->transport_list, client->connection_info.scheme);
  1241. if (client->transport == NULL) {
  1242. ESP_LOGE(TAG, "No transport found");
  1243. #ifndef CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS
  1244. if (strcasecmp(client->connection_info.scheme, "https") == 0) {
  1245. ESP_LOGE(TAG, "Please enable HTTPS at menuconfig to allow requesting via https");
  1246. }
  1247. #endif
  1248. return ESP_ERR_HTTP_INVALID_TRANSPORT;
  1249. }
  1250. if (!client->is_async) {
  1251. if (esp_transport_connect(client->transport, client->connection_info.host, client->connection_info.port, client->timeout_ms) < 0) {
  1252. ESP_LOGE(TAG, "Connection failed, sock < 0");
  1253. return ESP_ERR_HTTP_CONNECT;
  1254. }
  1255. } else {
  1256. int ret = esp_transport_connect_async(client->transport, client->connection_info.host, client->connection_info.port, client->timeout_ms);
  1257. if (ret == ASYNC_TRANS_CONNECT_FAIL) {
  1258. ESP_LOGE(TAG, "Connection failed");
  1259. if (strcasecmp(client->connection_info.scheme, "http") == 0) {
  1260. ESP_LOGE(TAG, "Asynchronous mode doesn't work for HTTP based connection");
  1261. return ESP_ERR_INVALID_ARG;
  1262. }
  1263. return ESP_ERR_HTTP_CONNECT;
  1264. } else if (ret == ASYNC_TRANS_CONNECTING) {
  1265. ESP_LOGD(TAG, "Connection not yet established");
  1266. return ESP_ERR_HTTP_CONNECTING;
  1267. }
  1268. }
  1269. client->state = HTTP_STATE_CONNECTED;
  1270. http_dispatch_event(client, HTTP_EVENT_ON_CONNECTED, NULL, 0);
  1271. http_dispatch_event_to_event_loop(HTTP_EVENT_ON_CONNECTED, &client, sizeof(esp_http_client_handle_t));
  1272. }
  1273. return ESP_OK;
  1274. }
  1275. static int http_client_prepare_first_line(esp_http_client_handle_t client, int write_len)
  1276. {
  1277. if (write_len >= 0) {
  1278. http_header_set_format(client->request->headers, "Content-Length", "%d", write_len);
  1279. } else {
  1280. esp_http_client_set_header(client, "Transfer-Encoding", "chunked");
  1281. }
  1282. const char *method = HTTP_METHOD_MAPPING[client->connection_info.method];
  1283. int first_line_len = snprintf(client->request->buffer->data,
  1284. client->buffer_size_tx, "%s %s",
  1285. method,
  1286. client->connection_info.path);
  1287. if (first_line_len >= client->buffer_size_tx) {
  1288. ESP_LOGE(TAG, "Out of buffer");
  1289. return -1;
  1290. }
  1291. if (client->connection_info.query) {
  1292. first_line_len += snprintf(client->request->buffer->data + first_line_len,
  1293. client->buffer_size_tx - first_line_len, "?%s", client->connection_info.query);
  1294. if (first_line_len >= client->buffer_size_tx) {
  1295. ESP_LOGE(TAG, "Out of buffer");
  1296. return -1;
  1297. }
  1298. }
  1299. first_line_len += snprintf(client->request->buffer->data + first_line_len,
  1300. client->buffer_size_tx - first_line_len, " %s\r\n", DEFAULT_HTTP_PROTOCOL);
  1301. if (first_line_len >= client->buffer_size_tx) {
  1302. ESP_LOGE(TAG, "Out of buffer");
  1303. return -1;
  1304. }
  1305. return first_line_len;
  1306. }
  1307. static esp_err_t esp_http_client_request_send(esp_http_client_handle_t client, int write_len)
  1308. {
  1309. int first_line_len = 0;
  1310. if (!client->first_line_prepared) {
  1311. if ((first_line_len = http_client_prepare_first_line(client, write_len)) < 0) {
  1312. return first_line_len;
  1313. }
  1314. client->first_line_prepared = true;
  1315. client->header_index = 0;
  1316. client->data_written_index = 0;
  1317. client->data_write_left = 0;
  1318. }
  1319. if (client->data_write_left > 0) {
  1320. /* sending leftover data from previous call to esp_http_client_request_send() API */
  1321. int wret = 0;
  1322. if (((wret = esp_http_client_write(client, client->request->buffer->data + client->data_written_index, client->data_write_left)) < 0)) {
  1323. ESP_LOGE(TAG, "Error write request");
  1324. return ESP_ERR_HTTP_WRITE_DATA;
  1325. }
  1326. client->data_write_left -= wret;
  1327. client->data_written_index += wret;
  1328. if (client->is_async && client->data_write_left > 0) {
  1329. return ESP_ERR_HTTP_WRITE_DATA; /* In case of EAGAIN error, we return ESP_ERR_HTTP_WRITE_DATA,
  1330. and the handling of EAGAIN should be done in the higher level APIs. */
  1331. }
  1332. }
  1333. int wlen = client->buffer_size_tx - first_line_len;
  1334. while ((client->header_index = http_header_generate_string(client->request->headers, client->header_index, client->request->buffer->data + first_line_len, &wlen))) {
  1335. if (wlen <= 0) {
  1336. break;
  1337. }
  1338. if (first_line_len) {
  1339. wlen += first_line_len;
  1340. first_line_len = 0;
  1341. }
  1342. client->request->buffer->data[wlen] = 0;
  1343. ESP_LOGD(TAG, "Write header[%d]: %s", client->header_index, client->request->buffer->data);
  1344. client->data_write_left = wlen;
  1345. client->data_written_index = 0;
  1346. while (client->data_write_left > 0) {
  1347. int wret = esp_transport_write(client->transport, client->request->buffer->data + client->data_written_index, client->data_write_left, client->timeout_ms);
  1348. if (wret <= 0) {
  1349. ESP_LOGE(TAG, "Error write request");
  1350. esp_http_client_close(client);
  1351. return ESP_ERR_HTTP_WRITE_DATA;
  1352. }
  1353. client->data_write_left -= wret;
  1354. client->data_written_index += wret;
  1355. }
  1356. wlen = client->buffer_size_tx;
  1357. }
  1358. client->data_written_index = 0;
  1359. client->data_write_left = client->post_len;
  1360. client->state = HTTP_STATE_REQ_COMPLETE_HEADER;
  1361. http_dispatch_event(client, HTTP_EVENT_HEADERS_SENT, NULL, 0);
  1362. http_dispatch_event_to_event_loop(HTTP_EVENT_HEADERS_SENT, &client, sizeof(esp_http_client_handle_t));
  1363. return ESP_OK;
  1364. }
  1365. static esp_err_t esp_http_client_send_post_data(esp_http_client_handle_t client)
  1366. {
  1367. if (client->state != HTTP_STATE_REQ_COMPLETE_HEADER) {
  1368. ESP_LOGE(TAG, "Invalid state");
  1369. return ESP_ERR_INVALID_STATE;
  1370. }
  1371. if (!(client->post_data && client->post_len)) {
  1372. goto success;
  1373. }
  1374. int wret = esp_http_client_write(client, client->post_data + client->data_written_index, client->data_write_left);
  1375. if (wret < 0) {
  1376. return wret;
  1377. }
  1378. client->data_write_left -= wret;
  1379. client->data_written_index += wret;
  1380. if (client->data_write_left <= 0) {
  1381. goto success;
  1382. } else {
  1383. return ESP_ERR_HTTP_WRITE_DATA;
  1384. }
  1385. success:
  1386. client->state = HTTP_STATE_REQ_COMPLETE_DATA;
  1387. return ESP_OK;
  1388. }
  1389. esp_err_t esp_http_client_open(esp_http_client_handle_t client, int write_len)
  1390. {
  1391. client->post_len = write_len;
  1392. esp_err_t err;
  1393. if ((err = esp_http_client_connect(client)) != ESP_OK) {
  1394. http_dispatch_event(client, HTTP_EVENT_ERROR, esp_transport_get_error_handle(client->transport), 0);
  1395. http_dispatch_event_to_event_loop(HTTP_EVENT_ERROR, &client, sizeof(esp_http_client_handle_t));
  1396. return err;
  1397. }
  1398. if ((err = esp_http_client_request_send(client, write_len)) != ESP_OK) {
  1399. http_dispatch_event(client, HTTP_EVENT_ERROR, esp_transport_get_error_handle(client->transport), 0);
  1400. http_dispatch_event_to_event_loop(HTTP_EVENT_ERROR, &client, sizeof(esp_http_client_handle_t));
  1401. return err;
  1402. }
  1403. return ESP_OK;
  1404. }
  1405. int esp_http_client_write(esp_http_client_handle_t client, const char *buffer, int len)
  1406. {
  1407. if (client->state < HTTP_STATE_REQ_COMPLETE_HEADER) {
  1408. return ESP_FAIL;
  1409. }
  1410. int wlen = 0, widx = 0;
  1411. while (len > 0) {
  1412. wlen = esp_transport_write(client->transport, buffer + widx, len, client->timeout_ms);
  1413. /* client->async_block is initialised in case of non-blocking IO, and in this case we return how
  1414. much ever data was written by the esp_transport_write() API. */
  1415. if (client->is_async || wlen <= 0) {
  1416. return wlen;
  1417. }
  1418. widx += wlen;
  1419. len -= wlen;
  1420. }
  1421. return widx;
  1422. }
  1423. esp_err_t esp_http_client_close(esp_http_client_handle_t client)
  1424. {
  1425. if (client->state >= HTTP_STATE_INIT) {
  1426. http_dispatch_event(client, HTTP_EVENT_DISCONNECTED, esp_transport_get_error_handle(client->transport), 0);
  1427. http_dispatch_event_to_event_loop(HTTP_EVENT_DISCONNECTED, &client, sizeof(esp_http_client_handle_t));
  1428. client->state = HTTP_STATE_INIT;
  1429. return esp_transport_close(client->transport);
  1430. }
  1431. return ESP_OK;
  1432. }
  1433. esp_err_t esp_http_client_set_post_field(esp_http_client_handle_t client, const char *data, int len)
  1434. {
  1435. esp_err_t err = ESP_OK;
  1436. client->post_data = (char *)data;
  1437. client->post_len = len;
  1438. ESP_LOGD(TAG, "set post file length = %d", len);
  1439. if (client->post_data) {
  1440. char *value = NULL;
  1441. if ((err = esp_http_client_get_header(client, "Content-Type", &value)) != ESP_OK) {
  1442. return err;
  1443. }
  1444. if (value == NULL) {
  1445. err = esp_http_client_set_header(client, "Content-Type", "application/x-www-form-urlencoded");
  1446. }
  1447. } else {
  1448. client->post_len = 0;
  1449. err = esp_http_client_set_header(client, "Content-Type", NULL);
  1450. }
  1451. return err;
  1452. }
  1453. int esp_http_client_get_post_field(esp_http_client_handle_t client, char **data)
  1454. {
  1455. if (client->post_data) {
  1456. *data = client->post_data;
  1457. return client->post_len;
  1458. }
  1459. return 0;
  1460. }
  1461. int esp_http_client_get_status_code(esp_http_client_handle_t client)
  1462. {
  1463. return client->response->status_code;
  1464. }
  1465. int64_t esp_http_client_get_content_length(esp_http_client_handle_t client)
  1466. {
  1467. return client->response->content_length;
  1468. }
  1469. bool esp_http_client_is_chunked_response(esp_http_client_handle_t client)
  1470. {
  1471. return client->response->is_chunked;
  1472. }
  1473. esp_http_client_transport_t esp_http_client_get_transport_type(esp_http_client_handle_t client)
  1474. {
  1475. if (!strcasecmp(client->connection_info.scheme, "https") ) {
  1476. return HTTP_TRANSPORT_OVER_SSL;
  1477. } else if (!strcasecmp(client->connection_info.scheme, "http")) {
  1478. return HTTP_TRANSPORT_OVER_TCP;
  1479. } else {
  1480. return HTTP_TRANSPORT_UNKNOWN;
  1481. }
  1482. }
  1483. esp_err_t esp_http_client_set_auth_data(esp_http_client_handle_t client, const char *auth_data, int len)
  1484. {
  1485. if (client == NULL || auth_data == NULL || len <= 0) {
  1486. return ESP_ERR_INVALID_ARG;
  1487. }
  1488. http_utils_append_string(&client->auth_header, auth_data, len);
  1489. return ESP_OK;
  1490. }
  1491. void esp_http_client_add_auth(esp_http_client_handle_t client)
  1492. {
  1493. if (client == NULL) {
  1494. return;
  1495. }
  1496. if (client->state != HTTP_STATE_RES_ON_DATA_START) {
  1497. return;
  1498. }
  1499. if (client->redirect_counter >= client->max_authorization_retries) {
  1500. ESP_LOGE(TAG, "Error, reached max_authorization_retries count=%d", client->redirect_counter);
  1501. return;
  1502. }
  1503. char *auth_header = client->auth_header;
  1504. if (auth_header) {
  1505. http_utils_trim_whitespace(&auth_header);
  1506. ESP_LOGD(TAG, "UNAUTHORIZED: %s", auth_header);
  1507. client->redirect_counter++;
  1508. #ifdef CONFIG_ESP_HTTP_CLIENT_ENABLE_DIGEST_AUTH
  1509. if (http_utils_str_starts_with(auth_header, "Digest") == 0) {
  1510. ESP_LOGD(TAG, "type = Digest");
  1511. client->connection_info.auth_type = HTTP_AUTH_TYPE_DIGEST;
  1512. } else {
  1513. #endif
  1514. #ifdef CONFIG_ESP_HTTP_CLIENT_ENABLE_BASIC_AUTH
  1515. if (http_utils_str_starts_with(auth_header, "Basic") == 0) {
  1516. ESP_LOGD(TAG, "type = Basic");
  1517. client->connection_info.auth_type = HTTP_AUTH_TYPE_BASIC;
  1518. } else {
  1519. #endif
  1520. client->connection_info.auth_type = HTTP_AUTH_TYPE_NONE;
  1521. ESP_LOGE(TAG, "This authentication method is not supported: %s", auth_header);
  1522. return;
  1523. #ifdef CONFIG_ESP_HTTP_CLIENT_ENABLE_BASIC_AUTH
  1524. }
  1525. #endif
  1526. #ifdef CONFIG_ESP_HTTP_CLIENT_ENABLE_DIGEST_AUTH
  1527. }
  1528. #endif
  1529. _clear_auth_data(client);
  1530. client->auth_data->method = strdup(HTTP_METHOD_MAPPING[client->connection_info.method]);
  1531. client->auth_data->nc = 1;
  1532. client->auth_data->realm = http_utils_get_string_between(auth_header, "realm=\"", "\"");
  1533. client->auth_data->algorithm = http_utils_get_string_between(auth_header, "algorithm=", ",");
  1534. if (client->auth_data->algorithm == NULL) {
  1535. client->auth_data->algorithm = strdup("MD5");
  1536. }
  1537. client->auth_data->qop = http_utils_get_string_between(auth_header, "qop=\"", "\"");
  1538. client->auth_data->nonce = http_utils_get_string_between(auth_header, "nonce=\"", "\"");
  1539. client->auth_data->opaque = http_utils_get_string_between(auth_header, "opaque=\"", "\"");
  1540. client->process_again = 1;
  1541. } else {
  1542. client->connection_info.auth_type = HTTP_AUTH_TYPE_NONE;
  1543. ESP_LOGW(TAG, "This request requires authentication, but does not provide header information for that");
  1544. }
  1545. }
  1546. int esp_http_client_read_response(esp_http_client_handle_t client, char *buffer, int len)
  1547. {
  1548. int read_len = 0;
  1549. while (read_len < len) {
  1550. int data_read = esp_http_client_read(client, buffer + read_len, len - read_len);
  1551. if (data_read <= 0) {
  1552. return read_len;
  1553. }
  1554. read_len += data_read;
  1555. }
  1556. return read_len;
  1557. }
  1558. esp_err_t esp_http_client_flush_response(esp_http_client_handle_t client, int *len)
  1559. {
  1560. if (client == NULL) {
  1561. ESP_LOGE(TAG, "client must not be NULL");
  1562. return ESP_ERR_INVALID_ARG;
  1563. }
  1564. int read_len = 0;
  1565. while (!esp_http_client_is_complete_data_received(client)) {
  1566. int data_read = esp_http_client_get_data(client);
  1567. if (data_read < 0) {
  1568. return ESP_FAIL;
  1569. }
  1570. read_len += data_read;
  1571. }
  1572. if (len) {
  1573. *len = read_len;
  1574. }
  1575. return ESP_OK;
  1576. }
  1577. esp_err_t esp_http_client_get_url(esp_http_client_handle_t client, char *url, const int len)
  1578. {
  1579. if (client == NULL || url == NULL) {
  1580. return ESP_ERR_INVALID_ARG;
  1581. }
  1582. if (client->connection_info.host && client->connection_info.scheme && client->connection_info.path) {
  1583. snprintf(url, len, "%s://%s%s", client->connection_info.scheme, client->connection_info.host, client->connection_info.path);
  1584. return ESP_OK;
  1585. } else {
  1586. ESP_LOGE(TAG, "Failed to get URL");
  1587. }
  1588. return ESP_FAIL;
  1589. }
  1590. esp_err_t esp_http_client_get_chunk_length(esp_http_client_handle_t client, int *len)
  1591. {
  1592. if (client == NULL || len == NULL) {
  1593. return ESP_ERR_INVALID_ARG;
  1594. }
  1595. if (esp_http_client_is_chunked_response(client)) {
  1596. *len = client->response->chunk_length;
  1597. } else {
  1598. ESP_LOGE(TAG, "Response is not chunked");
  1599. return ESP_FAIL;
  1600. }
  1601. return ESP_OK;
  1602. }