esp_http_client.c 53 KB

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