esp_http_client.c 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359
  1. // Copyright 2015-2018 Espressif Systems (Shanghai) PTE LTD
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. // http://www.apache.org/licenses/LICENSE-2.0
  7. //
  8. // Unless required by applicable law or agreed to in writing, software
  9. // distributed under the License is distributed on an "AS IS" BASIS,
  10. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. // See the License for the specific language governing permissions and
  12. // limitations under the License.
  13. #include <string.h>
  14. #include "esp_system.h"
  15. #include "esp_log.h"
  16. #include "http_header.h"
  17. #include "esp_transport.h"
  18. #include "esp_transport_tcp.h"
  19. #include "http_utils.h"
  20. #include "http_auth.h"
  21. #include "sdkconfig.h"
  22. #include "esp_http_client.h"
  23. #include "errno.h"
  24. #ifdef CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS
  25. #include "esp_transport_ssl.h"
  26. #endif
  27. static const char *TAG = "HTTP_CLIENT";
  28. /**
  29. * HTTP Buffer
  30. */
  31. typedef struct {
  32. char *data; /*!< The HTTP data received from the server */
  33. int len; /*!< The HTTP data len received from the server */
  34. char *raw_data; /*!< The HTTP data after decoding */
  35. int raw_len; /*!< The HTTP data len after decoding */
  36. char *output_ptr; /*!< The destination address of the data to be copied to after decoding */
  37. } esp_http_buffer_t;
  38. /**
  39. * private HTTP Data structure
  40. */
  41. typedef struct {
  42. http_header_handle_t headers; /*!< http header */
  43. esp_http_buffer_t *buffer; /*!< data buffer as linked list */
  44. int status_code; /*!< status code (integer) */
  45. int content_length; /*!< data length */
  46. int data_offset; /*!< offset to http data (Skip header) */
  47. int data_process; /*!< data processed */
  48. int method; /*!< http method */
  49. bool is_chunked;
  50. } esp_http_data_t;
  51. typedef struct {
  52. char *url;
  53. char *scheme;
  54. char *host;
  55. int port;
  56. char *username;
  57. char *password;
  58. char *path;
  59. char *query;
  60. char *cert_pem;
  61. esp_http_client_method_t method;
  62. esp_http_client_auth_type_t auth_type;
  63. esp_http_client_transport_t transport_type;
  64. int max_store_header_size;
  65. } connection_info_t;
  66. typedef enum {
  67. HTTP_STATE_UNINIT = 0,
  68. HTTP_STATE_INIT,
  69. HTTP_STATE_CONNECTED,
  70. HTTP_STATE_REQ_COMPLETE_HEADER,
  71. HTTP_STATE_REQ_COMPLETE_DATA,
  72. HTTP_STATE_RES_COMPLETE_HEADER,
  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 process_again;
  83. struct http_parser *parser;
  84. struct http_parser_settings *parser_settings;
  85. esp_transport_list_handle_t transport_list;
  86. esp_transport_handle_t transport;
  87. esp_http_data_t *request;
  88. esp_http_data_t *response;
  89. void *user_data;
  90. esp_http_auth_data_t *auth_data;
  91. char *post_data;
  92. char *location;
  93. char *auth_header;
  94. char *current_header_key;
  95. char *current_header_value;
  96. int post_len;
  97. connection_info_t connection_info;
  98. bool is_chunk_complete;
  99. esp_http_state_t state;
  100. http_event_handle_cb event_handler;
  101. int timeout_ms;
  102. int buffer_size_rx;
  103. int buffer_size_tx;
  104. bool disable_auto_redirect;
  105. esp_http_client_event_t event;
  106. int data_written_index;
  107. int data_write_left;
  108. bool first_line_prepared;
  109. int header_index;
  110. bool is_async;
  111. };
  112. typedef struct esp_http_client esp_http_client_t;
  113. static esp_err_t _clear_connection_info(esp_http_client_handle_t client);
  114. /**
  115. * Default settings
  116. */
  117. #define DEFAULT_HTTP_PORT (80)
  118. #define DEFAULT_HTTPS_PORT (443)
  119. #define ASYNC_TRANS_CONNECT_FAIL -1
  120. #define ASYNC_TRANS_CONNECTING 0
  121. #define ASYNC_TRANS_CONNECT_PASS 1
  122. static const char *DEFAULT_HTTP_USER_AGENT = "ESP32 HTTP Client/1.0";
  123. static const char *DEFAULT_HTTP_PROTOCOL = "HTTP/1.1";
  124. static const char *DEFAULT_HTTP_PATH = "/";
  125. static int DEFAULT_MAX_REDIRECT = 10;
  126. static int DEFAULT_TIMEOUT_MS = 5000;
  127. static const char *HTTP_METHOD_MAPPING[] = {
  128. "GET",
  129. "POST",
  130. "PUT",
  131. "PATCH",
  132. "DELETE",
  133. "HEAD",
  134. "NOTIFY",
  135. "SUBSCRIBE",
  136. "UNSUBSCRIBE",
  137. "OPTIONS"
  138. };
  139. static esp_err_t esp_http_client_request_send(esp_http_client_handle_t client, int write_len);
  140. static esp_err_t esp_http_client_connect(esp_http_client_handle_t client);
  141. static esp_err_t esp_http_client_send_post_data(esp_http_client_handle_t client);
  142. static esp_err_t http_dispatch_event(esp_http_client_t *client, esp_http_client_event_id_t event_id, void *data, int len)
  143. {
  144. esp_http_client_event_t *event = &client->event;
  145. if (client->event_handler) {
  146. event->event_id = event_id;
  147. event->user_data = client->user_data;
  148. event->data = data;
  149. event->data_len = len;
  150. return client->event_handler(event);
  151. }
  152. return ESP_OK;
  153. }
  154. static int http_on_message_begin(http_parser *parser)
  155. {
  156. esp_http_client_t *client = parser->data;
  157. ESP_LOGD(TAG, "on_message_begin");
  158. client->response->is_chunked = false;
  159. client->is_chunk_complete = false;
  160. return 0;
  161. }
  162. static int http_on_url(http_parser *parser, const char *at, size_t length)
  163. {
  164. ESP_LOGD(TAG, "http_on_url");
  165. return 0;
  166. }
  167. static int http_on_status(http_parser *parser, const char *at, size_t length)
  168. {
  169. return 0;
  170. }
  171. static int http_on_header_field(http_parser *parser, const char *at, size_t length)
  172. {
  173. esp_http_client_t *client = parser->data;
  174. http_utils_assign_string(&client->current_header_key, at, length);
  175. return 0;
  176. }
  177. static int http_on_header_value(http_parser *parser, const char *at, size_t length)
  178. {
  179. esp_http_client_handle_t client = parser->data;
  180. if (client->current_header_key == NULL) {
  181. return 0;
  182. }
  183. if (strcasecmp(client->current_header_key, "Location") == 0) {
  184. http_utils_assign_string(&client->location, at, length);
  185. } else if (strcasecmp(client->current_header_key, "Transfer-Encoding") == 0
  186. && memcmp(at, "chunked", length) == 0) {
  187. client->response->is_chunked = true;
  188. } else if (strcasecmp(client->current_header_key, "WWW-Authenticate") == 0) {
  189. http_utils_assign_string(&client->auth_header, at, length);
  190. }
  191. http_utils_assign_string(&client->current_header_value, at, length);
  192. ESP_LOGD(TAG, "HEADER=%s:%s", client->current_header_key, client->current_header_value);
  193. client->event.header_key = client->current_header_key;
  194. client->event.header_value = client->current_header_value;
  195. http_dispatch_event(client, HTTP_EVENT_ON_HEADER, NULL, 0);
  196. free(client->current_header_key);
  197. free(client->current_header_value);
  198. client->current_header_key = NULL;
  199. client->current_header_value = NULL;
  200. return 0;
  201. }
  202. static int http_on_headers_complete(http_parser *parser)
  203. {
  204. esp_http_client_handle_t client = parser->data;
  205. client->response->status_code = parser->status_code;
  206. client->response->data_offset = parser->nread;
  207. client->response->content_length = parser->content_length;
  208. client->response->data_process = 0;
  209. ESP_LOGD(TAG, "http_on_headers_complete, status=%d, offset=%d, nread=%d", parser->status_code, client->response->data_offset, parser->nread);
  210. client->state = HTTP_STATE_RES_COMPLETE_HEADER;
  211. return 0;
  212. }
  213. static int http_on_body(http_parser *parser, const char *at, size_t length)
  214. {
  215. esp_http_client_t *client = parser->data;
  216. ESP_LOGD(TAG, "http_on_body %d", length);
  217. client->response->buffer->raw_data = (char *)at;
  218. if (client->response->buffer->output_ptr) {
  219. memcpy(client->response->buffer->output_ptr, (char *)at, length);
  220. client->response->buffer->output_ptr += length;
  221. }
  222. client->response->data_process += length;
  223. client->response->buffer->raw_len += length;
  224. http_dispatch_event(client, HTTP_EVENT_ON_DATA, (void *)at, length);
  225. return 0;
  226. }
  227. static int http_on_message_complete(http_parser *parser)
  228. {
  229. ESP_LOGD(TAG, "http_on_message_complete, parser=%x", (int)parser);
  230. esp_http_client_handle_t client = parser->data;
  231. client->is_chunk_complete = true;
  232. return 0;
  233. }
  234. static int http_on_chunk_complete(http_parser *parser)
  235. {
  236. ESP_LOGD(TAG, "http_on_chunk_complete");
  237. return 0;
  238. }
  239. esp_err_t esp_http_client_set_header(esp_http_client_handle_t client, const char *key, const char *value)
  240. {
  241. return http_header_set(client->request->headers, key, value);
  242. }
  243. esp_err_t esp_http_client_get_header(esp_http_client_handle_t client, const char *key, char **value)
  244. {
  245. return http_header_get(client->request->headers, key, value);
  246. }
  247. esp_err_t esp_http_client_delete_header(esp_http_client_handle_t client, const char *key)
  248. {
  249. return http_header_delete(client->request->headers, key);
  250. }
  251. esp_err_t esp_http_client_get_username(esp_http_client_handle_t client, char **value)
  252. {
  253. if (client == NULL || value == NULL) {
  254. ESP_LOGE(TAG, "client or value must not be NULL");
  255. return ESP_ERR_INVALID_ARG;
  256. }
  257. *value = client->connection_info.username;
  258. return ESP_OK;
  259. }
  260. esp_err_t esp_http_client_set_username(esp_http_client_handle_t client, const char *username)
  261. {
  262. if (client == NULL) {
  263. ESP_LOGE(TAG, "client must not be NULL");
  264. return ESP_ERR_INVALID_ARG;
  265. }
  266. if (client->connection_info.username != NULL) {
  267. free(client->connection_info.username);
  268. }
  269. client->connection_info.username = username ? strdup(username) : NULL;
  270. return ESP_OK;
  271. }
  272. esp_err_t esp_http_client_get_password(esp_http_client_handle_t client, char **value)
  273. {
  274. if (client == NULL || value == NULL) {
  275. ESP_LOGE(TAG, "client or value must not be NULL");
  276. return ESP_ERR_INVALID_ARG;
  277. }
  278. *value = client->connection_info.password;
  279. return ESP_OK;
  280. }
  281. esp_err_t esp_http_client_set_password(esp_http_client_handle_t client, char *password)
  282. {
  283. if (client == NULL) {
  284. ESP_LOGE(TAG, "client must not be NULL");
  285. return ESP_ERR_INVALID_ARG;
  286. }
  287. if (client->connection_info.password != NULL) {
  288. memset(client->connection_info.password, 0, strlen(client->connection_info.password));
  289. free(client->connection_info.password);
  290. }
  291. client->connection_info.password = password ? strdup(password) : NULL;
  292. return ESP_OK;
  293. }
  294. esp_err_t esp_http_client_set_authtype(esp_http_client_handle_t client, esp_http_client_auth_type_t auth_type)
  295. {
  296. if (client == NULL) {
  297. ESP_LOGE(TAG, "client must not be NULL");
  298. return ESP_ERR_INVALID_ARG;
  299. }
  300. client->connection_info.auth_type = auth_type;
  301. return ESP_OK;
  302. }
  303. static esp_err_t _set_config(esp_http_client_handle_t client, const esp_http_client_config_t *config)
  304. {
  305. client->connection_info.method = config->method;
  306. client->connection_info.port = config->port;
  307. client->connection_info.auth_type = config->auth_type;
  308. client->event_handler = config->event_handler;
  309. client->timeout_ms = config->timeout_ms;
  310. client->max_redirection_count = config->max_redirection_count;
  311. client->user_data = config->user_data;
  312. client->buffer_size_rx = config->buffer_size;
  313. client->buffer_size_tx = config->buffer_size_tx;
  314. client->disable_auto_redirect = config->disable_auto_redirect;
  315. if (config->buffer_size == 0) {
  316. client->buffer_size_rx = DEFAULT_HTTP_BUF_SIZE;
  317. }
  318. if (config->buffer_size_tx == 0) {
  319. client->buffer_size_tx = DEFAULT_HTTP_BUF_SIZE;
  320. }
  321. if (client->max_redirection_count == 0) {
  322. client->max_redirection_count = DEFAULT_MAX_REDIRECT;
  323. }
  324. if (config->path) {
  325. client->connection_info.path = strdup(config->path);
  326. } else {
  327. client->connection_info.path = strdup(DEFAULT_HTTP_PATH);
  328. }
  329. HTTP_MEM_CHECK(TAG, client->connection_info.path, {
  330. return ESP_ERR_NO_MEM;
  331. });
  332. if (config->host) {
  333. client->connection_info.host = strdup(config->host);
  334. HTTP_MEM_CHECK(TAG, client->connection_info.host, {
  335. _clear_connection_info(client);
  336. return ESP_ERR_NO_MEM;
  337. });
  338. }
  339. if (config->query) {
  340. client->connection_info.query = strdup(config->query);
  341. HTTP_MEM_CHECK(TAG, client->connection_info.query, {
  342. _clear_connection_info(client);
  343. return ESP_ERR_NO_MEM;
  344. });
  345. }
  346. if (config->username) {
  347. client->connection_info.username = strdup(config->username);
  348. HTTP_MEM_CHECK(TAG, client->connection_info.username, {
  349. _clear_connection_info(client);
  350. return ESP_ERR_NO_MEM;
  351. });
  352. }
  353. if (config->password) {
  354. client->connection_info.password = strdup(config->password);
  355. HTTP_MEM_CHECK(TAG, client->connection_info.password, {
  356. _clear_connection_info(client);
  357. return ESP_ERR_NO_MEM;
  358. });
  359. }
  360. if (config->transport_type == HTTP_TRANSPORT_OVER_SSL) {
  361. http_utils_assign_string(&client->connection_info.scheme, "https", 0);
  362. if (client->connection_info.port == 0) {
  363. client->connection_info.port = DEFAULT_HTTPS_PORT;
  364. }
  365. } else {
  366. http_utils_assign_string(&client->connection_info.scheme, "http", 0);
  367. if (client->connection_info.port == 0) {
  368. client->connection_info.port = DEFAULT_HTTP_PORT;
  369. }
  370. }
  371. if (client->timeout_ms == 0) {
  372. client->timeout_ms = DEFAULT_TIMEOUT_MS;
  373. }
  374. if (config->is_async) {
  375. client->is_async = true;
  376. }
  377. return ESP_OK;
  378. }
  379. static esp_err_t _clear_connection_info(esp_http_client_handle_t client)
  380. {
  381. free(client->connection_info.path);
  382. free(client->connection_info.host);
  383. free(client->connection_info.query);
  384. free(client->connection_info.username);
  385. if (client->connection_info.password) {
  386. memset(client->connection_info.password, 0, strlen(client->connection_info.password));
  387. free(client->connection_info.password);
  388. }
  389. free(client->connection_info.scheme);
  390. free(client->connection_info.url);
  391. memset(&client->connection_info, 0, sizeof(connection_info_t));
  392. return ESP_OK;
  393. }
  394. static esp_err_t _clear_auth_data(esp_http_client_handle_t client)
  395. {
  396. if (client->auth_data == NULL) {
  397. return ESP_FAIL;
  398. }
  399. free(client->auth_data->method);
  400. free(client->auth_data->realm);
  401. free(client->auth_data->algorithm);
  402. free(client->auth_data->qop);
  403. free(client->auth_data->nonce);
  404. free(client->auth_data->opaque);
  405. memset(client->auth_data, 0, sizeof(esp_http_auth_data_t));
  406. return ESP_OK;
  407. }
  408. static esp_err_t esp_http_client_prepare(esp_http_client_handle_t client)
  409. {
  410. client->process_again = 0;
  411. client->response->data_process = 0;
  412. client->first_line_prepared = false;
  413. http_parser_init(client->parser, HTTP_RESPONSE);
  414. if (client->connection_info.username) {
  415. char *auth_response = NULL;
  416. if (client->connection_info.auth_type == HTTP_AUTH_TYPE_BASIC) {
  417. auth_response = http_auth_basic(client->connection_info.username, client->connection_info.password);
  418. } else if (client->connection_info.auth_type == HTTP_AUTH_TYPE_DIGEST && client->auth_data) {
  419. client->auth_data->uri = client->connection_info.path;
  420. client->auth_data->cnonce = ((uint64_t)esp_random() << 32) + esp_random();
  421. auth_response = http_auth_digest(client->connection_info.username, client->connection_info.password, client->auth_data);
  422. client->auth_data->nc ++;
  423. }
  424. if (auth_response) {
  425. ESP_LOGD(TAG, "auth_response=%s", auth_response);
  426. esp_http_client_set_header(client, "Authorization", auth_response);
  427. free(auth_response);
  428. }
  429. }
  430. return ESP_OK;
  431. }
  432. esp_http_client_handle_t esp_http_client_init(const esp_http_client_config_t *config)
  433. {
  434. esp_http_client_handle_t client;
  435. esp_transport_handle_t tcp;
  436. bool _success;
  437. _success = (
  438. (client = calloc(1, sizeof(esp_http_client_t))) &&
  439. (client->parser = calloc(1, sizeof(struct http_parser))) &&
  440. (client->parser_settings = calloc(1, sizeof(struct http_parser_settings))) &&
  441. (client->auth_data = calloc(1, sizeof(esp_http_auth_data_t))) &&
  442. (client->request = calloc(1, sizeof(esp_http_data_t))) &&
  443. (client->request->headers = http_header_init()) &&
  444. (client->request->buffer = calloc(1, sizeof(esp_http_buffer_t))) &&
  445. (client->response = calloc(1, sizeof(esp_http_data_t))) &&
  446. (client->response->headers = http_header_init()) &&
  447. (client->response->buffer = calloc(1, sizeof(esp_http_buffer_t)))
  448. );
  449. if (!_success) {
  450. ESP_LOGE(TAG, "Error allocate memory");
  451. goto error;
  452. }
  453. _success = (
  454. (client->transport_list = esp_transport_list_init()) &&
  455. (tcp = esp_transport_tcp_init()) &&
  456. (esp_transport_set_default_port(tcp, DEFAULT_HTTP_PORT) == ESP_OK) &&
  457. (esp_transport_list_add(client->transport_list, tcp, "http") == ESP_OK)
  458. );
  459. if (!_success) {
  460. ESP_LOGE(TAG, "Error initialize transport");
  461. goto error;
  462. }
  463. #ifdef CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS
  464. esp_transport_handle_t ssl;
  465. _success = (
  466. (ssl = esp_transport_ssl_init()) &&
  467. (esp_transport_set_default_port(ssl, DEFAULT_HTTPS_PORT) == ESP_OK) &&
  468. (esp_transport_list_add(client->transport_list, ssl, "https") == ESP_OK)
  469. );
  470. if (!_success) {
  471. ESP_LOGE(TAG, "Error initialize SSL Transport");
  472. goto error;
  473. }
  474. if (config->use_global_ca_store == true) {
  475. esp_transport_ssl_enable_global_ca_store(ssl);
  476. } else if (config->cert_pem) {
  477. esp_transport_ssl_set_cert_data(ssl, config->cert_pem, strlen(config->cert_pem));
  478. }
  479. if (config->client_cert_pem) {
  480. esp_transport_ssl_set_client_cert_data(ssl, config->client_cert_pem, strlen(config->client_cert_pem));
  481. }
  482. if (config->client_key_pem) {
  483. esp_transport_ssl_set_client_key_data(ssl, config->client_key_pem, strlen(config->client_key_pem));
  484. }
  485. if (config->skip_cert_common_name_check) {
  486. esp_transport_ssl_skip_common_name_check(ssl);
  487. }
  488. #endif
  489. if (_set_config(client, config) != ESP_OK) {
  490. ESP_LOGE(TAG, "Error set configurations");
  491. goto error;
  492. }
  493. _success = (
  494. (client->request->buffer->data = malloc(client->buffer_size_tx)) &&
  495. (client->response->buffer->data = malloc(client->buffer_size_rx))
  496. );
  497. if (!_success) {
  498. ESP_LOGE(TAG, "Allocation failed");
  499. goto error;
  500. }
  501. if (config->host != NULL && config->path != NULL) {
  502. _success = (
  503. (esp_http_client_set_header(client, "User-Agent", DEFAULT_HTTP_USER_AGENT) == ESP_OK) &&
  504. (esp_http_client_set_header(client, "Host", client->connection_info.host) == ESP_OK)
  505. );
  506. if (!_success) {
  507. ESP_LOGE(TAG, "Error while setting default configurations");
  508. goto error;
  509. }
  510. } else if (config->url != NULL) {
  511. _success = (
  512. (esp_http_client_set_url(client, config->url) == ESP_OK) &&
  513. (esp_http_client_set_header(client, "User-Agent", DEFAULT_HTTP_USER_AGENT) == ESP_OK) &&
  514. (esp_http_client_set_header(client, "Host", client->connection_info.host) == ESP_OK)
  515. );
  516. if (!_success) {
  517. ESP_LOGE(TAG, "Error while setting default configurations");
  518. goto error;
  519. }
  520. } else {
  521. ESP_LOGE(TAG, "config should have either URL or host & path");
  522. goto error;
  523. }
  524. client->parser_settings->on_message_begin = http_on_message_begin;
  525. client->parser_settings->on_url = http_on_url;
  526. client->parser_settings->on_status = http_on_status;
  527. client->parser_settings->on_header_field = http_on_header_field;
  528. client->parser_settings->on_header_value = http_on_header_value;
  529. client->parser_settings->on_headers_complete = http_on_headers_complete;
  530. client->parser_settings->on_body = http_on_body;
  531. client->parser_settings->on_message_complete = http_on_message_complete;
  532. client->parser_settings->on_chunk_complete = http_on_chunk_complete;
  533. client->parser->data = client;
  534. client->event.client = client;
  535. client->state = HTTP_STATE_INIT;
  536. return client;
  537. error:
  538. esp_http_client_cleanup(client);
  539. return NULL;
  540. }
  541. esp_err_t esp_http_client_cleanup(esp_http_client_handle_t client)
  542. {
  543. if (client == NULL) {
  544. return ESP_FAIL;
  545. }
  546. esp_http_client_close(client);
  547. esp_transport_list_destroy(client->transport_list);
  548. if (client->request) {
  549. http_header_destroy(client->request->headers);
  550. if (client->request->buffer) {
  551. free(client->request->buffer->data);
  552. }
  553. free(client->request->buffer);
  554. free(client->request);
  555. }
  556. if (client->response) {
  557. http_header_destroy(client->response->headers);
  558. if (client->response->buffer) {
  559. free(client->response->buffer->data);
  560. }
  561. free(client->response->buffer);
  562. free(client->response);
  563. }
  564. free(client->parser);
  565. free(client->parser_settings);
  566. _clear_connection_info(client);
  567. _clear_auth_data(client);
  568. free(client->auth_data);
  569. free(client->current_header_key);
  570. free(client->location);
  571. free(client->auth_header);
  572. free(client);
  573. return ESP_OK;
  574. }
  575. esp_err_t esp_http_client_set_redirection(esp_http_client_handle_t client)
  576. {
  577. if (client == NULL) {
  578. return ESP_ERR_INVALID_ARG;
  579. }
  580. if (client->location == NULL) {
  581. return ESP_ERR_INVALID_ARG;
  582. }
  583. ESP_LOGD(TAG, "Redirect to %s", client->location);
  584. return esp_http_client_set_url(client, client->location);
  585. }
  586. static esp_err_t esp_http_check_response(esp_http_client_handle_t client)
  587. {
  588. if (client->redirect_counter >= client->max_redirection_count || client->disable_auto_redirect) {
  589. ESP_LOGE(TAG, "Error, reach max_redirection_count count=%d", client->redirect_counter);
  590. return ESP_ERR_HTTP_MAX_REDIRECT;
  591. }
  592. switch (client->response->status_code) {
  593. case HttpStatus_MovedPermanently:
  594. case HttpStatus_Found:
  595. case HttpStatus_TemporaryRedirect:
  596. esp_http_client_set_redirection(client);
  597. client->redirect_counter ++;
  598. client->process_again = 1;
  599. break;
  600. case HttpStatus_Unauthorized:
  601. esp_http_client_add_auth(client);
  602. }
  603. return ESP_OK;
  604. }
  605. esp_err_t esp_http_client_set_url(esp_http_client_handle_t client, const char *url)
  606. {
  607. char *old_host = NULL;
  608. struct http_parser_url purl;
  609. int old_port;
  610. if (client == NULL || url == NULL) {
  611. ESP_LOGE(TAG, "client or url must not NULL");
  612. return ESP_ERR_INVALID_ARG;
  613. }
  614. http_parser_url_init(&purl);
  615. int parser_status = http_parser_parse_url(url, strlen(url), 0, &purl);
  616. if (parser_status != 0) {
  617. ESP_LOGE(TAG, "Error parse url %s", url);
  618. return ESP_ERR_INVALID_ARG;
  619. }
  620. if (client->connection_info.host) {
  621. old_host = strdup(client->connection_info.host);
  622. }
  623. old_port = client->connection_info.port;
  624. if (purl.field_data[UF_HOST].len) {
  625. http_utils_assign_string(&client->connection_info.host, url + purl.field_data[UF_HOST].off, purl.field_data[UF_HOST].len);
  626. HTTP_MEM_CHECK(TAG, client->connection_info.host, {
  627. free(old_host);
  628. return ESP_ERR_NO_MEM;
  629. });
  630. }
  631. // Close the connection if host was changed
  632. if (old_host && client->connection_info.host
  633. && strcasecmp(old_host, (const void *)client->connection_info.host) != 0) {
  634. ESP_LOGD(TAG, "New host assign = %s", client->connection_info.host);
  635. if (esp_http_client_set_header(client, "Host", client->connection_info.host) != ESP_OK) {
  636. free(old_host);
  637. return ESP_ERR_NO_MEM;
  638. }
  639. esp_http_client_close(client);
  640. }
  641. if (old_host) {
  642. free(old_host);
  643. old_host = NULL;
  644. }
  645. if (purl.field_data[UF_SCHEMA].len) {
  646. http_utils_assign_string(&client->connection_info.scheme, url + purl.field_data[UF_SCHEMA].off, purl.field_data[UF_SCHEMA].len);
  647. HTTP_MEM_CHECK(TAG, client->connection_info.scheme, return ESP_ERR_NO_MEM);
  648. if (strcasecmp(client->connection_info.scheme, "http") == 0) {
  649. client->connection_info.port = DEFAULT_HTTP_PORT;
  650. } else if (strcasecmp(client->connection_info.scheme, "https") == 0) {
  651. client->connection_info.port = DEFAULT_HTTPS_PORT;
  652. }
  653. }
  654. if (purl.field_data[UF_PORT].len) {
  655. client->connection_info.port = strtol((const char*)(url + purl.field_data[UF_PORT].off), NULL, 10);
  656. }
  657. if (old_port != client->connection_info.port) {
  658. esp_http_client_close(client);
  659. }
  660. if (purl.field_data[UF_USERINFO].len) {
  661. char *user_info = NULL;
  662. http_utils_assign_string(&user_info, url + purl.field_data[UF_USERINFO].off, purl.field_data[UF_USERINFO].len);
  663. if (user_info) {
  664. char *username = user_info;
  665. char *password = strchr(user_info, ':');
  666. if (password) {
  667. *password = 0;
  668. password ++;
  669. http_utils_assign_string(&client->connection_info.password, password, 0);
  670. HTTP_MEM_CHECK(TAG, client->connection_info.password, return ESP_ERR_NO_MEM);
  671. }
  672. http_utils_assign_string(&client->connection_info.username, username, 0);
  673. HTTP_MEM_CHECK(TAG, client->connection_info.username, return ESP_ERR_NO_MEM);
  674. free(user_info);
  675. } else {
  676. return ESP_ERR_NO_MEM;
  677. }
  678. }
  679. //Reset path and query if there are no information
  680. if (purl.field_data[UF_PATH].len) {
  681. http_utils_assign_string(&client->connection_info.path, url + purl.field_data[UF_PATH].off, purl.field_data[UF_PATH].len);
  682. } else {
  683. http_utils_assign_string(&client->connection_info.path, "/", 0);
  684. }
  685. HTTP_MEM_CHECK(TAG, client->connection_info.path, return ESP_ERR_NO_MEM);
  686. if (purl.field_data[UF_QUERY].len) {
  687. http_utils_assign_string(&client->connection_info.query, url + purl.field_data[UF_QUERY].off, purl.field_data[UF_QUERY].len);
  688. HTTP_MEM_CHECK(TAG, client->connection_info.query, return ESP_ERR_NO_MEM);
  689. } else if (client->connection_info.query) {
  690. free(client->connection_info.query);
  691. client->connection_info.query = NULL;
  692. }
  693. return ESP_OK;
  694. }
  695. esp_err_t esp_http_client_set_method(esp_http_client_handle_t client, esp_http_client_method_t method)
  696. {
  697. client->connection_info.method = method;
  698. return ESP_OK;
  699. }
  700. static int esp_http_client_get_data(esp_http_client_handle_t client)
  701. {
  702. if (client->state < HTTP_STATE_RES_COMPLETE_HEADER) {
  703. return ESP_FAIL;
  704. }
  705. if (client->connection_info.method == HTTP_METHOD_HEAD) {
  706. return 0;
  707. }
  708. esp_http_buffer_t *res_buffer = client->response->buffer;
  709. ESP_LOGD(TAG, "data_process=%d, content_length=%d", client->response->data_process, client->response->content_length);
  710. int rlen = esp_transport_read(client->transport, res_buffer->data, client->buffer_size_rx, client->timeout_ms);
  711. if (rlen >= 0) {
  712. http_parser_execute(client->parser, client->parser_settings, res_buffer->data, rlen);
  713. }
  714. return rlen;
  715. }
  716. bool esp_http_client_is_complete_data_received(esp_http_client_handle_t client)
  717. {
  718. if (client->response->is_chunked) {
  719. if (!client->is_chunk_complete) {
  720. ESP_LOGD(TAG, "Chunks were not completely read");
  721. return false;
  722. }
  723. } else {
  724. if (client->response->data_process != client->response->content_length) {
  725. ESP_LOGD(TAG, "Data processed %d != Data specified in content length %d", client->response->data_process, client->response->content_length);
  726. return false;
  727. }
  728. }
  729. return true;
  730. }
  731. int esp_http_client_read(esp_http_client_handle_t client, char *buffer, int len)
  732. {
  733. esp_http_buffer_t *res_buffer = client->response->buffer;
  734. int rlen = ESP_FAIL, ridx = 0;
  735. if (res_buffer->raw_len) {
  736. int remain_len = client->response->buffer->raw_len;
  737. if (remain_len > len) {
  738. remain_len = len;
  739. }
  740. memcpy(buffer, res_buffer->raw_data, remain_len);
  741. res_buffer->raw_len -= remain_len;
  742. res_buffer->raw_data += remain_len;
  743. ridx = remain_len;
  744. }
  745. int need_read = len - ridx;
  746. bool is_data_remain = true;
  747. while (need_read > 0 && is_data_remain) {
  748. if (client->response->is_chunked) {
  749. is_data_remain = !client->is_chunk_complete;
  750. } else {
  751. is_data_remain = client->response->data_process < client->response->content_length;
  752. }
  753. ESP_LOGD(TAG, "is_data_remain=%d, is_chunked=%d, content_length=%d", is_data_remain, client->response->is_chunked, client->response->content_length);
  754. if (!is_data_remain) {
  755. break;
  756. }
  757. int byte_to_read = need_read;
  758. if (byte_to_read > client->buffer_size_rx) {
  759. byte_to_read = client->buffer_size_rx;
  760. }
  761. errno = 0;
  762. rlen = esp_transport_read(client->transport, res_buffer->data, byte_to_read, client->timeout_ms);
  763. ESP_LOGD(TAG, "need_read=%d, byte_to_read=%d, rlen=%d, ridx=%d", need_read, byte_to_read, rlen, ridx);
  764. if (rlen <= 0) {
  765. if (errno != 0) {
  766. esp_log_level_t sev = ESP_LOG_WARN;
  767. /* On connection close from server, recv should ideally return 0 but we have error conversion
  768. * in `tcp_transport` SSL layer which translates it `-1` and hence below additional checks */
  769. if (rlen == -1 && errno == ENOTCONN && client->response->is_chunked) {
  770. /* Explicit call to parser for invoking `message_complete` callback */
  771. http_parser_execute(client->parser, client->parser_settings, res_buffer->data, 0);
  772. /* ...and lowering the message severity, as closed connection from server side is expected in chunked transport */
  773. sev = ESP_LOG_DEBUG;
  774. }
  775. ESP_LOG_LEVEL(sev, TAG, "esp_transport_read returned:%d and errno:%d ", rlen, errno);
  776. }
  777. if (rlen < 0 && ridx == 0) {
  778. return ESP_FAIL;
  779. } else {
  780. return ridx;
  781. }
  782. }
  783. res_buffer->output_ptr = buffer + ridx;
  784. http_parser_execute(client->parser, client->parser_settings, res_buffer->data, rlen);
  785. ridx += res_buffer->raw_len;
  786. need_read -= res_buffer->raw_len;
  787. res_buffer->raw_len = 0; //clear
  788. res_buffer->output_ptr = NULL;
  789. }
  790. return ridx;
  791. }
  792. esp_err_t esp_http_client_perform(esp_http_client_handle_t client)
  793. {
  794. esp_err_t err;
  795. do {
  796. if (client->process_again) {
  797. esp_http_client_prepare(client);
  798. }
  799. switch (client->state) {
  800. /* In case of blocking esp_http_client_perform(), the following states will fall through one after the after;
  801. in case of non-blocking esp_http_client_perform(), if there is an error condition, like EINPROGRESS or EAGAIN,
  802. then the esp_http_client_perform() API will return ESP_ERR_HTTP_EAGAIN error. The user may call
  803. esp_http_client_perform API again, and for this reason, we maintain the states */
  804. case HTTP_STATE_INIT:
  805. if ((err = esp_http_client_connect(client)) != ESP_OK) {
  806. if (client->is_async && err == ESP_ERR_HTTP_CONNECTING) {
  807. return ESP_ERR_HTTP_EAGAIN;
  808. }
  809. return err;
  810. }
  811. /* falls through */
  812. case HTTP_STATE_CONNECTED:
  813. if ((err = esp_http_client_request_send(client, client->post_len)) != ESP_OK) {
  814. if (client->is_async && errno == EAGAIN) {
  815. return ESP_ERR_HTTP_EAGAIN;
  816. }
  817. return err;
  818. }
  819. /* falls through */
  820. case HTTP_STATE_REQ_COMPLETE_HEADER:
  821. if ((err = esp_http_client_send_post_data(client)) != ESP_OK) {
  822. if (client->is_async && errno == EAGAIN) {
  823. return ESP_ERR_HTTP_EAGAIN;
  824. }
  825. return err;
  826. }
  827. /* falls through */
  828. case HTTP_STATE_REQ_COMPLETE_DATA:
  829. if (esp_http_client_fetch_headers(client) < 0) {
  830. if (client->is_async && errno == EAGAIN) {
  831. return ESP_ERR_HTTP_EAGAIN;
  832. }
  833. return ESP_ERR_HTTP_FETCH_HEADER;
  834. }
  835. /* falls through */
  836. case HTTP_STATE_RES_COMPLETE_HEADER:
  837. if ((err = esp_http_check_response(client)) != ESP_OK) {
  838. ESP_LOGE(TAG, "Error response");
  839. return err;
  840. }
  841. while (client->response->is_chunked && !client->is_chunk_complete) {
  842. if (esp_http_client_get_data(client) <= 0) {
  843. if (client->is_async && errno == EAGAIN) {
  844. return ESP_ERR_HTTP_EAGAIN;
  845. }
  846. ESP_LOGD(TAG, "Read finish or server requests close");
  847. break;
  848. }
  849. }
  850. while (client->response->data_process < client->response->content_length) {
  851. if (esp_http_client_get_data(client) <= 0) {
  852. if (client->is_async && errno == EAGAIN) {
  853. return ESP_ERR_HTTP_EAGAIN;
  854. }
  855. ESP_LOGD(TAG, "Read finish or server requests close");
  856. break;
  857. }
  858. }
  859. http_dispatch_event(client, HTTP_EVENT_ON_FINISH, NULL, 0);
  860. if (!http_should_keep_alive(client->parser)) {
  861. ESP_LOGD(TAG, "Close connection");
  862. esp_http_client_close(client);
  863. } else {
  864. if (client->state > HTTP_STATE_CONNECTED) {
  865. client->state = HTTP_STATE_CONNECTED;
  866. client->first_line_prepared = false;
  867. }
  868. }
  869. break;
  870. default:
  871. break;
  872. }
  873. } while (client->process_again);
  874. return ESP_OK;
  875. }
  876. int esp_http_client_fetch_headers(esp_http_client_handle_t client)
  877. {
  878. if (client->state < HTTP_STATE_REQ_COMPLETE_HEADER) {
  879. return ESP_FAIL;
  880. }
  881. client->state = HTTP_STATE_REQ_COMPLETE_DATA;
  882. esp_http_buffer_t *buffer = client->response->buffer;
  883. client->response->status_code = -1;
  884. while (client->state < HTTP_STATE_RES_COMPLETE_HEADER) {
  885. buffer->len = esp_transport_read(client->transport, buffer->data, client->buffer_size_rx, client->timeout_ms);
  886. if (buffer->len <= 0) {
  887. return ESP_FAIL;
  888. }
  889. http_parser_execute(client->parser, client->parser_settings, buffer->data, buffer->len);
  890. }
  891. ESP_LOGD(TAG, "content_length = %d", client->response->content_length);
  892. if (client->response->content_length <= 0) {
  893. client->response->is_chunked = true;
  894. return 0;
  895. }
  896. return client->response->content_length;
  897. }
  898. static esp_err_t esp_http_client_connect(esp_http_client_handle_t client)
  899. {
  900. esp_err_t err;
  901. if (client->state == HTTP_STATE_UNINIT) {
  902. ESP_LOGE(TAG, "Client has not been initialized");
  903. return ESP_ERR_INVALID_STATE;
  904. }
  905. if ((err = esp_http_client_prepare(client)) != ESP_OK) {
  906. ESP_LOGE(TAG, "Failed to initialize request data");
  907. esp_http_client_close(client);
  908. return err;
  909. }
  910. if (client->state < HTTP_STATE_CONNECTED) {
  911. ESP_LOGD(TAG, "Begin connect to: %s://%s:%d", client->connection_info.scheme, client->connection_info.host, client->connection_info.port);
  912. client->transport = esp_transport_list_get_transport(client->transport_list, client->connection_info.scheme);
  913. if (client->transport == NULL) {
  914. ESP_LOGE(TAG, "No transport found");
  915. #ifndef CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS
  916. if (strcasecmp(client->connection_info.scheme, "https") == 0) {
  917. ESP_LOGE(TAG, "Please enable HTTPS at menuconfig to allow requesting via https");
  918. }
  919. #endif
  920. return ESP_ERR_HTTP_INVALID_TRANSPORT;
  921. }
  922. if (!client->is_async) {
  923. if (esp_transport_connect(client->transport, client->connection_info.host, client->connection_info.port, client->timeout_ms) < 0) {
  924. ESP_LOGE(TAG, "Connection failed, sock < 0");
  925. return ESP_ERR_HTTP_CONNECT;
  926. }
  927. } else {
  928. int ret = esp_transport_connect_async(client->transport, client->connection_info.host, client->connection_info.port, client->timeout_ms);
  929. if (ret == ASYNC_TRANS_CONNECT_FAIL) {
  930. ESP_LOGE(TAG, "Connection failed");
  931. if (strcasecmp(client->connection_info.scheme, "http") == 0) {
  932. ESP_LOGE(TAG, "Asynchronous mode doesn't work for HTTP based connection");
  933. return ESP_ERR_INVALID_ARG;
  934. }
  935. return ESP_ERR_HTTP_CONNECT;
  936. } else if (ret == ASYNC_TRANS_CONNECTING) {
  937. ESP_LOGD(TAG, "Connection not yet established");
  938. return ESP_ERR_HTTP_CONNECTING;
  939. }
  940. }
  941. client->state = HTTP_STATE_CONNECTED;
  942. http_dispatch_event(client, HTTP_EVENT_ON_CONNECTED, NULL, 0);
  943. }
  944. return ESP_OK;
  945. }
  946. static int http_client_prepare_first_line(esp_http_client_handle_t client, int write_len)
  947. {
  948. if (write_len >= 0) {
  949. http_header_set_format(client->request->headers, "Content-Length", "%d", write_len);
  950. } else {
  951. esp_http_client_set_header(client, "Transfer-Encoding", "chunked");
  952. esp_http_client_set_method(client, HTTP_METHOD_POST);
  953. }
  954. const char *method = HTTP_METHOD_MAPPING[client->connection_info.method];
  955. int first_line_len = snprintf(client->request->buffer->data,
  956. client->buffer_size_tx, "%s %s",
  957. method,
  958. client->connection_info.path);
  959. if (first_line_len >= client->buffer_size_tx) {
  960. ESP_LOGE(TAG, "Out of buffer");
  961. return -1;
  962. }
  963. if (client->connection_info.query) {
  964. first_line_len += snprintf(client->request->buffer->data + first_line_len,
  965. client->buffer_size_tx - first_line_len, "?%s", client->connection_info.query);
  966. if (first_line_len >= client->buffer_size_tx) {
  967. ESP_LOGE(TAG, "Out of buffer");
  968. return -1;
  969. }
  970. }
  971. first_line_len += snprintf(client->request->buffer->data + first_line_len,
  972. client->buffer_size_tx - first_line_len, " %s\r\n", DEFAULT_HTTP_PROTOCOL);
  973. if (first_line_len >= client->buffer_size_tx) {
  974. ESP_LOGE(TAG, "Out of buffer");
  975. return -1;
  976. }
  977. return first_line_len;
  978. }
  979. static esp_err_t esp_http_client_request_send(esp_http_client_handle_t client, int write_len)
  980. {
  981. int first_line_len = 0;
  982. if (!client->first_line_prepared) {
  983. if ((first_line_len = http_client_prepare_first_line(client, write_len)) < 0) {
  984. return first_line_len;
  985. }
  986. client->first_line_prepared = true;
  987. client->header_index = 0;
  988. client->data_written_index = 0;
  989. client->data_write_left = 0;
  990. }
  991. if (client->data_write_left > 0) {
  992. /* sending leftover data from previous call to esp_http_client_request_send() API */
  993. int wret = 0;
  994. if (((wret = esp_http_client_write(client, client->request->buffer->data + client->data_written_index, client->data_write_left)) < 0)) {
  995. ESP_LOGE(TAG, "Error write request");
  996. return ESP_ERR_HTTP_WRITE_DATA;
  997. }
  998. client->data_write_left -= wret;
  999. client->data_written_index += wret;
  1000. if (client->is_async && client->data_write_left > 0) {
  1001. return ESP_ERR_HTTP_WRITE_DATA; /* In case of EAGAIN error, we return ESP_ERR_HTTP_WRITE_DATA,
  1002. and the handling of EAGAIN should be done in the higher level APIs. */
  1003. }
  1004. }
  1005. int wlen = client->buffer_size_tx - first_line_len;
  1006. while ((client->header_index = http_header_generate_string(client->request->headers, client->header_index, client->request->buffer->data + first_line_len, &wlen))) {
  1007. if (wlen <= 0) {
  1008. break;
  1009. }
  1010. if (first_line_len) {
  1011. wlen += first_line_len;
  1012. first_line_len = 0;
  1013. }
  1014. client->request->buffer->data[wlen] = 0;
  1015. ESP_LOGD(TAG, "Write header[%d]: %s", client->header_index, client->request->buffer->data);
  1016. client->data_write_left = wlen;
  1017. client->data_written_index = 0;
  1018. while (client->data_write_left > 0) {
  1019. int wret = esp_transport_write(client->transport, client->request->buffer->data + client->data_written_index, client->data_write_left, client->timeout_ms);
  1020. if (wret <= 0) {
  1021. ESP_LOGE(TAG, "Error write request");
  1022. esp_http_client_close(client);
  1023. return ESP_ERR_HTTP_WRITE_DATA;
  1024. }
  1025. client->data_write_left -= wret;
  1026. client->data_written_index += wret;
  1027. }
  1028. wlen = client->buffer_size_tx;
  1029. }
  1030. client->data_written_index = 0;
  1031. client->data_write_left = client->post_len;
  1032. http_dispatch_event(client, HTTP_EVENT_HEADERS_SENT, NULL, 0);
  1033. client->state = HTTP_STATE_REQ_COMPLETE_HEADER;
  1034. return ESP_OK;
  1035. }
  1036. static esp_err_t esp_http_client_send_post_data(esp_http_client_handle_t client)
  1037. {
  1038. if (client->state != HTTP_STATE_REQ_COMPLETE_HEADER) {
  1039. ESP_LOGE(TAG, "Invalid state");
  1040. return ESP_ERR_INVALID_STATE;
  1041. }
  1042. if (!(client->post_data && client->post_len)) {
  1043. goto success;
  1044. }
  1045. int wret = esp_http_client_write(client, client->post_data + client->data_written_index, client->data_write_left);
  1046. if (wret < 0) {
  1047. return wret;
  1048. }
  1049. client->data_write_left -= wret;
  1050. client->data_written_index += wret;
  1051. if (client->data_write_left <= 0) {
  1052. goto success;
  1053. } else {
  1054. return ESP_ERR_HTTP_WRITE_DATA;
  1055. }
  1056. success:
  1057. client->state = HTTP_STATE_REQ_COMPLETE_DATA;
  1058. return ESP_OK;
  1059. }
  1060. esp_err_t esp_http_client_open(esp_http_client_handle_t client, int write_len)
  1061. {
  1062. client->post_len = write_len;
  1063. esp_err_t err;
  1064. if ((err = esp_http_client_connect(client)) != ESP_OK) {
  1065. return err;
  1066. }
  1067. if ((err = esp_http_client_request_send(client, write_len)) != ESP_OK) {
  1068. return err;
  1069. }
  1070. return ESP_OK;
  1071. }
  1072. int esp_http_client_write(esp_http_client_handle_t client, const char *buffer, int len)
  1073. {
  1074. if (client->state < HTTP_STATE_REQ_COMPLETE_HEADER) {
  1075. return ESP_FAIL;
  1076. }
  1077. int wlen = 0, widx = 0;
  1078. while (len > 0) {
  1079. wlen = esp_transport_write(client->transport, buffer + widx, len, client->timeout_ms);
  1080. /* client->async_block is initialised in case of non-blocking IO, and in this case we return how
  1081. much ever data was written by the esp_transport_write() API. */
  1082. if (client->is_async || wlen <= 0) {
  1083. return wlen;
  1084. }
  1085. widx += wlen;
  1086. len -= wlen;
  1087. }
  1088. return widx;
  1089. }
  1090. esp_err_t esp_http_client_close(esp_http_client_handle_t client)
  1091. {
  1092. if (client->state >= HTTP_STATE_INIT) {
  1093. http_dispatch_event(client, HTTP_EVENT_DISCONNECTED, esp_transport_get_error_handle(client->transport), 0);
  1094. client->state = HTTP_STATE_INIT;
  1095. return esp_transport_close(client->transport);
  1096. }
  1097. return ESP_OK;
  1098. }
  1099. esp_err_t esp_http_client_set_post_field(esp_http_client_handle_t client, const char *data, int len)
  1100. {
  1101. esp_err_t err = ESP_OK;
  1102. client->post_data = (char *)data;
  1103. client->post_len = len;
  1104. ESP_LOGD(TAG, "set post file length = %d", len);
  1105. if (client->post_data) {
  1106. char *value = NULL;
  1107. if ((err = esp_http_client_get_header(client, "Content-Type", &value)) != ESP_OK) {
  1108. return err;
  1109. }
  1110. if (value == NULL) {
  1111. err = esp_http_client_set_header(client, "Content-Type", "application/x-www-form-urlencoded");
  1112. }
  1113. } else {
  1114. client->post_len = 0;
  1115. err = esp_http_client_set_header(client, "Content-Type", NULL);
  1116. }
  1117. return err;
  1118. }
  1119. int esp_http_client_get_post_field(esp_http_client_handle_t client, char **data)
  1120. {
  1121. if (client->post_data) {
  1122. *data = client->post_data;
  1123. return client->post_len;
  1124. }
  1125. return 0;
  1126. }
  1127. int esp_http_client_get_status_code(esp_http_client_handle_t client)
  1128. {
  1129. return client->response->status_code;
  1130. }
  1131. int esp_http_client_get_content_length(esp_http_client_handle_t client)
  1132. {
  1133. return client->response->content_length;
  1134. }
  1135. bool esp_http_client_is_chunked_response(esp_http_client_handle_t client)
  1136. {
  1137. return client->response->is_chunked;
  1138. }
  1139. esp_http_client_transport_t esp_http_client_get_transport_type(esp_http_client_handle_t client)
  1140. {
  1141. if (!strcasecmp(client->connection_info.scheme, "https") ) {
  1142. return HTTP_TRANSPORT_OVER_SSL;
  1143. } else if (!strcasecmp(client->connection_info.scheme, "http")) {
  1144. return HTTP_TRANSPORT_OVER_TCP;
  1145. } else {
  1146. return HTTP_TRANSPORT_UNKNOWN;
  1147. }
  1148. }
  1149. void esp_http_client_add_auth(esp_http_client_handle_t client)
  1150. {
  1151. if (client == NULL) {
  1152. return;
  1153. }
  1154. if (client->state != HTTP_STATE_RES_COMPLETE_HEADER) {
  1155. return;
  1156. }
  1157. char *auth_header = client->auth_header;
  1158. if (auth_header) {
  1159. http_utils_trim_whitespace(&auth_header);
  1160. ESP_LOGD(TAG, "UNAUTHORIZED: %s", auth_header);
  1161. client->redirect_counter++;
  1162. if (http_utils_str_starts_with(auth_header, "Digest") == 0) {
  1163. ESP_LOGD(TAG, "type = Digest");
  1164. client->connection_info.auth_type = HTTP_AUTH_TYPE_DIGEST;
  1165. #ifdef CONFIG_ESP_HTTP_CLIENT_ENABLE_BASIC_AUTH
  1166. } else if (http_utils_str_starts_with(auth_header, "Basic") == 0) {
  1167. ESP_LOGD(TAG, "type = Basic");
  1168. client->connection_info.auth_type = HTTP_AUTH_TYPE_BASIC;
  1169. #endif
  1170. } else {
  1171. client->connection_info.auth_type = HTTP_AUTH_TYPE_NONE;
  1172. ESP_LOGE(TAG, "This authentication method is not supported: %s", auth_header);
  1173. return;
  1174. }
  1175. _clear_auth_data(client);
  1176. client->auth_data->method = strdup(HTTP_METHOD_MAPPING[client->connection_info.method]);
  1177. client->auth_data->nc = 1;
  1178. client->auth_data->realm = http_utils_get_string_between(auth_header, "realm=\"", "\"");
  1179. client->auth_data->algorithm = http_utils_get_string_between(auth_header, "algorithm=", ",");
  1180. client->auth_data->qop = http_utils_get_string_between(auth_header, "qop=\"", "\"");
  1181. client->auth_data->nonce = http_utils_get_string_between(auth_header, "nonce=\"", "\"");
  1182. client->auth_data->opaque = http_utils_get_string_between(auth_header, "opaque=\"", "\"");
  1183. client->process_again = 1;
  1184. } else {
  1185. client->connection_info.auth_type = HTTP_AUTH_TYPE_NONE;
  1186. ESP_LOGW(TAG, "This request requires authentication, but does not provide header information for that");
  1187. }
  1188. }
  1189. int esp_http_client_read_response(esp_http_client_handle_t client, char *buffer, int len)
  1190. {
  1191. int read_len = 0;
  1192. while (read_len < len) {
  1193. int data_read = esp_http_client_read(client, buffer + read_len, len - read_len);
  1194. if (data_read <= 0) {
  1195. return read_len;
  1196. }
  1197. read_len += data_read;
  1198. }
  1199. return read_len;
  1200. }
  1201. esp_err_t esp_http_client_get_url(esp_http_client_handle_t client, char *url, const int len)
  1202. {
  1203. if (client == NULL || url == NULL) {
  1204. return ESP_ERR_INVALID_ARG;
  1205. }
  1206. if (client->connection_info.host && client->connection_info.scheme && client->connection_info.path) {
  1207. snprintf(url, len, "%s://%s%s", client->connection_info.scheme, client->connection_info.host, client->connection_info.path);
  1208. return ESP_OK;
  1209. } else {
  1210. ESP_LOGE(TAG, "Failed to get URL");
  1211. }
  1212. return ESP_FAIL;
  1213. }