esp_http_client.c 54 KB

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