webclient.c 47 KB

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