esp_http_client.c 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036
  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 "transport.h"
  18. #include "transport_tcp.h"
  19. #include "http_utils.h"
  20. #include "http_auth.h"
  21. #include "sdkconfig.h"
  22. #include "transport.h"
  23. #include "esp_http_client.h"
  24. #ifdef CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS
  25. #include "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. transport_list_handle_t transport_list;
  86. 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;
  103. bool disable_auto_redirect;
  104. esp_http_client_event_t event;
  105. };
  106. typedef struct esp_http_client esp_http_client_t;
  107. static esp_err_t _clear_connection_info(esp_http_client_handle_t client);
  108. /**
  109. * Default settings
  110. */
  111. #define DEFAULT_HTTP_PORT (80)
  112. #define DEFAULT_HTTPS_PORT (443)
  113. static const char *DEFAULT_HTTP_USER_AGENT = "ESP32 HTTP Client/1.0";
  114. static const char *DEFAULT_HTTP_PROTOCOL = "HTTP/1.1";
  115. static const char *DEFAULT_HTTP_PATH = "/";
  116. static int DEFAULT_MAX_REDIRECT = 10;
  117. static int DEFAULT_TIMEOUT_MS = 5000;
  118. static const char *HTTP_METHOD_MAPPING[] = {
  119. "GET",
  120. "POST",
  121. "PUT",
  122. "PATCH",
  123. "DELETE",
  124. "HEAD"
  125. };
  126. /**
  127. * Enum for the HTTP status codes.
  128. */
  129. enum HttpStatus_Code
  130. {
  131. /* 3xx - Redirection */
  132. HttpStatus_MovedPermanently = 301,
  133. HttpStatus_Found = 302,
  134. /* 4xx - Client Error */
  135. HttpStatus_Unauthorized = 401
  136. };
  137. static esp_err_t http_dispatch_event(esp_http_client_t *client, esp_http_client_event_id_t event_id, void *data, int len)
  138. {
  139. esp_http_client_event_t *event = &client->event;
  140. if (client->event_handler) {
  141. event->event_id = event_id;
  142. event->user_data = client->user_data;
  143. event->data = data;
  144. event->data_len = len;
  145. return client->event_handler(event);
  146. }
  147. return ESP_OK;
  148. }
  149. static int http_on_message_begin(http_parser *parser)
  150. {
  151. esp_http_client_t *client = parser->data;
  152. ESP_LOGD(TAG, "on_message_begin");
  153. client->response->is_chunked = false;
  154. client->is_chunk_complete = false;
  155. return 0;
  156. }
  157. static int http_on_url(http_parser *parser, const char *at, size_t length)
  158. {
  159. ESP_LOGD(TAG, "http_on_url");
  160. return 0;
  161. }
  162. static int http_on_status(http_parser *parser, const char *at, size_t length)
  163. {
  164. return 0;
  165. }
  166. static int http_on_header_field(http_parser *parser, const char *at, size_t length)
  167. {
  168. esp_http_client_t *client = parser->data;
  169. http_utils_assign_string(&client->current_header_key, at, length);
  170. return 0;
  171. }
  172. static int http_on_header_value(http_parser *parser, const char *at, size_t length)
  173. {
  174. esp_http_client_handle_t client = parser->data;
  175. if (client->current_header_key == NULL) {
  176. return 0;
  177. }
  178. if (strcasecmp(client->current_header_key, "Location") == 0) {
  179. http_utils_assign_string(&client->location, at, length);
  180. } else if (strcasecmp(client->current_header_key, "Transfer-Encoding") == 0
  181. && memcmp(at, "chunked", length) == 0) {
  182. client->response->is_chunked = true;
  183. } else if (strcasecmp(client->current_header_key, "WWW-Authenticate") == 0) {
  184. http_utils_assign_string(&client->auth_header, at, length);
  185. }
  186. http_utils_assign_string(&client->current_header_value, at, length);
  187. ESP_LOGD(TAG, "HEADER=%s:%s", client->current_header_key, client->current_header_value);
  188. client->event.header_key = client->current_header_key;
  189. client->event.header_value = client->current_header_value;
  190. http_dispatch_event(client, HTTP_EVENT_ON_HEADER, NULL, 0);
  191. free(client->current_header_key);
  192. free(client->current_header_value);
  193. client->current_header_key = NULL;
  194. client->current_header_value = NULL;
  195. return 0;
  196. }
  197. static int http_on_headers_complete(http_parser *parser)
  198. {
  199. esp_http_client_handle_t client = parser->data;
  200. client->response->status_code = parser->status_code;
  201. client->response->data_offset = parser->nread;
  202. client->response->content_length = parser->content_length;
  203. client->response->data_process = 0;
  204. ESP_LOGD(TAG, "http_on_headers_complete, status=%d, offset=%d, nread=%d", parser->status_code, client->response->data_offset, parser->nread);
  205. client->state = HTTP_STATE_RES_COMPLETE_HEADER;
  206. return 0;
  207. }
  208. static int http_on_body(http_parser *parser, const char *at, size_t length)
  209. {
  210. esp_http_client_t *client = parser->data;
  211. ESP_LOGD(TAG, "http_on_body %d", length);
  212. client->response->buffer->raw_data = (char *)at;
  213. if (client->response->buffer->output_ptr) {
  214. memcpy(client->response->buffer->output_ptr, (char *)at, length);
  215. client->response->buffer->output_ptr += length;
  216. }
  217. client->response->data_process += length;
  218. client->response->buffer->raw_len += length;
  219. http_dispatch_event(client, HTTP_EVENT_ON_DATA, (void *)at, length);
  220. return 0;
  221. }
  222. static int http_on_message_complete(http_parser *parser)
  223. {
  224. ESP_LOGD(TAG, "http_on_message_complete, parser=%x", (int)parser);
  225. esp_http_client_handle_t client = parser->data;
  226. client->is_chunk_complete = true;
  227. return 0;
  228. }
  229. static int http_on_chunk_complete(http_parser *parser)
  230. {
  231. ESP_LOGD(TAG, "http_on_chunk_complete");
  232. return 0;
  233. }
  234. esp_err_t esp_http_client_set_header(esp_http_client_handle_t client, const char *key, const char *value)
  235. {
  236. return http_header_set(client->request->headers, key, value);
  237. }
  238. esp_err_t esp_http_client_get_header(esp_http_client_handle_t client, const char *key, char **value)
  239. {
  240. return http_header_get(client->request->headers, key, value);
  241. }
  242. esp_err_t esp_http_client_delete_header(esp_http_client_handle_t client, const char *key)
  243. {
  244. return http_header_delete(client->request->headers, key);
  245. }
  246. static esp_err_t _set_config(esp_http_client_handle_t client, const esp_http_client_config_t *config)
  247. {
  248. client->connection_info.method = config->method;
  249. client->connection_info.port = config->port;
  250. client->connection_info.auth_type = config->auth_type;
  251. client->event_handler = config->event_handler;
  252. client->timeout_ms = config->timeout_ms;
  253. client->max_redirection_count = config->max_redirection_count;
  254. client->user_data = config->user_data;
  255. client->buffer_size = config->buffer_size;
  256. client->disable_auto_redirect = config->disable_auto_redirect;
  257. if (config->buffer_size == 0) {
  258. client->buffer_size = DEFAULT_HTTP_BUF_SIZE;
  259. }
  260. if (client->max_redirection_count == 0) {
  261. client->max_redirection_count = DEFAULT_MAX_REDIRECT;
  262. }
  263. if (config->path) {
  264. client->connection_info.path = strdup(config->path);
  265. } else {
  266. client->connection_info.path = strdup(DEFAULT_HTTP_PATH);
  267. }
  268. HTTP_MEM_CHECK(TAG, client->connection_info.path, {
  269. return ESP_ERR_NO_MEM;
  270. });
  271. if (config->host) {
  272. client->connection_info.host = strdup(config->host);
  273. HTTP_MEM_CHECK(TAG, client->connection_info.host, {
  274. _clear_connection_info(client);
  275. return ESP_ERR_NO_MEM;
  276. });
  277. }
  278. if (config->query) {
  279. client->connection_info.query = strdup(config->query);
  280. HTTP_MEM_CHECK(TAG, client->connection_info.query, {
  281. _clear_connection_info(client);
  282. return ESP_ERR_NO_MEM;
  283. });
  284. }
  285. if (config->username) {
  286. client->connection_info.username = strdup(config->username);
  287. HTTP_MEM_CHECK(TAG, client->connection_info.username, {
  288. _clear_connection_info(client);
  289. return ESP_ERR_NO_MEM;
  290. });
  291. }
  292. if (config->password) {
  293. client->connection_info.password = strdup(config->password);
  294. HTTP_MEM_CHECK(TAG, client->connection_info.password, {
  295. _clear_connection_info(client);
  296. return ESP_ERR_NO_MEM;
  297. });
  298. }
  299. if (config->transport_type == HTTP_TRANSPORT_OVER_SSL) {
  300. http_utils_assign_string(&client->connection_info.scheme, "https", 0);
  301. if (client->connection_info.port == 0) {
  302. client->connection_info.port = DEFAULT_HTTPS_PORT;
  303. }
  304. } else {
  305. http_utils_assign_string(&client->connection_info.scheme, "http", 0);
  306. if (client->connection_info.port == 0) {
  307. client->connection_info.port = DEFAULT_HTTP_PORT;
  308. }
  309. }
  310. if (client->timeout_ms == 0) {
  311. client->timeout_ms = DEFAULT_TIMEOUT_MS;
  312. }
  313. return ESP_OK;
  314. }
  315. static esp_err_t _clear_connection_info(esp_http_client_handle_t client)
  316. {
  317. free(client->connection_info.path);
  318. free(client->connection_info.host);
  319. free(client->connection_info.query);
  320. free(client->connection_info.username);
  321. if (client->connection_info.password) {
  322. memset(client->connection_info.password, 0, strlen(client->connection_info.password));
  323. free(client->connection_info.password);
  324. }
  325. free(client->connection_info.scheme);
  326. free(client->connection_info.url);
  327. memset(&client->connection_info, 0, sizeof(connection_info_t));
  328. return ESP_OK;
  329. }
  330. static esp_err_t _clear_auth_data(esp_http_client_handle_t client)
  331. {
  332. if (client->auth_data == NULL) {
  333. return ESP_FAIL;
  334. }
  335. free(client->auth_data->method);
  336. free(client->auth_data->realm);
  337. free(client->auth_data->algorithm);
  338. free(client->auth_data->qop);
  339. free(client->auth_data->nonce);
  340. free(client->auth_data->opaque);
  341. memset(client->auth_data, 0, sizeof(esp_http_auth_data_t));
  342. return ESP_OK;
  343. }
  344. static esp_err_t esp_http_client_prepare(esp_http_client_handle_t client)
  345. {
  346. client->process_again = 0;
  347. client->response->data_process = 0;
  348. http_parser_init(client->parser, HTTP_RESPONSE);
  349. if (client->connection_info.username) {
  350. char *auth_response = NULL;
  351. if (client->connection_info.auth_type == HTTP_AUTH_TYPE_BASIC) {
  352. auth_response = http_auth_basic(client->connection_info.username, client->connection_info.password);
  353. } else if (client->connection_info.auth_type == HTTP_AUTH_TYPE_DIGEST && client->auth_data) {
  354. client->auth_data->uri = client->connection_info.path;
  355. client->auth_data->cnonce = ((uint64_t)esp_random() << 32) + esp_random();
  356. auth_response = http_auth_digest(client->connection_info.username, client->connection_info.password, client->auth_data);
  357. client->auth_data->nc ++;
  358. }
  359. if (auth_response) {
  360. ESP_LOGD(TAG, "auth_response=%s", auth_response);
  361. esp_http_client_set_header(client, "Authorization", auth_response);
  362. free(auth_response);
  363. }
  364. }
  365. return ESP_OK;
  366. }
  367. esp_http_client_handle_t esp_http_client_init(const esp_http_client_config_t *config)
  368. {
  369. esp_http_client_handle_t client;
  370. transport_handle_t tcp;
  371. bool _success;
  372. _success = (
  373. (client = calloc(1, sizeof(esp_http_client_t))) &&
  374. (client->parser = calloc(1, sizeof(struct http_parser))) &&
  375. (client->parser_settings = calloc(1, sizeof(struct http_parser_settings))) &&
  376. (client->auth_data = calloc(1, sizeof(esp_http_auth_data_t))) &&
  377. (client->request = calloc(1, sizeof(esp_http_data_t))) &&
  378. (client->request->headers = http_header_init()) &&
  379. (client->request->buffer = calloc(1, sizeof(esp_http_buffer_t))) &&
  380. (client->response = calloc(1, sizeof(esp_http_data_t))) &&
  381. (client->response->headers = http_header_init()) &&
  382. (client->response->buffer = calloc(1, sizeof(esp_http_buffer_t)))
  383. );
  384. if (!_success) {
  385. ESP_LOGE(TAG, "Error allocate memory");
  386. esp_http_client_cleanup(client);
  387. return NULL;
  388. }
  389. _success = (
  390. (client->transport_list = transport_list_init()) &&
  391. (tcp = transport_tcp_init()) &&
  392. (transport_set_default_port(tcp, DEFAULT_HTTP_PORT) == ESP_OK) &&
  393. (transport_list_add(client->transport_list, tcp, "http") == ESP_OK)
  394. );
  395. if (!_success) {
  396. ESP_LOGE(TAG, "Error initialize transport");
  397. esp_http_client_cleanup(client);
  398. return NULL;
  399. }
  400. #ifdef CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS
  401. transport_handle_t ssl;
  402. _success = (
  403. (ssl = transport_ssl_init()) &&
  404. (transport_set_default_port(ssl, DEFAULT_HTTPS_PORT) == ESP_OK) &&
  405. (transport_list_add(client->transport_list, ssl, "https") == ESP_OK)
  406. );
  407. if (!_success) {
  408. ESP_LOGE(TAG, "Error initialize SSL Transport");
  409. esp_http_client_cleanup(client);
  410. return NULL;
  411. }
  412. if (config->cert_pem) {
  413. transport_ssl_set_cert_data(ssl, config->cert_pem, strlen(config->cert_pem));
  414. }
  415. #endif
  416. if (_set_config(client, config) != ESP_OK) {
  417. ESP_LOGE(TAG, "Error set configurations");
  418. esp_http_client_cleanup(client);
  419. return NULL;
  420. }
  421. _success = (
  422. (client->request->buffer->data = malloc(client->buffer_size)) &&
  423. (client->response->buffer->data = malloc(client->buffer_size))
  424. );
  425. if (!_success) {
  426. ESP_LOGE(TAG, "Allocation failed");
  427. esp_http_client_cleanup(client);
  428. return NULL;
  429. }
  430. _success = (
  431. (esp_http_client_set_url(client, config->url) == ESP_OK) &&
  432. (esp_http_client_set_header(client, "User-Agent", DEFAULT_HTTP_USER_AGENT) == ESP_OK) &&
  433. (esp_http_client_set_header(client, "Host", client->connection_info.host) == ESP_OK)
  434. );
  435. if (!_success) {
  436. ESP_LOGE(TAG, "Error set default configurations");
  437. esp_http_client_cleanup(client);
  438. return NULL;
  439. }
  440. client->parser_settings->on_message_begin = http_on_message_begin;
  441. client->parser_settings->on_url = http_on_url;
  442. client->parser_settings->on_status = http_on_status;
  443. client->parser_settings->on_header_field = http_on_header_field;
  444. client->parser_settings->on_header_value = http_on_header_value;
  445. client->parser_settings->on_headers_complete = http_on_headers_complete;
  446. client->parser_settings->on_body = http_on_body;
  447. client->parser_settings->on_message_complete = http_on_message_complete;
  448. client->parser_settings->on_chunk_complete = http_on_chunk_complete;
  449. client->parser->data = client;
  450. client->event.client = client;
  451. client->state = HTTP_STATE_INIT;
  452. return client;
  453. }
  454. esp_err_t esp_http_client_cleanup(esp_http_client_handle_t client)
  455. {
  456. if (client == NULL) {
  457. return ESP_FAIL;
  458. }
  459. esp_http_client_close(client);
  460. transport_list_destroy(client->transport_list);
  461. http_header_destroy(client->request->headers);
  462. free(client->request->buffer->data);
  463. free(client->request->buffer);
  464. free(client->request);
  465. http_header_destroy(client->response->headers);
  466. free(client->response->buffer->data);
  467. free(client->response->buffer);
  468. free(client->response);
  469. free(client->parser);
  470. free(client->parser_settings);
  471. _clear_connection_info(client);
  472. _clear_auth_data(client);
  473. free(client->auth_data);
  474. free(client->current_header_key);
  475. free(client->location);
  476. free(client->auth_header);
  477. free(client);
  478. return ESP_OK;
  479. }
  480. static esp_err_t esp_http_check_response(esp_http_client_handle_t client)
  481. {
  482. char *auth_header = NULL;
  483. if (client->redirect_counter >= client->max_redirection_count || client->disable_auto_redirect) {
  484. ESP_LOGE(TAG, "Error, reach max_redirection_count count=%d", client->redirect_counter);
  485. return ESP_ERR_HTTP_MAX_REDIRECT;
  486. }
  487. switch (client->response->status_code) {
  488. case HttpStatus_MovedPermanently:
  489. case HttpStatus_Found:
  490. ESP_LOGI(TAG, "Redirect to %s", client->location);
  491. esp_http_client_set_url(client, client->location);
  492. client->redirect_counter ++;
  493. client->process_again = 1;
  494. break;
  495. case HttpStatus_Unauthorized:
  496. auth_header = client->auth_header;
  497. if (auth_header) {
  498. http_utils_trim_whitespace(&auth_header);
  499. ESP_LOGD(TAG, "UNAUTHORIZED: %s", auth_header);
  500. client->redirect_counter ++;
  501. if (http_utils_str_starts_with(auth_header, "Digest") == 0) {
  502. ESP_LOGD(TAG, "type = Digest");
  503. client->connection_info.auth_type = HTTP_AUTH_TYPE_DIGEST;
  504. } else if (http_utils_str_starts_with(auth_header, "Basic") == 0) {
  505. ESP_LOGD(TAG, "type = Basic");
  506. client->connection_info.auth_type = HTTP_AUTH_TYPE_BASIC;
  507. } else {
  508. client->connection_info.auth_type = HTTP_AUTH_TYPE_NONE;
  509. ESP_LOGE(TAG, "This authentication method is not supported: %s", auth_header);
  510. break;
  511. }
  512. _clear_auth_data(client);
  513. client->auth_data->method = strdup(HTTP_METHOD_MAPPING[client->connection_info.method]);
  514. client->auth_data->nc = 1;
  515. client->auth_data->realm = http_utils_get_string_between(auth_header, "realm=\"", "\"");
  516. client->auth_data->algorithm = http_utils_get_string_between(auth_header, "algorithm=", ",");
  517. client->auth_data->qop = http_utils_get_string_between(auth_header, "qop=\"", "\"");
  518. client->auth_data->nonce = http_utils_get_string_between(auth_header, "nonce=\"", "\"");
  519. client->auth_data->opaque = http_utils_get_string_between(auth_header, "opaque=\"", "\"");
  520. client->process_again = 1;
  521. } else {
  522. client->connection_info.auth_type = HTTP_AUTH_TYPE_NONE;
  523. ESP_LOGW(TAG, "This request requires authentication, but does not provide header information for that");
  524. }
  525. }
  526. return ESP_OK;
  527. }
  528. esp_err_t esp_http_client_set_url(esp_http_client_handle_t client, const char *url)
  529. {
  530. char *old_host = NULL;
  531. struct http_parser_url purl;
  532. int old_port;
  533. if (client == NULL || url == NULL) {
  534. ESP_LOGE(TAG, "client or url must not NULL");
  535. return ESP_ERR_INVALID_ARG;
  536. }
  537. http_parser_url_init(&purl);
  538. int parser_status = http_parser_parse_url(url, strlen(url), 0, &purl);
  539. if (parser_status != 0) {
  540. ESP_LOGE(TAG, "Error parse url %s", url);
  541. return ESP_ERR_INVALID_ARG;
  542. }
  543. old_host = client->connection_info.host;
  544. old_port = client->connection_info.port;
  545. if (purl.field_data[UF_HOST].len) {
  546. http_utils_assign_string(&client->connection_info.host, url + purl.field_data[UF_HOST].off, purl.field_data[UF_HOST].len);
  547. HTTP_MEM_CHECK(TAG, client->connection_info.host, return ESP_ERR_NO_MEM);
  548. }
  549. // Close the connection if host was changed
  550. if (old_host && client->connection_info.host
  551. && strcasecmp(old_host, (const void *)client->connection_info.host) != 0) {
  552. ESP_LOGD(TAG, "New host assign = %s", client->connection_info.host);
  553. if (esp_http_client_set_header(client, "Host", client->connection_info.host) != ESP_OK) {
  554. return ESP_ERR_NO_MEM;
  555. }
  556. esp_http_client_close(client);
  557. }
  558. if (purl.field_data[UF_SCHEMA].len) {
  559. http_utils_assign_string(&client->connection_info.scheme, url + purl.field_data[UF_SCHEMA].off, purl.field_data[UF_SCHEMA].len);
  560. HTTP_MEM_CHECK(TAG, client->connection_info.scheme, return ESP_ERR_NO_MEM);
  561. if (strcasecmp(client->connection_info.scheme, "http") == 0) {
  562. client->connection_info.port = DEFAULT_HTTP_PORT;
  563. } else if (strcasecmp(client->connection_info.scheme, "https") == 0) {
  564. client->connection_info.port = DEFAULT_HTTPS_PORT;
  565. }
  566. }
  567. if (purl.field_data[UF_PORT].len) {
  568. client->connection_info.port = strtol((const char*)(url + purl.field_data[UF_PORT].off), NULL, 10);
  569. }
  570. if (old_port != client->connection_info.port) {
  571. esp_http_client_close(client);
  572. }
  573. if (purl.field_data[UF_USERINFO].len) {
  574. char *user_info = NULL;
  575. http_utils_assign_string(&user_info, url + purl.field_data[UF_USERINFO].off, purl.field_data[UF_USERINFO].len);
  576. if (user_info) {
  577. char *username = user_info;
  578. char *password = strchr(user_info, ':');
  579. if (password) {
  580. *password = 0;
  581. password ++;
  582. http_utils_assign_string(&client->connection_info.password, password, 0);
  583. HTTP_MEM_CHECK(TAG, client->connection_info.password, return ESP_ERR_NO_MEM);
  584. }
  585. http_utils_assign_string(&client->connection_info.username, username, 0);
  586. HTTP_MEM_CHECK(TAG, client->connection_info.username, return ESP_ERR_NO_MEM);
  587. free(user_info);
  588. } else {
  589. return ESP_ERR_NO_MEM;
  590. }
  591. } else {
  592. free(client->connection_info.username);
  593. free(client->connection_info.password);
  594. client->connection_info.username = NULL;
  595. client->connection_info.password = NULL;
  596. }
  597. //Reset path and query if there are no information
  598. if (purl.field_data[UF_PATH].len) {
  599. http_utils_assign_string(&client->connection_info.path, url + purl.field_data[UF_PATH].off, purl.field_data[UF_PATH].len);
  600. } else {
  601. http_utils_assign_string(&client->connection_info.path, "/", 0);
  602. }
  603. HTTP_MEM_CHECK(TAG, client->connection_info.path, return ESP_ERR_NO_MEM);
  604. if (purl.field_data[UF_QUERY].len) {
  605. http_utils_assign_string(&client->connection_info.query, url + purl.field_data[UF_QUERY].off, purl.field_data[UF_QUERY].len);
  606. HTTP_MEM_CHECK(TAG, client->connection_info.query, return ESP_ERR_NO_MEM);
  607. } else if (client->connection_info.query) {
  608. free(client->connection_info.query);
  609. client->connection_info.query = NULL;
  610. }
  611. return ESP_OK;
  612. }
  613. esp_err_t esp_http_client_set_method(esp_http_client_handle_t client, esp_http_client_method_t method)
  614. {
  615. client->connection_info.method = method;
  616. return ESP_OK;
  617. }
  618. static int esp_http_client_get_data(esp_http_client_handle_t client)
  619. {
  620. if (client->state < HTTP_STATE_RES_COMPLETE_HEADER) {
  621. return ESP_FAIL;
  622. }
  623. if (client->connection_info.method == HTTP_METHOD_HEAD) {
  624. return 0;
  625. }
  626. esp_http_buffer_t *res_buffer = client->response->buffer;
  627. ESP_LOGD(TAG, "data_process=%d, content_length=%d", client->response->data_process, client->response->content_length);
  628. int rlen = transport_read(client->transport, res_buffer->data, client->buffer_size, client->timeout_ms);
  629. if (rlen >= 0) {
  630. http_parser_execute(client->parser, client->parser_settings, res_buffer->data, rlen);
  631. }
  632. return rlen;
  633. }
  634. int esp_http_client_read(esp_http_client_handle_t client, char *buffer, int len)
  635. {
  636. esp_http_buffer_t *res_buffer = client->response->buffer;
  637. int rlen = ESP_FAIL, ridx = 0;
  638. if (res_buffer->raw_len) {
  639. int remain_len = client->response->buffer->raw_len;
  640. if (remain_len > len) {
  641. remain_len = len;
  642. }
  643. memcpy(buffer, res_buffer->raw_data, remain_len);
  644. res_buffer->raw_len -= remain_len;
  645. res_buffer->raw_data += remain_len;
  646. ridx = remain_len;
  647. }
  648. int need_read = len - ridx;
  649. bool is_data_remain = true;
  650. while (need_read > 0 && is_data_remain) {
  651. if (client->response->is_chunked) {
  652. is_data_remain = !client->is_chunk_complete;
  653. } else {
  654. is_data_remain = client->response->data_process < client->response->content_length;
  655. }
  656. ESP_LOGD(TAG, "is_data_remain=%d, is_chunked=%d", is_data_remain, client->response->is_chunked);
  657. if (!is_data_remain) {
  658. break;
  659. }
  660. int byte_to_read = need_read;
  661. if (byte_to_read > client->buffer_size) {
  662. byte_to_read = client->buffer_size;
  663. }
  664. rlen = transport_read(client->transport, res_buffer->data, byte_to_read, client->timeout_ms);
  665. ESP_LOGD(TAG, "need_read=%d, byte_to_read=%d, rlen=%d, ridx=%d", need_read, byte_to_read, rlen, ridx);
  666. if (rlen <= 0) {
  667. return ridx;
  668. }
  669. res_buffer->output_ptr = buffer + ridx;
  670. http_parser_execute(client->parser, client->parser_settings, res_buffer->data, rlen);
  671. ridx += res_buffer->raw_len;
  672. need_read -= res_buffer->raw_len;
  673. res_buffer->raw_len = 0; //clear
  674. res_buffer->output_ptr = NULL;
  675. }
  676. return ridx;
  677. }
  678. esp_err_t esp_http_client_perform(esp_http_client_handle_t client)
  679. {
  680. esp_err_t err;
  681. if (client == NULL) {
  682. return ESP_ERR_INVALID_ARG;
  683. }
  684. do {
  685. if ((err = esp_http_client_open(client, client->post_len)) != ESP_OK) {
  686. return err;
  687. }
  688. if (client->post_data && client->post_len) {
  689. if (esp_http_client_write(client, client->post_data, client->post_len) <= 0) {
  690. ESP_LOGE(TAG, "Error upload data");
  691. return ESP_ERR_HTTP_WRITE_DATA;
  692. }
  693. }
  694. if (esp_http_client_fetch_headers(client) < 0) {
  695. return ESP_ERR_HTTP_FETCH_HEADER;
  696. }
  697. if ((err = esp_http_check_response(client)) != ESP_OK) {
  698. ESP_LOGE(TAG, "Error response");
  699. return err;
  700. }
  701. while (client->response->is_chunked && !client->is_chunk_complete) {
  702. if (esp_http_client_get_data(client) <= 0) {
  703. ESP_LOGD(TAG, "Read finish or server requests close");
  704. break;
  705. }
  706. }
  707. while (client->response->data_process < client->response->content_length) {
  708. if (esp_http_client_get_data(client) <= 0) {
  709. ESP_LOGD(TAG, "Read finish or server requests close");
  710. break;
  711. }
  712. }
  713. http_dispatch_event(client, HTTP_EVENT_ON_FINISH, NULL, 0);
  714. if (!http_should_keep_alive(client->parser)) {
  715. ESP_LOGD(TAG, "Close connection");
  716. esp_http_client_close(client);
  717. } else {
  718. if (client->state > HTTP_STATE_CONNECTED) {
  719. client->state = HTTP_STATE_CONNECTED;
  720. }
  721. }
  722. } while (client->process_again);
  723. return ESP_OK;
  724. }
  725. int esp_http_client_fetch_headers(esp_http_client_handle_t client)
  726. {
  727. if (client->state < HTTP_STATE_REQ_COMPLETE_HEADER) {
  728. return ESP_FAIL;
  729. }
  730. client->state = HTTP_STATE_REQ_COMPLETE_DATA;
  731. esp_http_buffer_t *buffer = client->response->buffer;
  732. client->response->status_code = -1;
  733. while (client->state < HTTP_STATE_RES_COMPLETE_HEADER) {
  734. buffer->len = transport_read(client->transport, buffer->data, client->buffer_size, client->timeout_ms);
  735. if (buffer->len <= 0) {
  736. return ESP_FAIL;
  737. }
  738. http_parser_execute(client->parser, client->parser_settings, buffer->data, buffer->len);
  739. }
  740. ESP_LOGD(TAG, "content_length = %d", client->response->content_length);
  741. if (client->response->content_length <= 0) {
  742. client->response->is_chunked = true;
  743. return 0;
  744. }
  745. return client->response->content_length;
  746. }
  747. esp_err_t esp_http_client_open(esp_http_client_handle_t client, int write_len)
  748. {
  749. esp_err_t err;
  750. if (client->state == HTTP_STATE_UNINIT) {
  751. ESP_LOGE(TAG, "Client has not been initialized");
  752. return ESP_ERR_INVALID_STATE;
  753. }
  754. if ((err = esp_http_client_prepare(client)) != ESP_OK) {
  755. ESP_LOGE(TAG, "Failed to initialize request data");
  756. esp_http_client_close(client);
  757. return err;
  758. }
  759. if (client->state < HTTP_STATE_CONNECTED) {
  760. ESP_LOGD(TAG, "Begin connect to: %s://%s:%d", client->connection_info.scheme, client->connection_info.host, client->connection_info.port);
  761. client->transport = transport_list_get_transport(client->transport_list, client->connection_info.scheme);
  762. if (client->transport == NULL) {
  763. ESP_LOGE(TAG, "No transport found");
  764. #ifndef CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS
  765. if (strcasecmp(client->connection_info.scheme, "https") == 0) {
  766. ESP_LOGE(TAG, "Please enable HTTPS at menuconfig to allow requesting via https");
  767. }
  768. #endif
  769. return ESP_ERR_HTTP_INVALID_TRANSPORT;
  770. }
  771. if (transport_connect(client->transport, client->connection_info.host, client->connection_info.port, client->timeout_ms) < 0) {
  772. ESP_LOGE(TAG, "Connection failed");
  773. return ESP_ERR_HTTP_CONNECT;
  774. }
  775. http_dispatch_event(client, HTTP_EVENT_ON_CONNECTED, NULL, 0);
  776. client->state = HTTP_STATE_CONNECTED;
  777. }
  778. if (write_len >= 0) {
  779. http_header_set_format(client->request->headers, "Content-Length", "%d", write_len);
  780. } else if (write_len < 0) {
  781. esp_http_client_set_header(client, "Transfer-Encoding", "chunked");
  782. esp_http_client_set_method(client, HTTP_METHOD_POST);
  783. }
  784. int header_index = 0;
  785. int wlen = client->buffer_size;
  786. const char *method = HTTP_METHOD_MAPPING[client->connection_info.method];
  787. int first_line = snprintf(client->request->buffer->data,
  788. client->buffer_size, "%s %s",
  789. method,
  790. client->connection_info.path);
  791. if (first_line > client->buffer_size) {
  792. ESP_LOGE(TAG, "Out of buffer");
  793. return ESP_ERR_HTTP_CONNECT;
  794. }
  795. if (client->connection_info.query) {
  796. first_line += snprintf(client->request->buffer->data + first_line,
  797. client->buffer_size - first_line, "?%s", client->connection_info.query);
  798. if (first_line > client->buffer_size) {
  799. ESP_LOGE(TAG, "Out of buffer");
  800. return ESP_ERR_HTTP_CONNECT;
  801. }
  802. }
  803. first_line += snprintf(client->request->buffer->data + first_line,
  804. client->buffer_size - first_line, " %s\r\n", DEFAULT_HTTP_PROTOCOL);
  805. if (first_line > client->buffer_size) {
  806. ESP_LOGE(TAG, "Out of buffer");
  807. return ESP_ERR_HTTP_CONNECT;
  808. }
  809. wlen -= first_line;
  810. while ((header_index = http_header_generate_string(client->request->headers, header_index, client->request->buffer->data + first_line, &wlen))) {
  811. if (wlen <= 0) {
  812. break;
  813. }
  814. if (first_line) {
  815. wlen += first_line;
  816. first_line = 0;
  817. }
  818. client->request->buffer->data[wlen] = 0;
  819. ESP_LOGD(TAG, "Write header[%d]: %s", header_index, client->request->buffer->data);
  820. int widx = 0, wret = 0;
  821. while (wlen > 0) {
  822. wret = transport_write(client->transport, client->request->buffer->data + widx, wlen, client->timeout_ms);
  823. if (wret <= 0) {
  824. ESP_LOGE(TAG, "Error write request");
  825. esp_http_client_close(client);
  826. return ESP_ERR_HTTP_WRITE_DATA;
  827. }
  828. widx += wret;
  829. wlen -= wret;
  830. }
  831. wlen = client->buffer_size;
  832. }
  833. client->state = HTTP_STATE_REQ_COMPLETE_HEADER;
  834. return ESP_OK;
  835. }
  836. int esp_http_client_write(esp_http_client_handle_t client, const char *buffer, int len)
  837. {
  838. if (client->state < HTTP_STATE_REQ_COMPLETE_HEADER) {
  839. return ESP_FAIL;
  840. }
  841. int wlen = 0, widx = 0;
  842. while (len > 0) {
  843. wlen = transport_write(client->transport, buffer + widx, len, client->timeout_ms);
  844. if (wlen <= 0) {
  845. return wlen;
  846. }
  847. widx += wlen;
  848. len -= wlen;
  849. }
  850. return widx;
  851. }
  852. esp_err_t esp_http_client_close(esp_http_client_handle_t client)
  853. {
  854. if (client->state >= HTTP_STATE_INIT) {
  855. http_dispatch_event(client, HTTP_EVENT_DISCONNECTED, NULL, 0);
  856. client->state = HTTP_STATE_INIT;
  857. return transport_close(client->transport);
  858. }
  859. return ESP_OK;
  860. }
  861. esp_err_t esp_http_client_set_post_field(esp_http_client_handle_t client, const char *data, int len)
  862. {
  863. esp_err_t err = ESP_OK;
  864. client->post_data = (char *)data;
  865. client->post_len = len;
  866. ESP_LOGD(TAG, "set post file length = %d", len);
  867. if (client->post_data) {
  868. char *value = NULL;
  869. if ((err = esp_http_client_get_header(client, "Content-Type", &value)) != ESP_OK) {
  870. return err;
  871. }
  872. if (value == NULL) {
  873. err = esp_http_client_set_header(client, "Content-Type", "application/x-www-form-urlencoded");
  874. }
  875. } else {
  876. client->post_len = 0;
  877. err = esp_http_client_set_header(client, "Content-Type", NULL);
  878. }
  879. return err;
  880. }
  881. int esp_http_client_get_post_field(esp_http_client_handle_t client, char **data)
  882. {
  883. if (client->post_data) {
  884. *data = client->post_data;
  885. return client->post_len;
  886. }
  887. return 0;
  888. }
  889. int esp_http_client_get_status_code(esp_http_client_handle_t client)
  890. {
  891. return client->response->status_code;
  892. }
  893. int esp_http_client_get_content_length(esp_http_client_handle_t client)
  894. {
  895. return client->response->content_length;
  896. }
  897. bool esp_http_client_is_chunked_response(esp_http_client_handle_t client)
  898. {
  899. return client->response->is_chunked;
  900. }
  901. esp_http_client_transport_t esp_http_client_get_transport_type(esp_http_client_handle_t client)
  902. {
  903. if (!strcmp(client->connection_info.scheme, "https") ) {
  904. return HTTP_TRANSPORT_OVER_SSL;
  905. } else if (!strcmp(client->connection_info.scheme, "http")) {
  906. return HTTP_TRANSPORT_OVER_TCP;
  907. } else {
  908. return HTTP_TRANSPORT_UNKNOWN;
  909. }
  910. }