esp_http_client.c 66 KB

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