utils_httpc.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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,
  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\n", pMethod, path, host); /* 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. Timer timer;
  149. init_timer(&timer);
  150. countdown_ms(&timer, timeout_ms);
  151. *p_read_len = 0;
  152. ret = client->net.read(&client->net, buf, max_len, left_ms(&timer));
  153. if (ret > 0) {
  154. *p_read_len = ret;
  155. return 0;
  156. } else if (ret == 0) {
  157. /* timeout */
  158. return FAILURE_RET;
  159. } else {
  160. return ERR_HTTP_CONN_ERROR;
  161. }
  162. }
  163. static int _utils_check_deadloop(int len, Timer *timer, int ret, unsigned int *dead_loop_count,
  164. unsigned int *extend_count) {
  165. /* if timeout reduce to zero, it will be translated into NULL for select function in TLS lib */
  166. /* it would lead to indefinite behavior, so we avoid it */
  167. if (left_ms(timer) < MIN_TIMEOUT) {
  168. (*extend_count)++;
  169. countdown_ms(timer, MIN_TIMEOUT);
  170. }
  171. /* if it falls into deadloop before reconnected to internet, we just quit*/
  172. if ((0 == len) && (0 == left_ms(timer)) && (FAILURE_RET == ret)) {
  173. (*dead_loop_count)++;
  174. if (*dead_loop_count > MAX_RETRY_COUNT) {
  175. LOG_ERROR("deadloop detected, exit");
  176. return ERR_HTTP_CONN_ERROR;
  177. }
  178. } else {
  179. *dead_loop_count = 0;
  180. }
  181. /*if the internet connection is fixed during the loop, the download stream might be disconnected. we have to quit */
  182. if ((0 == len) && (*extend_count > 2 * MAX_RETRY_COUNT) && (FAILURE_RET == ret)) {
  183. LOG_ERROR("extend timer for too many times, exit");
  184. return ERR_HTTP_CONN_ERROR;
  185. }
  186. return SUCCESS_RET;
  187. }
  188. static int _utils_fill_rx_buf(int *recv_count, int len_to_write_to_response_buf, http_client_data_t *client_data,
  189. unsigned char *data) {
  190. int count = *recv_count;
  191. if (count + len_to_write_to_response_buf < client_data->response_buf_len - 1) {
  192. memcpy(client_data->response_buf + count, data, len_to_write_to_response_buf);
  193. count += len_to_write_to_response_buf;
  194. client_data->response_buf[count] = '\0';
  195. client_data->retrieve_len -= len_to_write_to_response_buf;
  196. *recv_count = count;
  197. return SUCCESS_RET;
  198. } else {
  199. memcpy(client_data->response_buf + count, data, client_data->response_buf_len - 1 - count);
  200. client_data->response_buf[client_data->response_buf_len - 1] = '\0';
  201. client_data->retrieve_len -= (client_data->response_buf_len - 1 - count);
  202. return HTTP_RETRIEVE_MORE_DATA;
  203. }
  204. }
  205. static int _http_get_response_body(http_client_t *client, unsigned char *data, int data_len_actually_received,
  206. uint32_t timeout_ms, http_client_data_t *client_data) {
  207. int written_response_buf_len = 0;
  208. int len_to_write_to_response_buf = 0;
  209. Timer timer;
  210. init_timer(&timer);
  211. countdown_ms(&timer, timeout_ms);
  212. /* Receive data */
  213. /* LOG_DEBUG("Current data: %s", data); */
  214. client_data->is_more = 1;
  215. /* the header is not received finished */
  216. if (client_data->response_content_len == -1 && client_data->is_chunked == 0) {
  217. /* can not enter this if */
  218. LOG_ERROR("header is not received yet");
  219. return ERR_HTTP_CONN_ERROR;
  220. }
  221. while (1) {
  222. unsigned int dead_loop_count = 0;
  223. unsigned int extend_count = 0;
  224. do {
  225. int res;
  226. /* move previous fetched data into response_buf */
  227. len_to_write_to_response_buf = Min(data_len_actually_received, client_data->retrieve_len);
  228. res = _utils_fill_rx_buf(&written_response_buf_len, len_to_write_to_response_buf, client_data, data);
  229. if (HTTP_RETRIEVE_MORE_DATA == res) {
  230. return HTTP_RETRIEVE_MORE_DATA;
  231. }
  232. /* get data from internet and put into "data" buf temporary */
  233. if (client_data->retrieve_len) {
  234. int ret;
  235. int max_len_to_receive = Min(HTTP_CLIENT_CHUNK_SIZE - 1,
  236. client_data->response_buf_len - 1 - written_response_buf_len);
  237. max_len_to_receive = Min(max_len_to_receive, client_data->retrieve_len);
  238. ret = _http_recv(client, data, max_len_to_receive, &data_len_actually_received, left_ms(&timer));
  239. if (ret == ERR_HTTP_CONN_ERROR) {
  240. return ret;
  241. }
  242. LOG_DEBUG("Total- remaind Payload: %d Bytes; currently Read: %d Bytes", client_data->retrieve_len,
  243. data_len_actually_received);
  244. ret = _utils_check_deadloop(data_len_actually_received, &timer, ret, &dead_loop_count,
  245. &extend_count);
  246. if (ERR_HTTP_CONN_ERROR == ret) {
  247. return ret;
  248. }
  249. }
  250. } while (client_data->retrieve_len);
  251. client_data->is_more = 0;
  252. break;
  253. }
  254. return SUCCESS_RET;
  255. }
  256. static int _http_parse_response_header(http_client_t *client, char *data, int len, uint32_t timeout_ms,
  257. http_client_data_t *client_data) {
  258. int crlf_pos;
  259. Timer timer;
  260. char *tmp_ptr, *ptr_body_end;
  261. int new_trf_len, ret;
  262. char *crlf_ptr;
  263. init_timer(&timer);
  264. countdown_ms(&timer, timeout_ms);
  265. client_data->response_content_len = -1;
  266. /* http client response */
  267. /* <status-line> HTTP/1.1 200 OK(CRLF)
  268. <headers> ...(CRLF)
  269. <blank line> (CRLF)
  270. [<response-body>] */
  271. crlf_ptr = strstr(data, "\r\n");
  272. if (crlf_ptr == NULL) {
  273. LOG_ERROR("\r\n not found");
  274. return ERR_HTTP_UNRESOLVED_DNS;
  275. }
  276. crlf_pos = crlf_ptr - data;
  277. data[crlf_pos] = '\0';
  278. client->response_code = atoi(data + 9);
  279. LOG_DEBUG("Reading headers: %s", data);
  280. memmove(data, &data[crlf_pos + 2], len - (crlf_pos + 2) + 1); /* Be sure to move NULL-terminating char as well */
  281. len -= (crlf_pos + 2); /* remove status_line length */
  282. client_data->is_chunked = 0;
  283. /*If not ending of response body*/
  284. /* try to read more header again until find response head ending "\r\n\r\n" */
  285. while (NULL == (ptr_body_end = strstr(data, "\r\n\r\n"))) {
  286. /* try to read more header */
  287. ret = _http_recv(client, (unsigned char *) (data + len), HTTP_CLIENT_READ_HEAD_SIZE, &new_trf_len,
  288. left_ms(&timer));
  289. if (ret == ERR_HTTP_CONN_ERROR) {
  290. return ret;
  291. }
  292. len += new_trf_len;
  293. data[len] = '\0';
  294. }
  295. /* parse response_content_len */
  296. if (NULL != (tmp_ptr = strstr(data, "Content-Length"))) {
  297. client_data->response_content_len = atoi(tmp_ptr + strlen("Content-Length: "));
  298. client_data->retrieve_len = client_data->response_content_len;
  299. } else {
  300. LOG_ERROR("Could not parse header");
  301. return ERR_HTTP_CONN_ERROR;
  302. }
  303. /* remove header length */
  304. /* len is Had read body's length */
  305. /* if client_data->response_content_len != 0, it is know response length */
  306. /* the remain length is client_data->response_content_len - len */
  307. len = len - (ptr_body_end + 4 - data);
  308. memmove(data, ptr_body_end + 4, len + 1);
  309. client_data->response_received_len += len;
  310. return _http_get_response_body(client, (unsigned char *) data, len, left_ms(&timer), client_data);
  311. }
  312. static int _http_connect(http_client_t *client) {
  313. int retry_max = 3;
  314. int retry_cnt = 1;
  315. int retry_interval = 1000;
  316. int rc = -1;
  317. do {
  318. client->net.handle = 0;
  319. LOG_DEBUG("calling TCP or TLS connect HAL for [%d/%d] iteration", retry_cnt, retry_max);
  320. rc = client->net.connect(&client->net);
  321. if (0 != rc) {
  322. client->net.disconnect(&client->net);
  323. LOG_ERROR("TCP or TLS connect failed, rc = %d", rc);
  324. HAL_SleepMs(retry_interval);
  325. continue;
  326. } else {
  327. LOG_DEBUG("rc = client->net.connect() = %d, success @ [%d/%d] iteration", rc, retry_cnt, retry_max);
  328. break;
  329. }
  330. } while (++retry_cnt <= retry_max);
  331. return SUCCESS_RET;
  332. }
  333. int _http_send_request(http_client_t *client, const char *url, HTTP_Request_Method method,
  334. http_client_data_t *client_data, uint32_t timeout_ms) {
  335. int ret = ERR_HTTP_CONN_ERROR;
  336. if (0 == client->net.handle) {
  337. return -1;
  338. }
  339. int rc;
  340. char host[HTTP_CLIENT_MAX_URL_LEN] = {0};
  341. char path[HTTP_CLIENT_MAX_URL_LEN] = {0};
  342. rc = _utils_parse_url(url, host, path);
  343. if (rc != SUCCESS_RET) {
  344. return rc;
  345. }
  346. ret = _http_send_header(client, host, path, method, client_data);
  347. if (ret != 0) {
  348. return -2;
  349. }
  350. if (method == HTTP_POST || method == HTTP_PUT) {
  351. ret = _http_send_user_data(client, client_data,timeout_ms);
  352. if (ret < 0) {
  353. ret = -3;
  354. }
  355. }
  356. return ret;
  357. }
  358. static int _http_client_recv_response(http_client_t *client, uint32_t timeout_ms, http_client_data_t *client_data) {
  359. int read_len = 0, ret = ERR_HTTP_CONN_ERROR;
  360. char buf[HTTP_CLIENT_READ_BUF_SIZE] = {0};
  361. Timer timer;
  362. init_timer(&timer);
  363. countdown_ms(&timer, timeout_ms);
  364. if (0 == client->net.handle) {
  365. LOG_ERROR("no connection have been established");
  366. return ret;
  367. }
  368. if (client_data->is_more) {
  369. client_data->response_buf[0] = '\0';
  370. ret = _http_get_response_body(client, (unsigned char *) buf, read_len, left_ms(&timer), client_data);
  371. } else {
  372. client_data->is_more = 1;
  373. /* try to read header */
  374. ret = _http_recv(client, (unsigned char *) buf, HTTP_CLIENT_READ_HEAD_SIZE, &read_len, left_ms(&timer));
  375. if (ret != 0) {
  376. return ret;
  377. }
  378. buf[read_len] = '\0';
  379. if (read_len) {
  380. ret = _http_parse_response_header(client, buf, read_len, left_ms(&timer), client_data);
  381. }
  382. }
  383. return ret;
  384. }
  385. int http_client_connect(http_client_t *client, const char *url, int port, const char *ca_crt) {
  386. if (client->net.handle != 0) {
  387. LOG_ERROR("http client has connected to host!");
  388. return ERR_HTTP_CONN_ERROR;
  389. }
  390. int rc;
  391. char host[HTTP_CLIENT_MAX_URL_LEN] = {0};
  392. char path[HTTP_CLIENT_MAX_URL_LEN] = {0};
  393. rc = _utils_parse_url(url, host, path);
  394. if (rc != SUCCESS_RET) {
  395. return rc;
  396. }
  397. rc = utils_net_init(&client->net, host, port, SSL_CA_VERIFY_REQUIRED, ca_crt);
  398. if (rc != SUCCESS_RET) {
  399. return rc;
  400. }
  401. rc = _http_connect(client);
  402. if (rc != SUCCESS_RET) {
  403. LOG_ERROR("_http_connect error, rc = %d", rc);
  404. http_client_close(client);
  405. } else {
  406. LOG_DEBUG("http client connect success");
  407. }
  408. return rc;
  409. }
  410. int http_client_common(http_client_t *client, const char *url, int port, const char *ca_crt,
  411. HTTP_Request_Method method, http_client_data_t *client_data, uint32_t timeout_ms) {
  412. int rc;
  413. if (client->net.handle == 0) {
  414. rc = http_client_connect(client, url, port, ca_crt);
  415. if (rc != SUCCESS_RET) {
  416. return rc;
  417. }
  418. }
  419. rc = _http_send_request(client, url, method, client_data, timeout_ms);
  420. if (rc != SUCCESS_RET) {
  421. LOG_ERROR("http_send_request error, rc = %d", rc);
  422. http_client_close(client);
  423. return rc;
  424. }
  425. return SUCCESS_RET;
  426. }
  427. int http_client_recv_data(http_client_t *client, uint32_t timeout_ms, http_client_data_t *client_data) {
  428. int rc;
  429. Timer timer;
  430. init_timer(&timer);
  431. countdown_ms(&timer, (unsigned int) timeout_ms);
  432. if ((NULL != client_data->response_buf)
  433. && (0 != client_data->response_buf_len)) {
  434. rc = _http_client_recv_response(client, left_ms(&timer), client_data);
  435. if (rc < 0) {
  436. LOG_ERROR("_http_client_recv_response is error, rc = %d", rc);
  437. http_client_close(client);
  438. return rc;
  439. }
  440. }
  441. return SUCCESS_RET;
  442. }
  443. void http_client_close(http_client_t *client) {
  444. if (client->net.handle > 0) {
  445. client->net.disconnect(&client->net);
  446. }
  447. client->net.handle = 0;
  448. LOG_INFO("client disconnected");
  449. }
  450. void http_client_file_md5(char* file_path, char *output)
  451. {
  452. iot_md5_context ctx;
  453. utils_md5_init(&ctx);
  454. utils_md5_starts(&ctx);
  455. char *buffer = (char *)HAL_Malloc(1024);
  456. if (NULL == buffer) {
  457. return;
  458. }
  459. memset(buffer,0,1024);
  460. uint32_t count = 0;
  461. FILE *fp = fopen(file_path, "rb+");
  462. if(NULL == fp)
  463. {
  464. return;
  465. }
  466. while((count = fread(buffer,1,1024,fp))){
  467. utils_md5_update(&ctx, (unsigned char *)buffer, count);
  468. }
  469. utils_md5_finish_hb2hex(&ctx, output);
  470. utils_md5_free(&ctx);
  471. fclose(fp);
  472. HAL_Free(buffer);
  473. }
  474. #ifdef __cplusplus
  475. }
  476. #endif