esp_http_client.c 50 KB

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