esp_http_client.c 50 KB

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