webclient.c 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029
  1. /*
  2. * Copyright (c) 2006-2022, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2013-05-05 Bernard the first version
  9. * 2013-06-10 Bernard fix the slow speed issue when download file.
  10. * 2015-11-14 aozima add content_length_remainder.
  11. * 2017-12-23 aozima update gethostbyname to getaddrinfo.
  12. * 2018-01-04 aozima add ipv6 address support.
  13. * 2018-07-26 chenyong modify log information
  14. * 2018-08-07 chenyong modify header processing
  15. * 2021-06-09 xiangxistu add shard download function
  16. */
  17. #include "webclient.h"
  18. #include <ctype.h>
  19. #include <stdio.h>
  20. #include <stdlib.h>
  21. #include <string.h>
  22. #define DBG_ENABLE
  23. #define DBG_SECTION_NAME "web"
  24. #ifdef WEBCLIENT_DEBUG
  25. #define DBG_LEVEL DBG_LOG
  26. #else
  27. #define DBG_LEVEL DBG_INFO
  28. #endif /* WEBCLIENT_DEBUG */
  29. #define DBG_COLOR
  30. // #include <rtdbg.h>
  31. /* default receive or send timeout */
  32. #define WEBCLIENT_DEFAULT_TIMEO 6
  33. extern long int strtol(const char* nptr, char** endptr, int base);
  34. static int webclient_strncasecmp(const char* a, const char* b, size_t n) {
  35. uint8_t c1, c2;
  36. if (n <= 0)
  37. return 0;
  38. do {
  39. c1 = tolower(*a++);
  40. c2 = tolower(*b++);
  41. } while (--n && c1 && c1 == c2);
  42. return c1 - c2;
  43. }
  44. static const char* webclient_strstri(const char* str, const char* subStr) {
  45. int len = strlen(subStr);
  46. if (len == 0) {
  47. return RT_NULL;
  48. }
  49. while (*str) {
  50. if (webclient_strncasecmp(str, subStr, len) == 0) {
  51. return str;
  52. }
  53. ++str;
  54. }
  55. return RT_NULL;
  56. }
  57. static int webclient_send(struct webclient_session* session,
  58. const void* buffer,
  59. size_t len,
  60. int flag) {
  61. #ifdef WEBCLIENT_USING_MBED_TLS
  62. if (session->tls_session) {
  63. return mbedtls_client_write(session->tls_session, buffer, len);
  64. }
  65. #endif
  66. return __platform_send(session->socket, buffer, len, flag);
  67. }
  68. static int webclient_recv(struct webclient_session* session,
  69. void* buffer,
  70. size_t len,
  71. int flag) {
  72. #ifdef WEBCLIENT_USING_MBED_TLS
  73. if (session->tls_session) {
  74. return mbedtls_client_read(session->tls_session, buffer, len);
  75. }
  76. #endif
  77. return __platform_recv(session->socket, buffer, len, flag);
  78. }
  79. static int webclient_read_line(struct webclient_session* session,
  80. char* buffer,
  81. int size) {
  82. int rc, count = 0;
  83. char ch = 0, last_ch = 0;
  84. RT_ASSERT(session);
  85. RT_ASSERT(buffer);
  86. /* Keep reading until we fill the buffer. */
  87. while (count < size) {
  88. rc = webclient_recv(session, (unsigned char*)&ch, 1, 0);
  89. #if defined(WEBCLIENT_USING_MBED_TLS) || defined(WEBCLIENT_USING_SAL_TLS)
  90. if (session->is_tls && (rc == MBEDTLS_ERR_SSL_WANT_READ ||
  91. rc == MBEDTLS_ERR_SSL_WANT_WRITE)) {
  92. continue;
  93. }
  94. #endif
  95. if (rc <= 0)
  96. return rc;
  97. if (ch == '\n' && last_ch == '\r')
  98. break;
  99. buffer[count++] = ch;
  100. last_ch = ch;
  101. }
  102. if (count > size) {
  103. LOG_E(
  104. "read line failed. The line data length is out of buffer size(%d)!",
  105. count);
  106. return -WEBCLIENT_ERROR;
  107. }
  108. return count;
  109. }
  110. /**
  111. * resolve server address
  112. *
  113. * @param session http session
  114. * @param res the server address information
  115. * @param url the input server URI address
  116. * @param request the pointer to point the request url, for example, /index.html
  117. *
  118. * @return 0 on resolve server address OK, others failed
  119. *
  120. * URL example:
  121. * http://www.rt-thread.org
  122. * http://www.rt-thread.org:80
  123. * https://www.rt-thread.org/
  124. * http://192.168.1.1:80/index.htm
  125. * http://[fe80::1]
  126. * http://[fe80::1]/
  127. * http://[fe80::1]/index.html
  128. * http://[fe80::1]:80/index.html
  129. */
  130. static int webclient_resolve_address(struct webclient_session* session,
  131. struct addrinfo** res,
  132. const char* url,
  133. const char** request) {
  134. int rc = WEBCLIENT_OK;
  135. char* ptr;
  136. char port_str[6] = "80"; /* default port of 80(http) */
  137. const char* port_ptr;
  138. const char* path_ptr;
  139. const char* host_addr = 0;
  140. int url_len, host_addr_len = 0;
  141. RT_ASSERT(res);
  142. RT_ASSERT(request);
  143. /* make sure *res = NULL before getaddrinfo */
  144. *res = RT_NULL;
  145. url_len = strlen(url);
  146. /* strip protocol(http or https) */
  147. if (strncmp(url, "http://", 7) == 0) {
  148. host_addr = url + 7;
  149. } else if (strncmp(url, "https://", 8) == 0) {
  150. strncpy(port_str, "443", 4);
  151. host_addr = url + 8;
  152. } else {
  153. rc = -WEBCLIENT_ERROR;
  154. goto __exit;
  155. }
  156. /* ipv6 address */
  157. if (host_addr[0] == '[') {
  158. host_addr += 1;
  159. ptr = strstr(host_addr, "]");
  160. if (!ptr) {
  161. rc = -WEBCLIENT_ERROR;
  162. goto __exit;
  163. }
  164. host_addr_len = ptr - host_addr;
  165. }
  166. path_ptr = strstr(host_addr, "/");
  167. *request = path_ptr ? path_ptr : "/";
  168. /* resolve port */
  169. port_ptr = strstr(host_addr + host_addr_len, ":");
  170. if (port_ptr && (!path_ptr || (port_ptr < path_ptr))) {
  171. if (!path_ptr) {
  172. strcpy(port_str, port_ptr + 1);
  173. } else {
  174. int port_len = path_ptr - port_ptr - 1;
  175. strncpy(port_str, port_ptr + 1, port_len);
  176. port_str[port_len] = '\0';
  177. }
  178. } else {
  179. port_ptr = RT_NULL;
  180. }
  181. if (port_ptr && (!path_ptr)) {
  182. strcpy(port_str, port_ptr + 1);
  183. }
  184. /* ipv4 or domain. */
  185. if (!host_addr_len) {
  186. if (port_ptr) {
  187. host_addr_len = port_ptr - host_addr;
  188. } else if (path_ptr) {
  189. host_addr_len = path_ptr - host_addr;
  190. } else {
  191. host_addr_len = strlen(host_addr);
  192. }
  193. }
  194. if ((host_addr_len < 1) || (host_addr_len > url_len)) {
  195. rc = -WEBCLIENT_ERROR;
  196. goto __exit;
  197. }
  198. /* get host address ok. */
  199. {
  200. char* host_addr_new = web_malloc(host_addr_len + 1);
  201. if (!host_addr_new) {
  202. rc = -WEBCLIENT_ERROR;
  203. goto __exit;
  204. }
  205. rt_memcpy(host_addr_new, host_addr, host_addr_len);
  206. host_addr_new[host_addr_len] = '\0';
  207. session->host = host_addr_new;
  208. }
  209. LOG_D("host address: %s , port: %s", session->host, port_str);
  210. #ifdef WEBCLIENT_USING_MBED_TLS
  211. if (session->tls_session) {
  212. session->tls_session->port = web_strdup(port_str);
  213. session->tls_session->host = web_strdup(session->host);
  214. if (session->tls_session->port == RT_NULL ||
  215. session->tls_session->host == RT_NULL) {
  216. return -WEBCLIENT_NOMEM;
  217. }
  218. return rc;
  219. }
  220. #endif
  221. /* resolve the host name. */
  222. {
  223. struct addrinfo hint;
  224. int ret;
  225. web_memset(&hint, 0, sizeof(hint));
  226. ret = __platform_getaddrinfo(session->host, port_str, &hint, res);
  227. if (ret != 0) {
  228. LOG_E("getaddrinfo err: %d '%s'.", ret, session->host);
  229. rc = -WEBCLIENT_ERROR;
  230. goto __exit;
  231. }
  232. }
  233. __exit:
  234. if (rc != WEBCLIENT_OK) {
  235. if (session->host) {
  236. web_free(session->host);
  237. session->host = RT_NULL;
  238. }
  239. if (*res) {
  240. __platform_freeaddrinfo(*res);
  241. *res = RT_NULL;
  242. }
  243. }
  244. return rc;
  245. }
  246. #ifdef WEBCLIENT_USING_MBED_TLS
  247. /**
  248. * create and initialize https session.
  249. *
  250. * @param session webclient session
  251. * @param URI input server URI address
  252. *
  253. * @return <0: create failed, no memory or other errors
  254. * =0: success
  255. */
  256. static int webclient_open_tls(struct webclient_session* session,
  257. const char* URI) {
  258. int tls_ret = 0;
  259. const char* pers = "webclient";
  260. RT_ASSERT(session);
  261. session->tls_session =
  262. (MbedTLSSession*)web_calloc(1, sizeof(MbedTLSSession));
  263. if (session->tls_session == RT_NULL) {
  264. return -WEBCLIENT_NOMEM;
  265. }
  266. session->tls_session->buffer_len = WEBCLIENT_RESPONSE_BUFSZ;
  267. session->tls_session->buffer = web_malloc(session->tls_session->buffer_len);
  268. if (session->tls_session->buffer == RT_NULL) {
  269. LOG_E("no memory for tls_session buffer!");
  270. return -WEBCLIENT_ERROR;
  271. }
  272. if ((tls_ret = mbedtls_client_init(session->tls_session, (void*)pers,
  273. strlen(pers))) < 0) {
  274. LOG_E("initialize https client failed return: -0x%x.", -tls_ret);
  275. return -WEBCLIENT_ERROR;
  276. }
  277. return WEBCLIENT_OK;
  278. }
  279. #endif
  280. /**
  281. * connect to http server.
  282. *
  283. * @param session webclient session
  284. * @param URI the input server URI address
  285. *
  286. * @return <0: connect failed or other error
  287. * =0: connect success
  288. */
  289. static int webclient_connect(struct webclient_session* session,
  290. const char* URI) {
  291. int rc = WEBCLIENT_OK;
  292. int socket_handle;
  293. struct timeval timeout;
  294. struct addrinfo* res = RT_NULL;
  295. const char* req_url;
  296. RT_ASSERT(session);
  297. RT_ASSERT(URI);
  298. timeout.tv_sec = WEBCLIENT_DEFAULT_TIMEO;
  299. timeout.tv_usec = 0;
  300. if (strncmp(URI, "https://", 8) == 0) {
  301. #if defined(WEBCLIENT_USING_SAL_TLS)
  302. session->is_tls = RT_TRUE;
  303. #elif defined(WEBCLIENT_USING_MBED_TLS)
  304. if (webclient_open_tls(session, URI) < 0) {
  305. LOG_E("connect failed, https client open URI(%s) failed!", URI);
  306. return -WEBCLIENT_ERROR;
  307. }
  308. session->is_tls = RT_TRUE;
  309. #else
  310. LOG_E(
  311. "not support https connect, please enable webclient https "
  312. "configure!");
  313. LOG_E("||url:%.1024s||", URI);
  314. rc = -WEBCLIENT_ERROR;
  315. goto __exit;
  316. #endif
  317. }
  318. /* Check valid IP address and URL */
  319. rc = webclient_resolve_address(session, &res, URI, &req_url);
  320. if (rc != WEBCLIENT_OK) {
  321. LOG_E("connect failed, resolve address error(%d).", rc);
  322. goto __exit;
  323. }
  324. /* Not use 'getaddrinfo()' for https connection */
  325. if (session->is_tls == RT_FALSE && res == RT_NULL) {
  326. rc = -WEBCLIENT_ERROR;
  327. goto __exit;
  328. }
  329. /* copy host address */
  330. if (req_url) {
  331. session->req_url = web_strdup(req_url);
  332. } else {
  333. LOG_E("connect failed, resolve request address error.");
  334. rc = -WEBCLIENT_ERROR;
  335. goto __exit;
  336. }
  337. #ifdef WEBCLIENT_USING_MBED_TLS
  338. if (session->tls_session) {
  339. int tls_ret = 0;
  340. if ((tls_ret = mbedtls_client_context(session->tls_session)) < 0) {
  341. LOG_E("connect failed, https client context return: -0x%x",
  342. -tls_ret);
  343. return -WEBCLIENT_ERROR;
  344. }
  345. if ((tls_ret = mbedtls_client_connect(session->tls_session)) < 0) {
  346. LOG_E("connect failed, https client connect return: -0x%x",
  347. -tls_ret);
  348. return -WEBCLIENT_CONNECT_FAILED;
  349. }
  350. socket_handle = session->tls_session->server_fd.fd;
  351. /* set recv timeout option */
  352. __platform_setsockopt(socket_handle, SOL_SOCKET, SO_RCVTIMEO,
  353. (void*)&timeout, sizeof(timeout));
  354. __platform_setsockopt(socket_handle, SOL_SOCKET, SO_SNDTIMEO,
  355. (void*)&timeout, sizeof(timeout));
  356. session->socket = socket_handle;
  357. return WEBCLIENT_OK;
  358. }
  359. #endif
  360. {
  361. #ifdef WEBCLIENT_USING_SAL_TLS
  362. if (session->is_tls) {
  363. socket_handle =
  364. __platform_socket(res->ai_family, SOCK_STREAM, PROTOCOL_TLS);
  365. } else {
  366. socket_handle =
  367. __platform_socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
  368. }
  369. #else
  370. socket_handle =
  371. __platform_socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
  372. #endif
  373. if (socket_handle < 0) {
  374. LOG_E("connect failed, create __platform_socket(%d) error.",
  375. socket_handle);
  376. rc = -WEBCLIENT_NOSOCKET;
  377. goto __exit;
  378. }
  379. /* set receive and send timeout option */
  380. __platform_setsockopt(socket_handle, SOL_SOCKET, SO_RCVTIMEO,
  381. (void*)&timeout, sizeof(timeout));
  382. __platform_setsockopt(socket_handle, SOL_SOCKET, SO_SNDTIMEO,
  383. (void*)&timeout, sizeof(timeout));
  384. if (__platform_connect(socket_handle, res->ai_addr, res->ai_addrlen) !=
  385. 0) {
  386. /* connect failed, close socket */
  387. LOG_E("connect failed, connect __platform_socket(%d) error.",
  388. socket_handle);
  389. __platform_close(socket_handle);
  390. rc = -WEBCLIENT_CONNECT_FAILED;
  391. goto __exit;
  392. }
  393. session->socket = socket_handle;
  394. }
  395. __exit:
  396. if (res) {
  397. __platform_freeaddrinfo(res);
  398. }
  399. return rc;
  400. }
  401. /**
  402. * FIXME: userful func
  403. * add fields data to request header data.
  404. *
  405. * @param session webclient session
  406. * @param fmt fields format
  407. *
  408. * @return >0: data length of successfully added
  409. * <0: not enough header buffer size
  410. */
  411. int webclient_header_fields_add(struct webclient_session* session,
  412. const char* fmt,
  413. ...) {
  414. rt_int32_t length;
  415. va_list args;
  416. RT_ASSERT(session);
  417. RT_ASSERT(session->header->buffer);
  418. va_start(args, fmt);
  419. length = web_vsnprintf(session->header->buffer + session->header->length,
  420. session->header->size - session->header->length, fmt,
  421. args);
  422. va_end(args);
  423. if (length < 0) {
  424. LOG_E("add fields header data failed, return length(%d) error.",
  425. length);
  426. return -WEBCLIENT_ERROR;
  427. }
  428. session->header->length += length;
  429. /* check header size */
  430. if (session->header->length >= session->header->size) {
  431. LOG_E("not enough header buffer size(%d)!", session->header->size);
  432. return -WEBCLIENT_ERROR;
  433. }
  434. return length;
  435. }
  436. /**
  437. * get fields information from request/response header data.
  438. *
  439. * @param session webclient session
  440. * @param fields fields keyword
  441. *
  442. * @return = NULL: get fields data failed
  443. * != NULL: success get fields data
  444. */
  445. const char* webclient_header_fields_get(struct webclient_session* session,
  446. const char* fields) {
  447. char* resp_buf = RT_NULL;
  448. size_t resp_buf_len = 0;
  449. RT_ASSERT(session);
  450. RT_ASSERT(session->header->buffer);
  451. resp_buf = session->header->buffer;
  452. while (resp_buf_len < session->header->length) {
  453. if (webclient_strstri(resp_buf, fields) == resp_buf) {
  454. char* mime_ptr = RT_NULL;
  455. /* jump space */
  456. mime_ptr = strstr(resp_buf, ":");
  457. if (mime_ptr != NULL) {
  458. mime_ptr += 1;
  459. while (*mime_ptr && (*mime_ptr == ' ' || *mime_ptr == '\t'))
  460. mime_ptr++;
  461. return mime_ptr;
  462. }
  463. }
  464. if (*resp_buf == '\0')
  465. break;
  466. resp_buf += strlen(resp_buf) + 1;
  467. resp_buf_len += strlen(resp_buf) + 1;
  468. }
  469. return RT_NULL;
  470. }
  471. /**
  472. * get http response status code.
  473. *
  474. * @param session webclient session
  475. *
  476. * @return response status code
  477. */
  478. int webclient_resp_status_get(struct webclient_session* session) {
  479. RT_ASSERT(session);
  480. return session->resp_status;
  481. }
  482. /**
  483. * get http response data content length.
  484. *
  485. * @param session webclient session
  486. *
  487. * @return response content length
  488. */
  489. int webclient_content_length_get(struct webclient_session* session) {
  490. RT_ASSERT(session);
  491. return session->content_length;
  492. }
  493. static int webclient_send_header(struct webclient_session* session,
  494. int method) {
  495. int rc = WEBCLIENT_OK;
  496. char* header = RT_NULL;
  497. RT_ASSERT(session);
  498. header = session->header->buffer;
  499. if (session->header->length == 0 && method <= WEBCLIENT_GET) {
  500. /* use default header data */
  501. if (webclient_header_fields_add(session, "GET %s HTTP/1.1\r\n",
  502. session->req_url) < 0)
  503. return -WEBCLIENT_NOMEM;
  504. if (webclient_header_fields_add(session, "Host: %s\r\n",
  505. session->host) < 0)
  506. return -WEBCLIENT_NOMEM;
  507. if (webclient_header_fields_add(
  508. session, "User-Agent: RT-Thread HTTP Agent\r\n\r\n") < 0)
  509. return -WEBCLIENT_NOMEM;
  510. webclient_write(session, (unsigned char*)session->header->buffer,
  511. session->header->length);
  512. } else {
  513. if (method != WEBCLIENT_USER_METHOD) {
  514. /* check and add fields header data */
  515. if (web_memcmp(header, "HTTP/1.", strlen("HTTP/1."))) {
  516. char* header_buffer = RT_NULL;
  517. int length = 0;
  518. header_buffer = web_strdup(session->header->buffer);
  519. if (header_buffer == RT_NULL) {
  520. LOG_E("no memory for header buffer!");
  521. rc = -WEBCLIENT_NOMEM;
  522. goto __exit;
  523. }
  524. /* splice http request header data */
  525. if (method == WEBCLIENT_GET)
  526. length = web_snprintf(
  527. session->header->buffer, session->header->size,
  528. "GET %s HTTP/1.1\r\n%s",
  529. session->req_url ? session->req_url : "/",
  530. header_buffer);
  531. else if (method == WEBCLIENT_POST)
  532. length = web_snprintf(
  533. session->header->buffer, session->header->size,
  534. "POST %s HTTP/1.1\r\n%s",
  535. session->req_url ? session->req_url : "/",
  536. header_buffer);
  537. else if (method == WEBCLIENT_HEAD)
  538. length = web_snprintf(
  539. session->header->buffer, session->header->size,
  540. "HEAD %s HTTP/1.1\r\n%s",
  541. session->req_url ? session->req_url : "/",
  542. header_buffer);
  543. session->header->length = length;
  544. web_free(header_buffer);
  545. }
  546. if (strstr(header, "Host:") == RT_NULL) {
  547. if (webclient_header_fields_add(session, "Host: %s\r\n",
  548. session->host) < 0)
  549. return -WEBCLIENT_NOMEM;
  550. }
  551. if (strstr(header, "User-Agent:") == RT_NULL) {
  552. if (webclient_header_fields_add(
  553. session, "User-Agent: RT-Thread HTTP Agent\r\n") < 0)
  554. return -WEBCLIENT_NOMEM;
  555. }
  556. if (strstr(header, "Accept:") == RT_NULL) {
  557. if (webclient_header_fields_add(session, "Accept: */*\r\n") < 0)
  558. return -WEBCLIENT_NOMEM;
  559. }
  560. /* header data end */
  561. web_snprintf(session->header->buffer + session->header->length,
  562. session->header->size - session->header->length,
  563. "\r\n");
  564. session->header->length += 2;
  565. /* check header size */
  566. if (session->header->length > session->header->size) {
  567. LOG_E("send header failed, not enough header buffer size(%d)!",
  568. session->header->size);
  569. rc = -WEBCLIENT_NOBUFFER;
  570. goto __exit;
  571. }
  572. webclient_write(session, (unsigned char*)session->header->buffer,
  573. session->header->length);
  574. } else {
  575. webclient_write(session, (unsigned char*)session->header->buffer,
  576. session->header->length);
  577. }
  578. }
  579. /* get and echo request header data */
  580. {
  581. char *header_str, *header_ptr;
  582. int header_line_len;
  583. LOG_D("request header:");
  584. for (header_str = session->header->buffer;
  585. (header_ptr = strstr(header_str, "\r\n")) != RT_NULL;) {
  586. header_line_len = header_ptr - header_str;
  587. if (header_line_len > 0) {
  588. LOG_D("%.*s", header_line_len, header_str);
  589. }
  590. header_str = header_ptr + strlen("\r\n");
  591. }
  592. #ifdef WEBCLIENT_DEBUG
  593. LOG_RAW("\n");
  594. #endif
  595. }
  596. __exit:
  597. return rc;
  598. }
  599. /* FIXME: 定制版发送响应头 */
  600. static int webclient_send_header2(struct webclient_session* session,
  601. int method) {
  602. int rc = WEBCLIENT_OK;
  603. char* header = RT_NULL;
  604. RT_ASSERT(session);
  605. header = session->header->buffer;
  606. if (strstr(header, "Host:") == RT_NULL) {
  607. if (webclient_header_fields_add(session, "Host: %s\r\n",
  608. session->host) < 0)
  609. return -WEBCLIENT_NOMEM;
  610. }
  611. if (strstr(header, "User-Agent:") == RT_NULL) {
  612. if (webclient_header_fields_add(
  613. session, "User-Agent: PikaScript HTTP Agent\r\n") < 0)
  614. return -WEBCLIENT_NOMEM;
  615. }
  616. if (strstr(header, "Accept:") == RT_NULL) {
  617. if (webclient_header_fields_add(session, "Accept: */*\r\n") < 0)
  618. return -WEBCLIENT_NOMEM;
  619. }
  620. /* header data end */
  621. web_snprintf(session->header->buffer + session->header->length,
  622. session->header->size - session->header->length,
  623. "\r\n");
  624. session->header->length += 2;
  625. /* check header size */
  626. if (session->header->length > session->header->size) {
  627. LOG_E("send header failed, not enough header buffer size(%d)!",
  628. session->header->size);
  629. rc = -WEBCLIENT_NOBUFFER;
  630. goto __exit;
  631. }
  632. webclient_write(session, (unsigned char*)session->header->buffer,
  633. session->header->length);
  634. __exit:
  635. return rc;
  636. }
  637. /**
  638. * resolve server response data.
  639. *
  640. * @param session webclient session
  641. *
  642. * @return <0: resolve response data failed
  643. * =0: success
  644. */
  645. int webclient_handle_response(struct webclient_session* session) {
  646. int rc = WEBCLIENT_OK;
  647. char* mime_buffer = RT_NULL;
  648. char* mime_ptr = RT_NULL;
  649. const char* transfer_encoding;
  650. int i;
  651. RT_ASSERT(session);
  652. /* clean header buffer and size */
  653. web_memset(session->header->buffer, 0x00, session->header->size);
  654. session->header->length = 0;
  655. LOG_D("response header:");
  656. /* We now need to read the header information */
  657. while (1) {
  658. mime_buffer = session->header->buffer + session->header->length;
  659. /* read a line from the header information. */
  660. rc = webclient_read_line(
  661. session, mime_buffer,
  662. session->header->size - session->header->length);
  663. if (rc < 0)
  664. break;
  665. /* End of headers is a blank line. exit. */
  666. if (rc == 0)
  667. break;
  668. if ((rc == 1) && (mime_buffer[0] == '\r')) {
  669. mime_buffer[0] = '\0';
  670. break;
  671. }
  672. /* set terminal charater */
  673. mime_buffer[rc - 1] = '\0';
  674. /* echo response header data */
  675. LOG_D("%s", mime_buffer);
  676. session->header->length += rc;
  677. if (session->header->length >= session->header->size) {
  678. LOG_E("not enough header buffer size(%d)!", session->header->size);
  679. return -WEBCLIENT_NOMEM;
  680. }
  681. }
  682. /* get HTTP status code */
  683. mime_ptr = web_strdup(session->header->buffer);
  684. if (mime_ptr == RT_NULL) {
  685. LOG_E("no memory for get http status code buffer!");
  686. return -WEBCLIENT_NOMEM;
  687. }
  688. if (strstr(mime_ptr, "HTTP/1.")) {
  689. char* ptr = mime_ptr;
  690. ptr += strlen("HTTP/1.x");
  691. while (*ptr && (*ptr == ' ' || *ptr == '\t'))
  692. ptr++;
  693. /* Terminate string after status code */
  694. for (i = 0; ((ptr[i] != ' ') && (ptr[i] != '\t')); i++)
  695. ;
  696. ptr[i] = '\0';
  697. session->resp_status = (int)strtol(ptr, RT_NULL, 10);
  698. }
  699. /* get content length */
  700. if (webclient_header_fields_get(session, "Content-Length") != RT_NULL) {
  701. session->content_length =
  702. atoi(webclient_header_fields_get(session, "Content-Length"));
  703. }
  704. session->content_remainder =
  705. session->content_length ? (size_t)session->content_length : 0xFFFFFFFF;
  706. transfer_encoding =
  707. webclient_header_fields_get(session, "Transfer-Encoding");
  708. if (transfer_encoding && strcmp(transfer_encoding, "chunked") == 0) {
  709. rt_uint16_t len = session->header->size;
  710. char* line = rt_malloc(len);
  711. /* chunk mode, we should get the first chunk size */
  712. webclient_read_line(session, line, len);
  713. session->chunk_sz = strtol(line, RT_NULL, len);
  714. session->chunk_offset = 0;
  715. rt_free(line);
  716. }
  717. if (mime_ptr) {
  718. web_free(mime_ptr);
  719. }
  720. if (rc < 0) {
  721. return rc;
  722. }
  723. return session->resp_status;
  724. }
  725. /**
  726. * FIXME: userful func
  727. * create webclient session, set maximum header and response size
  728. *
  729. * @param header_sz maximum send header size
  730. * @param resp_sz maximum response data size
  731. *
  732. * @return webclient session structure
  733. */
  734. struct webclient_session* webclient_session_create(size_t header_sz) {
  735. struct webclient_session* session;
  736. /* create session */
  737. session = (struct webclient_session*)web_calloc(
  738. 1, sizeof(struct webclient_session));
  739. if (session == RT_NULL) {
  740. LOG_E("webclient create failed, no memory for webclient session!");
  741. return RT_NULL;
  742. }
  743. /* initialize the socket of session */
  744. session->socket = -1;
  745. session->content_length = -1;
  746. session->header = (struct webclient_header*)web_calloc(
  747. 1, sizeof(struct webclient_header));
  748. if (session->header == RT_NULL) {
  749. LOG_E("webclient create failed, no memory for session header!");
  750. web_free(session);
  751. session = RT_NULL;
  752. return RT_NULL;
  753. }
  754. session->header->size = header_sz;
  755. session->header->buffer = (char*)web_calloc(1, header_sz);
  756. if (session->header->buffer == RT_NULL) {
  757. LOG_E("webclient create failed, no memory for session header buffer!");
  758. web_free(session->header);
  759. web_free(session);
  760. session = RT_NULL;
  761. return RT_NULL;
  762. }
  763. return session;
  764. }
  765. static int webclient_clean(struct webclient_session* session);
  766. /**
  767. * send GET request to http server and get response header.
  768. *
  769. * @param session webclient session
  770. * @param URI input server URI address
  771. * @param header GET request header
  772. * = NULL: use default header data
  773. * != NULL: use custom header data
  774. *
  775. * @return <0: send GET request failed
  776. * >0: response http status code
  777. */
  778. int webclient_get(struct webclient_session* session, const char* URI) {
  779. int rc = WEBCLIENT_OK;
  780. int resp_status = 0;
  781. RT_ASSERT(session);
  782. RT_ASSERT(URI);
  783. rc = webclient_connect(session, URI);
  784. if (rc != WEBCLIENT_OK) {
  785. /* connect to webclient server failed. */
  786. return rc;
  787. }
  788. rc = webclient_send_header(session, WEBCLIENT_GET);
  789. if (rc != WEBCLIENT_OK) {
  790. /* send header to webclient server failed. */
  791. return rc;
  792. }
  793. /* handle the response header of webclient server */
  794. resp_status = webclient_handle_response(session);
  795. LOG_D("get position handle response(%d).", resp_status);
  796. if (resp_status > 0) {
  797. const char* location = webclient_header_fields_get(session, "Location");
  798. /* relocation */
  799. if ((resp_status == 302 || resp_status == 301) && location) {
  800. char* new_url;
  801. new_url = web_strdup(location);
  802. if (new_url == RT_NULL) {
  803. return -WEBCLIENT_NOMEM;
  804. }
  805. /* clean webclient session */
  806. webclient_clean(session);
  807. /* clean webclient session header */
  808. session->header->length = 0;
  809. web_memset(session->header->buffer, 0, session->header->size);
  810. rc = webclient_get(session, new_url);
  811. web_free(new_url);
  812. return rc;
  813. }
  814. }
  815. return resp_status;
  816. }
  817. /**
  818. * FIXME: better interface
  819. * send GET request to http server and get response header.
  820. *
  821. * @param session webclient session
  822. * @param URI input server URI address
  823. * @param header GET request header
  824. * = NULL: use default header data
  825. * != NULL: use custom header data
  826. *
  827. * @return <0: send GET request failed
  828. * >0: response http status code
  829. */
  830. int webclient_get2(struct webclient_session* session, const char* URI) {
  831. int rc = WEBCLIENT_OK;
  832. int resp_status = 0;
  833. RT_ASSERT(session);
  834. RT_ASSERT(URI);
  835. /* LOG_E("||url:%.1024s||", URI); */
  836. rc = webclient_connect(session, URI);
  837. if (rc != WEBCLIENT_OK) {
  838. /* connect to webclient server failed. */
  839. return rc;
  840. }
  841. rc = webclient_send_header2(session, WEBCLIENT_GET);
  842. if (rc != WEBCLIENT_OK) {
  843. /* send header to webclient server failed. */
  844. return rc;
  845. }
  846. /* handle the response header of webclient server */
  847. resp_status = webclient_handle_response(session);
  848. LOG_D("get position handle response(%d).", resp_status);
  849. if (resp_status > 0) {
  850. const char* location = webclient_header_fields_get(session, "Location");
  851. /* relocation */
  852. if ((resp_status == 302 || resp_status == 301) && location) {
  853. char* new_url;
  854. new_url = web_strdup(location);
  855. if (new_url == RT_NULL) {
  856. return -WEBCLIENT_NOMEM;
  857. }
  858. /* clean webclient session */
  859. webclient_clean(session);
  860. /* clean webclient session header */
  861. session->header->length = 0;
  862. web_memset(session->header->buffer, 0, session->header->size);
  863. rc = webclient_get(session, new_url);
  864. web_free(new_url);
  865. return rc;
  866. }
  867. }
  868. return resp_status;
  869. }
  870. /**
  871. * register a handle function for http breakpoint resume and shard download.
  872. *
  873. * @param function
  874. *
  875. * @return the pointer
  876. */
  877. int* webclient_register_shard_position_function(
  878. struct webclient_session* session,
  879. int (*handle_function)(char* buffer, int size)) {
  880. session->handle_function = handle_function;
  881. return (int*)session->handle_function;
  882. }
  883. /**
  884. * http breakpoint resume and shard download.
  885. *
  886. * @param session webclient session
  887. * @param URI input server URI address
  888. * @param length the length of point
  889. *
  890. * @return <0: send GET request failed
  891. * >0: response http status code
  892. */
  893. int webclient_shard_head_function(struct webclient_session* session,
  894. const char* URI,
  895. int* length) {
  896. RT_ASSERT(session);
  897. RT_ASSERT(URI);
  898. int rc = WEBCLIENT_OK;
  899. int resp_status = 0;
  900. if (session->socket == -1) {
  901. rc = webclient_connect(session, URI);
  902. if (rc != WEBCLIENT_OK) {
  903. return rc;
  904. }
  905. }
  906. /* clean header buffer and size */
  907. web_memset(session->header->buffer, 0x00, session->header->size);
  908. session->header->length = 0;
  909. rc = webclient_send_header(session, WEBCLIENT_HEAD);
  910. if (rc != WEBCLIENT_OK) {
  911. return rc;
  912. }
  913. /* handle the response header of webclient server by HEAD request */
  914. resp_status = webclient_handle_response(session);
  915. if (resp_status >= 0) {
  916. *length = webclient_content_length_get(session);
  917. LOG_D("The length[%04d] of real data of URI.", *length);
  918. }
  919. return rc;
  920. }
  921. /**
  922. * http breakpoint resume and shard download.
  923. *
  924. * @param session webclient session
  925. * @param URI input server URI address
  926. * @param start the position of you want to receive
  927. * @param length the length of data length from "webclient_shard_head_function"
  928. * @param mem_size the buffer size that you alloc
  929. *
  930. * @return <0: send GET request failed
  931. * >0: response http status code
  932. */
  933. int webclient_shard_position_function(struct webclient_session* session,
  934. const char* URI,
  935. int start,
  936. int length,
  937. int mem_size) {
  938. int rc = WEBCLIENT_OK;
  939. int result = RT_EOK;
  940. int resp_status = 0;
  941. size_t resp_len = 0;
  942. char* buffer = RT_NULL;
  943. int start_position, end_position = 0;
  944. int total_len = 0;
  945. RT_ASSERT(session);
  946. RT_ASSERT(URI);
  947. RT_ASSERT(mem_size);
  948. /* set the offset of "Range" and "total_len" */
  949. end_position = start;
  950. total_len = start + length;
  951. /* clean header buffer and size */
  952. web_memset(session->header->buffer, 0x00, session->header->size);
  953. session->header->length = 0;
  954. for (start_position = end_position; total_len != end_position + 1;) {
  955. RT_ASSERT(start_position <= total_len);
  956. int data_len = 0;
  957. end_position = start_position + mem_size - 1;
  958. if (end_position >= total_len) {
  959. end_position = total_len - 1;
  960. }
  961. /* splice header and send header */
  962. LOG_D("Range: [%04d -> %04d]", start_position, end_position);
  963. webclient_header_fields_add(session, "Range: bytes=%d-%d\r\n",
  964. start_position, end_position);
  965. rc = webclient_send_header(session, WEBCLIENT_GET);
  966. if (rc != WEBCLIENT_OK) {
  967. return rc;
  968. }
  969. /* handle the response header of webclient server */
  970. resp_status = webclient_handle_response(session);
  971. LOG_D("get position handle response(%d).", resp_status);
  972. if (resp_status == 206) {
  973. /* normal resp_status */
  974. } else if (resp_status > 0) {
  975. const char* location =
  976. webclient_header_fields_get(session, "Location");
  977. /* relocation */
  978. if ((resp_status == 302 || resp_status == 301) && location) {
  979. char* new_url;
  980. new_url = web_strdup(location);
  981. if (new_url == RT_NULL) {
  982. return -WEBCLIENT_NOMEM;
  983. }
  984. /* clean webclient session */
  985. webclient_clean(session);
  986. /* clean webclient session header */
  987. session->header->length = 0;
  988. web_memset(session->header->buffer, 0, session->header->size);
  989. rc = webclient_shard_position_function(session, new_url, start,
  990. length, mem_size);
  991. web_free(new_url);
  992. return rc;
  993. }
  994. } else {
  995. if (resp_status == -WEBCLIENT_ERROR) {
  996. if (session->socket == -WEBCLIENT_ERROR) {
  997. /* clean webclient session */
  998. webclient_clean(session);
  999. if (webclient_connect(session, URI) == WEBCLIENT_OK) {
  1000. LOG_D("webclient reconnect success, retry at [%06d]",
  1001. end_position);
  1002. end_position = start_position;
  1003. continue;
  1004. } else {
  1005. LOG_E(
  1006. "webclient reconnect failed. Please retry by "
  1007. "yourself.");
  1008. return -WEBCLIENT_ERROR;
  1009. }
  1010. }
  1011. }
  1012. }
  1013. /* receive the incoming data */
  1014. data_len = webclient_response(session, (void**)&buffer, &resp_len);
  1015. if (data_len > 0) {
  1016. start_position += data_len;
  1017. result = session->handle_function(buffer, data_len);
  1018. if (result != RT_EOK) {
  1019. return -WEBCLIENT_ERROR;
  1020. }
  1021. } else {
  1022. /* clean webclient session */
  1023. webclient_clean(session);
  1024. if (session->socket == -WEBCLIENT_ERROR) {
  1025. webclient_connect(session, URI);
  1026. }
  1027. }
  1028. /* clean header buffer and size */
  1029. web_memset(session->header->buffer, 0x00, session->header->size);
  1030. session->header->length = 0;
  1031. }
  1032. return rc;
  1033. }
  1034. /**
  1035. * send POST request to server and get response header data.
  1036. *
  1037. * @param session webclient session
  1038. * @param URI input server URI address
  1039. * @param post_data data send to the server
  1040. * = NULL: just connect server and send header
  1041. * != NULL: send header and body data, resolve response data
  1042. * @param data_len the length of send data
  1043. *
  1044. * @return <0: send POST request failed
  1045. * =0: send POST header success
  1046. * >0: response http status code
  1047. */
  1048. int webclient_post(struct webclient_session* session,
  1049. const char* URI,
  1050. const void* post_data,
  1051. size_t data_len) {
  1052. int rc = WEBCLIENT_OK;
  1053. int resp_status = 0;
  1054. RT_ASSERT(session);
  1055. RT_ASSERT(URI);
  1056. if ((post_data != RT_NULL) && (data_len == 0)) {
  1057. LOG_E("input post data length failed");
  1058. return -WEBCLIENT_ERROR;
  1059. }
  1060. rc = webclient_connect(session, URI);
  1061. if (rc != WEBCLIENT_OK) {
  1062. /* connect to webclient server failed. */
  1063. return rc;
  1064. }
  1065. rc = webclient_send_header(session, WEBCLIENT_POST);
  1066. if (rc != WEBCLIENT_OK) {
  1067. /* send header to webclient server failed. */
  1068. return rc;
  1069. }
  1070. if (post_data && (data_len > 0)) {
  1071. webclient_write(session, post_data, data_len);
  1072. /* resolve response data, get http status code */
  1073. resp_status = webclient_handle_response(session);
  1074. LOG_D("post handle response(%d).", resp_status);
  1075. }
  1076. return resp_status;
  1077. }
  1078. /**
  1079. * FIXME: better interface
  1080. * send POST request to server and get response header data.
  1081. *
  1082. * @param session webclient session
  1083. * @param URI input server URI address
  1084. * @param post_data data send to the server
  1085. * = NULL: just connect server and send header
  1086. * != NULL: send header and body data, resolve response data
  1087. * @param data_len the length of send data
  1088. *
  1089. * @return <0: send POST request failed
  1090. * =0: send POST header success
  1091. * >0: response http status code
  1092. */
  1093. int webclient_post2(struct webclient_session* session,
  1094. const char* URI,
  1095. const void* post_data,
  1096. size_t data_len) {
  1097. int rc = WEBCLIENT_OK;
  1098. int resp_status = 0;
  1099. RT_ASSERT(session);
  1100. RT_ASSERT(URI);
  1101. if ((post_data != RT_NULL) && (data_len == 0)) {
  1102. LOG_E("input post data length failed");
  1103. return -WEBCLIENT_ERROR;
  1104. }
  1105. rc = webclient_connect(session, URI);
  1106. if (rc != WEBCLIENT_OK) {
  1107. /* connect to webclient server failed. */
  1108. return rc;
  1109. }
  1110. rc = webclient_send_header2(session, WEBCLIENT_POST);
  1111. if (rc != WEBCLIENT_OK) {
  1112. /* send header to webclient server failed. */
  1113. return rc;
  1114. }
  1115. if (post_data && (data_len > 0)) {
  1116. webclient_write(session, post_data, data_len);
  1117. /* resolve response data, get http status code */
  1118. resp_status = webclient_handle_response(session);
  1119. LOG_D("post handle response(%d).", resp_status);
  1120. }
  1121. return resp_status;
  1122. }
  1123. /**
  1124. * set receive and send data timeout.
  1125. *
  1126. * @param session http session
  1127. * @param millisecond timeout millisecond
  1128. *
  1129. * @return 0: set timeout success
  1130. */
  1131. int webclient_set_timeout(struct webclient_session* session, int millisecond) {
  1132. struct timeval timeout;
  1133. int second = rt_tick_from_millisecond(millisecond) / 1000;
  1134. RT_ASSERT(session);
  1135. timeout.tv_sec = second;
  1136. timeout.tv_usec = 0;
  1137. /* set recv timeout option */
  1138. __platform_setsockopt(session->socket, SOL_SOCKET, SO_RCVTIMEO,
  1139. (void*)&timeout, sizeof(timeout));
  1140. __platform_setsockopt(session->socket, SOL_SOCKET, SO_SNDTIMEO,
  1141. (void*)&timeout, sizeof(timeout));
  1142. return 0;
  1143. }
  1144. static int webclient_next_chunk(struct webclient_session* session) {
  1145. char line[64];
  1146. int length;
  1147. RT_ASSERT(session);
  1148. web_memset(line, 0x00, sizeof(line));
  1149. length = webclient_read_line(session, line, sizeof(line));
  1150. if (length > 0) {
  1151. if (strcmp(line, "\r") == 0) {
  1152. length = webclient_read_line(session, line, sizeof(line));
  1153. if (length <= 0) {
  1154. __platform_close(session->socket);
  1155. session->socket = -1;
  1156. return length;
  1157. }
  1158. }
  1159. } else {
  1160. __platform_close(session->socket);
  1161. session->socket = -1;
  1162. return length;
  1163. }
  1164. session->chunk_sz = strtol(line, RT_NULL, 16);
  1165. session->chunk_offset = 0;
  1166. if (session->chunk_sz == 0) {
  1167. /* end of chunks */
  1168. __platform_close(session->socket);
  1169. session->socket = -1;
  1170. session->chunk_sz = -1;
  1171. }
  1172. return session->chunk_sz;
  1173. }
  1174. /**
  1175. * read data from http server.
  1176. *
  1177. * @param session http session
  1178. * @param buffer read buffer
  1179. * @param length the maximum of read buffer size
  1180. *
  1181. * @return <0: read data error
  1182. * =0: http server disconnect
  1183. * >0: successfully read data length
  1184. */
  1185. int webclient_read(struct webclient_session* session,
  1186. void* buffer,
  1187. size_t length) {
  1188. int bytes_read = 0;
  1189. int total_read = 0;
  1190. int left;
  1191. RT_ASSERT(session);
  1192. /* get next chunk size is zero, client is already closed, return zero */
  1193. if (session->chunk_sz < 0) {
  1194. return 0;
  1195. }
  1196. if (session->socket < 0) {
  1197. return -WEBCLIENT_DISCONNECT;
  1198. }
  1199. if (length == 0) {
  1200. return 0;
  1201. }
  1202. /* which is transfered as chunk mode */
  1203. if (session->chunk_sz) {
  1204. if ((int)length > (session->chunk_sz - session->chunk_offset)) {
  1205. length = session->chunk_sz - session->chunk_offset;
  1206. }
  1207. bytes_read = webclient_recv(session, buffer, length, 0);
  1208. if (bytes_read <= 0) {
  1209. if (errno == EWOULDBLOCK || errno == EAGAIN) {
  1210. /* recv timeout */
  1211. return -WEBCLIENT_TIMEOUT;
  1212. } else {
  1213. __platform_close(session->socket);
  1214. session->socket = -1;
  1215. return 0;
  1216. }
  1217. }
  1218. session->chunk_offset += bytes_read;
  1219. if (session->chunk_offset >= session->chunk_sz) {
  1220. webclient_next_chunk(session);
  1221. }
  1222. return bytes_read;
  1223. }
  1224. if (session->content_length > 0) {
  1225. if (length > session->content_remainder) {
  1226. length = session->content_remainder;
  1227. }
  1228. if (length == 0) {
  1229. return 0;
  1230. }
  1231. }
  1232. /*
  1233. * Read until: there is an error, we've read "size" bytes or the remote
  1234. * side has closed the connection.
  1235. */
  1236. left = length;
  1237. do {
  1238. bytes_read = webclient_recv(
  1239. session, (void*)((char*)buffer + total_read), left, 0);
  1240. if (bytes_read <= 0) {
  1241. #if defined(WEBCLIENT_USING_SAL_TLS) || defined(WEBCLIENT_USING_MBED_TLS)
  1242. if (session->is_tls && (bytes_read == MBEDTLS_ERR_SSL_WANT_READ ||
  1243. bytes_read == MBEDTLS_ERR_SSL_WANT_WRITE)) {
  1244. continue;
  1245. }
  1246. #endif
  1247. LOG_D("receive data error(%d).", bytes_read);
  1248. if (total_read) {
  1249. break;
  1250. } else {
  1251. if (errno == EWOULDBLOCK || errno == EAGAIN) {
  1252. /* recv timeout */
  1253. LOG_E("receive data timeout.");
  1254. return -WEBCLIENT_TIMEOUT;
  1255. } else {
  1256. __platform_close(session->socket);
  1257. session->socket = -1;
  1258. return 0;
  1259. }
  1260. }
  1261. }
  1262. left -= bytes_read;
  1263. total_read += bytes_read;
  1264. } while (left);
  1265. if (session->content_length > 0) {
  1266. session->content_remainder -= total_read;
  1267. }
  1268. return total_read;
  1269. }
  1270. /**
  1271. * write data to http server.
  1272. *
  1273. * @param session http session
  1274. * @param buffer write buffer
  1275. * @param length write buffer size
  1276. *
  1277. * @return <0: write data error
  1278. * =0: http server disconnect
  1279. * >0: successfully write data length
  1280. */
  1281. int webclient_write(struct webclient_session* session,
  1282. const void* buffer,
  1283. size_t length) {
  1284. int bytes_write = 0;
  1285. int total_write = 0;
  1286. int left = length;
  1287. RT_ASSERT(session);
  1288. if (session->socket < 0) {
  1289. return -WEBCLIENT_DISCONNECT;
  1290. }
  1291. if (length == 0) {
  1292. return 0;
  1293. }
  1294. /* send all of data on the buffer. */
  1295. do {
  1296. bytes_write = webclient_send(
  1297. session, (void*)((char*)buffer + total_write), left, 0);
  1298. if (bytes_write <= 0) {
  1299. #if defined(WEBCLIENT_USING_SAL_TLS) || defined(WEBCLIENT_USING_MBED_TLS)
  1300. if (session->is_tls &&
  1301. (bytes_write == MBEDTLS_ERR_SSL_WANT_READ ||
  1302. bytes_write == MBEDTLS_ERR_SSL_WANT_WRITE)) {
  1303. continue;
  1304. }
  1305. #endif
  1306. if (errno == EWOULDBLOCK || errno == EAGAIN) {
  1307. /* send timeout */
  1308. if (total_write) {
  1309. return total_write;
  1310. }
  1311. continue;
  1312. /* TODO: whether return the TIMEOUT
  1313. * return -WEBCLIENT_TIMEOUT; */
  1314. } else {
  1315. __platform_close(session->socket);
  1316. session->socket = -1;
  1317. if (total_write == 0) {
  1318. return -WEBCLIENT_DISCONNECT;
  1319. }
  1320. break;
  1321. }
  1322. }
  1323. left -= bytes_write;
  1324. total_write += bytes_write;
  1325. } while (left);
  1326. return total_write;
  1327. }
  1328. /* close session socket, free host and request url */
  1329. static int webclient_clean(struct webclient_session* session) {
  1330. #ifdef WEBCLIENT_USING_MBED_TLS
  1331. if (session->tls_session) {
  1332. mbedtls_client_close(session->tls_session);
  1333. } else {
  1334. if (session->socket >= 0) {
  1335. __platform_close(session->socket);
  1336. session->socket = -1;
  1337. }
  1338. }
  1339. #else
  1340. if (session->socket >= 0) {
  1341. __platform_close(session->socket);
  1342. session->socket = -1;
  1343. }
  1344. #endif
  1345. if (session->host) {
  1346. web_free(session->host);
  1347. session->host = RT_NULL;
  1348. }
  1349. if (session->req_url) {
  1350. web_free(session->req_url);
  1351. session->req_url = RT_NULL;
  1352. }
  1353. session->content_length = -1;
  1354. return 0;
  1355. }
  1356. /**
  1357. * close a webclient client session.
  1358. *
  1359. * @param session http client session
  1360. *
  1361. * @return 0: close success
  1362. */
  1363. int webclient_close(struct webclient_session* session) {
  1364. RT_ASSERT(session);
  1365. webclient_clean(session);
  1366. if (session->header && session->header->buffer) {
  1367. web_free(session->header->buffer);
  1368. }
  1369. if (session->header) {
  1370. web_free(session->header);
  1371. }
  1372. if (session) {
  1373. web_free(session);
  1374. session = RT_NULL;
  1375. }
  1376. return 0;
  1377. }
  1378. /**
  1379. * get wenclient request response data.
  1380. *
  1381. * @param session wenclient session
  1382. * @param response response buffer address
  1383. * @param resp_len response buffer length
  1384. *
  1385. * @return response data size
  1386. */
  1387. int webclient_response(struct webclient_session* session,
  1388. void** response,
  1389. size_t* resp_len) {
  1390. unsigned char* buf_ptr;
  1391. unsigned char* response_buf = 0;
  1392. int length, total_read = 0;
  1393. RT_ASSERT(session);
  1394. RT_ASSERT(response);
  1395. /* initialize response */
  1396. *response = RT_NULL;
  1397. /* not content length field kind */
  1398. if (session->content_length < 0) {
  1399. size_t result_sz;
  1400. total_read = 0;
  1401. while (1) {
  1402. unsigned char* new_resp = RT_NULL;
  1403. result_sz = total_read + WEBCLIENT_RESPONSE_BUFSZ;
  1404. new_resp = web_realloc(response_buf, result_sz + 1);
  1405. if (new_resp == RT_NULL) {
  1406. LOG_E("no memory for realloc new response buffer!");
  1407. break;
  1408. }
  1409. response_buf = new_resp;
  1410. buf_ptr = (unsigned char*)response_buf + total_read;
  1411. /* read result */
  1412. length = webclient_read(session, buf_ptr, result_sz - total_read);
  1413. if (length <= 0)
  1414. break;
  1415. total_read += length;
  1416. }
  1417. } else {
  1418. int result_sz;
  1419. result_sz = session->content_length;
  1420. response_buf = web_calloc(1, result_sz + 1);
  1421. if (response_buf == RT_NULL) {
  1422. return -WEBCLIENT_NOMEM;
  1423. }
  1424. buf_ptr = (unsigned char*)response_buf;
  1425. for (total_read = 0; total_read < result_sz;) {
  1426. length = webclient_read(session, buf_ptr, result_sz - total_read);
  1427. if (length <= 0)
  1428. break;
  1429. buf_ptr += length;
  1430. total_read += length;
  1431. }
  1432. }
  1433. if ((total_read == 0) && (response_buf != 0)) {
  1434. web_free(response_buf);
  1435. response_buf = RT_NULL;
  1436. }
  1437. if (response_buf) {
  1438. *response = (void*)response_buf;
  1439. *(response_buf + total_read) = '\0';
  1440. *resp_len = total_read;
  1441. }
  1442. return total_read;
  1443. }
  1444. /**
  1445. * add request(GET/POST) header data.
  1446. *
  1447. * @param request_header add request buffer address
  1448. * @param fmt fields format
  1449. *
  1450. * @return <=0: add header failed
  1451. * >0: add header data size
  1452. */
  1453. int webclient_request_header_add(char** request_header, const char* fmt, ...) {
  1454. rt_int32_t length, header_length;
  1455. char* header;
  1456. va_list args;
  1457. RT_ASSERT(request_header);
  1458. if (*request_header == RT_NULL) {
  1459. header = rt_calloc(1, WEBCLIENT_HEADER_BUFSZ);
  1460. if (header == RT_NULL) {
  1461. LOG_E("No memory for webclient request header add.");
  1462. return RT_NULL;
  1463. }
  1464. *request_header = header;
  1465. } else {
  1466. header = *request_header;
  1467. }
  1468. va_start(args, fmt);
  1469. header_length = strlen(header);
  1470. length = web_vsnprintf(header + header_length,
  1471. WEBCLIENT_HEADER_BUFSZ - header_length, fmt, args);
  1472. if (length < 0) {
  1473. LOG_E("add request header data failed, return length(%d) error.",
  1474. length);
  1475. return -WEBCLIENT_ERROR;
  1476. }
  1477. va_end(args);
  1478. /* check header size */
  1479. if (strlen(header) >= WEBCLIENT_HEADER_BUFSZ) {
  1480. LOG_E("not enough request header data size(%d)!",
  1481. WEBCLIENT_HEADER_BUFSZ);
  1482. return -WEBCLIENT_ERROR;
  1483. }
  1484. return length;
  1485. }
  1486. /**
  1487. * send request(GET/POST) to server and get response data.
  1488. *
  1489. * @param URI input server address
  1490. * @param header send header data
  1491. * = NULL: use default header data, must be GET request
  1492. * != NULL: user custom header data, GET or POST request
  1493. * @param post_data data sent to the server
  1494. * = NULL: it is GET request
  1495. * != NULL: it is POST request
  1496. * @param data_len send data length
  1497. * @param response response buffer address
  1498. * @param resp_len response buffer length
  1499. *
  1500. * @return <0: request failed
  1501. * >=0: response buffer size
  1502. */
  1503. int webclient_request(const char* URI,
  1504. const char* header,
  1505. const void* post_data,
  1506. size_t data_len,
  1507. void** response,
  1508. size_t* resp_len) {
  1509. struct webclient_session* session = RT_NULL;
  1510. int rc = WEBCLIENT_OK;
  1511. int totle_length = 0;
  1512. RT_ASSERT(URI);
  1513. if (post_data == RT_NULL && response == RT_NULL) {
  1514. LOG_E("request get failed, get response data cannot be empty.");
  1515. return -WEBCLIENT_ERROR;
  1516. }
  1517. if ((post_data != RT_NULL) && (data_len == 0)) {
  1518. LOG_E("input post data length failed");
  1519. return -WEBCLIENT_ERROR;
  1520. }
  1521. if ((response != RT_NULL && resp_len == RT_NULL) ||
  1522. (response == RT_NULL && resp_len != RT_NULL)) {
  1523. LOG_E("input response data or length failed");
  1524. return -WEBCLIENT_ERROR;
  1525. }
  1526. if (post_data == RT_NULL) {
  1527. /* send get request */
  1528. session = webclient_session_create(WEBCLIENT_HEADER_BUFSZ);
  1529. if (session == RT_NULL) {
  1530. rc = -WEBCLIENT_NOMEM;
  1531. goto __exit;
  1532. }
  1533. if (header != RT_NULL) {
  1534. char *header_str, *header_ptr;
  1535. int header_line_length;
  1536. for (header_str = (char*)header;
  1537. (header_ptr = strstr(header_str, "\r\n")) != RT_NULL;) {
  1538. header_line_length = header_ptr + strlen("\r\n") - header_str;
  1539. webclient_header_fields_add(session, "%.*s", header_line_length,
  1540. header_str);
  1541. header_str += header_line_length;
  1542. }
  1543. }
  1544. if (webclient_get(session, URI) != 200) {
  1545. rc = -WEBCLIENT_ERROR;
  1546. goto __exit;
  1547. }
  1548. totle_length = webclient_response(session, response, resp_len);
  1549. if (totle_length <= 0) {
  1550. rc = -WEBCLIENT_ERROR;
  1551. goto __exit;
  1552. }
  1553. } else {
  1554. /* send post request */
  1555. session = webclient_session_create(WEBCLIENT_HEADER_BUFSZ);
  1556. if (session == RT_NULL) {
  1557. rc = -WEBCLIENT_NOMEM;
  1558. goto __exit;
  1559. }
  1560. if (header != RT_NULL) {
  1561. char *header_str, *header_ptr;
  1562. int header_line_length;
  1563. for (header_str = (char*)header;
  1564. (header_ptr = strstr(header_str, "\r\n")) != RT_NULL;) {
  1565. header_line_length = header_ptr + strlen("\r\n") - header_str;
  1566. webclient_header_fields_add(session, "%.*s", header_line_length,
  1567. header_str);
  1568. header_str += header_line_length;
  1569. }
  1570. }
  1571. if (strstr(session->header->buffer, "Content-Length") == RT_NULL) {
  1572. webclient_header_fields_add(session, "Content-Length: %d\r\n",
  1573. strlen(post_data));
  1574. }
  1575. if (strstr(session->header->buffer, "Content-Type") == RT_NULL) {
  1576. webclient_header_fields_add(
  1577. session, "Content-Type: application/octet-stream\r\n");
  1578. }
  1579. if (webclient_post(session, URI, post_data, data_len) != 200) {
  1580. rc = -WEBCLIENT_ERROR;
  1581. goto __exit;
  1582. }
  1583. totle_length = webclient_response(session, response, resp_len);
  1584. if (totle_length <= 0) {
  1585. rc = -WEBCLIENT_ERROR;
  1586. goto __exit;
  1587. }
  1588. }
  1589. __exit:
  1590. if (session) {
  1591. webclient_close(session);
  1592. session = RT_NULL;
  1593. }
  1594. if (rc < 0) {
  1595. return rc;
  1596. }
  1597. return totle_length;
  1598. }
  1599. /**
  1600. * Better interface.
  1601. * send request(GET/POST) to server and get response data.
  1602. *
  1603. * @param URI input server address
  1604. * @param header send header data
  1605. * = NULL: use default header data, must be GET request
  1606. * != NULL: user custom header data, GET or POST request
  1607. * @param post_data data sent to the server
  1608. * = NULL: it is GET request
  1609. * != NULL: it is POST request
  1610. * @param data_len send data length
  1611. * @param response response buffer address
  1612. * @param resp_len response buffer length
  1613. *
  1614. * @return <0: request failed
  1615. * >=0: response buffer size
  1616. */
  1617. int webclient_request2(
  1618. struct webclient_session* session,
  1619. const char* URI,
  1620. const char* header,
  1621. const void* post_data,
  1622. size_t data_len,
  1623. double timeout,
  1624. void** response,
  1625. size_t* resp_len) {
  1626. int rc = WEBCLIENT_OK;
  1627. int totle_length = 0;
  1628. if (post_data == RT_NULL && response == RT_NULL) {
  1629. LOG_E("request get failed, get response data cannot be empty.");
  1630. return -WEBCLIENT_ERROR;
  1631. }
  1632. if ((post_data != RT_NULL) && (data_len == 0)) {
  1633. LOG_E("input post data length failed");
  1634. return -WEBCLIENT_ERROR;
  1635. }
  1636. if ((response != RT_NULL && resp_len == RT_NULL) ||
  1637. (response == RT_NULL && resp_len != RT_NULL)) {
  1638. LOG_E("input response data or length failed");
  1639. return -WEBCLIENT_ERROR;
  1640. }
  1641. if (post_data == RT_NULL) {
  1642. /* send get request */
  1643. session = webclient_session_create(WEBCLIENT_HEADER_BUFSZ);
  1644. if (session == RT_NULL) {
  1645. rc = -WEBCLIENT_NOMEM;
  1646. goto __exit;
  1647. }
  1648. if (header != RT_NULL) {
  1649. char *header_str, *header_ptr;
  1650. int header_line_length;
  1651. for (header_str = (char*)header;
  1652. (header_ptr = strstr(header_str, "\r\n")) != RT_NULL;) {
  1653. header_line_length = header_ptr + strlen("\r\n") - header_str;
  1654. webclient_header_fields_add(session, "%.*s", header_line_length,
  1655. header_str);
  1656. header_str += header_line_length;
  1657. }
  1658. }
  1659. if (webclient_get(session, URI) != 200) {
  1660. rc = -WEBCLIENT_ERROR;
  1661. goto __exit;
  1662. }
  1663. totle_length = webclient_response(session, response, resp_len);
  1664. if (totle_length <= 0) {
  1665. rc = -WEBCLIENT_ERROR;
  1666. goto __exit;
  1667. }
  1668. } else {
  1669. /* send post request */
  1670. session = webclient_session_create(WEBCLIENT_HEADER_BUFSZ);
  1671. if (session == RT_NULL) {
  1672. rc = -WEBCLIENT_NOMEM;
  1673. goto __exit;
  1674. }
  1675. if (header != RT_NULL) {
  1676. char *header_str, *header_ptr;
  1677. int header_line_length;
  1678. for (header_str = (char*)header;
  1679. (header_ptr = strstr(header_str, "\r\n")) != RT_NULL;) {
  1680. header_line_length = header_ptr + strlen("\r\n") - header_str;
  1681. webclient_header_fields_add(session, "%.*s", header_line_length,
  1682. header_str);
  1683. header_str += header_line_length;
  1684. }
  1685. }
  1686. if (strstr(session->header->buffer, "Content-Length") == RT_NULL) {
  1687. webclient_header_fields_add(session, "Content-Length: %d\r\n",
  1688. strlen(post_data));
  1689. }
  1690. if (strstr(session->header->buffer, "Content-Type") == RT_NULL) {
  1691. webclient_header_fields_add(
  1692. session, "Content-Type: application/octet-stream\r\n");
  1693. }
  1694. if (webclient_post(session, URI, post_data, data_len) != 200) {
  1695. rc = -WEBCLIENT_ERROR;
  1696. goto __exit;
  1697. }
  1698. totle_length = webclient_response(session, response, resp_len);
  1699. if (totle_length <= 0) {
  1700. rc = -WEBCLIENT_ERROR;
  1701. goto __exit;
  1702. }
  1703. }
  1704. __exit:
  1705. if (session) {
  1706. webclient_close(session);
  1707. session = RT_NULL;
  1708. }
  1709. if (rc < 0) {
  1710. return rc;
  1711. }
  1712. return totle_length;
  1713. }