esp_http_client.c 53 KB

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