esp_http_client.c 56 KB

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