esp_http_client.c 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749
  1. /*
  2. * SPDX-FileCopyrightText: 2015-2022 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. esp_http_client_handle_t esp_http_client_init(const esp_http_client_config_t *config)
  560. {
  561. esp_http_client_handle_t client;
  562. esp_err_t ret = ESP_OK;
  563. esp_transport_handle_t tcp = NULL;
  564. char *host_name;
  565. bool _success;
  566. _success = (
  567. (client = calloc(1, sizeof(esp_http_client_t))) &&
  568. (client->parser = calloc(1, sizeof(struct http_parser))) &&
  569. (client->parser_settings = calloc(1, sizeof(struct http_parser_settings))) &&
  570. (client->auth_data = calloc(1, sizeof(esp_http_auth_data_t))) &&
  571. (client->request = calloc(1, sizeof(esp_http_data_t))) &&
  572. (client->request->headers = http_header_init()) &&
  573. (client->request->buffer = calloc(1, sizeof(esp_http_buffer_t))) &&
  574. (client->response = calloc(1, sizeof(esp_http_data_t))) &&
  575. (client->response->headers = http_header_init()) &&
  576. (client->response->buffer = calloc(1, sizeof(esp_http_buffer_t)))
  577. );
  578. if (!_success) {
  579. ESP_LOGE(TAG, "Error allocate memory");
  580. goto error;
  581. }
  582. _success = (
  583. (client->transport_list = esp_transport_list_init()) &&
  584. (tcp = esp_transport_tcp_init()) &&
  585. (esp_transport_set_default_port(tcp, DEFAULT_HTTP_PORT) == ESP_OK) &&
  586. (esp_transport_list_add(client->transport_list, tcp, "http") == ESP_OK)
  587. );
  588. if (!_success) {
  589. ESP_LOGE(TAG, "Error initialize transport");
  590. goto error;
  591. }
  592. if (config->keep_alive_enable == true) {
  593. client->keep_alive_cfg.keep_alive_enable = true;
  594. client->keep_alive_cfg.keep_alive_idle = (config->keep_alive_idle == 0) ? DEFAULT_KEEP_ALIVE_IDLE : config->keep_alive_idle;
  595. client->keep_alive_cfg.keep_alive_interval = (config->keep_alive_interval == 0) ? DEFAULT_KEEP_ALIVE_INTERVAL : config->keep_alive_interval;
  596. client->keep_alive_cfg.keep_alive_count = (config->keep_alive_count == 0) ? DEFAULT_KEEP_ALIVE_COUNT : config->keep_alive_count;
  597. esp_transport_tcp_set_keep_alive(tcp, &client->keep_alive_cfg);
  598. }
  599. if (config->if_name) {
  600. client->if_name = calloc(1, sizeof(struct ifreq) + 1);
  601. ESP_GOTO_ON_FALSE(client->if_name, ESP_FAIL, error, TAG, "Memory exhausted");
  602. memcpy(client->if_name, config->if_name, sizeof(struct ifreq));
  603. esp_transport_tcp_set_interface_name(tcp, client->if_name);
  604. }
  605. #ifdef CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS
  606. esp_transport_handle_t ssl = NULL;
  607. _success = (
  608. (ssl = esp_transport_ssl_init()) &&
  609. (esp_transport_set_default_port(ssl, DEFAULT_HTTPS_PORT) == ESP_OK) &&
  610. (esp_transport_list_add(client->transport_list, ssl, "https") == ESP_OK)
  611. );
  612. if (!_success) {
  613. ESP_LOGE(TAG, "Error initialize SSL Transport");
  614. goto error;
  615. }
  616. if (config->crt_bundle_attach != NULL) {
  617. #ifdef CONFIG_MBEDTLS_CERTIFICATE_BUNDLE
  618. esp_transport_ssl_crt_bundle_attach(ssl, config->crt_bundle_attach);
  619. #else //CONFIG_MBEDTLS_CERTIFICATE_BUNDLE
  620. ESP_LOGE(TAG, "use_crt_bundle configured but not enabled in menuconfig: Please enable MBEDTLS_CERTIFICATE_BUNDLE option");
  621. #endif
  622. } else if (config->use_global_ca_store == true) {
  623. esp_transport_ssl_enable_global_ca_store(ssl);
  624. } else if (config->cert_pem) {
  625. if (!config->cert_len) {
  626. esp_transport_ssl_set_cert_data(ssl, config->cert_pem, strlen(config->cert_pem));
  627. } else {
  628. esp_transport_ssl_set_cert_data_der(ssl, config->cert_pem, config->cert_len);
  629. }
  630. }
  631. if (config->client_cert_pem) {
  632. if (!config->client_cert_len) {
  633. esp_transport_ssl_set_client_cert_data(ssl, config->client_cert_pem, strlen(config->client_cert_pem));
  634. } else {
  635. esp_transport_ssl_set_client_cert_data_der(ssl, config->client_cert_pem, config->client_cert_len);
  636. }
  637. }
  638. #if CONFIG_ESP_TLS_USE_SECURE_ELEMENT
  639. if (config->use_secure_element) {
  640. esp_transport_ssl_use_secure_element(ssl);
  641. }
  642. #endif
  643. if (config->client_key_pem) {
  644. if (!config->client_key_len) {
  645. esp_transport_ssl_set_client_key_data(ssl, config->client_key_pem, strlen(config->client_key_pem));
  646. } else {
  647. esp_transport_ssl_set_client_key_data_der(ssl, config->client_key_pem, config->client_key_len);
  648. }
  649. }
  650. if (config->client_key_password && config->client_key_password_len > 0) {
  651. esp_transport_ssl_set_client_key_password(ssl, config->client_key_password, config->client_key_password_len);
  652. }
  653. if (config->skip_cert_common_name_check) {
  654. esp_transport_ssl_skip_common_name_check(ssl);
  655. }
  656. if (config->common_name) {
  657. esp_transport_ssl_set_common_name(ssl, config->common_name);
  658. }
  659. #endif
  660. if (_set_config(client, config) != ESP_OK) {
  661. ESP_LOGE(TAG, "Error set configurations");
  662. goto error;
  663. }
  664. _success = (
  665. (client->request->buffer->data = malloc(client->buffer_size_tx)) &&
  666. (client->response->buffer->data = malloc(client->buffer_size_rx))
  667. );
  668. if (!_success) {
  669. ESP_LOGE(TAG, "Allocation failed");
  670. goto error;
  671. }
  672. const char *user_agent = config->user_agent == NULL ? DEFAULT_HTTP_USER_AGENT : config->user_agent;
  673. if (config->host != NULL && config->path != NULL) {
  674. if (client->connection_info.host == NULL) {
  675. ESP_LOGE(TAG, "invalid host");
  676. goto error;
  677. }
  678. host_name = _get_host_header(client->connection_info.host, client->connection_info.port);
  679. if (host_name == NULL) {
  680. ESP_LOGE(TAG, "Failed to allocate memory for host header");
  681. goto error;
  682. }
  683. _success = (
  684. (esp_http_client_set_header(client, "User-Agent", user_agent) == ESP_OK) &&
  685. (esp_http_client_set_header(client, "Host", host_name) == ESP_OK)
  686. );
  687. free(host_name);
  688. if (!_success) {
  689. ESP_LOGE(TAG, "Error while setting default configurations");
  690. goto error;
  691. }
  692. } else if (config->url != NULL) {
  693. if (esp_http_client_set_url(client, config->url) != ESP_OK) {
  694. ESP_LOGE(TAG, "Failed to set URL");
  695. goto error;
  696. }
  697. if (client->connection_info.host == NULL) {
  698. ESP_LOGE(TAG, "invalid host");
  699. goto error;
  700. }
  701. host_name = _get_host_header(client->connection_info.host, client->connection_info.port);
  702. if (host_name == NULL) {
  703. ESP_LOGE(TAG, "Failed to allocate memory for host header");
  704. goto error;
  705. }
  706. _success = (
  707. (esp_http_client_set_header(client, "User-Agent", user_agent) == ESP_OK) &&
  708. (esp_http_client_set_header(client, "Host", host_name) == ESP_OK)
  709. );
  710. free(host_name);
  711. if (!_success) {
  712. ESP_LOGE(TAG, "Error while setting default configurations");
  713. goto error;
  714. }
  715. } else {
  716. ESP_LOGE(TAG, "config should have either URL or host & path");
  717. goto error;
  718. }
  719. /* As default behavior, cache data received in fetch header state. This will be
  720. * used in esp_http_client_read API only. For esp_http_perform we shall disable
  721. * this as data will be processed by event handler */
  722. client->cache_data_in_fetch_hdr = 1;
  723. client->parser_settings->on_message_begin = http_on_message_begin;
  724. client->parser_settings->on_url = http_on_url;
  725. client->parser_settings->on_status = http_on_status;
  726. client->parser_settings->on_header_field = http_on_header_field;
  727. client->parser_settings->on_header_value = http_on_header_value;
  728. client->parser_settings->on_headers_complete = http_on_headers_complete;
  729. client->parser_settings->on_body = http_on_body;
  730. client->parser_settings->on_message_complete = http_on_message_complete;
  731. client->parser_settings->on_chunk_complete = http_on_chunk_complete;
  732. client->parser_settings->on_chunk_header = http_on_chunk_header;
  733. client->parser->data = client;
  734. client->event.client = client;
  735. client->state = HTTP_STATE_INIT;
  736. if (ret == ESP_OK) {
  737. return client;
  738. }
  739. error:
  740. esp_http_client_cleanup(client);
  741. return NULL;
  742. }
  743. static void esp_http_client_cached_buf_cleanup(esp_http_buffer_t *res_buffer)
  744. {
  745. /* Free cached data if any, that was received during fetch header stage */
  746. if (res_buffer && res_buffer->orig_raw_data) {
  747. free(res_buffer->orig_raw_data);
  748. res_buffer->orig_raw_data = NULL;
  749. res_buffer->raw_data = NULL;
  750. res_buffer->raw_len = 0;
  751. }
  752. }
  753. esp_err_t esp_http_client_cleanup(esp_http_client_handle_t client)
  754. {
  755. if (client == NULL) {
  756. return ESP_FAIL;
  757. }
  758. esp_http_client_close(client);
  759. if (client->transport_list) {
  760. esp_transport_list_destroy(client->transport_list);
  761. }
  762. if (client->request) {
  763. http_header_destroy(client->request->headers);
  764. if (client->request->buffer) {
  765. free(client->request->buffer->data);
  766. }
  767. free(client->request->buffer);
  768. free(client->request);
  769. }
  770. if (client->response) {
  771. http_header_destroy(client->response->headers);
  772. if (client->response->buffer) {
  773. free(client->response->buffer->data);
  774. esp_http_client_cached_buf_cleanup(client->response->buffer);
  775. }
  776. free(client->response->buffer);
  777. free(client->response);
  778. }
  779. if (client->if_name) {
  780. free(client->if_name);
  781. }
  782. free(client->parser);
  783. free(client->parser_settings);
  784. _clear_connection_info(client);
  785. _clear_auth_data(client);
  786. free(client->auth_data);
  787. free(client->current_header_key);
  788. free(client->location);
  789. free(client->auth_header);
  790. free(client);
  791. return ESP_OK;
  792. }
  793. esp_err_t esp_http_client_set_redirection(esp_http_client_handle_t client)
  794. {
  795. if (client == NULL) {
  796. return ESP_ERR_INVALID_ARG;
  797. }
  798. if (client->location == NULL) {
  799. return ESP_ERR_INVALID_ARG;
  800. }
  801. ESP_LOGD(TAG, "Redirect to %s", client->location);
  802. esp_err_t err = esp_http_client_set_url(client, client->location);
  803. if (err == ESP_OK) {
  804. client->redirect_counter ++;
  805. client->process_again = 1; // used only in the blocking mode (when esp_http_client_perform() is called)
  806. }
  807. return err;
  808. }
  809. static esp_err_t esp_http_check_response(esp_http_client_handle_t client)
  810. {
  811. if (client->response->status_code >= HttpStatus_Ok && client->response->status_code < HttpStatus_MultipleChoices) {
  812. return ESP_OK;
  813. }
  814. if (client->redirect_counter >= client->max_redirection_count) {
  815. ESP_LOGE(TAG, "Error, reach max_redirection_count count=%d", client->redirect_counter);
  816. return ESP_ERR_HTTP_MAX_REDIRECT;
  817. }
  818. switch (client->response->status_code) {
  819. case HttpStatus_MovedPermanently:
  820. case HttpStatus_Found:
  821. case HttpStatus_SeeOther:
  822. case HttpStatus_TemporaryRedirect:
  823. case HttpStatus_PermanentRedirect:
  824. if (client->disable_auto_redirect) {
  825. http_dispatch_event(client, HTTP_EVENT_REDIRECT, NULL, 0);
  826. } else {
  827. if (esp_http_client_set_redirection(client) != ESP_OK){
  828. return ESP_FAIL;
  829. };
  830. }
  831. esp_http_client_redirect_event_data_t evt_data = {
  832. .status_code = client->response->status_code,
  833. .client = client,
  834. };
  835. http_dispatch_event_to_event_loop(HTTP_EVENT_REDIRECT, &evt_data, sizeof(esp_http_client_redirect_event_data_t));
  836. break;
  837. case HttpStatus_Unauthorized:
  838. esp_http_client_add_auth(client);
  839. }
  840. return ESP_OK;
  841. }
  842. esp_err_t esp_http_client_set_url(esp_http_client_handle_t client, const char *url)
  843. {
  844. esp_err_t ret = ESP_OK;
  845. char *old_host = NULL;
  846. struct http_parser_url purl;
  847. int old_port;
  848. if (client == NULL || url == NULL) {
  849. ESP_LOGE(TAG, "client or url must not NULL");
  850. return ESP_ERR_INVALID_ARG;
  851. }
  852. http_parser_url_init(&purl);
  853. int parser_status = http_parser_parse_url(url, strlen(url), 0, &purl);
  854. if (parser_status != 0) {
  855. ESP_LOGE(TAG, "Error parse url %s", url);
  856. return ESP_ERR_INVALID_ARG;
  857. }
  858. if (client->connection_info.host) {
  859. old_host = strdup(client->connection_info.host);
  860. }
  861. old_port = client->connection_info.port;
  862. if (purl.field_data[UF_HOST].len) {
  863. http_utils_assign_string(&client->connection_info.host, url + purl.field_data[UF_HOST].off, purl.field_data[UF_HOST].len);
  864. ESP_GOTO_ON_FALSE(client->connection_info.host, ESP_ERR_NO_MEM, error, TAG, "Memory exhausted");
  865. }
  866. // Close the connection if host was changed
  867. if (old_host && client->connection_info.host
  868. && strcasecmp(old_host, (const void *)client->connection_info.host) != 0) {
  869. ESP_LOGD(TAG, "New host assign = %s", client->connection_info.host);
  870. if (esp_http_client_set_header(client, "Host", client->connection_info.host) != ESP_OK) {
  871. free(old_host);
  872. return ESP_ERR_NO_MEM;
  873. }
  874. /* Free cached data if any, as we are closing this connection */
  875. esp_http_client_cached_buf_cleanup(client->response->buffer);
  876. esp_http_client_close(client);
  877. }
  878. if (old_host) {
  879. free(old_host);
  880. old_host = NULL;
  881. }
  882. if (purl.field_data[UF_SCHEMA].len) {
  883. http_utils_assign_string(&client->connection_info.scheme, url + purl.field_data[UF_SCHEMA].off, purl.field_data[UF_SCHEMA].len);
  884. ESP_RETURN_ON_FALSE(client->connection_info.scheme, ESP_ERR_NO_MEM, TAG, "Memory exhausted");
  885. if (strcasecmp(client->connection_info.scheme, "http") == 0) {
  886. client->connection_info.port = DEFAULT_HTTP_PORT;
  887. } else if (strcasecmp(client->connection_info.scheme, "https") == 0) {
  888. client->connection_info.port = DEFAULT_HTTPS_PORT;
  889. }
  890. }
  891. if (purl.field_data[UF_PORT].len) {
  892. client->connection_info.port = strtol((const char*)(url + purl.field_data[UF_PORT].off), NULL, 10);
  893. }
  894. if (old_port != client->connection_info.port) {
  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 (purl.field_data[UF_USERINFO].len) {
  900. char *user_info = NULL;
  901. http_utils_assign_string(&user_info, url + purl.field_data[UF_USERINFO].off, purl.field_data[UF_USERINFO].len);
  902. if (user_info) {
  903. char *username = user_info;
  904. char *password = strchr(user_info, ':');
  905. if (password) {
  906. *password = 0;
  907. password ++;
  908. http_utils_assign_string(&client->connection_info.password, password, -1);
  909. ESP_RETURN_ON_FALSE(client->connection_info.password, ESP_ERR_NO_MEM, TAG, "Memory exhausted");
  910. }
  911. http_utils_assign_string(&client->connection_info.username, username, -1);
  912. ESP_RETURN_ON_FALSE(client->connection_info.username, ESP_ERR_NO_MEM, TAG, "Memory exhausted");
  913. free(user_info);
  914. } else {
  915. return ESP_ERR_NO_MEM;
  916. }
  917. }
  918. //Reset path and query if there are no information
  919. if (purl.field_data[UF_PATH].len) {
  920. http_utils_assign_string(&client->connection_info.path, url + purl.field_data[UF_PATH].off, purl.field_data[UF_PATH].len);
  921. } else {
  922. http_utils_assign_string(&client->connection_info.path, "/", -1);
  923. }
  924. ESP_RETURN_ON_FALSE(client->connection_info.path, ESP_ERR_NO_MEM, TAG, "Memory exhausted");
  925. if (purl.field_data[UF_QUERY].len) {
  926. http_utils_assign_string(&client->connection_info.query, url + purl.field_data[UF_QUERY].off, purl.field_data[UF_QUERY].len);
  927. ESP_RETURN_ON_FALSE(client->connection_info.query, ESP_ERR_NO_MEM, TAG, "Memory exhausted");
  928. } else if (client->connection_info.query) {
  929. free(client->connection_info.query);
  930. client->connection_info.query = NULL;
  931. }
  932. return ret;
  933. error:
  934. free(old_host);
  935. return ret;
  936. }
  937. int esp_http_client_get_errno(esp_http_client_handle_t client)
  938. {
  939. if (!client) {
  940. ESP_LOGE(TAG, "Invalid client handle");
  941. return -1;
  942. }
  943. return esp_transport_get_errno(client->transport);
  944. }
  945. esp_err_t esp_http_client_set_method(esp_http_client_handle_t client, esp_http_client_method_t method)
  946. {
  947. client->connection_info.method = method;
  948. return ESP_OK;
  949. }
  950. esp_err_t esp_http_client_set_timeout_ms(esp_http_client_handle_t client, int timeout_ms)
  951. {
  952. if (client == NULL) {
  953. return ESP_ERR_INVALID_ARG;
  954. }
  955. client->timeout_ms = timeout_ms;
  956. return ESP_OK;
  957. }
  958. static int esp_http_client_get_data(esp_http_client_handle_t client)
  959. {
  960. if (client->state < HTTP_STATE_RES_ON_DATA_START) {
  961. return ESP_FAIL;
  962. }
  963. if (client->connection_info.method == HTTP_METHOD_HEAD) {
  964. return 0;
  965. }
  966. esp_http_buffer_t *res_buffer = client->response->buffer;
  967. ESP_LOGD(TAG, "data_process=%"PRId64", content_length=%"PRId64, client->response->data_process, client->response->content_length);
  968. int rlen = esp_transport_read(client->transport, res_buffer->data, client->buffer_size_rx, client->timeout_ms);
  969. if (rlen >= 0) {
  970. http_parser_execute(client->parser, client->parser_settings, res_buffer->data, rlen);
  971. }
  972. return rlen;
  973. }
  974. bool esp_http_client_is_complete_data_received(esp_http_client_handle_t client)
  975. {
  976. if (client->response->is_chunked) {
  977. if (!client->is_chunk_complete) {
  978. ESP_LOGD(TAG, "Chunks were not completely read");
  979. return false;
  980. }
  981. } else {
  982. if (client->response->data_process != client->response->content_length) {
  983. ESP_LOGD(TAG, "Data processed %"PRId64" != Data specified in content length %"PRId64, client->response->data_process, client->response->content_length);
  984. return false;
  985. }
  986. }
  987. return true;
  988. }
  989. int esp_http_client_read(esp_http_client_handle_t client, char *buffer, int len)
  990. {
  991. esp_http_buffer_t *res_buffer = client->response->buffer;
  992. int rlen = ESP_FAIL, ridx = 0;
  993. if (res_buffer->raw_len) {
  994. int remain_len = client->response->buffer->raw_len;
  995. if (remain_len > len) {
  996. remain_len = len;
  997. }
  998. memcpy(buffer, res_buffer->raw_data, remain_len);
  999. res_buffer->raw_len -= remain_len;
  1000. res_buffer->raw_data += remain_len;
  1001. ridx = remain_len;
  1002. if (res_buffer->raw_len == 0) {
  1003. esp_http_client_cached_buf_cleanup(res_buffer);
  1004. }
  1005. }
  1006. int need_read = len - ridx;
  1007. bool is_data_remain = true;
  1008. while (need_read > 0 && is_data_remain) {
  1009. if (client->response->is_chunked) {
  1010. is_data_remain = !client->is_chunk_complete;
  1011. } else {
  1012. is_data_remain = client->response->data_process < client->response->content_length;
  1013. }
  1014. ESP_LOGD(TAG, "is_data_remain=%d, is_chunked=%d, content_length=%"PRId64, is_data_remain, client->response->is_chunked, client->response->content_length);
  1015. if (!is_data_remain) {
  1016. break;
  1017. }
  1018. int byte_to_read = need_read;
  1019. if (byte_to_read > client->buffer_size_rx) {
  1020. byte_to_read = client->buffer_size_rx;
  1021. }
  1022. errno = 0;
  1023. rlen = esp_transport_read(client->transport, res_buffer->data, byte_to_read, client->timeout_ms);
  1024. ESP_LOGD(TAG, "need_read=%d, byte_to_read=%d, rlen=%d, ridx=%d", need_read, byte_to_read, rlen, ridx);
  1025. if (rlen <= 0) {
  1026. if (errno != 0) {
  1027. esp_log_level_t sev = ESP_LOG_WARN;
  1028. /* Check for cleanly closed connection */
  1029. if (rlen == ERR_TCP_TRANSPORT_CONNECTION_CLOSED_BY_FIN && client->response->is_chunked) {
  1030. /* Explicit call to parser for invoking `message_complete` callback */
  1031. http_parser_execute(client->parser, client->parser_settings, res_buffer->data, 0);
  1032. /* ...and lowering the message severity, as closed connection from server side is expected in chunked transport */
  1033. sev = ESP_LOG_DEBUG;
  1034. }
  1035. ESP_LOG_LEVEL(sev, TAG, "esp_transport_read returned:%d and errno:%d ", rlen, errno);
  1036. }
  1037. if (rlen == ERR_TCP_TRANSPORT_CONNECTION_TIMEOUT) {
  1038. ESP_LOGD(TAG, "Connection timed out before data was ready!");
  1039. /* Returning the number of bytes read upto the point where connection timed out */
  1040. if (ridx) {
  1041. return ridx;
  1042. }
  1043. return -ESP_ERR_HTTP_EAGAIN;
  1044. }
  1045. if (rlen != ERR_TCP_TRANSPORT_CONNECTION_CLOSED_BY_FIN) {
  1046. esp_err_t err = esp_transport_translate_error(rlen);
  1047. ESP_LOGE(TAG, "transport_read: error - %d | %s", err, esp_err_to_name(err));
  1048. }
  1049. if (rlen < 0 && ridx == 0 && !esp_http_client_is_complete_data_received(client)) {
  1050. http_dispatch_event(client, HTTP_EVENT_ERROR, esp_transport_get_error_handle(client->transport), 0);
  1051. http_dispatch_event_to_event_loop(HTTP_EVENT_ERROR, &client, sizeof(esp_http_client_handle_t));
  1052. return ESP_FAIL;
  1053. }
  1054. return ridx;
  1055. }
  1056. res_buffer->output_ptr = buffer + ridx;
  1057. http_parser_execute(client->parser, client->parser_settings, res_buffer->data, rlen);
  1058. ridx += res_buffer->raw_len;
  1059. need_read -= res_buffer->raw_len;
  1060. res_buffer->raw_len = 0; //clear
  1061. res_buffer->output_ptr = NULL;
  1062. }
  1063. return ridx;
  1064. }
  1065. esp_err_t esp_http_client_perform(esp_http_client_handle_t client)
  1066. {
  1067. esp_err_t err;
  1068. do {
  1069. if (client->process_again) {
  1070. esp_http_client_prepare(client);
  1071. }
  1072. switch (client->state) {
  1073. /* In case of blocking esp_http_client_perform(), the following states will fall through one after the after;
  1074. in case of non-blocking esp_http_client_perform(), if there is an error condition, like EINPROGRESS or EAGAIN,
  1075. then the esp_http_client_perform() API will return ESP_ERR_HTTP_EAGAIN error. The user may call
  1076. esp_http_client_perform API again, and for this reason, we maintain the states */
  1077. case HTTP_STATE_INIT:
  1078. if ((err = esp_http_client_connect(client)) != ESP_OK) {
  1079. if (client->is_async && err == ESP_ERR_HTTP_CONNECTING) {
  1080. return ESP_ERR_HTTP_EAGAIN;
  1081. }
  1082. http_dispatch_event(client, HTTP_EVENT_ERROR, esp_transport_get_error_handle(client->transport), 0);
  1083. http_dispatch_event_to_event_loop(HTTP_EVENT_ERROR, &client, sizeof(esp_http_client_handle_t));
  1084. return err;
  1085. }
  1086. /* falls through */
  1087. case HTTP_STATE_CONNECTED:
  1088. if ((err = esp_http_client_request_send(client, client->post_len)) != ESP_OK) {
  1089. if (client->is_async && errno == EAGAIN) {
  1090. return ESP_ERR_HTTP_EAGAIN;
  1091. }
  1092. http_dispatch_event(client, HTTP_EVENT_ERROR, esp_transport_get_error_handle(client->transport), 0);
  1093. http_dispatch_event_to_event_loop(HTTP_EVENT_ERROR, &client, sizeof(esp_http_client_handle_t));
  1094. return err;
  1095. }
  1096. /* falls through */
  1097. case HTTP_STATE_REQ_COMPLETE_HEADER:
  1098. if ((err = esp_http_client_send_post_data(client)) != ESP_OK) {
  1099. if (client->is_async && errno == EAGAIN) {
  1100. return ESP_ERR_HTTP_EAGAIN;
  1101. }
  1102. http_dispatch_event(client, HTTP_EVENT_ERROR, esp_transport_get_error_handle(client->transport), 0);
  1103. http_dispatch_event_to_event_loop(HTTP_EVENT_ERROR, &client, sizeof(esp_http_client_handle_t));
  1104. return err;
  1105. }
  1106. /* falls through */
  1107. case HTTP_STATE_REQ_COMPLETE_DATA:
  1108. /* Disable caching response body, as data should
  1109. * be handled by application event handler */
  1110. client->cache_data_in_fetch_hdr = 0;
  1111. int64_t ret = esp_http_client_fetch_headers(client);
  1112. if (ret < 0) {
  1113. if ((client->is_async && errno == EAGAIN) || ret == -ESP_ERR_HTTP_EAGAIN) {
  1114. return ESP_ERR_HTTP_EAGAIN;
  1115. }
  1116. /* Enable caching after error condition because next
  1117. * request could be performed using native APIs */
  1118. client->cache_data_in_fetch_hdr = 1;
  1119. if (esp_transport_get_errno(client->transport) == ENOTCONN) {
  1120. ESP_LOGW(TAG, "Close connection due to FIN received");
  1121. esp_http_client_close(client);
  1122. http_dispatch_event(client, HTTP_EVENT_ERROR, esp_transport_get_error_handle(client->transport), 0);
  1123. http_dispatch_event_to_event_loop(HTTP_EVENT_ERROR, &client, sizeof(esp_http_client_handle_t));
  1124. return ESP_ERR_HTTP_CONNECTION_CLOSED;
  1125. }
  1126. http_dispatch_event(client, HTTP_EVENT_ERROR, esp_transport_get_error_handle(client->transport), 0);
  1127. http_dispatch_event_to_event_loop(HTTP_EVENT_ERROR, &client, sizeof(esp_http_client_handle_t));
  1128. return ESP_ERR_HTTP_FETCH_HEADER;
  1129. }
  1130. /* falls through */
  1131. case HTTP_STATE_RES_ON_DATA_START:
  1132. /* Enable caching after fetch headers state because next
  1133. * request could be performed using native APIs */
  1134. client->cache_data_in_fetch_hdr = 1;
  1135. if ((err = esp_http_check_response(client)) != ESP_OK) {
  1136. ESP_LOGE(TAG, "Error response");
  1137. http_dispatch_event(client, HTTP_EVENT_ERROR, esp_transport_get_error_handle(client->transport), 0);
  1138. http_dispatch_event_to_event_loop(HTTP_EVENT_ERROR, &client, sizeof(esp_http_client_handle_t));
  1139. return err;
  1140. }
  1141. while (client->response->is_chunked && !client->is_chunk_complete) {
  1142. if (esp_http_client_get_data(client) <= 0) {
  1143. if (client->is_async && errno == EAGAIN) {
  1144. return ESP_ERR_HTTP_EAGAIN;
  1145. }
  1146. ESP_LOGD(TAG, "Read finish or server requests close");
  1147. break;
  1148. }
  1149. }
  1150. while (client->response->data_process < client->response->content_length) {
  1151. if (esp_http_client_get_data(client) <= 0) {
  1152. if (client->is_async && errno == EAGAIN) {
  1153. return ESP_ERR_HTTP_EAGAIN;
  1154. }
  1155. ESP_LOGD(TAG, "Read finish or server requests close");
  1156. break;
  1157. }
  1158. }
  1159. http_dispatch_event(client, HTTP_EVENT_ON_FINISH, NULL, 0);
  1160. http_dispatch_event_to_event_loop(HTTP_EVENT_ON_FINISH, &client, sizeof(esp_http_client_handle_t));
  1161. client->response->buffer->raw_len = 0;
  1162. if (!http_should_keep_alive(client->parser)) {
  1163. ESP_LOGD(TAG, "Close connection");
  1164. esp_http_client_close(client);
  1165. } else {
  1166. if (client->state > HTTP_STATE_CONNECTED) {
  1167. client->state = HTTP_STATE_CONNECTED;
  1168. client->first_line_prepared = false;
  1169. }
  1170. }
  1171. break;
  1172. default:
  1173. break;
  1174. }
  1175. } while (client->process_again);
  1176. return ESP_OK;
  1177. }
  1178. int64_t esp_http_client_fetch_headers(esp_http_client_handle_t client)
  1179. {
  1180. if (client->state < HTTP_STATE_REQ_COMPLETE_HEADER) {
  1181. return ESP_FAIL;
  1182. }
  1183. client->state = HTTP_STATE_REQ_COMPLETE_DATA;
  1184. esp_http_buffer_t *buffer = client->response->buffer;
  1185. client->response->status_code = -1;
  1186. while (client->state < HTTP_STATE_RES_COMPLETE_HEADER) {
  1187. buffer->len = esp_transport_read(client->transport, buffer->data, client->buffer_size_rx, client->timeout_ms);
  1188. if (buffer->len <= 0) {
  1189. if (buffer->len == ERR_TCP_TRANSPORT_CONNECTION_TIMEOUT) {
  1190. ESP_LOGW(TAG, "Connection timed out before data was ready!");
  1191. return -ESP_ERR_HTTP_EAGAIN;
  1192. }
  1193. return ESP_FAIL;
  1194. }
  1195. http_parser_execute(client->parser, client->parser_settings, buffer->data, buffer->len);
  1196. }
  1197. client->state = HTTP_STATE_RES_ON_DATA_START;
  1198. ESP_LOGD(TAG, "content_length = %"PRId64, client->response->content_length);
  1199. if (client->response->content_length <= 0) {
  1200. client->response->is_chunked = true;
  1201. return 0;
  1202. }
  1203. return client->response->content_length;
  1204. }
  1205. static esp_err_t esp_http_client_connect(esp_http_client_handle_t client)
  1206. {
  1207. esp_err_t err;
  1208. if (client->state == HTTP_STATE_UNINIT) {
  1209. ESP_LOGE(TAG, "Client has not been initialized");
  1210. return ESP_ERR_INVALID_STATE;
  1211. }
  1212. if ((err = esp_http_client_prepare(client)) != ESP_OK) {
  1213. ESP_LOGE(TAG, "Failed to initialize request data");
  1214. esp_http_client_close(client);
  1215. return err;
  1216. }
  1217. if (client->state < HTTP_STATE_CONNECTED) {
  1218. ESP_LOGD(TAG, "Begin connect to: %s://%s:%d", client->connection_info.scheme, client->connection_info.host, client->connection_info.port);
  1219. client->transport = esp_transport_list_get_transport(client->transport_list, client->connection_info.scheme);
  1220. if (client->transport == NULL) {
  1221. ESP_LOGE(TAG, "No transport found");
  1222. #ifndef CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS
  1223. if (strcasecmp(client->connection_info.scheme, "https") == 0) {
  1224. ESP_LOGE(TAG, "Please enable HTTPS at menuconfig to allow requesting via https");
  1225. }
  1226. #endif
  1227. return ESP_ERR_HTTP_INVALID_TRANSPORT;
  1228. }
  1229. if (!client->is_async) {
  1230. if (esp_transport_connect(client->transport, client->connection_info.host, client->connection_info.port, client->timeout_ms) < 0) {
  1231. ESP_LOGE(TAG, "Connection failed, sock < 0");
  1232. return ESP_ERR_HTTP_CONNECT;
  1233. }
  1234. } else {
  1235. int ret = esp_transport_connect_async(client->transport, client->connection_info.host, client->connection_info.port, client->timeout_ms);
  1236. if (ret == ASYNC_TRANS_CONNECT_FAIL) {
  1237. ESP_LOGE(TAG, "Connection failed");
  1238. if (strcasecmp(client->connection_info.scheme, "http") == 0) {
  1239. ESP_LOGE(TAG, "Asynchronous mode doesn't work for HTTP based connection");
  1240. return ESP_ERR_INVALID_ARG;
  1241. }
  1242. return ESP_ERR_HTTP_CONNECT;
  1243. } else if (ret == ASYNC_TRANS_CONNECTING) {
  1244. ESP_LOGD(TAG, "Connection not yet established");
  1245. return ESP_ERR_HTTP_CONNECTING;
  1246. }
  1247. }
  1248. client->state = HTTP_STATE_CONNECTED;
  1249. http_dispatch_event(client, HTTP_EVENT_ON_CONNECTED, NULL, 0);
  1250. http_dispatch_event_to_event_loop(HTTP_EVENT_ON_CONNECTED, &client, sizeof(esp_http_client_handle_t));
  1251. }
  1252. return ESP_OK;
  1253. }
  1254. static int http_client_prepare_first_line(esp_http_client_handle_t client, int write_len)
  1255. {
  1256. if (write_len >= 0) {
  1257. http_header_set_format(client->request->headers, "Content-Length", "%d", write_len);
  1258. } else {
  1259. esp_http_client_set_header(client, "Transfer-Encoding", "chunked");
  1260. }
  1261. const char *method = HTTP_METHOD_MAPPING[client->connection_info.method];
  1262. int first_line_len = snprintf(client->request->buffer->data,
  1263. client->buffer_size_tx, "%s %s",
  1264. method,
  1265. client->connection_info.path);
  1266. if (first_line_len >= client->buffer_size_tx) {
  1267. ESP_LOGE(TAG, "Out of buffer");
  1268. return -1;
  1269. }
  1270. if (client->connection_info.query) {
  1271. first_line_len += snprintf(client->request->buffer->data + first_line_len,
  1272. client->buffer_size_tx - first_line_len, "?%s", client->connection_info.query);
  1273. if (first_line_len >= client->buffer_size_tx) {
  1274. ESP_LOGE(TAG, "Out of buffer");
  1275. return -1;
  1276. }
  1277. }
  1278. first_line_len += snprintf(client->request->buffer->data + first_line_len,
  1279. client->buffer_size_tx - first_line_len, " %s\r\n", DEFAULT_HTTP_PROTOCOL);
  1280. if (first_line_len >= client->buffer_size_tx) {
  1281. ESP_LOGE(TAG, "Out of buffer");
  1282. return -1;
  1283. }
  1284. return first_line_len;
  1285. }
  1286. static esp_err_t esp_http_client_request_send(esp_http_client_handle_t client, int write_len)
  1287. {
  1288. int first_line_len = 0;
  1289. if (!client->first_line_prepared) {
  1290. if ((first_line_len = http_client_prepare_first_line(client, write_len)) < 0) {
  1291. return first_line_len;
  1292. }
  1293. client->first_line_prepared = true;
  1294. client->header_index = 0;
  1295. client->data_written_index = 0;
  1296. client->data_write_left = 0;
  1297. }
  1298. if (client->data_write_left > 0) {
  1299. /* sending leftover data from previous call to esp_http_client_request_send() API */
  1300. int wret = 0;
  1301. if (((wret = esp_http_client_write(client, client->request->buffer->data + client->data_written_index, client->data_write_left)) < 0)) {
  1302. ESP_LOGE(TAG, "Error write request");
  1303. return ESP_ERR_HTTP_WRITE_DATA;
  1304. }
  1305. client->data_write_left -= wret;
  1306. client->data_written_index += wret;
  1307. if (client->is_async && client->data_write_left > 0) {
  1308. return ESP_ERR_HTTP_WRITE_DATA; /* In case of EAGAIN error, we return ESP_ERR_HTTP_WRITE_DATA,
  1309. and the handling of EAGAIN should be done in the higher level APIs. */
  1310. }
  1311. }
  1312. int wlen = client->buffer_size_tx - first_line_len;
  1313. while ((client->header_index = http_header_generate_string(client->request->headers, client->header_index, client->request->buffer->data + first_line_len, &wlen))) {
  1314. if (wlen <= 0) {
  1315. break;
  1316. }
  1317. if (first_line_len) {
  1318. wlen += first_line_len;
  1319. first_line_len = 0;
  1320. }
  1321. client->request->buffer->data[wlen] = 0;
  1322. ESP_LOGD(TAG, "Write header[%d]: %s", client->header_index, client->request->buffer->data);
  1323. client->data_write_left = wlen;
  1324. client->data_written_index = 0;
  1325. while (client->data_write_left > 0) {
  1326. int wret = esp_transport_write(client->transport, client->request->buffer->data + client->data_written_index, client->data_write_left, client->timeout_ms);
  1327. if (wret <= 0) {
  1328. ESP_LOGE(TAG, "Error write request");
  1329. esp_http_client_close(client);
  1330. return ESP_ERR_HTTP_WRITE_DATA;
  1331. }
  1332. client->data_write_left -= wret;
  1333. client->data_written_index += wret;
  1334. }
  1335. wlen = client->buffer_size_tx;
  1336. }
  1337. client->data_written_index = 0;
  1338. client->data_write_left = client->post_len;
  1339. client->state = HTTP_STATE_REQ_COMPLETE_HEADER;
  1340. http_dispatch_event(client, HTTP_EVENT_HEADERS_SENT, NULL, 0);
  1341. http_dispatch_event_to_event_loop(HTTP_EVENT_HEADERS_SENT, &client, sizeof(esp_http_client_handle_t));
  1342. return ESP_OK;
  1343. }
  1344. static esp_err_t esp_http_client_send_post_data(esp_http_client_handle_t client)
  1345. {
  1346. if (client->state != HTTP_STATE_REQ_COMPLETE_HEADER) {
  1347. ESP_LOGE(TAG, "Invalid state");
  1348. return ESP_ERR_INVALID_STATE;
  1349. }
  1350. if (!(client->post_data && client->post_len)) {
  1351. goto success;
  1352. }
  1353. int wret = esp_http_client_write(client, client->post_data + client->data_written_index, client->data_write_left);
  1354. if (wret < 0) {
  1355. return wret;
  1356. }
  1357. client->data_write_left -= wret;
  1358. client->data_written_index += wret;
  1359. if (client->data_write_left <= 0) {
  1360. goto success;
  1361. } else {
  1362. return ESP_ERR_HTTP_WRITE_DATA;
  1363. }
  1364. success:
  1365. client->state = HTTP_STATE_REQ_COMPLETE_DATA;
  1366. return ESP_OK;
  1367. }
  1368. esp_err_t esp_http_client_open(esp_http_client_handle_t client, int write_len)
  1369. {
  1370. client->post_len = write_len;
  1371. esp_err_t err;
  1372. if ((err = esp_http_client_connect(client)) != ESP_OK) {
  1373. http_dispatch_event(client, HTTP_EVENT_ERROR, esp_transport_get_error_handle(client->transport), 0);
  1374. http_dispatch_event_to_event_loop(HTTP_EVENT_ERROR, &client, sizeof(esp_http_client_handle_t));
  1375. return err;
  1376. }
  1377. if ((err = esp_http_client_request_send(client, write_len)) != ESP_OK) {
  1378. http_dispatch_event(client, HTTP_EVENT_ERROR, esp_transport_get_error_handle(client->transport), 0);
  1379. http_dispatch_event_to_event_loop(HTTP_EVENT_ERROR, &client, sizeof(esp_http_client_handle_t));
  1380. return err;
  1381. }
  1382. return ESP_OK;
  1383. }
  1384. int esp_http_client_write(esp_http_client_handle_t client, const char *buffer, int len)
  1385. {
  1386. if (client->state < HTTP_STATE_REQ_COMPLETE_HEADER) {
  1387. return ESP_FAIL;
  1388. }
  1389. int wlen = 0, widx = 0;
  1390. while (len > 0) {
  1391. wlen = esp_transport_write(client->transport, buffer + widx, len, client->timeout_ms);
  1392. /* client->async_block is initialised in case of non-blocking IO, and in this case we return how
  1393. much ever data was written by the esp_transport_write() API. */
  1394. if (client->is_async || wlen <= 0) {
  1395. return wlen;
  1396. }
  1397. widx += wlen;
  1398. len -= wlen;
  1399. }
  1400. return widx;
  1401. }
  1402. esp_err_t esp_http_client_close(esp_http_client_handle_t client)
  1403. {
  1404. if (client->state >= HTTP_STATE_INIT) {
  1405. http_dispatch_event(client, HTTP_EVENT_DISCONNECTED, esp_transport_get_error_handle(client->transport), 0);
  1406. http_dispatch_event_to_event_loop(HTTP_EVENT_DISCONNECTED, &client, sizeof(esp_http_client_handle_t));
  1407. client->state = HTTP_STATE_INIT;
  1408. return esp_transport_close(client->transport);
  1409. }
  1410. return ESP_OK;
  1411. }
  1412. esp_err_t esp_http_client_set_post_field(esp_http_client_handle_t client, const char *data, int len)
  1413. {
  1414. esp_err_t err = ESP_OK;
  1415. client->post_data = (char *)data;
  1416. client->post_len = len;
  1417. ESP_LOGD(TAG, "set post file length = %d", len);
  1418. if (client->post_data) {
  1419. char *value = NULL;
  1420. if ((err = esp_http_client_get_header(client, "Content-Type", &value)) != ESP_OK) {
  1421. return err;
  1422. }
  1423. if (value == NULL) {
  1424. err = esp_http_client_set_header(client, "Content-Type", "application/x-www-form-urlencoded");
  1425. }
  1426. } else {
  1427. client->post_len = 0;
  1428. err = esp_http_client_set_header(client, "Content-Type", NULL);
  1429. }
  1430. return err;
  1431. }
  1432. int esp_http_client_get_post_field(esp_http_client_handle_t client, char **data)
  1433. {
  1434. if (client->post_data) {
  1435. *data = client->post_data;
  1436. return client->post_len;
  1437. }
  1438. return 0;
  1439. }
  1440. int esp_http_client_get_status_code(esp_http_client_handle_t client)
  1441. {
  1442. return client->response->status_code;
  1443. }
  1444. int64_t esp_http_client_get_content_length(esp_http_client_handle_t client)
  1445. {
  1446. return client->response->content_length;
  1447. }
  1448. bool esp_http_client_is_chunked_response(esp_http_client_handle_t client)
  1449. {
  1450. return client->response->is_chunked;
  1451. }
  1452. esp_http_client_transport_t esp_http_client_get_transport_type(esp_http_client_handle_t client)
  1453. {
  1454. if (!strcasecmp(client->connection_info.scheme, "https") ) {
  1455. return HTTP_TRANSPORT_OVER_SSL;
  1456. } else if (!strcasecmp(client->connection_info.scheme, "http")) {
  1457. return HTTP_TRANSPORT_OVER_TCP;
  1458. } else {
  1459. return HTTP_TRANSPORT_UNKNOWN;
  1460. }
  1461. }
  1462. void esp_http_client_add_auth(esp_http_client_handle_t client)
  1463. {
  1464. if (client == NULL) {
  1465. return;
  1466. }
  1467. if (client->state != HTTP_STATE_RES_ON_DATA_START) {
  1468. return;
  1469. }
  1470. if (client->redirect_counter >= client->max_authorization_retries) {
  1471. ESP_LOGE(TAG, "Error, reached max_authorization_retries count=%d", client->redirect_counter);
  1472. return;
  1473. }
  1474. char *auth_header = client->auth_header;
  1475. if (auth_header) {
  1476. http_utils_trim_whitespace(&auth_header);
  1477. ESP_LOGD(TAG, "UNAUTHORIZED: %s", auth_header);
  1478. client->redirect_counter++;
  1479. #ifdef CONFIG_ESP_HTTP_CLIENT_ENABLE_DIGEST_AUTH
  1480. if (http_utils_str_starts_with(auth_header, "Digest") == 0) {
  1481. ESP_LOGD(TAG, "type = Digest");
  1482. client->connection_info.auth_type = HTTP_AUTH_TYPE_DIGEST;
  1483. } else {
  1484. #endif
  1485. #ifdef CONFIG_ESP_HTTP_CLIENT_ENABLE_BASIC_AUTH
  1486. if (http_utils_str_starts_with(auth_header, "Basic") == 0) {
  1487. ESP_LOGD(TAG, "type = Basic");
  1488. client->connection_info.auth_type = HTTP_AUTH_TYPE_BASIC;
  1489. } else {
  1490. #endif
  1491. client->connection_info.auth_type = HTTP_AUTH_TYPE_NONE;
  1492. ESP_LOGE(TAG, "This authentication method is not supported: %s", auth_header);
  1493. return;
  1494. #ifdef CONFIG_ESP_HTTP_CLIENT_ENABLE_BASIC_AUTH
  1495. }
  1496. #endif
  1497. #ifdef CONFIG_ESP_HTTP_CLIENT_ENABLE_DIGEST_AUTH
  1498. }
  1499. #endif
  1500. _clear_auth_data(client);
  1501. client->auth_data->method = strdup(HTTP_METHOD_MAPPING[client->connection_info.method]);
  1502. client->auth_data->nc = 1;
  1503. client->auth_data->realm = http_utils_get_string_between(auth_header, "realm=\"", "\"");
  1504. client->auth_data->algorithm = http_utils_get_string_between(auth_header, "algorithm=", ",");
  1505. if (client->auth_data->algorithm == NULL) {
  1506. client->auth_data->algorithm = strdup("MD5");
  1507. }
  1508. client->auth_data->qop = http_utils_get_string_between(auth_header, "qop=\"", "\"");
  1509. client->auth_data->nonce = http_utils_get_string_between(auth_header, "nonce=\"", "\"");
  1510. client->auth_data->opaque = http_utils_get_string_between(auth_header, "opaque=\"", "\"");
  1511. client->process_again = 1;
  1512. } else {
  1513. client->connection_info.auth_type = HTTP_AUTH_TYPE_NONE;
  1514. ESP_LOGW(TAG, "This request requires authentication, but does not provide header information for that");
  1515. }
  1516. }
  1517. int esp_http_client_read_response(esp_http_client_handle_t client, char *buffer, int len)
  1518. {
  1519. int read_len = 0;
  1520. while (read_len < len) {
  1521. int data_read = esp_http_client_read(client, buffer + read_len, len - read_len);
  1522. if (data_read <= 0) {
  1523. return read_len;
  1524. }
  1525. read_len += data_read;
  1526. }
  1527. return read_len;
  1528. }
  1529. esp_err_t esp_http_client_flush_response(esp_http_client_handle_t client, int *len)
  1530. {
  1531. if (client == NULL) {
  1532. ESP_LOGE(TAG, "client must not be NULL");
  1533. return ESP_ERR_INVALID_ARG;
  1534. }
  1535. int read_len = 0;
  1536. while (!esp_http_client_is_complete_data_received(client)) {
  1537. int data_read = esp_http_client_get_data(client);
  1538. if (data_read < 0) {
  1539. return ESP_FAIL;
  1540. }
  1541. read_len += data_read;
  1542. }
  1543. if (len) {
  1544. *len = read_len;
  1545. }
  1546. return ESP_OK;
  1547. }
  1548. esp_err_t esp_http_client_get_url(esp_http_client_handle_t client, char *url, const int len)
  1549. {
  1550. if (client == NULL || url == NULL) {
  1551. return ESP_ERR_INVALID_ARG;
  1552. }
  1553. if (client->connection_info.host && client->connection_info.scheme && client->connection_info.path) {
  1554. snprintf(url, len, "%s://%s%s", client->connection_info.scheme, client->connection_info.host, client->connection_info.path);
  1555. return ESP_OK;
  1556. } else {
  1557. ESP_LOGE(TAG, "Failed to get URL");
  1558. }
  1559. return ESP_FAIL;
  1560. }
  1561. esp_err_t esp_http_client_get_chunk_length(esp_http_client_handle_t client, int *len)
  1562. {
  1563. if (client == NULL || len == NULL) {
  1564. return ESP_ERR_INVALID_ARG;
  1565. }
  1566. if (esp_http_client_is_chunked_response(client)) {
  1567. *len = client->response->chunk_length;
  1568. } else {
  1569. ESP_LOGE(TAG, "Response is not chunked");
  1570. return ESP_FAIL;
  1571. }
  1572. return ESP_OK;
  1573. }