utils_httpc.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. /*
  2. * Copyright (C) 2012-2019 UCloud. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License").
  5. * You may not use this file except in compliance with the License.
  6. * A copy of the License is located at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * or in the "license" file accompanying this file. This file is distributed
  11. * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
  12. * express or implied. See the License for the specific language governing
  13. * permissions and limitations under the License.
  14. */
  15. #ifdef __cplusplus
  16. extern "C" {
  17. #endif
  18. #include <string.h>
  19. #include <stddef.h>
  20. #include <stdlib.h>
  21. #include "uiot_defs.h"
  22. #include "utils_httpc.h"
  23. #include "utils_net.h"
  24. #include "utils_timer.h"
  25. #include "utils_md5.h"
  26. #define MIN_TIMEOUT (100)
  27. #define MAX_RETRY_COUNT (600)
  28. #define HTTP_CLIENT_READ_BUF_SIZE (1024) /* read payload */
  29. #define HTTP_CLIENT_READ_HEAD_SIZE (32) /* read header */
  30. #define HTTP_CLIENT_SEND_BUF_SIZE (1024) /* send */
  31. #define HTTP_CLIENT_REQUEST_BUF_SIZE (300) /* send */
  32. #define HTTP_CLIENT_MAX_URL_LEN (256)
  33. #define HTTP_RETRIEVE_MORE_DATA (1) /**< More data needs to be retrieved. */
  34. #define HTTP_CLIENT_CHUNK_SIZE (1024)
  35. static int _utils_parse_url(const char *url, char *host, char *path) {
  36. char *host_ptr = (char *) strstr(url, "://");
  37. uint32_t host_len = 0;
  38. uint32_t path_len;
  39. /* char *port_ptr; */
  40. char *path_ptr;
  41. char *fragment_ptr;
  42. if (host_ptr == NULL) {
  43. return -1; /* URL is invalid */
  44. }
  45. host_ptr += 3;
  46. path_ptr = strchr(host_ptr, '/');
  47. if (NULL == path_ptr) {
  48. return -2;
  49. }
  50. host_len = path_ptr - host_ptr;
  51. memcpy(host, host_ptr, host_len);
  52. host[host_len] = '\0';
  53. fragment_ptr = strchr(host_ptr, '#');
  54. if (fragment_ptr != NULL) {
  55. path_len = fragment_ptr - path_ptr;
  56. } else {
  57. path_len = strlen(path_ptr);
  58. }
  59. memcpy(path, path_ptr, path_len);
  60. path[path_len] = '\0';
  61. return SUCCESS_RET;
  62. }
  63. static int _utils_fill_tx_buffer(http_client_t *client, unsigned char *send_buf, int *send_idx, char *buf, uint32_t len) {
  64. int ret;
  65. int cp_len;
  66. int writen_len = 0;
  67. int idx = *send_idx;
  68. if (len == 0) {
  69. len = strlen(buf);
  70. }
  71. do {
  72. if ((HTTP_CLIENT_SEND_BUF_SIZE - idx) >= len) {
  73. cp_len = len;
  74. } else {
  75. cp_len = HTTP_CLIENT_SEND_BUF_SIZE - idx;
  76. }
  77. memcpy(send_buf + idx, buf + writen_len, cp_len);
  78. idx += cp_len;
  79. writen_len += cp_len;
  80. len -= cp_len;
  81. if (idx == HTTP_CLIENT_SEND_BUF_SIZE) {
  82. ret = client->net.write(&client->net, send_buf, HTTP_CLIENT_SEND_BUF_SIZE, 5000);
  83. if (ret < 0) {
  84. return (ret);
  85. } else if (ret != HTTP_CLIENT_SEND_BUF_SIZE) {
  86. return (ret == 0) ? ERR_HTTP_CLOSED : ERR_HTTP_CONN_ERROR;
  87. }
  88. idx -= ret;
  89. }
  90. } while (len);
  91. *send_idx = idx;
  92. return SUCCESS_RET;
  93. }
  94. static int _http_send_header(http_client_t *client, char *host, const char *path, int method, uint32_t size_fetched, size_t range_len,
  95. http_client_data_t *client_data) {
  96. int len;
  97. unsigned char send_buf[HTTP_CLIENT_SEND_BUF_SIZE] = {0};
  98. char buf[HTTP_CLIENT_REQUEST_BUF_SIZE] = {0};
  99. char *pMethod = (method == HTTP_GET) ? "GET" : (method == HTTP_POST) ? "POST" :
  100. (method == HTTP_PUT) ? "PUT" : (method == HTTP_DELETE) ? "DELETE" :
  101. (method == HTTP_HEAD) ? "HEAD" : "";
  102. int ret;
  103. /* Send request */
  104. memset(send_buf, 0, HTTP_CLIENT_SEND_BUF_SIZE);
  105. len = 0; /* Reset send buffer */
  106. HAL_Snprintf(buf, sizeof(buf), "%s %s HTTP/1.1\r\nHost: %s\r\nRange: bytes=%d-%d\r\n", pMethod, path, host, size_fetched, size_fetched + range_len); /* Write request */
  107. ret = _utils_fill_tx_buffer(client, send_buf, &len, buf, strlen(buf));
  108. if (ret < 0) {
  109. /* LOG_ERROR("Could not write request"); */
  110. return ERR_HTTP_CONN_ERROR;
  111. }
  112. /* Add user header information */
  113. if (client->header) {
  114. _utils_fill_tx_buffer(client, send_buf, &len, (char *) client->header, strlen(client->header));
  115. }
  116. if (client_data->post_buf != NULL) {
  117. HAL_Snprintf(buf, sizeof(buf), "Content-Length: %d\r\n", client_data->post_buf_len);
  118. _utils_fill_tx_buffer(client, send_buf, &len, buf, strlen(buf));
  119. if (client_data->post_content_type != NULL) {
  120. HAL_Snprintf(buf, sizeof(buf), "Content-Type: %s\r\n", client_data->post_content_type);
  121. _utils_fill_tx_buffer(client, send_buf, &len, buf, strlen(buf));
  122. }
  123. }
  124. /* Close headers */
  125. _utils_fill_tx_buffer(client, send_buf, &len, "\r\n", 0);
  126. ret = client->net.write(&client->net, send_buf, len, 5000);
  127. if (ret <= 0) {
  128. LOG_ERROR("ret = client->net.write() = %d", ret);
  129. return (ret == 0) ? ERR_HTTP_CLOSED : ERR_HTTP_CONN_ERROR;
  130. }
  131. return SUCCESS_RET;
  132. }
  133. int _http_send_user_data(http_client_t *client, http_client_data_t *client_data, uint32_t timeout_ms) {
  134. int ret = 0;
  135. if (client_data->post_buf && client_data->post_buf_len) {
  136. ret = client->net.write(&client->net, (unsigned char *) client_data->post_buf, client_data->post_buf_len, timeout_ms);
  137. LOG_DEBUG("client_data->post_buf: %s, ret is %d", client_data->post_buf, ret);
  138. if (ret <= 0) {
  139. return (ret == 0) ? ERR_HTTP_CLOSED : ERR_HTTP_CONN_ERROR; /* Connection was closed by server */
  140. }
  141. }
  142. return SUCCESS_RET;
  143. }
  144. /* 0 on success, err code on failure */
  145. static int _http_recv(http_client_t *client, unsigned char *buf, int max_len, int *p_read_len,
  146. uint32_t timeout_ms) {
  147. int ret = 0;
  148. *p_read_len = 0;
  149. ret = client->net.read(&client->net, buf, max_len, timeout_ms);
  150. if (ret > 0) {
  151. *p_read_len = ret;
  152. return 0;
  153. } else if (ret == 0) {
  154. /* timeout */
  155. return FAILURE_RET;
  156. } else {
  157. return ERR_HTTP_CONN_ERROR;
  158. }
  159. }
  160. static int _utils_check_deadloop(int len, Timer *timer, int ret, unsigned int *dead_loop_count,
  161. unsigned int *extend_count) {
  162. /* if timeout reduce to zero, it will be translated into NULL for select function in TLS lib */
  163. /* it would lead to indefinite behavior, so we avoid it */
  164. if (left_ms(timer) < MIN_TIMEOUT) {
  165. (*extend_count)++;
  166. countdown_ms(timer, MIN_TIMEOUT);
  167. }
  168. /* if it falls into deadloop before reconnected to internet, we just quit*/
  169. if ((0 == len) && (0 == left_ms(timer)) && (FAILURE_RET == ret)) {
  170. (*dead_loop_count)++;
  171. if (*dead_loop_count > MAX_RETRY_COUNT) {
  172. LOG_ERROR("deadloop detected, exit");
  173. return ERR_HTTP_CONN_ERROR;
  174. }
  175. } else {
  176. *dead_loop_count = 0;
  177. }
  178. /*if the internet connection is fixed during the loop, the download stream might be disconnected. we have to quit */
  179. if ((0 == len) && (*extend_count > 2 * MAX_RETRY_COUNT) && (FAILURE_RET == ret)) {
  180. LOG_ERROR("extend timer for too many times, exit");
  181. return ERR_HTTP_CONN_ERROR;
  182. }
  183. return SUCCESS_RET;
  184. }
  185. static int _utils_fill_rx_buf(int *recv_count, int len_to_write_to_response_buf, http_client_data_t *client_data,
  186. unsigned char *data) {
  187. int count = *recv_count;
  188. if (count + len_to_write_to_response_buf < client_data->response_buf_len - 1) {
  189. memcpy(client_data->response_buf + count, data, len_to_write_to_response_buf);
  190. count += len_to_write_to_response_buf;
  191. client_data->response_buf[count] = '\0';
  192. client_data->retrieve_len -= len_to_write_to_response_buf;
  193. *recv_count = count;
  194. return SUCCESS_RET;
  195. } else {
  196. memcpy(client_data->response_buf + count, data, client_data->response_buf_len - 1 - count);
  197. client_data->response_buf[client_data->response_buf_len - 1] = '\0';
  198. client_data->retrieve_len -= (client_data->response_buf_len - 1 - count);
  199. return HTTP_RETRIEVE_MORE_DATA;
  200. }
  201. }
  202. static int _http_get_response_body(http_client_t *client, unsigned char *data, int data_len_actually_received,
  203. uint32_t timeout_ms, http_client_data_t *client_data) {
  204. int written_response_buf_len = 0;
  205. int len_to_write_to_response_buf = 0;
  206. Timer timer;
  207. init_timer(&timer);
  208. countdown_ms(&timer, timeout_ms);
  209. /* Receive data */
  210. /* LOG_DEBUG("Current data: %s", data); */
  211. client_data->is_more = 1;
  212. /* the header is not received finished */
  213. if (client_data->response_content_len == -1 && client_data->is_chunked == 0) {
  214. /* can not enter this if */
  215. LOG_ERROR("header is not received yet");
  216. return ERR_HTTP_CONN_ERROR;
  217. }
  218. while (1) {
  219. unsigned int dead_loop_count = 0;
  220. unsigned int extend_count = 0;
  221. do {
  222. int res;
  223. /* move previous fetched data into response_buf */
  224. len_to_write_to_response_buf = Min(data_len_actually_received, client_data->retrieve_len);
  225. res = _utils_fill_rx_buf(&written_response_buf_len, len_to_write_to_response_buf, client_data, data);
  226. if (HTTP_RETRIEVE_MORE_DATA == res) {
  227. return HTTP_RETRIEVE_MORE_DATA;
  228. }
  229. /* get data from internet and put into "data" buf temporary */
  230. if (client_data->retrieve_len) {
  231. int ret;
  232. int max_len_to_receive = Min(HTTP_CLIENT_CHUNK_SIZE - 1,
  233. client_data->response_buf_len - 1 - written_response_buf_len);
  234. max_len_to_receive = Min(max_len_to_receive, client_data->retrieve_len);
  235. ret = _http_recv(client, data, max_len_to_receive, &data_len_actually_received, timeout_ms);
  236. if (ret == ERR_HTTP_CONN_ERROR) {
  237. return ret;
  238. }
  239. LOG_DEBUG("Total- remaind Payload: %d Bytes; currently Read: %d Bytes", client_data->retrieve_len,
  240. data_len_actually_received);
  241. ret = _utils_check_deadloop(data_len_actually_received, &timer, ret, &dead_loop_count,
  242. &extend_count);
  243. if (ERR_HTTP_CONN_ERROR == ret) {
  244. return ret;
  245. }
  246. }
  247. } while (client_data->retrieve_len);
  248. client_data->is_more = 0;
  249. break;
  250. }
  251. return SUCCESS_RET;
  252. }
  253. static int _http_parse_response_header(http_client_t *client, char *data, int len, uint32_t timeout_ms,
  254. http_client_data_t *client_data) {
  255. int crlf_pos;
  256. char *tmp_ptr, *ptr_body_end;
  257. int new_trf_len, ret;
  258. char *crlf_ptr;
  259. client_data->response_content_len = -1;
  260. /* http client response */
  261. /* <status-line> HTTP/1.1 200 OK(CRLF)
  262. <headers> ...(CRLF)
  263. <blank line> (CRLF)
  264. [<response-body>] */
  265. crlf_ptr = strstr(data, "\r\n");
  266. if (crlf_ptr == NULL) {
  267. LOG_ERROR("\r\n not found");
  268. return ERR_HTTP_UNRESOLVED_DNS;
  269. }
  270. crlf_pos = crlf_ptr - data;
  271. data[crlf_pos] = '\0';
  272. client->response_code = atoi(data + 9);
  273. LOG_DEBUG("Reading headers: %s", data);
  274. memmove(data, &data[crlf_pos + 2], len - (crlf_pos + 2) + 1); /* Be sure to move NULL-terminating char as well */
  275. len -= (crlf_pos + 2); /* remove status_line length */
  276. client_data->is_chunked = 0;
  277. /*If not ending of response body*/
  278. /* try to read more header again until find response head ending "\r\n\r\n" */
  279. while (NULL == (ptr_body_end = strstr(data, "\r\n\r\n"))) {
  280. /* try to read more header */
  281. ret = _http_recv(client, (unsigned char *) (data + len), HTTP_CLIENT_READ_HEAD_SIZE, &new_trf_len,
  282. timeout_ms);
  283. if (ret == ERR_HTTP_CONN_ERROR) {
  284. return ret;
  285. }
  286. len += new_trf_len;
  287. data[len] = '\0';
  288. }
  289. /* parse response_content_len */
  290. if (NULL != (tmp_ptr = strstr(data, "Content-Length"))) {
  291. client_data->response_content_len = atoi(tmp_ptr + strlen("Content-Length: "));
  292. client_data->retrieve_len = client_data->response_content_len;
  293. } else {
  294. LOG_ERROR("Could not parse header");
  295. return ERR_HTTP_CONN_ERROR;
  296. }
  297. /* remove header length */
  298. /* len is Had read body's length */
  299. /* if client_data->response_content_len != 0, it is know response length */
  300. /* the remain length is client_data->response_content_len - len */
  301. len = len - (ptr_body_end + 4 - data);
  302. memmove(data, ptr_body_end + 4, len + 1);
  303. client_data->response_received_len += len;
  304. return _http_get_response_body(client, (unsigned char *) data, len, timeout_ms, client_data);
  305. }
  306. static int _http_connect(http_client_t *client) {
  307. int retry_max = 3;
  308. int retry_cnt = 1;
  309. int retry_interval = 1000;
  310. int rc = -1;
  311. do {
  312. client->net.handle = 0;
  313. LOG_DEBUG("calling TCP or TLS connect HAL for [%d/%d] iteration", retry_cnt, retry_max);
  314. rc = client->net.connect(&client->net);
  315. if (0 != rc) {
  316. client->net.disconnect(&client->net);
  317. LOG_ERROR("TCP or TLS connect failed, rc = %d", rc);
  318. HAL_SleepMs(retry_interval);
  319. continue;
  320. } else {
  321. LOG_DEBUG("rc = client->net.connect() = %d, success @ [%d/%d] iteration", rc, retry_cnt, retry_max);
  322. break;
  323. }
  324. } while (++retry_cnt <= retry_max);
  325. return SUCCESS_RET;
  326. }
  327. int _http_send_request(http_client_t *client, const char *url, HTTP_Request_Method method, uint32_t size_fetched, size_t range_len,
  328. http_client_data_t *client_data, uint32_t timeout_ms) {
  329. int ret = ERR_HTTP_CONN_ERROR;
  330. if (0 == client->net.handle) {
  331. return -1;
  332. }
  333. int rc;
  334. char host[HTTP_CLIENT_MAX_URL_LEN] = {0};
  335. char path[HTTP_CLIENT_MAX_URL_LEN] = {0};
  336. rc = _utils_parse_url(url, host, path);
  337. if (rc != SUCCESS_RET) {
  338. return rc;
  339. }
  340. ret = _http_send_header(client, host, path, method, size_fetched, range_len, client_data);
  341. if (ret != 0) {
  342. return -2;
  343. }
  344. if (method == HTTP_POST || method == HTTP_PUT) {
  345. ret = _http_send_user_data(client, client_data,timeout_ms);
  346. if (ret < 0) {
  347. ret = -3;
  348. }
  349. }
  350. return ret;
  351. }
  352. static int _http_client_recv_response(http_client_t *client, uint32_t timeout_ms, http_client_data_t *client_data) {
  353. int read_len = 0, ret = ERR_HTTP_CONN_ERROR;
  354. char buf[HTTP_CLIENT_READ_BUF_SIZE] = {0};
  355. if (0 == client->net.handle) {
  356. LOG_ERROR("no connection have been established");
  357. return ret;
  358. }
  359. if (client_data->is_more) {
  360. client_data->response_buf[0] = '\0';
  361. ret = _http_get_response_body(client, (unsigned char *) buf, read_len, timeout_ms, client_data);
  362. } else {
  363. client_data->is_more = 1;
  364. /* try to read header */
  365. ret = _http_recv(client, (unsigned char *) buf, HTTP_CLIENT_READ_HEAD_SIZE, &read_len, timeout_ms);
  366. if (ret != 0) {
  367. return ret;
  368. }
  369. buf[read_len] = '\0';
  370. if (read_len) {
  371. ret = _http_parse_response_header(client, buf, read_len, timeout_ms, client_data);
  372. }
  373. }
  374. return ret;
  375. }
  376. int http_client_connect(http_client_t *client, const char *url, int port, const char *ca_crt) {
  377. if (client->net.handle != 0) {
  378. LOG_ERROR("http client has connected to host!");
  379. return ERR_HTTP_CONN_ERROR;
  380. }
  381. int rc;
  382. char host[HTTP_CLIENT_MAX_URL_LEN] = {0};
  383. char path[HTTP_CLIENT_MAX_URL_LEN] = {0};
  384. rc = _utils_parse_url(url, host, path);
  385. if (rc != SUCCESS_RET) {
  386. return rc;
  387. }
  388. rc = utils_net_init(&client->net, host, port, SSL_CA_VERIFY_REQUIRED, ca_crt);
  389. if (rc != SUCCESS_RET) {
  390. return rc;
  391. }
  392. rc = _http_connect(client);
  393. if (rc != SUCCESS_RET) {
  394. LOG_ERROR("_http_connect error, rc = %d", rc);
  395. http_client_close(client);
  396. } else {
  397. LOG_DEBUG("http client connect success");
  398. }
  399. return rc;
  400. }
  401. int http_client_recv_data(http_client_t *client, uint32_t timeout_ms, http_client_data_t *client_data) {
  402. int rc = SUCCESS_RET;
  403. Timer timer;
  404. init_timer(&timer);
  405. countdown_ms(&timer, timeout_ms);
  406. do
  407. {
  408. if ((NULL != client_data->response_buf)
  409. && (0 != client_data->response_buf_len)) {
  410. rc = _http_client_recv_response(client, timeout_ms, client_data);
  411. }
  412. if(client_data->is_more)
  413. {
  414. return SUCCESS_RET;
  415. }
  416. }while((rc != SUCCESS_RET) && (!has_expired(&timer)));
  417. return rc;
  418. }
  419. void http_client_close(http_client_t *client) {
  420. if (client->net.handle > 0) {
  421. client->net.disconnect(&client->net);
  422. }
  423. client->net.handle = 0;
  424. LOG_INFO("client disconnected");
  425. }
  426. void http_client_file_md5(char* file_path, char *output)
  427. {
  428. iot_md5_context ctx;
  429. utils_md5_init(&ctx);
  430. utils_md5_starts(&ctx);
  431. char *buffer = (char *)HAL_Malloc(1024);
  432. if (NULL == buffer) {
  433. return;
  434. }
  435. memset(buffer,0,1024);
  436. uint32_t count = 0;
  437. FILE *fp = fopen(file_path, "rb+");
  438. if(NULL == fp)
  439. {
  440. return;
  441. }
  442. while((count = fread(buffer,1,1024,fp))){
  443. utils_md5_update(&ctx, (unsigned char *)buffer, count);
  444. }
  445. utils_md5_finish_hb2hex(&ctx, output);
  446. utils_md5_free(&ctx);
  447. fclose(fp);
  448. HAL_Free(buffer);
  449. }
  450. #ifdef __cplusplus
  451. }
  452. #endif