esp_http_client.c 48 KB

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