esp_http_client.c 54 KB

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